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": "enerator-joomla-component\n\n\tindex.coffee\n\n\t@author Sean Goresht\n\n\t@note uses Codoc\n\t@see https://github.com/mklab", "end": 69, "score": 0.9998092651367188, "start": 57, "tag": "NAME", "value": "Sean Goresht" }, { "context": "resht\n\n\t@note uses Codoc\n\t@se...
view/index.coffee
srsgores/generator-joomla-component
16
### generator-joomla-component index.coffee @author Sean Goresht @note uses Codoc @see https://github.com/mklabs/yeoman/wiki/generators coffeescript with yeoman @see https://github.com/coffeedoc/codo ### "use strict" yeoman = require("yeoman-generator") path = require("path") ### @class ViewGenerator sub-generator for joomla component controllers ### module.exports = class ViewGenerator extends yeoman.generators.NamedBase constructor: (args, options, config) -> super args, options, config pkg = JSON.parse(@readFileAsString(path.join(process.cwd(), "./package.json"))) @componentName = pkg.componentName @description = pkg.description @requireManageRights = pkg.requireManageRights @authorName = pkg.author?.name @authorEmail = pkg.author?.email @authorURL = pkg.author?.url @license = pkg.licenses[0]?.type @currentDate = new Date().getFullYear() @viewFolderName = @._.slugify(@name) @viewClassName = @._.classify(@name) console.log """ You called the view subgenerator with the argument #{@name}. Now let's create that view under the subdirectory views/#{@viewFolderName} for you... """ generateView: -> @template "_view.html.php", "views/#{@viewFolderName}/view.html.php" @template "_default.php", "views/#{@viewFolderName}/default.php"
151437
### generator-joomla-component index.coffee @author <NAME> @note uses Codoc @see https://github.com/mklabs/yeoman/wiki/generators coffeescript with yeoman @see https://github.com/coffeedoc/codo ### "use strict" yeoman = require("yeoman-generator") path = require("path") ### @class ViewGenerator sub-generator for joomla component controllers ### module.exports = class ViewGenerator extends yeoman.generators.NamedBase constructor: (args, options, config) -> super args, options, config pkg = JSON.parse(@readFileAsString(path.join(process.cwd(), "./package.json"))) @componentName = pkg.componentName @description = pkg.description @requireManageRights = pkg.requireManageRights @authorName = pkg.author?.name @authorEmail = pkg.author?.email @authorURL = pkg.author?.url @license = pkg.licenses[0]?.type @currentDate = new Date().getFullYear() @viewFolderName = @._.slugify(@name) @viewClassName = @._.classify(@name) console.log """ You called the view subgenerator with the argument #{@name}. Now let's create that view under the subdirectory views/#{@viewFolderName} for you... """ generateView: -> @template "_view.html.php", "views/#{@viewFolderName}/view.html.php" @template "_default.php", "views/#{@viewFolderName}/default.php"
true
### generator-joomla-component index.coffee @author PI:NAME:<NAME>END_PI @note uses Codoc @see https://github.com/mklabs/yeoman/wiki/generators coffeescript with yeoman @see https://github.com/coffeedoc/codo ### "use strict" yeoman = require("yeoman-generator") path = require("path") ### @class ViewGenerator sub-generator for joomla component controllers ### module.exports = class ViewGenerator extends yeoman.generators.NamedBase constructor: (args, options, config) -> super args, options, config pkg = JSON.parse(@readFileAsString(path.join(process.cwd(), "./package.json"))) @componentName = pkg.componentName @description = pkg.description @requireManageRights = pkg.requireManageRights @authorName = pkg.author?.name @authorEmail = pkg.author?.email @authorURL = pkg.author?.url @license = pkg.licenses[0]?.type @currentDate = new Date().getFullYear() @viewFolderName = @._.slugify(@name) @viewClassName = @._.classify(@name) console.log """ You called the view subgenerator with the argument #{@name}. Now let's create that view under the subdirectory views/#{@viewFolderName} for you... """ generateView: -> @template "_view.html.php", "views/#{@viewFolderName}/view.html.php" @template "_default.php", "views/#{@viewFolderName}/default.php"
[ { "context": "mplete-plus provider code from https://github.com/benogle/autocomplete-clang\n# Copyright (c) 2015 Ben Ogle ", "end": 65, "score": 0.9996827244758606, "start": 58, "tag": "USERNAME", "value": "benogle" }, { "context": "om/benogle/autocomplete-clang\n# Copyright (c) 2015...
lib/clang-provider.coffee
aryyan-lab/autocomplete-clang
121
# autocomplete-plus provider code from https://github.com/benogle/autocomplete-clang # Copyright (c) 2015 Ben Ogle under MIT license # Clang related code from https://github.com/yasuyuky/autocomplete-clang {Range, CompositeDisposable} = require 'atom' path = require 'path' {spawnClang, buildCodeCompletionArgs} = require './clang-args-builder' {getScopeLang, prefixAtPosition, nearestSymbolPosition} = require './common-util' module.exports = class ClangProvider selector: 'c, cpp, .source.cpp, .source.c, .source.objc, .source.objcpp' inclusionPriority: 1 getSuggestions: ({editor, scopeDescriptor, bufferPosition}) -> language = getScopeLang scopeDescriptor.getScopesArray() prefix = prefixAtPosition(editor, bufferPosition) [symbolPosition,lastSymbol] = nearestSymbolPosition(editor, bufferPosition) minimumWordLength = atom.config.get('autocomplete-plus.minimumWordLength') if minimumWordLength? and prefix.length < minimumWordLength regex = /(?:\.|->|::)\s*\w*$/ line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]) return unless regex.test(line) if language? @codeCompletionAt(editor, symbolPosition.row, symbolPosition.column, language, prefix) codeCompletionAt: (editor, row, column, language, prefix) -> cwd = path.dirname editor.getPath() args = buildCodeCompletionArgs editor, row, column, language spawnClang cwd, args, editor.getText(), (code, outputs, errors, resolve) => console.log errors resolve(@handleCompletionResult(outputs, code, prefix)) convertCompletionLine: (line, prefix) -> contentRe = /^COMPLETION: (.*)/ [line, content] = line.match contentRe basicInfoRe = /^(.*?) : (.*)/ match = content.match basicInfoRe return {text: content} unless match? [content, basicInfo, completionAndComment] = match commentRe = /(?: : (.*))?$/ [completion, comment] = completionAndComment.split commentRe returnTypeRe = /^\[#(.*?)#\]/ returnType = completion.match(returnTypeRe)?[1] constMemFuncRe = /\[# const#\]$/ isConstMemFunc = constMemFuncRe.test completion infoTagsRe = /\[#(.*?)#\]/g completion = completion.replace infoTagsRe, '' argumentsRe = /<#(.*?)#>/g optionalArgumentsStart = completion.indexOf '{#' completion = completion.replace /\{#/g, '' completion = completion.replace /#\}/g, '' index = 0 completion = completion.replace argumentsRe, (match, arg, offset) -> index++ if optionalArgumentsStart > 0 and offset > optionalArgumentsStart return "${#{index}:optional #{arg}}" else return "${#{index}:#{arg}}" suggestion = {} suggestion.leftLabel = returnType if returnType? if index > 0 suggestion.snippet = completion else suggestion.text = completion if isConstMemFunc suggestion.displayText = completion + ' const' suggestion.description = comment if comment? suggestion.replacementPrefix = prefix suggestion handleCompletionResult: (result, returnCode, prefix) -> if returnCode is not 0 return unless atom.config.get "autocomplete-clang.ignoreClangErrors" # Find all completions that match our prefix in ONE regex # for performance reasons. completionsRe = new RegExp("^COMPLETION: (" + prefix + ".*)$", "mg") outputLines = result.match(completionsRe) if outputLines? return (@convertCompletionLine(line, prefix) for line in outputLines) else return []
77134
# autocomplete-plus provider code from https://github.com/benogle/autocomplete-clang # Copyright (c) 2015 <NAME> under MIT license # Clang related code from https://github.com/yasuyuky/autocomplete-clang {Range, CompositeDisposable} = require 'atom' path = require 'path' {spawnClang, buildCodeCompletionArgs} = require './clang-args-builder' {getScopeLang, prefixAtPosition, nearestSymbolPosition} = require './common-util' module.exports = class ClangProvider selector: 'c, cpp, .source.cpp, .source.c, .source.objc, .source.objcpp' inclusionPriority: 1 getSuggestions: ({editor, scopeDescriptor, bufferPosition}) -> language = getScopeLang scopeDescriptor.getScopesArray() prefix = prefixAtPosition(editor, bufferPosition) [symbolPosition,lastSymbol] = nearestSymbolPosition(editor, bufferPosition) minimumWordLength = atom.config.get('autocomplete-plus.minimumWordLength') if minimumWordLength? and prefix.length < minimumWordLength regex = /(?:\.|->|::)\s*\w*$/ line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]) return unless regex.test(line) if language? @codeCompletionAt(editor, symbolPosition.row, symbolPosition.column, language, prefix) codeCompletionAt: (editor, row, column, language, prefix) -> cwd = path.dirname editor.getPath() args = buildCodeCompletionArgs editor, row, column, language spawnClang cwd, args, editor.getText(), (code, outputs, errors, resolve) => console.log errors resolve(@handleCompletionResult(outputs, code, prefix)) convertCompletionLine: (line, prefix) -> contentRe = /^COMPLETION: (.*)/ [line, content] = line.match contentRe basicInfoRe = /^(.*?) : (.*)/ match = content.match basicInfoRe return {text: content} unless match? [content, basicInfo, completionAndComment] = match commentRe = /(?: : (.*))?$/ [completion, comment] = completionAndComment.split commentRe returnTypeRe = /^\[#(.*?)#\]/ returnType = completion.match(returnTypeRe)?[1] constMemFuncRe = /\[# const#\]$/ isConstMemFunc = constMemFuncRe.test completion infoTagsRe = /\[#(.*?)#\]/g completion = completion.replace infoTagsRe, '' argumentsRe = /<#(.*?)#>/g optionalArgumentsStart = completion.indexOf '{#' completion = completion.replace /\{#/g, '' completion = completion.replace /#\}/g, '' index = 0 completion = completion.replace argumentsRe, (match, arg, offset) -> index++ if optionalArgumentsStart > 0 and offset > optionalArgumentsStart return "${#{index}:optional #{arg}}" else return "${#{index}:#{arg}}" suggestion = {} suggestion.leftLabel = returnType if returnType? if index > 0 suggestion.snippet = completion else suggestion.text = completion if isConstMemFunc suggestion.displayText = completion + ' const' suggestion.description = comment if comment? suggestion.replacementPrefix = prefix suggestion handleCompletionResult: (result, returnCode, prefix) -> if returnCode is not 0 return unless atom.config.get "autocomplete-clang.ignoreClangErrors" # Find all completions that match our prefix in ONE regex # for performance reasons. completionsRe = new RegExp("^COMPLETION: (" + prefix + ".*)$", "mg") outputLines = result.match(completionsRe) if outputLines? return (@convertCompletionLine(line, prefix) for line in outputLines) else return []
true
# autocomplete-plus provider code from https://github.com/benogle/autocomplete-clang # Copyright (c) 2015 PI:NAME:<NAME>END_PI under MIT license # Clang related code from https://github.com/yasuyuky/autocomplete-clang {Range, CompositeDisposable} = require 'atom' path = require 'path' {spawnClang, buildCodeCompletionArgs} = require './clang-args-builder' {getScopeLang, prefixAtPosition, nearestSymbolPosition} = require './common-util' module.exports = class ClangProvider selector: 'c, cpp, .source.cpp, .source.c, .source.objc, .source.objcpp' inclusionPriority: 1 getSuggestions: ({editor, scopeDescriptor, bufferPosition}) -> language = getScopeLang scopeDescriptor.getScopesArray() prefix = prefixAtPosition(editor, bufferPosition) [symbolPosition,lastSymbol] = nearestSymbolPosition(editor, bufferPosition) minimumWordLength = atom.config.get('autocomplete-plus.minimumWordLength') if minimumWordLength? and prefix.length < minimumWordLength regex = /(?:\.|->|::)\s*\w*$/ line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]) return unless regex.test(line) if language? @codeCompletionAt(editor, symbolPosition.row, symbolPosition.column, language, prefix) codeCompletionAt: (editor, row, column, language, prefix) -> cwd = path.dirname editor.getPath() args = buildCodeCompletionArgs editor, row, column, language spawnClang cwd, args, editor.getText(), (code, outputs, errors, resolve) => console.log errors resolve(@handleCompletionResult(outputs, code, prefix)) convertCompletionLine: (line, prefix) -> contentRe = /^COMPLETION: (.*)/ [line, content] = line.match contentRe basicInfoRe = /^(.*?) : (.*)/ match = content.match basicInfoRe return {text: content} unless match? [content, basicInfo, completionAndComment] = match commentRe = /(?: : (.*))?$/ [completion, comment] = completionAndComment.split commentRe returnTypeRe = /^\[#(.*?)#\]/ returnType = completion.match(returnTypeRe)?[1] constMemFuncRe = /\[# const#\]$/ isConstMemFunc = constMemFuncRe.test completion infoTagsRe = /\[#(.*?)#\]/g completion = completion.replace infoTagsRe, '' argumentsRe = /<#(.*?)#>/g optionalArgumentsStart = completion.indexOf '{#' completion = completion.replace /\{#/g, '' completion = completion.replace /#\}/g, '' index = 0 completion = completion.replace argumentsRe, (match, arg, offset) -> index++ if optionalArgumentsStart > 0 and offset > optionalArgumentsStart return "${#{index}:optional #{arg}}" else return "${#{index}:#{arg}}" suggestion = {} suggestion.leftLabel = returnType if returnType? if index > 0 suggestion.snippet = completion else suggestion.text = completion if isConstMemFunc suggestion.displayText = completion + ' const' suggestion.description = comment if comment? suggestion.replacementPrefix = prefix suggestion handleCompletionResult: (result, returnCode, prefix) -> if returnCode is not 0 return unless atom.config.get "autocomplete-clang.ignoreClangErrors" # Find all completions that match our prefix in ONE regex # for performance reasons. completionsRe = new RegExp("^COMPLETION: (" + prefix + ".*)$", "mg") outputLines = result.match(completionsRe) if outputLines? return (@convertCompletionLine(line, prefix) for line in outputLines) else return []
[ { "context": "e-fetch\n# - underscore\n# - fuse.js\n#\n# Author:\n# ndaversa\n#\n# Contributions:\n# sjakubowski\n\n_ = require \"", "end": 387, "score": 0.9996685981750488, "start": 379, "tag": "USERNAME", "value": "ndaversa" }, { "context": "js\n#\n# Author:\n# ndaversa\n#\n#...
src/index.coffee
argo1984/hubot-jira-bot
0
# Description: # Lets you search for JIRA tickets, open # them, transition them thru different states, comment on them, rank # them up or down, start or stop watching them or change who is # assigned to a ticket. Also, notifications for mentions, assignments and watched tickets. # # Dependencies: # - moment # - octokat # - node-fetch # - underscore # - fuse.js # # Author: # ndaversa # # Contributions: # sjakubowski _ = require "underscore" moment = require "moment" Config = require "./config" Github = require "./github" Help = require "./help" Jira = require "./jira" Adapters = require "./adapters" Utils = require "./utils" class JiraBot constructor: (@robot) -> return new JiraBot @robot unless @ instanceof JiraBot Utils.robot = @robot Utils.JiraBot = @ @webhook = new Jira.Webhook @robot switch @robot.adapterName when "slack" @adapter = new Adapters.Slack @robot else @adapter = new Adapters.Generic @robot @registerWebhookListeners() @registerEventListeners() @registerRobotResponses() send: (context, message, filter=yes) -> context = @adapter.normalizeContext context message = @filterAttachmentsForPreviousMentions context, message if filter @adapter.send context, message filterAttachmentsForPreviousMentions: (context, message) -> return message if _(message).isString() return message unless message.attachments?.length > 0 room = context.message.room removals = [] for attachment in message.attachments when attachment and attachment.type is "JiraTicketAttachment" ticket = attachment.author_name?.trim().toUpperCase() continue unless Config.ticket.regex.test ticket key = "#{room}:#{ticket}" if Utils.cache.get key removals.push attachment Utils.Stats.increment "jirabot.surpress.attachment" @robot.logger.debug "Supressing ticket attachment for #{ticket} in #{@adapter.getRoomName context}" else Utils.cache.put key, true, Config.cache.mention.expiry message.attachments = _(message.attachments).difference removals return message matchJiraTicket: (context) -> if context.match? matches = context.match Config.ticket.regexGlobal unless matches and matches[0] urlMatch = context.match Config.jira.urlRegex if urlMatch and urlMatch[1] matches = [ urlMatch[1] ] if matches and matches[0] return matches else if context.message?.attachments? attachments = context.message.attachments for attachment in attachments when attachment.text? matches = attachment.text.match Config.ticket.regexGlobal if matches and matches[0] return matches return false prepareResponseForJiraTickets: (context) -> Promise.all(context.match.map (key) => _attachments = [] Jira.Create.fromKey(key).then (ticket) -> _attachments.push ticket.toAttachment() ticket .then (ticket) -> Github.PullRequests.fromKey ticket.key unless Config.github.disabled .then (prs) -> prs?.toAttachment() .then (attachments) -> _attachments.push a for a in attachments if attachments _attachments ).then (attachments) => @send context, attachments: _(attachments).flatten() .catch (error) => @send context, "#{error}" @robot.logger.error error.stack registerWebhookListeners: -> # Watchers disableDisclaimer = """ If you wish to stop receiving notifications for the tickets you are watching, reply with: > jira disable notifications """ @robot.on "JiraWebhookTicketInProgress", (ticket, event) => assignee = Utils.lookupUserWithJira ticket.fields.assignee assigneeText = "." assigneeText = " by #{assignee}" if assignee isnt "Unassigned" @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching is now being worked on#{assigneeText} """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.inprogress" @robot.on "JiraWebhookTicketInReview", (ticket, event) => assignee = Utils.lookupUserWithJira ticket.fields.assignee assigneeText = "" assigneeText = "Please message #{assignee} if you wish to provide feedback." if assignee isnt "Unassigned" @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching is now ready for review. #{assigneeText} """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.inreview" @robot.on "JiraWebhookTicketDone", (ticket, event) => @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching has been marked `Done`. """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.done" # Comment notifications for watchers @robot.on "JiraWebhookTicketComment", (ticket, comment) => @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching has a new comment from #{comment.author.displayName}: ``` #{comment.body} ``` """ author: comment.author footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.comment" # Comment notifications for assignee @robot.on "JiraWebhookTicketComment", (ticket, comment) => return unless ticket.fields.assignee return if ticket.watchers.length > 0 and _(ticket.watchers).findWhere name: ticket.fields.assignee.name @adapter.dm Utils.lookupChatUsersWithJira(ticket.fields.assignee), text: """ A ticket you are assigned to has a new comment from #{comment.author.displayName}: ``` #{comment.body} ``` """ author: comment.author footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.comment" # Mentions @robot.on "JiraWebhookTicketMention", (ticket, user, event, context) => return if not _(ticket.watchers).findWhere name: user @adapter.dm user, text: """ You were mentioned in a ticket by #{event.user.displayName}: ``` #{context} ``` """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.mention" # Assigned @robot.on "JiraWebhookTicketAssigned", (ticket, user, event) => @adapter.dm user, text: """ You were assigned to a ticket by #{event.user.displayName}: """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.assigned" registerEventListeners: -> #Find Matches (for cross-script usage) @robot.on "JiraFindTicketMatches", (context, cb) => cb @matchJiraTicket context #Prepare Responses For Tickets (for cross-script usage) @robot.on "JiraPrepareResponseForTickets", (context) => @prepareResponseForJiraTickets context #Create @robot.on "JiraTicketCreated", (context, details) => @send context, text: "Ticket created" attachments: [ details.ticket.toAttachment no details.assignee details.transition ] Utils.Stats.increment "jirabot.ticket.create.success" @robot.on "JiraTicketCreationFailed", (error, context) => robot.logger.error error.stack @send context, "Unable to create ticket #{error}" Utils.Stats.increment "jirabot.ticket.create.failed" #Created in another room @robot.on "JiraTicketCreatedElsewhere", (context, details) => room = @adapter.getRoom context for r in Utils.lookupRoomsForProject details.ticket.fields.project.key @send r, text: "Ticket created in <##{room.id}|#{room.name}> by <@#{context.message.user.id}>" attachments: [ details.ticket.toAttachment no details.assignee details.transition ] Utils.Stats.increment "jirabot.ticket.create.elsewhere" #Clone @robot.on "JiraTicketCloned", (ticket, channel, clone, context) => room = @adapter.getRoom context @send channel, text: "Ticket created: Cloned from #{clone} in <##{room.id}|#{room.name}> by <@#{context.message.user.id}>" attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.ticket.clone.success" @robot.on "JiraTicketCloneFailed", (error, ticket, context) => @robot.logger.error error.stack room = @adapter.getRoom context @send context, "Unable to clone `#{ticket}` to the <\##{room.id}|#{room.name}> project :sadpanda:\n```#{error}```" Utils.Stats.increment "jirabot.ticket.clone.failed" #Transition @robot.on "JiraTicketTransitioned", (ticket, transition, context, includeAttachment=no) => @send context, text: "Transitioned #{ticket.key} to `#{transition.to.name}`" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.transition.success" @robot.on "JiraTicketTransitionFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.transition.failed" #Assign @robot.on "JiraTicketAssigned", (ticket, user, context, includeAttachment=no) => @send context, text: "Assigned <@#{user.id}> to #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.assign.success" @robot.on "JiraTicketUnassigned", (ticket, context, includeAttachment=no) => @send context, text: "#{ticket.key} is now unassigned" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.unassign.success" @robot.on "JiraTicketAssignmentFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.assign.failed" #Watch @robot.on "JiraTicketWatched", (ticket, user, context, includeAttachment=no) => @send context, text: "Added <@#{user.id}> as a watcher on #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.watch.success" @robot.on "JiraTicketUnwatched", (ticket, user, context, includeAttachment=no) => @send context, text: "Removed <@#{user.id}> as a watcher on #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.unwatch.success" @robot.on "JiraTicketWatchFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.watch.failed" #Rank @robot.on "JiraTicketRanked", (ticket, direction, context, includeAttachment=no) => @send context, text: "Ranked #{ticket.key} to `#{direction}`" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.rank.success" @robot.on "JiraTicketRankFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.rank.failed" #Labels @robot.on "JiraTicketLabelled", (ticket, context, includeAttachment=no) => @send context, text: "Added labels to #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.label.success" @robot.on "JiraTicketLabelFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.label.failed" #Comments @robot.on "JiraTicketCommented", (ticket, context, includeAttachment=no) => @send context, text: "Added comment to #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.comment.success" @robot.on "JiraTicketCommentFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.comment.failed" registerRobotResponses: -> #Help @robot.respond Config.help.regex, (context) => context.finish() [ __, topic] = context.match @send context, Help.forTopic topic, @robot Utils.Stats.increment "command.jirabot.help" #Enable/Disable Watch Notifications @robot.respond Config.watch.notificationsRegex, (context) => context.finish() [ __, state ] = context.match switch state when "allow", "start", "enable" @adapter.enableNotificationsFor context.message.user @send context, """ JIRA Watch notifications have been *enabled* You will start receiving notifications for JIRA tickets you are watching If you wish to _disable_ them just send me this message: > jira disable notifications """ when "disallow", "stop", "disable" @adapter.disableNotificationsFor context.message.user @send context, """ JIRA Watch notifications have been *disabled* You will no longer receive notifications for JIRA tickets you are watching If you wish to _enable_ them again just send me this message: > jira enable notifications """ Utils.Stats.increment "command.jirabot.toggleNotifications" #Search @robot.respond Config.search.regex, (context) => context.finish() [__, query] = context.match room = context.message.room project = Config.maps.projects[room] Jira.Search.withQueryForProject(query, project, context) .then (results) => attachments = (ticket.toAttachment() for ticket in results.tickets) @send context, text: results.text attachments: attachments , no .catch (error) => @send context, "Unable to search for `#{query}` :sadpanda:" @robot.logger.error error.stack Utils.Stats.increment "command.jirabot.search" #Query @robot.respond Config.query.regex, (context) => context.finish() [__, query] = context.match Jira.Query.withQuery(query) .then (results) => attachments = (ticket.toAttachment(no) for ticket in results.tickets) @send context, text: results.text attachments: attachments , no .catch (error) => @send context, "Unable to execute query `#{query}` :sadpanda:" @robot.logger.error error.stack Utils.Stats.increment "command.jirabot.query" #Transition if Config.maps.transitions @robot.hear Config.transitions.regex, (context) => context.finish() [ __, key, toState ] = context.match Jira.Transition.forTicketKeyToState key, toState, context, no Utils.Stats.increment "command.jirabot.transition" #Clone @robot.hear Config.clone.regex, (context) => context.finish() [ __, ticket, channel ] = context.match project = Config.maps.projects[channel] Jira.Clone.fromTicketKeyToProject ticket, project, channel, context Utils.Stats.increment "command.jirabot.clone" #Watch @robot.hear Config.watch.regex, (context) => context.finish() [ __, key, remove, person ] = context.match if remove Jira.Watch.forTicketKeyRemovePerson key, person, context, no else Jira.Watch.forTicketKeyForPerson key, person, context, no Utils.Stats.increment "command.jirabot.watch" #Rank @robot.hear Config.rank.regex, (context) => context.finish() [ __, key, direction ] = context.match Jira.Rank.forTicketKeyByDirection key, direction, context, no Utils.Stats.increment "command.jirabot.rank" #Labels @robot.hear Config.labels.addRegex, (context) => context.finish() [ __, key ] = context.match {input: input} = context.match labels = [] labels = (input.match(Config.labels.regex).map((label) -> label.replace('#', '').trim())).concat(labels) Jira.Labels.forTicketKeyWith key, labels, context, no Utils.Stats.increment "command.jirabot.label" #Comment @robot.hear Config.comment.regex, (context) => context.finish() [ __, key, comment ] = context.match Jira.Comment.forTicketKeyWith key, comment, context, no Utils.Stats.increment "command.jirabot.comment" #Subtask @robot.respond Config.subtask.regex, (context) => context.finish() [ __, key, summary ] = context.match Jira.Create.subtaskFromKeyWith key, summary, context Utils.Stats.increment "command.jirabot.subtask" #Assign @robot.hear Config.assign.regex, (context) => context.finish() [ __, key, remove, person ] = context.match if remove Jira.Assign.forTicketKeyToUnassigned key, context, no else Jira.Assign.forTicketKeyToPerson key, person, context, no Utils.Stats.increment "command.jirabot.assign" #Create @robot.respond Config.commands.regex, (context) => [ __, project, command, summary ] = context.match room = project or @adapter.getRoomName context project = Config.maps.projects[room.toLowerCase()] type = Config.maps.types[command.toLowerCase()] unless project channels = [] for team, key of Config.maps.projects room = @adapter.getRoom team channels.push " <\##{room.id}|#{room.name}>" if room return context.reply "#{type} must be submitted in one of the following project channels: #{channels}" if Config.duplicates.detection and @adapter.detectForDuplicates? @adapter.detectForDuplicates project, type, summary, context else Jira.Create.with project, type, summary, context Utils.Stats.increment "command.jirabot.create" unless Config.jira.mentionsDisabled #Mention ticket by url or key @robot.listen @matchJiraTicket, (context) => @prepareResponseForJiraTickets context Utils.Stats.increment "command.jirabot.mention.ticket" module.exports = JiraBot
182562
# Description: # Lets you search for JIRA tickets, open # them, transition them thru different states, comment on them, rank # them up or down, start or stop watching them or change who is # assigned to a ticket. Also, notifications for mentions, assignments and watched tickets. # # Dependencies: # - moment # - octokat # - node-fetch # - underscore # - fuse.js # # Author: # ndaversa # # Contributions: # sjakubowski _ = require "underscore" moment = require "moment" Config = require "./config" Github = require "./github" Help = require "./help" Jira = require "./jira" Adapters = require "./adapters" Utils = require "./utils" class JiraBot constructor: (@robot) -> return new JiraBot @robot unless @ instanceof JiraBot Utils.robot = @robot Utils.JiraBot = @ @webhook = new Jira.Webhook @robot switch @robot.adapterName when "slack" @adapter = new Adapters.Slack @robot else @adapter = new Adapters.Generic @robot @registerWebhookListeners() @registerEventListeners() @registerRobotResponses() send: (context, message, filter=yes) -> context = @adapter.normalizeContext context message = @filterAttachmentsForPreviousMentions context, message if filter @adapter.send context, message filterAttachmentsForPreviousMentions: (context, message) -> return message if _(message).isString() return message unless message.attachments?.length > 0 room = context.message.room removals = [] for attachment in message.attachments when attachment and attachment.type is "JiraTicketAttachment" ticket = attachment.author_name?.trim().toUpperCase() continue unless Config.ticket.regex.test ticket key = <KEY> if Utils.cache.get key removals.push attachment Utils.Stats.increment "jirabot.surpress.attachment" @robot.logger.debug "Supressing ticket attachment for #{ticket} in #{@adapter.getRoomName context}" else Utils.cache.put key, true, Config.cache.mention.expiry message.attachments = _(message.attachments).difference removals return message matchJiraTicket: (context) -> if context.match? matches = context.match Config.ticket.regexGlobal unless matches and matches[0] urlMatch = context.match Config.jira.urlRegex if urlMatch and urlMatch[1] matches = [ urlMatch[1] ] if matches and matches[0] return matches else if context.message?.attachments? attachments = context.message.attachments for attachment in attachments when attachment.text? matches = attachment.text.match Config.ticket.regexGlobal if matches and matches[0] return matches return false prepareResponseForJiraTickets: (context) -> Promise.all(context.match.map (key) => _attachments = [] Jira.Create.fromKey(key).then (ticket) -> _attachments.push ticket.toAttachment() ticket .then (ticket) -> Github.PullRequests.fromKey ticket.key unless Config.github.disabled .then (prs) -> prs?.toAttachment() .then (attachments) -> _attachments.push a for a in attachments if attachments _attachments ).then (attachments) => @send context, attachments: _(attachments).flatten() .catch (error) => @send context, "#{error}" @robot.logger.error error.stack registerWebhookListeners: -> # Watchers disableDisclaimer = """ If you wish to stop receiving notifications for the tickets you are watching, reply with: > jira disable notifications """ @robot.on "JiraWebhookTicketInProgress", (ticket, event) => assignee = Utils.lookupUserWithJira ticket.fields.assignee assigneeText = "." assigneeText = " by #{assignee}" if assignee isnt "Unassigned" @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching is now being worked on#{assigneeText} """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.inprogress" @robot.on "JiraWebhookTicketInReview", (ticket, event) => assignee = Utils.lookupUserWithJira ticket.fields.assignee assigneeText = "" assigneeText = "Please message #{assignee} if you wish to provide feedback." if assignee isnt "Unassigned" @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching is now ready for review. #{assigneeText} """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.inreview" @robot.on "JiraWebhookTicketDone", (ticket, event) => @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching has been marked `Done`. """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.done" # Comment notifications for watchers @robot.on "JiraWebhookTicketComment", (ticket, comment) => @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching has a new comment from #{comment.author.displayName}: ``` #{comment.body} ``` """ author: comment.author footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.comment" # Comment notifications for assignee @robot.on "JiraWebhookTicketComment", (ticket, comment) => return unless ticket.fields.assignee return if ticket.watchers.length > 0 and _(ticket.watchers).findWhere name: ticket.fields.assignee.name @adapter.dm Utils.lookupChatUsersWithJira(ticket.fields.assignee), text: """ A ticket you are assigned to has a new comment from #{comment.author.displayName}: ``` #{comment.body} ``` """ author: comment.author footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.comment" # Mentions @robot.on "JiraWebhookTicketMention", (ticket, user, event, context) => return if not _(ticket.watchers).findWhere name: user @adapter.dm user, text: """ You were mentioned in a ticket by #{event.user.displayName}: ``` #{context} ``` """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.mention" # Assigned @robot.on "JiraWebhookTicketAssigned", (ticket, user, event) => @adapter.dm user, text: """ You were assigned to a ticket by #{event.user.displayName}: """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.assigned" registerEventListeners: -> #Find Matches (for cross-script usage) @robot.on "JiraFindTicketMatches", (context, cb) => cb @matchJiraTicket context #Prepare Responses For Tickets (for cross-script usage) @robot.on "JiraPrepareResponseForTickets", (context) => @prepareResponseForJiraTickets context #Create @robot.on "JiraTicketCreated", (context, details) => @send context, text: "Ticket created" attachments: [ details.ticket.toAttachment no details.assignee details.transition ] Utils.Stats.increment "jirabot.ticket.create.success" @robot.on "JiraTicketCreationFailed", (error, context) => robot.logger.error error.stack @send context, "Unable to create ticket #{error}" Utils.Stats.increment "jirabot.ticket.create.failed" #Created in another room @robot.on "JiraTicketCreatedElsewhere", (context, details) => room = @adapter.getRoom context for r in Utils.lookupRoomsForProject details.ticket.fields.project.key @send r, text: "Ticket created in <##{room.id}|#{room.name}> by <@#{context.message.user.id}>" attachments: [ details.ticket.toAttachment no details.assignee details.transition ] Utils.Stats.increment "jirabot.ticket.create.elsewhere" #Clone @robot.on "JiraTicketCloned", (ticket, channel, clone, context) => room = @adapter.getRoom context @send channel, text: "Ticket created: Cloned from #{clone} in <##{room.id}|#{room.name}> by <@#{context.message.user.id}>" attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.ticket.clone.success" @robot.on "JiraTicketCloneFailed", (error, ticket, context) => @robot.logger.error error.stack room = @adapter.getRoom context @send context, "Unable to clone `#{ticket}` to the <\##{room.id}|#{room.name}> project :sadpanda:\n```#{error}```" Utils.Stats.increment "jirabot.ticket.clone.failed" #Transition @robot.on "JiraTicketTransitioned", (ticket, transition, context, includeAttachment=no) => @send context, text: "Transitioned #{ticket.key} to `#{transition.to.name}`" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.transition.success" @robot.on "JiraTicketTransitionFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.transition.failed" #Assign @robot.on "JiraTicketAssigned", (ticket, user, context, includeAttachment=no) => @send context, text: "Assigned <@#{user.id}> to #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.assign.success" @robot.on "JiraTicketUnassigned", (ticket, context, includeAttachment=no) => @send context, text: "#{ticket.key} is now unassigned" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.unassign.success" @robot.on "JiraTicketAssignmentFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.assign.failed" #Watch @robot.on "JiraTicketWatched", (ticket, user, context, includeAttachment=no) => @send context, text: "Added <@#{user.id}> as a watcher on #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.watch.success" @robot.on "JiraTicketUnwatched", (ticket, user, context, includeAttachment=no) => @send context, text: "Removed <@#{user.id}> as a watcher on #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.unwatch.success" @robot.on "JiraTicketWatchFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.watch.failed" #Rank @robot.on "JiraTicketRanked", (ticket, direction, context, includeAttachment=no) => @send context, text: "Ranked #{ticket.key} to `#{direction}`" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.rank.success" @robot.on "JiraTicketRankFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.rank.failed" #Labels @robot.on "JiraTicketLabelled", (ticket, context, includeAttachment=no) => @send context, text: "Added labels to #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.label.success" @robot.on "JiraTicketLabelFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.label.failed" #Comments @robot.on "JiraTicketCommented", (ticket, context, includeAttachment=no) => @send context, text: "Added comment to #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.comment.success" @robot.on "JiraTicketCommentFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.comment.failed" registerRobotResponses: -> #Help @robot.respond Config.help.regex, (context) => context.finish() [ __, topic] = context.match @send context, Help.forTopic topic, @robot Utils.Stats.increment "command.jirabot.help" #Enable/Disable Watch Notifications @robot.respond Config.watch.notificationsRegex, (context) => context.finish() [ __, state ] = context.match switch state when "allow", "start", "enable" @adapter.enableNotificationsFor context.message.user @send context, """ JIRA Watch notifications have been *enabled* You will start receiving notifications for JIRA tickets you are watching If you wish to _disable_ them just send me this message: > jira disable notifications """ when "disallow", "stop", "disable" @adapter.disableNotificationsFor context.message.user @send context, """ JIRA Watch notifications have been *disabled* You will no longer receive notifications for JIRA tickets you are watching If you wish to _enable_ them again just send me this message: > jira enable notifications """ Utils.Stats.increment "command.jirabot.toggleNotifications" #Search @robot.respond Config.search.regex, (context) => context.finish() [__, query] = context.match room = context.message.room project = Config.maps.projects[room] Jira.Search.withQueryForProject(query, project, context) .then (results) => attachments = (ticket.toAttachment() for ticket in results.tickets) @send context, text: results.text attachments: attachments , no .catch (error) => @send context, "Unable to search for `#{query}` :sadpanda:" @robot.logger.error error.stack Utils.Stats.increment "command.jirabot.search" #Query @robot.respond Config.query.regex, (context) => context.finish() [__, query] = context.match Jira.Query.withQuery(query) .then (results) => attachments = (ticket.toAttachment(no) for ticket in results.tickets) @send context, text: results.text attachments: attachments , no .catch (error) => @send context, "Unable to execute query `#{query}` :sadpanda:" @robot.logger.error error.stack Utils.Stats.increment "command.jirabot.query" #Transition if Config.maps.transitions @robot.hear Config.transitions.regex, (context) => context.finish() [ __, key, toState ] = context.match Jira.Transition.forTicketKeyToState key, toState, context, no Utils.Stats.increment "command.jirabot.transition" #Clone @robot.hear Config.clone.regex, (context) => context.finish() [ __, ticket, channel ] = context.match project = Config.maps.projects[channel] Jira.Clone.fromTicketKeyToProject ticket, project, channel, context Utils.Stats.increment "command.jirabot.clone" #Watch @robot.hear Config.watch.regex, (context) => context.finish() [ __, key, remove, person ] = context.match if remove Jira.Watch.forTicketKeyRemovePerson key, person, context, no else Jira.Watch.forTicketKeyForPerson key, person, context, no Utils.Stats.increment "command.jirabot.watch" #Rank @robot.hear Config.rank.regex, (context) => context.finish() [ __, key, direction ] = context.match Jira.Rank.forTicketKeyByDirection key, direction, context, no Utils.Stats.increment "command.jirabot.rank" #Labels @robot.hear Config.labels.addRegex, (context) => context.finish() [ __, key ] = context.match {input: input} = context.match labels = [] labels = (input.match(Config.labels.regex).map((label) -> label.replace('#', '').trim())).concat(labels) Jira.Labels.forTicketKeyWith key, labels, context, no Utils.Stats.increment "command.jirabot.label" #Comment @robot.hear Config.comment.regex, (context) => context.finish() [ __, key, comment ] = context.match Jira.Comment.forTicketKeyWith key, comment, context, no Utils.Stats.increment "command.jirabot.comment" #Subtask @robot.respond Config.subtask.regex, (context) => context.finish() [ __, key, summary ] = context.match Jira.Create.subtaskFromKeyWith key, summary, context Utils.Stats.increment "command.jirabot.subtask" #Assign @robot.hear Config.assign.regex, (context) => context.finish() [ __, key, remove, person ] = context.match if remove Jira.Assign.forTicketKeyToUnassigned key, context, no else Jira.Assign.forTicketKeyToPerson key, person, context, no Utils.Stats.increment "command.jirabot.assign" #Create @robot.respond Config.commands.regex, (context) => [ __, project, command, summary ] = context.match room = project or @adapter.getRoomName context project = Config.maps.projects[room.toLowerCase()] type = Config.maps.types[command.toLowerCase()] unless project channels = [] for team, key of Config.maps.projects room = @adapter.getRoom team channels.push " <\##{room.id}|#{room.name}>" if room return context.reply "#{type} must be submitted in one of the following project channels: #{channels}" if Config.duplicates.detection and @adapter.detectForDuplicates? @adapter.detectForDuplicates project, type, summary, context else Jira.Create.with project, type, summary, context Utils.Stats.increment "command.jirabot.create" unless Config.jira.mentionsDisabled #Mention ticket by url or key @robot.listen @matchJiraTicket, (context) => @prepareResponseForJiraTickets context Utils.Stats.increment "command.jirabot.mention.ticket" module.exports = JiraBot
true
# Description: # Lets you search for JIRA tickets, open # them, transition them thru different states, comment on them, rank # them up or down, start or stop watching them or change who is # assigned to a ticket. Also, notifications for mentions, assignments and watched tickets. # # Dependencies: # - moment # - octokat # - node-fetch # - underscore # - fuse.js # # Author: # ndaversa # # Contributions: # sjakubowski _ = require "underscore" moment = require "moment" Config = require "./config" Github = require "./github" Help = require "./help" Jira = require "./jira" Adapters = require "./adapters" Utils = require "./utils" class JiraBot constructor: (@robot) -> return new JiraBot @robot unless @ instanceof JiraBot Utils.robot = @robot Utils.JiraBot = @ @webhook = new Jira.Webhook @robot switch @robot.adapterName when "slack" @adapter = new Adapters.Slack @robot else @adapter = new Adapters.Generic @robot @registerWebhookListeners() @registerEventListeners() @registerRobotResponses() send: (context, message, filter=yes) -> context = @adapter.normalizeContext context message = @filterAttachmentsForPreviousMentions context, message if filter @adapter.send context, message filterAttachmentsForPreviousMentions: (context, message) -> return message if _(message).isString() return message unless message.attachments?.length > 0 room = context.message.room removals = [] for attachment in message.attachments when attachment and attachment.type is "JiraTicketAttachment" ticket = attachment.author_name?.trim().toUpperCase() continue unless Config.ticket.regex.test ticket key = PI:KEY:<KEY>END_PI if Utils.cache.get key removals.push attachment Utils.Stats.increment "jirabot.surpress.attachment" @robot.logger.debug "Supressing ticket attachment for #{ticket} in #{@adapter.getRoomName context}" else Utils.cache.put key, true, Config.cache.mention.expiry message.attachments = _(message.attachments).difference removals return message matchJiraTicket: (context) -> if context.match? matches = context.match Config.ticket.regexGlobal unless matches and matches[0] urlMatch = context.match Config.jira.urlRegex if urlMatch and urlMatch[1] matches = [ urlMatch[1] ] if matches and matches[0] return matches else if context.message?.attachments? attachments = context.message.attachments for attachment in attachments when attachment.text? matches = attachment.text.match Config.ticket.regexGlobal if matches and matches[0] return matches return false prepareResponseForJiraTickets: (context) -> Promise.all(context.match.map (key) => _attachments = [] Jira.Create.fromKey(key).then (ticket) -> _attachments.push ticket.toAttachment() ticket .then (ticket) -> Github.PullRequests.fromKey ticket.key unless Config.github.disabled .then (prs) -> prs?.toAttachment() .then (attachments) -> _attachments.push a for a in attachments if attachments _attachments ).then (attachments) => @send context, attachments: _(attachments).flatten() .catch (error) => @send context, "#{error}" @robot.logger.error error.stack registerWebhookListeners: -> # Watchers disableDisclaimer = """ If you wish to stop receiving notifications for the tickets you are watching, reply with: > jira disable notifications """ @robot.on "JiraWebhookTicketInProgress", (ticket, event) => assignee = Utils.lookupUserWithJira ticket.fields.assignee assigneeText = "." assigneeText = " by #{assignee}" if assignee isnt "Unassigned" @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching is now being worked on#{assigneeText} """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.inprogress" @robot.on "JiraWebhookTicketInReview", (ticket, event) => assignee = Utils.lookupUserWithJira ticket.fields.assignee assigneeText = "" assigneeText = "Please message #{assignee} if you wish to provide feedback." if assignee isnt "Unassigned" @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching is now ready for review. #{assigneeText} """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.inreview" @robot.on "JiraWebhookTicketDone", (ticket, event) => @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching has been marked `Done`. """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.done" # Comment notifications for watchers @robot.on "JiraWebhookTicketComment", (ticket, comment) => @adapter.dm Utils.lookupChatUsersWithJira(ticket.watchers), text: """ A ticket you are watching has a new comment from #{comment.author.displayName}: ``` #{comment.body} ``` """ author: comment.author footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.comment" # Comment notifications for assignee @robot.on "JiraWebhookTicketComment", (ticket, comment) => return unless ticket.fields.assignee return if ticket.watchers.length > 0 and _(ticket.watchers).findWhere name: ticket.fields.assignee.name @adapter.dm Utils.lookupChatUsersWithJira(ticket.fields.assignee), text: """ A ticket you are assigned to has a new comment from #{comment.author.displayName}: ``` #{comment.body} ``` """ author: comment.author footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.comment" # Mentions @robot.on "JiraWebhookTicketMention", (ticket, user, event, context) => return if not _(ticket.watchers).findWhere name: user @adapter.dm user, text: """ You were mentioned in a ticket by #{event.user.displayName}: ``` #{context} ``` """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.mention" # Assigned @robot.on "JiraWebhookTicketAssigned", (ticket, user, event) => @adapter.dm user, text: """ You were assigned to a ticket by #{event.user.displayName}: """ author: event.user footer: disableDisclaimer attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.webhook.ticket.assigned" registerEventListeners: -> #Find Matches (for cross-script usage) @robot.on "JiraFindTicketMatches", (context, cb) => cb @matchJiraTicket context #Prepare Responses For Tickets (for cross-script usage) @robot.on "JiraPrepareResponseForTickets", (context) => @prepareResponseForJiraTickets context #Create @robot.on "JiraTicketCreated", (context, details) => @send context, text: "Ticket created" attachments: [ details.ticket.toAttachment no details.assignee details.transition ] Utils.Stats.increment "jirabot.ticket.create.success" @robot.on "JiraTicketCreationFailed", (error, context) => robot.logger.error error.stack @send context, "Unable to create ticket #{error}" Utils.Stats.increment "jirabot.ticket.create.failed" #Created in another room @robot.on "JiraTicketCreatedElsewhere", (context, details) => room = @adapter.getRoom context for r in Utils.lookupRoomsForProject details.ticket.fields.project.key @send r, text: "Ticket created in <##{room.id}|#{room.name}> by <@#{context.message.user.id}>" attachments: [ details.ticket.toAttachment no details.assignee details.transition ] Utils.Stats.increment "jirabot.ticket.create.elsewhere" #Clone @robot.on "JiraTicketCloned", (ticket, channel, clone, context) => room = @adapter.getRoom context @send channel, text: "Ticket created: Cloned from #{clone} in <##{room.id}|#{room.name}> by <@#{context.message.user.id}>" attachments: [ ticket.toAttachment no ] Utils.Stats.increment "jirabot.ticket.clone.success" @robot.on "JiraTicketCloneFailed", (error, ticket, context) => @robot.logger.error error.stack room = @adapter.getRoom context @send context, "Unable to clone `#{ticket}` to the <\##{room.id}|#{room.name}> project :sadpanda:\n```#{error}```" Utils.Stats.increment "jirabot.ticket.clone.failed" #Transition @robot.on "JiraTicketTransitioned", (ticket, transition, context, includeAttachment=no) => @send context, text: "Transitioned #{ticket.key} to `#{transition.to.name}`" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.transition.success" @robot.on "JiraTicketTransitionFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.transition.failed" #Assign @robot.on "JiraTicketAssigned", (ticket, user, context, includeAttachment=no) => @send context, text: "Assigned <@#{user.id}> to #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.assign.success" @robot.on "JiraTicketUnassigned", (ticket, context, includeAttachment=no) => @send context, text: "#{ticket.key} is now unassigned" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.unassign.success" @robot.on "JiraTicketAssignmentFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.assign.failed" #Watch @robot.on "JiraTicketWatched", (ticket, user, context, includeAttachment=no) => @send context, text: "Added <@#{user.id}> as a watcher on #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.watch.success" @robot.on "JiraTicketUnwatched", (ticket, user, context, includeAttachment=no) => @send context, text: "Removed <@#{user.id}> as a watcher on #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.unwatch.success" @robot.on "JiraTicketWatchFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.watch.failed" #Rank @robot.on "JiraTicketRanked", (ticket, direction, context, includeAttachment=no) => @send context, text: "Ranked #{ticket.key} to `#{direction}`" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.rank.success" @robot.on "JiraTicketRankFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.rank.failed" #Labels @robot.on "JiraTicketLabelled", (ticket, context, includeAttachment=no) => @send context, text: "Added labels to #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.label.success" @robot.on "JiraTicketLabelFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.label.failed" #Comments @robot.on "JiraTicketCommented", (ticket, context, includeAttachment=no) => @send context, text: "Added comment to #{ticket.key}" attachments: [ ticket.toAttachment no ] if includeAttachment Utils.Stats.increment "jirabot.ticket.comment.success" @robot.on "JiraTicketCommentFailed", (error, context) => @robot.logger.error error.stack @send context, "#{error}" Utils.Stats.increment "jirabot.ticket.comment.failed" registerRobotResponses: -> #Help @robot.respond Config.help.regex, (context) => context.finish() [ __, topic] = context.match @send context, Help.forTopic topic, @robot Utils.Stats.increment "command.jirabot.help" #Enable/Disable Watch Notifications @robot.respond Config.watch.notificationsRegex, (context) => context.finish() [ __, state ] = context.match switch state when "allow", "start", "enable" @adapter.enableNotificationsFor context.message.user @send context, """ JIRA Watch notifications have been *enabled* You will start receiving notifications for JIRA tickets you are watching If you wish to _disable_ them just send me this message: > jira disable notifications """ when "disallow", "stop", "disable" @adapter.disableNotificationsFor context.message.user @send context, """ JIRA Watch notifications have been *disabled* You will no longer receive notifications for JIRA tickets you are watching If you wish to _enable_ them again just send me this message: > jira enable notifications """ Utils.Stats.increment "command.jirabot.toggleNotifications" #Search @robot.respond Config.search.regex, (context) => context.finish() [__, query] = context.match room = context.message.room project = Config.maps.projects[room] Jira.Search.withQueryForProject(query, project, context) .then (results) => attachments = (ticket.toAttachment() for ticket in results.tickets) @send context, text: results.text attachments: attachments , no .catch (error) => @send context, "Unable to search for `#{query}` :sadpanda:" @robot.logger.error error.stack Utils.Stats.increment "command.jirabot.search" #Query @robot.respond Config.query.regex, (context) => context.finish() [__, query] = context.match Jira.Query.withQuery(query) .then (results) => attachments = (ticket.toAttachment(no) for ticket in results.tickets) @send context, text: results.text attachments: attachments , no .catch (error) => @send context, "Unable to execute query `#{query}` :sadpanda:" @robot.logger.error error.stack Utils.Stats.increment "command.jirabot.query" #Transition if Config.maps.transitions @robot.hear Config.transitions.regex, (context) => context.finish() [ __, key, toState ] = context.match Jira.Transition.forTicketKeyToState key, toState, context, no Utils.Stats.increment "command.jirabot.transition" #Clone @robot.hear Config.clone.regex, (context) => context.finish() [ __, ticket, channel ] = context.match project = Config.maps.projects[channel] Jira.Clone.fromTicketKeyToProject ticket, project, channel, context Utils.Stats.increment "command.jirabot.clone" #Watch @robot.hear Config.watch.regex, (context) => context.finish() [ __, key, remove, person ] = context.match if remove Jira.Watch.forTicketKeyRemovePerson key, person, context, no else Jira.Watch.forTicketKeyForPerson key, person, context, no Utils.Stats.increment "command.jirabot.watch" #Rank @robot.hear Config.rank.regex, (context) => context.finish() [ __, key, direction ] = context.match Jira.Rank.forTicketKeyByDirection key, direction, context, no Utils.Stats.increment "command.jirabot.rank" #Labels @robot.hear Config.labels.addRegex, (context) => context.finish() [ __, key ] = context.match {input: input} = context.match labels = [] labels = (input.match(Config.labels.regex).map((label) -> label.replace('#', '').trim())).concat(labels) Jira.Labels.forTicketKeyWith key, labels, context, no Utils.Stats.increment "command.jirabot.label" #Comment @robot.hear Config.comment.regex, (context) => context.finish() [ __, key, comment ] = context.match Jira.Comment.forTicketKeyWith key, comment, context, no Utils.Stats.increment "command.jirabot.comment" #Subtask @robot.respond Config.subtask.regex, (context) => context.finish() [ __, key, summary ] = context.match Jira.Create.subtaskFromKeyWith key, summary, context Utils.Stats.increment "command.jirabot.subtask" #Assign @robot.hear Config.assign.regex, (context) => context.finish() [ __, key, remove, person ] = context.match if remove Jira.Assign.forTicketKeyToUnassigned key, context, no else Jira.Assign.forTicketKeyToPerson key, person, context, no Utils.Stats.increment "command.jirabot.assign" #Create @robot.respond Config.commands.regex, (context) => [ __, project, command, summary ] = context.match room = project or @adapter.getRoomName context project = Config.maps.projects[room.toLowerCase()] type = Config.maps.types[command.toLowerCase()] unless project channels = [] for team, key of Config.maps.projects room = @adapter.getRoom team channels.push " <\##{room.id}|#{room.name}>" if room return context.reply "#{type} must be submitted in one of the following project channels: #{channels}" if Config.duplicates.detection and @adapter.detectForDuplicates? @adapter.detectForDuplicates project, type, summary, context else Jira.Create.with project, type, summary, context Utils.Stats.increment "command.jirabot.create" unless Config.jira.mentionsDisabled #Mention ticket by url or key @robot.listen @matchJiraTicket, (context) => @prepareResponseForJiraTickets context Utils.Stats.increment "command.jirabot.mention.ticket" module.exports = JiraBot
[ { "context": "eyhound to the Rainbow Bridge page\n#\n# Author:\n# Zach Whaley (zachwhaley) <zachbwhaley@gmail.com>\n\ngit = requi", "end": 211, "score": 0.9998734593391418, "start": 200, "tag": "NAME", "value": "Zach Whaley" }, { "context": " Rainbow Bridge page\n#\n# Author:\n# ...
scripts/goodbye.coffee
galtx-centex/roobot
3
# Description: # Move an deceased greyhound to the Rainbow Bridge page # # Commands: # hubot goodbye <greyhound> [m/d/yyyy] - Moves a deceased greyhound to the Rainbow Bridge page # # Author: # Zach Whaley (zachwhaley) <zachbwhaley@gmail.com> git = require '../lib/git' site = require '../lib/site' util = require '../lib/util' goodbye = (path, greyhound, name, dod, callback) -> site.loadGreyhound path, greyhound, (info, bio) -> if not info? return callback "Sorry, couldn't find #{greyhound} 😕" if info.category is 'deceased' return callback "#{name} has already crossed the Rainbow Bridge 😢" info.category = 'deceased' info.dod = util.thisDate(dod) if dod? site.dumpGreyhound path, greyhound, info, bio, callback module.exports = (robot) -> robot.respond /goodbye (.+?)\s*(\d{1,2}\/\d{1,2}\/\d{4})?$/i, (res) -> greyhound = util.slugify res.match[1] name = util.capitalize res.match[1] dod = res.match[2] gitOpts = message: "#{name} crossed the Rainbow Bridge 😢" branch: "goodbye-#{greyhound}" user: name: res.message.user?.real_name email: res.message.user?.email_address res.reply "Moving #{name} to the Rainbow Bridge 😢\n" + "Hang on a sec..." git.update goodbye, greyhound, name, dod, gitOpts, (err) -> unless err? res.reply "#{name} moved to the Rainbow Bridge 😢" else res.reply err
79929
# Description: # Move an deceased greyhound to the Rainbow Bridge page # # Commands: # hubot goodbye <greyhound> [m/d/yyyy] - Moves a deceased greyhound to the Rainbow Bridge page # # Author: # <NAME> (zachwhaley) <<EMAIL>> git = require '../lib/git' site = require '../lib/site' util = require '../lib/util' goodbye = (path, greyhound, name, dod, callback) -> site.loadGreyhound path, greyhound, (info, bio) -> if not info? return callback "Sorry, couldn't find #{greyhound} 😕" if info.category is 'deceased' return callback "#{name} has already crossed the Rainbow Bridge 😢" info.category = 'deceased' info.dod = util.thisDate(dod) if dod? site.dumpGreyhound path, greyhound, info, bio, callback module.exports = (robot) -> robot.respond /goodbye (.+?)\s*(\d{1,2}\/\d{1,2}\/\d{4})?$/i, (res) -> greyhound = util.slugify res.match[1] name = util.capitalize res.match[1] dod = res.match[2] gitOpts = message: "#{name} crossed the Rainbow Bridge 😢" branch: "goodbye-#{greyhound}" user: name: res.message.user?.real_name email: res.message.user?.email_address res.reply "Moving #{name} to the Rainbow Bridge 😢\n" + "Hang on a sec..." git.update goodbye, greyhound, name, dod, gitOpts, (err) -> unless err? res.reply "#{name} moved to the Rainbow Bridge 😢" else res.reply err
true
# Description: # Move an deceased greyhound to the Rainbow Bridge page # # Commands: # hubot goodbye <greyhound> [m/d/yyyy] - Moves a deceased greyhound to the Rainbow Bridge page # # Author: # PI:NAME:<NAME>END_PI (zachwhaley) <PI:EMAIL:<EMAIL>END_PI> git = require '../lib/git' site = require '../lib/site' util = require '../lib/util' goodbye = (path, greyhound, name, dod, callback) -> site.loadGreyhound path, greyhound, (info, bio) -> if not info? return callback "Sorry, couldn't find #{greyhound} 😕" if info.category is 'deceased' return callback "#{name} has already crossed the Rainbow Bridge 😢" info.category = 'deceased' info.dod = util.thisDate(dod) if dod? site.dumpGreyhound path, greyhound, info, bio, callback module.exports = (robot) -> robot.respond /goodbye (.+?)\s*(\d{1,2}\/\d{1,2}\/\d{4})?$/i, (res) -> greyhound = util.slugify res.match[1] name = util.capitalize res.match[1] dod = res.match[2] gitOpts = message: "#{name} crossed the Rainbow Bridge 😢" branch: "goodbye-#{greyhound}" user: name: res.message.user?.real_name email: res.message.user?.email_address res.reply "Moving #{name} to the Rainbow Bridge 😢\n" + "Hang on a sec..." git.update goodbye, greyhound, name, dod, gitOpts, (err) -> unless err? res.reply "#{name} moved to the Rainbow Bridge 😢" else res.reply err
[ { "context": "id: 1\nname: \"Check your State Pension\"\ndescription: \"Gives users a foreca", "end": 23, "score": 0.8212612867355347, "start": 13, "tag": "NAME", "value": "Check your" }, { "context": "id: 1\nname: \"Check your State Pension\"\ndescription: \"Gives users a forecast o...
app/data/projects/check-state-pension.cson
tsmorgan/dwp-ux-work
0
id: 1 name: "Check your State Pension" description: "Gives users a forecast of what their State Pension could be worth when they reach retirement age so that they can plan for their retirement." theme: "Retirement Provision" location: "Newcastle" phase: "beta" phase_modifier: "Public" sro: "Graeme Wallace" service_man: "Joy Bramfitt-Wanless" phase_history: discovery: [ { label: "Completed" date: "September 2014" } ] alpha: [ { label: "Completed" date: "January 2015" } ] beta: [ { label: "Started" date: "April 2015" } { label: "Private beta started" date: "August 2015" } { label: "Public beta started" date: "February 2016" } ] priority: "High" prototype: "http://nisp.herokuapp.com/" showntells: [ "14 September 2016, 11:00" "26 October 2016, 11:00" "7 December 2016, 11:00" ]
35711
id: 1 name: "<NAME> State <NAME>ension" description: "Gives users a forecast of what their State Pension could be worth when they reach retirement age so that they can plan for their retirement." theme: "Retirement Provision" location: "Newcastle" phase: "beta" phase_modifier: "Public" sro: "<NAME>" service_man: "<NAME>" phase_history: discovery: [ { label: "Completed" date: "September 2014" } ] alpha: [ { label: "Completed" date: "January 2015" } ] beta: [ { label: "Started" date: "April 2015" } { label: "Private beta started" date: "August 2015" } { label: "Public beta started" date: "February 2016" } ] priority: "High" prototype: "http://nisp.herokuapp.com/" showntells: [ "14 September 2016, 11:00" "26 October 2016, 11:00" "7 December 2016, 11:00" ]
true
id: 1 name: "PI:NAME:<NAME>END_PI State PI:NAME:<NAME>END_PIension" description: "Gives users a forecast of what their State Pension could be worth when they reach retirement age so that they can plan for their retirement." theme: "Retirement Provision" location: "Newcastle" phase: "beta" phase_modifier: "Public" sro: "PI:NAME:<NAME>END_PI" service_man: "PI:NAME:<NAME>END_PI" phase_history: discovery: [ { label: "Completed" date: "September 2014" } ] alpha: [ { label: "Completed" date: "January 2015" } ] beta: [ { label: "Started" date: "April 2015" } { label: "Private beta started" date: "August 2015" } { label: "Public beta started" date: "February 2016" } ] priority: "High" prototype: "http://nisp.herokuapp.com/" showntells: [ "14 September 2016, 11:00" "26 October 2016, 11:00" "7 December 2016, 11:00" ]
[ { "context": "eferences', (done) ->\n user = new User(email: 'some@email.com')\n expect(user.isEmailSubscriptionEnabled('gen", "end": 267, "score": 0.9999248385429382, "start": 253, "tag": "EMAIL", "value": "some@email.com" }, { "context": "re around', (done) ->\n user = new...
spec/server/unit/user.spec.coffee
IngJuanRuiz/codecombat
0
GLOBAL._ = require 'lodash' User = require '../../../server/models/User' utils = require '../utils' mongoose = require 'mongoose' describe 'User', -> it 'uses the schema defaults to fill in email preferences', (done) -> user = new User(email: 'some@email.com') expect(user.isEmailSubscriptionEnabled('generalNews')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('anyNotes')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('recruitNotes')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('archmageNews')).toBeFalsy() done() it 'uses old subs if they\'re around', (done) -> user = new User(email: 'some@email.com') user.set 'emailSubscriptions', ['tester'] expect(user.isEmailSubscriptionEnabled('adventurerNews')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('generalNews')).toBeFalsy() done() it 'maintains the old subs list if it\'s around', (done) -> user = new User(email: 'some@email.com') user.set 'emailSubscriptions', ['tester'] user.setEmailSubscription('artisanNews', true) expect(JSON.stringify(user.get('emailSubscriptions'))).toBe(JSON.stringify(['tester', 'level_creator'])) done() it 'does not allow anonymous to be set to true if there is a login method', utils.wrap (done) -> user = new User({passwordHash: '1234', anonymous: true}) user = yield user.save() expect(user.get('anonymous')).toBe(false) done() it 'prevents duplicate oAuthIdentities', utils.wrap (done) -> provider1 = new mongoose.Types.ObjectId() provider2 = new mongoose.Types.ObjectId() identity1 = { provider: provider1, id: 'abcd' } identity2 = { provider: provider2, id: 'abcd' } identity3 = { provider: provider1, id: '1234' } # These three should live in harmony users = [] users.push yield utils.initUser({ oAuthIdentities: [identity1] }) users.push yield utils.initUser({ oAuthIdentities: [identity2] }) users.push yield utils.initUser({ oAuthIdentities: [identity3] }) e = null try users.push yield utils.initUser({ oAuthIdentities: [identity1] }) catch e expect(e).not.toBe(null) done() describe 'cancelPayPalSubscription', -> describe 'when subscribed via payPal', -> beforeEach utils.wrap -> @user = yield utils.initUser({username: 'test1', payPal: {billingAgreementID: 'abc123', subscribeDate: new Date('2017-01-04')}}) it 'user unsubscribed with remaining time captured with stripe.free', utils.wrap -> beforeCancelDate = new Date() yield @user.cancelPayPalSubscription() cancelDate = @user.get('payPal').cancelDate cancelDate.setUTCDate(cancelDate.getUTCDate() - 1) expect(cancelDate).not.toBeGreaterThan(beforeCancelDate) cancelDate.setUTCDate(cancelDate.getUTCDate() + 2) expect(cancelDate).toBeGreaterThan(beforeCancelDate) expect(new Date(@user.get('stripe').free)).toBeGreaterThan(new Date()) describe 'when not subscribed via payPal', -> beforeEach utils.wrap -> @user = yield utils.initUser({username: 'test1'}) it 'user unchanged on cancel', utils.wrap -> beforeUser = JSON.stringify(@user) yield @user.cancelPayPalSubscription() expect(beforeUser).toEqual(JSON.stringify(@user)) describe '.updateServiceSettings()', -> it 'uses emails to determine what to send to MailChimp', utils.wrap (done) -> email = 'tester@gmail.com' user = new User({emailSubscriptions: ['announcement'], @email, emailLower: email}) spyOn(user, 'updateMailChimp').and.returnValue(Promise.resolve()) yield user.updateServiceSettings() expect(user.updateMailChimp).toHaveBeenCalled() done() it 'updates stripe email iff email changes on save', utils.wrap (done) -> stripeApi = require('../../../server/lib/stripe_utils').api spyOn(stripeApi.customers, 'update') user = new User({email: 'first@email.com'}) yield user.save() user = yield User.findById(user.id) user.set({email: 'second@email.com'}) yield user.save() user = yield User.findById(user.id) user.set({stripe: {customerID: '1234'}}) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(0) user = yield User.findById(user.id) user.set({email: 'third@email.com'}) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(1) user = yield User.findById(user.id) user.set({email: 'first@email.com'}) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(2) user = yield User.findById(user.id) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(2) done() describe '.isAdmin()', -> it 'returns true if user has "admin" permission', (done) -> adminUser = new User() adminUser.set('permissions', ['whatever', 'admin', 'user']) expect(adminUser.isAdmin()).toBeTruthy() done() it 'returns false if user has no permissions', (done) -> myUser = new User() myUser.set('permissions', []) expect(myUser.isAdmin()).toBeFalsy() done() it 'returns false if user has other permissions', (done) -> classicUser = new User() classicUser.set('permissions', ['user']) expect(classicUser.isAdmin()).toBeFalsy() done() describe '.verificationCode(timestamp)', -> it 'returns a timestamp and a hash', (done) -> user = new User() now = new Date() code = user.verificationCode(now.getTime()) expect(code).toMatch(/[0-9]{13}:[0-9a-f]{64}/) [timestamp, hash] = code.split(':') expect(new Date(parseInt(timestamp))).toEqual(now) done() describe '.incrementStatAsync()', -> it 'records nested stats', utils.wrap (done) -> user = yield utils.initUser() yield User.incrementStatAsync user.id, 'stats.testNumber' yield User.incrementStatAsync user.id, 'stats.concepts.basic', {inc: 10} user = yield User.findById(user.id) expect(user.get('stats.testNumber')).toBe(1) expect(user.get('stats.concepts.basic')).toBe(10) done() describe 'subscription virtual', -> it 'has active and ends properties', -> moment = require 'moment' stripeEnd = moment().add(12, 'months').toISOString().substring(0,10) user1 = new User({stripe: {free:stripeEnd}}) expectedEnd = "#{stripeEnd}T00:00:00.000Z" expect(user1.get('subscription').active).toBe(true) expect(user1.get('subscription').ends).toBe(expectedEnd) expect(user1.toObject({virtuals: true}).subscription.ends).toBe(expectedEnd) user2 = new User() expect(user2.get('subscription').active).toBe(false) user3 = new User({stripe: {free: true}}) expect(user3.get('subscription').active).toBe(true) expect(user3.get('subscription').ends).toBeUndefined() describe '.prepaidIncludesCourse(courseID)', -> describe 'when the prepaid is a legacy full license', -> it 'returns true', -> user = new User({ coursePrepaidID: 'prepaid_1' }) expect(user.prepaidIncludesCourse('course_1')).toBe(true) describe 'when the prepaid is a full license', -> it 'returns true', -> user = new User({ coursePrepaid: { _id: 'prepaid_1' } }) expect(user.prepaidIncludesCourse('course_1')).toBe(true) describe 'when the prepaid is a starter license', -> beforeEach -> @user = new User({ coursePrepaid: { _id: 'prepaid_1', includedCourseIDs: ['course_1'] } }) describe 'that does include the course', -> it 'returns true', -> expect(@user.prepaidIncludesCourse('course_1')).toBe(true) describe "that doesn't include the course", -> it 'returns false', -> expect(@user.prepaidIncludesCourse('course_2')).toBe(false) describe 'when the user has no prepaid', -> it 'returns false', -> @user = new User({ coursePrepaid: undefined }) expect(@user.prepaidIncludesCourse('course_2')).toBe(false) describe '.updateMailChimp()', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User]) done() mailChimp = require '../../../server/lib/mail-chimp' it 'propagates user notification and name settings to MailChimp', utils.wrap (done) -> user = yield utils.initUser({ emailVerified: true firstName: 'First' lastName: 'Last' emails: { diplomatNews: { enabled: true } generalNews: { enabled: true } } }) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[0]).toMatch("^/lists/[0-9a-f]+/members/[0-9a-f]+$") expect(args[1]?.email_address).toBe(user.get('email')) diplomatInterest = _.find(mailChimp.interests, (interest) -> interest.property is 'diplomatNews') announcementsInterest = _.find(mailChimp.interests, (interest) -> interest.property is 'generalNews') for [key, value] in _.pairs(args[1].interests) if key in [diplomatInterest.mailChimpId, announcementsInterest.mailChimpId] expect(value).toBe(true) else expect(value).toBeFalsy() expect(args[1]?.status).toBe('subscribed') expect(args[1]?.merge_fields['FNAME']).toBe('First') expect(args[1]?.merge_fields['LNAME']).toBe('Last') user = yield User.findById(user.id) expect(user.get('mailChimp').email).toBe(user.get('email')) done() describe 'when user email is validated on MailChimp but not CodeCombat', -> it 'still updates their settings on MailChimp', utils.wrap (done) -> email = 'some@email.com' user = yield utils.initUser({ email emailVerified: false emails: { diplomatNews: { enabled: true } } mailChimp: { email } }) user = yield User.findById(user.id) spyOn(mailChimp.api, 'get').and.returnValue(Promise.resolve({ status: 'subscribed' })) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.get.calls.count()).toBe(1) expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[1]?.status).toBe('subscribed') done() describe 'when the user\'s email changes', -> it 'unsubscribes the old entry, and does not subscribe the new email until validated', utils.wrap (done) -> oldEmail = 'old@email.com' newEmail = 'new@email.com' user = yield utils.initUser({ email: newEmail emailVerified: false emails: { diplomatNews: { enabled: true } } mailChimp: { email: oldEmail } }) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[1]?.status).toBe('unsubscribed') expect(args[0]).toBe(mailChimp.makeSubscriberUrl(oldEmail)) done() describe 'when the user is not subscribed on MailChimp and is not subscribed to any interests on CodeCombat', -> it 'does nothing', utils.wrap (done) -> user = yield utils.initUser({ emailVerified: true emails: { generalNews: { enabled: false } } }) spyOn(mailChimp.api, 'get') spyOn(mailChimp.api, 'put') yield user.updateMailChimp() expect(mailChimp.api.get.calls.count()).toBe(0) expect(mailChimp.api.put.calls.count()).toBe(0) done() describe 'when the user is on MailChimp but not validated there nor on CodeCombat', -> it 'updates with status set to unsubscribed', utils.wrap (done) -> spyOn(User.schema.methods, 'updateMailChimp').and.callThrough() email = 'some@email.com' user = yield utils.initUser({ email emailVerified: false emails: { diplomatNews: { enabled: true } } mailChimp: { email } }) yield new Promise((resolve) -> setTimeout(resolve, 10)) # hack to get initial updateMailChimp call flushed out spyOn(mailChimp.api, 'get').and.returnValue(Promise.resolve({ status: 'unsubscribed' })) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.get.calls.count()).toBe(1) expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[1]?.status).toBe('unsubscribed') done() describe 'inEU', -> it 'true if in EU country', utils.wrap -> u = yield utils.initUser({country: 'germany'}) expect(u.inEU()).toEqual(true) it 'false if not in EU country', utils.wrap -> u = yield utils.initUser({country: 'mexico'}) expect(u.inEU()).toEqual(false) it 'true if not defined', utils.wrap -> u = yield utils.initUser() expect(u.get('country')).toBeUndefined() expect(u.inEU()).toEqual(true)
55315
GLOBAL._ = require 'lodash' User = require '../../../server/models/User' utils = require '../utils' mongoose = require 'mongoose' describe 'User', -> it 'uses the schema defaults to fill in email preferences', (done) -> user = new User(email: '<EMAIL>') expect(user.isEmailSubscriptionEnabled('generalNews')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('anyNotes')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('recruitNotes')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('archmageNews')).toBeFalsy() done() it 'uses old subs if they\'re around', (done) -> user = new User(email: '<EMAIL>') user.set 'emailSubscriptions', ['tester'] expect(user.isEmailSubscriptionEnabled('adventurerNews')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('generalNews')).toBeFalsy() done() it 'maintains the old subs list if it\'s around', (done) -> user = new User(email: '<EMAIL>') user.set 'emailSubscriptions', ['tester'] user.setEmailSubscription('artisanNews', true) expect(JSON.stringify(user.get('emailSubscriptions'))).toBe(JSON.stringify(['tester', 'level_creator'])) done() it 'does not allow anonymous to be set to true if there is a login method', utils.wrap (done) -> user = new User({passwordHash: '<PASSWORD>', anonymous: true}) user = yield user.save() expect(user.get('anonymous')).toBe(false) done() it 'prevents duplicate oAuthIdentities', utils.wrap (done) -> provider1 = new mongoose.Types.ObjectId() provider2 = new mongoose.Types.ObjectId() identity1 = { provider: provider1, id: 'abcd' } identity2 = { provider: provider2, id: 'abcd' } identity3 = { provider: provider1, id: '1234' } # These three should live in harmony users = [] users.push yield utils.initUser({ oAuthIdentities: [identity1] }) users.push yield utils.initUser({ oAuthIdentities: [identity2] }) users.push yield utils.initUser({ oAuthIdentities: [identity3] }) e = null try users.push yield utils.initUser({ oAuthIdentities: [identity1] }) catch e expect(e).not.toBe(null) done() describe 'cancelPayPalSubscription', -> describe 'when subscribed via payPal', -> beforeEach utils.wrap -> @user = yield utils.initUser({username: 'test1', payPal: {billingAgreementID: 'abc123', subscribeDate: new Date('2017-01-04')}}) it 'user unsubscribed with remaining time captured with stripe.free', utils.wrap -> beforeCancelDate = new Date() yield @user.cancelPayPalSubscription() cancelDate = @user.get('payPal').cancelDate cancelDate.setUTCDate(cancelDate.getUTCDate() - 1) expect(cancelDate).not.toBeGreaterThan(beforeCancelDate) cancelDate.setUTCDate(cancelDate.getUTCDate() + 2) expect(cancelDate).toBeGreaterThan(beforeCancelDate) expect(new Date(@user.get('stripe').free)).toBeGreaterThan(new Date()) describe 'when not subscribed via payPal', -> beforeEach utils.wrap -> @user = yield utils.initUser({username: 'test1'}) it 'user unchanged on cancel', utils.wrap -> beforeUser = JSON.stringify(@user) yield @user.cancelPayPalSubscription() expect(beforeUser).toEqual(JSON.stringify(@user)) describe '.updateServiceSettings()', -> it 'uses emails to determine what to send to MailChimp', utils.wrap (done) -> email = '<EMAIL>' user = new User({emailSubscriptions: ['announcement'], @email, emailLower: email}) spyOn(user, 'updateMailChimp').and.returnValue(Promise.resolve()) yield user.updateServiceSettings() expect(user.updateMailChimp).toHaveBeenCalled() done() it 'updates stripe email iff email changes on save', utils.wrap (done) -> stripeApi = require('../../../server/lib/stripe_utils').api spyOn(stripeApi.customers, 'update') user = new User({email: '<EMAIL>'}) yield user.save() user = yield User.findById(user.id) user.set({email: '<EMAIL>'}) yield user.save() user = yield User.findById(user.id) user.set({stripe: {customerID: '1234'}}) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(0) user = yield User.findById(user.id) user.set({email: '<EMAIL>'}) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(1) user = yield User.findById(user.id) user.set({email: '<EMAIL>'}) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(2) user = yield User.findById(user.id) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(2) done() describe '.isAdmin()', -> it 'returns true if user has "admin" permission', (done) -> adminUser = new User() adminUser.set('permissions', ['whatever', 'admin', 'user']) expect(adminUser.isAdmin()).toBeTruthy() done() it 'returns false if user has no permissions', (done) -> myUser = new User() myUser.set('permissions', []) expect(myUser.isAdmin()).toBeFalsy() done() it 'returns false if user has other permissions', (done) -> classicUser = new User() classicUser.set('permissions', ['user']) expect(classicUser.isAdmin()).toBeFalsy() done() describe '.verificationCode(timestamp)', -> it 'returns a timestamp and a hash', (done) -> user = new User() now = new Date() code = user.verificationCode(now.getTime()) expect(code).toMatch(/[0-9]{13}:[0-9a-f]{64}/) [timestamp, hash] = code.split(':') expect(new Date(parseInt(timestamp))).toEqual(now) done() describe '.incrementStatAsync()', -> it 'records nested stats', utils.wrap (done) -> user = yield utils.initUser() yield User.incrementStatAsync user.id, 'stats.testNumber' yield User.incrementStatAsync user.id, 'stats.concepts.basic', {inc: 10} user = yield User.findById(user.id) expect(user.get('stats.testNumber')).toBe(1) expect(user.get('stats.concepts.basic')).toBe(10) done() describe 'subscription virtual', -> it 'has active and ends properties', -> moment = require 'moment' stripeEnd = moment().add(12, 'months').toISOString().substring(0,10) user1 = new User({stripe: {free:stripeEnd}}) expectedEnd = "#{stripeEnd}T00:00:00.000Z" expect(user1.get('subscription').active).toBe(true) expect(user1.get('subscription').ends).toBe(expectedEnd) expect(user1.toObject({virtuals: true}).subscription.ends).toBe(expectedEnd) user2 = new User() expect(user2.get('subscription').active).toBe(false) user3 = new User({stripe: {free: true}}) expect(user3.get('subscription').active).toBe(true) expect(user3.get('subscription').ends).toBeUndefined() describe '.prepaidIncludesCourse(courseID)', -> describe 'when the prepaid is a legacy full license', -> it 'returns true', -> user = new User({ coursePrepaidID: 'prepaid_1' }) expect(user.prepaidIncludesCourse('course_1')).toBe(true) describe 'when the prepaid is a full license', -> it 'returns true', -> user = new User({ coursePrepaid: { _id: 'prepaid_1' } }) expect(user.prepaidIncludesCourse('course_1')).toBe(true) describe 'when the prepaid is a starter license', -> beforeEach -> @user = new User({ coursePrepaid: { _id: 'prepaid_1', includedCourseIDs: ['course_1'] } }) describe 'that does include the course', -> it 'returns true', -> expect(@user.prepaidIncludesCourse('course_1')).toBe(true) describe "that doesn't include the course", -> it 'returns false', -> expect(@user.prepaidIncludesCourse('course_2')).toBe(false) describe 'when the user has no prepaid', -> it 'returns false', -> @user = new User({ coursePrepaid: undefined }) expect(@user.prepaidIncludesCourse('course_2')).toBe(false) describe '.updateMailChimp()', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User]) done() mailChimp = require '../../../server/lib/mail-chimp' it 'propagates user notification and name settings to MailChimp', utils.wrap (done) -> user = yield utils.initUser({ emailVerified: true firstName: '<NAME>' lastName: '<NAME>' emails: { diplomatNews: { enabled: true } generalNews: { enabled: true } } }) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[0]).toMatch("^/lists/[0-9a-f]+/members/[0-9a-f]+$") expect(args[1]?.email_address).toBe(user.get('email')) diplomatInterest = _.find(mailChimp.interests, (interest) -> interest.property is 'diplomatNews') announcementsInterest = _.find(mailChimp.interests, (interest) -> interest.property is 'generalNews') for [key, value] in _.pairs(args[1].interests) if key in [diplomatInterest.mailChimpId, announcementsInterest.mailChimpId] expect(value).toBe(true) else expect(value).toBeFalsy() expect(args[1]?.status).toBe('subscribed') expect(args[1]?.merge_fields['FNAME']).toBe('First') expect(args[1]?.merge_fields['LNAME']).toBe('Last') user = yield User.findById(user.id) expect(user.get('mailChimp').email).toBe(user.get('email')) done() describe 'when user email is validated on MailChimp but not CodeCombat', -> it 'still updates their settings on MailChimp', utils.wrap (done) -> email = '<EMAIL>' user = yield utils.initUser({ email emailVerified: false emails: { diplomatNews: { enabled: true } } mailChimp: { email } }) user = yield User.findById(user.id) spyOn(mailChimp.api, 'get').and.returnValue(Promise.resolve({ status: 'subscribed' })) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.get.calls.count()).toBe(1) expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[1]?.status).toBe('subscribed') done() describe 'when the user\'s email changes', -> it 'unsubscribes the old entry, and does not subscribe the new email until validated', utils.wrap (done) -> oldEmail = '<EMAIL>' newEmail = '<EMAIL>' user = yield utils.initUser({ email: newEmail emailVerified: false emails: { diplomatNews: { enabled: true } } mailChimp: { email: oldEmail } }) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[1]?.status).toBe('unsubscribed') expect(args[0]).toBe(mailChimp.makeSubscriberUrl(oldEmail)) done() describe 'when the user is not subscribed on MailChimp and is not subscribed to any interests on CodeCombat', -> it 'does nothing', utils.wrap (done) -> user = yield utils.initUser({ emailVerified: true emails: { generalNews: { enabled: false } } }) spyOn(mailChimp.api, 'get') spyOn(mailChimp.api, 'put') yield user.updateMailChimp() expect(mailChimp.api.get.calls.count()).toBe(0) expect(mailChimp.api.put.calls.count()).toBe(0) done() describe 'when the user is on MailChimp but not validated there nor on CodeCombat', -> it 'updates with status set to unsubscribed', utils.wrap (done) -> spyOn(User.schema.methods, 'updateMailChimp').and.callThrough() email = '<EMAIL>' user = yield utils.initUser({ email emailVerified: false emails: { diplomatNews: { enabled: true } } mailChimp: { email } }) yield new Promise((resolve) -> setTimeout(resolve, 10)) # hack to get initial updateMailChimp call flushed out spyOn(mailChimp.api, 'get').and.returnValue(Promise.resolve({ status: 'unsubscribed' })) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.get.calls.count()).toBe(1) expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[1]?.status).toBe('unsubscribed') done() describe 'inEU', -> it 'true if in EU country', utils.wrap -> u = yield utils.initUser({country: 'germany'}) expect(u.inEU()).toEqual(true) it 'false if not in EU country', utils.wrap -> u = yield utils.initUser({country: 'mexico'}) expect(u.inEU()).toEqual(false) it 'true if not defined', utils.wrap -> u = yield utils.initUser() expect(u.get('country')).toBeUndefined() expect(u.inEU()).toEqual(true)
true
GLOBAL._ = require 'lodash' User = require '../../../server/models/User' utils = require '../utils' mongoose = require 'mongoose' describe 'User', -> it 'uses the schema defaults to fill in email preferences', (done) -> user = new User(email: 'PI:EMAIL:<EMAIL>END_PI') expect(user.isEmailSubscriptionEnabled('generalNews')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('anyNotes')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('recruitNotes')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('archmageNews')).toBeFalsy() done() it 'uses old subs if they\'re around', (done) -> user = new User(email: 'PI:EMAIL:<EMAIL>END_PI') user.set 'emailSubscriptions', ['tester'] expect(user.isEmailSubscriptionEnabled('adventurerNews')).toBeTruthy() expect(user.isEmailSubscriptionEnabled('generalNews')).toBeFalsy() done() it 'maintains the old subs list if it\'s around', (done) -> user = new User(email: 'PI:EMAIL:<EMAIL>END_PI') user.set 'emailSubscriptions', ['tester'] user.setEmailSubscription('artisanNews', true) expect(JSON.stringify(user.get('emailSubscriptions'))).toBe(JSON.stringify(['tester', 'level_creator'])) done() it 'does not allow anonymous to be set to true if there is a login method', utils.wrap (done) -> user = new User({passwordHash: 'PI:PASSWORD:<PASSWORD>END_PI', anonymous: true}) user = yield user.save() expect(user.get('anonymous')).toBe(false) done() it 'prevents duplicate oAuthIdentities', utils.wrap (done) -> provider1 = new mongoose.Types.ObjectId() provider2 = new mongoose.Types.ObjectId() identity1 = { provider: provider1, id: 'abcd' } identity2 = { provider: provider2, id: 'abcd' } identity3 = { provider: provider1, id: '1234' } # These three should live in harmony users = [] users.push yield utils.initUser({ oAuthIdentities: [identity1] }) users.push yield utils.initUser({ oAuthIdentities: [identity2] }) users.push yield utils.initUser({ oAuthIdentities: [identity3] }) e = null try users.push yield utils.initUser({ oAuthIdentities: [identity1] }) catch e expect(e).not.toBe(null) done() describe 'cancelPayPalSubscription', -> describe 'when subscribed via payPal', -> beforeEach utils.wrap -> @user = yield utils.initUser({username: 'test1', payPal: {billingAgreementID: 'abc123', subscribeDate: new Date('2017-01-04')}}) it 'user unsubscribed with remaining time captured with stripe.free', utils.wrap -> beforeCancelDate = new Date() yield @user.cancelPayPalSubscription() cancelDate = @user.get('payPal').cancelDate cancelDate.setUTCDate(cancelDate.getUTCDate() - 1) expect(cancelDate).not.toBeGreaterThan(beforeCancelDate) cancelDate.setUTCDate(cancelDate.getUTCDate() + 2) expect(cancelDate).toBeGreaterThan(beforeCancelDate) expect(new Date(@user.get('stripe').free)).toBeGreaterThan(new Date()) describe 'when not subscribed via payPal', -> beforeEach utils.wrap -> @user = yield utils.initUser({username: 'test1'}) it 'user unchanged on cancel', utils.wrap -> beforeUser = JSON.stringify(@user) yield @user.cancelPayPalSubscription() expect(beforeUser).toEqual(JSON.stringify(@user)) describe '.updateServiceSettings()', -> it 'uses emails to determine what to send to MailChimp', utils.wrap (done) -> email = 'PI:EMAIL:<EMAIL>END_PI' user = new User({emailSubscriptions: ['announcement'], @email, emailLower: email}) spyOn(user, 'updateMailChimp').and.returnValue(Promise.resolve()) yield user.updateServiceSettings() expect(user.updateMailChimp).toHaveBeenCalled() done() it 'updates stripe email iff email changes on save', utils.wrap (done) -> stripeApi = require('../../../server/lib/stripe_utils').api spyOn(stripeApi.customers, 'update') user = new User({email: 'PI:EMAIL:<EMAIL>END_PI'}) yield user.save() user = yield User.findById(user.id) user.set({email: 'PI:EMAIL:<EMAIL>END_PI'}) yield user.save() user = yield User.findById(user.id) user.set({stripe: {customerID: '1234'}}) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(0) user = yield User.findById(user.id) user.set({email: 'PI:EMAIL:<EMAIL>END_PI'}) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(1) user = yield User.findById(user.id) user.set({email: 'PI:EMAIL:<EMAIL>END_PI'}) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(2) user = yield User.findById(user.id) yield user.save() expect(stripeApi.customers.update.calls.count()).toBe(2) done() describe '.isAdmin()', -> it 'returns true if user has "admin" permission', (done) -> adminUser = new User() adminUser.set('permissions', ['whatever', 'admin', 'user']) expect(adminUser.isAdmin()).toBeTruthy() done() it 'returns false if user has no permissions', (done) -> myUser = new User() myUser.set('permissions', []) expect(myUser.isAdmin()).toBeFalsy() done() it 'returns false if user has other permissions', (done) -> classicUser = new User() classicUser.set('permissions', ['user']) expect(classicUser.isAdmin()).toBeFalsy() done() describe '.verificationCode(timestamp)', -> it 'returns a timestamp and a hash', (done) -> user = new User() now = new Date() code = user.verificationCode(now.getTime()) expect(code).toMatch(/[0-9]{13}:[0-9a-f]{64}/) [timestamp, hash] = code.split(':') expect(new Date(parseInt(timestamp))).toEqual(now) done() describe '.incrementStatAsync()', -> it 'records nested stats', utils.wrap (done) -> user = yield utils.initUser() yield User.incrementStatAsync user.id, 'stats.testNumber' yield User.incrementStatAsync user.id, 'stats.concepts.basic', {inc: 10} user = yield User.findById(user.id) expect(user.get('stats.testNumber')).toBe(1) expect(user.get('stats.concepts.basic')).toBe(10) done() describe 'subscription virtual', -> it 'has active and ends properties', -> moment = require 'moment' stripeEnd = moment().add(12, 'months').toISOString().substring(0,10) user1 = new User({stripe: {free:stripeEnd}}) expectedEnd = "#{stripeEnd}T00:00:00.000Z" expect(user1.get('subscription').active).toBe(true) expect(user1.get('subscription').ends).toBe(expectedEnd) expect(user1.toObject({virtuals: true}).subscription.ends).toBe(expectedEnd) user2 = new User() expect(user2.get('subscription').active).toBe(false) user3 = new User({stripe: {free: true}}) expect(user3.get('subscription').active).toBe(true) expect(user3.get('subscription').ends).toBeUndefined() describe '.prepaidIncludesCourse(courseID)', -> describe 'when the prepaid is a legacy full license', -> it 'returns true', -> user = new User({ coursePrepaidID: 'prepaid_1' }) expect(user.prepaidIncludesCourse('course_1')).toBe(true) describe 'when the prepaid is a full license', -> it 'returns true', -> user = new User({ coursePrepaid: { _id: 'prepaid_1' } }) expect(user.prepaidIncludesCourse('course_1')).toBe(true) describe 'when the prepaid is a starter license', -> beforeEach -> @user = new User({ coursePrepaid: { _id: 'prepaid_1', includedCourseIDs: ['course_1'] } }) describe 'that does include the course', -> it 'returns true', -> expect(@user.prepaidIncludesCourse('course_1')).toBe(true) describe "that doesn't include the course", -> it 'returns false', -> expect(@user.prepaidIncludesCourse('course_2')).toBe(false) describe 'when the user has no prepaid', -> it 'returns false', -> @user = new User({ coursePrepaid: undefined }) expect(@user.prepaidIncludesCourse('course_2')).toBe(false) describe '.updateMailChimp()', -> beforeEach utils.wrap (done) -> yield utils.clearModels([User]) done() mailChimp = require '../../../server/lib/mail-chimp' it 'propagates user notification and name settings to MailChimp', utils.wrap (done) -> user = yield utils.initUser({ emailVerified: true firstName: 'PI:NAME:<NAME>END_PI' lastName: 'PI:NAME:<NAME>END_PI' emails: { diplomatNews: { enabled: true } generalNews: { enabled: true } } }) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[0]).toMatch("^/lists/[0-9a-f]+/members/[0-9a-f]+$") expect(args[1]?.email_address).toBe(user.get('email')) diplomatInterest = _.find(mailChimp.interests, (interest) -> interest.property is 'diplomatNews') announcementsInterest = _.find(mailChimp.interests, (interest) -> interest.property is 'generalNews') for [key, value] in _.pairs(args[1].interests) if key in [diplomatInterest.mailChimpId, announcementsInterest.mailChimpId] expect(value).toBe(true) else expect(value).toBeFalsy() expect(args[1]?.status).toBe('subscribed') expect(args[1]?.merge_fields['FNAME']).toBe('First') expect(args[1]?.merge_fields['LNAME']).toBe('Last') user = yield User.findById(user.id) expect(user.get('mailChimp').email).toBe(user.get('email')) done() describe 'when user email is validated on MailChimp but not CodeCombat', -> it 'still updates their settings on MailChimp', utils.wrap (done) -> email = 'PI:EMAIL:<EMAIL>END_PI' user = yield utils.initUser({ email emailVerified: false emails: { diplomatNews: { enabled: true } } mailChimp: { email } }) user = yield User.findById(user.id) spyOn(mailChimp.api, 'get').and.returnValue(Promise.resolve({ status: 'subscribed' })) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.get.calls.count()).toBe(1) expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[1]?.status).toBe('subscribed') done() describe 'when the user\'s email changes', -> it 'unsubscribes the old entry, and does not subscribe the new email until validated', utils.wrap (done) -> oldEmail = 'PI:EMAIL:<EMAIL>END_PI' newEmail = 'PI:EMAIL:<EMAIL>END_PI' user = yield utils.initUser({ email: newEmail emailVerified: false emails: { diplomatNews: { enabled: true } } mailChimp: { email: oldEmail } }) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[1]?.status).toBe('unsubscribed') expect(args[0]).toBe(mailChimp.makeSubscriberUrl(oldEmail)) done() describe 'when the user is not subscribed on MailChimp and is not subscribed to any interests on CodeCombat', -> it 'does nothing', utils.wrap (done) -> user = yield utils.initUser({ emailVerified: true emails: { generalNews: { enabled: false } } }) spyOn(mailChimp.api, 'get') spyOn(mailChimp.api, 'put') yield user.updateMailChimp() expect(mailChimp.api.get.calls.count()).toBe(0) expect(mailChimp.api.put.calls.count()).toBe(0) done() describe 'when the user is on MailChimp but not validated there nor on CodeCombat', -> it 'updates with status set to unsubscribed', utils.wrap (done) -> spyOn(User.schema.methods, 'updateMailChimp').and.callThrough() email = 'PI:EMAIL:<EMAIL>END_PI' user = yield utils.initUser({ email emailVerified: false emails: { diplomatNews: { enabled: true } } mailChimp: { email } }) yield new Promise((resolve) -> setTimeout(resolve, 10)) # hack to get initial updateMailChimp call flushed out spyOn(mailChimp.api, 'get').and.returnValue(Promise.resolve({ status: 'unsubscribed' })) spyOn(mailChimp.api, 'put').and.returnValue(Promise.resolve()) yield user.updateMailChimp() expect(mailChimp.api.get.calls.count()).toBe(1) expect(mailChimp.api.put.calls.count()).toBe(1) args = mailChimp.api.put.calls.argsFor(0) expect(args[1]?.status).toBe('unsubscribed') done() describe 'inEU', -> it 'true if in EU country', utils.wrap -> u = yield utils.initUser({country: 'germany'}) expect(u.inEU()).toEqual(true) it 'false if not in EU country', utils.wrap -> u = yield utils.initUser({country: 'mexico'}) expect(u.inEU()).toEqual(false) it 'true if not defined', utils.wrap -> u = yield utils.initUser() expect(u.get('country')).toBeUndefined() expect(u.inEU()).toEqual(true)
[ { "context": "t : \"00112233445566778899aabbccddeeff\"\n key : \"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f\"\n ciphertext : \"8ea2b7ca516745bfeafc49904b4960", "end": 251, "score": 0.9997795820236206, "start": 187, "tag": "KEY", "value": "000102030405060708090a0b0...
test/files/aes.iced
CyberFlameGO/triplesec
274
{AES} = require '../../lib/aes' {WordArray} = require '../../lib/wordarray' test_vectors = [ { desc : "fips-197 C.3" plaintext : "00112233445566778899aabbccddeeff" key : "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" ciphertext : "8ea2b7ca516745bfeafc49904b496089" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #1" plaintext : "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" key : "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4" ciphertext : "0bdf7df1591716335e9a8b15c860c502" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #2" plaintext : "f0f1f2f3f4f5f6f7f8f9fafbfcfdff00" key : "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4" ciphertext : "5a6e699d536119065433863c8f657b94" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #3" plaintext : "f0f1f2f3f4f5f6f7f8f9fafbfcfdff01" key : "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4" ciphertext : "1bc12c9c01610d5d0d8bd6a3378eca62" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #4" plaintext : "f0f1f2f3f4f5f6f7f8f9fafbfcfdff02" key : "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4" ciphertext : "2956e1c8693536b1bee99c73a31576b6" } ] test_single = (T, v) -> aes = new AES WordArray.from_hex v.key block = WordArray.from_hex v.plaintext aes.encryptBlock block.words ctext_hex = block.to_hex() T.equal ctext_hex, v.ciphertext, "#{v.desc} -- correct encryption" aes.decryptBlock block.words ptext_hex = block.to_hex() T.equal ptext_hex, v.plaintext, "#{v.desc} -- correct decryption" exports.test_aes = (T, cb) -> for v in test_vectors test_single T, v cb()
158742
{AES} = require '../../lib/aes' {WordArray} = require '../../lib/wordarray' test_vectors = [ { desc : "fips-197 C.3" plaintext : "00112233445566778899aabbccddeeff" key : "<KEY>" ciphertext : "8ea2b7ca516745bfeafc49904b496089" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #1" plaintext : "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" key : "<KEY>" ciphertext : "0bdf7df1591716335e9a8b15c860c502" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #2" plaintext : "f0f1f2f3f4f5f6f7f8f9fafbfcfdff00" key : "<KEY>" ciphertext : "5a6e699d536119065433863c8f657b94" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #3" plaintext : "f0<KEY>1f2f3f4f5f6f7f8f9fafbfcf<KEY>1" key : "<KEY>" ciphertext : "1bc12c9c01610d5d0d8bd6a3378eca62" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #4" plaintext : "f<KEY>2<KEY>3<KEY>4f5f6<KEY>7<KEY>8<KEY>9fafbfcf<KEY>" key : "<KEY>" ciphertext : "2956e1c8693536b1bee99c73a31576b6" } ] test_single = (T, v) -> aes = new AES WordArray.from_hex v.key block = WordArray.from_hex v.plaintext aes.encryptBlock block.words ctext_hex = block.to_hex() T.equal ctext_hex, v.ciphertext, "#{v.desc} -- correct encryption" aes.decryptBlock block.words ptext_hex = block.to_hex() T.equal ptext_hex, v.plaintext, "#{v.desc} -- correct decryption" exports.test_aes = (T, cb) -> for v in test_vectors test_single T, v cb()
true
{AES} = require '../../lib/aes' {WordArray} = require '../../lib/wordarray' test_vectors = [ { desc : "fips-197 C.3" plaintext : "00112233445566778899aabbccddeeff" key : "PI:KEY:<KEY>END_PI" ciphertext : "8ea2b7ca516745bfeafc49904b496089" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #1" plaintext : "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff" key : "PI:KEY:<KEY>END_PI" ciphertext : "0bdf7df1591716335e9a8b15c860c502" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #2" plaintext : "f0f1f2f3f4f5f6f7f8f9fafbfcfdff00" key : "PI:KEY:<KEY>END_PI" ciphertext : "5a6e699d536119065433863c8f657b94" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #3" plaintext : "f0PI:KEY:<KEY>END_PI1f2f3f4f5f6f7f8f9fafbfcfPI:KEY:<KEY>END_PI1" key : "PI:KEY:<KEY>END_PI" ciphertext : "1bc12c9c01610d5d0d8bd6a3378eca62" }, { desc : "NIST 800-38a F.5.5 CTR-AES256.Encrypt Block #4" plaintext : "fPI:KEY:<KEY>END_PI2PI:KEY:<KEY>END_PI3PI:KEY:<KEY>END_PI4f5f6PI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PI9fafbfcfPI:KEY:<KEY>END_PI" key : "PI:KEY:<KEY>END_PI" ciphertext : "2956e1c8693536b1bee99c73a31576b6" } ] test_single = (T, v) -> aes = new AES WordArray.from_hex v.key block = WordArray.from_hex v.plaintext aes.encryptBlock block.words ctext_hex = block.to_hex() T.equal ctext_hex, v.ciphertext, "#{v.desc} -- correct encryption" aes.decryptBlock block.words ptext_hex = block.to_hex() T.equal ptext_hex, v.plaintext, "#{v.desc} -- correct decryption" exports.test_aes = (T, cb) -> for v in test_vectors test_single T, v cb()
[ { "context": " }\n {\n name:\"量子人狼\"\n title:\"全员的职业将由概率表表示。只限村人・人狼・占", "end": 47802, "score": 0.5042986869812012, "start": 47801, "tag": "NAME", "value": "量" }, { "context": " }\n {\n name:\"量子人狼\"...
client/code/pages/game/game.coffee
Yukimir/jinrou
0
this_room_id=null socket_ids=[] my_job=null timerid=null # setTimeout remain_time=null this_rule=null # 规则オブジェクトがある enter_result=null #enter this_icons={} #名字と头像の対応表 this_logdata={} # ログ数据をアレする this_style=null #style要素(終わったら消したい) exports.start=(roomid)-> this_rule=null timerid=null remain_time=null my_job=null this_room_id=null # 职业名一览 cjobs=Shared.game.jobs.filter (x)->x!="Human" # 村人は自動で决定する # CSS操作 this_style=document.createElement "style" document.head.appendChild this_style sheet=this_style.sheet #现在の规则 myrules= player:null # プレイヤー・ネーム day:"all" # 表示する日にち setcss=-> while sheet.cssRules.length>0 sheet.deleteRule 0 if myrules.player? sheet.insertRule "#logs > div:not([data-name=\"#{myrules.player}\"]) {opacity: .5}",0 day=null if myrules.day=="today" day=this_logdata.day # 现在 else if myrules.day!="all" day=parseInt myrules.day # 表示したい日 if day? # 表示する sheet.insertRule "#logs > div:not([data-day=\"#{day}\"]){display: none}",0 getenter=(result)-> if result.error? # 错误 Index.util.message "房间",result.error return else if result.require? if result.require=="password" #密码入力 Index.util.prompt "房间","房间已加密,请输入密码",{type:"password"},(pass)-> unless pass? Index.app.showUrl "/rooms" return ss.rpc "game.rooms.enter", roomid,pass,getenter sessionStorage.roompassword = pass return enter_result=result this_room_id=roomid ss.rpc "game.rooms.oneRoom", roomid,initroom ss.rpc "game.rooms.enter", roomid,sessionStorage.roompassword ? null,getenter initroom=(room)-> unless room? Index.util.message "房间","这个房间不存在。" Index.app.showUrl "/rooms" return # 表单を修正する forminfo=-> setplayersnumber room,$("#gamestart").get(0), room.players.filter((x)->x.mode=="player").length # 今までのログを送ってもらう this_icons={} this_logdata={} this_openjob_flag=false # 职业情報をもらった getjobinfo=(obj)-> console.log obj,this_room_id return unless obj.id==this_room_id my_job=obj.type $("#jobinfo").empty() pp=(text)-> p=document.createElement "p" p.textContent=text p if obj.type infop=$ "<p>你的身份是<b>#{obj.jobname}</b>(</p>" if obj.desc # 职业説明 for o,i in obj.desc if i>0 infop.append "・" a=$ "<a href='/manual/job/#{o.type}'>#{if obj.desc.length==1 then '详细' else "#{o.name}的详细"}</a>" infop.append a infop.append ")" $("#jobinfo").append infop if obj.myteam? # ケミカル人狼用の陣営情報 if obj.myteam == "" $("#jobinfo").append pp "你没有初始阵营" else teamstring = Shared.game.jobinfo[obj.myteam]?.name $("#jobinfo").append pp "你的初始阵营是 #{teamstring}" if obj.wolves? $("#jobinfo").append pp "同伴的人狼是 #{obj.wolves.map((x)->x.name).join(",")}" if obj.peers? $("#jobinfo").append pp "共有者是 #{obj.peers.map((x)->x.name).join(',')}" if obj.foxes? $("#jobinfo").append pp "同伴的妖狐是 #{obj.foxes.map((x)->x.name).join(',')}" if obj.nobles? $("#jobinfo").append pp "贵族是 #{obj.nobles.map((x)->x.name).join(',')}" if obj.queens?.length>0 $("#jobinfo").append pp "女王观战者是 #{obj.queens.map((x)->x.name).join(',')}" if obj.spy2s?.length>0 $("#jobinfo").append pp "间谍Ⅱ是 #{obj.spy2s.map((x)->x.name).join(',')}" if obj.friends?.length>0 $("#jobinfo").append pp "恋人是 #{obj.friends.map((x)->x.name).join(',')}" if obj.stalking? $("#jobinfo").append pp "你是 #{obj.stalking.name}的跟踪狂" if obj.cultmembers? $("#jobinfo").append pp "信者是 #{obj.cultmembers.map((x)->x.name).join(',')}" if obj.vampires? $("#jobinfo").append pp "吸血鬼是 #{obj.vampires.map((x)->x.name).join(',')}" if obj.supporting? $("#jobinfo").append pp "向 #{obj.supporting.name}(#{obj.supportingJob}) 提供帮助" if obj.dogOwner? $("#jobinfo").append pp "你的饲主是 #{obj.dogOwner.name}" if obj.quantumwerewolf_number? $("#jobinfo").append pp "你的玩家编号是第 #{obj.quantumwerewolf_number} 号" if obj.winner? # 勝敗 $("#jobinfo").append pp "你#{if obj.winner then '胜利' else '败北'}了" if obj.dead # 自己は既に死んでいる document.body.classList.add "heaven" else document.body.classList.remove "heaven" if obj.will $("#willform").get(0).elements["will"].value=obj.will if game=obj.game if game.finished # 终了 document.body.classList.add "finished" document.body.classList.remove x for x in ["day","night"] if $(".sticky").length $(".sticky").removeAttr "style" $(".sticky").removeAttr "class" $("#logs").removeAttr "style" $("#jobform").attr "hidden","hidden" if timerid clearInterval timerid timerid=null else # 昼と夜の色 document.body.classList.add (if game.night then "night" else "day") document.body.classList.remove (if game.night then "day" else "night") if $("#sticky").hasClass("sticky") $("#sticky").css "background-color": $("body").css("background-color") unless $("#jobform").get(0).hidden= game.finished || obj.sleeping || !obj.type # 代入しつつの 投票表单必要な場合 $("#jobform div.jobformarea").attr "hidden","hidden" #$("#form_day").get(0).hidden= game.night || obj.sleeping || obj.type=="GameMaster" $("#form_day").get(0).hidden= !obj.voteopen obj.open?.forEach (x)-> # 開けるべき表单が指定されている $("#form_#{x}").prop "hidden",false if (obj.job_selection ? []).length==0 # 対象选择がない・・・表示しない $("#form_players").prop "hidden",true else $("#form_players").prop "hidden",false if game.players formplayers game.players unless this_rule? $("#speakform").get(0).elements["rulebutton"].disabled=false $("#speakform").get(0).elements["norevivebutton"].disabled=false this_rule= jobscount:game.jobscount rule:game.rule setJobSelection obj.job_selection ? [] select=$("#speakform").get(0).elements["mode"] if obj.speak && obj.speak.length>0 # 发言方法の选择 $(select).empty() select.disabled=false for val in obj.speak option=document.createElement "option" option.value=val option.text=speakValueToStr game,val select.add option select.value=obj.speak[0] select.options[0]?.selected=true else select.disabled=true if obj.openjob_flag==true && this_openjob_flag==false # 状況がかわったのでリフレッシュすべき this_openjob_flag=true unless obj.logs? # ログをもらってない場合はもらいたい ss.rpc "game.game.getlog",roomid,sentlog sentlog=(result)-> if result.error? Index.util.message "错误",result.error else if result.game?.day>=1 # 游戏が始まったら消す $("#playersinfo").empty() #TODO: 加入游戏ボタンが2箇所にあるぞ if result.game if !result.game.finished && result.game.rule.jobrule=="特殊规则.Endless黑暗火锅" && !result.type? # Endless黑暗火锅に参加可能 b=makebutton "加入游戏" $("#playersinfo").append b $(b).click joinbutton getjobinfo result $("#logs").empty() $("#chooseviewday").empty() # 何日目だけ表示 if result.game?.finished # 终了した・・・次の游戏ボタン b=makebutton "以相同设定建立新房间","新房间建成后仍可以变更设定。" $("#playersinfo").append b $(b).click (je)-> # 规则を保存 localStorage.savedRule=JSON.stringify result.game.rule localStorage.savedJobs=JSON.stringify result.game.jobscount #Index.app.showUrl "/newroom" # 新しいタブで開く a=document.createElement "a" a.href="/newroom" a.target="_blank" a.click() result.logs.forEach getlog gettimer parseInt(result.timer),result.timer_mode if result.timer? ss.rpc "game.game.getlog", roomid,sentlog # 新しい游戏 newgamebutton = (je)-> unless $("#gamestartsec").attr("hidden") == "hidden" return form=$("#gamestart").get 0 # 规则设定保存を参照する # 规则画面を構築するぞーーー(idx: グループのアレ) buildrules=(arr,parent)-> p=null for obj,idx in arr if obj.rules # グループだ if p && !p.get(0).hasChildNodes() # 空のpは要らない p.remove() fieldset=$ "<fieldset>" pn=parent.attr("name") || "" fieldset.attr "name","#{pn}.#{idx}" if obj.label fieldset.append $ "<legend>#{obj.label}</legend>" buildrules obj.rules,fieldset parent.append fieldset p=null else # ひとつの设定だ if obj.type=="separator" # pの区切り p=$ "<p>" p.appendTo parent continue unless p? p=$ "<p>" p.appendTo parent label=$ "<label>" if obj.title label.attr "title",obj.title unless obj.backlabel if obj.type!="hidden" label.text obj.label switch obj.type when "checkbox" input=$ "<input>" input.attr "type","checkbox" input.attr "name",obj.name input.attr "value",obj.value.value input.prop "checked",!!obj.value.checked label.append input when "select" select=$ "<select>" select.attr "name",obj.name slv=null for o in obj.values op=$ "<option>" op.text o.label if o.title op.attr "title",o.title op.attr "value",o.value select.append op if o.selected slv=o.value if slv? select.get(0).value=slv label.append select when "time" input=$ "<input>" input.attr "type","number" input.attr "name",obj.name.minute input.attr "min","0" input.attr "step","1" input.attr "size","5" input.attr "value",String obj.defaultValue.minute label.append input label.append document.createTextNode "分" input.change ()-> if(Number($(this).val()) < 0) $(this).val(0) input=$ "<input>" input.attr "type","number" input.attr "name",obj.name.second input.attr "min","-15" input.attr "max","60" input.attr "step","15" input.attr "size","5" input.attr "value",String obj.defaultValue.second label.append input label.append document.createTextNode "秒" input.change ()-> if(Number($(this).val()) >= 60) $(this).val(0) $(this).prev().val(Number($(this).prev().val())+1) $(this).prev().change() else if(Number($(this).val()) < 0) $(this).val(45) $(this).prev().val(Number($(this).prev().val())-1) $(this).prev().change() when "hidden" input=$ "<input>" input.attr "type","hidden" input.attr "name",obj.name input.attr "value",obj.value.value label.append input when "second" input=$ "<input>" input.attr "type","number" input.attr "name",obj.name input.attr "min","0" input.attr "step","1" input.attr "size","5" input.attr "value",obj.defaultValue.value label.append input if obj.backlabel if obj.type!="hidden" label.append document.createTextNode obj.label p.append label $("#rules").attr "name","rule" buildrules Shared.game.rules,$("#rules") if localStorage.savedRule rule=JSON.parse localStorage.savedRule jobs=JSON.parse localStorage.savedJobs delete localStorage.savedRule delete localStorage.savedJobs # 时间设定 daysec=rule.day-0 nightsec=rule.night-0 remainsec=rule.remain-0 form.elements["day_minute"].value=parseInt daysec/60 form.elements["day_second"].value=daysec%60 form.elements["night_minute"].value=parseInt nightsec/60 form.elements["night_second"].value=nightsec%60 form.elements["remain_minute"].value=parseInt remainsec/60 form.elements["remain_second"].value=remainsec%60 # 其他 delete rule.number # 人数は違うかも for key of rule e=form.elements[key] if e? if e.type=="checkbox" e.checked = e.value==rule[key] else e.value=rule[key] # 配置も再現 for job in Shared.game.jobs e=form.elements[job] # 职业 if e? e.value=jobs[job]?.number ? 0 $("#gamestartsec").removeAttr "hidden" forminfo() $("#roomname").text room.name if room.mode=="waiting" # 開始前のユーザー一覧は roomから取得する console.log room.players room.players.forEach (x)-> li=makeplayerbox x,room.blind $("#players").append li # 未参加の場合は参加ボタン joinbutton=(je)-> # 参加 opt= name:"" icon:null into=-> ss.rpc "game.rooms.join", roomid,opt,(result)-> if result?.require=="login" # ログインが必要 Index.util.loginWindow -> if Index.app.userid() into() else if result?.error? Index.util.message "房间",result.error else if result?.tip? Index.util.message result.title,result.tip # 如果房间有特殊提示 Index.app.refresh() else Index.app.refresh() if room.blind && !room.theme # 参加者名 ### Index.util.prompt "加入游戏","请输入昵称",null,(name)-> if name opt.name=name into() ### # ここ書いてないよ! Index.util.blindName null,(obj)-> if obj? opt.name=obj.name opt.icon=obj.icon into() else into() if (room.mode=="waiting" || room.mode=="playing" && room.jobrule=="特殊规则.Endless黑暗火锅") && !enter_result?.joined # 未参加 b=makebutton "加入游戏" $("#playersinfo").append b $(b).click joinbutton else if room.mode=="waiting" && enter_result?.joined # Endless黑暗火锅でも脱退はできない b=makebutton "退出游戏" $("#playersinfo").append b $(b).click (je)-> # 脱退 ss.rpc "game.rooms.unjoin", roomid,(result)-> if result? Index.util.message "房间",result else Index.app.refresh() if room.mode=="waiting" # 开始前 b=makebutton "准备/取消准备","全员准备好后即可开始游戏。" $("#playersinfo").append b $(b).click (je)-> ss.rpc "game.rooms.ready", roomid,(result)-> if result? Index.util.message "房间",result b=makebutton "帮手","成为他人的帮手后,将不会直接参与游戏,而是向帮助的对象提供建议。" # 帮手になる/やめるボタン $(b).click (je)-> Index.util.selectprompt "帮手","想要成为谁的帮手?",room.players.map((x)->{name:x.name,value:x.userid}),(id)-> ss.rpc "game.rooms.helper",roomid, id,(result)-> if result? Index.util.message "错误",result $("#playersinfo").append b userid=Index.app.userid() if room.mode=="waiting" if room.owner.userid==Index.app.userid() # 自己 b=makebutton "展开游戏开始界面" $("#playersinfo").append b $(b).click newgamebutton b=makebutton "将参加者踢出游戏" $("#playersinfo").append b $(b).click (je)-> Index.util.selectprompt "踢出","请选择要被踢出的人",room.players.map((x)->{name:x.name,value:x.userid}),(id)-> if id ss.rpc "game.rooms.kick", roomid,id,(result)-> if result? Index.util.message "错误",result b=makebutton "重置[ready]状态" $("#playersinfo").append b $(b).click (je)-> Index.util.ask "重置[ready]状态","要解除全员的[ready]状态吗?",(cb)-> if cb ss.rpc "game.rooms.unreadyall",roomid,(result)-> if result? Index.util.message "错误",result # 役職入力フォームを作る (()=> # job -> cat と job -> team を作る catTable = {} teamTable = {} dds = {} for category,members of Shared.game.categories # HTML dt = document.createElement "dt" dt.textContent = Shared.game.categoryNames[category] dt.classList.add "jobs-cat" dd = dds[category] = document.createElement "dd" dd.classList.add "jobs-cat" $("#jobsfield").append(dt).append(dd) # table for job in members catTable[job] = category dt = document.createElement "dt" dt.classList.add "jobs-cat" dt.textContent = "其他" dd = dds["*"] = document.createElement "dd" dd.classList.add "jobs-cat" # その他は今の所ない # $("#jobsfield").append(dt).append(dd) # table for team,members of Shared.game.teams for job in members teamTable[job] = team for job in Shared.game.jobs # 探す dd = $(dds[catTable[job] ? "*"]) team = teamTable[job] continue unless team? ji = Shared.game.jobinfo[team][job] div = document.createElement "div" div.classList.add "jobs-job" div.dataset.job = job b = document.createElement "b" span = document.createElement "span" span.textContent = ji.name b.appendChild span b.insertAdjacentHTML "beforeend", "<a class='jobs-job-help' href='/manual/job/#{job}'><i class='fa fa-question-circle-o'></i></a>" span = document.createElement "span" span.classList.add "jobs-job-controls" if job == "Human" # 村人は違う処理 output = document.createElement "output" output.name = job output.dataset.jobname = ji.name output.classList.add "jobs-job-controls-number" span.appendChild output check = document.createElement "input" check.type = "hidden" check.name = "job_use_#{job}" check.value = "on" span.appendChild check else # 使用チェック check = document.createElement "input" check.type = "checkbox" check.checked = true check.name = "job_use_#{job}" check.value = "on" check.classList.add "jobs-job-controls-check" check.title = "如果取消复选框,在手调黑暗火锅里 #{ji.name} 将不会出现。" span.appendChild check # 人数 input = document.createElement "input" input.type = "number" input.min = 0 input.step = 1 input.value = 0 input.name = job input.dataset.jobname = ji.name input.classList.add "jobs-job-controls-number" # plus / minus button button1 = document.createElement "button" button1.type = "button" button1.classList.add "jobs-job-controls-button" ic1 = document.createElement "i" ic1.classList.add "fa" ic1.classList.add "fa-plus-square" button1.appendChild ic1 button1.addEventListener 'click', ((job)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements[job] v = parseInt(num.value) num.value = String(v + 1) jobsformvalidate room, form )(job) button2 = document.createElement "button" button2.type = "button" button2.classList.add "jobs-job-controls-button" ic2 = document.createElement "i" ic2.classList.add "fa" ic2.classList.add "fa-minus-square" button2.appendChild ic2 button2.addEventListener 'click', ((job)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements[job] v = parseInt(num.value) if v > 0 num.value = String(v - 1) jobsformvalidate room, form )(job) span.appendChild input span.appendChild button1 span.appendChild button2 div.appendChild b div.appendChild span dd.append div # カテゴリ別のも用意しておく dt = document.createElement "dt" dt.classList.add "jobs-cat" dt.textContent = "手调黑暗火锅用" dd = document.createElement "dd" dd.classList.add "jobs-cat" for type,name of Shared.game.categoryNames div = document.createElement "div" div.classList.add "jobs-job" div.dataset.job = "category_#{type}" b = document.createElement "b" span = document.createElement "span" span.textContent = name b.appendChild span span = document.createElement "span" span.classList.add "jobs-job-controls" input = document.createElement "input" input.type = "number" input.min = 0 input.step = 1 input.value = 0 input.name = "category_#{type}" input.dataset.jobname = name input.classList.add "jobs-job-controls-number" # plus / minus button button1 = document.createElement "button" button1.type = "button" button1.classList.add "jobs-job-controls-button" ic1 = document.createElement "i" ic1.classList.add "fa" ic1.classList.add "fa-plus-square" button1.appendChild ic1 button1.addEventListener 'click', ((type)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements["category_#{type}"] v = parseInt(num.value) num.value = String(v + 1) jobsformvalidate room, form )(type) button2 = document.createElement "button" button2.type = "button" button2.classList.add "jobs-job-controls-button" ic2 = document.createElement "i" ic2.classList.add "fa" ic2.classList.add "fa-minus-square" button2.appendChild ic2 button2.addEventListener 'click', ((type)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements["category_#{type}"] v = parseInt(num.value) if v > 0 num.value = String(v - 1) jobsformvalidate room, form )(type) span.appendChild input span.appendChild button1 span.appendChild button2 div.appendChild b div.appendChild span dd.appendChild div $("#catesfield").append(dt).append(dd) )() if room.owner.userid==Index.app.userid() || room.old b=makebutton "废弃这个房间" $("#playersinfo").append b $(b).click (je)-> Index.util.ask "废弃房间","确定要废弃这个房间吗?",(cb)-> if cb ss.rpc "game.rooms.del", roomid,(result)-> if result? Index.util.message "错误",result form=$("#gamestart").get 0 # ゲーム開始フォームが何か変更されたら呼ばれる関数 jobsforminput=(e)-> t=e.target form=t.form pl=room.players.filter((x)->x.mode=="player").length if t.name=="jobrule" || t.name=="chemical" # ルール変更があった resetplayersinput room, form setplayersbyjobrule room,form,pl jobsformvalidate room,form form.addEventListener "input",jobsforminput,false form.addEventListener "change",jobsforminput,false $("#gamestart").submit (je)-> # いよいよ游戏开始だ! je.preventDefault() query=Index.util.formQuery je.target jobrule=query.jobrule ruleobj=Shared.game.getruleobj(jobrule) ? {} # ステップ2: 时间チェック step2=-> # 夜时间をチェック minNight = ruleobj.suggestedNight?.min ? -Infinity maxNight = ruleobj.suggestedNight?.max ? Infinity night = parseInt(query.night_minute)*60+parseInt(query.night_second) #console.log ruleobj,night,minNight,maxNight if night<minNight || maxNight<night # 範囲オーバー Index.util.ask "选项","这个配置推荐的夜间时间在#{if isFinite(minNight) then minNight+'秒以上' else ''}#{if isFinite(maxNight) then maxNight+'秒以下' else ''},确认要开始游戏吗?",(res)-> if res #OKだってよ... starting() else starting() # じっさいに开始 starting=-> ss.rpc "game.game.gameStart", roomid,query,(result)-> if result? Index.util.message "房间",result else $("#gamestartsec").attr "hidden","hidden" # 相違がないか探す diff=null for key,value of (ruleobj.suggestedOption ? {}) if query[key]!=value diff= key:key value:value break if diff? control=je.target.elements[diff.key] if control? sugval=null if control.type=="select-one" for opt in control.options if opt.value==diff.value sugval=opt.text break if sugval? Index.util.ask "选项","这个配置下推荐选项「#{control.dataset.name}」 「#{sugval}」。可以这样开始游戏吗?",(res)-> if res # OKだってよ... step2() return # とくに何もない step2() speakform=$("#speakform").get 0 $("#speakform").submit (je)-> form=je.target ss.rpc "game.game.speak", roomid,Index.util.formQuery(form),(result)-> if result? Index.util.message "错误",result je.preventDefault() form.elements["comment"].value="" if form.elements["multilinecheck"].checked # 複数行は直す form.elements["multilinecheck"].click() speakform.elements["willbutton"].addEventListener "click", (e)-> # 遗言表单オープン wf=$("#willform").get 0 if wf.hidden wf.hidden=false e.target.value="折叠遗言" else wf.hidden=true e.target.value="遗言" ,false speakform.elements["multilinecheck"].addEventListener "click",(e)-> # 複数行 t=e.target textarea=null comment=t.form.elements["comment"] if t.checked # これから複数行になる textarea=document.createElement "textarea" textarea.cols=50 textarea.rows=4 else # 複数行をやめる textarea=document.createElement "input" textarea.size=50 textarea.name="comment" textarea.value=comment.value if textarea.type=="textarea" && textarea.value textarea.value+="\n" textarea.required=true $(comment).replaceWith textarea textarea.focus() textarea.setSelectionRange textarea.value.length,textarea.value.length # 複数行ショートカット $(speakform).keydown (je)-> if je.keyCode==13 && je.shiftKey && je.target.form.elements["multilinecheck"].checked==false # 複数行にする je.target.form.elements["multilinecheck"].click() je.preventDefault() # 规则表示 $("#speakform").get(0).elements["rulebutton"].addEventListener "click", (e)-> return unless this_rule? win=Index.util.blankWindow() win.append $ "<h1>规则</h1>" p=document.createElement "p" Object.keys(this_rule.jobscount).forEach (x)-> a=document.createElement "a" a.href="/manual/job/#{x}" a.textContent="#{this_rule.jobscount[x].name}#{this_rule.jobscount[x].number}" p.appendChild a p.appendChild document.createTextNode " " win.append p chkrule=(ruleobj,jobscount,rules)-> for obj in rules if obj.rules continue unless obj.visible ruleobj,jobscount chkrule ruleobj,jobscount,obj.rules else p=$ "<p>" val="" if obj.title? p.attr "title",obj.title if obj.type=="separator" continue if obj.getstr? valobj=obj.getstr ruleobj[obj.name] unless valobj? continue val="#{valobj.label ? ''}:#{valobj.value ? ''}" else val="#{obj.label}:" switch obj.type when "checkbox" if ruleobj[obj.name]==obj.value.value unless obj.value.label? continue val+=obj.value.label else unless obj.value.nolabel? continue val+=obj.value.nolabel when "select" flg=false for vobj in obj.values if ruleobj[obj.name]==vobj.value val+=vobj.label if vobj.title p.attr "title",vobj.title flg=true break unless flg continue when "time" val+="#{ruleobj[obj.name.minute]}分#{ruleobj[obj.name.second]}秒" when "second" val+="#{ruleobj[obj.name]}秒" when "hidden" continue p.text val win.append p chkrule this_rule.rule, this_rule.jobscount,Shared.game.rules $("#willform").submit (je)-> form=je.target je.preventDefault() ss.rpc "game.game.will", roomid,form.elements["will"].value,(result)-> if result? Index.util.message "错误",result else $("#willform").get(0).hidden=true $("#speakform").get(0).elements["willbutton"].value="遗言" # 夜の仕事(あと投票) $("#jobform").submit (je)-> form=je.target je.preventDefault() $("#jobform").attr "hidden","hidden" ss.rpc "game.game.job", roomid,Index.util.formQuery(form), (result)-> if result?.error? Index.util.message "错误",result.error $("#jobform").removeAttr "hidden" else if !result?.sleeping # まだ仕事がある $("#jobform").removeAttr "hidden" getjobinfo result else getjobinfo result .click (je)-> bt=je.target if bt.type=="submit" # 送信ボタン bt.form.elements["commandname"].value=bt.name # コマンド名教えてあげる bt.form.elements["jobtype"].value=bt.dataset.job # 职业名も教えてあげる # 拒绝复活ボタン $("#speakform").get(0).elements["norevivebutton"].addEventListener "click",(e)-> Index.util.ask "拒绝复活","一旦拒绝复活将不能撤销。确定要这样做吗?",(result)-> if result ss.rpc "game.game.norevive", roomid, (result)-> if result? # 错误 Index.util.message "错误",result else Index.util.message "拒绝复活","成功拒绝复活。" ,false #======================================== # 誰かが参加した!!!! socket_ids.push Index.socket.on "join","room#{roomid}",(msg,channel)-> room.players.push msg ### li=document.createElement "li" li.title=msg.userid if room.blind li.textContent=msg.name else a=document.createElement "a" a.href="/user/#{msg.userid}" a.textContent=msg.name li.appendChild a ### li=makeplayerbox msg,room.blind $("#players").append li forminfo() # 誰かが出て行った!!! socket_ids.push Index.socket.on "unjoin","room#{roomid}",(msg,channel)-> room.players=room.players.filter (x)->x.userid!=msg $("#players li").filter((idx)-> this.dataset.id==msg).remove() forminfo() # kickされた socket_ids.push Index.socket.on "kicked",null,(msg,channel)-> if msg.id==roomid Index.app.refresh() # 準備 socket_ids.push Index.socket.on "ready","room#{roomid}",(msg,channel)-> for pl in room.players if pl.userid==msg.userid pl.start=msg.start li=$("#players li").filter((idx)-> this.dataset.id==msg.userid) li.replaceWith makeplayerbox pl,room.blind socket_ids.push Index.socket.on "unreadyall","room#{roomid}",(msg,channel)-> for pl in room.players if pl.start pl.start=false li=$("#players li").filter((idx)-> this.dataset.id==pl.userid) li.replaceWith makeplayerbox pl,room.blind socket_ids.push Index.socket.on "mode","room#{roomid}",(msg,channel)-> for pl in room.players if pl.userid==msg.userid pl.mode=msg.mode li=$("#players li").filter((idx)-> this.dataset.id==msg.userid) li.replaceWith makeplayerbox pl,room.blind forminfo() # ログが流れてきた!!! socket_ids.push Index.socket.on "log",null,(msg,channel)-> #if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() if msg.roomid==roomid # この部屋へのログ getlog msg # 職情報を教えてもらった!!! socket_ids.push Index.socket.on "getjob",null,(msg,channel)-> if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() getjobinfo msg # 更新したほうがいい socket_ids.push Index.socket.on "refresh",null,(msg,channel)-> if msg.id==roomid #Index.app.refresh() ss.rpc "game.rooms.enter", roomid,sessionStorage.roompassword ? null,(result)-> ss.rpc "game.game.getlog", roomid,sentlog ss.rpc "game.rooms.oneRoom", roomid,(r)->room=r # 投票表单オープン socket_ids.push Index.socket.on "voteform",null,(msg,channel)-> if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() if msg $("#jobform").removeAttr "hidden" else $("#jobform").attr "hidden","hidden" # 残り时间 socket_ids.push Index.socket.on "time",null,(msg,channel)-> if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() gettimer parseInt(msg.time),msg.mode # 向房间成员通报猝死统计 socket_ids.push Index.socket.on 'punishalert',null,(msg,channel)-> if msg.id==roomid Index.util.punish "猝死惩罚",msg,(result)-> # console.log "猝死名单" # console.log result ss.rpc "game.rooms.suddenDeathPunish", roomid,result,(result)-> if result? if result.error? # 错误 Index.util.message "猝死惩罚",result.error return Index.util.message "猝死惩罚",result return # 向房间成员通报猝死统计 socket_ids.push Index.socket.on 'punishresult',null,(msg,channel)-> if msg.id==roomid # Index.util.message "猝死惩罚",msg.name+"由于猝死被禁止游戏" console.log "room:",msg.id,msg $(document).click (je)-> # クリックで发言強調 li=if je.target.tagName.toLowerCase()=="li" then je.target else $(je.target).parents("li").get 0 myrules.player=null if $(li).parent("#players").length >0 if li? # 強調 myrules.player=li.dataset.name setcss() $("#chooseviewselect").change (je)-> # 表示部分を选择 v=je.target.value myrules.day=v setcss() .click (je)-> je.stopPropagation() # 配役タイプ setjobrule=(rulearr,names,parent)-> for obj in rulearr # name,title, ruleをもつ if obj.rule instanceof Array # さらに子 optgroup=document.createElement "optgroup" optgroup.label=obj.name parent.appendChild optgroup setjobrule obj.rule,names.concat([obj.name]),optgroup else # option option=document.createElement "option" option.textContent=obj.name option.value=names.concat([obj.name]).join "." option.title=obj.title parent.appendChild option setjobrule Shared.game.jobrules.concat([ name:"特殊规则" rule:[ { name:"自由配置" title:"可以自由的选择角色。" rule:null } { name:"黑暗火锅" title:"各角色人数将随机分配。" rule:null } { name:"手调黑暗火锅" title:"一部分角色由房主分配,其他角色随机分配。" rule:null } { name:"量子人狼" title:"全员的职业将由概率表表示。只限村人・人狼・占卜师。" rule:null suggestedNight:{ max:60 } } { name:"Endless黑暗火锅" title:"可以途中参加・死亡后立刻转生黑暗火锅。" rule:null suggestedOption:{ heavenview:"" } } ] ]),[],$("#jobruleselect").get 0 setplayersnumber=(room,form,number)-> form.elements["number"].value=number unless $("#gamestartsec").attr("hidden") == "hidden" setplayersbyjobrule room,form,number jobsformvalidate room,form # 配置一览をアレする setplayersbyjobrule=(room,form,number)-> jobrulename=form.elements["jobrule"].value if form.elements["scapegoat"]?.value=="on" number++ # 身代わりくん if jobrulename in ["特殊规则.自由配置","特殊规则.手调黑暗火锅"] j = $("#jobsfield").get 0 j.hidden=false j.dataset.checkboxes = (if jobrulename!="特殊规则.手调黑暗火锅" then "no" else "") $("#catesfield").get(0).hidden= jobrulename!="特殊规则.手调黑暗火锅" #$("#yaminabe_opt_nums").get(0).hidden=true else if jobrulename in ["特殊规则.黑暗火锅","特殊规则.Endless黑暗火锅"] $("#jobsfield").get(0).hidden=true $("#catesfield").get(0).hidden=true #$("#yaminabe_opt_nums").get(0).hidden=false else $("#jobsfield").get(0).hidden=true $("#catesfield").get(0).hidden=true if jobrulename=="特殊规则.量子人狼" jobrulename="内部利用.量子人狼" obj= Shared.game.getrulefunc jobrulename if obj? form.elements["number"].value=number for x in Shared.game.jobs form.elements[x].value=0 jobs=obj number count=0 #村人以外 for job,num of jobs form.elements[job]?.value=num count+=num # カテゴリ別 for type of Shared.game.categoryNames count+= parseInt(form.elements["category_#{type}"].value ? 0) # 残りが村人の人数 if form.elements["chemical"]?.checked # chemical人狼では村人を足す form.elements["Human"].value = number*2 - count else form.elements["Human"].value = number-count setjobsmonitor form,number jobsformvalidate=(room,form)-> # 村人の人数を調節する pl=room.players.filter((x)->x.mode=="player").length if form.elements["scapegoat"].value=="on" # 替身君 pl++ sum=0 cjobs.forEach (x)-> chk = form.elements["job_use_#{x}"].checked if chk sum+=Number form.elements[x].value else form.elements[x].value = 0 # カテゴリ別 for type of Shared.game.categoryNames sum+= parseInt(form.elements["category_#{type}"].value ? 0) if form.elements["chemical"].checked form.elements["Human"].value=pl*2-sum else form.elements["Human"].value=pl-sum form.elements["number"].value=pl setplayersinput room, form setjobsmonitor form,pl # 规则の表示具合をチェックする checkrule=(form,ruleobj,rules,fsetname)-> for obj,idx in rules continue unless obj.rules fsetname2="#{fsetname}.#{idx}" form.elements[fsetname2].hidden=!(obj.visible ruleobj,ruleobj) checkrule form,ruleobj,obj.rules,fsetname2 # ルールが変更されたときはチェックを元に戻す resetplayersinput=(room, form)-> rule = form.elements["jobrule"].value if rule != "特殊规则.手调黑暗火锅" checks = form.querySelectorAll 'input.jobs-job-controls-check[name^="job_use_"]' for check in checks check.checked = true # フォームに応じてプレイヤーの人数inputの表示を調整 setplayersinput=(room, form)-> divs = document.querySelectorAll "div.jobs-job" for div in divs job = div.dataset.job if job? e = form.elements[job] chk = form.elements["job_use_#{job}"] if e? v = Number e.value if chk? && chk.type=="checkbox" && !chk.checked # 無効化されている div.classList.remove "jobs-job-active" div.classList.add "jobs-job-inactive" div.classList.remove "jobs-job-error" else if v > 0 div.classList.add "jobs-job-active" div.classList.remove "jobs-job-inactive" div.classList.remove "jobs-job-error" else if v < 0 div.classList.remove "jobs-job-active" div.classList.remove "jobs-job-inactive" div.classList.add "jobs-job-error" else div.classList.remove "jobs-job-active" div.classList.remove "jobs-job-inactive" div.classList.remove "jobs-job-error" # 配置をテキストで書いてあげる setjobsmonitor=(form,number)-> text="" rule=Index.util.formQuery form jobrule=rule.jobrule if jobrule=="特殊规则.黑暗火锅" # 黑暗火锅の場合 $("#jobsmonitor").text "黑暗火锅" else if jobrule=="特殊规则.Endless黑暗火锅" $("#jobsmonitor").text "Endless黑暗火锅" else ruleobj=Shared.game.getruleobj jobrule if ruleobj?.minNumber>number $("#jobsmonitor").text "(这个配置最少需要#{ruleobj.minNumber}个人)" else $("#jobsmonitor").text Shared.game.getrulestr jobrule,rule ### jobprops=$("#jobprops") jobprops.children(".prop").prop "hidden",true for job in Shared.game.jobs jobpr=jobprops.children(".prop.#{job}") if jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅"] || form.elements[job].value>0 jobpr.prop "hidden",false # 规则による设定 ruleprops=$("#ruleprops") ruleprops.children(".prop").prop "hidden",true switch jobrule when "特殊规则.量子人狼" ruleprops.children(".prop.rule-quantum").prop "hidden",false # あと替身君はOFFにしたい form.elements["scapegoat"].value="off" ### if jobrule=="特殊规则.量子人狼" # あと替身君はOFFにしたい form.elements["scapegoat"].value="off" rule.scapegoat="off" checkrule form,rule,Shared.game.rules,$("#rules").attr("name") #ログをもらった getlog=(log)-> if log.mode in ["voteresult","probability_table"] # 表を出す p=document.createElement "div" div=document.createElement "div" div.classList.add "icon" p.appendChild div div=document.createElement "div" div.classList.add "name" p.appendChild div tb=document.createElement "table" if log.mode=="voteresult" tb.createCaption().textContent="投票结果" vr=log.voteresult tos=log.tos vr.forEach (player)-> tr=tb.insertRow(-1) tr.insertCell(-1).textContent=player.name tr.insertCell(-1).textContent="#{tos[player.id] ? '0'}票" tr.insertCell(-1).textContent="→#{vr.filter((x)->x.id==player.voteto)[0]?.name ? ''}" else # %表示整形 pbu=(node,num)-> node.textContent=(if num==1 "100%" else (num*100).toFixed(2)+"%" ) if num==1 node.style.fontWeight="bold" return tb.createCaption().textContent="概率表" pt=log.probability_table # 見出し tr=tb.insertRow -1 th=document.createElement "th" th.textContent="名字" tr.appendChild th th=document.createElement "th" if this_rule?.rule.quantumwerewolf_diviner=="on" th.textContent="村人" else th.textContent="人类" tr.appendChild th if this_rule?.rule.quantumwerewolf_diviner=="on" # 占卜师の確率も表示: th=document.createElement "th" th.textContent="占卜师" tr.appendChild th th=document.createElement "th" th.textContent="人狼" tr.appendChild th if this_rule?.rule.quantumwerewolf_dead!="no" th=document.createElement "th" th.textContent="死亡" tr.appendChild th for id,obj of pt tr=tb.insertRow -1 tr.insertCell(-1).textContent=obj.name pbu tr.insertCell(-1),obj.Human if obj.Diviner? pbu tr.insertCell(-1),obj.Diviner pbu tr.insertCell(-1),obj.Werewolf if this_rule?.rule.quantumwerewolf_dead!="no" pbu tr.insertCell(-1),obj.dead if obj.dead==1 tr.classList.add "deadoff-line" p.appendChild tb else p=document.createElement "div" div=document.createElement "div" div.classList.add "name" icondiv=document.createElement "div" icondiv.classList.add "icon" if log.name? div.textContent=switch log.mode when "monologue", "heavenmonologue" "#{log.name}自言自语:" when "will" "#{log.name}遗言:" else "#{log.name}:" if this_icons[log.name] # 头像がある img=document.createElement "img" img.style.width="1em" img.style.height="1em" img.src=this_icons[log.name] img.alt="" # 飾り icondiv.appendChild img p.appendChild icondiv p.appendChild div p.dataset.name=log.name span=document.createElement "div" span.classList.add "comment" if log.size in ["big","small"] # 大/小发言 span.classList.add log.size wrdv=document.createElement "div" wrdv.textContent=log.comment ? "" # 改行の処理 spp=wrdv.firstChild # Text wr=0 while spp? && (wr=spp.nodeValue.indexOf("\n"))>=0 spp=spp.splitText wr+1 wrdv.insertBefore document.createElement("br"),spp parselognode wrdv span.appendChild wrdv p.appendChild span if log.time? time=Index.util.timeFromDate new Date log.time time.classList.add "time" p.appendChild time if log.mode=="nextturn" && log.day #IDづけ p.id="turn_#{log.day}#{if log.night then '_night' else ''}" this_logdata.day=log.day this_logdata.night=log.night if log.night==false || log.day==1 # 朝の場合optgroupに追加 option=document.createElement "option" option.value=log.day option.textContent="第#{log.day}天" $("#chooseviewday").append option setcss() # 日にち数据 if this_logdata.day p.dataset.day=this_logdata.day if this_logdata.night p.dataset.night="night" else p.dataset.day=0 p.classList.add log.mode logs=$("#logs").get 0 logs.insertBefore p,logs.firstChild # プレイヤーオブジェクトのプロパティを得る ### getprop=(obj,propname)-> if obj[propname]? obj[propname] else if obj.main? getprop obj.main,propname else undefined getname=(obj)->getprop obj,"name" ### formplayers=(players)-> #jobflg: 1:生存の人 2:死人 $("#form_players").empty() $("#players").empty() $("#playernumberinfo").text "生存者#{players.filter((x)->!x.dead).length}人 / 死亡者#{players.filter((x)->x.dead).length}人" players.forEach (x)-> # 上の一览用 li=makeplayerbox x $("#players").append li # 头像 if x.icon this_icons[x.name]=x.icon setJobSelection=(selections)-> $("#form_players").empty() valuemap={} #重複を取り除く for x in selections continue if valuemap[x.value] # 重複チェック # 投票表单用 li=document.createElement "li" #if x.dead # li.classList.add "dead" label=document.createElement "label" label.textContent=x.name input=document.createElement "input" input.type="radio" input.name="target" input.value=x.value #input.disabled=!((x.dead && (jobflg&2))||(!x.dead && (jobflg&1))) label.appendChild input li.appendChild label $("#form_players").append li valuemap[x.value]=true # タイマー情報をもらった gettimer=(msg,mode)-> remain_time=parseInt msg clearInterval timerid if timerid? timerid=setInterval -> remain_time-- return if remain_time<0 min=parseInt remain_time/60 sec=remain_time%60 $("#time").text "#{mode || ''} #{min}:#{sec}" ,1000 makebutton=(text,title="")-> b=document.createElement "button" b.type="button" b.textContent=text b.title=title b exports.end=-> ss.rpc "game.rooms.exit", this_room_id,(result)-> if result? Index.util.message "房间",result return clearInterval timerid if timerid? alloff socket_ids... document.body.classList.remove x for x in ["day","night","finished","heaven"] if this_style? $(this_style).remove() #ソケットを全部off alloff= (ids...)-> ids.forEach (x)-> Index.socket.off x # ノードのコメントなどをパースする exports.parselognode=parselognode=(node)-> if node.nodeType==Node.TEXT_NODE # text node return unless node.parentNode result=document.createDocumentFragment() while v=node.nodeValue if res=v.match /^(.*?)(https?:\/\/)([^\s\/]+)(\/\S*)?/ res[4] ?= "" if res[1] # 前の部分 node=node.splitText res[1].length parselognode node.previousSibling url = res[2]+res[3]+res[4] a=document.createElement "a" a.href=url if res[3]==location.host && (res2=res[4].match /^\/room\/(\d+)$/) a.textContent="##{res2[1]}" else if res[4] in ["","/"] && res[3].length<20 a.textContent="#{res[2]}#{res[3]}/" else if res[3].length+res[4].length<60 a.textContent=res[2]+res[3]+res[4] else if res[3].length<40 a.textContent="#{res[2]}#{res[3]}#{res[4].slice(0,10)}...#{res[4].slice(-10)}" else a.textContent="#{res[2]}#{res[3].slice(0,30)}...#{(res[3]+res[4]).slice(-30)}" a.target="_blank" node=node.splitText url.length node.parentNode.replaceChild a,node.previousSibling continue if res=v.match /^(.*?)#(\d+)/ if res[1] # 前の部分 node=node.splitText res[1].length parselognode node.previousSibling a=document.createElement "a" a.href="/room/#{res[2]}" a.textContent="##{res[2]}" node=node.splitText res[2].length+1 # その部分どける node.parentNode.replaceChild a,node.previousSibling continue node.nodeValue=v.replace /(\w{30})(?=\w)/g,"$1\u200b" break else if node.childNodes for ch in node.childNodes if ch.parentNode== node parselognode ch # #players用要素 makeplayerbox=(obj,blindflg,tagname="li")->#obj:game.playersのアレ #df=document.createDocumentFragment() df=document.createElement tagname df.dataset.id=obj.id ? obj.userid df.dataset.name=obj.name if obj.icon figure=document.createElement "figure" figure.classList.add "icon" div=document.createElement "div" div.classList.add "avatar" img=document.createElement "img" img.src=obj.icon img.width=img.height=48 img.alt=obj.name div.appendChild img figure.appendChild div img2=document.createElement "img" img2.src="/images/dead.png" img2.width=img2.height=48 img2.alt="已死亡" img2.classList.add "dead_mark" figure.appendChild img2 df.appendChild figure df.classList.add "icon" p=document.createElement "p" p.classList.add "name" if obj.realid a=document.createElement "a" a.href="/user/#{obj.realid}" a.textContent=obj.name p.appendChild a else p.textContent=obj.name df.appendChild p if obj.jobname p=document.createElement "p" p.classList.add "job" if obj.originalJobname? ### if obj.originalJobname==obj.jobname || obj.originalJobname.indexOf("→")>=0 p.textContent=obj.originalJobname else p.textContent="#{obj.originalJobname}→#{obj.jobname}" ### p.textContent=obj.originalJobname else p.textContent=obj.jobname if obj.option p.textContent+= "(#{obj.option})" df.appendChild p if obj.winner? p=document.createElement "p" p.classList.add "outcome" if obj.winner p.classList.add "win" p.textContent="胜利" else p.classList.add "lose" p.textContent="败北" df.appendChild p if obj.dead df.classList.add "dead" if !obj.winner? && obj.norevive==true # 拒绝复活 p=document.createElement "p" p.classList.add "job" p.textContent="[不可复活]" df.appendChild p if obj.mode=="gm" # GM p=document.createElement "p" p.classList.add "job" p.classList.add "gm" p.textContent="[GM]" df.appendChild p else if /^helper_/.test obj.mode # 帮手 p=document.createElement "p" p.classList.add "job" p.classList.add "helper" p.textContent="[帮手]" df.appendChild p if obj.start # 準備完了 p=document.createElement "p" p.classList.add "job" p.textContent="[ready]" df.appendChild p df speakValueToStr=(game,value)-> # 发言のモード名を文字列に switch value when "day","prepare" "向全员发言" when "audience" "观战者的会话" when "monologue" "自言自语" when "werewolf" "人狼的会话" when "couple" "共有者的会话" when "fox" "妖狐的会话" when "gm" "致全员" when "gmheaven" "至灵界" when "gmaudience" "致观战者" when "gmmonologue" "自言自语" when "helperwhisper" # 帮手先がいない場合(自己への建议) "建议" else if result=value.match /^gmreply_(.+)$/ pl=game.players.filter((x)->x.id==result[1])[0] "→#{pl.name}" else if result=value.match /^helperwhisper_(.+)$/ "建议" $ -> $(window).resize -> unless $(".sticky").length > 0 return $("#sticky").css "width",$("#logs").css "width" unless $("div#content div.game").length $("#content").removeAttr "style" $("#widescreen").live "click",-> if $("#widescreen").is(':checked') $("#content").css "max-width","95%" else $("#content").removeAttr "style" $(".sticky").css "width": $("#logs").css "width" sticky_top = undefined $(window).scroll -> sticky() $("#isfloat").live "click",-> sticky() sticky = -> unless $("#sticky").length > 0 return unless $("#isfloat").is(':checked') $(".sticky").removeAttr "style" $(".sticky").removeAttr "class" $("#logs").removeAttr "style" return if $("body").hasClass("finished") return winTop = $(window).scrollTop() if winTop >= $("#sticky").offset().top and not $("#sticky").hasClass("sticky") sticky_top = $("#sticky").offset().top $("#logs").css "position": "relative" "top": $("#sticky").height() + "px" "padding-top": "5px" $("#sticky").addClass "sticky" $("#sticky").css "background-color": $("body").css("background-color") "width": $("#logs").css "width" if winTop < sticky_top and $("#sticky").hasClass("sticky") $(".sticky").removeAttr "style" $(".sticky").removeAttr "class" $("#logs").removeAttr "style"
205463
this_room_id=null socket_ids=[] my_job=null timerid=null # setTimeout remain_time=null this_rule=null # 规则オブジェクトがある enter_result=null #enter this_icons={} #名字と头像の対応表 this_logdata={} # ログ数据をアレする this_style=null #style要素(終わったら消したい) exports.start=(roomid)-> this_rule=null timerid=null remain_time=null my_job=null this_room_id=null # 职业名一览 cjobs=Shared.game.jobs.filter (x)->x!="Human" # 村人は自動で决定する # CSS操作 this_style=document.createElement "style" document.head.appendChild this_style sheet=this_style.sheet #现在の规则 myrules= player:null # プレイヤー・ネーム day:"all" # 表示する日にち setcss=-> while sheet.cssRules.length>0 sheet.deleteRule 0 if myrules.player? sheet.insertRule "#logs > div:not([data-name=\"#{myrules.player}\"]) {opacity: .5}",0 day=null if myrules.day=="today" day=this_logdata.day # 现在 else if myrules.day!="all" day=parseInt myrules.day # 表示したい日 if day? # 表示する sheet.insertRule "#logs > div:not([data-day=\"#{day}\"]){display: none}",0 getenter=(result)-> if result.error? # 错误 Index.util.message "房间",result.error return else if result.require? if result.require=="password" #密码入力 Index.util.prompt "房间","房间已加密,请输入密码",{type:"password"},(pass)-> unless pass? Index.app.showUrl "/rooms" return ss.rpc "game.rooms.enter", roomid,pass,getenter sessionStorage.roompassword = pass return enter_result=result this_room_id=roomid ss.rpc "game.rooms.oneRoom", roomid,initroom ss.rpc "game.rooms.enter", roomid,sessionStorage.roompassword ? null,getenter initroom=(room)-> unless room? Index.util.message "房间","这个房间不存在。" Index.app.showUrl "/rooms" return # 表单を修正する forminfo=-> setplayersnumber room,$("#gamestart").get(0), room.players.filter((x)->x.mode=="player").length # 今までのログを送ってもらう this_icons={} this_logdata={} this_openjob_flag=false # 职业情報をもらった getjobinfo=(obj)-> console.log obj,this_room_id return unless obj.id==this_room_id my_job=obj.type $("#jobinfo").empty() pp=(text)-> p=document.createElement "p" p.textContent=text p if obj.type infop=$ "<p>你的身份是<b>#{obj.jobname}</b>(</p>" if obj.desc # 职业説明 for o,i in obj.desc if i>0 infop.append "・" a=$ "<a href='/manual/job/#{o.type}'>#{if obj.desc.length==1 then '详细' else "#{o.name}的详细"}</a>" infop.append a infop.append ")" $("#jobinfo").append infop if obj.myteam? # ケミカル人狼用の陣営情報 if obj.myteam == "" $("#jobinfo").append pp "你没有初始阵营" else teamstring = Shared.game.jobinfo[obj.myteam]?.name $("#jobinfo").append pp "你的初始阵营是 #{teamstring}" if obj.wolves? $("#jobinfo").append pp "同伴的人狼是 #{obj.wolves.map((x)->x.name).join(",")}" if obj.peers? $("#jobinfo").append pp "共有者是 #{obj.peers.map((x)->x.name).join(',')}" if obj.foxes? $("#jobinfo").append pp "同伴的妖狐是 #{obj.foxes.map((x)->x.name).join(',')}" if obj.nobles? $("#jobinfo").append pp "贵族是 #{obj.nobles.map((x)->x.name).join(',')}" if obj.queens?.length>0 $("#jobinfo").append pp "女王观战者是 #{obj.queens.map((x)->x.name).join(',')}" if obj.spy2s?.length>0 $("#jobinfo").append pp "间谍Ⅱ是 #{obj.spy2s.map((x)->x.name).join(',')}" if obj.friends?.length>0 $("#jobinfo").append pp "恋人是 #{obj.friends.map((x)->x.name).join(',')}" if obj.stalking? $("#jobinfo").append pp "你是 #{obj.stalking.name}的跟踪狂" if obj.cultmembers? $("#jobinfo").append pp "信者是 #{obj.cultmembers.map((x)->x.name).join(',')}" if obj.vampires? $("#jobinfo").append pp "吸血鬼是 #{obj.vampires.map((x)->x.name).join(',')}" if obj.supporting? $("#jobinfo").append pp "向 #{obj.supporting.name}(#{obj.supportingJob}) 提供帮助" if obj.dogOwner? $("#jobinfo").append pp "你的饲主是 #{obj.dogOwner.name}" if obj.quantumwerewolf_number? $("#jobinfo").append pp "你的玩家编号是第 #{obj.quantumwerewolf_number} 号" if obj.winner? # 勝敗 $("#jobinfo").append pp "你#{if obj.winner then '胜利' else '败北'}了" if obj.dead # 自己は既に死んでいる document.body.classList.add "heaven" else document.body.classList.remove "heaven" if obj.will $("#willform").get(0).elements["will"].value=obj.will if game=obj.game if game.finished # 终了 document.body.classList.add "finished" document.body.classList.remove x for x in ["day","night"] if $(".sticky").length $(".sticky").removeAttr "style" $(".sticky").removeAttr "class" $("#logs").removeAttr "style" $("#jobform").attr "hidden","hidden" if timerid clearInterval timerid timerid=null else # 昼と夜の色 document.body.classList.add (if game.night then "night" else "day") document.body.classList.remove (if game.night then "day" else "night") if $("#sticky").hasClass("sticky") $("#sticky").css "background-color": $("body").css("background-color") unless $("#jobform").get(0).hidden= game.finished || obj.sleeping || !obj.type # 代入しつつの 投票表单必要な場合 $("#jobform div.jobformarea").attr "hidden","hidden" #$("#form_day").get(0).hidden= game.night || obj.sleeping || obj.type=="GameMaster" $("#form_day").get(0).hidden= !obj.voteopen obj.open?.forEach (x)-> # 開けるべき表单が指定されている $("#form_#{x}").prop "hidden",false if (obj.job_selection ? []).length==0 # 対象选择がない・・・表示しない $("#form_players").prop "hidden",true else $("#form_players").prop "hidden",false if game.players formplayers game.players unless this_rule? $("#speakform").get(0).elements["rulebutton"].disabled=false $("#speakform").get(0).elements["norevivebutton"].disabled=false this_rule= jobscount:game.jobscount rule:game.rule setJobSelection obj.job_selection ? [] select=$("#speakform").get(0).elements["mode"] if obj.speak && obj.speak.length>0 # 发言方法の选择 $(select).empty() select.disabled=false for val in obj.speak option=document.createElement "option" option.value=val option.text=speakValueToStr game,val select.add option select.value=obj.speak[0] select.options[0]?.selected=true else select.disabled=true if obj.openjob_flag==true && this_openjob_flag==false # 状況がかわったのでリフレッシュすべき this_openjob_flag=true unless obj.logs? # ログをもらってない場合はもらいたい ss.rpc "game.game.getlog",roomid,sentlog sentlog=(result)-> if result.error? Index.util.message "错误",result.error else if result.game?.day>=1 # 游戏が始まったら消す $("#playersinfo").empty() #TODO: 加入游戏ボタンが2箇所にあるぞ if result.game if !result.game.finished && result.game.rule.jobrule=="特殊规则.Endless黑暗火锅" && !result.type? # Endless黑暗火锅に参加可能 b=makebutton "加入游戏" $("#playersinfo").append b $(b).click joinbutton getjobinfo result $("#logs").empty() $("#chooseviewday").empty() # 何日目だけ表示 if result.game?.finished # 终了した・・・次の游戏ボタン b=makebutton "以相同设定建立新房间","新房间建成后仍可以变更设定。" $("#playersinfo").append b $(b).click (je)-> # 规则を保存 localStorage.savedRule=JSON.stringify result.game.rule localStorage.savedJobs=JSON.stringify result.game.jobscount #Index.app.showUrl "/newroom" # 新しいタブで開く a=document.createElement "a" a.href="/newroom" a.target="_blank" a.click() result.logs.forEach getlog gettimer parseInt(result.timer),result.timer_mode if result.timer? ss.rpc "game.game.getlog", roomid,sentlog # 新しい游戏 newgamebutton = (je)-> unless $("#gamestartsec").attr("hidden") == "hidden" return form=$("#gamestart").get 0 # 规则设定保存を参照する # 规则画面を構築するぞーーー(idx: グループのアレ) buildrules=(arr,parent)-> p=null for obj,idx in arr if obj.rules # グループだ if p && !p.get(0).hasChildNodes() # 空のpは要らない p.remove() fieldset=$ "<fieldset>" pn=parent.attr("name") || "" fieldset.attr "name","#{pn}.#{idx}" if obj.label fieldset.append $ "<legend>#{obj.label}</legend>" buildrules obj.rules,fieldset parent.append fieldset p=null else # ひとつの设定だ if obj.type=="separator" # pの区切り p=$ "<p>" p.appendTo parent continue unless p? p=$ "<p>" p.appendTo parent label=$ "<label>" if obj.title label.attr "title",obj.title unless obj.backlabel if obj.type!="hidden" label.text obj.label switch obj.type when "checkbox" input=$ "<input>" input.attr "type","checkbox" input.attr "name",obj.name input.attr "value",obj.value.value input.prop "checked",!!obj.value.checked label.append input when "select" select=$ "<select>" select.attr "name",obj.name slv=null for o in obj.values op=$ "<option>" op.text o.label if o.title op.attr "title",o.title op.attr "value",o.value select.append op if o.selected slv=o.value if slv? select.get(0).value=slv label.append select when "time" input=$ "<input>" input.attr "type","number" input.attr "name",obj.name.minute input.attr "min","0" input.attr "step","1" input.attr "size","5" input.attr "value",String obj.defaultValue.minute label.append input label.append document.createTextNode "分" input.change ()-> if(Number($(this).val()) < 0) $(this).val(0) input=$ "<input>" input.attr "type","number" input.attr "name",obj.name.second input.attr "min","-15" input.attr "max","60" input.attr "step","15" input.attr "size","5" input.attr "value",String obj.defaultValue.second label.append input label.append document.createTextNode "秒" input.change ()-> if(Number($(this).val()) >= 60) $(this).val(0) $(this).prev().val(Number($(this).prev().val())+1) $(this).prev().change() else if(Number($(this).val()) < 0) $(this).val(45) $(this).prev().val(Number($(this).prev().val())-1) $(this).prev().change() when "hidden" input=$ "<input>" input.attr "type","hidden" input.attr "name",obj.name input.attr "value",obj.value.value label.append input when "second" input=$ "<input>" input.attr "type","number" input.attr "name",obj.name input.attr "min","0" input.attr "step","1" input.attr "size","5" input.attr "value",obj.defaultValue.value label.append input if obj.backlabel if obj.type!="hidden" label.append document.createTextNode obj.label p.append label $("#rules").attr "name","rule" buildrules Shared.game.rules,$("#rules") if localStorage.savedRule rule=JSON.parse localStorage.savedRule jobs=JSON.parse localStorage.savedJobs delete localStorage.savedRule delete localStorage.savedJobs # 时间设定 daysec=rule.day-0 nightsec=rule.night-0 remainsec=rule.remain-0 form.elements["day_minute"].value=parseInt daysec/60 form.elements["day_second"].value=daysec%60 form.elements["night_minute"].value=parseInt nightsec/60 form.elements["night_second"].value=nightsec%60 form.elements["remain_minute"].value=parseInt remainsec/60 form.elements["remain_second"].value=remainsec%60 # 其他 delete rule.number # 人数は違うかも for key of rule e=form.elements[key] if e? if e.type=="checkbox" e.checked = e.value==rule[key] else e.value=rule[key] # 配置も再現 for job in Shared.game.jobs e=form.elements[job] # 职业 if e? e.value=jobs[job]?.number ? 0 $("#gamestartsec").removeAttr "hidden" forminfo() $("#roomname").text room.name if room.mode=="waiting" # 開始前のユーザー一覧は roomから取得する console.log room.players room.players.forEach (x)-> li=makeplayerbox x,room.blind $("#players").append li # 未参加の場合は参加ボタン joinbutton=(je)-> # 参加 opt= name:"" icon:null into=-> ss.rpc "game.rooms.join", roomid,opt,(result)-> if result?.require=="login" # ログインが必要 Index.util.loginWindow -> if Index.app.userid() into() else if result?.error? Index.util.message "房间",result.error else if result?.tip? Index.util.message result.title,result.tip # 如果房间有特殊提示 Index.app.refresh() else Index.app.refresh() if room.blind && !room.theme # 参加者名 ### Index.util.prompt "加入游戏","请输入昵称",null,(name)-> if name opt.name=name into() ### # ここ書いてないよ! Index.util.blindName null,(obj)-> if obj? opt.name=obj.name opt.icon=obj.icon into() else into() if (room.mode=="waiting" || room.mode=="playing" && room.jobrule=="特殊规则.Endless黑暗火锅") && !enter_result?.joined # 未参加 b=makebutton "加入游戏" $("#playersinfo").append b $(b).click joinbutton else if room.mode=="waiting" && enter_result?.joined # Endless黑暗火锅でも脱退はできない b=makebutton "退出游戏" $("#playersinfo").append b $(b).click (je)-> # 脱退 ss.rpc "game.rooms.unjoin", roomid,(result)-> if result? Index.util.message "房间",result else Index.app.refresh() if room.mode=="waiting" # 开始前 b=makebutton "准备/取消准备","全员准备好后即可开始游戏。" $("#playersinfo").append b $(b).click (je)-> ss.rpc "game.rooms.ready", roomid,(result)-> if result? Index.util.message "房间",result b=makebutton "帮手","成为他人的帮手后,将不会直接参与游戏,而是向帮助的对象提供建议。" # 帮手になる/やめるボタン $(b).click (je)-> Index.util.selectprompt "帮手","想要成为谁的帮手?",room.players.map((x)->{name:x.name,value:x.userid}),(id)-> ss.rpc "game.rooms.helper",roomid, id,(result)-> if result? Index.util.message "错误",result $("#playersinfo").append b userid=Index.app.userid() if room.mode=="waiting" if room.owner.userid==Index.app.userid() # 自己 b=makebutton "展开游戏开始界面" $("#playersinfo").append b $(b).click newgamebutton b=makebutton "将参加者踢出游戏" $("#playersinfo").append b $(b).click (je)-> Index.util.selectprompt "踢出","请选择要被踢出的人",room.players.map((x)->{name:x.name,value:x.userid}),(id)-> if id ss.rpc "game.rooms.kick", roomid,id,(result)-> if result? Index.util.message "错误",result b=makebutton "重置[ready]状态" $("#playersinfo").append b $(b).click (je)-> Index.util.ask "重置[ready]状态","要解除全员的[ready]状态吗?",(cb)-> if cb ss.rpc "game.rooms.unreadyall",roomid,(result)-> if result? Index.util.message "错误",result # 役職入力フォームを作る (()=> # job -> cat と job -> team を作る catTable = {} teamTable = {} dds = {} for category,members of Shared.game.categories # HTML dt = document.createElement "dt" dt.textContent = Shared.game.categoryNames[category] dt.classList.add "jobs-cat" dd = dds[category] = document.createElement "dd" dd.classList.add "jobs-cat" $("#jobsfield").append(dt).append(dd) # table for job in members catTable[job] = category dt = document.createElement "dt" dt.classList.add "jobs-cat" dt.textContent = "其他" dd = dds["*"] = document.createElement "dd" dd.classList.add "jobs-cat" # その他は今の所ない # $("#jobsfield").append(dt).append(dd) # table for team,members of Shared.game.teams for job in members teamTable[job] = team for job in Shared.game.jobs # 探す dd = $(dds[catTable[job] ? "*"]) team = teamTable[job] continue unless team? ji = Shared.game.jobinfo[team][job] div = document.createElement "div" div.classList.add "jobs-job" div.dataset.job = job b = document.createElement "b" span = document.createElement "span" span.textContent = ji.name b.appendChild span b.insertAdjacentHTML "beforeend", "<a class='jobs-job-help' href='/manual/job/#{job}'><i class='fa fa-question-circle-o'></i></a>" span = document.createElement "span" span.classList.add "jobs-job-controls" if job == "Human" # 村人は違う処理 output = document.createElement "output" output.name = job output.dataset.jobname = ji.name output.classList.add "jobs-job-controls-number" span.appendChild output check = document.createElement "input" check.type = "hidden" check.name = "job_use_#{job}" check.value = "on" span.appendChild check else # 使用チェック check = document.createElement "input" check.type = "checkbox" check.checked = true check.name = "job_use_#{job}" check.value = "on" check.classList.add "jobs-job-controls-check" check.title = "如果取消复选框,在手调黑暗火锅里 #{ji.name} 将不会出现。" span.appendChild check # 人数 input = document.createElement "input" input.type = "number" input.min = 0 input.step = 1 input.value = 0 input.name = job input.dataset.jobname = ji.name input.classList.add "jobs-job-controls-number" # plus / minus button button1 = document.createElement "button" button1.type = "button" button1.classList.add "jobs-job-controls-button" ic1 = document.createElement "i" ic1.classList.add "fa" ic1.classList.add "fa-plus-square" button1.appendChild ic1 button1.addEventListener 'click', ((job)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements[job] v = parseInt(num.value) num.value = String(v + 1) jobsformvalidate room, form )(job) button2 = document.createElement "button" button2.type = "button" button2.classList.add "jobs-job-controls-button" ic2 = document.createElement "i" ic2.classList.add "fa" ic2.classList.add "fa-minus-square" button2.appendChild ic2 button2.addEventListener 'click', ((job)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements[job] v = parseInt(num.value) if v > 0 num.value = String(v - 1) jobsformvalidate room, form )(job) span.appendChild input span.appendChild button1 span.appendChild button2 div.appendChild b div.appendChild span dd.append div # カテゴリ別のも用意しておく dt = document.createElement "dt" dt.classList.add "jobs-cat" dt.textContent = "手调黑暗火锅用" dd = document.createElement "dd" dd.classList.add "jobs-cat" for type,name of Shared.game.categoryNames div = document.createElement "div" div.classList.add "jobs-job" div.dataset.job = "category_#{type}" b = document.createElement "b" span = document.createElement "span" span.textContent = name b.appendChild span span = document.createElement "span" span.classList.add "jobs-job-controls" input = document.createElement "input" input.type = "number" input.min = 0 input.step = 1 input.value = 0 input.name = "category_#{type}" input.dataset.jobname = name input.classList.add "jobs-job-controls-number" # plus / minus button button1 = document.createElement "button" button1.type = "button" button1.classList.add "jobs-job-controls-button" ic1 = document.createElement "i" ic1.classList.add "fa" ic1.classList.add "fa-plus-square" button1.appendChild ic1 button1.addEventListener 'click', ((type)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements["category_#{type}"] v = parseInt(num.value) num.value = String(v + 1) jobsformvalidate room, form )(type) button2 = document.createElement "button" button2.type = "button" button2.classList.add "jobs-job-controls-button" ic2 = document.createElement "i" ic2.classList.add "fa" ic2.classList.add "fa-minus-square" button2.appendChild ic2 button2.addEventListener 'click', ((type)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements["category_#{type}"] v = parseInt(num.value) if v > 0 num.value = String(v - 1) jobsformvalidate room, form )(type) span.appendChild input span.appendChild button1 span.appendChild button2 div.appendChild b div.appendChild span dd.appendChild div $("#catesfield").append(dt).append(dd) )() if room.owner.userid==Index.app.userid() || room.old b=makebutton "废弃这个房间" $("#playersinfo").append b $(b).click (je)-> Index.util.ask "废弃房间","确定要废弃这个房间吗?",(cb)-> if cb ss.rpc "game.rooms.del", roomid,(result)-> if result? Index.util.message "错误",result form=$("#gamestart").get 0 # ゲーム開始フォームが何か変更されたら呼ばれる関数 jobsforminput=(e)-> t=e.target form=t.form pl=room.players.filter((x)->x.mode=="player").length if t.name=="jobrule" || t.name=="chemical" # ルール変更があった resetplayersinput room, form setplayersbyjobrule room,form,pl jobsformvalidate room,form form.addEventListener "input",jobsforminput,false form.addEventListener "change",jobsforminput,false $("#gamestart").submit (je)-> # いよいよ游戏开始だ! je.preventDefault() query=Index.util.formQuery je.target jobrule=query.jobrule ruleobj=Shared.game.getruleobj(jobrule) ? {} # ステップ2: 时间チェック step2=-> # 夜时间をチェック minNight = ruleobj.suggestedNight?.min ? -Infinity maxNight = ruleobj.suggestedNight?.max ? Infinity night = parseInt(query.night_minute)*60+parseInt(query.night_second) #console.log ruleobj,night,minNight,maxNight if night<minNight || maxNight<night # 範囲オーバー Index.util.ask "选项","这个配置推荐的夜间时间在#{if isFinite(minNight) then minNight+'秒以上' else ''}#{if isFinite(maxNight) then maxNight+'秒以下' else ''},确认要开始游戏吗?",(res)-> if res #OKだってよ... starting() else starting() # じっさいに开始 starting=-> ss.rpc "game.game.gameStart", roomid,query,(result)-> if result? Index.util.message "房间",result else $("#gamestartsec").attr "hidden","hidden" # 相違がないか探す diff=null for key,value of (ruleobj.suggestedOption ? {}) if query[key]!=value diff= key:key value:value break if diff? control=je.target.elements[diff.key] if control? sugval=null if control.type=="select-one" for opt in control.options if opt.value==diff.value sugval=opt.text break if sugval? Index.util.ask "选项","这个配置下推荐选项「#{control.dataset.name}」 「#{sugval}」。可以这样开始游戏吗?",(res)-> if res # OKだってよ... step2() return # とくに何もない step2() speakform=$("#speakform").get 0 $("#speakform").submit (je)-> form=je.target ss.rpc "game.game.speak", roomid,Index.util.formQuery(form),(result)-> if result? Index.util.message "错误",result je.preventDefault() form.elements["comment"].value="" if form.elements["multilinecheck"].checked # 複数行は直す form.elements["multilinecheck"].click() speakform.elements["willbutton"].addEventListener "click", (e)-> # 遗言表单オープン wf=$("#willform").get 0 if wf.hidden wf.hidden=false e.target.value="折叠遗言" else wf.hidden=true e.target.value="遗言" ,false speakform.elements["multilinecheck"].addEventListener "click",(e)-> # 複数行 t=e.target textarea=null comment=t.form.elements["comment"] if t.checked # これから複数行になる textarea=document.createElement "textarea" textarea.cols=50 textarea.rows=4 else # 複数行をやめる textarea=document.createElement "input" textarea.size=50 textarea.name="comment" textarea.value=comment.value if textarea.type=="textarea" && textarea.value textarea.value+="\n" textarea.required=true $(comment).replaceWith textarea textarea.focus() textarea.setSelectionRange textarea.value.length,textarea.value.length # 複数行ショートカット $(speakform).keydown (je)-> if je.keyCode==13 && je.shiftKey && je.target.form.elements["multilinecheck"].checked==false # 複数行にする je.target.form.elements["multilinecheck"].click() je.preventDefault() # 规则表示 $("#speakform").get(0).elements["rulebutton"].addEventListener "click", (e)-> return unless this_rule? win=Index.util.blankWindow() win.append $ "<h1>规则</h1>" p=document.createElement "p" Object.keys(this_rule.jobscount).forEach (x)-> a=document.createElement "a" a.href="/manual/job/#{x}" a.textContent="#{this_rule.jobscount[x].name}#{this_rule.jobscount[x].number}" p.appendChild a p.appendChild document.createTextNode " " win.append p chkrule=(ruleobj,jobscount,rules)-> for obj in rules if obj.rules continue unless obj.visible ruleobj,jobscount chkrule ruleobj,jobscount,obj.rules else p=$ "<p>" val="" if obj.title? p.attr "title",obj.title if obj.type=="separator" continue if obj.getstr? valobj=obj.getstr ruleobj[obj.name] unless valobj? continue val="#{valobj.label ? ''}:#{valobj.value ? ''}" else val="#{obj.label}:" switch obj.type when "checkbox" if ruleobj[obj.name]==obj.value.value unless obj.value.label? continue val+=obj.value.label else unless obj.value.nolabel? continue val+=obj.value.nolabel when "select" flg=false for vobj in obj.values if ruleobj[obj.name]==vobj.value val+=vobj.label if vobj.title p.attr "title",vobj.title flg=true break unless flg continue when "time" val+="#{ruleobj[obj.name.minute]}分#{ruleobj[obj.name.second]}秒" when "second" val+="#{ruleobj[obj.name]}秒" when "hidden" continue p.text val win.append p chkrule this_rule.rule, this_rule.jobscount,Shared.game.rules $("#willform").submit (je)-> form=je.target je.preventDefault() ss.rpc "game.game.will", roomid,form.elements["will"].value,(result)-> if result? Index.util.message "错误",result else $("#willform").get(0).hidden=true $("#speakform").get(0).elements["willbutton"].value="遗言" # 夜の仕事(あと投票) $("#jobform").submit (je)-> form=je.target je.preventDefault() $("#jobform").attr "hidden","hidden" ss.rpc "game.game.job", roomid,Index.util.formQuery(form), (result)-> if result?.error? Index.util.message "错误",result.error $("#jobform").removeAttr "hidden" else if !result?.sleeping # まだ仕事がある $("#jobform").removeAttr "hidden" getjobinfo result else getjobinfo result .click (je)-> bt=je.target if bt.type=="submit" # 送信ボタン bt.form.elements["commandname"].value=bt.name # コマンド名教えてあげる bt.form.elements["jobtype"].value=bt.dataset.job # 职业名も教えてあげる # 拒绝复活ボタン $("#speakform").get(0).elements["norevivebutton"].addEventListener "click",(e)-> Index.util.ask "拒绝复活","一旦拒绝复活将不能撤销。确定要这样做吗?",(result)-> if result ss.rpc "game.game.norevive", roomid, (result)-> if result? # 错误 Index.util.message "错误",result else Index.util.message "拒绝复活","成功拒绝复活。" ,false #======================================== # 誰かが参加した!!!! socket_ids.push Index.socket.on "join","room#{roomid}",(msg,channel)-> room.players.push msg ### li=document.createElement "li" li.title=msg.userid if room.blind li.textContent=msg.name else a=document.createElement "a" a.href="/user/#{msg.userid}" a.textContent=msg.name li.appendChild a ### li=makeplayerbox msg,room.blind $("#players").append li forminfo() # 誰かが出て行った!!! socket_ids.push Index.socket.on "unjoin","room#{roomid}",(msg,channel)-> room.players=room.players.filter (x)->x.userid!=msg $("#players li").filter((idx)-> this.dataset.id==msg).remove() forminfo() # kickされた socket_ids.push Index.socket.on "kicked",null,(msg,channel)-> if msg.id==roomid Index.app.refresh() # 準備 socket_ids.push Index.socket.on "ready","room#{roomid}",(msg,channel)-> for pl in room.players if pl.userid==msg.userid pl.start=msg.start li=$("#players li").filter((idx)-> this.dataset.id==msg.userid) li.replaceWith makeplayerbox pl,room.blind socket_ids.push Index.socket.on "unreadyall","room#{roomid}",(msg,channel)-> for pl in room.players if pl.start pl.start=false li=$("#players li").filter((idx)-> this.dataset.id==pl.userid) li.replaceWith makeplayerbox pl,room.blind socket_ids.push Index.socket.on "mode","room#{roomid}",(msg,channel)-> for pl in room.players if pl.userid==msg.userid pl.mode=msg.mode li=$("#players li").filter((idx)-> this.dataset.id==msg.userid) li.replaceWith makeplayerbox pl,room.blind forminfo() # ログが流れてきた!!! socket_ids.push Index.socket.on "log",null,(msg,channel)-> #if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() if msg.roomid==roomid # この部屋へのログ getlog msg # 職情報を教えてもらった!!! socket_ids.push Index.socket.on "getjob",null,(msg,channel)-> if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() getjobinfo msg # 更新したほうがいい socket_ids.push Index.socket.on "refresh",null,(msg,channel)-> if msg.id==roomid #Index.app.refresh() ss.rpc "game.rooms.enter", roomid,sessionStorage.roompassword ? null,(result)-> ss.rpc "game.game.getlog", roomid,sentlog ss.rpc "game.rooms.oneRoom", roomid,(r)->room=r # 投票表单オープン socket_ids.push Index.socket.on "voteform",null,(msg,channel)-> if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() if msg $("#jobform").removeAttr "hidden" else $("#jobform").attr "hidden","hidden" # 残り时间 socket_ids.push Index.socket.on "time",null,(msg,channel)-> if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() gettimer parseInt(msg.time),msg.mode # 向房间成员通报猝死统计 socket_ids.push Index.socket.on 'punishalert',null,(msg,channel)-> if msg.id==roomid Index.util.punish "猝死惩罚",msg,(result)-> # console.log "猝死名单" # console.log result ss.rpc "game.rooms.suddenDeathPunish", roomid,result,(result)-> if result? if result.error? # 错误 Index.util.message "猝死惩罚",result.error return Index.util.message "猝死惩罚",result return # 向房间成员通报猝死统计 socket_ids.push Index.socket.on 'punishresult',null,(msg,channel)-> if msg.id==roomid # Index.util.message "猝死惩罚",msg.name+"由于猝死被禁止游戏" console.log "room:",msg.id,msg $(document).click (je)-> # クリックで发言強調 li=if je.target.tagName.toLowerCase()=="li" then je.target else $(je.target).parents("li").get 0 myrules.player=null if $(li).parent("#players").length >0 if li? # 強調 myrules.player=li.dataset.name setcss() $("#chooseviewselect").change (je)-> # 表示部分を选择 v=je.target.value myrules.day=v setcss() .click (je)-> je.stopPropagation() # 配役タイプ setjobrule=(rulearr,names,parent)-> for obj in rulearr # name,title, ruleをもつ if obj.rule instanceof Array # さらに子 optgroup=document.createElement "optgroup" optgroup.label=obj.name parent.appendChild optgroup setjobrule obj.rule,names.concat([obj.name]),optgroup else # option option=document.createElement "option" option.textContent=obj.name option.value=names.concat([obj.name]).join "." option.title=obj.title parent.appendChild option setjobrule Shared.game.jobrules.concat([ name:"特殊规则" rule:[ { name:"自由配置" title:"可以自由的选择角色。" rule:null } { name:"黑暗火锅" title:"各角色人数将随机分配。" rule:null } { name:"手调黑暗火锅" title:"一部分角色由房主分配,其他角色随机分配。" rule:null } { name:"<NAME>子人<NAME>" title:"全员的职业将由概率表表示。只限村人・人狼・占卜师。" rule:null suggestedNight:{ max:60 } } { name:"Endless黑暗火锅" title:"可以途中参加・死亡后立刻转生黑暗火锅。" rule:null suggestedOption:{ heavenview:"" } } ] ]),[],$("#jobruleselect").get 0 setplayersnumber=(room,form,number)-> form.elements["number"].value=number unless $("#gamestartsec").attr("hidden") == "hidden" setplayersbyjobrule room,form,number jobsformvalidate room,form # 配置一览をアレする setplayersbyjobrule=(room,form,number)-> jobrulename=form.elements["jobrule"].value if form.elements["scapegoat"]?.value=="on" number++ # 身代わりくん if jobrulename in ["特殊规则.自由配置","特殊规则.手调黑暗火锅"] j = $("#jobsfield").get 0 j.hidden=false j.dataset.checkboxes = (if jobrulename!="特殊规则.手调黑暗火锅" then "no" else "") $("#catesfield").get(0).hidden= jobrulename!="特殊规则.手调黑暗火锅" #$("#yaminabe_opt_nums").get(0).hidden=true else if jobrulename in ["特殊规则.黑暗火锅","特殊规则.Endless黑暗火锅"] $("#jobsfield").get(0).hidden=true $("#catesfield").get(0).hidden=true #$("#yaminabe_opt_nums").get(0).hidden=false else $("#jobsfield").get(0).hidden=true $("#catesfield").get(0).hidden=true if jobrulename=="特殊规则.量子人狼" jobrulename="内部利用.量子人狼" obj= Shared.game.getrulefunc jobrulename if obj? form.elements["number"].value=number for x in Shared.game.jobs form.elements[x].value=0 jobs=obj number count=0 #村人以外 for job,num of jobs form.elements[job]?.value=num count+=num # カテゴリ別 for type of Shared.game.categoryNames count+= parseInt(form.elements["category_#{type}"].value ? 0) # 残りが村人の人数 if form.elements["chemical"]?.checked # chemical人狼では村人を足す form.elements["Human"].value = number*2 - count else form.elements["Human"].value = number-count setjobsmonitor form,number jobsformvalidate=(room,form)-> # 村人の人数を調節する pl=room.players.filter((x)->x.mode=="player").length if form.elements["scapegoat"].value=="on" # 替身君 pl++ sum=0 cjobs.forEach (x)-> chk = form.elements["job_use_#{x}"].checked if chk sum+=Number form.elements[x].value else form.elements[x].value = 0 # カテゴリ別 for type of Shared.game.categoryNames sum+= parseInt(form.elements["category_#{type}"].value ? 0) if form.elements["chemical"].checked form.elements["Human"].value=pl*2-sum else form.elements["Human"].value=pl-sum form.elements["number"].value=pl setplayersinput room, form setjobsmonitor form,pl # 规则の表示具合をチェックする checkrule=(form,ruleobj,rules,fsetname)-> for obj,idx in rules continue unless obj.rules fsetname2="#{fsetname}.#{idx}" form.elements[fsetname2].hidden=!(obj.visible ruleobj,ruleobj) checkrule form,ruleobj,obj.rules,fsetname2 # ルールが変更されたときはチェックを元に戻す resetplayersinput=(room, form)-> rule = form.elements["jobrule"].value if rule != "特殊规则.手调黑暗火锅" checks = form.querySelectorAll 'input.jobs-job-controls-check[name^="job_use_"]' for check in checks check.checked = true # フォームに応じてプレイヤーの人数inputの表示を調整 setplayersinput=(room, form)-> divs = document.querySelectorAll "div.jobs-job" for div in divs job = div.dataset.job if job? e = form.elements[job] chk = form.elements["job_use_#{job}"] if e? v = Number e.value if chk? && chk.type=="checkbox" && !chk.checked # 無効化されている div.classList.remove "jobs-job-active" div.classList.add "jobs-job-inactive" div.classList.remove "jobs-job-error" else if v > 0 div.classList.add "jobs-job-active" div.classList.remove "jobs-job-inactive" div.classList.remove "jobs-job-error" else if v < 0 div.classList.remove "jobs-job-active" div.classList.remove "jobs-job-inactive" div.classList.add "jobs-job-error" else div.classList.remove "jobs-job-active" div.classList.remove "jobs-job-inactive" div.classList.remove "jobs-job-error" # 配置をテキストで書いてあげる setjobsmonitor=(form,number)-> text="" rule=Index.util.formQuery form jobrule=rule.jobrule if jobrule=="特殊规则.黑暗火锅" # 黑暗火锅の場合 $("#jobsmonitor").text "黑暗火锅" else if jobrule=="特殊规则.Endless黑暗火锅" $("#jobsmonitor").text "Endless黑暗火锅" else ruleobj=Shared.game.getruleobj jobrule if ruleobj?.minNumber>number $("#jobsmonitor").text "(这个配置最少需要#{ruleobj.minNumber}个人)" else $("#jobsmonitor").text Shared.game.getrulestr jobrule,rule ### jobprops=$("#jobprops") jobprops.children(".prop").prop "hidden",true for job in Shared.game.jobs jobpr=jobprops.children(".prop.#{job}") if jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅"] || form.elements[job].value>0 jobpr.prop "hidden",false # 规则による设定 ruleprops=$("#ruleprops") ruleprops.children(".prop").prop "hidden",true switch jobrule when "特殊规则.量子人狼" ruleprops.children(".prop.rule-quantum").prop "hidden",false # あと替身君はOFFにしたい form.elements["scapegoat"].value="off" ### if jobrule=="特殊规则.量子人狼" # あと替身君はOFFにしたい form.elements["scapegoat"].value="off" rule.scapegoat="off" checkrule form,rule,Shared.game.rules,$("#rules").attr("name") #ログをもらった getlog=(log)-> if log.mode in ["voteresult","probability_table"] # 表を出す p=document.createElement "div" div=document.createElement "div" div.classList.add "icon" p.appendChild div div=document.createElement "div" div.classList.add "name" p.appendChild div tb=document.createElement "table" if log.mode=="voteresult" tb.createCaption().textContent="投票结果" vr=log.voteresult tos=log.tos vr.forEach (player)-> tr=tb.insertRow(-1) tr.insertCell(-1).textContent=player.name tr.insertCell(-1).textContent="#{tos[player.id] ? '0'}票" tr.insertCell(-1).textContent="→#{vr.filter((x)->x.id==player.voteto)[0]?.name ? ''}" else # %表示整形 pbu=(node,num)-> node.textContent=(if num==1 "100%" else (num*100).toFixed(2)+"%" ) if num==1 node.style.fontWeight="bold" return tb.createCaption().textContent="概率表" pt=log.probability_table # 見出し tr=tb.insertRow -1 th=document.createElement "th" th.textContent="名字" tr.appendChild th th=document.createElement "th" if this_rule?.rule.quantumwerewolf_diviner=="on" th.textContent="村人" else th.textContent="人类" tr.appendChild th if this_rule?.rule.quantumwerewolf_diviner=="on" # 占卜师の確率も表示: th=document.createElement "th" th.textContent="占卜师" tr.appendChild th th=document.createElement "th" th.textContent="人狼" tr.appendChild th if this_rule?.rule.quantumwerewolf_dead!="no" th=document.createElement "th" th.textContent="死亡" tr.appendChild th for id,obj of pt tr=tb.insertRow -1 tr.insertCell(-1).textContent=obj.name pbu tr.insertCell(-1),obj.Human if obj.Diviner? pbu tr.insertCell(-1),obj.Diviner pbu tr.insertCell(-1),obj.Werewolf if this_rule?.rule.quantumwerewolf_dead!="no" pbu tr.insertCell(-1),obj.dead if obj.dead==1 tr.classList.add "deadoff-line" p.appendChild tb else p=document.createElement "div" div=document.createElement "div" div.classList.add "name" icondiv=document.createElement "div" icondiv.classList.add "icon" if log.name? div.textContent=switch log.mode when "monologue", "heavenmonologue" "#{log.name}自言自语:" when "will" "#{log.name}遗言:" else "#{log.name}:" if this_icons[log.name] # 头像がある img=document.createElement "img" img.style.width="1em" img.style.height="1em" img.src=this_icons[log.name] img.alt="" # 飾り icondiv.appendChild img p.appendChild icondiv p.appendChild div p.dataset.name=log.name span=document.createElement "div" span.classList.add "comment" if log.size in ["big","small"] # 大/小发言 span.classList.add log.size wrdv=document.createElement "div" wrdv.textContent=log.comment ? "" # 改行の処理 spp=wrdv.firstChild # Text wr=0 while spp? && (wr=spp.nodeValue.indexOf("\n"))>=0 spp=spp.splitText wr+1 wrdv.insertBefore document.createElement("br"),spp parselognode wrdv span.appendChild wrdv p.appendChild span if log.time? time=Index.util.timeFromDate new Date log.time time.classList.add "time" p.appendChild time if log.mode=="nextturn" && log.day #IDづけ p.id="turn_#{log.day}#{if log.night then '_night' else ''}" this_logdata.day=log.day this_logdata.night=log.night if log.night==false || log.day==1 # 朝の場合optgroupに追加 option=document.createElement "option" option.value=log.day option.textContent="第#{log.day}天" $("#chooseviewday").append option setcss() # 日にち数据 if this_logdata.day p.dataset.day=this_logdata.day if this_logdata.night p.dataset.night="night" else p.dataset.day=0 p.classList.add log.mode logs=$("#logs").get 0 logs.insertBefore p,logs.firstChild # プレイヤーオブジェクトのプロパティを得る ### getprop=(obj,propname)-> if obj[propname]? obj[propname] else if obj.main? getprop obj.main,propname else undefined getname=(obj)->getprop obj,"name" ### formplayers=(players)-> #jobflg: 1:生存の人 2:死人 $("#form_players").empty() $("#players").empty() $("#playernumberinfo").text "生存者#{players.filter((x)->!x.dead).length}人 / 死亡者#{players.filter((x)->x.dead).length}人" players.forEach (x)-> # 上の一览用 li=makeplayerbox x $("#players").append li # 头像 if x.icon this_icons[x.name]=x.icon setJobSelection=(selections)-> $("#form_players").empty() valuemap={} #重複を取り除く for x in selections continue if valuemap[x.value] # 重複チェック # 投票表单用 li=document.createElement "li" #if x.dead # li.classList.add "dead" label=document.createElement "label" label.textContent=x.name input=document.createElement "input" input.type="radio" input.name="target" input.value=x.value #input.disabled=!((x.dead && (jobflg&2))||(!x.dead && (jobflg&1))) label.appendChild input li.appendChild label $("#form_players").append li valuemap[x.value]=true # タイマー情報をもらった gettimer=(msg,mode)-> remain_time=parseInt msg clearInterval timerid if timerid? timerid=setInterval -> remain_time-- return if remain_time<0 min=parseInt remain_time/60 sec=remain_time%60 $("#time").text "#{mode || ''} #{min}:#{sec}" ,1000 makebutton=(text,title="")-> b=document.createElement "button" b.type="button" b.textContent=text b.title=title b exports.end=-> ss.rpc "game.rooms.exit", this_room_id,(result)-> if result? Index.util.message "房间",result return clearInterval timerid if timerid? alloff socket_ids... document.body.classList.remove x for x in ["day","night","finished","heaven"] if this_style? $(this_style).remove() #ソケットを全部off alloff= (ids...)-> ids.forEach (x)-> Index.socket.off x # ノードのコメントなどをパースする exports.parselognode=parselognode=(node)-> if node.nodeType==Node.TEXT_NODE # text node return unless node.parentNode result=document.createDocumentFragment() while v=node.nodeValue if res=v.match /^(.*?)(https?:\/\/)([^\s\/]+)(\/\S*)?/ res[4] ?= "" if res[1] # 前の部分 node=node.splitText res[1].length parselognode node.previousSibling url = res[2]+res[3]+res[4] a=document.createElement "a" a.href=url if res[3]==location.host && (res2=res[4].match /^\/room\/(\d+)$/) a.textContent="##{res2[1]}" else if res[4] in ["","/"] && res[3].length<20 a.textContent="#{res[2]}#{res[3]}/" else if res[3].length+res[4].length<60 a.textContent=res[2]+res[3]+res[4] else if res[3].length<40 a.textContent="#{res[2]}#{res[3]}#{res[4].slice(0,10)}...#{res[4].slice(-10)}" else a.textContent="#{res[2]}#{res[3].slice(0,30)}...#{(res[3]+res[4]).slice(-30)}" a.target="_blank" node=node.splitText url.length node.parentNode.replaceChild a,node.previousSibling continue if res=v.match /^(.*?)#(\d+)/ if res[1] # 前の部分 node=node.splitText res[1].length parselognode node.previousSibling a=document.createElement "a" a.href="/room/#{res[2]}" a.textContent="##{res[2]}" node=node.splitText res[2].length+1 # その部分どける node.parentNode.replaceChild a,node.previousSibling continue node.nodeValue=v.replace /(\w{30})(?=\w)/g,"$1\u200b" break else if node.childNodes for ch in node.childNodes if ch.parentNode== node parselognode ch # #players用要素 makeplayerbox=(obj,blindflg,tagname="li")->#obj:game.playersのアレ #df=document.createDocumentFragment() df=document.createElement tagname df.dataset.id=obj.id ? obj.userid df.dataset.name=obj.name if obj.icon figure=document.createElement "figure" figure.classList.add "icon" div=document.createElement "div" div.classList.add "avatar" img=document.createElement "img" img.src=obj.icon img.width=img.height=48 img.alt=obj.name div.appendChild img figure.appendChild div img2=document.createElement "img" img2.src="/images/dead.png" img2.width=img2.height=48 img2.alt="已死亡" img2.classList.add "dead_mark" figure.appendChild img2 df.appendChild figure df.classList.add "icon" p=document.createElement "p" p.classList.add "name" if obj.realid a=document.createElement "a" a.href="/user/#{obj.realid}" a.textContent=obj.name p.appendChild a else p.textContent=obj.name df.appendChild p if obj.jobname p=document.createElement "p" p.classList.add "job" if obj.originalJobname? ### if obj.originalJobname==obj.jobname || obj.originalJobname.indexOf("→")>=0 p.textContent=obj.originalJobname else p.textContent="#{obj.originalJobname}→#{obj.jobname}" ### p.textContent=obj.originalJobname else p.textContent=obj.jobname if obj.option p.textContent+= "(#{obj.option})" df.appendChild p if obj.winner? p=document.createElement "p" p.classList.add "outcome" if obj.winner p.classList.add "win" p.textContent="胜利" else p.classList.add "lose" p.textContent="败北" df.appendChild p if obj.dead df.classList.add "dead" if !obj.winner? && obj.norevive==true # 拒绝复活 p=document.createElement "p" p.classList.add "job" p.textContent="[不可复活]" df.appendChild p if obj.mode=="gm" # GM p=document.createElement "p" p.classList.add "job" p.classList.add "gm" p.textContent="[GM]" df.appendChild p else if /^helper_/.test obj.mode # 帮手 p=document.createElement "p" p.classList.add "job" p.classList.add "helper" p.textContent="[帮手]" df.appendChild p if obj.start # 準備完了 p=document.createElement "p" p.classList.add "job" p.textContent="[ready]" df.appendChild p df speakValueToStr=(game,value)-> # 发言のモード名を文字列に switch value when "day","prepare" "向全员发言" when "audience" "观战者的会话" when "monologue" "自言自语" when "werewolf" "人狼的会话" when "couple" "共有者的会话" when "fox" "妖狐的会话" when "gm" "致全员" when "gmheaven" "至灵界" when "gmaudience" "致观战者" when "gmmonologue" "自言自语" when "helperwhisper" # 帮手先がいない場合(自己への建议) "建议" else if result=value.match /^gmreply_(.+)$/ pl=game.players.filter((x)->x.id==result[1])[0] "→#{pl.name}" else if result=value.match /^helperwhisper_(.+)$/ "建议" $ -> $(window).resize -> unless $(".sticky").length > 0 return $("#sticky").css "width",$("#logs").css "width" unless $("div#content div.game").length $("#content").removeAttr "style" $("#widescreen").live "click",-> if $("#widescreen").is(':checked') $("#content").css "max-width","95%" else $("#content").removeAttr "style" $(".sticky").css "width": $("#logs").css "width" sticky_top = undefined $(window).scroll -> sticky() $("#isfloat").live "click",-> sticky() sticky = -> unless $("#sticky").length > 0 return unless $("#isfloat").is(':checked') $(".sticky").removeAttr "style" $(".sticky").removeAttr "class" $("#logs").removeAttr "style" return if $("body").hasClass("finished") return winTop = $(window).scrollTop() if winTop >= $("#sticky").offset().top and not $("#sticky").hasClass("sticky") sticky_top = $("#sticky").offset().top $("#logs").css "position": "relative" "top": $("#sticky").height() + "px" "padding-top": "5px" $("#sticky").addClass "sticky" $("#sticky").css "background-color": $("body").css("background-color") "width": $("#logs").css "width" if winTop < sticky_top and $("#sticky").hasClass("sticky") $(".sticky").removeAttr "style" $(".sticky").removeAttr "class" $("#logs").removeAttr "style"
true
this_room_id=null socket_ids=[] my_job=null timerid=null # setTimeout remain_time=null this_rule=null # 规则オブジェクトがある enter_result=null #enter this_icons={} #名字と头像の対応表 this_logdata={} # ログ数据をアレする this_style=null #style要素(終わったら消したい) exports.start=(roomid)-> this_rule=null timerid=null remain_time=null my_job=null this_room_id=null # 职业名一览 cjobs=Shared.game.jobs.filter (x)->x!="Human" # 村人は自動で决定する # CSS操作 this_style=document.createElement "style" document.head.appendChild this_style sheet=this_style.sheet #现在の规则 myrules= player:null # プレイヤー・ネーム day:"all" # 表示する日にち setcss=-> while sheet.cssRules.length>0 sheet.deleteRule 0 if myrules.player? sheet.insertRule "#logs > div:not([data-name=\"#{myrules.player}\"]) {opacity: .5}",0 day=null if myrules.day=="today" day=this_logdata.day # 现在 else if myrules.day!="all" day=parseInt myrules.day # 表示したい日 if day? # 表示する sheet.insertRule "#logs > div:not([data-day=\"#{day}\"]){display: none}",0 getenter=(result)-> if result.error? # 错误 Index.util.message "房间",result.error return else if result.require? if result.require=="password" #密码入力 Index.util.prompt "房间","房间已加密,请输入密码",{type:"password"},(pass)-> unless pass? Index.app.showUrl "/rooms" return ss.rpc "game.rooms.enter", roomid,pass,getenter sessionStorage.roompassword = pass return enter_result=result this_room_id=roomid ss.rpc "game.rooms.oneRoom", roomid,initroom ss.rpc "game.rooms.enter", roomid,sessionStorage.roompassword ? null,getenter initroom=(room)-> unless room? Index.util.message "房间","这个房间不存在。" Index.app.showUrl "/rooms" return # 表单を修正する forminfo=-> setplayersnumber room,$("#gamestart").get(0), room.players.filter((x)->x.mode=="player").length # 今までのログを送ってもらう this_icons={} this_logdata={} this_openjob_flag=false # 职业情報をもらった getjobinfo=(obj)-> console.log obj,this_room_id return unless obj.id==this_room_id my_job=obj.type $("#jobinfo").empty() pp=(text)-> p=document.createElement "p" p.textContent=text p if obj.type infop=$ "<p>你的身份是<b>#{obj.jobname}</b>(</p>" if obj.desc # 职业説明 for o,i in obj.desc if i>0 infop.append "・" a=$ "<a href='/manual/job/#{o.type}'>#{if obj.desc.length==1 then '详细' else "#{o.name}的详细"}</a>" infop.append a infop.append ")" $("#jobinfo").append infop if obj.myteam? # ケミカル人狼用の陣営情報 if obj.myteam == "" $("#jobinfo").append pp "你没有初始阵营" else teamstring = Shared.game.jobinfo[obj.myteam]?.name $("#jobinfo").append pp "你的初始阵营是 #{teamstring}" if obj.wolves? $("#jobinfo").append pp "同伴的人狼是 #{obj.wolves.map((x)->x.name).join(",")}" if obj.peers? $("#jobinfo").append pp "共有者是 #{obj.peers.map((x)->x.name).join(',')}" if obj.foxes? $("#jobinfo").append pp "同伴的妖狐是 #{obj.foxes.map((x)->x.name).join(',')}" if obj.nobles? $("#jobinfo").append pp "贵族是 #{obj.nobles.map((x)->x.name).join(',')}" if obj.queens?.length>0 $("#jobinfo").append pp "女王观战者是 #{obj.queens.map((x)->x.name).join(',')}" if obj.spy2s?.length>0 $("#jobinfo").append pp "间谍Ⅱ是 #{obj.spy2s.map((x)->x.name).join(',')}" if obj.friends?.length>0 $("#jobinfo").append pp "恋人是 #{obj.friends.map((x)->x.name).join(',')}" if obj.stalking? $("#jobinfo").append pp "你是 #{obj.stalking.name}的跟踪狂" if obj.cultmembers? $("#jobinfo").append pp "信者是 #{obj.cultmembers.map((x)->x.name).join(',')}" if obj.vampires? $("#jobinfo").append pp "吸血鬼是 #{obj.vampires.map((x)->x.name).join(',')}" if obj.supporting? $("#jobinfo").append pp "向 #{obj.supporting.name}(#{obj.supportingJob}) 提供帮助" if obj.dogOwner? $("#jobinfo").append pp "你的饲主是 #{obj.dogOwner.name}" if obj.quantumwerewolf_number? $("#jobinfo").append pp "你的玩家编号是第 #{obj.quantumwerewolf_number} 号" if obj.winner? # 勝敗 $("#jobinfo").append pp "你#{if obj.winner then '胜利' else '败北'}了" if obj.dead # 自己は既に死んでいる document.body.classList.add "heaven" else document.body.classList.remove "heaven" if obj.will $("#willform").get(0).elements["will"].value=obj.will if game=obj.game if game.finished # 终了 document.body.classList.add "finished" document.body.classList.remove x for x in ["day","night"] if $(".sticky").length $(".sticky").removeAttr "style" $(".sticky").removeAttr "class" $("#logs").removeAttr "style" $("#jobform").attr "hidden","hidden" if timerid clearInterval timerid timerid=null else # 昼と夜の色 document.body.classList.add (if game.night then "night" else "day") document.body.classList.remove (if game.night then "day" else "night") if $("#sticky").hasClass("sticky") $("#sticky").css "background-color": $("body").css("background-color") unless $("#jobform").get(0).hidden= game.finished || obj.sleeping || !obj.type # 代入しつつの 投票表单必要な場合 $("#jobform div.jobformarea").attr "hidden","hidden" #$("#form_day").get(0).hidden= game.night || obj.sleeping || obj.type=="GameMaster" $("#form_day").get(0).hidden= !obj.voteopen obj.open?.forEach (x)-> # 開けるべき表单が指定されている $("#form_#{x}").prop "hidden",false if (obj.job_selection ? []).length==0 # 対象选择がない・・・表示しない $("#form_players").prop "hidden",true else $("#form_players").prop "hidden",false if game.players formplayers game.players unless this_rule? $("#speakform").get(0).elements["rulebutton"].disabled=false $("#speakform").get(0).elements["norevivebutton"].disabled=false this_rule= jobscount:game.jobscount rule:game.rule setJobSelection obj.job_selection ? [] select=$("#speakform").get(0).elements["mode"] if obj.speak && obj.speak.length>0 # 发言方法の选择 $(select).empty() select.disabled=false for val in obj.speak option=document.createElement "option" option.value=val option.text=speakValueToStr game,val select.add option select.value=obj.speak[0] select.options[0]?.selected=true else select.disabled=true if obj.openjob_flag==true && this_openjob_flag==false # 状況がかわったのでリフレッシュすべき this_openjob_flag=true unless obj.logs? # ログをもらってない場合はもらいたい ss.rpc "game.game.getlog",roomid,sentlog sentlog=(result)-> if result.error? Index.util.message "错误",result.error else if result.game?.day>=1 # 游戏が始まったら消す $("#playersinfo").empty() #TODO: 加入游戏ボタンが2箇所にあるぞ if result.game if !result.game.finished && result.game.rule.jobrule=="特殊规则.Endless黑暗火锅" && !result.type? # Endless黑暗火锅に参加可能 b=makebutton "加入游戏" $("#playersinfo").append b $(b).click joinbutton getjobinfo result $("#logs").empty() $("#chooseviewday").empty() # 何日目だけ表示 if result.game?.finished # 终了した・・・次の游戏ボタン b=makebutton "以相同设定建立新房间","新房间建成后仍可以变更设定。" $("#playersinfo").append b $(b).click (je)-> # 规则を保存 localStorage.savedRule=JSON.stringify result.game.rule localStorage.savedJobs=JSON.stringify result.game.jobscount #Index.app.showUrl "/newroom" # 新しいタブで開く a=document.createElement "a" a.href="/newroom" a.target="_blank" a.click() result.logs.forEach getlog gettimer parseInt(result.timer),result.timer_mode if result.timer? ss.rpc "game.game.getlog", roomid,sentlog # 新しい游戏 newgamebutton = (je)-> unless $("#gamestartsec").attr("hidden") == "hidden" return form=$("#gamestart").get 0 # 规则设定保存を参照する # 规则画面を構築するぞーーー(idx: グループのアレ) buildrules=(arr,parent)-> p=null for obj,idx in arr if obj.rules # グループだ if p && !p.get(0).hasChildNodes() # 空のpは要らない p.remove() fieldset=$ "<fieldset>" pn=parent.attr("name") || "" fieldset.attr "name","#{pn}.#{idx}" if obj.label fieldset.append $ "<legend>#{obj.label}</legend>" buildrules obj.rules,fieldset parent.append fieldset p=null else # ひとつの设定だ if obj.type=="separator" # pの区切り p=$ "<p>" p.appendTo parent continue unless p? p=$ "<p>" p.appendTo parent label=$ "<label>" if obj.title label.attr "title",obj.title unless obj.backlabel if obj.type!="hidden" label.text obj.label switch obj.type when "checkbox" input=$ "<input>" input.attr "type","checkbox" input.attr "name",obj.name input.attr "value",obj.value.value input.prop "checked",!!obj.value.checked label.append input when "select" select=$ "<select>" select.attr "name",obj.name slv=null for o in obj.values op=$ "<option>" op.text o.label if o.title op.attr "title",o.title op.attr "value",o.value select.append op if o.selected slv=o.value if slv? select.get(0).value=slv label.append select when "time" input=$ "<input>" input.attr "type","number" input.attr "name",obj.name.minute input.attr "min","0" input.attr "step","1" input.attr "size","5" input.attr "value",String obj.defaultValue.minute label.append input label.append document.createTextNode "分" input.change ()-> if(Number($(this).val()) < 0) $(this).val(0) input=$ "<input>" input.attr "type","number" input.attr "name",obj.name.second input.attr "min","-15" input.attr "max","60" input.attr "step","15" input.attr "size","5" input.attr "value",String obj.defaultValue.second label.append input label.append document.createTextNode "秒" input.change ()-> if(Number($(this).val()) >= 60) $(this).val(0) $(this).prev().val(Number($(this).prev().val())+1) $(this).prev().change() else if(Number($(this).val()) < 0) $(this).val(45) $(this).prev().val(Number($(this).prev().val())-1) $(this).prev().change() when "hidden" input=$ "<input>" input.attr "type","hidden" input.attr "name",obj.name input.attr "value",obj.value.value label.append input when "second" input=$ "<input>" input.attr "type","number" input.attr "name",obj.name input.attr "min","0" input.attr "step","1" input.attr "size","5" input.attr "value",obj.defaultValue.value label.append input if obj.backlabel if obj.type!="hidden" label.append document.createTextNode obj.label p.append label $("#rules").attr "name","rule" buildrules Shared.game.rules,$("#rules") if localStorage.savedRule rule=JSON.parse localStorage.savedRule jobs=JSON.parse localStorage.savedJobs delete localStorage.savedRule delete localStorage.savedJobs # 时间设定 daysec=rule.day-0 nightsec=rule.night-0 remainsec=rule.remain-0 form.elements["day_minute"].value=parseInt daysec/60 form.elements["day_second"].value=daysec%60 form.elements["night_minute"].value=parseInt nightsec/60 form.elements["night_second"].value=nightsec%60 form.elements["remain_minute"].value=parseInt remainsec/60 form.elements["remain_second"].value=remainsec%60 # 其他 delete rule.number # 人数は違うかも for key of rule e=form.elements[key] if e? if e.type=="checkbox" e.checked = e.value==rule[key] else e.value=rule[key] # 配置も再現 for job in Shared.game.jobs e=form.elements[job] # 职业 if e? e.value=jobs[job]?.number ? 0 $("#gamestartsec").removeAttr "hidden" forminfo() $("#roomname").text room.name if room.mode=="waiting" # 開始前のユーザー一覧は roomから取得する console.log room.players room.players.forEach (x)-> li=makeplayerbox x,room.blind $("#players").append li # 未参加の場合は参加ボタン joinbutton=(je)-> # 参加 opt= name:"" icon:null into=-> ss.rpc "game.rooms.join", roomid,opt,(result)-> if result?.require=="login" # ログインが必要 Index.util.loginWindow -> if Index.app.userid() into() else if result?.error? Index.util.message "房间",result.error else if result?.tip? Index.util.message result.title,result.tip # 如果房间有特殊提示 Index.app.refresh() else Index.app.refresh() if room.blind && !room.theme # 参加者名 ### Index.util.prompt "加入游戏","请输入昵称",null,(name)-> if name opt.name=name into() ### # ここ書いてないよ! Index.util.blindName null,(obj)-> if obj? opt.name=obj.name opt.icon=obj.icon into() else into() if (room.mode=="waiting" || room.mode=="playing" && room.jobrule=="特殊规则.Endless黑暗火锅") && !enter_result?.joined # 未参加 b=makebutton "加入游戏" $("#playersinfo").append b $(b).click joinbutton else if room.mode=="waiting" && enter_result?.joined # Endless黑暗火锅でも脱退はできない b=makebutton "退出游戏" $("#playersinfo").append b $(b).click (je)-> # 脱退 ss.rpc "game.rooms.unjoin", roomid,(result)-> if result? Index.util.message "房间",result else Index.app.refresh() if room.mode=="waiting" # 开始前 b=makebutton "准备/取消准备","全员准备好后即可开始游戏。" $("#playersinfo").append b $(b).click (je)-> ss.rpc "game.rooms.ready", roomid,(result)-> if result? Index.util.message "房间",result b=makebutton "帮手","成为他人的帮手后,将不会直接参与游戏,而是向帮助的对象提供建议。" # 帮手になる/やめるボタン $(b).click (je)-> Index.util.selectprompt "帮手","想要成为谁的帮手?",room.players.map((x)->{name:x.name,value:x.userid}),(id)-> ss.rpc "game.rooms.helper",roomid, id,(result)-> if result? Index.util.message "错误",result $("#playersinfo").append b userid=Index.app.userid() if room.mode=="waiting" if room.owner.userid==Index.app.userid() # 自己 b=makebutton "展开游戏开始界面" $("#playersinfo").append b $(b).click newgamebutton b=makebutton "将参加者踢出游戏" $("#playersinfo").append b $(b).click (je)-> Index.util.selectprompt "踢出","请选择要被踢出的人",room.players.map((x)->{name:x.name,value:x.userid}),(id)-> if id ss.rpc "game.rooms.kick", roomid,id,(result)-> if result? Index.util.message "错误",result b=makebutton "重置[ready]状态" $("#playersinfo").append b $(b).click (je)-> Index.util.ask "重置[ready]状态","要解除全员的[ready]状态吗?",(cb)-> if cb ss.rpc "game.rooms.unreadyall",roomid,(result)-> if result? Index.util.message "错误",result # 役職入力フォームを作る (()=> # job -> cat と job -> team を作る catTable = {} teamTable = {} dds = {} for category,members of Shared.game.categories # HTML dt = document.createElement "dt" dt.textContent = Shared.game.categoryNames[category] dt.classList.add "jobs-cat" dd = dds[category] = document.createElement "dd" dd.classList.add "jobs-cat" $("#jobsfield").append(dt).append(dd) # table for job in members catTable[job] = category dt = document.createElement "dt" dt.classList.add "jobs-cat" dt.textContent = "其他" dd = dds["*"] = document.createElement "dd" dd.classList.add "jobs-cat" # その他は今の所ない # $("#jobsfield").append(dt).append(dd) # table for team,members of Shared.game.teams for job in members teamTable[job] = team for job in Shared.game.jobs # 探す dd = $(dds[catTable[job] ? "*"]) team = teamTable[job] continue unless team? ji = Shared.game.jobinfo[team][job] div = document.createElement "div" div.classList.add "jobs-job" div.dataset.job = job b = document.createElement "b" span = document.createElement "span" span.textContent = ji.name b.appendChild span b.insertAdjacentHTML "beforeend", "<a class='jobs-job-help' href='/manual/job/#{job}'><i class='fa fa-question-circle-o'></i></a>" span = document.createElement "span" span.classList.add "jobs-job-controls" if job == "Human" # 村人は違う処理 output = document.createElement "output" output.name = job output.dataset.jobname = ji.name output.classList.add "jobs-job-controls-number" span.appendChild output check = document.createElement "input" check.type = "hidden" check.name = "job_use_#{job}" check.value = "on" span.appendChild check else # 使用チェック check = document.createElement "input" check.type = "checkbox" check.checked = true check.name = "job_use_#{job}" check.value = "on" check.classList.add "jobs-job-controls-check" check.title = "如果取消复选框,在手调黑暗火锅里 #{ji.name} 将不会出现。" span.appendChild check # 人数 input = document.createElement "input" input.type = "number" input.min = 0 input.step = 1 input.value = 0 input.name = job input.dataset.jobname = ji.name input.classList.add "jobs-job-controls-number" # plus / minus button button1 = document.createElement "button" button1.type = "button" button1.classList.add "jobs-job-controls-button" ic1 = document.createElement "i" ic1.classList.add "fa" ic1.classList.add "fa-plus-square" button1.appendChild ic1 button1.addEventListener 'click', ((job)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements[job] v = parseInt(num.value) num.value = String(v + 1) jobsformvalidate room, form )(job) button2 = document.createElement "button" button2.type = "button" button2.classList.add "jobs-job-controls-button" ic2 = document.createElement "i" ic2.classList.add "fa" ic2.classList.add "fa-minus-square" button2.appendChild ic2 button2.addEventListener 'click', ((job)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements[job] v = parseInt(num.value) if v > 0 num.value = String(v - 1) jobsformvalidate room, form )(job) span.appendChild input span.appendChild button1 span.appendChild button2 div.appendChild b div.appendChild span dd.append div # カテゴリ別のも用意しておく dt = document.createElement "dt" dt.classList.add "jobs-cat" dt.textContent = "手调黑暗火锅用" dd = document.createElement "dd" dd.classList.add "jobs-cat" for type,name of Shared.game.categoryNames div = document.createElement "div" div.classList.add "jobs-job" div.dataset.job = "category_#{type}" b = document.createElement "b" span = document.createElement "span" span.textContent = name b.appendChild span span = document.createElement "span" span.classList.add "jobs-job-controls" input = document.createElement "input" input.type = "number" input.min = 0 input.step = 1 input.value = 0 input.name = "category_#{type}" input.dataset.jobname = name input.classList.add "jobs-job-controls-number" # plus / minus button button1 = document.createElement "button" button1.type = "button" button1.classList.add "jobs-job-controls-button" ic1 = document.createElement "i" ic1.classList.add "fa" ic1.classList.add "fa-plus-square" button1.appendChild ic1 button1.addEventListener 'click', ((type)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements["category_#{type}"] v = parseInt(num.value) num.value = String(v + 1) jobsformvalidate room, form )(type) button2 = document.createElement "button" button2.type = "button" button2.classList.add "jobs-job-controls-button" ic2 = document.createElement "i" ic2.classList.add "fa" ic2.classList.add "fa-minus-square" button2.appendChild ic2 button2.addEventListener 'click', ((type)-> (e)-> # plus 1 form = e.currentTarget.form num = form.elements["category_#{type}"] v = parseInt(num.value) if v > 0 num.value = String(v - 1) jobsformvalidate room, form )(type) span.appendChild input span.appendChild button1 span.appendChild button2 div.appendChild b div.appendChild span dd.appendChild div $("#catesfield").append(dt).append(dd) )() if room.owner.userid==Index.app.userid() || room.old b=makebutton "废弃这个房间" $("#playersinfo").append b $(b).click (je)-> Index.util.ask "废弃房间","确定要废弃这个房间吗?",(cb)-> if cb ss.rpc "game.rooms.del", roomid,(result)-> if result? Index.util.message "错误",result form=$("#gamestart").get 0 # ゲーム開始フォームが何か変更されたら呼ばれる関数 jobsforminput=(e)-> t=e.target form=t.form pl=room.players.filter((x)->x.mode=="player").length if t.name=="jobrule" || t.name=="chemical" # ルール変更があった resetplayersinput room, form setplayersbyjobrule room,form,pl jobsformvalidate room,form form.addEventListener "input",jobsforminput,false form.addEventListener "change",jobsforminput,false $("#gamestart").submit (je)-> # いよいよ游戏开始だ! je.preventDefault() query=Index.util.formQuery je.target jobrule=query.jobrule ruleobj=Shared.game.getruleobj(jobrule) ? {} # ステップ2: 时间チェック step2=-> # 夜时间をチェック minNight = ruleobj.suggestedNight?.min ? -Infinity maxNight = ruleobj.suggestedNight?.max ? Infinity night = parseInt(query.night_minute)*60+parseInt(query.night_second) #console.log ruleobj,night,minNight,maxNight if night<minNight || maxNight<night # 範囲オーバー Index.util.ask "选项","这个配置推荐的夜间时间在#{if isFinite(minNight) then minNight+'秒以上' else ''}#{if isFinite(maxNight) then maxNight+'秒以下' else ''},确认要开始游戏吗?",(res)-> if res #OKだってよ... starting() else starting() # じっさいに开始 starting=-> ss.rpc "game.game.gameStart", roomid,query,(result)-> if result? Index.util.message "房间",result else $("#gamestartsec").attr "hidden","hidden" # 相違がないか探す diff=null for key,value of (ruleobj.suggestedOption ? {}) if query[key]!=value diff= key:key value:value break if diff? control=je.target.elements[diff.key] if control? sugval=null if control.type=="select-one" for opt in control.options if opt.value==diff.value sugval=opt.text break if sugval? Index.util.ask "选项","这个配置下推荐选项「#{control.dataset.name}」 「#{sugval}」。可以这样开始游戏吗?",(res)-> if res # OKだってよ... step2() return # とくに何もない step2() speakform=$("#speakform").get 0 $("#speakform").submit (je)-> form=je.target ss.rpc "game.game.speak", roomid,Index.util.formQuery(form),(result)-> if result? Index.util.message "错误",result je.preventDefault() form.elements["comment"].value="" if form.elements["multilinecheck"].checked # 複数行は直す form.elements["multilinecheck"].click() speakform.elements["willbutton"].addEventListener "click", (e)-> # 遗言表单オープン wf=$("#willform").get 0 if wf.hidden wf.hidden=false e.target.value="折叠遗言" else wf.hidden=true e.target.value="遗言" ,false speakform.elements["multilinecheck"].addEventListener "click",(e)-> # 複数行 t=e.target textarea=null comment=t.form.elements["comment"] if t.checked # これから複数行になる textarea=document.createElement "textarea" textarea.cols=50 textarea.rows=4 else # 複数行をやめる textarea=document.createElement "input" textarea.size=50 textarea.name="comment" textarea.value=comment.value if textarea.type=="textarea" && textarea.value textarea.value+="\n" textarea.required=true $(comment).replaceWith textarea textarea.focus() textarea.setSelectionRange textarea.value.length,textarea.value.length # 複数行ショートカット $(speakform).keydown (je)-> if je.keyCode==13 && je.shiftKey && je.target.form.elements["multilinecheck"].checked==false # 複数行にする je.target.form.elements["multilinecheck"].click() je.preventDefault() # 规则表示 $("#speakform").get(0).elements["rulebutton"].addEventListener "click", (e)-> return unless this_rule? win=Index.util.blankWindow() win.append $ "<h1>规则</h1>" p=document.createElement "p" Object.keys(this_rule.jobscount).forEach (x)-> a=document.createElement "a" a.href="/manual/job/#{x}" a.textContent="#{this_rule.jobscount[x].name}#{this_rule.jobscount[x].number}" p.appendChild a p.appendChild document.createTextNode " " win.append p chkrule=(ruleobj,jobscount,rules)-> for obj in rules if obj.rules continue unless obj.visible ruleobj,jobscount chkrule ruleobj,jobscount,obj.rules else p=$ "<p>" val="" if obj.title? p.attr "title",obj.title if obj.type=="separator" continue if obj.getstr? valobj=obj.getstr ruleobj[obj.name] unless valobj? continue val="#{valobj.label ? ''}:#{valobj.value ? ''}" else val="#{obj.label}:" switch obj.type when "checkbox" if ruleobj[obj.name]==obj.value.value unless obj.value.label? continue val+=obj.value.label else unless obj.value.nolabel? continue val+=obj.value.nolabel when "select" flg=false for vobj in obj.values if ruleobj[obj.name]==vobj.value val+=vobj.label if vobj.title p.attr "title",vobj.title flg=true break unless flg continue when "time" val+="#{ruleobj[obj.name.minute]}分#{ruleobj[obj.name.second]}秒" when "second" val+="#{ruleobj[obj.name]}秒" when "hidden" continue p.text val win.append p chkrule this_rule.rule, this_rule.jobscount,Shared.game.rules $("#willform").submit (je)-> form=je.target je.preventDefault() ss.rpc "game.game.will", roomid,form.elements["will"].value,(result)-> if result? Index.util.message "错误",result else $("#willform").get(0).hidden=true $("#speakform").get(0).elements["willbutton"].value="遗言" # 夜の仕事(あと投票) $("#jobform").submit (je)-> form=je.target je.preventDefault() $("#jobform").attr "hidden","hidden" ss.rpc "game.game.job", roomid,Index.util.formQuery(form), (result)-> if result?.error? Index.util.message "错误",result.error $("#jobform").removeAttr "hidden" else if !result?.sleeping # まだ仕事がある $("#jobform").removeAttr "hidden" getjobinfo result else getjobinfo result .click (je)-> bt=je.target if bt.type=="submit" # 送信ボタン bt.form.elements["commandname"].value=bt.name # コマンド名教えてあげる bt.form.elements["jobtype"].value=bt.dataset.job # 职业名も教えてあげる # 拒绝复活ボタン $("#speakform").get(0).elements["norevivebutton"].addEventListener "click",(e)-> Index.util.ask "拒绝复活","一旦拒绝复活将不能撤销。确定要这样做吗?",(result)-> if result ss.rpc "game.game.norevive", roomid, (result)-> if result? # 错误 Index.util.message "错误",result else Index.util.message "拒绝复活","成功拒绝复活。" ,false #======================================== # 誰かが参加した!!!! socket_ids.push Index.socket.on "join","room#{roomid}",(msg,channel)-> room.players.push msg ### li=document.createElement "li" li.title=msg.userid if room.blind li.textContent=msg.name else a=document.createElement "a" a.href="/user/#{msg.userid}" a.textContent=msg.name li.appendChild a ### li=makeplayerbox msg,room.blind $("#players").append li forminfo() # 誰かが出て行った!!! socket_ids.push Index.socket.on "unjoin","room#{roomid}",(msg,channel)-> room.players=room.players.filter (x)->x.userid!=msg $("#players li").filter((idx)-> this.dataset.id==msg).remove() forminfo() # kickされた socket_ids.push Index.socket.on "kicked",null,(msg,channel)-> if msg.id==roomid Index.app.refresh() # 準備 socket_ids.push Index.socket.on "ready","room#{roomid}",(msg,channel)-> for pl in room.players if pl.userid==msg.userid pl.start=msg.start li=$("#players li").filter((idx)-> this.dataset.id==msg.userid) li.replaceWith makeplayerbox pl,room.blind socket_ids.push Index.socket.on "unreadyall","room#{roomid}",(msg,channel)-> for pl in room.players if pl.start pl.start=false li=$("#players li").filter((idx)-> this.dataset.id==pl.userid) li.replaceWith makeplayerbox pl,room.blind socket_ids.push Index.socket.on "mode","room#{roomid}",(msg,channel)-> for pl in room.players if pl.userid==msg.userid pl.mode=msg.mode li=$("#players li").filter((idx)-> this.dataset.id==msg.userid) li.replaceWith makeplayerbox pl,room.blind forminfo() # ログが流れてきた!!! socket_ids.push Index.socket.on "log",null,(msg,channel)-> #if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() if msg.roomid==roomid # この部屋へのログ getlog msg # 職情報を教えてもらった!!! socket_ids.push Index.socket.on "getjob",null,(msg,channel)-> if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() getjobinfo msg # 更新したほうがいい socket_ids.push Index.socket.on "refresh",null,(msg,channel)-> if msg.id==roomid #Index.app.refresh() ss.rpc "game.rooms.enter", roomid,sessionStorage.roompassword ? null,(result)-> ss.rpc "game.game.getlog", roomid,sentlog ss.rpc "game.rooms.oneRoom", roomid,(r)->room=r # 投票表单オープン socket_ids.push Index.socket.on "voteform",null,(msg,channel)-> if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() if msg $("#jobform").removeAttr "hidden" else $("#jobform").attr "hidden","hidden" # 残り时间 socket_ids.push Index.socket.on "time",null,(msg,channel)-> if channel=="room#{roomid}" || channel.indexOf("room#{roomid}_")==0 || channel==Index.app.userid() gettimer parseInt(msg.time),msg.mode # 向房间成员通报猝死统计 socket_ids.push Index.socket.on 'punishalert',null,(msg,channel)-> if msg.id==roomid Index.util.punish "猝死惩罚",msg,(result)-> # console.log "猝死名单" # console.log result ss.rpc "game.rooms.suddenDeathPunish", roomid,result,(result)-> if result? if result.error? # 错误 Index.util.message "猝死惩罚",result.error return Index.util.message "猝死惩罚",result return # 向房间成员通报猝死统计 socket_ids.push Index.socket.on 'punishresult',null,(msg,channel)-> if msg.id==roomid # Index.util.message "猝死惩罚",msg.name+"由于猝死被禁止游戏" console.log "room:",msg.id,msg $(document).click (je)-> # クリックで发言強調 li=if je.target.tagName.toLowerCase()=="li" then je.target else $(je.target).parents("li").get 0 myrules.player=null if $(li).parent("#players").length >0 if li? # 強調 myrules.player=li.dataset.name setcss() $("#chooseviewselect").change (je)-> # 表示部分を选择 v=je.target.value myrules.day=v setcss() .click (je)-> je.stopPropagation() # 配役タイプ setjobrule=(rulearr,names,parent)-> for obj in rulearr # name,title, ruleをもつ if obj.rule instanceof Array # さらに子 optgroup=document.createElement "optgroup" optgroup.label=obj.name parent.appendChild optgroup setjobrule obj.rule,names.concat([obj.name]),optgroup else # option option=document.createElement "option" option.textContent=obj.name option.value=names.concat([obj.name]).join "." option.title=obj.title parent.appendChild option setjobrule Shared.game.jobrules.concat([ name:"特殊规则" rule:[ { name:"自由配置" title:"可以自由的选择角色。" rule:null } { name:"黑暗火锅" title:"各角色人数将随机分配。" rule:null } { name:"手调黑暗火锅" title:"一部分角色由房主分配,其他角色随机分配。" rule:null } { name:"PI:NAME:<NAME>END_PI子人PI:NAME:<NAME>END_PI" title:"全员的职业将由概率表表示。只限村人・人狼・占卜师。" rule:null suggestedNight:{ max:60 } } { name:"Endless黑暗火锅" title:"可以途中参加・死亡后立刻转生黑暗火锅。" rule:null suggestedOption:{ heavenview:"" } } ] ]),[],$("#jobruleselect").get 0 setplayersnumber=(room,form,number)-> form.elements["number"].value=number unless $("#gamestartsec").attr("hidden") == "hidden" setplayersbyjobrule room,form,number jobsformvalidate room,form # 配置一览をアレする setplayersbyjobrule=(room,form,number)-> jobrulename=form.elements["jobrule"].value if form.elements["scapegoat"]?.value=="on" number++ # 身代わりくん if jobrulename in ["特殊规则.自由配置","特殊规则.手调黑暗火锅"] j = $("#jobsfield").get 0 j.hidden=false j.dataset.checkboxes = (if jobrulename!="特殊规则.手调黑暗火锅" then "no" else "") $("#catesfield").get(0).hidden= jobrulename!="特殊规则.手调黑暗火锅" #$("#yaminabe_opt_nums").get(0).hidden=true else if jobrulename in ["特殊规则.黑暗火锅","特殊规则.Endless黑暗火锅"] $("#jobsfield").get(0).hidden=true $("#catesfield").get(0).hidden=true #$("#yaminabe_opt_nums").get(0).hidden=false else $("#jobsfield").get(0).hidden=true $("#catesfield").get(0).hidden=true if jobrulename=="特殊规则.量子人狼" jobrulename="内部利用.量子人狼" obj= Shared.game.getrulefunc jobrulename if obj? form.elements["number"].value=number for x in Shared.game.jobs form.elements[x].value=0 jobs=obj number count=0 #村人以外 for job,num of jobs form.elements[job]?.value=num count+=num # カテゴリ別 for type of Shared.game.categoryNames count+= parseInt(form.elements["category_#{type}"].value ? 0) # 残りが村人の人数 if form.elements["chemical"]?.checked # chemical人狼では村人を足す form.elements["Human"].value = number*2 - count else form.elements["Human"].value = number-count setjobsmonitor form,number jobsformvalidate=(room,form)-> # 村人の人数を調節する pl=room.players.filter((x)->x.mode=="player").length if form.elements["scapegoat"].value=="on" # 替身君 pl++ sum=0 cjobs.forEach (x)-> chk = form.elements["job_use_#{x}"].checked if chk sum+=Number form.elements[x].value else form.elements[x].value = 0 # カテゴリ別 for type of Shared.game.categoryNames sum+= parseInt(form.elements["category_#{type}"].value ? 0) if form.elements["chemical"].checked form.elements["Human"].value=pl*2-sum else form.elements["Human"].value=pl-sum form.elements["number"].value=pl setplayersinput room, form setjobsmonitor form,pl # 规则の表示具合をチェックする checkrule=(form,ruleobj,rules,fsetname)-> for obj,idx in rules continue unless obj.rules fsetname2="#{fsetname}.#{idx}" form.elements[fsetname2].hidden=!(obj.visible ruleobj,ruleobj) checkrule form,ruleobj,obj.rules,fsetname2 # ルールが変更されたときはチェックを元に戻す resetplayersinput=(room, form)-> rule = form.elements["jobrule"].value if rule != "特殊规则.手调黑暗火锅" checks = form.querySelectorAll 'input.jobs-job-controls-check[name^="job_use_"]' for check in checks check.checked = true # フォームに応じてプレイヤーの人数inputの表示を調整 setplayersinput=(room, form)-> divs = document.querySelectorAll "div.jobs-job" for div in divs job = div.dataset.job if job? e = form.elements[job] chk = form.elements["job_use_#{job}"] if e? v = Number e.value if chk? && chk.type=="checkbox" && !chk.checked # 無効化されている div.classList.remove "jobs-job-active" div.classList.add "jobs-job-inactive" div.classList.remove "jobs-job-error" else if v > 0 div.classList.add "jobs-job-active" div.classList.remove "jobs-job-inactive" div.classList.remove "jobs-job-error" else if v < 0 div.classList.remove "jobs-job-active" div.classList.remove "jobs-job-inactive" div.classList.add "jobs-job-error" else div.classList.remove "jobs-job-active" div.classList.remove "jobs-job-inactive" div.classList.remove "jobs-job-error" # 配置をテキストで書いてあげる setjobsmonitor=(form,number)-> text="" rule=Index.util.formQuery form jobrule=rule.jobrule if jobrule=="特殊规则.黑暗火锅" # 黑暗火锅の場合 $("#jobsmonitor").text "黑暗火锅" else if jobrule=="特殊规则.Endless黑暗火锅" $("#jobsmonitor").text "Endless黑暗火锅" else ruleobj=Shared.game.getruleobj jobrule if ruleobj?.minNumber>number $("#jobsmonitor").text "(这个配置最少需要#{ruleobj.minNumber}个人)" else $("#jobsmonitor").text Shared.game.getrulestr jobrule,rule ### jobprops=$("#jobprops") jobprops.children(".prop").prop "hidden",true for job in Shared.game.jobs jobpr=jobprops.children(".prop.#{job}") if jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅"] || form.elements[job].value>0 jobpr.prop "hidden",false # 规则による设定 ruleprops=$("#ruleprops") ruleprops.children(".prop").prop "hidden",true switch jobrule when "特殊规则.量子人狼" ruleprops.children(".prop.rule-quantum").prop "hidden",false # あと替身君はOFFにしたい form.elements["scapegoat"].value="off" ### if jobrule=="特殊规则.量子人狼" # あと替身君はOFFにしたい form.elements["scapegoat"].value="off" rule.scapegoat="off" checkrule form,rule,Shared.game.rules,$("#rules").attr("name") #ログをもらった getlog=(log)-> if log.mode in ["voteresult","probability_table"] # 表を出す p=document.createElement "div" div=document.createElement "div" div.classList.add "icon" p.appendChild div div=document.createElement "div" div.classList.add "name" p.appendChild div tb=document.createElement "table" if log.mode=="voteresult" tb.createCaption().textContent="投票结果" vr=log.voteresult tos=log.tos vr.forEach (player)-> tr=tb.insertRow(-1) tr.insertCell(-1).textContent=player.name tr.insertCell(-1).textContent="#{tos[player.id] ? '0'}票" tr.insertCell(-1).textContent="→#{vr.filter((x)->x.id==player.voteto)[0]?.name ? ''}" else # %表示整形 pbu=(node,num)-> node.textContent=(if num==1 "100%" else (num*100).toFixed(2)+"%" ) if num==1 node.style.fontWeight="bold" return tb.createCaption().textContent="概率表" pt=log.probability_table # 見出し tr=tb.insertRow -1 th=document.createElement "th" th.textContent="名字" tr.appendChild th th=document.createElement "th" if this_rule?.rule.quantumwerewolf_diviner=="on" th.textContent="村人" else th.textContent="人类" tr.appendChild th if this_rule?.rule.quantumwerewolf_diviner=="on" # 占卜师の確率も表示: th=document.createElement "th" th.textContent="占卜师" tr.appendChild th th=document.createElement "th" th.textContent="人狼" tr.appendChild th if this_rule?.rule.quantumwerewolf_dead!="no" th=document.createElement "th" th.textContent="死亡" tr.appendChild th for id,obj of pt tr=tb.insertRow -1 tr.insertCell(-1).textContent=obj.name pbu tr.insertCell(-1),obj.Human if obj.Diviner? pbu tr.insertCell(-1),obj.Diviner pbu tr.insertCell(-1),obj.Werewolf if this_rule?.rule.quantumwerewolf_dead!="no" pbu tr.insertCell(-1),obj.dead if obj.dead==1 tr.classList.add "deadoff-line" p.appendChild tb else p=document.createElement "div" div=document.createElement "div" div.classList.add "name" icondiv=document.createElement "div" icondiv.classList.add "icon" if log.name? div.textContent=switch log.mode when "monologue", "heavenmonologue" "#{log.name}自言自语:" when "will" "#{log.name}遗言:" else "#{log.name}:" if this_icons[log.name] # 头像がある img=document.createElement "img" img.style.width="1em" img.style.height="1em" img.src=this_icons[log.name] img.alt="" # 飾り icondiv.appendChild img p.appendChild icondiv p.appendChild div p.dataset.name=log.name span=document.createElement "div" span.classList.add "comment" if log.size in ["big","small"] # 大/小发言 span.classList.add log.size wrdv=document.createElement "div" wrdv.textContent=log.comment ? "" # 改行の処理 spp=wrdv.firstChild # Text wr=0 while spp? && (wr=spp.nodeValue.indexOf("\n"))>=0 spp=spp.splitText wr+1 wrdv.insertBefore document.createElement("br"),spp parselognode wrdv span.appendChild wrdv p.appendChild span if log.time? time=Index.util.timeFromDate new Date log.time time.classList.add "time" p.appendChild time if log.mode=="nextturn" && log.day #IDづけ p.id="turn_#{log.day}#{if log.night then '_night' else ''}" this_logdata.day=log.day this_logdata.night=log.night if log.night==false || log.day==1 # 朝の場合optgroupに追加 option=document.createElement "option" option.value=log.day option.textContent="第#{log.day}天" $("#chooseviewday").append option setcss() # 日にち数据 if this_logdata.day p.dataset.day=this_logdata.day if this_logdata.night p.dataset.night="night" else p.dataset.day=0 p.classList.add log.mode logs=$("#logs").get 0 logs.insertBefore p,logs.firstChild # プレイヤーオブジェクトのプロパティを得る ### getprop=(obj,propname)-> if obj[propname]? obj[propname] else if obj.main? getprop obj.main,propname else undefined getname=(obj)->getprop obj,"name" ### formplayers=(players)-> #jobflg: 1:生存の人 2:死人 $("#form_players").empty() $("#players").empty() $("#playernumberinfo").text "生存者#{players.filter((x)->!x.dead).length}人 / 死亡者#{players.filter((x)->x.dead).length}人" players.forEach (x)-> # 上の一览用 li=makeplayerbox x $("#players").append li # 头像 if x.icon this_icons[x.name]=x.icon setJobSelection=(selections)-> $("#form_players").empty() valuemap={} #重複を取り除く for x in selections continue if valuemap[x.value] # 重複チェック # 投票表单用 li=document.createElement "li" #if x.dead # li.classList.add "dead" label=document.createElement "label" label.textContent=x.name input=document.createElement "input" input.type="radio" input.name="target" input.value=x.value #input.disabled=!((x.dead && (jobflg&2))||(!x.dead && (jobflg&1))) label.appendChild input li.appendChild label $("#form_players").append li valuemap[x.value]=true # タイマー情報をもらった gettimer=(msg,mode)-> remain_time=parseInt msg clearInterval timerid if timerid? timerid=setInterval -> remain_time-- return if remain_time<0 min=parseInt remain_time/60 sec=remain_time%60 $("#time").text "#{mode || ''} #{min}:#{sec}" ,1000 makebutton=(text,title="")-> b=document.createElement "button" b.type="button" b.textContent=text b.title=title b exports.end=-> ss.rpc "game.rooms.exit", this_room_id,(result)-> if result? Index.util.message "房间",result return clearInterval timerid if timerid? alloff socket_ids... document.body.classList.remove x for x in ["day","night","finished","heaven"] if this_style? $(this_style).remove() #ソケットを全部off alloff= (ids...)-> ids.forEach (x)-> Index.socket.off x # ノードのコメントなどをパースする exports.parselognode=parselognode=(node)-> if node.nodeType==Node.TEXT_NODE # text node return unless node.parentNode result=document.createDocumentFragment() while v=node.nodeValue if res=v.match /^(.*?)(https?:\/\/)([^\s\/]+)(\/\S*)?/ res[4] ?= "" if res[1] # 前の部分 node=node.splitText res[1].length parselognode node.previousSibling url = res[2]+res[3]+res[4] a=document.createElement "a" a.href=url if res[3]==location.host && (res2=res[4].match /^\/room\/(\d+)$/) a.textContent="##{res2[1]}" else if res[4] in ["","/"] && res[3].length<20 a.textContent="#{res[2]}#{res[3]}/" else if res[3].length+res[4].length<60 a.textContent=res[2]+res[3]+res[4] else if res[3].length<40 a.textContent="#{res[2]}#{res[3]}#{res[4].slice(0,10)}...#{res[4].slice(-10)}" else a.textContent="#{res[2]}#{res[3].slice(0,30)}...#{(res[3]+res[4]).slice(-30)}" a.target="_blank" node=node.splitText url.length node.parentNode.replaceChild a,node.previousSibling continue if res=v.match /^(.*?)#(\d+)/ if res[1] # 前の部分 node=node.splitText res[1].length parselognode node.previousSibling a=document.createElement "a" a.href="/room/#{res[2]}" a.textContent="##{res[2]}" node=node.splitText res[2].length+1 # その部分どける node.parentNode.replaceChild a,node.previousSibling continue node.nodeValue=v.replace /(\w{30})(?=\w)/g,"$1\u200b" break else if node.childNodes for ch in node.childNodes if ch.parentNode== node parselognode ch # #players用要素 makeplayerbox=(obj,blindflg,tagname="li")->#obj:game.playersのアレ #df=document.createDocumentFragment() df=document.createElement tagname df.dataset.id=obj.id ? obj.userid df.dataset.name=obj.name if obj.icon figure=document.createElement "figure" figure.classList.add "icon" div=document.createElement "div" div.classList.add "avatar" img=document.createElement "img" img.src=obj.icon img.width=img.height=48 img.alt=obj.name div.appendChild img figure.appendChild div img2=document.createElement "img" img2.src="/images/dead.png" img2.width=img2.height=48 img2.alt="已死亡" img2.classList.add "dead_mark" figure.appendChild img2 df.appendChild figure df.classList.add "icon" p=document.createElement "p" p.classList.add "name" if obj.realid a=document.createElement "a" a.href="/user/#{obj.realid}" a.textContent=obj.name p.appendChild a else p.textContent=obj.name df.appendChild p if obj.jobname p=document.createElement "p" p.classList.add "job" if obj.originalJobname? ### if obj.originalJobname==obj.jobname || obj.originalJobname.indexOf("→")>=0 p.textContent=obj.originalJobname else p.textContent="#{obj.originalJobname}→#{obj.jobname}" ### p.textContent=obj.originalJobname else p.textContent=obj.jobname if obj.option p.textContent+= "(#{obj.option})" df.appendChild p if obj.winner? p=document.createElement "p" p.classList.add "outcome" if obj.winner p.classList.add "win" p.textContent="胜利" else p.classList.add "lose" p.textContent="败北" df.appendChild p if obj.dead df.classList.add "dead" if !obj.winner? && obj.norevive==true # 拒绝复活 p=document.createElement "p" p.classList.add "job" p.textContent="[不可复活]" df.appendChild p if obj.mode=="gm" # GM p=document.createElement "p" p.classList.add "job" p.classList.add "gm" p.textContent="[GM]" df.appendChild p else if /^helper_/.test obj.mode # 帮手 p=document.createElement "p" p.classList.add "job" p.classList.add "helper" p.textContent="[帮手]" df.appendChild p if obj.start # 準備完了 p=document.createElement "p" p.classList.add "job" p.textContent="[ready]" df.appendChild p df speakValueToStr=(game,value)-> # 发言のモード名を文字列に switch value when "day","prepare" "向全员发言" when "audience" "观战者的会话" when "monologue" "自言自语" when "werewolf" "人狼的会话" when "couple" "共有者的会话" when "fox" "妖狐的会话" when "gm" "致全员" when "gmheaven" "至灵界" when "gmaudience" "致观战者" when "gmmonologue" "自言自语" when "helperwhisper" # 帮手先がいない場合(自己への建议) "建议" else if result=value.match /^gmreply_(.+)$/ pl=game.players.filter((x)->x.id==result[1])[0] "→#{pl.name}" else if result=value.match /^helperwhisper_(.+)$/ "建议" $ -> $(window).resize -> unless $(".sticky").length > 0 return $("#sticky").css "width",$("#logs").css "width" unless $("div#content div.game").length $("#content").removeAttr "style" $("#widescreen").live "click",-> if $("#widescreen").is(':checked') $("#content").css "max-width","95%" else $("#content").removeAttr "style" $(".sticky").css "width": $("#logs").css "width" sticky_top = undefined $(window).scroll -> sticky() $("#isfloat").live "click",-> sticky() sticky = -> unless $("#sticky").length > 0 return unless $("#isfloat").is(':checked') $(".sticky").removeAttr "style" $(".sticky").removeAttr "class" $("#logs").removeAttr "style" return if $("body").hasClass("finished") return winTop = $(window).scrollTop() if winTop >= $("#sticky").offset().top and not $("#sticky").hasClass("sticky") sticky_top = $("#sticky").offset().top $("#logs").css "position": "relative" "top": $("#sticky").height() + "px" "padding-top": "5px" $("#sticky").addClass "sticky" $("#sticky").css "background-color": $("body").css("background-color") "width": $("#logs").css "width" if winTop < sticky_top and $("#sticky").hasClass("sticky") $(".sticky").removeAttr "style" $(".sticky").removeAttr "class" $("#logs").removeAttr "style"
[ { "context": "caption</a>'\n\ntest \"mail_to\", ->\n equal mail_to(\"david@loudthinking.com\"),\n '<a href=\"mailto:david@loudthinking.co", "end": 2746, "score": 0.9999342560768127, "start": 2724, "tag": "EMAIL", "value": "david@loudthinking.com" }, { "context": "avid@loudthi...
test/javascripts/tests/helpers/url_test.js.coffee
evrone/ultimate-helpers
2
#= require ultimate/underscore/underscore #= require ultimate/underscore/underscore.string #= require ultimate/helpers/url module "Ultimate.Helpers.Url" _.extend @, Ultimate.Helpers.Url test "url_for", -> strictEqual url_for(), 'javascript:;' strictEqual url_for({}), 'javascript:;' strictEqual url_for(gamma: 2.2), '?gamma=2.2' strictEqual url_for(gamma: 2.2, url: 'some_url'), 'some_url?gamma=2.2' # strictEqual url_for(host: "www.example.com"), 'http://www.example.com/' strictEqual url_for(url: -> 'some_url'), 'some_url' options = gamma: 2.2, anchor: 'comments', url: 'some_url', lambda: false strictEqual url_for(options), 'some_url?gamma=2.2&lambda=false#comments' deepEqual options, gamma: 2.2, anchor: 'comments', url: 'some_url', lambda: false strictEqual url_for("back"), 'javascript:history.back();' strictEqual url_for("/back"), '/back' test "link_to", -> equal link_to('Hello', 'http://www.example.com'), '<a href="http://www.example.com">Hello</a>' equal link_to('Test Link', '/'), '<a href="/">Test Link</a>' equal link_to(null, 'http://ya.ru/'), '<a href="http://ya.ru/">http://ya.ru/</a>' equal link_to('caption'), '<a href="javascript:;">caption</a>' equal link_to('caption', null, class: 'link'), '<a class="link" href="javascript:;">caption</a>' equal link_to("Hello", "http://www.example.com", class: "red", data: {confirm: 'You cant possibly be sure,\n can you?'}), '<a class="red" data-confirm="You cant possibly be sure,\n can you?" href="http://www.example.com">Hello</a>' equal link_to(null, -> 'caption'), '<a href="javascript:;">caption</a>' equal link_to(-> 'caption'), '<a href="javascript:;">caption</a>' equal link_to('0', 'http://www.example.com'), '<a href="http://www.example.com">0</a>' equal link_to(0, 'http://www.example.com'), '<a href="http://www.example.com">0</a>' equal link_to(false, 'http://www.example.com'), '<a href="http://www.example.com">false</a>' equal link_to('', 'http://www.example.com'), '<a href="http://www.example.com"></a>' test "link_to_js", -> equal link_to_js('caption'), '<a href="javascript:;">caption</a>' equal link_to_js('caption', class: 'link'), '<a class="link" href="javascript:;">caption</a>' equal link_to_js("Hello", class: "red", data: {confirm: 'You cant possibly be sure,\n can you?'}), '<a class="red" data-confirm="You cant possibly be sure,\n can you?" href="javascript:;">Hello</a>' equal link_to_js(null, -> 'caption'), '<a href="javascript:;">caption</a>' equal link_to_js(class: 'link', -> 'caption'), '<a class="link" href="javascript:;">caption</a>' equal link_to_js(-> 'caption'), '<a href="javascript:;">caption</a>' test "mail_to", -> equal mail_to("david@loudthinking.com"), '<a href="mailto:david@loudthinking.com">david@loudthinking.com</a>' equal mail_to("david@loudthinking.com", "David Heinemeier Hansson"), '<a href="mailto:david@loudthinking.com">David Heinemeier Hansson</a>' equal mail_to("david@loudthinking.com", "David Heinemeier Hansson", class: "admin"), '<a class="admin" href="mailto:david@loudthinking.com">David Heinemeier Hansson</a>' equal mail_to("me@domain.com", "My email", encode: "javascript"), "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>" # equal mail_to("unicode@example.com", "únicode", encode: "javascript"), # "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%75%6e%69%63%6f%64%65%40%65%78%61%6d%70%6c%65%2e%63%6f%6d%5c%22%3e%c3%ba%6e%69%63%6f%64%65%3c%5c%2f%61%3e%27%29%3b'))</script>" equal mail_to("me@example.com", "My email", cc: "ccaddress@example.com", bcc: "bccaddress@example.com", subject: "This is an example email", body: "This is the body of the message."), '<a href="mailto:me@example.com?cc=ccaddress%40example.com&amp;bcc=bccaddress%40example.com&amp;body=This%20is%20the%20body%20of%20the%20message.&amp;subject=This%20is%20an%20example%20email">My email</a>' equal mail_to('feedback@example.com', '<img src="/feedback.png" />'), '<a href="mailto:feedback@example.com"><img src="/feedback.png" /></a>' equal mail_to("me@domain.com", "My email", encode: "hex"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>' equal mail_to("me@domain.com", null, encode: "hex"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">&#109;&#101;&#64;&#100;&#111;&#109;&#97;&#105;&#110;&#46;&#99;&#111;&#109;</a>' equal mail_to("wolfgang@stufenlos.net", null, replace_at: "(at)", replace_dot: "(dot)"), '<a href="mailto:wolfgang@stufenlos.net">wolfgang(at)stufenlos(dot)net</a>' equal mail_to("me@domain.com", null, encode: "hex", replace_at: "(at)"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">&#109;&#101;&#40;&#97;&#116;&#41;&#100;&#111;&#109;&#97;&#105;&#110;&#46;&#99;&#111;&#109;</a>' equal mail_to("me@domain.com", "My email", encode: "hex", replace_at: "(at)"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>' equal mail_to("me@domain.com", null, encode: "hex", replace_at: "(at)", replace_dot: "(dot)"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">&#109;&#101;&#40;&#97;&#116;&#41;&#100;&#111;&#109;&#97;&#105;&#110;&#40;&#100;&#111;&#116;&#41;&#99;&#111;&#109;</a>' equal mail_to("me@domain.com", "My email", encode: "javascript", replace_at: "(at)", replace_dot: "(dot)"), "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>" equal mail_to("me@domain.com", null, encode: "javascript", replace_at: "(at)", replace_dot: "(dot)"), "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%5c%2f%61%3e%27%29%3b'))</script>"
74836
#= require ultimate/underscore/underscore #= require ultimate/underscore/underscore.string #= require ultimate/helpers/url module "Ultimate.Helpers.Url" _.extend @, Ultimate.Helpers.Url test "url_for", -> strictEqual url_for(), 'javascript:;' strictEqual url_for({}), 'javascript:;' strictEqual url_for(gamma: 2.2), '?gamma=2.2' strictEqual url_for(gamma: 2.2, url: 'some_url'), 'some_url?gamma=2.2' # strictEqual url_for(host: "www.example.com"), 'http://www.example.com/' strictEqual url_for(url: -> 'some_url'), 'some_url' options = gamma: 2.2, anchor: 'comments', url: 'some_url', lambda: false strictEqual url_for(options), 'some_url?gamma=2.2&lambda=false#comments' deepEqual options, gamma: 2.2, anchor: 'comments', url: 'some_url', lambda: false strictEqual url_for("back"), 'javascript:history.back();' strictEqual url_for("/back"), '/back' test "link_to", -> equal link_to('Hello', 'http://www.example.com'), '<a href="http://www.example.com">Hello</a>' equal link_to('Test Link', '/'), '<a href="/">Test Link</a>' equal link_to(null, 'http://ya.ru/'), '<a href="http://ya.ru/">http://ya.ru/</a>' equal link_to('caption'), '<a href="javascript:;">caption</a>' equal link_to('caption', null, class: 'link'), '<a class="link" href="javascript:;">caption</a>' equal link_to("Hello", "http://www.example.com", class: "red", data: {confirm: 'You cant possibly be sure,\n can you?'}), '<a class="red" data-confirm="You cant possibly be sure,\n can you?" href="http://www.example.com">Hello</a>' equal link_to(null, -> 'caption'), '<a href="javascript:;">caption</a>' equal link_to(-> 'caption'), '<a href="javascript:;">caption</a>' equal link_to('0', 'http://www.example.com'), '<a href="http://www.example.com">0</a>' equal link_to(0, 'http://www.example.com'), '<a href="http://www.example.com">0</a>' equal link_to(false, 'http://www.example.com'), '<a href="http://www.example.com">false</a>' equal link_to('', 'http://www.example.com'), '<a href="http://www.example.com"></a>' test "link_to_js", -> equal link_to_js('caption'), '<a href="javascript:;">caption</a>' equal link_to_js('caption', class: 'link'), '<a class="link" href="javascript:;">caption</a>' equal link_to_js("Hello", class: "red", data: {confirm: 'You cant possibly be sure,\n can you?'}), '<a class="red" data-confirm="You cant possibly be sure,\n can you?" href="javascript:;">Hello</a>' equal link_to_js(null, -> 'caption'), '<a href="javascript:;">caption</a>' equal link_to_js(class: 'link', -> 'caption'), '<a class="link" href="javascript:;">caption</a>' equal link_to_js(-> 'caption'), '<a href="javascript:;">caption</a>' test "mail_to", -> equal mail_to("<EMAIL>"), '<a href="mailto:<EMAIL>"><EMAIL></a>' equal mail_to("<EMAIL>", "<NAME>"), '<a href="mailto:<EMAIL>"><NAME></a>' equal mail_to("<EMAIL>", "<NAME>", class: "admin"), '<a class="admin" href="mailto:<EMAIL>"><NAME></a>' equal mail_to("<EMAIL>", "My email", encode: "javascript"), "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>" # equal mail_to("<EMAIL>", "únicode", encode: "javascript"), # "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%75%6e%69%63%6f%64%65%40%65%78%61%6d%70%6c%65%2e%63%6f%6d%5c%22%3e%c3%ba%6e%69%63%6f%64%65%3c%5c%2f%61%3e%27%29%3b'))</script>" equal mail_to("<EMAIL>", "My email", cc: "<EMAIL>", bcc: "<EMAIL>", subject: "This is an example email", body: "This is the body of the message."), '<a href="mailto:<EMAIL>?cc=ccaddress%40example.com&amp;bcc=bccaddress%40example.com&amp;body=This%20is%20the%20body%20of%20the%20message.&amp;subject=This%20is%20an%20example%20email">My email</a>' equal mail_to('<EMAIL>', '<img src="/feedback.png" />'), '<a href="mailto:<EMAIL>"><img src="/feedback.png" /></a>' equal mail_to("<EMAIL>", "My email", encode: "hex"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>' equal mail_to("<EMAIL>", null, encode: "hex"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">&#109;&#101;&#64;&#100;&#111;&#109;&#97;&#105;&#110;&#46;&#99;&#111;&#109;</a>' equal mail_to("<EMAIL>", null, replace_at: "(at)", replace_dot: "(dot)"), '<a href="mailto:<EMAIL>">wolfgang(at)stufenlos(dot)net</a>' equal mail_to("<EMAIL>", null, encode: "hex", replace_at: "(at)"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">&#109;&#101;&#40;&#97;&#116;&#41;&#100;&#111;&#109;&#97;&#105;&#110;&#46;&#99;&#111;&#109;</a>' equal mail_to("<EMAIL>", "My email", encode: "hex", replace_at: "(at)"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>' equal mail_to("<EMAIL>", null, encode: "hex", replace_at: "(at)", replace_dot: "(dot)"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">&#109;&#101;&#40;&#97;&#116;&#41;&#100;&#111;&#109;&#97;&#105;&#110;&#40;&#100;&#111;&#116;&#41;&#99;&#111;&#109;</a>' equal mail_to("<EMAIL>", "My email", encode: "javascript", replace_at: "(at)", replace_dot: "(dot)"), "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>" equal mail_to("<EMAIL>", null, encode: "javascript", replace_at: "(at)", replace_dot: "(dot)"), "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%5c%2f%61%3e%27%29%3b'))</script>"
true
#= require ultimate/underscore/underscore #= require ultimate/underscore/underscore.string #= require ultimate/helpers/url module "Ultimate.Helpers.Url" _.extend @, Ultimate.Helpers.Url test "url_for", -> strictEqual url_for(), 'javascript:;' strictEqual url_for({}), 'javascript:;' strictEqual url_for(gamma: 2.2), '?gamma=2.2' strictEqual url_for(gamma: 2.2, url: 'some_url'), 'some_url?gamma=2.2' # strictEqual url_for(host: "www.example.com"), 'http://www.example.com/' strictEqual url_for(url: -> 'some_url'), 'some_url' options = gamma: 2.2, anchor: 'comments', url: 'some_url', lambda: false strictEqual url_for(options), 'some_url?gamma=2.2&lambda=false#comments' deepEqual options, gamma: 2.2, anchor: 'comments', url: 'some_url', lambda: false strictEqual url_for("back"), 'javascript:history.back();' strictEqual url_for("/back"), '/back' test "link_to", -> equal link_to('Hello', 'http://www.example.com'), '<a href="http://www.example.com">Hello</a>' equal link_to('Test Link', '/'), '<a href="/">Test Link</a>' equal link_to(null, 'http://ya.ru/'), '<a href="http://ya.ru/">http://ya.ru/</a>' equal link_to('caption'), '<a href="javascript:;">caption</a>' equal link_to('caption', null, class: 'link'), '<a class="link" href="javascript:;">caption</a>' equal link_to("Hello", "http://www.example.com", class: "red", data: {confirm: 'You cant possibly be sure,\n can you?'}), '<a class="red" data-confirm="You cant possibly be sure,\n can you?" href="http://www.example.com">Hello</a>' equal link_to(null, -> 'caption'), '<a href="javascript:;">caption</a>' equal link_to(-> 'caption'), '<a href="javascript:;">caption</a>' equal link_to('0', 'http://www.example.com'), '<a href="http://www.example.com">0</a>' equal link_to(0, 'http://www.example.com'), '<a href="http://www.example.com">0</a>' equal link_to(false, 'http://www.example.com'), '<a href="http://www.example.com">false</a>' equal link_to('', 'http://www.example.com'), '<a href="http://www.example.com"></a>' test "link_to_js", -> equal link_to_js('caption'), '<a href="javascript:;">caption</a>' equal link_to_js('caption', class: 'link'), '<a class="link" href="javascript:;">caption</a>' equal link_to_js("Hello", class: "red", data: {confirm: 'You cant possibly be sure,\n can you?'}), '<a class="red" data-confirm="You cant possibly be sure,\n can you?" href="javascript:;">Hello</a>' equal link_to_js(null, -> 'caption'), '<a href="javascript:;">caption</a>' equal link_to_js(class: 'link', -> 'caption'), '<a class="link" href="javascript:;">caption</a>' equal link_to_js(-> 'caption'), '<a href="javascript:;">caption</a>' test "mail_to", -> equal mail_to("PI:EMAIL:<EMAIL>END_PI"), '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>' equal mail_to("PI:EMAIL:<EMAIL>END_PI", "PI:NAME:<NAME>END_PI"), '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:NAME:<NAME>END_PI</a>' equal mail_to("PI:EMAIL:<EMAIL>END_PI", "PI:NAME:<NAME>END_PI", class: "admin"), '<a class="admin" href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:NAME:<NAME>END_PI</a>' equal mail_to("PI:EMAIL:<EMAIL>END_PI", "My email", encode: "javascript"), "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>" # equal mail_to("PI:EMAIL:<EMAIL>END_PI", "únicode", encode: "javascript"), # "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%75%6e%69%63%6f%64%65%40%65%78%61%6d%70%6c%65%2e%63%6f%6d%5c%22%3e%c3%ba%6e%69%63%6f%64%65%3c%5c%2f%61%3e%27%29%3b'))</script>" equal mail_to("PI:EMAIL:<EMAIL>END_PI", "My email", cc: "PI:EMAIL:<EMAIL>END_PI", bcc: "PI:EMAIL:<EMAIL>END_PI", subject: "This is an example email", body: "This is the body of the message."), '<a href="mailto:PI:EMAIL:<EMAIL>END_PI?cc=ccaddress%40example.com&amp;bcc=bccaddress%40example.com&amp;body=This%20is%20the%20body%20of%20the%20message.&amp;subject=This%20is%20an%20example%20email">My email</a>' equal mail_to('PI:EMAIL:<EMAIL>END_PI', '<img src="/feedback.png" />'), '<a href="mailto:PI:EMAIL:<EMAIL>END_PI"><img src="/feedback.png" /></a>' equal mail_to("PI:EMAIL:<EMAIL>END_PI", "My email", encode: "hex"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>' equal mail_to("PI:EMAIL:<EMAIL>END_PI", null, encode: "hex"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">&#109;&#101;&#64;&#100;&#111;&#109;&#97;&#105;&#110;&#46;&#99;&#111;&#109;</a>' equal mail_to("PI:EMAIL:<EMAIL>END_PI", null, replace_at: "(at)", replace_dot: "(dot)"), '<a href="mailto:PI:EMAIL:<EMAIL>END_PI">wolfgang(at)stufenlos(dot)net</a>' equal mail_to("PI:EMAIL:<EMAIL>END_PI", null, encode: "hex", replace_at: "(at)"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">&#109;&#101;&#40;&#97;&#116;&#41;&#100;&#111;&#109;&#97;&#105;&#110;&#46;&#99;&#111;&#109;</a>' equal mail_to("PI:EMAIL:<EMAIL>END_PI", "My email", encode: "hex", replace_at: "(at)"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>' equal mail_to("PI:EMAIL:<EMAIL>END_PI", null, encode: "hex", replace_at: "(at)", replace_dot: "(dot)"), '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">&#109;&#101;&#40;&#97;&#116;&#41;&#100;&#111;&#109;&#97;&#105;&#110;&#40;&#100;&#111;&#116;&#41;&#99;&#111;&#109;</a>' equal mail_to("PI:EMAIL:<EMAIL>END_PI", "My email", encode: "javascript", replace_at: "(at)", replace_dot: "(dot)"), "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%4d%79%20%65%6d%61%69%6c%3c%5c%2f%61%3e%27%29%3b'))</script>" equal mail_to("PI:EMAIL:<EMAIL>END_PI", null, encode: "javascript", replace_at: "(at)", replace_dot: "(dot)"), "<script>eval(decodeURIComponent('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%5c%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%5c%22%3e%6d%65%28%61%74%29%64%6f%6d%61%69%6e%28%64%6f%74%29%63%6f%6d%3c%5c%2f%61%3e%27%29%3b'))</script>"
[ { "context": "gle result entry, which is a View element\n\n@author Roelof Roos (https://github.com/roelofr)\n###\n{View} = require", "end": 107, "score": 0.9998840689659119, "start": 96, "tag": "NAME", "value": "Roelof Roos" }, { "context": " element\n\n@author Roelof Roos (https://g...
lib/views/testresult-class.coffee
roelofr/php-report
0
### PHP Report result-entry A model for a single result entry, which is a View element @author Roelof Roos (https://github.com/roelofr) ### {View} = require 'space-pen' module.exports = class TestResultSingle extends View @content: -> @div class: 'php-report-result', outlet: 'container', => @div class: 'php-report-result__header php-report-result-header', outlet: 'header' => @div class: 'php-report-result-header__icon', outlet: 'icon' @div class: 'php-report-result-header__title', => @h4 outlet: 'title', => @span() @span class: 'php-report-result-header__title-class', outlet: 'header_class' @span class: 'php-report-result-header__title-test', outlet: 'header_test' @div class: 'php-report-result-header__stats', => @div class: 'php-report-result-header__stat', => @ @button click: 'clear', class: 'btn btn-default pull-right', => @span class: 'icon icon-trashcan' @span "Dismiss" @button click: 'run', class: 'btn btn-default pull-right', outlet: 'buttonRun', => @span class: 'icon icon-playback-play' @span "Restart" @button click: 'kill', class: 'btn btn-default pull-right', outlet: 'buttonKill', enabled: false, => @span class: 'icon icon-stop' @span "Abort" @div class: 'phpunit-contents', outlet: 'output', style: 'font-family: monospace' clear: -> @output.html "" setCommand: (command, action) -> @commands[command] = action kill: -> if @commands.kill @commands.kill() run: -> if @commands.run @commands.run() close: -> if @commands.close @commands.close() copy: -> atom.clipboard.write @output.text() append: (data, parse = true) -> breakTag = "<br>" data = data + "" if parse data = data.replace /([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, "$1" + breakTag + "$2" data = data.replace /\son line\s(\d+)/g, ":$1" data = data.replace /((([A-Z]\\:)?([\\/]+(\w|-|_|\.)+)+(\.(\w|-|_)+)+(:\d+)?))/g, "<a>$1</a>" @output.append data
72844
### PHP Report result-entry A model for a single result entry, which is a View element @author <NAME> (https://github.com/roelofr) ### {View} = require 'space-pen' module.exports = class TestResultSingle extends View @content: -> @div class: 'php-report-result', outlet: 'container', => @div class: 'php-report-result__header php-report-result-header', outlet: 'header' => @div class: 'php-report-result-header__icon', outlet: 'icon' @div class: 'php-report-result-header__title', => @h4 outlet: 'title', => @span() @span class: 'php-report-result-header__title-class', outlet: 'header_class' @span class: 'php-report-result-header__title-test', outlet: 'header_test' @div class: 'php-report-result-header__stats', => @div class: 'php-report-result-header__stat', => @ @button click: 'clear', class: 'btn btn-default pull-right', => @span class: 'icon icon-trashcan' @span "Dismiss" @button click: 'run', class: 'btn btn-default pull-right', outlet: 'buttonRun', => @span class: 'icon icon-playback-play' @span "Restart" @button click: 'kill', class: 'btn btn-default pull-right', outlet: 'buttonKill', enabled: false, => @span class: 'icon icon-stop' @span "Abort" @div class: 'phpunit-contents', outlet: 'output', style: 'font-family: monospace' clear: -> @output.html "" setCommand: (command, action) -> @commands[command] = action kill: -> if @commands.kill @commands.kill() run: -> if @commands.run @commands.run() close: -> if @commands.close @commands.close() copy: -> atom.clipboard.write @output.text() append: (data, parse = true) -> breakTag = "<br>" data = data + "" if parse data = data.replace /([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, "$1" + breakTag + "$2" data = data.replace /\son line\s(\d+)/g, ":$1" data = data.replace /((([A-Z]\\:)?([\\/]+(\w|-|_|\.)+)+(\.(\w|-|_)+)+(:\d+)?))/g, "<a>$1</a>" @output.append data
true
### PHP Report result-entry A model for a single result entry, which is a View element @author PI:NAME:<NAME>END_PI (https://github.com/roelofr) ### {View} = require 'space-pen' module.exports = class TestResultSingle extends View @content: -> @div class: 'php-report-result', outlet: 'container', => @div class: 'php-report-result__header php-report-result-header', outlet: 'header' => @div class: 'php-report-result-header__icon', outlet: 'icon' @div class: 'php-report-result-header__title', => @h4 outlet: 'title', => @span() @span class: 'php-report-result-header__title-class', outlet: 'header_class' @span class: 'php-report-result-header__title-test', outlet: 'header_test' @div class: 'php-report-result-header__stats', => @div class: 'php-report-result-header__stat', => @ @button click: 'clear', class: 'btn btn-default pull-right', => @span class: 'icon icon-trashcan' @span "Dismiss" @button click: 'run', class: 'btn btn-default pull-right', outlet: 'buttonRun', => @span class: 'icon icon-playback-play' @span "Restart" @button click: 'kill', class: 'btn btn-default pull-right', outlet: 'buttonKill', enabled: false, => @span class: 'icon icon-stop' @span "Abort" @div class: 'phpunit-contents', outlet: 'output', style: 'font-family: monospace' clear: -> @output.html "" setCommand: (command, action) -> @commands[command] = action kill: -> if @commands.kill @commands.kill() run: -> if @commands.run @commands.run() close: -> if @commands.close @commands.close() copy: -> atom.clipboard.write @output.text() append: (data, parse = true) -> breakTag = "<br>" data = data + "" if parse data = data.replace /([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, "$1" + breakTag + "$2" data = data.replace /\son line\s(\d+)/g, ":$1" data = data.replace /((([A-Z]\\:)?([\\/]+(\w|-|_|\.)+)+(\.(\w|-|_)+)+(:\d+)?))/g, "<a>$1</a>" @output.append data
[ { "context": "angular: [\n { key: \"options.broadcastInterval\" }\n { key: \"events.blink\" }\n { key: \"events.dat", "end": 46, "score": 0.7936486005783081, "start": 21, "tag": "KEY", "value": "options.broadcastInterval" }, { "context": "\n { key: \"options.broadcastInterval\" }...
configs/default/form.cson
octoblu/meshblu-connector-mindwave
0
angular: [ { key: "options.broadcastInterval" } { key: "events.blink" } { key: "events.data" } { key: "events.eeg" } ]
155747
angular: [ { key: "<KEY>" } { key: "<KEY>" } { key: "<KEY>" } { key: "events.eeg" } ]
true
angular: [ { key: "PI:KEY:<KEY>END_PI" } { key: "PI:KEY:<KEY>END_PI" } { key: "PI:KEY:<KEY>END_PI" } { key: "events.eeg" } ]
[ { "context": "ticky menu with changing active element\n# Author: Scott Elwood\n# Maintained By: We the Media, inc.\n# License: ", "end": 178, "score": 0.9993985295295715, "start": 166, "tag": "NAME", "value": "Scott Elwood" } ]
core/jquery.tacky.coffee
AshesOfOwls/jquery.tacky
2
# ---------------------------------------------------------------------- # Project: jQuery.Tacky # Description: Sticky menu with changing active element # Author: Scott Elwood # Maintained By: We the Media, inc. # License: MIT # # Version: 1.0 # ---------------------------------------------------------------------- (($, window, document, undefined_) -> pluginName = 'tacky' defaults = itemSelector: 'a' parentSelector: null tackedClass: 'tacked' activeClass: 'active' toggleClass: 'toggle' openClass: 'open' floating: false scrollSpeed: 500 scrollEasing: '' closeMenuWidth: 700 markerOffset: .4 Plugin = (element, options) -> @options = $.extend({}, defaults, options) @$nav = $(element) @$toggle_button = @$nav.find("." + @options.toggleClass) @options.itemSelector += '[href^="#"]' @init() # In case of elements loading slowly, initialize again setTimeout (=> @init()), 500 Plugin:: = init: -> @_getDOMProperties() @_getPositions() @_createEvents() _getDOMProperties: -> @_getElementSizes() @_getNavOrigin() _getElementSizes: -> @document_height = $(document).height() @window_height = $(window).height() @marker_offset = @window_height * @options.markerOffset @nav_height = @$nav.height() _getNavOrigin: -> tackedClass = @options.tackedClass if @$nav.hasClass(tackedClass) @$clone.hide() if @$clone @$nav.removeClass(tackedClass) @nav_origin = @$nav.offset().top @$nav.addClass(tackedClass) @$clone.show() if @$clone else @nav_origin = @$nav.offset().top _getPositions: -> @links = @$nav.find(@options.itemSelector) @targets = @links.map -> $(this).attr('href') @positions = [] @targets.each (i, target) => @positions.push $(target).offset().top + 1 _createEvents: -> $(document).off('scroll.tacky').on "scroll.tacky", => @_scroll() $(window).off('scroll.tacky').on "resize.tacky", => @_resize() self = @ @links.off('click.tacky').on "click.tacky", (evt, i) -> evt.preventDefault() self._scrollToTarget($(this).attr('href')) @$toggle_button.off('click.tacky').on 'click.tacky', => @_toggleOpen() _scroll: -> scroll_position = $(document).scrollTop() active_i = null if scroll_position > @nav_origin @_tackNav(true) nav_position = scroll_position + @nav_height if nav_position >= @positions[0] - 1 marker_position = scroll_position + @marker_offset if scroll_position + @window_height is @document_height marker_position = @document_height for pos, i in @positions if marker_position >= pos active_i = i else @_tackNav(false) @_setActive(active_i) if active_i isnt null _tackNav: (tacked) -> if tacked if @$nav.css('position') is 'static' @$clone = @$nav.clone(false).insertBefore(@$nav).css({ visibility: 0 }) @$nav.addClass(@options.tackedClass) else @_clearActive() @$clone.remove() if @$clone @$nav.removeClass(@options.tackedClass) _setActive: (i) -> if i isnt @active_i @_clearActive() @active_i = i $active_item = @links.eq(i) parentSelector = @options.parentSelector if parentSelector $active_item.closest(parentSelector).addClass(@options.activeClass) else $active_item.addClass(@options.activeClass) _clearActive: -> @active_i = null active_class = @options.activeClass @$nav.find('.'+active_class).removeClass(active_class) _resize: -> @_getDOMProperties() # Recalculate @_getPositions() # Recalculate @_scroll() # Trigger reset @_detoggle() _scrollToTarget: (target_id) -> position_index = $.inArray(target_id, @targets) position = @positions[position_index] position -= @nav_height unless @options.floating scroll_speed = if @$nav.hasClass(@options.openClass) then 0 else @options.scrollSpeed @_scrollTo(position, scroll_speed) openClass = @options.openClass @$nav.removeClass(openClass) if @$nav.hasClass(openClass) _scrollTo: (position, speed) -> $("html, body").stop().animate({scrollTop: position}, speed, @options.scrollEasing) _toggleOpen: -> openClass = @options.openClass tackedClass = @options.tackedClass if @$nav.hasClass(openClass) @$nav.removeClass(openClass) else @$nav.addClass(openClass) _detoggle: -> closeMenuWidth = @options.closeMenuWidth if closeMenuWidth >= 0 document_width = $(document).width() if document_width >= closeMenuWidth @$nav.removeClass(@options.openClass) destroy: -> $(document).off('scroll.tacky') $(window).off('scroll.tacky') @links.off('click.tacky') @$toggle_button.off('click.tacky') # ---------------------------------------------------------------------- # ------------------------ Dirty Initialization ------------------------ # ---------------------------------------------------------------------- $.fn[pluginName] = (options) -> args = arguments scoped_name = "plugin_" + pluginName if options is `undefined` or typeof options is "object" # Initialization @each -> unless $.data(@, scoped_name) $.data @, scoped_name, new Plugin(@, options) else if typeof options is "string" and options[0] isnt "_" and options isnt "init" # Calling public methods returns = undefined @each -> instance = $.data(@, scoped_name) if instance instanceof Plugin and typeof instance[options] is "function" returns = instance[options].apply(instance, Array::slice.call(args, 1)) $.data @, scoped_name, null if options is "destroy" (if returns isnt `undefined` then returns else @) ) jQuery, window, document
99206
# ---------------------------------------------------------------------- # Project: jQuery.Tacky # Description: Sticky menu with changing active element # Author: <NAME> # Maintained By: We the Media, inc. # License: MIT # # Version: 1.0 # ---------------------------------------------------------------------- (($, window, document, undefined_) -> pluginName = 'tacky' defaults = itemSelector: 'a' parentSelector: null tackedClass: 'tacked' activeClass: 'active' toggleClass: 'toggle' openClass: 'open' floating: false scrollSpeed: 500 scrollEasing: '' closeMenuWidth: 700 markerOffset: .4 Plugin = (element, options) -> @options = $.extend({}, defaults, options) @$nav = $(element) @$toggle_button = @$nav.find("." + @options.toggleClass) @options.itemSelector += '[href^="#"]' @init() # In case of elements loading slowly, initialize again setTimeout (=> @init()), 500 Plugin:: = init: -> @_getDOMProperties() @_getPositions() @_createEvents() _getDOMProperties: -> @_getElementSizes() @_getNavOrigin() _getElementSizes: -> @document_height = $(document).height() @window_height = $(window).height() @marker_offset = @window_height * @options.markerOffset @nav_height = @$nav.height() _getNavOrigin: -> tackedClass = @options.tackedClass if @$nav.hasClass(tackedClass) @$clone.hide() if @$clone @$nav.removeClass(tackedClass) @nav_origin = @$nav.offset().top @$nav.addClass(tackedClass) @$clone.show() if @$clone else @nav_origin = @$nav.offset().top _getPositions: -> @links = @$nav.find(@options.itemSelector) @targets = @links.map -> $(this).attr('href') @positions = [] @targets.each (i, target) => @positions.push $(target).offset().top + 1 _createEvents: -> $(document).off('scroll.tacky').on "scroll.tacky", => @_scroll() $(window).off('scroll.tacky').on "resize.tacky", => @_resize() self = @ @links.off('click.tacky').on "click.tacky", (evt, i) -> evt.preventDefault() self._scrollToTarget($(this).attr('href')) @$toggle_button.off('click.tacky').on 'click.tacky', => @_toggleOpen() _scroll: -> scroll_position = $(document).scrollTop() active_i = null if scroll_position > @nav_origin @_tackNav(true) nav_position = scroll_position + @nav_height if nav_position >= @positions[0] - 1 marker_position = scroll_position + @marker_offset if scroll_position + @window_height is @document_height marker_position = @document_height for pos, i in @positions if marker_position >= pos active_i = i else @_tackNav(false) @_setActive(active_i) if active_i isnt null _tackNav: (tacked) -> if tacked if @$nav.css('position') is 'static' @$clone = @$nav.clone(false).insertBefore(@$nav).css({ visibility: 0 }) @$nav.addClass(@options.tackedClass) else @_clearActive() @$clone.remove() if @$clone @$nav.removeClass(@options.tackedClass) _setActive: (i) -> if i isnt @active_i @_clearActive() @active_i = i $active_item = @links.eq(i) parentSelector = @options.parentSelector if parentSelector $active_item.closest(parentSelector).addClass(@options.activeClass) else $active_item.addClass(@options.activeClass) _clearActive: -> @active_i = null active_class = @options.activeClass @$nav.find('.'+active_class).removeClass(active_class) _resize: -> @_getDOMProperties() # Recalculate @_getPositions() # Recalculate @_scroll() # Trigger reset @_detoggle() _scrollToTarget: (target_id) -> position_index = $.inArray(target_id, @targets) position = @positions[position_index] position -= @nav_height unless @options.floating scroll_speed = if @$nav.hasClass(@options.openClass) then 0 else @options.scrollSpeed @_scrollTo(position, scroll_speed) openClass = @options.openClass @$nav.removeClass(openClass) if @$nav.hasClass(openClass) _scrollTo: (position, speed) -> $("html, body").stop().animate({scrollTop: position}, speed, @options.scrollEasing) _toggleOpen: -> openClass = @options.openClass tackedClass = @options.tackedClass if @$nav.hasClass(openClass) @$nav.removeClass(openClass) else @$nav.addClass(openClass) _detoggle: -> closeMenuWidth = @options.closeMenuWidth if closeMenuWidth >= 0 document_width = $(document).width() if document_width >= closeMenuWidth @$nav.removeClass(@options.openClass) destroy: -> $(document).off('scroll.tacky') $(window).off('scroll.tacky') @links.off('click.tacky') @$toggle_button.off('click.tacky') # ---------------------------------------------------------------------- # ------------------------ Dirty Initialization ------------------------ # ---------------------------------------------------------------------- $.fn[pluginName] = (options) -> args = arguments scoped_name = "plugin_" + pluginName if options is `undefined` or typeof options is "object" # Initialization @each -> unless $.data(@, scoped_name) $.data @, scoped_name, new Plugin(@, options) else if typeof options is "string" and options[0] isnt "_" and options isnt "init" # Calling public methods returns = undefined @each -> instance = $.data(@, scoped_name) if instance instanceof Plugin and typeof instance[options] is "function" returns = instance[options].apply(instance, Array::slice.call(args, 1)) $.data @, scoped_name, null if options is "destroy" (if returns isnt `undefined` then returns else @) ) jQuery, window, document
true
# ---------------------------------------------------------------------- # Project: jQuery.Tacky # Description: Sticky menu with changing active element # Author: PI:NAME:<NAME>END_PI # Maintained By: We the Media, inc. # License: MIT # # Version: 1.0 # ---------------------------------------------------------------------- (($, window, document, undefined_) -> pluginName = 'tacky' defaults = itemSelector: 'a' parentSelector: null tackedClass: 'tacked' activeClass: 'active' toggleClass: 'toggle' openClass: 'open' floating: false scrollSpeed: 500 scrollEasing: '' closeMenuWidth: 700 markerOffset: .4 Plugin = (element, options) -> @options = $.extend({}, defaults, options) @$nav = $(element) @$toggle_button = @$nav.find("." + @options.toggleClass) @options.itemSelector += '[href^="#"]' @init() # In case of elements loading slowly, initialize again setTimeout (=> @init()), 500 Plugin:: = init: -> @_getDOMProperties() @_getPositions() @_createEvents() _getDOMProperties: -> @_getElementSizes() @_getNavOrigin() _getElementSizes: -> @document_height = $(document).height() @window_height = $(window).height() @marker_offset = @window_height * @options.markerOffset @nav_height = @$nav.height() _getNavOrigin: -> tackedClass = @options.tackedClass if @$nav.hasClass(tackedClass) @$clone.hide() if @$clone @$nav.removeClass(tackedClass) @nav_origin = @$nav.offset().top @$nav.addClass(tackedClass) @$clone.show() if @$clone else @nav_origin = @$nav.offset().top _getPositions: -> @links = @$nav.find(@options.itemSelector) @targets = @links.map -> $(this).attr('href') @positions = [] @targets.each (i, target) => @positions.push $(target).offset().top + 1 _createEvents: -> $(document).off('scroll.tacky').on "scroll.tacky", => @_scroll() $(window).off('scroll.tacky').on "resize.tacky", => @_resize() self = @ @links.off('click.tacky').on "click.tacky", (evt, i) -> evt.preventDefault() self._scrollToTarget($(this).attr('href')) @$toggle_button.off('click.tacky').on 'click.tacky', => @_toggleOpen() _scroll: -> scroll_position = $(document).scrollTop() active_i = null if scroll_position > @nav_origin @_tackNav(true) nav_position = scroll_position + @nav_height if nav_position >= @positions[0] - 1 marker_position = scroll_position + @marker_offset if scroll_position + @window_height is @document_height marker_position = @document_height for pos, i in @positions if marker_position >= pos active_i = i else @_tackNav(false) @_setActive(active_i) if active_i isnt null _tackNav: (tacked) -> if tacked if @$nav.css('position') is 'static' @$clone = @$nav.clone(false).insertBefore(@$nav).css({ visibility: 0 }) @$nav.addClass(@options.tackedClass) else @_clearActive() @$clone.remove() if @$clone @$nav.removeClass(@options.tackedClass) _setActive: (i) -> if i isnt @active_i @_clearActive() @active_i = i $active_item = @links.eq(i) parentSelector = @options.parentSelector if parentSelector $active_item.closest(parentSelector).addClass(@options.activeClass) else $active_item.addClass(@options.activeClass) _clearActive: -> @active_i = null active_class = @options.activeClass @$nav.find('.'+active_class).removeClass(active_class) _resize: -> @_getDOMProperties() # Recalculate @_getPositions() # Recalculate @_scroll() # Trigger reset @_detoggle() _scrollToTarget: (target_id) -> position_index = $.inArray(target_id, @targets) position = @positions[position_index] position -= @nav_height unless @options.floating scroll_speed = if @$nav.hasClass(@options.openClass) then 0 else @options.scrollSpeed @_scrollTo(position, scroll_speed) openClass = @options.openClass @$nav.removeClass(openClass) if @$nav.hasClass(openClass) _scrollTo: (position, speed) -> $("html, body").stop().animate({scrollTop: position}, speed, @options.scrollEasing) _toggleOpen: -> openClass = @options.openClass tackedClass = @options.tackedClass if @$nav.hasClass(openClass) @$nav.removeClass(openClass) else @$nav.addClass(openClass) _detoggle: -> closeMenuWidth = @options.closeMenuWidth if closeMenuWidth >= 0 document_width = $(document).width() if document_width >= closeMenuWidth @$nav.removeClass(@options.openClass) destroy: -> $(document).off('scroll.tacky') $(window).off('scroll.tacky') @links.off('click.tacky') @$toggle_button.off('click.tacky') # ---------------------------------------------------------------------- # ------------------------ Dirty Initialization ------------------------ # ---------------------------------------------------------------------- $.fn[pluginName] = (options) -> args = arguments scoped_name = "plugin_" + pluginName if options is `undefined` or typeof options is "object" # Initialization @each -> unless $.data(@, scoped_name) $.data @, scoped_name, new Plugin(@, options) else if typeof options is "string" and options[0] isnt "_" and options isnt "init" # Calling public methods returns = undefined @each -> instance = $.data(@, scoped_name) if instance instanceof Plugin and typeof instance[options] is "function" returns = instance[options].apply(instance, Array::slice.call(args, 1)) $.data @, scoped_name, null if options is "destroy" (if returns isnt `undefined` then returns else @) ) jQuery, window, document
[ { "context": "# Description:\n# Applause from Orson Welles\n#\n# Dependencies:\n# None\n#\n# Configuration:\n# ", "end": 45, "score": 0.9777237176895142, "start": 33, "tag": "NAME", "value": "Orson Welles" }, { "context": "ud|bravo|slow clap) - Get applause\n#\n# Author:\n# jo...
src/scripts/applause.coffee
neilprosser/hubot-scripts
1
# Description: # Applause from Orson Welles # # Dependencies: # None # # Configuration: # None # # Commands: # (applause|applaud|bravo|slow clap) - Get applause # # Author: # joshfrench module.exports = (robot) -> robot.hear /applau(d|se)|bravo|slow clap/i, (msg) -> msg.send "http://i.imgur.com/9Zv4V.gif"
168263
# Description: # Applause from <NAME> # # Dependencies: # None # # Configuration: # None # # Commands: # (applause|applaud|bravo|slow clap) - Get applause # # Author: # joshfrench module.exports = (robot) -> robot.hear /applau(d|se)|bravo|slow clap/i, (msg) -> msg.send "http://i.imgur.com/9Zv4V.gif"
true
# Description: # Applause from PI:NAME:<NAME>END_PI # # Dependencies: # None # # Configuration: # None # # Commands: # (applause|applaud|bravo|slow clap) - Get applause # # Author: # joshfrench module.exports = (robot) -> robot.hear /applau(d|se)|bravo|slow clap/i, (msg) -> msg.send "http://i.imgur.com/9Zv4V.gif"
[ { "context": "RogueGirl.define 'user', (f) ->\n f.name = 'Peter'\n f.email = 'peter@peter.com'\n\n defin", "end": 235, "score": 0.9992185235023499, "start": 230, "tag": "NAME", "value": "Peter" }, { "context": "f) ->\n f.name = 'Peter'\n f.email = 'pe...
spec/rogue_girl_spec.coffee
smolnar/rogue-girl
0
#= require spec_helper #= require_tree ./rogue_girl #= require_tree ./features describe 'RogueGirl', -> describe '#define', -> it 'creates definition for factory', -> RogueGirl.define 'user', (f) -> f.name = 'Peter' f.email = 'peter@peter.com' definition = RogueGirl.Definitions.of 'user' expect(definition.name).to.eql('user') expect(definition.type).to.eql('user') expect(definition.attributes.name.value()).to.eql('Peter') expect(definition.attributes.email.value()).to.eql('peter@peter.com') it 'creates definition with traits', -> RogueGirl.define 'user', (f) -> f.name = 'Peter' f.email = 'peter@peter.com' @trait 'with permissions', (f) -> f.permission = 'super' f.role = 'admin' definition = RogueGirl.Definitions.of 'user' expect(definition.name).to.eql('user') expect(definition.type).to.eql('user') expect(definition.attributes.name.value()).to.eql('Peter') expect(definition.attributes.email.value()).to.eql('peter@peter.com') expect(definition.traits['with permissions'].permission.value()).to.eql('super') expect(definition.traits['with permissions'].role.value()).to.eql('admin') describe '#build', -> beforeEach -> @builder = mock('RogueGirl.Builder', build: ->) it 'builds an record', -> @builder .expects('build') .withExactArgs('user', 'trait 1', 'trait 2', name: 'Peter') .once() RogueGirl.build('user', 'trait 1', 'trait 2', name: 'Peter') describe '#create', -> beforeEach -> @builder = mock('RogueGirl.Builder', build: ->) @driver = mock('RogueGirl.driver', save: ->) it 'creates an record', -> @record = { id: 1, name: 'Peter' } @builder .expects('build') .withExactArgs('user', 'trait 1', 'trait 2', name: 'Peter') .returns(@record) .once() @driver .expects('save') .withExactArgs(@record) .returns(@record) RogueGirl.create('user', 'trait 1', 'trait 2', name: 'Peter')
21945
#= require spec_helper #= require_tree ./rogue_girl #= require_tree ./features describe 'RogueGirl', -> describe '#define', -> it 'creates definition for factory', -> RogueGirl.define 'user', (f) -> f.name = '<NAME>' f.email = '<EMAIL>' definition = RogueGirl.Definitions.of 'user' expect(definition.name).to.eql('user') expect(definition.type).to.eql('user') expect(definition.attributes.name.value()).to.eql('P<NAME>') expect(definition.attributes.email.value()).to.eql('<EMAIL>') it 'creates definition with traits', -> RogueGirl.define 'user', (f) -> f.name = '<NAME>' f.email = '<EMAIL>' @trait 'with permissions', (f) -> f.permission = 'super' f.role = 'admin' definition = RogueGirl.Definitions.of 'user' expect(definition.name).to.eql('user') expect(definition.type).to.eql('user') expect(definition.attributes.name.value()).to.eql('<NAME>') expect(definition.attributes.email.value()).to.eql('<EMAIL>') expect(definition.traits['with permissions'].permission.value()).to.eql('super') expect(definition.traits['with permissions'].role.value()).to.eql('admin') describe '#build', -> beforeEach -> @builder = mock('RogueGirl.Builder', build: ->) it 'builds an record', -> @builder .expects('build') .withExactArgs('user', 'trait 1', 'trait 2', name: '<NAME>') .once() RogueGirl.build('user', 'trait 1', 'trait 2', name: '<NAME>') describe '#create', -> beforeEach -> @builder = mock('RogueGirl.Builder', build: ->) @driver = mock('RogueGirl.driver', save: ->) it 'creates an record', -> @record = { id: 1, name: '<NAME>' } @builder .expects('build') .withExactArgs('user', 'trait 1', 'trait 2', name: '<NAME>') .returns(@record) .once() @driver .expects('save') .withExactArgs(@record) .returns(@record) RogueGirl.create('user', 'trait 1', 'trait 2', name: '<NAME>')
true
#= require spec_helper #= require_tree ./rogue_girl #= require_tree ./features describe 'RogueGirl', -> describe '#define', -> it 'creates definition for factory', -> RogueGirl.define 'user', (f) -> f.name = 'PI:NAME:<NAME>END_PI' f.email = 'PI:EMAIL:<EMAIL>END_PI' definition = RogueGirl.Definitions.of 'user' expect(definition.name).to.eql('user') expect(definition.type).to.eql('user') expect(definition.attributes.name.value()).to.eql('PPI:NAME:<NAME>END_PI') expect(definition.attributes.email.value()).to.eql('PI:EMAIL:<EMAIL>END_PI') it 'creates definition with traits', -> RogueGirl.define 'user', (f) -> f.name = 'PI:NAME:<NAME>END_PI' f.email = 'PI:EMAIL:<EMAIL>END_PI' @trait 'with permissions', (f) -> f.permission = 'super' f.role = 'admin' definition = RogueGirl.Definitions.of 'user' expect(definition.name).to.eql('user') expect(definition.type).to.eql('user') expect(definition.attributes.name.value()).to.eql('PI:NAME:<NAME>END_PI') expect(definition.attributes.email.value()).to.eql('PI:EMAIL:<EMAIL>END_PI') expect(definition.traits['with permissions'].permission.value()).to.eql('super') expect(definition.traits['with permissions'].role.value()).to.eql('admin') describe '#build', -> beforeEach -> @builder = mock('RogueGirl.Builder', build: ->) it 'builds an record', -> @builder .expects('build') .withExactArgs('user', 'trait 1', 'trait 2', name: 'PI:NAME:<NAME>END_PI') .once() RogueGirl.build('user', 'trait 1', 'trait 2', name: 'PI:NAME:<NAME>END_PI') describe '#create', -> beforeEach -> @builder = mock('RogueGirl.Builder', build: ->) @driver = mock('RogueGirl.driver', save: ->) it 'creates an record', -> @record = { id: 1, name: 'PI:NAME:<NAME>END_PI' } @builder .expects('build') .withExactArgs('user', 'trait 1', 'trait 2', name: 'PI:NAME:<NAME>END_PI') .returns(@record) .once() @driver .expects('save') .withExactArgs(@record) .returns(@record) RogueGirl.create('user', 'trait 1', 'trait 2', name: 'PI:NAME:<NAME>END_PI')
[ { "context": "0/basic_auth\", {\n auth: {\n username: \"cypress\"\n password: \"password123\"\n }\n })\n ", "end": 1432, "score": 0.9934301972389221, "start": 1425, "tag": "USERNAME", "value": "cypress" }, { "context": " {\n username: \"cypress\"\n ...
packages/driver/test/cypress/integration/issues/573_spec.coffee
nongmanh/cypress
3
run = -> cy.window() .then { timeout: 60000 }, (win) -> new Cypress.Promise (resolve) -> i = win.document.createElement("iframe") i.onload = resolve i.src = "/basic_auth" win.document.body.appendChild(i) .get("iframe").should ($iframe) -> expect($iframe.contents().text()).to.include("basic auth worked") .window().then { timeout: 60000 }, (win) -> new Cypress.Promise (resolve, reject) -> xhr = new win.XMLHttpRequest() xhr.open("GET", "/basic_auth") xhr.onload = -> try expect(@responseText).to.include("basic auth worked") resolve(win) catch err reject(err) xhr.send() .then { timeout: 60000 }, (win) -> new Cypress.Promise (resolve, reject) -> ## ensure other origins do not have auth headers attached xhr = new win.XMLHttpRequest() xhr.open("GET", "http://localhost:3501/basic_auth") xhr.onload = -> try expect(@status).to.eq(401) resolve(win) catch err reject(err) xhr.send() # cy.visit("http://admin:admin@the-internet.herokuapp.com/basic_auth") describe "basic auth", -> it "can visit with username/pw in url", -> cy.visit("http://cypress:password123@localhost:3500/basic_auth") run() it "can visit with auth options", -> cy.visit("http://localhost:3500/basic_auth", { auth: { username: "cypress" password: "password123" } }) run()
76145
run = -> cy.window() .then { timeout: 60000 }, (win) -> new Cypress.Promise (resolve) -> i = win.document.createElement("iframe") i.onload = resolve i.src = "/basic_auth" win.document.body.appendChild(i) .get("iframe").should ($iframe) -> expect($iframe.contents().text()).to.include("basic auth worked") .window().then { timeout: 60000 }, (win) -> new Cypress.Promise (resolve, reject) -> xhr = new win.XMLHttpRequest() xhr.open("GET", "/basic_auth") xhr.onload = -> try expect(@responseText).to.include("basic auth worked") resolve(win) catch err reject(err) xhr.send() .then { timeout: 60000 }, (win) -> new Cypress.Promise (resolve, reject) -> ## ensure other origins do not have auth headers attached xhr = new win.XMLHttpRequest() xhr.open("GET", "http://localhost:3501/basic_auth") xhr.onload = -> try expect(@status).to.eq(401) resolve(win) catch err reject(err) xhr.send() # cy.visit("http://admin:admin@the-internet.herokuapp.com/basic_auth") describe "basic auth", -> it "can visit with username/pw in url", -> cy.visit("http://cypress:password123@localhost:3500/basic_auth") run() it "can visit with auth options", -> cy.visit("http://localhost:3500/basic_auth", { auth: { username: "cypress" password: "<PASSWORD>" } }) run()
true
run = -> cy.window() .then { timeout: 60000 }, (win) -> new Cypress.Promise (resolve) -> i = win.document.createElement("iframe") i.onload = resolve i.src = "/basic_auth" win.document.body.appendChild(i) .get("iframe").should ($iframe) -> expect($iframe.contents().text()).to.include("basic auth worked") .window().then { timeout: 60000 }, (win) -> new Cypress.Promise (resolve, reject) -> xhr = new win.XMLHttpRequest() xhr.open("GET", "/basic_auth") xhr.onload = -> try expect(@responseText).to.include("basic auth worked") resolve(win) catch err reject(err) xhr.send() .then { timeout: 60000 }, (win) -> new Cypress.Promise (resolve, reject) -> ## ensure other origins do not have auth headers attached xhr = new win.XMLHttpRequest() xhr.open("GET", "http://localhost:3501/basic_auth") xhr.onload = -> try expect(@status).to.eq(401) resolve(win) catch err reject(err) xhr.send() # cy.visit("http://admin:admin@the-internet.herokuapp.com/basic_auth") describe "basic auth", -> it "can visit with username/pw in url", -> cy.visit("http://cypress:password123@localhost:3500/basic_auth") run() it "can visit with auth options", -> cy.visit("http://localhost:3500/basic_auth", { auth: { username: "cypress" password: "PI:PASSWORD:<PASSWORD>END_PI" } }) run()
[ { "context": "on:\n# None. All bots use the public beta key: dc6zaTOxFJmzC\n#\n# Commands:\n# giphy help - commands availab", "end": 123, "score": 0.9994337558746338, "start": 110, "tag": "KEY", "value": "dc6zaTOxFJmzC" }, { "context": "t a random recently trending gif\n#\n#...
src/scripts/giphy-bot.coffee
Giphy/hubot-scripts
0
# Description: # The Official Giphy Bot # # Configuration: # None. All bots use the public beta key: dc6zaTOxFJmzC # # Commands: # giphy help - commands available # giphy <query> - translate to gif # giphy bomb <query> - return 5 random found gifs # giphy trending - get a random recently trending gif # # Author: # alexchung module.exports = (robot) -> # use the public beta key api_key = 'dc6zaTOxFJmzC' # listen for giphy robot.hear /^(giphy|gif) (.*)/i, (msg) -> bot msg, msg.match[0], (url) -> msg.send url # giphy bot using public beta key bot = (msg, query, cb) -> msg.http('http://api.giphy.com/v1/bots/hubot') .query q: query api_key: api_key .get() (err, res, body) -> response = JSON.parse(body) gifs = response.data for gif in gifs if gif.images cb gif.images.original.url
192875
# Description: # The Official Giphy Bot # # Configuration: # None. All bots use the public beta key: <KEY> # # Commands: # giphy help - commands available # giphy <query> - translate to gif # giphy bomb <query> - return 5 random found gifs # giphy trending - get a random recently trending gif # # Author: # alexchung module.exports = (robot) -> # use the public beta key api_key = '<KEY>' # listen for giphy robot.hear /^(giphy|gif) (.*)/i, (msg) -> bot msg, msg.match[0], (url) -> msg.send url # giphy bot using public beta key bot = (msg, query, cb) -> msg.http('http://api.giphy.com/v1/bots/hubot') .query q: query api_key: api_key .get() (err, res, body) -> response = JSON.parse(body) gifs = response.data for gif in gifs if gif.images cb gif.images.original.url
true
# Description: # The Official Giphy Bot # # Configuration: # None. All bots use the public beta key: PI:KEY:<KEY>END_PI # # Commands: # giphy help - commands available # giphy <query> - translate to gif # giphy bomb <query> - return 5 random found gifs # giphy trending - get a random recently trending gif # # Author: # alexchung module.exports = (robot) -> # use the public beta key api_key = 'PI:KEY:<KEY>END_PI' # listen for giphy robot.hear /^(giphy|gif) (.*)/i, (msg) -> bot msg, msg.match[0], (url) -> msg.send url # giphy bot using public beta key bot = (msg, query, cb) -> msg.http('http://api.giphy.com/v1/bots/hubot') .query q: query api_key: api_key .get() (err, res, body) -> response = JSON.parse(body) gifs = response.data for gif in gifs if gif.images cb gif.images.original.url
[ { "context": "name: 'say'\ncycleMarkers: [\n\t{\n\t\ttype: 'greedy'\n\t\tvalue: 'me", "end": 10, "score": 0.9165688753128052, "start": 7, "tag": "NAME", "value": "say" } ]
commands/commands/say.cson
Czaplicki/mcfunction-support-data
0
name: 'say' cycleMarkers: [ { type: 'greedy' value: 'message' } ]
117842
name: '<NAME>' cycleMarkers: [ { type: 'greedy' value: 'message' } ]
true
name: 'PI:NAME:<NAME>END_PI' cycleMarkers: [ { type: 'greedy' value: 'message' } ]
[ { "context": "dia-content\">\n <p class=\"title is-4\">John Smith</p>\n <p class=\"subtitle is-6\">@johns", "end": 1388, "score": 0.9087768793106079, "start": 1378, "tag": "NAME", "value": "John Smith" }, { "context": "hn Smith</p>\n <p class=\"...
snippets/bulma_components.cson
kikoseijo/atom-bootstrap-snippets
0
'.text.html.php.blade, .text.html, .text.html.php, .text.html.hack': 'Bulma component - Breadcrumb': prefix: 'bulma:Breadcrumb' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Breadcrumb' body: """ <nav class="breadcrumb" aria-label="breadcrumbs"> <ul> <li><a href="#">Bulma</a></li> <li><a href="#">Documentation</a></li> <li><a href="#">Components</a></li> <li class="is-active"><a href="#" aria-current="page">Breadcrumb</a></li> </ul> </nav> """ 'Bulma component - Card': prefix: 'bulma:card' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Card' body: """ <div class="card"> <div class="card-image"> <figure class="image is-4by3"> <img src="http://via.placeholder.com/1280x960" alt="Placeholder image"> </figure> </div> <div class="card-content"> <div class="media"> <div class="media-left"> <figure class="image is-48x48"> <img src="http://via.placeholder.com/96x96" alt="Placeholder image"> </figure> </div> <div class="media-content"> <p class="title is-4">John Smith</p> <p class="subtitle is-6">@johnsmith</p> </div> </div> <div class="content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec iaculis mauris. <a>@bulmaio</a>. <a href="#">#css</a> <a href="#">#responsive</a> <br> <time datetime="2016-1-1">11:09 PM - 1 Jan 2016</time> </div> </div> <footer class="card-footer"> <a href="#" class="card-footer-item">Save</a> <a href="#" class="card-footer-item">Edit</a> <a href="#" class="card-footer-item">Delete</a> </footer> </div> """ 'Bulma component - Dropdown': prefix: 'bulma:dropdown' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Dropdown' body: """ <div class="dropdown is-hoverable"> <div class="dropdown-trigger"> <button class="button is-info" aria-haspopup="true" aria-controls="dropdown-menu4"> <span>Hover me</span> <span class="icon is-small"> <i class="fa fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu4" role="menu"> <div class="dropdown-content"> <div class="dropdown-item"> <p>You can insert <strong>any type of content</strong> within the dropdown menu.</p> </div> </div> </div> </div> """ 'Bulma component - Menu': prefix: 'bulma:menu' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Menu' body: """ <aside class="menu"> <p class="menu-label"> General </p> <ul class="menu-list"> <li><a>Dashboard</a></li> <li><a>Customers</a></li> </ul> <p class="menu-label"> Administration </p> <ul class="menu-list"> <li><a>Team Settings</a></li> <li> <a class="is-active">Manage Your Team</a> <ul> <li><a>Members</a></li> <li><a>Plugins</a></li> <li><a>Add a member</a></li> </ul> </li> <li><a>Invitations</a></li> <li><a>Cloud Storage Environment Settings</a></li> <li><a>Authentication</a></li> </ul> <p class="menu-label"> Transactions </p> <ul class="menu-list"> <li><a>Payments</a></li> <li><a>Transfers</a></li> <li><a>Balance</a></li> </ul> </aside> """ 'Bulma component - Message': prefix: 'bulma:message' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Message' body: """ <article class="message"> <div class="message-header"> <p>Hello World</p> <button class="delete" aria-label="delete"></button> </div> <div class="message-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. <strong>Pellentesque risus mi</strong>, tempus quis placerat ut, porta nec nulla. Vestibulum rhoncus ac ex sit amet fringilla. Nullam gravida purus diam, et dictum <a>felis venenatis</a> efficitur. Aenean ac <em>eleifend lacus</em>, in mollis lectus. Donec sodales, arcu et sollicitudin porttitor, tortor urna tempor ligula, id porttitor mi magna a neque. Donec dui urna, vehicula et sem eget, facilisis sodales sem. </div> </article> """ 'Bulma component - Modal': prefix: 'bulma:modal' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Modal' body: """ <div class="modal"> <div class="modal-background"></div> <div class="modal-content"> <p class="image is-4by3"> <img src="http://via.placeholder.com/1280x960" alt=""> </p> </div> <button class="modal-close is-large" aria-label="close"></button> </div> """ 'Bulma component - Modal Card': prefix: 'bulma:modal-card' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Modal Card' body: """ <div class="modal"> <div class="modal-background"></div> <div class="modal-card"> <header class="modal-card-head"> <p class="modal-card-title">Modal title</p> <button class="delete" aria-label="close"></button> </header> <section class="modal-card-body"> <!-- Content ... --> </section> <footer class="modal-card-foot"> <button class="button is-success">Save changes</button> <button class="button">Cancel</button> </footer> </div> </div> """ 'Bulma component - Navbar': prefix: 'bulma:navbar' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Navbar' body: """ <nav class="navbar" role="navigation" aria-label="main navigation"> <div class="navbar-brand"> <a class="navbar-item" href="http://bulma.io"> <img src="http://bulma.io/images/bulma-logo.png" alt="Bulma: a modern CSS framework based on Flexbox" width="112" height="28"> </a> <button class="button navbar-burger" data-target="navMenu"> <span></span> <span></span> <span></span> </button> </div> <div class="navbar-menu" id="navMenu"> <!-- navbar-start, navbar-end... --> <a class="navbar-item">Home</a> <a class="navbar-item"> <img src="http://bulma.io/images/bulma-logo.png" width="112" height="28" alt="Bulma"> </a> <div class="navbar-item has-dropdown"> <a class="navbar-link">Docs</a> <div class="navbar-dropdown"> <!-- Other navbar items --> <a class="navbar-item"> Overview </a> </div> </div> </div> </nav> <script> document.addEventListener('DOMContentLoaded', function () { // Get all "navbar-burger" elements var $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0); // Check if there are any navbar burgers if ($navbarBurgers.length > 0) { // Add a click event on each of them $navbarBurgers.forEach(function ($el) { $el.addEventListener('click', function () { // Get the target from the "data-target" attribute var target = $el.dataset.target; var $target = document.getElementById(target); // Toggle the class on both the "navbar-burger" and the "navbar-menu" $el.classList.toggle('is-active'); $target.classList.toggle('is-active'); }); }); } }); </script> """ 'Bulma component - Pagination': prefix: 'bulma:pagination' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Pagination' body: """ <nav class="pagination" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <span class="pagination-ellipsis">&hellip;</span> </li> <li> <a class="pagination-link" aria-label="Goto page 45">45</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 46" aria-current="page">46</a> </li> <li> <a class="pagination-link" aria-label="Goto page 47">47</a> </li> <li> <span class="pagination-ellipsis">&hellip;</span> </li> <li> <a class="pagination-link" aria-label="Goto page 86">86</a> </li> </ul> </nav> """ 'Bulma component - Panel': prefix: 'bulma:panel' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Panel' body: """ <nav class="panel"> <p class="panel-heading"> repositories </p> <div class="panel-block"> <p class="control has-icons-left"> <input class="input is-small" type="text" placeholder="search"> <span class="icon is-small is-left"> <i class="fa fa-search"></i> </span> </p> </div> <p class="panel-tabs"> <a class="is-active">all</a> <a>public</a> <a>private</a> <a>sources</a> <a>forks</a> </p> <a class="panel-block is-active"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> bulma </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> marksheet </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> minireset.css </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> jgthms.github.io </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-code-fork"></i> </span> daniellowtw/infboard </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-code-fork"></i> </span> mojs </a> <label class="panel-block"> <input type="checkbox"> remember me </label> <div class="panel-block"> <button class="button is-primary is-outlined is-fullwidth"> reset all filters </button> </div> </nav> """ 'Bulma component - Tabs': prefix: 'bulma:tabs' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Tabs' body: """ <div class="tabs is-centered"> <ul> <li class="is-active"> <a> <span class="icon is-small"><i class="fa fa-image"></i></span> <span>Pictures</span> </a> </li> <li> <a> <span class="icon is-small"><i class="fa fa-music"></i></span> <span>Music</span> </a> </li> <li> <a> <span class="icon is-small"><i class="fa fa-film"></i></span> <span>Videos</span> </a> </li> <li> <a> <span class="icon is-small"><i class="fa fa-file-text-o"></i></span> <span>Documents</span> </a> </li> </ul> </div> """
181724
'.text.html.php.blade, .text.html, .text.html.php, .text.html.hack': 'Bulma component - Breadcrumb': prefix: 'bulma:Breadcrumb' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Breadcrumb' body: """ <nav class="breadcrumb" aria-label="breadcrumbs"> <ul> <li><a href="#">Bulma</a></li> <li><a href="#">Documentation</a></li> <li><a href="#">Components</a></li> <li class="is-active"><a href="#" aria-current="page">Breadcrumb</a></li> </ul> </nav> """ 'Bulma component - Card': prefix: 'bulma:card' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Card' body: """ <div class="card"> <div class="card-image"> <figure class="image is-4by3"> <img src="http://via.placeholder.com/1280x960" alt="Placeholder image"> </figure> </div> <div class="card-content"> <div class="media"> <div class="media-left"> <figure class="image is-48x48"> <img src="http://via.placeholder.com/96x96" alt="Placeholder image"> </figure> </div> <div class="media-content"> <p class="title is-4"><NAME></p> <p class="subtitle is-6">@johnsmith</p> </div> </div> <div class="content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec iaculis mauris. <a>@bulmaio</a>. <a href="#">#css</a> <a href="#">#responsive</a> <br> <time datetime="2016-1-1">11:09 PM - 1 Jan 2016</time> </div> </div> <footer class="card-footer"> <a href="#" class="card-footer-item">Save</a> <a href="#" class="card-footer-item">Edit</a> <a href="#" class="card-footer-item">Delete</a> </footer> </div> """ 'Bulma component - Dropdown': prefix: 'bulma:dropdown' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Dropdown' body: """ <div class="dropdown is-hoverable"> <div class="dropdown-trigger"> <button class="button is-info" aria-haspopup="true" aria-controls="dropdown-menu4"> <span>Hover me</span> <span class="icon is-small"> <i class="fa fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu4" role="menu"> <div class="dropdown-content"> <div class="dropdown-item"> <p>You can insert <strong>any type of content</strong> within the dropdown menu.</p> </div> </div> </div> </div> """ 'Bulma component - Menu': prefix: 'bulma:menu' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Menu' body: """ <aside class="menu"> <p class="menu-label"> General </p> <ul class="menu-list"> <li><a>Dashboard</a></li> <li><a>Customers</a></li> </ul> <p class="menu-label"> Administration </p> <ul class="menu-list"> <li><a>Team Settings</a></li> <li> <a class="is-active">Manage Your Team</a> <ul> <li><a>Members</a></li> <li><a>Plugins</a></li> <li><a>Add a member</a></li> </ul> </li> <li><a>Invitations</a></li> <li><a>Cloud Storage Environment Settings</a></li> <li><a>Authentication</a></li> </ul> <p class="menu-label"> Transactions </p> <ul class="menu-list"> <li><a>Payments</a></li> <li><a>Transfers</a></li> <li><a>Balance</a></li> </ul> </aside> """ 'Bulma component - Message': prefix: 'bulma:message' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Message' body: """ <article class="message"> <div class="message-header"> <p>Hello World</p> <button class="delete" aria-label="delete"></button> </div> <div class="message-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. <strong>Pellentesque risus mi</strong>, tempus quis placerat ut, porta nec nulla. Vestibulum rhoncus ac ex sit amet fringilla. Nullam gravida purus diam, et dictum <a>felis venenatis</a> efficitur. Aenean ac <em>eleifend lacus</em>, in mollis lectus. Donec sodales, arcu et sollicitudin porttitor, tortor urna tempor ligula, id porttitor mi magna a neque. Donec dui urna, vehicula et sem eget, facilisis sodales sem. </div> </article> """ 'Bulma component - Modal': prefix: 'bulma:modal' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Modal' body: """ <div class="modal"> <div class="modal-background"></div> <div class="modal-content"> <p class="image is-4by3"> <img src="http://via.placeholder.com/1280x960" alt=""> </p> </div> <button class="modal-close is-large" aria-label="close"></button> </div> """ 'Bulma component - Modal Card': prefix: 'bulma:modal-card' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Modal Card' body: """ <div class="modal"> <div class="modal-background"></div> <div class="modal-card"> <header class="modal-card-head"> <p class="modal-card-title">Modal title</p> <button class="delete" aria-label="close"></button> </header> <section class="modal-card-body"> <!-- Content ... --> </section> <footer class="modal-card-foot"> <button class="button is-success">Save changes</button> <button class="button">Cancel</button> </footer> </div> </div> """ 'Bulma component - Navbar': prefix: 'bulma:navbar' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Navbar' body: """ <nav class="navbar" role="navigation" aria-label="main navigation"> <div class="navbar-brand"> <a class="navbar-item" href="http://bulma.io"> <img src="http://bulma.io/images/bulma-logo.png" alt="Bulma: a modern CSS framework based on Flexbox" width="112" height="28"> </a> <button class="button navbar-burger" data-target="navMenu"> <span></span> <span></span> <span></span> </button> </div> <div class="navbar-menu" id="navMenu"> <!-- navbar-start, navbar-end... --> <a class="navbar-item">Home</a> <a class="navbar-item"> <img src="http://bulma.io/images/bulma-logo.png" width="112" height="28" alt="Bulma"> </a> <div class="navbar-item has-dropdown"> <a class="navbar-link">Docs</a> <div class="navbar-dropdown"> <!-- Other navbar items --> <a class="navbar-item"> Overview </a> </div> </div> </div> </nav> <script> document.addEventListener('DOMContentLoaded', function () { // Get all "navbar-burger" elements var $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0); // Check if there are any navbar burgers if ($navbarBurgers.length > 0) { // Add a click event on each of them $navbarBurgers.forEach(function ($el) { $el.addEventListener('click', function () { // Get the target from the "data-target" attribute var target = $el.dataset.target; var $target = document.getElementById(target); // Toggle the class on both the "navbar-burger" and the "navbar-menu" $el.classList.toggle('is-active'); $target.classList.toggle('is-active'); }); }); } }); </script> """ 'Bulma component - Pagination': prefix: 'bulma:pagination' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Pagination' body: """ <nav class="pagination" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <span class="pagination-ellipsis">&hellip;</span> </li> <li> <a class="pagination-link" aria-label="Goto page 45">45</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 46" aria-current="page">46</a> </li> <li> <a class="pagination-link" aria-label="Goto page 47">47</a> </li> <li> <span class="pagination-ellipsis">&hellip;</span> </li> <li> <a class="pagination-link" aria-label="Goto page 86">86</a> </li> </ul> </nav> """ 'Bulma component - Panel': prefix: 'bulma:panel' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Panel' body: """ <nav class="panel"> <p class="panel-heading"> repositories </p> <div class="panel-block"> <p class="control has-icons-left"> <input class="input is-small" type="text" placeholder="search"> <span class="icon is-small is-left"> <i class="fa fa-search"></i> </span> </p> </div> <p class="panel-tabs"> <a class="is-active">all</a> <a>public</a> <a>private</a> <a>sources</a> <a>forks</a> </p> <a class="panel-block is-active"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> bulma </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> marksheet </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> minireset.css </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> jgthms.github.io </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-code-fork"></i> </span> daniellowtw/infboard </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-code-fork"></i> </span> mojs </a> <label class="panel-block"> <input type="checkbox"> remember me </label> <div class="panel-block"> <button class="button is-primary is-outlined is-fullwidth"> reset all filters </button> </div> </nav> """ 'Bulma component - Tabs': prefix: 'bulma:tabs' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Tabs' body: """ <div class="tabs is-centered"> <ul> <li class="is-active"> <a> <span class="icon is-small"><i class="fa fa-image"></i></span> <span>Pictures</span> </a> </li> <li> <a> <span class="icon is-small"><i class="fa fa-music"></i></span> <span>Music</span> </a> </li> <li> <a> <span class="icon is-small"><i class="fa fa-film"></i></span> <span>Videos</span> </a> </li> <li> <a> <span class="icon is-small"><i class="fa fa-file-text-o"></i></span> <span>Documents</span> </a> </li> </ul> </div> """
true
'.text.html.php.blade, .text.html, .text.html.php, .text.html.hack': 'Bulma component - Breadcrumb': prefix: 'bulma:Breadcrumb' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Breadcrumb' body: """ <nav class="breadcrumb" aria-label="breadcrumbs"> <ul> <li><a href="#">Bulma</a></li> <li><a href="#">Documentation</a></li> <li><a href="#">Components</a></li> <li class="is-active"><a href="#" aria-current="page">Breadcrumb</a></li> </ul> </nav> """ 'Bulma component - Card': prefix: 'bulma:card' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Card' body: """ <div class="card"> <div class="card-image"> <figure class="image is-4by3"> <img src="http://via.placeholder.com/1280x960" alt="Placeholder image"> </figure> </div> <div class="card-content"> <div class="media"> <div class="media-left"> <figure class="image is-48x48"> <img src="http://via.placeholder.com/96x96" alt="Placeholder image"> </figure> </div> <div class="media-content"> <p class="title is-4">PI:NAME:<NAME>END_PI</p> <p class="subtitle is-6">@johnsmith</p> </div> </div> <div class="content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec iaculis mauris. <a>@bulmaio</a>. <a href="#">#css</a> <a href="#">#responsive</a> <br> <time datetime="2016-1-1">11:09 PM - 1 Jan 2016</time> </div> </div> <footer class="card-footer"> <a href="#" class="card-footer-item">Save</a> <a href="#" class="card-footer-item">Edit</a> <a href="#" class="card-footer-item">Delete</a> </footer> </div> """ 'Bulma component - Dropdown': prefix: 'bulma:dropdown' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Dropdown' body: """ <div class="dropdown is-hoverable"> <div class="dropdown-trigger"> <button class="button is-info" aria-haspopup="true" aria-controls="dropdown-menu4"> <span>Hover me</span> <span class="icon is-small"> <i class="fa fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu4" role="menu"> <div class="dropdown-content"> <div class="dropdown-item"> <p>You can insert <strong>any type of content</strong> within the dropdown menu.</p> </div> </div> </div> </div> """ 'Bulma component - Menu': prefix: 'bulma:menu' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Menu' body: """ <aside class="menu"> <p class="menu-label"> General </p> <ul class="menu-list"> <li><a>Dashboard</a></li> <li><a>Customers</a></li> </ul> <p class="menu-label"> Administration </p> <ul class="menu-list"> <li><a>Team Settings</a></li> <li> <a class="is-active">Manage Your Team</a> <ul> <li><a>Members</a></li> <li><a>Plugins</a></li> <li><a>Add a member</a></li> </ul> </li> <li><a>Invitations</a></li> <li><a>Cloud Storage Environment Settings</a></li> <li><a>Authentication</a></li> </ul> <p class="menu-label"> Transactions </p> <ul class="menu-list"> <li><a>Payments</a></li> <li><a>Transfers</a></li> <li><a>Balance</a></li> </ul> </aside> """ 'Bulma component - Message': prefix: 'bulma:message' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Message' body: """ <article class="message"> <div class="message-header"> <p>Hello World</p> <button class="delete" aria-label="delete"></button> </div> <div class="message-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. <strong>Pellentesque risus mi</strong>, tempus quis placerat ut, porta nec nulla. Vestibulum rhoncus ac ex sit amet fringilla. Nullam gravida purus diam, et dictum <a>felis venenatis</a> efficitur. Aenean ac <em>eleifend lacus</em>, in mollis lectus. Donec sodales, arcu et sollicitudin porttitor, tortor urna tempor ligula, id porttitor mi magna a neque. Donec dui urna, vehicula et sem eget, facilisis sodales sem. </div> </article> """ 'Bulma component - Modal': prefix: 'bulma:modal' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Modal' body: """ <div class="modal"> <div class="modal-background"></div> <div class="modal-content"> <p class="image is-4by3"> <img src="http://via.placeholder.com/1280x960" alt=""> </p> </div> <button class="modal-close is-large" aria-label="close"></button> </div> """ 'Bulma component - Modal Card': prefix: 'bulma:modal-card' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Modal Card' body: """ <div class="modal"> <div class="modal-background"></div> <div class="modal-card"> <header class="modal-card-head"> <p class="modal-card-title">Modal title</p> <button class="delete" aria-label="close"></button> </header> <section class="modal-card-body"> <!-- Content ... --> </section> <footer class="modal-card-foot"> <button class="button is-success">Save changes</button> <button class="button">Cancel</button> </footer> </div> </div> """ 'Bulma component - Navbar': prefix: 'bulma:navbar' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Navbar' body: """ <nav class="navbar" role="navigation" aria-label="main navigation"> <div class="navbar-brand"> <a class="navbar-item" href="http://bulma.io"> <img src="http://bulma.io/images/bulma-logo.png" alt="Bulma: a modern CSS framework based on Flexbox" width="112" height="28"> </a> <button class="button navbar-burger" data-target="navMenu"> <span></span> <span></span> <span></span> </button> </div> <div class="navbar-menu" id="navMenu"> <!-- navbar-start, navbar-end... --> <a class="navbar-item">Home</a> <a class="navbar-item"> <img src="http://bulma.io/images/bulma-logo.png" width="112" height="28" alt="Bulma"> </a> <div class="navbar-item has-dropdown"> <a class="navbar-link">Docs</a> <div class="navbar-dropdown"> <!-- Other navbar items --> <a class="navbar-item"> Overview </a> </div> </div> </div> </nav> <script> document.addEventListener('DOMContentLoaded', function () { // Get all "navbar-burger" elements var $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0); // Check if there are any navbar burgers if ($navbarBurgers.length > 0) { // Add a click event on each of them $navbarBurgers.forEach(function ($el) { $el.addEventListener('click', function () { // Get the target from the "data-target" attribute var target = $el.dataset.target; var $target = document.getElementById(target); // Toggle the class on both the "navbar-burger" and the "navbar-menu" $el.classList.toggle('is-active'); $target.classList.toggle('is-active'); }); }); } }); </script> """ 'Bulma component - Pagination': prefix: 'bulma:pagination' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Pagination' body: """ <nav class="pagination" role="navigation" aria-label="pagination"> <a class="pagination-previous">Previous</a> <a class="pagination-next">Next page</a> <ul class="pagination-list"> <li> <a class="pagination-link" aria-label="Goto page 1">1</a> </li> <li> <span class="pagination-ellipsis">&hellip;</span> </li> <li> <a class="pagination-link" aria-label="Goto page 45">45</a> </li> <li> <a class="pagination-link is-current" aria-label="Page 46" aria-current="page">46</a> </li> <li> <a class="pagination-link" aria-label="Goto page 47">47</a> </li> <li> <span class="pagination-ellipsis">&hellip;</span> </li> <li> <a class="pagination-link" aria-label="Goto page 86">86</a> </li> </ul> </nav> """ 'Bulma component - Panel': prefix: 'bulma:panel' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Panel' body: """ <nav class="panel"> <p class="panel-heading"> repositories </p> <div class="panel-block"> <p class="control has-icons-left"> <input class="input is-small" type="text" placeholder="search"> <span class="icon is-small is-left"> <i class="fa fa-search"></i> </span> </p> </div> <p class="panel-tabs"> <a class="is-active">all</a> <a>public</a> <a>private</a> <a>sources</a> <a>forks</a> </p> <a class="panel-block is-active"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> bulma </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> marksheet </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> minireset.css </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-book"></i> </span> jgthms.github.io </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-code-fork"></i> </span> daniellowtw/infboard </a> <a class="panel-block"> <span class="panel-icon"> <i class="fa fa-code-fork"></i> </span> mojs </a> <label class="panel-block"> <input type="checkbox"> remember me </label> <div class="panel-block"> <button class="button is-primary is-outlined is-fullwidth"> reset all filters </button> </div> </nav> """ 'Bulma component - Tabs': prefix: 'bulma:tabs' leftLabelHTML: '<span style="color:#1B81B6">Ⓢ</span>' rightLabelHTML: '<span style="color:#00d1b2">Bulma.io</span> Tabs' body: """ <div class="tabs is-centered"> <ul> <li class="is-active"> <a> <span class="icon is-small"><i class="fa fa-image"></i></span> <span>Pictures</span> </a> </li> <li> <a> <span class="icon is-small"><i class="fa fa-music"></i></span> <span>Music</span> </a> </li> <li> <a> <span class="icon is-small"><i class="fa fa-film"></i></span> <span>Videos</span> </a> </li> <li> <a> <span class="icon is-small"><i class="fa fa-file-text-o"></i></span> <span>Documents</span> </a> </li> </ul> </div> """
[ { "context": " explicitly given id', ->\n @render '#jonas[id=\"peter\"]'\n expect(@body).not.to.have.element('div#jon", "end": 1172, "score": 0.4652306139469147, "start": 1167, "tag": "USERNAME", "value": "peter" }, { "context": "ute changes', ->\n context = Serenade( names:...
test/integration/shortcuts.spec.coffee
jnicklas/serenade.js
1
require './../spec_helper' Serenade = require('../../lib/serenade') describe 'Shortcuts', -> beforeEach -> @setupDom() it 'compiles an element with an id', -> @render 'div#jonas' expect(@body).to.have.element('div#jonas') it 'compiles an element with a class', -> @render 'div.jonas' expect(@body).to.have.element('div.jonas') it 'compiles an element with multiple classes', -> @render 'div.jonas.peter.pan' expect(@body).to.have.element('div.jonas.peter.pan') it 'compiles an element with id and classes', -> @render 'div#jonas.peter.pan' expect(@body).to.have.element('div#jonas.peter.pan') it 'compiles an id without an explicit element name into a div', -> @render '#jonas' expect(@body).to.have.element('div#jonas') it 'compiles a class without an explicit element name into a div', -> @render '.jonas' expect(@body).to.have.element('div.jonas') it 'compiles multiple classes without an explicit element name into a div', -> @render '.jonas.peter.pan' expect(@body).to.have.element('div.jonas.peter.pan') it 'is overridden by explicitly given id', -> @render '#jonas[id="peter"]' expect(@body).not.to.have.element('div#jonas') expect(@body).to.have.element('div#peter') it 'is joined with explicitly given classes', -> @render '.jonas[class="peter"]' expect(@body).to.have.element('div.peter.jonas') it 'updates multiple classes with short form as the class attribute changes', -> context = Serenade( names: ['jonas', 'peter'] ) @render 'div.quack[class=@names]', context expect(@body).to.have.element('div.quack.jonas.peter') context.names = undefined expect(@body).to.have.element('div.quack') expect(@body).not.to.have.element('div.jonas') expect(@body).not.to.have.element('div.peter') context.names = 'jonas' expect(@body).to.have.element('div.jonas') context.names = ['harry', 'jonas'] expect(@body).to.have.element('div.harry.jonas')
191132
require './../spec_helper' Serenade = require('../../lib/serenade') describe 'Shortcuts', -> beforeEach -> @setupDom() it 'compiles an element with an id', -> @render 'div#jonas' expect(@body).to.have.element('div#jonas') it 'compiles an element with a class', -> @render 'div.jonas' expect(@body).to.have.element('div.jonas') it 'compiles an element with multiple classes', -> @render 'div.jonas.peter.pan' expect(@body).to.have.element('div.jonas.peter.pan') it 'compiles an element with id and classes', -> @render 'div#jonas.peter.pan' expect(@body).to.have.element('div#jonas.peter.pan') it 'compiles an id without an explicit element name into a div', -> @render '#jonas' expect(@body).to.have.element('div#jonas') it 'compiles a class without an explicit element name into a div', -> @render '.jonas' expect(@body).to.have.element('div.jonas') it 'compiles multiple classes without an explicit element name into a div', -> @render '.jonas.peter.pan' expect(@body).to.have.element('div.jonas.peter.pan') it 'is overridden by explicitly given id', -> @render '#jonas[id="peter"]' expect(@body).not.to.have.element('div#jonas') expect(@body).to.have.element('div#peter') it 'is joined with explicitly given classes', -> @render '.jonas[class="peter"]' expect(@body).to.have.element('div.peter.jonas') it 'updates multiple classes with short form as the class attribute changes', -> context = Serenade( names: ['<NAME>', '<NAME>'] ) @render 'div.quack[class=@names]', context expect(@body).to.have.element('div.quack.jonas.peter') context.names = undefined expect(@body).to.have.element('div.quack') expect(@body).not.to.have.element('div.jonas') expect(@body).not.to.have.element('div.peter') context.names = '<NAME>' expect(@body).to.have.element('div.jonas') context.names = ['<NAME>', '<NAME>'] expect(@body).to.have.element('div.harry.jonas')
true
require './../spec_helper' Serenade = require('../../lib/serenade') describe 'Shortcuts', -> beforeEach -> @setupDom() it 'compiles an element with an id', -> @render 'div#jonas' expect(@body).to.have.element('div#jonas') it 'compiles an element with a class', -> @render 'div.jonas' expect(@body).to.have.element('div.jonas') it 'compiles an element with multiple classes', -> @render 'div.jonas.peter.pan' expect(@body).to.have.element('div.jonas.peter.pan') it 'compiles an element with id and classes', -> @render 'div#jonas.peter.pan' expect(@body).to.have.element('div#jonas.peter.pan') it 'compiles an id without an explicit element name into a div', -> @render '#jonas' expect(@body).to.have.element('div#jonas') it 'compiles a class without an explicit element name into a div', -> @render '.jonas' expect(@body).to.have.element('div.jonas') it 'compiles multiple classes without an explicit element name into a div', -> @render '.jonas.peter.pan' expect(@body).to.have.element('div.jonas.peter.pan') it 'is overridden by explicitly given id', -> @render '#jonas[id="peter"]' expect(@body).not.to.have.element('div#jonas') expect(@body).to.have.element('div#peter') it 'is joined with explicitly given classes', -> @render '.jonas[class="peter"]' expect(@body).to.have.element('div.peter.jonas') it 'updates multiple classes with short form as the class attribute changes', -> context = Serenade( names: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] ) @render 'div.quack[class=@names]', context expect(@body).to.have.element('div.quack.jonas.peter') context.names = undefined expect(@body).to.have.element('div.quack') expect(@body).not.to.have.element('div.jonas') expect(@body).not.to.have.element('div.peter') context.names = 'PI:NAME:<NAME>END_PI' expect(@body).to.have.element('div.jonas') context.names = ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] expect(@body).to.have.element('div.harry.jonas')
[ { "context": "r\n # normalize key names\n key = poly.parser.normalize(key)\n spec.formatter[key] = val\n spec\n\nclass ", "end": 619, "score": 0.522851824760437, "start": 610, "tag": "KEY", "value": "normalize" } ]
src/pivot.coffee
Polychart/polychart2
64
## # Pivot table object and entry point: poly.pivot() # ------------------------------------------------ # This is the main pivot table object; controls workflow ## toStrictMode = (spec) -> for aes in ['row', 'column', 'value'] if not spec[aes+'s'] spec[aes+'s'] = [] if spec[aes]? spec[aes+'s'].push(spec[aes]) for aes in ['rows', 'columns', 'values'] for mappedTo, i in spec[aes] if _.isString mappedTo spec[aes][i] = { var: mappedTo } spec.full ?= false spec.formatter ?= {} for key, val of spec.formatter # normalize key names key = poly.parser.normalize(key) spec.formatter[key] = val spec class PivotProcessedData constructor: (@statData, @ticks, @spec) -> # Construct the data # put data in a structure such that a data point can be fetched by # identifying the ROWS then COLS, and also COLS then ROWS @rows = (poly.parser.unbracket item.var for item in @spec.rows) @columns = (poly.parser.unbracket item.var for item in @spec.columns) indexRows = @rows.concat(@columns) # actually used indexCols = @columns # only for header calculation @dataIndexByRows = {} @dataIndexByCols = {} _insertInto = (structure, keys, row) -> tmp = tmp_parent = structure for key in keys tmp[row[key]] ?= {} tmp_parent = tmp tmp = tmp_parent[row[key]] tmp_parent[row[key]] = row for row in @statData _insertInto(@dataIndexByRows, indexRows, row) _insertInto(@dataIndexByCols, indexCols, row) makeHeaders: () => full = @spec.full _recurse = (accumulator, indexValues, keys, item) => if keys.length is 0 accumulator.push(indexValues) else key = keys[0] restOfKeys = keys[1..] values = _.keys(item) # all possible values (or column headers) _.each @ticks[key].ticks, (tickValue, v) => if full or _.contains(values, ""+tickValue.location) indexV = _.clone(indexValues) indexV[key] = tickValue.value _recurse(accumulator, indexV, restOfKeys, item[tickValue.location]) @rowHeaders=[] @colHeaders=[] _recurse(@rowHeaders, {}, @rows, @dataIndexByRows) _recurse(@colHeaders, {}, @columns, @dataIndexByCols) {@rowHeaders, @colHeaders} makeFormatters: () => # must have formatter for values values = (poly.parser.unbracket item.var for item in @spec.values) formatters = {} for v in values formatters[v] = if v of @spec.formatter @spec.formatter[v] else exp = poly.format.getExp(_.min(_.pluck(@statData, v))) degree = exp poly.format.number(degree) # can optionally have formatter for columns & rows for v in @columns.concat(@rows) if v of @spec.formatter formatters[v] = @spec.formatter[v] formatters get: (rowMindex, colMindex, val) => retvalue = @dataIndexByRows for key in @rows index = @ticks[key].ticks[rowMindex[key]].location if retvalue? and retvalue[index]? retvalue = retvalue[index] for key in @columns index = @ticks[key].ticks[colMindex[key]].location if retvalue? and retvalue[index]? retvalue = retvalue[index] if retvalue? and retvalue[val]? retvalue[val] class Pivot constructor: (spec, @callback, @prepare) -> if not spec? throw poly.error.defn "No pivot table specification is passed in!" @make(spec) make: (spec) -> @spec = toStrictMode(spec) ps = new poly.DataProcess(@spec, [], @spec.strict, poly.spec.pivotToData) ps.make @spec, [], @render generateTicks: (spec, statData, metaData) => ticks = {} for aes in ['rows', 'columns'] for item in spec[aes] key = poly.parser.unbracket item.var meta = metaData[key] values = _.pluck(statData, key) domain = poly.domain.single(values, metaData[key], {}) guideSpec = if meta.type is 'cat' ticks: domain.levels else if meta.type is 'num' numticks: (domain.max - domain.min) / meta.bw else # meta.type is 'date' bw = poly.const.approxTimeInSeconds[meta.bw] numticks: (domain.max - domain.min) / bw tick = poly.tick.make(domain, guideSpec, metaData[key].type) ticks[key] = tick ticks render: (err, statData, metaData) => # create ticks ticks = @generateTicks(@spec, statData, metaData) pivotData = new PivotProcessedData(statData, ticks, @spec) {rowHeaders, colHeaders} = pivotData.makeHeaders() formatters = pivotData.makeFormatters() pivotMeta = ncol: @spec.columns.length nrow: @spec.rows.length nval: @spec.values.length # render a table... if not $ throw poly.error.depn "Pivot Tables require jQuery!" table = $('<table></table>').attr('border', '1px solid black') table.attr('cellspacing', 0) table.attr('cellpadding', 0) i = 0 # COLUMN headers while i < pivotMeta.ncol row = $('<tr></tr>') key = poly.parser.unbracket @spec.columns[i].var ## SPACE in the FIRST ROW if i is 0 if pivotMeta.nrow > 1 space = $('<td></td>') space.attr('rowspan', pivotMeta.ncol) space.attr('colspan', pivotMeta.nrow-1) row.append(space) ## COLUMN header names row.append $("<th>#{key}:</th>").attr('align', 'right') ## COLUMN header values j = 0 while j < colHeaders.length value = colHeaders[j][key] colspan = 1 while ((j+colspan) < colHeaders.length) and (value is colHeaders[j+colspan][key]) colspan++ if formatters[key] then value = formatters[key](value) cell = $("<td class='heading'>#{value}</td>").attr('colspan', colspan*pivotMeta.nval) cell.attr('align', 'center') row.append(cell) j += colspan table.append(row) i++ # VALUE headers row = $('<tr></tr>') if pivotMeta.nrow is 0 ## SPACE space = $("<td class='spacing'></td>") space.attr('rowspan', rowHeaders.length+1) row.append(space) ## ROW header names i = 0 while i < pivotMeta.nrow key = poly.parser.unbracket @spec.rows[i].var row.append $("<th>#{key}</th>").attr('align', 'center') i++ k = 0 while k < colHeaders.length for v in @spec.values cell = $("<td class='heading'>#{poly.parser.unbracket v.var}</td>") cell.attr('align', 'center') row.append(cell) k++ table.append(row) # REST OF TABLE i = 0 rows_mindex = [] cols_mindex = [] while i < rowHeaders.length # total rows row = $('<tr></tr>') # ROW HEADERS for key in @spec.rows key = poly.parser.unbracket key.var value = rowHeaders[i][key] if (i is 0) or value != rowHeaders[i-1][key] rowspan = 1 while (i+rowspan < rowHeaders.length) and value == rowHeaders[i+rowspan][key] rowspan++ # add a cell!! if formatters[key] then value = formatters[key](value) cell = $("<td class='heading'>#{value}</td>").attr('rowspan', rowspan) cell.attr('align', 'center') cell.attr('valign', 'middle') row.append(cell) # ROW VALUES j = 0 while j < colHeaders.length cols = colHeaders[j] rows = rowHeaders[i] for val in @spec.values name = poly.parser.unbracket val.var v = pivotData.get(rows, cols, name) v = if v then formatters[name](v) else '-' row.append $("<td class='value'>#{v}</td>").attr('align', 'right') j++ table.append(row) i++ if @prepare then @prepare @ if @spec.width then table.attr('width', @spec.width) if @spec.height then table.attr('height', @spec.height) @dom = if _.isString(@spec.dom) then $('#'+@spec.dom) else $(@spec.dom) @dom.empty() @dom.append(table) if @callback then @callback null, @ poly.pivot = (spec, callback, prepare) -> new Pivot(spec, callback, prepare)
96631
## # Pivot table object and entry point: poly.pivot() # ------------------------------------------------ # This is the main pivot table object; controls workflow ## toStrictMode = (spec) -> for aes in ['row', 'column', 'value'] if not spec[aes+'s'] spec[aes+'s'] = [] if spec[aes]? spec[aes+'s'].push(spec[aes]) for aes in ['rows', 'columns', 'values'] for mappedTo, i in spec[aes] if _.isString mappedTo spec[aes][i] = { var: mappedTo } spec.full ?= false spec.formatter ?= {} for key, val of spec.formatter # normalize key names key = poly.parser.<KEY>(key) spec.formatter[key] = val spec class PivotProcessedData constructor: (@statData, @ticks, @spec) -> # Construct the data # put data in a structure such that a data point can be fetched by # identifying the ROWS then COLS, and also COLS then ROWS @rows = (poly.parser.unbracket item.var for item in @spec.rows) @columns = (poly.parser.unbracket item.var for item in @spec.columns) indexRows = @rows.concat(@columns) # actually used indexCols = @columns # only for header calculation @dataIndexByRows = {} @dataIndexByCols = {} _insertInto = (structure, keys, row) -> tmp = tmp_parent = structure for key in keys tmp[row[key]] ?= {} tmp_parent = tmp tmp = tmp_parent[row[key]] tmp_parent[row[key]] = row for row in @statData _insertInto(@dataIndexByRows, indexRows, row) _insertInto(@dataIndexByCols, indexCols, row) makeHeaders: () => full = @spec.full _recurse = (accumulator, indexValues, keys, item) => if keys.length is 0 accumulator.push(indexValues) else key = keys[0] restOfKeys = keys[1..] values = _.keys(item) # all possible values (or column headers) _.each @ticks[key].ticks, (tickValue, v) => if full or _.contains(values, ""+tickValue.location) indexV = _.clone(indexValues) indexV[key] = tickValue.value _recurse(accumulator, indexV, restOfKeys, item[tickValue.location]) @rowHeaders=[] @colHeaders=[] _recurse(@rowHeaders, {}, @rows, @dataIndexByRows) _recurse(@colHeaders, {}, @columns, @dataIndexByCols) {@rowHeaders, @colHeaders} makeFormatters: () => # must have formatter for values values = (poly.parser.unbracket item.var for item in @spec.values) formatters = {} for v in values formatters[v] = if v of @spec.formatter @spec.formatter[v] else exp = poly.format.getExp(_.min(_.pluck(@statData, v))) degree = exp poly.format.number(degree) # can optionally have formatter for columns & rows for v in @columns.concat(@rows) if v of @spec.formatter formatters[v] = @spec.formatter[v] formatters get: (rowMindex, colMindex, val) => retvalue = @dataIndexByRows for key in @rows index = @ticks[key].ticks[rowMindex[key]].location if retvalue? and retvalue[index]? retvalue = retvalue[index] for key in @columns index = @ticks[key].ticks[colMindex[key]].location if retvalue? and retvalue[index]? retvalue = retvalue[index] if retvalue? and retvalue[val]? retvalue[val] class Pivot constructor: (spec, @callback, @prepare) -> if not spec? throw poly.error.defn "No pivot table specification is passed in!" @make(spec) make: (spec) -> @spec = toStrictMode(spec) ps = new poly.DataProcess(@spec, [], @spec.strict, poly.spec.pivotToData) ps.make @spec, [], @render generateTicks: (spec, statData, metaData) => ticks = {} for aes in ['rows', 'columns'] for item in spec[aes] key = poly.parser.unbracket item.var meta = metaData[key] values = _.pluck(statData, key) domain = poly.domain.single(values, metaData[key], {}) guideSpec = if meta.type is 'cat' ticks: domain.levels else if meta.type is 'num' numticks: (domain.max - domain.min) / meta.bw else # meta.type is 'date' bw = poly.const.approxTimeInSeconds[meta.bw] numticks: (domain.max - domain.min) / bw tick = poly.tick.make(domain, guideSpec, metaData[key].type) ticks[key] = tick ticks render: (err, statData, metaData) => # create ticks ticks = @generateTicks(@spec, statData, metaData) pivotData = new PivotProcessedData(statData, ticks, @spec) {rowHeaders, colHeaders} = pivotData.makeHeaders() formatters = pivotData.makeFormatters() pivotMeta = ncol: @spec.columns.length nrow: @spec.rows.length nval: @spec.values.length # render a table... if not $ throw poly.error.depn "Pivot Tables require jQuery!" table = $('<table></table>').attr('border', '1px solid black') table.attr('cellspacing', 0) table.attr('cellpadding', 0) i = 0 # COLUMN headers while i < pivotMeta.ncol row = $('<tr></tr>') key = poly.parser.unbracket @spec.columns[i].var ## SPACE in the FIRST ROW if i is 0 if pivotMeta.nrow > 1 space = $('<td></td>') space.attr('rowspan', pivotMeta.ncol) space.attr('colspan', pivotMeta.nrow-1) row.append(space) ## COLUMN header names row.append $("<th>#{key}:</th>").attr('align', 'right') ## COLUMN header values j = 0 while j < colHeaders.length value = colHeaders[j][key] colspan = 1 while ((j+colspan) < colHeaders.length) and (value is colHeaders[j+colspan][key]) colspan++ if formatters[key] then value = formatters[key](value) cell = $("<td class='heading'>#{value}</td>").attr('colspan', colspan*pivotMeta.nval) cell.attr('align', 'center') row.append(cell) j += colspan table.append(row) i++ # VALUE headers row = $('<tr></tr>') if pivotMeta.nrow is 0 ## SPACE space = $("<td class='spacing'></td>") space.attr('rowspan', rowHeaders.length+1) row.append(space) ## ROW header names i = 0 while i < pivotMeta.nrow key = poly.parser.unbracket @spec.rows[i].var row.append $("<th>#{key}</th>").attr('align', 'center') i++ k = 0 while k < colHeaders.length for v in @spec.values cell = $("<td class='heading'>#{poly.parser.unbracket v.var}</td>") cell.attr('align', 'center') row.append(cell) k++ table.append(row) # REST OF TABLE i = 0 rows_mindex = [] cols_mindex = [] while i < rowHeaders.length # total rows row = $('<tr></tr>') # ROW HEADERS for key in @spec.rows key = poly.parser.unbracket key.var value = rowHeaders[i][key] if (i is 0) or value != rowHeaders[i-1][key] rowspan = 1 while (i+rowspan < rowHeaders.length) and value == rowHeaders[i+rowspan][key] rowspan++ # add a cell!! if formatters[key] then value = formatters[key](value) cell = $("<td class='heading'>#{value}</td>").attr('rowspan', rowspan) cell.attr('align', 'center') cell.attr('valign', 'middle') row.append(cell) # ROW VALUES j = 0 while j < colHeaders.length cols = colHeaders[j] rows = rowHeaders[i] for val in @spec.values name = poly.parser.unbracket val.var v = pivotData.get(rows, cols, name) v = if v then formatters[name](v) else '-' row.append $("<td class='value'>#{v}</td>").attr('align', 'right') j++ table.append(row) i++ if @prepare then @prepare @ if @spec.width then table.attr('width', @spec.width) if @spec.height then table.attr('height', @spec.height) @dom = if _.isString(@spec.dom) then $('#'+@spec.dom) else $(@spec.dom) @dom.empty() @dom.append(table) if @callback then @callback null, @ poly.pivot = (spec, callback, prepare) -> new Pivot(spec, callback, prepare)
true
## # Pivot table object and entry point: poly.pivot() # ------------------------------------------------ # This is the main pivot table object; controls workflow ## toStrictMode = (spec) -> for aes in ['row', 'column', 'value'] if not spec[aes+'s'] spec[aes+'s'] = [] if spec[aes]? spec[aes+'s'].push(spec[aes]) for aes in ['rows', 'columns', 'values'] for mappedTo, i in spec[aes] if _.isString mappedTo spec[aes][i] = { var: mappedTo } spec.full ?= false spec.formatter ?= {} for key, val of spec.formatter # normalize key names key = poly.parser.PI:KEY:<KEY>END_PI(key) spec.formatter[key] = val spec class PivotProcessedData constructor: (@statData, @ticks, @spec) -> # Construct the data # put data in a structure such that a data point can be fetched by # identifying the ROWS then COLS, and also COLS then ROWS @rows = (poly.parser.unbracket item.var for item in @spec.rows) @columns = (poly.parser.unbracket item.var for item in @spec.columns) indexRows = @rows.concat(@columns) # actually used indexCols = @columns # only for header calculation @dataIndexByRows = {} @dataIndexByCols = {} _insertInto = (structure, keys, row) -> tmp = tmp_parent = structure for key in keys tmp[row[key]] ?= {} tmp_parent = tmp tmp = tmp_parent[row[key]] tmp_parent[row[key]] = row for row in @statData _insertInto(@dataIndexByRows, indexRows, row) _insertInto(@dataIndexByCols, indexCols, row) makeHeaders: () => full = @spec.full _recurse = (accumulator, indexValues, keys, item) => if keys.length is 0 accumulator.push(indexValues) else key = keys[0] restOfKeys = keys[1..] values = _.keys(item) # all possible values (or column headers) _.each @ticks[key].ticks, (tickValue, v) => if full or _.contains(values, ""+tickValue.location) indexV = _.clone(indexValues) indexV[key] = tickValue.value _recurse(accumulator, indexV, restOfKeys, item[tickValue.location]) @rowHeaders=[] @colHeaders=[] _recurse(@rowHeaders, {}, @rows, @dataIndexByRows) _recurse(@colHeaders, {}, @columns, @dataIndexByCols) {@rowHeaders, @colHeaders} makeFormatters: () => # must have formatter for values values = (poly.parser.unbracket item.var for item in @spec.values) formatters = {} for v in values formatters[v] = if v of @spec.formatter @spec.formatter[v] else exp = poly.format.getExp(_.min(_.pluck(@statData, v))) degree = exp poly.format.number(degree) # can optionally have formatter for columns & rows for v in @columns.concat(@rows) if v of @spec.formatter formatters[v] = @spec.formatter[v] formatters get: (rowMindex, colMindex, val) => retvalue = @dataIndexByRows for key in @rows index = @ticks[key].ticks[rowMindex[key]].location if retvalue? and retvalue[index]? retvalue = retvalue[index] for key in @columns index = @ticks[key].ticks[colMindex[key]].location if retvalue? and retvalue[index]? retvalue = retvalue[index] if retvalue? and retvalue[val]? retvalue[val] class Pivot constructor: (spec, @callback, @prepare) -> if not spec? throw poly.error.defn "No pivot table specification is passed in!" @make(spec) make: (spec) -> @spec = toStrictMode(spec) ps = new poly.DataProcess(@spec, [], @spec.strict, poly.spec.pivotToData) ps.make @spec, [], @render generateTicks: (spec, statData, metaData) => ticks = {} for aes in ['rows', 'columns'] for item in spec[aes] key = poly.parser.unbracket item.var meta = metaData[key] values = _.pluck(statData, key) domain = poly.domain.single(values, metaData[key], {}) guideSpec = if meta.type is 'cat' ticks: domain.levels else if meta.type is 'num' numticks: (domain.max - domain.min) / meta.bw else # meta.type is 'date' bw = poly.const.approxTimeInSeconds[meta.bw] numticks: (domain.max - domain.min) / bw tick = poly.tick.make(domain, guideSpec, metaData[key].type) ticks[key] = tick ticks render: (err, statData, metaData) => # create ticks ticks = @generateTicks(@spec, statData, metaData) pivotData = new PivotProcessedData(statData, ticks, @spec) {rowHeaders, colHeaders} = pivotData.makeHeaders() formatters = pivotData.makeFormatters() pivotMeta = ncol: @spec.columns.length nrow: @spec.rows.length nval: @spec.values.length # render a table... if not $ throw poly.error.depn "Pivot Tables require jQuery!" table = $('<table></table>').attr('border', '1px solid black') table.attr('cellspacing', 0) table.attr('cellpadding', 0) i = 0 # COLUMN headers while i < pivotMeta.ncol row = $('<tr></tr>') key = poly.parser.unbracket @spec.columns[i].var ## SPACE in the FIRST ROW if i is 0 if pivotMeta.nrow > 1 space = $('<td></td>') space.attr('rowspan', pivotMeta.ncol) space.attr('colspan', pivotMeta.nrow-1) row.append(space) ## COLUMN header names row.append $("<th>#{key}:</th>").attr('align', 'right') ## COLUMN header values j = 0 while j < colHeaders.length value = colHeaders[j][key] colspan = 1 while ((j+colspan) < colHeaders.length) and (value is colHeaders[j+colspan][key]) colspan++ if formatters[key] then value = formatters[key](value) cell = $("<td class='heading'>#{value}</td>").attr('colspan', colspan*pivotMeta.nval) cell.attr('align', 'center') row.append(cell) j += colspan table.append(row) i++ # VALUE headers row = $('<tr></tr>') if pivotMeta.nrow is 0 ## SPACE space = $("<td class='spacing'></td>") space.attr('rowspan', rowHeaders.length+1) row.append(space) ## ROW header names i = 0 while i < pivotMeta.nrow key = poly.parser.unbracket @spec.rows[i].var row.append $("<th>#{key}</th>").attr('align', 'center') i++ k = 0 while k < colHeaders.length for v in @spec.values cell = $("<td class='heading'>#{poly.parser.unbracket v.var}</td>") cell.attr('align', 'center') row.append(cell) k++ table.append(row) # REST OF TABLE i = 0 rows_mindex = [] cols_mindex = [] while i < rowHeaders.length # total rows row = $('<tr></tr>') # ROW HEADERS for key in @spec.rows key = poly.parser.unbracket key.var value = rowHeaders[i][key] if (i is 0) or value != rowHeaders[i-1][key] rowspan = 1 while (i+rowspan < rowHeaders.length) and value == rowHeaders[i+rowspan][key] rowspan++ # add a cell!! if formatters[key] then value = formatters[key](value) cell = $("<td class='heading'>#{value}</td>").attr('rowspan', rowspan) cell.attr('align', 'center') cell.attr('valign', 'middle') row.append(cell) # ROW VALUES j = 0 while j < colHeaders.length cols = colHeaders[j] rows = rowHeaders[i] for val in @spec.values name = poly.parser.unbracket val.var v = pivotData.get(rows, cols, name) v = if v then formatters[name](v) else '-' row.append $("<td class='value'>#{v}</td>").attr('align', 'right') j++ table.append(row) i++ if @prepare then @prepare @ if @spec.width then table.attr('width', @spec.width) if @spec.height then table.attr('height', @spec.height) @dom = if _.isString(@spec.dom) then $('#'+@spec.dom) else $(@spec.dom) @dom.empty() @dom.append(table) if @callback then @callback null, @ poly.pivot = (spec, callback, prepare) -> new Pivot(spec, callback, prepare)
[ { "context": "lishableKey = if application.isProduction() then 'pk_live_27jQZozjDGN1HSUTnSuM578g' else 'pk_test_zG5UwVu6Ww8YhtE9ZYh0JO6a'\n \nmodul", "end": 85, "score": 0.9966737627983093, "start": 53, "tag": "KEY", "value": "pk_live_27jQZozjDGN1HSUTnSuM578g" }, { "context": "n() t...
app/core/services/stripe.coffee
rishiloyola/codecombat
1
publishableKey = if application.isProduction() then 'pk_live_27jQZozjDGN1HSUTnSuM578g' else 'pk_test_zG5UwVu6Ww8YhtE9ZYh0JO6a' module.exports = handler = StripeCheckout.configure({ key: publishableKey name: 'CodeCombat' email: me.get('email') image: '/images/pages/base/logo_square_250.png' token: (token) -> Backbone.Mediator.publish 'stripe:received-token', { token: token } })
5417
publishableKey = if application.isProduction() then '<KEY>' else '<KEY>' module.exports = handler = StripeCheckout.configure({ key: publishableKey name: 'CodeCombat' email: me.get('email') image: '/images/pages/base/logo_square_250.png' token: (token) -> Backbone.Mediator.publish 'stripe:received-token', { token: token } })
true
publishableKey = if application.isProduction() then 'PI:KEY:<KEY>END_PI' else 'PI:KEY:<KEY>END_PI' module.exports = handler = StripeCheckout.configure({ key: publishableKey name: 'CodeCombat' email: me.get('email') image: '/images/pages/base/logo_square_250.png' token: (token) -> Backbone.Mediator.publish 'stripe:received-token', { token: token } })
[ { "context": "onthlyScheduler extends Base\n @extend()\n\n _key: -> \"#{@date}:#{@hour}:#{@min}\"\n\n _parseOptions: ->\n @date = @opt.date\n @date =", "end": 110, "score": 0.8506552577018738, "start": 83, "tag": "KEY", "value": "\"#{@date}:#{@hour}:#{@min}\"" } ]
monthly.coffee
pavanvidusankha/Archiver
0
Base = require './base' class MonthlyScheduler extends Base @extend() _key: -> "#{@date}:#{@hour}:#{@min}" _parseOptions: -> @date = @opt.date @date = parseInt @date @hour = parseInt @opt.hour @min = parseInt @opt.minute if not @date? or isNaN @date throw new Error "Scheduler missing/invalid date value in scheduler #{@id}" if not @hour? or isNaN @hour throw new Error "Scheduler missing/invalid hour value in scheduler #{@id}" if not @min? or isNaN @min throw new Error "Scheduler missing/invalid minute value in scheduler #{@id}" @hour = @hour % 24 @min = @min % 60 _nextTime: (Time) -> cur = new Date Time next = new Date cur.getFullYear(), cur.getMonth(), @date, @hour, @min time = next.getTime() if time <= cur.getTime() next.setMonth next.getMonth() + 1 time = next.getTime() return time _lastTime: (Time) -> cur = new Date Time last = new Date cur.getFullYear(), cur.getMonth(), @date, @hour, @min time = last.getTime() if time > cur.getTime() last.setMonth last.getMonth() - 1 time = last.getTime() return time module.exports = (Types) -> Types.monthly = MonthlyScheduler
66551
Base = require './base' class MonthlyScheduler extends Base @extend() _key: -> <KEY> _parseOptions: -> @date = @opt.date @date = parseInt @date @hour = parseInt @opt.hour @min = parseInt @opt.minute if not @date? or isNaN @date throw new Error "Scheduler missing/invalid date value in scheduler #{@id}" if not @hour? or isNaN @hour throw new Error "Scheduler missing/invalid hour value in scheduler #{@id}" if not @min? or isNaN @min throw new Error "Scheduler missing/invalid minute value in scheduler #{@id}" @hour = @hour % 24 @min = @min % 60 _nextTime: (Time) -> cur = new Date Time next = new Date cur.getFullYear(), cur.getMonth(), @date, @hour, @min time = next.getTime() if time <= cur.getTime() next.setMonth next.getMonth() + 1 time = next.getTime() return time _lastTime: (Time) -> cur = new Date Time last = new Date cur.getFullYear(), cur.getMonth(), @date, @hour, @min time = last.getTime() if time > cur.getTime() last.setMonth last.getMonth() - 1 time = last.getTime() return time module.exports = (Types) -> Types.monthly = MonthlyScheduler
true
Base = require './base' class MonthlyScheduler extends Base @extend() _key: -> PI:KEY:<KEY>END_PI _parseOptions: -> @date = @opt.date @date = parseInt @date @hour = parseInt @opt.hour @min = parseInt @opt.minute if not @date? or isNaN @date throw new Error "Scheduler missing/invalid date value in scheduler #{@id}" if not @hour? or isNaN @hour throw new Error "Scheduler missing/invalid hour value in scheduler #{@id}" if not @min? or isNaN @min throw new Error "Scheduler missing/invalid minute value in scheduler #{@id}" @hour = @hour % 24 @min = @min % 60 _nextTime: (Time) -> cur = new Date Time next = new Date cur.getFullYear(), cur.getMonth(), @date, @hour, @min time = next.getTime() if time <= cur.getTime() next.setMonth next.getMonth() + 1 time = next.getTime() return time _lastTime: (Time) -> cur = new Date Time last = new Date cur.getFullYear(), cur.getMonth(), @date, @hour, @min time = last.getTime() if time > cur.getTime() last.setMonth last.getMonth() - 1 time = last.getTime() return time module.exports = (Types) -> Types.monthly = MonthlyScheduler
[ { "context": " maxWidth + 16\n\n # XXX, messy...\n sort: (key='name', order='ascent') ->\n return if not @treeView\n", "end": 6768, "score": 0.7626171112060547, "start": 6764, "tag": "KEY", "value": "name" }, { "context": " aWin = -1\n stringCompFunc = (a, b, key = 'nam...
lib/file-info.coffee
isabella232/tree-view-finder
14
{requirePackages} = require 'atom-utils' fs = require 'fs-plus' module.exports = class FileInfo visible: false debug: false sortKey: 'name' sortOrder: 'ascent' constructor: () -> destroy: -> initialize: -> console.log 'file-info: initialize' if @debug show: (treeView) -> console.log 'file-info: show: treeView =', treeView if @debug return if not treeView @treeView = treeView @visible = true @update() hide: -> console.log 'file-info: hide' if @debug @visible = false @update() @treeView = null update: -> if @treeView? if @visible @add() else @delete() delete:-> console.log 'file-info: delete' if @debug elements = @treeView.element.querySelectorAll '.entry .file-info' for element in elements element.classList.remove('file-info') element.classList.remove('file-info-debug') if @debug elements = @treeView.element.querySelectorAll '.entry .file-info-added' for element in elements element.remove() add: -> console.log 'file-info: add' if @debug @updateWidth() updateWidth: (nameWidth = @nameWidth, sizeWidth = @sizeWidth, mdateWidth = @mdateWidth) -> console.log 'file-info: updateWidth:', nameWidth, sizeWidth, mdateWidth if @debug @nameWidth = nameWidth @sizeWidth = sizeWidth @mdateWidth = mdateWidth if @treeView and @visible ol = @treeView.element.querySelector '.tree-view' if @debug console.log "file-info: updateWidth: querySelector('.tree-view') =", ol, ol.getBoundingClientRect() @offset = ol.getBoundingClientRect().left @fileEntries = @treeView.element.querySelectorAll '.entry' @fileEntryIndex = 0 clearInterval(@timer) console.log 'file-info: update thread...' if @debug console.log 'file-info: update thread...', @updateThread if @debug @timer = setInterval(@updateThread, 1) updateThread: => if not @treeView or not @visible clearInterval(@timer) @timer = null @fileEntries = null return cost = 0 added = 0 while fileEntry = @fileEntries[@fileEntryIndex++] name = fileEntry.querySelector 'span.name' if not name.classList.contains('file-info') added++ name.classList.add('file-info') name.classList.add('file-info-debug') if @debug stat = fs.statSyncNoException(name.dataset.path) padding = document.createElement('span') padding.textContent = '\u00A0' # XXX fileEntry.dataset.name = name.textContent.toLowerCase() # use for sorting padding.classList.add('file-info-added') padding.classList.add('file-info-padding') padding.classList.add('file-info-debug') if @debug name.parentNode.appendChild(padding) size = document.createElement('span') innerSize = document.createElement('span') if fileEntry.classList.contains('file') innerSize.textContent = @toSizeString(stat.size) fileEntry.dataset.size = stat.size # use for sorting else innerSize.textContent = '--' fileEntry.dataset.size = -1 # use for sorting innerSize.classList.add('file-info-inner-size') innerSize.classList.add('file-info-debug') if @debug size.appendChild(innerSize) size.classList.add('file-info-added') size.classList.add('file-info-size') size.classList.add('file-info-debug') if @debug name.parentNode.appendChild(size) date = document.createElement('span') innerDate = document.createElement('span') innerDate.textContent = @toDateString(stat.mtime) fileEntry.dataset.mdate = stat.mtime.getTime() # use for sorting innerDate.classList.add('file-info-inner-mdate') innerDate.classList.add('file-info-debug') if @debug date.appendChild(innerDate) date.classList.add('file-info-added') date.classList.add('file-info-mdate') date.classList.add('file-info-debug') if @debug name.parentNode.appendChild(date) name = fileEntry.querySelector 'span.name' [padding] = name.parentNode.querySelectorAll '.file-info-padding' [size] = name.parentNode.querySelectorAll '.file-info-size' [mdate] = name.parentNode.querySelectorAll '.file-info-mdate' rect = name.getBoundingClientRect() margin = @nameWidth - (rect.left - @offset + rect.width) if margin < 10 padding.style.marginRight = margin + 'px' padding.style.width = '0px' else padding.style.marginRight = '0px' padding.style.width = margin + 'px' if @debug console.log 'file-info: updateWidth:', @fileEntryIndex-1 + ':', padding.style.width, padding.style.marginRight, '(' + @nameWidth + ' - ' + (rect.left - @offset) + ' - ' + rect.width + ')' size.style.width = @sizeWidth + 'px' mdate.style.width = @mdateWidth+ 'px' if 50 < ++cost @sort(@sortKey, @sortOrder) if added return console.log 'file-info: update thread...done' if @debug clearInterval(@timer) @sort(@sortKey, @sortOrder) if added toSizeString: (size) -> if size < 1 return 'Zero bytes' if size < 2 return '1 byte' if size < 1000 return size + ' bytes' if size < 999500 return Math.round(size/1000)/1 + ' KB' if size < 999950000 return Math.round(size/100000)/10 + ' MB' return Math.round(size/10000000)/100 + ' GB' toDateString: (date) -> shortMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] res = new Date(date + '') shortMonth[res.getMonth()] + ' ' + res.getDate() + ', ' + res.getFullYear() + ', ' + res.getHours() + ':' + res.getMinutes() calcOptWidthName: => ol = @treeView.element.querySelector '.tree-view' offset = ol.getBoundingClientRect().left elems = @treeView.element.querySelectorAll '.entry span.name' maxWidth = 0 for elem in elems rect = elem.getBoundingClientRect() width = (rect.left - @offset + rect.width) maxWidth = Math.max(width, maxWidth) maxWidth calcOptWidthSize: => @calcOptWidth '.entry .file-info-inner-size' calcOptWidthMdate: => @calcOptWidth '.entry .file-info-inner-mdate' calcOptWidth: (selector) -> elems = @treeView.element.querySelectorAll selector maxWidth = 0 for elem in elems maxWidth = Math.max(elem.offsetWidth, maxWidth) maxWidth + 16 # XXX, messy... sort: (key='name', order='ascent') -> return if not @treeView @sortKey = key @sortOrder = order if @debug console.log 'file-info: sort:', 'key =', @sortKey, ', order =', @sortOrder ols = @treeView.element.querySelectorAll 'ol.entries.list-tree' for ol in ols # if ol.childNodes.length # console.log '====================', ol, ol.childNodes ar = [] for li in ol.childNodes # console.log li.dataset['name'], 'value =', li.dataset[key] ar.push li for li in ar ol.removeChild(li) if order is 'ascent' bWin = -1 aWin = 1 else bWin = 1 aWin = -1 stringCompFunc = (a, b, key = 'name') -> if a.dataset[key] < b.dataset[key] return bWin if a.dataset[key] > b.dataset[key] return aWin return 0 numberCompFunc = (a, b, key = 'name') -> return (a.dataset[key] - b.dataset[key]) * aWin if key is 'name' ar.sort (a, b) -> stringCompFunc(a, b, key) else ar.sort (a, b) -> if (res = numberCompFunc(a, b, key)) == 0 res = stringCompFunc(a, b, 'name') res for li in ar ol.appendChild(li) ar = null
46614
{requirePackages} = require 'atom-utils' fs = require 'fs-plus' module.exports = class FileInfo visible: false debug: false sortKey: 'name' sortOrder: 'ascent' constructor: () -> destroy: -> initialize: -> console.log 'file-info: initialize' if @debug show: (treeView) -> console.log 'file-info: show: treeView =', treeView if @debug return if not treeView @treeView = treeView @visible = true @update() hide: -> console.log 'file-info: hide' if @debug @visible = false @update() @treeView = null update: -> if @treeView? if @visible @add() else @delete() delete:-> console.log 'file-info: delete' if @debug elements = @treeView.element.querySelectorAll '.entry .file-info' for element in elements element.classList.remove('file-info') element.classList.remove('file-info-debug') if @debug elements = @treeView.element.querySelectorAll '.entry .file-info-added' for element in elements element.remove() add: -> console.log 'file-info: add' if @debug @updateWidth() updateWidth: (nameWidth = @nameWidth, sizeWidth = @sizeWidth, mdateWidth = @mdateWidth) -> console.log 'file-info: updateWidth:', nameWidth, sizeWidth, mdateWidth if @debug @nameWidth = nameWidth @sizeWidth = sizeWidth @mdateWidth = mdateWidth if @treeView and @visible ol = @treeView.element.querySelector '.tree-view' if @debug console.log "file-info: updateWidth: querySelector('.tree-view') =", ol, ol.getBoundingClientRect() @offset = ol.getBoundingClientRect().left @fileEntries = @treeView.element.querySelectorAll '.entry' @fileEntryIndex = 0 clearInterval(@timer) console.log 'file-info: update thread...' if @debug console.log 'file-info: update thread...', @updateThread if @debug @timer = setInterval(@updateThread, 1) updateThread: => if not @treeView or not @visible clearInterval(@timer) @timer = null @fileEntries = null return cost = 0 added = 0 while fileEntry = @fileEntries[@fileEntryIndex++] name = fileEntry.querySelector 'span.name' if not name.classList.contains('file-info') added++ name.classList.add('file-info') name.classList.add('file-info-debug') if @debug stat = fs.statSyncNoException(name.dataset.path) padding = document.createElement('span') padding.textContent = '\u00A0' # XXX fileEntry.dataset.name = name.textContent.toLowerCase() # use for sorting padding.classList.add('file-info-added') padding.classList.add('file-info-padding') padding.classList.add('file-info-debug') if @debug name.parentNode.appendChild(padding) size = document.createElement('span') innerSize = document.createElement('span') if fileEntry.classList.contains('file') innerSize.textContent = @toSizeString(stat.size) fileEntry.dataset.size = stat.size # use for sorting else innerSize.textContent = '--' fileEntry.dataset.size = -1 # use for sorting innerSize.classList.add('file-info-inner-size') innerSize.classList.add('file-info-debug') if @debug size.appendChild(innerSize) size.classList.add('file-info-added') size.classList.add('file-info-size') size.classList.add('file-info-debug') if @debug name.parentNode.appendChild(size) date = document.createElement('span') innerDate = document.createElement('span') innerDate.textContent = @toDateString(stat.mtime) fileEntry.dataset.mdate = stat.mtime.getTime() # use for sorting innerDate.classList.add('file-info-inner-mdate') innerDate.classList.add('file-info-debug') if @debug date.appendChild(innerDate) date.classList.add('file-info-added') date.classList.add('file-info-mdate') date.classList.add('file-info-debug') if @debug name.parentNode.appendChild(date) name = fileEntry.querySelector 'span.name' [padding] = name.parentNode.querySelectorAll '.file-info-padding' [size] = name.parentNode.querySelectorAll '.file-info-size' [mdate] = name.parentNode.querySelectorAll '.file-info-mdate' rect = name.getBoundingClientRect() margin = @nameWidth - (rect.left - @offset + rect.width) if margin < 10 padding.style.marginRight = margin + 'px' padding.style.width = '0px' else padding.style.marginRight = '0px' padding.style.width = margin + 'px' if @debug console.log 'file-info: updateWidth:', @fileEntryIndex-1 + ':', padding.style.width, padding.style.marginRight, '(' + @nameWidth + ' - ' + (rect.left - @offset) + ' - ' + rect.width + ')' size.style.width = @sizeWidth + 'px' mdate.style.width = @mdateWidth+ 'px' if 50 < ++cost @sort(@sortKey, @sortOrder) if added return console.log 'file-info: update thread...done' if @debug clearInterval(@timer) @sort(@sortKey, @sortOrder) if added toSizeString: (size) -> if size < 1 return 'Zero bytes' if size < 2 return '1 byte' if size < 1000 return size + ' bytes' if size < 999500 return Math.round(size/1000)/1 + ' KB' if size < 999950000 return Math.round(size/100000)/10 + ' MB' return Math.round(size/10000000)/100 + ' GB' toDateString: (date) -> shortMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] res = new Date(date + '') shortMonth[res.getMonth()] + ' ' + res.getDate() + ', ' + res.getFullYear() + ', ' + res.getHours() + ':' + res.getMinutes() calcOptWidthName: => ol = @treeView.element.querySelector '.tree-view' offset = ol.getBoundingClientRect().left elems = @treeView.element.querySelectorAll '.entry span.name' maxWidth = 0 for elem in elems rect = elem.getBoundingClientRect() width = (rect.left - @offset + rect.width) maxWidth = Math.max(width, maxWidth) maxWidth calcOptWidthSize: => @calcOptWidth '.entry .file-info-inner-size' calcOptWidthMdate: => @calcOptWidth '.entry .file-info-inner-mdate' calcOptWidth: (selector) -> elems = @treeView.element.querySelectorAll selector maxWidth = 0 for elem in elems maxWidth = Math.max(elem.offsetWidth, maxWidth) maxWidth + 16 # XXX, messy... sort: (key='<KEY>', order='ascent') -> return if not @treeView @sortKey = key @sortOrder = order if @debug console.log 'file-info: sort:', 'key =', @sortKey, ', order =', @sortOrder ols = @treeView.element.querySelectorAll 'ol.entries.list-tree' for ol in ols # if ol.childNodes.length # console.log '====================', ol, ol.childNodes ar = [] for li in ol.childNodes # console.log li.dataset['name'], 'value =', li.dataset[key] ar.push li for li in ar ol.removeChild(li) if order is 'ascent' bWin = -1 aWin = 1 else bWin = 1 aWin = -1 stringCompFunc = (a, b, key = '<KEY>') -> if a.dataset[key] < b.dataset[key] return bWin if a.dataset[key] > b.dataset[key] return aWin return 0 numberCompFunc = (a, b, key = '<KEY>') -> return (a.dataset[key] - b.dataset[key]) * aWin if key is '<KEY>' ar.sort (a, b) -> stringCompFunc(a, b, key) else ar.sort (a, b) -> if (res = numberCompFunc(a, b, key)) == 0 res = stringCompFunc(a, b, 'name') res for li in ar ol.appendChild(li) ar = null
true
{requirePackages} = require 'atom-utils' fs = require 'fs-plus' module.exports = class FileInfo visible: false debug: false sortKey: 'name' sortOrder: 'ascent' constructor: () -> destroy: -> initialize: -> console.log 'file-info: initialize' if @debug show: (treeView) -> console.log 'file-info: show: treeView =', treeView if @debug return if not treeView @treeView = treeView @visible = true @update() hide: -> console.log 'file-info: hide' if @debug @visible = false @update() @treeView = null update: -> if @treeView? if @visible @add() else @delete() delete:-> console.log 'file-info: delete' if @debug elements = @treeView.element.querySelectorAll '.entry .file-info' for element in elements element.classList.remove('file-info') element.classList.remove('file-info-debug') if @debug elements = @treeView.element.querySelectorAll '.entry .file-info-added' for element in elements element.remove() add: -> console.log 'file-info: add' if @debug @updateWidth() updateWidth: (nameWidth = @nameWidth, sizeWidth = @sizeWidth, mdateWidth = @mdateWidth) -> console.log 'file-info: updateWidth:', nameWidth, sizeWidth, mdateWidth if @debug @nameWidth = nameWidth @sizeWidth = sizeWidth @mdateWidth = mdateWidth if @treeView and @visible ol = @treeView.element.querySelector '.tree-view' if @debug console.log "file-info: updateWidth: querySelector('.tree-view') =", ol, ol.getBoundingClientRect() @offset = ol.getBoundingClientRect().left @fileEntries = @treeView.element.querySelectorAll '.entry' @fileEntryIndex = 0 clearInterval(@timer) console.log 'file-info: update thread...' if @debug console.log 'file-info: update thread...', @updateThread if @debug @timer = setInterval(@updateThread, 1) updateThread: => if not @treeView or not @visible clearInterval(@timer) @timer = null @fileEntries = null return cost = 0 added = 0 while fileEntry = @fileEntries[@fileEntryIndex++] name = fileEntry.querySelector 'span.name' if not name.classList.contains('file-info') added++ name.classList.add('file-info') name.classList.add('file-info-debug') if @debug stat = fs.statSyncNoException(name.dataset.path) padding = document.createElement('span') padding.textContent = '\u00A0' # XXX fileEntry.dataset.name = name.textContent.toLowerCase() # use for sorting padding.classList.add('file-info-added') padding.classList.add('file-info-padding') padding.classList.add('file-info-debug') if @debug name.parentNode.appendChild(padding) size = document.createElement('span') innerSize = document.createElement('span') if fileEntry.classList.contains('file') innerSize.textContent = @toSizeString(stat.size) fileEntry.dataset.size = stat.size # use for sorting else innerSize.textContent = '--' fileEntry.dataset.size = -1 # use for sorting innerSize.classList.add('file-info-inner-size') innerSize.classList.add('file-info-debug') if @debug size.appendChild(innerSize) size.classList.add('file-info-added') size.classList.add('file-info-size') size.classList.add('file-info-debug') if @debug name.parentNode.appendChild(size) date = document.createElement('span') innerDate = document.createElement('span') innerDate.textContent = @toDateString(stat.mtime) fileEntry.dataset.mdate = stat.mtime.getTime() # use for sorting innerDate.classList.add('file-info-inner-mdate') innerDate.classList.add('file-info-debug') if @debug date.appendChild(innerDate) date.classList.add('file-info-added') date.classList.add('file-info-mdate') date.classList.add('file-info-debug') if @debug name.parentNode.appendChild(date) name = fileEntry.querySelector 'span.name' [padding] = name.parentNode.querySelectorAll '.file-info-padding' [size] = name.parentNode.querySelectorAll '.file-info-size' [mdate] = name.parentNode.querySelectorAll '.file-info-mdate' rect = name.getBoundingClientRect() margin = @nameWidth - (rect.left - @offset + rect.width) if margin < 10 padding.style.marginRight = margin + 'px' padding.style.width = '0px' else padding.style.marginRight = '0px' padding.style.width = margin + 'px' if @debug console.log 'file-info: updateWidth:', @fileEntryIndex-1 + ':', padding.style.width, padding.style.marginRight, '(' + @nameWidth + ' - ' + (rect.left - @offset) + ' - ' + rect.width + ')' size.style.width = @sizeWidth + 'px' mdate.style.width = @mdateWidth+ 'px' if 50 < ++cost @sort(@sortKey, @sortOrder) if added return console.log 'file-info: update thread...done' if @debug clearInterval(@timer) @sort(@sortKey, @sortOrder) if added toSizeString: (size) -> if size < 1 return 'Zero bytes' if size < 2 return '1 byte' if size < 1000 return size + ' bytes' if size < 999500 return Math.round(size/1000)/1 + ' KB' if size < 999950000 return Math.round(size/100000)/10 + ' MB' return Math.round(size/10000000)/100 + ' GB' toDateString: (date) -> shortMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] res = new Date(date + '') shortMonth[res.getMonth()] + ' ' + res.getDate() + ', ' + res.getFullYear() + ', ' + res.getHours() + ':' + res.getMinutes() calcOptWidthName: => ol = @treeView.element.querySelector '.tree-view' offset = ol.getBoundingClientRect().left elems = @treeView.element.querySelectorAll '.entry span.name' maxWidth = 0 for elem in elems rect = elem.getBoundingClientRect() width = (rect.left - @offset + rect.width) maxWidth = Math.max(width, maxWidth) maxWidth calcOptWidthSize: => @calcOptWidth '.entry .file-info-inner-size' calcOptWidthMdate: => @calcOptWidth '.entry .file-info-inner-mdate' calcOptWidth: (selector) -> elems = @treeView.element.querySelectorAll selector maxWidth = 0 for elem in elems maxWidth = Math.max(elem.offsetWidth, maxWidth) maxWidth + 16 # XXX, messy... sort: (key='PI:KEY:<KEY>END_PI', order='ascent') -> return if not @treeView @sortKey = key @sortOrder = order if @debug console.log 'file-info: sort:', 'key =', @sortKey, ', order =', @sortOrder ols = @treeView.element.querySelectorAll 'ol.entries.list-tree' for ol in ols # if ol.childNodes.length # console.log '====================', ol, ol.childNodes ar = [] for li in ol.childNodes # console.log li.dataset['name'], 'value =', li.dataset[key] ar.push li for li in ar ol.removeChild(li) if order is 'ascent' bWin = -1 aWin = 1 else bWin = 1 aWin = -1 stringCompFunc = (a, b, key = 'PI:KEY:<KEY>END_PI') -> if a.dataset[key] < b.dataset[key] return bWin if a.dataset[key] > b.dataset[key] return aWin return 0 numberCompFunc = (a, b, key = 'PI:KEY:<KEY>END_PI') -> return (a.dataset[key] - b.dataset[key]) * aWin if key is 'PI:KEY:<KEY>END_PI' ar.sort (a, b) -> stringCompFunc(a, b, key) else ar.sort (a, b) -> if (res = numberCompFunc(a, b, key)) == 0 res = stringCompFunc(a, b, 'name') res for li in ar ol.appendChild(li) ar = null
[ { "context": " = @\n\n export: ->\n data = {}\n for key in ['angle']\n data[key] = @[key]\n\n data\n", "end": 271, "score": 0.9609166383743286, "start": 266, "tag": "KEY", "value": "angle" } ]
lib/psd/resources/angle.coffee
aleczratiu/psd.js
0
module.exports = class Angle id: 1037 name: 'angle' constructor: (@resource) -> @file = @resource.file parse: -> # 32-bit fixed-point number (16.16) @angle = @file.readUInt() @resource.data = @ export: -> data = {} for key in ['angle'] data[key] = @[key] data
40496
module.exports = class Angle id: 1037 name: 'angle' constructor: (@resource) -> @file = @resource.file parse: -> # 32-bit fixed-point number (16.16) @angle = @file.readUInt() @resource.data = @ export: -> data = {} for key in ['<KEY>'] data[key] = @[key] data
true
module.exports = class Angle id: 1037 name: 'angle' constructor: (@resource) -> @file = @resource.file parse: -> # 32-bit fixed-point number (16.16) @angle = @file.readUInt() @resource.data = @ export: -> data = {} for key in ['PI:KEY:<KEY>END_PI'] data[key] = @[key] data
[ { "context": " = \"http://api.bilibili.com/view?type=json&appkey=12737ff7776f1ade&id=\" + _params[2] + if _params[3] isnt undefined ", "end": 4101, "score": 0.9992948770523071, "start": 4085, "tag": "KEY", "value": "12737ff7776f1ade" } ]
coffee/heikeji.coffee
daiyeqi/bilibili_hkj
3
((d,w) -> @_c_tip = (elem, tips...) -> callout = d.createElement("div") callout.className = "tip" for tip in tips _p = d.createElement("p") _p.innerHTML = tip callout.appendChild _p elem.appendChild callout __hidden callout, 5000 @_c_message = (elem, title, url, messages...) -> callout = d.createElement("div") callout.className = "message" _h4 = d.createElement("h4") _a = d.createElement("a") _a.innerHTML = title _a.href = url _a.target = "_blank" _h4.appendChild _a callout.appendChild _h4 for message in messages _p = d.createElement("p") _p.innerHTML = message callout.appendChild _p elem.appendChild callout __hidden callout, 20000 @__hidden = (elem, sleep) -> setTimeout(-> opacity = 1 pid = setInterval(-> opacity -= 0.01 elem.style.opacity = opacity if opacity < 0 w.clearInterval pid elem.parentNode.removeChild elem , 20) , sleep) # 判断是否是b站, 非b站连接不执行 _params = /http:\/\/(www\.bilibili\.com|www\.bilibili\.tv|bilibili\.kankanews\.com)?\/video\/av([0-9]+)\/(?:index_([0-9]+)\.html)?/.exec(d.URL) _b_url_r = (/http:\/\/(www\.bilibili\.com|www\.bilibili\.tv|bilibili\.kankanews\.com)/.exec(d.URL)) tpModel = !_params && !!_b_url_r _bilibili_url = if !_b_url_r then null else _b_url_r[0] head = d.getElementsByTagName("head")[0] style = d.createElement "style" style.type = "text/css" style.appendChild d.createTextNode(""" #_callouts { position: fixed; right: 16px; bottom: 32px; z-index: 999; } #_callouts div { position: relative; margin: 10px 0; padding: 7px 15px 7px 12px; text-align:left; border-left:5px solid #eee; font: 13px/1.65 "Segoe UI", "Helvetica Neue", Helvetica, Arial, "Hiragino Kaku Gothic Pro", "Meiryo", "Hiragino Sans GB", "Microsoft YaHei", "STHeiti", "SimSun", Sans-serif; z-index: 999; } #_callouts div p, #_callouts div h4 { margin: 0; } #_callouts div.message { background-color: #fdf7f7; border-color: #d9534f; } #_callouts div.message h4, #_callouts div.message h4 * { color: #d9534f; text-decoration: none; } #_callouts div.tip { background-color: #f4f8fa; border-color: #5bc0de; } """) head.appendChild style callouts = d.createElement "div" callouts.id = "_callouts" d.body.appendChild callouts if !_params && !tpModel (w.bilibili_hkj =-> _c_tip callouts, "痴萝莉, 爱腐女", "控锁骨, 恋百合" )() return # 显示公告 messageExpires = (new Date("2014/10/6")).getTime() + 15 * 1000 * 3600 * 24 if new Date().getTime() - messageExpires < 0 _c_message callouts, "修复新版bilibili下2P模式失效问题", "http://keyfunc.github.io/bilibili_hkj/", "重构部分代码,增加异常处理" # 初始化相关方法与组件 jQueryVersion = "1.11.1" @Loader = importJS: (url, head, func) -> script = d.createElement "script" script.type = "text/javascript" script.onload =-> console.log "onLoad: " + url if func isnt undefined func() script.src = url head.appendChild script importCSS: (url, head, func) -> css = d.createElement "link" css.type = "text/css" css.rel = "stylesheet" css.onload =-> console.log "onLoad: " + url if func isnt undefined func() css.href = url head.appendChild css # 判断是否需要重新加载jQuery loadjQuery = yes if w.jQuery isnt undefined version = jQueryVersion.split "." current_version = $.fn.jquery.split "." for v, i in current_version v = parseInt v _v = parseInt version[i] if v < _v _$ = jQuery.noConflict() console.log "jQuery version: " + _$.fn.jquery + " --> " + jQueryVersion loadjQuery = yes break else if v > _v loadjQuery = no break else loadjQuery = no # 正常体位 normalModel = (_params) -> api = "http://api.bilibili.com/view?type=json&appkey=12737ff7776f1ade&id=" + _params[2] + if _params[3] isnt undefined then "&page=" + _params[3] else "" url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url=%22" + encodeURIComponent(api) + "%22&format=json&callback=cbfunc" # bofqi = d.getElementById "bofqi" # bofqi.innerHTML = "" $("#bofqi").empty() $("#bofqi").append("<div id='player_placeholder' class='player'></div>") _c_tip callouts, "成功干掉原先的播放器" jsonp = d.createElement "script" jsonp.setAttribute "src", url jsonp.onload =-> this.parentNode.removeChild this jsonp = null head.appendChild jsonp (w.bilibili_hkj =-> _c_tip callouts, "正在获取神秘代码" )() return # 主要执行逻辑函数 blhkj_main =-> # 2P模式 if tpModel $("a[href*='/video/av']").click (event) -> event.preventDefault() _params = /(\/video|video)\/av([0-9]+)?/.exec($(this).attr("href")) _title = $(this).text() $(".z").remove() $z = $("<div class=\"z\"></div>") $(".header").after($z) $z.load _bilibili_url + "/video/av877489/ .z:first", -> try $(".cover_image", $z).hide() $(".tminfo span[typeof='v:Breadcrumb']", $z).remove() $(".tminfo time", $z).remove() #$("#assdown", $z).attr("href", $("#assdown", $z).attr("href").replace("877489", _params[2])) $(".info .fav_btn_top", $z).attr("onclick", $(".info .fav_btn_top", $z).attr("onclick").replace("877489", _params[2])) $(".arc-tool-bar .fav a", $z).attr("href", $(".arc-tool-bar .fav a", $z).attr("href").replace("877489", _params[2])) $(".arc-tool-bar .fav a", $z).attr("onclick", $(".arc-tool-bar .fav a", $z).attr("onclick").replace("877489", _params[2])) $(".ad-f", $z).remove() $(".ad-e1", $z).remove() $(".ad-e2", $z).remove() #$(".ad-e3", $z).remove() #$(".ad-e4", $z).remove() $(".info h2", $z).text("").attr("title", "") $(".intro", $z).text("") $(".common .comm img", $z).attr("onclick", $(".common .comm img", $z).attr("onclick").replace("877489", _params[2])) $("#newtag a", $z).attr("onclick", $("#newtag a", $z).attr("onclick").replace("877489", _params[2])) $("#rate_frm", $z).attr("aid", _params[2]) catch error console.log error if w.history.pushState isnt undefined w.history.pushState(null, _title, _bilibili_url + "/video/av" + _params[2]) Loader.importJS 'http://static.hdslb.com/js/page.arc.js', head Loader.importJS 'http://static.hdslb.com/js/jquery.qrcode.min.js', head Loader.importJS 'http://interface.bilibili.cn/count?aid=' + _params[2], head Loader.importJS 'http://static.hdslb.com/js/swfobject.js', head Loader.importJS 'http://static.hdslb.com/js/video.min.js', head Loader.importCSS 'http://static.hdslb.com/css/bpoint/bpoints.css', head Loader.importJS 'http://static.hdslb.com/js/bpoint/bpoints.js', head normalModel _params $(w).on("popstate", (event) -> w.location.replace d.location ) (w.bilibili_hkj =-> _c_tip callouts, "2P模式初始化完成", "\(・ω・\)丧尸!(/・ω・)/bishi" )() return else if !!d.getElementById("player_placeholder") or !!d.getElementById("bofqi_embed") or (-> iframes = d.getElementsByTagName "iframe" iframePlay = /https:\/\/secure\.bilibili\.com\/secure,cid=([0-9]+)(?:&aid=([0-9]+))?/ for key of iframes if !!iframePlay.exec(iframes[key].src) return yes return no )() (w.bilibili_hkj =-> _c_tip callouts, "bilibili满状态中", "\(・ω・\)丧尸!(/・ω・)/bishi" )() return normalModel(_params) # 回调函数 @cbfunc =-> info = arguments[0].query.results.json if info.cid isnt undefined _c_tip callouts, "获取神秘代码成功", "神秘代码ID: " + info.cid if tpModel $(".info h2").text(info.title).attr("title", info.title) $(".intro").text(info.description) @mid = info.mid kwtags(info.tag.split(","), "") $("title").text(info.title) EmbedPlayer('player', "http://static.hdslb.com/play.swf", "cid=" + info.cid + "&aid=" + _params[2]) # iframe = d.createElement("iframe") # iframe.height = 482 # iframe.width = 950 # iframe.src = "https://secure.bilibili.com/secure,cid=" + info.cid + "&amp;aid="+ _params[2] # iframe.setAttribute "class", "player" # iframe.setAttribute "border", 0 # iframe.setAttribute "scrolling", "no" # iframe.setAttribute "frameborder", "no" # iframe.setAttribute "framespacing", 0 # bofqi.appendChild iframe # # #增加iframe通讯功能 # if w.postMessage # onMessage = (e) -> # if e.origin is "https://secure.bilibili.com" and e.data.substr(0, 6) is "secJS:" # eval e.data.substr(6) # if w.addEventListener # w.addEventListener "message", onMessage, false # else if w.attachEvent # w.attachEvent "onmessage", onMessage # # else # setInterval(-> # if evalCode = __GetCookie '__secureJS' # __SetCookie '__secureJS', '' # eval evalCode # , 1000) (w.bilibili_hkj =-> _c_tip callouts, "Mission Completed", "嗶哩嗶哩 - ( ゜- ゜)つロ 乾杯~" )() else _c_tip callouts, "非常抱歉, bishi姥爷不肯给神秘代码", "要不你吼一声\"兵库北\"后再试试?" w.bilibili_hkj = null # 同步加载jQuery if loadjQuery Loader.importJS 'http://keyfunc.github.io/bilibili_hkj/assets/js/jquery-' + jQueryVersion + '.min.js', head, blhkj_main else blhkj_main() )(document, window)
170262
((d,w) -> @_c_tip = (elem, tips...) -> callout = d.createElement("div") callout.className = "tip" for tip in tips _p = d.createElement("p") _p.innerHTML = tip callout.appendChild _p elem.appendChild callout __hidden callout, 5000 @_c_message = (elem, title, url, messages...) -> callout = d.createElement("div") callout.className = "message" _h4 = d.createElement("h4") _a = d.createElement("a") _a.innerHTML = title _a.href = url _a.target = "_blank" _h4.appendChild _a callout.appendChild _h4 for message in messages _p = d.createElement("p") _p.innerHTML = message callout.appendChild _p elem.appendChild callout __hidden callout, 20000 @__hidden = (elem, sleep) -> setTimeout(-> opacity = 1 pid = setInterval(-> opacity -= 0.01 elem.style.opacity = opacity if opacity < 0 w.clearInterval pid elem.parentNode.removeChild elem , 20) , sleep) # 判断是否是b站, 非b站连接不执行 _params = /http:\/\/(www\.bilibili\.com|www\.bilibili\.tv|bilibili\.kankanews\.com)?\/video\/av([0-9]+)\/(?:index_([0-9]+)\.html)?/.exec(d.URL) _b_url_r = (/http:\/\/(www\.bilibili\.com|www\.bilibili\.tv|bilibili\.kankanews\.com)/.exec(d.URL)) tpModel = !_params && !!_b_url_r _bilibili_url = if !_b_url_r then null else _b_url_r[0] head = d.getElementsByTagName("head")[0] style = d.createElement "style" style.type = "text/css" style.appendChild d.createTextNode(""" #_callouts { position: fixed; right: 16px; bottom: 32px; z-index: 999; } #_callouts div { position: relative; margin: 10px 0; padding: 7px 15px 7px 12px; text-align:left; border-left:5px solid #eee; font: 13px/1.65 "Segoe UI", "Helvetica Neue", Helvetica, Arial, "Hiragino Kaku Gothic Pro", "Meiryo", "Hiragino Sans GB", "Microsoft YaHei", "STHeiti", "SimSun", Sans-serif; z-index: 999; } #_callouts div p, #_callouts div h4 { margin: 0; } #_callouts div.message { background-color: #fdf7f7; border-color: #d9534f; } #_callouts div.message h4, #_callouts div.message h4 * { color: #d9534f; text-decoration: none; } #_callouts div.tip { background-color: #f4f8fa; border-color: #5bc0de; } """) head.appendChild style callouts = d.createElement "div" callouts.id = "_callouts" d.body.appendChild callouts if !_params && !tpModel (w.bilibili_hkj =-> _c_tip callouts, "痴萝莉, 爱腐女", "控锁骨, 恋百合" )() return # 显示公告 messageExpires = (new Date("2014/10/6")).getTime() + 15 * 1000 * 3600 * 24 if new Date().getTime() - messageExpires < 0 _c_message callouts, "修复新版bilibili下2P模式失效问题", "http://keyfunc.github.io/bilibili_hkj/", "重构部分代码,增加异常处理" # 初始化相关方法与组件 jQueryVersion = "1.11.1" @Loader = importJS: (url, head, func) -> script = d.createElement "script" script.type = "text/javascript" script.onload =-> console.log "onLoad: " + url if func isnt undefined func() script.src = url head.appendChild script importCSS: (url, head, func) -> css = d.createElement "link" css.type = "text/css" css.rel = "stylesheet" css.onload =-> console.log "onLoad: " + url if func isnt undefined func() css.href = url head.appendChild css # 判断是否需要重新加载jQuery loadjQuery = yes if w.jQuery isnt undefined version = jQueryVersion.split "." current_version = $.fn.jquery.split "." for v, i in current_version v = parseInt v _v = parseInt version[i] if v < _v _$ = jQuery.noConflict() console.log "jQuery version: " + _$.fn.jquery + " --> " + jQueryVersion loadjQuery = yes break else if v > _v loadjQuery = no break else loadjQuery = no # 正常体位 normalModel = (_params) -> api = "http://api.bilibili.com/view?type=json&appkey=<KEY>&id=" + _params[2] + if _params[3] isnt undefined then "&page=" + _params[3] else "" url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url=%22" + encodeURIComponent(api) + "%22&format=json&callback=cbfunc" # bofqi = d.getElementById "bofqi" # bofqi.innerHTML = "" $("#bofqi").empty() $("#bofqi").append("<div id='player_placeholder' class='player'></div>") _c_tip callouts, "成功干掉原先的播放器" jsonp = d.createElement "script" jsonp.setAttribute "src", url jsonp.onload =-> this.parentNode.removeChild this jsonp = null head.appendChild jsonp (w.bilibili_hkj =-> _c_tip callouts, "正在获取神秘代码" )() return # 主要执行逻辑函数 blhkj_main =-> # 2P模式 if tpModel $("a[href*='/video/av']").click (event) -> event.preventDefault() _params = /(\/video|video)\/av([0-9]+)?/.exec($(this).attr("href")) _title = $(this).text() $(".z").remove() $z = $("<div class=\"z\"></div>") $(".header").after($z) $z.load _bilibili_url + "/video/av877489/ .z:first", -> try $(".cover_image", $z).hide() $(".tminfo span[typeof='v:Breadcrumb']", $z).remove() $(".tminfo time", $z).remove() #$("#assdown", $z).attr("href", $("#assdown", $z).attr("href").replace("877489", _params[2])) $(".info .fav_btn_top", $z).attr("onclick", $(".info .fav_btn_top", $z).attr("onclick").replace("877489", _params[2])) $(".arc-tool-bar .fav a", $z).attr("href", $(".arc-tool-bar .fav a", $z).attr("href").replace("877489", _params[2])) $(".arc-tool-bar .fav a", $z).attr("onclick", $(".arc-tool-bar .fav a", $z).attr("onclick").replace("877489", _params[2])) $(".ad-f", $z).remove() $(".ad-e1", $z).remove() $(".ad-e2", $z).remove() #$(".ad-e3", $z).remove() #$(".ad-e4", $z).remove() $(".info h2", $z).text("").attr("title", "") $(".intro", $z).text("") $(".common .comm img", $z).attr("onclick", $(".common .comm img", $z).attr("onclick").replace("877489", _params[2])) $("#newtag a", $z).attr("onclick", $("#newtag a", $z).attr("onclick").replace("877489", _params[2])) $("#rate_frm", $z).attr("aid", _params[2]) catch error console.log error if w.history.pushState isnt undefined w.history.pushState(null, _title, _bilibili_url + "/video/av" + _params[2]) Loader.importJS 'http://static.hdslb.com/js/page.arc.js', head Loader.importJS 'http://static.hdslb.com/js/jquery.qrcode.min.js', head Loader.importJS 'http://interface.bilibili.cn/count?aid=' + _params[2], head Loader.importJS 'http://static.hdslb.com/js/swfobject.js', head Loader.importJS 'http://static.hdslb.com/js/video.min.js', head Loader.importCSS 'http://static.hdslb.com/css/bpoint/bpoints.css', head Loader.importJS 'http://static.hdslb.com/js/bpoint/bpoints.js', head normalModel _params $(w).on("popstate", (event) -> w.location.replace d.location ) (w.bilibili_hkj =-> _c_tip callouts, "2P模式初始化完成", "\(・ω・\)丧尸!(/・ω・)/bishi" )() return else if !!d.getElementById("player_placeholder") or !!d.getElementById("bofqi_embed") or (-> iframes = d.getElementsByTagName "iframe" iframePlay = /https:\/\/secure\.bilibili\.com\/secure,cid=([0-9]+)(?:&aid=([0-9]+))?/ for key of iframes if !!iframePlay.exec(iframes[key].src) return yes return no )() (w.bilibili_hkj =-> _c_tip callouts, "bilibili满状态中", "\(・ω・\)丧尸!(/・ω・)/bishi" )() return normalModel(_params) # 回调函数 @cbfunc =-> info = arguments[0].query.results.json if info.cid isnt undefined _c_tip callouts, "获取神秘代码成功", "神秘代码ID: " + info.cid if tpModel $(".info h2").text(info.title).attr("title", info.title) $(".intro").text(info.description) @mid = info.mid kwtags(info.tag.split(","), "") $("title").text(info.title) EmbedPlayer('player', "http://static.hdslb.com/play.swf", "cid=" + info.cid + "&aid=" + _params[2]) # iframe = d.createElement("iframe") # iframe.height = 482 # iframe.width = 950 # iframe.src = "https://secure.bilibili.com/secure,cid=" + info.cid + "&amp;aid="+ _params[2] # iframe.setAttribute "class", "player" # iframe.setAttribute "border", 0 # iframe.setAttribute "scrolling", "no" # iframe.setAttribute "frameborder", "no" # iframe.setAttribute "framespacing", 0 # bofqi.appendChild iframe # # #增加iframe通讯功能 # if w.postMessage # onMessage = (e) -> # if e.origin is "https://secure.bilibili.com" and e.data.substr(0, 6) is "secJS:" # eval e.data.substr(6) # if w.addEventListener # w.addEventListener "message", onMessage, false # else if w.attachEvent # w.attachEvent "onmessage", onMessage # # else # setInterval(-> # if evalCode = __GetCookie '__secureJS' # __SetCookie '__secureJS', '' # eval evalCode # , 1000) (w.bilibili_hkj =-> _c_tip callouts, "Mission Completed", "嗶哩嗶哩 - ( ゜- ゜)つロ 乾杯~" )() else _c_tip callouts, "非常抱歉, bishi姥爷不肯给神秘代码", "要不你吼一声\"兵库北\"后再试试?" w.bilibili_hkj = null # 同步加载jQuery if loadjQuery Loader.importJS 'http://keyfunc.github.io/bilibili_hkj/assets/js/jquery-' + jQueryVersion + '.min.js', head, blhkj_main else blhkj_main() )(document, window)
true
((d,w) -> @_c_tip = (elem, tips...) -> callout = d.createElement("div") callout.className = "tip" for tip in tips _p = d.createElement("p") _p.innerHTML = tip callout.appendChild _p elem.appendChild callout __hidden callout, 5000 @_c_message = (elem, title, url, messages...) -> callout = d.createElement("div") callout.className = "message" _h4 = d.createElement("h4") _a = d.createElement("a") _a.innerHTML = title _a.href = url _a.target = "_blank" _h4.appendChild _a callout.appendChild _h4 for message in messages _p = d.createElement("p") _p.innerHTML = message callout.appendChild _p elem.appendChild callout __hidden callout, 20000 @__hidden = (elem, sleep) -> setTimeout(-> opacity = 1 pid = setInterval(-> opacity -= 0.01 elem.style.opacity = opacity if opacity < 0 w.clearInterval pid elem.parentNode.removeChild elem , 20) , sleep) # 判断是否是b站, 非b站连接不执行 _params = /http:\/\/(www\.bilibili\.com|www\.bilibili\.tv|bilibili\.kankanews\.com)?\/video\/av([0-9]+)\/(?:index_([0-9]+)\.html)?/.exec(d.URL) _b_url_r = (/http:\/\/(www\.bilibili\.com|www\.bilibili\.tv|bilibili\.kankanews\.com)/.exec(d.URL)) tpModel = !_params && !!_b_url_r _bilibili_url = if !_b_url_r then null else _b_url_r[0] head = d.getElementsByTagName("head")[0] style = d.createElement "style" style.type = "text/css" style.appendChild d.createTextNode(""" #_callouts { position: fixed; right: 16px; bottom: 32px; z-index: 999; } #_callouts div { position: relative; margin: 10px 0; padding: 7px 15px 7px 12px; text-align:left; border-left:5px solid #eee; font: 13px/1.65 "Segoe UI", "Helvetica Neue", Helvetica, Arial, "Hiragino Kaku Gothic Pro", "Meiryo", "Hiragino Sans GB", "Microsoft YaHei", "STHeiti", "SimSun", Sans-serif; z-index: 999; } #_callouts div p, #_callouts div h4 { margin: 0; } #_callouts div.message { background-color: #fdf7f7; border-color: #d9534f; } #_callouts div.message h4, #_callouts div.message h4 * { color: #d9534f; text-decoration: none; } #_callouts div.tip { background-color: #f4f8fa; border-color: #5bc0de; } """) head.appendChild style callouts = d.createElement "div" callouts.id = "_callouts" d.body.appendChild callouts if !_params && !tpModel (w.bilibili_hkj =-> _c_tip callouts, "痴萝莉, 爱腐女", "控锁骨, 恋百合" )() return # 显示公告 messageExpires = (new Date("2014/10/6")).getTime() + 15 * 1000 * 3600 * 24 if new Date().getTime() - messageExpires < 0 _c_message callouts, "修复新版bilibili下2P模式失效问题", "http://keyfunc.github.io/bilibili_hkj/", "重构部分代码,增加异常处理" # 初始化相关方法与组件 jQueryVersion = "1.11.1" @Loader = importJS: (url, head, func) -> script = d.createElement "script" script.type = "text/javascript" script.onload =-> console.log "onLoad: " + url if func isnt undefined func() script.src = url head.appendChild script importCSS: (url, head, func) -> css = d.createElement "link" css.type = "text/css" css.rel = "stylesheet" css.onload =-> console.log "onLoad: " + url if func isnt undefined func() css.href = url head.appendChild css # 判断是否需要重新加载jQuery loadjQuery = yes if w.jQuery isnt undefined version = jQueryVersion.split "." current_version = $.fn.jquery.split "." for v, i in current_version v = parseInt v _v = parseInt version[i] if v < _v _$ = jQuery.noConflict() console.log "jQuery version: " + _$.fn.jquery + " --> " + jQueryVersion loadjQuery = yes break else if v > _v loadjQuery = no break else loadjQuery = no # 正常体位 normalModel = (_params) -> api = "http://api.bilibili.com/view?type=json&appkey=PI:KEY:<KEY>END_PI&id=" + _params[2] + if _params[3] isnt undefined then "&page=" + _params[3] else "" url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url=%22" + encodeURIComponent(api) + "%22&format=json&callback=cbfunc" # bofqi = d.getElementById "bofqi" # bofqi.innerHTML = "" $("#bofqi").empty() $("#bofqi").append("<div id='player_placeholder' class='player'></div>") _c_tip callouts, "成功干掉原先的播放器" jsonp = d.createElement "script" jsonp.setAttribute "src", url jsonp.onload =-> this.parentNode.removeChild this jsonp = null head.appendChild jsonp (w.bilibili_hkj =-> _c_tip callouts, "正在获取神秘代码" )() return # 主要执行逻辑函数 blhkj_main =-> # 2P模式 if tpModel $("a[href*='/video/av']").click (event) -> event.preventDefault() _params = /(\/video|video)\/av([0-9]+)?/.exec($(this).attr("href")) _title = $(this).text() $(".z").remove() $z = $("<div class=\"z\"></div>") $(".header").after($z) $z.load _bilibili_url + "/video/av877489/ .z:first", -> try $(".cover_image", $z).hide() $(".tminfo span[typeof='v:Breadcrumb']", $z).remove() $(".tminfo time", $z).remove() #$("#assdown", $z).attr("href", $("#assdown", $z).attr("href").replace("877489", _params[2])) $(".info .fav_btn_top", $z).attr("onclick", $(".info .fav_btn_top", $z).attr("onclick").replace("877489", _params[2])) $(".arc-tool-bar .fav a", $z).attr("href", $(".arc-tool-bar .fav a", $z).attr("href").replace("877489", _params[2])) $(".arc-tool-bar .fav a", $z).attr("onclick", $(".arc-tool-bar .fav a", $z).attr("onclick").replace("877489", _params[2])) $(".ad-f", $z).remove() $(".ad-e1", $z).remove() $(".ad-e2", $z).remove() #$(".ad-e3", $z).remove() #$(".ad-e4", $z).remove() $(".info h2", $z).text("").attr("title", "") $(".intro", $z).text("") $(".common .comm img", $z).attr("onclick", $(".common .comm img", $z).attr("onclick").replace("877489", _params[2])) $("#newtag a", $z).attr("onclick", $("#newtag a", $z).attr("onclick").replace("877489", _params[2])) $("#rate_frm", $z).attr("aid", _params[2]) catch error console.log error if w.history.pushState isnt undefined w.history.pushState(null, _title, _bilibili_url + "/video/av" + _params[2]) Loader.importJS 'http://static.hdslb.com/js/page.arc.js', head Loader.importJS 'http://static.hdslb.com/js/jquery.qrcode.min.js', head Loader.importJS 'http://interface.bilibili.cn/count?aid=' + _params[2], head Loader.importJS 'http://static.hdslb.com/js/swfobject.js', head Loader.importJS 'http://static.hdslb.com/js/video.min.js', head Loader.importCSS 'http://static.hdslb.com/css/bpoint/bpoints.css', head Loader.importJS 'http://static.hdslb.com/js/bpoint/bpoints.js', head normalModel _params $(w).on("popstate", (event) -> w.location.replace d.location ) (w.bilibili_hkj =-> _c_tip callouts, "2P模式初始化完成", "\(・ω・\)丧尸!(/・ω・)/bishi" )() return else if !!d.getElementById("player_placeholder") or !!d.getElementById("bofqi_embed") or (-> iframes = d.getElementsByTagName "iframe" iframePlay = /https:\/\/secure\.bilibili\.com\/secure,cid=([0-9]+)(?:&aid=([0-9]+))?/ for key of iframes if !!iframePlay.exec(iframes[key].src) return yes return no )() (w.bilibili_hkj =-> _c_tip callouts, "bilibili满状态中", "\(・ω・\)丧尸!(/・ω・)/bishi" )() return normalModel(_params) # 回调函数 @cbfunc =-> info = arguments[0].query.results.json if info.cid isnt undefined _c_tip callouts, "获取神秘代码成功", "神秘代码ID: " + info.cid if tpModel $(".info h2").text(info.title).attr("title", info.title) $(".intro").text(info.description) @mid = info.mid kwtags(info.tag.split(","), "") $("title").text(info.title) EmbedPlayer('player', "http://static.hdslb.com/play.swf", "cid=" + info.cid + "&aid=" + _params[2]) # iframe = d.createElement("iframe") # iframe.height = 482 # iframe.width = 950 # iframe.src = "https://secure.bilibili.com/secure,cid=" + info.cid + "&amp;aid="+ _params[2] # iframe.setAttribute "class", "player" # iframe.setAttribute "border", 0 # iframe.setAttribute "scrolling", "no" # iframe.setAttribute "frameborder", "no" # iframe.setAttribute "framespacing", 0 # bofqi.appendChild iframe # # #增加iframe通讯功能 # if w.postMessage # onMessage = (e) -> # if e.origin is "https://secure.bilibili.com" and e.data.substr(0, 6) is "secJS:" # eval e.data.substr(6) # if w.addEventListener # w.addEventListener "message", onMessage, false # else if w.attachEvent # w.attachEvent "onmessage", onMessage # # else # setInterval(-> # if evalCode = __GetCookie '__secureJS' # __SetCookie '__secureJS', '' # eval evalCode # , 1000) (w.bilibili_hkj =-> _c_tip callouts, "Mission Completed", "嗶哩嗶哩 - ( ゜- ゜)つロ 乾杯~" )() else _c_tip callouts, "非常抱歉, bishi姥爷不肯给神秘代码", "要不你吼一声\"兵库北\"后再试试?" w.bilibili_hkj = null # 同步加载jQuery if loadjQuery Loader.importJS 'http://keyfunc.github.io/bilibili_hkj/assets/js/jquery-' + jQueryVersion + '.min.js', head, blhkj_main else blhkj_main() )(document, window)
[ { "context": "cDWVVE9n1G6EE8U2vyy')\ncurrentRoomID = 0\nusername = ''\nuserID = 0\nrooms = {} \n# rooms -> key = roomID, v", "end": 127, "score": 0.8753162026405334, "start": 127, "tag": "USERNAME", "value": "" }, { "context": "ring('utf8'))\n\ncreateName = (name) ->\n username = na...
chat_api.coffee
agilgur5/DeChat
8
crypto = require('crypto') comm = new Icecomm('5icHQ35/1XMHZM3UJF4MoPNh/lWhScDWVVE9n1G6EE8U2vyy') currentRoomID = 0 username = '' userID = 0 rooms = {} # rooms -> key = roomID, value = {users, channels} # channels -> key = channelName, value = [messages] # messages -> {text, callerID} # users -> key = callerID, value = {stream, name} # encrypt data encrypt = (data) -> return JSON.stringify(data)#crypto.publicEncrypt(currentRoomID, new Buffer(JSON.stringify(data), 'utf8')) # decrypt data decrypt = (data) -> return JSON.parse(data)#JSON.parse(crypto.privateDecrypt(currentRoomID, data).toString('utf8')) createName = (name) -> username = name # add a chat room locally (helper) addLocalChatRoom = (roomID) -> # create channel dict in room + message array in channel if !rooms[roomID]? rooms[roomID] = {"users": {}, "channels": {"default": []}} # create a chat room createChatRoom = () -> currentRoomID = crypto.randomBytes(20).toString('hex') addLocalChatRoom(currentRoomID) comm.connect(currentRoomID) # join a chat room joinChatRoom = (roomID) -> currentRoomID = roomID addLocalChatRoom(currentRoomID) comm.connect(currentRoomID) # add a channel locally (helper) addLocalChannel = (channelName) -> # create message array in channel if !rooms[currentRoomID].channels[channelName]? rooms[currentRoomID].channels[channelName] = [] # create a channel createChannel = (channelName) -> addLocalChannel(channelName) comm.send(encrypt({channel: channelName})) # add a message locally (helper) addLocalMessage = (message, channelName, callerID) -> addLocalChannel(channelName) rooms[currentRoomID].channels[channelName].push({text: message, callerID: callerID}) # send a message createMessage = (messageText, channelName) -> channel = channelName || "default" addLocalMessage(messageText, channel, userID) comm.send(encrypt({channel: channel, message: messageText})) # add a local user's name (helper) addLocalUserName = (name, callerID) -> rooms[currentRoomID].users[callerID].name = name # receive a message receiveData = (options) -> console.log options data = decrypt(options.data) callerID = options.callerID # decode the data stream if data.message? addLocalMessage(data.message, data.channel, callerID) else if data.channel? addLocalChannel(data.channel) else addLocalUserName(data.name, callerID) addLocalUser = (stream, callerID) -> rooms[currentRoomID].users[callerID] = {stream: stream, name: ""} # receive a connection receiveConnection = (options) -> addLocalUser(options.stream, options.callerID) comm.send(encrypt({name: username})) # TODO: Flux the rooms variable and possibly username/userID/currentRoomID comm.on('data', receiveData) comm.on('connected', receiveConnection) createName("Anton") joinChatRoom("87d5d3539c0e4743d1825afb5be3cffb1e49605d") #userID = comm.getLocalID() module.exports = { currentRoomID: currentRoomID username: username userID: userID rooms: rooms createName: createName createChatRoom: createChatRoom joinChatRoom: joinChatRoom createChannel: createChannel createMessage: createMessage }
115879
crypto = require('crypto') comm = new Icecomm('5icHQ35/1XMHZM3UJF4MoPNh/lWhScDWVVE9n1G6EE8U2vyy') currentRoomID = 0 username = '' userID = 0 rooms = {} # rooms -> key = roomID, value = {users, channels} # channels -> key = channelName, value = [messages] # messages -> {text, callerID} # users -> key = callerID, value = {stream, name} # encrypt data encrypt = (data) -> return JSON.stringify(data)#crypto.publicEncrypt(currentRoomID, new Buffer(JSON.stringify(data), 'utf8')) # decrypt data decrypt = (data) -> return JSON.parse(data)#JSON.parse(crypto.privateDecrypt(currentRoomID, data).toString('utf8')) createName = (name) -> username = name # add a chat room locally (helper) addLocalChatRoom = (roomID) -> # create channel dict in room + message array in channel if !rooms[roomID]? rooms[roomID] = {"users": {}, "channels": {"default": []}} # create a chat room createChatRoom = () -> currentRoomID = crypto.randomBytes(20).toString('hex') addLocalChatRoom(currentRoomID) comm.connect(currentRoomID) # join a chat room joinChatRoom = (roomID) -> currentRoomID = roomID addLocalChatRoom(currentRoomID) comm.connect(currentRoomID) # add a channel locally (helper) addLocalChannel = (channelName) -> # create message array in channel if !rooms[currentRoomID].channels[channelName]? rooms[currentRoomID].channels[channelName] = [] # create a channel createChannel = (channelName) -> addLocalChannel(channelName) comm.send(encrypt({channel: channelName})) # add a message locally (helper) addLocalMessage = (message, channelName, callerID) -> addLocalChannel(channelName) rooms[currentRoomID].channels[channelName].push({text: message, callerID: callerID}) # send a message createMessage = (messageText, channelName) -> channel = channelName || "default" addLocalMessage(messageText, channel, userID) comm.send(encrypt({channel: channel, message: messageText})) # add a local user's name (helper) addLocalUserName = (name, callerID) -> rooms[currentRoomID].users[callerID].name = name # receive a message receiveData = (options) -> console.log options data = decrypt(options.data) callerID = options.callerID # decode the data stream if data.message? addLocalMessage(data.message, data.channel, callerID) else if data.channel? addLocalChannel(data.channel) else addLocalUserName(data.name, callerID) addLocalUser = (stream, callerID) -> rooms[currentRoomID].users[callerID] = {stream: stream, name: ""} # receive a connection receiveConnection = (options) -> addLocalUser(options.stream, options.callerID) comm.send(encrypt({name: username})) # TODO: Flux the rooms variable and possibly username/userID/currentRoomID comm.on('data', receiveData) comm.on('connected', receiveConnection) createName("<NAME>") joinChatRoom("87d5d3539c0e4743d1825afb5be3cffb1e49605d") #userID = comm.getLocalID() module.exports = { currentRoomID: currentRoomID username: username userID: userID rooms: rooms createName: createName createChatRoom: createChatRoom joinChatRoom: joinChatRoom createChannel: createChannel createMessage: createMessage }
true
crypto = require('crypto') comm = new Icecomm('5icHQ35/1XMHZM3UJF4MoPNh/lWhScDWVVE9n1G6EE8U2vyy') currentRoomID = 0 username = '' userID = 0 rooms = {} # rooms -> key = roomID, value = {users, channels} # channels -> key = channelName, value = [messages] # messages -> {text, callerID} # users -> key = callerID, value = {stream, name} # encrypt data encrypt = (data) -> return JSON.stringify(data)#crypto.publicEncrypt(currentRoomID, new Buffer(JSON.stringify(data), 'utf8')) # decrypt data decrypt = (data) -> return JSON.parse(data)#JSON.parse(crypto.privateDecrypt(currentRoomID, data).toString('utf8')) createName = (name) -> username = name # add a chat room locally (helper) addLocalChatRoom = (roomID) -> # create channel dict in room + message array in channel if !rooms[roomID]? rooms[roomID] = {"users": {}, "channels": {"default": []}} # create a chat room createChatRoom = () -> currentRoomID = crypto.randomBytes(20).toString('hex') addLocalChatRoom(currentRoomID) comm.connect(currentRoomID) # join a chat room joinChatRoom = (roomID) -> currentRoomID = roomID addLocalChatRoom(currentRoomID) comm.connect(currentRoomID) # add a channel locally (helper) addLocalChannel = (channelName) -> # create message array in channel if !rooms[currentRoomID].channels[channelName]? rooms[currentRoomID].channels[channelName] = [] # create a channel createChannel = (channelName) -> addLocalChannel(channelName) comm.send(encrypt({channel: channelName})) # add a message locally (helper) addLocalMessage = (message, channelName, callerID) -> addLocalChannel(channelName) rooms[currentRoomID].channels[channelName].push({text: message, callerID: callerID}) # send a message createMessage = (messageText, channelName) -> channel = channelName || "default" addLocalMessage(messageText, channel, userID) comm.send(encrypt({channel: channel, message: messageText})) # add a local user's name (helper) addLocalUserName = (name, callerID) -> rooms[currentRoomID].users[callerID].name = name # receive a message receiveData = (options) -> console.log options data = decrypt(options.data) callerID = options.callerID # decode the data stream if data.message? addLocalMessage(data.message, data.channel, callerID) else if data.channel? addLocalChannel(data.channel) else addLocalUserName(data.name, callerID) addLocalUser = (stream, callerID) -> rooms[currentRoomID].users[callerID] = {stream: stream, name: ""} # receive a connection receiveConnection = (options) -> addLocalUser(options.stream, options.callerID) comm.send(encrypt({name: username})) # TODO: Flux the rooms variable and possibly username/userID/currentRoomID comm.on('data', receiveData) comm.on('connected', receiveConnection) createName("PI:NAME:<NAME>END_PI") joinChatRoom("87d5d3539c0e4743d1825afb5be3cffb1e49605d") #userID = comm.getLocalID() module.exports = { currentRoomID: currentRoomID username: username userID: userID rooms: rooms createName: createName createChatRoom: createChatRoom joinChatRoom: joinChatRoom createChannel: createChannel createMessage: createMessage }
[ { "context": "ld single record\n # App.User.build(firstName: 'Lance')\n #\n # @example Build multiple records\n # #", "end": 2091, "score": 0.9983193874359131, "start": 2086, "tag": "NAME", "value": "Lance" }, { "context": "splat arguments\n # App.User.build({firstName: 'L...
node_modules/tower/packages/tower-model/shared/scope.coffee
MagicPower2/Power
1
_ = Tower._ # Interface to {Tower.ModelCursor}, used to build database operations. # # @todo Remove this layer, if you want to manually reuse a scope maybe have to call `clone` directly? class Tower.ModelScope @finderMethods: [ 'find' 'all' 'first' 'last' 'count' 'exists' 'fetch' 'instantiate' 'pluck' 'live' 'toArray' ] @persistenceMethods: [ 'insert' 'update' 'create' 'destroy' 'build' ] # These methods are added to {Tower.Model}. @queryMethods: [ 'where' 'order' 'sort' 'asc' 'desc' 'gte' 'gt' 'lte' 'lt' 'limit' 'offset' 'select' 'joins' 'includes' 'excludes' 'paginate' 'page' 'allIn' 'allOf' 'alsoIn' 'anyIn' 'anyOf' 'notIn' 'near' 'within' ] # Map of human readable query operators to # normalized query operators to pass to a {Tower.Store}. @queryOperators: '>=': '$gte' '$gte': '$gte' '>': '$gt' '$gt': '$gt' '<=': '$lte' '$lte': '$lte' '<': '$lt' '$lt': '$lt' '$in': '$in' '$nin': '$nin' '$any': '$any' '$all': '$all' '=~': '$regex' '$m': '$regex' '$regex': '$regex' '$match': '$match' '$notMatch': '$notMatch' '!~': '$nm' '$nm': '$nm' '=': '$eq' '$eq': '$eq' '!=': '$neq' '$neq': '$neq' '$null': '$null' '$notNull': '$notNull' '$near': '$near' constructor: (cursor) -> @cursor = cursor # Check if this scope or relation contains this object # # @param [Object] object an object or array of objects. has: (object) -> @cursor.has(object) # tells us we want to register it to the cursors list # might rename to [live, subscribe, publish, io] live: -> @ # Builds one or many records based on the scope's cursor. # # @example Build single record # App.User.build(firstName: 'Lance') # # @example Build multiple records # # splat arguments # App.User.build({firstName: 'Lance'}, {firstName: 'John'}) # # or pass in an explicit array of records # App.User.build([{firstName: 'Lance'}, {firstName: 'John'}]) # # @example Build by passing in records # App.User.build(new User(firstName: 'Lance')) # # @example Build from scope # # single record # App.User.where(firstName: 'Lance').build() # # multiple records # App.User.where(firstName: 'Lance').build([{lastName: 'Pollard'}, {lastName: 'Smith'}]) # # @example Build without instantiating the object in memory # App.User.options(instantiate: false).where(firstName: 'Lance').build() # # @return [void] Requires a callback to get the data. build: -> cursor = @compile() args = _.compact _.args(arguments) callback = _.extractBlock(args) # for `create`, the rest of the arguments must be records cursor.addData(args) cursor.build(callback) # Creates one or many records based on the scope's cursor. # # @example Create single record # App.User.insert(firstName: 'Lance') # # @example Create multiple records # # splat arguments # App.User.insert({firstName: 'Lance'}, {firstName: 'John'}) # # or pass in an explicit array of records # App.User.insert([{firstName: 'Lance'}, {firstName: 'John'}]) # # @example Create by passing in records # App.User.insert(new User(firstName: 'Lance')) # # @example Create from scope # # single record # App.User.where(firstName: 'Lance').insert() # # multiple records # App.User.where(firstName: 'Lance').insert([{lastName: 'Pollard'}, {lastName: 'Smith'}]) # # @example Create without instantiating the object in memory # App.User.options(instantiate: false).where(firstName: 'Lance').insert() # # @return [void] Requires a callback to get the data. insert: -> cursor = @compile() args = _.compact _.args(arguments) callback = _.extractBlock(args) # for `insert`, the rest of the arguments must be records cursor.addData(args) cursor.insert(callback) create: @::insert # Updates records based on the scope's cursor. # # @example Update by id # App.User.update(1, firstName: 'Lance') # App.User.update(1, 2, firstName: 'Lance') # App.User.update([1, 2], firstName: 'Lance') # # @example Update all # App.User.update(firstName: 'Lance') # # @example Update by passing in records # App.User.update(userA, firstName: 'Lance') # App.User.update(userA, userB, firstName: 'Lance') # App.User.update([userA, userB], firstName: 'Lance') # # @example Update from scope # App.User.where(firstName: 'John').update(firstName: 'Lance') # App.User.where(firstName: 'John').update(1, 2, 3, firstName: 'Lance') # # @return [void] Requires a callback to get the data. update: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) # for `update`, the last argument before the callback must be the updates you're making updates = args.pop() throw new Error('Must pass in updates hash') unless updates && typeof updates == 'object' cursor.addData(updates) cursor.addIds(args) cursor.update(callback) # Deletes records based on the scope's cursor. # # @example Destroy by id # App.User.destroy(1) # App.User.destroy(1, 2) # App.User.destroy([1, 2]) # # @example Destroy all # App.User.destroy() # # @example Update by passing in records # App.User.destroy(userA) # App.User.destroy(userA, userB) # App.User.destroy([userA, userB]) # # @example Update from scope # App.User.where(firstName: 'John').destroy() # App.User.where(firstName: 'John').destroy(1, 2, 3) # # @return [void] Requires a callback to get the data. destroy: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) cursor.addIds(args) cursor.destroy(callback) # Add to set. add: -> cursor = @compile() args = _.args(arguments) callback = _.extractBlock(args) # for `create`, the rest of the arguments must be records cursor.addData(args) cursor.add(callback) # Remove from set. remove: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) cursor.addIds(args) cursor.remove(callback) # Used for hasMany association only right now. # Probably should be moved to cursor class. load: (records) -> @cursor.load(records) reset: -> @cursor.reset() # @todo Should probably do some more delegating to the cursor, but don't want to hardcode too many methods. getEach: -> @cursor.getEach(arguments...) # Updates one or many records based on the scope's cursor. # # @example Find single record # # find record with `id` 45 # App.User.find(45) # # @example Find multiple records # # splat arguments # App.User.find(10, 20) # # or pass in an explicit array of records # App.User.find([10, 20]) # # @example Create from scope # App.User.where(firstName: 'Lance').find(1, 2) # # @return [undefined] Requires a callback to get the data. find: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) cursor.addIds(args) cursor.find(callback) # Find the first record matching this scope's cursor. # # @param [Function] callback first: (callback) -> cursor = @compile() cursor.findOne(callback) # Find the last record matching this scope's cursor. # # @param [Function] callback last: (callback) -> cursor = @compile() cursor.reverseSort() cursor.findOne(callback) # Find all the records matching this scope's cursor. # # @param [Function] callback all: (callback) -> @compile().all(callback) toArray: -> @all().toArray() # Returns an array of column values directly from the underlying table/collection. # This also works with serialized attributes. # @todo pluck: (attributes...) -> @compile().find(callback) # Show query that will be used for the datastore. # @todo explain: -> @compile().explain(callback) # Count the number of records matching this scope's cursor. # # @param [Function] callback count: (callback) -> @compile().count(callback) # Check if a record exists that matches this scope's cursor. # # @param [Function] callback exists: (callback) -> @compile().exists(callback) fetch: (callback) -> @compile().fetch(callback) # @todo batch: -> @ # Metadata. # # @param [Object] options # # @return [Object] returns all of the options. options: (options) -> _.extend(@cursor.options, options) compile: (cloneContent = true) -> @cursor.clone(cloneContent) toCursor: -> @compile() toJSON: -> @cursor.toParams() # Clone this scope (and the critera attached to it). # # @return [Tower.ModelScope] clone: -> new @constructor(@cursor.clone(false)) for key in Tower.ModelScope.queryMethods do (key) => Tower.ModelScope::[key] = -> clone = @clone() clone.cursor[key](arguments...) clone module.exports = Tower.ModelScope
195962
_ = Tower._ # Interface to {Tower.ModelCursor}, used to build database operations. # # @todo Remove this layer, if you want to manually reuse a scope maybe have to call `clone` directly? class Tower.ModelScope @finderMethods: [ 'find' 'all' 'first' 'last' 'count' 'exists' 'fetch' 'instantiate' 'pluck' 'live' 'toArray' ] @persistenceMethods: [ 'insert' 'update' 'create' 'destroy' 'build' ] # These methods are added to {Tower.Model}. @queryMethods: [ 'where' 'order' 'sort' 'asc' 'desc' 'gte' 'gt' 'lte' 'lt' 'limit' 'offset' 'select' 'joins' 'includes' 'excludes' 'paginate' 'page' 'allIn' 'allOf' 'alsoIn' 'anyIn' 'anyOf' 'notIn' 'near' 'within' ] # Map of human readable query operators to # normalized query operators to pass to a {Tower.Store}. @queryOperators: '>=': '$gte' '$gte': '$gte' '>': '$gt' '$gt': '$gt' '<=': '$lte' '$lte': '$lte' '<': '$lt' '$lt': '$lt' '$in': '$in' '$nin': '$nin' '$any': '$any' '$all': '$all' '=~': '$regex' '$m': '$regex' '$regex': '$regex' '$match': '$match' '$notMatch': '$notMatch' '!~': '$nm' '$nm': '$nm' '=': '$eq' '$eq': '$eq' '!=': '$neq' '$neq': '$neq' '$null': '$null' '$notNull': '$notNull' '$near': '$near' constructor: (cursor) -> @cursor = cursor # Check if this scope or relation contains this object # # @param [Object] object an object or array of objects. has: (object) -> @cursor.has(object) # tells us we want to register it to the cursors list # might rename to [live, subscribe, publish, io] live: -> @ # Builds one or many records based on the scope's cursor. # # @example Build single record # App.User.build(firstName: '<NAME>') # # @example Build multiple records # # splat arguments # App.User.build({firstName: '<NAME>'}, {firstName: '<NAME>'}) # # or pass in an explicit array of records # App.User.build([{firstName: '<NAME>'}, {firstName: '<NAME>'}]) # # @example Build by passing in records # App.User.build(new User(firstName: '<NAME>')) # # @example Build from scope # # single record # App.User.where(firstName: '<NAME>').build() # # multiple records # App.User.where(firstName: '<NAME>').build([{lastName: '<NAME>'}, {lastName: '<NAME>'}]) # # @example Build without instantiating the object in memory # App.User.options(instantiate: false).where(firstName: '<NAME>').build() # # @return [void] Requires a callback to get the data. build: -> cursor = @compile() args = _.compact _.args(arguments) callback = _.extractBlock(args) # for `create`, the rest of the arguments must be records cursor.addData(args) cursor.build(callback) # Creates one or many records based on the scope's cursor. # # @example Create single record # App.User.insert(firstName: '<NAME>') # # @example Create multiple records # # splat arguments # App.User.insert({firstName: '<NAME>'}, {firstName: '<NAME>'}) # # or pass in an explicit array of records # App.User.insert([{firstName: '<NAME>'}, {firstName: '<NAME>'}]) # # @example Create by passing in records # App.User.insert(new User(firstName: 'L<NAME>')) # # @example Create from scope # # single record # App.User.where(firstName: '<NAME>').insert() # # multiple records # App.User.where(firstName: '<NAME>').insert([{lastName: '<NAME>'}, {lastName: '<NAME>'}]) # # @example Create without instantiating the object in memory # App.User.options(instantiate: false).where(firstName: '<NAME>').insert() # # @return [void] Requires a callback to get the data. insert: -> cursor = @compile() args = _.compact _.args(arguments) callback = _.extractBlock(args) # for `insert`, the rest of the arguments must be records cursor.addData(args) cursor.insert(callback) create: @::insert # Updates records based on the scope's cursor. # # @example Update by id # App.User.update(1, firstName: 'L<NAME>') # App.User.update(1, 2, firstName: 'L<NAME>') # App.User.update([1, 2], firstName: 'Lance') # # @example Update all # App.User.update(firstName: 'Lance') # # @example Update by passing in records # App.User.update(userA, firstName: 'L<NAME>') # App.User.update(userA, userB, firstName: 'Lance') # App.User.update([userA, userB], firstName: 'Lance') # # @example Update from scope # App.User.where(firstName: '<NAME>').update(firstName: 'Lance') # App.User.where(firstName: '<NAME>').update(1, 2, 3, firstName: 'Lance') # # @return [void] Requires a callback to get the data. update: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) # for `update`, the last argument before the callback must be the updates you're making updates = args.pop() throw new Error('Must pass in updates hash') unless updates && typeof updates == 'object' cursor.addData(updates) cursor.addIds(args) cursor.update(callback) # Deletes records based on the scope's cursor. # # @example Destroy by id # App.User.destroy(1) # App.User.destroy(1, 2) # App.User.destroy([1, 2]) # # @example Destroy all # App.User.destroy() # # @example Update by passing in records # App.User.destroy(userA) # App.User.destroy(userA, userB) # App.User.destroy([userA, userB]) # # @example Update from scope # App.User.where(firstName: '<NAME>').destroy() # App.User.where(firstName: '<NAME>').destroy(1, 2, 3) # # @return [void] Requires a callback to get the data. destroy: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) cursor.addIds(args) cursor.destroy(callback) # Add to set. add: -> cursor = @compile() args = _.args(arguments) callback = _.extractBlock(args) # for `create`, the rest of the arguments must be records cursor.addData(args) cursor.add(callback) # Remove from set. remove: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) cursor.addIds(args) cursor.remove(callback) # Used for hasMany association only right now. # Probably should be moved to cursor class. load: (records) -> @cursor.load(records) reset: -> @cursor.reset() # @todo Should probably do some more delegating to the cursor, but don't want to hardcode too many methods. getEach: -> @cursor.getEach(arguments...) # Updates one or many records based on the scope's cursor. # # @example Find single record # # find record with `id` 45 # App.User.find(45) # # @example Find multiple records # # splat arguments # App.User.find(10, 20) # # or pass in an explicit array of records # App.User.find([10, 20]) # # @example Create from scope # App.User.where(firstName: '<NAME>').find(1, 2) # # @return [undefined] Requires a callback to get the data. find: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) cursor.addIds(args) cursor.find(callback) # Find the first record matching this scope's cursor. # # @param [Function] callback first: (callback) -> cursor = @compile() cursor.findOne(callback) # Find the last record matching this scope's cursor. # # @param [Function] callback last: (callback) -> cursor = @compile() cursor.reverseSort() cursor.findOne(callback) # Find all the records matching this scope's cursor. # # @param [Function] callback all: (callback) -> @compile().all(callback) toArray: -> @all().toArray() # Returns an array of column values directly from the underlying table/collection. # This also works with serialized attributes. # @todo pluck: (attributes...) -> @compile().find(callback) # Show query that will be used for the datastore. # @todo explain: -> @compile().explain(callback) # Count the number of records matching this scope's cursor. # # @param [Function] callback count: (callback) -> @compile().count(callback) # Check if a record exists that matches this scope's cursor. # # @param [Function] callback exists: (callback) -> @compile().exists(callback) fetch: (callback) -> @compile().fetch(callback) # @todo batch: -> @ # Metadata. # # @param [Object] options # # @return [Object] returns all of the options. options: (options) -> _.extend(@cursor.options, options) compile: (cloneContent = true) -> @cursor.clone(cloneContent) toCursor: -> @compile() toJSON: -> @cursor.toParams() # Clone this scope (and the critera attached to it). # # @return [Tower.ModelScope] clone: -> new @constructor(@cursor.clone(false)) for key in Tower.ModelScope.queryMethods do (key) => Tower.ModelScope::[key] = -> clone = @clone() clone.cursor[key](arguments...) clone module.exports = Tower.ModelScope
true
_ = Tower._ # Interface to {Tower.ModelCursor}, used to build database operations. # # @todo Remove this layer, if you want to manually reuse a scope maybe have to call `clone` directly? class Tower.ModelScope @finderMethods: [ 'find' 'all' 'first' 'last' 'count' 'exists' 'fetch' 'instantiate' 'pluck' 'live' 'toArray' ] @persistenceMethods: [ 'insert' 'update' 'create' 'destroy' 'build' ] # These methods are added to {Tower.Model}. @queryMethods: [ 'where' 'order' 'sort' 'asc' 'desc' 'gte' 'gt' 'lte' 'lt' 'limit' 'offset' 'select' 'joins' 'includes' 'excludes' 'paginate' 'page' 'allIn' 'allOf' 'alsoIn' 'anyIn' 'anyOf' 'notIn' 'near' 'within' ] # Map of human readable query operators to # normalized query operators to pass to a {Tower.Store}. @queryOperators: '>=': '$gte' '$gte': '$gte' '>': '$gt' '$gt': '$gt' '<=': '$lte' '$lte': '$lte' '<': '$lt' '$lt': '$lt' '$in': '$in' '$nin': '$nin' '$any': '$any' '$all': '$all' '=~': '$regex' '$m': '$regex' '$regex': '$regex' '$match': '$match' '$notMatch': '$notMatch' '!~': '$nm' '$nm': '$nm' '=': '$eq' '$eq': '$eq' '!=': '$neq' '$neq': '$neq' '$null': '$null' '$notNull': '$notNull' '$near': '$near' constructor: (cursor) -> @cursor = cursor # Check if this scope or relation contains this object # # @param [Object] object an object or array of objects. has: (object) -> @cursor.has(object) # tells us we want to register it to the cursors list # might rename to [live, subscribe, publish, io] live: -> @ # Builds one or many records based on the scope's cursor. # # @example Build single record # App.User.build(firstName: 'PI:NAME:<NAME>END_PI') # # @example Build multiple records # # splat arguments # App.User.build({firstName: 'PI:NAME:<NAME>END_PI'}, {firstName: 'PI:NAME:<NAME>END_PI'}) # # or pass in an explicit array of records # App.User.build([{firstName: 'PI:NAME:<NAME>END_PI'}, {firstName: 'PI:NAME:<NAME>END_PI'}]) # # @example Build by passing in records # App.User.build(new User(firstName: 'PI:NAME:<NAME>END_PI')) # # @example Build from scope # # single record # App.User.where(firstName: 'PI:NAME:<NAME>END_PI').build() # # multiple records # App.User.where(firstName: 'PI:NAME:<NAME>END_PI').build([{lastName: 'PI:NAME:<NAME>END_PI'}, {lastName: 'PI:NAME:<NAME>END_PI'}]) # # @example Build without instantiating the object in memory # App.User.options(instantiate: false).where(firstName: 'PI:NAME:<NAME>END_PI').build() # # @return [void] Requires a callback to get the data. build: -> cursor = @compile() args = _.compact _.args(arguments) callback = _.extractBlock(args) # for `create`, the rest of the arguments must be records cursor.addData(args) cursor.build(callback) # Creates one or many records based on the scope's cursor. # # @example Create single record # App.User.insert(firstName: 'PI:NAME:<NAME>END_PI') # # @example Create multiple records # # splat arguments # App.User.insert({firstName: 'PI:NAME:<NAME>END_PI'}, {firstName: 'PI:NAME:<NAME>END_PI'}) # # or pass in an explicit array of records # App.User.insert([{firstName: 'PI:NAME:<NAME>END_PI'}, {firstName: 'PI:NAME:<NAME>END_PI'}]) # # @example Create by passing in records # App.User.insert(new User(firstName: 'LPI:NAME:<NAME>END_PI')) # # @example Create from scope # # single record # App.User.where(firstName: 'PI:NAME:<NAME>END_PI').insert() # # multiple records # App.User.where(firstName: 'PI:NAME:<NAME>END_PI').insert([{lastName: 'PI:NAME:<NAME>END_PI'}, {lastName: 'PI:NAME:<NAME>END_PI'}]) # # @example Create without instantiating the object in memory # App.User.options(instantiate: false).where(firstName: 'PI:NAME:<NAME>END_PI').insert() # # @return [void] Requires a callback to get the data. insert: -> cursor = @compile() args = _.compact _.args(arguments) callback = _.extractBlock(args) # for `insert`, the rest of the arguments must be records cursor.addData(args) cursor.insert(callback) create: @::insert # Updates records based on the scope's cursor. # # @example Update by id # App.User.update(1, firstName: 'LPI:NAME:<NAME>END_PI') # App.User.update(1, 2, firstName: 'LPI:NAME:<NAME>END_PI') # App.User.update([1, 2], firstName: 'Lance') # # @example Update all # App.User.update(firstName: 'Lance') # # @example Update by passing in records # App.User.update(userA, firstName: 'LPI:NAME:<NAME>END_PI') # App.User.update(userA, userB, firstName: 'Lance') # App.User.update([userA, userB], firstName: 'Lance') # # @example Update from scope # App.User.where(firstName: 'PI:NAME:<NAME>END_PI').update(firstName: 'Lance') # App.User.where(firstName: 'PI:NAME:<NAME>END_PI').update(1, 2, 3, firstName: 'Lance') # # @return [void] Requires a callback to get the data. update: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) # for `update`, the last argument before the callback must be the updates you're making updates = args.pop() throw new Error('Must pass in updates hash') unless updates && typeof updates == 'object' cursor.addData(updates) cursor.addIds(args) cursor.update(callback) # Deletes records based on the scope's cursor. # # @example Destroy by id # App.User.destroy(1) # App.User.destroy(1, 2) # App.User.destroy([1, 2]) # # @example Destroy all # App.User.destroy() # # @example Update by passing in records # App.User.destroy(userA) # App.User.destroy(userA, userB) # App.User.destroy([userA, userB]) # # @example Update from scope # App.User.where(firstName: 'PI:NAME:<NAME>END_PI').destroy() # App.User.where(firstName: 'PI:NAME:<NAME>END_PI').destroy(1, 2, 3) # # @return [void] Requires a callback to get the data. destroy: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) cursor.addIds(args) cursor.destroy(callback) # Add to set. add: -> cursor = @compile() args = _.args(arguments) callback = _.extractBlock(args) # for `create`, the rest of the arguments must be records cursor.addData(args) cursor.add(callback) # Remove from set. remove: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) cursor.addIds(args) cursor.remove(callback) # Used for hasMany association only right now. # Probably should be moved to cursor class. load: (records) -> @cursor.load(records) reset: -> @cursor.reset() # @todo Should probably do some more delegating to the cursor, but don't want to hardcode too many methods. getEach: -> @cursor.getEach(arguments...) # Updates one or many records based on the scope's cursor. # # @example Find single record # # find record with `id` 45 # App.User.find(45) # # @example Find multiple records # # splat arguments # App.User.find(10, 20) # # or pass in an explicit array of records # App.User.find([10, 20]) # # @example Create from scope # App.User.where(firstName: 'PI:NAME:<NAME>END_PI').find(1, 2) # # @return [undefined] Requires a callback to get the data. find: -> cursor = @compile() args = _.flatten _.args(arguments) callback = _.extractBlock(args) cursor.addIds(args) cursor.find(callback) # Find the first record matching this scope's cursor. # # @param [Function] callback first: (callback) -> cursor = @compile() cursor.findOne(callback) # Find the last record matching this scope's cursor. # # @param [Function] callback last: (callback) -> cursor = @compile() cursor.reverseSort() cursor.findOne(callback) # Find all the records matching this scope's cursor. # # @param [Function] callback all: (callback) -> @compile().all(callback) toArray: -> @all().toArray() # Returns an array of column values directly from the underlying table/collection. # This also works with serialized attributes. # @todo pluck: (attributes...) -> @compile().find(callback) # Show query that will be used for the datastore. # @todo explain: -> @compile().explain(callback) # Count the number of records matching this scope's cursor. # # @param [Function] callback count: (callback) -> @compile().count(callback) # Check if a record exists that matches this scope's cursor. # # @param [Function] callback exists: (callback) -> @compile().exists(callback) fetch: (callback) -> @compile().fetch(callback) # @todo batch: -> @ # Metadata. # # @param [Object] options # # @return [Object] returns all of the options. options: (options) -> _.extend(@cursor.options, options) compile: (cloneContent = true) -> @cursor.clone(cloneContent) toCursor: -> @compile() toJSON: -> @cursor.toParams() # Clone this scope (and the critera attached to it). # # @return [Tower.ModelScope] clone: -> new @constructor(@cursor.clone(false)) for key in Tower.ModelScope.queryMethods do (key) => Tower.ModelScope::[key] = -> clone = @clone() clone.cursor[key](arguments...) clone module.exports = Tower.ModelScope
[ { "context": "atform specific React Native components.\n# @author Tom Hastjarjanto\n###\n\n'use strict'\n\n# ----------------------------", "end": 137, "score": 0.999896228313446, "start": 121, "tag": "NAME", "value": "Tom Hastjarjanto" } ]
src/tests/rules/split-platform-components.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Android and IOS components should be # used in platform specific React Native components. # @author Tom Hastjarjanto ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/split-platform-components' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' tests = valid: [ code: ''' React = require('react-native') { ActivityIndicatiorIOS, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' filename: 'Hello.ios.js' , code: ''' React = require('react-native') { ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ProgressBarAndroid /> }) ''' filename: 'Hello.android.js' , code: ''' React = require('react-native') { View, } = React Hello = React.createClass({ render: -> <View /> }) ''' filename: 'Hello.js' , code: ''' import { ActivityIndicatiorIOS, } from 'react-native' ''' filename: 'Hello.ios.js' , code: ''' import { ProgressBarAndroid, } from 'react-native' ''' filename: 'Hello.android.js' , code: ''' import { View, } from 'react-native' ''' filename: 'Hello.js' , code: ''' React = require('react-native') { ActivityIndicatiorIOS, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' options: [iosPathRegex: '\\.ios(\\.test)?\\.js$'] filename: 'Hello.ios.test.js' , code: ''' React = require('react-native') { ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ProgressBarAndroid /> }) ''' options: [androidPathRegex: '\\.android(\\.test)?\\.js$'] filename: 'Hello.android.test.js' ] invalid: [ code: ''' React = require('react-native') { ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ProgressBarAndroid /> }) ''' filename: 'Hello.js' errors: [message: 'Android components should be placed in android files'] , code: ''' React = require('react-native') { ActivityIndicatiorIOS, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' filename: 'Hello.js' errors: [message: 'IOS components should be placed in ios files'] , code: ''' React = require('react-native') { ActivityIndicatiorIOS, ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' filename: 'Hello.js' errors: [ message: "IOS and Android components can't be mixed" , message: "IOS and Android components can't be mixed" ] , code: ''' import { ProgressBarAndroid, } from 'react-native' ''' filename: 'Hello.js' errors: [message: 'Android components should be placed in android files'] , code: ''' import { ActivityIndicatiorIOS, } from 'react-native' ''' filename: 'Hello.js' errors: [message: 'IOS components should be placed in ios files'] , code: ''' import { ActivityIndicatiorIOS, ProgressBarAndroid, } from 'react-native' ''' filename: 'Hello.js' errors: [ message: "IOS and Android components can't be mixed" , message: "IOS and Android components can't be mixed" ] ] ruleTester.run 'split-platform-components', rule, tests
1950
###* # @fileoverview Android and IOS components should be # used in platform specific React Native components. # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/split-platform-components' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' tests = valid: [ code: ''' React = require('react-native') { ActivityIndicatiorIOS, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' filename: 'Hello.ios.js' , code: ''' React = require('react-native') { ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ProgressBarAndroid /> }) ''' filename: 'Hello.android.js' , code: ''' React = require('react-native') { View, } = React Hello = React.createClass({ render: -> <View /> }) ''' filename: 'Hello.js' , code: ''' import { ActivityIndicatiorIOS, } from 'react-native' ''' filename: 'Hello.ios.js' , code: ''' import { ProgressBarAndroid, } from 'react-native' ''' filename: 'Hello.android.js' , code: ''' import { View, } from 'react-native' ''' filename: 'Hello.js' , code: ''' React = require('react-native') { ActivityIndicatiorIOS, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' options: [iosPathRegex: '\\.ios(\\.test)?\\.js$'] filename: 'Hello.ios.test.js' , code: ''' React = require('react-native') { ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ProgressBarAndroid /> }) ''' options: [androidPathRegex: '\\.android(\\.test)?\\.js$'] filename: 'Hello.android.test.js' ] invalid: [ code: ''' React = require('react-native') { ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ProgressBarAndroid /> }) ''' filename: 'Hello.js' errors: [message: 'Android components should be placed in android files'] , code: ''' React = require('react-native') { ActivityIndicatiorIOS, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' filename: 'Hello.js' errors: [message: 'IOS components should be placed in ios files'] , code: ''' React = require('react-native') { ActivityIndicatiorIOS, ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' filename: 'Hello.js' errors: [ message: "IOS and Android components can't be mixed" , message: "IOS and Android components can't be mixed" ] , code: ''' import { ProgressBarAndroid, } from 'react-native' ''' filename: 'Hello.js' errors: [message: 'Android components should be placed in android files'] , code: ''' import { ActivityIndicatiorIOS, } from 'react-native' ''' filename: 'Hello.js' errors: [message: 'IOS components should be placed in ios files'] , code: ''' import { ActivityIndicatiorIOS, ProgressBarAndroid, } from 'react-native' ''' filename: 'Hello.js' errors: [ message: "IOS and Android components can't be mixed" , message: "IOS and Android components can't be mixed" ] ] ruleTester.run 'split-platform-components', rule, tests
true
###* # @fileoverview Android and IOS components should be # used in platform specific React Native components. # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ rule = require '../../rules/split-platform-components' {RuleTester} = require 'eslint' path = require 'path' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' tests = valid: [ code: ''' React = require('react-native') { ActivityIndicatiorIOS, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' filename: 'Hello.ios.js' , code: ''' React = require('react-native') { ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ProgressBarAndroid /> }) ''' filename: 'Hello.android.js' , code: ''' React = require('react-native') { View, } = React Hello = React.createClass({ render: -> <View /> }) ''' filename: 'Hello.js' , code: ''' import { ActivityIndicatiorIOS, } from 'react-native' ''' filename: 'Hello.ios.js' , code: ''' import { ProgressBarAndroid, } from 'react-native' ''' filename: 'Hello.android.js' , code: ''' import { View, } from 'react-native' ''' filename: 'Hello.js' , code: ''' React = require('react-native') { ActivityIndicatiorIOS, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' options: [iosPathRegex: '\\.ios(\\.test)?\\.js$'] filename: 'Hello.ios.test.js' , code: ''' React = require('react-native') { ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ProgressBarAndroid /> }) ''' options: [androidPathRegex: '\\.android(\\.test)?\\.js$'] filename: 'Hello.android.test.js' ] invalid: [ code: ''' React = require('react-native') { ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ProgressBarAndroid /> }) ''' filename: 'Hello.js' errors: [message: 'Android components should be placed in android files'] , code: ''' React = require('react-native') { ActivityIndicatiorIOS, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' filename: 'Hello.js' errors: [message: 'IOS components should be placed in ios files'] , code: ''' React = require('react-native') { ActivityIndicatiorIOS, ProgressBarAndroid, } = React Hello = React.createClass({ render: -> return <ActivityIndicatiorIOS /> }) ''' filename: 'Hello.js' errors: [ message: "IOS and Android components can't be mixed" , message: "IOS and Android components can't be mixed" ] , code: ''' import { ProgressBarAndroid, } from 'react-native' ''' filename: 'Hello.js' errors: [message: 'Android components should be placed in android files'] , code: ''' import { ActivityIndicatiorIOS, } from 'react-native' ''' filename: 'Hello.js' errors: [message: 'IOS components should be placed in ios files'] , code: ''' import { ActivityIndicatiorIOS, ProgressBarAndroid, } from 'react-native' ''' filename: 'Hello.js' errors: [ message: "IOS and Android components can't be mixed" , message: "IOS and Android components can't be mixed" ] ] ruleTester.run 'split-platform-components', rule, tests
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999160766601562, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" }, { "context": "ication\n\n@formConfirmation ?= new FormConfirmation(@formErro...
resources/assets/coffee/main.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. @polyfills ?= new Polyfills Turbolinks.setProgressBarDelay(0) Lang.setLocale(@currentLocale) jQuery.timeago.settings.allowFuture = true # loading animation overlay # fired from turbolinks $(document).on 'turbolinks:request-start', LoadingOverlay.show $(document).on 'turbolinks:request-end', LoadingOverlay.hide # form submission is not covered by turbolinks $(document).on 'submit', 'form', (e) -> LoadingOverlay.show() if e.currentTarget.dataset.loadingOverlay != '0' $(document).on 'turbolinks:load', -> BeatmapPack.initialize() StoreSupporterTag.initialize() StoreCheckout.initialize() # ensure currentUser is updated early enough. @currentUserObserver ?= new CurrentUserObserver @throttledWindowEvents ?= new ThrottledWindowEvents @syncHeight ?= new SyncHeight @stickyHeader ?= new StickyHeader @accountEdit ?= new AccountEdit @accountEditAvatar ?= new AccountEditAvatar @accountEditBlocklist ?= new AccountEditBlocklist @beatmapsetDownloadObserver ?= new BeatmapsetDownloadObserver @changelogChartLoader ?= new ChangelogChartLoader @checkboxValidation ?= new CheckboxValidation @clickMenu ?= new _exported.ClickMenu @fancyGraph ?= new FancyGraph @formClear ?= new FormClear @formError ?= new FormError @formPlaceholderHide ?= new FormPlaceholderHide @formToggle ?= new FormToggle @forum ?= new Forum @forumAutoClick ?= new ForumAutoClick @forumCover ?= new ForumCover @forumPoll ?= new _exported.ForumPoll(@) @forumPostPreview ?= new ForumPostPreview @forumTopicTitle ?= new ForumTopicTitle @forumTopicWatchAjax ?= new ForumTopicWatchAjax @gallery ?= new Gallery @globalDrag ?= new GlobalDrag @landingGraph ?= new LandingGraph @menu ?= new Menu @mobileToggle ?= new _exported.MobileToggle @navButton ?= new NavButton @osuAudio ?= new OsuAudio @osuLayzr ?= new OsuLayzr @postPreview ?= new PostPreview @scale ?= new Scale @search ?= new Search @stickyFooter ?= new StickyFooter @timeago ?= new Timeago @tooltipBeatmap ?= new TooltipBeatmap @tooltipDefault ?= new TooltipDefault @turbolinksReload ?= new _exported.TurbolinksReload @userLogin ?= new UserLogin @userVerification ?= new UserVerification @formConfirmation ?= new FormConfirmation(@formError) @forumPostsSeek ?= new ForumPostsSeek(@forum) @forumTopicPostJump ?= new ForumTopicPostJump(@forum) @forumTopicReply ?= new ForumTopicReply({ @forum, @forumPostPreview, @stickyFooter }) @nav2 ?= new Nav2(@clickMenu) @osuEnchant ?= new _exported.Enchant(@, @turbolinksReload) @twitchPlayer ?= new TwitchPlayer(@turbolinksReload) _exported.WindowVHPatcher.init(window) $(document).on 'change', '.js-url-selector', (e) -> osu.navigate e.target.value, (e.target.dataset.keepScroll == '1') $(document).on 'keydown', (e) -> $.publish 'key:esc' if e.keyCode == 27 rootUrl = "#{document.location.protocol}//#{document.location.host}" rootUrl += ":#{document.location.port}" if document.location.port rootUrl += '/' # Internal Helper $.expr[':'].internal = (obj, index, meta, stack) -> # Prepare $this = $(obj) url = $this.attr('href') or '' url.substring(0, rootUrl.length) == rootUrl or url.indexOf(':') == -1
4589
# 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. @polyfills ?= new Polyfills Turbolinks.setProgressBarDelay(0) Lang.setLocale(@currentLocale) jQuery.timeago.settings.allowFuture = true # loading animation overlay # fired from turbolinks $(document).on 'turbolinks:request-start', LoadingOverlay.show $(document).on 'turbolinks:request-end', LoadingOverlay.hide # form submission is not covered by turbolinks $(document).on 'submit', 'form', (e) -> LoadingOverlay.show() if e.currentTarget.dataset.loadingOverlay != '0' $(document).on 'turbolinks:load', -> BeatmapPack.initialize() StoreSupporterTag.initialize() StoreCheckout.initialize() # ensure currentUser is updated early enough. @currentUserObserver ?= new CurrentUserObserver @throttledWindowEvents ?= new ThrottledWindowEvents @syncHeight ?= new SyncHeight @stickyHeader ?= new StickyHeader @accountEdit ?= new AccountEdit @accountEditAvatar ?= new AccountEditAvatar @accountEditBlocklist ?= new AccountEditBlocklist @beatmapsetDownloadObserver ?= new BeatmapsetDownloadObserver @changelogChartLoader ?= new ChangelogChartLoader @checkboxValidation ?= new CheckboxValidation @clickMenu ?= new _exported.ClickMenu @fancyGraph ?= new FancyGraph @formClear ?= new FormClear @formError ?= new FormError @formPlaceholderHide ?= new FormPlaceholderHide @formToggle ?= new FormToggle @forum ?= new Forum @forumAutoClick ?= new ForumAutoClick @forumCover ?= new ForumCover @forumPoll ?= new _exported.ForumPoll(@) @forumPostPreview ?= new ForumPostPreview @forumTopicTitle ?= new ForumTopicTitle @forumTopicWatchAjax ?= new ForumTopicWatchAjax @gallery ?= new Gallery @globalDrag ?= new GlobalDrag @landingGraph ?= new LandingGraph @menu ?= new Menu @mobileToggle ?= new _exported.MobileToggle @navButton ?= new NavButton @osuAudio ?= new OsuAudio @osuLayzr ?= new OsuLayzr @postPreview ?= new PostPreview @scale ?= new Scale @search ?= new Search @stickyFooter ?= new StickyFooter @timeago ?= new Timeago @tooltipBeatmap ?= new TooltipBeatmap @tooltipDefault ?= new TooltipDefault @turbolinksReload ?= new _exported.TurbolinksReload @userLogin ?= new UserLogin @userVerification ?= new UserVerification @formConfirmation ?= new FormConfirmation(@formError) @forumPostsSeek ?= new ForumPostsSeek(@forum) @forumTopicPostJump ?= new ForumTopicPostJump(@forum) @forumTopicReply ?= new ForumTopicReply({ @forum, @forumPostPreview, @stickyFooter }) @nav2 ?= new Nav2(@clickMenu) @osuEnchant ?= new _exported.Enchant(@, @turbolinksReload) @twitchPlayer ?= new TwitchPlayer(@turbolinksReload) _exported.WindowVHPatcher.init(window) $(document).on 'change', '.js-url-selector', (e) -> osu.navigate e.target.value, (e.target.dataset.keepScroll == '1') $(document).on 'keydown', (e) -> $.publish 'key:esc' if e.keyCode == 27 rootUrl = "#{document.location.protocol}//#{document.location.host}" rootUrl += ":#{document.location.port}" if document.location.port rootUrl += '/' # Internal Helper $.expr[':'].internal = (obj, index, meta, stack) -> # Prepare $this = $(obj) url = $this.attr('href') or '' url.substring(0, rootUrl.length) == rootUrl or url.indexOf(':') == -1
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. @polyfills ?= new Polyfills Turbolinks.setProgressBarDelay(0) Lang.setLocale(@currentLocale) jQuery.timeago.settings.allowFuture = true # loading animation overlay # fired from turbolinks $(document).on 'turbolinks:request-start', LoadingOverlay.show $(document).on 'turbolinks:request-end', LoadingOverlay.hide # form submission is not covered by turbolinks $(document).on 'submit', 'form', (e) -> LoadingOverlay.show() if e.currentTarget.dataset.loadingOverlay != '0' $(document).on 'turbolinks:load', -> BeatmapPack.initialize() StoreSupporterTag.initialize() StoreCheckout.initialize() # ensure currentUser is updated early enough. @currentUserObserver ?= new CurrentUserObserver @throttledWindowEvents ?= new ThrottledWindowEvents @syncHeight ?= new SyncHeight @stickyHeader ?= new StickyHeader @accountEdit ?= new AccountEdit @accountEditAvatar ?= new AccountEditAvatar @accountEditBlocklist ?= new AccountEditBlocklist @beatmapsetDownloadObserver ?= new BeatmapsetDownloadObserver @changelogChartLoader ?= new ChangelogChartLoader @checkboxValidation ?= new CheckboxValidation @clickMenu ?= new _exported.ClickMenu @fancyGraph ?= new FancyGraph @formClear ?= new FormClear @formError ?= new FormError @formPlaceholderHide ?= new FormPlaceholderHide @formToggle ?= new FormToggle @forum ?= new Forum @forumAutoClick ?= new ForumAutoClick @forumCover ?= new ForumCover @forumPoll ?= new _exported.ForumPoll(@) @forumPostPreview ?= new ForumPostPreview @forumTopicTitle ?= new ForumTopicTitle @forumTopicWatchAjax ?= new ForumTopicWatchAjax @gallery ?= new Gallery @globalDrag ?= new GlobalDrag @landingGraph ?= new LandingGraph @menu ?= new Menu @mobileToggle ?= new _exported.MobileToggle @navButton ?= new NavButton @osuAudio ?= new OsuAudio @osuLayzr ?= new OsuLayzr @postPreview ?= new PostPreview @scale ?= new Scale @search ?= new Search @stickyFooter ?= new StickyFooter @timeago ?= new Timeago @tooltipBeatmap ?= new TooltipBeatmap @tooltipDefault ?= new TooltipDefault @turbolinksReload ?= new _exported.TurbolinksReload @userLogin ?= new UserLogin @userVerification ?= new UserVerification @formConfirmation ?= new FormConfirmation(@formError) @forumPostsSeek ?= new ForumPostsSeek(@forum) @forumTopicPostJump ?= new ForumTopicPostJump(@forum) @forumTopicReply ?= new ForumTopicReply({ @forum, @forumPostPreview, @stickyFooter }) @nav2 ?= new Nav2(@clickMenu) @osuEnchant ?= new _exported.Enchant(@, @turbolinksReload) @twitchPlayer ?= new TwitchPlayer(@turbolinksReload) _exported.WindowVHPatcher.init(window) $(document).on 'change', '.js-url-selector', (e) -> osu.navigate e.target.value, (e.target.dataset.keepScroll == '1') $(document).on 'keydown', (e) -> $.publish 'key:esc' if e.keyCode == 27 rootUrl = "#{document.location.protocol}//#{document.location.host}" rootUrl += ":#{document.location.port}" if document.location.port rootUrl += '/' # Internal Helper $.expr[':'].internal = (obj, index, meta, stack) -> # Prepare $this = $(obj) url = $this.attr('href') or '' url.substring(0, rootUrl.length) == rootUrl or url.indexOf(':') == -1
[ { "context": "ata.name = $(\"#name\").val()\n reqData.password = $(\"#password\").val()\n reqData.port = $(\"#port\").val()\n r", "end": 1299, "score": 0.9503995776176453, "start": 1287, "tag": "PASSWORD", "value": "$(\"#password" } ]
static/javascripts/test.coffee
youqingkui/FlaskSQLAlchemyModels
0
$(document).ready () -> $("#get_db").click -> reqData = getInfo() $.post '/get_db', reqData, (body) -> console.log(body) data = JSON.parse(body) console.log(data) if data.msg is 'ok' $('#database').html('') $.each data.data, (index, dbName) -> $('#database').append "<option value=#{dbName}>#{dbName}</option>" alert("获取数据库成功") else alert(data.msg) $('#database').change () -> dbName = $(this).val() reqData = getInfo() reqData.db_name = dbName $.post '/get_tb', reqData, (body) -> data = JSON.parse(body) console.log(data) if data.msg is 'ok' $('#tb_name').html('') $.each data.data, (index, tbName) -> $('#tb_name').append "<option value=#{tbName}>#{tbName}</option>" alert("获取数据库成功") else alert(data.msg) $('#tb_name').change () -> dbName = $("#database").val() tbName = $(this).val() reqData = getInfo() reqData.tb_name = tbName reqData.db_name = dbName $.post '/get_sql_code', reqData, (body) -> data = JSON.parse(body) console.log data getInfo = () -> reqData = {} reqData.host = $("#host").val() reqData.name = $("#name").val() reqData.password = $("#password").val() reqData.port = $("#port").val() return reqData
201173
$(document).ready () -> $("#get_db").click -> reqData = getInfo() $.post '/get_db', reqData, (body) -> console.log(body) data = JSON.parse(body) console.log(data) if data.msg is 'ok' $('#database').html('') $.each data.data, (index, dbName) -> $('#database').append "<option value=#{dbName}>#{dbName}</option>" alert("获取数据库成功") else alert(data.msg) $('#database').change () -> dbName = $(this).val() reqData = getInfo() reqData.db_name = dbName $.post '/get_tb', reqData, (body) -> data = JSON.parse(body) console.log(data) if data.msg is 'ok' $('#tb_name').html('') $.each data.data, (index, tbName) -> $('#tb_name').append "<option value=#{tbName}>#{tbName}</option>" alert("获取数据库成功") else alert(data.msg) $('#tb_name').change () -> dbName = $("#database").val() tbName = $(this).val() reqData = getInfo() reqData.tb_name = tbName reqData.db_name = dbName $.post '/get_sql_code', reqData, (body) -> data = JSON.parse(body) console.log data getInfo = () -> reqData = {} reqData.host = $("#host").val() reqData.name = $("#name").val() reqData.password = <PASSWORD>").val() reqData.port = $("#port").val() return reqData
true
$(document).ready () -> $("#get_db").click -> reqData = getInfo() $.post '/get_db', reqData, (body) -> console.log(body) data = JSON.parse(body) console.log(data) if data.msg is 'ok' $('#database').html('') $.each data.data, (index, dbName) -> $('#database').append "<option value=#{dbName}>#{dbName}</option>" alert("获取数据库成功") else alert(data.msg) $('#database').change () -> dbName = $(this).val() reqData = getInfo() reqData.db_name = dbName $.post '/get_tb', reqData, (body) -> data = JSON.parse(body) console.log(data) if data.msg is 'ok' $('#tb_name').html('') $.each data.data, (index, tbName) -> $('#tb_name').append "<option value=#{tbName}>#{tbName}</option>" alert("获取数据库成功") else alert(data.msg) $('#tb_name').change () -> dbName = $("#database").val() tbName = $(this).val() reqData = getInfo() reqData.tb_name = tbName reqData.db_name = dbName $.post '/get_sql_code', reqData, (body) -> data = JSON.parse(body) console.log data getInfo = () -> reqData = {} reqData.host = $("#host").val() reqData.name = $("#name").val() reqData.password = PI:PASSWORD:<PASSWORD>END_PI").val() reqData.port = $("#port").val() return reqData
[ { "context": "iosk.Components.layout\n storeKey: 'question.answers'\n lowIndex: 0\n defaultAnswers: -> ", "end": 150, "score": 0.5544825196266174, "start": 150, "tag": "KEY", "value": "" } ]
src/coffee/controllers/questions_controller.coffee
TheSwanFactory/self-service-kiosk
0
class SwanKiosk.Controllers.QuestionsController extends SwanKiosk.Controller layout: SwanKiosk.Components.layout storeKey: 'question.answers' lowIndex: 0 defaultAnswers: -> {} selectedClass: 'selected' # Callbacks _beforeAction: -> @setStore() @setConfig() @setQuestions() @setId() @setAnswers() @setQuestion() # Helpers setStore: -> @store = new SwanKiosk.Store.LocalStorage setConfig: -> @config = SwanKiosk.Config setId: -> @id = parseInt(@params.id, 10) || @lowIndex setQuestions: -> @questions = @config.questions setAnswers: -> @answers = @store.getObject(@storeKey) || @defaultAnswers() setQuestion: -> @question = @questions[@id] return unless @question? @checkPassWhenClause() checkPassWhenClause: -> whenClause = @question.when pass = true if whenClause? for key, value of whenClause if @answers[key] != value pass = false break unless pass @id++ @setQuestion() # Routes routes: ['show', 'results'] show: -> if @question? @questionKey = @question.key @answer = @answers[@questionKey] new SwanKiosk.Interpreters.Question @question, @answer else page.redirect '/questions/results' results: -> new SwanKiosk.Interpreters.Results @answers # Page Actions selectOption: (element, event) -> $answer = $ element $answer.siblings().removeClass @selectedClass $answer.addClass @selectedClass @answer = $answer.attr 'value' nextQuestion: (element, event) -> @storeAnswer() page.redirect "/questions/#{@id + 1}" storeAnswer: -> @answers[@questionKey] = @answer @store.set @storeKey, @answers prevQuestion: (element, event) -> page.redirect "/questions/#{@id - 1}" hasPreviousQuestion: -> @id > 0 startOver: (element, event) -> @clearAnswers() page.redirect "/questions/#{@lowIndex}" clearAnswers: -> @store.set @storeKey, @defaultAnswers()
18319
class SwanKiosk.Controllers.QuestionsController extends SwanKiosk.Controller layout: SwanKiosk.Components.layout storeKey: 'question<KEY>.answers' lowIndex: 0 defaultAnswers: -> {} selectedClass: 'selected' # Callbacks _beforeAction: -> @setStore() @setConfig() @setQuestions() @setId() @setAnswers() @setQuestion() # Helpers setStore: -> @store = new SwanKiosk.Store.LocalStorage setConfig: -> @config = SwanKiosk.Config setId: -> @id = parseInt(@params.id, 10) || @lowIndex setQuestions: -> @questions = @config.questions setAnswers: -> @answers = @store.getObject(@storeKey) || @defaultAnswers() setQuestion: -> @question = @questions[@id] return unless @question? @checkPassWhenClause() checkPassWhenClause: -> whenClause = @question.when pass = true if whenClause? for key, value of whenClause if @answers[key] != value pass = false break unless pass @id++ @setQuestion() # Routes routes: ['show', 'results'] show: -> if @question? @questionKey = @question.key @answer = @answers[@questionKey] new SwanKiosk.Interpreters.Question @question, @answer else page.redirect '/questions/results' results: -> new SwanKiosk.Interpreters.Results @answers # Page Actions selectOption: (element, event) -> $answer = $ element $answer.siblings().removeClass @selectedClass $answer.addClass @selectedClass @answer = $answer.attr 'value' nextQuestion: (element, event) -> @storeAnswer() page.redirect "/questions/#{@id + 1}" storeAnswer: -> @answers[@questionKey] = @answer @store.set @storeKey, @answers prevQuestion: (element, event) -> page.redirect "/questions/#{@id - 1}" hasPreviousQuestion: -> @id > 0 startOver: (element, event) -> @clearAnswers() page.redirect "/questions/#{@lowIndex}" clearAnswers: -> @store.set @storeKey, @defaultAnswers()
true
class SwanKiosk.Controllers.QuestionsController extends SwanKiosk.Controller layout: SwanKiosk.Components.layout storeKey: 'questionPI:KEY:<KEY>END_PI.answers' lowIndex: 0 defaultAnswers: -> {} selectedClass: 'selected' # Callbacks _beforeAction: -> @setStore() @setConfig() @setQuestions() @setId() @setAnswers() @setQuestion() # Helpers setStore: -> @store = new SwanKiosk.Store.LocalStorage setConfig: -> @config = SwanKiosk.Config setId: -> @id = parseInt(@params.id, 10) || @lowIndex setQuestions: -> @questions = @config.questions setAnswers: -> @answers = @store.getObject(@storeKey) || @defaultAnswers() setQuestion: -> @question = @questions[@id] return unless @question? @checkPassWhenClause() checkPassWhenClause: -> whenClause = @question.when pass = true if whenClause? for key, value of whenClause if @answers[key] != value pass = false break unless pass @id++ @setQuestion() # Routes routes: ['show', 'results'] show: -> if @question? @questionKey = @question.key @answer = @answers[@questionKey] new SwanKiosk.Interpreters.Question @question, @answer else page.redirect '/questions/results' results: -> new SwanKiosk.Interpreters.Results @answers # Page Actions selectOption: (element, event) -> $answer = $ element $answer.siblings().removeClass @selectedClass $answer.addClass @selectedClass @answer = $answer.attr 'value' nextQuestion: (element, event) -> @storeAnswer() page.redirect "/questions/#{@id + 1}" storeAnswer: -> @answers[@questionKey] = @answer @store.set @storeKey, @answers prevQuestion: (element, event) -> page.redirect "/questions/#{@id - 1}" hasPreviousQuestion: -> @id > 0 startOver: (element, event) -> @clearAnswers() page.redirect "/questions/#{@lowIndex}" clearAnswers: -> @store.set @storeKey, @defaultAnswers()
[ { "context": "an_educator: \"I'm an Educator\"\n im_a_teacher: \"Sóc Docent\"\n im_a_student: \"Sóc Alumna/e\"\n learn_more:", "end": 9361, "score": 0.9998894929885864, "start": 9351, "tag": "NAME", "value": "Sóc Docent" }, { "context": "res\"\n contact: \"Contacta\"\n ...
app/locale/ca.coffee
toivomattila/codecombat
0
module.exports = nativeDescription: "Català", englishDescription: "Catalan", translation: new_home: # title: "CodeCombat - Coding games to learn Python and JavaScript" # meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." # built_for_teachers_title: "A Coding Game Built with Teachers in Mind" # built_for_teachers_blurb: "Teaching kids to code can often feel overwhelming. CodeCombat helps all educators teach students how to code in either JavaScript or Python, two of the most popular programming languages. With a comprehensive curriculum that includes six computer science units and reinforces learning through project-based game development and web development units, kids will progress on a journey from basic syntax to recursion!" # built_for_teachers_subtitle1: "Computer Science" # built_for_teachers_subblurb1: "Starting with our free Introduction to Computer Science course, students master core coding concepts such as while/for loops, functions, and algorithms." # built_for_teachers_subtitle2: "Game Development" # built_for_teachers_subblurb2: "Learners construct mazes and use basic input handling to code their own games that can be shared with friends and family." # built_for_teachers_subtitle3: "Web Development" # built_for_teachers_subblurb3: "Using HTML, CSS, and jQuery, learners flex their creative muscles to program their own webpages with a custom URL to share with their classmates." # century_skills_title: "21st Century Skills" # century_skills_blurb1: "Students Don't Just Level Up Their Hero, They Level Up Themselves" # century_skills_quote1: "You mess up…so then you think about all of the possible ways to fix it, and then try again. I wouldn't be able to get here without trying hard." # century_skills_subtitle1: "Critical Thinking" # century_skills_subblurb1: "With coding puzzles that are naturally scaffolded into increasingly challenging levels, CodeCombat's programming game ensures kids are always practicing critical thinking." # century_skills_quote2: "Everyone else was making mazes, so I thought, ‘capture the flag’ and that’s what I did." # century_skills_subtitle2: "Creativity" # century_skills_subblurb2: "CodeCombat encourages students to showcase their creativity by building and sharing their own games and webpages." # century_skills_quote3: "If I got stuck on a level. I would work with people around me until we were all able to figure it out." # century_skills_subtitle3: "Collaboration" # century_skills_subblurb3: "Throughout the game, there are opportunities for students to collaborate when they get stuck and to work together using our pair programming guide." # century_skills_quote4: "I’ve always had aspirations of designing video games and learning how to code ... this is giving me a great starting point." # century_skills_subtitle4: "Communication" # century_skills_subblurb4: "Coding requires kids to practice new forms of communication, including communicating with the computer itself and conveying their ideas using the most efficient code." # classroom_in_box_title: "We Strive To:" # classroom_in_box_blurb1: "Engage every student so that they believe coding is for them." # classroom_in_box_blurb2: "Empower any educator to feel confident when teaching coding." # classroom_in_box_blurb3: "Inspire all school leaders to create a world-class computer science program." # creativity_rigor_title: "Where Creativity Meets Rigor" # creativity_rigor_subtitle1: "Make coding fun and teach real-world skills" # creativity_rigor_blurb1: "Students type real Python and JavaScript while playing games that encourage trial-and-error, critical thinking, and creativity. Students then apply the coding skills they’ve learned by developing their own games and websites in project-based courses." # creativity_rigor_subtitle2: "Reach students at their level" # creativity_rigor_blurb2: "Every CodeCombat level is scaffolded based on millions of data points and optimized to adapt to each learner. Practice levels and hints help students when they get stuck, and challenge levels assess students' learning throughout the game." # creativity_rigor_subtitle3: "Built for all teachers, regardless of experience" # creativity_rigor_blurb3: "CodeCombat’s self-paced, standards-aligned curriculum makes teaching computer science possible for everyone. CodeCombat equips teachers with the training, instructional resources, and dedicated support to feel confident and successful in the classroom." # featured_partners_title1: "Featured In" # featured_partners_title2: "Awards & Partners" # featured_partners_blurb1: "CollegeBoard Endorsed Provider" # featured_partners_blurb2: "Best Creativity Tool for Students" # featured_partners_blurb3: "Top Pick for Learning" # featured_partners_blurb4: "Code.org Official Partner" # featured_partners_blurb5: "CSforAll Official Member" # featured_partners_blurb6: "Hour of Code Activity Partner" # for_leaders_title: "For School Leaders" # for_leaders_blurb: "A Comprehensive, Standards-Aligned Computer Science Program" # for_leaders_subtitle1: "Easy Implementation" # for_leaders_subblurb1: "A web-based program that requires no IT support. Get started in under 5 minutes using Google or Clever Single Sign-On (SSO)." # for_leaders_subtitle2: "Full Coding Curriculum" # for_leaders_subblurb2: "A standards-aligned curriculum with instructional resources and professional development to enable any teacher to teach computer science." # for_leaders_subtitle3: "Flexible Use Cases" # for_leaders_subblurb3: "Whether you want to build a Middle School coding elective, a CTE pathway, or an AP Computer Science Principles class, CodeCombat is tailored to suit your needs." # for_leaders_subtitle4: "Real-World Skills" # for_leaders_subblurb4: "Students build grit and develop a growth mindset through coding challenges that prepare them for the 500K+ open computing jobs." # for_teachers_title: "For Teachers" # for_teachers_blurb: "Tools to Unlock Student Potential" # for_teachers_subtitle1: "Project-Based Learning" # for_teachers_subblurb1: "Promote creativity, problem-solving, and confidence in project-based courses where students develop their own games and webpages." # for_teachers_subtitle2: "Teacher Dashboard" # for_teachers_subblurb2: "View data on student progress, discover curriculum resources, and access real-time support to empower student learning." # for_teachers_subtitle3: "Built-in Assessments" # for_teachers_subblurb3: "Personalize instruction and ensure students understand core concepts with formative and summative assessments." # for_teachers_subtitle4: "Automatic Differentiation" # for_teachers_subblurb4: "Engage all learners in a diverse classroom with practice levels that adapt to each student's learning needs." # game_based_blurb: "CodeCombat is a game-based computer science program where students type real code and see their characters react in real time." # get_started: "Get started" # global_title: "Join Our Global Community of Learners and Educators" # global_subtitle1: "Learners" # global_subtitle2: "Lines of Code" # global_subtitle3: "Teachers" # global_subtitle4: "Countries" # go_to_my_classes: "Go to my classes" # go_to_my_courses: "Go to my courses" # quotes_quote1: "Name any program online, I’ve tried it. None of them match up to CodeCombat. Any teacher who wants their students to learn how to code... start here!" # quotes_quote2: " I was surprised about how easy and intuitive CodeCombat makes learning computer science. The scores on the AP exam were much higher than I expected and I believe CodeCombat is the reason why this was the case." # quotes_quote3: "CodeCombat has been the most beneficial for teaching my students real-life coding capabilities. My husband is a software engineer and he has tested out all of my programs. He put this as his top choice." # quotes_quote4: "The feedback … has been so positive that we are structuring a computer science class around CodeCombat. The program really engages the students with a gaming style platform that is entertaining and instructional at the same time. Keep up the good work, CodeCombat!" # see_example: "See example" slogan: "El joc més atractiu per aprendre a programar." # {change} # teach_cs1_free: "Teach CS1 Free" # teachers_love_codecombat_title: "Teachers Love CodeCombat" # teachers_love_codecombat_blurb1: "Report that their students enjoy using CodeCombat to learn how to code" # teachers_love_codecombat_blurb2: "Would recommend CodeCombat to other computer science teachers" # teachers_love_codecombat_blurb3: "Say that CodeCombat helps them support students’ problem solving abilities" # teachers_love_codecombat_subblurb: "In partnership with McREL International, a leader in research-based guidance and evaluations of educational technology." # try_the_game: "Try the game" classroom_edition: "Edició d'Aula:" learn_to_code: "Aprendre a programar:" play_now: "Juga Ara" # im_an_educator: "I'm an Educator" im_a_teacher: "Sóc Docent" im_a_student: "Sóc Alumna/e" learn_more: "Aprén més" classroom_in_a_box: "Una aula preparada per a l'ensenyament de la informàtica." codecombat_is: "CodeCombat és una plataforma <strong> per als estudiants </ strong> per aprendre ciències de la computació mentre es juga a través d'un veritable joc." our_courses: "Els nostres cursos han estat específicament provats <strong> de manera excel·lent a l'aula </ strong>, fins i tot per a professorat amb poca o cap experiència prèvia de programació." watch_how: "Observeu com CodeCombat està transformant la manera com la gent aprèn la informàtica." top_screenshots_hint: "Els alumnes escriuen el codi i veuen la seva actualització de canvis en temps real" designed_with: "Dissenyat pensant en el professorat" real_code: "Codi real tipificat" from_the_first_level: "des del nivell elemental" getting_students: "Acostumar l'alumnat al codi escrit amb la major rapidesa possible és fonamental per aprendre la sintaxi de programació i l'estructura adient." educator_resources: "Recursos educatius" course_guides: "i guies de curs" teaching_computer_science: "L'ensenyament de la informàtica no requereix un estudi costós, ja que proporcionem eines per donar suport als educadors de tots els àmbits." accessible_to: "Accessible a" everyone: "tothom" democratizing: "Democratitzar el procés d'aprenentatge de codificació és el nucli de la nostra filosofia. Tothom ha de poder aprendre a codificar." forgot_learning: "Crec que en realitat es van oblidar que realment estaven aprenent." wanted_to_do: " La codificació és una cosa que sempre he volgut fer, i mai vaig pensar que seria capaç d'aprendre a l'escola." builds_concepts_up: "M'agrada com CodeCombat construeix els conceptes. Realment és fàcil d'entendre i divertit de comprovar." why_games: "Per què és important aprendre mitjançant els jocs?" games_reward: "Els jocs recompensen la lluita productiva." encourage: "El joc és un mitjà que afavoreix la interacció, el descobriment i la prova i error. Un bon joc desafia el jugador a dominar les habilitats al llarg del temps, que és el mateix procés crític que passen els estudiants a mesura que aprenen." excel: "Els jocs són excel·lents en recompensar" struggle: "lluita productiva" kind_of_struggle: "el tipus de lluita que resulta en l'aprenentatge que és comprometent i" motivating: "motivador" not_tedious: "no tediós." gaming_is_good: "Els estudis confirmen que jugar és bo pel desenvolupament de la ment dels infants. (De debó!)" game_based: "Quan el sistema d'aprenenetatge basat en jocs és" compared: "comparat" conventional: "amb els mètodes d'avaluació convencionals, la diferència és clara: els jocs són millors per ajudar l'alumnat a mantenir el coneixement, concentrar-se i" perform_at_higher_level: "assolir un major rendiment" feedback: "Els jocs també proporcionen comentaris en temps real que permeten a l'alumnat ajustar la seva ruta de solució i entendre conceptes de manera més holística, en lloc de limitar-se a respostes “correctes” o “incorrectes”." real_game: "Un joc real, jugat amb la codificació real." great_game: "Un gran joc és més que simples emblemes i èxits: es tracta del viatge d'un jugador, dels trencaclosques ben dissenyats i de la capacitat per afrontar els desafiaments amb decisió i confiança." agency: "CodeCombat és un joc que dóna als jugadors aquesta decisió i confiança amb el nostre robust motor de codi mecanografiat, que ajuda tant als estudiants principiants com a estudiants avançats a escriure el codi correcte i vàlid." request_demo_title: "Comença avui mateix amb el teu alumnat!" request_demo_subtitle: "Sol·licita una demo i fes que el teu alumnat comenci en menys d'una hora." get_started_title: "Configureu la vostra classe avui mateix" get_started_subtitle: "Configureu una classe, afegiu-hi l'alumnat i seguiu el seu progrés a mesura que aprenguin informàtica." request_demo: "Sol·liciteu una demostració" # request_quote: "Request a Quote" setup_a_class: "Configureu una Classe" have_an_account: "Tens un compte?" logged_in_as: "Ja has iniciat la sessió com a" computer_science: "Els nostres cursos autoformatius cobreixen la sintaxi bàsica als conceptes avançats" ffa: "Gratuït per a tot l'alumnat" coming_soon: "Aviat, més!" courses_available_in: "Els cursos estan disponibles a JavaScript i Python. Els cursos de desenvolupament web utilitzen HTML, CSS i jQuery." boast: "Compta amb endevinalles que són prou complexas per fascinar als jugadors i als codificadors." winning: "Una combinació exitosa del joc de rol i la tasca de programació que fa que l'educació educativa sigui legítimament agradable." run_class: "Tot el que necessiteu per dirigir una classe d'informàtica a la vostra escola avui dia, no cal preparar res." goto_classes: "Ves a Les Meves Classes" view_profile: "Veure El meu Perfil" view_progress: "Veure Progrés" go_to_courses: "Vés a Els meus Cursos" want_coco: "Vols CodeCombat al teu centre?" # educator: "Educator" # student: "Student" nav: # educators: "Educators" # follow_us: "Follow Us" # general: "General" map: "Mapa" play: "Nivells" # The top nav bar entry where players choose which levels to play community: "Comunitat" courses: "Cursos" blog: "Bloc" forum: "Fòrum" account: "Compte" my_account: "El Meu Compte" profile: "Perfil" home: "Inici" contribute: "Col·laborar" legal: "Legalitat" privacy: "Privadesa" about: "Sobre Nosaltres" contact: "Contacta" twitter_follow: "Segueix-nos" my_classrooms: "Les Meves Classes" my_courses: "Els Meus Cursos" # my_teachers: "My Teachers" careers: "Professions" facebook: "Facebook" twitter: "Twitter" create_a_class: "Crear una Classe" other: "Altra" learn_to_code: "Aprendre a Programar!" toggle_nav: "Commuta la Navegació" schools: "Centres" get_involved: "Involucrar-se" open_source: "Codi Obert (GitHub)" support: "Suport" faqs: "Preguntes freqüents" copyright_prefix: "Copyright" copyright_suffix: "Tots els drets reservats." help_pref: "Necessites ajuda? Envia'ns un e-mail" help_suff: "i contactarem amb tu!" resource_hub: "Centre de Recursos" apcsp: "Principis AP CS" parent: "Pares" modal: close: "Tancar" okay: "D'acord" not_found: page_not_found: "Pàgina no trobada" diplomat_suggestion: title: "Ajuda a traduir CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Neccesitem les teves habilitats lingüístiques." pitch_body: "Hem desenvolupat CodeCombat en anglès, però tenim jugadors per tot el món. Molts d'ells volen jugar en Català, però no parlen anglès, per tant si pots parlar ambdues llengües, siusplau considereu iniciar sessió per a ser Diplomàtic i ajudar a traduir la web de CodeCombat i tots els seus nivells en Català." missing_translations: "Fins que puguem traduir-ho tot en català, ho veuràs en anglès quant no estigui en català." learn_more: "Aprèn més sobre ser un diplomàtic" subscribe_as_diplomat: "Subscriu-te com a diplomàtic" play: # title: "Play CodeCombat Levels - Learn Python, JavaScript, and HTML" # meta_description: "Learn programming with a coding game for beginners. Learn Python or JavaScript as you solve mazes, make your own games, and level up. Challenge your friends in multiplayer arena levels!" # level_title: "__level__ - Learn to Code in Python, JavaScript, HTML" # video_title: "__video__ | Video Level" # game_development_title: "__level__ | Game Development" # web_development_title: "__level__ | Web Development" # anon_signup_title_1: "CodeCombat has a" # anon_signup_title_2: "Classroom Version!" # anon_signup_enter_code: "Enter Class Code:" # anon_signup_ask_teacher: "Don't have one? Ask your teacher!" # anon_signup_create_class: "Want to create a class?" # anon_signup_setup_class: "Set up a class, add your students, and monitor progress!" # anon_signup_create_teacher: "Create free teacher account" play_as: "Jugar com" # Ladder page get_course_for_class: "Assigna el desenvolupament del joc i més a les vostres classes!" request_licenses: "Posa't en contacte amb els especialistes del centre per obtenir més informació." compete: "Competir!" # Course details page spectate: "Espectador" # Ladder page players: "Jugadors" # Hover over a level on /play hours_played: "Hores jugades" # Hover over a level on /play items: "Objectes" # Tooltip on item shop button from /play unlock: "Desbloquejar" # For purchasing items and heroes confirm: "Confirmar" owned: "Adquirit" # For items you own locked: "Bloquejat" available: "Disponible" skills_granted: "Habilitats Garantides" # Property documentation details heroes: "Herois" # Tooltip on hero shop button from /play achievements: "Triomfs" # Tooltip on achievement list button from /play settings: "Configuració" # Tooltip on settings button from /play poll: "Enquesta" # Tooltip on poll button from /play next: "Següent" # Go from choose hero to choose inventory before playing a level change_hero: "Canviar heroi" # Go back from choose inventory to choose hero change_hero_or_language: "Canviar heroi o Idioma" buy_gems: "Comprar Gemmes" subscribers_only: "Només subscriptors!" subscribe_unlock: "Subscriu-te per desbloquejar!" subscriber_heroes: "Subscriu-te avui per desbloquejar immediatament a Amara, Hushbaum i Hattori!" subscriber_gems: "Subscriu-te avui per comprar aquest heroi amb gemmes!" anonymous: "Jugador anònim" level_difficulty: "Dificultat: " awaiting_levels_adventurer_prefix: "Publiquem nous nivells cada setmana." awaiting_levels_adventurer: "Inicia sessió com a aventurer" awaiting_levels_adventurer_suffix: "Sigues el primer en jugar els nous nivells" adjust_volume: "Ajustar volum" campaign_multiplayer: "Arenes Multijugador" campaign_multiplayer_description: "... on programes cara a cara contra altres jugadors." brain_pop_done: "Has derrotat els ogres amb el codi! Tu guanyes!" brain_pop_challenge: "Desafíeu-vos a jugar de nou utilitzant un llenguatge de programació diferent." replay: "Repeteix" back_to_classroom: "Tornar a l'aula" teacher_button: "Per a Docents" get_more_codecombat: "Obté més CodeCombat" code: if: "si" # Keywords--these translations show up on hover, so please translate them all, even if it's kind of long. (In the code editor, they will still be in English.) else: "en cas contrari" elif: "en cas contrari, si" while: "mentre" loop: "repeteix" for: "des de" break: "trenca" continue: "continua" pass: "passar" return: "return" then: "llavors" do: "fes" end: "fi" function: "funció" def: "defineix" var: "variable" self: "si mateix" hero: "heroi" this: "això" or: "o" "||": "o" and: "i" "&&": "i" not: "no" "!": "no" "=": "assigna" "==": "igual" "===": "estrictament iguals" "!=": "no és igual" "!==": "no és estrictament igual" ">": "és més gran que" ">=": "és més gran o igual" "<": "és més petit que" "<=": "és més petit o igual" "*": "multiplicat per" "/": "dividit per" "+": "més" "-": "menys" "+=": "suma i assigna" "-=": "resta i assigna" True: "Veritat" true: "veritat" False: "Fals" false: "fals" undefined: "indefinit" null: "nul" nil: "nul" None: "Cap" share_progress_modal: blurb: "Estàs progressant molt! Digues als teus pares quant n'has après amb CodeCombat." email_invalid: "Correu electrònic invàlid." form_blurb: "Escriu els seus emails a sota i els hi ensenyarem!" form_label: "Correu electrònic" placeholder: "adreça de correu electrònic" title: "Excel·lent feina, aprenent" login: sign_up: "Crear un compte" email_or_username: "E-mail o usuari" log_in: "Iniciar Sessió" logging_in: "Iniciant Sessió" log_out: "Tancar Sessió" forgot_password: "Contrasenya oblidada?" finishing: "Acabant" sign_in_with_facebook: "Inicia amb Facebook" sign_in_with_gplus: "Inicia amb G+" signup_switch: "Vols crear-te un compte?" signup: complete_subscription: "Subscripció completa" create_student_header: "Crea un compte d'estudiant" create_teacher_header: "Crea un compte de docent" create_individual_header: "Crea un compte Individual" email_announcements: "Rebre anuncis sobre nous nivells CodeCombat i les seves característiques" sign_in_to_continue: "Inicieu sessió o creeu un compte per continuar" teacher_email_announcements: "Mantén-me actualitzat sobre nous recursos docents, currículum i cursos!" creating: "Creant Compte..." sign_up: "Registrar-se" log_in: "Iniciar sessió amb la teva contrasenya" # login: "Login" required: "Neccesites iniciar sessió abans ." login_switch: "Ja tens un compte?" optional: "opcional" connected_gplus_header: "Has connectat correctament amb Google+." connected_gplus_p: "Accediu a la subscripció perquè pugueu iniciar la sessió amb el vostre compte de Google+." connected_facebook_header: "Has connectat correctament amb Facebook!" connected_facebook_p: "Finalitzeu la subscripció perquè pugueu iniciar sessió amb el vostre compte de Facebook." hey_students: "Estudiants, introduïu el codi de classe del vostre professor." birthday: "Aniversari" parent_email_blurb: "Sabem que no podeu esperar per a aprendre programació &mdash; A nosaltres també ens emociona. Els vostres pares rebran un e-mail amb més instruccions sobre com crear un compte per a vosaltres. Podeu escriure a l'e-mail ({email_link}} si teniu algun dubte." classroom_not_found: "No existeixen classes amb aquest Codi de classe. Consulteu la ortografia o demaneu ajuda al vostre professor." checking: "Comprovant..." account_exists: "Aquest e-mail ja està en ús:" sign_in: "Inicieu sessió" email_good: "El correu electrònic està bé!" name_taken: "El nom d'usuari ja està agafat! Prova amb {{suggestedName}}?" name_available: "Nom d'usuari disponible!" name_is_email: "El nom d'usuari no pot ser un e-mail" choose_type: "Tria el teu tipus de compte:" teacher_type_1: "Ensenyeu la programació amb CodeCombat!" teacher_type_2: "Configureu la vostra classe" teacher_type_3: "Accediu a guies del curs" teacher_type_4: "Mostra el progrés de l'alumnat" signup_as_teacher: "Registra't com a docent" student_type_1: "Aprèn a programar mentre fas un joc atractiu!" student_type_2: "Juga amb la teva classe" student_type_3: "Competeix en els estàdiums" student_type_4: "Tria el teu heroi!" student_type_5: "Tingues preparat el teu Codi de classe!" signup_as_student: "Registra't com a estudiant" individuals_or_parents: "Particulars i pares" individual_type: "Per als jugadors que aprenen a codificar fora d'una classe. Els pares s'han d'inscriure a un compte aquí." signup_as_individual: "Inscriviu-vos com a particular" enter_class_code: "Introduïu el codi de la vostra classe" enter_birthdate: "Introduïu la data de naixement:" parent_use_birthdate: "Pares, utilitzeu la vostra data de naixement." ask_teacher_1: "Pregunteu al vostre professor pel vostre codi de classe." ask_teacher_2: "No és part d'una classe? Crea un " ask_teacher_3: "Compte Individual" ask_teacher_4: " en el seu lloc." about_to_join: "Estàs a punt d'unir-te:" enter_parent_email: "Introduïu l'adreça electrònica del vostres pares:" parent_email_error: "S'ha produït un error al intentar enviar el correu electrònic. Comproveu l'adreça de correu electrònic i torneu-ho a provar." parent_email_sent: "Hem enviat un correu electrònic amb més instruccions sobre com crear un compte. Demaneu als vostres pares que comprovin la seva safata d'entrada." account_created: "S'ha creat el compte!" confirm_student_blurb: "Escriviu la vostra informació perquè no us oblideu. El vostre professor també us pot ajudar a restablir la vostra contrasenya en qualsevol moment." confirm_individual_blurb: "Escriviu la informació d'inici de sessió en cas que la necessiti més tard. Verifiqueu el vostre correu electrònic perquè pugueu recuperar el vostre compte si alguna vegada us oblideu de la contrasenya: consulteu la safata d'entrada!" write_this_down: "Escriviu això:" start_playing: "Comença a jugar!" sso_connected: "S'ha connectat correctament amb:" select_your_starting_hero: "Seleccioneu el vostre heroi inicial:" you_can_always_change_your_hero_later: "Sempre podeu canviar l'heroi més tard." finish: "Acaba" teacher_ready_to_create_class: "Estàs preparat per crear la teva primera classe!" teacher_students_can_start_now: "Els teus alumnes podran començar a jugar immediatament al primer curs, Introducció a la informàtica." teacher_list_create_class: "A la pantalla següent podreu crear una nova classe." teacher_list_add_students: "Afegiu estudiants a la classe fent clic a l'enllaç Visualitza la classe i, a continuació, envia als vostres estudiants el codi de la classe o l'URL. També podeu convidar-los per correu electrònic si tenen adreces de correu electrònic." teacher_list_resource_hub_1: "Consulteu les" teacher_list_resource_hub_2: "Guies del Curs" teacher_list_resource_hub_3: "per obtenir solucions a tots els nivells, i el" teacher_list_resource_hub_4: "Centre de Recursos" teacher_list_resource_hub_5: "per guies curriculars, activitats i molt més!" teacher_additional_questions: "Això és! Si necessiteu ajuda addicional o teniu preguntes, consulteu __supportEmail__." dont_use_our_email_silly: "No posis el teu correu electrònic aquí! Posa el correu electrònic dels teus pares." want_codecombat_in_school: "Vols jugar CodeCombat tot el temps?" eu_confirmation: "Estic d'acord en permetre que CodeCombat desi les meves dades als servidors dels EE.UU." eu_confirmation_place_of_processing: "Saber més sobre possibles riscos" eu_confirmation_student: "Si dubtes, consulta al teu professorat." eu_confirmation_individual: "Si no vols que desem les teves dades als servidors dels EE.UU., sempre pots continuar jugant de manera anònima sense desar el teu codi." recover: recover_account_title: "Recuperar Compte" send_password: "Enviar contrasenya oblidada" recovery_sent: "Correu de recuperació de contrasenya enviat." items: primary: "Primari" secondary: "Secundari" armor: "Armadura" accessories: "Accessoris" misc: "Misc" books: "Llibres" common: # default_title: "CodeCombat - Coding games to learn Python and JavaScript" # default_meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." back: "Endarrere" # When used as an action verb, like "Navigate backward" coming_soon: "Pròximament!" continue: "Continua" # When used as an action verb, like "Continue forward" next: "Següent" default_code: "Codi per defecte" loading: "Carregant..." overview: "Resum" processing: "Processant..." solution: "Solució" table_of_contents: "Taula de Continguts" intro: "Intro" saving: "Guardant..." sending: "Enviant..." send: "Enviar" sent: "Enviat" cancel: "Cancel·lant" save: "Guardar" publish: "Publica" create: "Crear" fork: "Fork" play: "Jugar" # When used as an action verb, like "Play next level" retry: "Tornar a intentar" actions: "Accions" info: "Info" help: "Ajuda" watch: "Veure" unwatch: "Amaga" submit_patch: "Enviar pegat" submit_changes: "Puja canvis" save_changes: "Guarda canvis" required_field: "obligatori" general: and: "i" name: "Nom" date: "Data" body: "Cos" version: "Versió" pending: "Pendent" accepted: "Acceptat" rejected: "Rebutjat" withdrawn: "Retirat" accept: "Accepta" accept_and_save: "Accepta i desa" reject: "Refusa" withdraw: "Retira" submitter: "Remitent" submitted: "Presentat" commit_msg: "Enviar missatge" version_history: "Historial de versions" version_history_for: "Historial de versions per: " select_changes: "Selecciona dos canvis de sota per veure les diferències." undo_prefix: "Desfer" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Refés" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Reproduir avanç del nivell actual" result: "Resultat" results: "Resultats" description: "Descripció" or: "o" subject: "Tema" email: "Correu electrònic" password: "Contrasenya" confirm_password: "Confirmar Contrasenya" message: "Missatge" code: "Codi" ladder: "Escala" when: "Quan" opponent: "Oponent" rank: "Rang" score: "Puntuació" win: "Guanyats" loss: "Perduts" tie: "Empat" easy: "Fàcil" medium: "Intermedi" hard: "Difícil" player: "Jugador" player_level: "Nivell" # Like player level 5, not like level: Dungeons of Kithgard warrior: "Guerrer" ranger: "Explorador" wizard: "Mag" first_name: "Nom" last_name: "Cognom" last_initial: "Última inicial" username: "Usuari" contact_us: "Contacta amb nosaltres" close_window: "Tanca finestra" learn_more: "Aprèn més" more: "Més" fewer: "Menys" with: "amb" units: second: "segon" seconds: "segons" sec: "sec" minute: "minut" minutes: "minuts" hour: "hora" hours: "hores" day: "dia" days: "dies" week: "setmana" weeks: "setmanes" month: "mes" months: "mesos" year: "any" years: "anys" play_level: back_to_map: "Torna al mapa" directions: "Direccions" edit_level: "Edita Nivell" keep_learning: "Segueix aprenent" explore_codecombat: "Explora CodeCombat" finished_hoc: "He acabat amb la meva Hora de Codi" get_certificate: "Aconsegueix el teu certificat!" level_complete: "Nivell complet" completed_level: "Nivell completat:" course: "Curs:" done: "Fet" next_level: "Següent nivell" combo_challenge: "Repte combinat" concept_challenge: "Repte conceptual" challenge_unlocked: "Repte desbloquejat" combo_challenge_unlocked: "Repte combinat desbloquejat" concept_challenge_unlocked: "Repte conceptual desbloquejat" concept_challenge_complete: "Repte Conceptual Complet!" combo_challenge_complete: "Repte Combinat Complet!" combo_challenge_complete_body: "Bona feina, sembla que estàs disfrutant d'entendre __concept__!" replay_level: "Repeteix Nivell" combo_concepts_used: "__complete__/__total__ conceptes emprats" combo_all_concepts_used: "Has fet servir tots els conceptes possibles per resoldre el repte. Bona feina!" combo_not_all_concepts_used: "Has emprat __complete__ dels __total__ conceptes possibles per resoldre el repte. Prova d'emprar tots __total__ conceptes la propera vegada!" start_challenge: "Començar el Repte" next_game: "Següent joc" languages: "Llenguatges" programming_language: "Llenguatge de Programació" show_menu: "Mostrar menú del joc" home: "Inici" # Not used any more, will be removed soon. level: "Nivell" # Like "Level: Dungeons of Kithgard" skip: "Ometre" game_menu: "Menú de joc" restart: "Reiniciar" goals: "Objectius" goal: "Objectiu" challenge_level_goals: "Objectius del Nivell del Repte" challenge_level_goal: "Objectiu del Nivell del Repte" concept_challenge_goals: "Objectius del Repte Conceptual" combo_challenge_goals: "Objectius del Repte Combinat" concept_challenge_goal: "Objectiu del Repte Conceptual" combo_challenge_goal: "Objectiu del Repte Combinat" running: "Executant..." success: "Èxit!" incomplete: "Incomplet" timed_out: "S'ha acabat el temps" failing: "Fallant" reload: "Recarregar" reload_title: "Recarregar tot el codi?" reload_really: "Estàs segur que vols recarregar aquest nivell des del principi?" reload_confirm: "Recarregar tot" test_level: "Test de Nivell" victory: "Victòria" victory_title_prefix: "" victory_title_suffix: " Complet" victory_sign_up: "Inicia sessió per a desar el progressos" victory_sign_up_poke: "Vols guardar el teu codi? Crea un compte gratuït!" victory_rate_the_level: "Era molt divertit aquest nivell?" victory_return_to_ladder: "Retorna a les Escales" victory_saving_progress: "Desa progrés" victory_go_home: "Tornar a l'inici" victory_review: "Explica'ns més!" victory_review_placeholder: "Com ha anat el nivell?" victory_hour_of_code_done: "Has acabat?" victory_hour_of_code_done_yes: "Sí, he acabat amb la meva Hora del Codi™!" victory_experience_gained: "XP Guanyada" victory_gems_gained: "Gemmes guanyades" victory_new_item: "Objecte nou" victory_new_hero: "Nou Heroi" victory_viking_code_school: "Ostres! Aquest nivell era un nivell difícil de superar! Si no ets un programador, ho hauries de ser. Acabes d'aconseguir una acceptació per la via ràpida a l'Escola de Programació Vikinga, on pot millorar les teves habilitats fins al següent nivell i esdevenir un programador de webs professional en 14 setmanes." victory_become_a_viking: "Converteix-te en un víking" victory_no_progress_for_teachers: "El progrés no es guarda per als professors. Però, podeu afegir un compte d'estudiant a l'aula per vosaltres mateixos." tome_cast_button_run: "Executar" tome_cast_button_running: "Executant" tome_cast_button_ran: "Executat" tome_submit_button: "Envia" tome_reload_method: "Recarrega el codi original per reiniciar el nivell" tome_available_spells: "Encanteris disponibles" tome_your_skills: "Les teves habilitats" hints: "Consells" # videos: "Videos" hints_title: "Consell {{number}}" code_saved: "Codi Guardat" skip_tutorial: "Ometre (esc)" keyboard_shortcuts: "Dreceres del teclat" loading_start: "Comença el nivell" loading_start_combo: "Començar Repte Combinat" loading_start_concept: "Començar Repte Conceptual" problem_alert_title: "Arregla el Teu Codi" time_current: "Ara:" time_total: "Màxim:" time_goto: "Ves a:" non_user_code_problem_title: "Impossible carregar el nivell" infinite_loop_title: "Detectat un bucle infinit" infinite_loop_description: "El codi inicial mai acaba d'executar-se. Probablement sigui molt lent o tingui un bucle infinit. O pot ser un error. Pots provar de tornar a executar el codi o reiniciar-lo al seu estat original. Si no es soluciona, si us plau, fes-nos-ho saber." check_dev_console: "També pots obrir la consola de desenvolupament per veure què surt malament." check_dev_console_link: "(instruccions)" infinite_loop_try_again: "Tornar a intentar" infinite_loop_reset_level: "Reiniciar nivell" infinite_loop_comment_out: "Treu els comentaris del meu codi" tip_toggle_play: "Canvia entre reproduir/pausa amb Ctrl+P" tip_scrub_shortcut: "Ctrl+[ i Ctrl+] per rebobinar i avançar ràpid" tip_guide_exists: "Clica a la guia dins el menú del joc (a la part superior de la pàgina) per informació útil." tip_open_source: "CodeCombat és 100% codi lliure!" tip_tell_friends: "Gaudint de CodeCombat? Explica'ls-ho als teus amics!" tip_beta_launch: "CodeCombat va llançar la seva beta l'octubre de 2013." tip_think_solution: "Pensa en la solució, no en el problema." tip_theory_practice: "En teoria no hi ha diferència entre la teoria i la pràctica. Però a la pràctica si que n'hi ha. - Yogi Berra" tip_error_free: "Només hi ha dues maneres d'escriure programes sense errors; la tercera és la única que funciona. - Alan Perlis" tip_debugging_program: "Si depurar és el procés per eliminar errors, llavors programar és el procés de posar-los. - Edsger W. Dijkstra" tip_forums: "Passa pels fòrums i digues el que penses!" tip_baby_coders: "En el futur fins i tot els nadons podran ser mags." tip_morale_improves: "La càrrega continuarà fins que la moral millori." tip_all_species: "Creiem en la igualtat d'oportunitats per aprendre a programar per a totes les espècies." tip_reticulating: "Reticulant punxes." tip_harry: "Ets un bruixot, " tip_great_responsibility: "Un gran coneixement del codi comporta una gran responsabilitat per a depurar-lo." tip_munchkin: "Si no menges les teves verdures, un munchkin vindrà mentre dormis." tip_binary: "Hi ha 10 tipus de persones al món, les que saben programar en binari i les que no" tip_commitment_yoda: "Un programador ha de tenir un compromís profund, una ment seriosa. ~ Yoda" tip_no_try: "Fes-ho. O no ho facis. Però no ho intentis. - Yoda" tip_patience: "Pacient has de ser, jove Padawan. - Yoda" tip_documented_bug: "Un error documentat no és un error; és un atractiu." tip_impossible: "Sempre sembla impossible fins que es fa. - Nelson Mandela" tip_talk_is_cheap: "Parlar és barat. Mostra'm el codi. - Linus Torvalds" tip_first_language: "La cosa més desastrosa que aprendràs mai és el teu primer llenguatge de programació. - Alan Kay" tip_hardware_problem: "P: Quants programadors són necessaris per canviar una bombeta? R: Cap, és un problema de hardware." tip_hofstadters_law: "Llei de Hofstadter: Sempre et portarà més feina del que esperaves, fins i tot tenint en compte la llei de Hofstadter." tip_premature_optimization: "La optimització prematura és l'arrel de la maldat. - Donald Knuth" tip_brute_force: "Quan dubtis, usa força bruta. - Ken Thompson" tip_extrapolation: "Hi ha dos tipus de persones: aquells que poden extrapolar des de dades incompletes..." tip_superpower: "Programar és el que més s'aproxima a un super poder." tip_control_destiny: "En un codi obert real tens el dret a controlar el teu propi destí. - Linus Torvalds" tip_no_code: "Cap codi és més ràpid que l'absència de codi." tip_code_never_lies: "El codi mai menteix, els comentaris a vegades. — Ron Jeffries" tip_reusable_software: "Abans que el codi sigui reutilitzable, ha de ser usable." tip_optimization_operator: "Cada llenguatge té un operador d'optimització. En la majoria d'ells és ‘//’" tip_lines_of_code: "Mesurar el progrés d'un codi per les seves línies és com mesurar el progrés d'un avió pel seu pes. — Bill Gates" tip_source_code: "Vull canviar el món, però no em vol donar el seu codi font." tip_javascript_java: "Java és a JavaScript el que un cotxe a una catifa. - Chris Heilmann" tip_move_forward: "Facis el que facis, sempre segueix endavant. - Martin Luther King Jr." tip_google: "Tens un problema que no pots resoldre? Cerca a Google!" tip_adding_evil: "Afegint una mica de maldat." tip_hate_computers: "La raó real per la qual la gent creu que odia els ordinadors és pels programadors pèssims. - Larry Niven" tip_open_source_contribute: "Pots ajudar a millorar CodeCombat!" tip_recurse: "La iteració és humana, la recursivitat és divina. - L. Peter Deutsch" tip_free_your_mind: "T'has de deixar endur, Neo. Por, dubtes, i incredulitat. Allibera la teva ment. - Morpheus" tip_strong_opponents: "Fins i tot el més fort dels oponents té alguna debilitat. - Itachi Uchiha" tip_paper_and_pen: "Abans de començar a programar, sempre has de començar planejant amb paper i boli." tip_solve_then_write: "Primer, resol el problema. Després, escriu el codi. - John Johnson" tip_compiler_ignores_comments: "De vegades crec que el compilador ignora els meus comentaris." tip_understand_recursion: "L'única manera d'entendre la recursió és comprendre la recursió." tip_life_and_polymorphism: "Open Source és com una estructura heterogènia totalment polimòrfica: tots els tipus són benvinguts." tip_mistakes_proof_of_trying: "Els errors del vostre codi són només una prova que esteu provant." tip_adding_orgres: "Arreglant els ogres." tip_sharpening_swords: "Afilant les espases." tip_ratatouille: "No podeu deixar que ningú defineixi els vostres límits a causa d'on prové. El vostre únic límit és la vostra ànima. - Gusteau, Ratatouille" tip_nemo: "Quan la vida et fa baixar, vols saber què has de fer? Només has de seguir nedant, només siguir nedant. - Dory, Cercant Nemo" tip_internet_weather: "Només has de mudar-te a Internet, es viu genial aquí. No sortim de casa on el clima és sempre increïble. - John Green" tip_nerds: "Als llestos se'ls permet estimar coses, com fer-petits-salts-d'emoció-a-la-cadira-sense-control. - John Green" tip_self_taught: "Em vaig ensenyar el 90% del que he après. I això és normal! - Hank Green" tip_luna_lovegood: "No et preocupis. Tens tan bon enteniment com jo. - Luna Lovegood" tip_good_idea: "La millor manera de tenir una bona idea és tenir moltes idees. - Linus Pauling" tip_programming_not_about_computers: "La informàtica no tracta tant sobre ordinadors com l'astronomia sobre telescopis. - Edsger Dijkstra" tip_mulan: "Pensa que pots, llavors ho faràs. - Mulan" project_complete: "Projecte Complet!" share_this_project: "Comparteix aquest projecte amb amics o familiars:" ready_to_share: "Preparat per publicar el teu projecte?" click_publish: "Fes clic a \"Publicar\" per fer que aparegui a la galeria de classes i, a continuació, mira els projectes dels teus companys! Podàs tornar i continuar treballant en aquest projecte. Qualsevol altre canvi es desarà automàticament i es compartirà amb els companys." already_published_prefix: "Els teus canvis s'han publicat a la galeria de classes." already_published_suffix: "Continua experimentant i millorant aquest projecte, o mira el que la resta de la teva classe ha fet. Els teus canvis es desaran i es compartiran automàticament amb els teus companys." view_gallery: "Veure Galeria" project_published_noty: "S'ha publicat el teu nivell!" keep_editing: "Segueix editant" # learn_new_concepts: "Learn new concepts" # watch_a_video: "Watch a video on __concept_name__" # concept_unlocked: "Concept Unlocked" # use_at_least_one_concept: "Use at least one concept: " apis: methods: "Mètodes" events: "Esdeveniments" handlers: "Manipuladors" properties: "Propietats" snippets: "Fragments" spawnable: "Desmuntable" html: "HTML" math: "Mates" array: "matriu" object: "Objecte" string: "Cadena" function: "Funció" vector: "Vector" date: "Data" jquery: "jQuery" json: "JSON" number: "Número" webjavascript: "JavaScript" amazon_hoc: title: "Segueix aprenent amb Amazon!" congrats: "Felicitats per conquerir aquesta desafiant Hora de Codi!" educate_1: "Ara, continueu informant-vos sobre codificació i computació en el núvol amb AWS Educate, un programa emocionant i gratuït d'Amazon per a estudiants i professors. Amb AWS Educate, podeu guanyar insígnies interessants a mesura que apreneu els aspectes bàsics del núvol i tecnologies d'avantguarda, com ara jocs, realitat virtual i Alexa." educate_2: "Més informació i registre aquí" future_eng_1: "També podeu provar de construir les vostres habilitats pròpies de l'escola per a Alexa" future_eng_2: "aquí" future_eng_3: "(no es requereix dispositiu). Aquesta activitat Alexa és presentada pel programa" future_eng_4: "Amazon Future Engineer" future_eng_5: "que crea oportunitats d'aprenentatge i treball per a tots els estudiants de K-12 als Estats Units que vulguin cursar informàtica." play_game_dev_level: created_by: "Creat per {{name}}" created_during_hoc: "Creat durant l'Hora del Codi" restart: "Reinicia el nivell" play: "Juga el nivell" play_more_codecombat: "Juga més CodeCombat" default_student_instructions: "Fes clic per controlar el teu heroi i guanyar el joc!" goal_survive: "Sobreviu." goal_survive_time: "Sobreviu __seconds__ segons." goal_defeat: "Derrota tots els enemics." goal_defeat_amount: "Derrota __amount__ enemics." goal_move: "Mou-te a totes les X vermelles." goal_collect: "Recull tots els ítems." goal_collect_amount: "Recull __amount__ ítems." game_menu: inventory_tab: "Inventari" save_load_tab: "Desa/Carrega" options_tab: "Opcions" guide_tab: "Gui" guide_video_tutorial: "Vídeo Tutorial" guide_tips: "Consells" multiplayer_tab: "Multijugador" auth_tab: "Dona't d'alta" inventory_caption: "Equipa el teu heroi" choose_hero_caption: "Tria l'heroi, llenguatge" options_caption: "Edita la configuració" guide_caption: "Documents i pistes" multiplayer_caption: "Juga amb amics!" auth_caption: "Desa el progrés." leaderboard: view_other_solutions: "Veure les taules de classificació" scores: "Puntuació" top_players: "Els millors jugadors de" day: "Avui" week: "Aquesta Setmana" all: "Tots els temps" latest: "Recent" time: "Temps" damage_taken: "Mal rebut" damage_dealt: "Mal inflingit" difficulty: "Dificultat" gold_collected: "Or recol·lectat" survival_time: "Sobreviscut" defeated: "Enemics derrotats" code_length: "Línies de Codi" score_display: "__scoreType__: __score__" inventory: equipped_item: "Equipat" required_purchase_title: "Necessari" available_item: "Disponible" restricted_title: "Restringit" should_equip: "(doble-clic per equipar)" equipped: "(equipat)" locked: "(bloquejat)" restricted: "(restringit en aquest nivell)" equip: "Equipa" unequip: "Desequipa" warrior_only: "Només Guerrers" ranger_only: "Només Exploradors" wizard_only: "Només Mags" buy_gems: few_gems: "Algunes gemmes" pile_gems: "Pila de gemmes" chest_gems: "Cofre de gemmes" purchasing: "Comprant..." declined: "La teva targeta ha estat rebutjada" retrying: "Error del servidor, intentant de nou." prompt_title: "Gemmes insuficients" prompt_body: "En vols més?" prompt_button: "Entrar a la botiga" recovered: "S'han recuperat les anteriors compres de gemmes. Si us plaus, recarrega al pàgina." price: "x{{gems}} / més" buy_premium: "Compra Premium" purchase: "Compra" purchased: "Comprat" subscribe_for_gems: prompt_title: "No hi ha prou gemmes!" prompt_body: "Compra Prèmium per tenir gemes i accedir fins i tot a més nivells!" earn_gems: prompt_title: "No hi ha prou gemmes" prompt_body: "Continua jugant per guanyar-ne més!" subscribe: best_deal: "Millor oferta!" confirmation: "Felicitats! Ja tens una subscripció a CodeCombat Prèmium!" premium_already_subscribed: "Ja estàs subscrit a Prèmium!" subscribe_modal_title: "CodeCombat Prèmium" comparison_blurb: "Millora les teves habilitats amb una subscripció a CodeCombat!" must_be_logged: "Necessites identificar-te. Si us plau, crea un compte o identifica't al menú de la part superior." subscribe_title: "Subscriu-te" # Actually used in subscribe buttons, too unsubscribe: "Donar-se de baixa" confirm_unsubscribe: "Confirmar la baixa" never_mind: "No et preocupis, encara t'estimo!" thank_you_months_prefix: "Gràcies pel suport donat els últims" thank_you_months_suffix: "mesos." thank_you: "Gràcies per donar suport a CodeCombat." sorry_to_see_you_go: "Llàstima que te'n vagis! Deixa'ns saber què podríem haver fet millor." unsubscribe_feedback_placeholder: "Oh, què hem fet?" stripe_description: "Subscripció mensual" buy_now: "Compra ara" subscription_required_to_play: "Necessitarás una subscripció per jugar aquest nivell." unlock_help_videos: "Subscriu-te per desbloquejar tots els vídeo-tutorials." personal_sub: "Subscripció Personal" # Accounts Subscription View below loading_info: "Carregant informació de la subscripció..." managed_by: "Gestionat per" will_be_cancelled: "Se't cancel·larà" currently_free: "Ara tens una subscripció gratuïta" currently_free_until: "Ara tens uns subscripció fins al" free_subscription: "Subscripció gratuïta" was_free_until: "Tens una subscripció gratuïta fins al" managed_subs: "Subscripcions gestionades" subscribing: "Subscrivint..." current_recipients: "Destinataris actuals" unsubscribing: "Anul·lació de subscripcions" subscribe_prepaid: "Feu clic a Subscripció per utilitzar el codi prepagat" using_prepaid: "Ús del codi prepagat per a la subscripció mensual" feature_level_access: "Accediu a més de 300 nivells disponibles" feature_heroes: "Desbloqueja herois exclusius i mascotes" feature_learn: "Aprèn a fer jocs i llocs web" month_price: "$__price__" first_month_price: "Només $__price__ pel teu primer mes!" lifetime: "Accés de per vida" lifetime_price: "$__price__" year_subscription: "Subscripció anual" year_price: "$__price__/any" support_part1: "Necessites ajuda amb el pagament o prefereixes PayPal? Envia'ns un e-mail a" support_part2: "support@codecombat.com" announcement: now_available: "Ja disponible pels subscriptors!" subscriber: "subscriptor" cuddly_companions: "Companys tendres!" # Pet Announcement Modal kindling_name: "Kindling Elemental" kindling_description: "Els Kindling Elementals només volen escalfar-te per la nit. I pel dia. De fet, sempre." griffin_name: "Nadó Grif" griffin_description: "Els Grifs són mig àguila, mig lleó, tots adorables." raven_name: "Corb" raven_description: "Els Corbs són excel·lentsa l'hora de recollir ampolles brillants plenes de salut per a tu." mimic_name: "Mimic" mimic_description: "Els Mimics poden recollir monedes per a tu. Mou-los damunt les monedes per augmentar el teu subministrament d'or." cougar_name: "Puma" cougar_description: "Als pumes els encanta guanyar un doctorat en ronronejar feliços diàriament." fox_name: "Guineu Blava" fox_description: "Les Guineus blaves són molt llestes i les encanta cavar a la brutícia i a la neu!" pugicorn_name: "Pugicorn" pugicorn_description: "Els Pugicorns són algunes de les criatures més rares i poden llançar encanteris!" wolf_name: "Cadell Llop" wolf_description: "Els Cadells Llops són excel·lents caçant, reunint-se i jugant a fet-i-amagar!" ball_name: "Bola Squeaky Vermella" ball_description: "ball.squeak()" collect_pets: "Col·lecciona mascotes pels teus herois!" each_pet: "Cada mascota té una habilitat d'ajuda única!" upgrade_to_premium: "Esdevé un {{subscriber}} per equipar mascotes." play_second_kithmaze: "Juga a {{the_second_kithmaze}} per desbloquejar el Cadell Llop!" the_second_kithmaze: "El Segon Kithlaberint" keep_playing: "Continua jugant per descobrir la primera mascota!" coming_soon: "Pròximament" ritic: "Rític el Fred" # Ritic Announcement Modal ritic_description: "Rític el Fred. Atrapat a la Glacera de Kelvintaph per innombrables edats, finalment lliure i llest per tendir als ogres que el van empresonar." ice_block: "Un bloc de gel" ice_description: "Sembla que hi ha alguna cosa atrapada a l'interior..." blink_name: "Parpelleig" blink_description: "Rític desapareix i reapareix en un obrir i tancar els ulls, deixant res més que una ombra." shadowStep_name: "Passaombres" shadowStep_description: "Un mestre assassí sap caminar entre les ombres." tornado_name: "Tornado" tornado_description: "És bo tenir un botó de restabliment quan la coberta surt pels aires." wallOfDarkness_name: "Paret de Foscor" wallOfDarkness_description: "Amaga't darrere una paret d'ombres per evitar la mirada d'ulls curiosos." premium_features: get_premium: "Aconsegueix<br>CodeCombat<br>Prèmium" # Fit into the banner on the /features page master_coder: "Converteix-te en un Maestre Codificador subscrivint-te avui mateix!" paypal_redirect: "Se't redirigirà a PayPal per completar el procés de subscripció." subscribe_now: "Subscriu-te Ara" hero_blurb_1: "Accediu a __premiumHeroesCount__ herois superequipats només per a subscriptors! Aprofita el poder imparable d'Okar Stompfoot, la mortal precisió de Naria de les Fulles, o convoca esquelets \"adorables\" amb Nalfar Cryptor." hero_blurb_2: "Els guerrers Prèmium desbloquegen unes habilitats marcials impresionants com ara Crit de Guerra, Sofriment, i Llança Enemics. O, juga com a explorador, utilitzant sigil i arcs, llançant ganivets, i trampes! Prova la vostra habilitat com a mag codificador, i desencadena una potent matriu de Màgia Primordial, Necromàntica o Elemental!" hero_caption: "Herois nous i emocionants!" pet_blurb_1: "Les mascotes no són només companys adorables, sinó que també ofereixen funcions i mètodes únics. El Nadó Grif pot transportar unitats a través de l'aire, el Cadell Llop juga amb fletxes enemigues, al Puma li encanta perseguir els ogres del voltant, i el Mimic atreu monedes com un imant!" pet_blurb_2: "Aconsegueix totes les mascotes per descobrir les seves habilitats úniques." pet_caption: "Adopta mascotes per acompanyar al teu heroi!" game_dev_blurb: "Aprén seqüències d'ordres de jocs i construeix nivells nous per compartir amb els teus amics! Col·loca els ítems que vulguis, escriu el codi per la unitat lògica i de comportament i observa si els teus amics poden superar el nivell!" game_dev_caption: "Dissenya els teus propis jocs per desafiar als teus amics!" everything_in_premium: "Tot el que obtens en CodeCombat Prèmium:" list_gems: "Rep gemmes de bonificació per comprar equips, mascotes i herois" list_levels: "Guanya accés a __premiumLevelsCount__ nivells més" list_heroes: "Desbloqueja herois exclusius, inclosos del tipus Explorador i Mag" list_game_dev: "Fes i comparteix jocs amb els teus amics" list_web_dev: "Crea llocs web i aplicacions interactives" list_items: "Equipa amb elements exclusius Prèmium com ara mascotes" list_support: "Obté suport Prèmium per ajudar-te a depurar el codi delicat" list_clans: "Crea clans privats per convidar els teus amics i competir en una taula de classificació del grup" choose_hero: choose_hero: "Escull el teu heroi" programming_language: "Llenguatge de programació" programming_language_description: "Quin llenguatge de programació vols utilitzar?" default: "Per defecte" experimental: "Experimental" python_blurb: "Simple però poderós, Python és un bon llenguatge d'ús general." javascript_blurb: "El llenguatge de les webs." coffeescript_blurb: "Sintaxi JavaScript millorat." lua_blurb: "Llenguatge script per a jocs." java_blurb: "(Només subscriptor) Android i empresa." status: "Estat" weapons: "Armes" weapons_warrior: "Espases - Curt abast, no hi ha màgia" weapons_ranger: "Ballestes, armes - de llarg abast, no hi ha màgia" weapons_wizard: "Varetes, bastons - Llarg abast, Màgia" attack: "Dany" # Can also translate as "Attack" health: "Salut" speed: "Velocitat" regeneration: "Regeneració" range: "Abast" # As in "attack or visual range" blocks: "Bloqueja" # As in "this shield blocks this much damage" backstab: "Punyalada per l'esquena" # As in "this dagger does this much backstab damage" skills: "Habilitats" attack_1: "Danys" attack_2: "de la llista" attack_3: "dany d'armes." health_1: "Guanys" health_2: "de la llista" health_3: "salut d'armes." speed_1: "Es mou a" speed_2: "metres per segon." available_for_purchase: "Disponible per a la compra" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Nivell per desbloquejar:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see) restricted_to_certain_heroes: "Només certs herois poden jugar aquest nivell." skill_docs: function: "funció" # skill types method: "mètode" snippet: "fragment" number: "nombre" array: "matriu" object: "objecte" string: "cadena" writable: "editable" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "Només lectura" action: "Acció" spell: "Encantament" action_name: "nom" action_cooldown: "pren" action_specific_cooldown: "Refredat" action_damage: "Dany" action_range: "Abast" action_radius: "Radi" action_duration: "Duracció" example: "Exemple" ex: "ex" # Abbreviation of "example" current_value: "Valor actual" default_value: "Valor per defecte" parameters: "Paràmetres" required_parameters: "Paràmetres requerits" optional_parameters: "Paràmetres opcionals" returns: "Retorna" granted_by: "Atorgat per" save_load: granularity_saved_games: "Desats" granularity_change_history: "Historial" options: general_options: "Opcions generals" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volum" music_label: "Musica" music_description: "Activa / desactiva la música de fons." editor_config_title: "Configuració de l'editor" editor_config_livecompletion_label: "Autocompleció en directe" editor_config_livecompletion_description: "Mostra els suggeriments automàtics mentre escriviu." editor_config_invisibles_label: "Mostra invisibles" editor_config_invisibles_description: "Mostra invisibles com ara espais o tabuladors." editor_config_indentguides_label: "Mostra guies de sagnia" editor_config_indentguides_description: "Mostra línees verticals per veure i identificar millor." editor_config_behaviors_label: "Comportament intel·ligent" editor_config_behaviors_description: "Autocompleta claudàtors, correctors i cometes." about: # title: "About CodeCombat - Engaging Students, Empowering Teachers, Inspiring Creation" # meta_description: "Our mission is to level computer science through game-based learning and make coding accessible to every learner. We believe programming is magic and want learners to be empowered to to create things from pure imagination." learn_more: "Aprèn més" main_title: "Si vols aprendre a programar, has d'escriure (molt) codi." main_description: "A CodeCombat, el nostre treball és assegurar-vos que ho feu amb un somriure a la cara." mission_link: "Missió" team_link: "Equip" story_link: "Història" press_link: "Prensa" mission_title: "La nostra missió: fer que la programació sigui accessible per a tots els estudiants de la Terra." mission_description_1: "<strong>Programar és màgic</strong>. És la capacitat de crear coses des d'una imaginació pura. Vam començar CodeCombat per donar a l'alumnat la sensació d'un poder màgic al seu abast usant <strong>codi escrit</strong>." mission_description_2: "Com a conseqüència, això els permet aprendre més ràpidament. MOLT ràpidament. És com tenir una conversa en comptes de llegir un manual. Volem portar aquesta conversa a cada escola i <strong>a cada alumne</strong>, perquè tothom hauria de tenir l'oportunitat d'aprendre la màgia de la programació." team_title: "Coneix l'equip de CodeCombat" team_values: "Valorem un diàleg obert i respectuós, on guanyi la millor idea. Les nostres decisions es basen en la investigació del client i el nostre procés se centra a oferir resultats tangibles per a ells. Tothom en té cabuda, del nostre CEO als nostres col·laboradors de GitHub, perquè valorem el creixement i l'aprenentatge al nostre equip." nick_title: "Cofundador, CEO" matt_title: "Cofundador, CTO" cat_title: "Dissenyador de jocs" scott_title: "Cofundador, Enginyer de Programari" maka_title: "Advocat de clients" robin_title: "Gerent de producció" nolan_title: "Cap de vendes" david_title: "Direcció de Comercialització" titles_csm: "Gerent d'èxit del client" titles_territory_manager: "Administrador de territori" retrostyle_title: "Il·lustració" retrostyle_blurb: "Jocs estil retro" bryukh_title: "Dissenyador de jocs" bryukh_blurb: "Constructor de trencaclosques" community_title: "...i la nostra comunitat de codi obert" community_subtitle: "Més de 500 contribuents han ajudat a construir CodeCombat, amb més unió cada setmana." community_description_3: "CodeCombat és un" community_description_link_2: "projecte comunitari" community_description_1: "amb centenars de jugadors voluntaris per crear nivells, contibuir al nostre codi per afegir característiques, arreglar errors, comprovar, i fins i tot traduir el joc a més de 50 llenguas. Els empleats, els contribuents i el lloc s'enriqueixen compartint idees i esforç de combinació, igual que la comunitat de codi obert en general. El lloc està construït amb nombrosos projectes de codi obert, i estem obert per retornar-los a la comunitat i proporcionar-li als usuaris curiosos un projecte familiar per explorar i experimentar. Qualsevol pot unir-se a la comunitat de CodeCombat! Consulta la nostra" community_description_link: "pàgina de contribució" community_description_2: "per a més informació." number_contributors: "Més de 450 col·laboradors han prestat el seu suport i el seu temps a aquest projecte." story_title: "La nostra història fins ara" story_subtitle: "Des de 2013, CodeCombat ha passat de ser un mer conjunt d'esbossos a un joc viu i pròsper." story_statistic_1a: "Més de 5,000,000" story_statistic_1b: "de jugadors en total" story_statistic_1c: "han iniciat el seu viatge vers la programació mitjançant CodeCombat" story_statistic_2a: "Hem estat treduits a més de 50 idiomes — els nostres jugadors provenen de" story_statistic_2b: "més de 190 països" story_statistic_3a: "Tots junts, han escrit" story_statistic_3b: "més d'un bilió de línies de codi" story_statistic_3c: "en molts idiomes de programació diferents" story_long_way_1: "Tot i que hem recorregut un llarg camí..." story_sketch_caption: "El primer esbós de Nick que representa un joc de programació en acció." story_long_way_2: "encara tenim molt per fer abans de completar la nostra recerca, així que..." jobs_title: "Vine a treballar amb nosaltres i ajuda'ns a escriure la història de CodeCombat!" jobs_subtitle: "No ho veus clar però t'interessa mantenir-te en contacte? Mira nostra \"Crea Tu Mateix\" llista." jobs_benefits: "Beneficis per l'empleat" jobs_benefit_4: "Vacances il·limitades" jobs_benefit_5: "Desenvolupament professional i suport a la formació contínua - llibres i jocs gratuïts!" jobs_benefit_6: "Metge (or), dental, visió, proximitat" jobs_benefit_7: "Taules amb seients per a tothom" jobs_benefit_9: "Finestra d'exercici opcional de 10 anys" jobs_benefit_10: "Permís de maternitat: paga 10 setmanes, les següents 6 al 55% de sou" jobs_benefit_11: "Permís de paternitat: paga 10 setmanes" jobs_custom_title: "Crea Tu Mateix" jobs_custom_description: "Estàs apassionat amb CodeCombat, però no veus una feina que coincideixi amb les teves qualitats? Escriu-nos i mostra'ns com creus que pots contribuir al nostre equip. Ens encantaria saber de tu!" jobs_custom_contact_1: "Envia'ns una nota a" jobs_custom_contact_2: "introduint-te i podrem contactar amb tu en el futur!" contact_title: "Premsa i Contacte" contact_subtitle: "Necessites més informació? Contacta amb nosaltres a" screenshots_title: "Captures de pantalla del joc" screenshots_hint: "(clica per veure a mida completa)" downloads_title: "Baixa Actius i Informació" about_codecombat: "Sobre CodeCombat" logo: "Logo" screenshots: "Captures de pantalla" character_art: "Art del personatge" download_all: "Baixa tot" previous: "Previ" location_title: "Ens trobem al centre de SF:" teachers: licenses_needed: "Calen llicències" special_offer: special_offer: "Oferta Especial" project_based_title: "Cursos basats en projectes" project_based_description: "Els cursos de desenvolupament web i jocs tenen projectes finals compartibles." great_for_clubs_title: "Ideal per a tallers i optatives" great_for_clubs_description: "Els professors poden comprar fins a __maxQuantityStarterLicenses__ llicències inicials." low_price_title: "Només __starterLicensePrice__ per alumne" low_price_description: "Les llicències inicials estan actives per __starterLicenseLengthMonths__ mesos a partir de la compra." three_great_courses: "Tres grans cursos inclosos a la Llicència inicial:" license_limit_description: "Els professors poden comprar fins a __maxQuantityStarterLicenses__ llicències inicials. Ja has comprat __quantityAlreadyPurchased__. Si necessites més, contacta amb __supportEmail__. Les Llicències inicials són vàlides per __starterLicenseLengthMonths__ mesos." student_starter_license: "Llicència inicial d'Estudiant" purchase_starter_licenses: "Compra les Llicències inicials" purchase_starter_licenses_to_grant: "Compra les Llicències inicials per donar accés a __starterLicenseCourseList__" starter_licenses_can_be_used: "Les Llicències inicials es poden usar per assignar cursos adicionals immediatament després de la compra." pay_now: "Paga ara" we_accept_all_major_credit_cards: "Acceptem la majoria de targetes de crèdit." cs2_description: "es basa en els fonaments de la Introducció a la informàtica, submergint-se en declaracions, funcions, esdeveniments i molt més." wd1_description: "introdueix els conceptes bàsics de l'HTML i el CSS, mentre ensenya les habilitats necessàries perquè els alumnes construeixin la seva primera pàgina web." gd1_description: "fa servir sintaxi molt familiar pels estudiants per mostrar-los com crear i compartir els seus propis jocs amb nivells." see_an_example_project: "vegeu un projecte d'exemple" get_started_today: "Comença avui mateix!" want_all_the_courses: "Vols tots els cursos? Sol·licita informació sobre les nostres llicències completes." compare_license_types: "Compara tipus de Llicències:" cs: "Ciències de la Computació" wd: "Desenvolupament web" wd1: "Desenvolupament web 1" gd: "Desenvolupament de jocs" gd1: "Desenvolupament de jocs 1" maximum_students: "Nombre màxim d'estudiants" unlimited: "Il·limitat" priority_support: "Suport prioritari" yes: "Sí" price_per_student: "__price__ per alumne" pricing: "Preus" free: "Gratuït" purchase: "Compra" courses_prefix: "Cursos" courses_suffix: "" course_prefix: "Curs" course_suffix: "" teachers_quote: subtitle: "Feu que els vostres estudiants comencin en menys d'una hora. Podràs <strong>crear una classe, afegir alumnes, i monitoritzar el seu progrés</strong> mentre aprenen informàtica." email_exists: "L'usuari existeix amb aquest correu electrònic." phone_number: "Número de telèfon" phone_number_help: "On podem trobar-te durant la jornada laboral?" primary_role_label: "El vostre rol principal" role_default: "Selecciona rol" primary_role_default: "Selecciona rol principal" purchaser_role_default: "Selecciona rol de comprador" tech_coordinator: "Coordinador de tecnologia" advisor: "Especialista / assessor de currículum" principal: "Director" superintendent: "Inspector" parent: "Pare" purchaser_role_label: "El teu rol de comprador" influence_advocate: "Influir/Optar" evaluate_recommend: "Evaluar/Recomanar" approve_funds: "Aprovació de fons" no_purchaser_role: "Cap rol en decisions de compra" district_label: "Districte" district_name: "Nom del Districte" district_na: "Poseu N/A si no és aplicable" organization_label: "Centre" school_name: "Nom de l'escola/institut" city: "Ciutat" state: "Província" country: "País" num_students_help: "Quants alumnes usaran CodeCombat?" num_students_default: "Selecciona Rang" education_level_label: "Nivell educatiu dels alumnes" education_level_help: "Trieu tants com calgui." elementary_school: "Primària" high_school: "Batxillerat/Mòduls" please_explain: "(per favor, explicar)" middle_school: "Secundària" college_plus: "Universitat o superior" referrer: "Com ens va conèixer?" referrer_help: "Per exemple: d'un altre professor, una conferència, els vostres estudiants, Code.org, etc." referrer_default: "Selecciona una" referrer_hoc: "Code.org/Hour of Code" referrer_teacher: "Un professor" referrer_admin: "Un administrador" referrer_student: "Un estudiant" referrer_pd: "Formacions / tallers professionals" referrer_web: "Google" referrer_other: "Altres" anything_else: "Amb quin tipus de classe preveus usar CodeCombat?" thanks_header: "Sol·licitud rebuda!" thanks_sub_header: "Gràcies per expressar l'interès en CodeCombat per al vostre centre." thanks_p: "Estarem en contacte aviat! Si necessiteu posar-vos en contacte, podeu contactar amb nosaltres a:" back_to_classes: "Torna a Classes" finish_signup: "Acaba de crear el vostre compte de professor:" finish_signup_p: "Creeu un compte per configurar una classe, afegir-hi els estudiants i supervisar el seu progrés a mesura que aprenen informàtica." signup_with: "Registreu-vos amb:" connect_with: "Connectar amb:" conversion_warning: "AVÍS: El teu compte actual és un <em>Compte estudiantil</em>. Un cop enviat aquest formulari, el teu compte s'actualitzarà a un compte del professor." learn_more_modal: "Els comptes de professors de CodeCombat tenen la capacitat de supervisar el progrés dels estudiants, assignar llicències i gestionar les aules. Els comptes de professors no poden formar part d'una aula: si actualment esteu inscrit en una classe amb aquest compte, ja no podreu accedir-hi una vegada que l'actualitzeu a un compte del professor." create_account: "Crear un compte de professor" create_account_subtitle: "Obteniu accés a les eines exclusives de professors per utilitzar CodeCombat a l'aula. <strong>Configura una classe</strong>, afegeix els teus alumnes, i <strong>supervisa el seu progrés</strong>!" convert_account_title: "Actualitza a compte del professor" not: "No" versions: save_version_title: "Guarda una nova versió" new_major_version: "Nova versió principal" submitting_patch: "S'està enviant el pedaç..." cla_prefix: "Per guardar els canvis primer has d'acceptar" cla_url: "CLA" cla_suffix: "." cla_agree: "Estic d'acord" owner_approve: "Un propietari ho haurà d'aprovar abans que els canvis es facin visibles." contact: contact_us: "Contacta CodeCombat" welcome: "Què bé poder escoltar-te! Fes servir aquest formulari per enviar-nos un email. " forum_prefix: "Per a qualsevol publicació, si us plau prova " forum_page: "el nostre fòrum" forum_suffix: " sinó" faq_prefix: "També pots mirar a les" faq: "Preguntes Freqüents" subscribe_prefix: "Si necessites ajuda per superar un nivell, si us plau" subscribe: "compra una subscripció de CodeCombat" subscribe_suffix: "i estarem encantats d'ajudar-te amb el teu codi." subscriber_support: "Com que seràs subscriptor de CodeCombat, el teu e-mail tindrà el nostre suport prioritari." screenshot_included: "Captura de pantalla inclosa." where_reply: "On hem de respondre?" send: "Enviar comentari" account_settings: title: "Configuració del compte" not_logged_in: "Inicia sessió o crea un compte per a canviar la configuració." me_tab: "Jo" picture_tab: "Foto" delete_account_tab: "Elimina el teu compte" wrong_email: "Correu erroni" wrong_password: "Contrasenya invàlida" delete_this_account: "Elimina aquest compte de forma permanent" reset_progress_tab: "Reinicia tot el progrés" reset_your_progress: "Reiniciar tot el progrés i començar de nou" god_mode: "Mode Déu" emails_tab: "Missatges" admin: "Administrador" manage_subscription: "Clica aquí per administrar la teva subscripció." new_password: "Contrasenya nova" new_password_verify: "Verifica" type_in_email: "Escriu el teu e-mail o nom d'usuari per confirmar l'eliminació del compte." type_in_email_progress: "Escriu el teu correu electrònic per confirmar l'eliminació del teu progrés." type_in_password: "Escriu també la teva contrasenya." email_subscriptions: "Subscripcions via correu electrònic" email_subscriptions_none: "Sense subsrcipcions de correu electrònic." email_announcements: "Notícies" email_announcements_description: "Rebre les últimes notícies i desenvolupaments de CodeCombat." email_notifications: "Notificacions" email_notifications_summary: "Controls per personalitzar les teves notificacions d'email automàtiques relacionades amb la teva activitat a CodeCombat." email_any_notes: "Cap notificació" email_any_notes_description: "Desactiva totes les notificacions via correu electrònic." email_news: "Noticies" email_recruit_notes: "Oportunitats de feina" email_recruit_notes_description: "Si jugues realment bé ens posarem en contacte amb tu per oferir-te feina." contributor_emails: "Subscripció als correus electrònics de cada classe" contribute_prefix: "Estem buscant gent que s'uneixi! Mira " contribute_page: "la pàgina de col·laboració" contribute_suffix: " per llegir més informació." email_toggle: "Activa-ho tot" error_saving: "Error en desar" saved: "Canvis desats" password_mismatch: "Les contrasenyes no coincideixen." password_repeat: "Siusplau, repetiu la contrasenya." keyboard_shortcuts: keyboard_shortcuts: "Dreceres del teclat" space: "Espai" enter: "Enter" press_enter: "prem Enter" escape: "Escape" shift: "Majúscula" run_code: "Executa el codi actual." run_real_time: "Executa en temps real." continue_script: "Continua passant l'script actual." skip_scripts: "Omet tots els scripts que es poden ometre." toggle_playback: "Commuta play/pausa." scrub_playback: "Mou-te enradere i endavant a través del temps." single_scrub_playback: "Mou-te enradere i endavant a través del temps pas a pas." scrub_execution: "Mou-te a través de l'execució de l'encanteri actual." toggle_debug: "Canvia la visualització de depuració." toggle_grid: "Commuta la superposició de la graella." toggle_pathfinding: "Canvia la superposició d'enfocament de camí." beautify: "Embelleix el teu codi estandarditzant el format." maximize_editor: "Maximitza/minimitza l'editor de codi." community: main_title: "Comunitat CodeCombat" introduction: "Consulta les maneres en que et pots implicar i decideix quina et sembla més divertida. Esperem treballar amb tu!" level_editor_prefix: "Usa CodeCombat" level_editor_suffix: "per crear i editar nivells. Els usuaris han creat nivells per a les seves classes, amics, festes de programació, estudiants i germans. Si crear un nou nivell sona intimidant pots començar picant un dels nostres!" thang_editor_prefix: "Anomenem 'thangs' a les unitats dintre del joc. Usa" thang_editor_suffix: "per modificar el codi d'origen de CoodeCombat. Permet que unitats llancin projectils, alterin l'orientació d'una animació, canvien els punts d'èxit d'una unitat o carreguin els vostres propis sprites vectorials." article_editor_prefix: "Veus errades en alguns dels nostres documents? Vols crear algunes instruccions per a les teves pròpies creacions? Prova amb" article_editor_suffix: "i ajuda als jugadors de CodeCombat a treure el màxim profit del seu temps de joc." find_us: "Troba'ns en aquests llocs" social_github: "Consulteu tot el nostre codi a GitHub" social_blog: "Llegiu el bloc de CodeCombat al setembre" social_discource: "Uneix-te a les discussions al nostre fòrum de comentaris" social_facebook: "Fes Like a CodeCombat en Facebook" social_twitter: "Segueix CodeCombat al Twitter" social_gplus: "Uneix-te a CodeCombat en Google+" social_slack: "Xateja amb nosaltres al canal públic CodeCombat Slack" contribute_to_the_project: "Contribueix al projecte" clans: # title: "Join CodeCombat Clans - Learn to Code in Python, JavaScript, and HTML" # clan_title: "__clan__ - Join CodeCombat Clans and Learn to Code" # meta_description: "Join a Clan or build your own community of coders. Play multiplayer arena levels and level up your hero and your coding skills." clan: "Clan" clans: "Clans" new_name: "Nou nom de clan" new_description: "Nova descripció de clan" make_private: "Fes el clan privat" subs_only: "només subscriptors" create_clan: "Crear un Nou Clan" private_preview: "Vista prèvia" private_clans: "Clans privats" public_clans: "Clans públics" my_clans: "Els meus Clans" clan_name: "Nom del Clan" name: "Nom" chieftain: "Capità" edit_clan_name: "Edita el nom del Clan" edit_clan_description: "Edita la descripció del Clan" edit_name: "edita el nom" edit_description: "edita la descripció" private: "(privat)" summary: "Resum" average_level: "Nivell Mitjà" average_achievements: "Mitjana de realitzacions" delete_clan: "Esborrar Clan" leave_clan: "Abandonar Clan" join_clan: "Unir-se al Clan" invite_1: "Invitar:" invite_2: "*Invita jugadors a aquest Clan tot enviant-los aquest enllaç." members: "Membres" progress: "Progrés" not_started_1: "no iniciat" started_1: "iniciat" complete_1: "complert" exp_levels: "Amplia els nivells" rem_hero: "Elimina l'heroi" status: "Estat" complete_2: "Complert" started_2: "Iniciat" not_started_2: "No Iniciat" view_solution: "Clica per veure la solució." view_attempt: "Clica per veure l'intent." latest_achievement: "Darrera Realització" playtime: "Temps de joc" last_played: "Darrer joc" leagues_explanation: "Participa en una lliga contra d'altres membres del clan en el camp de joc multijugador." track_concepts1: "Seguiment dels conceptes" track_concepts2a: "après per cada estudiant" track_concepts2b: "après per cada membre" track_concepts3a: "Seguiment dels nivells complets per a cada estudiant" track_concepts3b: "Seguiment dels nivells complets per a cada membre" track_concepts4a: "Mira com els teus alumnes" track_concepts4b: "Mira com els teus membres" track_concepts5: "ho han resolt" track_concepts6a: "Ordena alumnes per nom o progrés" track_concepts6b: "Ordena membres per nom o progrés" track_concepts7: "Requereix invitació" track_concepts8: "per unir-se" private_require_sub: "Els Clans Privats requereixen subscripció per crear-los o unir-se'n." courses: create_new_class: "Crear una Classe Nova" # hoc_blurb1: "Try the" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity! Construct four different minigames to learn the basics of game development, then make your own!" solutions_require_licenses: "Hi ha disponibles solucions de nivell per als professors que tenen llicències." unnamed_class: "Classe sense nom" edit_settings1: "Edita la configuració de la Classe" add_students: "Afegeix Alumnes" stats: "Estadístiques" student_email_invite_blurb: "Els teus alumnes també poden utilitzar el codi de la classe <strong>__classCode__</strong> quan creen un Compte Estudiantil, no és necessari e-mail." total_students: "Alumnes totals:" average_time: "Mitjana de temps de joc:" total_time: "Temps de joc total:" average_levels: "Mitjana de nivells assolits:" total_levels: "Nivells assolits totals:" students: "Alumnes" concepts: "Conceptes" play_time: "Temps de joc:" completed: "Assolit:" enter_emails: "Separa cada adreça e-mail amb un salt de línia o amb comes" send_invites: "Invita Alumnes" number_programming_students: "Nombre d'alumnes a Programació" number_total_students: "Alumnes totals al Centre/Districte" enroll: "Inscriure's" enroll_paid: "Inscriure els alumnes en cursos de pagament" get_enrollments: "Obteniu més llicències" change_language: "Canvia el Llenguatge del Curs" keep_using: "Segueix utilitzant" switch_to: "Canvia a" greetings: "Felicitats!" back_classrooms: "Torna a Les Meves Classes" back_classroom: "Torna a Classe" back_courses: "Torna a Els Meus Cursos" edit_details: "Edita els detalls de la classe" purchase_enrollments: "Compra Llicències Estudiantils" remove_student: "esborrar alumne" assign: "Assignar" to_assign: "per assignar cursos de pagament." student: "Alumne" teacher: "Docent" arena: "Camp de joc" available_levels: "Nivells disponibles" started: "iniciat" complete: "completat" practice: "pràctica" required: "requerit" welcome_to_courses: "Aventurers, benvinguts als Cursos!" ready_to_play: "Preparats per jugar?" start_new_game: "Començar un Joc Nou" play_now_learn_header: "Juga ara per aprendre" play_now_learn_1: "sintaxi bàsica per controlar el teu personatge" play_now_learn_2: "bucles 'while' per resoldre molestos trencaclosques" play_now_learn_3: "cadenes i variables per personalitzar accions" play_now_learn_4: "com vèncer a un ogre (habilitats vitals importants!)" welcome_to_page: "el meu Tauler d'alumnat" my_classes: "Classes Actuals" class_added: "Classe afegida satisfactòriament!" # view_map: "view map" # view_videos: "view videos" view_project_gallery: "veure els projectes dels meus companys" join_class: "Uneix-te a una Classe" join_class_2: "Unir-se a una classe" ask_teacher_for_code: "Demana al teu professorat si té un codi de classe CodeCombat! Si el té, posa'l a continuació:" enter_c_code: "<Posa el Codi de Classe>" join: "Unir-se" joining: "Unint-se a la classe" course_complete: "Curs Complet" play_arena: "Terreny de joc" view_project: "Veure Projecte" start: "Començar" last_level: "Darrer nivell jugat" not_you: "No ets tu?" continue_playing: "Continua Jugant" option1_header: "Invita Alumnes via e-mail" remove_student1: "Esborra Alumnes" are_you_sure: "Estàs segur que vols esborrar aquest alumne d'aquesta classe?" remove_description1: "L'alumne perdrà l'accés a aquesta aula i a les classes assignades. El seu progrés i jocs NO es perdran, i l'alumne podrà tornar a ser afegit a l'aula en qualsevol moment." remove_description2: "No es retornarà la llicència de pagament activada." license_will_revoke: "La llicència de pagament d'aquest alumne serà revocada i restarà disponible per ésser assignada a qualsevol altre alumne." keep_student: "Mantenir l'alumne" removing_user: "Esborrant l'usuari" subtitle: "Reviseu els detalls i nivells del curs" # Flat style redesign changelog: "Veure els darrers canvis als nivells del curs." select_language: "Seleccionar idioma" select_level: "Seleccionar nivell" play_level: "Jugar Nivell" concepts_covered: "Conceptes treballats" view_guide_online: "Visions i solucions de nivell" grants_lifetime_access: "Concedeix accés a tots els cursos." enrollment_credits_available: "Llicències Disponibles:" language_select: "Tria un idioma" # ClassroomSettingsModal language_cannot_change: "L'Idioma no es podrà canviar una vegada l'alumnat s'uneixi a la classe." avg_student_exp_label: "Experiència mitjana de programació de l'alumnat" avg_student_exp_desc: "Això ens ajudarà a comprendre com fer els cursos millor." avg_student_exp_select: "Selecciona la millor opció" avg_student_exp_none: "Cap experiència - molt poca experiència" avg_student_exp_beginner: "Principiant - alguna vegada o programació mitjançant blocs" avg_student_exp_intermediate: "Intermig - alguna experiència amb codi escrit" avg_student_exp_advanced: "Advançat - experiència extensa amb codi escrit" avg_student_exp_varied: "Nivells variats d'experiència" student_age_range_label: "Rang d'edat de l'alumnat" student_age_range_younger: "Més joves de 6" student_age_range_older: "Més vells de 18" student_age_range_to: "a" # estimated_class_dates_label: "Estimated Class Dates" # estimated_class_frequency_label: "Estimated Class Frequency" # classes_per_week: "classes per week" # minutes_per_class: "minutes per class" create_class: "Crear Classe" class_name: "Nom de la Classe" teacher_account_restricted: "El teu compte és de professorat i no pots accedir al contingut de l'alumnat." account_restricted: "És necessari un compte estudiantil per accedir a aquesta plana." update_account_login_title: "Inicia sessió per actualitzar el teu compte" update_account_title: "El teu compte necessita atenció!" update_account_blurb: "Abans de poder accedir a les teves classes, tria com vols utilitzar aquest compte." update_account_current_type: "Tipus de compte actual:" update_account_account_email: "E-mail del compte/nom d'usuari:" update_account_am_teacher: "Sóc docent" update_account_keep_access: "Manteniu accés a les classes que he creat" update_account_teachers_can: "Els comptes de docent poden:" update_account_teachers_can1: "Crear/manegar/afegir classes" update_account_teachers_can2: "Assignar/donar d'alta alumnat als cursos" update_account_teachers_can3: "Desbloquejar tots els nivells dels cursos per provar-los" update_account_teachers_can4: "Accedir a noves característiques només per a docents de seguida que les creem" update_account_teachers_warning: "Atenció: Se t'esborrarà de toes les classes que anteriorment t'havies afegit i ja no podràs jugar com a alumne." update_account_remain_teacher: "Romandre com a docent" update_account_update_teacher: "Canviar a docent" update_account_am_student: "Sóc alumne/a" update_account_remove_access: "Esborrar l'accés a les classes que he creat" update_account_students_can: "Els comptes d'estudiant poden:" update_account_students_can1: "Unir-se a classes" update_account_students_can2: "Jugar en els cursos com a estudiant i seguir el teu propi progrés" update_account_students_can3: "Competir contra companys als camps de joc" update_account_students_can4: "Accedir a les noves característiques només per a alumnes de seguida que els creem" update_account_students_warning: "Atenció: No podràs manegar cap classe que hagis creat previament ni crear classes noves." unsubscribe_warning: "Atenció: Seràs esborrat de la subscripció mensual." update_account_remain_student: "Continua com a Alumne" update_account_update_student: "Canvia a Alumne" need_a_class_code: "Necessitaràs un codi de Classe per la classe a la que et vols unir:" update_account_not_sure: "No saps quina triar? Envia un e-mail" update_account_confirm_update_student: "Estàs segur que vols canviar el teu compte a Alumnat?" update_account_confirm_update_student2: "No podràs manegar cap classe que hagis creat anteriorment ni crear classes noves. Les teves classes creades anteriorment s'esborraran de CodeCombat i no es podran recuperar." instructor: "Instructor: " youve_been_invited_1: "Has estat invitat a unir-te " youve_been_invited_2: ", on aprendràs " youve_been_invited_3: " amb els teus companys amb CodeCombat." by_joining_1: "Unint-se " by_joining_2: "podràs ajudar a restablir la teva contrasenya si la oblides o la perds. També podràs verificar la teva adreça e-mail i així reiniciar la contrasenya tu mateix!" sent_verification: "Hem enviat un e-mail de verificació a:" you_can_edit: "Pots editar el teu e-mail a " account_settings: "Configuració del Compte" select_your_hero: "Selecciona el teu Heroi" select_your_hero_description: "Sempre pots canviar el teu heroi anant a la plana Els Teus Cursos i fent clic a \"Canviar Heroi\"" select_this_hero: "Selecciona aquest Heroi" current_hero: "Heroi actual:" current_hero_female: "Heroïna actual:" web_dev_language_transition: "En aquest curs totes les classes programen en HTML / JavaScript. Les classes que han estat usant Python començaran amb uns nivells d'introducció extra de JavaScripts per fer la transició més fàcil. Les classes que ja usaven JavaScript ometran els nivells introductoris." course_membership_required_to_play: "T'has d'unir a un curs per jugar aquest nivell." license_required_to_play: "Demana al teu professorat que t'assigni una llicència per continuar jugant a CodeCombat!" update_old_classroom: "Nou curs escolar, nous nivells!" update_old_classroom_detail: "Per assegurar-se que estàs obtenint els nivells actualitzats, comprova haver creat una classe nova per aquest semestre clicant Crear una Classe Nova al teu" teacher_dashboard: "taulell del professorat" update_old_classroom_detail_2: "i donant a l'alumnat el nou Codi de Classe que apareixerà." view_assessments: "Veure Avaluacions" view_challenges: "veure els nivells de desafiament" challenge: "Desafiament:" challenge_level: "Nivell de Desafiament:" status: "Estat:" assessments: "Avaluacions" challenges: "Desafiaments" level_name: "Nom del nivell:" keep_trying: "Continua intentant" start_challenge: "Començar el Desafiament" locked: "Bloquejat" concepts_used: "Conceptes Usats:" show_change_log: "Mostra els canvis als nivells d'aquest curs" hide_change_log: "Amaga els canvis als nivells d'aquest curs" # concept_videos: "Concept Videos" # concept: "Concept:" # basic_syntax: "Basic Syntax" # while_loops: "While Loops" # variables: "Variables" # basic_syntax_desc: "Syntax is how we write code. Just as spelling and grammar are important in writing narratives and essays, syntax is important when writing code. Humans are good at figuring out what something means, even if it isn't exactly correct, but computers aren't that smart, and they need you to write very precisely." # while_loops_desc: "A loop is a way of repeating actions in a program. You can use them so you don't have to keep writing repetitive code, and when you don't know exactly how many times an action will need to occur to accomplish a task." # variables_desc: "Working with variables is like organizing things in shoeboxes. You give the shoebox a name, like \"School Supplies\", and then you put things inside. The exact contents of the box might change over time, but whatever's inside will always be called \"School Supplies\". In programming, variables are symbols used to store data that will change over the course of the program. Variables can hold a variety of data types, including numbers and strings." # locked_videos_desc: "Keep playing the game to unlock the __concept_name__ concept video." # unlocked_videos_desc: "Review the __concept_name__ concept video." # video_shown_before: "shown before __level__" # link_google_classroom: "Link Google Classroom" # select_your_classroom: "Select Your Classroom" # no_classrooms_found: "No classrooms found" # create_classroom_manually: "Create classroom manually" # classes: "Classes" project_gallery: no_projects_published: "Sigues el primer en publicar un projecte en aquest curs!" view_project: "Veure Projecte" edit_project: "Editar Projecte" teacher: assigning_course: "Assignant curs" back_to_top: "Tornar a l'inici" click_student_code: "Feu clic a qualsevol nivell que l'alumne hagi començat o completat a continuació per veure el codi que va escriure." code: "Codi d'en/na __name__" complete_solution: "Solució Completa" course_not_started: "L'alumnat encara no ha començat aquest curs." # appreciation_week_blurb1: "For <strong>Teacher Appreciation Week 2019</strong>, we are offering free 1-week licenses!<br />Email Rob Arevalo (<a href=\"mailto:robarev@codecombat.com?subject=Teacher Appreciation Week\">robarev@codecombat.com</a>) with subject line \"<strong>Teacher Appreciation Week</strong>\", and include:" # appreciation_week_blurb2: "the quantity of 1-week licenses you'd like (1 per student)" # appreciation_week_blurb3: "the email address of your CodeCombat teacher account" # appreciation_week_blurb4: "whether you'd like licenses for Week 1 (May 6-10) or Week 2 (May 13-17)" # hoc_happy_ed_week: "Happy Computer Science Education Week!" # hoc_blurb1: "Learn about the free" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity, download a new teacher lesson plan, and tell your students to log in to play!" # hoc_button_text: "View Activity" no_code_yet: "L'alumnat encara no ha escrit cap codi en aquest nivell." open_ended_level: "Nivell obert" partial_solution: "Solució Parcial" removing_course: "Esborrant curs" solution_arena_blurb: "Es recomana a l'alumnat que resolgui els nivells del camp de joc amb creativitat. La solució que es proporciona a continuació compleix els requisits del nivell del camp de joc." solution_challenge_blurb: "Es recomana a l'alumnat que resolgui els nivells de desafiament obert amb creativitat. Una possible solució es mostra a continuació." solution_project_blurb: "Es recomana a l'alumnat que construeixi un projecte creatiu en aquest nivell. La solució que es proporciona a continuació compleix els requisits del nivell del projecte." students_code_blurb: "Es proporcionarà una solució correcta per a cada nivell, quan correspongui. En alguns casos, és possible que un estudiant resolgui un nivell amb un codi diferent. No es mostren solucions per als nivells que l'alumne no ha iniciat." course_solution: "Solució del curs" level_overview_solutions: "Visió general del nivell i solucions" no_student_assigned: "No s'ha assignat cap alumnat a aquest curs." paren_new: "(nou)" student_code: "Codi d'alumnat de __name__" teacher_dashboard: "Taulell del Professorat" # Navbar my_classes: "Les Meves Classes" courses: "Guies dels Cursos" enrollments: "Llicències d'Alumnat" resources: "Recursos" help: "Ajuda" language: "Idioma" edit_class_settings: "edita la configuració de la classe" access_restricted: "Actualització del compte obligatori" teacher_account_required: "Es requereix un compte de professorat per accedir a aquest contingut." create_teacher_account: "Crear un compte de professorat" what_is_a_teacher_account: "Què és un Compte de Professorat?" teacher_account_explanation: "Un compte de professorat CodeCombat et permet configurar aules, veure el progrés de l'alumnat mentre van fent els cursos, administrar llicències i accedir a recursos per ajudar-te en la creació de currículums." current_classes: "Classes actuals" archived_classes: "Classes arxivades" archived_classes_blurb: "Les Classes es poden arxivar per referències futures. Desarxiva una classe per veure-la de nou a la llista actual de Classes." view_class: "veure classe" archive_class: "arxivar classe" unarchive_class: "desarxivar classe" unarchive_this_class: "Desarxiva aquesta classe" no_students_yet: "Aquesta classe encara no té alumnes." no_students_yet_view_class: "Veure classe per afegir alumnes." try_refreshing: "(És possible que hàgiu d'actualitzar la pàgina)" create_new_class: "Crear una Classe Nova" class_overview: "Descripció de la classe" # View Class page avg_playtime: "Mitjana de temps de joc del nivell" total_playtime: "Temps de joc total" avg_completed: "Mitjana de nivells assolits" total_completed: "Total de nivells assolits" created: "Creat" concepts_covered: "Conceptes tractats" earliest_incomplete: "Primer nivell incomplet" latest_complete: "Darrer nivell assolit" enroll_student: "Inscriure l'estudiant" apply_license: "Aplicar Llicència" revoke_license: "Revocar Llicència" revoke_licenses: "Revocar Totes les llicències" course_progress: "Progrés del curs" not_applicable: "N/A" edit: "edita" edit_2: "Edita" remove: "esborra" latest_completed: "Darrer assolit:" sort_by: "Ordena per" progress: "Progrés" concepts_used: "Conceptes emprats per Alumnat:" concept_checked: "Concepte verificat:" completed: "Assolit" practice: "Practica" started: "Iniciat" no_progress: "Cap progrés" not_required: "No requerit" view_student_code: "Fes clic per veure el codi d'alumnat" select_course: "Selecciona el curs per veure'l" progress_color_key: "Codi de colors de progrés:" level_in_progress: "Nivell en Progrés" level_not_started: "Nivell no Iniciat" project_or_arena: "Projecte o Terreny de Joc" students_not_assigned: "Alumnat que no ha estat assignat {{courseName}}" course_overview: "Descripció general del curs" copy_class_code: "Copiar Codi de Classe" class_code_blurb: "L'alumnat pot unir-se a la teva classe amb aquest Codi de Classe. No és neessari cap adreça e-mail per crear un Compte d'Estudiant amb aquest Codi de Classe." copy_class_url: "Copiar URL de la Classe" class_join_url_blurb: "També pots posar aquesta URL única d'aquesta classe en una plana web compartida." add_students_manually: "Invitar Alumnes per e-mail" bulk_assign: "Seleccionar curs" assigned_msg_1: "{{numberAssigned}} alumnes s'han assignat a {{courseName}}." assigned_msg_2: "{{numberEnrolled}} llicències s'han utilitzat." assigned_msg_3: "Ara teniu {{remainingSpots}} llicències restants disponibles." assign_course: "Assignar Curs" removed_course_msg: "{{numberRemoved}} alumnes s'han esborrat de {{courseName}}." remove_course: "Esborrar Curs" not_assigned_modal_title: "Els cursos no es van assignar" not_assigned_modal_starter_body_1: "Aquest curs requereix Llicències Inicials. No tens suficients Llicències Inicials disponibles per assignar aquest curs a tots els __selected__ alumnes seleccionats." not_assigned_modal_starter_body_2: "Compra Llicències Inicials per garantir l'accés a aquest curs." not_assigned_modal_full_body_1: "Aquest curs requereix Llicències Totals. No tens suficients Llicències Totals disponibles per assignar aquest curs a tots els __selected__ alumnes seleccionats." not_assigned_modal_full_body_2: "Només tens __numFullLicensesAvailable__ Llicències Totals disponibles (__numStudentsWithoutFullLicenses__ alumnes no tenen encara Llicències Totals actives)." not_assigned_modal_full_body_3: "Si us plau selecciona menys alumnes, o demana ajuda a __supportEmail__." assigned: "Assignats" enroll_selected_students: "Inscriviu l'alumnat seleccionat" no_students_selected: "No s'ha seleccionat cap alumne." show_students_from: "Mostrar alumnat de" # Enroll students modal apply_licenses_to_the_following_students: "Otorgar Llicències als següents Alumnes" students_have_licenses: "Els següents alumnes ja tenen llicències otorgades:" all_students: "Tots els Alumnes" apply_licenses: "Otorgar Llicències" not_enough_enrollments: "No n'hi han suficients llicències." enrollments_blurb: "Als alumnes se'ls demana tenir una llicència per accedir a qualsevol contingut després del primer curs." how_to_apply_licenses: "Com otorgar llicències" export_student_progress: "Exportar el Progrés de l'Alumnat (CSV)" send_email_to: "Envieu Recuperar contrasenya per e-mail a:" email_sent: "E-mail enviat" send_recovery_email: "Enviar e-mail de recuperació" enter_new_password_below: "Introduïu una contrasenya nova a continuació:" change_password: "Canviar Contrasenya" changed: "Canviada" available_credits: "Llicències disponibles" pending_credits: "Llicències pendents" empty_credits: "Llicències gastades" license_remaining: "llicència restant" licenses_remaining: "llicències restants" one_license_used: "1 llicència s'ha usat" num_licenses_used: "__numLicensesUsed__ llicències s'han usat" starter_licenses: "llicències inicials" start_date: "data d'inici:" end_date: "data d'acabament:" get_enrollments_blurb: " Us ajudarem a construir una solució que satisfaci les necessitats de la vostra classe, escola o districte." how_to_apply_licenses_blurb_1: "Quan un professor assigni un curs a un estudiant per primera vegada, aplicarem automàticament una llicència. Utilitzau el menú desplegables d'assignació massiva a la vostra aula per assignar un curs als alumnes selececionats:" how_to_apply_licenses_blurb_2: "Puc aplicar una llicència encara que no hagi assignat un curs?" how_to_apply_licenses_blurb_3: "Sí — ves a l'etiqueta Estat de les Llicències a la teva aula i fes clic a \"Aplicar Llicència\" a qualsevol alumne que no tingui una llicència activa." request_sent: "Petició enviada!" assessments: "Avaluacions" license_status: "Estat de les Llicències" status_expired: "Caducada el {{date}}" status_not_enrolled: "No inscrit" status_enrolled: "Caduca el {{date}}" select_all: "Selecciona Tot" project: "Projecte" project_gallery: "Galeria de Projectes" view_project: "Veure Projecte" unpublished: "(no publicades)" view_arena_ladder: "Veure escala del camp de joc" resource_hub: "Centre de recursos" pacing_guides: "Guies tot-en-un de l'aula" pacing_guides_desc: "Aprendre com incorporar tots els recursos de CodeCombat per planificar el teu curs escolar!" pacing_guides_elem: "Guia pas a pas d'una Escola de Primària" pacing_guides_middle: "Guia pas a pas d'una Escola de Secundària" pacing_guides_high: "Guia pas a pas d'un Centre d'Estudis Postobligatoris" getting_started: "Començant" educator_faq: "Preguntes freqüents de Docents" educator_faq_desc: "Preguntes habituals sobre l'ús de CodeCombat a la teva aula o al teu centre." teacher_getting_started: "Guia d'introducció per a docents" teacher_getting_started_desc: "Ets nou a CodeCombat? Descarrega aquesta Guia d'introducció per a docents per configurar el teu compte, crear la teva primera classe, i invitar alumnat al primer curs." student_getting_started: "Guia d'introducció per l'alumnat" student_getting_started_desc: "Pots distribuir aquesta guia al teu alumnat abans de començar amb CodeCombat per a que es puguin anar familiaritzant amb l'editor de codi. Aquesta guis serveix tant per classes de Python com de JavaScript." ap_cs_principles: "AP Principis d'informàtica" ap_cs_principles_desc: "AP Principis d'informàtica dona als estudiants una àmplia introducció al poder, l'impacte i les possibilitats de la informàtica. El curs fa èmfasi en el pensament computacional i la resolució de problemes, a més d'ensenyar els fonaments de la programació." cs1: "Introducció a la informàtica" cs2: "Informàtica 2" cs3: "Informàtica 3" cs4: "Informàtica 4" cs5: "Informàtica 5" cs1_syntax_python: "Guia de sintaxi de Python del curs 1" cs1_syntax_python_desc: "Full de trucs amb referències a la sintaxi comuna de Python que els estudiants aprendran en Introducció a la informàtica." cs1_syntax_javascript: "Guia de sintaxi de JavaScript del curs 1" cs1_syntax_javascript_desc: "Full de trucs amb referències a la sintaxi comuna de JavaScript que els estudiants aprendran en Introducció a la informàtica." coming_soon: "Guies addicionals properament!" engineering_cycle_worksheet: "Full de cicle d'enginyeria" engineering_cycle_worksheet_desc: "Utilitzeu aquest full de càlcul per ensenyar als estudiants els conceptes bàsics del cicle d'enginyeria: Avaluar, dissenyar, implementar i depurar. Consulteu el full de càlcul de l'exemple complet com a guia." engineering_cycle_worksheet_link: "Mostra l'exemple" progress_journal: "Diari de progrés" progress_journal_desc: "Anima els estudiants a fer un seguiment del progrés a través d'un diari de progrés." cs1_curriculum: "Introducció a la informàtica - Guia del currículum" cs1_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 1." arenas_curriculum: "Nivells del camp de joc - Guia dels professors" arenas_curriculum_desc: "Instruccions sobre com usar els camps de joc multijugadors Wakka Maul, Cross Bones i Power Peak amb les teves classes." # assessments_curriculum: "Assessment Levels - Teacher Guide" # assessments_curriculum_desc: "Learn how to use Challenge Levels and Combo Challenge levels to assess students' learning outcomes." cs2_curriculum: "Informàtica 2 - Guia del currículum" cs2_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 2." cs3_curriculum: "Informàtica 3 - Guia del currículum" cs3_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 3." cs4_curriculum: "Informàtica 4 - Guia del currículum" cs4_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 4." cs5_curriculum_js: "Informàtica 5 - Guia del currículum (JavaScript)" cs5_curriculum_desc_js: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 5 fent servir JavaScript." cs5_curriculum_py: "Informàtica 5 - Guia del currículum (Python)" cs5_curriculum_desc_py: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 5 fent servir Python." cs1_pairprogramming: "Activitat de programació en parelles" cs1_pairprogramming_desc: "Introduir els estudiants a un exercici de programació en parelles que els ajudarà a ser millors oients i comunicadors." gd1: "Desenvolupament del Joc 1" gd1_guide: "Desenvolupament del Joc 1 - Guia del Projecte" gd1_guide_desc: "Utilitzeu això per guiar els vostres estudiants a mesura que creen el primer projecte de joc compartit en 5 dies." gd1_rubric: "Desenvolupament del Joc 1 - Rúbrica del Project" gd1_rubric_desc: "Utilitza aquesta rúbrica per avaluar els projectes dels alumnes al final de Desenvolupament del Joc 1." gd2: "Desenvolupament del Joc 2" gd2_curriculum: "Desenvolupament del Joc 2 - Guia del Currículum" gd2_curriculum_desc: "Planificació de classes per Desenvolupament del Joc 2." gd3: "Desenvolupament del Joc 3" gd3_curriculum: "Desenvolupament del Joc 3 - Guia del Currículum" gd3_curriculum_desc: "Planificació de classes per Desenvolupament del Joc 3." wd1: "Desenvolupament Web 1" wd1_curriculum: "Desenvolupament Web 1 - Guia del Currículum" wd1_curriculum_desc: "Planificació de classes per Desenvolupament Web 1." # {change} wd1_headlines: "Activitats amb Titulars i Encapçalaments" wd1_headlines_example: "Veure un exemple de solució" wd1_headlines_desc: "Per què són importants els paràgrafs i les etiquetes de capçalera? Utilitzeu aquesta activitat per mostrar com els encapçalaments ben escollits fan que les pàgines web siguin més fàcils de llegir. Hi ha moltes solucions correctes per a això." wd1_html_syntax: "Guia de sintaxi HTML" wd1_html_syntax_desc: "Referència d'una pàgina per a l'estil HTML que els estudiants aprendran en el Desenvolupament Web 1." wd1_css_syntax: "Guia de sintaxi CSS" wd1_css_syntax_desc: "Referència d'una pàgina per a la sintaxi CSS i Style que els estudiants aprendran en el Desenvolupament Web 1." wd2: "Desenvolupament Web 2" wd2_jquery_syntax: "Guia de sintaxi de funcions jQuery" wd2_jquery_syntax_desc: "Referència d'una pàgina per a les funcions jQuery que els estudiants aprendran en el Desenvolupament Web 2." wd2_quizlet_worksheet: "Full de càlcul de planificació del Qüestionari" wd2_quizlet_worksheet_instructions: "Veure instruccions i exemples" wd2_quizlet_worksheet_desc: "Abans que els vostres estudiants construeixin el seu projecte de qüestionació de personalitat al final del Desenvolupament web 2, haurien de planificar les preguntes, els resultats i les respostes del qüestionari utilitzant aquest full de càlcul. Els professors poden distribuir les instruccions i els exemples als quals es refereixen els estudiants." student_overview: "Resum" student_details: "Detalls dels alumnes" student_name: "nom de l'alumne" no_name: "No es proporciona cap nom." no_username: "No s'ha proporcionat cap nom d'usuari." no_email: "L'estudiant no té una adreça electrònica configurada." student_profile: "Perfil de l'estudiant" playtime_detail: "Detall del temps de joc" student_completed: "Estudiants completats" student_in_progress: "Estudiant en curs" class_average: "Mitjana de classe" not_assigned: "No s'ha assignat els cursos següents" playtime_axis: "Temps de joc en segons" levels_axis: "Nivells en" student_state: "Com està " student_state_2: " fent?" student_good: "ho està fent bé a" student_good_detail: "Aquest alumne manté el ritme de la classe." student_warn: "podria necessitar ajuda en" student_warn_detail: "Aquest estudiant pot necessitar ajuda amb els nous conceptes que s'han introduït en aquest curs." student_great: "ho està fent molt bé a" student_great_detail: "Aquest estudiant pot ser un bon candidat per ajudar altres estudiants que iintentin fer aquest curs." full_license: "Llicència Total" starter_license: "Llicència Inicial" trial: "Prova" hoc_welcome: "Feliç setmana de l'aprenentatge d'Informàtica" # hoc_title: "Hour of Code Games - Free Activities to Learn Real Coding Languages" # hoc_meta_description: "Make your own game or code your way out of a dungeon! CodeCombat has four different Hour of Code activities and over 60 levels to learn code, play, and create." hoc_intro: "Hi ha tres maneres per a que la vostra classe participi en Hora del Codi amb CodeCombat" hoc_self_led: "Joc d'autoaprenentatge" hoc_self_led_desc: "Els alumnes poden accedir a dues hores de tutorials de CodeCombat per compte propi" hoc_game_dev: "Desenvolupament de Jocs" hoc_and: "i" hoc_programming: "Programació en JavaScript/Python" hoc_teacher_led: "Lliçons magistrals" hoc_teacher_led_desc1: "Baixa't la nostra" hoc_teacher_led_link: "planificació de lliçons sobre Introducció a la Informàtica" hoc_teacher_led_desc2: "per introduir els vostres estudiants en conceptes de programació utilitzant activitats fora de línia" hoc_group: "Joc Grupal" hoc_group_desc_1: "Els professors poden utilitzar les lliçons juntament amb el nostre curs de Introducció a la informàtica per fer un seguiment del progrés dels estudiants. Mira la nostra" hoc_group_link: "Guia d'introducció" hoc_group_desc_2: "per més detalls" hoc_additional_desc1: "Per a recursos i activitats addicionals de CodeCombat, minar les nostres" hoc_additional_desc2: "Preguntes" hoc_additional_contact: "Posar-se en contacte" revoke_confirm: "Estàs segur que vols revocar una llicència total de {{student_name}}? La llicència restarà disponible per assignar-la a un altre estudiant." revoke_all_confirm: "Estàs segur que vols revocar les llicències totals de tots els estudiants d'aquesta classe?" revoking: "Revocant..." unused_licenses: "Teniu llicències no utilitzades que us permeten assignar cursos pagats pels estudiants quan estiguin preparats per obtenir més informació!" remember_new_courses: "Recorda assignar nous cursos!" more_info: "Més informació" how_to_assign_courses: "Com assignar cursos" select_students: "Seleccionar Alumnes" select_instructions: "Feu clic a la casella de verificació al costat de cada alumne al qual voleu assignar els cursos." choose_course: "Tria Curs" choose_instructions: "Seleccioneu el curs des del menú desplegable que vulgueu assignar, i després feu clic a “Assigna als Alumnes Seleccionats.”" push_projects: "Es recomana assignar Desenvolupament web 1 o Desenvolupament de jocs 1 després que els alumnes hagin acabat la Introducció a la informàtica! Veure el nostre {{resource_hub}} per més detalls sobre aquests cursos." teacher_quest: "Missió del Docent per tenir èxit" quests_complete: "Missió Complerta" teacher_quest_create_classroom: "Crear un aula" teacher_quest_add_students: "Afegir l'alumnat" teacher_quest_teach_methods: "Ajudar el teu alumnat a aprendre com `cridar mètodes`." teacher_quest_teach_methods_step1: "Tenir el 75% com a mínim d'una classe amb el primer nivell passat, __Dungeons of Kithgard__" teacher_quest_teach_methods_step2: "Imprimir la [Guia d'introducció per l'alumnat](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) del Centre de Recursos." teacher_quest_teach_strings: "No encadenar els teus alumnes junts, ensenya'ls `cadenes`." teacher_quest_teach_strings_step1: "Tenir el 75% com a mínim d'una classe amb __True Names__ passat" teacher_quest_teach_strings_step2: "Usar el Selector de Nivells del Professorat a la plana [Guies del Curs](/teachers/courses) per tenir una vista prèvia de __True Names__." teacher_quest_teach_loops: "Mantenir els alumnes en el bucle sobre els `bucles`." teacher_quest_teach_loops_step1: "Tenir el 75% com a mínim d'una classe amb __Fire Dancing__ passat." teacher_quest_teach_loops_step2: "Usar el __Loops Activity__ en la [CS1 Guia del Currículum](/teachers/resources/cs1) per reforçar aquest concepte." teacher_quest_teach_variables: "Variar-los amb les `variables`." teacher_quest_teach_variables_step1: "Tenir el 75% com a mínim d'una classe amb __Known Enemy__ passat." teacher_quest_teach_variables_step2: "Fomentar la col·laboració utilitzant l'[Activitat de Programació per parelles](/teachers/resources/pair-programming)." teacher_quest_kithgard_gates_100: "Escapar de les portes de Kithgard amb la teva classe." teacher_quest_kithgard_gates_100_step1: "Tenir el 75% com a mínim d'una classe amb __Kithgard Gates__ passat." teacher_quest_kithgard_gates_100_step2: "Guiar l'alumnat per pensar en problemes difícils usant el [Full de cicle d'enginyeria](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)." teacher_quest_wakka_maul_100: "Preparar pel duel a Wakka Maul." teacher_quest_wakka_maul_100_step1: "Tenir el 75% com a mínim d'una classe amb __Wakka Maul__ passat." teacher_quest_wakka_maul_100_step2: "Veure la [Guia del Camp de Joc](/teachers/resources/arenas) al [Centre de Recursos](/teachers/resources) per trobar idees sobre com fer un joc de camp amb èxit." teacher_quest_reach_gamedev: "Explora nous móns!" teacher_quest_reach_gamedev_step1: "[Aconsegueix llicències](/teachers/licenses) per a que els teus alumnes puguin explorar nous móns, com ara Desenvolupament de jocs i Desenvolupament de Webs!" teacher_quest_done: "Encara volen aprendre més codi els teus alumnes? Posa't en contacte avui mateix amb els nostres [especialistes escolars](mailto:schools@codecombat.com)!" teacher_quest_keep_going: "Segueix endavant! A continuació t'indiquem què pots fer:" teacher_quest_more: "Veure totes les missions" teacher_quest_less: "Veure menys missions" refresh_to_update: "(actualitzeu la pàgina per veure les actualitzacions)" view_project_gallery: "Mostra la Galeria de Projectes" office_hours: "Seminari de Professorat" office_hours_detail: "Apreneu a mantenir-se al dia amb els vostres estudiants a mesura que creen jocs i s'embarquen en el seu viatge de codificació! Assisteix a les nostres" office_hours_link: "sessions de Seminari de Professorat" office_hours_detail_2: "." success: "Èxit" in_progress: "En Progrés" not_started: "No Iniciat" mid_course: "Mig Curs" end_course: "Fi del Curs" none: "Cap detectat encara" explain_open_ended: "Nota: Es recomana als estudiants que resolguin aquest nivell de forma creativa, a continuació es proporciona una possible solució." level_label: "Nivell:" time_played_label: "Temps jugat:" back_to_resource_hub: "Tornar al Centre de Recursos" back_to_course_guides: "Tornar a les Guies del Curs" print_guide: "Imprimir aquesta guia" combo: "Combinat" combo_explanation: "Els estudiants passen els nivells de desafiament combinat utilitzant com a mínim un concepte enumerat. Reviseu el codi de l'alumne fent clic al punt de progrés." concept: "Concepte" # sync_google_classroom: "Sync Google Classroom" share_licenses: share_licenses: "Compartir llicències" shared_by: "Compartida amb:" add_teacher_label: "Introduïu el correu electrònic del professorat exacte:" add_teacher_button: "Afegir professorat" subheader: "Podeu fer que les vostres llicències estiguin disponibles per a altres professors de la vostra organització. Cada llicència només es pot utilitzar per a un estudiant a la vegada." teacher_not_found: "No s'ha trobat el professor. Assegureu-vos que aquest professor ja ha creat un compte de professor." teacher_not_valid: "Aquest no és un compte de professor vàlid. Només els comptes de professors poden compartir llicències." already_shared: "Ja heu compartit aquestes llicències amb aquest professor." teachers_using_these: "Professors que poden accedir a aquestes llicències:" footer: "Quan els professors revocuen llicències dels estudiants, les llicències es retornaran al grup compartit d'altres professors d'aquest grup per utilitzar-les." you: "(tu)" one_license_used: "(1 llicència utilitzada)" licenses_used: "(__licensesUsed__ llicències utilitzades)" more_info: "Més informació" sharing: game: "Joc" webpage: "Plana Web" your_students_preview: "Els vostres alumnes faran clic aquí per veure els projectes acabats! No disponible a la previsualització del professor." unavailable: "L'intercanvi d'enllaços no està disponible a la previsualització del professor." share_game: "Comparteix aquest joc" share_web: "Comparteix aquesta Plana Web" victory_share_prefix: "Comparteix aquest enllaç per convidar els teus amics i família a" victory_share_prefix_short: "Convida gent a" victory_share_game: "jugar al teu joc" victory_share_web: "veure la teva plana web" victory_share_suffix: "." victory_course_share_prefix: "Aquest enllaç permetrà als teus amics i família" victory_course_share_game: "jugar al joc" victory_course_share_web: "veure la plana web" victory_course_share_suffix: "que acabes de crear." copy_url: "Copiar URL" share_with_teacher_email: "Enviar al teu professor/a" game_dev: creator: "Creador" web_dev: image_gallery_title: "Galeria d'imatges" select_an_image: "Selecciona la imatge que vulguis utilitzar" scroll_down_for_more_images: "(Desplaceu-vos cap avall per obtenir més imatges)" copy_the_url: "Copieu l'URL següent" copy_the_url_description: "Útil si voleu reemplaçar una imatge existent." copy_the_img_tag: "Copieu l'etiqueta <img>" copy_the_img_tag_description: "Útil si voleu inserir una imatge nova." copy_url: "Copiar URL" copy_img: "Copiar <img>" how_to_copy_paste: "Com Copiar/Pegar" copy: "Copiar" paste: "Pegar" back_to_editing: "Tornar a Editar" classes: archmage_title: "Arximag" archmage_title_description: "(Programador)" archmage_summary: "Si ets un programador interessat en els jocs educatius sigues un arximag i ajuda'ns a construir CodeCombat!" artisan_title: "Artesà" artisan_title_description: "(Creador de nivells)" artisan_summary: "Construeix i comparteix nivells per als teus amics. Sigues un Artesà per aprendre l'art d'ensenyar als altres a programar." adventurer_title: "Aventurer" adventurer_title_description: "(Provador de nivells)" adventurer_summary: "Accedeix als nostres nivells (fins i tot el contingut de pagament) una setmana abans i gratuïtament i ajuda'ns a descobrir errors abans que siguin públics." scribe_title: "Escriba" scribe_title_description: "(Editor d'articles)" scribe_summary: "Un bon codi necessita una bona documentació. Escriu, edita i millora els documents que són llegits per milions de jugadors arreu del món." diplomat_title: "Diplomàtic" diplomat_title_description: "(Traductor)" diplomat_summary: "CodeCombat s'està traduint a més de 45 idiomes pels nostres Displomàtics. Ajuda'ns a traduir!" ambassador_title: "Ambaixador" ambassador_title_description: "(Suport)" ambassador_summary: "Posar ordre als fòrums i respondre a les preguntes que sorgeixin. Els nostres Ambaixadors representen a CodeCombat envers el món." teacher_title: "Mestre" editor: main_title: "Editors de CodeCombat" article_title: "Editor d'articles " thang_title: "Editor de Thang" level_title: "Editor de nivells" course_title: "Editor de Cursos" achievement_title: "Editor de triomfs" poll_title: "Editor d'Enquestes" back: "Enrere" revert: "Reverteix" revert_models: "Reverteix Models" pick_a_terrain: "Tria un Terreny" dungeon: "Masmorra" indoor: "Interior" desert: "Desert" grassy: "Herba" mountain: "Muntanya" glacier: "Glaciar" small: "Petit" large: "Gran" fork_title: "Nova versió Bifurcació" fork_creating: "Creant bifurcació..." generate_terrain: "Generar Terreny" more: "Més" wiki: "Wiki" live_chat: "Xat en directe" thang_main: "Principal" thang_spritesheets: "Capes" thang_colors: "Colors" level_some_options: "Algunes opcions?" level_tab_thangs: "Thangs" level_tab_scripts: "Escripts" level_tab_components: "Components" level_tab_systems: "Sistemes" level_tab_docs: "Documentació" level_tab_thangs_title: "Thangs actuals" level_tab_thangs_all: "Tot" level_tab_thangs_conditions: "Condicions Inicials" level_tab_thangs_add: "Afegeix Thangs" level_tab_thangs_search: "Cerca thangs" add_components: "Afegir Components" component_configs: "Configuracions de Components" config_thang: "Fes doble clic per configurar un thang" delete: "Esborrar" duplicate: "Duplicar" stop_duplicate: "Atura el duplicat" rotate: "Rotar" level_component_tab_title: "Components actuals" level_component_btn_new: "Crear Nou Component" level_systems_tab_title: "Sistemes actuals" level_systems_btn_new: "Crea un nou sistema" level_systems_btn_add: "Afegir sistema" level_components_title: "Torna a Tots els Thangs" level_components_type: "Escriu" level_component_edit_title: "Edita Component" level_component_config_schema: "Esquema de configuració" level_system_edit_title: "Editar sistema" create_system_title: "Crea un nou sistema" new_component_title: "Crea un nou Component" new_component_field_system: "Sistema" new_article_title: "Crea un article nou" new_thang_title: "Crea un nou tipus de Thang" new_level_title: "Crea un nou nivell" new_article_title_login: "Inicia sessió per a crear un article nou" new_thang_title_login: "Inicia la sessió per crear un nou tipus de Thang" new_level_title_login: "Inicia sessió per a crear un nou nivell" new_achievement_title: "Crea un nou triomf" new_achievement_title_login: "Inicia sessió per a crear un nou triomf" new_poll_title: "Crea una nova enquesta" new_poll_title_login: "Inicia sessió per a crear una nova enquesta" article_search_title: "Cerca Articles aquí" thang_search_title: "Cerca tipus de Thang aquí" level_search_title: "Cerca nivells aquí" achievement_search_title: "Cerca assoliments" poll_search_title: "Cerca enquestes" read_only_warning2: "Nota: no podeu desar edicions aquí, perquè no heu iniciat la sessió." no_achievements: "Encara no s'ha afegit cap assoliment per aquest nivell." achievement_query_misc: "L'assoliment clau fora de miscel·lània" achievement_query_goals: "L'assoliment clau no té objectius de nivell" level_completion: "Compleció de nivell" pop_i18n: "Omple I18N" tasks: "Tasques" clear_storage: "Esborreu els canvis locals" add_system_title: "Afegiu sistemes al nivell" done_adding: "Afegits fets" article: edit_btn_preview: "Vista prèvia" edit_article_title: "Editar l'article" polls: priority: "Prioritat" contribute: page_title: "Contribueix" intro_blurb: "CodeCombat és 100% codi obert! Una gran quantitat de jugadors ens han ajudat a construir el joc tal com és avui. Uneix-te a l'aventura d'ensenyar a programar!" alert_account_message_intro: "Hola!" alert_account_message: "Per subscriure't a alguna classe, necessites estar identificat." archmage_introduction: "Una de les millors parts de construir jocs és que aglutinen coses molt diverses. Gràfics, sons, treball en temps real, xarxes socials, i per suposat la programació, des del baix nivell d'ús de bases de dades i administració del servidor fins a dissenyar i crear interfícies. Hi ha molt a fer, i si ets un programador amb experiència i amb l'anhel de submergir-te dins CodeCombat aquesta classe és per tu. Ens encantarà tenir la teva ajuda en el millor joc de programació que hi ha." class_attributes: "Atributs de la classe" archmage_attribute_1_pref: "Coneixement en " archmage_attribute_1_suf: ", o ganes d'aprendre'n. La major part del nostre codi és en aquest llenguatge. Si ets un fan de Ruby o Python et sentiràs com a casa. És JavaScript però més agradable." archmage_attribute_2: "Certa experiència programant i iniciativa personal. T'orientarem, però no podem dedicar molt de temps en ensenyar-te." how_to_join: "Com unir-se" join_desc_1: "Qualsevol pot ajudar! Visita el nostre " join_desc_2: "per començar i i marca la casella d'abaix per registra-te com a Arximag i estar al dia del correus electrònics que enviem. Vols saber què fer o que t'expliquem més a fons en què consisteix? " join_desc_3: ", o troba'ns al nostre " join_desc_4: "i t'ho explicarem!" join_url_email: "Escriu-nos" join_url_slack: "Canal de Contractació pública" archmage_subscribe_desc: "Rebre els correus sobre noves oportunitats de programació." artisan_introduction_pref: "Hem de construir nous nivells! La gent reclama més continguts i les nostres forces són limitades. Ara mateix el nostre lloc de treball és de nivell 1; el nostre editor de nivells és tot just útil per als seus creadors, així que ves en compte. Si tens algunes idees sobre campanyes amb bucles for per " artisan_introduction_suf: ", llavors aquesta classe és per a tu." artisan_attribute_1: "Experiència en construcció de continguts d'aquest estil seria genial, com per exemple l'editor de nivells de Blizzard. Però no és un requisit!" artisan_attribute_2: "Ganes de fer moltes proves i iteracions. Per fer bons nivells necessitaràs mostrar-ho a altres i veure com juguen i estar preparat per a reparar tot el que calgui." artisan_attribute_3: "De moment, la resistència va de la mà de l'Aventurer. El nostre editor de nivells es troba en una fase molt preliminar i pot ser un poc frustrant. Estàs avisat!" artisan_join_desc: "Utilitza l'editor de nivells a través d'aquests passos:" artisan_join_step1: "Llegeix la documentació." artisan_join_step2: "Crea un nivell nou i explora els ja creats." artisan_join_step3: "Troba'ns al nostre canal públic d'Slack per a més ajuda." artisan_join_step4: "Anuncia els teus nivells al fòrum per a més opinions." artisan_subscribe_desc: "Rebre els correus electrònics per seguir les novetats." adventurer_introduction: "Anem a tenir clar el vostre paper: sou el tanc. Vas a patir grans danys. Necessitem que les persones puguin provar nous nivells i ajudar a identificar com millorar les coses. El dolor serà enorme; fer bons jocs és un procés llarg i ningú ho fa bé la primera vegada. Si pateix i té una puntuació alta de constitució, aquesta classe pot ser per a vostè." adventurer_attribute_1: "Un set d'aprenentatge. Tu vols aprendre a codificar i nosaltres volem ensenyar-te com codificar. Probablement estaràs fent la majoria dels aprenentatges en aquesta classe." adventurer_attribute_2: "Carismàtic. Sigues amable però escriu sobre el que necessites millorar i ofereix suggeriments sobre com millorar-los." adventurer_join_pref: "Alineeu-vos amb (o recluta) un Artesà i treballeu amb ells, o marqueu la casella següent per rebre correus electrònics quan hi hagi nous nivells per provar. També publicarem sobre els nivells per revisar a les nostres xarxes, com ara" adventurer_forum_url: "el nostre fòrum" adventurer_join_suf: "per tant, si prefereixes que t'ho notifiquem així, inscriu-te aquí!" adventurer_subscribe_desc: "Rep correus electrònics quan hi hagi nous nivells per provar." scribe_introduction_pref: "CodeCombat no només vol ser un munt de nivells. També inclourà un recurs per al coneixement, una wiki de conceptes de programació que els nivells poden connectar. D'aquesta manera, en lloc que cada Artesà hagi d'descriure amb detall el que és un operador de comparació, simplement pot enllaçar el seu nivell amb l'article que els descriu que ja està escrit per a l'edificació del jugador. Al llarg de la línia del que el" scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: "ha construit. Si la vostra idea de diversió és articular els conceptes de programació en forma de marca, aquesta classe pot ser per a vosaltres." scribe_attribute_1: "L'habilitat en paraules és pràcticament tot el que necessiteu. No només la gramàtica i l'ortografia, sinó que poden transmetre idees complicades als altres." contact_us_url: "Contacta amb nosaltres" scribe_join_description: "Explica'ns una mica sobre tu mateix, la teva experiència amb la programació i sobre quin tipus de coses t'agradaria escriure. Començarem per això!" scribe_subscribe_desc: "Rep correus electrònics sobre anuncis d'escriptura d'articles." diplomat_introduction_pref: "Si alguna cosa vam aprendre del que vam " diplomat_launch_url: "llançar a l'octubre" diplomat_introduction_suf: "és que hi ha un gran interès en CodeCombat a altres països! Estem construint un cos de traductors per aconseguir que CodeCombat sigui tan accessible arreu del món com sigui possible. Si t'agrada aconseguir els nivells tan aviat com surten i poder-los oferir als teus compatriotes llavors aquesta classe és per tu." diplomat_attribute_1: "Fluïdesa en l'anglès i en l'idioma al que vulguis traduir. Al transmetre idees complicades és important tenir un gran coneixement dels dos idiomes!" diplomat_i18n_page_prefix: "Pots començar traduint els nostres nivells a la" diplomat_i18n_page: "pàgina de traduccions" diplomat_i18n_page_suffix: ", o bé la interfície web a GitHub." diplomat_join_pref_github: "Troba els nostres fitxers d'idiomes " diplomat_github_url: "a GitHub" diplomat_join_suf_github: ", edita'ls i envia una petició de modificació. A més, marca la casella d'abaix per mantenir-te informat d'esdeveniments de traducció!" diplomat_subscribe_desc: "Rebre correus sobre el desenvolupament de i18n i la traducció de nivells." ambassador_introduction: "Aquesta és una comunitat que estem construint, i tu ets les connexions. Tenim fòrums, correus electrònics i xarxes socials amb molta gent per parlar i ajudar-vos a conèixer el joc i aprendre-ne. Si voleu ajudar a la gent a participar-hi i divertir-se i tenir una bona idea del pols de CodeCombat i on anem, aquesta classe pot ser per a vosaltres." ambassador_attribute_1: "Habilitats comunicatives. Ser capaç d'identificar els problemes que tenen els jugadors i ajudar-los a resoldre'ls. A més, manten-nos informats sobre el que diuen els jugadors, el que els agrada i no els agrada i sobre què més volen!" ambassador_join_desc: "explica'ns una mica sobre tu mateix, què has fet i què t'interessaria fer. Començarem per això!" ambassador_join_note_strong: "Nota" ambassador_join_note_desc: "Una de les nostres principals prioritats és crear multijugador on els jugadors que tinguin dificultats per resoldre els nivells poden convocar assistents de nivell superior per ajudar-los. Serà una bona manera de fer la tasca d'Ambaixador. T'anirem informant!" ambassador_subscribe_desc: "Obteniu correus electrònics sobre actualitzacions de suport i desenvolupaments multijugador." teacher_subscribe_desc: "Obteniu correus electrònics sobre actualitzacions i anuncis per a professors." changes_auto_save: "Els canvis es desen automàticament quan canvieu les caselles de selecció." diligent_scribes: "Els Nostres Escribes Diligents:" powerful_archmages: "Els Nostres Arximags Poderosos:" creative_artisans: "Els Nostres Artesans Creatius:" brave_adventurers: "Els Nostres Aventurers Valents:" translating_diplomats: "Els Nostres Diplomàtics Traductors:" helpful_ambassadors: "Els Nostres Ambaixadors Útils:" ladder: # title: "Multiplayer Arenas" # arena_title: "__arena__ | Multiplayer Arenas" my_matches: "Les meves partides" simulate: "Simula" simulation_explanation: "Al simular jocs, pots aconseguir que el teu joc sigui més ràpid!" simulation_explanation_leagues: "Us ajudarà principalment a simular jocs per als jugadors aliats dels vostres clans i cursos." simulate_games: "Simula Jocs!" games_simulated_by: "Jocs que has simulat:" games_simulated_for: "Jocs simulats per a tu:" games_in_queue: "Jocs actualment a la cua:" games_simulated: "Partides simulades" games_played: "Partides guanyades" ratio: "Ràtio" leaderboard: "Taulell de Classificació" battle_as: "Batalla com " summary_your: "Les teves " summary_matches: "Partides - " summary_wins: " Victòries, " summary_losses: " Derrotes" rank_no_code: "No hi ha cap codi nou per classificar" rank_my_game: "Classifica el meu Joc!" rank_submitting: "Enviant..." rank_submitted: "Enviat per Classificar" rank_failed: "No s'ha pogut classificar" rank_being_ranked: "El Joc s'està Classificant" rank_last_submitted: "enviat " help_simulate: "T'ajudem a simular jocs?" code_being_simulated: "El teu nou codi està sent simulat per altres jugadors per al rànquing. Això s'actualitzarà a mesura que entrin noves coincidències." no_ranked_matches_pre: "No hi ha partides classificades per a l'equip " no_ranked_matches_post: " ! Juga contra alguns competidors i torna aquí per aconseguir que el teu joc sigui classificat." choose_opponent: "Escull adversari" select_your_language: "Escull el teu idioma!" tutorial_play: "Juga el tutorial" tutorial_recommended: "Recomenat si no has jugat abans" tutorial_skip: "Salta el tutorial" tutorial_not_sure: "No estàs segur de què està passant?" tutorial_play_first: "Juga el tutorial primer." simple_ai: "Simple CPU" warmup: "Escalfament" friends_playing: "Amics jugant" log_in_for_friends: "Inicia sessió per jugar amb els teus amics!" social_connect_blurb: "Connecta't i juga contra els teus amics!" invite_friends_to_battle: "Invita els teus amics a unir-se a la batalla!" fight: "Lluita!" watch_victory: "Mira la teva victòria" defeat_the: "Derrota a" watch_battle: "Observa la batalla" tournament_started: ", iniciada" tournament_ends: "El torneig acaba" tournament_ended: "El torneig ha acabat" tournament_rules: "Normes del torneig" tournament_blurb: "Escriu codi, recull or, construeix exèrcits, enderroca enemics, guanya premis i millora el teu rànquing al nostre torneig Greed de $ 40,000! Consulteu els detalls" tournament_blurb_criss_cross: "Obté ofertes, construeix camins, reparteix opositors, agafa gemmes i actualitza el teu rànquing al nostre torneig Criss-Cross! Consulteu els detalls" tournament_blurb_zero_sum: "Allibera la teva creativitat de codificació tant en la trobada d'or i en les tàctiques de batalla en aquest joc de miralls alpins entre el bruixot i el bruixot blau. El torneig va començar el divendres 27 de març i tindrà lloc fins el dilluns 6 d'abril a les 5PM PDT. Competeix per diversió i glòria! Consulteu els detalls" tournament_blurb_ace_of_coders: "Treu-lo a la glacera congelada en aquest joc de mirall d'estil dominació! El torneig va començar el dimecres 16 de setembre i es disputarà fins el dimecres 14 d'octubre a les 5PM PDT. Consulteu els detalls" tournament_blurb_blog: "en el nostre blog" rules: "Normes" winners: "Guanyadors" league: "Lliga" red_ai: "CPU vermella" # "Red AI Wins", at end of multiplayer match playback blue_ai: "CPU blava" wins: "Guanya" # At end of multiplayer match playback humans: "Vermell" # Ladder page display team name ogres: "Blau" user: # user_title: "__name__ - Learn to Code with CodeCombat" stats: "Estadístiques" singleplayer_title: "Nivell d'un sol jugador" multiplayer_title: "Nivells multijugador" achievements_title: "Triomfs" last_played: "Ultim jugat" status: "Estat" status_completed: "Complet" status_unfinished: "Inacabat" no_singleplayer: "Encara no s'han jugat nivells individuals." no_multiplayer: "Encara no s'han jugat nivells multijugador." no_achievements: "No has aconseguit cap triomf encara." favorite_prefix: "L'idioma preferit és " favorite_postfix: "." not_member_of_clans: "Encara no ets membre de cap clan" certificate_view: "veure certificat" certificate_click_to_view: "fes clic per veure el certificat" certificate_course_incomplete: "curs incomplet" certificate_of_completion: "Certificat de Finalització" certificate_endorsed_by: "Aprovat per" certificate_stats: "Estadístiques del curs" certificate_lines_of: "línies de" certificate_levels_completed: "nivells completats" certificate_for: "Per" # certificate_number: "No." achievements: last_earned: "Últim aconseguit" amount_achieved: "Cantitat" achievement: "Triomf" current_xp_prefix: "" current_xp_postfix: " en total" new_xp_prefix: "" new_xp_postfix: " guanyat" left_xp_prefix: "" left_xp_infix: " fins el nivell " left_xp_postfix: "" account: # title: "Account" # settings_title: "Account Settings" # unsubscribe_title: "Unsubscribe" # payments_title: "Payments" # subscription_title: "Subscription" # invoices_title: "Invoices" # prepaids_title: "Prepaids" payments: "Pagaments" prepaid_codes: "Codis prepagats" purchased: "Comprat" subscribe_for_gems: "Subscriure's per gemmes" subscription: "Subscripció" invoices: "Factures" service_apple: "Apple" service_web: "Web" paid_on: "Pagat a" service: "Servei" price: "Preu" gems: "Gemmess" active: "Actiu" subscribed: "Subscrit" unsubscribed: "No s'ha subscrit" active_until: "Actiu fins a" cost: "Cost" next_payment: "Següent pagament" card: "Targeta" status_unsubscribed_active: "No esteu subscrit i no se us facturarà, però el vostre compte encara està actiu per ara." status_unsubscribed: "Accediu a nous nivells, herois, ítems i gemmes de bonificació amb una subscripció a CodeCombat!" not_yet_verified: "Encara no s'ha verificat." resend_email: "Reenvia l'e-mail" email_sent: "E-mail enviat! Comprova la teva safata d'entrada." verifying_email: "Verificant la teva adreça e-mail..." successfully_verified: "Has verificat correctament la teva adreça e-mail!" verify_error: "S'ha produït un error en verificar el teu e-mail :(" unsubscribe_from_marketing: "Abandonar la subscripció a __email__ de tots els e-mails de màrqueting de CodeCombat?" unsubscribe_button: "Sí, abandonar la subscripció" unsubscribe_failed: "Errada" unsubscribe_success: "Èxit" account_invoices: amount: "Quantitat en dòlars nord-americans" declined: "S'ha denegat la targeta" invalid_amount: "Si us plau, introduïu un import en dòlars nord-americans." not_logged_in: "Inicieu sessió o creeu un compte per accedir a les factures." pay: "Factures de Pagament" purchasing: "Comprant..." retrying: "Error del Servidor, reintentant." success: "S'ha pagat correctament. Gràcies!" account_prepaid: purchase_code: "Compreu un codi de subscripció" purchase_code1: "Es poden bescanviar els codis de subscripció per afegir el temps de subscripció premium a un o més comptes de la versió Home de CodeCombat." purchase_code2: "Cada compte de CodeCombat només pot bescanviar un codi de subscripció en particular una vegada." purchase_code3: "Els mesos del codi de subscripció s'afegiran al final de qualsevol subscripció existent al compte." purchase_code4: "Els codis de subscripció són per als comptes que reprodueixen la versió inicial de CodeCombat, no es poden utilitzar en lloc de les llicències d'estudiants per a la versió de Classroom." purchase_code5: "Per obtenir més informació sobre les llicències d'estudiants, consulteu-les a" users: "Usuaris" months: "Mesos" purchase_total: "Total" purchase_button: "Enviar compra" your_codes: "Els teus Codis" redeem_codes: "Canvia un codi de subscripció" prepaid_code: "Codi Prepagat" lookup_code: "Cerca el Codi Prepagat" apply_account: "Aplicar al teu compte" copy_link: "Podeu copiar l'enllaç del codi i enviar-lo a algú." quantity: "Quantitat" redeemed: "Canviats" no_codes: "Encara no hi ha cap codi!" you_can1: "Pots" you_can2: "comprar un codi Prepagat" you_can3: "per aplicar al teu compte o donar a d'altres." loading_error: could_not_load: "Error de carrega del servidor" connection_failure: "Connexió fallida." connection_failure_desc: "Sembla que no estàs connectat a internet! Comprova la teva connexió a la xarxa i després recarrega aquesta plana." login_required: "Es requereix iniciar sessió" login_required_desc: "Necessites iniciar sessió per accedir a aquesta plana." unauthorized: "Has d'iniciar la sessió. Tens les galetes desactivades?" forbidden: "No disposes dels permisos." forbidden_desc: "Oh no, aquí no et podem mostrar res! Comprova que has iniciat sessió amb el compte correcte, o visita un dels enllaços següents per tornar a programar!" not_found: "No trobat." not_found_desc: "Hm, aquí no hi ha res. Visita un dels enllaços següents per tornar a programar!" not_allowed: "Metode no permès." timeout: "Temps d'espera del servidor superat" conflict: "Conflicte de recursos." bad_input: "Entrada incorrecta." server_error: "Error del servidor." unknown: "Error Desconegut" error: "ERROR" general_desc: "Alguna cosa ha anat malament, i és probable que sigui culpa nostra. Mira d'esperar una mica i després recarrega la plana, o visita un dels enllaços següents per tornar a programar!" resources: level: "Nivell" patch: "Pedaç" patches: "Pedaços" system: "Sistema" systems: "Sistemes" component: "Component" components: "Components" hero: "Heroi" campaigns: "Campanyes" concepts: advanced_css_rules: "Regles CSS avançades" advanced_css_selectors: "Selectors CSS avançats" advanced_html_attributes: "Atributs HTML avançats" advanced_html_tags: "Etiquetes HTML avançades" algorithm_average: "Algorisme mitjà" algorithm_find_minmax: "Algorisme Trobar Mínim/Màxim" algorithm_search_binary: "Algorisme Cerca Binària" algorithm_search_graph: "Algorisme Cerca Gràfica" algorithm_sort: "Algorisme Tipus" algorithm_sum: "Algorisme Suma" arguments: "Arguments" arithmetic: "Aritmètica" array_2d: "Cadenes 2D" array_index: "Indexació de Cadenes" array_iterating: "Iteració en Cadenes" array_literals: "Cadenes Literals" array_searching: "Cerca en Cadenes" array_sorting: "Classificació en Cadenes" arrays: "Cadenes" basic_css_rules: "Regles bàsiques CSS" basic_css_selectors: "Selectors bàsics CSS" basic_html_attributes: "Atributs bàsics HTML" basic_html_tags: "Etiquetes bàsiques HTML" basic_syntax: "Sintaxis bàsica" binary: "Binari" boolean_and: "I Booleana" boolean_inequality: "Desigualtat Booleana" boolean_equality: "Igualtat Booleana" boolean_greater_less: "Major/Menor Booleans" boolean_logic_shortcircuit: "Circuits lògics Booleans" boolean_not: "Negació Booleana" boolean_operator_precedence: "Ordre d'operadors Booleans" boolean_or: "O Booleana" boolean_with_xycoordinates: "Comparació coordinada" bootstrap: "Programa d'arranque" break_statements: "Declaracions Break" classes: "Classes" continue_statements: "Sentències Continue" dom_events: "Events DOM" dynamic_styling: "Estilisme dinàmic" # events: "Events" event_concurrency: "Concurrència d'events" event_data: "Data d'event" event_handlers: "Controlador d'Events" event_spawn: "Event generador" for_loops: "Bucles (For)" for_loops_nested: "Anidació amb bucles" for_loops_range: "Pel rang de bucles" functions: "Funcions" functions_parameters: "Paràmetres" functions_multiple_parameters: "Paràmetres múltiples" game_ai: "Joc AI" game_goals: "Objectius del Joc" game_spawn: "Generador del Joc" graphics: "Gràfics" graphs: "Gràfics" heaps: "Munts" if_condition: "Sentències Condicionals 'If'" if_else_if: "Sentències 'If/Else If'" if_else_statements: "Sentències 'If/Else'" if_statements: "Sentències If" if_statements_nested: "Sentències If anidades" indexing: "Indexació en Matrius" input_handling_flags: "Manipulació d'entrades - Banderes" input_handling_keyboard: "Manipulació d'entrades - Teclat" input_handling_mouse: "Manipulació d'entrades - Ratolí" intermediate_css_rules: "Regles intermàdies de CSS" intermediate_css_selectors: "Selector intermedis CSS" intermediate_html_attributes: "Atributs intermedis HTML" intermediate_html_tags: "Etiquetes intermèdies HTML" jquery: "jQuery" jquery_animations: "Animacions jQuery" jquery_filtering: "Filtratge d'elements jQuery" jquery_selectors: "Selectors jQuery" length: "longitud de la matriu" math_coordinates: "Coordinar Matemàtiques" math_geometry: "Geometria" math_operations: "Operacions matemàtiques" math_proportions: "Proporcions matemàtiques" math_trigonometry: "Trigonometria" object_literals: "Objectes Literals" parameters: "Paràmetres" # programs: "Programs" # properties: "Properties" property_access: "Accés a Propietats" property_assignment: "Assignar Propietats" property_coordinate: "Coordinar Propietat" queues: "Estructures de dades - Cues" reading_docs: "Llegint els Documents" recursion: "Recursivitat" return_statements: "Sentències de retorn" stacks: "Estructures de dades - Piles" strings: "Cadenes" strings_concatenation: "Concatenació de cadenes" strings_substrings: "Subcadenes" trees: "Estructures de dades - Arbres" variables: "Variables" vectors: "Vectors" while_condition_loops: "Bucles 'While' amb condicionals" while_loops_simple: "Bucles 'While'" while_loops_nested: "Bucles 'While' anidats" xy_coordinates: "Coordenades Cartesianes" advanced_strings: "Cadenes de text avançades (string)" # Rest of concepts are deprecated algorithms: "Algorismes" boolean_logic: "Lògica booleana" basic_html: "HTML Bàsic" basic_css: "CSS Bàsic" basic_web_scripting: "Escriptura Web bàsica" intermediate_html: "HTML intermig" intermediate_css: "CSS intermig" intermediate_web_scripting: "Escriptura Web intermitja" advanced_html: "HTML avançat" advanced_css: "CSS avançat" advanced_web_scripting: "Escriptura Web avançada" input_handling: "Manipulació de dades d'entrada" while_loops: "Bucles 'While'" place_game_objects: "Situar objectes del joc" construct_mazes: "Construir laberints" create_playable_game: "Crear un projecte de joc que es pugui jugar i compartir" alter_existing_web_pages: "Modificar planes web existents" create_sharable_web_page: "Crear una plana web compartible" basic_input_handling: "Manipulació d'entrada bàsica" basic_game_ai: "Joc bàsic d'AI" basic_javascript: "JavaScript bàsic" basic_event_handling: "Manipulació d'Events bàsica" create_sharable_interactive_web_page: "Crear una plana web compartible interactiva" anonymous_teacher: notify_teacher: "Notificar Professor" create_teacher_account: "Crear un compte de professorat gràtis" enter_student_name: "El teu nom:" enter_teacher_email: "El teu e-mail de professor:" teacher_email_placeholder: "teacher.email@example.com" student_name_placeholder: "Escriu aquí el teu nom" teachers_section: "Docents:" students_section: "Alumnat:" teacher_notified: "Hem notificat al vostre professor que voleu jugar més a CodeCombat en classe." delta: added: "Afegit" modified: "Modificat" not_modified: "No modificat" deleted: "Eliminat" moved_index: "Índex desplaçat" text_diff: "Diferir text" merge_conflict_with: "Conflicte d'unió amb" no_changes: "Sense canvis" legal: page_title: "Legalitat" # opensource_introduction: "CodeCombat is part of the open source community." opensource_description_prefix: "Comprova " github_url: "el nostre GitHub" opensource_description_center: "i ajuda'ns si vols! CodeCombat està construit amb dotzenes de projectes de codi obert, i ens encanta. Mira " archmage_wiki_url: "la nostra wiki d'ArxiMags" opensource_description_suffix: "per observar la llista de software que fa possible aquest joc." practices_title: "Bones Pràctiques Respectuoses" practices_description: "Aquesta és la promesa que et fem, jugador, d'una manera no tant legal." privacy_title: "Privacitat" privacy_description: "No vendrem cap informació personal teva." security_title: "Seguretat" security_description: "Ens esforcem per mantenir segura la vostra informació personal. Com a projecte de codi obert, el nostre lloc està lliurement obert a tothom per revisar i millorar els nostres sistemes de seguretat." email_title: "E-mail" email_description_prefix: "No us inundarem amb correu brossa. Mitjançant" email_settings_url: "la teva configuració d'e-mail" email_description_suffix: "o mitjançant els enllaços als e-mails que t'enviem, pots canviar les teves preferències i donar-te de baixa fàcilment en qualsevol moment." cost_title: "Cost" cost_description: "CodeCombat és gratuït per a tots els nivells bàsics, amb una subscripció de ${{price}} USD al mes per accedir a branques de nivells extra i {{gems}} bonus de gemmes al mes. Pots cancel·lar-ho amb un clic i oferim una garantia de devolució del 100%." copyrights_title: "Copyrights i Llicències" contributor_title: "Acord de Llicència de Col·laborador (CLA)" contributor_description_prefix: "Tots els col·laboradors, tant del lloc com del repositori GitHub, estan subjets al nostre" cla_url: "CLA" contributor_description_suffix: "que has d'acceptar abans de fer contribucions." code_title: "Codi - MIT" # client_code_description_prefix: "All client-side code for codecombat.com in the public GitHub repository and in the codecombat.com database, is licensed under the" mit_license_url: "llicència MIT" code_description_suffix: "Això inclou tot el codi a Sistemes i Components que s'han fet possibles per CodeCombat amb el proposit de crear nivells." art_title: "Art/Música - Creative Commons " art_description_prefix: "Tot el contingut comú està disponible sota" cc_license_url: "llicència Creative Commons Attribution 4.0 International" art_description_suffix: "El contingut comú és generalment disponible per CodeCombat amb la finalitat de crear nivells. Inclou:" art_music: "Musica" art_sound: "So" art_artwork: "Art" art_sprites: "Capes" art_other: "Tots i cadascun dels treballs creatius que no siguin de codi que estiguin disponibles quan es creïn Nivells." art_access: "Actualment, no hi ha cap sistema universal i fàcil d'obtenir aquests actius. En general, obtingueu-les des dels URL que utilitzeu el lloc, contacteu-nos per obtenir assistència o ens ajudeu a ampliar el lloc per fer-los accessibles amb més facilitat." art_paragraph_1: "Per a l'atribució, si us plau, cita i vincle a codecombat.com a prop d'on s'utilitza la font o, si escau, per al mitjà. Per exemple:" use_list_1: "Si s'utilitza en una pel·lícula o en un altre joc, incloeu codecombat.com en els crèdits." use_list_2: "Si s'utilitza en un lloc web, incloeu un enllaç prop de l'ús, per exemple, sota una imatge o en una pàgina d'atribucions generals on també podeu esmentar altres obres de Creative Commons i programari de codi obert que s'utilitza al lloc. Alguna cosa que ja fa referència clarament a CodeCombat, com ara una publicació de bloc que menciona CodeCombat, no necessita cap atribució per separat." art_paragraph_2: "Si el contingut que s'utilitza no és creat per CodeCombat sinó per un usuari de codecombat.com, atribueix-lo a ell, i seguiu les indicacions d'atribució proporcionades en la descripció del recurs si hi ha alguna." rights_title: "Drets reservats" rights_desc: "Tots els drets estan reservats per als mateixos Nivells. Això inclou" rights_scripts: "Scripts" rights_unit: "Configuració de la unitat" rights_writings: "Escrits" rights_media: "Mitjans de comunicació (sons, música) i qualsevol altre contingut creatiu fet específicament per a aquest nivell i generalment no està disponible quan es creen nivells." rights_clarification: "Per aclarir, qualsevol cosa que estigui disponible a l'Editor de Nivells amb la finalitat de fer nivells està sota CC, mentre que el contingut creat amb l'Editor de Nivells o carregat en el curs de creació de Nivells no ho és." nutshell_title: "En poques paraules" nutshell_description: "Els recursos que oferim a l'Editor de Nivells es poden utilitzar de la manera que vulgueu per crear nivells. Però ens reservem el dret de restringir la distribució dels mateixos Nivells (que es creen a codecombat.com) perquè es puguin cobrar." nutshell_see_also: "Veure també:" canonical: "La versió en anglès d'aquest document és la versió definitiva i canònica. Si hi ha discrepàncies entre les traduccions, el document anglès té prioritat." third_party_title: "Serveis de tercers" third_party_description: "CodeCombat usa els següents serveis de tercers (entre d'altres):" cookies_message: "CodeCombat utilitza unes quantes galetes essencials i no essencials." cookies_deny: "Declareu les galetes no essencials" ladder_prizes: title: "Premis del torneig" # This section was for an old tournament and doesn't need new translations now. blurb_1: "Aquests premis seran guanyats d'acord amb" blurb_2: "Les normes del torneig" blurb_3: "els millors jugadors humans i ogres." blurb_4: "Dos equips signifiquen el doble de premis!" blurb_5: "(Hi haura dos guanyadors pel primer lloc, dos pels del segon lloc, etc.)" rank: "Rang" prizes: "Premis" total_value: "Valor total" in_cash: "en diners" custom_wizard: "Personalitza el teu bruixot de CodeCombat" custom_avatar: "Personalitza el teu avatar de CodeCombat" heap: "per sis mesos d'acces \"Startup\" " credits: "crèdits" one_month_coupon: "cupó: trieu Rails o HTML" one_month_discount: "descompte del 30%: seleccioneu Rails o HTML" license: "llicencia" oreilly: "ebook de la vostra elecció" calendar: year: "Any" day: "Dia" month: "Mes" january: "Gener" february: "Febrer" march: "Març" april: "Abril" may: "Maig" june: "Juny" july: "Juliol" august: "Agost" september: "Setembre" october: "Octubre" november: "Novembre" december: "Desembre" code_play_create_account_modal: title: "Ho has fet!" # This section is only needed in US, UK, Mexico, India, and Germany body: "Ara estàs en camí d'esdevenir un mestre codificador. Registra't per rebre un extra de <strong>100 Gemmes</strong> i també se't donarà l'oportunitat de <strong>guanyar $2,500 i altres premis de Lenovo</strong>." sign_up: "Retistra't i continua codificant ▶" victory_sign_up_poke: "Crea un compte gratuït per desar el codi i ingressa per obtenir premis." victory_sign_up: "Inscriu-te i accedeix a poder <strong>gunayar $2,500</strong>" server_error: email_taken: "E-mail ja agafat" username_taken: "Usuari ja agafat" esper: line_no: "Línia $1: " uncaught: "Irreconeixible $1" # $1 will be an error type, eg "Uncaught SyntaxError" reference_error: "Error de Referència: " argument_error: "Error d'Argument: " type_error: "Error d'Escriptura: " syntax_error: "Error de Sintaxi: " error: "Error: " x_not_a_function: "$1 no és una funció" x_not_defined: "$1 no s'ha definit" spelling_issues: "Revisa l'ortografia: volies dir `$1` en lloc de `$2`?" capitalization_issues: "Revisa les majúscules: `$1` hauria de ser `$2`." py_empty_block: "$1 buit. Posa 4 espais abans de la declaració dintre de la declaració $2." fx_missing_paren: "Si vols cridar `$1` com a funció, necessites posar `()`" unmatched_token: "`$1` sense parella. Cada `$2` obert necessita un `$3` tancat per emparellar-se." unterminated_string: "Cadena sense finalitzar. Afegeix una `\"` a joc al final de la teva cadena." missing_semicolon: "Punt i coma oblidat." missing_quotes: "Cometes oblidades. Prova `$1`" argument_type: "L'argument de `$1`, `$2`, hauria de tenir tipus `$3`, però té `$4`: `$5`." argument_type2: "L'argument de `$1`', `$2`, hauria de tenir tipus `$3`, però té `$4`." target_a_unit: "Invoca una unitat." attack_capitalization: "Attack $1, no $2. (Les majúscules són importants.)" empty_while: "Ordre 'while' buida. Posa 4 espais al davant de les següents ordres que pertanyin a while." line_of_site: "L'argument de `$1`, `$2`, té un problema. Ja tens cap enemic a la teva línia d'acció?" need_a_after_while: "Necessites `$1` després de `$2`." too_much_indentation: "Massa sagnat a l'inici d'aquesta línia." missing_hero: "Falta paraula clau a `$1`; hauria de ser `$2`." takes_no_arguments: "`$1` no pren cap argument." no_one_named: "No n'hi ha cap anomenat \"$1\" a qui adreçar-se." separated_by_comma: "Els paràmetres que crida la funció han d'anar separats mitjançant `,`" protected_property: "No puc llegir la propietat protegida: $1" need_parens_to_call: "Si vols cridar `$1` com a funció, necessites posar `()`" expected_an_identifier: "S'esperava un identificador i en canvi vam veure '$1'." unexpected_identifier: "Identificador inesperat" unexpected_end_of: "Final d'entrada inesperat" unnecessary_semicolon: "Punt i coma innecessari." unexpected_token_expected: "Simbol inesperat: esperavem $1 però hem trobat $2 mentre analitzavem $3" unexpected_token: "Simbol $1 inesperat" unexpected_token2: "Simbol inesperat" unexpected_number: "Número inesperat" unexpected: "'$1' inesperat." escape_pressed_code: "En picar Escape; s'aborta el codi." target_an_enemy: "Invoca un enemic pel nom, com ara `$1`, no amb la cadena `$2`." target_an_enemy_2: "Invoca un enemic pel nom, com ara $1." cannot_read_property: "No puc llegir bé '$1' o indefinit" attempted_to_assign: "S'ha intentat assignar a la propietat que és només de lectura." unexpected_early_end: "Final prematur de programa inesperat." you_need_a_string: "Necessites una cadena per construir; una de $1" unable_to_get_property: "Impossible adquirir la propietat '$1' d'una referència indefinida o nula" # TODO: Do we translate undefined/null? code_never_finished_its: "El codi mai finalitza. Realment va lent o té un bucle infinit." unclosed_string: "Cadena sense tancar." unmatched: "'$1' sense emparellar." error_you_said_achoo: "Has dit: $1, però la contrasenya és: $2. (Les majúscules són importants.)" indentation_error_unindent_does: "Error de sagnat: el sagnat no coincideix amb cap altre nivell de sagnat" indentation_error: "Error de sagnat." need_a_on_the: "Necessites posar `:` al final de la línia que segueix a `$1`." attempt_to_call_undefined: "intentes anomenar '$1' (un valor nul)" unterminated: "`$1` sense acabar" target_an_enemy_variable: "Invoca la variable $1, no la cadena $2. (Prova a usar $3.)" error_use_the_variable: "Usa el nom de la variable com ara `$1` enlloc de la cadena com ara `$2`" indentation_unindent_does_not: "Sagnat indegut que no concorda amb cap altre nivell" unclosed_paren_in_function_arguments: "Sense tancar $1 en els arguments de la funció." unexpected_end_of_input: "Final d'entrada inesperat" there_is_no_enemy: "No hi ha cap `$1`. Usa `$2` primer." # Hints start here try_herofindnearestenemy: "Prova amb `$1`" there_is_no_function: "No hi ha cap funció `$1`, però `$2` té un mètode `$3`." attacks_argument_enemy_has: "L'argument de `$1`, `$2`, té un problema." is_there_an_enemy: "Ja n'hi ha algun enemic dintre de la teva línia de visió?" target_is_null_is: "Has invocat $1. Sempre hi ha un invocat per atacar? (Usa $2?)" hero_has_no_method: "`$1` no té mètode `$2`." there_is_a_problem: "Hi ha un problema amb el teu codi." did_you_mean: "Volies dir $1? No tens cap ítem equipat amb aquesta habilitat." missing_a_quotation_mark: "T'has oblidat posar una cometa. " missing_var_use_var: "T'has oblidat `$1`. Usa `$2` per crear una nova variable." you_do_not_have: "No tens cap ítem equipat amb l'habilitat $1." put_each_command_on: "Posa cada comand en una línia diferent" are_you_missing_a: "T'estàs oblidant de '$1' després de '$2'? " your_parentheses_must_match: "Els teus parèntesis han de coincidir." apcsp: # title: "AP Computer Science Principals | College Board Endorsed" # meta_description: "CodeCombat’s comprehensive curriculum and professional development program are all you need to offer College Board’s newest computer science course to your students." syllabus: "Pla d'Estudis de Fonaments de Programació" syllabus_description: "Utilitza aquest recurs per planificar el currículum de CodeCombat pel teu Pla d'Estudis de Fonaments de Programació de la teva classe." computational_thinking_practices: "Pràctiques de Pensament Computacional" learning_objectives: "Objectius d'Aprenentatge" curricular_requirements: "Requeriments Curriculars" unit_1: "Unitat 1: Tecnologia Creativa" unit_1_activity_1: "Unitat 1 Activitat: Revisió de la usabilitat tecnològica" unit_2: "Unitat 2: Pensament Computacional" unit_2_activity_1: "Unitat 2 Activitat: Seqüències Binaries" unit_2_activity_2: "Unitat 2 Activitat: Projecte de lliçons informàtiques" unit_3: "Unitat 3: Algorismes" unit_3_activity_1: "Unitat 3 Activitat: Algorismes - Guia de l'Autoestopista" unit_3_activity_2: "Unitat 3 Activitat: Simulació - Depredador i Presa" unit_3_activity_3: "Unitat 3 Activitat: Algorismes - Disseny de parelles i Programació" unit_4: "Unitat 4: Programació" unit_4_activity_1: "Unitat 4 Activitat: Abstraccions" unit_4_activity_2: "Unitat 4 Activitat: Cerca i Classificació" unit_4_activity_3: "Unitat 4 Activitat: Refactorització" unit_5: "Unitat 5: Internet" unit_5_activity_1: "Unitat 5 Activitat: Com funciona Internet" unit_5_activity_2: "Unitat 5 Activitat: Simulació d'Internet" unit_5_activity_3: "Unitat 5 Activitat: Simulation d'un Xat" unit_5_activity_4: "Unitat 5 Activitat: Cyberseguritat" unit_6: "Unitat 6: Dades" unit_6_activity_1: "Unitat 6 Activitat: Introducció a les Dades" unit_6_activity_2: "Unitat 6 Activitat: Big Data" unit_6_activity_3: "Unitat 6 Activitat: Compressió amb i sense Pèrdua" unit_7: "Unitat 7: Impacte Personal i Global" unit_7_activity_1: "Unitat 7 Activitat: Impacte Personal i Global" unit_7_activity_2: "Unitat 7 Activitat: Crowdsourcing" unit_8: "Unitat 8: Tasques de Rendiment" unit_8_description: "Prepara els estudiants per a Tasca Creativa, construint els seus propis jocs i practicant conceptes clau." unit_8_activity_1: "Pràctica Tasca Creativa 1: Desenvolupament de Jocs 1" unit_8_activity_2: "Pràctica Tasca Creativa 2: Desenvolupament de Jocs 2" unit_8_activity_3: "Pràctica Tasca Creativa 3: Desenvolupament de Jocs 3" unit_9: "Unitat 9: Revisió dels Fonaments" unit_10: "Unitat 10: Més enllà dels Fonaments" unit_10_activity_1: "Unitat 10 Activitat: Web Quiz" parent_landing: slogan_quote: "\"CodeCombat és realment difertit, i aprens molt.\"" quote_attr: "5è grau, Oakland, CA" refer_teacher: "Consulteu al Professor" focus_quote: "Desbloqueja el futur del teus fills" value_head1: "La forma més atractiva d'aprendre codi escrit" value_copy1: "CodeCombat és un tutor personal dels nens. Amb material de cobertura d'acord amb els estàndards curriculars nacionals, el vostre fill programarà algorismes, crearà llocs web i fins i tot dissenyarà els seus propis jocs." value_head2: "Construint habilitats claus per al segle XXI" value_copy2: "Els vostres fills aprendran a navegar i esdevenir ciutadans del món digital. CodeCombat és una solució que millora el pensament crític i la capacitat de recuperació del vostre fill." value_head3: "Herois que els vostres fills estimaran" value_copy3: "Sabem la importància que té divertir-se i implicar-se pel desenvolupament del cervell, per això hem encabit tant aprenentatge com hem pogut presentant-lo en un joc que els encantarà." dive_head1: "No només per als enginyers de programació" dive_intro: "Les habilitats informàtiques tenen una àmplia gamma d'aplicacions. Mireu alguns exemples a continuació!" medical_flag: "Aplicacions Mèdiques" medical_flag_copy: "Des del mapatge del genoma humà fins a les màquines de ressonància magnètica, la codificació ens permet comprendre el cos de maneres que mai no hem pogut fer." explore_flag: "Exploració Espacial" explore_flag_copy: "Apol·lo va arribar a la Lluna gràcies al treball humà amb ordinadors, i els científics utilitzen programes informàtics per analitzar la gravetat dels planetes i buscar noves estrelles." filmaking_flag: "Producció de Vídeo i Animació" filmaking_flag_copy: "Des de la robòtica del Jurassic Park fins a l'increïble animació de Dreamworks i Pixar, les pel·lícules no serien les mateixes sense les creacions digitals darrere de les escenes." dive_head2: "Els jocs són importants per aprendre" dive_par1: "Múltiples estudis han trobat que l'aprenentatge mitjançant jocs promou" dive_link1: "el desenvolupament cognitiu" dive_par2: "en els nens al mateix temps que demostra ser" dive_link2: "més efectiu" dive_par3: "ajudant els alumnes a" dive_link3: "aprendre i retenir coneixements" dive_par4: "," dive_link4: "concentrar-se" dive_par5: ", i aconseguir un major assoliment." dive_par6: "L'aprenentatge basat en jocs també és bo per desenvolupar" dive_link5: "resiliència" dive_par7: ", raonament cognitiu, i" dive_par8: ". Les Ciències només ens diuen què han de saber els nens. Aquests aprenen millor jugant." dive_link6: "funcions executives" dive_head3: "Fent Equip amb els Professors" dive_3_par1: "En el futur, " dive_3_link1: "codificar serà tan fonamental com aprendre a llegir i escriure" dive_3_par2: ". Hem treballat estretament amb els professors per dissenyar i desenvolupar el nostre contingut, i estem ensiosos per ensenyar als vostres fills. Els programes de tecnologia educativa com CodeCombat funcionen millor quan els professors els implementen de forma coherent. Ajudeu-nos a fer aquesta connexió presentant-nos als professors del vostre fill." mission: "La nostra missió: ensenyar i participar" mission1_heading: "Codificant per la generació d'avui" mission2_heading: "Preparant pel futur" mission3_heading: "Recolzat per pares com tu" mission1_copy: "Els nostres especialistes en educació treballen estretament amb els professors per conèixer els nens que es troben a l'entorn educatiu. Els nens aprenen habilitats que es poden aplicar fora del joc perquè aprenen a resoldre problemes, independentment del seu estil d'aprenentatge." mission2_copy: "Una enquesta de 2016 va demostrar que el 64% de les noies de 3r a 5è grau volien aprendre a codificar. Es van crear 7 milions de llocs de treball al 2015 on es requerien habilitats en codificació. Hem construït CodeCombat perquè cada nen hauria de tenir l'oportunitat de crear el seu millor futur." mission3_copy: "A CodeCombat, som pares. Som coders. Som educadors. Però, sobretot, som persones que creiem en donar als nostres fills la millor oportunitat per l'èxit en qualsevol cosa que decideixin fer." parent_modal: refer_teacher: "Consulteu al Professor" name: "El teu Nom" parent_email: "El teu E-mail" teacher_email: "E-mail del Professor" message: "Missatge" custom_message: "Acabo de trobar CodeCombat i vaig pensar que seria un gran programa per a la vostra aula! És una plataforma d'aprenentatge d'informàtica amb un pla d'estudis amb estàndards.\n\nL'alfabetització informàtica és tan important i crec que aquesta seria una gran manera d'aconseguir que els estudiants es dediquin a aprendre a codificar." send: "E-mail enviat" hoc_2018: # banner: "Happy Computer Science Education Week 2018!" page_heading: "Ensenya als teus alumnes com construir el seu propi joc d'arcade!" # {change} # step_1: "Step 1: Watch Video Overview" # step_2: "Step 2: Try it Yourself" # step_3: "Step 3: Download Lesson Plan" # try_activity: "Try Activity" download_pdf: "Descarregar PDF" # teacher_signup_heading: "Turn Hour of Code into a Year of Code" # teacher_signup_blurb: "Everything you need to teach computer science, no prior experience needed." # teacher_signup_input_blurb: "Get first course free:" # teacher_signup_input_placeholder: "Teacher email address" # teacher_signup_input_button: "Get CS1 Free" # activities_header: "More Hour of Code Activities" # activity_label_1: "Escape the Dungeon!" # activity_label_2: " Beginner: Build a Game!" # activity_label_3: "Advanced: Build an Arcade Game!" # activity_button_1: "View Lesson" about: "Sobre CodeCombat:" # {change} about_copy: "CodeCombat és un programa informàtic basat en jocs per ensenyar Python i JavaScript reals. El currículum d'acord amb els estàndards de CodeCombat es basa en un joc que els estudiants estimen. Més de 12 milions d'estudiants han après a codificar amb CodeCombat!" # {change} point1: "✓ Amb recolçament" point2: "✓ Diferenciat" point3: "✓ Avaluació Formativa i Sumativa" # {change} point4: "✓ Cursos basats en Projectes" point5: "✓ Seguiment de l'Alumnat" point6: "✓ Planificació de Lliçons complertes" # title: "HOUR OF CODE 2018" # acronym: "HOC" # hoc_2018_interstitial: # welcome: "Welcome to CodeCombat's Hour of Code 2018!" # educator: "I'm an educator" # show_resources: "Show me teacher resources!" # student: "I'm a student" # ready_to_code: "I'm ready to code!" # hoc_2018_completion: # congratulations: "Congratulations on completing <b>Code, Play, Share!</b>" # send: "Send your Hour of Code game to friends and family!" # copy: "Copy URL" # get_certificate: "Get a certificate of completion to celebrate with your class!" # get_cert_btn: "Get Certificate" # first_name: "First Name" # last_initial: "Last Initial" # teacher_email: "Teacher's email address" # school_administrator: # title: "School Administrator Dashboard" # my_teachers: "My Teachers" # last_login: "Last Login" # licenses_used: "licenses used" # total_students: "total students" # active_students: "active students" # projects_created: "projects created" # other: "Other" # notice: "The following school administrators have view-only access to your classroom data:" # add_additional_teacher: "Need to add an additional teacher? Contact your CodeCombat Account Manager or email support@codecombat.com. " # license_stat_description: "Licenses available accounts for the total number of licenses available to the teacher, including Shared Licenses." # students_stat_description: "Total students accounts for all students across all classrooms, regardless of whether they have licenses applied." # active_students_stat_description: "Active students counts the number of students that have logged into CodeCombat in the last 60 days." # project_stat_description: "Projects created counts the total number of Game and Web development projects that have been created." # no_teachers: "You are not administrating any teachers."
202423
module.exports = nativeDescription: "Català", englishDescription: "Catalan", translation: new_home: # title: "CodeCombat - Coding games to learn Python and JavaScript" # meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." # built_for_teachers_title: "A Coding Game Built with Teachers in Mind" # built_for_teachers_blurb: "Teaching kids to code can often feel overwhelming. CodeCombat helps all educators teach students how to code in either JavaScript or Python, two of the most popular programming languages. With a comprehensive curriculum that includes six computer science units and reinforces learning through project-based game development and web development units, kids will progress on a journey from basic syntax to recursion!" # built_for_teachers_subtitle1: "Computer Science" # built_for_teachers_subblurb1: "Starting with our free Introduction to Computer Science course, students master core coding concepts such as while/for loops, functions, and algorithms." # built_for_teachers_subtitle2: "Game Development" # built_for_teachers_subblurb2: "Learners construct mazes and use basic input handling to code their own games that can be shared with friends and family." # built_for_teachers_subtitle3: "Web Development" # built_for_teachers_subblurb3: "Using HTML, CSS, and jQuery, learners flex their creative muscles to program their own webpages with a custom URL to share with their classmates." # century_skills_title: "21st Century Skills" # century_skills_blurb1: "Students Don't Just Level Up Their Hero, They Level Up Themselves" # century_skills_quote1: "You mess up…so then you think about all of the possible ways to fix it, and then try again. I wouldn't be able to get here without trying hard." # century_skills_subtitle1: "Critical Thinking" # century_skills_subblurb1: "With coding puzzles that are naturally scaffolded into increasingly challenging levels, CodeCombat's programming game ensures kids are always practicing critical thinking." # century_skills_quote2: "Everyone else was making mazes, so I thought, ‘capture the flag’ and that’s what I did." # century_skills_subtitle2: "Creativity" # century_skills_subblurb2: "CodeCombat encourages students to showcase their creativity by building and sharing their own games and webpages." # century_skills_quote3: "If I got stuck on a level. I would work with people around me until we were all able to figure it out." # century_skills_subtitle3: "Collaboration" # century_skills_subblurb3: "Throughout the game, there are opportunities for students to collaborate when they get stuck and to work together using our pair programming guide." # century_skills_quote4: "I’ve always had aspirations of designing video games and learning how to code ... this is giving me a great starting point." # century_skills_subtitle4: "Communication" # century_skills_subblurb4: "Coding requires kids to practice new forms of communication, including communicating with the computer itself and conveying their ideas using the most efficient code." # classroom_in_box_title: "We Strive To:" # classroom_in_box_blurb1: "Engage every student so that they believe coding is for them." # classroom_in_box_blurb2: "Empower any educator to feel confident when teaching coding." # classroom_in_box_blurb3: "Inspire all school leaders to create a world-class computer science program." # creativity_rigor_title: "Where Creativity Meets Rigor" # creativity_rigor_subtitle1: "Make coding fun and teach real-world skills" # creativity_rigor_blurb1: "Students type real Python and JavaScript while playing games that encourage trial-and-error, critical thinking, and creativity. Students then apply the coding skills they’ve learned by developing their own games and websites in project-based courses." # creativity_rigor_subtitle2: "Reach students at their level" # creativity_rigor_blurb2: "Every CodeCombat level is scaffolded based on millions of data points and optimized to adapt to each learner. Practice levels and hints help students when they get stuck, and challenge levels assess students' learning throughout the game." # creativity_rigor_subtitle3: "Built for all teachers, regardless of experience" # creativity_rigor_blurb3: "CodeCombat’s self-paced, standards-aligned curriculum makes teaching computer science possible for everyone. CodeCombat equips teachers with the training, instructional resources, and dedicated support to feel confident and successful in the classroom." # featured_partners_title1: "Featured In" # featured_partners_title2: "Awards & Partners" # featured_partners_blurb1: "CollegeBoard Endorsed Provider" # featured_partners_blurb2: "Best Creativity Tool for Students" # featured_partners_blurb3: "Top Pick for Learning" # featured_partners_blurb4: "Code.org Official Partner" # featured_partners_blurb5: "CSforAll Official Member" # featured_partners_blurb6: "Hour of Code Activity Partner" # for_leaders_title: "For School Leaders" # for_leaders_blurb: "A Comprehensive, Standards-Aligned Computer Science Program" # for_leaders_subtitle1: "Easy Implementation" # for_leaders_subblurb1: "A web-based program that requires no IT support. Get started in under 5 minutes using Google or Clever Single Sign-On (SSO)." # for_leaders_subtitle2: "Full Coding Curriculum" # for_leaders_subblurb2: "A standards-aligned curriculum with instructional resources and professional development to enable any teacher to teach computer science." # for_leaders_subtitle3: "Flexible Use Cases" # for_leaders_subblurb3: "Whether you want to build a Middle School coding elective, a CTE pathway, or an AP Computer Science Principles class, CodeCombat is tailored to suit your needs." # for_leaders_subtitle4: "Real-World Skills" # for_leaders_subblurb4: "Students build grit and develop a growth mindset through coding challenges that prepare them for the 500K+ open computing jobs." # for_teachers_title: "For Teachers" # for_teachers_blurb: "Tools to Unlock Student Potential" # for_teachers_subtitle1: "Project-Based Learning" # for_teachers_subblurb1: "Promote creativity, problem-solving, and confidence in project-based courses where students develop their own games and webpages." # for_teachers_subtitle2: "Teacher Dashboard" # for_teachers_subblurb2: "View data on student progress, discover curriculum resources, and access real-time support to empower student learning." # for_teachers_subtitle3: "Built-in Assessments" # for_teachers_subblurb3: "Personalize instruction and ensure students understand core concepts with formative and summative assessments." # for_teachers_subtitle4: "Automatic Differentiation" # for_teachers_subblurb4: "Engage all learners in a diverse classroom with practice levels that adapt to each student's learning needs." # game_based_blurb: "CodeCombat is a game-based computer science program where students type real code and see their characters react in real time." # get_started: "Get started" # global_title: "Join Our Global Community of Learners and Educators" # global_subtitle1: "Learners" # global_subtitle2: "Lines of Code" # global_subtitle3: "Teachers" # global_subtitle4: "Countries" # go_to_my_classes: "Go to my classes" # go_to_my_courses: "Go to my courses" # quotes_quote1: "Name any program online, I’ve tried it. None of them match up to CodeCombat. Any teacher who wants their students to learn how to code... start here!" # quotes_quote2: " I was surprised about how easy and intuitive CodeCombat makes learning computer science. The scores on the AP exam were much higher than I expected and I believe CodeCombat is the reason why this was the case." # quotes_quote3: "CodeCombat has been the most beneficial for teaching my students real-life coding capabilities. My husband is a software engineer and he has tested out all of my programs. He put this as his top choice." # quotes_quote4: "The feedback … has been so positive that we are structuring a computer science class around CodeCombat. The program really engages the students with a gaming style platform that is entertaining and instructional at the same time. Keep up the good work, CodeCombat!" # see_example: "See example" slogan: "El joc més atractiu per aprendre a programar." # {change} # teach_cs1_free: "Teach CS1 Free" # teachers_love_codecombat_title: "Teachers Love CodeCombat" # teachers_love_codecombat_blurb1: "Report that their students enjoy using CodeCombat to learn how to code" # teachers_love_codecombat_blurb2: "Would recommend CodeCombat to other computer science teachers" # teachers_love_codecombat_blurb3: "Say that CodeCombat helps them support students’ problem solving abilities" # teachers_love_codecombat_subblurb: "In partnership with McREL International, a leader in research-based guidance and evaluations of educational technology." # try_the_game: "Try the game" classroom_edition: "Edició d'Aula:" learn_to_code: "Aprendre a programar:" play_now: "Juga Ara" # im_an_educator: "I'm an Educator" im_a_teacher: "<NAME>" im_a_student: "Sóc Alumna/e" learn_more: "Aprén més" classroom_in_a_box: "Una aula preparada per a l'ensenyament de la informàtica." codecombat_is: "CodeCombat és una plataforma <strong> per als estudiants </ strong> per aprendre ciències de la computació mentre es juga a través d'un veritable joc." our_courses: "Els nostres cursos han estat específicament provats <strong> de manera excel·lent a l'aula </ strong>, fins i tot per a professorat amb poca o cap experiència prèvia de programació." watch_how: "Observeu com CodeCombat està transformant la manera com la gent aprèn la informàtica." top_screenshots_hint: "Els alumnes escriuen el codi i veuen la seva actualització de canvis en temps real" designed_with: "Dissenyat pensant en el professorat" real_code: "Codi real tipificat" from_the_first_level: "des del nivell elemental" getting_students: "Acostumar l'alumnat al codi escrit amb la major rapidesa possible és fonamental per aprendre la sintaxi de programació i l'estructura adient." educator_resources: "Recursos educatius" course_guides: "i guies de curs" teaching_computer_science: "L'ensenyament de la informàtica no requereix un estudi costós, ja que proporcionem eines per donar suport als educadors de tots els àmbits." accessible_to: "Accessible a" everyone: "tothom" democratizing: "Democratitzar el procés d'aprenentatge de codificació és el nucli de la nostra filosofia. Tothom ha de poder aprendre a codificar." forgot_learning: "Crec que en realitat es van oblidar que realment estaven aprenent." wanted_to_do: " La codificació és una cosa que sempre he volgut fer, i mai vaig pensar que seria capaç d'aprendre a l'escola." builds_concepts_up: "M'agrada com CodeCombat construeix els conceptes. Realment és fàcil d'entendre i divertit de comprovar." why_games: "Per què és important aprendre mitjançant els jocs?" games_reward: "Els jocs recompensen la lluita productiva." encourage: "El joc és un mitjà que afavoreix la interacció, el descobriment i la prova i error. Un bon joc desafia el jugador a dominar les habilitats al llarg del temps, que és el mateix procés crític que passen els estudiants a mesura que aprenen." excel: "Els jocs són excel·lents en recompensar" struggle: "lluita productiva" kind_of_struggle: "el tipus de lluita que resulta en l'aprenentatge que és comprometent i" motivating: "motivador" not_tedious: "no tediós." gaming_is_good: "Els estudis confirmen que jugar és bo pel desenvolupament de la ment dels infants. (De debó!)" game_based: "Quan el sistema d'aprenenetatge basat en jocs és" compared: "comparat" conventional: "amb els mètodes d'avaluació convencionals, la diferència és clara: els jocs són millors per ajudar l'alumnat a mantenir el coneixement, concentrar-se i" perform_at_higher_level: "assolir un major rendiment" feedback: "Els jocs també proporcionen comentaris en temps real que permeten a l'alumnat ajustar la seva ruta de solució i entendre conceptes de manera més holística, en lloc de limitar-se a respostes “correctes” o “incorrectes”." real_game: "Un joc real, jugat amb la codificació real." great_game: "Un gran joc és més que simples emblemes i èxits: es tracta del viatge d'un jugador, dels trencaclosques ben dissenyats i de la capacitat per afrontar els desafiaments amb decisió i confiança." agency: "CodeCombat és un joc que dóna als jugadors aquesta decisió i confiança amb el nostre robust motor de codi mecanografiat, que ajuda tant als estudiants principiants com a estudiants avançats a escriure el codi correcte i vàlid." request_demo_title: "Comença avui mateix amb el teu alumnat!" request_demo_subtitle: "Sol·licita una demo i fes que el teu alumnat comenci en menys d'una hora." get_started_title: "Configureu la vostra classe avui mateix" get_started_subtitle: "Configureu una classe, afegiu-hi l'alumnat i seguiu el seu progrés a mesura que aprenguin informàtica." request_demo: "Sol·liciteu una demostració" # request_quote: "Request a Quote" setup_a_class: "Configureu una Classe" have_an_account: "Tens un compte?" logged_in_as: "Ja has iniciat la sessió com a" computer_science: "Els nostres cursos autoformatius cobreixen la sintaxi bàsica als conceptes avançats" ffa: "Gratuït per a tot l'alumnat" coming_soon: "Aviat, més!" courses_available_in: "Els cursos estan disponibles a JavaScript i Python. Els cursos de desenvolupament web utilitzen HTML, CSS i jQuery." boast: "Compta amb endevinalles que són prou complexas per fascinar als jugadors i als codificadors." winning: "Una combinació exitosa del joc de rol i la tasca de programació que fa que l'educació educativa sigui legítimament agradable." run_class: "Tot el que necessiteu per dirigir una classe d'informàtica a la vostra escola avui dia, no cal preparar res." goto_classes: "Ves a Les Meves Classes" view_profile: "Veure El meu Perfil" view_progress: "Veure Progrés" go_to_courses: "Vés a Els meus Cursos" want_coco: "Vols CodeCombat al teu centre?" # educator: "Educator" # student: "Student" nav: # educators: "Educators" # follow_us: "Follow Us" # general: "General" map: "Mapa" play: "Nivells" # The top nav bar entry where players choose which levels to play community: "Comunitat" courses: "Cursos" blog: "Bloc" forum: "Fòrum" account: "Compte" my_account: "El Meu Compte" profile: "Perfil" home: "Inici" contribute: "Col·laborar" legal: "Legalitat" privacy: "Privadesa" about: "Sobre Nosaltres" contact: "Contacta" twitter_follow: "Segueix-nos" my_classrooms: "Les Meves Classes" my_courses: "Els Meus Cursos" # my_teachers: "My Teachers" careers: "Professions" facebook: "Facebook" twitter: "Twitter" create_a_class: "Crear una Classe" other: "Altra" learn_to_code: "Aprendre a Programar!" toggle_nav: "Commuta la Navegació" schools: "Centres" get_involved: "Involucrar-se" open_source: "Codi Obert (GitHub)" support: "Suport" faqs: "Preguntes freqüents" copyright_prefix: "Copyright" copyright_suffix: "Tots els drets reservats." help_pref: "Necessites ajuda? Envia'ns un e-mail" help_suff: "i contactarem amb tu!" resource_hub: "Centre de Recursos" apcsp: "Principis AP CS" parent: "Pares" modal: close: "Tancar" okay: "D'acord" not_found: page_not_found: "Pàgina no trobada" diplomat_suggestion: title: "Ajuda a traduir CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Neccesitem les teves habilitats lingüístiques." pitch_body: "Hem desenvolupat CodeCombat en anglès, però tenim jugadors per tot el món. Molts d'ells volen jugar en Català, però no parlen anglès, per tant si pots parlar ambdues llengües, siusplau considereu iniciar sessió per a ser Diplomàtic i ajudar a traduir la web de CodeCombat i tots els seus nivells en Català." missing_translations: "Fins que puguem traduir-ho tot en català, ho veuràs en anglès quant no estigui en català." learn_more: "Aprèn més sobre ser un diplomàtic" subscribe_as_diplomat: "Subscriu-te com a diplomàtic" play: # title: "Play CodeCombat Levels - Learn Python, JavaScript, and HTML" # meta_description: "Learn programming with a coding game for beginners. Learn Python or JavaScript as you solve mazes, make your own games, and level up. Challenge your friends in multiplayer arena levels!" # level_title: "__level__ - Learn to Code in Python, JavaScript, HTML" # video_title: "__video__ | Video Level" # game_development_title: "__level__ | Game Development" # web_development_title: "__level__ | Web Development" # anon_signup_title_1: "CodeCombat has a" # anon_signup_title_2: "Classroom Version!" # anon_signup_enter_code: "Enter Class Code:" # anon_signup_ask_teacher: "Don't have one? Ask your teacher!" # anon_signup_create_class: "Want to create a class?" # anon_signup_setup_class: "Set up a class, add your students, and monitor progress!" # anon_signup_create_teacher: "Create free teacher account" play_as: "Jugar com" # Ladder page get_course_for_class: "Assigna el desenvolupament del joc i més a les vostres classes!" request_licenses: "Posa't en contacte amb els especialistes del centre per obtenir més informació." compete: "Competir!" # Course details page spectate: "Espectador" # Ladder page players: "<NAME>" # Hover over a level on /play hours_played: "Hores jugades" # Hover over a level on /play items: "Objectes" # Tooltip on item shop button from /play unlock: "Desbloquejar" # For purchasing items and heroes confirm: "Confirmar" owned: "Adquirit" # For items you own locked: "Bloquejat" available: "Disponible" skills_granted: "Habilitats Garantides" # Property documentation details heroes: "Herois" # Tooltip on hero shop button from /play achievements: "Triomfs" # Tooltip on achievement list button from /play settings: "Configuració" # Tooltip on settings button from /play poll: "Enquesta" # Tooltip on poll button from /play next: "Següent" # Go from choose hero to choose inventory before playing a level change_hero: "Canviar heroi" # Go back from choose inventory to choose hero change_hero_or_language: "Canviar heroi o Idioma" buy_gems: "Comprar Gemmes" subscribers_only: "Només subscriptors!" subscribe_unlock: "Subscriu-te per desbloquejar!" subscriber_heroes: "Subscriu-te avui per desbloquejar immediatament a Amara, Hushbaum i Hattori!" subscriber_gems: "Subscriu-te avui per comprar aquest heroi amb gemmes!" anonymous: "<NAME>" level_difficulty: "Dificultat: " awaiting_levels_adventurer_prefix: "Publiquem nous nivells cada setmana." awaiting_levels_adventurer: "Inicia sessió com a aventurer" awaiting_levels_adventurer_suffix: "Sigues el primer en jugar els nous nivells" adjust_volume: "Ajustar volum" campaign_multiplayer: "Arenes Multijugador" campaign_multiplayer_description: "... on programes cara a cara contra altres jugadors." brain_pop_done: "Has derrotat els ogres amb el codi! Tu guanyes!" brain_pop_challenge: "Desafíeu-vos a jugar de nou utilitzant un llenguatge de programació diferent." replay: "Repeteix" back_to_classroom: "Tornar a l'aula" teacher_button: "Per a Docents" get_more_codecombat: "Obté més CodeCombat" code: if: "si" # Keywords--these translations show up on hover, so please translate them all, even if it's kind of long. (In the code editor, they will still be in English.) else: "en cas contrari" elif: "en cas contrari, si" while: "mentre" loop: "repeteix" for: "des de" break: "trenca" continue: "continua" pass: "passar" return: "return" then: "llavors" do: "fes" end: "fi" function: "funció" def: "defineix" var: "variable" self: "si mateix" hero: "heroi" this: "això" or: "o" "||": "o" and: "i" "&&": "i" not: "no" "!": "no" "=": "assigna" "==": "igual" "===": "estrictament iguals" "!=": "no és igual" "!==": "no és estrictament igual" ">": "és més gran que" ">=": "és més gran o igual" "<": "és més petit que" "<=": "és més petit o igual" "*": "multiplicat per" "/": "dividit per" "+": "més" "-": "menys" "+=": "suma i assigna" "-=": "resta i assigna" True: "Veritat" true: "veritat" False: "Fals" false: "fals" undefined: "indefinit" null: "nul" nil: "nul" None: "Cap" share_progress_modal: blurb: "Estàs progressant molt! Digues als teus pares quant n'has après amb CodeCombat." email_invalid: "Correu electrònic invàlid." form_blurb: "Escriu els seus emails a sota i els hi ensenyarem!" form_label: "Correu electrònic" placeholder: "adreça de correu electrònic" title: "Excel·lent feina, aprenent" login: sign_up: "Crear un compte" email_or_username: "E-mail o usuari" log_in: "Iniciar Sessió" logging_in: "Iniciant Sessió" log_out: "<NAME>" forgot_password: "<PASSWORD>?" finishing: "Acabant" sign_in_with_facebook: "Inicia amb Facebook" sign_in_with_gplus: "Inicia amb G+" signup_switch: "Vols crear-te un compte?" signup: complete_subscription: "Subscripció completa" create_student_header: "Crea un compte d'estudiant" create_teacher_header: "Crea un compte de docent" create_individual_header: "Crea un compte Individual" email_announcements: "Rebre anuncis sobre nous nivells CodeCombat i les seves característiques" sign_in_to_continue: "Inicieu sessió o creeu un compte per continuar" teacher_email_announcements: "Mantén-me actualitzat sobre nous recursos docents, currículum i cursos!" creating: "Creant Compte..." sign_up: "Registrar-se" log_in: "Iniciar sessió amb la teva contrasenya" # login: "Login" required: "Neccesites iniciar sessió abans ." login_switch: "Ja tens un compte?" optional: "opcional" connected_gplus_header: "Has connectat correctament amb Google+." connected_gplus_p: "Accediu a la subscripció perquè pugueu iniciar la sessió amb el vostre compte de Google+." connected_facebook_header: "Has connectat correctament amb Facebook!" connected_facebook_p: "Finalitzeu la subscripció perquè pugueu iniciar sessió amb el vostre compte de Facebook." hey_students: "Estudiants, introduïu el codi de classe del vostre professor." birthday: "Aniversari" parent_email_blurb: "Sabem que no podeu esperar per a aprendre programació &mdash; A nosaltres també ens emociona. Els vostres pares rebran un e-mail amb més instruccions sobre com crear un compte per a vosaltres. Podeu escriure a l'e-mail ({email_link}} si teniu algun dubte." classroom_not_found: "No existeixen classes amb aquest Codi de classe. Consulteu la ortografia o demaneu ajuda al vostre professor." checking: "Comprovant..." account_exists: "Aquest e-mail ja està en ús:" sign_in: "Inicieu sessió" email_good: "El correu electrònic està bé!" name_taken: "El nom d'usuari ja està agafat! Prova amb {{suggestedName}}?" name_available: "Nom d'usuari disponible!" name_is_email: "El nom d'usuari no pot ser un e-mail" choose_type: "Tria el teu tipus de compte:" teacher_type_1: "Ensenyeu la programació amb CodeCombat!" teacher_type_2: "Configureu la vostra classe" teacher_type_3: "Accediu a guies del curs" teacher_type_4: "Mostra el progrés de l'alumnat" signup_as_teacher: "Registra't com a docent" student_type_1: "Aprèn a programar mentre fas un joc atractiu!" student_type_2: "Juga amb la teva classe" student_type_3: "Competeix en els estàdiums" student_type_4: "Tria el teu heroi!" student_type_5: "Tingues preparat el teu Codi de classe!" signup_as_student: "Registra't com a estudiant" individuals_or_parents: "Particulars i pares" individual_type: "Per als jugadors que aprenen a codificar fora d'una classe. Els pares s'han d'inscriure a un compte aquí." signup_as_individual: "Inscriviu-vos com a particular" enter_class_code: "Introduïu el codi de la vostra classe" enter_birthdate: "Introduïu la data de naixement:" parent_use_birthdate: "Pares, utilitzeu la vostra data de naixement." ask_teacher_1: "Pregunteu al vostre professor pel vostre codi de classe." ask_teacher_2: "No és part d'una classe? Crea un " ask_teacher_3: "Compte Individual" ask_teacher_4: " en el seu lloc." about_to_join: "Estàs a punt d'unir-te:" enter_parent_email: "Introduïu l'adreça electrònica del vostres pares:" parent_email_error: "S'ha produït un error al intentar enviar el correu electrònic. Comproveu l'adreça de correu electrònic i torneu-ho a provar." parent_email_sent: "Hem enviat un correu electrònic amb més instruccions sobre com crear un compte. Demaneu als vostres pares que comprovin la seva safata d'entrada." account_created: "S'ha creat el compte!" confirm_student_blurb: "Escriviu la vostra informació perquè no us oblideu. El vostre professor també us pot ajudar a restablir la vostra contrasenya en qualsevol moment." confirm_individual_blurb: "Escriviu la informació d'inici de sessió en cas que la necessiti més tard. Verifiqueu el vostre correu electrònic perquè pugueu recuperar el vostre compte si alguna vegada us oblideu de la contrasenya: consulteu la safata d'entrada!" write_this_down: "Escriviu això:" start_playing: "Comença a jugar!" sso_connected: "S'ha connectat correctament amb:" select_your_starting_hero: "Seleccioneu el vostre heroi inicial:" you_can_always_change_your_hero_later: "Sempre podeu canviar l'heroi més tard." finish: "Acaba" teacher_ready_to_create_class: "Estàs preparat per crear la teva primera classe!" teacher_students_can_start_now: "Els teus alumnes podran començar a jugar immediatament al primer curs, Introducció a la informàtica." teacher_list_create_class: "A la pantalla següent podreu crear una nova classe." teacher_list_add_students: "Afegiu estudiants a la classe fent clic a l'enllaç Visualitza la classe i, a continuació, envia als vostres estudiants el codi de la classe o l'URL. També podeu convidar-los per correu electrònic si tenen adreces de correu electrònic." teacher_list_resource_hub_1: "Consulteu les" teacher_list_resource_hub_2: "Guies del Curs" teacher_list_resource_hub_3: "per obtenir solucions a tots els nivells, i el" teacher_list_resource_hub_4: "Centre de Recursos" teacher_list_resource_hub_5: "per guies curriculars, activitats i molt més!" teacher_additional_questions: "Això és! Si necessiteu ajuda addicional o teniu preguntes, consulteu __supportEmail__." dont_use_our_email_silly: "No posis el teu correu electrònic aquí! Posa el correu electrònic dels teus pares." want_codecombat_in_school: "Vols jugar CodeCombat tot el temps?" eu_confirmation: "Estic d'acord en permetre que CodeCombat desi les meves dades als servidors dels EE.UU." eu_confirmation_place_of_processing: "Saber més sobre possibles riscos" eu_confirmation_student: "Si dubtes, consulta al teu professorat." eu_confirmation_individual: "Si no vols que desem les teves dades als servidors dels EE.UU., sempre pots continuar jugant de manera anònima sense desar el teu codi." recover: recover_account_title: "Recuperar Compte" send_password: "<PASSWORD>" recovery_sent: "Correu de recuperació de contrasenya enviat." items: primary: "Primari" secondary: "Secundari" armor: "Armadura" accessories: "Accessoris" misc: "Misc" books: "Llibres" common: # default_title: "CodeCombat - Coding games to learn Python and JavaScript" # default_meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." back: "Endarrere" # When used as an action verb, like "Navigate backward" coming_soon: "Pròximament!" continue: "Continua" # When used as an action verb, like "Continue forward" next: "Següent" default_code: "Codi per defecte" loading: "Carregant..." overview: "Resum" processing: "Processant..." solution: "Solució" table_of_contents: "Taula de Continguts" intro: "Intro" saving: "Guardant..." sending: "Enviant..." send: "Enviar" sent: "Enviat" cancel: "Cancel·lant" save: "Guardar" publish: "Publica" create: "Crear" fork: "Fork" play: "Jugar" # When used as an action verb, like "Play next level" retry: "Tornar a intentar" actions: "Accions" info: "Info" help: "Ajuda" watch: "Veure" unwatch: "Amaga" submit_patch: "Enviar pegat" submit_changes: "Puja canvis" save_changes: "Guarda canvis" required_field: "obligatori" general: and: "i" name: "Nom" date: "Data" body: "Cos" version: "Versió" pending: "Pendent" accepted: "Acceptat" rejected: "Rebutjat" withdrawn: "Retirat" accept: "Accepta" accept_and_save: "Accepta i desa" reject: "Refusa" withdraw: "Retira" submitter: "Remitent" submitted: "Presentat" commit_msg: "Enviar missatge" version_history: "Historial de versions" version_history_for: "Historial de versions per: " select_changes: "Selecciona dos canvis de sota per veure les diferències." undo_prefix: "Desfer" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Refés" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Reproduir avanç del nivell actual" result: "Resultat" results: "Resultats" description: "Descripció" or: "o" subject: "Tema" email: "Correu electrònic" password: "<PASSWORD>" confirm_password: "<PASSWORD>" message: "Missatge" code: "Codi" ladder: "Escala" when: "Quan" opponent: "Oponent" rank: "Rang" score: "Puntuació" win: "Guanyats" loss: "Perduts" tie: "Empat" easy: "Fàcil" medium: "Intermedi" hard: "Difícil" player: "<NAME>" player_level: "Nivell" # Like player level 5, not like level: Dungeons of Kithgard warrior: "Guerrer" ranger: "Explorador" wizard: "Mag" first_name: "<NAME>" last_name: "<NAME>" last_initial: "Última inicial" username: "Usuari" contact_us: "Contacta amb nosaltres" close_window: "Tanca finestra" learn_more: "Aprèn més" more: "Més" fewer: "Menys" with: "amb" units: second: "segon" seconds: "segons" sec: "sec" minute: "minut" minutes: "minuts" hour: "hora" hours: "hores" day: "dia" days: "dies" week: "setmana" weeks: "setmanes" month: "mes" months: "mesos" year: "any" years: "anys" play_level: back_to_map: "Torna al mapa" directions: "Direccions" edit_level: "Edita Nivell" keep_learning: "Segueix aprenent" explore_codecombat: "Explora CodeCombat" finished_hoc: "He acabat amb la meva Hora de Codi" get_certificate: "Aconsegueix el teu certificat!" level_complete: "Nivell complet" completed_level: "Nivell completat:" course: "Curs:" done: "Fet" next_level: "Següent nivell" combo_challenge: "Repte combinat" concept_challenge: "Repte conceptual" challenge_unlocked: "Repte desbloquejat" combo_challenge_unlocked: "Repte combinat desbloquejat" concept_challenge_unlocked: "Repte conceptual desbloquejat" concept_challenge_complete: "Repte Conceptual Complet!" combo_challenge_complete: "Repte Combinat Complet!" combo_challenge_complete_body: "Bona feina, sembla que estàs disfrutant d'entendre __concept__!" replay_level: "Repeteix Nivell" combo_concepts_used: "__complete__/__total__ conceptes emprats" combo_all_concepts_used: "Has fet servir tots els conceptes possibles per resoldre el repte. Bona feina!" combo_not_all_concepts_used: "Has emprat __complete__ dels __total__ conceptes possibles per resoldre el repte. Prova d'emprar tots __total__ conceptes la propera vegada!" start_challenge: "Començar el Repte" next_game: "Següent joc" languages: "Llenguatges" programming_language: "Llenguatge de Programació" show_menu: "Mostrar menú del joc" home: "Inici" # Not used any more, will be removed soon. level: "Nivell" # Like "Level: Dungeons of Kithgard" skip: "Ometre" game_menu: "Menú de joc" restart: "Reiniciar" goals: "Objectius" goal: "Objectiu" challenge_level_goals: "Objectius del Nivell del Repte" challenge_level_goal: "Objectiu del Nivell del Repte" concept_challenge_goals: "Objectius del Repte Conceptual" combo_challenge_goals: "Objectius del Repte Combinat" concept_challenge_goal: "Objectiu del Repte Conceptual" combo_challenge_goal: "Objectiu del Repte Combinat" running: "Executant..." success: "Èxit!" incomplete: "Incomplet" timed_out: "S'ha acabat el temps" failing: "Fallant" reload: "Recarregar" reload_title: "Recarregar tot el codi?" reload_really: "Estàs segur que vols recarregar aquest nivell des del principi?" reload_confirm: "Recarregar tot" test_level: "Test de Nivell" victory: "Victòria" victory_title_prefix: "" victory_title_suffix: " Complet" victory_sign_up: "Inicia sessió per a desar el progressos" victory_sign_up_poke: "Vols guardar el teu codi? Crea un compte gratuït!" victory_rate_the_level: "Era molt divertit aquest nivell?" victory_return_to_ladder: "Retorna a les Escales" victory_saving_progress: "Desa progrés" victory_go_home: "Tornar a l'inici" victory_review: "Explica'ns més!" victory_review_placeholder: "Com ha anat el nivell?" victory_hour_of_code_done: "Has acabat?" victory_hour_of_code_done_yes: "Sí, he acabat amb la meva Hora del Codi™!" victory_experience_gained: "XP Guanyada" victory_gems_gained: "Gemmes guanyades" victory_new_item: "Objecte nou" victory_new_hero: "Nou Heroi" victory_viking_code_school: "Ostres! Aquest nivell era un nivell difícil de superar! Si no ets un programador, ho hauries de ser. Acabes d'aconseguir una acceptació per la via ràpida a l'Escola de Programació Vikinga, on pot millorar les teves habilitats fins al següent nivell i esdevenir un programador de webs professional en 14 setmanes." victory_become_a_viking: "Converteix-te en un víking" victory_no_progress_for_teachers: "El progrés no es guarda per als professors. Però, podeu afegir un compte d'estudiant a l'aula per vosaltres mateixos." tome_cast_button_run: "Executar" tome_cast_button_running: "Executant" tome_cast_button_ran: "Executat" tome_submit_button: "Envia" tome_reload_method: "Recarrega el codi original per reiniciar el nivell" tome_available_spells: "Encanteris disponibles" tome_your_skills: "Les teves habilitats" hints: "Consells" # videos: "Videos" hints_title: "Consell {{number}}" code_saved: "Codi Guardat" skip_tutorial: "Ometre (esc)" keyboard_shortcuts: "Dreceres del teclat" loading_start: "Comença el nivell" loading_start_combo: "Començar Repte Combinat" loading_start_concept: "Començar Repte Conceptual" problem_alert_title: "Arregla el Teu Codi" time_current: "Ara:" time_total: "Màxim:" time_goto: "Ves a:" non_user_code_problem_title: "Impossible carregar el nivell" infinite_loop_title: "Detectat un bucle infinit" infinite_loop_description: "El codi inicial mai acaba d'executar-se. Probablement sigui molt lent o tingui un bucle infinit. O pot ser un error. Pots provar de tornar a executar el codi o reiniciar-lo al seu estat original. Si no es soluciona, si us plau, fes-nos-ho saber." check_dev_console: "També pots obrir la consola de desenvolupament per veure què surt malament." check_dev_console_link: "(instruccions)" infinite_loop_try_again: "Tornar a intentar" infinite_loop_reset_level: "Reiniciar nivell" infinite_loop_comment_out: "Treu els comentaris del meu codi" tip_toggle_play: "Canvia entre reproduir/pausa amb Ctrl+P" tip_scrub_shortcut: "Ctrl+[ i Ctrl+] per rebobinar i avançar ràpid" tip_guide_exists: "Clica a la guia dins el menú del joc (a la part superior de la pàgina) per informació útil." tip_open_source: "CodeCombat és 100% codi lliure!" tip_tell_friends: "Gaudint de CodeCombat? Explica'ls-ho als teus amics!" tip_beta_launch: "CodeCombat va llançar la seva beta l'octubre de 2013." tip_think_solution: "Pensa en la solució, no en el problema." tip_theory_practice: "En teoria no hi ha diferència entre la teoria i la pràctica. Però a la pràctica si que n'hi ha. - <NAME>" tip_error_free: "Només hi ha dues maneres d'escriure programes sense errors; la tercera és la única que funciona. - <NAME>" tip_debugging_program: "Si depurar és el procés per eliminar errors, llavors programar és el procés de posar-los. - <NAME>" tip_forums: "Passa pels fòrums i digues el que penses!" tip_baby_coders: "En el futur fins i tot els nadons podran ser mags." tip_morale_improves: "La càrrega continuarà fins que la moral millori." tip_all_species: "Creiem en la igualtat d'oportunitats per aprendre a programar per a totes les espècies." tip_reticulating: "Reticulant punxes." tip_harry: "Ets un bruixot, " tip_great_responsibility: "Un gran coneixement del codi comporta una gran responsabilitat per a depurar-lo." tip_munchkin: "Si no menges les teves verdures, un munchkin vindrà mentre dormis." tip_binary: "Hi ha 10 tipus de persones al món, les que saben programar en binari i les que no" tip_commitment_yoda: "Un programador ha de tenir un compromís profund, una ment seriosa. ~ Yoda" tip_no_try: "Fes-ho. O no ho facis. Però no ho intentis. - Yoda" tip_patience: "Pacient has de ser, jove Pad<NAME>. - Yoda" tip_documented_bug: "Un error documentat no és un error; és un atractiu." tip_impossible: "Sempre sembla impossible fins que es fa. - <NAME>" tip_talk_is_cheap: "Parlar és barat. Mostra'm el codi. - <NAME>" tip_first_language: "La cosa més desastrosa que aprendràs mai és el teu primer llenguatge de programació. - <NAME>" tip_hardware_problem: "P: Quants programadors són necessaris per canviar una bombeta? R: Cap, és un problema de hardware." tip_hofstadters_law: "Llei de Hofstadter: Sempre et portarà més feina del que esperaves, fins i tot tenint en compte la llei de Hofstadter." tip_premature_optimization: "La optimització prematura és l'arrel de la maldat. - <NAME>" tip_brute_force: "Quan dubtis, usa força bruta. - <NAME>" tip_extrapolation: "Hi ha dos tipus de persones: aquells que poden extrapolar des de dades incompletes..." tip_superpower: "Programar és el que més s'aproxima a un super poder." tip_control_destiny: "En un codi obert real tens el dret a controlar el teu propi destí. - <NAME>" tip_no_code: "Cap codi és més ràpid que l'absència de codi." tip_code_never_lies: "El codi mai menteix, els comentaris a vegades. — <NAME>" tip_reusable_software: "Abans que el codi sigui reutilitzable, ha de ser usable." tip_optimization_operator: "Cada llenguatge té un operador d'optimització. En la majoria d'ells és ‘//’" tip_lines_of_code: "Mesurar el progrés d'un codi per les seves línies és com mesurar el progrés d'un avió pel seu pes. — <NAME>" tip_source_code: "Vull canviar el món, però no em vol donar el seu codi font." tip_javascript_java: "Java és a JavaScript el que un cotxe a una catifa. - <NAME>" tip_move_forward: "Facis el que facis, sempre segueix endavant. - <NAME>r." tip_google: "Tens un problema que no pots resoldre? Cerca a Google!" tip_adding_evil: "Afegint una mica de maldat." tip_hate_computers: "La raó real per la qual la gent creu que odia els ordinadors és pels programadors pèssims. - <NAME>" tip_open_source_contribute: "Pots ajudar a millorar CodeCombat!" tip_recurse: "La iteració és humana, la recursivitat és divina. - <NAME>" tip_free_your_mind: "T'has de deixar endur, Neo. Por, dubtes, i incredulitat. Allibera la teva ment. - Morpheus" tip_strong_opponents: "Fins i tot el més fort dels oponents té alguna debilitat. - <NAME>" tip_paper_and_pen: "Abans de començar a programar, sempre has de començar planejant amb paper i boli." tip_solve_then_write: "Primer, resol el problema. Després, escriu el codi. - <NAME>" tip_compiler_ignores_comments: "De vegades crec que el compilador ignora els meus comentaris." tip_understand_recursion: "L'única manera d'entendre la recursió és comprendre la recursió." tip_life_and_polymorphism: "Open Source és com una estructura heterogènia totalment polimòrfica: tots els tipus són benvinguts." tip_mistakes_proof_of_trying: "Els errors del vostre codi són només una prova que esteu provant." tip_adding_orgres: "Arreglant els ogres." tip_sharpening_swords: "Afilant les espases." tip_ratatouille: "No podeu deixar que ningú defineixi els vostres límits a causa d'on prové. El vostre únic límit és la vostra ànima. - <NAME>" tip_nemo: "Quan la vida et fa baixar, vols saber què has de fer? Només has de seguir nedant, només siguir nedant. - <NAME>" tip_internet_weather: "Només has de mudar-te a Internet, es viu genial aquí. No sortim de casa on el clima és sempre increïble. - <NAME>" tip_nerds: "Als llestos se'ls permet estimar coses, com fer-petits-salts-d'emoció-a-la-cadira-sense-control. - <NAME>" tip_self_taught: "Em vaig ensenyar el 90% del que he après. I això és normal! - <NAME>" tip_luna_lovegood: "No et preocupis. Tens tan bon enteniment com jo. - <NAME>" tip_good_idea: "La millor manera de tenir una bona idea és tenir moltes idees. - <NAME>" tip_programming_not_about_computers: "La informàtica no tracta tant sobre ordinadors com l'astronomia sobre telescopis. - <NAME>" tip_mulan: "Pensa que pots, llavors ho faràs. - <NAME>" project_complete: "Projecte Complet!" share_this_project: "Comparteix aquest projecte amb amics o familiars:" ready_to_share: "Preparat per publicar el teu projecte?" click_publish: "Fes clic a \"Publicar\" per fer que aparegui a la galeria de classes i, a continuació, mira els projectes dels teus companys! Podàs tornar i continuar treballant en aquest projecte. Qualsevol altre canvi es desarà automàticament i es compartirà amb els companys." already_published_prefix: "Els teus canvis s'han publicat a la galeria de classes." already_published_suffix: "Continua experimentant i millorant aquest projecte, o mira el que la resta de la teva classe ha fet. Els teus canvis es desaran i es compartiran automàticament amb els teus companys." view_gallery: "Veure Galeria" project_published_noty: "S'ha publicat el teu nivell!" keep_editing: "Segueix editant" # learn_new_concepts: "Learn new concepts" # watch_a_video: "Watch a video on __concept_name__" # concept_unlocked: "Concept Unlocked" # use_at_least_one_concept: "Use at least one concept: " apis: methods: "Mètodes" events: "Esdeveniments" handlers: "Manipuladors" properties: "Propietats" snippets: "Fragments" spawnable: "Desmuntable" html: "HTML" math: "Mates" array: "matriu" object: "Objecte" string: "Cadena" function: "Funció" vector: "Vector" date: "Data" jquery: "jQuery" json: "JSON" number: "Número" webjavascript: "JavaScript" amazon_hoc: title: "Segueix aprenent amb Amazon!" congrats: "Felicitats per conquerir aquesta desafiant Hora de Codi!" educate_1: "Ara, continueu informant-vos sobre codificació i computació en el núvol amb AWS Educate, un programa emocionant i gratuït d'Amazon per a estudiants i professors. Amb AWS Educate, podeu guanyar insígnies interessants a mesura que apreneu els aspectes bàsics del núvol i tecnologies d'avantguarda, com ara jocs, realitat virtual i Alexa." educate_2: "Més informació i registre aquí" future_eng_1: "També podeu provar de construir les vostres habilitats pròpies de l'escola per a <NAME>" future_eng_2: "aquí" future_eng_3: "(no es requereix dispositiu). Aquesta activitat Alexa és presentada pel programa" future_eng_4: "Amazon Future Engineer" future_eng_5: "que crea oportunitats d'aprenentatge i treball per a tots els estudiants de K-12 als Estats Units que vulguin cursar informàtica." play_game_dev_level: created_by: "Creat per {{name}}" created_during_hoc: "Creat durant l'Hora del Codi" restart: "Reinicia el nivell" play: "Juga el nivell" play_more_codecombat: "Juga més CodeCombat" default_student_instructions: "Fes clic per controlar el teu heroi i guanyar el joc!" goal_survive: "Sobreviu." goal_survive_time: "Sobreviu __seconds__ segons." goal_defeat: "Derrota tots els enemics." goal_defeat_amount: "Derrota __amount__ enemics." goal_move: "Mou-te a totes les X vermelles." goal_collect: "Recull tots els ítems." goal_collect_amount: "Recull __amount__ ítems." game_menu: inventory_tab: "Inventari" save_load_tab: "Desa/Carrega" options_tab: "Opcions" guide_tab: "Gui" guide_video_tutorial: "Vídeo Tutorial" guide_tips: "Consells" multiplayer_tab: "Multijugador" auth_tab: "Dona't d'alta" inventory_caption: "Equipa el teu heroi" choose_hero_caption: "Tria l'heroi, llenguatge" options_caption: "Edita la configuració" guide_caption: "Documents i pistes" multiplayer_caption: "Juga amb amics!" auth_caption: "Desa el progrés." leaderboard: view_other_solutions: "Veure les taules de classificació" scores: "Puntuació" top_players: "Els millors jugadors de" day: "Avui" week: "Aquesta Setmana" all: "Tots els temps" latest: "Recent" time: "Temps" damage_taken: "Mal rebut" damage_dealt: "Mal inflingit" difficulty: "Dificultat" gold_collected: "Or recol·lectat" survival_time: "Sobreviscut" defeated: "Enemics derrotats" code_length: "Línies de Codi" score_display: "__scoreType__: __score__" inventory: equipped_item: "Equipat" required_purchase_title: "Necessari" available_item: "Disponible" restricted_title: "Restringit" should_equip: "(doble-clic per equipar)" equipped: "(equipat)" locked: "(bloquejat)" restricted: "(restringit en aquest nivell)" equip: "Equipa" unequip: "Desequipa" warrior_only: "Només Guerrers" ranger_only: "Només Exploradors" wizard_only: "Només Mags" buy_gems: few_gems: "Algunes gemmes" pile_gems: "Pila de gemmes" chest_gems: "Cofre de gemmes" purchasing: "Comprant..." declined: "La teva targeta ha estat rebutjada" retrying: "Error del servidor, intentant de nou." prompt_title: "Gemmes insuficients" prompt_body: "En vols més?" prompt_button: "Entrar a la botiga" recovered: "S'han recuperat les anteriors compres de gemmes. Si us plaus, recarrega al pàgina." price: "x{{gems}} / més" buy_premium: "Compra Premium" purchase: "Compra" purchased: "Comprat" subscribe_for_gems: prompt_title: "No hi ha prou gemmes!" prompt_body: "Compra Prèmium per tenir gemes i accedir fins i tot a més nivells!" earn_gems: prompt_title: "No hi ha prou gemmes" prompt_body: "Continua jugant per guanyar-ne més!" subscribe: best_deal: "Millor oferta!" confirmation: "Felicitats! Ja tens una subscripció a CodeCombat Prèmium!" premium_already_subscribed: "Ja estàs subscrit a Prèmium!" subscribe_modal_title: "CodeCombat Prèmium" comparison_blurb: "Millora les teves habilitats amb una subscripció a CodeCombat!" must_be_logged: "Necessites identificar-te. Si us plau, crea un compte o identifica't al menú de la part superior." subscribe_title: "Subscriu-te" # Actually used in subscribe buttons, too unsubscribe: "Donar-se de baixa" confirm_unsubscribe: "Confirmar la baixa" never_mind: "No et preocupis, encara t'estimo!" thank_you_months_prefix: "Gràcies pel suport donat els últims" thank_you_months_suffix: "mesos." thank_you: "Gràcies per donar suport a CodeCombat." sorry_to_see_you_go: "Llàstima que te'n vagis! Deixa'ns saber què podríem haver fet millor." unsubscribe_feedback_placeholder: "Oh, què hem fet?" stripe_description: "Subscripció mensual" buy_now: "Compra ara" subscription_required_to_play: "Necessitarás una subscripció per jugar aquest nivell." unlock_help_videos: "Subscriu-te per desbloquejar tots els vídeo-tutorials." personal_sub: "Subscripció Personal" # Accounts Subscription View below loading_info: "Carregant informació de la subscripció..." managed_by: "Gestionat per" will_be_cancelled: "Se't cancel·larà" currently_free: "Ara tens una subscripció gratuïta" currently_free_until: "Ara tens uns subscripció fins al" free_subscription: "Subscripció gratuïta" was_free_until: "Tens una subscripció gratuïta fins al" managed_subs: "Subscripcions gestionades" subscribing: "Subscrivint..." current_recipients: "Destinataris actuals" unsubscribing: "Anul·lació de subscripcions" subscribe_prepaid: "Feu clic a Subscripció per utilitzar el codi prepagat" using_prepaid: "Ús del codi prepagat per a la subscripció mensual" feature_level_access: "Accediu a més de 300 nivells disponibles" feature_heroes: "Desbloqueja herois exclusius i mascotes" feature_learn: "Aprèn a fer jocs i llocs web" month_price: "$__price__" first_month_price: "Només $__price__ pel teu primer mes!" lifetime: "Accés de per vida" lifetime_price: "$__price__" year_subscription: "Subscripció anual" year_price: "$__price__/any" support_part1: "Necessites ajuda amb el pagament o prefereixes PayPal? Envia'ns un e-mail a" support_part2: "<EMAIL>" announcement: now_available: "Ja disponible pels subscriptors!" subscriber: "subscriptor" cuddly_companions: "Companys tendres!" # Pet Announcement Modal kindling_name: "<NAME>ling Elemental" kindling_description: "Els Kindling Elementals només volen escalfar-te per la nit. I pel dia. De fet, sempre." griffin_name: "<NAME>" griffin_description: "Els Grifs són mig àguila, mig lleó, tots adorables." raven_name: "<NAME>" raven_description: "Els Corbs són excel·lentsa l'hora de recollir ampolles brillants plenes de salut per a tu." mimic_name: "<NAME>" mimic_description: "Els Mimics poden recollir monedes per a tu. Mou-los damunt les monedes per augmentar el teu subministrament d'or." cougar_name: "<NAME>" cougar_description: "Als pumes els encanta guanyar un doctorat en ronronejar feliços diàriament." fox_name: "<NAME>" fox_description: "Les Guineus blaves són molt llestes i les encanta cavar a la brutícia i a la neu!" pugicorn_name: "<NAME>" pugicorn_description: "Els Pugicorns són algunes de les criatures més rares i poden llançar encanteris!" wolf_name: "<NAME>" wolf_description: "Els Cadells Llops són excel·lents caçant, reunint-se i jugant a fet-i-amagar!" ball_name: "<NAME>" ball_description: "ball.squeak()" collect_pets: "Col·lecciona mascotes pels teus herois!" each_pet: "Cada mascota té una habilitat d'ajuda única!" upgrade_to_premium: "Esdevé un {{subscriber}} per equipar mascotes." play_second_kithmaze: "Juga a {{the_second_kithmaze}} per desbloquejar el Cadell Llop!" the_second_kithmaze: "El Se<NAME>" keep_playing: "Continua jugant per descobrir la primera mascota!" coming_soon: "Pròximament" ritic: "<NAME> el <NAME>" # Ritic Announcement Modal ritic_description: "Rític el <NAME>. Atrapat a la Glacera de <NAME> per innombrables edats, finalment lliure i llest per tendir als ogres que el van empresonar." ice_block: "Un bloc de gel" ice_description: "Sembla que hi ha alguna cosa atrapada a l'interior..." blink_name: "<NAME>" blink_description: "Rític desapareix i reapareix en un obrir i tancar els ulls, deixant res més que una ombra." shadowStep_name: "<NAME>ombres" shadowStep_description: "Un mestre assassí sap caminar entre les ombres." tornado_name: "<NAME>" tornado_description: "És bo tenir un botó de restabliment quan la coberta surt pels aires." wallOfDarkness_name: "<NAME>" wallOfDarkness_description: "Amaga't darrere una paret d'ombres per evitar la mirada d'ulls curiosos." premium_features: get_premium: "Aconsegueix<br>CodeCombat<br>Prèmium" # Fit into the banner on the /features page master_coder: "Converteix-te en un Maestre Codificador subscrivint-te avui mateix!" paypal_redirect: "Se't redirigirà a PayPal per completar el procés de subscripció." subscribe_now: "Subscriu-te Ara" hero_blurb_1: "Accediu a __premiumHeroesCount__ herois superequipats només per a subscriptors! Aprofita el poder imparable d'<NAME>, la mortal precisió de Naria de les Fulles, o convoca esquelets \"adorables\" amb <NAME>." hero_blurb_2: "Els guerrers Prèmium desbloquegen unes habilitats marcials impresionants com ara Crit de Guerra, Sofriment, i Llança Enemics. O, juga com a explorador, utilitzant sigil i arcs, llançant ganivets, i trampes! Prova la vostra habilitat com a mag codificador, i desencadena una potent matriu de Màgia Primordial, Necromàntica o Elemental!" hero_caption: "Herois nous i emocionants!" pet_blurb_1: "Les mascotes no són només companys adorables, sinó que també ofereixen funcions i mètodes únics. El Nadó Grif pot transportar unitats a través de l'aire, el Cadell Llop juga amb fletxes enemigues, al Puma li encanta perseguir els ogres del voltant, i el Mimic atreu monedes com un imant!" pet_blurb_2: "Aconsegueix totes les mascotes per descobrir les seves habilitats úniques." pet_caption: "Adopta mascotes per acompanyar al teu heroi!" game_dev_blurb: "Aprén seqüències d'ordres de jocs i construeix nivells nous per compartir amb els teus amics! Col·loca els ítems que vulguis, escriu el codi per la unitat lògica i de comportament i observa si els teus amics poden superar el nivell!" game_dev_caption: "Dissenya els teus propis jocs per desafiar als teus amics!" everything_in_premium: "Tot el que obtens en CodeCombat Prèmium:" list_gems: "Rep gemmes de bonificació per comprar equips, mascotes i herois" list_levels: "Guanya accés a __premiumLevelsCount__ nivells més" list_heroes: "Desbloqueja herois exclusius, inclosos del tipus Explorador i Mag" list_game_dev: "Fes i comparteix jocs amb els teus amics" list_web_dev: "Crea llocs web i aplicacions interactives" list_items: "Equipa amb elements exclusius Prèmium com ara mascotes" list_support: "Obté suport Prèmium per ajudar-te a depurar el codi delicat" list_clans: "Crea clans privats per convidar els teus amics i competir en una taula de classificació del grup" choose_hero: choose_hero: "Escull el teu heroi" programming_language: "Llenguatge de programació" programming_language_description: "Quin llenguatge de programació vols utilitzar?" default: "Per defecte" experimental: "Experimental" python_blurb: "Simple però poderós, Python és un bon llenguatge d'ús general." javascript_blurb: "El llenguatge de les webs." coffeescript_blurb: "Sintaxi JavaScript millorat." lua_blurb: "Llenguatge script per a jocs." java_blurb: "(Només subscriptor) Android i empresa." status: "Estat" weapons: "Armes" weapons_warrior: "Espases - Curt abast, no hi ha màgia" weapons_ranger: "Ballestes, armes - de llarg abast, no hi ha màgia" weapons_wizard: "Varetes, bastons - Llarg abast, Màgia" attack: "Dany" # Can also translate as "Attack" health: "Salut" speed: "Velocitat" regeneration: "Regeneració" range: "Abast" # As in "attack or visual range" blocks: "Bloqueja" # As in "this shield blocks this much damage" backstab: "Punyalada per l'esquena" # As in "this dagger does this much backstab damage" skills: "Habilitats" attack_1: "Danys" attack_2: "de la llista" attack_3: "dany d'armes." health_1: "Guanys" health_2: "de la llista" health_3: "salut d'armes." speed_1: "Es mou a" speed_2: "metres per segon." available_for_purchase: "Disponible per a la compra" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Nivell per desbloquejar:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see) restricted_to_certain_heroes: "Només certs herois poden jugar aquest nivell." skill_docs: function: "funció" # skill types method: "mètode" snippet: "fragment" number: "nombre" array: "matriu" object: "objecte" string: "cadena" writable: "editable" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "Només lectura" action: "Acció" spell: "Encantament" action_name: "nom" action_cooldown: "pren" action_specific_cooldown: "Refredat" action_damage: "Dany" action_range: "Abast" action_radius: "Radi" action_duration: "Duracció" example: "Exemple" ex: "ex" # Abbreviation of "example" current_value: "Valor actual" default_value: "Valor per defecte" parameters: "Paràmetres" required_parameters: "Paràmetres requerits" optional_parameters: "Paràmetres opcionals" returns: "Retorna" granted_by: "Atorgat per" save_load: granularity_saved_games: "Desats" granularity_change_history: "Historial" options: general_options: "Opcions generals" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volum" music_label: "Musica" music_description: "Activa / desactiva la música de fons." editor_config_title: "Configuració de l'editor" editor_config_livecompletion_label: "Autocompleció en directe" editor_config_livecompletion_description: "Mostra els suggeriments automàtics mentre escriviu." editor_config_invisibles_label: "Mostra invisibles" editor_config_invisibles_description: "Mostra invisibles com ara espais o tabuladors." editor_config_indentguides_label: "Mostra guies de sagnia" editor_config_indentguides_description: "Mostra línees verticals per veure i identificar millor." editor_config_behaviors_label: "Comportament intel·ligent" editor_config_behaviors_description: "Autocompleta claudàtors, correctors i cometes." about: # title: "About CodeCombat - Engaging Students, Empowering Teachers, Inspiring Creation" # meta_description: "Our mission is to level computer science through game-based learning and make coding accessible to every learner. We believe programming is magic and want learners to be empowered to to create things from pure imagination." learn_more: "Aprèn més" main_title: "Si vols aprendre a programar, has d'escriure (molt) codi." main_description: "A CodeCombat, el nostre treball és assegurar-vos que ho feu amb un somriure a la cara." mission_link: "Missió" team_link: "Equip" story_link: "Història" press_link: "Prensa" mission_title: "La nostra missió: fer que la programació sigui accessible per a tots els estudiants de la Terra." mission_description_1: "<strong>Programar és màgic</strong>. És la capacitat de crear coses des d'una imaginació pura. Vam començar CodeCombat per donar a l'alumnat la sensació d'un poder màgic al seu abast usant <strong>codi escrit</strong>." mission_description_2: "Com a conseqüència, això els permet aprendre més ràpidament. MOLT ràpidament. És com tenir una conversa en comptes de llegir un manual. Volem portar aquesta conversa a cada escola i <strong>a cada alumne</strong>, perquè tothom hauria de tenir l'oportunitat d'aprendre la màgia de la programació." team_title: "Coneix l'equip de CodeCombat" team_values: "Valorem un diàleg obert i respectuós, on guanyi la millor idea. Les nostres decisions es basen en la investigació del client i el nostre procés se centra a oferir resultats tangibles per a ells. Tothom en té cabuda, del nostre CEO als nostres col·laboradors de GitHub, perquè valorem el creixement i l'aprenentatge al nostre equip." nick_title: "C<NAME>, CEO" matt_title: "Cofundador, CTO" cat_title: "Dissenyador de jocs" scott_title: "Cofundador, Enginyer de Programari" maka_title: "Advocat de clients" robin_title: "Gerent de producció" nolan_title: "Cap de vendes" david_title: "Direcció de Comercialització" titles_csm: "Gerent d'èxit del client" titles_territory_manager: "Administrador de territori" retrostyle_title: "Il·lustració" retrostyle_blurb: "Jocs estil retro" bryukh_title: "Dissenyador de jocs" bryukh_blurb: "Constructor de trencaclosques" community_title: "...i la nostra comunitat de codi obert" community_subtitle: "Més de 500 contribuents han ajudat a construir CodeCombat, amb més unió cada setmana." community_description_3: "CodeCombat és un" community_description_link_2: "projecte comunitari" community_description_1: "amb centenars de jugadors voluntaris per crear nivells, contibuir al nostre codi per afegir característiques, arreglar errors, comprovar, i fins i tot traduir el joc a més de 50 llenguas. Els empleats, els contribuents i el lloc s'enriqueixen compartint idees i esforç de combinació, igual que la comunitat de codi obert en general. El lloc està construït amb nombrosos projectes de codi obert, i estem obert per retornar-los a la comunitat i proporcionar-li als usuaris curiosos un projecte familiar per explorar i experimentar. Qualsevol pot unir-se a la comunitat de CodeCombat! Consulta la nostra" community_description_link: "pàgina de contribució" community_description_2: "per a més informació." number_contributors: "Més de 450 col·laboradors han prestat el seu suport i el seu temps a aquest projecte." story_title: "La nostra història fins ara" story_subtitle: "Des de 2013, CodeCombat ha passat de ser un mer conjunt d'esbossos a un joc viu i pròsper." story_statistic_1a: "Més de 5,000,000" story_statistic_1b: "de jugadors en total" story_statistic_1c: "han iniciat el seu viatge vers la programació mitjançant CodeCombat" story_statistic_2a: "Hem estat treduits a més de 50 idiomes — els nostres jugadors provenen de" story_statistic_2b: "més de 190 països" story_statistic_3a: "Tots junts, han escrit" story_statistic_3b: "més d'un bilió de línies de codi" story_statistic_3c: "en molts idiomes de programació diferents" story_long_way_1: "Tot i que hem recorregut un llarg camí..." story_sketch_caption: "El primer esbós de Nick que representa un joc de programació en acció." story_long_way_2: "encara tenim molt per fer abans de completar la nostra recerca, així que..." jobs_title: "Vine a treballar amb nosaltres i ajuda'ns a escriure la història de CodeCombat!" jobs_subtitle: "No ho veus clar però t'interessa mantenir-te en contacte? Mira nostra \"Crea Tu Mateix\" llista." jobs_benefits: "Beneficis per l'empleat" jobs_benefit_4: "Vacances il·limitades" jobs_benefit_5: "Desenvolupament professional i suport a la formació contínua - llibres i jocs gratuïts!" jobs_benefit_6: "Metge (or), dental, visió, proximitat" jobs_benefit_7: "Taules amb seients per a tothom" jobs_benefit_9: "Finestra d'exercici opcional de 10 anys" jobs_benefit_10: "Permís de maternitat: paga 10 setmanes, les següents 6 al 55% de sou" jobs_benefit_11: "Permís de paternitat: paga 10 setmanes" jobs_custom_title: "Crea Tu Mateix" jobs_custom_description: "Estàs apassionat amb CodeCombat, però no veus una feina que coincideixi amb les teves qualitats? Escriu-nos i mostra'ns com creus que pots contribuir al nostre equip. Ens encantaria saber de tu!" jobs_custom_contact_1: "Envia'ns una nota a" jobs_custom_contact_2: "introduint-te i podrem contactar amb tu en el futur!" contact_title: "Premsa i Contacte" contact_subtitle: "Necessites més informació? Contacta amb nosaltres a" screenshots_title: "Captures de pantalla del joc" screenshots_hint: "(clica per veure a mida completa)" downloads_title: "Baixa Actius i Informació" about_codecombat: "Sobre CodeCombat" logo: "Logo" screenshots: "Captures de pantalla" character_art: "Art del personatge" download_all: "Baixa tot" previous: "Previ" location_title: "Ens trobem al centre de SF:" teachers: licenses_needed: "Calen llicències" special_offer: special_offer: "Oferta Especial" project_based_title: "Cursos basats en projectes" project_based_description: "Els cursos de desenvolupament web i jocs tenen projectes finals compartibles." great_for_clubs_title: "Ideal per a tallers i optatives" great_for_clubs_description: "Els professors poden comprar fins a __maxQuantityStarterLicenses__ llicències inicials." low_price_title: "Només __starterLicensePrice__ per alumne" low_price_description: "Les llicències inicials estan actives per __starterLicenseLengthMonths__ mesos a partir de la compra." three_great_courses: "Tres grans cursos inclosos a la Llicència inicial:" license_limit_description: "Els professors poden comprar fins a __maxQuantityStarterLicenses__ llicències inicials. Ja has comprat __quantityAlreadyPurchased__. Si necessites més, contacta amb __supportEmail__. Les Llicències inicials són vàlides per __starterLicenseLengthMonths__ mesos." student_starter_license: "Llicència inicial d'Estudiant" purchase_starter_licenses: "Compra les Llicències inicials" purchase_starter_licenses_to_grant: "Compra les Llicències inicials per donar accés a __starterLicenseCourseList__" starter_licenses_can_be_used: "Les Llicències inicials es poden usar per assignar cursos adicionals immediatament després de la compra." pay_now: "Paga ara" we_accept_all_major_credit_cards: "Acceptem la majoria de targetes de crèdit." cs2_description: "es basa en els fonaments de la Introducció a la informàtica, submergint-se en declaracions, funcions, esdeveniments i molt més." wd1_description: "introdueix els conceptes bàsics de l'HTML i el CSS, mentre ensenya les habilitats necessàries perquè els alumnes construeixin la seva primera pàgina web." gd1_description: "fa servir sintaxi molt familiar pels estudiants per mostrar-los com crear i compartir els seus propis jocs amb nivells." see_an_example_project: "vegeu un projecte d'exemple" get_started_today: "Comença avui mateix!" want_all_the_courses: "Vols tots els cursos? Sol·licita informació sobre les nostres llicències completes." compare_license_types: "Compara tipus de Llicències:" cs: "Ciències de la Computació" wd: "Desenvolupament web" wd1: "Desenvolupament web 1" gd: "Desenvolupament de jocs" gd1: "Desenvolupament de jocs 1" maximum_students: "Nombre màxim d'estudiants" unlimited: "Il·limitat" priority_support: "Suport prioritari" yes: "Sí" price_per_student: "__price__ per alumne" pricing: "Preus" free: "Gratuït" purchase: "Compra" courses_prefix: "Cursos" courses_suffix: "" course_prefix: "Curs" course_suffix: "" teachers_quote: subtitle: "Feu que els vostres estudiants comencin en menys d'una hora. Podràs <strong>crear una classe, afegir alumnes, i monitoritzar el seu progrés</strong> mentre aprenen informàtica." email_exists: "L'usuari existeix amb aquest correu electrònic." phone_number: "Número de telèfon" phone_number_help: "On podem trobar-te durant la jornada laboral?" primary_role_label: "El vostre rol principal" role_default: "Selecciona rol" primary_role_default: "Selecciona rol principal" purchaser_role_default: "Selecciona rol de comprador" tech_coordinator: "Coordinador de tecnologia" advisor: "Especialista / assessor de currículum" principal: "Director" superintendent: "Inspector" parent: "Pare" purchaser_role_label: "El teu rol de comprador" influence_advocate: "Influir/Optar" evaluate_recommend: "Evaluar/Recomanar" approve_funds: "Aprovació de fons" no_purchaser_role: "Cap rol en decisions de compra" district_label: "Districte" district_name: "Nom del Districte" district_na: "Poseu N/A si no és aplicable" organization_label: "Centre" school_name: "Nom de l'escola/institut" city: "Ciutat" state: "Província" country: "País" num_students_help: "Quants alumnes usaran CodeCombat?" num_students_default: "Selecciona Rang" education_level_label: "Nivell educatiu dels alumnes" education_level_help: "Trieu tants com calgui." elementary_school: "Primària" high_school: "Batxillerat/Mòduls" please_explain: "(per favor, explicar)" middle_school: "Secundària" college_plus: "Universitat o superior" referrer: "Com ens va conèixer?" referrer_help: "Per exemple: d'un altre professor, una conferència, els vostres estudiants, Code.org, etc." referrer_default: "Selecciona una" referrer_hoc: "Code.org/Hour of Code" referrer_teacher: "Un professor" referrer_admin: "Un administrador" referrer_student: "Un estudiant" referrer_pd: "Formacions / tallers professionals" referrer_web: "Google" referrer_other: "Altres" anything_else: "Amb quin tipus de classe preveus usar CodeCombat?" thanks_header: "Sol·licitud rebuda!" thanks_sub_header: "Gràcies per expressar l'interès en CodeCombat per al vostre centre." thanks_p: "Estarem en contacte aviat! Si necessiteu posar-vos en contacte, podeu contactar amb nosaltres a:" back_to_classes: "Torna a Classes" finish_signup: "Acaba de crear el vostre compte de professor:" finish_signup_p: "Creeu un compte per configurar una classe, afegir-hi els estudiants i supervisar el seu progrés a mesura que aprenen informàtica." signup_with: "Registreu-vos amb:" connect_with: "Connectar amb:" conversion_warning: "AVÍS: El teu compte actual és un <em>Compte estudiantil</em>. Un cop enviat aquest formulari, el teu compte s'actualitzarà a un compte del professor." learn_more_modal: "Els comptes de professors de CodeCombat tenen la capacitat de supervisar el progrés dels estudiants, assignar llicències i gestionar les aules. Els comptes de professors no poden formar part d'una aula: si actualment esteu inscrit en una classe amb aquest compte, ja no podreu accedir-hi una vegada que l'actualitzeu a un compte del professor." create_account: "Crear un compte de professor" create_account_subtitle: "Obteniu accés a les eines exclusives de professors per utilitzar CodeCombat a l'aula. <strong>Configura una classe</strong>, afegeix els teus alumnes, i <strong>supervisa el seu progrés</strong>!" convert_account_title: "Actualitza a compte del professor" not: "No" versions: save_version_title: "Guarda una nova versió" new_major_version: "Nova versió principal" submitting_patch: "S'està enviant el pedaç..." cla_prefix: "Per guardar els canvis primer has d'acceptar" cla_url: "CLA" cla_suffix: "." cla_agree: "Estic d'acord" owner_approve: "Un propietari ho haurà d'aprovar abans que els canvis es facin visibles." contact: contact_us: "Contacta CodeCombat" welcome: "Què bé poder escoltar-te! Fes servir aquest formulari per enviar-nos un email. " forum_prefix: "Per a qualsevol publicació, si us plau prova " forum_page: "el nostre fòrum" forum_suffix: " sinó" faq_prefix: "També pots mirar a les" faq: "Preguntes Freqüents" subscribe_prefix: "Si necessites ajuda per superar un nivell, si us plau" subscribe: "compra una subscripció de CodeCombat" subscribe_suffix: "i estarem encantats d'ajudar-te amb el teu codi." subscriber_support: "Com que seràs subscriptor de CodeCombat, el teu e-mail tindrà el nostre suport prioritari." screenshot_included: "Captura de pantalla inclosa." where_reply: "On hem de respondre?" send: "Enviar comentari" account_settings: title: "Configuració del compte" not_logged_in: "Inicia sessió o crea un compte per a canviar la configuració." me_tab: "Jo" picture_tab: "Foto" delete_account_tab: "Elimina el teu compte" wrong_email: "Correu erroni" wrong_password: "<PASSWORD>" delete_this_account: "Elimina aquest compte de forma permanent" reset_progress_tab: "Reinicia tot el progrés" reset_your_progress: "Reiniciar tot el progrés i començar de nou" god_mode: "Mode Déu" emails_tab: "Missatges" admin: "Administrador" manage_subscription: "Clica aquí per administrar la teva subscripció." new_password: "<PASSWORD>" new_password_verify: "<PASSWORD>" type_in_email: "Escriu el teu e-mail o nom d'usuari per confirmar l'eliminació del compte." type_in_email_progress: "Escriu el teu correu electrònic per confirmar l'eliminació del teu progrés." type_in_password: "<PASSWORD>." email_subscriptions: "Subscripcions via correu electrònic" email_subscriptions_none: "Sense subsrcipcions de correu electrònic." email_announcements: "Notícies" email_announcements_description: "Rebre les últimes notícies i desenvolupaments de CodeCombat." email_notifications: "Notificacions" email_notifications_summary: "Controls per personalitzar les teves notificacions d'email automàtiques relacionades amb la teva activitat a CodeCombat." email_any_notes: "Cap notificació" email_any_notes_description: "Desactiva totes les notificacions via correu electrònic." email_news: "Noticies" email_recruit_notes: "Oportunitats de feina" email_recruit_notes_description: "Si jugues realment bé ens posarem en contacte amb tu per oferir-te feina." contributor_emails: "Subscripció als correus electrònics de cada classe" contribute_prefix: "Estem buscant gent que s'uneixi! Mira " contribute_page: "la pàgina de col·laboració" contribute_suffix: " per llegir més informació." email_toggle: "Activa-ho tot" error_saving: "Error en desar" saved: "Canvis desats" password_mismatch: "Les contrasenyes no coincideixen." password_repeat: "Siusplau, repetiu la contrasenya." keyboard_shortcuts: keyboard_shortcuts: "Dreceres del teclat" space: "Espai" enter: "Enter" press_enter: "prem Enter" escape: "Escape" shift: "Majúscula" run_code: "Executa el codi actual." run_real_time: "Executa en temps real." continue_script: "Continua passant l'script actual." skip_scripts: "Omet tots els scripts que es poden ometre." toggle_playback: "Commuta play/pausa." scrub_playback: "Mou-te enradere i endavant a través del temps." single_scrub_playback: "Mou-te enradere i endavant a través del temps pas a pas." scrub_execution: "Mou-te a través de l'execució de l'encanteri actual." toggle_debug: "Canvia la visualització de depuració." toggle_grid: "Commuta la superposició de la graella." toggle_pathfinding: "Canvia la superposició d'enfocament de camí." beautify: "Embelleix el teu codi estandarditzant el format." maximize_editor: "Maximitza/minimitza l'editor de codi." community: main_title: "Comunitat CodeCombat" introduction: "Consulta les maneres en que et pots implicar i decideix quina et sembla més divertida. Esperem treballar amb tu!" level_editor_prefix: "Usa CodeCombat" level_editor_suffix: "per crear i editar nivells. Els usuaris han creat nivells per a les seves classes, amics, festes de programació, estudiants i germans. Si crear un nou nivell sona intimidant pots començar picant un dels nostres!" thang_editor_prefix: "Anomenem 'thangs' a les unitats dintre del joc. Usa" thang_editor_suffix: "per modificar el codi d'origen de CoodeCombat. Permet que unitats llancin projectils, alterin l'orientació d'una animació, canvien els punts d'èxit d'una unitat o carreguin els vostres propis sprites vectorials." article_editor_prefix: "Veus errades en alguns dels nostres documents? Vols crear algunes instruccions per a les teves pròpies creacions? Prova amb" article_editor_suffix: "i ajuda als jugadors de CodeCombat a treure el màxim profit del seu temps de joc." find_us: "Troba'ns en aquests llocs" social_github: "Consulteu tot el nostre codi a GitHub" social_blog: "Llegiu el bloc de CodeCombat al setembre" social_discource: "Uneix-te a les discussions al nostre fòrum de comentaris" social_facebook: "Fes Like a CodeCombat en Facebook" social_twitter: "Segueix CodeCombat al Twitter" social_gplus: "Uneix-te a CodeCombat en Google+" social_slack: "Xateja amb nosaltres al canal públic CodeCombat Slack" contribute_to_the_project: "Contribueix al projecte" clans: # title: "Join CodeCombat Clans - Learn to Code in Python, JavaScript, and HTML" # clan_title: "__clan__ - Join CodeCombat Clans and Learn to Code" # meta_description: "Join a Clan or build your own community of coders. Play multiplayer arena levels and level up your hero and your coding skills." clan: "Clan" clans: "Clans" new_name: "Nou nom de clan" new_description: "Nova descripció de clan" make_private: "Fes el clan privat" subs_only: "només subscriptors" create_clan: "Crear un Nou Clan" private_preview: "Vista prèvia" private_clans: "Clans privats" public_clans: "Clans públics" my_clans: "Els meus Clans" clan_name: "Nom del Clan" name: "Nom" chieftain: "Capità" edit_clan_name: "Edita el nom del Clan" edit_clan_description: "Edita la descripció del Clan" edit_name: "edita el nom" edit_description: "edita la descripció" private: "(privat)" summary: "Resum" average_level: "Nivell Mitjà" average_achievements: "Mitjana de realitzacions" delete_clan: "Esborrar Clan" leave_clan: "Abandonar Clan" join_clan: "Unir-se al Clan" invite_1: "Invitar:" invite_2: "*Invita jugadors a aquest Clan tot enviant-los aquest enllaç." members: "Membres" progress: "Progrés" not_started_1: "no iniciat" started_1: "iniciat" complete_1: "complert" exp_levels: "Amplia els nivells" rem_hero: "Elimina l'heroi" status: "Estat" complete_2: "Complert" started_2: "Iniciat" not_started_2: "No Iniciat" view_solution: "Clica per veure la solució." view_attempt: "Clica per veure l'intent." latest_achievement: "Darrera Realització" playtime: "Temps de joc" last_played: "Darrer joc" leagues_explanation: "Participa en una lliga contra d'altres membres del clan en el camp de joc multijugador." track_concepts1: "Seguiment dels conceptes" track_concepts2a: "après per cada estudiant" track_concepts2b: "après per cada membre" track_concepts3a: "Seguiment dels nivells complets per a cada estudiant" track_concepts3b: "Seguiment dels nivells complets per a cada membre" track_concepts4a: "Mira com els teus alumnes" track_concepts4b: "Mira com els teus membres" track_concepts5: "ho han resolt" track_concepts6a: "Ordena alumnes per nom o progrés" track_concepts6b: "Ordena membres per nom o progrés" track_concepts7: "Requereix invitació" track_concepts8: "per unir-se" private_require_sub: "Els Clans Privats requereixen subscripció per crear-los o unir-se'n." courses: create_new_class: "Crear una Classe Nova" # hoc_blurb1: "Try the" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity! Construct four different minigames to learn the basics of game development, then make your own!" solutions_require_licenses: "Hi ha disponibles solucions de nivell per als professors que tenen llicències." unnamed_class: "Classe sense nom" edit_settings1: "Edita la configuració de la Classe" add_students: "Afegeix Alumnes" stats: "Estadístiques" student_email_invite_blurb: "Els teus alumnes també poden utilitzar el codi de la classe <strong>__classCode__</strong> quan creen un Compte Estudiantil, no és necessari e-mail." total_students: "Alumnes totals:" average_time: "Mitjana de temps de joc:" total_time: "Temps de joc total:" average_levels: "Mitjana de nivells assolits:" total_levels: "Nivells assolits totals:" students: "Alumnes" concepts: "Conceptes" play_time: "Temps de joc:" completed: "Assolit:" enter_emails: "Separa cada adreça e-mail amb un salt de línia o amb comes" send_invites: "Invita Alumnes" number_programming_students: "Nombre d'alumnes a Programació" number_total_students: "Alumnes totals al Centre/Districte" enroll: "Inscriure's" enroll_paid: "Inscriure els alumnes en cursos de pagament" get_enrollments: "Obteniu més llicències" change_language: "Canvia el Llenguatge del Curs" keep_using: "Segueix utilitzant" switch_to: "Canvia a" greetings: "Felicitats!" back_classrooms: "Torna a Les Meves Classes" back_classroom: "Torna a Classe" back_courses: "Torna a Els Meus Cursos" edit_details: "Edita els detalls de la classe" purchase_enrollments: "Compra Llicències Estudiantils" remove_student: "esborrar alumne" assign: "Assignar" to_assign: "per assignar cursos de pagament." student: "<NAME>" teacher: "<NAME>" arena: "Camp de joc" available_levels: "Nivells disponibles" started: "iniciat" complete: "completat" practice: "pràctica" required: "requerit" welcome_to_courses: "Aventurers, benvinguts als Cursos!" ready_to_play: "Preparats per jugar?" start_new_game: "Començar un Joc Nou" play_now_learn_header: "Juga ara per aprendre" play_now_learn_1: "sintaxi bàsica per controlar el teu personatge" play_now_learn_2: "bucles 'while' per resoldre molestos trencaclosques" play_now_learn_3: "cadenes i variables per personalitzar accions" play_now_learn_4: "com vèncer a un ogre (habilitats vitals importants!)" welcome_to_page: "el meu Tauler d'alumnat" my_classes: "Classes Actuals" class_added: "Classe afegida satisfactòriament!" # view_map: "view map" # view_videos: "view videos" view_project_gallery: "veure els projectes dels meus companys" join_class: "Uneix-te a una Classe" join_class_2: "Unir-se a una classe" ask_teacher_for_code: "Demana al teu professorat si té un codi de classe CodeCombat! Si el té, posa'l a continuació:" enter_c_code: "<Posa el Codi de Classe>" join: "Unir-se" joining: "Unint-se a la classe" course_complete: "Curs Complet" play_arena: "Terreny de joc" view_project: "Veure Projecte" start: "Començar" last_level: "Darrer nivell jugat" not_you: "No ets tu?" continue_playing: "Continua Jugant" option1_header: "Invita Alumnes via e-mail" remove_student1: "Esborra Alumnes" are_you_sure: "Estàs segur que vols esborrar aquest alumne d'aquesta classe?" remove_description1: "L'alumne perdrà l'accés a aquesta aula i a les classes assignades. El seu progrés i jocs NO es perdran, i l'alumne podrà tornar a ser afegit a l'aula en qualsevol moment." remove_description2: "No es retornarà la llicència de pagament activada." license_will_revoke: "La llicència de pagament d'aquest alumne serà revocada i restarà disponible per ésser assignada a qualsevol altre alumne." keep_student: "Mantenir l'alumne" removing_user: "Esborrant l'usuari" subtitle: "Reviseu els detalls i nivells del curs" # Flat style redesign changelog: "Veure els darrers canvis als nivells del curs." select_language: "Seleccionar idioma" select_level: "Seleccionar nivell" play_level: "Jugar Nivell" concepts_covered: "Conceptes treballats" view_guide_online: "Visions i solucions de nivell" grants_lifetime_access: "Concedeix accés a tots els cursos." enrollment_credits_available: "Llicències Disponibles:" language_select: "Tria un idioma" # ClassroomSettingsModal language_cannot_change: "L'Idioma no es podrà canviar una vegada l'alumnat s'uneixi a la classe." avg_student_exp_label: "Experiència mitjana de programació de l'alumnat" avg_student_exp_desc: "Això ens ajudarà a comprendre com fer els cursos millor." avg_student_exp_select: "Selecciona la millor opció" avg_student_exp_none: "Cap experiència - molt poca experiència" avg_student_exp_beginner: "Principiant - alguna vegada o programació mitjançant blocs" avg_student_exp_intermediate: "Intermig - alguna experiència amb codi escrit" avg_student_exp_advanced: "Advançat - experiència extensa amb codi escrit" avg_student_exp_varied: "Nivells variats d'experiència" student_age_range_label: "Rang d'edat de l'alumnat" student_age_range_younger: "M<NAME> joves de 6" student_age_range_older: "M<NAME> vells de 18" student_age_range_to: "a" # estimated_class_dates_label: "Estimated Class Dates" # estimated_class_frequency_label: "Estimated Class Frequency" # classes_per_week: "classes per week" # minutes_per_class: "minutes per class" create_class: "Crear Classe" class_name: "Nom de la Classe" teacher_account_restricted: "El teu compte és de professorat i no pots accedir al contingut de l'alumnat." account_restricted: "És necessari un compte estudiantil per accedir a aquesta plana." update_account_login_title: "Inicia sessió per actualitzar el teu compte" update_account_title: "El teu compte necessita atenció!" update_account_blurb: "Abans de poder accedir a les teves classes, tria com vols utilitzar aquest compte." update_account_current_type: "Tipus de compte actual:" update_account_account_email: "E-mail del compte/nom d'usuari:" update_account_am_teacher: "Sóc docent" update_account_keep_access: "Manteniu accés a les classes que he creat" update_account_teachers_can: "Els comptes de docent poden:" update_account_teachers_can1: "Crear/manegar/afegir classes" update_account_teachers_can2: "Assignar/donar d'alta alumnat als cursos" update_account_teachers_can3: "Desbloquejar tots els nivells dels cursos per provar-los" update_account_teachers_can4: "Accedir a noves característiques només per a docents de seguida que les creem" update_account_teachers_warning: "Atenció: Se t'esborrarà de toes les classes que anteriorment t'havies afegit i ja no podràs jugar com a alumne." update_account_remain_teacher: "<NAME> com a docent" update_account_update_teacher: "Can<NAME> a docent" update_account_am_student: "Sóc alumne/a" update_account_remove_access: "Esborrar l'accés a les classes que he creat" update_account_students_can: "Els comptes d'estudiant poden:" update_account_students_can1: "Unir-se a classes" update_account_students_can2: "Jugar en els cursos com a estudiant i seguir el teu propi progrés" update_account_students_can3: "Competir contra companys als camps de joc" update_account_students_can4: "Accedir a les noves característiques només per a alumnes de seguida que els creem" update_account_students_warning: "Atenció: No podràs manegar cap classe que hagis creat previament ni crear classes noves." unsubscribe_warning: "Atenció: Seràs esborrat de la subscripció mensual." update_account_remain_student: "Continua com a Alumne" update_account_update_student: "<NAME>" need_a_class_code: "Necessitaràs un codi de Classe per la classe a la que et vols unir:" update_account_not_sure: "No saps quina triar? Envia un e-mail" update_account_confirm_update_student: "Estàs segur que vols canviar el teu compte a Alumnat?" update_account_confirm_update_student2: "No podràs manegar cap classe que hagis creat anteriorment ni crear classes noves. Les teves classes creades anteriorment s'esborraran de CodeCombat i no es podran recuperar." instructor: "Instructor: " youve_been_invited_1: "Has estat invitat a unir-te " youve_been_invited_2: ", on aprendràs " youve_been_invited_3: " amb els teus companys amb CodeCombat." by_joining_1: "Unint-se " by_joining_2: "podràs ajudar a restablir la teva contrasenya si la oblides o la perds. També podràs verificar la teva adreça e-mail i així reiniciar la contrasenya tu mateix!" sent_verification: "Hem enviat un e-mail de verificació a:" you_can_edit: "Pots editar el teu e-mail a " account_settings: "Configuració del Compte" select_your_hero: "Selecciona el teu Heroi" select_your_hero_description: "Sempre pots canviar el teu heroi anant a la plana Els Teus Cursos i fent clic a \"Canviar Heroi\"" select_this_hero: "Selecciona aquest Heroi" current_hero: "Heroi actual:" current_hero_female: "Heroïna actual:" web_dev_language_transition: "En aquest curs totes les classes programen en HTML / JavaScript. Les classes que han estat usant Python començaran amb uns nivells d'introducció extra de JavaScripts per fer la transició més fàcil. Les classes que ja usaven JavaScript ometran els nivells introductoris." course_membership_required_to_play: "T'has d'unir a un curs per jugar aquest nivell." license_required_to_play: "Demana al teu professorat que t'assigni una llicència per continuar jugant a CodeCombat!" update_old_classroom: "Nou curs escolar, nous nivells!" update_old_classroom_detail: "Per assegurar-se que estàs obtenint els nivells actualitzats, comprova haver creat una classe nova per aquest semestre clicant Crear una Classe Nova al teu" teacher_dashboard: "taulell del professorat" update_old_classroom_detail_2: "i donant a l'alumnat el nou Codi de Classe que apareixerà." view_assessments: "Veure Avaluacions" view_challenges: "veure els nivells de desafiament" challenge: "Desafiament:" challenge_level: "Nivell de Desafiament:" status: "Estat:" assessments: "Avaluacions" challenges: "Desafiaments" level_name: "Nom del nivell:" keep_trying: "Continua intentant" start_challenge: "Començar el Desafiament" locked: "Bloquejat" concepts_used: "Conceptes Usats:" show_change_log: "Mostra els canvis als nivells d'aquest curs" hide_change_log: "Amaga els canvis als nivells d'aquest curs" # concept_videos: "Concept Videos" # concept: "Concept:" # basic_syntax: "Basic Syntax" # while_loops: "While Loops" # variables: "Variables" # basic_syntax_desc: "Syntax is how we write code. Just as spelling and grammar are important in writing narratives and essays, syntax is important when writing code. Humans are good at figuring out what something means, even if it isn't exactly correct, but computers aren't that smart, and they need you to write very precisely." # while_loops_desc: "A loop is a way of repeating actions in a program. You can use them so you don't have to keep writing repetitive code, and when you don't know exactly how many times an action will need to occur to accomplish a task." # variables_desc: "Working with variables is like organizing things in shoeboxes. You give the shoebox a name, like \"School Supplies\", and then you put things inside. The exact contents of the box might change over time, but whatever's inside will always be called \"School Supplies\". In programming, variables are symbols used to store data that will change over the course of the program. Variables can hold a variety of data types, including numbers and strings." # locked_videos_desc: "Keep playing the game to unlock the __concept_name__ concept video." # unlocked_videos_desc: "Review the __concept_name__ concept video." # video_shown_before: "shown before __level__" # link_google_classroom: "Link Google Classroom" # select_your_classroom: "Select Your Classroom" # no_classrooms_found: "No classrooms found" # create_classroom_manually: "Create classroom manually" # classes: "Classes" project_gallery: no_projects_published: "Sigues el primer en publicar un projecte en aquest curs!" view_project: "Veure Projecte" edit_project: "Editar Projecte" teacher: assigning_course: "Assignant curs" back_to_top: "Tornar a l'inici" click_student_code: "Feu clic a qualsevol nivell que l'alumne hagi començat o completat a continuació per veure el codi que va escriure." code: "Codi d'en/na __name__" complete_solution: "Solució Completa" course_not_started: "L'alumnat encara no ha començat aquest curs." # appreciation_week_blurb1: "For <strong>Teacher Appreciation Week 2019</strong>, we are offering free 1-week licenses!<br />Email <NAME> (<a href=\"mailto:<EMAIL>?subject=Teacher Appreciation Week\"><EMAIL></a>) with subject line \"<strong>Teacher Appreciation Week</strong>\", and include:" # appreciation_week_blurb2: "the quantity of 1-week licenses you'd like (1 per student)" # appreciation_week_blurb3: "the email address of your CodeCombat teacher account" # appreciation_week_blurb4: "whether you'd like licenses for Week 1 (May 6-10) or Week 2 (May 13-17)" # hoc_happy_ed_week: "Happy Computer Science Education Week!" # hoc_blurb1: "Learn about the free" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity, download a new teacher lesson plan, and tell your students to log in to play!" # hoc_button_text: "View Activity" no_code_yet: "L'alumnat encara no ha escrit cap codi en aquest nivell." open_ended_level: "Nivell obert" partial_solution: "Solució Parcial" removing_course: "Esborrant curs" solution_arena_blurb: "Es recomana a l'alumnat que resolgui els nivells del camp de joc amb creativitat. La solució que es proporciona a continuació compleix els requisits del nivell del camp de joc." solution_challenge_blurb: "Es recomana a l'alumnat que resolgui els nivells de desafiament obert amb creativitat. Una possible solució es mostra a continuació." solution_project_blurb: "Es recomana a l'alumnat que construeixi un projecte creatiu en aquest nivell. La solució que es proporciona a continuació compleix els requisits del nivell del projecte." students_code_blurb: "Es proporcionarà una solució correcta per a cada nivell, quan correspongui. En alguns casos, és possible que un estudiant resolgui un nivell amb un codi diferent. No es mostren solucions per als nivells que l'alumne no ha iniciat." course_solution: "Solució del curs" level_overview_solutions: "Visió general del nivell i solucions" no_student_assigned: "No s'ha assignat cap alumnat a aquest curs." paren_new: "(nou)" student_code: "Codi d'alumnat de __name__" teacher_dashboard: "Taulell del Professorat" # Navbar my_classes: "Les Meves Classes" courses: "Guies dels Cursos" enrollments: "Llicències d'Alumnat" resources: "Recursos" help: "Ajuda" language: "Idioma" edit_class_settings: "edita la configuració de la classe" access_restricted: "Actualització del compte obligatori" teacher_account_required: "Es requereix un compte de professorat per accedir a aquest contingut." create_teacher_account: "Crear un compte de professorat" what_is_a_teacher_account: "Què és un Compte de Professorat?" teacher_account_explanation: "Un compte de professorat CodeCombat et permet configurar aules, veure el progrés de l'alumnat mentre van fent els cursos, administrar llicències i accedir a recursos per ajudar-te en la creació de currículums." current_classes: "Classes actuals" archived_classes: "Classes arxivades" archived_classes_blurb: "Les Classes es poden arxivar per referències futures. Desarxiva una classe per veure-la de nou a la llista actual de Classes." view_class: "veure classe" archive_class: "arxivar classe" unarchive_class: "desarxivar classe" unarchive_this_class: "Desarxiva aquesta classe" no_students_yet: "Aquesta classe encara no té alumnes." no_students_yet_view_class: "Veure classe per afegir alumnes." try_refreshing: "(És possible que hàgiu d'actualitzar la pàgina)" create_new_class: "Crear una Classe Nova" class_overview: "Descripció de la classe" # View Class page avg_playtime: "Mitjana de temps de joc del nivell" total_playtime: "Temps de joc total" avg_completed: "Mitjana de nivells assolits" total_completed: "Total de nivells assolits" created: "Creat" concepts_covered: "Conceptes tractats" earliest_incomplete: "Primer nivell incomplet" latest_complete: "Darrer nivell assolit" enroll_student: "Inscriure l'estudiant" apply_license: "Aplicar Llicència" revoke_license: "Revocar Llicència" revoke_licenses: "Revocar Totes les llicències" course_progress: "Progrés del curs" not_applicable: "N/A" edit: "edita" edit_2: "Edita" remove: "esborra" latest_completed: "Darrer assolit:" sort_by: "Ordena per" progress: "Progrés" concepts_used: "Conceptes emprats per Alumnat:" concept_checked: "Concepte verificat:" completed: "Assolit" practice: "Practica" started: "Iniciat" no_progress: "Cap progrés" not_required: "No requerit" view_student_code: "Fes clic per veure el codi d'alumnat" select_course: "Selecciona el curs per veure'<NAME>" progress_color_key: "Codi de colors de progrés:" level_in_progress: "Nivell en Progrés" level_not_started: "Nivell no Iniciat" project_or_arena: "Projecte o Terreny de Joc" students_not_assigned: "Alumnat que no ha estat assignat {{courseName}}" course_overview: "Descripció general del curs" copy_class_code: "Copiar Codi de Classe" class_code_blurb: "L'alumnat pot unir-se a la teva classe amb aquest Codi de Classe. No és neessari cap adreça e-mail per crear un Compte d'Estudiant amb aquest Codi de Classe." copy_class_url: "Copiar URL de la Classe" class_join_url_blurb: "També pots posar aquesta URL única d'aquesta classe en una plana web compartida." add_students_manually: "Invitar Alumnes per e-mail" bulk_assign: "Seleccionar curs" assigned_msg_1: "{{numberAssigned}} alumnes s'han assignat a {{courseName}}." assigned_msg_2: "{{numberEnrolled}} llicències s'han utilitzat." assigned_msg_3: "Ara teniu {{remainingSpots}} llicències restants disponibles." assign_course: "Assignar Curs" removed_course_msg: "{{numberRemoved}} alumnes s'han esborrat de {{courseName}}." remove_course: "Esborrar Curs" not_assigned_modal_title: "Els cursos no es van assignar" not_assigned_modal_starter_body_1: "Aquest curs requereix Llicències Inicials. No tens suficients Llicències Inicials disponibles per assignar aquest curs a tots els __selected__ alumnes seleccionats." not_assigned_modal_starter_body_2: "Compra Llicències Inicials per garantir l'accés a aquest curs." not_assigned_modal_full_body_1: "Aquest curs requereix Llicències Totals. No tens suficients Llicències Totals disponibles per assignar aquest curs a tots els __selected__ alumnes seleccionats." not_assigned_modal_full_body_2: "Només tens __numFullLicensesAvailable__ Llicències Totals disponibles (__numStudentsWithoutFullLicenses__ alumnes no tenen encara Llicències Totals actives)." not_assigned_modal_full_body_3: "Si us plau selecciona menys alumnes, o demana ajuda a __supportEmail__." assigned: "Assignats" enroll_selected_students: "Inscriviu l'alumnat seleccionat" no_students_selected: "No s'ha seleccionat cap alumne." show_students_from: "Mostrar alumnat de" # Enroll students modal apply_licenses_to_the_following_students: "Otorgar Llicències als següents Alumnes" students_have_licenses: "Els següents alumnes ja tenen llicències otorgades:" all_students: "Tots els Alumnes" apply_licenses: "Otorgar Llicències" not_enough_enrollments: "No n'hi han suficients llicències." enrollments_blurb: "Als alumnes se'ls demana tenir una llicència per accedir a qualsevol contingut després del primer curs." how_to_apply_licenses: "Com otorgar llicències" export_student_progress: "Exportar el Progrés de l'Alumnat (CSV)" send_email_to: "Envieu Recuperar contrasenya per e-mail a:" email_sent: "E-mail enviat" send_recovery_email: "Enviar e-mail de recuperació" enter_new_password_below: "Introduïu una contrasenya nova a continuació:" change_password: "<PASSWORD>" changed: "Canviada" available_credits: "Llicències disponibles" pending_credits: "Llicències pendents" empty_credits: "Llicències gastades" license_remaining: "llicència restant" licenses_remaining: "llicències restants" one_license_used: "1 llicència s'ha usat" num_licenses_used: "__numLicensesUsed__ llicències s'han usat" starter_licenses: "llicències inicials" start_date: "data d'inici:" end_date: "data d'acabament:" get_enrollments_blurb: " Us ajudarem a construir una solució que satisfaci les necessitats de la vostra classe, escola o districte." how_to_apply_licenses_blurb_1: "Quan un professor assigni un curs a un estudiant per primera vegada, aplicarem automàticament una llicència. Utilitzau el menú desplegables d'assignació massiva a la vostra aula per assignar un curs als alumnes selececionats:" how_to_apply_licenses_blurb_2: "Puc aplicar una llicència encara que no hagi assignat un curs?" how_to_apply_licenses_blurb_3: "Sí — ves a l'etiqueta Estat de les Llicències a la teva aula i fes clic a \"Aplicar Llicència\" a qualsevol alumne que no tingui una llicència activa." request_sent: "Petició enviada!" assessments: "Avaluacions" license_status: "Estat de les Llicències" status_expired: "Caducada el {{date}}" status_not_enrolled: "No inscrit" status_enrolled: "Caduca el {{date}}" select_all: "Selecciona Tot" project: "Projecte" project_gallery: "Galeria de Projectes" view_project: "Veure Projecte" unpublished: "(no publicades)" view_arena_ladder: "Veure escala del camp de joc" resource_hub: "Centre de recursos" pacing_guides: "Guies tot-en-un de l'aula" pacing_guides_desc: "Aprendre com incorporar tots els recursos de CodeCombat per planificar el teu curs escolar!" pacing_guides_elem: "Guia pas a pas d'una Escola de Primària" pacing_guides_middle: "Guia pas a pas d'una Escola de Secundària" pacing_guides_high: "Guia pas a pas d'un Centre d'Estudis Postobligatoris" getting_started: "Començant" educator_faq: "Preguntes freqüents de Docents" educator_faq_desc: "Preguntes habituals sobre l'ús de CodeCombat a la teva aula o al teu centre." teacher_getting_started: "Guia d'introducció per a docents" teacher_getting_started_desc: "Ets nou a CodeCombat? Descarrega aquesta Guia d'introducció per a docents per configurar el teu compte, crear la teva primera classe, i invitar alumnat al primer curs." student_getting_started: "Guia d'introducció per l'alumnat" student_getting_started_desc: "Pots distribuir aquesta guia al teu alumnat abans de començar amb CodeCombat per a que es puguin anar familiaritzant amb l'editor de codi. Aquesta guis serveix tant per classes de Python com de JavaScript." ap_cs_principles: "AP Principis d'informàtica" ap_cs_principles_desc: "AP Principis d'informàtica dona als estudiants una àmplia introducció al poder, l'impacte i les possibilitats de la informàtica. El curs fa èmfasi en el pensament computacional i la resolució de problemes, a més d'ensenyar els fonaments de la programació." cs1: "Introducció a la informàtica" cs2: "Informàtica 2" cs3: "Informàtica 3" cs4: "Informàtica 4" cs5: "Informàtica 5" cs1_syntax_python: "Guia de sintaxi de Python del curs 1" cs1_syntax_python_desc: "Full de trucs amb referències a la sintaxi comuna de Python que els estudiants aprendran en Introducció a la informàtica." cs1_syntax_javascript: "Guia de sintaxi de JavaScript del curs 1" cs1_syntax_javascript_desc: "Full de trucs amb referències a la sintaxi comuna de JavaScript que els estudiants aprendran en Introducció a la informàtica." coming_soon: "Guies addicionals properament!" engineering_cycle_worksheet: "Full de cicle d'enginyeria" engineering_cycle_worksheet_desc: "Utilitzeu aquest full de càlcul per ensenyar als estudiants els conceptes bàsics del cicle d'enginyeria: Avaluar, dissenyar, implementar i depurar. Consulteu el full de càlcul de l'exemple complet com a guia." engineering_cycle_worksheet_link: "Mostra l'exemple" progress_journal: "Diari de progrés" progress_journal_desc: "Anima els estudiants a fer un seguiment del progrés a través d'un diari de progrés." cs1_curriculum: "Introducció a la informàtica - Guia del currículum" cs1_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 1." arenas_curriculum: "Nivells del camp de joc - Guia dels professors" arenas_curriculum_desc: "Instruccions sobre com usar els camps de joc multijugadors Wakka Maul, Cross Bones i Power Peak amb les teves classes." # assessments_curriculum: "Assessment Levels - Teacher Guide" # assessments_curriculum_desc: "Learn how to use Challenge Levels and Combo Challenge levels to assess students' learning outcomes." cs2_curriculum: "Informàtica 2 - Guia del currículum" cs2_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 2." cs3_curriculum: "Informàtica 3 - Guia del currículum" cs3_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 3." cs4_curriculum: "Informàtica 4 - Guia del currículum" cs4_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 4." cs5_curriculum_js: "Informàtica 5 - Guia del currículum (JavaScript)" cs5_curriculum_desc_js: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 5 fent servir JavaScript." cs5_curriculum_py: "Informàtica 5 - Guia del currículum (Python)" cs5_curriculum_desc_py: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 5 fent servir Python." cs1_pairprogramming: "Activitat de programació en parelles" cs1_pairprogramming_desc: "Introduir els estudiants a un exercici de programació en parelles que els ajudarà a ser millors oients i comunicadors." gd1: "Desenvolupament del Joc 1" gd1_guide: "Desenvolupament del Joc 1 - Guia del Projecte" gd1_guide_desc: "Utilitzeu això per guiar els vostres estudiants a mesura que creen el primer projecte de joc compartit en 5 dies." gd1_rubric: "Desenvolupament del Joc 1 - Rúbrica del Project" gd1_rubric_desc: "Utilitza aquesta rúbrica per avaluar els projectes dels alumnes al final de Desenvolupament del Joc 1." gd2: "Desenvolupament del Joc 2" gd2_curriculum: "Desenvolupament del Joc 2 - Guia del Currículum" gd2_curriculum_desc: "Planificació de classes per Desenvolupament del Joc 2." gd3: "Desenvolupament del Joc 3" gd3_curriculum: "Desenvolupament del Joc 3 - Guia del Currículum" gd3_curriculum_desc: "Planificació de classes per Desenvolupament del Joc 3." wd1: "Desenvolupament Web 1" wd1_curriculum: "Desenvolupament Web 1 - Guia del Currículum" wd1_curriculum_desc: "Planificació de classes per Desenvolupament Web 1." # {change} wd1_headlines: "Activitats amb Titulars i Encapçalaments" wd1_headlines_example: "Veure un exemple de solució" wd1_headlines_desc: "Per què són importants els paràgrafs i les etiquetes de capçalera? Utilitzeu aquesta activitat per mostrar com els encapçalaments ben escollits fan que les pàgines web siguin més fàcils de llegir. Hi ha moltes solucions correctes per a això." wd1_html_syntax: "Guia de sintaxi HTML" wd1_html_syntax_desc: "Referència d'una pàgina per a l'estil HTML que els estudiants aprendran en el Desenvolupament Web 1." wd1_css_syntax: "Guia de sintaxi CSS" wd1_css_syntax_desc: "Referència d'una pàgina per a la sintaxi CSS i Style que els estudiants aprendran en el Desenvolupament Web 1." wd2: "Desenvolupament Web 2" wd2_jquery_syntax: "Guia de sintaxi de funcions jQuery" wd2_jquery_syntax_desc: "Referència d'una pàgina per a les funcions jQuery que els estudiants aprendran en el Desenvolupament Web 2." wd2_quizlet_worksheet: "Full de càlcul de planificació del Qüestionari" wd2_quizlet_worksheet_instructions: "Veure instruccions i exemples" wd2_quizlet_worksheet_desc: "Abans que els vostres estudiants construeixin el seu projecte de qüestionació de personalitat al final del Desenvolupament web 2, haurien de planificar les preguntes, els resultats i les respostes del qüestionari utilitzant aquest full de càlcul. Els professors poden distribuir les instruccions i els exemples als quals es refereixen els estudiants." student_overview: "Resum" student_details: "Detalls dels alumnes" student_name: "<NAME>" no_name: "No es proporciona cap nom." no_username: "No s'ha proporcionat cap nom d'usuari." no_email: "L'estudiant no té una adreça electrònica configurada." student_profile: "Perfil de l'estudiant" playtime_detail: "Detall del temps de joc" student_completed: "Estudiants completats" student_in_progress: "Estudiant en curs" class_average: "Mitjana de classe" not_assigned: "No s'ha assignat els cursos següents" playtime_axis: "Temps de joc en segons" levels_axis: "Nivells en" student_state: "Com està " student_state_2: " fent?" student_good: "ho està fent bé a" student_good_detail: "Aquest alumne manté el ritme de la classe." student_warn: "podria necessitar ajuda en" student_warn_detail: "Aquest estudiant pot necessitar ajuda amb els nous conceptes que s'han introduït en aquest curs." student_great: "ho està fent molt bé a" student_great_detail: "Aquest estudiant pot ser un bon candidat per ajudar altres estudiants que iintentin fer aquest curs." full_license: "Llicència Total" starter_license: "Llicència Inicial" trial: "Prova" hoc_welcome: "Feliç setmana de l'aprenentatge d'Informàtica" # hoc_title: "Hour of Code Games - Free Activities to Learn Real Coding Languages" # hoc_meta_description: "Make your own game or code your way out of a dungeon! CodeCombat has four different Hour of Code activities and over 60 levels to learn code, play, and create." hoc_intro: "Hi ha tres maneres per a que la vostra classe participi en Hora del Codi amb CodeCombat" hoc_self_led: "Joc d'autoaprenentatge" hoc_self_led_desc: "Els alumnes poden accedir a dues hores de tutorials de CodeCombat per compte propi" hoc_game_dev: "Desenvolupament de Jocs" hoc_and: "i" hoc_programming: "Programació en JavaScript/Python" hoc_teacher_led: "Lliçons magistrals" hoc_teacher_led_desc1: "Baixa't la nostra" hoc_teacher_led_link: "planificació de lliçons sobre Introducció a la Informàtica" hoc_teacher_led_desc2: "per introduir els vostres estudiants en conceptes de programació utilitzant activitats fora de línia" hoc_group: "Joc Grupal" hoc_group_desc_1: "Els professors poden utilitzar les lliçons juntament amb el nostre curs de Introducció a la informàtica per fer un seguiment del progrés dels estudiants. Mira la nostra" hoc_group_link: "Guia d'introducció" hoc_group_desc_2: "per més detalls" hoc_additional_desc1: "Per a recursos i activitats addicionals de CodeCombat, minar les nostres" hoc_additional_desc2: "Preguntes" hoc_additional_contact: "Posar-se en contacte" revoke_confirm: "Estàs segur que vols revocar una llicència total de {{student_name}}? La llicència restarà disponible per assignar-la a un altre estudiant." revoke_all_confirm: "Estàs segur que vols revocar les llicències totals de tots els estudiants d'aquesta classe?" revoking: "Revocant..." unused_licenses: "Teniu llicències no utilitzades que us permeten assignar cursos pagats pels estudiants quan estiguin preparats per obtenir més informació!" remember_new_courses: "Recorda assignar nous cursos!" more_info: "Més informació" how_to_assign_courses: "Com assignar cursos" select_students: "Seleccionar Alumnes" select_instructions: "Feu clic a la casella de verificació al costat de cada alumne al qual voleu assignar els cursos." choose_course: "Tria Curs" choose_instructions: "Seleccioneu el curs des del menú desplegable que vulgueu assignar, i després feu clic a “Assigna als Alumnes Seleccionats.”" push_projects: "Es recomana assignar Desenvolupament web 1 o Desenvolupament de jocs 1 després que els alumnes hagin acabat la Introducció a la informàtica! Veure el nostre {{resource_hub}} per més detalls sobre aquests cursos." teacher_quest: "Missió del Docent per tenir èxit" quests_complete: "Missió Complerta" teacher_quest_create_classroom: "Crear un aula" teacher_quest_add_students: "Afegir l'alumnat" teacher_quest_teach_methods: "Ajudar el teu alumnat a aprendre com `cridar mètodes`." teacher_quest_teach_methods_step1: "Tenir el 75% com a mínim d'una classe amb el primer nivell passat, __Dungeons of Kithgard__" teacher_quest_teach_methods_step2: "Imprimir la [Guia d'introducció per l'alumnat](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) del Centre de Recursos." teacher_quest_teach_strings: "No encadenar els teus alumnes junts, ensenya'ls `cadenes`." teacher_quest_teach_strings_step1: "Tenir el 75% com a mínim d'una classe amb __True Names__ passat" teacher_quest_teach_strings_step2: "Usar el Selector de Nivells del Professorat a la plana [Guies del Curs](/teachers/courses) per tenir una vista prèvia de __True Names__." teacher_quest_teach_loops: "Mantenir els alumnes en el bucle sobre els `bucles`." teacher_quest_teach_loops_step1: "Tenir el 75% com a mínim d'una classe amb __Fire Dancing__ passat." teacher_quest_teach_loops_step2: "Usar el __Loops Activity__ en la [CS1 Guia del Currículum](/teachers/resources/cs1) per reforçar aquest concepte." teacher_quest_teach_variables: "Variar-los amb les `variables`." teacher_quest_teach_variables_step1: "Tenir el 75% com a mínim d'una classe amb __Known Enemy__ passat." teacher_quest_teach_variables_step2: "Fomentar la col·laboració utilitzant l'[Activitat de Programació per parelles](/teachers/resources/pair-programming)." teacher_quest_kithgard_gates_100: "Escapar de les portes de Kithgard amb la teva classe." teacher_quest_kithgard_gates_100_step1: "Tenir el 75% com a mínim d'una classe amb __Kithgard Gates__ passat." teacher_quest_kithgard_gates_100_step2: "Guiar l'alumnat per pensar en problemes difícils usant el [Full de cicle d'enginyeria](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)." teacher_quest_wakka_maul_100: "Preparar pel duel a Wakka Maul." teacher_quest_wakka_maul_100_step1: "Tenir el 75% com a mínim d'una classe amb __Wakka Maul__ passat." teacher_quest_wakka_maul_100_step2: "Veure la [Guia del Camp de Joc](/teachers/resources/arenas) al [Centre de Recursos](/teachers/resources) per trobar idees sobre com fer un joc de camp amb èxit." teacher_quest_reach_gamedev: "Explora nous móns!" teacher_quest_reach_gamedev_step1: "[Aconsegueix llicències](/teachers/licenses) per a que els teus alumnes puguin explorar nous móns, com ara Desenvolupament de jocs i Desenvolupament de Webs!" teacher_quest_done: "Encara volen aprendre més codi els teus alumnes? Posa't en contacte avui mateix amb els nostres [especialistes escolars](mailto:<EMAIL>)!" teacher_quest_keep_going: "Segueix endavant! A continuació t'indiquem què pots fer:" teacher_quest_more: "Veure totes les missions" teacher_quest_less: "Veure menys missions" refresh_to_update: "(actualitzeu la pàgina per veure les actualitzacions)" view_project_gallery: "Mostra la Galeria de Projectes" office_hours: "Seminari de Professorat" office_hours_detail: "Apreneu a mantenir-se al dia amb els vostres estudiants a mesura que creen jocs i s'embarquen en el seu viatge de codificació! Assisteix a les nostres" office_hours_link: "sessions de Seminari de Professorat" office_hours_detail_2: "." success: "Èxit" in_progress: "En Progrés" not_started: "No Iniciat" mid_course: "Mig Curs" end_course: "Fi del Curs" none: "Cap detectat encara" explain_open_ended: "Nota: Es recomana als estudiants que resolguin aquest nivell de forma creativa, a continuació es proporciona una possible solució." level_label: "Nivell:" time_played_label: "Temps jugat:" back_to_resource_hub: "Tornar al Centre de Recursos" back_to_course_guides: "Tornar a les Guies del Curs" print_guide: "Imprimir aquesta guia" combo: "Combinat" combo_explanation: "Els estudiants passen els nivells de desafiament combinat utilitzant com a mínim un concepte enumerat. Reviseu el codi de l'alumne fent clic al punt de progrés." concept: "Concepte" # sync_google_classroom: "Sync Google Classroom" share_licenses: share_licenses: "Compartir llicències" shared_by: "Compartida amb:" add_teacher_label: "Introduïu el correu electrònic del professorat exacte:" add_teacher_button: "Afegir professorat" subheader: "Podeu fer que les vostres llicències estiguin disponibles per a altres professors de la vostra organització. Cada llicència només es pot utilitzar per a un estudiant a la vegada." teacher_not_found: "No s'ha trobat el professor. Assegureu-vos que aquest professor ja ha creat un compte de professor." teacher_not_valid: "Aquest no és un compte de professor vàlid. Només els comptes de professors poden compartir llicències." already_shared: "Ja heu compartit aquestes llicències amb aquest professor." teachers_using_these: "Professors que poden accedir a aquestes llicències:" footer: "Quan els professors revocuen llicències dels estudiants, les llicències es retornaran al grup compartit d'altres professors d'aquest grup per utilitzar-les." you: "(tu)" one_license_used: "(1 llicència utilitzada)" licenses_used: "(__licensesUsed__ llicències utilitzades)" more_info: "Més informació" sharing: game: "Joc" webpage: "Plana Web" your_students_preview: "Els vostres alumnes faran clic aquí per veure els projectes acabats! No disponible a la previsualització del professor." unavailable: "L'intercanvi d'enllaços no està disponible a la previsualització del professor." share_game: "Comparteix aquest joc" share_web: "Comparteix aquesta Plana Web" victory_share_prefix: "Comparteix aquest enllaç per convidar els teus amics i família a" victory_share_prefix_short: "Convida gent a" victory_share_game: "jugar al teu joc" victory_share_web: "veure la teva plana web" victory_share_suffix: "." victory_course_share_prefix: "Aquest enllaç permetrà als teus amics i família" victory_course_share_game: "jugar al joc" victory_course_share_web: "veure la plana web" victory_course_share_suffix: "que acabes de crear." copy_url: "Copiar URL" share_with_teacher_email: "Enviar al teu professor/a" game_dev: creator: "Creador" web_dev: image_gallery_title: "Galeria d'imatges" select_an_image: "Selecciona la imatge que vulguis utilitzar" scroll_down_for_more_images: "(Desplaceu-vos cap avall per obtenir més imatges)" copy_the_url: "Copieu l'URL següent" copy_the_url_description: "Útil si voleu reemplaçar una imatge existent." copy_the_img_tag: "Copieu l'etiqueta <img>" copy_the_img_tag_description: "Útil si voleu inserir una imatge nova." copy_url: "Copiar URL" copy_img: "Copiar <img>" how_to_copy_paste: "Com Copiar/Pegar" copy: "Copiar" paste: "Pegar" back_to_editing: "Tornar a Editar" classes: archmage_title: "Arximag" archmage_title_description: "(Programador)" archmage_summary: "Si ets un programador interessat en els jocs educatius sigues un arximag i ajuda'ns a construir CodeCombat!" artisan_title: "Artesà" artisan_title_description: "(Creador de nivells)" artisan_summary: "Construeix i comparteix nivells per als teus amics. Sigues un Artesà per aprendre l'art d'ensenyar als altres a programar." adventurer_title: "Aventurer" adventurer_title_description: "(Provador de nivells)" adventurer_summary: "Accedeix als nostres nivells (fins i tot el contingut de pagament) una setmana abans i gratuïtament i ajuda'ns a descobrir errors abans que siguin públics." scribe_title: "Escriba" scribe_title_description: "(Editor d'articles)" scribe_summary: "Un bon codi necessita una bona documentació. Escriu, edita i millora els documents que són llegits per milions de jugadors arreu del món." diplomat_title: "Diplomàtic" diplomat_title_description: "(Traductor)" diplomat_summary: "CodeCombat s'està traduint a més de 45 idiomes pels nostres Displomàtics. Ajuda'ns a traduir!" ambassador_title: "Ambaixador" ambassador_title_description: "(Suport)" ambassador_summary: "Posar ordre als fòrums i respondre a les preguntes que sorgeixin. Els nostres Ambaixadors representen a CodeCombat envers el món." teacher_title: "<NAME>" editor: main_title: "Editors de CodeCombat" article_title: "Editor d'articles " thang_title: "Editor de Thang" level_title: "Editor de nivells" course_title: "Editor de Cursos" achievement_title: "Editor de triomfs" poll_title: "Editor d'Enquestes" back: "Enrere" revert: "Reverteix" revert_models: "Reverteix Models" pick_a_terrain: "Tria un Terreny" dungeon: "Masmorra" indoor: "Interior" desert: "Desert" grassy: "Herba" mountain: "Muntanya" glacier: "Glaciar" small: "Petit" large: "Gran" fork_title: "Nova versió Bifurcació" fork_creating: "Creant bifurcació..." generate_terrain: "Generar Terreny" more: "Més" wiki: "Wiki" live_chat: "Xat en directe" thang_main: "Principal" thang_spritesheets: "Capes" thang_colors: "Colors" level_some_options: "Algunes opcions?" level_tab_thangs: "Thangs" level_tab_scripts: "Escripts" level_tab_components: "Components" level_tab_systems: "Sistemes" level_tab_docs: "Documentació" level_tab_thangs_title: "Thangs actuals" level_tab_thangs_all: "Tot" level_tab_thangs_conditions: "Condicions Inicials" level_tab_thangs_add: "Afegeix Thangs" level_tab_thangs_search: "Cerca thangs" add_components: "Afegir Components" component_configs: "Configuracions de Components" config_thang: "Fes doble clic per configurar un thang" delete: "Esborrar" duplicate: "Duplicar" stop_duplicate: "Atura el duplicat" rotate: "Rotar" level_component_tab_title: "Components actuals" level_component_btn_new: "Crear Nou Component" level_systems_tab_title: "Sistemes actuals" level_systems_btn_new: "Crea un nou sistema" level_systems_btn_add: "Afegir sistema" level_components_title: "Torna a Tots els Thangs" level_components_type: "Escriu" level_component_edit_title: "Edita Component" level_component_config_schema: "Esquema de configuració" level_system_edit_title: "Editar sistema" create_system_title: "Crea un nou sistema" new_component_title: "Crea un nou Component" new_component_field_system: "Sistema" new_article_title: "Crea un article nou" new_thang_title: "Crea un nou tipus de Thang" new_level_title: "Crea un nou nivell" new_article_title_login: "Inicia sessió per a crear un article nou" new_thang_title_login: "Inicia la sessió per crear un nou tipus de Thang" new_level_title_login: "Inicia sessió per a crear un nou nivell" new_achievement_title: "Crea un nou triomf" new_achievement_title_login: "Inicia sessió per a crear un nou triomf" new_poll_title: "Crea una nova enquesta" new_poll_title_login: "Inicia sessió per a crear una nova enquesta" article_search_title: "Cerca Articles aquí" thang_search_title: "Cerca tipus de Thang aquí" level_search_title: "Cerca nivells aquí" achievement_search_title: "Cerca assoliments" poll_search_title: "Cerca enquestes" read_only_warning2: "Nota: no podeu desar edicions aquí, perquè no heu iniciat la sessió." no_achievements: "Encara no s'ha afegit cap assoliment per aquest nivell." achievement_query_misc: "L'assoliment clau fora de miscel·lània" achievement_query_goals: "L'assoliment clau no té objectius de nivell" level_completion: "Compleció de nivell" pop_i18n: "Omple I18N" tasks: "Tasques" clear_storage: "Esborreu els canvis locals" add_system_title: "Afegiu sistemes al nivell" done_adding: "Afegits fets" article: edit_btn_preview: "Vista prèvia" edit_article_title: "Editar l'article" polls: priority: "Prioritat" contribute: page_title: "Contribueix" intro_blurb: "CodeCombat és 100% codi obert! Una gran quantitat de jugadors ens han ajudat a construir el joc tal com és avui. Uneix-te a l'aventura d'ensenyar a programar!" alert_account_message_intro: "Hola!" alert_account_message: "Per subscriure't a alguna classe, necessites estar identificat." archmage_introduction: "Una de les millors parts de construir jocs és que aglutinen coses molt diverses. Gràfics, sons, treball en temps real, xarxes socials, i per suposat la programació, des del baix nivell d'ús de bases de dades i administració del servidor fins a dissenyar i crear interfícies. Hi ha molt a fer, i si ets un programador amb experiència i amb l'anhel de submergir-te dins CodeCombat aquesta classe és per tu. Ens encantarà tenir la teva ajuda en el millor joc de programació que hi ha." class_attributes: "Atributs de la classe" archmage_attribute_1_pref: "Coneixement en " archmage_attribute_1_suf: ", o ganes d'aprendre'n. La major part del nostre codi és en aquest llenguatge. Si ets un fan de Ruby o Python et sentiràs com a casa. És JavaScript però més agradable." archmage_attribute_2: "Certa experiència programant i iniciativa personal. T'orientarem, però no podem dedicar molt de temps en ensenyar-te." how_to_join: "Com unir-se" join_desc_1: "Qualsevol pot ajudar! Visita el nostre " join_desc_2: "per començar i i marca la casella d'abaix per registra-te com a Arximag i estar al dia del correus electrònics que enviem. Vols saber què fer o que t'expliquem més a fons en què consisteix? " join_desc_3: ", o troba'ns al nostre " join_desc_4: "i t'ho explicarem!" join_url_email: "Escriu-nos" join_url_slack: "Canal de Contractació pública" archmage_subscribe_desc: "Rebre els correus sobre noves oportunitats de programació." artisan_introduction_pref: "Hem de construir nous nivells! La gent reclama més continguts i les nostres forces són limitades. Ara mateix el nostre lloc de treball és de nivell 1; el nostre editor de nivells és tot just útil per als seus creadors, així que ves en compte. Si tens algunes idees sobre campanyes amb bucles for per " artisan_introduction_suf: ", llavors aquesta classe és per a tu." artisan_attribute_1: "Experiència en construcció de continguts d'aquest estil seria genial, com per exemple l'editor de nivells de Blizzard. Però no és un requisit!" artisan_attribute_2: "Ganes de fer moltes proves i iteracions. Per fer bons nivells necessitaràs mostrar-ho a altres i veure com juguen i estar preparat per a reparar tot el que calgui." artisan_attribute_3: "De moment, la resistència va de la mà de l'Aventurer. El nostre editor de nivells es troba en una fase molt preliminar i pot ser un poc frustrant. Estàs avisat!" artisan_join_desc: "Utilitza l'editor de nivells a través d'aquests passos:" artisan_join_step1: "Llegeix la documentació." artisan_join_step2: "Crea un nivell nou i explora els ja creats." artisan_join_step3: "Troba'ns al nostre canal públic d'Slack per a més ajuda." artisan_join_step4: "Anuncia els teus nivells al fòrum per a més opinions." artisan_subscribe_desc: "Rebre els correus electrònics per seguir les novetats." adventurer_introduction: "Anem a tenir clar el vostre paper: sou el tanc. Vas a patir grans danys. Necessitem que les persones puguin provar nous nivells i ajudar a identificar com millorar les coses. El dolor serà enorme; fer bons jocs és un procés llarg i ningú ho fa bé la primera vegada. Si pateix i té una puntuació alta de constitució, aquesta classe pot ser per a vostè." adventurer_attribute_1: "Un set d'aprenentatge. Tu vols aprendre a codificar i nosaltres volem ensenyar-te com codificar. Probablement estaràs fent la majoria dels aprenentatges en aquesta classe." adventurer_attribute_2: "Carismàtic. Sigues amable però escriu sobre el que necessites millorar i ofereix suggeriments sobre com millorar-los." adventurer_join_pref: "Alineeu-vos amb (o recluta) un Artesà i treballeu amb ells, o marqueu la casella següent per rebre correus electrònics quan hi hagi nous nivells per provar. També publicarem sobre els nivells per revisar a les nostres xarxes, com ara" adventurer_forum_url: "el nostre fòrum" adventurer_join_suf: "per tant, si prefereixes que t'ho notifiquem així, inscriu-te aquí!" adventurer_subscribe_desc: "Rep correus electrònics quan hi hagi nous nivells per provar." scribe_introduction_pref: "CodeCombat no només vol ser un munt de nivells. També inclourà un recurs per al coneixement, una wiki de conceptes de programació que els nivells poden connectar. D'aquesta manera, en lloc que cada Artesà hagi d'descriure amb detall el que és un operador de comparació, simplement pot enllaçar el seu nivell amb l'article que els descriu que ja està escrit per a l'edificació del jugador. Al llarg de la línia del que el" scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: "ha construit. Si la vostra idea de diversió és articular els conceptes de programació en forma de marca, aquesta classe pot ser per a vosaltres." scribe_attribute_1: "L'habilitat en paraules és pràcticament tot el que necessiteu. No només la gramàtica i l'ortografia, sinó que poden transmetre idees complicades als altres." contact_us_url: "Contacta amb nosaltres" scribe_join_description: "Explica'ns una mica sobre tu mateix, la teva experiència amb la programació i sobre quin tipus de coses t'agradaria escriure. Començarem per això!" scribe_subscribe_desc: "Rep correus electrònics sobre anuncis d'escriptura d'articles." diplomat_introduction_pref: "Si alguna cosa vam aprendre del que vam " diplomat_launch_url: "llançar a l'octubre" diplomat_introduction_suf: "és que hi ha un gran interès en CodeCombat a altres països! Estem construint un cos de traductors per aconseguir que CodeCombat sigui tan accessible arreu del món com sigui possible. Si t'agrada aconseguir els nivells tan aviat com surten i poder-los oferir als teus compatriotes llavors aquesta classe és per tu." diplomat_attribute_1: "Fluïdesa en l'anglès i en l'idioma al que vulguis traduir. Al transmetre idees complicades és important tenir un gran coneixement dels dos idiomes!" diplomat_i18n_page_prefix: "Pots començar traduint els nostres nivells a la" diplomat_i18n_page: "pàgina de traduccions" diplomat_i18n_page_suffix: ", o bé la interfície web a GitHub." diplomat_join_pref_github: "Troba els nostres fitxers d'idiomes " diplomat_github_url: "a GitHub" diplomat_join_suf_github: ", edita'ls i envia una petició de modificació. A més, marca la casella d'abaix per mantenir-te informat d'esdeveniments de traducció!" diplomat_subscribe_desc: "Rebre correus sobre el desenvolupament de i18n i la traducció de nivells." ambassador_introduction: "Aquesta és una comunitat que estem construint, i tu ets les connexions. Tenim fòrums, correus electrònics i xarxes socials amb molta gent per parlar i ajudar-vos a conèixer el joc i aprendre-ne. Si voleu ajudar a la gent a participar-hi i divertir-se i tenir una bona idea del pols de CodeCombat i on anem, aquesta classe pot ser per a vosaltres." ambassador_attribute_1: "Habilitats comunicatives. Ser capaç d'identificar els problemes que tenen els jugadors i ajudar-los a resoldre'ls. A més, manten-nos informats sobre el que diuen els jugadors, el que els agrada i no els agrada i sobre què més volen!" ambassador_join_desc: "explica'ns una mica sobre tu mateix, què has fet i què t'interessaria fer. Començarem per això!" ambassador_join_note_strong: "Nota" ambassador_join_note_desc: "Una de les nostres principals prioritats és crear multijugador on els jugadors que tinguin dificultats per resoldre els nivells poden convocar assistents de nivell superior per ajudar-los. Serà una bona manera de fer la tasca d'Ambaixador. T'anirem informant!" ambassador_subscribe_desc: "Obteniu correus electrònics sobre actualitzacions de suport i desenvolupaments multijugador." teacher_subscribe_desc: "Obteniu correus electrònics sobre actualitzacions i anuncis per a professors." changes_auto_save: "Els canvis es desen automàticament quan canvieu les caselles de selecció." diligent_scribes: "Els Nostres Escribes Diligents:" powerful_archmages: "Els Nostres Arximags Poderosos:" creative_artisans: "Els Nostres Artesans Creatius:" brave_adventurers: "Els Nostres Aventurers Valents:" translating_diplomats: "Els Nostres Diplomàtics Traductors:" helpful_ambassadors: "Els Nostres Ambaixadors Útils:" ladder: # title: "Multiplayer Arenas" # arena_title: "__arena__ | Multiplayer Arenas" my_matches: "Les meves partides" simulate: "Simula" simulation_explanation: "Al simular jocs, pots aconseguir que el teu joc sigui més ràpid!" simulation_explanation_leagues: "Us ajudarà principalment a simular jocs per als jugadors aliats dels vostres clans i cursos." simulate_games: "Simula Jocs!" games_simulated_by: "Jocs que has simulat:" games_simulated_for: "Jocs simulats per a tu:" games_in_queue: "Jocs actualment a la cua:" games_simulated: "Partides simulades" games_played: "Partides guanyades" ratio: "Ràtio" leaderboard: "Taulell de Classificació" battle_as: "Batalla com " summary_your: "Les teves " summary_matches: "Partides - " summary_wins: " Victòries, " summary_losses: " Derrotes" rank_no_code: "No hi ha cap codi nou per classificar" rank_my_game: "Classifica el meu Joc!" rank_submitting: "Enviant..." rank_submitted: "Enviat per Classificar" rank_failed: "No s'ha pogut classificar" rank_being_ranked: "El Joc s'està Classificant" rank_last_submitted: "enviat " help_simulate: "T'ajudem a simular jocs?" code_being_simulated: "El teu nou codi està sent simulat per altres jugadors per al rànquing. Això s'actualitzarà a mesura que entrin noves coincidències." no_ranked_matches_pre: "No hi ha partides classificades per a l'equip " no_ranked_matches_post: " ! Juga contra alguns competidors i torna aquí per aconseguir que el teu joc sigui classificat." choose_opponent: "Escull adversari" select_your_language: "Escull el teu idioma!" tutorial_play: "Juga el tutorial" tutorial_recommended: "Recomenat si no has jugat abans" tutorial_skip: "Salta el tutorial" tutorial_not_sure: "No estàs segur de què està passant?" tutorial_play_first: "Juga el tutorial primer." simple_ai: "Simple CPU" warmup: "Escalfament" friends_playing: "Amics jugant" log_in_for_friends: "Inicia sessió per jugar amb els teus amics!" social_connect_blurb: "Connecta't i juga contra els teus amics!" invite_friends_to_battle: "Invita els teus amics a unir-se a la batalla!" fight: "Lluita!" watch_victory: "Mira la teva victòria" defeat_the: "Derrota a" watch_battle: "Observa la batalla" tournament_started: ", iniciada" tournament_ends: "El torneig acaba" tournament_ended: "El torneig ha acabat" tournament_rules: "Normes del torneig" tournament_blurb: "Escriu codi, recull or, construeix exèrcits, enderroca enemics, guanya premis i millora el teu rànquing al nostre torneig Greed de $ 40,000! Consulteu els detalls" tournament_blurb_criss_cross: "Obté ofertes, construeix camins, reparteix opositors, agafa gemmes i actualitza el teu rànquing al nostre torneig Criss-Cross! Consulteu els detalls" tournament_blurb_zero_sum: "Allibera la teva creativitat de codificació tant en la trobada d'or i en les tàctiques de batalla en aquest joc de miralls alpins entre el bruixot i el bruixot blau. El torneig va començar el divendres 27 de març i tindrà lloc fins el dilluns 6 d'abril a les 5PM PDT. Competeix per diversió i glòria! Consulteu els detalls" tournament_blurb_ace_of_coders: "Treu-lo a la glacera congelada en aquest joc de mirall d'estil dominació! El torneig va començar el dimecres 16 de setembre i es disputarà fins el dimecres 14 d'octubre a les 5PM PDT. Consulteu els detalls" tournament_blurb_blog: "en el nostre blog" rules: "Normes" winners: "<NAME>" league: "Lliga" red_ai: "CPU vermella" # "Red AI Wins", at end of multiplayer match playback blue_ai: "CPU blava" wins: "Guanya" # At end of multiplayer match playback humans: "Vermell" # Ladder page display team name ogres: "Blau" user: # user_title: "__name__ - Learn to Code with CodeCombat" stats: "Estadístiques" singleplayer_title: "<NAME> d'un sol jugador" multiplayer_title: "<NAME>s multijugador" achievements_title: "Triomfs" last_played: "Ultim jugat" status: "Estat" status_completed: "Complet" status_unfinished: "Inacabat" no_singleplayer: "Encara no s'han jugat nivells individuals." no_multiplayer: "Encara no s'han jugat nivells multijugador." no_achievements: "No has aconseguit cap triomf encara." favorite_prefix: "L'idioma preferit és " favorite_postfix: "." not_member_of_clans: "Encara no ets membre de cap clan" certificate_view: "veure certificat" certificate_click_to_view: "fes clic per veure el certificat" certificate_course_incomplete: "curs incomplet" certificate_of_completion: "Certificat de Finalització" certificate_endorsed_by: "Aprovat per" certificate_stats: "Estadístiques del curs" certificate_lines_of: "línies de" certificate_levels_completed: "nivells completats" certificate_for: "Per" # certificate_number: "No." achievements: last_earned: "Últim aconseguit" amount_achieved: "Cantitat" achievement: "Triomf" current_xp_prefix: "" current_xp_postfix: " en total" new_xp_prefix: "" new_xp_postfix: " guanyat" left_xp_prefix: "" left_xp_infix: " fins el nivell " left_xp_postfix: "" account: # title: "Account" # settings_title: "Account Settings" # unsubscribe_title: "Unsubscribe" # payments_title: "Payments" # subscription_title: "Subscription" # invoices_title: "Invoices" # prepaids_title: "Prepaids" payments: "Pagaments" prepaid_codes: "Codis prepagats" purchased: "Comprat" subscribe_for_gems: "Subscriure's per gemmes" subscription: "Subscripció" invoices: "Factures" service_apple: "Apple" service_web: "Web" paid_on: "Pagat a" service: "Servei" price: "Preu" gems: "Gemmess" active: "Actiu" subscribed: "Subscrit" unsubscribed: "No s'ha subscrit" active_until: "Actiu fins a" cost: "Cost" next_payment: "Següent pagament" card: "Targeta" status_unsubscribed_active: "No esteu subscrit i no se us facturarà, però el vostre compte encara està actiu per ara." status_unsubscribed: "Accediu a nous nivells, herois, ítems i gemmes de bonificació amb una subscripció a CodeCombat!" not_yet_verified: "Encara no s'ha verificat." resend_email: "Reenvia l'e-mail" email_sent: "E-mail enviat! Comprova la teva safata d'entrada." verifying_email: "Verificant la teva adreça e-mail..." successfully_verified: "Has verificat correctament la teva adreça e-mail!" verify_error: "S'ha produït un error en verificar el teu e-mail :(" unsubscribe_from_marketing: "Abandonar la subscripció a __email__ de tots els e-mails de màrqueting de CodeCombat?" unsubscribe_button: "Sí, abandonar la subscripció" unsubscribe_failed: "Errada" unsubscribe_success: "Èxit" account_invoices: amount: "Quantitat en dòlars nord-americans" declined: "S'ha denegat la targeta" invalid_amount: "Si us plau, introduïu un import en dòlars nord-americans." not_logged_in: "Inicieu sessió o creeu un compte per accedir a les factures." pay: "Factures de Pagament" purchasing: "Comprant..." retrying: "Error del Servidor, reintentant." success: "S'ha pagat correctament. Gràcies!" account_prepaid: purchase_code: "Compreu un codi de subscripció" purchase_code1: "Es poden bescanviar els codis de subscripció per afegir el temps de subscripció premium a un o més comptes de la versió Home de CodeCombat." purchase_code2: "Cada compte de CodeCombat només pot bescanviar un codi de subscripció en particular una vegada." purchase_code3: "Els mesos del codi de subscripció s'afegiran al final de qualsevol subscripció existent al compte." purchase_code4: "Els codis de subscripció són per als comptes que reprodueixen la versió inicial de CodeCombat, no es poden utilitzar en lloc de les llicències d'estudiants per a la versió de Classroom." purchase_code5: "Per obtenir més informació sobre les llicències d'estudiants, consulteu-les a" users: "Usuaris" months: "Mesos" purchase_total: "Total" purchase_button: "Enviar compra" your_codes: "Els teus Codis" redeem_codes: "Canvia un codi de subscripció" prepaid_code: "Codi Prepagat" lookup_code: "Cerca el Codi Prepagat" apply_account: "Aplicar al teu compte" copy_link: "Podeu copiar l'enllaç del codi i enviar-lo a algú." quantity: "Quantitat" redeemed: "Canviats" no_codes: "Encara no hi ha cap codi!" you_can1: "Pots" you_can2: "comprar un codi Prepagat" you_can3: "per aplicar al teu compte o donar a d'altres." loading_error: could_not_load: "Error de carrega del servidor" connection_failure: "Connexió fallida." connection_failure_desc: "Sembla que no estàs connectat a internet! Comprova la teva connexió a la xarxa i després recarrega aquesta plana." login_required: "Es requereix iniciar sessió" login_required_desc: "Necessites iniciar sessió per accedir a aquesta plana." unauthorized: "Has d'iniciar la sessió. Tens les galetes desactivades?" forbidden: "No disposes dels permisos." forbidden_desc: "Oh no, aquí no et podem mostrar res! Comprova que has iniciat sessió amb el compte correcte, o visita un dels enllaços següents per tornar a programar!" not_found: "No trobat." not_found_desc: "Hm, aquí no hi ha res. Visita un dels enllaços següents per tornar a programar!" not_allowed: "Metode no permès." timeout: "Temps d'espera del servidor superat" conflict: "Conflicte de recursos." bad_input: "Entrada incorrecta." server_error: "Error del servidor." unknown: "Error Desconegut" error: "ERROR" general_desc: "Alguna cosa ha anat malament, i és probable que sigui culpa nostra. Mira d'esperar una mica i després recarrega la plana, o visita un dels enllaços següents per tornar a programar!" resources: level: "Nivell" patch: "Pedaç" patches: "Pedaços" system: "Sistema" systems: "Sistemes" component: "Component" components: "Components" hero: "Heroi" campaigns: "Campanyes" concepts: advanced_css_rules: "Regles CSS avançades" advanced_css_selectors: "Selectors CSS avançats" advanced_html_attributes: "Atributs HTML avançats" advanced_html_tags: "Etiquetes HTML avançades" algorithm_average: "Algorisme mitjà" algorithm_find_minmax: "Algorisme Trobar Mínim/Màxim" algorithm_search_binary: "Algorisme Cerca Binària" algorithm_search_graph: "Algorisme Cerca Gràfica" algorithm_sort: "Algorisme Tipus" algorithm_sum: "Algorisme Suma" arguments: "Arguments" arithmetic: "Aritmètica" array_2d: "Cadenes 2D" array_index: "Indexació de Cadenes" array_iterating: "Iteració en Cadenes" array_literals: "Cadenes Literals" array_searching: "Cerca en Cadenes" array_sorting: "Classificació en Cadenes" arrays: "Cadenes" basic_css_rules: "Regles bàsiques CSS" basic_css_selectors: "Selectors bàsics CSS" basic_html_attributes: "Atributs bàsics HTML" basic_html_tags: "Etiquetes bàsiques HTML" basic_syntax: "Sintaxis bàsica" binary: "Binari" boolean_and: "I Booleana" boolean_inequality: "Desigualtat Booleana" boolean_equality: "Igualtat Booleana" boolean_greater_less: "Major/Menor Booleans" boolean_logic_shortcircuit: "Circuits lògics Booleans" boolean_not: "Negació Booleana" boolean_operator_precedence: "Ordre d'operadors Booleans" boolean_or: "O Booleana" boolean_with_xycoordinates: "Comparació coordinada" bootstrap: "Programa d'arranque" break_statements: "Declaracions Break" classes: "Classes" continue_statements: "Sentències Continue" dom_events: "Events DOM" dynamic_styling: "Estilisme dinàmic" # events: "Events" event_concurrency: "Concurrència d'events" event_data: "Data d'event" event_handlers: "Controlador d'Events" event_spawn: "Event generador" for_loops: "Bucles (For)" for_loops_nested: "Anidació amb bucles" for_loops_range: "Pel rang de bucles" functions: "Funcions" functions_parameters: "Paràmetres" functions_multiple_parameters: "Paràmetres múltiples" game_ai: "Joc AI" game_goals: "Objectius del Joc" game_spawn: "Generador del Joc" graphics: "Gràfics" graphs: "Gràfics" heaps: "Munts" if_condition: "Sentències Condicionals 'If'" if_else_if: "Sentències 'If/Else If'" if_else_statements: "Sentències 'If/Else'" if_statements: "Sentències If" if_statements_nested: "Sentències If anidades" indexing: "Indexació en Matrius" input_handling_flags: "Manipulació d'entrades - Banderes" input_handling_keyboard: "Manipulació d'entrades - Teclat" input_handling_mouse: "Manipulació d'entrades - Ratolí" intermediate_css_rules: "Regles intermàdies de CSS" intermediate_css_selectors: "Selector intermedis CSS" intermediate_html_attributes: "Atributs intermedis HTML" intermediate_html_tags: "Etiquetes intermèdies HTML" jquery: "jQuery" jquery_animations: "Animacions jQuery" jquery_filtering: "Filtratge d'elements jQuery" jquery_selectors: "Selectors jQuery" length: "longitud de la matriu" math_coordinates: "Coordinar Matemàtiques" math_geometry: "Geometria" math_operations: "Operacions matemàtiques" math_proportions: "Proporcions matemàtiques" math_trigonometry: "Trigonometria" object_literals: "Objectes Literals" parameters: "Paràmetres" # programs: "Programs" # properties: "Properties" property_access: "Accés a Propietats" property_assignment: "Assignar Propietats" property_coordinate: "Coordinar Propietat" queues: "Estructures de dades - Cues" reading_docs: "Llegint els Documents" recursion: "Recursivitat" return_statements: "Sentències de retorn" stacks: "Estructures de dades - Piles" strings: "Cadenes" strings_concatenation: "Concatenació de cadenes" strings_substrings: "Subcadenes" trees: "Estructures de dades - Arbres" variables: "Variables" vectors: "Vectors" while_condition_loops: "Bucles 'While' amb condicionals" while_loops_simple: "Bucles 'While'" while_loops_nested: "Bucles 'While' anidats" xy_coordinates: "Coordenades Cartesianes" advanced_strings: "Cadenes de text avançades (string)" # Rest of concepts are deprecated algorithms: "Algorismes" boolean_logic: "Lògica booleana" basic_html: "HTML Bàsic" basic_css: "CSS Bàsic" basic_web_scripting: "Escriptura Web bàsica" intermediate_html: "HTML intermig" intermediate_css: "CSS intermig" intermediate_web_scripting: "Escriptura Web intermitja" advanced_html: "HTML avançat" advanced_css: "CSS avançat" advanced_web_scripting: "Escriptura Web avançada" input_handling: "Manipulació de dades d'entrada" while_loops: "Bucles 'While'" place_game_objects: "Situar objectes del joc" construct_mazes: "Construir laberints" create_playable_game: "Crear un projecte de joc que es pugui jugar i compartir" alter_existing_web_pages: "Modificar planes web existents" create_sharable_web_page: "Crear una plana web compartible" basic_input_handling: "Manipulació d'entrada bàsica" basic_game_ai: "Joc bàsic d'AI" basic_javascript: "JavaScript bàsic" basic_event_handling: "Manipulació d'Events bàsica" create_sharable_interactive_web_page: "Crear una plana web compartible interactiva" anonymous_teacher: notify_teacher: "Notificar Prof<NAME>" create_teacher_account: "Crear un compte de professorat gràtis" enter_student_name: "El teu nom:" enter_teacher_email: "El teu e-mail de professor:" teacher_email_placeholder: "<EMAIL>" student_name_placeholder: "Escriu aquí el teu nom" teachers_section: "Docents:" students_section: "Alumnat:" teacher_notified: "Hem notificat al vostre professor que voleu jugar més a CodeCombat en classe." delta: added: "Afegit" modified: "Modificat" not_modified: "No modificat" deleted: "Eliminat" moved_index: "Índex desplaçat" text_diff: "Diferir text" merge_conflict_with: "Conflicte d'unió amb" no_changes: "Sense canvis" legal: page_title: "Legalitat" # opensource_introduction: "CodeCombat is part of the open source community." opensource_description_prefix: "Comprova " github_url: "el nostre GitHub" opensource_description_center: "i ajuda'ns si vols! CodeCombat està construit amb dotzenes de projectes de codi obert, i ens encanta. Mira " archmage_wiki_url: "la nostra wiki d'ArxiMags" opensource_description_suffix: "per observar la llista de software que fa possible aquest joc." practices_title: "Bones Pràctiques Respectuoses" practices_description: "Aquesta és la promesa que et fem, jugador, d'una manera no tant legal." privacy_title: "Privacitat" privacy_description: "No vendrem cap informació personal teva." security_title: "Seguretat" security_description: "Ens esforcem per mantenir segura la vostra informació personal. Com a projecte de codi obert, el nostre lloc està lliurement obert a tothom per revisar i millorar els nostres sistemes de seguretat." email_title: "E-mail" email_description_prefix: "No us inundarem amb correu brossa. Mitjançant" email_settings_url: "la teva configuració d'e-mail" email_description_suffix: "o mitjançant els enllaços als e-mails que t'enviem, pots canviar les teves preferències i donar-te de baixa fàcilment en qualsevol moment." cost_title: "Cost" cost_description: "CodeCombat és gratuït per a tots els nivells bàsics, amb una subscripció de ${{price}} USD al mes per accedir a branques de nivells extra i {{gems}} bonus de gemmes al mes. Pots cancel·lar-ho amb un clic i oferim una garantia de devolució del 100%." copyrights_title: "Copyrights i Llicències" contributor_title: "Acord de Llicència de Col·laborador (CLA)" contributor_description_prefix: "Tots els col·laboradors, tant del lloc com del repositori GitHub, estan subjets al nostre" cla_url: "CLA" contributor_description_suffix: "que has d'acceptar abans de fer contribucions." code_title: "Codi - MIT" # client_code_description_prefix: "All client-side code for codecombat.com in the public GitHub repository and in the codecombat.com database, is licensed under the" mit_license_url: "llicència MIT" code_description_suffix: "Això inclou tot el codi a Sistemes i Components que s'han fet possibles per CodeCombat amb el proposit de crear nivells." art_title: "Art/Música - Creative Commons " art_description_prefix: "Tot el contingut comú està disponible sota" cc_license_url: "llicència Creative Commons Attribution 4.0 International" art_description_suffix: "El contingut comú és generalment disponible per CodeCombat amb la finalitat de crear nivells. Inclou:" art_music: "Musica" art_sound: "So" art_artwork: "Art" art_sprites: "Capes" art_other: "Tots i cadascun dels treballs creatius que no siguin de codi que estiguin disponibles quan es creïn Nivells." art_access: "Actualment, no hi ha cap sistema universal i fàcil d'obtenir aquests actius. En general, obtingueu-les des dels URL que utilitzeu el lloc, contacteu-nos per obtenir assistència o ens ajudeu a ampliar el lloc per fer-los accessibles amb més facilitat." art_paragraph_1: "Per a l'atribució, si us plau, cita i vincle a codecombat.com a prop d'on s'utilitza la font o, si escau, per al mitjà. Per exemple:" use_list_1: "Si s'utilitza en una pel·lícula o en un altre joc, incloeu codecombat.com en els crèdits." use_list_2: "Si s'utilitza en un lloc web, incloeu un enllaç prop de l'ús, per exemple, sota una imatge o en una pàgina d'atribucions generals on també podeu esmentar altres obres de Creative Commons i programari de codi obert que s'utilitza al lloc. Alguna cosa que ja fa referència clarament a CodeCombat, com ara una publicació de bloc que menciona CodeCombat, no necessita cap atribució per separat." art_paragraph_2: "Si el contingut que s'utilitza no és creat per CodeCombat sinó per un usuari de codecombat.com, atribueix-lo a ell, i seguiu les indicacions d'atribució proporcionades en la descripció del recurs si hi ha alguna." rights_title: "Drets reservats" rights_desc: "Tots els drets estan reservats per als mateixos Nivells. Això inclou" rights_scripts: "Scripts" rights_unit: "Configuració de la unitat" rights_writings: "Escrits" rights_media: "Mitjans de comunicació (sons, música) i qualsevol altre contingut creatiu fet específicament per a aquest nivell i generalment no està disponible quan es creen nivells." rights_clarification: "Per aclarir, qualsevol cosa que estigui disponible a l'Editor de Nivells amb la finalitat de fer nivells està sota CC, mentre que el contingut creat amb l'Editor de Nivells o carregat en el curs de creació de Nivells no ho és." nutshell_title: "En poques paraules" nutshell_description: "Els recursos que oferim a l'Editor de Nivells es poden utilitzar de la manera que vulgueu per crear nivells. Però ens reservem el dret de restringir la distribució dels mateixos Nivells (que es creen a codecombat.com) perquè es puguin cobrar." nutshell_see_also: "Veure també:" canonical: "La versió en anglès d'aquest document és la versió definitiva i canònica. Si hi ha discrepàncies entre les traduccions, el document anglès té prioritat." third_party_title: "Serveis de tercers" third_party_description: "CodeCombat usa els següents serveis de tercers (entre d'altres):" cookies_message: "CodeCombat utilitza unes quantes galetes essencials i no essencials." cookies_deny: "Declareu les galetes no essencials" ladder_prizes: title: "Premis del torneig" # This section was for an old tournament and doesn't need new translations now. blurb_1: "Aquests premis seran guanyats d'acord amb" blurb_2: "Les normes del torneig" blurb_3: "els millors jugadors humans i ogres." blurb_4: "Dos equips signifiquen el doble de premis!" blurb_5: "(Hi haura dos guanyadors pel primer lloc, dos pels del segon lloc, etc.)" rank: "Rang" prizes: "Premis" total_value: "Valor total" in_cash: "en diners" custom_wizard: "Personalitza el teu bruixot de CodeCombat" custom_avatar: "Personalitza el teu avatar de CodeCombat" heap: "per sis mesos d'acces \"Startup\" " credits: "crèdits" one_month_coupon: "cupó: trieu Rails o HTML" one_month_discount: "descompte del 30%: seleccioneu Rails o HTML" license: "llicencia" oreilly: "ebook de la vostra elecció" calendar: year: "Any" day: "Dia" month: "Mes" january: "Gener" february: "Febrer" march: "Març" april: "Abril" may: "Maig" june: "Juny" july: "Juliol" august: "Agost" september: "Setembre" october: "Octubre" november: "Novembre" december: "Desembre" code_play_create_account_modal: title: "Ho has fet!" # This section is only needed in US, UK, Mexico, India, and Germany body: "Ara estàs en camí d'esdevenir un mestre codificador. Registra't per rebre un extra de <strong>100 Gemmes</strong> i també se't donarà l'oportunitat de <strong>guanyar $2,500 i altres premis de Lenovo</strong>." sign_up: "Retistra't i continua codificant ▶" victory_sign_up_poke: "Crea un compte gratuït per desar el codi i ingressa per obtenir premis." victory_sign_up: "Inscriu-te i accedeix a poder <strong>gunayar $2,500</strong>" server_error: email_taken: "E-mail ja agafat" username_taken: "Usuari ja agafat" esper: line_no: "Línia $1: " uncaught: "Irreconeixible $1" # $1 will be an error type, eg "Uncaught SyntaxError" reference_error: "Error de Referència: " argument_error: "Error d'Argument: " type_error: "Error d'Escriptura: " syntax_error: "Error de Sintaxi: " error: "Error: " x_not_a_function: "$1 no és una funció" x_not_defined: "$1 no s'ha definit" spelling_issues: "Revisa l'ortografia: volies dir `$1` en lloc de `$2`?" capitalization_issues: "Revisa les majúscules: `$1` hauria de ser `$2`." py_empty_block: "$1 buit. Posa 4 espais abans de la declaració dintre de la declaració $2." fx_missing_paren: "Si vols cridar `$1` com a funció, necessites posar `()`" unmatched_token: "`$1` sense parella. Cada `$2` obert necessita un `$3` tancat per emparellar-se." unterminated_string: "Cadena sense finalitzar. Afegeix una `\"` a joc al final de la teva cadena." missing_semicolon: "Punt i coma oblidat." missing_quotes: "Cometes oblidades. Prova `$1`" argument_type: "L'argument de `$1`, `$2`, hauria de tenir tipus `$3`, però té `$4`: `$5`." argument_type2: "L'argument de `$1`', `$2`, hauria de tenir tipus `$3`, però té `$4`." target_a_unit: "Invoca una unitat." attack_capitalization: "Attack $1, no $2. (Les majúscules són importants.)" empty_while: "Ordre 'while' buida. Posa 4 espais al davant de les següents ordres que pertanyin a while." line_of_site: "L'argument de `$1`, `$2`, té un problema. Ja tens cap enemic a la teva línia d'acció?" need_a_after_while: "Necessites `$1` després de `$2`." too_much_indentation: "Massa sagnat a l'inici d'aquesta línia." missing_hero: "Falta paraula clau a `$1`; hauria de ser `$2`." takes_no_arguments: "`$1` no pren cap argument." no_one_named: "No n'hi ha cap anomenat \"$1\" a qui adreçar-se." separated_by_comma: "Els paràmetres que crida la funció han d'anar separats mitjançant `,`" protected_property: "No puc llegir la propietat protegida: $1" need_parens_to_call: "Si vols cridar `$1` com a funció, necessites posar `()`" expected_an_identifier: "S'esperava un identificador i en canvi vam veure '$1'." unexpected_identifier: "Identificador inesperat" unexpected_end_of: "Final d'entrada inesperat" unnecessary_semicolon: "Punt i coma innecessari." unexpected_token_expected: "Simbol inesperat: esperavem $1 però hem trobat $2 mentre analitzavem $3" unexpected_token: "Simbol $1 inesperat" unexpected_token2: "Simbol inesperat" unexpected_number: "Número inesperat" unexpected: "'$1' inesperat." escape_pressed_code: "En picar Escape; s'aborta el codi." target_an_enemy: "Invoca un enemic pel nom, com ara `$1`, no amb la cadena `$2`." target_an_enemy_2: "Invoca un enemic pel nom, com ara $1." cannot_read_property: "No puc llegir bé '$1' o indefinit" attempted_to_assign: "S'ha intentat assignar a la propietat que és només de lectura." unexpected_early_end: "Final prematur de programa inesperat." you_need_a_string: "Necessites una cadena per construir; una de $1" unable_to_get_property: "Impossible adquirir la propietat '$1' d'una referència indefinida o nula" # TODO: Do we translate undefined/null? code_never_finished_its: "El codi mai finalitza. Realment va lent o té un bucle infinit." unclosed_string: "Cadena sense tancar." unmatched: "'$1' sense emparellar." error_you_said_achoo: "Has dit: $1, però la contrasenya és: $2. (Les majúscules són importants.)" indentation_error_unindent_does: "Error de sagnat: el sagnat no coincideix amb cap altre nivell de sagnat" indentation_error: "Error de sagnat." need_a_on_the: "Necessites posar `:` al final de la línia que segueix a `$1`." attempt_to_call_undefined: "intentes anomenar '$1' (un valor nul)" unterminated: "`$1` sense acabar" target_an_enemy_variable: "Invoca la variable $1, no la cadena $2. (Prova a usar $3.)" error_use_the_variable: "Usa el nom de la variable com ara `$1` enlloc de la cadena com ara `$2`" indentation_unindent_does_not: "Sagnat indegut que no concorda amb cap altre nivell" unclosed_paren_in_function_arguments: "Sense tancar $1 en els arguments de la funció." unexpected_end_of_input: "Final d'entrada inesperat" there_is_no_enemy: "No hi ha cap `$1`. Usa `$2` primer." # Hints start here try_herofindnearestenemy: "Prova amb `$1`" there_is_no_function: "No hi ha cap funció `$1`, però `$2` té un mètode `$3`." attacks_argument_enemy_has: "L'argument de `$1`, `$2`, té un problema." is_there_an_enemy: "Ja n'hi ha algun enemic dintre de la teva línia de visió?" target_is_null_is: "Has invocat $1. Sempre hi ha un invocat per atacar? (Usa $2?)" hero_has_no_method: "`$1` no té mètode `$2`." there_is_a_problem: "Hi ha un problema amb el teu codi." did_you_mean: "Volies dir $1? No tens cap ítem equipat amb aquesta habilitat." missing_a_quotation_mark: "T'has oblidat posar una cometa. " missing_var_use_var: "T'has oblidat `$1`. Usa `$2` per crear una nova variable." you_do_not_have: "No tens cap ítem equipat amb l'habilitat $1." put_each_command_on: "Posa cada comand en una línia diferent" are_you_missing_a: "T'estàs oblidant de '$1' després de '$2'? " your_parentheses_must_match: "Els teus parèntesis han de coincidir." apcsp: # title: "AP Computer Science Principals | College Board Endorsed" # meta_description: "CodeCombat’s comprehensive curriculum and professional development program are all you need to offer College Board’s newest computer science course to your students." syllabus: "Pla d'Estudis de Fonaments de Programació" syllabus_description: "Utilitza aquest recurs per planificar el currículum de CodeCombat pel teu Pla d'Estudis de Fonaments de Programació de la teva classe." computational_thinking_practices: "Pràctiques de Pensament Computacional" learning_objectives: "Objectius d'Aprenentatge" curricular_requirements: "Requeriments Curriculars" unit_1: "Unitat 1: Tecnologia Creativa" unit_1_activity_1: "Unitat 1 Activitat: Revisió de la usabilitat tecnològica" unit_2: "Unitat 2: Pensament Computacional" unit_2_activity_1: "Unitat 2 Activitat: Seqüències Binaries" unit_2_activity_2: "Unitat 2 Activitat: Projecte de lliçons informàtiques" unit_3: "Unitat 3: Algorismes" unit_3_activity_1: "Unitat 3 Activitat: Algorismes - Guia de l'Autoestopista" unit_3_activity_2: "Unitat 3 Activitat: Simulació - Depredador i Presa" unit_3_activity_3: "Unitat 3 Activitat: Algorismes - Disseny de parelles i Programació" unit_4: "Unitat 4: Programació" unit_4_activity_1: "Unitat 4 Activitat: Abstraccions" unit_4_activity_2: "Unitat 4 Activitat: Cerca i Classificació" unit_4_activity_3: "Unitat 4 Activitat: Refactorització" unit_5: "Unitat 5: Internet" unit_5_activity_1: "Unitat 5 Activitat: Com funciona Internet" unit_5_activity_2: "Unitat 5 Activitat: Simulació d'Internet" unit_5_activity_3: "Unitat 5 Activitat: Simulation d'un Xat" unit_5_activity_4: "Unitat 5 Activitat: Cyberseguritat" unit_6: "Unitat 6: Dades" unit_6_activity_1: "Unitat 6 Activitat: Introducció a les Dades" unit_6_activity_2: "Unitat 6 Activitat: Big Data" unit_6_activity_3: "Unitat 6 Activitat: Compressió amb i sense Pèrdua" unit_7: "Unitat 7: Impacte Personal i Global" unit_7_activity_1: "Unitat 7 Activitat: Impacte Personal i Global" unit_7_activity_2: "Unitat 7 Activitat: Crowdsourcing" unit_8: "Unitat 8: Tasques de Rendiment" unit_8_description: "Prepara els estudiants per a Tasca Creativa, construint els seus propis jocs i practicant conceptes clau." unit_8_activity_1: "Pràctica Tasca Creativa 1: Desenvolupament de Jocs 1" unit_8_activity_2: "Pràctica Tasca Creativa 2: Desenvolupament de Jocs 2" unit_8_activity_3: "Pràctica Tasca Creativa 3: Desenvolupament de Jocs 3" unit_9: "Unitat 9: Revisió dels Fonaments" unit_10: "Unitat 10: Més enllà dels Fonaments" unit_10_activity_1: "Unitat 10 Activitat: Web Quiz" parent_landing: slogan_quote: "\"CodeCombat és realment difertit, i aprens molt.\"" quote_attr: "5è grau, Oakland, CA" refer_teacher: "Consulteu al Professor" focus_quote: "Desbloqueja el futur del teus fills" value_head1: "La forma més atractiva d'aprendre codi escrit" value_copy1: "CodeCombat és un tutor personal dels nens. Amb material de cobertura d'acord amb els estàndards curriculars nacionals, el vostre fill programarà algorismes, crearà llocs web i fins i tot dissenyarà els seus propis jocs." value_head2: "Construint habilitats claus per al segle XXI" value_copy2: "Els vostres fills aprendran a navegar i esdevenir ciutadans del món digital. CodeCombat és una solució que millora el pensament crític i la capacitat de recuperació del vostre fill." value_head3: "Herois que els vostres fills estimaran" value_copy3: "Sabem la importància que té divertir-se i implicar-se pel desenvolupament del cervell, per això hem encabit tant aprenentatge com hem pogut presentant-lo en un joc que els encantarà." dive_head1: "No només per als enginyers de programació" dive_intro: "Les habilitats informàtiques tenen una àmplia gamma d'aplicacions. Mireu alguns exemples a continuació!" medical_flag: "Aplicacions Mèdiques" medical_flag_copy: "Des del mapatge del genoma humà fins a les màquines de ressonància magnètica, la codificació ens permet comprendre el cos de maneres que mai no hem pogut fer." explore_flag: "Exploració Espacial" explore_flag_copy: "Apol·lo va arribar a la Lluna gràcies al treball humà amb ordinadors, i els científics utilitzen programes informàtics per analitzar la gravetat dels planetes i buscar noves estrelles." filmaking_flag: "Producció de Vídeo i Animació" filmaking_flag_copy: "Des de la robòtica del Jurassic Park fins a l'increïble animació de Dreamworks i Pixar, les pel·lícules no serien les mateixes sense les creacions digitals darrere de les escenes." dive_head2: "Els jocs són importants per aprendre" dive_par1: "Múltiples estudis han trobat que l'aprenentatge mitjançant jocs promou" dive_link1: "el desenvolupament cognitiu" dive_par2: "en els nens al mateix temps que demostra ser" dive_link2: "més efectiu" dive_par3: "ajudant els alumnes a" dive_link3: "aprendre i retenir coneixements" dive_par4: "," dive_link4: "concentrar-se" dive_par5: ", i aconseguir un major assoliment." dive_par6: "L'aprenentatge basat en jocs també és bo per desenvolupar" dive_link5: "resiliència" dive_par7: ", raonament cognitiu, i" dive_par8: ". Les Ciències només ens diuen què han de saber els nens. Aquests aprenen millor jugant." dive_link6: "funcions executives" dive_head3: "Fent Equip amb els Professors" dive_3_par1: "En el futur, " dive_3_link1: "codificar serà tan fonamental com aprendre a llegir i escriure" dive_3_par2: ". Hem treballat estretament amb els professors per dissenyar i desenvolupar el nostre contingut, i estem ensiosos per ensenyar als vostres fills. Els programes de tecnologia educativa com CodeCombat funcionen millor quan els professors els implementen de forma coherent. Ajudeu-nos a fer aquesta connexió presentant-nos als professors del vostre fill." mission: "La nostra missió: ensenyar i participar" mission1_heading: "Codificant per la generació d'avui" mission2_heading: "Preparant pel futur" mission3_heading: "Recolzat per pares com tu" mission1_copy: "Els nostres especialistes en educació treballen estretament amb els professors per conèixer els nens que es troben a l'entorn educatiu. Els nens aprenen habilitats que es poden aplicar fora del joc perquè aprenen a resoldre problemes, independentment del seu estil d'aprenentatge." mission2_copy: "Una enquesta de 2016 va demostrar que el 64% de les noies de 3r a 5è grau volien aprendre a codificar. Es van crear 7 milions de llocs de treball al 2015 on es requerien habilitats en codificació. Hem construït CodeCombat perquè cada nen hauria de tenir l'oportunitat de crear el seu millor futur." mission3_copy: "A CodeCombat, som pares. Som coders. Som educadors. Però, sobretot, som persones que creiem en donar als nostres fills la millor oportunitat per l'èxit en qualsevol cosa que decideixin fer." parent_modal: refer_teacher: "Consulteu al Professor" name: "El teu Nom" parent_email: "El teu E-mail" teacher_email: "E-mail del Professor" message: "Missatge" custom_message: "Acabo de trobar CodeCombat i vaig pensar que seria un gran programa per a la vostra aula! És una plataforma d'aprenentatge d'informàtica amb un pla d'estudis amb estàndards.\n\nL'alfabetització informàtica és tan important i crec que aquesta seria una gran manera d'aconseguir que els estudiants es dediquin a aprendre a codificar." send: "E-mail enviat" hoc_2018: # banner: "Happy Computer Science Education Week 2018!" page_heading: "Ensenya als teus alumnes com construir el seu propi joc d'arcade!" # {change} # step_1: "Step 1: Watch Video Overview" # step_2: "Step 2: Try it Yourself" # step_3: "Step 3: Download Lesson Plan" # try_activity: "Try Activity" download_pdf: "Descarregar PDF" # teacher_signup_heading: "Turn Hour of Code into a Year of Code" # teacher_signup_blurb: "Everything you need to teach computer science, no prior experience needed." # teacher_signup_input_blurb: "Get first course free:" # teacher_signup_input_placeholder: "Teacher email address" # teacher_signup_input_button: "Get CS1 Free" # activities_header: "More Hour of Code Activities" # activity_label_1: "Escape the Dungeon!" # activity_label_2: " Beginner: Build a Game!" # activity_label_3: "Advanced: Build an Arcade Game!" # activity_button_1: "View Lesson" about: "Sobre CodeCombat:" # {change} about_copy: "CodeCombat és un programa informàtic basat en jocs per ensenyar Python i JavaScript reals. El currículum d'acord amb els estàndards de CodeCombat es basa en un joc que els estudiants estimen. Més de 12 milions d'estudiants han après a codificar amb CodeCombat!" # {change} point1: "✓ Amb recolçament" point2: "✓ Diferenciat" point3: "✓ Avaluació Formativa i Sumativa" # {change} point4: "✓ Cursos basats en Projectes" point5: "✓ Seguiment de l'Alumnat" point6: "✓ Planificació de Lliçons complertes" # title: "HOUR OF CODE 2018" # acronym: "HOC" # hoc_2018_interstitial: # welcome: "Welcome to CodeCombat's Hour of Code 2018!" # educator: "I'm an educator" # show_resources: "Show me teacher resources!" # student: "I'm a student" # ready_to_code: "I'm ready to code!" # hoc_2018_completion: # congratulations: "Congratulations on completing <b>Code, Play, Share!</b>" # send: "Send your Hour of Code game to friends and family!" # copy: "Copy URL" # get_certificate: "Get a certificate of completion to celebrate with your class!" # get_cert_btn: "Get Certificate" # first_name: "<NAME>" # last_initial: "<NAME> Initial" # teacher_email: "Teacher's email address" # school_administrator: # title: "School Administrator Dashboard" # my_teachers: "My Teachers" # last_login: "Last Login" # licenses_used: "licenses used" # total_students: "total students" # active_students: "active students" # projects_created: "projects created" # other: "Other" # notice: "The following school administrators have view-only access to your classroom data:" # add_additional_teacher: "Need to add an additional teacher? Contact your CodeCombat Account Manager or email <EMAIL>. " # license_stat_description: "Licenses available accounts for the total number of licenses available to the teacher, including Shared Licenses." # students_stat_description: "Total students accounts for all students across all classrooms, regardless of whether they have licenses applied." # active_students_stat_description: "Active students counts the number of students that have logged into CodeCombat in the last 60 days." # project_stat_description: "Projects created counts the total number of Game and Web development projects that have been created." # no_teachers: "You are not administrating any teachers."
true
module.exports = nativeDescription: "Català", englishDescription: "Catalan", translation: new_home: # title: "CodeCombat - Coding games to learn Python and JavaScript" # meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." # built_for_teachers_title: "A Coding Game Built with Teachers in Mind" # built_for_teachers_blurb: "Teaching kids to code can often feel overwhelming. CodeCombat helps all educators teach students how to code in either JavaScript or Python, two of the most popular programming languages. With a comprehensive curriculum that includes six computer science units and reinforces learning through project-based game development and web development units, kids will progress on a journey from basic syntax to recursion!" # built_for_teachers_subtitle1: "Computer Science" # built_for_teachers_subblurb1: "Starting with our free Introduction to Computer Science course, students master core coding concepts such as while/for loops, functions, and algorithms." # built_for_teachers_subtitle2: "Game Development" # built_for_teachers_subblurb2: "Learners construct mazes and use basic input handling to code their own games that can be shared with friends and family." # built_for_teachers_subtitle3: "Web Development" # built_for_teachers_subblurb3: "Using HTML, CSS, and jQuery, learners flex their creative muscles to program their own webpages with a custom URL to share with their classmates." # century_skills_title: "21st Century Skills" # century_skills_blurb1: "Students Don't Just Level Up Their Hero, They Level Up Themselves" # century_skills_quote1: "You mess up…so then you think about all of the possible ways to fix it, and then try again. I wouldn't be able to get here without trying hard." # century_skills_subtitle1: "Critical Thinking" # century_skills_subblurb1: "With coding puzzles that are naturally scaffolded into increasingly challenging levels, CodeCombat's programming game ensures kids are always practicing critical thinking." # century_skills_quote2: "Everyone else was making mazes, so I thought, ‘capture the flag’ and that’s what I did." # century_skills_subtitle2: "Creativity" # century_skills_subblurb2: "CodeCombat encourages students to showcase their creativity by building and sharing their own games and webpages." # century_skills_quote3: "If I got stuck on a level. I would work with people around me until we were all able to figure it out." # century_skills_subtitle3: "Collaboration" # century_skills_subblurb3: "Throughout the game, there are opportunities for students to collaborate when they get stuck and to work together using our pair programming guide." # century_skills_quote4: "I’ve always had aspirations of designing video games and learning how to code ... this is giving me a great starting point." # century_skills_subtitle4: "Communication" # century_skills_subblurb4: "Coding requires kids to practice new forms of communication, including communicating with the computer itself and conveying their ideas using the most efficient code." # classroom_in_box_title: "We Strive To:" # classroom_in_box_blurb1: "Engage every student so that they believe coding is for them." # classroom_in_box_blurb2: "Empower any educator to feel confident when teaching coding." # classroom_in_box_blurb3: "Inspire all school leaders to create a world-class computer science program." # creativity_rigor_title: "Where Creativity Meets Rigor" # creativity_rigor_subtitle1: "Make coding fun and teach real-world skills" # creativity_rigor_blurb1: "Students type real Python and JavaScript while playing games that encourage trial-and-error, critical thinking, and creativity. Students then apply the coding skills they’ve learned by developing their own games and websites in project-based courses." # creativity_rigor_subtitle2: "Reach students at their level" # creativity_rigor_blurb2: "Every CodeCombat level is scaffolded based on millions of data points and optimized to adapt to each learner. Practice levels and hints help students when they get stuck, and challenge levels assess students' learning throughout the game." # creativity_rigor_subtitle3: "Built for all teachers, regardless of experience" # creativity_rigor_blurb3: "CodeCombat’s self-paced, standards-aligned curriculum makes teaching computer science possible for everyone. CodeCombat equips teachers with the training, instructional resources, and dedicated support to feel confident and successful in the classroom." # featured_partners_title1: "Featured In" # featured_partners_title2: "Awards & Partners" # featured_partners_blurb1: "CollegeBoard Endorsed Provider" # featured_partners_blurb2: "Best Creativity Tool for Students" # featured_partners_blurb3: "Top Pick for Learning" # featured_partners_blurb4: "Code.org Official Partner" # featured_partners_blurb5: "CSforAll Official Member" # featured_partners_blurb6: "Hour of Code Activity Partner" # for_leaders_title: "For School Leaders" # for_leaders_blurb: "A Comprehensive, Standards-Aligned Computer Science Program" # for_leaders_subtitle1: "Easy Implementation" # for_leaders_subblurb1: "A web-based program that requires no IT support. Get started in under 5 minutes using Google or Clever Single Sign-On (SSO)." # for_leaders_subtitle2: "Full Coding Curriculum" # for_leaders_subblurb2: "A standards-aligned curriculum with instructional resources and professional development to enable any teacher to teach computer science." # for_leaders_subtitle3: "Flexible Use Cases" # for_leaders_subblurb3: "Whether you want to build a Middle School coding elective, a CTE pathway, or an AP Computer Science Principles class, CodeCombat is tailored to suit your needs." # for_leaders_subtitle4: "Real-World Skills" # for_leaders_subblurb4: "Students build grit and develop a growth mindset through coding challenges that prepare them for the 500K+ open computing jobs." # for_teachers_title: "For Teachers" # for_teachers_blurb: "Tools to Unlock Student Potential" # for_teachers_subtitle1: "Project-Based Learning" # for_teachers_subblurb1: "Promote creativity, problem-solving, and confidence in project-based courses where students develop their own games and webpages." # for_teachers_subtitle2: "Teacher Dashboard" # for_teachers_subblurb2: "View data on student progress, discover curriculum resources, and access real-time support to empower student learning." # for_teachers_subtitle3: "Built-in Assessments" # for_teachers_subblurb3: "Personalize instruction and ensure students understand core concepts with formative and summative assessments." # for_teachers_subtitle4: "Automatic Differentiation" # for_teachers_subblurb4: "Engage all learners in a diverse classroom with practice levels that adapt to each student's learning needs." # game_based_blurb: "CodeCombat is a game-based computer science program where students type real code and see their characters react in real time." # get_started: "Get started" # global_title: "Join Our Global Community of Learners and Educators" # global_subtitle1: "Learners" # global_subtitle2: "Lines of Code" # global_subtitle3: "Teachers" # global_subtitle4: "Countries" # go_to_my_classes: "Go to my classes" # go_to_my_courses: "Go to my courses" # quotes_quote1: "Name any program online, I’ve tried it. None of them match up to CodeCombat. Any teacher who wants their students to learn how to code... start here!" # quotes_quote2: " I was surprised about how easy and intuitive CodeCombat makes learning computer science. The scores on the AP exam were much higher than I expected and I believe CodeCombat is the reason why this was the case." # quotes_quote3: "CodeCombat has been the most beneficial for teaching my students real-life coding capabilities. My husband is a software engineer and he has tested out all of my programs. He put this as his top choice." # quotes_quote4: "The feedback … has been so positive that we are structuring a computer science class around CodeCombat. The program really engages the students with a gaming style platform that is entertaining and instructional at the same time. Keep up the good work, CodeCombat!" # see_example: "See example" slogan: "El joc més atractiu per aprendre a programar." # {change} # teach_cs1_free: "Teach CS1 Free" # teachers_love_codecombat_title: "Teachers Love CodeCombat" # teachers_love_codecombat_blurb1: "Report that their students enjoy using CodeCombat to learn how to code" # teachers_love_codecombat_blurb2: "Would recommend CodeCombat to other computer science teachers" # teachers_love_codecombat_blurb3: "Say that CodeCombat helps them support students’ problem solving abilities" # teachers_love_codecombat_subblurb: "In partnership with McREL International, a leader in research-based guidance and evaluations of educational technology." # try_the_game: "Try the game" classroom_edition: "Edició d'Aula:" learn_to_code: "Aprendre a programar:" play_now: "Juga Ara" # im_an_educator: "I'm an Educator" im_a_teacher: "PI:NAME:<NAME>END_PI" im_a_student: "Sóc Alumna/e" learn_more: "Aprén més" classroom_in_a_box: "Una aula preparada per a l'ensenyament de la informàtica." codecombat_is: "CodeCombat és una plataforma <strong> per als estudiants </ strong> per aprendre ciències de la computació mentre es juga a través d'un veritable joc." our_courses: "Els nostres cursos han estat específicament provats <strong> de manera excel·lent a l'aula </ strong>, fins i tot per a professorat amb poca o cap experiència prèvia de programació." watch_how: "Observeu com CodeCombat està transformant la manera com la gent aprèn la informàtica." top_screenshots_hint: "Els alumnes escriuen el codi i veuen la seva actualització de canvis en temps real" designed_with: "Dissenyat pensant en el professorat" real_code: "Codi real tipificat" from_the_first_level: "des del nivell elemental" getting_students: "Acostumar l'alumnat al codi escrit amb la major rapidesa possible és fonamental per aprendre la sintaxi de programació i l'estructura adient." educator_resources: "Recursos educatius" course_guides: "i guies de curs" teaching_computer_science: "L'ensenyament de la informàtica no requereix un estudi costós, ja que proporcionem eines per donar suport als educadors de tots els àmbits." accessible_to: "Accessible a" everyone: "tothom" democratizing: "Democratitzar el procés d'aprenentatge de codificació és el nucli de la nostra filosofia. Tothom ha de poder aprendre a codificar." forgot_learning: "Crec que en realitat es van oblidar que realment estaven aprenent." wanted_to_do: " La codificació és una cosa que sempre he volgut fer, i mai vaig pensar que seria capaç d'aprendre a l'escola." builds_concepts_up: "M'agrada com CodeCombat construeix els conceptes. Realment és fàcil d'entendre i divertit de comprovar." why_games: "Per què és important aprendre mitjançant els jocs?" games_reward: "Els jocs recompensen la lluita productiva." encourage: "El joc és un mitjà que afavoreix la interacció, el descobriment i la prova i error. Un bon joc desafia el jugador a dominar les habilitats al llarg del temps, que és el mateix procés crític que passen els estudiants a mesura que aprenen." excel: "Els jocs són excel·lents en recompensar" struggle: "lluita productiva" kind_of_struggle: "el tipus de lluita que resulta en l'aprenentatge que és comprometent i" motivating: "motivador" not_tedious: "no tediós." gaming_is_good: "Els estudis confirmen que jugar és bo pel desenvolupament de la ment dels infants. (De debó!)" game_based: "Quan el sistema d'aprenenetatge basat en jocs és" compared: "comparat" conventional: "amb els mètodes d'avaluació convencionals, la diferència és clara: els jocs són millors per ajudar l'alumnat a mantenir el coneixement, concentrar-se i" perform_at_higher_level: "assolir un major rendiment" feedback: "Els jocs també proporcionen comentaris en temps real que permeten a l'alumnat ajustar la seva ruta de solució i entendre conceptes de manera més holística, en lloc de limitar-se a respostes “correctes” o “incorrectes”." real_game: "Un joc real, jugat amb la codificació real." great_game: "Un gran joc és més que simples emblemes i èxits: es tracta del viatge d'un jugador, dels trencaclosques ben dissenyats i de la capacitat per afrontar els desafiaments amb decisió i confiança." agency: "CodeCombat és un joc que dóna als jugadors aquesta decisió i confiança amb el nostre robust motor de codi mecanografiat, que ajuda tant als estudiants principiants com a estudiants avançats a escriure el codi correcte i vàlid." request_demo_title: "Comença avui mateix amb el teu alumnat!" request_demo_subtitle: "Sol·licita una demo i fes que el teu alumnat comenci en menys d'una hora." get_started_title: "Configureu la vostra classe avui mateix" get_started_subtitle: "Configureu una classe, afegiu-hi l'alumnat i seguiu el seu progrés a mesura que aprenguin informàtica." request_demo: "Sol·liciteu una demostració" # request_quote: "Request a Quote" setup_a_class: "Configureu una Classe" have_an_account: "Tens un compte?" logged_in_as: "Ja has iniciat la sessió com a" computer_science: "Els nostres cursos autoformatius cobreixen la sintaxi bàsica als conceptes avançats" ffa: "Gratuït per a tot l'alumnat" coming_soon: "Aviat, més!" courses_available_in: "Els cursos estan disponibles a JavaScript i Python. Els cursos de desenvolupament web utilitzen HTML, CSS i jQuery." boast: "Compta amb endevinalles que són prou complexas per fascinar als jugadors i als codificadors." winning: "Una combinació exitosa del joc de rol i la tasca de programació que fa que l'educació educativa sigui legítimament agradable." run_class: "Tot el que necessiteu per dirigir una classe d'informàtica a la vostra escola avui dia, no cal preparar res." goto_classes: "Ves a Les Meves Classes" view_profile: "Veure El meu Perfil" view_progress: "Veure Progrés" go_to_courses: "Vés a Els meus Cursos" want_coco: "Vols CodeCombat al teu centre?" # educator: "Educator" # student: "Student" nav: # educators: "Educators" # follow_us: "Follow Us" # general: "General" map: "Mapa" play: "Nivells" # The top nav bar entry where players choose which levels to play community: "Comunitat" courses: "Cursos" blog: "Bloc" forum: "Fòrum" account: "Compte" my_account: "El Meu Compte" profile: "Perfil" home: "Inici" contribute: "Col·laborar" legal: "Legalitat" privacy: "Privadesa" about: "Sobre Nosaltres" contact: "Contacta" twitter_follow: "Segueix-nos" my_classrooms: "Les Meves Classes" my_courses: "Els Meus Cursos" # my_teachers: "My Teachers" careers: "Professions" facebook: "Facebook" twitter: "Twitter" create_a_class: "Crear una Classe" other: "Altra" learn_to_code: "Aprendre a Programar!" toggle_nav: "Commuta la Navegació" schools: "Centres" get_involved: "Involucrar-se" open_source: "Codi Obert (GitHub)" support: "Suport" faqs: "Preguntes freqüents" copyright_prefix: "Copyright" copyright_suffix: "Tots els drets reservats." help_pref: "Necessites ajuda? Envia'ns un e-mail" help_suff: "i contactarem amb tu!" resource_hub: "Centre de Recursos" apcsp: "Principis AP CS" parent: "Pares" modal: close: "Tancar" okay: "D'acord" not_found: page_not_found: "Pàgina no trobada" diplomat_suggestion: title: "Ajuda a traduir CodeCombat!" # This shows up when a player switches to a non-English language using the language selector. sub_heading: "Neccesitem les teves habilitats lingüístiques." pitch_body: "Hem desenvolupat CodeCombat en anglès, però tenim jugadors per tot el món. Molts d'ells volen jugar en Català, però no parlen anglès, per tant si pots parlar ambdues llengües, siusplau considereu iniciar sessió per a ser Diplomàtic i ajudar a traduir la web de CodeCombat i tots els seus nivells en Català." missing_translations: "Fins que puguem traduir-ho tot en català, ho veuràs en anglès quant no estigui en català." learn_more: "Aprèn més sobre ser un diplomàtic" subscribe_as_diplomat: "Subscriu-te com a diplomàtic" play: # title: "Play CodeCombat Levels - Learn Python, JavaScript, and HTML" # meta_description: "Learn programming with a coding game for beginners. Learn Python or JavaScript as you solve mazes, make your own games, and level up. Challenge your friends in multiplayer arena levels!" # level_title: "__level__ - Learn to Code in Python, JavaScript, HTML" # video_title: "__video__ | Video Level" # game_development_title: "__level__ | Game Development" # web_development_title: "__level__ | Web Development" # anon_signup_title_1: "CodeCombat has a" # anon_signup_title_2: "Classroom Version!" # anon_signup_enter_code: "Enter Class Code:" # anon_signup_ask_teacher: "Don't have one? Ask your teacher!" # anon_signup_create_class: "Want to create a class?" # anon_signup_setup_class: "Set up a class, add your students, and monitor progress!" # anon_signup_create_teacher: "Create free teacher account" play_as: "Jugar com" # Ladder page get_course_for_class: "Assigna el desenvolupament del joc i més a les vostres classes!" request_licenses: "Posa't en contacte amb els especialistes del centre per obtenir més informació." compete: "Competir!" # Course details page spectate: "Espectador" # Ladder page players: "PI:NAME:<NAME>END_PI" # Hover over a level on /play hours_played: "Hores jugades" # Hover over a level on /play items: "Objectes" # Tooltip on item shop button from /play unlock: "Desbloquejar" # For purchasing items and heroes confirm: "Confirmar" owned: "Adquirit" # For items you own locked: "Bloquejat" available: "Disponible" skills_granted: "Habilitats Garantides" # Property documentation details heroes: "Herois" # Tooltip on hero shop button from /play achievements: "Triomfs" # Tooltip on achievement list button from /play settings: "Configuració" # Tooltip on settings button from /play poll: "Enquesta" # Tooltip on poll button from /play next: "Següent" # Go from choose hero to choose inventory before playing a level change_hero: "Canviar heroi" # Go back from choose inventory to choose hero change_hero_or_language: "Canviar heroi o Idioma" buy_gems: "Comprar Gemmes" subscribers_only: "Només subscriptors!" subscribe_unlock: "Subscriu-te per desbloquejar!" subscriber_heroes: "Subscriu-te avui per desbloquejar immediatament a Amara, Hushbaum i Hattori!" subscriber_gems: "Subscriu-te avui per comprar aquest heroi amb gemmes!" anonymous: "PI:NAME:<NAME>END_PI" level_difficulty: "Dificultat: " awaiting_levels_adventurer_prefix: "Publiquem nous nivells cada setmana." awaiting_levels_adventurer: "Inicia sessió com a aventurer" awaiting_levels_adventurer_suffix: "Sigues el primer en jugar els nous nivells" adjust_volume: "Ajustar volum" campaign_multiplayer: "Arenes Multijugador" campaign_multiplayer_description: "... on programes cara a cara contra altres jugadors." brain_pop_done: "Has derrotat els ogres amb el codi! Tu guanyes!" brain_pop_challenge: "Desafíeu-vos a jugar de nou utilitzant un llenguatge de programació diferent." replay: "Repeteix" back_to_classroom: "Tornar a l'aula" teacher_button: "Per a Docents" get_more_codecombat: "Obté més CodeCombat" code: if: "si" # Keywords--these translations show up on hover, so please translate them all, even if it's kind of long. (In the code editor, they will still be in English.) else: "en cas contrari" elif: "en cas contrari, si" while: "mentre" loop: "repeteix" for: "des de" break: "trenca" continue: "continua" pass: "passar" return: "return" then: "llavors" do: "fes" end: "fi" function: "funció" def: "defineix" var: "variable" self: "si mateix" hero: "heroi" this: "això" or: "o" "||": "o" and: "i" "&&": "i" not: "no" "!": "no" "=": "assigna" "==": "igual" "===": "estrictament iguals" "!=": "no és igual" "!==": "no és estrictament igual" ">": "és més gran que" ">=": "és més gran o igual" "<": "és més petit que" "<=": "és més petit o igual" "*": "multiplicat per" "/": "dividit per" "+": "més" "-": "menys" "+=": "suma i assigna" "-=": "resta i assigna" True: "Veritat" true: "veritat" False: "Fals" false: "fals" undefined: "indefinit" null: "nul" nil: "nul" None: "Cap" share_progress_modal: blurb: "Estàs progressant molt! Digues als teus pares quant n'has après amb CodeCombat." email_invalid: "Correu electrònic invàlid." form_blurb: "Escriu els seus emails a sota i els hi ensenyarem!" form_label: "Correu electrònic" placeholder: "adreça de correu electrònic" title: "Excel·lent feina, aprenent" login: sign_up: "Crear un compte" email_or_username: "E-mail o usuari" log_in: "Iniciar Sessió" logging_in: "Iniciant Sessió" log_out: "PI:NAME:<NAME>END_PI" forgot_password: "PI:PASSWORD:<PASSWORD>END_PI?" finishing: "Acabant" sign_in_with_facebook: "Inicia amb Facebook" sign_in_with_gplus: "Inicia amb G+" signup_switch: "Vols crear-te un compte?" signup: complete_subscription: "Subscripció completa" create_student_header: "Crea un compte d'estudiant" create_teacher_header: "Crea un compte de docent" create_individual_header: "Crea un compte Individual" email_announcements: "Rebre anuncis sobre nous nivells CodeCombat i les seves característiques" sign_in_to_continue: "Inicieu sessió o creeu un compte per continuar" teacher_email_announcements: "Mantén-me actualitzat sobre nous recursos docents, currículum i cursos!" creating: "Creant Compte..." sign_up: "Registrar-se" log_in: "Iniciar sessió amb la teva contrasenya" # login: "Login" required: "Neccesites iniciar sessió abans ." login_switch: "Ja tens un compte?" optional: "opcional" connected_gplus_header: "Has connectat correctament amb Google+." connected_gplus_p: "Accediu a la subscripció perquè pugueu iniciar la sessió amb el vostre compte de Google+." connected_facebook_header: "Has connectat correctament amb Facebook!" connected_facebook_p: "Finalitzeu la subscripció perquè pugueu iniciar sessió amb el vostre compte de Facebook." hey_students: "Estudiants, introduïu el codi de classe del vostre professor." birthday: "Aniversari" parent_email_blurb: "Sabem que no podeu esperar per a aprendre programació &mdash; A nosaltres també ens emociona. Els vostres pares rebran un e-mail amb més instruccions sobre com crear un compte per a vosaltres. Podeu escriure a l'e-mail ({email_link}} si teniu algun dubte." classroom_not_found: "No existeixen classes amb aquest Codi de classe. Consulteu la ortografia o demaneu ajuda al vostre professor." checking: "Comprovant..." account_exists: "Aquest e-mail ja està en ús:" sign_in: "Inicieu sessió" email_good: "El correu electrònic està bé!" name_taken: "El nom d'usuari ja està agafat! Prova amb {{suggestedName}}?" name_available: "Nom d'usuari disponible!" name_is_email: "El nom d'usuari no pot ser un e-mail" choose_type: "Tria el teu tipus de compte:" teacher_type_1: "Ensenyeu la programació amb CodeCombat!" teacher_type_2: "Configureu la vostra classe" teacher_type_3: "Accediu a guies del curs" teacher_type_4: "Mostra el progrés de l'alumnat" signup_as_teacher: "Registra't com a docent" student_type_1: "Aprèn a programar mentre fas un joc atractiu!" student_type_2: "Juga amb la teva classe" student_type_3: "Competeix en els estàdiums" student_type_4: "Tria el teu heroi!" student_type_5: "Tingues preparat el teu Codi de classe!" signup_as_student: "Registra't com a estudiant" individuals_or_parents: "Particulars i pares" individual_type: "Per als jugadors que aprenen a codificar fora d'una classe. Els pares s'han d'inscriure a un compte aquí." signup_as_individual: "Inscriviu-vos com a particular" enter_class_code: "Introduïu el codi de la vostra classe" enter_birthdate: "Introduïu la data de naixement:" parent_use_birthdate: "Pares, utilitzeu la vostra data de naixement." ask_teacher_1: "Pregunteu al vostre professor pel vostre codi de classe." ask_teacher_2: "No és part d'una classe? Crea un " ask_teacher_3: "Compte Individual" ask_teacher_4: " en el seu lloc." about_to_join: "Estàs a punt d'unir-te:" enter_parent_email: "Introduïu l'adreça electrònica del vostres pares:" parent_email_error: "S'ha produït un error al intentar enviar el correu electrònic. Comproveu l'adreça de correu electrònic i torneu-ho a provar." parent_email_sent: "Hem enviat un correu electrònic amb més instruccions sobre com crear un compte. Demaneu als vostres pares que comprovin la seva safata d'entrada." account_created: "S'ha creat el compte!" confirm_student_blurb: "Escriviu la vostra informació perquè no us oblideu. El vostre professor també us pot ajudar a restablir la vostra contrasenya en qualsevol moment." confirm_individual_blurb: "Escriviu la informació d'inici de sessió en cas que la necessiti més tard. Verifiqueu el vostre correu electrònic perquè pugueu recuperar el vostre compte si alguna vegada us oblideu de la contrasenya: consulteu la safata d'entrada!" write_this_down: "Escriviu això:" start_playing: "Comença a jugar!" sso_connected: "S'ha connectat correctament amb:" select_your_starting_hero: "Seleccioneu el vostre heroi inicial:" you_can_always_change_your_hero_later: "Sempre podeu canviar l'heroi més tard." finish: "Acaba" teacher_ready_to_create_class: "Estàs preparat per crear la teva primera classe!" teacher_students_can_start_now: "Els teus alumnes podran començar a jugar immediatament al primer curs, Introducció a la informàtica." teacher_list_create_class: "A la pantalla següent podreu crear una nova classe." teacher_list_add_students: "Afegiu estudiants a la classe fent clic a l'enllaç Visualitza la classe i, a continuació, envia als vostres estudiants el codi de la classe o l'URL. També podeu convidar-los per correu electrònic si tenen adreces de correu electrònic." teacher_list_resource_hub_1: "Consulteu les" teacher_list_resource_hub_2: "Guies del Curs" teacher_list_resource_hub_3: "per obtenir solucions a tots els nivells, i el" teacher_list_resource_hub_4: "Centre de Recursos" teacher_list_resource_hub_5: "per guies curriculars, activitats i molt més!" teacher_additional_questions: "Això és! Si necessiteu ajuda addicional o teniu preguntes, consulteu __supportEmail__." dont_use_our_email_silly: "No posis el teu correu electrònic aquí! Posa el correu electrònic dels teus pares." want_codecombat_in_school: "Vols jugar CodeCombat tot el temps?" eu_confirmation: "Estic d'acord en permetre que CodeCombat desi les meves dades als servidors dels EE.UU." eu_confirmation_place_of_processing: "Saber més sobre possibles riscos" eu_confirmation_student: "Si dubtes, consulta al teu professorat." eu_confirmation_individual: "Si no vols que desem les teves dades als servidors dels EE.UU., sempre pots continuar jugant de manera anònima sense desar el teu codi." recover: recover_account_title: "Recuperar Compte" send_password: "PI:PASSWORD:<PASSWORD>END_PI" recovery_sent: "Correu de recuperació de contrasenya enviat." items: primary: "Primari" secondary: "Secundari" armor: "Armadura" accessories: "Accessoris" misc: "Misc" books: "Llibres" common: # default_title: "CodeCombat - Coding games to learn Python and JavaScript" # default_meta_description: "Learn typed code through a programming game. Learn Python, JavaScript, and HTML as you solve puzzles and learn to make your own coding games and websites." back: "Endarrere" # When used as an action verb, like "Navigate backward" coming_soon: "Pròximament!" continue: "Continua" # When used as an action verb, like "Continue forward" next: "Següent" default_code: "Codi per defecte" loading: "Carregant..." overview: "Resum" processing: "Processant..." solution: "Solució" table_of_contents: "Taula de Continguts" intro: "Intro" saving: "Guardant..." sending: "Enviant..." send: "Enviar" sent: "Enviat" cancel: "Cancel·lant" save: "Guardar" publish: "Publica" create: "Crear" fork: "Fork" play: "Jugar" # When used as an action verb, like "Play next level" retry: "Tornar a intentar" actions: "Accions" info: "Info" help: "Ajuda" watch: "Veure" unwatch: "Amaga" submit_patch: "Enviar pegat" submit_changes: "Puja canvis" save_changes: "Guarda canvis" required_field: "obligatori" general: and: "i" name: "Nom" date: "Data" body: "Cos" version: "Versió" pending: "Pendent" accepted: "Acceptat" rejected: "Rebutjat" withdrawn: "Retirat" accept: "Accepta" accept_and_save: "Accepta i desa" reject: "Refusa" withdraw: "Retira" submitter: "Remitent" submitted: "Presentat" commit_msg: "Enviar missatge" version_history: "Historial de versions" version_history_for: "Historial de versions per: " select_changes: "Selecciona dos canvis de sota per veure les diferències." undo_prefix: "Desfer" undo_shortcut: "(Ctrl+Z)" redo_prefix: "Refés" redo_shortcut: "(Ctrl+Shift+Z)" play_preview: "Reproduir avanç del nivell actual" result: "Resultat" results: "Resultats" description: "Descripció" or: "o" subject: "Tema" email: "Correu electrònic" password: "PI:PASSWORD:<PASSWORD>END_PI" confirm_password: "PI:PASSWORD:<PASSWORD>END_PI" message: "Missatge" code: "Codi" ladder: "Escala" when: "Quan" opponent: "Oponent" rank: "Rang" score: "Puntuació" win: "Guanyats" loss: "Perduts" tie: "Empat" easy: "Fàcil" medium: "Intermedi" hard: "Difícil" player: "PI:NAME:<NAME>END_PI" player_level: "Nivell" # Like player level 5, not like level: Dungeons of Kithgard warrior: "Guerrer" ranger: "Explorador" wizard: "Mag" first_name: "PI:NAME:<NAME>END_PI" last_name: "PI:NAME:<NAME>END_PI" last_initial: "Última inicial" username: "Usuari" contact_us: "Contacta amb nosaltres" close_window: "Tanca finestra" learn_more: "Aprèn més" more: "Més" fewer: "Menys" with: "amb" units: second: "segon" seconds: "segons" sec: "sec" minute: "minut" minutes: "minuts" hour: "hora" hours: "hores" day: "dia" days: "dies" week: "setmana" weeks: "setmanes" month: "mes" months: "mesos" year: "any" years: "anys" play_level: back_to_map: "Torna al mapa" directions: "Direccions" edit_level: "Edita Nivell" keep_learning: "Segueix aprenent" explore_codecombat: "Explora CodeCombat" finished_hoc: "He acabat amb la meva Hora de Codi" get_certificate: "Aconsegueix el teu certificat!" level_complete: "Nivell complet" completed_level: "Nivell completat:" course: "Curs:" done: "Fet" next_level: "Següent nivell" combo_challenge: "Repte combinat" concept_challenge: "Repte conceptual" challenge_unlocked: "Repte desbloquejat" combo_challenge_unlocked: "Repte combinat desbloquejat" concept_challenge_unlocked: "Repte conceptual desbloquejat" concept_challenge_complete: "Repte Conceptual Complet!" combo_challenge_complete: "Repte Combinat Complet!" combo_challenge_complete_body: "Bona feina, sembla que estàs disfrutant d'entendre __concept__!" replay_level: "Repeteix Nivell" combo_concepts_used: "__complete__/__total__ conceptes emprats" combo_all_concepts_used: "Has fet servir tots els conceptes possibles per resoldre el repte. Bona feina!" combo_not_all_concepts_used: "Has emprat __complete__ dels __total__ conceptes possibles per resoldre el repte. Prova d'emprar tots __total__ conceptes la propera vegada!" start_challenge: "Començar el Repte" next_game: "Següent joc" languages: "Llenguatges" programming_language: "Llenguatge de Programació" show_menu: "Mostrar menú del joc" home: "Inici" # Not used any more, will be removed soon. level: "Nivell" # Like "Level: Dungeons of Kithgard" skip: "Ometre" game_menu: "Menú de joc" restart: "Reiniciar" goals: "Objectius" goal: "Objectiu" challenge_level_goals: "Objectius del Nivell del Repte" challenge_level_goal: "Objectiu del Nivell del Repte" concept_challenge_goals: "Objectius del Repte Conceptual" combo_challenge_goals: "Objectius del Repte Combinat" concept_challenge_goal: "Objectiu del Repte Conceptual" combo_challenge_goal: "Objectiu del Repte Combinat" running: "Executant..." success: "Èxit!" incomplete: "Incomplet" timed_out: "S'ha acabat el temps" failing: "Fallant" reload: "Recarregar" reload_title: "Recarregar tot el codi?" reload_really: "Estàs segur que vols recarregar aquest nivell des del principi?" reload_confirm: "Recarregar tot" test_level: "Test de Nivell" victory: "Victòria" victory_title_prefix: "" victory_title_suffix: " Complet" victory_sign_up: "Inicia sessió per a desar el progressos" victory_sign_up_poke: "Vols guardar el teu codi? Crea un compte gratuït!" victory_rate_the_level: "Era molt divertit aquest nivell?" victory_return_to_ladder: "Retorna a les Escales" victory_saving_progress: "Desa progrés" victory_go_home: "Tornar a l'inici" victory_review: "Explica'ns més!" victory_review_placeholder: "Com ha anat el nivell?" victory_hour_of_code_done: "Has acabat?" victory_hour_of_code_done_yes: "Sí, he acabat amb la meva Hora del Codi™!" victory_experience_gained: "XP Guanyada" victory_gems_gained: "Gemmes guanyades" victory_new_item: "Objecte nou" victory_new_hero: "Nou Heroi" victory_viking_code_school: "Ostres! Aquest nivell era un nivell difícil de superar! Si no ets un programador, ho hauries de ser. Acabes d'aconseguir una acceptació per la via ràpida a l'Escola de Programació Vikinga, on pot millorar les teves habilitats fins al següent nivell i esdevenir un programador de webs professional en 14 setmanes." victory_become_a_viking: "Converteix-te en un víking" victory_no_progress_for_teachers: "El progrés no es guarda per als professors. Però, podeu afegir un compte d'estudiant a l'aula per vosaltres mateixos." tome_cast_button_run: "Executar" tome_cast_button_running: "Executant" tome_cast_button_ran: "Executat" tome_submit_button: "Envia" tome_reload_method: "Recarrega el codi original per reiniciar el nivell" tome_available_spells: "Encanteris disponibles" tome_your_skills: "Les teves habilitats" hints: "Consells" # videos: "Videos" hints_title: "Consell {{number}}" code_saved: "Codi Guardat" skip_tutorial: "Ometre (esc)" keyboard_shortcuts: "Dreceres del teclat" loading_start: "Comença el nivell" loading_start_combo: "Començar Repte Combinat" loading_start_concept: "Començar Repte Conceptual" problem_alert_title: "Arregla el Teu Codi" time_current: "Ara:" time_total: "Màxim:" time_goto: "Ves a:" non_user_code_problem_title: "Impossible carregar el nivell" infinite_loop_title: "Detectat un bucle infinit" infinite_loop_description: "El codi inicial mai acaba d'executar-se. Probablement sigui molt lent o tingui un bucle infinit. O pot ser un error. Pots provar de tornar a executar el codi o reiniciar-lo al seu estat original. Si no es soluciona, si us plau, fes-nos-ho saber." check_dev_console: "També pots obrir la consola de desenvolupament per veure què surt malament." check_dev_console_link: "(instruccions)" infinite_loop_try_again: "Tornar a intentar" infinite_loop_reset_level: "Reiniciar nivell" infinite_loop_comment_out: "Treu els comentaris del meu codi" tip_toggle_play: "Canvia entre reproduir/pausa amb Ctrl+P" tip_scrub_shortcut: "Ctrl+[ i Ctrl+] per rebobinar i avançar ràpid" tip_guide_exists: "Clica a la guia dins el menú del joc (a la part superior de la pàgina) per informació útil." tip_open_source: "CodeCombat és 100% codi lliure!" tip_tell_friends: "Gaudint de CodeCombat? Explica'ls-ho als teus amics!" tip_beta_launch: "CodeCombat va llançar la seva beta l'octubre de 2013." tip_think_solution: "Pensa en la solució, no en el problema." tip_theory_practice: "En teoria no hi ha diferència entre la teoria i la pràctica. Però a la pràctica si que n'hi ha. - PI:NAME:<NAME>END_PI" tip_error_free: "Només hi ha dues maneres d'escriure programes sense errors; la tercera és la única que funciona. - PI:NAME:<NAME>END_PI" tip_debugging_program: "Si depurar és el procés per eliminar errors, llavors programar és el procés de posar-los. - PI:NAME:<NAME>END_PI" tip_forums: "Passa pels fòrums i digues el que penses!" tip_baby_coders: "En el futur fins i tot els nadons podran ser mags." tip_morale_improves: "La càrrega continuarà fins que la moral millori." tip_all_species: "Creiem en la igualtat d'oportunitats per aprendre a programar per a totes les espècies." tip_reticulating: "Reticulant punxes." tip_harry: "Ets un bruixot, " tip_great_responsibility: "Un gran coneixement del codi comporta una gran responsabilitat per a depurar-lo." tip_munchkin: "Si no menges les teves verdures, un munchkin vindrà mentre dormis." tip_binary: "Hi ha 10 tipus de persones al món, les que saben programar en binari i les que no" tip_commitment_yoda: "Un programador ha de tenir un compromís profund, una ment seriosa. ~ Yoda" tip_no_try: "Fes-ho. O no ho facis. Però no ho intentis. - Yoda" tip_patience: "Pacient has de ser, jove PadPI:NAME:<NAME>END_PI. - Yoda" tip_documented_bug: "Un error documentat no és un error; és un atractiu." tip_impossible: "Sempre sembla impossible fins que es fa. - PI:NAME:<NAME>END_PI" tip_talk_is_cheap: "Parlar és barat. Mostra'm el codi. - PI:NAME:<NAME>END_PI" tip_first_language: "La cosa més desastrosa que aprendràs mai és el teu primer llenguatge de programació. - PI:NAME:<NAME>END_PI" tip_hardware_problem: "P: Quants programadors són necessaris per canviar una bombeta? R: Cap, és un problema de hardware." tip_hofstadters_law: "Llei de Hofstadter: Sempre et portarà més feina del que esperaves, fins i tot tenint en compte la llei de Hofstadter." tip_premature_optimization: "La optimització prematura és l'arrel de la maldat. - PI:NAME:<NAME>END_PI" tip_brute_force: "Quan dubtis, usa força bruta. - PI:NAME:<NAME>END_PI" tip_extrapolation: "Hi ha dos tipus de persones: aquells que poden extrapolar des de dades incompletes..." tip_superpower: "Programar és el que més s'aproxima a un super poder." tip_control_destiny: "En un codi obert real tens el dret a controlar el teu propi destí. - PI:NAME:<NAME>END_PI" tip_no_code: "Cap codi és més ràpid que l'absència de codi." tip_code_never_lies: "El codi mai menteix, els comentaris a vegades. — PI:NAME:<NAME>END_PI" tip_reusable_software: "Abans que el codi sigui reutilitzable, ha de ser usable." tip_optimization_operator: "Cada llenguatge té un operador d'optimització. En la majoria d'ells és ‘//’" tip_lines_of_code: "Mesurar el progrés d'un codi per les seves línies és com mesurar el progrés d'un avió pel seu pes. — PI:NAME:<NAME>END_PI" tip_source_code: "Vull canviar el món, però no em vol donar el seu codi font." tip_javascript_java: "Java és a JavaScript el que un cotxe a una catifa. - PI:NAME:<NAME>END_PI" tip_move_forward: "Facis el que facis, sempre segueix endavant. - PI:NAME:<NAME>END_PIr." tip_google: "Tens un problema que no pots resoldre? Cerca a Google!" tip_adding_evil: "Afegint una mica de maldat." tip_hate_computers: "La raó real per la qual la gent creu que odia els ordinadors és pels programadors pèssims. - PI:NAME:<NAME>END_PI" tip_open_source_contribute: "Pots ajudar a millorar CodeCombat!" tip_recurse: "La iteració és humana, la recursivitat és divina. - PI:NAME:<NAME>END_PI" tip_free_your_mind: "T'has de deixar endur, Neo. Por, dubtes, i incredulitat. Allibera la teva ment. - Morpheus" tip_strong_opponents: "Fins i tot el més fort dels oponents té alguna debilitat. - PI:NAME:<NAME>END_PI" tip_paper_and_pen: "Abans de començar a programar, sempre has de començar planejant amb paper i boli." tip_solve_then_write: "Primer, resol el problema. Després, escriu el codi. - PI:NAME:<NAME>END_PI" tip_compiler_ignores_comments: "De vegades crec que el compilador ignora els meus comentaris." tip_understand_recursion: "L'única manera d'entendre la recursió és comprendre la recursió." tip_life_and_polymorphism: "Open Source és com una estructura heterogènia totalment polimòrfica: tots els tipus són benvinguts." tip_mistakes_proof_of_trying: "Els errors del vostre codi són només una prova que esteu provant." tip_adding_orgres: "Arreglant els ogres." tip_sharpening_swords: "Afilant les espases." tip_ratatouille: "No podeu deixar que ningú defineixi els vostres límits a causa d'on prové. El vostre únic límit és la vostra ànima. - PI:NAME:<NAME>END_PI" tip_nemo: "Quan la vida et fa baixar, vols saber què has de fer? Només has de seguir nedant, només siguir nedant. - PI:NAME:<NAME>END_PI" tip_internet_weather: "Només has de mudar-te a Internet, es viu genial aquí. No sortim de casa on el clima és sempre increïble. - PI:NAME:<NAME>END_PI" tip_nerds: "Als llestos se'ls permet estimar coses, com fer-petits-salts-d'emoció-a-la-cadira-sense-control. - PI:NAME:<NAME>END_PI" tip_self_taught: "Em vaig ensenyar el 90% del que he après. I això és normal! - PI:NAME:<NAME>END_PI" tip_luna_lovegood: "No et preocupis. Tens tan bon enteniment com jo. - PI:NAME:<NAME>END_PI" tip_good_idea: "La millor manera de tenir una bona idea és tenir moltes idees. - PI:NAME:<NAME>END_PI" tip_programming_not_about_computers: "La informàtica no tracta tant sobre ordinadors com l'astronomia sobre telescopis. - PI:NAME:<NAME>END_PI" tip_mulan: "Pensa que pots, llavors ho faràs. - PI:NAME:<NAME>END_PI" project_complete: "Projecte Complet!" share_this_project: "Comparteix aquest projecte amb amics o familiars:" ready_to_share: "Preparat per publicar el teu projecte?" click_publish: "Fes clic a \"Publicar\" per fer que aparegui a la galeria de classes i, a continuació, mira els projectes dels teus companys! Podàs tornar i continuar treballant en aquest projecte. Qualsevol altre canvi es desarà automàticament i es compartirà amb els companys." already_published_prefix: "Els teus canvis s'han publicat a la galeria de classes." already_published_suffix: "Continua experimentant i millorant aquest projecte, o mira el que la resta de la teva classe ha fet. Els teus canvis es desaran i es compartiran automàticament amb els teus companys." view_gallery: "Veure Galeria" project_published_noty: "S'ha publicat el teu nivell!" keep_editing: "Segueix editant" # learn_new_concepts: "Learn new concepts" # watch_a_video: "Watch a video on __concept_name__" # concept_unlocked: "Concept Unlocked" # use_at_least_one_concept: "Use at least one concept: " apis: methods: "Mètodes" events: "Esdeveniments" handlers: "Manipuladors" properties: "Propietats" snippets: "Fragments" spawnable: "Desmuntable" html: "HTML" math: "Mates" array: "matriu" object: "Objecte" string: "Cadena" function: "Funció" vector: "Vector" date: "Data" jquery: "jQuery" json: "JSON" number: "Número" webjavascript: "JavaScript" amazon_hoc: title: "Segueix aprenent amb Amazon!" congrats: "Felicitats per conquerir aquesta desafiant Hora de Codi!" educate_1: "Ara, continueu informant-vos sobre codificació i computació en el núvol amb AWS Educate, un programa emocionant i gratuït d'Amazon per a estudiants i professors. Amb AWS Educate, podeu guanyar insígnies interessants a mesura que apreneu els aspectes bàsics del núvol i tecnologies d'avantguarda, com ara jocs, realitat virtual i Alexa." educate_2: "Més informació i registre aquí" future_eng_1: "També podeu provar de construir les vostres habilitats pròpies de l'escola per a PI:NAME:<NAME>END_PI" future_eng_2: "aquí" future_eng_3: "(no es requereix dispositiu). Aquesta activitat Alexa és presentada pel programa" future_eng_4: "Amazon Future Engineer" future_eng_5: "que crea oportunitats d'aprenentatge i treball per a tots els estudiants de K-12 als Estats Units que vulguin cursar informàtica." play_game_dev_level: created_by: "Creat per {{name}}" created_during_hoc: "Creat durant l'Hora del Codi" restart: "Reinicia el nivell" play: "Juga el nivell" play_more_codecombat: "Juga més CodeCombat" default_student_instructions: "Fes clic per controlar el teu heroi i guanyar el joc!" goal_survive: "Sobreviu." goal_survive_time: "Sobreviu __seconds__ segons." goal_defeat: "Derrota tots els enemics." goal_defeat_amount: "Derrota __amount__ enemics." goal_move: "Mou-te a totes les X vermelles." goal_collect: "Recull tots els ítems." goal_collect_amount: "Recull __amount__ ítems." game_menu: inventory_tab: "Inventari" save_load_tab: "Desa/Carrega" options_tab: "Opcions" guide_tab: "Gui" guide_video_tutorial: "Vídeo Tutorial" guide_tips: "Consells" multiplayer_tab: "Multijugador" auth_tab: "Dona't d'alta" inventory_caption: "Equipa el teu heroi" choose_hero_caption: "Tria l'heroi, llenguatge" options_caption: "Edita la configuració" guide_caption: "Documents i pistes" multiplayer_caption: "Juga amb amics!" auth_caption: "Desa el progrés." leaderboard: view_other_solutions: "Veure les taules de classificació" scores: "Puntuació" top_players: "Els millors jugadors de" day: "Avui" week: "Aquesta Setmana" all: "Tots els temps" latest: "Recent" time: "Temps" damage_taken: "Mal rebut" damage_dealt: "Mal inflingit" difficulty: "Dificultat" gold_collected: "Or recol·lectat" survival_time: "Sobreviscut" defeated: "Enemics derrotats" code_length: "Línies de Codi" score_display: "__scoreType__: __score__" inventory: equipped_item: "Equipat" required_purchase_title: "Necessari" available_item: "Disponible" restricted_title: "Restringit" should_equip: "(doble-clic per equipar)" equipped: "(equipat)" locked: "(bloquejat)" restricted: "(restringit en aquest nivell)" equip: "Equipa" unequip: "Desequipa" warrior_only: "Només Guerrers" ranger_only: "Només Exploradors" wizard_only: "Només Mags" buy_gems: few_gems: "Algunes gemmes" pile_gems: "Pila de gemmes" chest_gems: "Cofre de gemmes" purchasing: "Comprant..." declined: "La teva targeta ha estat rebutjada" retrying: "Error del servidor, intentant de nou." prompt_title: "Gemmes insuficients" prompt_body: "En vols més?" prompt_button: "Entrar a la botiga" recovered: "S'han recuperat les anteriors compres de gemmes. Si us plaus, recarrega al pàgina." price: "x{{gems}} / més" buy_premium: "Compra Premium" purchase: "Compra" purchased: "Comprat" subscribe_for_gems: prompt_title: "No hi ha prou gemmes!" prompt_body: "Compra Prèmium per tenir gemes i accedir fins i tot a més nivells!" earn_gems: prompt_title: "No hi ha prou gemmes" prompt_body: "Continua jugant per guanyar-ne més!" subscribe: best_deal: "Millor oferta!" confirmation: "Felicitats! Ja tens una subscripció a CodeCombat Prèmium!" premium_already_subscribed: "Ja estàs subscrit a Prèmium!" subscribe_modal_title: "CodeCombat Prèmium" comparison_blurb: "Millora les teves habilitats amb una subscripció a CodeCombat!" must_be_logged: "Necessites identificar-te. Si us plau, crea un compte o identifica't al menú de la part superior." subscribe_title: "Subscriu-te" # Actually used in subscribe buttons, too unsubscribe: "Donar-se de baixa" confirm_unsubscribe: "Confirmar la baixa" never_mind: "No et preocupis, encara t'estimo!" thank_you_months_prefix: "Gràcies pel suport donat els últims" thank_you_months_suffix: "mesos." thank_you: "Gràcies per donar suport a CodeCombat." sorry_to_see_you_go: "Llàstima que te'n vagis! Deixa'ns saber què podríem haver fet millor." unsubscribe_feedback_placeholder: "Oh, què hem fet?" stripe_description: "Subscripció mensual" buy_now: "Compra ara" subscription_required_to_play: "Necessitarás una subscripció per jugar aquest nivell." unlock_help_videos: "Subscriu-te per desbloquejar tots els vídeo-tutorials." personal_sub: "Subscripció Personal" # Accounts Subscription View below loading_info: "Carregant informació de la subscripció..." managed_by: "Gestionat per" will_be_cancelled: "Se't cancel·larà" currently_free: "Ara tens una subscripció gratuïta" currently_free_until: "Ara tens uns subscripció fins al" free_subscription: "Subscripció gratuïta" was_free_until: "Tens una subscripció gratuïta fins al" managed_subs: "Subscripcions gestionades" subscribing: "Subscrivint..." current_recipients: "Destinataris actuals" unsubscribing: "Anul·lació de subscripcions" subscribe_prepaid: "Feu clic a Subscripció per utilitzar el codi prepagat" using_prepaid: "Ús del codi prepagat per a la subscripció mensual" feature_level_access: "Accediu a més de 300 nivells disponibles" feature_heroes: "Desbloqueja herois exclusius i mascotes" feature_learn: "Aprèn a fer jocs i llocs web" month_price: "$__price__" first_month_price: "Només $__price__ pel teu primer mes!" lifetime: "Accés de per vida" lifetime_price: "$__price__" year_subscription: "Subscripció anual" year_price: "$__price__/any" support_part1: "Necessites ajuda amb el pagament o prefereixes PayPal? Envia'ns un e-mail a" support_part2: "PI:EMAIL:<EMAIL>END_PI" announcement: now_available: "Ja disponible pels subscriptors!" subscriber: "subscriptor" cuddly_companions: "Companys tendres!" # Pet Announcement Modal kindling_name: "PI:NAME:<NAME>END_PIling Elemental" kindling_description: "Els Kindling Elementals només volen escalfar-te per la nit. I pel dia. De fet, sempre." griffin_name: "PI:NAME:<NAME>END_PI" griffin_description: "Els Grifs són mig àguila, mig lleó, tots adorables." raven_name: "PI:NAME:<NAME>END_PI" raven_description: "Els Corbs són excel·lentsa l'hora de recollir ampolles brillants plenes de salut per a tu." mimic_name: "PI:NAME:<NAME>END_PI" mimic_description: "Els Mimics poden recollir monedes per a tu. Mou-los damunt les monedes per augmentar el teu subministrament d'or." cougar_name: "PI:NAME:<NAME>END_PI" cougar_description: "Als pumes els encanta guanyar un doctorat en ronronejar feliços diàriament." fox_name: "PI:NAME:<NAME>END_PI" fox_description: "Les Guineus blaves són molt llestes i les encanta cavar a la brutícia i a la neu!" pugicorn_name: "PI:NAME:<NAME>END_PI" pugicorn_description: "Els Pugicorns són algunes de les criatures més rares i poden llançar encanteris!" wolf_name: "PI:NAME:<NAME>END_PI" wolf_description: "Els Cadells Llops són excel·lents caçant, reunint-se i jugant a fet-i-amagar!" ball_name: "PI:NAME:<NAME>END_PI" ball_description: "ball.squeak()" collect_pets: "Col·lecciona mascotes pels teus herois!" each_pet: "Cada mascota té una habilitat d'ajuda única!" upgrade_to_premium: "Esdevé un {{subscriber}} per equipar mascotes." play_second_kithmaze: "Juga a {{the_second_kithmaze}} per desbloquejar el Cadell Llop!" the_second_kithmaze: "El SePI:NAME:<NAME>END_PI" keep_playing: "Continua jugant per descobrir la primera mascota!" coming_soon: "Pròximament" ritic: "PI:NAME:<NAME>END_PI el PI:NAME:<NAME>END_PI" # Ritic Announcement Modal ritic_description: "Rític el PI:NAME:<NAME>END_PI. Atrapat a la Glacera de PI:NAME:<NAME>END_PI per innombrables edats, finalment lliure i llest per tendir als ogres que el van empresonar." ice_block: "Un bloc de gel" ice_description: "Sembla que hi ha alguna cosa atrapada a l'interior..." blink_name: "PI:NAME:<NAME>END_PI" blink_description: "Rític desapareix i reapareix en un obrir i tancar els ulls, deixant res més que una ombra." shadowStep_name: "PI:NAME:<NAME>END_PIombres" shadowStep_description: "Un mestre assassí sap caminar entre les ombres." tornado_name: "PI:NAME:<NAME>END_PI" tornado_description: "És bo tenir un botó de restabliment quan la coberta surt pels aires." wallOfDarkness_name: "PI:NAME:<NAME>END_PI" wallOfDarkness_description: "Amaga't darrere una paret d'ombres per evitar la mirada d'ulls curiosos." premium_features: get_premium: "Aconsegueix<br>CodeCombat<br>Prèmium" # Fit into the banner on the /features page master_coder: "Converteix-te en un Maestre Codificador subscrivint-te avui mateix!" paypal_redirect: "Se't redirigirà a PayPal per completar el procés de subscripció." subscribe_now: "Subscriu-te Ara" hero_blurb_1: "Accediu a __premiumHeroesCount__ herois superequipats només per a subscriptors! Aprofita el poder imparable d'PI:NAME:<NAME>END_PI, la mortal precisió de Naria de les Fulles, o convoca esquelets \"adorables\" amb PI:NAME:<NAME>END_PI." hero_blurb_2: "Els guerrers Prèmium desbloquegen unes habilitats marcials impresionants com ara Crit de Guerra, Sofriment, i Llança Enemics. O, juga com a explorador, utilitzant sigil i arcs, llançant ganivets, i trampes! Prova la vostra habilitat com a mag codificador, i desencadena una potent matriu de Màgia Primordial, Necromàntica o Elemental!" hero_caption: "Herois nous i emocionants!" pet_blurb_1: "Les mascotes no són només companys adorables, sinó que també ofereixen funcions i mètodes únics. El Nadó Grif pot transportar unitats a través de l'aire, el Cadell Llop juga amb fletxes enemigues, al Puma li encanta perseguir els ogres del voltant, i el Mimic atreu monedes com un imant!" pet_blurb_2: "Aconsegueix totes les mascotes per descobrir les seves habilitats úniques." pet_caption: "Adopta mascotes per acompanyar al teu heroi!" game_dev_blurb: "Aprén seqüències d'ordres de jocs i construeix nivells nous per compartir amb els teus amics! Col·loca els ítems que vulguis, escriu el codi per la unitat lògica i de comportament i observa si els teus amics poden superar el nivell!" game_dev_caption: "Dissenya els teus propis jocs per desafiar als teus amics!" everything_in_premium: "Tot el que obtens en CodeCombat Prèmium:" list_gems: "Rep gemmes de bonificació per comprar equips, mascotes i herois" list_levels: "Guanya accés a __premiumLevelsCount__ nivells més" list_heroes: "Desbloqueja herois exclusius, inclosos del tipus Explorador i Mag" list_game_dev: "Fes i comparteix jocs amb els teus amics" list_web_dev: "Crea llocs web i aplicacions interactives" list_items: "Equipa amb elements exclusius Prèmium com ara mascotes" list_support: "Obté suport Prèmium per ajudar-te a depurar el codi delicat" list_clans: "Crea clans privats per convidar els teus amics i competir en una taula de classificació del grup" choose_hero: choose_hero: "Escull el teu heroi" programming_language: "Llenguatge de programació" programming_language_description: "Quin llenguatge de programació vols utilitzar?" default: "Per defecte" experimental: "Experimental" python_blurb: "Simple però poderós, Python és un bon llenguatge d'ús general." javascript_blurb: "El llenguatge de les webs." coffeescript_blurb: "Sintaxi JavaScript millorat." lua_blurb: "Llenguatge script per a jocs." java_blurb: "(Només subscriptor) Android i empresa." status: "Estat" weapons: "Armes" weapons_warrior: "Espases - Curt abast, no hi ha màgia" weapons_ranger: "Ballestes, armes - de llarg abast, no hi ha màgia" weapons_wizard: "Varetes, bastons - Llarg abast, Màgia" attack: "Dany" # Can also translate as "Attack" health: "Salut" speed: "Velocitat" regeneration: "Regeneració" range: "Abast" # As in "attack or visual range" blocks: "Bloqueja" # As in "this shield blocks this much damage" backstab: "Punyalada per l'esquena" # As in "this dagger does this much backstab damage" skills: "Habilitats" attack_1: "Danys" attack_2: "de la llista" attack_3: "dany d'armes." health_1: "Guanys" health_2: "de la llista" health_3: "salut d'armes." speed_1: "Es mou a" speed_2: "metres per segon." available_for_purchase: "Disponible per a la compra" # Shows up when you have unlocked, but not purchased, a hero in the hero store level_to_unlock: "Nivell per desbloquejar:" # Label for which level you have to beat to unlock a particular hero (click a locked hero in the store to see) restricted_to_certain_heroes: "Només certs herois poden jugar aquest nivell." skill_docs: function: "funció" # skill types method: "mètode" snippet: "fragment" number: "nombre" array: "matriu" object: "objecte" string: "cadena" writable: "editable" # Hover over "attack" in Your Skills while playing a level to see most of this read_only: "Només lectura" action: "Acció" spell: "Encantament" action_name: "nom" action_cooldown: "pren" action_specific_cooldown: "Refredat" action_damage: "Dany" action_range: "Abast" action_radius: "Radi" action_duration: "Duracció" example: "Exemple" ex: "ex" # Abbreviation of "example" current_value: "Valor actual" default_value: "Valor per defecte" parameters: "Paràmetres" required_parameters: "Paràmetres requerits" optional_parameters: "Paràmetres opcionals" returns: "Retorna" granted_by: "Atorgat per" save_load: granularity_saved_games: "Desats" granularity_change_history: "Historial" options: general_options: "Opcions generals" # Check out the Options tab in the Game Menu while playing a level volume_label: "Volum" music_label: "Musica" music_description: "Activa / desactiva la música de fons." editor_config_title: "Configuració de l'editor" editor_config_livecompletion_label: "Autocompleció en directe" editor_config_livecompletion_description: "Mostra els suggeriments automàtics mentre escriviu." editor_config_invisibles_label: "Mostra invisibles" editor_config_invisibles_description: "Mostra invisibles com ara espais o tabuladors." editor_config_indentguides_label: "Mostra guies de sagnia" editor_config_indentguides_description: "Mostra línees verticals per veure i identificar millor." editor_config_behaviors_label: "Comportament intel·ligent" editor_config_behaviors_description: "Autocompleta claudàtors, correctors i cometes." about: # title: "About CodeCombat - Engaging Students, Empowering Teachers, Inspiring Creation" # meta_description: "Our mission is to level computer science through game-based learning and make coding accessible to every learner. We believe programming is magic and want learners to be empowered to to create things from pure imagination." learn_more: "Aprèn més" main_title: "Si vols aprendre a programar, has d'escriure (molt) codi." main_description: "A CodeCombat, el nostre treball és assegurar-vos que ho feu amb un somriure a la cara." mission_link: "Missió" team_link: "Equip" story_link: "Història" press_link: "Prensa" mission_title: "La nostra missió: fer que la programació sigui accessible per a tots els estudiants de la Terra." mission_description_1: "<strong>Programar és màgic</strong>. És la capacitat de crear coses des d'una imaginació pura. Vam començar CodeCombat per donar a l'alumnat la sensació d'un poder màgic al seu abast usant <strong>codi escrit</strong>." mission_description_2: "Com a conseqüència, això els permet aprendre més ràpidament. MOLT ràpidament. És com tenir una conversa en comptes de llegir un manual. Volem portar aquesta conversa a cada escola i <strong>a cada alumne</strong>, perquè tothom hauria de tenir l'oportunitat d'aprendre la màgia de la programació." team_title: "Coneix l'equip de CodeCombat" team_values: "Valorem un diàleg obert i respectuós, on guanyi la millor idea. Les nostres decisions es basen en la investigació del client i el nostre procés se centra a oferir resultats tangibles per a ells. Tothom en té cabuda, del nostre CEO als nostres col·laboradors de GitHub, perquè valorem el creixement i l'aprenentatge al nostre equip." nick_title: "CPI:NAME:<NAME>END_PI, CEO" matt_title: "Cofundador, CTO" cat_title: "Dissenyador de jocs" scott_title: "Cofundador, Enginyer de Programari" maka_title: "Advocat de clients" robin_title: "Gerent de producció" nolan_title: "Cap de vendes" david_title: "Direcció de Comercialització" titles_csm: "Gerent d'èxit del client" titles_territory_manager: "Administrador de territori" retrostyle_title: "Il·lustració" retrostyle_blurb: "Jocs estil retro" bryukh_title: "Dissenyador de jocs" bryukh_blurb: "Constructor de trencaclosques" community_title: "...i la nostra comunitat de codi obert" community_subtitle: "Més de 500 contribuents han ajudat a construir CodeCombat, amb més unió cada setmana." community_description_3: "CodeCombat és un" community_description_link_2: "projecte comunitari" community_description_1: "amb centenars de jugadors voluntaris per crear nivells, contibuir al nostre codi per afegir característiques, arreglar errors, comprovar, i fins i tot traduir el joc a més de 50 llenguas. Els empleats, els contribuents i el lloc s'enriqueixen compartint idees i esforç de combinació, igual que la comunitat de codi obert en general. El lloc està construït amb nombrosos projectes de codi obert, i estem obert per retornar-los a la comunitat i proporcionar-li als usuaris curiosos un projecte familiar per explorar i experimentar. Qualsevol pot unir-se a la comunitat de CodeCombat! Consulta la nostra" community_description_link: "pàgina de contribució" community_description_2: "per a més informació." number_contributors: "Més de 450 col·laboradors han prestat el seu suport i el seu temps a aquest projecte." story_title: "La nostra història fins ara" story_subtitle: "Des de 2013, CodeCombat ha passat de ser un mer conjunt d'esbossos a un joc viu i pròsper." story_statistic_1a: "Més de 5,000,000" story_statistic_1b: "de jugadors en total" story_statistic_1c: "han iniciat el seu viatge vers la programació mitjançant CodeCombat" story_statistic_2a: "Hem estat treduits a més de 50 idiomes — els nostres jugadors provenen de" story_statistic_2b: "més de 190 països" story_statistic_3a: "Tots junts, han escrit" story_statistic_3b: "més d'un bilió de línies de codi" story_statistic_3c: "en molts idiomes de programació diferents" story_long_way_1: "Tot i que hem recorregut un llarg camí..." story_sketch_caption: "El primer esbós de Nick que representa un joc de programació en acció." story_long_way_2: "encara tenim molt per fer abans de completar la nostra recerca, així que..." jobs_title: "Vine a treballar amb nosaltres i ajuda'ns a escriure la història de CodeCombat!" jobs_subtitle: "No ho veus clar però t'interessa mantenir-te en contacte? Mira nostra \"Crea Tu Mateix\" llista." jobs_benefits: "Beneficis per l'empleat" jobs_benefit_4: "Vacances il·limitades" jobs_benefit_5: "Desenvolupament professional i suport a la formació contínua - llibres i jocs gratuïts!" jobs_benefit_6: "Metge (or), dental, visió, proximitat" jobs_benefit_7: "Taules amb seients per a tothom" jobs_benefit_9: "Finestra d'exercici opcional de 10 anys" jobs_benefit_10: "Permís de maternitat: paga 10 setmanes, les següents 6 al 55% de sou" jobs_benefit_11: "Permís de paternitat: paga 10 setmanes" jobs_custom_title: "Crea Tu Mateix" jobs_custom_description: "Estàs apassionat amb CodeCombat, però no veus una feina que coincideixi amb les teves qualitats? Escriu-nos i mostra'ns com creus que pots contribuir al nostre equip. Ens encantaria saber de tu!" jobs_custom_contact_1: "Envia'ns una nota a" jobs_custom_contact_2: "introduint-te i podrem contactar amb tu en el futur!" contact_title: "Premsa i Contacte" contact_subtitle: "Necessites més informació? Contacta amb nosaltres a" screenshots_title: "Captures de pantalla del joc" screenshots_hint: "(clica per veure a mida completa)" downloads_title: "Baixa Actius i Informació" about_codecombat: "Sobre CodeCombat" logo: "Logo" screenshots: "Captures de pantalla" character_art: "Art del personatge" download_all: "Baixa tot" previous: "Previ" location_title: "Ens trobem al centre de SF:" teachers: licenses_needed: "Calen llicències" special_offer: special_offer: "Oferta Especial" project_based_title: "Cursos basats en projectes" project_based_description: "Els cursos de desenvolupament web i jocs tenen projectes finals compartibles." great_for_clubs_title: "Ideal per a tallers i optatives" great_for_clubs_description: "Els professors poden comprar fins a __maxQuantityStarterLicenses__ llicències inicials." low_price_title: "Només __starterLicensePrice__ per alumne" low_price_description: "Les llicències inicials estan actives per __starterLicenseLengthMonths__ mesos a partir de la compra." three_great_courses: "Tres grans cursos inclosos a la Llicència inicial:" license_limit_description: "Els professors poden comprar fins a __maxQuantityStarterLicenses__ llicències inicials. Ja has comprat __quantityAlreadyPurchased__. Si necessites més, contacta amb __supportEmail__. Les Llicències inicials són vàlides per __starterLicenseLengthMonths__ mesos." student_starter_license: "Llicència inicial d'Estudiant" purchase_starter_licenses: "Compra les Llicències inicials" purchase_starter_licenses_to_grant: "Compra les Llicències inicials per donar accés a __starterLicenseCourseList__" starter_licenses_can_be_used: "Les Llicències inicials es poden usar per assignar cursos adicionals immediatament després de la compra." pay_now: "Paga ara" we_accept_all_major_credit_cards: "Acceptem la majoria de targetes de crèdit." cs2_description: "es basa en els fonaments de la Introducció a la informàtica, submergint-se en declaracions, funcions, esdeveniments i molt més." wd1_description: "introdueix els conceptes bàsics de l'HTML i el CSS, mentre ensenya les habilitats necessàries perquè els alumnes construeixin la seva primera pàgina web." gd1_description: "fa servir sintaxi molt familiar pels estudiants per mostrar-los com crear i compartir els seus propis jocs amb nivells." see_an_example_project: "vegeu un projecte d'exemple" get_started_today: "Comença avui mateix!" want_all_the_courses: "Vols tots els cursos? Sol·licita informació sobre les nostres llicències completes." compare_license_types: "Compara tipus de Llicències:" cs: "Ciències de la Computació" wd: "Desenvolupament web" wd1: "Desenvolupament web 1" gd: "Desenvolupament de jocs" gd1: "Desenvolupament de jocs 1" maximum_students: "Nombre màxim d'estudiants" unlimited: "Il·limitat" priority_support: "Suport prioritari" yes: "Sí" price_per_student: "__price__ per alumne" pricing: "Preus" free: "Gratuït" purchase: "Compra" courses_prefix: "Cursos" courses_suffix: "" course_prefix: "Curs" course_suffix: "" teachers_quote: subtitle: "Feu que els vostres estudiants comencin en menys d'una hora. Podràs <strong>crear una classe, afegir alumnes, i monitoritzar el seu progrés</strong> mentre aprenen informàtica." email_exists: "L'usuari existeix amb aquest correu electrònic." phone_number: "Número de telèfon" phone_number_help: "On podem trobar-te durant la jornada laboral?" primary_role_label: "El vostre rol principal" role_default: "Selecciona rol" primary_role_default: "Selecciona rol principal" purchaser_role_default: "Selecciona rol de comprador" tech_coordinator: "Coordinador de tecnologia" advisor: "Especialista / assessor de currículum" principal: "Director" superintendent: "Inspector" parent: "Pare" purchaser_role_label: "El teu rol de comprador" influence_advocate: "Influir/Optar" evaluate_recommend: "Evaluar/Recomanar" approve_funds: "Aprovació de fons" no_purchaser_role: "Cap rol en decisions de compra" district_label: "Districte" district_name: "Nom del Districte" district_na: "Poseu N/A si no és aplicable" organization_label: "Centre" school_name: "Nom de l'escola/institut" city: "Ciutat" state: "Província" country: "País" num_students_help: "Quants alumnes usaran CodeCombat?" num_students_default: "Selecciona Rang" education_level_label: "Nivell educatiu dels alumnes" education_level_help: "Trieu tants com calgui." elementary_school: "Primària" high_school: "Batxillerat/Mòduls" please_explain: "(per favor, explicar)" middle_school: "Secundària" college_plus: "Universitat o superior" referrer: "Com ens va conèixer?" referrer_help: "Per exemple: d'un altre professor, una conferència, els vostres estudiants, Code.org, etc." referrer_default: "Selecciona una" referrer_hoc: "Code.org/Hour of Code" referrer_teacher: "Un professor" referrer_admin: "Un administrador" referrer_student: "Un estudiant" referrer_pd: "Formacions / tallers professionals" referrer_web: "Google" referrer_other: "Altres" anything_else: "Amb quin tipus de classe preveus usar CodeCombat?" thanks_header: "Sol·licitud rebuda!" thanks_sub_header: "Gràcies per expressar l'interès en CodeCombat per al vostre centre." thanks_p: "Estarem en contacte aviat! Si necessiteu posar-vos en contacte, podeu contactar amb nosaltres a:" back_to_classes: "Torna a Classes" finish_signup: "Acaba de crear el vostre compte de professor:" finish_signup_p: "Creeu un compte per configurar una classe, afegir-hi els estudiants i supervisar el seu progrés a mesura que aprenen informàtica." signup_with: "Registreu-vos amb:" connect_with: "Connectar amb:" conversion_warning: "AVÍS: El teu compte actual és un <em>Compte estudiantil</em>. Un cop enviat aquest formulari, el teu compte s'actualitzarà a un compte del professor." learn_more_modal: "Els comptes de professors de CodeCombat tenen la capacitat de supervisar el progrés dels estudiants, assignar llicències i gestionar les aules. Els comptes de professors no poden formar part d'una aula: si actualment esteu inscrit en una classe amb aquest compte, ja no podreu accedir-hi una vegada que l'actualitzeu a un compte del professor." create_account: "Crear un compte de professor" create_account_subtitle: "Obteniu accés a les eines exclusives de professors per utilitzar CodeCombat a l'aula. <strong>Configura una classe</strong>, afegeix els teus alumnes, i <strong>supervisa el seu progrés</strong>!" convert_account_title: "Actualitza a compte del professor" not: "No" versions: save_version_title: "Guarda una nova versió" new_major_version: "Nova versió principal" submitting_patch: "S'està enviant el pedaç..." cla_prefix: "Per guardar els canvis primer has d'acceptar" cla_url: "CLA" cla_suffix: "." cla_agree: "Estic d'acord" owner_approve: "Un propietari ho haurà d'aprovar abans que els canvis es facin visibles." contact: contact_us: "Contacta CodeCombat" welcome: "Què bé poder escoltar-te! Fes servir aquest formulari per enviar-nos un email. " forum_prefix: "Per a qualsevol publicació, si us plau prova " forum_page: "el nostre fòrum" forum_suffix: " sinó" faq_prefix: "També pots mirar a les" faq: "Preguntes Freqüents" subscribe_prefix: "Si necessites ajuda per superar un nivell, si us plau" subscribe: "compra una subscripció de CodeCombat" subscribe_suffix: "i estarem encantats d'ajudar-te amb el teu codi." subscriber_support: "Com que seràs subscriptor de CodeCombat, el teu e-mail tindrà el nostre suport prioritari." screenshot_included: "Captura de pantalla inclosa." where_reply: "On hem de respondre?" send: "Enviar comentari" account_settings: title: "Configuració del compte" not_logged_in: "Inicia sessió o crea un compte per a canviar la configuració." me_tab: "Jo" picture_tab: "Foto" delete_account_tab: "Elimina el teu compte" wrong_email: "Correu erroni" wrong_password: "PI:PASSWORD:<PASSWORD>END_PI" delete_this_account: "Elimina aquest compte de forma permanent" reset_progress_tab: "Reinicia tot el progrés" reset_your_progress: "Reiniciar tot el progrés i començar de nou" god_mode: "Mode Déu" emails_tab: "Missatges" admin: "Administrador" manage_subscription: "Clica aquí per administrar la teva subscripció." new_password: "PI:PASSWORD:<PASSWORD>END_PI" new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI" type_in_email: "Escriu el teu e-mail o nom d'usuari per confirmar l'eliminació del compte." type_in_email_progress: "Escriu el teu correu electrònic per confirmar l'eliminació del teu progrés." type_in_password: "PI:PASSWORD:<PASSWORD>END_PI." email_subscriptions: "Subscripcions via correu electrònic" email_subscriptions_none: "Sense subsrcipcions de correu electrònic." email_announcements: "Notícies" email_announcements_description: "Rebre les últimes notícies i desenvolupaments de CodeCombat." email_notifications: "Notificacions" email_notifications_summary: "Controls per personalitzar les teves notificacions d'email automàtiques relacionades amb la teva activitat a CodeCombat." email_any_notes: "Cap notificació" email_any_notes_description: "Desactiva totes les notificacions via correu electrònic." email_news: "Noticies" email_recruit_notes: "Oportunitats de feina" email_recruit_notes_description: "Si jugues realment bé ens posarem en contacte amb tu per oferir-te feina." contributor_emails: "Subscripció als correus electrònics de cada classe" contribute_prefix: "Estem buscant gent que s'uneixi! Mira " contribute_page: "la pàgina de col·laboració" contribute_suffix: " per llegir més informació." email_toggle: "Activa-ho tot" error_saving: "Error en desar" saved: "Canvis desats" password_mismatch: "Les contrasenyes no coincideixen." password_repeat: "Siusplau, repetiu la contrasenya." keyboard_shortcuts: keyboard_shortcuts: "Dreceres del teclat" space: "Espai" enter: "Enter" press_enter: "prem Enter" escape: "Escape" shift: "Majúscula" run_code: "Executa el codi actual." run_real_time: "Executa en temps real." continue_script: "Continua passant l'script actual." skip_scripts: "Omet tots els scripts que es poden ometre." toggle_playback: "Commuta play/pausa." scrub_playback: "Mou-te enradere i endavant a través del temps." single_scrub_playback: "Mou-te enradere i endavant a través del temps pas a pas." scrub_execution: "Mou-te a través de l'execució de l'encanteri actual." toggle_debug: "Canvia la visualització de depuració." toggle_grid: "Commuta la superposició de la graella." toggle_pathfinding: "Canvia la superposició d'enfocament de camí." beautify: "Embelleix el teu codi estandarditzant el format." maximize_editor: "Maximitza/minimitza l'editor de codi." community: main_title: "Comunitat CodeCombat" introduction: "Consulta les maneres en que et pots implicar i decideix quina et sembla més divertida. Esperem treballar amb tu!" level_editor_prefix: "Usa CodeCombat" level_editor_suffix: "per crear i editar nivells. Els usuaris han creat nivells per a les seves classes, amics, festes de programació, estudiants i germans. Si crear un nou nivell sona intimidant pots començar picant un dels nostres!" thang_editor_prefix: "Anomenem 'thangs' a les unitats dintre del joc. Usa" thang_editor_suffix: "per modificar el codi d'origen de CoodeCombat. Permet que unitats llancin projectils, alterin l'orientació d'una animació, canvien els punts d'èxit d'una unitat o carreguin els vostres propis sprites vectorials." article_editor_prefix: "Veus errades en alguns dels nostres documents? Vols crear algunes instruccions per a les teves pròpies creacions? Prova amb" article_editor_suffix: "i ajuda als jugadors de CodeCombat a treure el màxim profit del seu temps de joc." find_us: "Troba'ns en aquests llocs" social_github: "Consulteu tot el nostre codi a GitHub" social_blog: "Llegiu el bloc de CodeCombat al setembre" social_discource: "Uneix-te a les discussions al nostre fòrum de comentaris" social_facebook: "Fes Like a CodeCombat en Facebook" social_twitter: "Segueix CodeCombat al Twitter" social_gplus: "Uneix-te a CodeCombat en Google+" social_slack: "Xateja amb nosaltres al canal públic CodeCombat Slack" contribute_to_the_project: "Contribueix al projecte" clans: # title: "Join CodeCombat Clans - Learn to Code in Python, JavaScript, and HTML" # clan_title: "__clan__ - Join CodeCombat Clans and Learn to Code" # meta_description: "Join a Clan or build your own community of coders. Play multiplayer arena levels and level up your hero and your coding skills." clan: "Clan" clans: "Clans" new_name: "Nou nom de clan" new_description: "Nova descripció de clan" make_private: "Fes el clan privat" subs_only: "només subscriptors" create_clan: "Crear un Nou Clan" private_preview: "Vista prèvia" private_clans: "Clans privats" public_clans: "Clans públics" my_clans: "Els meus Clans" clan_name: "Nom del Clan" name: "Nom" chieftain: "Capità" edit_clan_name: "Edita el nom del Clan" edit_clan_description: "Edita la descripció del Clan" edit_name: "edita el nom" edit_description: "edita la descripció" private: "(privat)" summary: "Resum" average_level: "Nivell Mitjà" average_achievements: "Mitjana de realitzacions" delete_clan: "Esborrar Clan" leave_clan: "Abandonar Clan" join_clan: "Unir-se al Clan" invite_1: "Invitar:" invite_2: "*Invita jugadors a aquest Clan tot enviant-los aquest enllaç." members: "Membres" progress: "Progrés" not_started_1: "no iniciat" started_1: "iniciat" complete_1: "complert" exp_levels: "Amplia els nivells" rem_hero: "Elimina l'heroi" status: "Estat" complete_2: "Complert" started_2: "Iniciat" not_started_2: "No Iniciat" view_solution: "Clica per veure la solució." view_attempt: "Clica per veure l'intent." latest_achievement: "Darrera Realització" playtime: "Temps de joc" last_played: "Darrer joc" leagues_explanation: "Participa en una lliga contra d'altres membres del clan en el camp de joc multijugador." track_concepts1: "Seguiment dels conceptes" track_concepts2a: "après per cada estudiant" track_concepts2b: "après per cada membre" track_concepts3a: "Seguiment dels nivells complets per a cada estudiant" track_concepts3b: "Seguiment dels nivells complets per a cada membre" track_concepts4a: "Mira com els teus alumnes" track_concepts4b: "Mira com els teus membres" track_concepts5: "ho han resolt" track_concepts6a: "Ordena alumnes per nom o progrés" track_concepts6b: "Ordena membres per nom o progrés" track_concepts7: "Requereix invitació" track_concepts8: "per unir-se" private_require_sub: "Els Clans Privats requereixen subscripció per crear-los o unir-se'n." courses: create_new_class: "Crear una Classe Nova" # hoc_blurb1: "Try the" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity! Construct four different minigames to learn the basics of game development, then make your own!" solutions_require_licenses: "Hi ha disponibles solucions de nivell per als professors que tenen llicències." unnamed_class: "Classe sense nom" edit_settings1: "Edita la configuració de la Classe" add_students: "Afegeix Alumnes" stats: "Estadístiques" student_email_invite_blurb: "Els teus alumnes també poden utilitzar el codi de la classe <strong>__classCode__</strong> quan creen un Compte Estudiantil, no és necessari e-mail." total_students: "Alumnes totals:" average_time: "Mitjana de temps de joc:" total_time: "Temps de joc total:" average_levels: "Mitjana de nivells assolits:" total_levels: "Nivells assolits totals:" students: "Alumnes" concepts: "Conceptes" play_time: "Temps de joc:" completed: "Assolit:" enter_emails: "Separa cada adreça e-mail amb un salt de línia o amb comes" send_invites: "Invita Alumnes" number_programming_students: "Nombre d'alumnes a Programació" number_total_students: "Alumnes totals al Centre/Districte" enroll: "Inscriure's" enroll_paid: "Inscriure els alumnes en cursos de pagament" get_enrollments: "Obteniu més llicències" change_language: "Canvia el Llenguatge del Curs" keep_using: "Segueix utilitzant" switch_to: "Canvia a" greetings: "Felicitats!" back_classrooms: "Torna a Les Meves Classes" back_classroom: "Torna a Classe" back_courses: "Torna a Els Meus Cursos" edit_details: "Edita els detalls de la classe" purchase_enrollments: "Compra Llicències Estudiantils" remove_student: "esborrar alumne" assign: "Assignar" to_assign: "per assignar cursos de pagament." student: "PI:NAME:<NAME>END_PI" teacher: "PI:NAME:<NAME>END_PI" arena: "Camp de joc" available_levels: "Nivells disponibles" started: "iniciat" complete: "completat" practice: "pràctica" required: "requerit" welcome_to_courses: "Aventurers, benvinguts als Cursos!" ready_to_play: "Preparats per jugar?" start_new_game: "Començar un Joc Nou" play_now_learn_header: "Juga ara per aprendre" play_now_learn_1: "sintaxi bàsica per controlar el teu personatge" play_now_learn_2: "bucles 'while' per resoldre molestos trencaclosques" play_now_learn_3: "cadenes i variables per personalitzar accions" play_now_learn_4: "com vèncer a un ogre (habilitats vitals importants!)" welcome_to_page: "el meu Tauler d'alumnat" my_classes: "Classes Actuals" class_added: "Classe afegida satisfactòriament!" # view_map: "view map" # view_videos: "view videos" view_project_gallery: "veure els projectes dels meus companys" join_class: "Uneix-te a una Classe" join_class_2: "Unir-se a una classe" ask_teacher_for_code: "Demana al teu professorat si té un codi de classe CodeCombat! Si el té, posa'l a continuació:" enter_c_code: "<Posa el Codi de Classe>" join: "Unir-se" joining: "Unint-se a la classe" course_complete: "Curs Complet" play_arena: "Terreny de joc" view_project: "Veure Projecte" start: "Començar" last_level: "Darrer nivell jugat" not_you: "No ets tu?" continue_playing: "Continua Jugant" option1_header: "Invita Alumnes via e-mail" remove_student1: "Esborra Alumnes" are_you_sure: "Estàs segur que vols esborrar aquest alumne d'aquesta classe?" remove_description1: "L'alumne perdrà l'accés a aquesta aula i a les classes assignades. El seu progrés i jocs NO es perdran, i l'alumne podrà tornar a ser afegit a l'aula en qualsevol moment." remove_description2: "No es retornarà la llicència de pagament activada." license_will_revoke: "La llicència de pagament d'aquest alumne serà revocada i restarà disponible per ésser assignada a qualsevol altre alumne." keep_student: "Mantenir l'alumne" removing_user: "Esborrant l'usuari" subtitle: "Reviseu els detalls i nivells del curs" # Flat style redesign changelog: "Veure els darrers canvis als nivells del curs." select_language: "Seleccionar idioma" select_level: "Seleccionar nivell" play_level: "Jugar Nivell" concepts_covered: "Conceptes treballats" view_guide_online: "Visions i solucions de nivell" grants_lifetime_access: "Concedeix accés a tots els cursos." enrollment_credits_available: "Llicències Disponibles:" language_select: "Tria un idioma" # ClassroomSettingsModal language_cannot_change: "L'Idioma no es podrà canviar una vegada l'alumnat s'uneixi a la classe." avg_student_exp_label: "Experiència mitjana de programació de l'alumnat" avg_student_exp_desc: "Això ens ajudarà a comprendre com fer els cursos millor." avg_student_exp_select: "Selecciona la millor opció" avg_student_exp_none: "Cap experiència - molt poca experiència" avg_student_exp_beginner: "Principiant - alguna vegada o programació mitjançant blocs" avg_student_exp_intermediate: "Intermig - alguna experiència amb codi escrit" avg_student_exp_advanced: "Advançat - experiència extensa amb codi escrit" avg_student_exp_varied: "Nivells variats d'experiència" student_age_range_label: "Rang d'edat de l'alumnat" student_age_range_younger: "MPI:NAME:<NAME>END_PI joves de 6" student_age_range_older: "MPI:NAME:<NAME>END_PI vells de 18" student_age_range_to: "a" # estimated_class_dates_label: "Estimated Class Dates" # estimated_class_frequency_label: "Estimated Class Frequency" # classes_per_week: "classes per week" # minutes_per_class: "minutes per class" create_class: "Crear Classe" class_name: "Nom de la Classe" teacher_account_restricted: "El teu compte és de professorat i no pots accedir al contingut de l'alumnat." account_restricted: "És necessari un compte estudiantil per accedir a aquesta plana." update_account_login_title: "Inicia sessió per actualitzar el teu compte" update_account_title: "El teu compte necessita atenció!" update_account_blurb: "Abans de poder accedir a les teves classes, tria com vols utilitzar aquest compte." update_account_current_type: "Tipus de compte actual:" update_account_account_email: "E-mail del compte/nom d'usuari:" update_account_am_teacher: "Sóc docent" update_account_keep_access: "Manteniu accés a les classes que he creat" update_account_teachers_can: "Els comptes de docent poden:" update_account_teachers_can1: "Crear/manegar/afegir classes" update_account_teachers_can2: "Assignar/donar d'alta alumnat als cursos" update_account_teachers_can3: "Desbloquejar tots els nivells dels cursos per provar-los" update_account_teachers_can4: "Accedir a noves característiques només per a docents de seguida que les creem" update_account_teachers_warning: "Atenció: Se t'esborrarà de toes les classes que anteriorment t'havies afegit i ja no podràs jugar com a alumne." update_account_remain_teacher: "PI:NAME:<NAME>END_PI com a docent" update_account_update_teacher: "CanPI:NAME:<NAME>END_PI a docent" update_account_am_student: "Sóc alumne/a" update_account_remove_access: "Esborrar l'accés a les classes que he creat" update_account_students_can: "Els comptes d'estudiant poden:" update_account_students_can1: "Unir-se a classes" update_account_students_can2: "Jugar en els cursos com a estudiant i seguir el teu propi progrés" update_account_students_can3: "Competir contra companys als camps de joc" update_account_students_can4: "Accedir a les noves característiques només per a alumnes de seguida que els creem" update_account_students_warning: "Atenció: No podràs manegar cap classe que hagis creat previament ni crear classes noves." unsubscribe_warning: "Atenció: Seràs esborrat de la subscripció mensual." update_account_remain_student: "Continua com a Alumne" update_account_update_student: "PI:NAME:<NAME>END_PI" need_a_class_code: "Necessitaràs un codi de Classe per la classe a la que et vols unir:" update_account_not_sure: "No saps quina triar? Envia un e-mail" update_account_confirm_update_student: "Estàs segur que vols canviar el teu compte a Alumnat?" update_account_confirm_update_student2: "No podràs manegar cap classe que hagis creat anteriorment ni crear classes noves. Les teves classes creades anteriorment s'esborraran de CodeCombat i no es podran recuperar." instructor: "Instructor: " youve_been_invited_1: "Has estat invitat a unir-te " youve_been_invited_2: ", on aprendràs " youve_been_invited_3: " amb els teus companys amb CodeCombat." by_joining_1: "Unint-se " by_joining_2: "podràs ajudar a restablir la teva contrasenya si la oblides o la perds. També podràs verificar la teva adreça e-mail i així reiniciar la contrasenya tu mateix!" sent_verification: "Hem enviat un e-mail de verificació a:" you_can_edit: "Pots editar el teu e-mail a " account_settings: "Configuració del Compte" select_your_hero: "Selecciona el teu Heroi" select_your_hero_description: "Sempre pots canviar el teu heroi anant a la plana Els Teus Cursos i fent clic a \"Canviar Heroi\"" select_this_hero: "Selecciona aquest Heroi" current_hero: "Heroi actual:" current_hero_female: "Heroïna actual:" web_dev_language_transition: "En aquest curs totes les classes programen en HTML / JavaScript. Les classes que han estat usant Python començaran amb uns nivells d'introducció extra de JavaScripts per fer la transició més fàcil. Les classes que ja usaven JavaScript ometran els nivells introductoris." course_membership_required_to_play: "T'has d'unir a un curs per jugar aquest nivell." license_required_to_play: "Demana al teu professorat que t'assigni una llicència per continuar jugant a CodeCombat!" update_old_classroom: "Nou curs escolar, nous nivells!" update_old_classroom_detail: "Per assegurar-se que estàs obtenint els nivells actualitzats, comprova haver creat una classe nova per aquest semestre clicant Crear una Classe Nova al teu" teacher_dashboard: "taulell del professorat" update_old_classroom_detail_2: "i donant a l'alumnat el nou Codi de Classe que apareixerà." view_assessments: "Veure Avaluacions" view_challenges: "veure els nivells de desafiament" challenge: "Desafiament:" challenge_level: "Nivell de Desafiament:" status: "Estat:" assessments: "Avaluacions" challenges: "Desafiaments" level_name: "Nom del nivell:" keep_trying: "Continua intentant" start_challenge: "Començar el Desafiament" locked: "Bloquejat" concepts_used: "Conceptes Usats:" show_change_log: "Mostra els canvis als nivells d'aquest curs" hide_change_log: "Amaga els canvis als nivells d'aquest curs" # concept_videos: "Concept Videos" # concept: "Concept:" # basic_syntax: "Basic Syntax" # while_loops: "While Loops" # variables: "Variables" # basic_syntax_desc: "Syntax is how we write code. Just as spelling and grammar are important in writing narratives and essays, syntax is important when writing code. Humans are good at figuring out what something means, even if it isn't exactly correct, but computers aren't that smart, and they need you to write very precisely." # while_loops_desc: "A loop is a way of repeating actions in a program. You can use them so you don't have to keep writing repetitive code, and when you don't know exactly how many times an action will need to occur to accomplish a task." # variables_desc: "Working with variables is like organizing things in shoeboxes. You give the shoebox a name, like \"School Supplies\", and then you put things inside. The exact contents of the box might change over time, but whatever's inside will always be called \"School Supplies\". In programming, variables are symbols used to store data that will change over the course of the program. Variables can hold a variety of data types, including numbers and strings." # locked_videos_desc: "Keep playing the game to unlock the __concept_name__ concept video." # unlocked_videos_desc: "Review the __concept_name__ concept video." # video_shown_before: "shown before __level__" # link_google_classroom: "Link Google Classroom" # select_your_classroom: "Select Your Classroom" # no_classrooms_found: "No classrooms found" # create_classroom_manually: "Create classroom manually" # classes: "Classes" project_gallery: no_projects_published: "Sigues el primer en publicar un projecte en aquest curs!" view_project: "Veure Projecte" edit_project: "Editar Projecte" teacher: assigning_course: "Assignant curs" back_to_top: "Tornar a l'inici" click_student_code: "Feu clic a qualsevol nivell que l'alumne hagi començat o completat a continuació per veure el codi que va escriure." code: "Codi d'en/na __name__" complete_solution: "Solució Completa" course_not_started: "L'alumnat encara no ha començat aquest curs." # appreciation_week_blurb1: "For <strong>Teacher Appreciation Week 2019</strong>, we are offering free 1-week licenses!<br />Email PI:NAME:<NAME>END_PI (<a href=\"mailto:PI:EMAIL:<EMAIL>END_PI?subject=Teacher Appreciation Week\">PI:EMAIL:<EMAIL>END_PI</a>) with subject line \"<strong>Teacher Appreciation Week</strong>\", and include:" # appreciation_week_blurb2: "the quantity of 1-week licenses you'd like (1 per student)" # appreciation_week_blurb3: "the email address of your CodeCombat teacher account" # appreciation_week_blurb4: "whether you'd like licenses for Week 1 (May 6-10) or Week 2 (May 13-17)" # hoc_happy_ed_week: "Happy Computer Science Education Week!" # hoc_blurb1: "Learn about the free" # hoc_blurb2: "Code, Play, Share" # hoc_blurb3: "activity, download a new teacher lesson plan, and tell your students to log in to play!" # hoc_button_text: "View Activity" no_code_yet: "L'alumnat encara no ha escrit cap codi en aquest nivell." open_ended_level: "Nivell obert" partial_solution: "Solució Parcial" removing_course: "Esborrant curs" solution_arena_blurb: "Es recomana a l'alumnat que resolgui els nivells del camp de joc amb creativitat. La solució que es proporciona a continuació compleix els requisits del nivell del camp de joc." solution_challenge_blurb: "Es recomana a l'alumnat que resolgui els nivells de desafiament obert amb creativitat. Una possible solució es mostra a continuació." solution_project_blurb: "Es recomana a l'alumnat que construeixi un projecte creatiu en aquest nivell. La solució que es proporciona a continuació compleix els requisits del nivell del projecte." students_code_blurb: "Es proporcionarà una solució correcta per a cada nivell, quan correspongui. En alguns casos, és possible que un estudiant resolgui un nivell amb un codi diferent. No es mostren solucions per als nivells que l'alumne no ha iniciat." course_solution: "Solució del curs" level_overview_solutions: "Visió general del nivell i solucions" no_student_assigned: "No s'ha assignat cap alumnat a aquest curs." paren_new: "(nou)" student_code: "Codi d'alumnat de __name__" teacher_dashboard: "Taulell del Professorat" # Navbar my_classes: "Les Meves Classes" courses: "Guies dels Cursos" enrollments: "Llicències d'Alumnat" resources: "Recursos" help: "Ajuda" language: "Idioma" edit_class_settings: "edita la configuració de la classe" access_restricted: "Actualització del compte obligatori" teacher_account_required: "Es requereix un compte de professorat per accedir a aquest contingut." create_teacher_account: "Crear un compte de professorat" what_is_a_teacher_account: "Què és un Compte de Professorat?" teacher_account_explanation: "Un compte de professorat CodeCombat et permet configurar aules, veure el progrés de l'alumnat mentre van fent els cursos, administrar llicències i accedir a recursos per ajudar-te en la creació de currículums." current_classes: "Classes actuals" archived_classes: "Classes arxivades" archived_classes_blurb: "Les Classes es poden arxivar per referències futures. Desarxiva una classe per veure-la de nou a la llista actual de Classes." view_class: "veure classe" archive_class: "arxivar classe" unarchive_class: "desarxivar classe" unarchive_this_class: "Desarxiva aquesta classe" no_students_yet: "Aquesta classe encara no té alumnes." no_students_yet_view_class: "Veure classe per afegir alumnes." try_refreshing: "(És possible que hàgiu d'actualitzar la pàgina)" create_new_class: "Crear una Classe Nova" class_overview: "Descripció de la classe" # View Class page avg_playtime: "Mitjana de temps de joc del nivell" total_playtime: "Temps de joc total" avg_completed: "Mitjana de nivells assolits" total_completed: "Total de nivells assolits" created: "Creat" concepts_covered: "Conceptes tractats" earliest_incomplete: "Primer nivell incomplet" latest_complete: "Darrer nivell assolit" enroll_student: "Inscriure l'estudiant" apply_license: "Aplicar Llicència" revoke_license: "Revocar Llicència" revoke_licenses: "Revocar Totes les llicències" course_progress: "Progrés del curs" not_applicable: "N/A" edit: "edita" edit_2: "Edita" remove: "esborra" latest_completed: "Darrer assolit:" sort_by: "Ordena per" progress: "Progrés" concepts_used: "Conceptes emprats per Alumnat:" concept_checked: "Concepte verificat:" completed: "Assolit" practice: "Practica" started: "Iniciat" no_progress: "Cap progrés" not_required: "No requerit" view_student_code: "Fes clic per veure el codi d'alumnat" select_course: "Selecciona el curs per veure'PI:NAME:<NAME>END_PI" progress_color_key: "Codi de colors de progrés:" level_in_progress: "Nivell en Progrés" level_not_started: "Nivell no Iniciat" project_or_arena: "Projecte o Terreny de Joc" students_not_assigned: "Alumnat que no ha estat assignat {{courseName}}" course_overview: "Descripció general del curs" copy_class_code: "Copiar Codi de Classe" class_code_blurb: "L'alumnat pot unir-se a la teva classe amb aquest Codi de Classe. No és neessari cap adreça e-mail per crear un Compte d'Estudiant amb aquest Codi de Classe." copy_class_url: "Copiar URL de la Classe" class_join_url_blurb: "També pots posar aquesta URL única d'aquesta classe en una plana web compartida." add_students_manually: "Invitar Alumnes per e-mail" bulk_assign: "Seleccionar curs" assigned_msg_1: "{{numberAssigned}} alumnes s'han assignat a {{courseName}}." assigned_msg_2: "{{numberEnrolled}} llicències s'han utilitzat." assigned_msg_3: "Ara teniu {{remainingSpots}} llicències restants disponibles." assign_course: "Assignar Curs" removed_course_msg: "{{numberRemoved}} alumnes s'han esborrat de {{courseName}}." remove_course: "Esborrar Curs" not_assigned_modal_title: "Els cursos no es van assignar" not_assigned_modal_starter_body_1: "Aquest curs requereix Llicències Inicials. No tens suficients Llicències Inicials disponibles per assignar aquest curs a tots els __selected__ alumnes seleccionats." not_assigned_modal_starter_body_2: "Compra Llicències Inicials per garantir l'accés a aquest curs." not_assigned_modal_full_body_1: "Aquest curs requereix Llicències Totals. No tens suficients Llicències Totals disponibles per assignar aquest curs a tots els __selected__ alumnes seleccionats." not_assigned_modal_full_body_2: "Només tens __numFullLicensesAvailable__ Llicències Totals disponibles (__numStudentsWithoutFullLicenses__ alumnes no tenen encara Llicències Totals actives)." not_assigned_modal_full_body_3: "Si us plau selecciona menys alumnes, o demana ajuda a __supportEmail__." assigned: "Assignats" enroll_selected_students: "Inscriviu l'alumnat seleccionat" no_students_selected: "No s'ha seleccionat cap alumne." show_students_from: "Mostrar alumnat de" # Enroll students modal apply_licenses_to_the_following_students: "Otorgar Llicències als següents Alumnes" students_have_licenses: "Els següents alumnes ja tenen llicències otorgades:" all_students: "Tots els Alumnes" apply_licenses: "Otorgar Llicències" not_enough_enrollments: "No n'hi han suficients llicències." enrollments_blurb: "Als alumnes se'ls demana tenir una llicència per accedir a qualsevol contingut després del primer curs." how_to_apply_licenses: "Com otorgar llicències" export_student_progress: "Exportar el Progrés de l'Alumnat (CSV)" send_email_to: "Envieu Recuperar contrasenya per e-mail a:" email_sent: "E-mail enviat" send_recovery_email: "Enviar e-mail de recuperació" enter_new_password_below: "Introduïu una contrasenya nova a continuació:" change_password: "PI:PASSWORD:<PASSWORD>END_PI" changed: "Canviada" available_credits: "Llicències disponibles" pending_credits: "Llicències pendents" empty_credits: "Llicències gastades" license_remaining: "llicència restant" licenses_remaining: "llicències restants" one_license_used: "1 llicència s'ha usat" num_licenses_used: "__numLicensesUsed__ llicències s'han usat" starter_licenses: "llicències inicials" start_date: "data d'inici:" end_date: "data d'acabament:" get_enrollments_blurb: " Us ajudarem a construir una solució que satisfaci les necessitats de la vostra classe, escola o districte." how_to_apply_licenses_blurb_1: "Quan un professor assigni un curs a un estudiant per primera vegada, aplicarem automàticament una llicència. Utilitzau el menú desplegables d'assignació massiva a la vostra aula per assignar un curs als alumnes selececionats:" how_to_apply_licenses_blurb_2: "Puc aplicar una llicència encara que no hagi assignat un curs?" how_to_apply_licenses_blurb_3: "Sí — ves a l'etiqueta Estat de les Llicències a la teva aula i fes clic a \"Aplicar Llicència\" a qualsevol alumne que no tingui una llicència activa." request_sent: "Petició enviada!" assessments: "Avaluacions" license_status: "Estat de les Llicències" status_expired: "Caducada el {{date}}" status_not_enrolled: "No inscrit" status_enrolled: "Caduca el {{date}}" select_all: "Selecciona Tot" project: "Projecte" project_gallery: "Galeria de Projectes" view_project: "Veure Projecte" unpublished: "(no publicades)" view_arena_ladder: "Veure escala del camp de joc" resource_hub: "Centre de recursos" pacing_guides: "Guies tot-en-un de l'aula" pacing_guides_desc: "Aprendre com incorporar tots els recursos de CodeCombat per planificar el teu curs escolar!" pacing_guides_elem: "Guia pas a pas d'una Escola de Primària" pacing_guides_middle: "Guia pas a pas d'una Escola de Secundària" pacing_guides_high: "Guia pas a pas d'un Centre d'Estudis Postobligatoris" getting_started: "Començant" educator_faq: "Preguntes freqüents de Docents" educator_faq_desc: "Preguntes habituals sobre l'ús de CodeCombat a la teva aula o al teu centre." teacher_getting_started: "Guia d'introducció per a docents" teacher_getting_started_desc: "Ets nou a CodeCombat? Descarrega aquesta Guia d'introducció per a docents per configurar el teu compte, crear la teva primera classe, i invitar alumnat al primer curs." student_getting_started: "Guia d'introducció per l'alumnat" student_getting_started_desc: "Pots distribuir aquesta guia al teu alumnat abans de començar amb CodeCombat per a que es puguin anar familiaritzant amb l'editor de codi. Aquesta guis serveix tant per classes de Python com de JavaScript." ap_cs_principles: "AP Principis d'informàtica" ap_cs_principles_desc: "AP Principis d'informàtica dona als estudiants una àmplia introducció al poder, l'impacte i les possibilitats de la informàtica. El curs fa èmfasi en el pensament computacional i la resolució de problemes, a més d'ensenyar els fonaments de la programació." cs1: "Introducció a la informàtica" cs2: "Informàtica 2" cs3: "Informàtica 3" cs4: "Informàtica 4" cs5: "Informàtica 5" cs1_syntax_python: "Guia de sintaxi de Python del curs 1" cs1_syntax_python_desc: "Full de trucs amb referències a la sintaxi comuna de Python que els estudiants aprendran en Introducció a la informàtica." cs1_syntax_javascript: "Guia de sintaxi de JavaScript del curs 1" cs1_syntax_javascript_desc: "Full de trucs amb referències a la sintaxi comuna de JavaScript que els estudiants aprendran en Introducció a la informàtica." coming_soon: "Guies addicionals properament!" engineering_cycle_worksheet: "Full de cicle d'enginyeria" engineering_cycle_worksheet_desc: "Utilitzeu aquest full de càlcul per ensenyar als estudiants els conceptes bàsics del cicle d'enginyeria: Avaluar, dissenyar, implementar i depurar. Consulteu el full de càlcul de l'exemple complet com a guia." engineering_cycle_worksheet_link: "Mostra l'exemple" progress_journal: "Diari de progrés" progress_journal_desc: "Anima els estudiants a fer un seguiment del progrés a través d'un diari de progrés." cs1_curriculum: "Introducció a la informàtica - Guia del currículum" cs1_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 1." arenas_curriculum: "Nivells del camp de joc - Guia dels professors" arenas_curriculum_desc: "Instruccions sobre com usar els camps de joc multijugadors Wakka Maul, Cross Bones i Power Peak amb les teves classes." # assessments_curriculum: "Assessment Levels - Teacher Guide" # assessments_curriculum_desc: "Learn how to use Challenge Levels and Combo Challenge levels to assess students' learning outcomes." cs2_curriculum: "Informàtica 2 - Guia del currículum" cs2_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 2." cs3_curriculum: "Informàtica 3 - Guia del currículum" cs3_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 3." cs4_curriculum: "Informàtica 4 - Guia del currículum" cs4_curriculum_desc: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 4." cs5_curriculum_js: "Informàtica 5 - Guia del currículum (JavaScript)" cs5_curriculum_desc_js: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 5 fent servir JavaScript." cs5_curriculum_py: "Informàtica 5 - Guia del currículum (Python)" cs5_curriculum_desc_py: "Àmbit i seqüència, planificació de classes, activitats i molt més per al curs 5 fent servir Python." cs1_pairprogramming: "Activitat de programació en parelles" cs1_pairprogramming_desc: "Introduir els estudiants a un exercici de programació en parelles que els ajudarà a ser millors oients i comunicadors." gd1: "Desenvolupament del Joc 1" gd1_guide: "Desenvolupament del Joc 1 - Guia del Projecte" gd1_guide_desc: "Utilitzeu això per guiar els vostres estudiants a mesura que creen el primer projecte de joc compartit en 5 dies." gd1_rubric: "Desenvolupament del Joc 1 - Rúbrica del Project" gd1_rubric_desc: "Utilitza aquesta rúbrica per avaluar els projectes dels alumnes al final de Desenvolupament del Joc 1." gd2: "Desenvolupament del Joc 2" gd2_curriculum: "Desenvolupament del Joc 2 - Guia del Currículum" gd2_curriculum_desc: "Planificació de classes per Desenvolupament del Joc 2." gd3: "Desenvolupament del Joc 3" gd3_curriculum: "Desenvolupament del Joc 3 - Guia del Currículum" gd3_curriculum_desc: "Planificació de classes per Desenvolupament del Joc 3." wd1: "Desenvolupament Web 1" wd1_curriculum: "Desenvolupament Web 1 - Guia del Currículum" wd1_curriculum_desc: "Planificació de classes per Desenvolupament Web 1." # {change} wd1_headlines: "Activitats amb Titulars i Encapçalaments" wd1_headlines_example: "Veure un exemple de solució" wd1_headlines_desc: "Per què són importants els paràgrafs i les etiquetes de capçalera? Utilitzeu aquesta activitat per mostrar com els encapçalaments ben escollits fan que les pàgines web siguin més fàcils de llegir. Hi ha moltes solucions correctes per a això." wd1_html_syntax: "Guia de sintaxi HTML" wd1_html_syntax_desc: "Referència d'una pàgina per a l'estil HTML que els estudiants aprendran en el Desenvolupament Web 1." wd1_css_syntax: "Guia de sintaxi CSS" wd1_css_syntax_desc: "Referència d'una pàgina per a la sintaxi CSS i Style que els estudiants aprendran en el Desenvolupament Web 1." wd2: "Desenvolupament Web 2" wd2_jquery_syntax: "Guia de sintaxi de funcions jQuery" wd2_jquery_syntax_desc: "Referència d'una pàgina per a les funcions jQuery que els estudiants aprendran en el Desenvolupament Web 2." wd2_quizlet_worksheet: "Full de càlcul de planificació del Qüestionari" wd2_quizlet_worksheet_instructions: "Veure instruccions i exemples" wd2_quizlet_worksheet_desc: "Abans que els vostres estudiants construeixin el seu projecte de qüestionació de personalitat al final del Desenvolupament web 2, haurien de planificar les preguntes, els resultats i les respostes del qüestionari utilitzant aquest full de càlcul. Els professors poden distribuir les instruccions i els exemples als quals es refereixen els estudiants." student_overview: "Resum" student_details: "Detalls dels alumnes" student_name: "PI:NAME:<NAME>END_PI" no_name: "No es proporciona cap nom." no_username: "No s'ha proporcionat cap nom d'usuari." no_email: "L'estudiant no té una adreça electrònica configurada." student_profile: "Perfil de l'estudiant" playtime_detail: "Detall del temps de joc" student_completed: "Estudiants completats" student_in_progress: "Estudiant en curs" class_average: "Mitjana de classe" not_assigned: "No s'ha assignat els cursos següents" playtime_axis: "Temps de joc en segons" levels_axis: "Nivells en" student_state: "Com està " student_state_2: " fent?" student_good: "ho està fent bé a" student_good_detail: "Aquest alumne manté el ritme de la classe." student_warn: "podria necessitar ajuda en" student_warn_detail: "Aquest estudiant pot necessitar ajuda amb els nous conceptes que s'han introduït en aquest curs." student_great: "ho està fent molt bé a" student_great_detail: "Aquest estudiant pot ser un bon candidat per ajudar altres estudiants que iintentin fer aquest curs." full_license: "Llicència Total" starter_license: "Llicència Inicial" trial: "Prova" hoc_welcome: "Feliç setmana de l'aprenentatge d'Informàtica" # hoc_title: "Hour of Code Games - Free Activities to Learn Real Coding Languages" # hoc_meta_description: "Make your own game or code your way out of a dungeon! CodeCombat has four different Hour of Code activities and over 60 levels to learn code, play, and create." hoc_intro: "Hi ha tres maneres per a que la vostra classe participi en Hora del Codi amb CodeCombat" hoc_self_led: "Joc d'autoaprenentatge" hoc_self_led_desc: "Els alumnes poden accedir a dues hores de tutorials de CodeCombat per compte propi" hoc_game_dev: "Desenvolupament de Jocs" hoc_and: "i" hoc_programming: "Programació en JavaScript/Python" hoc_teacher_led: "Lliçons magistrals" hoc_teacher_led_desc1: "Baixa't la nostra" hoc_teacher_led_link: "planificació de lliçons sobre Introducció a la Informàtica" hoc_teacher_led_desc2: "per introduir els vostres estudiants en conceptes de programació utilitzant activitats fora de línia" hoc_group: "Joc Grupal" hoc_group_desc_1: "Els professors poden utilitzar les lliçons juntament amb el nostre curs de Introducció a la informàtica per fer un seguiment del progrés dels estudiants. Mira la nostra" hoc_group_link: "Guia d'introducció" hoc_group_desc_2: "per més detalls" hoc_additional_desc1: "Per a recursos i activitats addicionals de CodeCombat, minar les nostres" hoc_additional_desc2: "Preguntes" hoc_additional_contact: "Posar-se en contacte" revoke_confirm: "Estàs segur que vols revocar una llicència total de {{student_name}}? La llicència restarà disponible per assignar-la a un altre estudiant." revoke_all_confirm: "Estàs segur que vols revocar les llicències totals de tots els estudiants d'aquesta classe?" revoking: "Revocant..." unused_licenses: "Teniu llicències no utilitzades que us permeten assignar cursos pagats pels estudiants quan estiguin preparats per obtenir més informació!" remember_new_courses: "Recorda assignar nous cursos!" more_info: "Més informació" how_to_assign_courses: "Com assignar cursos" select_students: "Seleccionar Alumnes" select_instructions: "Feu clic a la casella de verificació al costat de cada alumne al qual voleu assignar els cursos." choose_course: "Tria Curs" choose_instructions: "Seleccioneu el curs des del menú desplegable que vulgueu assignar, i després feu clic a “Assigna als Alumnes Seleccionats.”" push_projects: "Es recomana assignar Desenvolupament web 1 o Desenvolupament de jocs 1 després que els alumnes hagin acabat la Introducció a la informàtica! Veure el nostre {{resource_hub}} per més detalls sobre aquests cursos." teacher_quest: "Missió del Docent per tenir èxit" quests_complete: "Missió Complerta" teacher_quest_create_classroom: "Crear un aula" teacher_quest_add_students: "Afegir l'alumnat" teacher_quest_teach_methods: "Ajudar el teu alumnat a aprendre com `cridar mètodes`." teacher_quest_teach_methods_step1: "Tenir el 75% com a mínim d'una classe amb el primer nivell passat, __Dungeons of Kithgard__" teacher_quest_teach_methods_step2: "Imprimir la [Guia d'introducció per l'alumnat](http://files.codecombat.com/docs/resources/StudentQuickStartGuide.pdf) del Centre de Recursos." teacher_quest_teach_strings: "No encadenar els teus alumnes junts, ensenya'ls `cadenes`." teacher_quest_teach_strings_step1: "Tenir el 75% com a mínim d'una classe amb __True Names__ passat" teacher_quest_teach_strings_step2: "Usar el Selector de Nivells del Professorat a la plana [Guies del Curs](/teachers/courses) per tenir una vista prèvia de __True Names__." teacher_quest_teach_loops: "Mantenir els alumnes en el bucle sobre els `bucles`." teacher_quest_teach_loops_step1: "Tenir el 75% com a mínim d'una classe amb __Fire Dancing__ passat." teacher_quest_teach_loops_step2: "Usar el __Loops Activity__ en la [CS1 Guia del Currículum](/teachers/resources/cs1) per reforçar aquest concepte." teacher_quest_teach_variables: "Variar-los amb les `variables`." teacher_quest_teach_variables_step1: "Tenir el 75% com a mínim d'una classe amb __Known Enemy__ passat." teacher_quest_teach_variables_step2: "Fomentar la col·laboració utilitzant l'[Activitat de Programació per parelles](/teachers/resources/pair-programming)." teacher_quest_kithgard_gates_100: "Escapar de les portes de Kithgard amb la teva classe." teacher_quest_kithgard_gates_100_step1: "Tenir el 75% com a mínim d'una classe amb __Kithgard Gates__ passat." teacher_quest_kithgard_gates_100_step2: "Guiar l'alumnat per pensar en problemes difícils usant el [Full de cicle d'enginyeria](http://files.codecombat.com/docs/resources/EngineeringCycleWorksheet.pdf)." teacher_quest_wakka_maul_100: "Preparar pel duel a Wakka Maul." teacher_quest_wakka_maul_100_step1: "Tenir el 75% com a mínim d'una classe amb __Wakka Maul__ passat." teacher_quest_wakka_maul_100_step2: "Veure la [Guia del Camp de Joc](/teachers/resources/arenas) al [Centre de Recursos](/teachers/resources) per trobar idees sobre com fer un joc de camp amb èxit." teacher_quest_reach_gamedev: "Explora nous móns!" teacher_quest_reach_gamedev_step1: "[Aconsegueix llicències](/teachers/licenses) per a que els teus alumnes puguin explorar nous móns, com ara Desenvolupament de jocs i Desenvolupament de Webs!" teacher_quest_done: "Encara volen aprendre més codi els teus alumnes? Posa't en contacte avui mateix amb els nostres [especialistes escolars](mailto:PI:EMAIL:<EMAIL>END_PI)!" teacher_quest_keep_going: "Segueix endavant! A continuació t'indiquem què pots fer:" teacher_quest_more: "Veure totes les missions" teacher_quest_less: "Veure menys missions" refresh_to_update: "(actualitzeu la pàgina per veure les actualitzacions)" view_project_gallery: "Mostra la Galeria de Projectes" office_hours: "Seminari de Professorat" office_hours_detail: "Apreneu a mantenir-se al dia amb els vostres estudiants a mesura que creen jocs i s'embarquen en el seu viatge de codificació! Assisteix a les nostres" office_hours_link: "sessions de Seminari de Professorat" office_hours_detail_2: "." success: "Èxit" in_progress: "En Progrés" not_started: "No Iniciat" mid_course: "Mig Curs" end_course: "Fi del Curs" none: "Cap detectat encara" explain_open_ended: "Nota: Es recomana als estudiants que resolguin aquest nivell de forma creativa, a continuació es proporciona una possible solució." level_label: "Nivell:" time_played_label: "Temps jugat:" back_to_resource_hub: "Tornar al Centre de Recursos" back_to_course_guides: "Tornar a les Guies del Curs" print_guide: "Imprimir aquesta guia" combo: "Combinat" combo_explanation: "Els estudiants passen els nivells de desafiament combinat utilitzant com a mínim un concepte enumerat. Reviseu el codi de l'alumne fent clic al punt de progrés." concept: "Concepte" # sync_google_classroom: "Sync Google Classroom" share_licenses: share_licenses: "Compartir llicències" shared_by: "Compartida amb:" add_teacher_label: "Introduïu el correu electrònic del professorat exacte:" add_teacher_button: "Afegir professorat" subheader: "Podeu fer que les vostres llicències estiguin disponibles per a altres professors de la vostra organització. Cada llicència només es pot utilitzar per a un estudiant a la vegada." teacher_not_found: "No s'ha trobat el professor. Assegureu-vos que aquest professor ja ha creat un compte de professor." teacher_not_valid: "Aquest no és un compte de professor vàlid. Només els comptes de professors poden compartir llicències." already_shared: "Ja heu compartit aquestes llicències amb aquest professor." teachers_using_these: "Professors que poden accedir a aquestes llicències:" footer: "Quan els professors revocuen llicències dels estudiants, les llicències es retornaran al grup compartit d'altres professors d'aquest grup per utilitzar-les." you: "(tu)" one_license_used: "(1 llicència utilitzada)" licenses_used: "(__licensesUsed__ llicències utilitzades)" more_info: "Més informació" sharing: game: "Joc" webpage: "Plana Web" your_students_preview: "Els vostres alumnes faran clic aquí per veure els projectes acabats! No disponible a la previsualització del professor." unavailable: "L'intercanvi d'enllaços no està disponible a la previsualització del professor." share_game: "Comparteix aquest joc" share_web: "Comparteix aquesta Plana Web" victory_share_prefix: "Comparteix aquest enllaç per convidar els teus amics i família a" victory_share_prefix_short: "Convida gent a" victory_share_game: "jugar al teu joc" victory_share_web: "veure la teva plana web" victory_share_suffix: "." victory_course_share_prefix: "Aquest enllaç permetrà als teus amics i família" victory_course_share_game: "jugar al joc" victory_course_share_web: "veure la plana web" victory_course_share_suffix: "que acabes de crear." copy_url: "Copiar URL" share_with_teacher_email: "Enviar al teu professor/a" game_dev: creator: "Creador" web_dev: image_gallery_title: "Galeria d'imatges" select_an_image: "Selecciona la imatge que vulguis utilitzar" scroll_down_for_more_images: "(Desplaceu-vos cap avall per obtenir més imatges)" copy_the_url: "Copieu l'URL següent" copy_the_url_description: "Útil si voleu reemplaçar una imatge existent." copy_the_img_tag: "Copieu l'etiqueta <img>" copy_the_img_tag_description: "Útil si voleu inserir una imatge nova." copy_url: "Copiar URL" copy_img: "Copiar <img>" how_to_copy_paste: "Com Copiar/Pegar" copy: "Copiar" paste: "Pegar" back_to_editing: "Tornar a Editar" classes: archmage_title: "Arximag" archmage_title_description: "(Programador)" archmage_summary: "Si ets un programador interessat en els jocs educatius sigues un arximag i ajuda'ns a construir CodeCombat!" artisan_title: "Artesà" artisan_title_description: "(Creador de nivells)" artisan_summary: "Construeix i comparteix nivells per als teus amics. Sigues un Artesà per aprendre l'art d'ensenyar als altres a programar." adventurer_title: "Aventurer" adventurer_title_description: "(Provador de nivells)" adventurer_summary: "Accedeix als nostres nivells (fins i tot el contingut de pagament) una setmana abans i gratuïtament i ajuda'ns a descobrir errors abans que siguin públics." scribe_title: "Escriba" scribe_title_description: "(Editor d'articles)" scribe_summary: "Un bon codi necessita una bona documentació. Escriu, edita i millora els documents que són llegits per milions de jugadors arreu del món." diplomat_title: "Diplomàtic" diplomat_title_description: "(Traductor)" diplomat_summary: "CodeCombat s'està traduint a més de 45 idiomes pels nostres Displomàtics. Ajuda'ns a traduir!" ambassador_title: "Ambaixador" ambassador_title_description: "(Suport)" ambassador_summary: "Posar ordre als fòrums i respondre a les preguntes que sorgeixin. Els nostres Ambaixadors representen a CodeCombat envers el món." teacher_title: "PI:NAME:<NAME>END_PI" editor: main_title: "Editors de CodeCombat" article_title: "Editor d'articles " thang_title: "Editor de Thang" level_title: "Editor de nivells" course_title: "Editor de Cursos" achievement_title: "Editor de triomfs" poll_title: "Editor d'Enquestes" back: "Enrere" revert: "Reverteix" revert_models: "Reverteix Models" pick_a_terrain: "Tria un Terreny" dungeon: "Masmorra" indoor: "Interior" desert: "Desert" grassy: "Herba" mountain: "Muntanya" glacier: "Glaciar" small: "Petit" large: "Gran" fork_title: "Nova versió Bifurcació" fork_creating: "Creant bifurcació..." generate_terrain: "Generar Terreny" more: "Més" wiki: "Wiki" live_chat: "Xat en directe" thang_main: "Principal" thang_spritesheets: "Capes" thang_colors: "Colors" level_some_options: "Algunes opcions?" level_tab_thangs: "Thangs" level_tab_scripts: "Escripts" level_tab_components: "Components" level_tab_systems: "Sistemes" level_tab_docs: "Documentació" level_tab_thangs_title: "Thangs actuals" level_tab_thangs_all: "Tot" level_tab_thangs_conditions: "Condicions Inicials" level_tab_thangs_add: "Afegeix Thangs" level_tab_thangs_search: "Cerca thangs" add_components: "Afegir Components" component_configs: "Configuracions de Components" config_thang: "Fes doble clic per configurar un thang" delete: "Esborrar" duplicate: "Duplicar" stop_duplicate: "Atura el duplicat" rotate: "Rotar" level_component_tab_title: "Components actuals" level_component_btn_new: "Crear Nou Component" level_systems_tab_title: "Sistemes actuals" level_systems_btn_new: "Crea un nou sistema" level_systems_btn_add: "Afegir sistema" level_components_title: "Torna a Tots els Thangs" level_components_type: "Escriu" level_component_edit_title: "Edita Component" level_component_config_schema: "Esquema de configuració" level_system_edit_title: "Editar sistema" create_system_title: "Crea un nou sistema" new_component_title: "Crea un nou Component" new_component_field_system: "Sistema" new_article_title: "Crea un article nou" new_thang_title: "Crea un nou tipus de Thang" new_level_title: "Crea un nou nivell" new_article_title_login: "Inicia sessió per a crear un article nou" new_thang_title_login: "Inicia la sessió per crear un nou tipus de Thang" new_level_title_login: "Inicia sessió per a crear un nou nivell" new_achievement_title: "Crea un nou triomf" new_achievement_title_login: "Inicia sessió per a crear un nou triomf" new_poll_title: "Crea una nova enquesta" new_poll_title_login: "Inicia sessió per a crear una nova enquesta" article_search_title: "Cerca Articles aquí" thang_search_title: "Cerca tipus de Thang aquí" level_search_title: "Cerca nivells aquí" achievement_search_title: "Cerca assoliments" poll_search_title: "Cerca enquestes" read_only_warning2: "Nota: no podeu desar edicions aquí, perquè no heu iniciat la sessió." no_achievements: "Encara no s'ha afegit cap assoliment per aquest nivell." achievement_query_misc: "L'assoliment clau fora de miscel·lània" achievement_query_goals: "L'assoliment clau no té objectius de nivell" level_completion: "Compleció de nivell" pop_i18n: "Omple I18N" tasks: "Tasques" clear_storage: "Esborreu els canvis locals" add_system_title: "Afegiu sistemes al nivell" done_adding: "Afegits fets" article: edit_btn_preview: "Vista prèvia" edit_article_title: "Editar l'article" polls: priority: "Prioritat" contribute: page_title: "Contribueix" intro_blurb: "CodeCombat és 100% codi obert! Una gran quantitat de jugadors ens han ajudat a construir el joc tal com és avui. Uneix-te a l'aventura d'ensenyar a programar!" alert_account_message_intro: "Hola!" alert_account_message: "Per subscriure't a alguna classe, necessites estar identificat." archmage_introduction: "Una de les millors parts de construir jocs és que aglutinen coses molt diverses. Gràfics, sons, treball en temps real, xarxes socials, i per suposat la programació, des del baix nivell d'ús de bases de dades i administració del servidor fins a dissenyar i crear interfícies. Hi ha molt a fer, i si ets un programador amb experiència i amb l'anhel de submergir-te dins CodeCombat aquesta classe és per tu. Ens encantarà tenir la teva ajuda en el millor joc de programació que hi ha." class_attributes: "Atributs de la classe" archmage_attribute_1_pref: "Coneixement en " archmage_attribute_1_suf: ", o ganes d'aprendre'n. La major part del nostre codi és en aquest llenguatge. Si ets un fan de Ruby o Python et sentiràs com a casa. És JavaScript però més agradable." archmage_attribute_2: "Certa experiència programant i iniciativa personal. T'orientarem, però no podem dedicar molt de temps en ensenyar-te." how_to_join: "Com unir-se" join_desc_1: "Qualsevol pot ajudar! Visita el nostre " join_desc_2: "per començar i i marca la casella d'abaix per registra-te com a Arximag i estar al dia del correus electrònics que enviem. Vols saber què fer o que t'expliquem més a fons en què consisteix? " join_desc_3: ", o troba'ns al nostre " join_desc_4: "i t'ho explicarem!" join_url_email: "Escriu-nos" join_url_slack: "Canal de Contractació pública" archmage_subscribe_desc: "Rebre els correus sobre noves oportunitats de programació." artisan_introduction_pref: "Hem de construir nous nivells! La gent reclama més continguts i les nostres forces són limitades. Ara mateix el nostre lloc de treball és de nivell 1; el nostre editor de nivells és tot just útil per als seus creadors, així que ves en compte. Si tens algunes idees sobre campanyes amb bucles for per " artisan_introduction_suf: ", llavors aquesta classe és per a tu." artisan_attribute_1: "Experiència en construcció de continguts d'aquest estil seria genial, com per exemple l'editor de nivells de Blizzard. Però no és un requisit!" artisan_attribute_2: "Ganes de fer moltes proves i iteracions. Per fer bons nivells necessitaràs mostrar-ho a altres i veure com juguen i estar preparat per a reparar tot el que calgui." artisan_attribute_3: "De moment, la resistència va de la mà de l'Aventurer. El nostre editor de nivells es troba en una fase molt preliminar i pot ser un poc frustrant. Estàs avisat!" artisan_join_desc: "Utilitza l'editor de nivells a través d'aquests passos:" artisan_join_step1: "Llegeix la documentació." artisan_join_step2: "Crea un nivell nou i explora els ja creats." artisan_join_step3: "Troba'ns al nostre canal públic d'Slack per a més ajuda." artisan_join_step4: "Anuncia els teus nivells al fòrum per a més opinions." artisan_subscribe_desc: "Rebre els correus electrònics per seguir les novetats." adventurer_introduction: "Anem a tenir clar el vostre paper: sou el tanc. Vas a patir grans danys. Necessitem que les persones puguin provar nous nivells i ajudar a identificar com millorar les coses. El dolor serà enorme; fer bons jocs és un procés llarg i ningú ho fa bé la primera vegada. Si pateix i té una puntuació alta de constitució, aquesta classe pot ser per a vostè." adventurer_attribute_1: "Un set d'aprenentatge. Tu vols aprendre a codificar i nosaltres volem ensenyar-te com codificar. Probablement estaràs fent la majoria dels aprenentatges en aquesta classe." adventurer_attribute_2: "Carismàtic. Sigues amable però escriu sobre el que necessites millorar i ofereix suggeriments sobre com millorar-los." adventurer_join_pref: "Alineeu-vos amb (o recluta) un Artesà i treballeu amb ells, o marqueu la casella següent per rebre correus electrònics quan hi hagi nous nivells per provar. També publicarem sobre els nivells per revisar a les nostres xarxes, com ara" adventurer_forum_url: "el nostre fòrum" adventurer_join_suf: "per tant, si prefereixes que t'ho notifiquem així, inscriu-te aquí!" adventurer_subscribe_desc: "Rep correus electrònics quan hi hagi nous nivells per provar." scribe_introduction_pref: "CodeCombat no només vol ser un munt de nivells. També inclourà un recurs per al coneixement, una wiki de conceptes de programació que els nivells poden connectar. D'aquesta manera, en lloc que cada Artesà hagi d'descriure amb detall el que és un operador de comparació, simplement pot enllaçar el seu nivell amb l'article que els descriu que ja està escrit per a l'edificació del jugador. Al llarg de la línia del que el" scribe_introduction_url_mozilla: "Mozilla Developer Network" scribe_introduction_suf: "ha construit. Si la vostra idea de diversió és articular els conceptes de programació en forma de marca, aquesta classe pot ser per a vosaltres." scribe_attribute_1: "L'habilitat en paraules és pràcticament tot el que necessiteu. No només la gramàtica i l'ortografia, sinó que poden transmetre idees complicades als altres." contact_us_url: "Contacta amb nosaltres" scribe_join_description: "Explica'ns una mica sobre tu mateix, la teva experiència amb la programació i sobre quin tipus de coses t'agradaria escriure. Començarem per això!" scribe_subscribe_desc: "Rep correus electrònics sobre anuncis d'escriptura d'articles." diplomat_introduction_pref: "Si alguna cosa vam aprendre del que vam " diplomat_launch_url: "llançar a l'octubre" diplomat_introduction_suf: "és que hi ha un gran interès en CodeCombat a altres països! Estem construint un cos de traductors per aconseguir que CodeCombat sigui tan accessible arreu del món com sigui possible. Si t'agrada aconseguir els nivells tan aviat com surten i poder-los oferir als teus compatriotes llavors aquesta classe és per tu." diplomat_attribute_1: "Fluïdesa en l'anglès i en l'idioma al que vulguis traduir. Al transmetre idees complicades és important tenir un gran coneixement dels dos idiomes!" diplomat_i18n_page_prefix: "Pots començar traduint els nostres nivells a la" diplomat_i18n_page: "pàgina de traduccions" diplomat_i18n_page_suffix: ", o bé la interfície web a GitHub." diplomat_join_pref_github: "Troba els nostres fitxers d'idiomes " diplomat_github_url: "a GitHub" diplomat_join_suf_github: ", edita'ls i envia una petició de modificació. A més, marca la casella d'abaix per mantenir-te informat d'esdeveniments de traducció!" diplomat_subscribe_desc: "Rebre correus sobre el desenvolupament de i18n i la traducció de nivells." ambassador_introduction: "Aquesta és una comunitat que estem construint, i tu ets les connexions. Tenim fòrums, correus electrònics i xarxes socials amb molta gent per parlar i ajudar-vos a conèixer el joc i aprendre-ne. Si voleu ajudar a la gent a participar-hi i divertir-se i tenir una bona idea del pols de CodeCombat i on anem, aquesta classe pot ser per a vosaltres." ambassador_attribute_1: "Habilitats comunicatives. Ser capaç d'identificar els problemes que tenen els jugadors i ajudar-los a resoldre'ls. A més, manten-nos informats sobre el que diuen els jugadors, el que els agrada i no els agrada i sobre què més volen!" ambassador_join_desc: "explica'ns una mica sobre tu mateix, què has fet i què t'interessaria fer. Començarem per això!" ambassador_join_note_strong: "Nota" ambassador_join_note_desc: "Una de les nostres principals prioritats és crear multijugador on els jugadors que tinguin dificultats per resoldre els nivells poden convocar assistents de nivell superior per ajudar-los. Serà una bona manera de fer la tasca d'Ambaixador. T'anirem informant!" ambassador_subscribe_desc: "Obteniu correus electrònics sobre actualitzacions de suport i desenvolupaments multijugador." teacher_subscribe_desc: "Obteniu correus electrònics sobre actualitzacions i anuncis per a professors." changes_auto_save: "Els canvis es desen automàticament quan canvieu les caselles de selecció." diligent_scribes: "Els Nostres Escribes Diligents:" powerful_archmages: "Els Nostres Arximags Poderosos:" creative_artisans: "Els Nostres Artesans Creatius:" brave_adventurers: "Els Nostres Aventurers Valents:" translating_diplomats: "Els Nostres Diplomàtics Traductors:" helpful_ambassadors: "Els Nostres Ambaixadors Útils:" ladder: # title: "Multiplayer Arenas" # arena_title: "__arena__ | Multiplayer Arenas" my_matches: "Les meves partides" simulate: "Simula" simulation_explanation: "Al simular jocs, pots aconseguir que el teu joc sigui més ràpid!" simulation_explanation_leagues: "Us ajudarà principalment a simular jocs per als jugadors aliats dels vostres clans i cursos." simulate_games: "Simula Jocs!" games_simulated_by: "Jocs que has simulat:" games_simulated_for: "Jocs simulats per a tu:" games_in_queue: "Jocs actualment a la cua:" games_simulated: "Partides simulades" games_played: "Partides guanyades" ratio: "Ràtio" leaderboard: "Taulell de Classificació" battle_as: "Batalla com " summary_your: "Les teves " summary_matches: "Partides - " summary_wins: " Victòries, " summary_losses: " Derrotes" rank_no_code: "No hi ha cap codi nou per classificar" rank_my_game: "Classifica el meu Joc!" rank_submitting: "Enviant..." rank_submitted: "Enviat per Classificar" rank_failed: "No s'ha pogut classificar" rank_being_ranked: "El Joc s'està Classificant" rank_last_submitted: "enviat " help_simulate: "T'ajudem a simular jocs?" code_being_simulated: "El teu nou codi està sent simulat per altres jugadors per al rànquing. Això s'actualitzarà a mesura que entrin noves coincidències." no_ranked_matches_pre: "No hi ha partides classificades per a l'equip " no_ranked_matches_post: " ! Juga contra alguns competidors i torna aquí per aconseguir que el teu joc sigui classificat." choose_opponent: "Escull adversari" select_your_language: "Escull el teu idioma!" tutorial_play: "Juga el tutorial" tutorial_recommended: "Recomenat si no has jugat abans" tutorial_skip: "Salta el tutorial" tutorial_not_sure: "No estàs segur de què està passant?" tutorial_play_first: "Juga el tutorial primer." simple_ai: "Simple CPU" warmup: "Escalfament" friends_playing: "Amics jugant" log_in_for_friends: "Inicia sessió per jugar amb els teus amics!" social_connect_blurb: "Connecta't i juga contra els teus amics!" invite_friends_to_battle: "Invita els teus amics a unir-se a la batalla!" fight: "Lluita!" watch_victory: "Mira la teva victòria" defeat_the: "Derrota a" watch_battle: "Observa la batalla" tournament_started: ", iniciada" tournament_ends: "El torneig acaba" tournament_ended: "El torneig ha acabat" tournament_rules: "Normes del torneig" tournament_blurb: "Escriu codi, recull or, construeix exèrcits, enderroca enemics, guanya premis i millora el teu rànquing al nostre torneig Greed de $ 40,000! Consulteu els detalls" tournament_blurb_criss_cross: "Obté ofertes, construeix camins, reparteix opositors, agafa gemmes i actualitza el teu rànquing al nostre torneig Criss-Cross! Consulteu els detalls" tournament_blurb_zero_sum: "Allibera la teva creativitat de codificació tant en la trobada d'or i en les tàctiques de batalla en aquest joc de miralls alpins entre el bruixot i el bruixot blau. El torneig va començar el divendres 27 de març i tindrà lloc fins el dilluns 6 d'abril a les 5PM PDT. Competeix per diversió i glòria! Consulteu els detalls" tournament_blurb_ace_of_coders: "Treu-lo a la glacera congelada en aquest joc de mirall d'estil dominació! El torneig va començar el dimecres 16 de setembre i es disputarà fins el dimecres 14 d'octubre a les 5PM PDT. Consulteu els detalls" tournament_blurb_blog: "en el nostre blog" rules: "Normes" winners: "PI:NAME:<NAME>END_PI" league: "Lliga" red_ai: "CPU vermella" # "Red AI Wins", at end of multiplayer match playback blue_ai: "CPU blava" wins: "Guanya" # At end of multiplayer match playback humans: "Vermell" # Ladder page display team name ogres: "Blau" user: # user_title: "__name__ - Learn to Code with CodeCombat" stats: "Estadístiques" singleplayer_title: "PI:NAME:<NAME>END_PI d'un sol jugador" multiplayer_title: "PI:NAME:<NAME>END_PIs multijugador" achievements_title: "Triomfs" last_played: "Ultim jugat" status: "Estat" status_completed: "Complet" status_unfinished: "Inacabat" no_singleplayer: "Encara no s'han jugat nivells individuals." no_multiplayer: "Encara no s'han jugat nivells multijugador." no_achievements: "No has aconseguit cap triomf encara." favorite_prefix: "L'idioma preferit és " favorite_postfix: "." not_member_of_clans: "Encara no ets membre de cap clan" certificate_view: "veure certificat" certificate_click_to_view: "fes clic per veure el certificat" certificate_course_incomplete: "curs incomplet" certificate_of_completion: "Certificat de Finalització" certificate_endorsed_by: "Aprovat per" certificate_stats: "Estadístiques del curs" certificate_lines_of: "línies de" certificate_levels_completed: "nivells completats" certificate_for: "Per" # certificate_number: "No." achievements: last_earned: "Últim aconseguit" amount_achieved: "Cantitat" achievement: "Triomf" current_xp_prefix: "" current_xp_postfix: " en total" new_xp_prefix: "" new_xp_postfix: " guanyat" left_xp_prefix: "" left_xp_infix: " fins el nivell " left_xp_postfix: "" account: # title: "Account" # settings_title: "Account Settings" # unsubscribe_title: "Unsubscribe" # payments_title: "Payments" # subscription_title: "Subscription" # invoices_title: "Invoices" # prepaids_title: "Prepaids" payments: "Pagaments" prepaid_codes: "Codis prepagats" purchased: "Comprat" subscribe_for_gems: "Subscriure's per gemmes" subscription: "Subscripció" invoices: "Factures" service_apple: "Apple" service_web: "Web" paid_on: "Pagat a" service: "Servei" price: "Preu" gems: "Gemmess" active: "Actiu" subscribed: "Subscrit" unsubscribed: "No s'ha subscrit" active_until: "Actiu fins a" cost: "Cost" next_payment: "Següent pagament" card: "Targeta" status_unsubscribed_active: "No esteu subscrit i no se us facturarà, però el vostre compte encara està actiu per ara." status_unsubscribed: "Accediu a nous nivells, herois, ítems i gemmes de bonificació amb una subscripció a CodeCombat!" not_yet_verified: "Encara no s'ha verificat." resend_email: "Reenvia l'e-mail" email_sent: "E-mail enviat! Comprova la teva safata d'entrada." verifying_email: "Verificant la teva adreça e-mail..." successfully_verified: "Has verificat correctament la teva adreça e-mail!" verify_error: "S'ha produït un error en verificar el teu e-mail :(" unsubscribe_from_marketing: "Abandonar la subscripció a __email__ de tots els e-mails de màrqueting de CodeCombat?" unsubscribe_button: "Sí, abandonar la subscripció" unsubscribe_failed: "Errada" unsubscribe_success: "Èxit" account_invoices: amount: "Quantitat en dòlars nord-americans" declined: "S'ha denegat la targeta" invalid_amount: "Si us plau, introduïu un import en dòlars nord-americans." not_logged_in: "Inicieu sessió o creeu un compte per accedir a les factures." pay: "Factures de Pagament" purchasing: "Comprant..." retrying: "Error del Servidor, reintentant." success: "S'ha pagat correctament. Gràcies!" account_prepaid: purchase_code: "Compreu un codi de subscripció" purchase_code1: "Es poden bescanviar els codis de subscripció per afegir el temps de subscripció premium a un o més comptes de la versió Home de CodeCombat." purchase_code2: "Cada compte de CodeCombat només pot bescanviar un codi de subscripció en particular una vegada." purchase_code3: "Els mesos del codi de subscripció s'afegiran al final de qualsevol subscripció existent al compte." purchase_code4: "Els codis de subscripció són per als comptes que reprodueixen la versió inicial de CodeCombat, no es poden utilitzar en lloc de les llicències d'estudiants per a la versió de Classroom." purchase_code5: "Per obtenir més informació sobre les llicències d'estudiants, consulteu-les a" users: "Usuaris" months: "Mesos" purchase_total: "Total" purchase_button: "Enviar compra" your_codes: "Els teus Codis" redeem_codes: "Canvia un codi de subscripció" prepaid_code: "Codi Prepagat" lookup_code: "Cerca el Codi Prepagat" apply_account: "Aplicar al teu compte" copy_link: "Podeu copiar l'enllaç del codi i enviar-lo a algú." quantity: "Quantitat" redeemed: "Canviats" no_codes: "Encara no hi ha cap codi!" you_can1: "Pots" you_can2: "comprar un codi Prepagat" you_can3: "per aplicar al teu compte o donar a d'altres." loading_error: could_not_load: "Error de carrega del servidor" connection_failure: "Connexió fallida." connection_failure_desc: "Sembla que no estàs connectat a internet! Comprova la teva connexió a la xarxa i després recarrega aquesta plana." login_required: "Es requereix iniciar sessió" login_required_desc: "Necessites iniciar sessió per accedir a aquesta plana." unauthorized: "Has d'iniciar la sessió. Tens les galetes desactivades?" forbidden: "No disposes dels permisos." forbidden_desc: "Oh no, aquí no et podem mostrar res! Comprova que has iniciat sessió amb el compte correcte, o visita un dels enllaços següents per tornar a programar!" not_found: "No trobat." not_found_desc: "Hm, aquí no hi ha res. Visita un dels enllaços següents per tornar a programar!" not_allowed: "Metode no permès." timeout: "Temps d'espera del servidor superat" conflict: "Conflicte de recursos." bad_input: "Entrada incorrecta." server_error: "Error del servidor." unknown: "Error Desconegut" error: "ERROR" general_desc: "Alguna cosa ha anat malament, i és probable que sigui culpa nostra. Mira d'esperar una mica i després recarrega la plana, o visita un dels enllaços següents per tornar a programar!" resources: level: "Nivell" patch: "Pedaç" patches: "Pedaços" system: "Sistema" systems: "Sistemes" component: "Component" components: "Components" hero: "Heroi" campaigns: "Campanyes" concepts: advanced_css_rules: "Regles CSS avançades" advanced_css_selectors: "Selectors CSS avançats" advanced_html_attributes: "Atributs HTML avançats" advanced_html_tags: "Etiquetes HTML avançades" algorithm_average: "Algorisme mitjà" algorithm_find_minmax: "Algorisme Trobar Mínim/Màxim" algorithm_search_binary: "Algorisme Cerca Binària" algorithm_search_graph: "Algorisme Cerca Gràfica" algorithm_sort: "Algorisme Tipus" algorithm_sum: "Algorisme Suma" arguments: "Arguments" arithmetic: "Aritmètica" array_2d: "Cadenes 2D" array_index: "Indexació de Cadenes" array_iterating: "Iteració en Cadenes" array_literals: "Cadenes Literals" array_searching: "Cerca en Cadenes" array_sorting: "Classificació en Cadenes" arrays: "Cadenes" basic_css_rules: "Regles bàsiques CSS" basic_css_selectors: "Selectors bàsics CSS" basic_html_attributes: "Atributs bàsics HTML" basic_html_tags: "Etiquetes bàsiques HTML" basic_syntax: "Sintaxis bàsica" binary: "Binari" boolean_and: "I Booleana" boolean_inequality: "Desigualtat Booleana" boolean_equality: "Igualtat Booleana" boolean_greater_less: "Major/Menor Booleans" boolean_logic_shortcircuit: "Circuits lògics Booleans" boolean_not: "Negació Booleana" boolean_operator_precedence: "Ordre d'operadors Booleans" boolean_or: "O Booleana" boolean_with_xycoordinates: "Comparació coordinada" bootstrap: "Programa d'arranque" break_statements: "Declaracions Break" classes: "Classes" continue_statements: "Sentències Continue" dom_events: "Events DOM" dynamic_styling: "Estilisme dinàmic" # events: "Events" event_concurrency: "Concurrència d'events" event_data: "Data d'event" event_handlers: "Controlador d'Events" event_spawn: "Event generador" for_loops: "Bucles (For)" for_loops_nested: "Anidació amb bucles" for_loops_range: "Pel rang de bucles" functions: "Funcions" functions_parameters: "Paràmetres" functions_multiple_parameters: "Paràmetres múltiples" game_ai: "Joc AI" game_goals: "Objectius del Joc" game_spawn: "Generador del Joc" graphics: "Gràfics" graphs: "Gràfics" heaps: "Munts" if_condition: "Sentències Condicionals 'If'" if_else_if: "Sentències 'If/Else If'" if_else_statements: "Sentències 'If/Else'" if_statements: "Sentències If" if_statements_nested: "Sentències If anidades" indexing: "Indexació en Matrius" input_handling_flags: "Manipulació d'entrades - Banderes" input_handling_keyboard: "Manipulació d'entrades - Teclat" input_handling_mouse: "Manipulació d'entrades - Ratolí" intermediate_css_rules: "Regles intermàdies de CSS" intermediate_css_selectors: "Selector intermedis CSS" intermediate_html_attributes: "Atributs intermedis HTML" intermediate_html_tags: "Etiquetes intermèdies HTML" jquery: "jQuery" jquery_animations: "Animacions jQuery" jquery_filtering: "Filtratge d'elements jQuery" jquery_selectors: "Selectors jQuery" length: "longitud de la matriu" math_coordinates: "Coordinar Matemàtiques" math_geometry: "Geometria" math_operations: "Operacions matemàtiques" math_proportions: "Proporcions matemàtiques" math_trigonometry: "Trigonometria" object_literals: "Objectes Literals" parameters: "Paràmetres" # programs: "Programs" # properties: "Properties" property_access: "Accés a Propietats" property_assignment: "Assignar Propietats" property_coordinate: "Coordinar Propietat" queues: "Estructures de dades - Cues" reading_docs: "Llegint els Documents" recursion: "Recursivitat" return_statements: "Sentències de retorn" stacks: "Estructures de dades - Piles" strings: "Cadenes" strings_concatenation: "Concatenació de cadenes" strings_substrings: "Subcadenes" trees: "Estructures de dades - Arbres" variables: "Variables" vectors: "Vectors" while_condition_loops: "Bucles 'While' amb condicionals" while_loops_simple: "Bucles 'While'" while_loops_nested: "Bucles 'While' anidats" xy_coordinates: "Coordenades Cartesianes" advanced_strings: "Cadenes de text avançades (string)" # Rest of concepts are deprecated algorithms: "Algorismes" boolean_logic: "Lògica booleana" basic_html: "HTML Bàsic" basic_css: "CSS Bàsic" basic_web_scripting: "Escriptura Web bàsica" intermediate_html: "HTML intermig" intermediate_css: "CSS intermig" intermediate_web_scripting: "Escriptura Web intermitja" advanced_html: "HTML avançat" advanced_css: "CSS avançat" advanced_web_scripting: "Escriptura Web avançada" input_handling: "Manipulació de dades d'entrada" while_loops: "Bucles 'While'" place_game_objects: "Situar objectes del joc" construct_mazes: "Construir laberints" create_playable_game: "Crear un projecte de joc que es pugui jugar i compartir" alter_existing_web_pages: "Modificar planes web existents" create_sharable_web_page: "Crear una plana web compartible" basic_input_handling: "Manipulació d'entrada bàsica" basic_game_ai: "Joc bàsic d'AI" basic_javascript: "JavaScript bàsic" basic_event_handling: "Manipulació d'Events bàsica" create_sharable_interactive_web_page: "Crear una plana web compartible interactiva" anonymous_teacher: notify_teacher: "Notificar ProfPI:NAME:<NAME>END_PI" create_teacher_account: "Crear un compte de professorat gràtis" enter_student_name: "El teu nom:" enter_teacher_email: "El teu e-mail de professor:" teacher_email_placeholder: "PI:EMAIL:<EMAIL>END_PI" student_name_placeholder: "Escriu aquí el teu nom" teachers_section: "Docents:" students_section: "Alumnat:" teacher_notified: "Hem notificat al vostre professor que voleu jugar més a CodeCombat en classe." delta: added: "Afegit" modified: "Modificat" not_modified: "No modificat" deleted: "Eliminat" moved_index: "Índex desplaçat" text_diff: "Diferir text" merge_conflict_with: "Conflicte d'unió amb" no_changes: "Sense canvis" legal: page_title: "Legalitat" # opensource_introduction: "CodeCombat is part of the open source community." opensource_description_prefix: "Comprova " github_url: "el nostre GitHub" opensource_description_center: "i ajuda'ns si vols! CodeCombat està construit amb dotzenes de projectes de codi obert, i ens encanta. Mira " archmage_wiki_url: "la nostra wiki d'ArxiMags" opensource_description_suffix: "per observar la llista de software que fa possible aquest joc." practices_title: "Bones Pràctiques Respectuoses" practices_description: "Aquesta és la promesa que et fem, jugador, d'una manera no tant legal." privacy_title: "Privacitat" privacy_description: "No vendrem cap informació personal teva." security_title: "Seguretat" security_description: "Ens esforcem per mantenir segura la vostra informació personal. Com a projecte de codi obert, el nostre lloc està lliurement obert a tothom per revisar i millorar els nostres sistemes de seguretat." email_title: "E-mail" email_description_prefix: "No us inundarem amb correu brossa. Mitjançant" email_settings_url: "la teva configuració d'e-mail" email_description_suffix: "o mitjançant els enllaços als e-mails que t'enviem, pots canviar les teves preferències i donar-te de baixa fàcilment en qualsevol moment." cost_title: "Cost" cost_description: "CodeCombat és gratuït per a tots els nivells bàsics, amb una subscripció de ${{price}} USD al mes per accedir a branques de nivells extra i {{gems}} bonus de gemmes al mes. Pots cancel·lar-ho amb un clic i oferim una garantia de devolució del 100%." copyrights_title: "Copyrights i Llicències" contributor_title: "Acord de Llicència de Col·laborador (CLA)" contributor_description_prefix: "Tots els col·laboradors, tant del lloc com del repositori GitHub, estan subjets al nostre" cla_url: "CLA" contributor_description_suffix: "que has d'acceptar abans de fer contribucions." code_title: "Codi - MIT" # client_code_description_prefix: "All client-side code for codecombat.com in the public GitHub repository and in the codecombat.com database, is licensed under the" mit_license_url: "llicència MIT" code_description_suffix: "Això inclou tot el codi a Sistemes i Components que s'han fet possibles per CodeCombat amb el proposit de crear nivells." art_title: "Art/Música - Creative Commons " art_description_prefix: "Tot el contingut comú està disponible sota" cc_license_url: "llicència Creative Commons Attribution 4.0 International" art_description_suffix: "El contingut comú és generalment disponible per CodeCombat amb la finalitat de crear nivells. Inclou:" art_music: "Musica" art_sound: "So" art_artwork: "Art" art_sprites: "Capes" art_other: "Tots i cadascun dels treballs creatius que no siguin de codi que estiguin disponibles quan es creïn Nivells." art_access: "Actualment, no hi ha cap sistema universal i fàcil d'obtenir aquests actius. En general, obtingueu-les des dels URL que utilitzeu el lloc, contacteu-nos per obtenir assistència o ens ajudeu a ampliar el lloc per fer-los accessibles amb més facilitat." art_paragraph_1: "Per a l'atribució, si us plau, cita i vincle a codecombat.com a prop d'on s'utilitza la font o, si escau, per al mitjà. Per exemple:" use_list_1: "Si s'utilitza en una pel·lícula o en un altre joc, incloeu codecombat.com en els crèdits." use_list_2: "Si s'utilitza en un lloc web, incloeu un enllaç prop de l'ús, per exemple, sota una imatge o en una pàgina d'atribucions generals on també podeu esmentar altres obres de Creative Commons i programari de codi obert que s'utilitza al lloc. Alguna cosa que ja fa referència clarament a CodeCombat, com ara una publicació de bloc que menciona CodeCombat, no necessita cap atribució per separat." art_paragraph_2: "Si el contingut que s'utilitza no és creat per CodeCombat sinó per un usuari de codecombat.com, atribueix-lo a ell, i seguiu les indicacions d'atribució proporcionades en la descripció del recurs si hi ha alguna." rights_title: "Drets reservats" rights_desc: "Tots els drets estan reservats per als mateixos Nivells. Això inclou" rights_scripts: "Scripts" rights_unit: "Configuració de la unitat" rights_writings: "Escrits" rights_media: "Mitjans de comunicació (sons, música) i qualsevol altre contingut creatiu fet específicament per a aquest nivell i generalment no està disponible quan es creen nivells." rights_clarification: "Per aclarir, qualsevol cosa que estigui disponible a l'Editor de Nivells amb la finalitat de fer nivells està sota CC, mentre que el contingut creat amb l'Editor de Nivells o carregat en el curs de creació de Nivells no ho és." nutshell_title: "En poques paraules" nutshell_description: "Els recursos que oferim a l'Editor de Nivells es poden utilitzar de la manera que vulgueu per crear nivells. Però ens reservem el dret de restringir la distribució dels mateixos Nivells (que es creen a codecombat.com) perquè es puguin cobrar." nutshell_see_also: "Veure també:" canonical: "La versió en anglès d'aquest document és la versió definitiva i canònica. Si hi ha discrepàncies entre les traduccions, el document anglès té prioritat." third_party_title: "Serveis de tercers" third_party_description: "CodeCombat usa els següents serveis de tercers (entre d'altres):" cookies_message: "CodeCombat utilitza unes quantes galetes essencials i no essencials." cookies_deny: "Declareu les galetes no essencials" ladder_prizes: title: "Premis del torneig" # This section was for an old tournament and doesn't need new translations now. blurb_1: "Aquests premis seran guanyats d'acord amb" blurb_2: "Les normes del torneig" blurb_3: "els millors jugadors humans i ogres." blurb_4: "Dos equips signifiquen el doble de premis!" blurb_5: "(Hi haura dos guanyadors pel primer lloc, dos pels del segon lloc, etc.)" rank: "Rang" prizes: "Premis" total_value: "Valor total" in_cash: "en diners" custom_wizard: "Personalitza el teu bruixot de CodeCombat" custom_avatar: "Personalitza el teu avatar de CodeCombat" heap: "per sis mesos d'acces \"Startup\" " credits: "crèdits" one_month_coupon: "cupó: trieu Rails o HTML" one_month_discount: "descompte del 30%: seleccioneu Rails o HTML" license: "llicencia" oreilly: "ebook de la vostra elecció" calendar: year: "Any" day: "Dia" month: "Mes" january: "Gener" february: "Febrer" march: "Març" april: "Abril" may: "Maig" june: "Juny" july: "Juliol" august: "Agost" september: "Setembre" october: "Octubre" november: "Novembre" december: "Desembre" code_play_create_account_modal: title: "Ho has fet!" # This section is only needed in US, UK, Mexico, India, and Germany body: "Ara estàs en camí d'esdevenir un mestre codificador. Registra't per rebre un extra de <strong>100 Gemmes</strong> i també se't donarà l'oportunitat de <strong>guanyar $2,500 i altres premis de Lenovo</strong>." sign_up: "Retistra't i continua codificant ▶" victory_sign_up_poke: "Crea un compte gratuït per desar el codi i ingressa per obtenir premis." victory_sign_up: "Inscriu-te i accedeix a poder <strong>gunayar $2,500</strong>" server_error: email_taken: "E-mail ja agafat" username_taken: "Usuari ja agafat" esper: line_no: "Línia $1: " uncaught: "Irreconeixible $1" # $1 will be an error type, eg "Uncaught SyntaxError" reference_error: "Error de Referència: " argument_error: "Error d'Argument: " type_error: "Error d'Escriptura: " syntax_error: "Error de Sintaxi: " error: "Error: " x_not_a_function: "$1 no és una funció" x_not_defined: "$1 no s'ha definit" spelling_issues: "Revisa l'ortografia: volies dir `$1` en lloc de `$2`?" capitalization_issues: "Revisa les majúscules: `$1` hauria de ser `$2`." py_empty_block: "$1 buit. Posa 4 espais abans de la declaració dintre de la declaració $2." fx_missing_paren: "Si vols cridar `$1` com a funció, necessites posar `()`" unmatched_token: "`$1` sense parella. Cada `$2` obert necessita un `$3` tancat per emparellar-se." unterminated_string: "Cadena sense finalitzar. Afegeix una `\"` a joc al final de la teva cadena." missing_semicolon: "Punt i coma oblidat." missing_quotes: "Cometes oblidades. Prova `$1`" argument_type: "L'argument de `$1`, `$2`, hauria de tenir tipus `$3`, però té `$4`: `$5`." argument_type2: "L'argument de `$1`', `$2`, hauria de tenir tipus `$3`, però té `$4`." target_a_unit: "Invoca una unitat." attack_capitalization: "Attack $1, no $2. (Les majúscules són importants.)" empty_while: "Ordre 'while' buida. Posa 4 espais al davant de les següents ordres que pertanyin a while." line_of_site: "L'argument de `$1`, `$2`, té un problema. Ja tens cap enemic a la teva línia d'acció?" need_a_after_while: "Necessites `$1` després de `$2`." too_much_indentation: "Massa sagnat a l'inici d'aquesta línia." missing_hero: "Falta paraula clau a `$1`; hauria de ser `$2`." takes_no_arguments: "`$1` no pren cap argument." no_one_named: "No n'hi ha cap anomenat \"$1\" a qui adreçar-se." separated_by_comma: "Els paràmetres que crida la funció han d'anar separats mitjançant `,`" protected_property: "No puc llegir la propietat protegida: $1" need_parens_to_call: "Si vols cridar `$1` com a funció, necessites posar `()`" expected_an_identifier: "S'esperava un identificador i en canvi vam veure '$1'." unexpected_identifier: "Identificador inesperat" unexpected_end_of: "Final d'entrada inesperat" unnecessary_semicolon: "Punt i coma innecessari." unexpected_token_expected: "Simbol inesperat: esperavem $1 però hem trobat $2 mentre analitzavem $3" unexpected_token: "Simbol $1 inesperat" unexpected_token2: "Simbol inesperat" unexpected_number: "Número inesperat" unexpected: "'$1' inesperat." escape_pressed_code: "En picar Escape; s'aborta el codi." target_an_enemy: "Invoca un enemic pel nom, com ara `$1`, no amb la cadena `$2`." target_an_enemy_2: "Invoca un enemic pel nom, com ara $1." cannot_read_property: "No puc llegir bé '$1' o indefinit" attempted_to_assign: "S'ha intentat assignar a la propietat que és només de lectura." unexpected_early_end: "Final prematur de programa inesperat." you_need_a_string: "Necessites una cadena per construir; una de $1" unable_to_get_property: "Impossible adquirir la propietat '$1' d'una referència indefinida o nula" # TODO: Do we translate undefined/null? code_never_finished_its: "El codi mai finalitza. Realment va lent o té un bucle infinit." unclosed_string: "Cadena sense tancar." unmatched: "'$1' sense emparellar." error_you_said_achoo: "Has dit: $1, però la contrasenya és: $2. (Les majúscules són importants.)" indentation_error_unindent_does: "Error de sagnat: el sagnat no coincideix amb cap altre nivell de sagnat" indentation_error: "Error de sagnat." need_a_on_the: "Necessites posar `:` al final de la línia que segueix a `$1`." attempt_to_call_undefined: "intentes anomenar '$1' (un valor nul)" unterminated: "`$1` sense acabar" target_an_enemy_variable: "Invoca la variable $1, no la cadena $2. (Prova a usar $3.)" error_use_the_variable: "Usa el nom de la variable com ara `$1` enlloc de la cadena com ara `$2`" indentation_unindent_does_not: "Sagnat indegut que no concorda amb cap altre nivell" unclosed_paren_in_function_arguments: "Sense tancar $1 en els arguments de la funció." unexpected_end_of_input: "Final d'entrada inesperat" there_is_no_enemy: "No hi ha cap `$1`. Usa `$2` primer." # Hints start here try_herofindnearestenemy: "Prova amb `$1`" there_is_no_function: "No hi ha cap funció `$1`, però `$2` té un mètode `$3`." attacks_argument_enemy_has: "L'argument de `$1`, `$2`, té un problema." is_there_an_enemy: "Ja n'hi ha algun enemic dintre de la teva línia de visió?" target_is_null_is: "Has invocat $1. Sempre hi ha un invocat per atacar? (Usa $2?)" hero_has_no_method: "`$1` no té mètode `$2`." there_is_a_problem: "Hi ha un problema amb el teu codi." did_you_mean: "Volies dir $1? No tens cap ítem equipat amb aquesta habilitat." missing_a_quotation_mark: "T'has oblidat posar una cometa. " missing_var_use_var: "T'has oblidat `$1`. Usa `$2` per crear una nova variable." you_do_not_have: "No tens cap ítem equipat amb l'habilitat $1." put_each_command_on: "Posa cada comand en una línia diferent" are_you_missing_a: "T'estàs oblidant de '$1' després de '$2'? " your_parentheses_must_match: "Els teus parèntesis han de coincidir." apcsp: # title: "AP Computer Science Principals | College Board Endorsed" # meta_description: "CodeCombat’s comprehensive curriculum and professional development program are all you need to offer College Board’s newest computer science course to your students." syllabus: "Pla d'Estudis de Fonaments de Programació" syllabus_description: "Utilitza aquest recurs per planificar el currículum de CodeCombat pel teu Pla d'Estudis de Fonaments de Programació de la teva classe." computational_thinking_practices: "Pràctiques de Pensament Computacional" learning_objectives: "Objectius d'Aprenentatge" curricular_requirements: "Requeriments Curriculars" unit_1: "Unitat 1: Tecnologia Creativa" unit_1_activity_1: "Unitat 1 Activitat: Revisió de la usabilitat tecnològica" unit_2: "Unitat 2: Pensament Computacional" unit_2_activity_1: "Unitat 2 Activitat: Seqüències Binaries" unit_2_activity_2: "Unitat 2 Activitat: Projecte de lliçons informàtiques" unit_3: "Unitat 3: Algorismes" unit_3_activity_1: "Unitat 3 Activitat: Algorismes - Guia de l'Autoestopista" unit_3_activity_2: "Unitat 3 Activitat: Simulació - Depredador i Presa" unit_3_activity_3: "Unitat 3 Activitat: Algorismes - Disseny de parelles i Programació" unit_4: "Unitat 4: Programació" unit_4_activity_1: "Unitat 4 Activitat: Abstraccions" unit_4_activity_2: "Unitat 4 Activitat: Cerca i Classificació" unit_4_activity_3: "Unitat 4 Activitat: Refactorització" unit_5: "Unitat 5: Internet" unit_5_activity_1: "Unitat 5 Activitat: Com funciona Internet" unit_5_activity_2: "Unitat 5 Activitat: Simulació d'Internet" unit_5_activity_3: "Unitat 5 Activitat: Simulation d'un Xat" unit_5_activity_4: "Unitat 5 Activitat: Cyberseguritat" unit_6: "Unitat 6: Dades" unit_6_activity_1: "Unitat 6 Activitat: Introducció a les Dades" unit_6_activity_2: "Unitat 6 Activitat: Big Data" unit_6_activity_3: "Unitat 6 Activitat: Compressió amb i sense Pèrdua" unit_7: "Unitat 7: Impacte Personal i Global" unit_7_activity_1: "Unitat 7 Activitat: Impacte Personal i Global" unit_7_activity_2: "Unitat 7 Activitat: Crowdsourcing" unit_8: "Unitat 8: Tasques de Rendiment" unit_8_description: "Prepara els estudiants per a Tasca Creativa, construint els seus propis jocs i practicant conceptes clau." unit_8_activity_1: "Pràctica Tasca Creativa 1: Desenvolupament de Jocs 1" unit_8_activity_2: "Pràctica Tasca Creativa 2: Desenvolupament de Jocs 2" unit_8_activity_3: "Pràctica Tasca Creativa 3: Desenvolupament de Jocs 3" unit_9: "Unitat 9: Revisió dels Fonaments" unit_10: "Unitat 10: Més enllà dels Fonaments" unit_10_activity_1: "Unitat 10 Activitat: Web Quiz" parent_landing: slogan_quote: "\"CodeCombat és realment difertit, i aprens molt.\"" quote_attr: "5è grau, Oakland, CA" refer_teacher: "Consulteu al Professor" focus_quote: "Desbloqueja el futur del teus fills" value_head1: "La forma més atractiva d'aprendre codi escrit" value_copy1: "CodeCombat és un tutor personal dels nens. Amb material de cobertura d'acord amb els estàndards curriculars nacionals, el vostre fill programarà algorismes, crearà llocs web i fins i tot dissenyarà els seus propis jocs." value_head2: "Construint habilitats claus per al segle XXI" value_copy2: "Els vostres fills aprendran a navegar i esdevenir ciutadans del món digital. CodeCombat és una solució que millora el pensament crític i la capacitat de recuperació del vostre fill." value_head3: "Herois que els vostres fills estimaran" value_copy3: "Sabem la importància que té divertir-se i implicar-se pel desenvolupament del cervell, per això hem encabit tant aprenentatge com hem pogut presentant-lo en un joc que els encantarà." dive_head1: "No només per als enginyers de programació" dive_intro: "Les habilitats informàtiques tenen una àmplia gamma d'aplicacions. Mireu alguns exemples a continuació!" medical_flag: "Aplicacions Mèdiques" medical_flag_copy: "Des del mapatge del genoma humà fins a les màquines de ressonància magnètica, la codificació ens permet comprendre el cos de maneres que mai no hem pogut fer." explore_flag: "Exploració Espacial" explore_flag_copy: "Apol·lo va arribar a la Lluna gràcies al treball humà amb ordinadors, i els científics utilitzen programes informàtics per analitzar la gravetat dels planetes i buscar noves estrelles." filmaking_flag: "Producció de Vídeo i Animació" filmaking_flag_copy: "Des de la robòtica del Jurassic Park fins a l'increïble animació de Dreamworks i Pixar, les pel·lícules no serien les mateixes sense les creacions digitals darrere de les escenes." dive_head2: "Els jocs són importants per aprendre" dive_par1: "Múltiples estudis han trobat que l'aprenentatge mitjançant jocs promou" dive_link1: "el desenvolupament cognitiu" dive_par2: "en els nens al mateix temps que demostra ser" dive_link2: "més efectiu" dive_par3: "ajudant els alumnes a" dive_link3: "aprendre i retenir coneixements" dive_par4: "," dive_link4: "concentrar-se" dive_par5: ", i aconseguir un major assoliment." dive_par6: "L'aprenentatge basat en jocs també és bo per desenvolupar" dive_link5: "resiliència" dive_par7: ", raonament cognitiu, i" dive_par8: ". Les Ciències només ens diuen què han de saber els nens. Aquests aprenen millor jugant." dive_link6: "funcions executives" dive_head3: "Fent Equip amb els Professors" dive_3_par1: "En el futur, " dive_3_link1: "codificar serà tan fonamental com aprendre a llegir i escriure" dive_3_par2: ". Hem treballat estretament amb els professors per dissenyar i desenvolupar el nostre contingut, i estem ensiosos per ensenyar als vostres fills. Els programes de tecnologia educativa com CodeCombat funcionen millor quan els professors els implementen de forma coherent. Ajudeu-nos a fer aquesta connexió presentant-nos als professors del vostre fill." mission: "La nostra missió: ensenyar i participar" mission1_heading: "Codificant per la generació d'avui" mission2_heading: "Preparant pel futur" mission3_heading: "Recolzat per pares com tu" mission1_copy: "Els nostres especialistes en educació treballen estretament amb els professors per conèixer els nens que es troben a l'entorn educatiu. Els nens aprenen habilitats que es poden aplicar fora del joc perquè aprenen a resoldre problemes, independentment del seu estil d'aprenentatge." mission2_copy: "Una enquesta de 2016 va demostrar que el 64% de les noies de 3r a 5è grau volien aprendre a codificar. Es van crear 7 milions de llocs de treball al 2015 on es requerien habilitats en codificació. Hem construït CodeCombat perquè cada nen hauria de tenir l'oportunitat de crear el seu millor futur." mission3_copy: "A CodeCombat, som pares. Som coders. Som educadors. Però, sobretot, som persones que creiem en donar als nostres fills la millor oportunitat per l'èxit en qualsevol cosa que decideixin fer." parent_modal: refer_teacher: "Consulteu al Professor" name: "El teu Nom" parent_email: "El teu E-mail" teacher_email: "E-mail del Professor" message: "Missatge" custom_message: "Acabo de trobar CodeCombat i vaig pensar que seria un gran programa per a la vostra aula! És una plataforma d'aprenentatge d'informàtica amb un pla d'estudis amb estàndards.\n\nL'alfabetització informàtica és tan important i crec que aquesta seria una gran manera d'aconseguir que els estudiants es dediquin a aprendre a codificar." send: "E-mail enviat" hoc_2018: # banner: "Happy Computer Science Education Week 2018!" page_heading: "Ensenya als teus alumnes com construir el seu propi joc d'arcade!" # {change} # step_1: "Step 1: Watch Video Overview" # step_2: "Step 2: Try it Yourself" # step_3: "Step 3: Download Lesson Plan" # try_activity: "Try Activity" download_pdf: "Descarregar PDF" # teacher_signup_heading: "Turn Hour of Code into a Year of Code" # teacher_signup_blurb: "Everything you need to teach computer science, no prior experience needed." # teacher_signup_input_blurb: "Get first course free:" # teacher_signup_input_placeholder: "Teacher email address" # teacher_signup_input_button: "Get CS1 Free" # activities_header: "More Hour of Code Activities" # activity_label_1: "Escape the Dungeon!" # activity_label_2: " Beginner: Build a Game!" # activity_label_3: "Advanced: Build an Arcade Game!" # activity_button_1: "View Lesson" about: "Sobre CodeCombat:" # {change} about_copy: "CodeCombat és un programa informàtic basat en jocs per ensenyar Python i JavaScript reals. El currículum d'acord amb els estàndards de CodeCombat es basa en un joc que els estudiants estimen. Més de 12 milions d'estudiants han après a codificar amb CodeCombat!" # {change} point1: "✓ Amb recolçament" point2: "✓ Diferenciat" point3: "✓ Avaluació Formativa i Sumativa" # {change} point4: "✓ Cursos basats en Projectes" point5: "✓ Seguiment de l'Alumnat" point6: "✓ Planificació de Lliçons complertes" # title: "HOUR OF CODE 2018" # acronym: "HOC" # hoc_2018_interstitial: # welcome: "Welcome to CodeCombat's Hour of Code 2018!" # educator: "I'm an educator" # show_resources: "Show me teacher resources!" # student: "I'm a student" # ready_to_code: "I'm ready to code!" # hoc_2018_completion: # congratulations: "Congratulations on completing <b>Code, Play, Share!</b>" # send: "Send your Hour of Code game to friends and family!" # copy: "Copy URL" # get_certificate: "Get a certificate of completion to celebrate with your class!" # get_cert_btn: "Get Certificate" # first_name: "PI:NAME:<NAME>END_PI" # last_initial: "PI:NAME:<NAME>END_PI Initial" # teacher_email: "Teacher's email address" # school_administrator: # title: "School Administrator Dashboard" # my_teachers: "My Teachers" # last_login: "Last Login" # licenses_used: "licenses used" # total_students: "total students" # active_students: "active students" # projects_created: "projects created" # other: "Other" # notice: "The following school administrators have view-only access to your classroom data:" # add_additional_teacher: "Need to add an additional teacher? Contact your CodeCombat Account Manager or email PI:EMAIL:<EMAIL>END_PI. " # license_stat_description: "Licenses available accounts for the total number of licenses available to the teacher, including Shared Licenses." # students_stat_description: "Total students accounts for all students across all classrooms, regardless of whether they have licenses applied." # active_students_stat_description: "Active students counts the number of students that have logged into CodeCombat in the last 60 days." # project_stat_description: "Projects created counts the total number of Game and Web development projects that have been created." # no_teachers: "You are not administrating any teachers."
[ { "context": "#\n# Author: Corey Auger\n# corey@nxtwv.com\n#\n\nwebrtcControllers = angular.", "end": 23, "score": 0.9998912215232849, "start": 12, "tag": "NAME", "value": "Corey Auger" }, { "context": "#\n# Author: Corey Auger\n# corey@nxtwv.com\n#\n\nwebrtcControllers = angular.mod...
app/assets/javascripts/controllers.coffee
coreyauger/play-webrtc
18
# # Author: Corey Auger # corey@nxtwv.com # webrtcControllers = angular.module('webrtcControllers', []) webrtcControllers.controller('HomeCtrl', ($scope, $routeParams, $location, worker) -> $scope.user = name: '' role: '' $scope.room = name: '' members: '' $scope.connect = (u) -> worker.username = @username worker.role = @role worker.testing = true worker.connect() $scope.join = (name) -> $location.path('/room/'+name+'/none') setTimeout(-> $scope.$apply() ,0) $scope.joinRoom = (name) -> $location.path('/room/'+$scope.room.name+'/'+$scope.room.members) setTimeout(-> $scope.$apply() ,0) worker.onNext({slot:'room', op:'list',data:{}}) ).controller('RoomCtrl',($scope, $routeParams, $location, worker) -> $scope.room = $routeParams.room $scope.members = $routeParams.members.split(',') $scope.memberList = [] $scope.peers = [] $scope.local = {} $scope.msgs = [] $scope.message = '' jidToPeerId = {} $scope.chat = active: false dataChannelList = [] $scope.toggleChat = -> $scope.chat.active = !$scope.chat.active; setTimeout(-> $scope.$apply() ,0) $scope.sendMessage = (txt) -> $scope.msgs.push(txt) for dc in dataChannelList console.log('dataChannel', dc) dc.send(txt) $scope.message = '' setTimeout( -> $scope.$apply() ,0) $scope.webrtc = muteAudio: false muteVideo: false hangup: -> worker.webrtc().stop() worker.onNext({slot:'room',op:'leave',data:{room:$scope.room}}) call: (name) -> alert('call') toggleMuteVideo: -> $scope.webrtc.muteVideo = !$scope.webrtc.muteVideo worker.walkabout.webrtcVideoMute($scope.webrtc.muteVideo); setTimeout( -> $scope.$apply(); ,0) toggleMuteAudio: -> $scope.webrtc.muteAudio = !$scope.webrtc.muteAudio worker.walkabout.webrtcAudioMute($scope.webrtc.muteAudio); setTimeout( -> $scope.$apply() ,0) worker.webrtc().onAddRemoteStream = (uuid, video, dataChannel) -> id = $scope.peers.length+1; dataChannelList.push(dataChannel) $scope.peers.push({ uuid:uuid local: false username: '' id: id }) jidToPeerId[uuid] = id dataChannel.onmessage = (msg) => console.log('onmessage',msg) $scope.msgs.push(msg.data) setTimeout(-> $scope.$apply() ,0) setTimeout(-> $scope.$apply() $('#video'+id).append(video) ,0) worker.webrtc().onRemoveRemoteStream = (uuid) -> $scope.peers = $scope.peers.filter((p) -> p.uuid != uuid ) setTimeout(-> $scope.$apply() ,0) worker.webrtc().onAddLocalStream = (video) -> id = 0 $scope.local = uuid:worker.username() username: '' local: true id: id #$scope.peers.push($scope.local) jidToPeerId[worker.username()] = id setTimeout( -> $scope.$apply() $('#video'+id).append(video) ,0) roomSubject = worker.subject('room') roomSub = roomSubject.filter( (r) -> r.op == 'join' ).subscribe( (ret) -> console.log('ret.data.members',ret.data.members) worker.webrtc().init($scope.room, true) ) roomSubDestry = roomSubject.filter( (r) -> r.op == 'destroy').subscribe( (ret) -> console.log('ret',ret) alert('This room is no longer available...') ) worker.onNext({slot:'room',op:'join',data:{name: $scope.room, members:$scope.members}}) $scope.$on("$destroy", -> worker.webrtc().stop() roomSub.dispose() roomSubDestry.dispose() ) ).controller('AppCtrl',($scope, $routeParams, $location, worker) -> # always in scope... $scope.roomList = [] roomSubject = worker.subject('room') roomSub = roomSubject.filter( (r) -> r.op == 'list' ).subscribe( (ret) -> console.log('room list', ret.data.rooms) $scope.roomList = ret.data.rooms setTimeout(-> $scope.$apply() ,0) ) ) webrtcControllers.factory("worker",['$rootScope','$q', ($rootScope,$q) -> window.WorkerData.testing = true window.WorkerData.role = window._role worker = new window.SocketWorker(window._username,window._token) worker.controllerOps ])
144928
# # Author: <NAME> # <EMAIL> # webrtcControllers = angular.module('webrtcControllers', []) webrtcControllers.controller('HomeCtrl', ($scope, $routeParams, $location, worker) -> $scope.user = name: '' role: '' $scope.room = name: '' members: '' $scope.connect = (u) -> worker.username = @username worker.role = @role worker.testing = true worker.connect() $scope.join = (name) -> $location.path('/room/'+name+'/none') setTimeout(-> $scope.$apply() ,0) $scope.joinRoom = (name) -> $location.path('/room/'+$scope.room.name+'/'+$scope.room.members) setTimeout(-> $scope.$apply() ,0) worker.onNext({slot:'room', op:'list',data:{}}) ).controller('RoomCtrl',($scope, $routeParams, $location, worker) -> $scope.room = $routeParams.room $scope.members = $routeParams.members.split(',') $scope.memberList = [] $scope.peers = [] $scope.local = {} $scope.msgs = [] $scope.message = '' jidToPeerId = {} $scope.chat = active: false dataChannelList = [] $scope.toggleChat = -> $scope.chat.active = !$scope.chat.active; setTimeout(-> $scope.$apply() ,0) $scope.sendMessage = (txt) -> $scope.msgs.push(txt) for dc in dataChannelList console.log('dataChannel', dc) dc.send(txt) $scope.message = '' setTimeout( -> $scope.$apply() ,0) $scope.webrtc = muteAudio: false muteVideo: false hangup: -> worker.webrtc().stop() worker.onNext({slot:'room',op:'leave',data:{room:$scope.room}}) call: (name) -> alert('call') toggleMuteVideo: -> $scope.webrtc.muteVideo = !$scope.webrtc.muteVideo worker.walkabout.webrtcVideoMute($scope.webrtc.muteVideo); setTimeout( -> $scope.$apply(); ,0) toggleMuteAudio: -> $scope.webrtc.muteAudio = !$scope.webrtc.muteAudio worker.walkabout.webrtcAudioMute($scope.webrtc.muteAudio); setTimeout( -> $scope.$apply() ,0) worker.webrtc().onAddRemoteStream = (uuid, video, dataChannel) -> id = $scope.peers.length+1; dataChannelList.push(dataChannel) $scope.peers.push({ uuid:uuid local: false username: '' id: id }) jidToPeerId[uuid] = id dataChannel.onmessage = (msg) => console.log('onmessage',msg) $scope.msgs.push(msg.data) setTimeout(-> $scope.$apply() ,0) setTimeout(-> $scope.$apply() $('#video'+id).append(video) ,0) worker.webrtc().onRemoveRemoteStream = (uuid) -> $scope.peers = $scope.peers.filter((p) -> p.uuid != uuid ) setTimeout(-> $scope.$apply() ,0) worker.webrtc().onAddLocalStream = (video) -> id = 0 $scope.local = uuid:worker.username() username: '' local: true id: id #$scope.peers.push($scope.local) jidToPeerId[worker.username()] = id setTimeout( -> $scope.$apply() $('#video'+id).append(video) ,0) roomSubject = worker.subject('room') roomSub = roomSubject.filter( (r) -> r.op == 'join' ).subscribe( (ret) -> console.log('ret.data.members',ret.data.members) worker.webrtc().init($scope.room, true) ) roomSubDestry = roomSubject.filter( (r) -> r.op == 'destroy').subscribe( (ret) -> console.log('ret',ret) alert('This room is no longer available...') ) worker.onNext({slot:'room',op:'join',data:{name: $scope.room, members:$scope.members}}) $scope.$on("$destroy", -> worker.webrtc().stop() roomSub.dispose() roomSubDestry.dispose() ) ).controller('AppCtrl',($scope, $routeParams, $location, worker) -> # always in scope... $scope.roomList = [] roomSubject = worker.subject('room') roomSub = roomSubject.filter( (r) -> r.op == 'list' ).subscribe( (ret) -> console.log('room list', ret.data.rooms) $scope.roomList = ret.data.rooms setTimeout(-> $scope.$apply() ,0) ) ) webrtcControllers.factory("worker",['$rootScope','$q', ($rootScope,$q) -> window.WorkerData.testing = true window.WorkerData.role = window._role worker = new window.SocketWorker(window._username,window._token) worker.controllerOps ])
true
# # Author: PI:NAME:<NAME>END_PI # PI:EMAIL:<EMAIL>END_PI # webrtcControllers = angular.module('webrtcControllers', []) webrtcControllers.controller('HomeCtrl', ($scope, $routeParams, $location, worker) -> $scope.user = name: '' role: '' $scope.room = name: '' members: '' $scope.connect = (u) -> worker.username = @username worker.role = @role worker.testing = true worker.connect() $scope.join = (name) -> $location.path('/room/'+name+'/none') setTimeout(-> $scope.$apply() ,0) $scope.joinRoom = (name) -> $location.path('/room/'+$scope.room.name+'/'+$scope.room.members) setTimeout(-> $scope.$apply() ,0) worker.onNext({slot:'room', op:'list',data:{}}) ).controller('RoomCtrl',($scope, $routeParams, $location, worker) -> $scope.room = $routeParams.room $scope.members = $routeParams.members.split(',') $scope.memberList = [] $scope.peers = [] $scope.local = {} $scope.msgs = [] $scope.message = '' jidToPeerId = {} $scope.chat = active: false dataChannelList = [] $scope.toggleChat = -> $scope.chat.active = !$scope.chat.active; setTimeout(-> $scope.$apply() ,0) $scope.sendMessage = (txt) -> $scope.msgs.push(txt) for dc in dataChannelList console.log('dataChannel', dc) dc.send(txt) $scope.message = '' setTimeout( -> $scope.$apply() ,0) $scope.webrtc = muteAudio: false muteVideo: false hangup: -> worker.webrtc().stop() worker.onNext({slot:'room',op:'leave',data:{room:$scope.room}}) call: (name) -> alert('call') toggleMuteVideo: -> $scope.webrtc.muteVideo = !$scope.webrtc.muteVideo worker.walkabout.webrtcVideoMute($scope.webrtc.muteVideo); setTimeout( -> $scope.$apply(); ,0) toggleMuteAudio: -> $scope.webrtc.muteAudio = !$scope.webrtc.muteAudio worker.walkabout.webrtcAudioMute($scope.webrtc.muteAudio); setTimeout( -> $scope.$apply() ,0) worker.webrtc().onAddRemoteStream = (uuid, video, dataChannel) -> id = $scope.peers.length+1; dataChannelList.push(dataChannel) $scope.peers.push({ uuid:uuid local: false username: '' id: id }) jidToPeerId[uuid] = id dataChannel.onmessage = (msg) => console.log('onmessage',msg) $scope.msgs.push(msg.data) setTimeout(-> $scope.$apply() ,0) setTimeout(-> $scope.$apply() $('#video'+id).append(video) ,0) worker.webrtc().onRemoveRemoteStream = (uuid) -> $scope.peers = $scope.peers.filter((p) -> p.uuid != uuid ) setTimeout(-> $scope.$apply() ,0) worker.webrtc().onAddLocalStream = (video) -> id = 0 $scope.local = uuid:worker.username() username: '' local: true id: id #$scope.peers.push($scope.local) jidToPeerId[worker.username()] = id setTimeout( -> $scope.$apply() $('#video'+id).append(video) ,0) roomSubject = worker.subject('room') roomSub = roomSubject.filter( (r) -> r.op == 'join' ).subscribe( (ret) -> console.log('ret.data.members',ret.data.members) worker.webrtc().init($scope.room, true) ) roomSubDestry = roomSubject.filter( (r) -> r.op == 'destroy').subscribe( (ret) -> console.log('ret',ret) alert('This room is no longer available...') ) worker.onNext({slot:'room',op:'join',data:{name: $scope.room, members:$scope.members}}) $scope.$on("$destroy", -> worker.webrtc().stop() roomSub.dispose() roomSubDestry.dispose() ) ).controller('AppCtrl',($scope, $routeParams, $location, worker) -> # always in scope... $scope.roomList = [] roomSubject = worker.subject('room') roomSub = roomSubject.filter( (r) -> r.op == 'list' ).subscribe( (ret) -> console.log('room list', ret.data.rooms) $scope.roomList = ret.data.rooms setTimeout(-> $scope.$apply() ,0) ) ) webrtcControllers.factory("worker",['$rootScope','$q', ($rootScope,$q) -> window.WorkerData.testing = true window.WorkerData.role = window._role worker = new window.SocketWorker(window._username,window._token) worker.controllerOps ])
[ { "context": "fc3-12c0-48c2-82ed-6eac9052acc9'\nmeshblu_token = 'f58db94b792816fc7b046c44acdd9a7f835fd45e'\n\nSAMPLES = [{\n name : 'kick',\n sampleUrl : '/s", "end": 111, "score": 0.5945132374763489, "start": 71, "tag": "PASSWORD", "value": "f58db94b792816fc7b046c44acdd9a7f835fd45e" }, ...
app/drums.coffee
octoblu/tone-site
1
meshblu_uuid = '50fc4fc3-12c0-48c2-82ed-6eac9052acc9' meshblu_token = 'f58db94b792816fc7b046c44acdd9a7f835fd45e' SAMPLES = [{ name : 'kick', sampleUrl : '/sounds/kick.wav' }, { name : 'bass', sampleUrl : '/sounds/bass/bass.wav' }, { name : 'clap', sampleUrl : '/sounds/clap.wav' }, { name : 'cymbal', sampleUrl : '/sounds/cymbal.wav' }, { name : 'hi hat', sampleUrl : '/sounds/hi hat.wav' }, { name : 'snare', sampleUrl : '/sounds/snare.wav' }, { name : 'tom', sampleUrl : '/sounds/tom.wav' }] class Drumkit constructor: (samples) -> @drumMachines = {} _.each samples, (drumConfig) => console.log 'setting up', drumConfig.name @drumMachines[drumConfig.name] = @setupDrum drumConfig play: (drumName) => drum = @drumMachines[drumName] return unless drum? drum.play() setupDrum: (drumConfig) => return new Howl { urls: [drumConfig.sampleUrl], volume: 1, buffer: false, onend: -> console.log 'played', drumConfig.name onload: -> console.log 'loaded', drumConfig.name } $ -> drumkit = new Drumkit SAMPLES config = uuid: meshblu_uuid token: meshblu_token server: 'wss://meshblu.octoblu.com' port: 443 type: 'device:drumkit' conn = meshblu.createConnection config window.conn = conn window.drumkit = drumkit conn.subscribe meshblu_uuid conn.on 'ready', => drumkitDevice = _.extend uuid: conn.options.uuid token: conn.options.token , config console.log 'Device Config', drumkitDevice # # $.cookie 'meshblu-drumkit', JSON.stringify drumkitDevice # # # # $(".meshblu-uuid").text drumkitDevice.uuid # # $(".meshblu-token").text drumkitDevice.token conn.on 'message', (message) => console.log 'message', message if message.topic == 'set-property' drumkit[message.payload.property] = message.payload.value; return drumkit[message.topic]?(message.payload.sound)
81513
meshblu_uuid = '50fc4fc3-12c0-48c2-82ed-6eac9052acc9' meshblu_token = '<PASSWORD>' SAMPLES = [{ name : 'kick', sampleUrl : '/sounds/kick.wav' }, { name : 'bass', sampleUrl : '/sounds/bass/bass.wav' }, { name : 'clap', sampleUrl : '/sounds/clap.wav' }, { name : 'cymbal', sampleUrl : '/sounds/cymbal.wav' }, { name : 'hi hat', sampleUrl : '/sounds/hi hat.wav' }, { name : 'snare', sampleUrl : '/sounds/snare.wav' }, { name : 'tom', sampleUrl : '/sounds/tom.wav' }] class Drumkit constructor: (samples) -> @drumMachines = {} _.each samples, (drumConfig) => console.log 'setting up', drumConfig.name @drumMachines[drumConfig.name] = @setupDrum drumConfig play: (drumName) => drum = @drumMachines[drumName] return unless drum? drum.play() setupDrum: (drumConfig) => return new Howl { urls: [drumConfig.sampleUrl], volume: 1, buffer: false, onend: -> console.log 'played', drumConfig.name onload: -> console.log 'loaded', drumConfig.name } $ -> drumkit = new Drumkit SAMPLES config = uuid: meshblu_uuid token: <PASSWORD> server: 'wss://meshblu.octoblu.com' port: 443 type: 'device:drumkit' conn = meshblu.createConnection config window.conn = conn window.drumkit = drumkit conn.subscribe meshblu_uuid conn.on 'ready', => drumkitDevice = _.extend uuid: conn.options.uuid token: conn.options.token , config console.log 'Device Config', drumkitDevice # # $.cookie 'meshblu-drumkit', JSON.stringify drumkitDevice # # # # $(".meshblu-uuid").text drumkitDevice.uuid # # $(".meshblu-token").text drumkitDevice.token conn.on 'message', (message) => console.log 'message', message if message.topic == 'set-property' drumkit[message.payload.property] = message.payload.value; return drumkit[message.topic]?(message.payload.sound)
true
meshblu_uuid = '50fc4fc3-12c0-48c2-82ed-6eac9052acc9' meshblu_token = 'PI:PASSWORD:<PASSWORD>END_PI' SAMPLES = [{ name : 'kick', sampleUrl : '/sounds/kick.wav' }, { name : 'bass', sampleUrl : '/sounds/bass/bass.wav' }, { name : 'clap', sampleUrl : '/sounds/clap.wav' }, { name : 'cymbal', sampleUrl : '/sounds/cymbal.wav' }, { name : 'hi hat', sampleUrl : '/sounds/hi hat.wav' }, { name : 'snare', sampleUrl : '/sounds/snare.wav' }, { name : 'tom', sampleUrl : '/sounds/tom.wav' }] class Drumkit constructor: (samples) -> @drumMachines = {} _.each samples, (drumConfig) => console.log 'setting up', drumConfig.name @drumMachines[drumConfig.name] = @setupDrum drumConfig play: (drumName) => drum = @drumMachines[drumName] return unless drum? drum.play() setupDrum: (drumConfig) => return new Howl { urls: [drumConfig.sampleUrl], volume: 1, buffer: false, onend: -> console.log 'played', drumConfig.name onload: -> console.log 'loaded', drumConfig.name } $ -> drumkit = new Drumkit SAMPLES config = uuid: meshblu_uuid token: PI:PASSWORD:<PASSWORD>END_PI server: 'wss://meshblu.octoblu.com' port: 443 type: 'device:drumkit' conn = meshblu.createConnection config window.conn = conn window.drumkit = drumkit conn.subscribe meshblu_uuid conn.on 'ready', => drumkitDevice = _.extend uuid: conn.options.uuid token: conn.options.token , config console.log 'Device Config', drumkitDevice # # $.cookie 'meshblu-drumkit', JSON.stringify drumkitDevice # # # # $(".meshblu-uuid").text drumkitDevice.uuid # # $(".meshblu-token").text drumkitDevice.token conn.on 'message', (message) => console.log 'message', message if message.topic == 'set-property' drumkit[message.payload.property] = message.payload.value; return drumkit[message.topic]?(message.payload.sound)
[ { "context": "usr/bin/env coffee\n#\n# Animation script for HQZ.\n# Micah Elizabeth Scott <micah@scanlime.org>\n# Creative Commons BY-SA lic", "end": 75, "score": 0.9998683929443359, "start": 54, "tag": "NAME", "value": "Micah Elizabeth Scott" }, { "context": "nimation script for HQZ...
example /hqz/examples/harmonic.coffee
amane312/photon_generator
0
#!/usr/bin/env coffee # # Animation script for HQZ. # Micah Elizabeth Scott <micah@scanlime.org> # Creative Commons BY-SA license: # http://creativecommons.org/licenses/by-sa/3.0/ # plot = require './plot' arc4rand = require 'arc4rand' TAU = Math.PI * 2 toRadians = (degrees) -> degrees * (Math.PI / 180.0) harmonicOscillator = (frame, opts) -> rnd = (new arc4rand(opts.seed)).random # Calculate series coefficients once per frame series = for i in [1 .. 20] freq: i amplitude: rnd(0, 1.0) / i phase: rnd(0, TAU) + rnd(-0.01, 0.01) * frame plot opts, (t) -> # Draw a truncated Fourier series, in polar coordinates t *= TAU r = 0 r += s.amplitude * Math.sin(s.freq * (t + s.phase)) for s in series r = opts.radius + r * opts.radius * opts.modulationDepth [ opts.x0 + r * Math.cos(t), opts.y0 + r * Math.sin(t) ] zoomViewport = (width, height, focusX, focusY, zoom) -> left = focusX right = width - focusX top = focusY bottom = height - focusY scale = 1.0 - zoom left = focusX - left * scale right = focusX + right * scale top = focusY - top * scale bottom = focusY + bottom * scale [ left, top, right - left, bottom - top ] scene = (frame) -> # Glowing oscillator also moves, eventually intersecting the other. glowy = x: 1920*0.8 y: 1080/3 speed: 0.9 angle: toRadians 160 glowy.x += glowy.speed * frame * Math.cos glowy.angle glowy.y += glowy.speed * frame * Math.sin glowy.angle resolution: [1920, 1080] timelimit: 60 * 60 rays: 5000000 seed: frame * 100000 exposure: 0.7 gamma: 1.8 viewport: zoomViewport 1920, 1080, 1920/2, 1080/2, frame * 0.001 lights: [ [0.75, 1920/2, 1080/2, [0, -180], 1200, [0, 360], 480] [0.2, 1920/2, 1080/2, [0, -180], 1200, [0, 360], 0] [0.1, glowy.x, glowy.y, [0, 360], [0, 15], [0, 360], 590] ] objects: [].concat [], harmonicOscillator frame, material: 0 seed: 's' x0: 1920*0.4 y0: 1080*2/3 radius: 500 modulationDepth: 0.25 harmonicOscillator frame, material: 1 seed: 't' x0: glowy.x y0: glowy.y radius: 120 modulationDepth: 0.25 materials: [ # 0. Light catching. Lots of internal reflection. [ [0.1, "d"], [0.9, "r"] ] # 1. Light emitting. Diffuse the light, reflect only a little. [ [0.99, "d"], [0.01, "r"] ] ] console.log JSON.stringify scene i for i in [0 .. 800] #console.log JSON.stringify scene 0
11865
#!/usr/bin/env coffee # # Animation script for HQZ. # <NAME> <<EMAIL>> # Creative Commons BY-SA license: # http://creativecommons.org/licenses/by-sa/3.0/ # plot = require './plot' arc4rand = require 'arc4rand' TAU = Math.PI * 2 toRadians = (degrees) -> degrees * (Math.PI / 180.0) harmonicOscillator = (frame, opts) -> rnd = (new arc4rand(opts.seed)).random # Calculate series coefficients once per frame series = for i in [1 .. 20] freq: i amplitude: rnd(0, 1.0) / i phase: rnd(0, TAU) + rnd(-0.01, 0.01) * frame plot opts, (t) -> # Draw a truncated Fourier series, in polar coordinates t *= TAU r = 0 r += s.amplitude * Math.sin(s.freq * (t + s.phase)) for s in series r = opts.radius + r * opts.radius * opts.modulationDepth [ opts.x0 + r * Math.cos(t), opts.y0 + r * Math.sin(t) ] zoomViewport = (width, height, focusX, focusY, zoom) -> left = focusX right = width - focusX top = focusY bottom = height - focusY scale = 1.0 - zoom left = focusX - left * scale right = focusX + right * scale top = focusY - top * scale bottom = focusY + bottom * scale [ left, top, right - left, bottom - top ] scene = (frame) -> # Glowing oscillator also moves, eventually intersecting the other. glowy = x: 1920*0.8 y: 1080/3 speed: 0.9 angle: toRadians 160 glowy.x += glowy.speed * frame * Math.cos glowy.angle glowy.y += glowy.speed * frame * Math.sin glowy.angle resolution: [1920, 1080] timelimit: 60 * 60 rays: 5000000 seed: frame * 100000 exposure: 0.7 gamma: 1.8 viewport: zoomViewport 1920, 1080, 1920/2, 1080/2, frame * 0.001 lights: [ [0.75, 1920/2, 1080/2, [0, -180], 1200, [0, 360], 480] [0.2, 1920/2, 1080/2, [0, -180], 1200, [0, 360], 0] [0.1, glowy.x, glowy.y, [0, 360], [0, 15], [0, 360], 590] ] objects: [].concat [], harmonicOscillator frame, material: 0 seed: 's' x0: 1920*0.4 y0: 1080*2/3 radius: 500 modulationDepth: 0.25 harmonicOscillator frame, material: 1 seed: 't' x0: glowy.x y0: glowy.y radius: 120 modulationDepth: 0.25 materials: [ # 0. Light catching. Lots of internal reflection. [ [0.1, "d"], [0.9, "r"] ] # 1. Light emitting. Diffuse the light, reflect only a little. [ [0.99, "d"], [0.01, "r"] ] ] console.log JSON.stringify scene i for i in [0 .. 800] #console.log JSON.stringify scene 0
true
#!/usr/bin/env coffee # # Animation script for HQZ. # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Creative Commons BY-SA license: # http://creativecommons.org/licenses/by-sa/3.0/ # plot = require './plot' arc4rand = require 'arc4rand' TAU = Math.PI * 2 toRadians = (degrees) -> degrees * (Math.PI / 180.0) harmonicOscillator = (frame, opts) -> rnd = (new arc4rand(opts.seed)).random # Calculate series coefficients once per frame series = for i in [1 .. 20] freq: i amplitude: rnd(0, 1.0) / i phase: rnd(0, TAU) + rnd(-0.01, 0.01) * frame plot opts, (t) -> # Draw a truncated Fourier series, in polar coordinates t *= TAU r = 0 r += s.amplitude * Math.sin(s.freq * (t + s.phase)) for s in series r = opts.radius + r * opts.radius * opts.modulationDepth [ opts.x0 + r * Math.cos(t), opts.y0 + r * Math.sin(t) ] zoomViewport = (width, height, focusX, focusY, zoom) -> left = focusX right = width - focusX top = focusY bottom = height - focusY scale = 1.0 - zoom left = focusX - left * scale right = focusX + right * scale top = focusY - top * scale bottom = focusY + bottom * scale [ left, top, right - left, bottom - top ] scene = (frame) -> # Glowing oscillator also moves, eventually intersecting the other. glowy = x: 1920*0.8 y: 1080/3 speed: 0.9 angle: toRadians 160 glowy.x += glowy.speed * frame * Math.cos glowy.angle glowy.y += glowy.speed * frame * Math.sin glowy.angle resolution: [1920, 1080] timelimit: 60 * 60 rays: 5000000 seed: frame * 100000 exposure: 0.7 gamma: 1.8 viewport: zoomViewport 1920, 1080, 1920/2, 1080/2, frame * 0.001 lights: [ [0.75, 1920/2, 1080/2, [0, -180], 1200, [0, 360], 480] [0.2, 1920/2, 1080/2, [0, -180], 1200, [0, 360], 0] [0.1, glowy.x, glowy.y, [0, 360], [0, 15], [0, 360], 590] ] objects: [].concat [], harmonicOscillator frame, material: 0 seed: 's' x0: 1920*0.4 y0: 1080*2/3 radius: 500 modulationDepth: 0.25 harmonicOscillator frame, material: 1 seed: 't' x0: glowy.x y0: glowy.y radius: 120 modulationDepth: 0.25 materials: [ # 0. Light catching. Lots of internal reflection. [ [0.1, "d"], [0.9, "r"] ] # 1. Light emitting. Diffuse the light, reflect only a little. [ [0.99, "d"], [0.01, "r"] ] ] console.log JSON.stringify scene i for i in [0 .. 800] #console.log JSON.stringify scene 0
[ { "context": "b)->\n ops = options user\n ops.body =\n name: 'test project'\n createdDate: new Date()\n request.po", "end": 526, "score": 0.7982785701751709, "start": 522, "tag": "NAME", "value": "test" } ]
test/routes/time_entries.coffee
t3mpus/tempus-api
3
request = require 'request' async = require 'async' should = require 'should' _ = require 'underscore' uuid = require 'uuid' startApp = require './../start_app' base = require './../base' optionsBase = require './../options' user_test_helper = require './user_test_helper' TimeEntry = require "#{__dirname}/../../models/time_entry" testUser = undefined testProject = undefined timeEntriesCreated = [] options = (u)-> optionsBase u or testUser makeProject = (user, cb)-> ops = options user ops.body = name: 'test project' createdDate: new Date() request.post (base '/projects'), ops, (e,r,b)-> cb b describe 'Time Entries', -> before (done) -> startApp -> user_test_helper.makeUser (user)-> testUser = user makeProject user, (project)-> testProject = project done() after (done) -> deleteUserAndProject = (cb)-> async.eachSeries [ {what: 'projects', id:testProject.id} {what: 'users', id:testUser.id} ], (obj)-> request.del (base "/#{obj.what}/#{obj.id}"), options(), (e,r,b)-> cb(e) deleteTimeEntries = (cb)-> async.each timeEntriesCreated, (e, cb)-> request.del (base "/time_entries/#{e.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 cb e , cb async.parallel [deleteTimeEntries, deleteUserAndProject], done it 'should make a time entry', (done)-> ops = options() ops.body = start: new Date('May 4 1987') end: new Date() message: 'I am a wonderful time entry :)' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 te = new TimeEntry b timeEntriesCreated.push te te.validate().should.be.true done() it 'should make a time entry with only duration', (done)-> ops = options() ops.body = duration: 40.5 message: 'check yourself before you wreck yourself' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 te = new TimeEntry b timeEntriesCreated.push te te.validate().should.be.true done() it 'should not be able to insert a te without duration or start and end', (done)-> ops = options() ops.body = message: 'check yourself before you wreck yourself' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 400 done() it 'should not process a te with a negative duration', (done)-> ops = options() ops.body = message: 'check yourself before you wreck yourself' projectId: testProject.id duration: -300 request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 400 done() it 'should get a time entry', (done)-> ops = options() ops.body = start: new Date('January 1 1994') end: new Date() message: 'Try and get me!!!' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 te = new TimeEntry b timeEntriesCreated.push te te.validate().should.be.true request (base "/time_entries/#{te.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 tegb = new TimeEntry b tegb.validate().should.be.true done() it 'should delete a time entry', (done)-> ops = options() ops.body = start: new Date('June 18, 2013') end: new Date('June 22, 2013') message: 'I will be deleted very soon!' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> teb = new TimeEntry b r.statusCode.should.be.equal 200 request.del (base "/time_entries/#{teb.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 request (base "/time_entries/#{teb.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 404 done() describe 'in a project', -> it 'should have time entries associated with the project', (done)-> request.get (base "/projects/#{testProject.id}/time_entries"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 b.should.have.property 'length' if b.length is 0 throw new Error 'No time_entries to test' else _.every b, (t)-> (new TimeEntry t).validate().should.be.true done() it 'should have an appropriate error with a bad project id', (done)-> request.get (base "/projects/999933/time_entries"), options(), (e,r,b) -> r.statusCode.should.be.equal 404 b.error.should.not.be.equal null done() it 'should delete time entries if project is deleted', (done) -> makeProject testUser, (p) -> makeTimeEntry = (seed, cb)-> ops = options() ops.body = start: new Date() end: new Date() message: 'I will be deleted very soon!' + seed projectId: p.id request.post (base "/time_entries"), ops, (e,r,b)-> cb null, b makeEntries = (num, cb)-> async.map [1..num], makeTimeEntry, (err, entries)-> entries.length.should.be.equal num cb() checkEntries = (num, cb) -> request.get (base "/time_entries?projectId=#{p.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 b.length.should.equal num cb() deleteProject = (project, cb)-> request.del (base "/projects/#{p.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 cb() desiredEntries = 10 makeEntries desiredEntries, ()-> checkEntries desiredEntries, ()-> deleteProject p, ()-> checkEntries 0, done
121636
request = require 'request' async = require 'async' should = require 'should' _ = require 'underscore' uuid = require 'uuid' startApp = require './../start_app' base = require './../base' optionsBase = require './../options' user_test_helper = require './user_test_helper' TimeEntry = require "#{__dirname}/../../models/time_entry" testUser = undefined testProject = undefined timeEntriesCreated = [] options = (u)-> optionsBase u or testUser makeProject = (user, cb)-> ops = options user ops.body = name: '<NAME> project' createdDate: new Date() request.post (base '/projects'), ops, (e,r,b)-> cb b describe 'Time Entries', -> before (done) -> startApp -> user_test_helper.makeUser (user)-> testUser = user makeProject user, (project)-> testProject = project done() after (done) -> deleteUserAndProject = (cb)-> async.eachSeries [ {what: 'projects', id:testProject.id} {what: 'users', id:testUser.id} ], (obj)-> request.del (base "/#{obj.what}/#{obj.id}"), options(), (e,r,b)-> cb(e) deleteTimeEntries = (cb)-> async.each timeEntriesCreated, (e, cb)-> request.del (base "/time_entries/#{e.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 cb e , cb async.parallel [deleteTimeEntries, deleteUserAndProject], done it 'should make a time entry', (done)-> ops = options() ops.body = start: new Date('May 4 1987') end: new Date() message: 'I am a wonderful time entry :)' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 te = new TimeEntry b timeEntriesCreated.push te te.validate().should.be.true done() it 'should make a time entry with only duration', (done)-> ops = options() ops.body = duration: 40.5 message: 'check yourself before you wreck yourself' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 te = new TimeEntry b timeEntriesCreated.push te te.validate().should.be.true done() it 'should not be able to insert a te without duration or start and end', (done)-> ops = options() ops.body = message: 'check yourself before you wreck yourself' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 400 done() it 'should not process a te with a negative duration', (done)-> ops = options() ops.body = message: 'check yourself before you wreck yourself' projectId: testProject.id duration: -300 request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 400 done() it 'should get a time entry', (done)-> ops = options() ops.body = start: new Date('January 1 1994') end: new Date() message: 'Try and get me!!!' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 te = new TimeEntry b timeEntriesCreated.push te te.validate().should.be.true request (base "/time_entries/#{te.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 tegb = new TimeEntry b tegb.validate().should.be.true done() it 'should delete a time entry', (done)-> ops = options() ops.body = start: new Date('June 18, 2013') end: new Date('June 22, 2013') message: 'I will be deleted very soon!' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> teb = new TimeEntry b r.statusCode.should.be.equal 200 request.del (base "/time_entries/#{teb.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 request (base "/time_entries/#{teb.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 404 done() describe 'in a project', -> it 'should have time entries associated with the project', (done)-> request.get (base "/projects/#{testProject.id}/time_entries"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 b.should.have.property 'length' if b.length is 0 throw new Error 'No time_entries to test' else _.every b, (t)-> (new TimeEntry t).validate().should.be.true done() it 'should have an appropriate error with a bad project id', (done)-> request.get (base "/projects/999933/time_entries"), options(), (e,r,b) -> r.statusCode.should.be.equal 404 b.error.should.not.be.equal null done() it 'should delete time entries if project is deleted', (done) -> makeProject testUser, (p) -> makeTimeEntry = (seed, cb)-> ops = options() ops.body = start: new Date() end: new Date() message: 'I will be deleted very soon!' + seed projectId: p.id request.post (base "/time_entries"), ops, (e,r,b)-> cb null, b makeEntries = (num, cb)-> async.map [1..num], makeTimeEntry, (err, entries)-> entries.length.should.be.equal num cb() checkEntries = (num, cb) -> request.get (base "/time_entries?projectId=#{p.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 b.length.should.equal num cb() deleteProject = (project, cb)-> request.del (base "/projects/#{p.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 cb() desiredEntries = 10 makeEntries desiredEntries, ()-> checkEntries desiredEntries, ()-> deleteProject p, ()-> checkEntries 0, done
true
request = require 'request' async = require 'async' should = require 'should' _ = require 'underscore' uuid = require 'uuid' startApp = require './../start_app' base = require './../base' optionsBase = require './../options' user_test_helper = require './user_test_helper' TimeEntry = require "#{__dirname}/../../models/time_entry" testUser = undefined testProject = undefined timeEntriesCreated = [] options = (u)-> optionsBase u or testUser makeProject = (user, cb)-> ops = options user ops.body = name: 'PI:NAME:<NAME>END_PI project' createdDate: new Date() request.post (base '/projects'), ops, (e,r,b)-> cb b describe 'Time Entries', -> before (done) -> startApp -> user_test_helper.makeUser (user)-> testUser = user makeProject user, (project)-> testProject = project done() after (done) -> deleteUserAndProject = (cb)-> async.eachSeries [ {what: 'projects', id:testProject.id} {what: 'users', id:testUser.id} ], (obj)-> request.del (base "/#{obj.what}/#{obj.id}"), options(), (e,r,b)-> cb(e) deleteTimeEntries = (cb)-> async.each timeEntriesCreated, (e, cb)-> request.del (base "/time_entries/#{e.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 cb e , cb async.parallel [deleteTimeEntries, deleteUserAndProject], done it 'should make a time entry', (done)-> ops = options() ops.body = start: new Date('May 4 1987') end: new Date() message: 'I am a wonderful time entry :)' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 te = new TimeEntry b timeEntriesCreated.push te te.validate().should.be.true done() it 'should make a time entry with only duration', (done)-> ops = options() ops.body = duration: 40.5 message: 'check yourself before you wreck yourself' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 te = new TimeEntry b timeEntriesCreated.push te te.validate().should.be.true done() it 'should not be able to insert a te without duration or start and end', (done)-> ops = options() ops.body = message: 'check yourself before you wreck yourself' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 400 done() it 'should not process a te with a negative duration', (done)-> ops = options() ops.body = message: 'check yourself before you wreck yourself' projectId: testProject.id duration: -300 request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 400 done() it 'should get a time entry', (done)-> ops = options() ops.body = start: new Date('January 1 1994') end: new Date() message: 'Try and get me!!!' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 te = new TimeEntry b timeEntriesCreated.push te te.validate().should.be.true request (base "/time_entries/#{te.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 tegb = new TimeEntry b tegb.validate().should.be.true done() it 'should delete a time entry', (done)-> ops = options() ops.body = start: new Date('June 18, 2013') end: new Date('June 22, 2013') message: 'I will be deleted very soon!' projectId: testProject.id request.post (base '/time_entries'), ops, (e,r,b)-> teb = new TimeEntry b r.statusCode.should.be.equal 200 request.del (base "/time_entries/#{teb.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 request (base "/time_entries/#{teb.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 404 done() describe 'in a project', -> it 'should have time entries associated with the project', (done)-> request.get (base "/projects/#{testProject.id}/time_entries"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 b.should.have.property 'length' if b.length is 0 throw new Error 'No time_entries to test' else _.every b, (t)-> (new TimeEntry t).validate().should.be.true done() it 'should have an appropriate error with a bad project id', (done)-> request.get (base "/projects/999933/time_entries"), options(), (e,r,b) -> r.statusCode.should.be.equal 404 b.error.should.not.be.equal null done() it 'should delete time entries if project is deleted', (done) -> makeProject testUser, (p) -> makeTimeEntry = (seed, cb)-> ops = options() ops.body = start: new Date() end: new Date() message: 'I will be deleted very soon!' + seed projectId: p.id request.post (base "/time_entries"), ops, (e,r,b)-> cb null, b makeEntries = (num, cb)-> async.map [1..num], makeTimeEntry, (err, entries)-> entries.length.should.be.equal num cb() checkEntries = (num, cb) -> request.get (base "/time_entries?projectId=#{p.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 b.length.should.equal num cb() deleteProject = (project, cb)-> request.del (base "/projects/#{p.id}"), options(), (e,r,b)-> r.statusCode.should.be.equal 200 cb() desiredEntries = 10 makeEntries desiredEntries, ()-> checkEntries desiredEntries, ()-> deleteProject p, ()-> checkEntries 0, done
[ { "context": "###\n#Auth Configuration\n*__Author__: Panjie SW <panjie@panjiesw.com>*\n*__Project__: ah-auth-plug", "end": 46, "score": 0.9998669028282166, "start": 37, "tag": "NAME", "value": "Panjie SW" }, { "context": "###\n#Auth Configuration\n*__Author__: Panjie SW <panjie@panji...
.src/config/auth.coffee
manjunathkg/ah-auth-plugin
0
### #Auth Configuration *__Author__: Panjie SW <panjie@panjiesw.com>* *__Project__: ah-auth-plugin* *__Company__: PanjieSW* Defines configuration for Auth plugin. ********************************************* ### exports['default'] = auth: (api) -> ### Verification process. If it's enabled then a newly signed up user will have to verify their email account before able to sign in. Defaults to ``true``. ### enableVerification: yes ### JSON Web Token configurations. ### jwt: ### Secret string used in signing the json payload. Be sure to change this in production. ### secret: 'some-secret' ### Algorithm used in signing the json payload. See https://github.com/auth0/node-jsonwebtoken#algorithms-supported for list of supported algorithms. Defaults to ``HS512``. ### algorithm: "HS512" ### How long the token will expire in milisecond. If the token is expired then the signed in user has to relogin. Defaults to 2 hours time. ### expire: 2*60*60*1000 ### Scrypt configurations. Scrypt is used in encoding the user's password before saving it to database. Also for verifying it later in signin process. ### scrypt: # Password hash maxtime used in encoding password, in second. maxtime: 0.2
6368
### #Auth Configuration *__Author__: <NAME> <<EMAIL>>* *__Project__: ah-auth-plugin* *__Company__: PanjieSW* Defines configuration for Auth plugin. ********************************************* ### exports['default'] = auth: (api) -> ### Verification process. If it's enabled then a newly signed up user will have to verify their email account before able to sign in. Defaults to ``true``. ### enableVerification: yes ### JSON Web Token configurations. ### jwt: ### Secret string used in signing the json payload. Be sure to change this in production. ### secret: 'some-secret' ### Algorithm used in signing the json payload. See https://github.com/auth0/node-jsonwebtoken#algorithms-supported for list of supported algorithms. Defaults to ``HS512``. ### algorithm: "HS512" ### How long the token will expire in milisecond. If the token is expired then the signed in user has to relogin. Defaults to 2 hours time. ### expire: 2*60*60*1000 ### Scrypt configurations. Scrypt is used in encoding the user's password before saving it to database. Also for verifying it later in signin process. ### scrypt: # Password hash maxtime used in encoding password, in second. maxtime: 0.2
true
### #Auth Configuration *__Author__: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>* *__Project__: ah-auth-plugin* *__Company__: PanjieSW* Defines configuration for Auth plugin. ********************************************* ### exports['default'] = auth: (api) -> ### Verification process. If it's enabled then a newly signed up user will have to verify their email account before able to sign in. Defaults to ``true``. ### enableVerification: yes ### JSON Web Token configurations. ### jwt: ### Secret string used in signing the json payload. Be sure to change this in production. ### secret: 'some-secret' ### Algorithm used in signing the json payload. See https://github.com/auth0/node-jsonwebtoken#algorithms-supported for list of supported algorithms. Defaults to ``HS512``. ### algorithm: "HS512" ### How long the token will expire in milisecond. If the token is expired then the signed in user has to relogin. Defaults to 2 hours time. ### expire: 2*60*60*1000 ### Scrypt configurations. Scrypt is used in encoding the user's password before saving it to database. Also for verifying it later in signin process. ### scrypt: # Password hash maxtime used in encoding password, in second. maxtime: 0.2
[ { "context": "_NAME = 'autocomplete-robot-framework'\nCFG_KEY = 'autocomplete-robot-framework'\n\nTIMEOUT=5000 #ms\n\ndescribe 'Autocomplete Robot ", "end": 221, "score": 0.9991658926010132, "start": 193, "tag": "KEY", "value": "autocomplete-robot-framework" } ]
spec/autocomplete-robot-provider-spec.coffee
cweidner3/autocomplete-robot-framework
7
pathUtils = require('path') robotParser = require('../lib/parse-robot') libdocParser = require('../lib/parse-libdoc') fs = require 'fs' PACKAGE_NAME = 'autocomplete-robot-framework' CFG_KEY = 'autocomplete-robot-framework' TIMEOUT=5000 #ms describe 'Autocomplete Robot Provider', -> [provider, editor]=[] beforeEach -> waitsForPromise -> atom.packages.activatePackage(PACKAGE_NAME) runs -> mainModule = atom.packages.getActivePackage(PACKAGE_NAME).mainModule autocompletePlusProvider = mainModule.getAutocompletePlusProvider() provider = mainModule.getAutocompleteRobotProvider() waitsForPromise -> atom.workspace.open('autocomplete/Test_Autocomplete_Testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() waitsFor -> return !autocompletePlusProvider.loading , 'Provider should finish loading', TIMEOUT it 'finds keyword by name', -> keywords = provider.getKeywordsByName('Run Program') expect(keywords).toBeDefined() expect(keywords.length).toEqual 1 keyword = keywords[0] resource = provider.getResourceByKey(keyword.resourceKey) expect(pathUtils.basename(resource.path)).toEqual 'Test_Autocomplete_Keywords.rOBOt' it 'finds duplicated keywords by name', -> keywords = provider.getKeywordsByName('non existing keyword') expect(keywords).toBeDefined() expect(keywords.length).toEqual 0 keywords = provider.getKeywordsByName('Duplicated keyword') expect(keywords).toBeDefined() expect(keywords.length).toEqual 2 it 'finds resource by key', -> resource = provider.getResourceByKey('non existing resource') expect(resource).not.toBeDefined() resourceKey = editor.getPath().toLowerCase() resource = provider.getResourceByKey(resourceKey) expect(resource).toBeDefined() expect(resource.keywords.length).toBeGreaterThan 0 expect(resource.keywords[0].name).toEqual 'Private keyword' it 'provides all keyword names', -> kwNames = provider.getKeywordNames() expect(kwNames).toContain('Run Program', 'Dot.punctuation keyword', 'Duplicated keyword') expect(kwNames.indexOf('Duplicated keyword')).toEqual(kwNames.lastIndexOf('Duplicated keyword')) for name in kwNames keywords = provider.getKeywordsByName(name) expect(keywords.length).toBeGreaterThan 0 it 'provides all resource keys', -> resourceKeys = provider.getResourceKeys() resourceNames = [] for resourceKey in resourceKeys resourceNames.push(pathUtils.basename(resourceKey)) expect(resourceNames).toContain 'test_autocomplete_keywords.robot' for resourceKey in resourceKeys resource = provider.getResourceByKey(resourceKey) expect(resource).toBeDefined() it 'provides library source information', -> keywords = provider.getKeywordsByName('Should Match') expect(keywords).toBeDefined() expect(keywords.length).toEqual 1 keyword = keywords[0] resource = provider.getResourceByKey(keyword.resourceKey) expect(resource.libraryPath).toContain '.py'
78582
pathUtils = require('path') robotParser = require('../lib/parse-robot') libdocParser = require('../lib/parse-libdoc') fs = require 'fs' PACKAGE_NAME = 'autocomplete-robot-framework' CFG_KEY = '<KEY>' TIMEOUT=5000 #ms describe 'Autocomplete Robot Provider', -> [provider, editor]=[] beforeEach -> waitsForPromise -> atom.packages.activatePackage(PACKAGE_NAME) runs -> mainModule = atom.packages.getActivePackage(PACKAGE_NAME).mainModule autocompletePlusProvider = mainModule.getAutocompletePlusProvider() provider = mainModule.getAutocompleteRobotProvider() waitsForPromise -> atom.workspace.open('autocomplete/Test_Autocomplete_Testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() waitsFor -> return !autocompletePlusProvider.loading , 'Provider should finish loading', TIMEOUT it 'finds keyword by name', -> keywords = provider.getKeywordsByName('Run Program') expect(keywords).toBeDefined() expect(keywords.length).toEqual 1 keyword = keywords[0] resource = provider.getResourceByKey(keyword.resourceKey) expect(pathUtils.basename(resource.path)).toEqual 'Test_Autocomplete_Keywords.rOBOt' it 'finds duplicated keywords by name', -> keywords = provider.getKeywordsByName('non existing keyword') expect(keywords).toBeDefined() expect(keywords.length).toEqual 0 keywords = provider.getKeywordsByName('Duplicated keyword') expect(keywords).toBeDefined() expect(keywords.length).toEqual 2 it 'finds resource by key', -> resource = provider.getResourceByKey('non existing resource') expect(resource).not.toBeDefined() resourceKey = editor.getPath().toLowerCase() resource = provider.getResourceByKey(resourceKey) expect(resource).toBeDefined() expect(resource.keywords.length).toBeGreaterThan 0 expect(resource.keywords[0].name).toEqual 'Private keyword' it 'provides all keyword names', -> kwNames = provider.getKeywordNames() expect(kwNames).toContain('Run Program', 'Dot.punctuation keyword', 'Duplicated keyword') expect(kwNames.indexOf('Duplicated keyword')).toEqual(kwNames.lastIndexOf('Duplicated keyword')) for name in kwNames keywords = provider.getKeywordsByName(name) expect(keywords.length).toBeGreaterThan 0 it 'provides all resource keys', -> resourceKeys = provider.getResourceKeys() resourceNames = [] for resourceKey in resourceKeys resourceNames.push(pathUtils.basename(resourceKey)) expect(resourceNames).toContain 'test_autocomplete_keywords.robot' for resourceKey in resourceKeys resource = provider.getResourceByKey(resourceKey) expect(resource).toBeDefined() it 'provides library source information', -> keywords = provider.getKeywordsByName('Should Match') expect(keywords).toBeDefined() expect(keywords.length).toEqual 1 keyword = keywords[0] resource = provider.getResourceByKey(keyword.resourceKey) expect(resource.libraryPath).toContain '.py'
true
pathUtils = require('path') robotParser = require('../lib/parse-robot') libdocParser = require('../lib/parse-libdoc') fs = require 'fs' PACKAGE_NAME = 'autocomplete-robot-framework' CFG_KEY = 'PI:KEY:<KEY>END_PI' TIMEOUT=5000 #ms describe 'Autocomplete Robot Provider', -> [provider, editor]=[] beforeEach -> waitsForPromise -> atom.packages.activatePackage(PACKAGE_NAME) runs -> mainModule = atom.packages.getActivePackage(PACKAGE_NAME).mainModule autocompletePlusProvider = mainModule.getAutocompletePlusProvider() provider = mainModule.getAutocompleteRobotProvider() waitsForPromise -> atom.workspace.open('autocomplete/Test_Autocomplete_Testcase.robot') runs -> editor = atom.workspace.getActiveTextEditor() waitsFor -> return !autocompletePlusProvider.loading , 'Provider should finish loading', TIMEOUT it 'finds keyword by name', -> keywords = provider.getKeywordsByName('Run Program') expect(keywords).toBeDefined() expect(keywords.length).toEqual 1 keyword = keywords[0] resource = provider.getResourceByKey(keyword.resourceKey) expect(pathUtils.basename(resource.path)).toEqual 'Test_Autocomplete_Keywords.rOBOt' it 'finds duplicated keywords by name', -> keywords = provider.getKeywordsByName('non existing keyword') expect(keywords).toBeDefined() expect(keywords.length).toEqual 0 keywords = provider.getKeywordsByName('Duplicated keyword') expect(keywords).toBeDefined() expect(keywords.length).toEqual 2 it 'finds resource by key', -> resource = provider.getResourceByKey('non existing resource') expect(resource).not.toBeDefined() resourceKey = editor.getPath().toLowerCase() resource = provider.getResourceByKey(resourceKey) expect(resource).toBeDefined() expect(resource.keywords.length).toBeGreaterThan 0 expect(resource.keywords[0].name).toEqual 'Private keyword' it 'provides all keyword names', -> kwNames = provider.getKeywordNames() expect(kwNames).toContain('Run Program', 'Dot.punctuation keyword', 'Duplicated keyword') expect(kwNames.indexOf('Duplicated keyword')).toEqual(kwNames.lastIndexOf('Duplicated keyword')) for name in kwNames keywords = provider.getKeywordsByName(name) expect(keywords.length).toBeGreaterThan 0 it 'provides all resource keys', -> resourceKeys = provider.getResourceKeys() resourceNames = [] for resourceKey in resourceKeys resourceNames.push(pathUtils.basename(resourceKey)) expect(resourceNames).toContain 'test_autocomplete_keywords.robot' for resourceKey in resourceKeys resource = provider.getResourceByKey(resourceKey) expect(resource).toBeDefined() it 'provides library source information', -> keywords = provider.getKeywordsByName('Should Match') expect(keywords).toBeDefined() expect(keywords.length).toEqual 1 keyword = keywords[0] resource = provider.getResourceByKey(keyword.resourceKey) expect(resource.libraryPath).toContain '.py'
[ { "context": "ons\", \"ProvisionedThroughput\"]\n optionalKeys = [\"LocalSecondaryIndexes\", \"GlobalSecondaryIndexes\", \"StreamSpecification\"", "end": 450, "score": 0.9801831245422363, "start": 429, "tag": "KEY", "value": "LocalSecondaryIndexes" }, { "context": "put\"]\n optiona...
src/cli/commands/table/create.coffee
pandastrike/sky-mixin-dynamodb
0
# Helper to: # 1) Break full specification into something SunDog can consume # 2) Create the table # 3) Wait until we get back "Ready" for the Table's status. import {curry} from "panda-garden" import {clone, pick} from "panda-parchment" create = curry (DynamoDB, table) -> {tableCreate, tableWaitForReady} = DynamoDB mainArgs = ["TableName", "KeySchema", "AttributeDefinitions", "ProvisionedThroughput"] optionalKeys = ["LocalSecondaryIndexes", "GlobalSecondaryIndexes", "StreamSpecification"] f = (key) -> key in mainArgs args = (v for k, v of pick f, clone table) f = (key) -> key in optionalKeys options = pick f, clone table await tableCreate args..., options await tableWaitForReady table.TableName export default create
110693
# Helper to: # 1) Break full specification into something SunDog can consume # 2) Create the table # 3) Wait until we get back "Ready" for the Table's status. import {curry} from "panda-garden" import {clone, pick} from "panda-parchment" create = curry (DynamoDB, table) -> {tableCreate, tableWaitForReady} = DynamoDB mainArgs = ["TableName", "KeySchema", "AttributeDefinitions", "ProvisionedThroughput"] optionalKeys = ["<KEY>", "<KEY>", "<KEY>"] f = (key) -> key in mainArgs args = (v for k, v of pick f, clone table) f = (key) -> key in optionalKeys options = pick f, clone table await tableCreate args..., options await tableWaitForReady table.TableName export default create
true
# Helper to: # 1) Break full specification into something SunDog can consume # 2) Create the table # 3) Wait until we get back "Ready" for the Table's status. import {curry} from "panda-garden" import {clone, pick} from "panda-parchment" create = curry (DynamoDB, table) -> {tableCreate, tableWaitForReady} = DynamoDB mainArgs = ["TableName", "KeySchema", "AttributeDefinitions", "ProvisionedThroughput"] optionalKeys = ["PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI"] f = (key) -> key in mainArgs args = (v for k, v of pick f, clone table) f = (key) -> key in optionalKeys options = pick f, clone table await tableCreate args..., options await tableWaitForReady table.TableName export default create
[ { "context": ")\ncommon = require(\"./lib/common.js\")\nDEP_USER = \"username\"\nnerfed = \"//localhost:\" + server.port + \"/:\"\ncon", "end": 113, "score": 0.9987026453018188, "start": 105, "tag": "USERNAME", "value": "username" }, { "context": "R\nconfiguration[nerfed + \"_passwor...
deps/npm/node_modules/npm-registry-client/test/star.coffee
lxe/io.coffee
0
tap = require("tap") server = require("./lib/server.js") common = require("./lib/common.js") DEP_USER = "username" nerfed = "//localhost:" + server.port + "/:" configuration = {} configuration[nerfed + "username"] = DEP_USER configuration[nerfed + "_password"] = new Buffer("%1234@asdf%").toString("base64") configuration[nerfed + "email"] = "i@izs.me" client = common.freshClient(configuration) cache = require("./fixtures/underscore/cache.json") tap.test "star a package", (t) -> server.expect "GET", "/underscore?write=true", (req, res) -> t.equal req.method, "GET" res.json cache return server.expect "PUT", "/underscore", (req, res) -> t.equal req.method, "PUT" b = "" req.setEncoding "utf8" req.on "data", (d) -> b += d return req.on "end", -> updated = JSON.parse(b) already = [ "vesln" "mvolkmann" "lancehunt" "mikl" "linus" "vasc" "bat" "dmalam" "mbrevoort" "danielr" "rsimoes" "thlorenz" ] i = 0 while i < already.length current = already[i] t.ok updated.users[current], current + " still likes this package" i++ t.ok updated.users[DEP_USER], "user is in the starred list" res.statusCode = 201 res.json starred: true return return client.star "http://localhost:1337/underscore", true, (error, data) -> t.ifError error, "no errors" t.ok data.starred, "was starred" t.end() return return
32970
tap = require("tap") server = require("./lib/server.js") common = require("./lib/common.js") DEP_USER = "username" nerfed = "//localhost:" + server.port + "/:" configuration = {} configuration[nerfed + "username"] = DEP_USER configuration[nerfed + "_password"] = new Buffer("<PASSWORD>%").toString("base64") configuration[nerfed + "email"] = "<EMAIL>" client = common.freshClient(configuration) cache = require("./fixtures/underscore/cache.json") tap.test "star a package", (t) -> server.expect "GET", "/underscore?write=true", (req, res) -> t.equal req.method, "GET" res.json cache return server.expect "PUT", "/underscore", (req, res) -> t.equal req.method, "PUT" b = "" req.setEncoding "utf8" req.on "data", (d) -> b += d return req.on "end", -> updated = JSON.parse(b) already = [ "vesln" "mvolkmann" "lancehunt" "<NAME>l" "<NAME>us" "<NAME>" "<NAME>" "dmalam" "mbrevoort" "danielr" "rsimoes" "thlorenz" ] i = 0 while i < already.length current = already[i] t.ok updated.users[current], current + " still likes this package" i++ t.ok updated.users[DEP_USER], "user is in the starred list" res.statusCode = 201 res.json starred: true return return client.star "http://localhost:1337/underscore", true, (error, data) -> t.ifError error, "no errors" t.ok data.starred, "was starred" t.end() return return
true
tap = require("tap") server = require("./lib/server.js") common = require("./lib/common.js") DEP_USER = "username" nerfed = "//localhost:" + server.port + "/:" configuration = {} configuration[nerfed + "username"] = DEP_USER configuration[nerfed + "_password"] = new Buffer("PI:PASSWORD:<PASSWORD>END_PI%").toString("base64") configuration[nerfed + "email"] = "PI:EMAIL:<EMAIL>END_PI" client = common.freshClient(configuration) cache = require("./fixtures/underscore/cache.json") tap.test "star a package", (t) -> server.expect "GET", "/underscore?write=true", (req, res) -> t.equal req.method, "GET" res.json cache return server.expect "PUT", "/underscore", (req, res) -> t.equal req.method, "PUT" b = "" req.setEncoding "utf8" req.on "data", (d) -> b += d return req.on "end", -> updated = JSON.parse(b) already = [ "vesln" "mvolkmann" "lancehunt" "PI:NAME:<NAME>END_PIl" "PI:NAME:<NAME>END_PIus" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "dmalam" "mbrevoort" "danielr" "rsimoes" "thlorenz" ] i = 0 while i < already.length current = already[i] t.ok updated.users[current], current + " still likes this package" i++ t.ok updated.users[DEP_USER], "user is in the starred list" res.statusCode = 201 res.json starred: true return return client.star "http://localhost:1337/underscore", true, (error, data) -> t.ifError error, "no errors" t.ok data.starred, "was starred" t.end() return return
[ { "context": "e.Model\n\n cache_enabled: false\n cache_key: \"id\"\n\n constructor: (attr) ->\n @on \"change:id\", @", "end": 111, "score": 0.9149196147918701, "start": 109, "tag": "KEY", "value": "id" } ]
app/assets/javascripts/models/_staffplan_model.js.coffee
rescuedcode/StaffPlan
3
@instance_store = {} class StaffPlan.Model extends Backbone.Model cache_enabled: false cache_key: "id" constructor: (attr) -> @on "change:id", @_addToStore @on "destroy", @_removeFromStore return super unless attr?.id id = attr.id klass = @_getJsonRoot() instance_store[klass] ||= {} return( if instance_store[klass][id] instance_store[klass][id] else super instance_store[klass][id] = this) _getJsonRoot: -> @jsonRoot ||= @constructor.toString().match(/^function ([\w]+)/i)[1].toLowerCase() #-------------------------------------------- # INSTANCE STORE #-------------------------------------------- _addToStore: => klass = @_getJsonRoot() instance_store[klass] ||= {} instance_store[klass][@id] return _removeFromStore: => klass = @_getJsonRoot() delete instance_store[klass]?[@id] return
31521
@instance_store = {} class StaffPlan.Model extends Backbone.Model cache_enabled: false cache_key: "<KEY>" constructor: (attr) -> @on "change:id", @_addToStore @on "destroy", @_removeFromStore return super unless attr?.id id = attr.id klass = @_getJsonRoot() instance_store[klass] ||= {} return( if instance_store[klass][id] instance_store[klass][id] else super instance_store[klass][id] = this) _getJsonRoot: -> @jsonRoot ||= @constructor.toString().match(/^function ([\w]+)/i)[1].toLowerCase() #-------------------------------------------- # INSTANCE STORE #-------------------------------------------- _addToStore: => klass = @_getJsonRoot() instance_store[klass] ||= {} instance_store[klass][@id] return _removeFromStore: => klass = @_getJsonRoot() delete instance_store[klass]?[@id] return
true
@instance_store = {} class StaffPlan.Model extends Backbone.Model cache_enabled: false cache_key: "PI:KEY:<KEY>END_PI" constructor: (attr) -> @on "change:id", @_addToStore @on "destroy", @_removeFromStore return super unless attr?.id id = attr.id klass = @_getJsonRoot() instance_store[klass] ||= {} return( if instance_store[klass][id] instance_store[klass][id] else super instance_store[klass][id] = this) _getJsonRoot: -> @jsonRoot ||= @constructor.toString().match(/^function ([\w]+)/i)[1].toLowerCase() #-------------------------------------------- # INSTANCE STORE #-------------------------------------------- _addToStore: => klass = @_getJsonRoot() instance_store[klass] ||= {} instance_store[klass][@id] return _removeFromStore: => klass = @_getJsonRoot() delete instance_store[klass]?[@id] return
[ { "context": "# Copyright Vladimir Andreev\n\n# Required modules\n\nHTTPS = require('https')\nCry", "end": 28, "score": 0.9998726844787598, "start": 12, "tag": "NAME", "value": "Vladimir Andreev" } ]
src/client.coffee
tucan/qiwi
5
# Copyright Vladimir Andreev # Required modules HTTPS = require('https') Crypto = require('crypto') RSA = require('ursa') Iconv = require('iconv-lite') XML = require('nice-xml') QS = require('qs') # QIWI client class Client # Connection default parameters @SERVER_NAME: 'w.qiwi.com' @SERVER_PORT: 443 # Request and response default parameters @REQUEST_CHARSET: 'utf-8' @RESPONSE_MAX_SIZE: 1024 * 1024 # 1M # Cipher parameters CIPHER_NAME = 'aes-256-cbc' CIPHER_IV = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) CIPHER_KEY_LENGTH = 32 # Magic values of the protocol REQUEST_PREFIX = 'v3.qiwi-' RESPONSE_MARKER = 'B64\n' # Object constructor constructor: (options) -> @_host = @constructor.SERVER_NAME @_port = @constructor.SERVER_PORT @_charset = @constructor.REQUEST_CHARSET @_headers = Object.create(null) @_extra = Object.create(null) @_session = null @_token = null @_terminalId = null # _encryptKey = (publicKey, nonce, aesKey) -> blob = new Buffer(2 + nonce.length + aesKey.length) blob[0] = nonce.length nonce.copy(blob, 1) blob[1 + nonce.length] = aesKey.length aesKey.copy(blob, 1 + nonce.length + 1) publicKey.encrypt(blob, null, 'base64', RSA.RSA_PKCS1_PADDING) # Encrypts request body and returns string containing encrypted data _encryptBody: (data) -> cipher = Crypto.createCipheriv(CIPHER_NAME, @_session.key, CIPHER_IV) cipher.end(data) blob = cipher.read() REQUEST_PREFIX + @_session.id + '\n' + blob.toString('base64') # _decryptBody: (text) -> decipher = Crypto.createDecipheriv(CIPHER_NAME, @_session.key, CIPHER_IV) decipher.end(text, 'base64') decipher.read() # Generate request options based on provided parameters _requestOptions: (endpoint, body) -> path = '/xml/xmlutf_' + endpoint + '.jsp' headers = 'Content-Type': 'application/x-www-form-urlencoded; charset=' + @_charset 'Content-Length': body.length # Merge const headers and request specific headers fullHeaders = Object.create(null) fullHeaders[key] = value for key, value of @_headers fullHeaders[key] = value for key, value of headers options = host: @_host, port: @_port method: 'POST', path: path headers: fullHeaders options # Generate onResponse handler for provided callback _responseHandler: (callback) -> (response) => # Array for arriving chunks chunks = [] # Assign necessary event handlers response.on('readable', () -> chunk = response.read() chunks.push(chunk) if chunk? return ) response.on('end', () => body = Buffer.concat(chunks) text = Iconv.decode(body, 'utf-8') # Decrypt text (if it was encrypted of course) if text[0..3] is RESPONSE_MARKER text = Iconv.decode(@_decryptBody(text[4..]), 'utf-8') try output = XML.parse(text) callback(null, output.response) catch error callback(error) return ) return # setHeader: (name, value) -> @_headers[name] = value @ # removeHeader: (name) -> delete @_headers[name] @ # Sends init request to the server sendInit: (input, callback) -> # Make serialization and encode derived text blob = Iconv.encode(QS.stringify(input), @_charset) # Create request using generated options request = HTTPS.request(@_requestOptions('newcrypt_init_session', blob)) # Assign necessary event handlers request.on('response', @_responseHandler(callback)) request.on('error', (error) -> callback?(error) return ) # Write body and finish request request.end(blob) @ # Creates new session using provided public key createSession: (publicKey, callback) -> publicKey = RSA.createPublicKey(publicKey) # Phase 1 - receive server nonce @sendInit(command: 'init_start', (error, output) => # Extract necessary data from server response sessionId = output.session_id serverNonce = new Buffer(output.init_hs, 'base64') # Create AES key and encrypt it using public RSA key aesKey = Crypto.randomBytes(CIPHER_KEY_LENGTH) encryptedKey = _encryptKey(publicKey, serverNonce, aesKey) # Phase 2 - send our encrypted key to the server input = command: 'init_get_key', session_id: sessionId, key_v: 2, key_hs: encryptedKey @sendInit(input, (error) => unless error? session = id: sessionId, key: aesKey callback?(null, session) else callback?(error) return ) return ) @ # Makes provided session current setSession: (session) -> @_session = session @ # Removes previously stored session data removeSession: () -> @_session = null @ # Invokes pointed method on the remote side invokeMethod: (name, input, callback) -> # Form request data based on provided input envelope = request: 'request-type': name extra = [] extra.push($: (name: key), $text: value) for key, value of @_extra envelope.request.extra = extra if extra.length for key, value of input item = envelope.request[key] unless item? envelope.request[key] = value else if Array.isArray(item) item.push(value) else envelope.request[key] = [item, value] # Make serialization and encode derived text blob = Iconv.encode(XML.stringify(envelope), @_charset) # Encrypt plain body and encode derived cipher-text blob = Iconv.encode(@_encryptBody(blob), @_charset) # Create request using generated options request = HTTPS.request(@_requestOptions('newcrypt', blob)) # Assign necessary event handlers request.on('response', @_responseHandler(callback)) request.on('error', (error) -> callback?(error) return ) # Write body and finish request request.end(blob) @ # Sets extra field to be sent to the server setExtra: (name, value) -> @_extra[name] = value @ # Removes extra field with pointed name removeExtra: (name) -> delete @_extra[name] @ # receiveToken: (input, callback) -> fullInput = 'client-id': 'android', 'auth-version': '2.0' fullInput[key] = value for key, value of input when value isnt undefined @invokeMethod('oauth-token', fullInput, callback) # setAccess: (token, terminalId) -> @_token = token @_terminalId = terminalId @ # removeAccess: () -> @_token = null @_terminalId = null @ # accountInfo: (callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token @invokeMethod('ping', fullInput, callback) # chargeList: (input, callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token check: payment: input @invokeMethod('pay', fullInput, callback) # operationReport: (input, callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token fullInput[key] = value for key, value of input when value isnt undefined @invokeMethod('get-payments-report', fullInput, callback) # makePayment: (input, callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token auth: payment: input @invokeMethod('pay', fullInput, callback) # Exported objects module.exports = Client
168619
# Copyright <NAME> # Required modules HTTPS = require('https') Crypto = require('crypto') RSA = require('ursa') Iconv = require('iconv-lite') XML = require('nice-xml') QS = require('qs') # QIWI client class Client # Connection default parameters @SERVER_NAME: 'w.qiwi.com' @SERVER_PORT: 443 # Request and response default parameters @REQUEST_CHARSET: 'utf-8' @RESPONSE_MAX_SIZE: 1024 * 1024 # 1M # Cipher parameters CIPHER_NAME = 'aes-256-cbc' CIPHER_IV = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) CIPHER_KEY_LENGTH = 32 # Magic values of the protocol REQUEST_PREFIX = 'v3.qiwi-' RESPONSE_MARKER = 'B64\n' # Object constructor constructor: (options) -> @_host = @constructor.SERVER_NAME @_port = @constructor.SERVER_PORT @_charset = @constructor.REQUEST_CHARSET @_headers = Object.create(null) @_extra = Object.create(null) @_session = null @_token = null @_terminalId = null # _encryptKey = (publicKey, nonce, aesKey) -> blob = new Buffer(2 + nonce.length + aesKey.length) blob[0] = nonce.length nonce.copy(blob, 1) blob[1 + nonce.length] = aesKey.length aesKey.copy(blob, 1 + nonce.length + 1) publicKey.encrypt(blob, null, 'base64', RSA.RSA_PKCS1_PADDING) # Encrypts request body and returns string containing encrypted data _encryptBody: (data) -> cipher = Crypto.createCipheriv(CIPHER_NAME, @_session.key, CIPHER_IV) cipher.end(data) blob = cipher.read() REQUEST_PREFIX + @_session.id + '\n' + blob.toString('base64') # _decryptBody: (text) -> decipher = Crypto.createDecipheriv(CIPHER_NAME, @_session.key, CIPHER_IV) decipher.end(text, 'base64') decipher.read() # Generate request options based on provided parameters _requestOptions: (endpoint, body) -> path = '/xml/xmlutf_' + endpoint + '.jsp' headers = 'Content-Type': 'application/x-www-form-urlencoded; charset=' + @_charset 'Content-Length': body.length # Merge const headers and request specific headers fullHeaders = Object.create(null) fullHeaders[key] = value for key, value of @_headers fullHeaders[key] = value for key, value of headers options = host: @_host, port: @_port method: 'POST', path: path headers: fullHeaders options # Generate onResponse handler for provided callback _responseHandler: (callback) -> (response) => # Array for arriving chunks chunks = [] # Assign necessary event handlers response.on('readable', () -> chunk = response.read() chunks.push(chunk) if chunk? return ) response.on('end', () => body = Buffer.concat(chunks) text = Iconv.decode(body, 'utf-8') # Decrypt text (if it was encrypted of course) if text[0..3] is RESPONSE_MARKER text = Iconv.decode(@_decryptBody(text[4..]), 'utf-8') try output = XML.parse(text) callback(null, output.response) catch error callback(error) return ) return # setHeader: (name, value) -> @_headers[name] = value @ # removeHeader: (name) -> delete @_headers[name] @ # Sends init request to the server sendInit: (input, callback) -> # Make serialization and encode derived text blob = Iconv.encode(QS.stringify(input), @_charset) # Create request using generated options request = HTTPS.request(@_requestOptions('newcrypt_init_session', blob)) # Assign necessary event handlers request.on('response', @_responseHandler(callback)) request.on('error', (error) -> callback?(error) return ) # Write body and finish request request.end(blob) @ # Creates new session using provided public key createSession: (publicKey, callback) -> publicKey = RSA.createPublicKey(publicKey) # Phase 1 - receive server nonce @sendInit(command: 'init_start', (error, output) => # Extract necessary data from server response sessionId = output.session_id serverNonce = new Buffer(output.init_hs, 'base64') # Create AES key and encrypt it using public RSA key aesKey = Crypto.randomBytes(CIPHER_KEY_LENGTH) encryptedKey = _encryptKey(publicKey, serverNonce, aesKey) # Phase 2 - send our encrypted key to the server input = command: 'init_get_key', session_id: sessionId, key_v: 2, key_hs: encryptedKey @sendInit(input, (error) => unless error? session = id: sessionId, key: aesKey callback?(null, session) else callback?(error) return ) return ) @ # Makes provided session current setSession: (session) -> @_session = session @ # Removes previously stored session data removeSession: () -> @_session = null @ # Invokes pointed method on the remote side invokeMethod: (name, input, callback) -> # Form request data based on provided input envelope = request: 'request-type': name extra = [] extra.push($: (name: key), $text: value) for key, value of @_extra envelope.request.extra = extra if extra.length for key, value of input item = envelope.request[key] unless item? envelope.request[key] = value else if Array.isArray(item) item.push(value) else envelope.request[key] = [item, value] # Make serialization and encode derived text blob = Iconv.encode(XML.stringify(envelope), @_charset) # Encrypt plain body and encode derived cipher-text blob = Iconv.encode(@_encryptBody(blob), @_charset) # Create request using generated options request = HTTPS.request(@_requestOptions('newcrypt', blob)) # Assign necessary event handlers request.on('response', @_responseHandler(callback)) request.on('error', (error) -> callback?(error) return ) # Write body and finish request request.end(blob) @ # Sets extra field to be sent to the server setExtra: (name, value) -> @_extra[name] = value @ # Removes extra field with pointed name removeExtra: (name) -> delete @_extra[name] @ # receiveToken: (input, callback) -> fullInput = 'client-id': 'android', 'auth-version': '2.0' fullInput[key] = value for key, value of input when value isnt undefined @invokeMethod('oauth-token', fullInput, callback) # setAccess: (token, terminalId) -> @_token = token @_terminalId = terminalId @ # removeAccess: () -> @_token = null @_terminalId = null @ # accountInfo: (callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token @invokeMethod('ping', fullInput, callback) # chargeList: (input, callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token check: payment: input @invokeMethod('pay', fullInput, callback) # operationReport: (input, callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token fullInput[key] = value for key, value of input when value isnt undefined @invokeMethod('get-payments-report', fullInput, callback) # makePayment: (input, callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token auth: payment: input @invokeMethod('pay', fullInput, callback) # Exported objects module.exports = Client
true
# Copyright PI:NAME:<NAME>END_PI # Required modules HTTPS = require('https') Crypto = require('crypto') RSA = require('ursa') Iconv = require('iconv-lite') XML = require('nice-xml') QS = require('qs') # QIWI client class Client # Connection default parameters @SERVER_NAME: 'w.qiwi.com' @SERVER_PORT: 443 # Request and response default parameters @REQUEST_CHARSET: 'utf-8' @RESPONSE_MAX_SIZE: 1024 * 1024 # 1M # Cipher parameters CIPHER_NAME = 'aes-256-cbc' CIPHER_IV = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) CIPHER_KEY_LENGTH = 32 # Magic values of the protocol REQUEST_PREFIX = 'v3.qiwi-' RESPONSE_MARKER = 'B64\n' # Object constructor constructor: (options) -> @_host = @constructor.SERVER_NAME @_port = @constructor.SERVER_PORT @_charset = @constructor.REQUEST_CHARSET @_headers = Object.create(null) @_extra = Object.create(null) @_session = null @_token = null @_terminalId = null # _encryptKey = (publicKey, nonce, aesKey) -> blob = new Buffer(2 + nonce.length + aesKey.length) blob[0] = nonce.length nonce.copy(blob, 1) blob[1 + nonce.length] = aesKey.length aesKey.copy(blob, 1 + nonce.length + 1) publicKey.encrypt(blob, null, 'base64', RSA.RSA_PKCS1_PADDING) # Encrypts request body and returns string containing encrypted data _encryptBody: (data) -> cipher = Crypto.createCipheriv(CIPHER_NAME, @_session.key, CIPHER_IV) cipher.end(data) blob = cipher.read() REQUEST_PREFIX + @_session.id + '\n' + blob.toString('base64') # _decryptBody: (text) -> decipher = Crypto.createDecipheriv(CIPHER_NAME, @_session.key, CIPHER_IV) decipher.end(text, 'base64') decipher.read() # Generate request options based on provided parameters _requestOptions: (endpoint, body) -> path = '/xml/xmlutf_' + endpoint + '.jsp' headers = 'Content-Type': 'application/x-www-form-urlencoded; charset=' + @_charset 'Content-Length': body.length # Merge const headers and request specific headers fullHeaders = Object.create(null) fullHeaders[key] = value for key, value of @_headers fullHeaders[key] = value for key, value of headers options = host: @_host, port: @_port method: 'POST', path: path headers: fullHeaders options # Generate onResponse handler for provided callback _responseHandler: (callback) -> (response) => # Array for arriving chunks chunks = [] # Assign necessary event handlers response.on('readable', () -> chunk = response.read() chunks.push(chunk) if chunk? return ) response.on('end', () => body = Buffer.concat(chunks) text = Iconv.decode(body, 'utf-8') # Decrypt text (if it was encrypted of course) if text[0..3] is RESPONSE_MARKER text = Iconv.decode(@_decryptBody(text[4..]), 'utf-8') try output = XML.parse(text) callback(null, output.response) catch error callback(error) return ) return # setHeader: (name, value) -> @_headers[name] = value @ # removeHeader: (name) -> delete @_headers[name] @ # Sends init request to the server sendInit: (input, callback) -> # Make serialization and encode derived text blob = Iconv.encode(QS.stringify(input), @_charset) # Create request using generated options request = HTTPS.request(@_requestOptions('newcrypt_init_session', blob)) # Assign necessary event handlers request.on('response', @_responseHandler(callback)) request.on('error', (error) -> callback?(error) return ) # Write body and finish request request.end(blob) @ # Creates new session using provided public key createSession: (publicKey, callback) -> publicKey = RSA.createPublicKey(publicKey) # Phase 1 - receive server nonce @sendInit(command: 'init_start', (error, output) => # Extract necessary data from server response sessionId = output.session_id serverNonce = new Buffer(output.init_hs, 'base64') # Create AES key and encrypt it using public RSA key aesKey = Crypto.randomBytes(CIPHER_KEY_LENGTH) encryptedKey = _encryptKey(publicKey, serverNonce, aesKey) # Phase 2 - send our encrypted key to the server input = command: 'init_get_key', session_id: sessionId, key_v: 2, key_hs: encryptedKey @sendInit(input, (error) => unless error? session = id: sessionId, key: aesKey callback?(null, session) else callback?(error) return ) return ) @ # Makes provided session current setSession: (session) -> @_session = session @ # Removes previously stored session data removeSession: () -> @_session = null @ # Invokes pointed method on the remote side invokeMethod: (name, input, callback) -> # Form request data based on provided input envelope = request: 'request-type': name extra = [] extra.push($: (name: key), $text: value) for key, value of @_extra envelope.request.extra = extra if extra.length for key, value of input item = envelope.request[key] unless item? envelope.request[key] = value else if Array.isArray(item) item.push(value) else envelope.request[key] = [item, value] # Make serialization and encode derived text blob = Iconv.encode(XML.stringify(envelope), @_charset) # Encrypt plain body and encode derived cipher-text blob = Iconv.encode(@_encryptBody(blob), @_charset) # Create request using generated options request = HTTPS.request(@_requestOptions('newcrypt', blob)) # Assign necessary event handlers request.on('response', @_responseHandler(callback)) request.on('error', (error) -> callback?(error) return ) # Write body and finish request request.end(blob) @ # Sets extra field to be sent to the server setExtra: (name, value) -> @_extra[name] = value @ # Removes extra field with pointed name removeExtra: (name) -> delete @_extra[name] @ # receiveToken: (input, callback) -> fullInput = 'client-id': 'android', 'auth-version': '2.0' fullInput[key] = value for key, value of input when value isnt undefined @invokeMethod('oauth-token', fullInput, callback) # setAccess: (token, terminalId) -> @_token = token @_terminalId = terminalId @ # removeAccess: () -> @_token = null @_terminalId = null @ # accountInfo: (callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token @invokeMethod('ping', fullInput, callback) # chargeList: (input, callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token check: payment: input @invokeMethod('pay', fullInput, callback) # operationReport: (input, callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token fullInput[key] = value for key, value of input when value isnt undefined @invokeMethod('get-payments-report', fullInput, callback) # makePayment: (input, callback) -> fullInput = 'terminal-id': @_terminalId extra: $: (name: 'token'), $text: @_token auth: payment: input @invokeMethod('pay', fullInput, callback) # Exported objects module.exports = Client
[ { "context": "m FOASS\n#\n# Dependencies:\n# None\n#\n# Author:\n# zacechola\n\noptions = [\n 'off',\n 'you',\n 'donut',\n 'shak", "end": 188, "score": 0.9984981417655945, "start": 179, "tag": "USERNAME", "value": "zacechola" }, { "context": "la\n\noptions = [\n 'off',\n 'y...
src/scripts/foass.coffee
TaxiOS/hubot-scripts
9
# Description: # Basic interface for FOAAS.com # # Commands # fu <object> - tells <object> to f off with random response from FOASS # # Dependencies: # None # # Author: # zacechola options = [ 'off', 'you', 'donut', 'shakespeare', 'linus', 'king', 'chainsaw' ] module.exports = (robot) -> robot.hear /^fu (.\w*)/i, (msg) -> to = msg.match[1] from = msg.message.user.name random_fu = msg.random options msg.http("http://foaas.com/#{random_fu}/#{to}/#{from}/") .headers(Accept: 'application/json') .get() (err, res, body) -> try json = JSON.parse body msg.send json.message msg.send json.subtitle catch error msg.send "Fuck this error!"
213894
# Description: # Basic interface for FOAAS.com # # Commands # fu <object> - tells <object> to f off with random response from FOASS # # Dependencies: # None # # Author: # zacechola options = [ 'off', 'you', 'donut', 'sh<NAME>', 'linus', 'king', 'chainsaw' ] module.exports = (robot) -> robot.hear /^fu (.\w*)/i, (msg) -> to = msg.match[1] from = msg.message.user.name random_fu = msg.random options msg.http("http://foaas.com/#{random_fu}/#{to}/#{from}/") .headers(Accept: 'application/json') .get() (err, res, body) -> try json = JSON.parse body msg.send json.message msg.send json.subtitle catch error msg.send "Fuck this error!"
true
# Description: # Basic interface for FOAAS.com # # Commands # fu <object> - tells <object> to f off with random response from FOASS # # Dependencies: # None # # Author: # zacechola options = [ 'off', 'you', 'donut', 'shPI:NAME:<NAME>END_PI', 'linus', 'king', 'chainsaw' ] module.exports = (robot) -> robot.hear /^fu (.\w*)/i, (msg) -> to = msg.match[1] from = msg.message.user.name random_fu = msg.random options msg.http("http://foaas.com/#{random_fu}/#{to}/#{from}/") .headers(Accept: 'application/json') .get() (err, res, body) -> try json = JSON.parse body msg.send json.message msg.send json.subtitle catch error msg.send "Fuck this error!"
[ { "context": " {\n id: 1\n number: '1'\n customer: 'Marko Liebknecht'\n adress: 'Tannenallee 23\\n23443 Freiland'\n ", "end": 1285, "score": 0.9998908638954163, "start": 1269, "tag": "NAME", "value": "Marko Liebknecht" }, { "context": " {\n id: 2\n numbe...
app/models/order.coffee
koenig/moosi
0
`import DS from 'ember-data'` [attr, hasMany, belongsTo] = [DS.attr, DS.hasMany, DS.belongsTo] Order = DS.Model.extend number: attr 'string' customer: attr 'string' adress: attr 'string' date: attr 'date', defaultValue: -> new Date() isPackingList: attr 'boolean', defaultValue: false isOrder: Em.computed.not 'isPackingList' orderItems: hasMany 'orderItem' findOrderItemFor: (plant) -> orderItem = @get('orderItems').find (orderItem) -> orderItem.get('plant') is plant return orderItem if orderItem orderItem = @store.createRecord 'orderItem', order: @ plant: plant quantity: 0 plantName: plant.get('name') plantPriceInCents: plant.get('priceInCents') orderItem typeName: Em.computed 'isPackingList', -> return 'packing-list' if @get 'isPackingList' 'order' totalInCentsValues: Em.computed.mapBy 'orderItems', 'totalInCents' totalInCents: Em.computed.sum 'totalInCentsValues' totalPrice: Em.computed 'totalInCents', -> @get('totalInCents')/100 name: Em.computed 'number', 'customer', 'isPackingList', -> return @get('customer') if @get('isPackingList') "Rechnung #{@get('number')}" Order.reopenClass FIXTURES: [ { id: 1 number: '1' customer: 'Marko Liebknecht' adress: 'Tannenallee 23\n23443 Freiland' date: '2014-11-15' orderItems: [1, 2] isPackingList: no } { id: 2 number: '2' customer: 'Resi Laub' adress: 'Hammer Baum 23\n20243 Hamburg' date: '2014-12-02' orderItems: [3] isPackingList: no } { id: 3 number: null customer: 'Höwer Markt' date: '2014-12-22' orderItems: [4, 5] isPackingList: yes } ] `export default Order`
185803
`import DS from 'ember-data'` [attr, hasMany, belongsTo] = [DS.attr, DS.hasMany, DS.belongsTo] Order = DS.Model.extend number: attr 'string' customer: attr 'string' adress: attr 'string' date: attr 'date', defaultValue: -> new Date() isPackingList: attr 'boolean', defaultValue: false isOrder: Em.computed.not 'isPackingList' orderItems: hasMany 'orderItem' findOrderItemFor: (plant) -> orderItem = @get('orderItems').find (orderItem) -> orderItem.get('plant') is plant return orderItem if orderItem orderItem = @store.createRecord 'orderItem', order: @ plant: plant quantity: 0 plantName: plant.get('name') plantPriceInCents: plant.get('priceInCents') orderItem typeName: Em.computed 'isPackingList', -> return 'packing-list' if @get 'isPackingList' 'order' totalInCentsValues: Em.computed.mapBy 'orderItems', 'totalInCents' totalInCents: Em.computed.sum 'totalInCentsValues' totalPrice: Em.computed 'totalInCents', -> @get('totalInCents')/100 name: Em.computed 'number', 'customer', 'isPackingList', -> return @get('customer') if @get('isPackingList') "Rechnung #{@get('number')}" Order.reopenClass FIXTURES: [ { id: 1 number: '1' customer: '<NAME>' adress: 'Tannenallee 23\n23443 Freiland' date: '2014-11-15' orderItems: [1, 2] isPackingList: no } { id: 2 number: '2' customer: '<NAME>' adress: 'Hammer Baum 23\n20243 Hamburg' date: '2014-12-02' orderItems: [3] isPackingList: no } { id: 3 number: null customer: '<NAME>' date: '2014-12-22' orderItems: [4, 5] isPackingList: yes } ] `export default Order`
true
`import DS from 'ember-data'` [attr, hasMany, belongsTo] = [DS.attr, DS.hasMany, DS.belongsTo] Order = DS.Model.extend number: attr 'string' customer: attr 'string' adress: attr 'string' date: attr 'date', defaultValue: -> new Date() isPackingList: attr 'boolean', defaultValue: false isOrder: Em.computed.not 'isPackingList' orderItems: hasMany 'orderItem' findOrderItemFor: (plant) -> orderItem = @get('orderItems').find (orderItem) -> orderItem.get('plant') is plant return orderItem if orderItem orderItem = @store.createRecord 'orderItem', order: @ plant: plant quantity: 0 plantName: plant.get('name') plantPriceInCents: plant.get('priceInCents') orderItem typeName: Em.computed 'isPackingList', -> return 'packing-list' if @get 'isPackingList' 'order' totalInCentsValues: Em.computed.mapBy 'orderItems', 'totalInCents' totalInCents: Em.computed.sum 'totalInCentsValues' totalPrice: Em.computed 'totalInCents', -> @get('totalInCents')/100 name: Em.computed 'number', 'customer', 'isPackingList', -> return @get('customer') if @get('isPackingList') "Rechnung #{@get('number')}" Order.reopenClass FIXTURES: [ { id: 1 number: '1' customer: 'PI:NAME:<NAME>END_PI' adress: 'Tannenallee 23\n23443 Freiland' date: '2014-11-15' orderItems: [1, 2] isPackingList: no } { id: 2 number: '2' customer: 'PI:NAME:<NAME>END_PI' adress: 'Hammer Baum 23\n20243 Hamburg' date: '2014-12-02' orderItems: [3] isPackingList: no } { id: 3 number: null customer: 'PI:NAME:<NAME>END_PI' date: '2014-12-22' orderItems: [4, 5] isPackingList: yes } ] `export default Order`
[ { "context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig", "end": 74, "score": 0.9998795986175537, "start": 61, "tag": "NAME", "value": "Jessym Reziga" }, { "context": "f the Konsserto package.\n *\n * (c) Je...
node_modules/konsserto/lib/src/Konsserto/Component/Console/Input/InputOption.coffee
konsserto/konsserto
2
### * This file is part of the Konsserto package. * * (c) Jessym Reziga <jessym@konsserto.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### # # InputOption is a command line option (--option) # # @author Jessym Reziga <jessym@konsserto.com> # class InputOption @VALUE_NONE = 1 @VALUE_REQUIRED = 2 @VALUE_OPTIONAL = 4 @VALUE_IS_ARRAY = 8 constructor:(name,shortcut,mode, description,cdefault) -> if name.indexOf('--') == 0 name = name.substr(2) if name == undefined throw new Error('An option name cannot be empty.') if shortcut != undefined if shortcut.constructor.name == 'Array' for short in shortcut short = short.replace(/-/g,'') shortcut = shortcut.join('|') else shortcut = shortcut.replace(/-/g,'') if mode == undefined mode = InputOption.VALUE_NONE else if ( !parseInt(mode) || mode > 15 || mode < 1) throw new Error('Option mode '+mode+' is not valid.') @name = name @shortcut = shortcut @mode = mode @description = description if @isArray() && !@acceptValue() throw new Error('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.') @setDefault(cdefault) getShortcut:() -> return @shortcut getName:() -> return @name acceptValue:() -> return @isValueRequired() || @isValueOptional() isValueRequired:() -> return InputOption.VALUE_REQUIRED == (InputOption.VALUE_REQUIRED & @mode) isValueOptional:() -> return InputOption.VALUE_OPTIONAL == (InputOption.VALUE_OPTIONAL & @mode) isArray:() -> return InputOption.VALUE_IS_ARRAY == (InputOption.VALUE_IS_ARRAY & @mode) setDefault:(cdefault) -> if (InputOption.VALUE_NONE == (InputOption.VALUE_NONE & @mode) && cdefault != undefined) throw new Error('Cannot set a default value when using InputOption.VALUE_NONE mode.') if (@isArray()) if cdefault == undefined cdefault = [] else if cdefault.constructor.name != 'Array' throw new Error('A default value for an array option must be an array.') @default = if @acceptValue() then cdefault else false getDefault:() -> return @default getDescription:() -> return @description equals:(option) -> return ( option.getName() == @getName() && option.getShortcut() == @getShortcut() && option.getDefault() == @getDefault() && option.isArray() == @isArray() && option.isValueRequired() == @isValueRequired() && option.isValueOptional() == @isValueOptional() ) module.exports = InputOption;
205694
### * This file is part of the Konsserto package. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### # # InputOption is a command line option (--option) # # @author <NAME> <<EMAIL>> # class InputOption @VALUE_NONE = 1 @VALUE_REQUIRED = 2 @VALUE_OPTIONAL = 4 @VALUE_IS_ARRAY = 8 constructor:(name,shortcut,mode, description,cdefault) -> if name.indexOf('--') == 0 name = name.substr(2) if name == undefined throw new Error('An option name cannot be empty.') if shortcut != undefined if shortcut.constructor.name == 'Array' for short in shortcut short = short.replace(/-/g,'') shortcut = shortcut.join('|') else shortcut = shortcut.replace(/-/g,'') if mode == undefined mode = InputOption.VALUE_NONE else if ( !parseInt(mode) || mode > 15 || mode < 1) throw new Error('Option mode '+mode+' is not valid.') @name = name @shortcut = shortcut @mode = mode @description = description if @isArray() && !@acceptValue() throw new Error('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.') @setDefault(cdefault) getShortcut:() -> return @shortcut getName:() -> return @name acceptValue:() -> return @isValueRequired() || @isValueOptional() isValueRequired:() -> return InputOption.VALUE_REQUIRED == (InputOption.VALUE_REQUIRED & @mode) isValueOptional:() -> return InputOption.VALUE_OPTIONAL == (InputOption.VALUE_OPTIONAL & @mode) isArray:() -> return InputOption.VALUE_IS_ARRAY == (InputOption.VALUE_IS_ARRAY & @mode) setDefault:(cdefault) -> if (InputOption.VALUE_NONE == (InputOption.VALUE_NONE & @mode) && cdefault != undefined) throw new Error('Cannot set a default value when using InputOption.VALUE_NONE mode.') if (@isArray()) if cdefault == undefined cdefault = [] else if cdefault.constructor.name != 'Array' throw new Error('A default value for an array option must be an array.') @default = if @acceptValue() then cdefault else false getDefault:() -> return @default getDescription:() -> return @description equals:(option) -> return ( option.getName() == @getName() && option.getShortcut() == @getShortcut() && option.getDefault() == @getDefault() && option.isArray() == @isArray() && option.isValueRequired() == @isValueRequired() && option.isValueOptional() == @isValueOptional() ) module.exports = InputOption;
true
### * This file is part of the Konsserto package. * * (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. ### # # InputOption is a command line option (--option) # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # class InputOption @VALUE_NONE = 1 @VALUE_REQUIRED = 2 @VALUE_OPTIONAL = 4 @VALUE_IS_ARRAY = 8 constructor:(name,shortcut,mode, description,cdefault) -> if name.indexOf('--') == 0 name = name.substr(2) if name == undefined throw new Error('An option name cannot be empty.') if shortcut != undefined if shortcut.constructor.name == 'Array' for short in shortcut short = short.replace(/-/g,'') shortcut = shortcut.join('|') else shortcut = shortcut.replace(/-/g,'') if mode == undefined mode = InputOption.VALUE_NONE else if ( !parseInt(mode) || mode > 15 || mode < 1) throw new Error('Option mode '+mode+' is not valid.') @name = name @shortcut = shortcut @mode = mode @description = description if @isArray() && !@acceptValue() throw new Error('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.') @setDefault(cdefault) getShortcut:() -> return @shortcut getName:() -> return @name acceptValue:() -> return @isValueRequired() || @isValueOptional() isValueRequired:() -> return InputOption.VALUE_REQUIRED == (InputOption.VALUE_REQUIRED & @mode) isValueOptional:() -> return InputOption.VALUE_OPTIONAL == (InputOption.VALUE_OPTIONAL & @mode) isArray:() -> return InputOption.VALUE_IS_ARRAY == (InputOption.VALUE_IS_ARRAY & @mode) setDefault:(cdefault) -> if (InputOption.VALUE_NONE == (InputOption.VALUE_NONE & @mode) && cdefault != undefined) throw new Error('Cannot set a default value when using InputOption.VALUE_NONE mode.') if (@isArray()) if cdefault == undefined cdefault = [] else if cdefault.constructor.name != 'Array' throw new Error('A default value for an array option must be an array.') @default = if @acceptValue() then cdefault else false getDefault:() -> return @default getDescription:() -> return @description equals:(option) -> return ( option.getName() == @getName() && option.getShortcut() == @getShortcut() && option.getDefault() == @getDefault() && option.isArray() == @isArray() && option.isValueRequired() == @isValueRequired() && option.isValueOptional() == @isValueOptional() ) module.exports = InputOption;
[ { "context": "= (require '../')\n url: 'test'\n token: 'test'\n\n projects = gitlab.projects\n repository =", "end": 286, "score": 0.507554292678833, "start": 282, "tag": "KEY", "value": "test" } ]
tests/ProjectRepository.test.coffee
lengyuedaidai/node-gitlab
7
chai = require 'chai' expect = chai.expect sinon = require 'sinon' sinonChai = require 'sinon-chai' chai.use sinonChai describe "ProjectRepository", -> gitlab = null projects = null repository = null before -> gitlab = (require '../') url: 'test' token: 'test' projects = gitlab.projects repository = projects.repository beforeEach -> describe "listBranches()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listBranches 1 getStub.restore() expect(getStub).to.have.been.called describe "listCommits()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listCommits 1 getStub.restore() expect(getStub).to.have.been.called describe "addTag()", -> it "should use POST verb", -> postStub = sinon.stub repository, "post" opts = id: 1, tag_name: "v1.0.0", ref: "2695effb5807a22ff3d138d593fd856244e155e7", message: "Annotated message", release_description: "Release description" repository.addTag opts postStub.restore() expect(postStub).to.have.been.called describe "listTags()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listTags 1 getStub.restore() expect(getStub).to.have.been.called describe "listTree()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listTree 1 getStub.restore() expect(getStub).to.have.been.called describe "showFile()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.showFile 1, { file_path: "test", ref: "test" } getStub.restore() expect(getStub).to.have.been.called
65736
chai = require 'chai' expect = chai.expect sinon = require 'sinon' sinonChai = require 'sinon-chai' chai.use sinonChai describe "ProjectRepository", -> gitlab = null projects = null repository = null before -> gitlab = (require '../') url: 'test' token: '<KEY>' projects = gitlab.projects repository = projects.repository beforeEach -> describe "listBranches()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listBranches 1 getStub.restore() expect(getStub).to.have.been.called describe "listCommits()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listCommits 1 getStub.restore() expect(getStub).to.have.been.called describe "addTag()", -> it "should use POST verb", -> postStub = sinon.stub repository, "post" opts = id: 1, tag_name: "v1.0.0", ref: "2695effb5807a22ff3d138d593fd856244e155e7", message: "Annotated message", release_description: "Release description" repository.addTag opts postStub.restore() expect(postStub).to.have.been.called describe "listTags()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listTags 1 getStub.restore() expect(getStub).to.have.been.called describe "listTree()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listTree 1 getStub.restore() expect(getStub).to.have.been.called describe "showFile()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.showFile 1, { file_path: "test", ref: "test" } getStub.restore() expect(getStub).to.have.been.called
true
chai = require 'chai' expect = chai.expect sinon = require 'sinon' sinonChai = require 'sinon-chai' chai.use sinonChai describe "ProjectRepository", -> gitlab = null projects = null repository = null before -> gitlab = (require '../') url: 'test' token: 'PI:KEY:<KEY>END_PI' projects = gitlab.projects repository = projects.repository beforeEach -> describe "listBranches()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listBranches 1 getStub.restore() expect(getStub).to.have.been.called describe "listCommits()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listCommits 1 getStub.restore() expect(getStub).to.have.been.called describe "addTag()", -> it "should use POST verb", -> postStub = sinon.stub repository, "post" opts = id: 1, tag_name: "v1.0.0", ref: "2695effb5807a22ff3d138d593fd856244e155e7", message: "Annotated message", release_description: "Release description" repository.addTag opts postStub.restore() expect(postStub).to.have.been.called describe "listTags()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listTags 1 getStub.restore() expect(getStub).to.have.been.called describe "listTree()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.listTree 1 getStub.restore() expect(getStub).to.have.been.called describe "showFile()", -> it "should use GET verb", -> getStub = sinon.stub repository, "get" repository.showFile 1, { file_path: "test", ref: "test" } getStub.restore() expect(getStub).to.have.been.called
[ { "context": "###\nCasua 0.0.2\nCopyright (c) 2013-2016 aligo Kang\n\nReleased under the MIT license\n###\n\n\n_shallowCop", "end": 50, "score": 0.9997391700744629, "start": 40, "tag": "NAME", "value": "aligo Kang" } ]
src/casua.coffee
aligo/casua
2
### Casua 0.0.2 Copyright (c) 2013-2016 aligo Kang Released under the MIT license ### _shallowCopy = (src, dst = {}) -> dst[key] = value for key, value of src dst _isFunction = (obj) -> !!(obj && obj.constructor && obj.call && obj.apply); _escape_chars = { lt: '<', gt: '>', quot: '"', amp: '&', apos: "'" } _reversed_escape_chars = {} _reversed_escape_chars[v] = k for k, v of _escape_chars _escapeHTML = (str) -> str.replace /[&<>"']/g, (m) -> '&' + _reversed_escape_chars[m] + ';' __boolean_attr_regexp = /^multiple|selected|checked|disabled|required|open$/ _css_selector = typeof document.querySelectorAll is 'function' casua = {} class casua.Node _addNodes = (_node, elements) -> elements = [elements] if elements.nodeName for element in elements element._node = _node _push _node, element _push = (_node, one) -> _node[_node.length] = one _node.length += 1 _forEach = (_node, callback) -> ret = for one, idx in _node callback.call one, idx, one ret[0] __addEventListenerFn = if window.document.addEventListener (element, type, fn) -> element.addEventListener type, fn, false else (element, type, fn) -> element.attachEvent 'on' + type, fn __createEventHanlder = (element, events) -> ret = (event, type) -> event.preventDefault ||= -> event.returnValue = false event.stopPropagation ||= -> event.cancelBubble = true event.target ||= event.srcElement || document unless event.defaultPrevented? prevent = event.preventDefault event.preventDefault = -> event.defaultPrevented = true prevent.call event event.defaultPrevented = false event.isDefaultPrevented = -> ( event.defaultPrevented ) || ( event.returnValue == false ) eventFns = _shallowCopy( events[type || event.type] || []) fn.call element, event for i, fn of eventFns delete event.preventDefault delete event.stopPropagation delete event.isDefaultPrevented ret.elem = element ret.handleds = [] ret __trigger_to_dom_regexp = /^focus$/ constructor: (node_meta) -> @handlers = {} @events = {} @length = 0 if node_meta instanceof casua.Node return node_meta else if typeof node_meta is 'string' if node_meta.charAt(0) != '<' attrs_data = node_meta.split ' ' tag_data = attrs_data.shift() el = document.createElement if r = tag_data.match(/^([^\.^#]+)/) r[1] else 'div' if r = tag_data.match /\.([^\.^#]+)/g el.className = r.join(' ').replace /\./g, '' if r = tag_data.match /#([^\.^#]+)/ el.id = r[1] _addNodes @, el for attr in attrs_data if attr.charAt(0) != '#' && r = attr.match /^([^=]+)(?:=(['"])(.+?)\2)?$/ @attr r[1], ( r[3] || r[1] ) else div = document.createElement 'div' div.innerHTML = '<div>&#160;</div>' + node_meta div.removeChild div.firstChild for child in div.childNodes _addNodes @, child else _addNodes @, node_meta attr: (name, value) -> name = name.toLowerCase() return @val(value) if name.match /^val|value$/ if name.match __boolean_attr_regexp if value? if value _forEach @, -> @setAttribute name, name @[name] = true else _forEach @, -> @removeAttribute name @[name] = false @ else @[0][name] else if value? _forEach @, -> @setAttribute name, value @ else @[0].getAttribute name, 2 append: (node) -> node = new casua.Node node if typeof node is 'string' _forEach @, (i, parent) -> _forEach node, (j, child) -> parent.appendChild child @ empty: -> _forEach @, -> while @firstChild @removeChild @firstChild @ html: (value) -> if value? @empty() _forEach @, -> @innerHTML = value @ else @[0].innerHTML text: (value) -> if value? @html _escapeHTML(value) else @html() on: (type, fn) -> _node = @ @events[type] ||= [] @events[type].push fn _forEach @, (idx) -> handler = _node.handlers[idx] ||= __createEventHanlder @, _node.events handleds = handler.handleds if handleds.indexOf(type) == -1 __addEventListenerFn @, type, handler handleds.push type @ trigger: (type, event_data = {}) -> if type.match __trigger_to_dom_regexp trigger_to_dom = true _forEach @, -> event = document.createEvent 'HTMLEvents' event.initEvent type, true, true event[key] = value for key, value of event_data @dispatchEvent event @[type]() if trigger_to_dom @ remove: -> _forEach @, -> @parentNode.removeChild @ if @parentNode @ replaceWith: (node) -> node = new casua.Node node if typeof node is 'string' _forEach @, (i, from) -> _forEach node, (j, to) -> from.parentNode.replaceChild to, from if from.parentNode @ val: (value) -> if value? _forEach @, -> @value = value @ else @[0].value parent: -> if parent = @[0].parentNode parent._node || new casua.Node parent find: (query) -> element = if _css_selector @[0].querySelector query else @[0].getElementsByTagName query if element element._node || new casua.Node element _scopeInitParent = (_scope, _parent) -> _scope._childs = [] if _parent? _parent._childs.push _scope if _parent._childs.indexOf(_scope) == -1 _scope._parent = _parent _scopeRemovePrepare = (_scope, key) -> if _scope._data[key] instanceof casua.Scope s = _scope._data[key] if s._parent? i = s._parent._childs.indexOf s s._parent._childs.splice i, 1 _scopeCallWatch _scope, _scope._data[key], key, '$delete' _scopeCallWatch = (_scope, new_val, old_val, key) -> if typeof key is 'string' && key.charAt(0) == '$' _scopeCallAltWatch _scope, new_val, old_val, key else if _scope._watches[key] fn.call _scope, new_val, old_val, key for fn in _scope._watches[key] for child in _scope._childs unless child._data[key]? _scopeCallWatch child, new_val, old_val, key _scopeCallAltWatch = (_scope, new_val, key, type) -> if _scope._watches[type] fn.call _scope, new_val, type, key for fn in _scope._watches[type] __mutiple_levels_key_regexp = /^([^\.]+)\.(.+)$/ class casua.Scope constructor: (init_data, parent) -> if _isFunction(init_data) || ( init_data instanceof casua.Scope ) || ( init_data instanceof casua.Node ) return init_data else if init_data.length? return new casua.ArrayScope init_data, parent else _scopeInitParent @, parent @_watches = {} @_data = {} @set key, value for key, value of init_data get: (key) -> @_watch_lists.push key if @_watch_lists && @_watch_lists.indexOf(key) == -1 if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp if path = @get(r[1]) path.get(r[2]) else null else if key == '$parent' @_parent else ret = @_data[key] ret = @_parent.get(key) if !ret? && @_parent? ret set: (key, value) -> if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp @get(r[1]).set r[2], value else unless typeof key is 'string' && key.charAt(0) == '$' if typeof value is 'object' value = new casua.Scope value, @ if @_data[key] != value old = @_data[key] @_data[key] = value unless old? _scopeCallWatch @, value, key, '$add' _scopeCallWatch @, value, old, key @ remove: (key) -> if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp @get(r[1]).remove(r[2]) else _scopeRemovePrepare @, key delete @_data[key] @ $watch: (key, fn) -> if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp @get(r[1]).$watch r[2], fn @$watch r[1], fn else @_watches[key] ||= [] @_watches[key].push fn @ $startGetWatches: -> @_parent.$startGetWatches() if @_parent? @_watch_lists = [] $stopGetWatches: -> lists = for one in @_watch_lists one delete @_watch_lists lists = lists.concat @_parent.$stopGetWatches() if @_parent? lists _scopeChangeLength = (_scope, fn) -> _old_length = _scope._data.length ret = fn.call _scope _scopeCallWatch _scope, _scope._data.length, _old_length, 'length' ret class casua.ArrayScope extends casua.Scope constructor: (init_data, parent) -> if init_data instanceof casua.Scope return init_data else if not init_data.length? return new casua.Scope init_data, parent else _scopeInitParent @, parent @_watches = {} @_data = [] @set idx, value for value, idx in init_data length: -> @_data.length indexOf: (child) -> @_data.indexOf child remove: (key) -> _scopeChangeLength @, -> _scopeRemovePrepare @, key @_data.splice key, 1 each: (fn) -> for one, i in @_data fn.call @, @get(i), i @ pop: -> @remove(@_data.length - 1)[0] shift: -> @remove(0)[0] push: -> args = arguments _scopeChangeLength @, -> @set @_data.length, one for one in args @_data.length unshift: -> _old_length = @_data.length @push.apply @, arguments pos = for one, i in @_data if i < _old_length i + arguments.length else i - _old_length _scopeCallWatch @, pos, null, '$move' _scopeCallWatch @, @_data.length, _old_length, 'length' @_data.length reverse: -> @_data.reverse() pos = for one, i in @_data @_data.length - 1 - i _scopeCallWatch @, pos, null, '$move' @ sort: (fn) -> self = @ to_sort = for one, i in @_data e: one o: i to_sort.sort (a, b) -> fn.call self, a.e, b.e pos = [] @_data = for one, i in to_sort pos[one.o] = i one.e _scopeCallWatch @, pos, null, '$move' @ filter: (fn) -> to_remove = [] for one, i in @_data to_remove.push i unless fn.call @, one, i @remove i for i in to_remove.reverse() casua.defineController = (init_fn) -> _renderNode = (_controller, _scope, _root, named_nodes, template) -> if _scope instanceof casua.ArrayScope _renderNodes _controller, _scope, _root, named_nodes, template else if template['@controller'] new_template = _shallowCopy template new_controller = new template['@controller'](_scope, _controller) delete new_template['@controller'] _renderNode new_controller, _scope, _root, named_nodes, new_template else _context = _generateContext _controller, _root, named_nodes ret_nodes = [] for node_meta, child of template if node_meta.charAt(0) == '@' if r = node_meta.toLowerCase().match /^@(\w+)(?: (\S+))?$/ switch r[1] when 'on' if m = child.match __compute_controller_method_regexp method = __resolveMethod(_controller, m[1]) _root.on r[2], (e) -> method.call _context, e, _scope when 'html', 'text', 'append' __nodeBind _controller, _root, r[1], _scope, _context, child when 'val' __nodeValueBind _controller, _root, _scope, _context, child when 'attr' __nodeAttrBind _controller, _root, r[2], _scope, _context, child when 'class' __nodeAttrBind _controller, _root, r[1], _scope, _context, child when 'child' __nodeChildBind _controller, _root, r[2], _scope, named_nodes, child when 'if' __nodeCondition _controller, _root, r[1], _scope, _context, child when 'unless' __nodeCondition _controller, _root, r[1], _scope, _context, child, true else r = node_meta.match /^(.*?)(?: \$(\S+))?(?: \#.*)?$/ node = new casua.Node r[1] named_nodes['$' + r[2]] = node if r[2] ret_nodes.push node _root.append node if typeof child is 'object' _renderNode _controller, _scope, node, named_nodes, child else __nodeBind _controller, node, 'text', _scope, _context, child ret_nodes _renderNodes = (_controller, _scope, _root, named_nodes, template) -> _root.empty() _nodes = [] add_fn = (new_scope, type, idx) -> _new_named_nodes = _shallowCopy named_nodes _nodes[idx] = _renderNode _controller, new_scope, _root, _new_named_nodes, template _scope.$watch '$add', add_fn _scope.$watch '$delete', (new_scope, type, idx) -> nodes = _nodes.splice(idx, 1)[0] node.remove() for node in nodes _scope.$watch '$move', (new_pos) -> _new_nodes = [] _new_nodes[new_po] = _nodes[old_po] for new_po, old_po in new_pos _nodes = _new_nodes _root.empty() for nodes in _nodes _root.append node for node in nodes _scope.each (one, idx) -> add_fn.call {}, one, null, idx _generateContext = (_controller, _node, named_nodes) -> context = $node: (name) -> if name? if name.charAt(0) == '$' named_nodes[name] else named_nodes.$root.find name else _node parent = _controller $parent = context while parent for name, fn of parent.methods bound_fn = fn.bind context $parent[name] = bound_fn context[name] ||= bound_fn $parent = $parent.$parent = {} if parent = parent._parent context __nodeChildBind = (_controller, _root, attr, _scope, named_nodes, child) -> watch_fn = -> _renderNode _controller, _scope.get(attr), _root, named_nodes, child _scope.$watch attr, watch_fn watch_fn.call _scope __nodeBind = (_controller, _node, _method, _scope, _context, src) -> __computeBind _controller, _scope, _context, src, (result) -> _node[_method].call _node, result __keep_original_attr_regexp = /^class$/ __nodeAttrBind = (_controller, _node, attr, _scope, _context, src) -> original = if attr.match(__keep_original_attr_regexp) && o = _node.attr(attr) o + ' ' __computeBind _controller, _scope, _context, src, (result) -> result = original + result if original? _node.attr attr, result # if attr.match(__boolean_attr_regexp) # if _isFunction(src) # setter = -> # src.call _context, _node.attr(attr), _scope # else if r = src.match(__compute_scope_key_regexp) # setter = -> # _scope.set r[1], _node.attr(attr) # _node.on 'click', setter __nodeValueBind = (_controller, _node, _scope, _context, src) -> if r = src.match __compute_scope_key_regexp getter = -> _node.val _scope.get(r[1]) setter = -> _scope.set r[1], _node.val() else if r = src.match __compute_controller_method_regexp method = __resolveMethod _controller, r[1] getter = -> _node.val method.call(_context) setter = -> method.call _context, _node.val(), _scope else return __nodeBind _controller, _root, 'val', _scope, _context, child _node.on 'change', setter _node.on 'keyup', setter _scope.$startGetWatches() getter.call _scope _scope.$watch key, getter for key in _scope.$stopGetWatches() __nodeCondition = (_controller, _node, _method, _scope, _context, src, _unless = false) -> cur_node = true_node = _node false_node = new casua.Node '<!-- -->' __computeBind _controller, _scope, _context, src, ( (result) -> result = !result if _unless if result cur_node.replaceWith true_node cur_node = true_node else cur_node.replaceWith false_node cur_node = false_node ), true __compute_match_regexp = /\{\{([\S^\}]+?)\}\}/g __compute_match_key_regexp = /^\{\{([\S^\}]+?)\}\}$/ __compute_scope_regexp = /@(\S+)/g __compute_scope_key_regexp = /^@(\S+)$/ __compute_controller_regexp = /(\w\S*)\(\)/g __compute_controller_method_regexp = /^(\w\S*)\(\)$/ __computeBind = (_controller, _scope, _context, src, fn, to_eval = false) -> watch_fn = if _isFunction(src) -> fn.call {}, src.call(_context, _scope) else if r = src.match __compute_controller_method_regexp method = __resolveMethod _controller, r[1] -> fn.call {}, method.call(_context, _scope) else if r = src.match __compute_scope_key_regexp -> fn.call {}, @get(r[1]) else if r = src.match __compute_match_regexp -> scope = @ fn.call {}, src.replace __compute_match_regexp, (part) -> part = part.match __compute_match_key_regexp if r = part[1].match __compute_controller_method_regexp method = __resolveMethod _controller, r[1] method.call _context, _scope else if r = part[1].match __compute_scope_key_regexp scope.get(r[1]) else if to_eval ct = _context sc = _scope mm = {} src = src.replace __compute_controller_regexp, (part) -> part = part.match __compute_controller_method_regexp mm[part[1]] = __resolveMethod _controller, part[1] 'mm["' + part[1] + '"].call(ct, sc)' src = src.replace __compute_scope_regexp, (part) -> part = part.match __compute_scope_key_regexp 'sc.get("' + part[1] + '")' -> fn.call {}, eval(src) else -> fn.call {}, src _scope.$startGetWatches() watch_fn.call _scope _scope.$watch key, watch_fn for key in _scope.$stopGetWatches() __resolveMethod = (_controller, method) -> resolved_controller = _controller while true resolved_method = if resolved_controller.methods? resolved_controller.methods[method] if resolved_method? break else break unless resolved_controller = resolved_controller._parent resolved_method class constructor: (init_data = {}, @_parent) -> @scope = new casua.Scope init_data @methods = init_fn.call @, @scope, @ renderAt: (container, template) -> container = (new casua.Node container).empty() named_nodes = $root: container _renderNode @, @scope, container, named_nodes, template render: (template) -> fragment = new casua.Node document.createElement 'div' @renderAt fragment, template fragment window.casua = casua
25453
### Casua 0.0.2 Copyright (c) 2013-2016 <NAME> Released under the MIT license ### _shallowCopy = (src, dst = {}) -> dst[key] = value for key, value of src dst _isFunction = (obj) -> !!(obj && obj.constructor && obj.call && obj.apply); _escape_chars = { lt: '<', gt: '>', quot: '"', amp: '&', apos: "'" } _reversed_escape_chars = {} _reversed_escape_chars[v] = k for k, v of _escape_chars _escapeHTML = (str) -> str.replace /[&<>"']/g, (m) -> '&' + _reversed_escape_chars[m] + ';' __boolean_attr_regexp = /^multiple|selected|checked|disabled|required|open$/ _css_selector = typeof document.querySelectorAll is 'function' casua = {} class casua.Node _addNodes = (_node, elements) -> elements = [elements] if elements.nodeName for element in elements element._node = _node _push _node, element _push = (_node, one) -> _node[_node.length] = one _node.length += 1 _forEach = (_node, callback) -> ret = for one, idx in _node callback.call one, idx, one ret[0] __addEventListenerFn = if window.document.addEventListener (element, type, fn) -> element.addEventListener type, fn, false else (element, type, fn) -> element.attachEvent 'on' + type, fn __createEventHanlder = (element, events) -> ret = (event, type) -> event.preventDefault ||= -> event.returnValue = false event.stopPropagation ||= -> event.cancelBubble = true event.target ||= event.srcElement || document unless event.defaultPrevented? prevent = event.preventDefault event.preventDefault = -> event.defaultPrevented = true prevent.call event event.defaultPrevented = false event.isDefaultPrevented = -> ( event.defaultPrevented ) || ( event.returnValue == false ) eventFns = _shallowCopy( events[type || event.type] || []) fn.call element, event for i, fn of eventFns delete event.preventDefault delete event.stopPropagation delete event.isDefaultPrevented ret.elem = element ret.handleds = [] ret __trigger_to_dom_regexp = /^focus$/ constructor: (node_meta) -> @handlers = {} @events = {} @length = 0 if node_meta instanceof casua.Node return node_meta else if typeof node_meta is 'string' if node_meta.charAt(0) != '<' attrs_data = node_meta.split ' ' tag_data = attrs_data.shift() el = document.createElement if r = tag_data.match(/^([^\.^#]+)/) r[1] else 'div' if r = tag_data.match /\.([^\.^#]+)/g el.className = r.join(' ').replace /\./g, '' if r = tag_data.match /#([^\.^#]+)/ el.id = r[1] _addNodes @, el for attr in attrs_data if attr.charAt(0) != '#' && r = attr.match /^([^=]+)(?:=(['"])(.+?)\2)?$/ @attr r[1], ( r[3] || r[1] ) else div = document.createElement 'div' div.innerHTML = '<div>&#160;</div>' + node_meta div.removeChild div.firstChild for child in div.childNodes _addNodes @, child else _addNodes @, node_meta attr: (name, value) -> name = name.toLowerCase() return @val(value) if name.match /^val|value$/ if name.match __boolean_attr_regexp if value? if value _forEach @, -> @setAttribute name, name @[name] = true else _forEach @, -> @removeAttribute name @[name] = false @ else @[0][name] else if value? _forEach @, -> @setAttribute name, value @ else @[0].getAttribute name, 2 append: (node) -> node = new casua.Node node if typeof node is 'string' _forEach @, (i, parent) -> _forEach node, (j, child) -> parent.appendChild child @ empty: -> _forEach @, -> while @firstChild @removeChild @firstChild @ html: (value) -> if value? @empty() _forEach @, -> @innerHTML = value @ else @[0].innerHTML text: (value) -> if value? @html _escapeHTML(value) else @html() on: (type, fn) -> _node = @ @events[type] ||= [] @events[type].push fn _forEach @, (idx) -> handler = _node.handlers[idx] ||= __createEventHanlder @, _node.events handleds = handler.handleds if handleds.indexOf(type) == -1 __addEventListenerFn @, type, handler handleds.push type @ trigger: (type, event_data = {}) -> if type.match __trigger_to_dom_regexp trigger_to_dom = true _forEach @, -> event = document.createEvent 'HTMLEvents' event.initEvent type, true, true event[key] = value for key, value of event_data @dispatchEvent event @[type]() if trigger_to_dom @ remove: -> _forEach @, -> @parentNode.removeChild @ if @parentNode @ replaceWith: (node) -> node = new casua.Node node if typeof node is 'string' _forEach @, (i, from) -> _forEach node, (j, to) -> from.parentNode.replaceChild to, from if from.parentNode @ val: (value) -> if value? _forEach @, -> @value = value @ else @[0].value parent: -> if parent = @[0].parentNode parent._node || new casua.Node parent find: (query) -> element = if _css_selector @[0].querySelector query else @[0].getElementsByTagName query if element element._node || new casua.Node element _scopeInitParent = (_scope, _parent) -> _scope._childs = [] if _parent? _parent._childs.push _scope if _parent._childs.indexOf(_scope) == -1 _scope._parent = _parent _scopeRemovePrepare = (_scope, key) -> if _scope._data[key] instanceof casua.Scope s = _scope._data[key] if s._parent? i = s._parent._childs.indexOf s s._parent._childs.splice i, 1 _scopeCallWatch _scope, _scope._data[key], key, '$delete' _scopeCallWatch = (_scope, new_val, old_val, key) -> if typeof key is 'string' && key.charAt(0) == '$' _scopeCallAltWatch _scope, new_val, old_val, key else if _scope._watches[key] fn.call _scope, new_val, old_val, key for fn in _scope._watches[key] for child in _scope._childs unless child._data[key]? _scopeCallWatch child, new_val, old_val, key _scopeCallAltWatch = (_scope, new_val, key, type) -> if _scope._watches[type] fn.call _scope, new_val, type, key for fn in _scope._watches[type] __mutiple_levels_key_regexp = /^([^\.]+)\.(.+)$/ class casua.Scope constructor: (init_data, parent) -> if _isFunction(init_data) || ( init_data instanceof casua.Scope ) || ( init_data instanceof casua.Node ) return init_data else if init_data.length? return new casua.ArrayScope init_data, parent else _scopeInitParent @, parent @_watches = {} @_data = {} @set key, value for key, value of init_data get: (key) -> @_watch_lists.push key if @_watch_lists && @_watch_lists.indexOf(key) == -1 if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp if path = @get(r[1]) path.get(r[2]) else null else if key == '$parent' @_parent else ret = @_data[key] ret = @_parent.get(key) if !ret? && @_parent? ret set: (key, value) -> if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp @get(r[1]).set r[2], value else unless typeof key is 'string' && key.charAt(0) == '$' if typeof value is 'object' value = new casua.Scope value, @ if @_data[key] != value old = @_data[key] @_data[key] = value unless old? _scopeCallWatch @, value, key, '$add' _scopeCallWatch @, value, old, key @ remove: (key) -> if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp @get(r[1]).remove(r[2]) else _scopeRemovePrepare @, key delete @_data[key] @ $watch: (key, fn) -> if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp @get(r[1]).$watch r[2], fn @$watch r[1], fn else @_watches[key] ||= [] @_watches[key].push fn @ $startGetWatches: -> @_parent.$startGetWatches() if @_parent? @_watch_lists = [] $stopGetWatches: -> lists = for one in @_watch_lists one delete @_watch_lists lists = lists.concat @_parent.$stopGetWatches() if @_parent? lists _scopeChangeLength = (_scope, fn) -> _old_length = _scope._data.length ret = fn.call _scope _scopeCallWatch _scope, _scope._data.length, _old_length, 'length' ret class casua.ArrayScope extends casua.Scope constructor: (init_data, parent) -> if init_data instanceof casua.Scope return init_data else if not init_data.length? return new casua.Scope init_data, parent else _scopeInitParent @, parent @_watches = {} @_data = [] @set idx, value for value, idx in init_data length: -> @_data.length indexOf: (child) -> @_data.indexOf child remove: (key) -> _scopeChangeLength @, -> _scopeRemovePrepare @, key @_data.splice key, 1 each: (fn) -> for one, i in @_data fn.call @, @get(i), i @ pop: -> @remove(@_data.length - 1)[0] shift: -> @remove(0)[0] push: -> args = arguments _scopeChangeLength @, -> @set @_data.length, one for one in args @_data.length unshift: -> _old_length = @_data.length @push.apply @, arguments pos = for one, i in @_data if i < _old_length i + arguments.length else i - _old_length _scopeCallWatch @, pos, null, '$move' _scopeCallWatch @, @_data.length, _old_length, 'length' @_data.length reverse: -> @_data.reverse() pos = for one, i in @_data @_data.length - 1 - i _scopeCallWatch @, pos, null, '$move' @ sort: (fn) -> self = @ to_sort = for one, i in @_data e: one o: i to_sort.sort (a, b) -> fn.call self, a.e, b.e pos = [] @_data = for one, i in to_sort pos[one.o] = i one.e _scopeCallWatch @, pos, null, '$move' @ filter: (fn) -> to_remove = [] for one, i in @_data to_remove.push i unless fn.call @, one, i @remove i for i in to_remove.reverse() casua.defineController = (init_fn) -> _renderNode = (_controller, _scope, _root, named_nodes, template) -> if _scope instanceof casua.ArrayScope _renderNodes _controller, _scope, _root, named_nodes, template else if template['@controller'] new_template = _shallowCopy template new_controller = new template['@controller'](_scope, _controller) delete new_template['@controller'] _renderNode new_controller, _scope, _root, named_nodes, new_template else _context = _generateContext _controller, _root, named_nodes ret_nodes = [] for node_meta, child of template if node_meta.charAt(0) == '@' if r = node_meta.toLowerCase().match /^@(\w+)(?: (\S+))?$/ switch r[1] when 'on' if m = child.match __compute_controller_method_regexp method = __resolveMethod(_controller, m[1]) _root.on r[2], (e) -> method.call _context, e, _scope when 'html', 'text', 'append' __nodeBind _controller, _root, r[1], _scope, _context, child when 'val' __nodeValueBind _controller, _root, _scope, _context, child when 'attr' __nodeAttrBind _controller, _root, r[2], _scope, _context, child when 'class' __nodeAttrBind _controller, _root, r[1], _scope, _context, child when 'child' __nodeChildBind _controller, _root, r[2], _scope, named_nodes, child when 'if' __nodeCondition _controller, _root, r[1], _scope, _context, child when 'unless' __nodeCondition _controller, _root, r[1], _scope, _context, child, true else r = node_meta.match /^(.*?)(?: \$(\S+))?(?: \#.*)?$/ node = new casua.Node r[1] named_nodes['$' + r[2]] = node if r[2] ret_nodes.push node _root.append node if typeof child is 'object' _renderNode _controller, _scope, node, named_nodes, child else __nodeBind _controller, node, 'text', _scope, _context, child ret_nodes _renderNodes = (_controller, _scope, _root, named_nodes, template) -> _root.empty() _nodes = [] add_fn = (new_scope, type, idx) -> _new_named_nodes = _shallowCopy named_nodes _nodes[idx] = _renderNode _controller, new_scope, _root, _new_named_nodes, template _scope.$watch '$add', add_fn _scope.$watch '$delete', (new_scope, type, idx) -> nodes = _nodes.splice(idx, 1)[0] node.remove() for node in nodes _scope.$watch '$move', (new_pos) -> _new_nodes = [] _new_nodes[new_po] = _nodes[old_po] for new_po, old_po in new_pos _nodes = _new_nodes _root.empty() for nodes in _nodes _root.append node for node in nodes _scope.each (one, idx) -> add_fn.call {}, one, null, idx _generateContext = (_controller, _node, named_nodes) -> context = $node: (name) -> if name? if name.charAt(0) == '$' named_nodes[name] else named_nodes.$root.find name else _node parent = _controller $parent = context while parent for name, fn of parent.methods bound_fn = fn.bind context $parent[name] = bound_fn context[name] ||= bound_fn $parent = $parent.$parent = {} if parent = parent._parent context __nodeChildBind = (_controller, _root, attr, _scope, named_nodes, child) -> watch_fn = -> _renderNode _controller, _scope.get(attr), _root, named_nodes, child _scope.$watch attr, watch_fn watch_fn.call _scope __nodeBind = (_controller, _node, _method, _scope, _context, src) -> __computeBind _controller, _scope, _context, src, (result) -> _node[_method].call _node, result __keep_original_attr_regexp = /^class$/ __nodeAttrBind = (_controller, _node, attr, _scope, _context, src) -> original = if attr.match(__keep_original_attr_regexp) && o = _node.attr(attr) o + ' ' __computeBind _controller, _scope, _context, src, (result) -> result = original + result if original? _node.attr attr, result # if attr.match(__boolean_attr_regexp) # if _isFunction(src) # setter = -> # src.call _context, _node.attr(attr), _scope # else if r = src.match(__compute_scope_key_regexp) # setter = -> # _scope.set r[1], _node.attr(attr) # _node.on 'click', setter __nodeValueBind = (_controller, _node, _scope, _context, src) -> if r = src.match __compute_scope_key_regexp getter = -> _node.val _scope.get(r[1]) setter = -> _scope.set r[1], _node.val() else if r = src.match __compute_controller_method_regexp method = __resolveMethod _controller, r[1] getter = -> _node.val method.call(_context) setter = -> method.call _context, _node.val(), _scope else return __nodeBind _controller, _root, 'val', _scope, _context, child _node.on 'change', setter _node.on 'keyup', setter _scope.$startGetWatches() getter.call _scope _scope.$watch key, getter for key in _scope.$stopGetWatches() __nodeCondition = (_controller, _node, _method, _scope, _context, src, _unless = false) -> cur_node = true_node = _node false_node = new casua.Node '<!-- -->' __computeBind _controller, _scope, _context, src, ( (result) -> result = !result if _unless if result cur_node.replaceWith true_node cur_node = true_node else cur_node.replaceWith false_node cur_node = false_node ), true __compute_match_regexp = /\{\{([\S^\}]+?)\}\}/g __compute_match_key_regexp = /^\{\{([\S^\}]+?)\}\}$/ __compute_scope_regexp = /@(\S+)/g __compute_scope_key_regexp = /^@(\S+)$/ __compute_controller_regexp = /(\w\S*)\(\)/g __compute_controller_method_regexp = /^(\w\S*)\(\)$/ __computeBind = (_controller, _scope, _context, src, fn, to_eval = false) -> watch_fn = if _isFunction(src) -> fn.call {}, src.call(_context, _scope) else if r = src.match __compute_controller_method_regexp method = __resolveMethod _controller, r[1] -> fn.call {}, method.call(_context, _scope) else if r = src.match __compute_scope_key_regexp -> fn.call {}, @get(r[1]) else if r = src.match __compute_match_regexp -> scope = @ fn.call {}, src.replace __compute_match_regexp, (part) -> part = part.match __compute_match_key_regexp if r = part[1].match __compute_controller_method_regexp method = __resolveMethod _controller, r[1] method.call _context, _scope else if r = part[1].match __compute_scope_key_regexp scope.get(r[1]) else if to_eval ct = _context sc = _scope mm = {} src = src.replace __compute_controller_regexp, (part) -> part = part.match __compute_controller_method_regexp mm[part[1]] = __resolveMethod _controller, part[1] 'mm["' + part[1] + '"].call(ct, sc)' src = src.replace __compute_scope_regexp, (part) -> part = part.match __compute_scope_key_regexp 'sc.get("' + part[1] + '")' -> fn.call {}, eval(src) else -> fn.call {}, src _scope.$startGetWatches() watch_fn.call _scope _scope.$watch key, watch_fn for key in _scope.$stopGetWatches() __resolveMethod = (_controller, method) -> resolved_controller = _controller while true resolved_method = if resolved_controller.methods? resolved_controller.methods[method] if resolved_method? break else break unless resolved_controller = resolved_controller._parent resolved_method class constructor: (init_data = {}, @_parent) -> @scope = new casua.Scope init_data @methods = init_fn.call @, @scope, @ renderAt: (container, template) -> container = (new casua.Node container).empty() named_nodes = $root: container _renderNode @, @scope, container, named_nodes, template render: (template) -> fragment = new casua.Node document.createElement 'div' @renderAt fragment, template fragment window.casua = casua
true
### Casua 0.0.2 Copyright (c) 2013-2016 PI:NAME:<NAME>END_PI Released under the MIT license ### _shallowCopy = (src, dst = {}) -> dst[key] = value for key, value of src dst _isFunction = (obj) -> !!(obj && obj.constructor && obj.call && obj.apply); _escape_chars = { lt: '<', gt: '>', quot: '"', amp: '&', apos: "'" } _reversed_escape_chars = {} _reversed_escape_chars[v] = k for k, v of _escape_chars _escapeHTML = (str) -> str.replace /[&<>"']/g, (m) -> '&' + _reversed_escape_chars[m] + ';' __boolean_attr_regexp = /^multiple|selected|checked|disabled|required|open$/ _css_selector = typeof document.querySelectorAll is 'function' casua = {} class casua.Node _addNodes = (_node, elements) -> elements = [elements] if elements.nodeName for element in elements element._node = _node _push _node, element _push = (_node, one) -> _node[_node.length] = one _node.length += 1 _forEach = (_node, callback) -> ret = for one, idx in _node callback.call one, idx, one ret[0] __addEventListenerFn = if window.document.addEventListener (element, type, fn) -> element.addEventListener type, fn, false else (element, type, fn) -> element.attachEvent 'on' + type, fn __createEventHanlder = (element, events) -> ret = (event, type) -> event.preventDefault ||= -> event.returnValue = false event.stopPropagation ||= -> event.cancelBubble = true event.target ||= event.srcElement || document unless event.defaultPrevented? prevent = event.preventDefault event.preventDefault = -> event.defaultPrevented = true prevent.call event event.defaultPrevented = false event.isDefaultPrevented = -> ( event.defaultPrevented ) || ( event.returnValue == false ) eventFns = _shallowCopy( events[type || event.type] || []) fn.call element, event for i, fn of eventFns delete event.preventDefault delete event.stopPropagation delete event.isDefaultPrevented ret.elem = element ret.handleds = [] ret __trigger_to_dom_regexp = /^focus$/ constructor: (node_meta) -> @handlers = {} @events = {} @length = 0 if node_meta instanceof casua.Node return node_meta else if typeof node_meta is 'string' if node_meta.charAt(0) != '<' attrs_data = node_meta.split ' ' tag_data = attrs_data.shift() el = document.createElement if r = tag_data.match(/^([^\.^#]+)/) r[1] else 'div' if r = tag_data.match /\.([^\.^#]+)/g el.className = r.join(' ').replace /\./g, '' if r = tag_data.match /#([^\.^#]+)/ el.id = r[1] _addNodes @, el for attr in attrs_data if attr.charAt(0) != '#' && r = attr.match /^([^=]+)(?:=(['"])(.+?)\2)?$/ @attr r[1], ( r[3] || r[1] ) else div = document.createElement 'div' div.innerHTML = '<div>&#160;</div>' + node_meta div.removeChild div.firstChild for child in div.childNodes _addNodes @, child else _addNodes @, node_meta attr: (name, value) -> name = name.toLowerCase() return @val(value) if name.match /^val|value$/ if name.match __boolean_attr_regexp if value? if value _forEach @, -> @setAttribute name, name @[name] = true else _forEach @, -> @removeAttribute name @[name] = false @ else @[0][name] else if value? _forEach @, -> @setAttribute name, value @ else @[0].getAttribute name, 2 append: (node) -> node = new casua.Node node if typeof node is 'string' _forEach @, (i, parent) -> _forEach node, (j, child) -> parent.appendChild child @ empty: -> _forEach @, -> while @firstChild @removeChild @firstChild @ html: (value) -> if value? @empty() _forEach @, -> @innerHTML = value @ else @[0].innerHTML text: (value) -> if value? @html _escapeHTML(value) else @html() on: (type, fn) -> _node = @ @events[type] ||= [] @events[type].push fn _forEach @, (idx) -> handler = _node.handlers[idx] ||= __createEventHanlder @, _node.events handleds = handler.handleds if handleds.indexOf(type) == -1 __addEventListenerFn @, type, handler handleds.push type @ trigger: (type, event_data = {}) -> if type.match __trigger_to_dom_regexp trigger_to_dom = true _forEach @, -> event = document.createEvent 'HTMLEvents' event.initEvent type, true, true event[key] = value for key, value of event_data @dispatchEvent event @[type]() if trigger_to_dom @ remove: -> _forEach @, -> @parentNode.removeChild @ if @parentNode @ replaceWith: (node) -> node = new casua.Node node if typeof node is 'string' _forEach @, (i, from) -> _forEach node, (j, to) -> from.parentNode.replaceChild to, from if from.parentNode @ val: (value) -> if value? _forEach @, -> @value = value @ else @[0].value parent: -> if parent = @[0].parentNode parent._node || new casua.Node parent find: (query) -> element = if _css_selector @[0].querySelector query else @[0].getElementsByTagName query if element element._node || new casua.Node element _scopeInitParent = (_scope, _parent) -> _scope._childs = [] if _parent? _parent._childs.push _scope if _parent._childs.indexOf(_scope) == -1 _scope._parent = _parent _scopeRemovePrepare = (_scope, key) -> if _scope._data[key] instanceof casua.Scope s = _scope._data[key] if s._parent? i = s._parent._childs.indexOf s s._parent._childs.splice i, 1 _scopeCallWatch _scope, _scope._data[key], key, '$delete' _scopeCallWatch = (_scope, new_val, old_val, key) -> if typeof key is 'string' && key.charAt(0) == '$' _scopeCallAltWatch _scope, new_val, old_val, key else if _scope._watches[key] fn.call _scope, new_val, old_val, key for fn in _scope._watches[key] for child in _scope._childs unless child._data[key]? _scopeCallWatch child, new_val, old_val, key _scopeCallAltWatch = (_scope, new_val, key, type) -> if _scope._watches[type] fn.call _scope, new_val, type, key for fn in _scope._watches[type] __mutiple_levels_key_regexp = /^([^\.]+)\.(.+)$/ class casua.Scope constructor: (init_data, parent) -> if _isFunction(init_data) || ( init_data instanceof casua.Scope ) || ( init_data instanceof casua.Node ) return init_data else if init_data.length? return new casua.ArrayScope init_data, parent else _scopeInitParent @, parent @_watches = {} @_data = {} @set key, value for key, value of init_data get: (key) -> @_watch_lists.push key if @_watch_lists && @_watch_lists.indexOf(key) == -1 if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp if path = @get(r[1]) path.get(r[2]) else null else if key == '$parent' @_parent else ret = @_data[key] ret = @_parent.get(key) if !ret? && @_parent? ret set: (key, value) -> if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp @get(r[1]).set r[2], value else unless typeof key is 'string' && key.charAt(0) == '$' if typeof value is 'object' value = new casua.Scope value, @ if @_data[key] != value old = @_data[key] @_data[key] = value unless old? _scopeCallWatch @, value, key, '$add' _scopeCallWatch @, value, old, key @ remove: (key) -> if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp @get(r[1]).remove(r[2]) else _scopeRemovePrepare @, key delete @_data[key] @ $watch: (key, fn) -> if typeof key is 'string' && r = key.match __mutiple_levels_key_regexp @get(r[1]).$watch r[2], fn @$watch r[1], fn else @_watches[key] ||= [] @_watches[key].push fn @ $startGetWatches: -> @_parent.$startGetWatches() if @_parent? @_watch_lists = [] $stopGetWatches: -> lists = for one in @_watch_lists one delete @_watch_lists lists = lists.concat @_parent.$stopGetWatches() if @_parent? lists _scopeChangeLength = (_scope, fn) -> _old_length = _scope._data.length ret = fn.call _scope _scopeCallWatch _scope, _scope._data.length, _old_length, 'length' ret class casua.ArrayScope extends casua.Scope constructor: (init_data, parent) -> if init_data instanceof casua.Scope return init_data else if not init_data.length? return new casua.Scope init_data, parent else _scopeInitParent @, parent @_watches = {} @_data = [] @set idx, value for value, idx in init_data length: -> @_data.length indexOf: (child) -> @_data.indexOf child remove: (key) -> _scopeChangeLength @, -> _scopeRemovePrepare @, key @_data.splice key, 1 each: (fn) -> for one, i in @_data fn.call @, @get(i), i @ pop: -> @remove(@_data.length - 1)[0] shift: -> @remove(0)[0] push: -> args = arguments _scopeChangeLength @, -> @set @_data.length, one for one in args @_data.length unshift: -> _old_length = @_data.length @push.apply @, arguments pos = for one, i in @_data if i < _old_length i + arguments.length else i - _old_length _scopeCallWatch @, pos, null, '$move' _scopeCallWatch @, @_data.length, _old_length, 'length' @_data.length reverse: -> @_data.reverse() pos = for one, i in @_data @_data.length - 1 - i _scopeCallWatch @, pos, null, '$move' @ sort: (fn) -> self = @ to_sort = for one, i in @_data e: one o: i to_sort.sort (a, b) -> fn.call self, a.e, b.e pos = [] @_data = for one, i in to_sort pos[one.o] = i one.e _scopeCallWatch @, pos, null, '$move' @ filter: (fn) -> to_remove = [] for one, i in @_data to_remove.push i unless fn.call @, one, i @remove i for i in to_remove.reverse() casua.defineController = (init_fn) -> _renderNode = (_controller, _scope, _root, named_nodes, template) -> if _scope instanceof casua.ArrayScope _renderNodes _controller, _scope, _root, named_nodes, template else if template['@controller'] new_template = _shallowCopy template new_controller = new template['@controller'](_scope, _controller) delete new_template['@controller'] _renderNode new_controller, _scope, _root, named_nodes, new_template else _context = _generateContext _controller, _root, named_nodes ret_nodes = [] for node_meta, child of template if node_meta.charAt(0) == '@' if r = node_meta.toLowerCase().match /^@(\w+)(?: (\S+))?$/ switch r[1] when 'on' if m = child.match __compute_controller_method_regexp method = __resolveMethod(_controller, m[1]) _root.on r[2], (e) -> method.call _context, e, _scope when 'html', 'text', 'append' __nodeBind _controller, _root, r[1], _scope, _context, child when 'val' __nodeValueBind _controller, _root, _scope, _context, child when 'attr' __nodeAttrBind _controller, _root, r[2], _scope, _context, child when 'class' __nodeAttrBind _controller, _root, r[1], _scope, _context, child when 'child' __nodeChildBind _controller, _root, r[2], _scope, named_nodes, child when 'if' __nodeCondition _controller, _root, r[1], _scope, _context, child when 'unless' __nodeCondition _controller, _root, r[1], _scope, _context, child, true else r = node_meta.match /^(.*?)(?: \$(\S+))?(?: \#.*)?$/ node = new casua.Node r[1] named_nodes['$' + r[2]] = node if r[2] ret_nodes.push node _root.append node if typeof child is 'object' _renderNode _controller, _scope, node, named_nodes, child else __nodeBind _controller, node, 'text', _scope, _context, child ret_nodes _renderNodes = (_controller, _scope, _root, named_nodes, template) -> _root.empty() _nodes = [] add_fn = (new_scope, type, idx) -> _new_named_nodes = _shallowCopy named_nodes _nodes[idx] = _renderNode _controller, new_scope, _root, _new_named_nodes, template _scope.$watch '$add', add_fn _scope.$watch '$delete', (new_scope, type, idx) -> nodes = _nodes.splice(idx, 1)[0] node.remove() for node in nodes _scope.$watch '$move', (new_pos) -> _new_nodes = [] _new_nodes[new_po] = _nodes[old_po] for new_po, old_po in new_pos _nodes = _new_nodes _root.empty() for nodes in _nodes _root.append node for node in nodes _scope.each (one, idx) -> add_fn.call {}, one, null, idx _generateContext = (_controller, _node, named_nodes) -> context = $node: (name) -> if name? if name.charAt(0) == '$' named_nodes[name] else named_nodes.$root.find name else _node parent = _controller $parent = context while parent for name, fn of parent.methods bound_fn = fn.bind context $parent[name] = bound_fn context[name] ||= bound_fn $parent = $parent.$parent = {} if parent = parent._parent context __nodeChildBind = (_controller, _root, attr, _scope, named_nodes, child) -> watch_fn = -> _renderNode _controller, _scope.get(attr), _root, named_nodes, child _scope.$watch attr, watch_fn watch_fn.call _scope __nodeBind = (_controller, _node, _method, _scope, _context, src) -> __computeBind _controller, _scope, _context, src, (result) -> _node[_method].call _node, result __keep_original_attr_regexp = /^class$/ __nodeAttrBind = (_controller, _node, attr, _scope, _context, src) -> original = if attr.match(__keep_original_attr_regexp) && o = _node.attr(attr) o + ' ' __computeBind _controller, _scope, _context, src, (result) -> result = original + result if original? _node.attr attr, result # if attr.match(__boolean_attr_regexp) # if _isFunction(src) # setter = -> # src.call _context, _node.attr(attr), _scope # else if r = src.match(__compute_scope_key_regexp) # setter = -> # _scope.set r[1], _node.attr(attr) # _node.on 'click', setter __nodeValueBind = (_controller, _node, _scope, _context, src) -> if r = src.match __compute_scope_key_regexp getter = -> _node.val _scope.get(r[1]) setter = -> _scope.set r[1], _node.val() else if r = src.match __compute_controller_method_regexp method = __resolveMethod _controller, r[1] getter = -> _node.val method.call(_context) setter = -> method.call _context, _node.val(), _scope else return __nodeBind _controller, _root, 'val', _scope, _context, child _node.on 'change', setter _node.on 'keyup', setter _scope.$startGetWatches() getter.call _scope _scope.$watch key, getter for key in _scope.$stopGetWatches() __nodeCondition = (_controller, _node, _method, _scope, _context, src, _unless = false) -> cur_node = true_node = _node false_node = new casua.Node '<!-- -->' __computeBind _controller, _scope, _context, src, ( (result) -> result = !result if _unless if result cur_node.replaceWith true_node cur_node = true_node else cur_node.replaceWith false_node cur_node = false_node ), true __compute_match_regexp = /\{\{([\S^\}]+?)\}\}/g __compute_match_key_regexp = /^\{\{([\S^\}]+?)\}\}$/ __compute_scope_regexp = /@(\S+)/g __compute_scope_key_regexp = /^@(\S+)$/ __compute_controller_regexp = /(\w\S*)\(\)/g __compute_controller_method_regexp = /^(\w\S*)\(\)$/ __computeBind = (_controller, _scope, _context, src, fn, to_eval = false) -> watch_fn = if _isFunction(src) -> fn.call {}, src.call(_context, _scope) else if r = src.match __compute_controller_method_regexp method = __resolveMethod _controller, r[1] -> fn.call {}, method.call(_context, _scope) else if r = src.match __compute_scope_key_regexp -> fn.call {}, @get(r[1]) else if r = src.match __compute_match_regexp -> scope = @ fn.call {}, src.replace __compute_match_regexp, (part) -> part = part.match __compute_match_key_regexp if r = part[1].match __compute_controller_method_regexp method = __resolveMethod _controller, r[1] method.call _context, _scope else if r = part[1].match __compute_scope_key_regexp scope.get(r[1]) else if to_eval ct = _context sc = _scope mm = {} src = src.replace __compute_controller_regexp, (part) -> part = part.match __compute_controller_method_regexp mm[part[1]] = __resolveMethod _controller, part[1] 'mm["' + part[1] + '"].call(ct, sc)' src = src.replace __compute_scope_regexp, (part) -> part = part.match __compute_scope_key_regexp 'sc.get("' + part[1] + '")' -> fn.call {}, eval(src) else -> fn.call {}, src _scope.$startGetWatches() watch_fn.call _scope _scope.$watch key, watch_fn for key in _scope.$stopGetWatches() __resolveMethod = (_controller, method) -> resolved_controller = _controller while true resolved_method = if resolved_controller.methods? resolved_controller.methods[method] if resolved_method? break else break unless resolved_controller = resolved_controller._parent resolved_method class constructor: (init_data = {}, @_parent) -> @scope = new casua.Scope init_data @methods = init_fn.call @, @scope, @ renderAt: (container, template) -> container = (new casua.Node container).empty() named_nodes = $root: container _renderNode @, @scope, container, named_nodes, template render: (template) -> fragment = new casua.Node document.createElement 'div' @renderAt fragment, template fragment window.casua = casua
[ { "context": "rm')\n form.on 'submit', (e) ->\n password = new Password()\n decryptedPassword = $('#decrypted_passwor", "end": 561, "score": 0.964015007019043, "start": 549, "tag": "PASSWORD", "value": "new Password" }, { "context": "ey\", \"\")\n\n if key\n ...
app/assets/javascripts/passwords.js.coffee
randx/code-test
4
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ class @Password encrypt: (key, password)-> CryptoJS.AES.encrypt(password, key).toString() decrypt: (key, encryptedPassword)-> CryptoJS.AES.decrypt(encryptedPassword, key). toString(CryptoJS.enc.Utf8); class @PasswordForm constructor: -> form = $('#password-form') form.on 'submit', (e) -> password = new Password() decryptedPassword = $('#decrypted_password').val() key = prompt("Please enter encryption key", "") if key encryptedPassword = password.encrypt(key, decryptedPassword) $('#password_password').val(encryptedPassword) else form.find('.errors').text('Encryption key cant be blank').show() e.preventDefault() class @PasswordShow constructor: -> form = $('.decrypt-form') form.on 'submit', (e) -> e.preventDefault() password = new Password() encryptedPassword = $('#encrypted_password').val() key = form.find('#encrypt_key').val() password = password.decrypt(key, encryptedPassword) if password $('.password').text(password) $('.errors').hide() form.hide() else $('.errors').text('Wrong encryption key').show() class @PasswordMigrate constructor: -> form = $('.migrate-form') form.on 'submit', (e) -> e.preventDefault() key = form.find('#encrypt_key').val() password = new Password() form.find('.btn').hide() form.find('.loading').show() $('.migrate-password-form').each (i, e)-> decryptedPassword = $(e).find('.decrypted-pass').val() encryptedPassword = password.encrypt(key, decryptedPassword) $(e).find('.encrypted-pass').val(encryptedPassword) $(e).on "ajax:success", (event, xhr, settings) => $(e).parent().remove() if $('.migrate-password-form').size() == 0 location.reload() $(e).trigger('submit.rails')
44418
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ class @Password encrypt: (key, password)-> CryptoJS.AES.encrypt(password, key).toString() decrypt: (key, encryptedPassword)-> CryptoJS.AES.decrypt(encryptedPassword, key). toString(CryptoJS.enc.Utf8); class @PasswordForm constructor: -> form = $('#password-form') form.on 'submit', (e) -> password = <PASSWORD>() decryptedPassword = $('#decrypted_password').val() key = prompt("Please enter encryption key", "") if key encryptedPassword = <PASSWORD>.encrypt(key, decryptedPassword) $('#password_password').val(encryptedPassword) else form.find('.errors').text('Encryption key cant be blank').show() e.preventDefault() class @PasswordShow constructor: -> form = $('.decrypt-form') form.on 'submit', (e) -> e.preventDefault() password = <PASSWORD>() encryptedPassword = $('#encrypted_password').val() key = form.find('#encrypt_key').val() password = <PASSWORD>.<PASSWORD>(key, encrypted<PASSWORD>) if password $('.password').text(password) $('.errors').hide() form.hide() else $('.errors').text('Wrong encryption key').show() class @PasswordMigrate constructor: -> form = $('.migrate-form') form.on 'submit', (e) -> e.preventDefault() key = form.find('#encrypt_key').val() password = <PASSWORD>() form.find('.btn').hide() form.find('.loading').show() $('.migrate-password-form').each (i, e)-> decryptedPassword = $(e).find('.decrypted-pass').val() encryptedPassword = password.encrypt(key, decryptedPassword) $(e).find('.encrypted-pass').val(encryptedPassword) $(e).on "ajax:success", (event, xhr, settings) => $(e).parent().remove() if $('.migrate-password-form').size() == 0 location.reload() $(e).trigger('submit.rails')
true
# Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ class @Password encrypt: (key, password)-> CryptoJS.AES.encrypt(password, key).toString() decrypt: (key, encryptedPassword)-> CryptoJS.AES.decrypt(encryptedPassword, key). toString(CryptoJS.enc.Utf8); class @PasswordForm constructor: -> form = $('#password-form') form.on 'submit', (e) -> password = PI:PASSWORD:<PASSWORD>END_PI() decryptedPassword = $('#decrypted_password').val() key = prompt("Please enter encryption key", "") if key encryptedPassword = PI:PASSWORD:<PASSWORD>END_PI.encrypt(key, decryptedPassword) $('#password_password').val(encryptedPassword) else form.find('.errors').text('Encryption key cant be blank').show() e.preventDefault() class @PasswordShow constructor: -> form = $('.decrypt-form') form.on 'submit', (e) -> e.preventDefault() password = PI:PASSWORD:<PASSWORD>END_PI() encryptedPassword = $('#encrypted_password').val() key = form.find('#encrypt_key').val() password = PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI(key, encryptedPI:PASSWORD:<PASSWORD>END_PI) if password $('.password').text(password) $('.errors').hide() form.hide() else $('.errors').text('Wrong encryption key').show() class @PasswordMigrate constructor: -> form = $('.migrate-form') form.on 'submit', (e) -> e.preventDefault() key = form.find('#encrypt_key').val() password = PI:PASSWORD:<PASSWORD>END_PI() form.find('.btn').hide() form.find('.loading').show() $('.migrate-password-form').each (i, e)-> decryptedPassword = $(e).find('.decrypted-pass').val() encryptedPassword = password.encrypt(key, decryptedPassword) $(e).find('.encrypted-pass').val(encryptedPassword) $(e).on "ajax:success", (event, xhr, settings) => $(e).parent().remove() if $('.migrate-password-form').size() == 0 location.reload() $(e).trigger('submit.rails')
[ { "context": " service = new HiveTaxi.Service(accessKeyId: 'foo', secretAccessKey: 'bar')\n expect(service.co", "end": 2138, "score": 0.9391584992408752, "start": 2135, "tag": "KEY", "value": "foo" }, { "context": "axi.Service(accessKeyId: 'foo', secretAccessKey: 'bar')\n ...
test/service.spec.coffee
HIVETAXI/hive.taxi.sdk.js
0
helpers = require('./helpers') HiveTaxi = helpers.HiveTaxi MockService = helpers.MockService metadata = require('../apis/metadata.json') describe 'HiveTaxi.Service', -> config = null; service = null retryableError = (error, result) -> expect(service.retryableError(error)).to.eql(result) beforeEach (done) -> config = new HiveTaxi.Config() service = new HiveTaxi.Service(config) done() describe 'apiVersions', -> it 'should set apiVersions property', -> CustomService = HiveTaxi.Service.defineService('custom', ['1.2', '2.4']) expect(CustomService.apiVersions).to.eql(['1.2', '2.4']) describe 'constructor', -> it 'should use HiveTaxi.config copy if no config is provided', -> service = new HiveTaxi.Service() expect(service.config).not.to.equal(HiveTaxi.config) expect(service.config.sslEnabled).to.equal(true) it 'should merge custom options on top of global defaults if config provided', -> service = new HiveTaxi.Service(maxRetries: 5) expect(service.config.sslEnabled).to.equal(true) expect(service.config.maxRetries).to.equal(5) it 'merges service-specific configuration from global config', -> HiveTaxi.config.update(cartographer: endpoint: 'localhost') crt = new HiveTaxi.Cartographer expect(crt.endpoint.host).to.equal('localhost') delete HiveTaxi.config.cartographer it 'service-specific global config overrides global config', -> region = HiveTaxi.config.region HiveTaxi.config.update(region: 'ru-2', cartographer: region: 'ru-1') crt = new HiveTaxi.Cartographer expect(crt.config.region).to.equal('ru-1') HiveTaxi.config.region = region delete HiveTaxi.config.cartographer it 'service-specific local config overrides service-specific global config', -> HiveTaxi.config.update(cartographer: region: 'ru-2') crt = new HiveTaxi.Cartographer region: 'ru-1' expect(crt.config.region).to.equal('ru-1') delete HiveTaxi.config.cartographer it 'merges credential data into config', -> service = new HiveTaxi.Service(accessKeyId: 'foo', secretAccessKey: 'bar') expect(service.config.credentials.accessKeyId).to.equal('foo') expect(service.config.credentials.secretAccessKey).to.equal('bar') it 'should allow HiveTaxi.config to be object literal', -> cfg = HiveTaxi.config HiveTaxi.config = maxRetries: 20 service = new HiveTaxi.Service({}) expect(service.config.maxRetries).to.equal(20) expect(service.config.sslEnabled).to.equal(true) HiveTaxi.config = cfg it 'tries to construct service with latest API version', -> CustomService = HiveTaxi.Service.defineService('custom', ['2.7', '1.9']) errmsg = "Could not find API configuration custom-2.7" expect(-> new CustomService()).to.throw(errmsg) it 'tries to construct service with exact API version match', -> CustomService = HiveTaxi.Service.defineService('custom', ['2.7', '1.9']) errmsg = "Could not find API configuration custom-1.9" expect(-> new CustomService(apiVersion: '1.9')).to.throw(errmsg) it 'skips any API versions with a * and uses next (future) service', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.6', '0.8*', '0.9']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService(apiVersion: '0.8')).to.throw(errmsg) it 'skips multiple API versions with a * and uses next (future) service', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.6', '0.7*', '0.8*', '0.9']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService(apiVersion: '0.7')).to.throw(errmsg) it 'tries to construct service with fuzzy API version match', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.7']) errmsg = "Could not find API configuration custom-0.7" expect(-> new CustomService(apiVersion: '0.8')).to.throw(errmsg) it 'uses global apiVersion value when constructing versioned services', -> HiveTaxi.config.apiVersion = '1.0' CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService).to.throw(errmsg) HiveTaxi.config.apiVersion = null it 'uses global apiVersions value when constructing versioned services', -> HiveTaxi.config.apiVersions = {custom: '1.0'} CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService).to.throw(errmsg) HiveTaxi.config.apiVersions = {} it 'uses service specific apiVersions before apiVersion', -> HiveTaxi.config.apiVersions = {custom: '0.8'} HiveTaxi.config.apiVersion = '1.2' CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.6" expect(-> new CustomService).to.throw(errmsg) HiveTaxi.config.apiVersion = null HiveTaxi.config.apiVersions = {} it 'tries to construct service with fuzzy API version match', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.6" expect(-> new CustomService(apiVersion: '0.8')).to.throw(errmsg) it 'fails if apiVersion matches nothing', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find custom API to satisfy version constraint `0.5'" expect(-> new CustomService(apiVersion: '0.5')).to.throw(errmsg) it 'allows construction of services from one-off apiConfig properties', -> service = new HiveTaxi.Service apiConfig: operations: operationName: input: {}, output: {} expect(typeof service.operationName).to.equal('function') expect(service.operationName() instanceof HiveTaxi.Request).to.equal(true) it 'interpolates endpoint when reading from configuration', -> service = new MockService(endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('https://mockservice.mock-region.domain.tld') service = new MockService(sslEnabled: false, endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('http://mockservice.mock-region.domain.tld') describe 'will work with', -> allServices = require('../clients/all') for own className, ctor of allServices serviceIdentifier = className.toLowerCase() # check for obsolete versions obsoleteVersions = metadata[serviceIdentifier].versions || [] for version in obsoleteVersions ((ctor, id, v) -> it id + ' version ' + v, -> expect(-> new ctor(apiVersion: v)).not.to.throw() )(ctor, serviceIdentifier, version) describe 'setEndpoint', -> FooService = null beforeEach (done) -> FooService = HiveTaxi.util.inherit HiveTaxi.Service, api: endpointPrefix: 'fooservice' done() it 'uses specified endpoint if provided', -> service = new FooService() service.setEndpoint('notfooservice.hivetaxi.com') expect(service.endpoint.host).to.equal('notfooservice.hivetaxi.com') describe 'makeRequest', -> it 'it treats params as an optinal parameter', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() service.makeRequest 'operationName', (err, data) -> expect(data).to.equal('FOOBAR') it 'yields data to the callback', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() req = service.makeRequest 'operation', (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') it 'yields service errors to the callback', -> helpers.mockHttpResponse(500, {}, ['ServiceError']) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err.code).to.equal('ServiceError') expect(err.message).to.equal(null) expect(err.statusCode).to.equal(500) expect(err.retryable).to.equal(true) expect(data).to.equal(null) it 'yields network errors to the callback', -> error = { code: 'NetworkingError' } helpers.mockHttpResponse(error) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.eql(error) expect(data).to.equal(null) it 'does not send the request if a callback function is omitted', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) httpClient = HiveTaxi.HttpClient.getInstance() helpers.spyOn(httpClient, 'handleRequest') new MockService().makeRequest('operation') expect(httpClient.handleRequest.calls.length).to.equal(0) it 'allows parameter validation to be disabled in config', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService(paramValidation: false) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') describe 'bound parameters', -> it 'accepts toplevel bound parameters on the service', -> service = new HiveTaxi.Cartographer(params: {formalName: 'London', shortName: 'key'}) req = service.makeRequest 'findObjects' expect(req.params).to.eql(formalName: 'London', shortName: 'key') it 'ignores bound parameters not in input members', -> service = new HiveTaxi.Cartographer(params: {formalName: 'London', Key: 'key'}) req = service.makeRequest 'findObjects' expect(req.params).to.eql(formalName: 'London') it 'can override bound parameters', -> service = new HiveTaxi.Cartographer(params: {formalName: 'London', Key: 'key'}) params = formalName: 'notLondon' req = service.makeRequest('findObjects', params) expect(params).not.to.equal(req.params) expect(req.params).to.eql(formalName: 'notLondon') describe 'global events', -> it 'adds HiveTaxi.events listeners to requests', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) event = helpers.createSpy() HiveTaxi.events.on('complete', event) new MockService().makeRequest('operation').send() expect(event.calls.length).not.to.equal(0) describe 'retryableError', -> it 'should retry on throttle error', -> retryableError({code: 'ProvisionedThroughputExceededException', statusCode:400}, true) retryableError({code: 'ThrottlingException', statusCode:400}, true) retryableError({code: 'Throttling', statusCode:400}, true) retryableError({code: 'RequestLimitExceeded', statusCode:400}, true) retryableError({code: 'RequestThrottled', statusCode:400}, true) it 'should retry on expired credentials error', -> retryableError({code: 'ExpiredTokenException', statusCode:400}, true) it 'should retry on 500 or above regardless of error', -> retryableError({code: 'Error', statusCode:500 }, true) retryableError({code: 'RandomError', statusCode:505 }, true) it 'should not retry when error is < 500 level status code', -> retryableError({code: 'Error', statusCode:200 }, false) retryableError({code: 'Error', statusCode:302 }, false) retryableError({code: 'Error', statusCode:404 }, false) describe 'numRetries', -> it 'should use config max retry value if defined', -> service.config.maxRetries = 30 expect(service.numRetries()).to.equal(30) it 'should use defaultRetries defined on object if undefined on config', -> service.defaultRetryCount = 13 service.config.maxRetries = undefined expect(service.numRetries()).to.equal(13) describe 'defineMethods', -> operations = null serviceConstructor = null beforeEach (done) -> serviceConstructor = () -> HiveTaxi.Service.call(this, new HiveTaxi.Config()) serviceConstructor.prototype = Object.create(HiveTaxi.Service.prototype) serviceConstructor.prototype.api = {} operations = {'foo': {}, 'bar': {}} serviceConstructor.prototype.api.operations = operations done() it 'should add operation methods', -> HiveTaxi.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(typeof serviceConstructor.prototype.bar).to.equal('function') it 'should not overwrite methods with generated methods', -> foo = -> serviceConstructor.prototype.foo = foo HiveTaxi.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(serviceConstructor.prototype.foo).to.eql(foo) expect(typeof serviceConstructor.prototype.bar).to.equal('function') describe 'should generate a method', -> it 'that makes an authenticated request by default', (done) -> HiveTaxi.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') customService.foo(); expect(customService.makeRequest.calls.length).to.equal(1) done() it 'that makes an unauthenticated request when operation authtype is none', (done) -> serviceConstructor.prototype.api.operations.foo.authtype = 'none' HiveTaxi.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') helpers.spyOn(customService, 'makeUnauthenticatedRequest') expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(0) customService.foo(); expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) customService.bar(); expect(customService.makeRequest.calls.length).to.equal(1) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) done()
74198
helpers = require('./helpers') HiveTaxi = helpers.HiveTaxi MockService = helpers.MockService metadata = require('../apis/metadata.json') describe 'HiveTaxi.Service', -> config = null; service = null retryableError = (error, result) -> expect(service.retryableError(error)).to.eql(result) beforeEach (done) -> config = new HiveTaxi.Config() service = new HiveTaxi.Service(config) done() describe 'apiVersions', -> it 'should set apiVersions property', -> CustomService = HiveTaxi.Service.defineService('custom', ['1.2', '2.4']) expect(CustomService.apiVersions).to.eql(['1.2', '2.4']) describe 'constructor', -> it 'should use HiveTaxi.config copy if no config is provided', -> service = new HiveTaxi.Service() expect(service.config).not.to.equal(HiveTaxi.config) expect(service.config.sslEnabled).to.equal(true) it 'should merge custom options on top of global defaults if config provided', -> service = new HiveTaxi.Service(maxRetries: 5) expect(service.config.sslEnabled).to.equal(true) expect(service.config.maxRetries).to.equal(5) it 'merges service-specific configuration from global config', -> HiveTaxi.config.update(cartographer: endpoint: 'localhost') crt = new HiveTaxi.Cartographer expect(crt.endpoint.host).to.equal('localhost') delete HiveTaxi.config.cartographer it 'service-specific global config overrides global config', -> region = HiveTaxi.config.region HiveTaxi.config.update(region: 'ru-2', cartographer: region: 'ru-1') crt = new HiveTaxi.Cartographer expect(crt.config.region).to.equal('ru-1') HiveTaxi.config.region = region delete HiveTaxi.config.cartographer it 'service-specific local config overrides service-specific global config', -> HiveTaxi.config.update(cartographer: region: 'ru-2') crt = new HiveTaxi.Cartographer region: 'ru-1' expect(crt.config.region).to.equal('ru-1') delete HiveTaxi.config.cartographer it 'merges credential data into config', -> service = new HiveTaxi.Service(accessKeyId: '<KEY>', secretAccessKey: '<KEY>') expect(service.config.credentials.accessKeyId).to.equal('foo') expect(service.config.credentials.secretAccessKey).to.equal('bar') it 'should allow HiveTaxi.config to be object literal', -> cfg = HiveTaxi.config HiveTaxi.config = maxRetries: 20 service = new HiveTaxi.Service({}) expect(service.config.maxRetries).to.equal(20) expect(service.config.sslEnabled).to.equal(true) HiveTaxi.config = cfg it 'tries to construct service with latest API version', -> CustomService = HiveTaxi.Service.defineService('custom', ['2.7', '1.9']) errmsg = "Could not find API configuration custom-2.7" expect(-> new CustomService()).to.throw(errmsg) it 'tries to construct service with exact API version match', -> CustomService = HiveTaxi.Service.defineService('custom', ['2.7', '1.9']) errmsg = "Could not find API configuration custom-1.9" expect(-> new CustomService(apiVersion: '1.9')).to.throw(errmsg) it 'skips any API versions with a * and uses next (future) service', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.6', '0.8*', '0.9']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService(apiVersion: '0.8')).to.throw(errmsg) it 'skips multiple API versions with a * and uses next (future) service', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.6', '0.7*', '0.8*', '0.9']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService(apiVersion: '0.7')).to.throw(errmsg) it 'tries to construct service with fuzzy API version match', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.7']) errmsg = "Could not find API configuration custom-0.7" expect(-> new CustomService(apiVersion: '0.8')).to.throw(errmsg) it 'uses global apiVersion value when constructing versioned services', -> HiveTaxi.config.apiVersion = '1.0' CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService).to.throw(errmsg) HiveTaxi.config.apiVersion = null it 'uses global apiVersions value when constructing versioned services', -> HiveTaxi.config.apiVersions = {custom: '1.0'} CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService).to.throw(errmsg) HiveTaxi.config.apiVersions = {} it 'uses service specific apiVersions before apiVersion', -> HiveTaxi.config.apiVersions = {custom: '0.8'} HiveTaxi.config.apiVersion = '1.2' CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.6" expect(-> new CustomService).to.throw(errmsg) HiveTaxi.config.apiVersion = null HiveTaxi.config.apiVersions = {} it 'tries to construct service with fuzzy API version match', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.6" expect(-> new CustomService(apiVersion: '0.8')).to.throw(errmsg) it 'fails if apiVersion matches nothing', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find custom API to satisfy version constraint `0.5'" expect(-> new CustomService(apiVersion: '0.5')).to.throw(errmsg) it 'allows construction of services from one-off apiConfig properties', -> service = new HiveTaxi.Service apiConfig: operations: operationName: input: {}, output: {} expect(typeof service.operationName).to.equal('function') expect(service.operationName() instanceof HiveTaxi.Request).to.equal(true) it 'interpolates endpoint when reading from configuration', -> service = new MockService(endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('https://mockservice.mock-region.domain.tld') service = new MockService(sslEnabled: false, endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('http://mockservice.mock-region.domain.tld') describe 'will work with', -> allServices = require('../clients/all') for own className, ctor of allServices serviceIdentifier = className.toLowerCase() # check for obsolete versions obsoleteVersions = metadata[serviceIdentifier].versions || [] for version in obsoleteVersions ((ctor, id, v) -> it id + ' version ' + v, -> expect(-> new ctor(apiVersion: v)).not.to.throw() )(ctor, serviceIdentifier, version) describe 'setEndpoint', -> FooService = null beforeEach (done) -> FooService = HiveTaxi.util.inherit HiveTaxi.Service, api: endpointPrefix: 'fooservice' done() it 'uses specified endpoint if provided', -> service = new FooService() service.setEndpoint('notfooservice.hivetaxi.com') expect(service.endpoint.host).to.equal('notfooservice.hivetaxi.com') describe 'makeRequest', -> it 'it treats params as an optinal parameter', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() service.makeRequest 'operationName', (err, data) -> expect(data).to.equal('FOOBAR') it 'yields data to the callback', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() req = service.makeRequest 'operation', (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') it 'yields service errors to the callback', -> helpers.mockHttpResponse(500, {}, ['ServiceError']) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err.code).to.equal('ServiceError') expect(err.message).to.equal(null) expect(err.statusCode).to.equal(500) expect(err.retryable).to.equal(true) expect(data).to.equal(null) it 'yields network errors to the callback', -> error = { code: 'NetworkingError' } helpers.mockHttpResponse(error) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.eql(error) expect(data).to.equal(null) it 'does not send the request if a callback function is omitted', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) httpClient = HiveTaxi.HttpClient.getInstance() helpers.spyOn(httpClient, 'handleRequest') new MockService().makeRequest('operation') expect(httpClient.handleRequest.calls.length).to.equal(0) it 'allows parameter validation to be disabled in config', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService(paramValidation: false) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') describe 'bound parameters', -> it 'accepts toplevel bound parameters on the service', -> service = new HiveTaxi.Cartographer(params: {formalName: 'London', shortName: 'key'}) req = service.makeRequest 'findObjects' expect(req.params).to.eql(formalName: 'London', shortName: 'key') it 'ignores bound parameters not in input members', -> service = new HiveTaxi.Cartographer(params: {formalName: '<NAME>ondon', Key: 'key'}) req = service.makeRequest 'findObjects' expect(req.params).to.eql(formalName: 'London') it 'can override bound parameters', -> service = new HiveTaxi.Cartographer(params: {formalName: '<NAME>ondon', Key: 'key'}) params = formalName: 'notLondon' req = service.makeRequest('findObjects', params) expect(params).not.to.equal(req.params) expect(req.params).to.eql(formalName: 'notLondon') describe 'global events', -> it 'adds HiveTaxi.events listeners to requests', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) event = helpers.createSpy() HiveTaxi.events.on('complete', event) new MockService().makeRequest('operation').send() expect(event.calls.length).not.to.equal(0) describe 'retryableError', -> it 'should retry on throttle error', -> retryableError({code: 'ProvisionedThroughputExceededException', statusCode:400}, true) retryableError({code: 'ThrottlingException', statusCode:400}, true) retryableError({code: 'Throttling', statusCode:400}, true) retryableError({code: 'RequestLimitExceeded', statusCode:400}, true) retryableError({code: 'RequestThrottled', statusCode:400}, true) it 'should retry on expired credentials error', -> retryableError({code: 'ExpiredTokenException', statusCode:400}, true) it 'should retry on 500 or above regardless of error', -> retryableError({code: 'Error', statusCode:500 }, true) retryableError({code: 'RandomError', statusCode:505 }, true) it 'should not retry when error is < 500 level status code', -> retryableError({code: 'Error', statusCode:200 }, false) retryableError({code: 'Error', statusCode:302 }, false) retryableError({code: 'Error', statusCode:404 }, false) describe 'numRetries', -> it 'should use config max retry value if defined', -> service.config.maxRetries = 30 expect(service.numRetries()).to.equal(30) it 'should use defaultRetries defined on object if undefined on config', -> service.defaultRetryCount = 13 service.config.maxRetries = undefined expect(service.numRetries()).to.equal(13) describe 'defineMethods', -> operations = null serviceConstructor = null beforeEach (done) -> serviceConstructor = () -> HiveTaxi.Service.call(this, new HiveTaxi.Config()) serviceConstructor.prototype = Object.create(HiveTaxi.Service.prototype) serviceConstructor.prototype.api = {} operations = {'foo': {}, 'bar': {}} serviceConstructor.prototype.api.operations = operations done() it 'should add operation methods', -> HiveTaxi.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(typeof serviceConstructor.prototype.bar).to.equal('function') it 'should not overwrite methods with generated methods', -> foo = -> serviceConstructor.prototype.foo = foo HiveTaxi.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(serviceConstructor.prototype.foo).to.eql(foo) expect(typeof serviceConstructor.prototype.bar).to.equal('function') describe 'should generate a method', -> it 'that makes an authenticated request by default', (done) -> HiveTaxi.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') customService.foo(); expect(customService.makeRequest.calls.length).to.equal(1) done() it 'that makes an unauthenticated request when operation authtype is none', (done) -> serviceConstructor.prototype.api.operations.foo.authtype = 'none' HiveTaxi.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') helpers.spyOn(customService, 'makeUnauthenticatedRequest') expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(0) customService.foo(); expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) customService.bar(); expect(customService.makeRequest.calls.length).to.equal(1) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) done()
true
helpers = require('./helpers') HiveTaxi = helpers.HiveTaxi MockService = helpers.MockService metadata = require('../apis/metadata.json') describe 'HiveTaxi.Service', -> config = null; service = null retryableError = (error, result) -> expect(service.retryableError(error)).to.eql(result) beforeEach (done) -> config = new HiveTaxi.Config() service = new HiveTaxi.Service(config) done() describe 'apiVersions', -> it 'should set apiVersions property', -> CustomService = HiveTaxi.Service.defineService('custom', ['1.2', '2.4']) expect(CustomService.apiVersions).to.eql(['1.2', '2.4']) describe 'constructor', -> it 'should use HiveTaxi.config copy if no config is provided', -> service = new HiveTaxi.Service() expect(service.config).not.to.equal(HiveTaxi.config) expect(service.config.sslEnabled).to.equal(true) it 'should merge custom options on top of global defaults if config provided', -> service = new HiveTaxi.Service(maxRetries: 5) expect(service.config.sslEnabled).to.equal(true) expect(service.config.maxRetries).to.equal(5) it 'merges service-specific configuration from global config', -> HiveTaxi.config.update(cartographer: endpoint: 'localhost') crt = new HiveTaxi.Cartographer expect(crt.endpoint.host).to.equal('localhost') delete HiveTaxi.config.cartographer it 'service-specific global config overrides global config', -> region = HiveTaxi.config.region HiveTaxi.config.update(region: 'ru-2', cartographer: region: 'ru-1') crt = new HiveTaxi.Cartographer expect(crt.config.region).to.equal('ru-1') HiveTaxi.config.region = region delete HiveTaxi.config.cartographer it 'service-specific local config overrides service-specific global config', -> HiveTaxi.config.update(cartographer: region: 'ru-2') crt = new HiveTaxi.Cartographer region: 'ru-1' expect(crt.config.region).to.equal('ru-1') delete HiveTaxi.config.cartographer it 'merges credential data into config', -> service = new HiveTaxi.Service(accessKeyId: 'PI:KEY:<KEY>END_PI', secretAccessKey: 'PI:KEY:<KEY>END_PI') expect(service.config.credentials.accessKeyId).to.equal('foo') expect(service.config.credentials.secretAccessKey).to.equal('bar') it 'should allow HiveTaxi.config to be object literal', -> cfg = HiveTaxi.config HiveTaxi.config = maxRetries: 20 service = new HiveTaxi.Service({}) expect(service.config.maxRetries).to.equal(20) expect(service.config.sslEnabled).to.equal(true) HiveTaxi.config = cfg it 'tries to construct service with latest API version', -> CustomService = HiveTaxi.Service.defineService('custom', ['2.7', '1.9']) errmsg = "Could not find API configuration custom-2.7" expect(-> new CustomService()).to.throw(errmsg) it 'tries to construct service with exact API version match', -> CustomService = HiveTaxi.Service.defineService('custom', ['2.7', '1.9']) errmsg = "Could not find API configuration custom-1.9" expect(-> new CustomService(apiVersion: '1.9')).to.throw(errmsg) it 'skips any API versions with a * and uses next (future) service', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.6', '0.8*', '0.9']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService(apiVersion: '0.8')).to.throw(errmsg) it 'skips multiple API versions with a * and uses next (future) service', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.6', '0.7*', '0.8*', '0.9']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService(apiVersion: '0.7')).to.throw(errmsg) it 'tries to construct service with fuzzy API version match', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.7']) errmsg = "Could not find API configuration custom-0.7" expect(-> new CustomService(apiVersion: '0.8')).to.throw(errmsg) it 'uses global apiVersion value when constructing versioned services', -> HiveTaxi.config.apiVersion = '1.0' CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService).to.throw(errmsg) HiveTaxi.config.apiVersion = null it 'uses global apiVersions value when constructing versioned services', -> HiveTaxi.config.apiVersions = {custom: '1.0'} CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.9" expect(-> new CustomService).to.throw(errmsg) HiveTaxi.config.apiVersions = {} it 'uses service specific apiVersions before apiVersion', -> HiveTaxi.config.apiVersions = {custom: '0.8'} HiveTaxi.config.apiVersion = '1.2' CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.6" expect(-> new CustomService).to.throw(errmsg) HiveTaxi.config.apiVersion = null HiveTaxi.config.apiVersions = {} it 'tries to construct service with fuzzy API version match', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find API configuration custom-0.6" expect(-> new CustomService(apiVersion: '0.8')).to.throw(errmsg) it 'fails if apiVersion matches nothing', -> CustomService = HiveTaxi.Service.defineService('custom', ['0.9', '0.6']) errmsg = "Could not find custom API to satisfy version constraint `0.5'" expect(-> new CustomService(apiVersion: '0.5')).to.throw(errmsg) it 'allows construction of services from one-off apiConfig properties', -> service = new HiveTaxi.Service apiConfig: operations: operationName: input: {}, output: {} expect(typeof service.operationName).to.equal('function') expect(service.operationName() instanceof HiveTaxi.Request).to.equal(true) it 'interpolates endpoint when reading from configuration', -> service = new MockService(endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('https://mockservice.mock-region.domain.tld') service = new MockService(sslEnabled: false, endpoint: '{scheme}://{service}.{region}.domain.tld') expect(service.config.endpoint).to.equal('http://mockservice.mock-region.domain.tld') describe 'will work with', -> allServices = require('../clients/all') for own className, ctor of allServices serviceIdentifier = className.toLowerCase() # check for obsolete versions obsoleteVersions = metadata[serviceIdentifier].versions || [] for version in obsoleteVersions ((ctor, id, v) -> it id + ' version ' + v, -> expect(-> new ctor(apiVersion: v)).not.to.throw() )(ctor, serviceIdentifier, version) describe 'setEndpoint', -> FooService = null beforeEach (done) -> FooService = HiveTaxi.util.inherit HiveTaxi.Service, api: endpointPrefix: 'fooservice' done() it 'uses specified endpoint if provided', -> service = new FooService() service.setEndpoint('notfooservice.hivetaxi.com') expect(service.endpoint.host).to.equal('notfooservice.hivetaxi.com') describe 'makeRequest', -> it 'it treats params as an optinal parameter', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() service.makeRequest 'operationName', (err, data) -> expect(data).to.equal('FOOBAR') it 'yields data to the callback', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService() req = service.makeRequest 'operation', (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') it 'yields service errors to the callback', -> helpers.mockHttpResponse(500, {}, ['ServiceError']) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err.code).to.equal('ServiceError') expect(err.message).to.equal(null) expect(err.statusCode).to.equal(500) expect(err.retryable).to.equal(true) expect(data).to.equal(null) it 'yields network errors to the callback', -> error = { code: 'NetworkingError' } helpers.mockHttpResponse(error) service = new MockService(maxRetries: 0) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.eql(error) expect(data).to.equal(null) it 'does not send the request if a callback function is omitted', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) httpClient = HiveTaxi.HttpClient.getInstance() helpers.spyOn(httpClient, 'handleRequest') new MockService().makeRequest('operation') expect(httpClient.handleRequest.calls.length).to.equal(0) it 'allows parameter validation to be disabled in config', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) service = new MockService(paramValidation: false) req = service.makeRequest 'operation', {}, (err, data) -> expect(err).to.equal(null) expect(data).to.equal('FOOBAR') describe 'bound parameters', -> it 'accepts toplevel bound parameters on the service', -> service = new HiveTaxi.Cartographer(params: {formalName: 'London', shortName: 'key'}) req = service.makeRequest 'findObjects' expect(req.params).to.eql(formalName: 'London', shortName: 'key') it 'ignores bound parameters not in input members', -> service = new HiveTaxi.Cartographer(params: {formalName: 'PI:NAME:<NAME>END_PIondon', Key: 'key'}) req = service.makeRequest 'findObjects' expect(req.params).to.eql(formalName: 'London') it 'can override bound parameters', -> service = new HiveTaxi.Cartographer(params: {formalName: 'PI:NAME:<NAME>END_PIondon', Key: 'key'}) params = formalName: 'notLondon' req = service.makeRequest('findObjects', params) expect(params).not.to.equal(req.params) expect(req.params).to.eql(formalName: 'notLondon') describe 'global events', -> it 'adds HiveTaxi.events listeners to requests', -> helpers.mockHttpResponse(200, {}, ['FOO', 'BAR']) event = helpers.createSpy() HiveTaxi.events.on('complete', event) new MockService().makeRequest('operation').send() expect(event.calls.length).not.to.equal(0) describe 'retryableError', -> it 'should retry on throttle error', -> retryableError({code: 'ProvisionedThroughputExceededException', statusCode:400}, true) retryableError({code: 'ThrottlingException', statusCode:400}, true) retryableError({code: 'Throttling', statusCode:400}, true) retryableError({code: 'RequestLimitExceeded', statusCode:400}, true) retryableError({code: 'RequestThrottled', statusCode:400}, true) it 'should retry on expired credentials error', -> retryableError({code: 'ExpiredTokenException', statusCode:400}, true) it 'should retry on 500 or above regardless of error', -> retryableError({code: 'Error', statusCode:500 }, true) retryableError({code: 'RandomError', statusCode:505 }, true) it 'should not retry when error is < 500 level status code', -> retryableError({code: 'Error', statusCode:200 }, false) retryableError({code: 'Error', statusCode:302 }, false) retryableError({code: 'Error', statusCode:404 }, false) describe 'numRetries', -> it 'should use config max retry value if defined', -> service.config.maxRetries = 30 expect(service.numRetries()).to.equal(30) it 'should use defaultRetries defined on object if undefined on config', -> service.defaultRetryCount = 13 service.config.maxRetries = undefined expect(service.numRetries()).to.equal(13) describe 'defineMethods', -> operations = null serviceConstructor = null beforeEach (done) -> serviceConstructor = () -> HiveTaxi.Service.call(this, new HiveTaxi.Config()) serviceConstructor.prototype = Object.create(HiveTaxi.Service.prototype) serviceConstructor.prototype.api = {} operations = {'foo': {}, 'bar': {}} serviceConstructor.prototype.api.operations = operations done() it 'should add operation methods', -> HiveTaxi.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(typeof serviceConstructor.prototype.bar).to.equal('function') it 'should not overwrite methods with generated methods', -> foo = -> serviceConstructor.prototype.foo = foo HiveTaxi.Service.defineMethods(serviceConstructor); expect(typeof serviceConstructor.prototype.foo).to.equal('function') expect(serviceConstructor.prototype.foo).to.eql(foo) expect(typeof serviceConstructor.prototype.bar).to.equal('function') describe 'should generate a method', -> it 'that makes an authenticated request by default', (done) -> HiveTaxi.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') customService.foo(); expect(customService.makeRequest.calls.length).to.equal(1) done() it 'that makes an unauthenticated request when operation authtype is none', (done) -> serviceConstructor.prototype.api.operations.foo.authtype = 'none' HiveTaxi.Service.defineMethods(serviceConstructor); customService = new serviceConstructor() helpers.spyOn(customService, 'makeRequest') helpers.spyOn(customService, 'makeUnauthenticatedRequest') expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(0) customService.foo(); expect(customService.makeRequest.calls.length).to.equal(0) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) customService.bar(); expect(customService.makeRequest.calls.length).to.equal(1) expect(customService.makeUnauthenticatedRequest.calls.length).to.equal(1) done()
[ { "context": " be persisted', ->\n\t\t\t@epubController.set(\"key\", \"alksjflkasd\")\n\t\t\t@epubController.set(\"updated_at\", \"alksdjfs\"", "end": 2946, "score": 0.9996368288993835, "start": 2935, "tag": "KEY", "value": "alksjflkasd" } ]
spec/javascripts/models/epub_controller_spec.coffee
benetech/readium
6
describe "Readium.Models.EPUBController", -> describe "initialization", -> beforeEach -> stubFileSystem() describe "with valid params", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) it "initializes a pagination strategy selector", -> epub = new Readium.Models.EPUBController({"epub" : @epub}) expect(epub.paginator).toBeDefined() it "initializes a reference to the package document", -> epubController = new Readium.Models.EPUBController({"epub" : @epub}) expect(epubController.packageDocument).toBeDefined() # TODO: This is still broken it "calls fetch on the package document", -> packDoc = new Readium.Models.PackageDocument({book: {}, "file_path": "some/path"}) spyOn(Readium.Models, "PackageDocument").andReturn(packDoc) spyOn(packDoc, "fetch") epubController = new Readium.Models.EPUBController({"epub" : @epub}) expect(Readium.Models.PackageDocument).toHaveBeenCalled() expect(packDoc.fetch).toHaveBeenCalled() describe "sets up event handlers", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) @epubController = new Readium.Models.EPUBController({"epub" : @epub}) it 'savePosition and setMetaSize on change:spine_position', -> spyOn(@epubController.savePosition, "apply") spyOn(@epubController.setMetaSize, "apply") @epubController.trigger("change:spine_position") expect(@epubController.savePosition.apply).toHaveBeenCalled() expect(@epubController.setMetaSize.apply).toHaveBeenCalled() describe "defaults", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) @epubController = new Readium.Models.EPUBController({"epub" : @epub}) it 'correctly sets default attributes', -> expect(@epubController.get("font_size")).toEqual(10) expect(@epubController.get("two_up")).toEqual(false) expect(@epubController.get("full_screen")).toEqual(false) expect(@epubController.get("toolbar_visible")).toEqual(true) expect(@epubController.get("toc_visible")).toEqual(false) expect(@epubController.get("rendered_spine_items")).toEqual([]) expect(@epubController.get("current_theme")).toEqual("default-theme") expect(@epubController.get("current_margin")).toEqual(3) describe "toJSON", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) @epubController = new Readium.Models.EPUBController({"epub" : @epub}) it 'does not serialize attributes that should not be presisted', -> @epubController.set("rendered_spine_items", [1, 2, 3]) @epubController.set("spine_index", [1]) json = @epubController.toJSON() expect(json.rendered_spine_items).not.toBeDefined() expect(json.spine_index).not.toBeDefined() it 'serializes attributes that should be persisted', -> @epubController.set("key", "alksjflkasd") @epubController.set("updated_at", "alksdjfs") json = @epubController.toJSON() expect(json.current_theme).toBeDefined() expect(json.updated_at).toBeDefined() expect(json.current_margin).toBeDefined() expect(json.font_size).toBeDefined() expect(json.two_up).toBeDefined() expect(json.key).toBeDefined()
118187
describe "Readium.Models.EPUBController", -> describe "initialization", -> beforeEach -> stubFileSystem() describe "with valid params", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) it "initializes a pagination strategy selector", -> epub = new Readium.Models.EPUBController({"epub" : @epub}) expect(epub.paginator).toBeDefined() it "initializes a reference to the package document", -> epubController = new Readium.Models.EPUBController({"epub" : @epub}) expect(epubController.packageDocument).toBeDefined() # TODO: This is still broken it "calls fetch on the package document", -> packDoc = new Readium.Models.PackageDocument({book: {}, "file_path": "some/path"}) spyOn(Readium.Models, "PackageDocument").andReturn(packDoc) spyOn(packDoc, "fetch") epubController = new Readium.Models.EPUBController({"epub" : @epub}) expect(Readium.Models.PackageDocument).toHaveBeenCalled() expect(packDoc.fetch).toHaveBeenCalled() describe "sets up event handlers", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) @epubController = new Readium.Models.EPUBController({"epub" : @epub}) it 'savePosition and setMetaSize on change:spine_position', -> spyOn(@epubController.savePosition, "apply") spyOn(@epubController.setMetaSize, "apply") @epubController.trigger("change:spine_position") expect(@epubController.savePosition.apply).toHaveBeenCalled() expect(@epubController.setMetaSize.apply).toHaveBeenCalled() describe "defaults", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) @epubController = new Readium.Models.EPUBController({"epub" : @epub}) it 'correctly sets default attributes', -> expect(@epubController.get("font_size")).toEqual(10) expect(@epubController.get("two_up")).toEqual(false) expect(@epubController.get("full_screen")).toEqual(false) expect(@epubController.get("toolbar_visible")).toEqual(true) expect(@epubController.get("toc_visible")).toEqual(false) expect(@epubController.get("rendered_spine_items")).toEqual([]) expect(@epubController.get("current_theme")).toEqual("default-theme") expect(@epubController.get("current_margin")).toEqual(3) describe "toJSON", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) @epubController = new Readium.Models.EPUBController({"epub" : @epub}) it 'does not serialize attributes that should not be presisted', -> @epubController.set("rendered_spine_items", [1, 2, 3]) @epubController.set("spine_index", [1]) json = @epubController.toJSON() expect(json.rendered_spine_items).not.toBeDefined() expect(json.spine_index).not.toBeDefined() it 'serializes attributes that should be persisted', -> @epubController.set("key", "<KEY>") @epubController.set("updated_at", "alksdjfs") json = @epubController.toJSON() expect(json.current_theme).toBeDefined() expect(json.updated_at).toBeDefined() expect(json.current_margin).toBeDefined() expect(json.font_size).toBeDefined() expect(json.two_up).toBeDefined() expect(json.key).toBeDefined()
true
describe "Readium.Models.EPUBController", -> describe "initialization", -> beforeEach -> stubFileSystem() describe "with valid params", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) it "initializes a pagination strategy selector", -> epub = new Readium.Models.EPUBController({"epub" : @epub}) expect(epub.paginator).toBeDefined() it "initializes a reference to the package document", -> epubController = new Readium.Models.EPUBController({"epub" : @epub}) expect(epubController.packageDocument).toBeDefined() # TODO: This is still broken it "calls fetch on the package document", -> packDoc = new Readium.Models.PackageDocument({book: {}, "file_path": "some/path"}) spyOn(Readium.Models, "PackageDocument").andReturn(packDoc) spyOn(packDoc, "fetch") epubController = new Readium.Models.EPUBController({"epub" : @epub}) expect(Readium.Models.PackageDocument).toHaveBeenCalled() expect(packDoc.fetch).toHaveBeenCalled() describe "sets up event handlers", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) @epubController = new Readium.Models.EPUBController({"epub" : @epub}) it 'savePosition and setMetaSize on change:spine_position', -> spyOn(@epubController.savePosition, "apply") spyOn(@epubController.setMetaSize, "apply") @epubController.trigger("change:spine_position") expect(@epubController.savePosition.apply).toHaveBeenCalled() expect(@epubController.setMetaSize.apply).toHaveBeenCalled() describe "defaults", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) @epubController = new Readium.Models.EPUBController({"epub" : @epub}) it 'correctly sets default attributes', -> expect(@epubController.get("font_size")).toEqual(10) expect(@epubController.get("two_up")).toEqual(false) expect(@epubController.get("full_screen")).toEqual(false) expect(@epubController.get("toolbar_visible")).toEqual(true) expect(@epubController.get("toc_visible")).toEqual(false) expect(@epubController.get("rendered_spine_items")).toEqual([]) expect(@epubController.get("current_theme")).toEqual("default-theme") expect(@epubController.get("current_margin")).toEqual(3) describe "toJSON", -> beforeEach -> @epub = new Readium.Models.EPUB({"package_doc_path": "some/file/path"}) @epubController = new Readium.Models.EPUBController({"epub" : @epub}) it 'does not serialize attributes that should not be presisted', -> @epubController.set("rendered_spine_items", [1, 2, 3]) @epubController.set("spine_index", [1]) json = @epubController.toJSON() expect(json.rendered_spine_items).not.toBeDefined() expect(json.spine_index).not.toBeDefined() it 'serializes attributes that should be persisted', -> @epubController.set("key", "PI:KEY:<KEY>END_PI") @epubController.set("updated_at", "alksdjfs") json = @epubController.toJSON() expect(json.current_theme).toBeDefined() expect(json.updated_at).toBeDefined() expect(json.current_margin).toBeDefined() expect(json.font_size).toBeDefined() expect(json.two_up).toBeDefined() expect(json.key).toBeDefined()
[ { "context": "# Copyright © 2013 All rights reserved\n# Author: nhim175@gmail.com\n\nconfig = require '../config.coffee'\nRedDuck = re", "end": 66, "score": 0.9999125599861145, "start": 49, "tag": "EMAIL", "value": "nhim175@gmail.com" } ]
src/lib/states/menu_state.coffee
nhim175/scorpionsmasher
0
# Copyright © 2013 All rights reserved # Author: nhim175@gmail.com config = require '../config.coffee' RedDuck = require '../red_duck.coffee' Platform = require '../platform.coffee' Logger = require '../../mixins/logger.coffee' Module = require '../module.coffee' Button = require '../button.coffee' LOGO_WIDTH = 368 LOGO_HEIGHT = 144 START_BTN_WIDTH = 212 class MenuState extends Module @include Logger logPrefix: 'MenuState' constructor: (game)-> preload: -> create: -> @game.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT @game.scale.setScreenSize true # set background @game.add.sprite 0, 0, 'background' @GUI = @game.add.group() @logo = @game.add.sprite @game.world.centerX, @game.world.centerY - 100, 'logo' @logo.anchor.setTo 0.5, 0.5 @game.add.tween(@logo).to {y: @game.world.centerY - 150}, 1000, Phaser.Easing.Cubic.InOut, true, 0, Number.MAX_VALUE, true @startBtn = new Button @game, @game.world.centerX, @game.world.centerY, 'start_btn', @onStartBtnClickListener @startBtn.anchor.setTo 0.5, 0.5 @GUI.add @logo @GUI.add @startBtn @debug @startBtn onStartBtnClickListener: => @debug 'start btn click listener' @game.state.start 'play' update: -> module.exports = MenuState
106648
# Copyright © 2013 All rights reserved # Author: <EMAIL> config = require '../config.coffee' RedDuck = require '../red_duck.coffee' Platform = require '../platform.coffee' Logger = require '../../mixins/logger.coffee' Module = require '../module.coffee' Button = require '../button.coffee' LOGO_WIDTH = 368 LOGO_HEIGHT = 144 START_BTN_WIDTH = 212 class MenuState extends Module @include Logger logPrefix: 'MenuState' constructor: (game)-> preload: -> create: -> @game.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT @game.scale.setScreenSize true # set background @game.add.sprite 0, 0, 'background' @GUI = @game.add.group() @logo = @game.add.sprite @game.world.centerX, @game.world.centerY - 100, 'logo' @logo.anchor.setTo 0.5, 0.5 @game.add.tween(@logo).to {y: @game.world.centerY - 150}, 1000, Phaser.Easing.Cubic.InOut, true, 0, Number.MAX_VALUE, true @startBtn = new Button @game, @game.world.centerX, @game.world.centerY, 'start_btn', @onStartBtnClickListener @startBtn.anchor.setTo 0.5, 0.5 @GUI.add @logo @GUI.add @startBtn @debug @startBtn onStartBtnClickListener: => @debug 'start btn click listener' @game.state.start 'play' update: -> module.exports = MenuState
true
# Copyright © 2013 All rights reserved # Author: PI:EMAIL:<EMAIL>END_PI config = require '../config.coffee' RedDuck = require '../red_duck.coffee' Platform = require '../platform.coffee' Logger = require '../../mixins/logger.coffee' Module = require '../module.coffee' Button = require '../button.coffee' LOGO_WIDTH = 368 LOGO_HEIGHT = 144 START_BTN_WIDTH = 212 class MenuState extends Module @include Logger logPrefix: 'MenuState' constructor: (game)-> preload: -> create: -> @game.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT @game.scale.setScreenSize true # set background @game.add.sprite 0, 0, 'background' @GUI = @game.add.group() @logo = @game.add.sprite @game.world.centerX, @game.world.centerY - 100, 'logo' @logo.anchor.setTo 0.5, 0.5 @game.add.tween(@logo).to {y: @game.world.centerY - 150}, 1000, Phaser.Easing.Cubic.InOut, true, 0, Number.MAX_VALUE, true @startBtn = new Button @game, @game.world.centerX, @game.world.centerY, 'start_btn', @onStartBtnClickListener @startBtn.anchor.setTo 0.5, 0.5 @GUI.add @logo @GUI.add @startBtn @debug @startBtn onStartBtnClickListener: => @debug 'start btn click listener' @game.state.start 'play' update: -> module.exports = MenuState
[ { "context": "'codewars-workspace'\nOPEN_FILE_KEY = DATA_DIR + '-loading'\n\nmodule.exports = Codewars =\n subscriptions: nu", "end": 210, "score": 0.8494628667831421, "start": 203, "tag": "KEY", "value": "loading" } ]
lib/main.coffee
JCCR/atom-codewars
2
fs = require 'fs' path = require 'path' mkdirp = require 'mkdirp' {CompositeDisposable} = require 'atom' MainView = null # Defer until used DATA_DIR = 'codewars-workspace' OPEN_FILE_KEY = DATA_DIR + '-loading' module.exports = Codewars = subscriptions: null mainView: null path: null pathStatesDir: null pathWindowState: null pathFocusState: null firstWindowAtLaunch: false activate: (state) -> window.codewars = @ @state = state @path = path.join atom.getConfigDirPath(), DATA_DIR @pathStatesDir = path.join @path, '.states' @pathWindowState = path.join @pathStatesDir, 'window' @pathFocusState = path.join @pathStatesDir, 'focus' if state.isCodewarsWindow @_clearWindowState -> atom.close() return if atom.getCurrentWindow().id is 1 @firstWindowAtLaunch = true fs.access @pathWindowState, (err) => if err then @firstWindowAtLaunch = false checkIfCodewarsWindow = (textEditorFile) => if (path.basename textEditorFile) is OPEN_FILE_KEY @_writeWindowState() # Actually create the view now @createView state mkdirp @pathStatesDir, (err) -> throw err if err # Check if the window has the codewars initial file open disposable = new CompositeDisposable disposable.add atom.workspace.observeTextEditors (editor) -> checkIfCodewarsWindow editor?.getPath() disposable.dispose() @subscriptions = new CompositeDisposable # Register command that toggles this view @subscriptions.add atom.commands.add 'atom-workspace', 'codewars:toggle': => @toggle() createView: (state) -> MainView ?= require './main-view' @mainView = new MainView @path, state.mainViewState @_watchStateFiles() deactivate: -> @_pathStatesWatcher?.close() @_clearWindowState() @subscriptions?.dispose() @mainView?.destroy() serialize: -> isCodewarsWindow: !!@mainView mainViewState: @mainView?.serialize() toggle: -> @_checkWindowState (openNewWindow) => return unless openNewWindow atom.open pathsToOpen: [path.join(@path, OPEN_FILE_KEY)], newWindow: true if @mainView @mainView.activate() else @_touchFocusState() # == Private functions == # _writeWindowState: (cb) -> fs.writeFile @pathWindowState, atom.getCurrentWindow().id, cb _checkWindowState: (callback) -> fs.readFile @pathWindowState, (err, data) => if err or @firstWindowAtLaunch or not data?.toString()?.length @firstWindowAtLaunch = false @_clearWindowState -> callback true else callback false _clearWindowState: (callback) -> fs.unlink @pathWindowState, -> callback?() _touchFocusState: -> fs.writeFile @pathFocusState _watchStateFiles: -> @_pathStatesWatcher = fs.watch @pathStatesDir @_pathStatesWatcher.on 'change', (event, filename) => if filename is 'window' fs.readFile @pathWindowState, (err, data) => if err or (parseInt data.toString()) isnt atom.getCurrentWindow().id @_writeWindowState() if filename is 'focus' @mainView.activate() atom.getCurrentWindow().focus()
218945
fs = require 'fs' path = require 'path' mkdirp = require 'mkdirp' {CompositeDisposable} = require 'atom' MainView = null # Defer until used DATA_DIR = 'codewars-workspace' OPEN_FILE_KEY = DATA_DIR + '-<KEY>' module.exports = Codewars = subscriptions: null mainView: null path: null pathStatesDir: null pathWindowState: null pathFocusState: null firstWindowAtLaunch: false activate: (state) -> window.codewars = @ @state = state @path = path.join atom.getConfigDirPath(), DATA_DIR @pathStatesDir = path.join @path, '.states' @pathWindowState = path.join @pathStatesDir, 'window' @pathFocusState = path.join @pathStatesDir, 'focus' if state.isCodewarsWindow @_clearWindowState -> atom.close() return if atom.getCurrentWindow().id is 1 @firstWindowAtLaunch = true fs.access @pathWindowState, (err) => if err then @firstWindowAtLaunch = false checkIfCodewarsWindow = (textEditorFile) => if (path.basename textEditorFile) is OPEN_FILE_KEY @_writeWindowState() # Actually create the view now @createView state mkdirp @pathStatesDir, (err) -> throw err if err # Check if the window has the codewars initial file open disposable = new CompositeDisposable disposable.add atom.workspace.observeTextEditors (editor) -> checkIfCodewarsWindow editor?.getPath() disposable.dispose() @subscriptions = new CompositeDisposable # Register command that toggles this view @subscriptions.add atom.commands.add 'atom-workspace', 'codewars:toggle': => @toggle() createView: (state) -> MainView ?= require './main-view' @mainView = new MainView @path, state.mainViewState @_watchStateFiles() deactivate: -> @_pathStatesWatcher?.close() @_clearWindowState() @subscriptions?.dispose() @mainView?.destroy() serialize: -> isCodewarsWindow: !!@mainView mainViewState: @mainView?.serialize() toggle: -> @_checkWindowState (openNewWindow) => return unless openNewWindow atom.open pathsToOpen: [path.join(@path, OPEN_FILE_KEY)], newWindow: true if @mainView @mainView.activate() else @_touchFocusState() # == Private functions == # _writeWindowState: (cb) -> fs.writeFile @pathWindowState, atom.getCurrentWindow().id, cb _checkWindowState: (callback) -> fs.readFile @pathWindowState, (err, data) => if err or @firstWindowAtLaunch or not data?.toString()?.length @firstWindowAtLaunch = false @_clearWindowState -> callback true else callback false _clearWindowState: (callback) -> fs.unlink @pathWindowState, -> callback?() _touchFocusState: -> fs.writeFile @pathFocusState _watchStateFiles: -> @_pathStatesWatcher = fs.watch @pathStatesDir @_pathStatesWatcher.on 'change', (event, filename) => if filename is 'window' fs.readFile @pathWindowState, (err, data) => if err or (parseInt data.toString()) isnt atom.getCurrentWindow().id @_writeWindowState() if filename is 'focus' @mainView.activate() atom.getCurrentWindow().focus()
true
fs = require 'fs' path = require 'path' mkdirp = require 'mkdirp' {CompositeDisposable} = require 'atom' MainView = null # Defer until used DATA_DIR = 'codewars-workspace' OPEN_FILE_KEY = DATA_DIR + '-PI:KEY:<KEY>END_PI' module.exports = Codewars = subscriptions: null mainView: null path: null pathStatesDir: null pathWindowState: null pathFocusState: null firstWindowAtLaunch: false activate: (state) -> window.codewars = @ @state = state @path = path.join atom.getConfigDirPath(), DATA_DIR @pathStatesDir = path.join @path, '.states' @pathWindowState = path.join @pathStatesDir, 'window' @pathFocusState = path.join @pathStatesDir, 'focus' if state.isCodewarsWindow @_clearWindowState -> atom.close() return if atom.getCurrentWindow().id is 1 @firstWindowAtLaunch = true fs.access @pathWindowState, (err) => if err then @firstWindowAtLaunch = false checkIfCodewarsWindow = (textEditorFile) => if (path.basename textEditorFile) is OPEN_FILE_KEY @_writeWindowState() # Actually create the view now @createView state mkdirp @pathStatesDir, (err) -> throw err if err # Check if the window has the codewars initial file open disposable = new CompositeDisposable disposable.add atom.workspace.observeTextEditors (editor) -> checkIfCodewarsWindow editor?.getPath() disposable.dispose() @subscriptions = new CompositeDisposable # Register command that toggles this view @subscriptions.add atom.commands.add 'atom-workspace', 'codewars:toggle': => @toggle() createView: (state) -> MainView ?= require './main-view' @mainView = new MainView @path, state.mainViewState @_watchStateFiles() deactivate: -> @_pathStatesWatcher?.close() @_clearWindowState() @subscriptions?.dispose() @mainView?.destroy() serialize: -> isCodewarsWindow: !!@mainView mainViewState: @mainView?.serialize() toggle: -> @_checkWindowState (openNewWindow) => return unless openNewWindow atom.open pathsToOpen: [path.join(@path, OPEN_FILE_KEY)], newWindow: true if @mainView @mainView.activate() else @_touchFocusState() # == Private functions == # _writeWindowState: (cb) -> fs.writeFile @pathWindowState, atom.getCurrentWindow().id, cb _checkWindowState: (callback) -> fs.readFile @pathWindowState, (err, data) => if err or @firstWindowAtLaunch or not data?.toString()?.length @firstWindowAtLaunch = false @_clearWindowState -> callback true else callback false _clearWindowState: (callback) -> fs.unlink @pathWindowState, -> callback?() _touchFocusState: -> fs.writeFile @pathFocusState _watchStateFiles: -> @_pathStatesWatcher = fs.watch @pathStatesDir @_pathStatesWatcher.on 'change', (event, filename) => if filename is 'window' fs.readFile @pathWindowState, (err, data) => if err or (parseInt data.toString()) isnt atom.getCurrentWindow().id @_writeWindowState() if filename is 'focus' @mainView.activate() atom.getCurrentWindow().focus()
[ { "context": " @artist = new Artist fabricate 'artist', name: 'Seth Clark', cta_image: thumb: url: 'http://thumb.jpg'\n ", "end": 384, "score": 0.9997922778129578, "start": 374, "tag": "NAME", "value": "Seth Clark" }, { "context": "should.equal 'Join Artsy to discover new works ...
src/desktop/components/artist_page_cta/test/template.coffee
kanaabe/force
1
_ = require 'underscore' $ = require 'cheerio' benv = require 'benv' jade = require 'jade' { fabricate } = require 'antigravity' Artist = require '../../../models/artist' templates = overlay: jade.compileFile(require.resolve '../templates/overlay.jade') describe 'templates', -> before (done) -> benv.setup => @artist = new Artist fabricate 'artist', name: 'Seth Clark', cta_image: thumb: url: 'http://thumb.jpg' benv.expose sd: AP: 'http://test.test' done() after -> benv.teardown() describe 'when there are null cta artists', -> beforeEach -> @artist.set cta_artists: null @data = _.extend {}, { artist: @artist } it 'renders correctly', -> $template = $(templates.overlay @data) $template.find('.artist-page-cta-overlay__feed__items__row').length.should.equal 1 text = $template.find('.artist-page-cta-overlay__headline').text() text.should.equal 'Join Artsy to discover new works by Seth Clark and more artists you love' it 'renders gdpr checkbox', -> $template = $(templates.overlay @data) $template.find('input[type=checkbox]').length.should.equal 1 describe 'when there are null cta artists', -> beforeEach -> @artist.set cta_artists: [] @data = _.extend {}, { artist: @artist } it 'renders correctly', -> $template = $(templates.overlay @data) $template.find('.artist-page-cta-overlay__feed__items__row').length.should.equal 1 text = $template.find('.artist-page-cta-overlay__headline').text() text.should.equal 'Join Artsy to discover new works by Seth Clark and more artists you love' describe 'when there are some cta artists', -> beforeEach -> @artist.set cta_artists: [{ name: 'Drew Conrad', image: { thumb: { url: 'http://thumb1.jpg' } } }] @data = _.extend {}, { artist: @artist } it 'renders correctly', -> $template = $(templates.overlay @data) $template.find('.artist-page-cta-overlay__feed__items__row').length.should.equal 2 text = $($template.find('.artist-page-cta-overlay__feed__items__row__artist-info')[1]).text() text.should.equal '3 New WorksTodayDrew Conrad'
163240
_ = require 'underscore' $ = require 'cheerio' benv = require 'benv' jade = require 'jade' { fabricate } = require 'antigravity' Artist = require '../../../models/artist' templates = overlay: jade.compileFile(require.resolve '../templates/overlay.jade') describe 'templates', -> before (done) -> benv.setup => @artist = new Artist fabricate 'artist', name: '<NAME>', cta_image: thumb: url: 'http://thumb.jpg' benv.expose sd: AP: 'http://test.test' done() after -> benv.teardown() describe 'when there are null cta artists', -> beforeEach -> @artist.set cta_artists: null @data = _.extend {}, { artist: @artist } it 'renders correctly', -> $template = $(templates.overlay @data) $template.find('.artist-page-cta-overlay__feed__items__row').length.should.equal 1 text = $template.find('.artist-page-cta-overlay__headline').text() text.should.equal 'Join Artsy to discover new works by <NAME> and more artists you love' it 'renders gdpr checkbox', -> $template = $(templates.overlay @data) $template.find('input[type=checkbox]').length.should.equal 1 describe 'when there are null cta artists', -> beforeEach -> @artist.set cta_artists: [] @data = _.extend {}, { artist: @artist } it 'renders correctly', -> $template = $(templates.overlay @data) $template.find('.artist-page-cta-overlay__feed__items__row').length.should.equal 1 text = $template.find('.artist-page-cta-overlay__headline').text() text.should.equal 'Join Artsy to discover new works by <NAME> and more artists you love' describe 'when there are some cta artists', -> beforeEach -> @artist.set cta_artists: [{ name: '<NAME>', image: { thumb: { url: 'http://thumb1.jpg' } } }] @data = _.extend {}, { artist: @artist } it 'renders correctly', -> $template = $(templates.overlay @data) $template.find('.artist-page-cta-overlay__feed__items__row').length.should.equal 2 text = $($template.find('.artist-page-cta-overlay__feed__items__row__artist-info')[1]).text() text.should.equal '3 New WorksToday<NAME>'
true
_ = require 'underscore' $ = require 'cheerio' benv = require 'benv' jade = require 'jade' { fabricate } = require 'antigravity' Artist = require '../../../models/artist' templates = overlay: jade.compileFile(require.resolve '../templates/overlay.jade') describe 'templates', -> before (done) -> benv.setup => @artist = new Artist fabricate 'artist', name: 'PI:NAME:<NAME>END_PI', cta_image: thumb: url: 'http://thumb.jpg' benv.expose sd: AP: 'http://test.test' done() after -> benv.teardown() describe 'when there are null cta artists', -> beforeEach -> @artist.set cta_artists: null @data = _.extend {}, { artist: @artist } it 'renders correctly', -> $template = $(templates.overlay @data) $template.find('.artist-page-cta-overlay__feed__items__row').length.should.equal 1 text = $template.find('.artist-page-cta-overlay__headline').text() text.should.equal 'Join Artsy to discover new works by PI:NAME:<NAME>END_PI and more artists you love' it 'renders gdpr checkbox', -> $template = $(templates.overlay @data) $template.find('input[type=checkbox]').length.should.equal 1 describe 'when there are null cta artists', -> beforeEach -> @artist.set cta_artists: [] @data = _.extend {}, { artist: @artist } it 'renders correctly', -> $template = $(templates.overlay @data) $template.find('.artist-page-cta-overlay__feed__items__row').length.should.equal 1 text = $template.find('.artist-page-cta-overlay__headline').text() text.should.equal 'Join Artsy to discover new works by PI:NAME:<NAME>END_PI and more artists you love' describe 'when there are some cta artists', -> beforeEach -> @artist.set cta_artists: [{ name: 'PI:NAME:<NAME>END_PI', image: { thumb: { url: 'http://thumb1.jpg' } } }] @data = _.extend {}, { artist: @artist } it 'renders correctly', -> $template = $(templates.overlay @data) $template.find('.artist-page-cta-overlay__feed__items__row').length.should.equal 2 text = $($template.find('.artist-page-cta-overlay__feed__items__row__artist-info')[1]).text() text.should.equal '3 New WorksTodayPI:NAME:<NAME>END_PI'
[ { "context": ":text-domain} ),\n\t\t\t\t\t\t'DG' \t\t\t=> esc_html__( 'Diego Garcia', ${3:text-domain} ),\n\t\t\t\t\t\t'DJ' \t\t\t=> esc_html__", "end": 19580, "score": 0.9423100352287292, "start": 19571, "tag": "NAME", "value": "go Garcia" } ]
snippets/customizer.cson
slushman/atom-wp-snippets
29
".text.html.php, .source.php": "WPCustomizerPanel": "prefix": "wpcp" "body": """// ${1:panel_name} Panel $wp_customize->add_panel( '${2:panel_id}', array( 'capability' => 'edgepait_theme_options', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'priority' => 10, 'theme_supports' => '', 'title' => esc_html__( '${1:panel_name}', '${4:text-domain}' ), ) );""" "WPCustomizerSection": "prefix": "wpcs" "body": """// ${1:section_name} Section $wp_customize->add_section( '${2:section_id}', array( 'active_callback' => '${3:callback_function}', 'capability' => 'edit_theme_options', 'description' => esc_html__( '${4:description}', '${5:text-domain}' ), 'panel' => '${1:panel_id}', 'priority' => 10, 'theme_supports' => '', 'title' => esc_html__( '${1:section_name}', '${5:text-domain}' ), ) );""" "WPCustomizerText": "prefix": "wpct" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'text' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerURL": "prefix": "wpcu" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'url' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerEmail": "prefix": "wpce" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'sanitize_email', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'email' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerDate": "prefix": "wpcd" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'date' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerCheckbox": "prefix": "wpcc" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'absint', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'checkbox' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerPassword": "prefix": "wpcpw" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'password' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerRadios": "prefix": "wpcr" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '${3:choice1_id}', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( '${3:choice1_id}' => esc_html__( '${4:choice1_name}', '${5:text-domain}' ), ), 'description' => esc_html__( '${6:description}', '${5:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${5:text-domain}' ), 'priority' => 10, 'section' => '${7:section_id}', 'settings' => '${2:field_id}', 'type' => 'radio' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerSelect": "prefix": "wpcsel" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '${3:choice1_id}', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( '${3:choice1_id}' => esc_html__( '${4:choice1_name}', '${5:text-domain}' ), ), 'description' => esc_html__( '${6:description}', '${5:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${5:text-domain}' ), 'priority' => 10, 'section' => '${7:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerTextArea": "prefix": "wpcta" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_textarea', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'textarea' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerRange": "prefix": "wpcrange" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'intval', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${6:description}', '${5:text-domain}' ), 'input_attrs' => array( 'class' => 'range-field', 'max' => ${7:max_value}, 'min' => ${8:min_value}, 'step' => ${9:step_value}, 'style' => 'color: #020202' ), 'label' => esc_html__( '${1:field_name}', '${5:text-domain}' ), 'priority' => 10, 'section' => '${10:section_id}', 'settings' => '${2:field_id}', 'type' => 'range' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerPageSelect": "prefix": "wpcpage" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'dropdown-pages' ) ); $wp_customize->get_setting( 'dropdown-pages' )->transport = 'postMessage';""" "WPCustomizerColorChoose": "prefix": "wpccolor" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '#ffffff', 'sanitize_callback' => 'sanitize_hex_color', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerFileUpload": "prefix": "wpcfile" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) );""" "WPCustomizerImageUpload": "prefix": "wpcimg" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) );""" "WPCustomizerMediaUpload": "prefix": "wpcmedia" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Media_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) );""" "WPCustomizerCroppedImage": "prefix": "wpccrop" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'flex_height' => '${5:flex_height_true_or_false}', 'flex_width' => '${6:flex_width_true_or_false}', 'height' => '${7:height_in_pixels}', 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${8:section_id}', 'settings' => '${2:field_id}', 'width' => '${9:width_in_pixels}' ) ) );""" "WPCustomizerCountriesList": "prefix": "wpccountry" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => 'US, 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'AF' => esc_html__( 'Afghanistan (‫افغانستان‬‎)', ${3:text-domain} ), 'AX' => esc_html__( 'Åland Islands (Åland)', ${3:text-domain} ), 'AL' => esc_html__( 'Albania (Shqipëri)', ${3:text-domain} ), 'DZ' => esc_html__( 'Algeria (‫الجزائر‬‎)', ${3:text-domain} ), 'AS' => esc_html__( 'American Samoa', ${3:text-domain} ), 'AD' => esc_html__( 'Andorra', ${3:text-domain} ), 'AO' => esc_html__( 'Angola', ${3:text-domain} ), 'AI' => esc_html__( 'Anguilla', ${3:text-domain} ), 'AQ' => esc_html__( 'Antarctica', ${3:text-domain} ), 'AG' => esc_html__( 'Antigua and Barbuda', ${3:text-domain} ), 'AR' => esc_html__( 'Argentina', ${3:text-domain} ), 'AM' => esc_html__( 'Armenia (Հայաստան)', ${3:text-domain} ), 'AW' => esc_html__( 'Aruba', ${3:text-domain} ), 'AC' => esc_html__( 'Ascension Island', ${3:text-domain} ), 'AU' => esc_html__( 'Australia', ${3:text-domain} ), 'AT' => esc_html__( 'Austria (Österreich)', ${3:text-domain} ), 'AZ' => esc_html__( 'Azerbaijan (Azərbaycan)', ${3:text-domain} ), 'BS' => esc_html__( 'Bahamas', ${3:text-domain} ), 'BH' => esc_html__( 'Bahrain (‫البحرين‬‎)', ${3:text-domain} ), 'BD' => esc_html__( 'Bangladesh (বাংলাদেশ)', ${3:text-domain} ), 'BB' => esc_html__( 'Barbados', ${3:text-domain} ), 'BY' => esc_html__( 'Belarus (Беларусь)', ${3:text-domain} ), 'BE' => esc_html__( 'Belgium (België)', ${3:text-domain} ), 'BZ' => esc_html__( 'Belize', ${3:text-domain} ), 'BJ' => esc_html__( 'Benin (Bénin)', ${3:text-domain} ), 'BM' => esc_html__( 'Bermuda', ${3:text-domain} ), 'BT' => esc_html__( 'Bhutan (འབྲུག)', ${3:text-domain} ), 'BO' => esc_html__( 'Bolivia', ${3:text-domain} ), 'BA' => esc_html__( 'Bosnia and Herzegovina (Босна и Херцеговина)', ${3:text-domain} ), 'BW' => esc_html__( 'Botswana', ${3:text-domain} ), 'BV' => esc_html__( 'Bouvet Island', ${3:text-domain} ), 'BR' => esc_html__( 'Brazil (Brasil)', ${3:text-domain} ), 'IO' => esc_html__( 'British Indian Ocean Territory', ${3:text-domain} ), 'VG' => esc_html__( 'British Virgin Islands', ${3:text-domain} ), 'BN' => esc_html__( 'Brunei', ${3:text-domain} ), 'BG' => esc_html__( 'Bulgaria (България)', ${3:text-domain} ), 'BF' => esc_html__( 'Burkina Faso', ${3:text-domain} ), 'BI' => esc_html__( 'Burundi (Uburundi)', ${3:text-domain} ), 'KH' => esc_html__( 'Cambodia (កម្ពុជា)', ${3:text-domain} ), 'CM' => esc_html__( 'Cameroon (Cameroun)', ${3:text-domain} ), 'CA' => esc_html__( 'Canada', ${3:text-domain} ), 'IC' => esc_html__( 'Canary Islands (islas Canarias)', ${3:text-domain} ), 'CV' => esc_html__( 'Cape Verde (Kabu Verdi)', ${3:text-domain} ), 'BQ' => esc_html__( 'Caribbean Netherlands', ${3:text-domain} ), 'KY' => esc_html__( 'Cayman Islands', ${3:text-domain} ), 'CF' => esc_html__( 'Central African Republic (République centrafricaine)', ${3:text-domain} ), 'EA' => esc_html__( 'Ceuta and Melilla (Ceuta y Melilla)', ${3:text-domain} ), 'TD' => esc_html__( 'Chad (Tchad)', ${3:text-domain} ), 'CL' => esc_html__( 'Chile', ${3:text-domain} ), 'CN' => esc_html__( 'China (中国)', ${3:text-domain} ), 'CX' => esc_html__( 'Christmas Island', ${3:text-domain} ), 'CP' => esc_html__( 'Clipperton Island', ${3:text-domain} ), 'CC' => esc_html__( 'Cocos (Keeling) Islands (Kepulauan Cocos (Keeling))', ${3:text-domain} ), 'CO' => esc_html__( 'Colombia', ${3:text-domain} ), 'KM' => esc_html__( 'Comoros (‫جزر القمر‬‎)', ${3:text-domain} ), 'CD' => esc_html__( 'Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)', ${3:text-domain} ), 'CG' => esc_html__( 'Congo (Republic) (Congo-Brazzaville)', ${3:text-domain} ), 'CK' => esc_html__( 'Cook Islands', ${3:text-domain} ), 'CR' => esc_html__( 'Costa Rica', ${3:text-domain} ), 'CI' => esc_html__( 'Côte d’Ivoire', ${3:text-domain} ), 'HR' => esc_html__( 'Croatia (Hrvatska)', ${3:text-domain} ), 'CU' => esc_html__( 'Cuba', ${3:text-domain} ), 'CW' => esc_html__( 'Curaçao', ${3:text-domain} ), 'CY' => esc_html__( 'Cyprus (Κύπρος)', ${3:text-domain} ), 'CZ' => esc_html__( 'Czech Republic (Česká republika)', ${3:text-domain} ), 'DK' => esc_html__( 'Denmark (Danmark)', ${3:text-domain} ), 'DG' => esc_html__( 'Diego Garcia', ${3:text-domain} ), 'DJ' => esc_html__( 'Djibouti', ${3:text-domain} ), 'DM' => esc_html__( 'Dominica', ${3:text-domain} ), 'DO' => esc_html__( 'Dominican Republic (República Dominicana)', ${3:text-domain} ), 'EC' => esc_html__( 'Ecuador', ${3:text-domain} ), 'EG' => esc_html__( 'Egypt (‫مصر‬‎)', ${3:text-domain} ), 'SV' => esc_html__( 'El Salvador', ${3:text-domain} ), 'GQ' => esc_html__( 'Equatorial Guinea (Guinea Ecuatorial)', ${3:text-domain} ), 'ER' => esc_html__( 'Eritrea', ${3:text-domain} ), 'EE' => esc_html__( 'Estonia (Eesti)', ${3:text-domain} ), 'ET' => esc_html__( 'Ethiopia', ${3:text-domain} ), 'FK' => esc_html__( 'Falkland Islands (Islas Malvinas)', ${3:text-domain} ), 'FO' => esc_html__( 'Faroe Islands (Føroyar)', ${3:text-domain} ), 'FJ' => esc_html__( 'Fiji', ${3:text-domain} ), 'FI' => esc_html__( 'Finland (Suomi)', ${3:text-domain} ), 'FR' => esc_html__( 'France', ${3:text-domain} ), 'GF' => esc_html__( 'French Guiana (Guyane française)', ${3:text-domain} ), 'PF' => esc_html__( 'French Polynesia (Polynésie française)', ${3:text-domain} ), 'TF' => esc_html__( 'French Southern Territories (Terres australes françaises)', ${3:text-domain} ), 'GA' => esc_html__( 'Gabon', ${3:text-domain} ), 'GM' => esc_html__( 'Gambia', ${3:text-domain} ), 'GE' => esc_html__( 'Georgia (საქართველო)', ${3:text-domain} ), 'DE' => esc_html__( 'Germany (Deutschland)', ${3:text-domain} ), 'GH' => esc_html__( 'Ghana (Gaana)', ${3:text-domain} ), 'GI' => esc_html__( 'Gibraltar', ${3:text-domain} ), 'GR' => esc_html__( 'Greece (Ελλάδα)', ${3:text-domain} ), 'GL' => esc_html__( 'Greenland (Kalaallit Nunaat)', ${3:text-domain} ), 'GD' => esc_html__( 'Grenada', ${3:text-domain} ), 'GP' => esc_html__( 'Guadeloupe', ${3:text-domain} ), 'GU' => esc_html__( 'Guam', ${3:text-domain} ), 'GT' => esc_html__( 'Guatemala', ${3:text-domain} ), 'GG' => esc_html__( 'Guernsey', ${3:text-domain} ), 'GN' => esc_html__( 'Guinea (Guinée)', ${3:text-domain} ), 'GW' => esc_html__( 'Guinea-Bissau (Guiné Bissau)', ${3:text-domain} ), 'GY' => esc_html__( 'Guyana', ${3:text-domain} ), 'HT' => esc_html__( 'Haiti', ${3:text-domain} ), 'HM' => esc_html__( 'Heard & McDonald Islands', ${3:text-domain} ), 'HN' => esc_html__( 'Honduras', ${3:text-domain} ), 'HK' => esc_html__( 'Hong Kong (香港)', ${3:text-domain} ), 'HU' => esc_html__( 'Hungary (Magyarország)', ${3:text-domain} ), 'IS' => esc_html__( 'Iceland (Ísland)', ${3:text-domain} ), 'IN' => esc_html__( 'India (भारत)', ${3:text-domain} ), 'ID' => esc_html__( 'Indonesia', ${3:text-domain} ), 'IR' => esc_html__( 'Iran (‫ایران‬‎)', ${3:text-domain} ), 'IQ' => esc_html__( 'Iraq (‫العراق‬‎)', ${3:text-domain} ), 'IE' => esc_html__( 'Ireland', ${3:text-domain} ), 'IM' => esc_html__( 'Isle of Man', ${3:text-domain} ), 'IL' => esc_html__( 'Israel (‫ישראל‬‎)', ${3:text-domain} ), 'IT' => esc_html__( 'Italy (Italia)', ${3:text-domain} ), 'JM' => esc_html__( 'Jamaica', ${3:text-domain} ), 'JP' => esc_html__( 'Japan (日本)', ${3:text-domain} ), 'JE' => esc_html__( 'Jersey', ${3:text-domain} ), 'JO' => esc_html__( 'Jordan (‫الأردن‬‎)', ${3:text-domain} ), 'KZ' => esc_html__( 'Kazakhstan (Казахстан)', ${3:text-domain} ), 'KE' => esc_html__( 'Kenya', ${3:text-domain} ), 'KI' => esc_html__( 'Kiribati', ${3:text-domain} ), 'XK' => esc_html__( 'Kosovo (Kosovë)', ${3:text-domain} ), 'KW' => esc_html__( 'Kuwait (‫الكويت‬‎)', ${3:text-domain} ), 'KG' => esc_html__( 'Kyrgyzstan (Кыргызстан)', ${3:text-domain} ), 'LA' => esc_html__( 'Laos (ລາວ)', ${3:text-domain} ), 'LV' => esc_html__( 'Latvia (Latvija)', ${3:text-domain} ), 'LB' => esc_html__( 'Lebanon (‫لبنان‬‎)', ${3:text-domain} ), 'LS' => esc_html__( 'Lesotho', ${3:text-domain} ), 'LR' => esc_html__( 'Liberia', ${3:text-domain} ), 'LY' => esc_html__( 'Libya (‫ليبيا‬‎)', ${3:text-domain} ), 'LI' => esc_html__( 'Liechtenstein', ${3:text-domain} ), 'LT' => esc_html__( 'Lithuania (Lietuva)', ${3:text-domain} ), 'LU' => esc_html__( 'Luxembourg', ${3:text-domain} ), 'MO' => esc_html__( 'Macau (澳門)', ${3:text-domain} ), 'MK' => esc_html__( 'Macedonia (FYROM) (Македонија)', ${3:text-domain} ), 'MG' => esc_html__( 'Madagascar (Madagasikara)', ${3:text-domain} ), 'MW' => esc_html__( 'Malawi', ${3:text-domain} ), 'MY' => esc_html__( 'Malaysia', ${3:text-domain} ), 'MV' => esc_html__( 'Maldives', ${3:text-domain} ), 'ML' => esc_html__( 'Mali', ${3:text-domain} ), 'MT' => esc_html__( 'Malta', ${3:text-domain} ), 'MH' => esc_html__( 'Marshall Islands', ${3:text-domain} ), 'MQ' => esc_html__( 'Martinique', ${3:text-domain} ), 'MR' => esc_html__( 'Mauritania (‫موريتانيا‬‎)', ${3:text-domain} ), 'MU' => esc_html__( 'Mauritius (Moris)', ${3:text-domain} ), 'YT' => esc_html__( 'Mayotte', ${3:text-domain} ), 'MX' => esc_html__( 'Mexico (México)', ${3:text-domain} ), 'FM' => esc_html__( 'Micronesia', ${3:text-domain} ), 'MD' => esc_html__( 'Moldova (Republica Moldova)', ${3:text-domain} ), 'MC' => esc_html__( 'Monaco', ${3:text-domain} ), 'MN' => esc_html__( 'Mongolia (Монгол)', ${3:text-domain} ), 'ME' => esc_html__( 'Montenegro (Crna Gora)', ${3:text-domain} ), 'MS' => esc_html__( 'Montserrat', ${3:text-domain} ), 'MA' => esc_html__( 'Morocco (‫المغرب‬‎)', ${3:text-domain} ), 'MZ' => esc_html__( 'Mozambique (Moçambique)', ${3:text-domain} ), 'MM' => esc_html__( 'Myanmar (Burma) (မြန်မာ)', ${3:text-domain} ), 'NA' => esc_html__( 'Namibia (Namibië)', ${3:text-domain} ), 'NR' => esc_html__( 'Nauru', ${3:text-domain} ), 'NP' => esc_html__( 'Nepal (नेपाल)', ${3:text-domain} ), 'NL' => esc_html__( 'Netherlands (Nederland)', ${3:text-domain} ), 'NC' => esc_html__( 'New Caledonia (Nouvelle-Calédonie)', ${3:text-domain} ), 'NZ' => esc_html__( 'New Zealand', ${3:text-domain} ), 'NI' => esc_html__( 'Nicaragua', ${3:text-domain} ), 'NE' => esc_html__( 'Niger (Nijar)', ${3:text-domain} ), 'NG' => esc_html__( 'Nigeria', ${3:text-domain} ), 'NU' => esc_html__( 'Niue', ${3:text-domain} ), 'NF' => esc_html__( 'Norfolk Island', ${3:text-domain} ), 'MP' => esc_html__( 'Northern Mariana Islands', ${3:text-domain} ), 'KP' => esc_html__( 'North Korea (조선 민주주의 인민 공화국)', ${3:text-domain} ), 'NO' => esc_html__( 'Norway (Norge)', ${3:text-domain} ), 'OM' => esc_html__( 'Oman (‫عُمان‬‎)', ${3:text-domain} ), 'PK' => esc_html__( 'Pakistan (‫پاکستان‬‎)', ${3:text-domain} ), 'PW' => esc_html__( 'Palau', ${3:text-domain} ), 'PS' => esc_html__( 'Palestine (‫فلسطين‬‎)', ${3:text-domain} ), 'PA' => esc_html__( 'Panama (Panamá)', ${3:text-domain} ), 'PG' => esc_html__( 'Papua New Guinea', ${3:text-domain} ), 'PY' => esc_html__( 'Paraguay', ${3:text-domain} ), 'PE' => esc_html__( 'Peru (Perú)', ${3:text-domain} ), 'PH' => esc_html__( 'Philippines', ${3:text-domain} ), 'PN' => esc_html__( 'Pitcairn Islands', ${3:text-domain} ), 'PL' => esc_html__( 'Poland (Polska)', ${3:text-domain} ), 'PT' => esc_html__( 'Portugal', ${3:text-domain} ), 'PR' => esc_html__( 'Puerto Rico', ${3:text-domain} ), 'QA' => esc_html__( 'Qatar (‫قطر‬‎)', ${3:text-domain} ), 'RE' => esc_html__( 'Réunion (La Réunion)', ${3:text-domain} ), 'RO' => esc_html__( 'Romania (România)', ${3:text-domain} ), 'RU' => esc_html__( 'Russia (Россия)', ${3:text-domain} ), 'RW' => esc_html__( 'Rwanda', ${3:text-domain} ), 'BL' => esc_html__( 'Saint Barthélemy (Saint-Barthélemy)', ${3:text-domain} ), 'SH' => esc_html__( 'Saint Helena', ${3:text-domain} ), 'KN' => esc_html__( 'Saint Kitts and Nevis', ${3:text-domain} ), 'LC' => esc_html__( 'Saint Lucia', ${3:text-domain} ), 'MF' => esc_html__( 'Saint Martin (Saint-Martin (partie française))', ${3:text-domain} ), 'PM' => esc_html__( 'Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)', ${3:text-domain} ), 'WS' => esc_html__( 'Samoa', ${3:text-domain} ), 'SM' => esc_html__( 'San Marino', ${3:text-domain} ), 'ST' => esc_html__( 'São Tomé and Príncipe (São Tomé e Príncipe)', ${3:text-domain} ), 'SA' => esc_html__( 'Saudi Arabia (‫المملكة العربية السعودية‬‎)', ${3:text-domain} ), 'SN' => esc_html__( 'Senegal (Sénégal)', ${3:text-domain} ), 'RS' => esc_html__( 'Serbia (Србија)', ${3:text-domain} ), 'SC' => esc_html__( 'Seychelles', ${3:text-domain} ), 'SL' => esc_html__( 'Sierra Leone', ${3:text-domain} ), 'SG' => esc_html__( 'Singapore', ${3:text-domain} ), 'SX' => esc_html__( 'Sint Maarten', ${3:text-domain} ), 'SK' => esc_html__( 'Slovakia (Slovensko)', ${3:text-domain} ), 'SI' => esc_html__( 'Slovenia (Slovenija)', ${3:text-domain} ), 'SB' => esc_html__( 'Solomon Islands', ${3:text-domain} ), 'SO' => esc_html__( 'Somalia (Soomaaliya)', ${3:text-domain} ), 'ZA' => esc_html__( 'South Africa', ${3:text-domain} ), 'GS' => esc_html__( 'South Georgia & South Sandwich Islands', ${3:text-domain} ), 'KR' => esc_html__( 'South Korea (대한민국)', ${3:text-domain} ), 'SS' => esc_html__( 'South Sudan (‫جنوب السودان‬‎)', ${3:text-domain} ), 'ES' => esc_html__( 'Spain (España)', ${3:text-domain} ), 'LK' => esc_html__( 'Sri Lanka (ශ්‍රී ලංකාව)', ${3:text-domain} ), 'VC' => esc_html__( 'St. Vincent & Grenadines', ${3:text-domain} ), 'SD' => esc_html__( 'Sudan (‫السودان‬‎)', ${3:text-domain} ), 'SR' => esc_html__( 'Suriname', ${3:text-domain} ), 'SJ' => esc_html__( 'Svalbard and Jan Mayen (Svalbard og Jan Mayen)', ${3:text-domain} ), 'SZ' => esc_html__( 'Swaziland', ${3:text-domain} ), 'SE' => esc_html__( 'Sweden (Sverige)', ${3:text-domain} ), 'CH' => esc_html__( 'Switzerland (Schweiz)', ${3:text-domain} ), 'SY' => esc_html__( 'Syria (‫سوريا‬‎)', ${3:text-domain} ), 'TW' => esc_html__( 'Taiwan (台灣)', ${3:text-domain} ), 'TJ' => esc_html__( 'Tajikistan', ${3:text-domain} ), 'TZ' => esc_html__( 'Tanzania', ${3:text-domain} ), 'TH' => esc_html__( 'Thailand (ไทย)', ${3:text-domain} ), 'TL' => esc_html__( 'Timor-Leste', ${3:text-domain} ), 'TG' => esc_html__( 'Togo', ${3:text-domain} ), 'TK' => esc_html__( 'Tokelau', ${3:text-domain} ), 'TO' => esc_html__( 'Tonga', ${3:text-domain} ), 'TT' => esc_html__( 'Trinidad and Tobago', ${3:text-domain} ), 'TA' => esc_html__( 'Tristan da Cunha', ${3:text-domain} ), 'TN' => esc_html__( 'Tunisia (‫تونس‬‎)', ${3:text-domain} ), 'TR' => esc_html__( 'Turkey (Türkiye)', ${3:text-domain} ), 'TM' => esc_html__( 'Turkmenistan', ${3:text-domain} ), 'TC' => esc_html__( 'Turks and Caicos Islands', ${3:text-domain} ), 'TV' => esc_html__( 'Tuvalu', ${3:text-domain} ), 'UM' => esc_html__( 'U.S. Outlying Islands', ${3:text-domain} ), 'VI' => esc_html__( 'U.S. Virgin Islands', ${3:text-domain} ), 'UG' => esc_html__( 'Uganda', ${3:text-domain} ), 'UA' => esc_html__( 'Ukraine (Україна)', ${3:text-domain} ), 'AE' => esc_html__( 'United Arab Emirates (‫الإمارات العربية المتحدة‬‎)', ${3:text-domain} ), 'GB' => esc_html__( 'United Kingdom', ${3:text-domain} ), 'US' => esc_html__( 'United States', ${3:text-domain} ), 'UY' => esc_html__( 'Uruguay', ${3:text-domain} ), 'UZ' => esc_html__( 'Uzbekistan (Oʻzbekiston)', ${3:text-domain} ), 'VU' => esc_html__( 'Vanuatu', ${3:text-domain} ), 'VA' => esc_html__( 'Vatican City (Città del Vaticano)', ${3:text-domain} ), 'VE' => esc_html__( 'Venezuela', ${3:text-domain} ), 'VN' => esc_html__( 'Vietnam (Việt Nam)', ${3:text-domain} ), 'WF' => esc_html__( 'Wallis and Futuna', ${3:text-domain} ), 'EH' => esc_html__( 'Western Sahara (‫الصحراء الغربية‬‎)', ${3:text-domain} ), 'YE' => esc_html__( 'Yemen (‫اليمن‬‎)', ${3:text-domain} ), 'ZM' => esc_html__( 'Zambia', ${3:text-domain} ), 'ZW' => esc_html__( 'Zimbabwe', ${3:text-domain} ), ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerUSStates": "prefix": "wpcus" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'AL' => esc_html__( 'Alabama', ${3:text-domain} ), 'AK' => esc_html__( 'Alaska', ${3:text-domain} ), 'AZ' => esc_html__( 'Arizona', ${3:text-domain} ), 'AR' => esc_html__( 'Arkansas', ${3:text-domain} ), 'CA' => esc_html__( 'California', ${3:text-domain} ), 'CO' => esc_html__( 'Colorado', ${3:text-domain} ), 'CT' => esc_html__( 'Connecticut', ${3:text-domain} ), 'DE' => esc_html__( 'Delaware', ${3:text-domain} ), 'DC' => esc_html__( 'District of Columbia', ${3:text-domain} ), 'FL' => esc_html__( 'Florida', ${3:text-domain} ), 'GA' => esc_html__( 'Georgia', ${3:text-domain} ), 'HI' => esc_html__( 'Hawaii', ${3:text-domain} ), 'ID' => esc_html__( 'Idaho', ${3:text-domain} ), 'IL' => esc_html__( 'Illinois', ${3:text-domain} ), 'IN' => esc_html__( 'Indiana', ${3:text-domain} ), 'IA' => esc_html__( 'Iowa', ${3:text-domain} ), 'KS' => esc_html__( 'Kansas', ${3:text-domain} ), 'KY' => esc_html__( 'Kentucky', ${3:text-domain} ), 'LA' => esc_html__( 'Louisiana', ${3:text-domain} ), 'ME' => esc_html__( 'Maine', ${3:text-domain} ), 'MD' => esc_html__( 'Maryland', ${3:text-domain} ), 'MA' => esc_html__( 'Massachusetts', ${3:text-domain} ), 'MI' => esc_html__( 'Michigan', ${3:text-domain} ), 'MN' => esc_html__( 'Minnesota', ${3:text-domain} ), 'MS' => esc_html__( 'Mississippi', ${3:text-domain} ), 'MO' => esc_html__( 'Missouri', ${3:text-domain} ), 'MT' => esc_html__( 'Montana', ${3:text-domain} ), 'NE' => esc_html__( 'Nebraska', ${3:text-domain} ), 'NV' => esc_html__( 'Nevada', ${3:text-domain} ), 'NH' => esc_html__( 'New Hampshire', ${3:text-domain} ), 'NJ' => esc_html__( 'New Jersey', ${3:text-domain} ), 'NM' => esc_html__( 'New Mexico', ${3:text-domain} ), 'NY' => esc_html__( 'New York', ${3:text-domain} ), 'NC' => esc_html__( 'North Carolina', ${3:text-domain} ), 'ND' => esc_html__( 'North Dakota', ${3:text-domain} ), 'OH' => esc_html__( 'Ohio', ${3:text-domain} ), 'OK' => esc_html__( 'Oklahoma', ${3:text-domain} ), 'OR' => esc_html__( 'Oregon', ${3:text-domain} ), 'PA' => esc_html__( 'Pennsylvania', ${3:text-domain} ), 'RI' => esc_html__( 'Rhode Island', ${3:text-domain} ), 'SC' => esc_html__( 'South Carolina', ${3:text-domain} ), 'SD' => esc_html__( 'South Dakota', ${3:text-domain} ), 'TN' => esc_html__( 'Tennessee', ${3:text-domain} ), 'TX' => esc_html__( 'Texas', ${3:text-domain} ), 'UT' => esc_html__( 'Utah', ${3:text-domain} ), 'VT' => esc_html__( 'Vermont', ${3:text-domain} ), 'VA' => esc_html__( 'Virginia', ${3:text-domain} ), 'WA' => esc_html__( 'Washington', ${3:text-domain} ), 'WV' => esc_html__( 'West Virginia', ${3:text-domain} ), 'WI' => esc_html__( 'Wisconsin', ${3:text-domain} ), 'WY' => esc_html__( 'Wyoming', ${3:text-domain} ), 'AS' => esc_html__( 'American Samoa', ${3:text-domain} ), 'AA' => esc_html__( 'Armed Forces America (except Canada)', ${3:text-domain} ), 'AE' => esc_html__( 'Armed Forces Africa/Canada/Europe/Middle East', ${3:text-domain} ), 'AP' => esc_html__( 'Armed Forces Pacific', ${3:text-domain} ), 'FM' => esc_html__( 'Federated States of Micronesia', ${3:text-domain} ), 'GU' => esc_html__( 'Guam', ${3:text-domain} ), 'MH' => esc_html__( 'Marshall Islands', ${3:text-domain} ), 'MP' => esc_html__( 'Northern Mariana Islands', ${3:text-domain} ), 'PR' => esc_html__( 'Puerto Rico', ${3:text-domain} ), 'PW' => esc_html__( 'Palau', ${3:text-domain} ), 'VI' => esc_html__( 'Virgin Islands', ${3:text-domain} ) ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerCanadianStates": "prefix": "wpccanada" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'AB' => esc_html__( 'Alberta', '${3:text-domain}' ), 'BC' => esc_html__( 'British Columbia', '${3:text-domain}' ), 'MB' => esc_html__( 'Manitoba', '${3:text-domain}' ), 'NB' => esc_html__( 'New Brunswick', '${3:text-domain}' ), 'NL' => esc_html__( 'Newfoundland and Labrador', '${3:text-domain}' ), 'NT' => esc_html__( 'Northwest Territories', '${3:text-domain}' ), 'NS' => esc_html__( 'Nova Scotia', '${3:text-domain}' ), 'NU' => esc_html__( 'Nunavut', '${3:text-domain}' ), 'ON' => esc_html__( 'Ontario', '${3:text-domain}' ), 'PE' => esc_html__( 'Prince Edward Island', '${3:text-domain}' ), 'QC' => esc_html__( 'Quebec', '${3:text-domain}' ), 'SK' => esc_html__( 'Saskatchewan', '${3:text-domain}' ), 'YT' => esc_html__( 'Yukon', '${3:text-domain}' ) ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerAustralianStates": "prefix": "wpcaus" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'ACT' => esc_html__( 'Australian Capital Territory', '${3:text-domain}' ), 'NSW' => esc_html__( 'New South Wales', '${3:text-domain}' ), 'NT' => esc_html__( 'Northern Territory', '${3:text-domain}' ), 'QLD' => esc_html__( 'Queensland', '${3:text-domain}' ), 'SA' => esc_html__( 'South Australia', '${3:text-domain}' ), 'TAS' => esc_html__( 'Tasmania', '${3:text-domain}' ), 'VIC' => esc_html__( 'Victoria', '${3:text-domain}' ), 'WA' => esc_html__( 'Western Australia', '${3:text-domain}' ) ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" ".source.js": "WPCustomizerBasicJS": "prefix": "wpcjs" "body": """// ${1:setting_name}. wp.customize( '${2:setting_id}', function( value ) { value.bind( function( to ) { $( '${3:id_or_class}' ).text( to ); } ); } );"""
214912
".text.html.php, .source.php": "WPCustomizerPanel": "prefix": "wpcp" "body": """// ${1:panel_name} Panel $wp_customize->add_panel( '${2:panel_id}', array( 'capability' => 'edgepait_theme_options', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'priority' => 10, 'theme_supports' => '', 'title' => esc_html__( '${1:panel_name}', '${4:text-domain}' ), ) );""" "WPCustomizerSection": "prefix": "wpcs" "body": """// ${1:section_name} Section $wp_customize->add_section( '${2:section_id}', array( 'active_callback' => '${3:callback_function}', 'capability' => 'edit_theme_options', 'description' => esc_html__( '${4:description}', '${5:text-domain}' ), 'panel' => '${1:panel_id}', 'priority' => 10, 'theme_supports' => '', 'title' => esc_html__( '${1:section_name}', '${5:text-domain}' ), ) );""" "WPCustomizerText": "prefix": "wpct" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'text' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerURL": "prefix": "wpcu" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'url' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerEmail": "prefix": "wpce" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'sanitize_email', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'email' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerDate": "prefix": "wpcd" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'date' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerCheckbox": "prefix": "wpcc" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'absint', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'checkbox' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerPassword": "prefix": "wpcpw" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'password' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerRadios": "prefix": "wpcr" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '${3:choice1_id}', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( '${3:choice1_id}' => esc_html__( '${4:choice1_name}', '${5:text-domain}' ), ), 'description' => esc_html__( '${6:description}', '${5:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${5:text-domain}' ), 'priority' => 10, 'section' => '${7:section_id}', 'settings' => '${2:field_id}', 'type' => 'radio' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerSelect": "prefix": "wpcsel" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '${3:choice1_id}', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( '${3:choice1_id}' => esc_html__( '${4:choice1_name}', '${5:text-domain}' ), ), 'description' => esc_html__( '${6:description}', '${5:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${5:text-domain}' ), 'priority' => 10, 'section' => '${7:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerTextArea": "prefix": "wpcta" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_textarea', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'textarea' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerRange": "prefix": "wpcrange" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'intval', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${6:description}', '${5:text-domain}' ), 'input_attrs' => array( 'class' => 'range-field', 'max' => ${7:max_value}, 'min' => ${8:min_value}, 'step' => ${9:step_value}, 'style' => 'color: #020202' ), 'label' => esc_html__( '${1:field_name}', '${5:text-domain}' ), 'priority' => 10, 'section' => '${10:section_id}', 'settings' => '${2:field_id}', 'type' => 'range' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerPageSelect": "prefix": "wpcpage" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'dropdown-pages' ) ); $wp_customize->get_setting( 'dropdown-pages' )->transport = 'postMessage';""" "WPCustomizerColorChoose": "prefix": "wpccolor" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '#ffffff', 'sanitize_callback' => 'sanitize_hex_color', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerFileUpload": "prefix": "wpcfile" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) );""" "WPCustomizerImageUpload": "prefix": "wpcimg" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) );""" "WPCustomizerMediaUpload": "prefix": "wpcmedia" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Media_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) );""" "WPCustomizerCroppedImage": "prefix": "wpccrop" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'flex_height' => '${5:flex_height_true_or_false}', 'flex_width' => '${6:flex_width_true_or_false}', 'height' => '${7:height_in_pixels}', 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${8:section_id}', 'settings' => '${2:field_id}', 'width' => '${9:width_in_pixels}' ) ) );""" "WPCustomizerCountriesList": "prefix": "wpccountry" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => 'US, 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'AF' => esc_html__( 'Afghanistan (‫افغانستان‬‎)', ${3:text-domain} ), 'AX' => esc_html__( 'Åland Islands (Åland)', ${3:text-domain} ), 'AL' => esc_html__( 'Albania (Shqipëri)', ${3:text-domain} ), 'DZ' => esc_html__( 'Algeria (‫الجزائر‬‎)', ${3:text-domain} ), 'AS' => esc_html__( 'American Samoa', ${3:text-domain} ), 'AD' => esc_html__( 'Andorra', ${3:text-domain} ), 'AO' => esc_html__( 'Angola', ${3:text-domain} ), 'AI' => esc_html__( 'Anguilla', ${3:text-domain} ), 'AQ' => esc_html__( 'Antarctica', ${3:text-domain} ), 'AG' => esc_html__( 'Antigua and Barbuda', ${3:text-domain} ), 'AR' => esc_html__( 'Argentina', ${3:text-domain} ), 'AM' => esc_html__( 'Armenia (Հայաստան)', ${3:text-domain} ), 'AW' => esc_html__( 'Aruba', ${3:text-domain} ), 'AC' => esc_html__( 'Ascension Island', ${3:text-domain} ), 'AU' => esc_html__( 'Australia', ${3:text-domain} ), 'AT' => esc_html__( 'Austria (Österreich)', ${3:text-domain} ), 'AZ' => esc_html__( 'Azerbaijan (Azərbaycan)', ${3:text-domain} ), 'BS' => esc_html__( 'Bahamas', ${3:text-domain} ), 'BH' => esc_html__( 'Bahrain (‫البحرين‬‎)', ${3:text-domain} ), 'BD' => esc_html__( 'Bangladesh (বাংলাদেশ)', ${3:text-domain} ), 'BB' => esc_html__( 'Barbados', ${3:text-domain} ), 'BY' => esc_html__( 'Belarus (Беларусь)', ${3:text-domain} ), 'BE' => esc_html__( 'Belgium (België)', ${3:text-domain} ), 'BZ' => esc_html__( 'Belize', ${3:text-domain} ), 'BJ' => esc_html__( 'Benin (Bénin)', ${3:text-domain} ), 'BM' => esc_html__( 'Bermuda', ${3:text-domain} ), 'BT' => esc_html__( 'Bhutan (འབྲུག)', ${3:text-domain} ), 'BO' => esc_html__( 'Bolivia', ${3:text-domain} ), 'BA' => esc_html__( 'Bosnia and Herzegovina (Босна и Херцеговина)', ${3:text-domain} ), 'BW' => esc_html__( 'Botswana', ${3:text-domain} ), 'BV' => esc_html__( 'Bouvet Island', ${3:text-domain} ), 'BR' => esc_html__( 'Brazil (Brasil)', ${3:text-domain} ), 'IO' => esc_html__( 'British Indian Ocean Territory', ${3:text-domain} ), 'VG' => esc_html__( 'British Virgin Islands', ${3:text-domain} ), 'BN' => esc_html__( 'Brunei', ${3:text-domain} ), 'BG' => esc_html__( 'Bulgaria (България)', ${3:text-domain} ), 'BF' => esc_html__( 'Burkina Faso', ${3:text-domain} ), 'BI' => esc_html__( 'Burundi (Uburundi)', ${3:text-domain} ), 'KH' => esc_html__( 'Cambodia (កម្ពុជា)', ${3:text-domain} ), 'CM' => esc_html__( 'Cameroon (Cameroun)', ${3:text-domain} ), 'CA' => esc_html__( 'Canada', ${3:text-domain} ), 'IC' => esc_html__( 'Canary Islands (islas Canarias)', ${3:text-domain} ), 'CV' => esc_html__( 'Cape Verde (Kabu Verdi)', ${3:text-domain} ), 'BQ' => esc_html__( 'Caribbean Netherlands', ${3:text-domain} ), 'KY' => esc_html__( 'Cayman Islands', ${3:text-domain} ), 'CF' => esc_html__( 'Central African Republic (République centrafricaine)', ${3:text-domain} ), 'EA' => esc_html__( 'Ceuta and Melilla (Ceuta y Melilla)', ${3:text-domain} ), 'TD' => esc_html__( 'Chad (Tchad)', ${3:text-domain} ), 'CL' => esc_html__( 'Chile', ${3:text-domain} ), 'CN' => esc_html__( 'China (中国)', ${3:text-domain} ), 'CX' => esc_html__( 'Christmas Island', ${3:text-domain} ), 'CP' => esc_html__( 'Clipperton Island', ${3:text-domain} ), 'CC' => esc_html__( 'Cocos (Keeling) Islands (Kepulauan Cocos (Keeling))', ${3:text-domain} ), 'CO' => esc_html__( 'Colombia', ${3:text-domain} ), 'KM' => esc_html__( 'Comoros (‫جزر القمر‬‎)', ${3:text-domain} ), 'CD' => esc_html__( 'Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)', ${3:text-domain} ), 'CG' => esc_html__( 'Congo (Republic) (Congo-Brazzaville)', ${3:text-domain} ), 'CK' => esc_html__( 'Cook Islands', ${3:text-domain} ), 'CR' => esc_html__( 'Costa Rica', ${3:text-domain} ), 'CI' => esc_html__( 'Côte d’Ivoire', ${3:text-domain} ), 'HR' => esc_html__( 'Croatia (Hrvatska)', ${3:text-domain} ), 'CU' => esc_html__( 'Cuba', ${3:text-domain} ), 'CW' => esc_html__( 'Curaçao', ${3:text-domain} ), 'CY' => esc_html__( 'Cyprus (Κύπρος)', ${3:text-domain} ), 'CZ' => esc_html__( 'Czech Republic (Česká republika)', ${3:text-domain} ), 'DK' => esc_html__( 'Denmark (Danmark)', ${3:text-domain} ), 'DG' => esc_html__( 'Die<NAME>', ${3:text-domain} ), 'DJ' => esc_html__( 'Djibouti', ${3:text-domain} ), 'DM' => esc_html__( 'Dominica', ${3:text-domain} ), 'DO' => esc_html__( 'Dominican Republic (República Dominicana)', ${3:text-domain} ), 'EC' => esc_html__( 'Ecuador', ${3:text-domain} ), 'EG' => esc_html__( 'Egypt (‫مصر‬‎)', ${3:text-domain} ), 'SV' => esc_html__( 'El Salvador', ${3:text-domain} ), 'GQ' => esc_html__( 'Equatorial Guinea (Guinea Ecuatorial)', ${3:text-domain} ), 'ER' => esc_html__( 'Eritrea', ${3:text-domain} ), 'EE' => esc_html__( 'Estonia (Eesti)', ${3:text-domain} ), 'ET' => esc_html__( 'Ethiopia', ${3:text-domain} ), 'FK' => esc_html__( 'Falkland Islands (Islas Malvinas)', ${3:text-domain} ), 'FO' => esc_html__( 'Faroe Islands (Føroyar)', ${3:text-domain} ), 'FJ' => esc_html__( 'Fiji', ${3:text-domain} ), 'FI' => esc_html__( 'Finland (Suomi)', ${3:text-domain} ), 'FR' => esc_html__( 'France', ${3:text-domain} ), 'GF' => esc_html__( 'French Guiana (Guyane française)', ${3:text-domain} ), 'PF' => esc_html__( 'French Polynesia (Polynésie française)', ${3:text-domain} ), 'TF' => esc_html__( 'French Southern Territories (Terres australes françaises)', ${3:text-domain} ), 'GA' => esc_html__( 'Gabon', ${3:text-domain} ), 'GM' => esc_html__( 'Gambia', ${3:text-domain} ), 'GE' => esc_html__( 'Georgia (საქართველო)', ${3:text-domain} ), 'DE' => esc_html__( 'Germany (Deutschland)', ${3:text-domain} ), 'GH' => esc_html__( 'Ghana (Gaana)', ${3:text-domain} ), 'GI' => esc_html__( 'Gibraltar', ${3:text-domain} ), 'GR' => esc_html__( 'Greece (Ελλάδα)', ${3:text-domain} ), 'GL' => esc_html__( 'Greenland (Kalaallit Nunaat)', ${3:text-domain} ), 'GD' => esc_html__( 'Grenada', ${3:text-domain} ), 'GP' => esc_html__( 'Guadeloupe', ${3:text-domain} ), 'GU' => esc_html__( 'Guam', ${3:text-domain} ), 'GT' => esc_html__( 'Guatemala', ${3:text-domain} ), 'GG' => esc_html__( 'Guernsey', ${3:text-domain} ), 'GN' => esc_html__( 'Guinea (Guinée)', ${3:text-domain} ), 'GW' => esc_html__( 'Guinea-Bissau (Guiné Bissau)', ${3:text-domain} ), 'GY' => esc_html__( 'Guyana', ${3:text-domain} ), 'HT' => esc_html__( 'Haiti', ${3:text-domain} ), 'HM' => esc_html__( 'Heard & McDonald Islands', ${3:text-domain} ), 'HN' => esc_html__( 'Honduras', ${3:text-domain} ), 'HK' => esc_html__( 'Hong Kong (香港)', ${3:text-domain} ), 'HU' => esc_html__( 'Hungary (Magyarország)', ${3:text-domain} ), 'IS' => esc_html__( 'Iceland (Ísland)', ${3:text-domain} ), 'IN' => esc_html__( 'India (भारत)', ${3:text-domain} ), 'ID' => esc_html__( 'Indonesia', ${3:text-domain} ), 'IR' => esc_html__( 'Iran (‫ایران‬‎)', ${3:text-domain} ), 'IQ' => esc_html__( 'Iraq (‫العراق‬‎)', ${3:text-domain} ), 'IE' => esc_html__( 'Ireland', ${3:text-domain} ), 'IM' => esc_html__( 'Isle of Man', ${3:text-domain} ), 'IL' => esc_html__( 'Israel (‫ישראל‬‎)', ${3:text-domain} ), 'IT' => esc_html__( 'Italy (Italia)', ${3:text-domain} ), 'JM' => esc_html__( 'Jamaica', ${3:text-domain} ), 'JP' => esc_html__( 'Japan (日本)', ${3:text-domain} ), 'JE' => esc_html__( 'Jersey', ${3:text-domain} ), 'JO' => esc_html__( 'Jordan (‫الأردن‬‎)', ${3:text-domain} ), 'KZ' => esc_html__( 'Kazakhstan (Казахстан)', ${3:text-domain} ), 'KE' => esc_html__( 'Kenya', ${3:text-domain} ), 'KI' => esc_html__( 'Kiribati', ${3:text-domain} ), 'XK' => esc_html__( 'Kosovo (Kosovë)', ${3:text-domain} ), 'KW' => esc_html__( 'Kuwait (‫الكويت‬‎)', ${3:text-domain} ), 'KG' => esc_html__( 'Kyrgyzstan (Кыргызстан)', ${3:text-domain} ), 'LA' => esc_html__( 'Laos (ລາວ)', ${3:text-domain} ), 'LV' => esc_html__( 'Latvia (Latvija)', ${3:text-domain} ), 'LB' => esc_html__( 'Lebanon (‫لبنان‬‎)', ${3:text-domain} ), 'LS' => esc_html__( 'Lesotho', ${3:text-domain} ), 'LR' => esc_html__( 'Liberia', ${3:text-domain} ), 'LY' => esc_html__( 'Libya (‫ليبيا‬‎)', ${3:text-domain} ), 'LI' => esc_html__( 'Liechtenstein', ${3:text-domain} ), 'LT' => esc_html__( 'Lithuania (Lietuva)', ${3:text-domain} ), 'LU' => esc_html__( 'Luxembourg', ${3:text-domain} ), 'MO' => esc_html__( 'Macau (澳門)', ${3:text-domain} ), 'MK' => esc_html__( 'Macedonia (FYROM) (Македонија)', ${3:text-domain} ), 'MG' => esc_html__( 'Madagascar (Madagasikara)', ${3:text-domain} ), 'MW' => esc_html__( 'Malawi', ${3:text-domain} ), 'MY' => esc_html__( 'Malaysia', ${3:text-domain} ), 'MV' => esc_html__( 'Maldives', ${3:text-domain} ), 'ML' => esc_html__( 'Mali', ${3:text-domain} ), 'MT' => esc_html__( 'Malta', ${3:text-domain} ), 'MH' => esc_html__( 'Marshall Islands', ${3:text-domain} ), 'MQ' => esc_html__( 'Martinique', ${3:text-domain} ), 'MR' => esc_html__( 'Mauritania (‫موريتانيا‬‎)', ${3:text-domain} ), 'MU' => esc_html__( 'Mauritius (Moris)', ${3:text-domain} ), 'YT' => esc_html__( 'Mayotte', ${3:text-domain} ), 'MX' => esc_html__( 'Mexico (México)', ${3:text-domain} ), 'FM' => esc_html__( 'Micronesia', ${3:text-domain} ), 'MD' => esc_html__( 'Moldova (Republica Moldova)', ${3:text-domain} ), 'MC' => esc_html__( 'Monaco', ${3:text-domain} ), 'MN' => esc_html__( 'Mongolia (Монгол)', ${3:text-domain} ), 'ME' => esc_html__( 'Montenegro (Crna Gora)', ${3:text-domain} ), 'MS' => esc_html__( 'Montserrat', ${3:text-domain} ), 'MA' => esc_html__( 'Morocco (‫المغرب‬‎)', ${3:text-domain} ), 'MZ' => esc_html__( 'Mozambique (Moçambique)', ${3:text-domain} ), 'MM' => esc_html__( 'Myanmar (Burma) (မြန်မာ)', ${3:text-domain} ), 'NA' => esc_html__( 'Namibia (Namibië)', ${3:text-domain} ), 'NR' => esc_html__( 'Nauru', ${3:text-domain} ), 'NP' => esc_html__( 'Nepal (नेपाल)', ${3:text-domain} ), 'NL' => esc_html__( 'Netherlands (Nederland)', ${3:text-domain} ), 'NC' => esc_html__( 'New Caledonia (Nouvelle-Calédonie)', ${3:text-domain} ), 'NZ' => esc_html__( 'New Zealand', ${3:text-domain} ), 'NI' => esc_html__( 'Nicaragua', ${3:text-domain} ), 'NE' => esc_html__( 'Niger (Nijar)', ${3:text-domain} ), 'NG' => esc_html__( 'Nigeria', ${3:text-domain} ), 'NU' => esc_html__( 'Niue', ${3:text-domain} ), 'NF' => esc_html__( 'Norfolk Island', ${3:text-domain} ), 'MP' => esc_html__( 'Northern Mariana Islands', ${3:text-domain} ), 'KP' => esc_html__( 'North Korea (조선 민주주의 인민 공화국)', ${3:text-domain} ), 'NO' => esc_html__( 'Norway (Norge)', ${3:text-domain} ), 'OM' => esc_html__( 'Oman (‫عُمان‬‎)', ${3:text-domain} ), 'PK' => esc_html__( 'Pakistan (‫پاکستان‬‎)', ${3:text-domain} ), 'PW' => esc_html__( 'Palau', ${3:text-domain} ), 'PS' => esc_html__( 'Palestine (‫فلسطين‬‎)', ${3:text-domain} ), 'PA' => esc_html__( 'Panama (Panamá)', ${3:text-domain} ), 'PG' => esc_html__( 'Papua New Guinea', ${3:text-domain} ), 'PY' => esc_html__( 'Paraguay', ${3:text-domain} ), 'PE' => esc_html__( 'Peru (Perú)', ${3:text-domain} ), 'PH' => esc_html__( 'Philippines', ${3:text-domain} ), 'PN' => esc_html__( 'Pitcairn Islands', ${3:text-domain} ), 'PL' => esc_html__( 'Poland (Polska)', ${3:text-domain} ), 'PT' => esc_html__( 'Portugal', ${3:text-domain} ), 'PR' => esc_html__( 'Puerto Rico', ${3:text-domain} ), 'QA' => esc_html__( 'Qatar (‫قطر‬‎)', ${3:text-domain} ), 'RE' => esc_html__( 'Réunion (La Réunion)', ${3:text-domain} ), 'RO' => esc_html__( 'Romania (România)', ${3:text-domain} ), 'RU' => esc_html__( 'Russia (Россия)', ${3:text-domain} ), 'RW' => esc_html__( 'Rwanda', ${3:text-domain} ), 'BL' => esc_html__( 'Saint Barthélemy (Saint-Barthélemy)', ${3:text-domain} ), 'SH' => esc_html__( 'Saint Helena', ${3:text-domain} ), 'KN' => esc_html__( 'Saint Kitts and Nevis', ${3:text-domain} ), 'LC' => esc_html__( 'Saint Lucia', ${3:text-domain} ), 'MF' => esc_html__( 'Saint Martin (Saint-Martin (partie française))', ${3:text-domain} ), 'PM' => esc_html__( 'Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)', ${3:text-domain} ), 'WS' => esc_html__( 'Samoa', ${3:text-domain} ), 'SM' => esc_html__( 'San Marino', ${3:text-domain} ), 'ST' => esc_html__( 'São Tomé and Príncipe (São Tomé e Príncipe)', ${3:text-domain} ), 'SA' => esc_html__( 'Saudi Arabia (‫المملكة العربية السعودية‬‎)', ${3:text-domain} ), 'SN' => esc_html__( 'Senegal (Sénégal)', ${3:text-domain} ), 'RS' => esc_html__( 'Serbia (Србија)', ${3:text-domain} ), 'SC' => esc_html__( 'Seychelles', ${3:text-domain} ), 'SL' => esc_html__( 'Sierra Leone', ${3:text-domain} ), 'SG' => esc_html__( 'Singapore', ${3:text-domain} ), 'SX' => esc_html__( 'Sint Maarten', ${3:text-domain} ), 'SK' => esc_html__( 'Slovakia (Slovensko)', ${3:text-domain} ), 'SI' => esc_html__( 'Slovenia (Slovenija)', ${3:text-domain} ), 'SB' => esc_html__( 'Solomon Islands', ${3:text-domain} ), 'SO' => esc_html__( 'Somalia (Soomaaliya)', ${3:text-domain} ), 'ZA' => esc_html__( 'South Africa', ${3:text-domain} ), 'GS' => esc_html__( 'South Georgia & South Sandwich Islands', ${3:text-domain} ), 'KR' => esc_html__( 'South Korea (대한민국)', ${3:text-domain} ), 'SS' => esc_html__( 'South Sudan (‫جنوب السودان‬‎)', ${3:text-domain} ), 'ES' => esc_html__( 'Spain (España)', ${3:text-domain} ), 'LK' => esc_html__( 'Sri Lanka (ශ්‍රී ලංකාව)', ${3:text-domain} ), 'VC' => esc_html__( 'St. Vincent & Grenadines', ${3:text-domain} ), 'SD' => esc_html__( 'Sudan (‫السودان‬‎)', ${3:text-domain} ), 'SR' => esc_html__( 'Suriname', ${3:text-domain} ), 'SJ' => esc_html__( 'Svalbard and Jan Mayen (Svalbard og Jan Mayen)', ${3:text-domain} ), 'SZ' => esc_html__( 'Swaziland', ${3:text-domain} ), 'SE' => esc_html__( 'Sweden (Sverige)', ${3:text-domain} ), 'CH' => esc_html__( 'Switzerland (Schweiz)', ${3:text-domain} ), 'SY' => esc_html__( 'Syria (‫سوريا‬‎)', ${3:text-domain} ), 'TW' => esc_html__( 'Taiwan (台灣)', ${3:text-domain} ), 'TJ' => esc_html__( 'Tajikistan', ${3:text-domain} ), 'TZ' => esc_html__( 'Tanzania', ${3:text-domain} ), 'TH' => esc_html__( 'Thailand (ไทย)', ${3:text-domain} ), 'TL' => esc_html__( 'Timor-Leste', ${3:text-domain} ), 'TG' => esc_html__( 'Togo', ${3:text-domain} ), 'TK' => esc_html__( 'Tokelau', ${3:text-domain} ), 'TO' => esc_html__( 'Tonga', ${3:text-domain} ), 'TT' => esc_html__( 'Trinidad and Tobago', ${3:text-domain} ), 'TA' => esc_html__( 'Tristan da Cunha', ${3:text-domain} ), 'TN' => esc_html__( 'Tunisia (‫تونس‬‎)', ${3:text-domain} ), 'TR' => esc_html__( 'Turkey (Türkiye)', ${3:text-domain} ), 'TM' => esc_html__( 'Turkmenistan', ${3:text-domain} ), 'TC' => esc_html__( 'Turks and Caicos Islands', ${3:text-domain} ), 'TV' => esc_html__( 'Tuvalu', ${3:text-domain} ), 'UM' => esc_html__( 'U.S. Outlying Islands', ${3:text-domain} ), 'VI' => esc_html__( 'U.S. Virgin Islands', ${3:text-domain} ), 'UG' => esc_html__( 'Uganda', ${3:text-domain} ), 'UA' => esc_html__( 'Ukraine (Україна)', ${3:text-domain} ), 'AE' => esc_html__( 'United Arab Emirates (‫الإمارات العربية المتحدة‬‎)', ${3:text-domain} ), 'GB' => esc_html__( 'United Kingdom', ${3:text-domain} ), 'US' => esc_html__( 'United States', ${3:text-domain} ), 'UY' => esc_html__( 'Uruguay', ${3:text-domain} ), 'UZ' => esc_html__( 'Uzbekistan (Oʻzbekiston)', ${3:text-domain} ), 'VU' => esc_html__( 'Vanuatu', ${3:text-domain} ), 'VA' => esc_html__( 'Vatican City (Città del Vaticano)', ${3:text-domain} ), 'VE' => esc_html__( 'Venezuela', ${3:text-domain} ), 'VN' => esc_html__( 'Vietnam (Việt Nam)', ${3:text-domain} ), 'WF' => esc_html__( 'Wallis and Futuna', ${3:text-domain} ), 'EH' => esc_html__( 'Western Sahara (‫الصحراء الغربية‬‎)', ${3:text-domain} ), 'YE' => esc_html__( 'Yemen (‫اليمن‬‎)', ${3:text-domain} ), 'ZM' => esc_html__( 'Zambia', ${3:text-domain} ), 'ZW' => esc_html__( 'Zimbabwe', ${3:text-domain} ), ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerUSStates": "prefix": "wpcus" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'AL' => esc_html__( 'Alabama', ${3:text-domain} ), 'AK' => esc_html__( 'Alaska', ${3:text-domain} ), 'AZ' => esc_html__( 'Arizona', ${3:text-domain} ), 'AR' => esc_html__( 'Arkansas', ${3:text-domain} ), 'CA' => esc_html__( 'California', ${3:text-domain} ), 'CO' => esc_html__( 'Colorado', ${3:text-domain} ), 'CT' => esc_html__( 'Connecticut', ${3:text-domain} ), 'DE' => esc_html__( 'Delaware', ${3:text-domain} ), 'DC' => esc_html__( 'District of Columbia', ${3:text-domain} ), 'FL' => esc_html__( 'Florida', ${3:text-domain} ), 'GA' => esc_html__( 'Georgia', ${3:text-domain} ), 'HI' => esc_html__( 'Hawaii', ${3:text-domain} ), 'ID' => esc_html__( 'Idaho', ${3:text-domain} ), 'IL' => esc_html__( 'Illinois', ${3:text-domain} ), 'IN' => esc_html__( 'Indiana', ${3:text-domain} ), 'IA' => esc_html__( 'Iowa', ${3:text-domain} ), 'KS' => esc_html__( 'Kansas', ${3:text-domain} ), 'KY' => esc_html__( 'Kentucky', ${3:text-domain} ), 'LA' => esc_html__( 'Louisiana', ${3:text-domain} ), 'ME' => esc_html__( 'Maine', ${3:text-domain} ), 'MD' => esc_html__( 'Maryland', ${3:text-domain} ), 'MA' => esc_html__( 'Massachusetts', ${3:text-domain} ), 'MI' => esc_html__( 'Michigan', ${3:text-domain} ), 'MN' => esc_html__( 'Minnesota', ${3:text-domain} ), 'MS' => esc_html__( 'Mississippi', ${3:text-domain} ), 'MO' => esc_html__( 'Missouri', ${3:text-domain} ), 'MT' => esc_html__( 'Montana', ${3:text-domain} ), 'NE' => esc_html__( 'Nebraska', ${3:text-domain} ), 'NV' => esc_html__( 'Nevada', ${3:text-domain} ), 'NH' => esc_html__( 'New Hampshire', ${3:text-domain} ), 'NJ' => esc_html__( 'New Jersey', ${3:text-domain} ), 'NM' => esc_html__( 'New Mexico', ${3:text-domain} ), 'NY' => esc_html__( 'New York', ${3:text-domain} ), 'NC' => esc_html__( 'North Carolina', ${3:text-domain} ), 'ND' => esc_html__( 'North Dakota', ${3:text-domain} ), 'OH' => esc_html__( 'Ohio', ${3:text-domain} ), 'OK' => esc_html__( 'Oklahoma', ${3:text-domain} ), 'OR' => esc_html__( 'Oregon', ${3:text-domain} ), 'PA' => esc_html__( 'Pennsylvania', ${3:text-domain} ), 'RI' => esc_html__( 'Rhode Island', ${3:text-domain} ), 'SC' => esc_html__( 'South Carolina', ${3:text-domain} ), 'SD' => esc_html__( 'South Dakota', ${3:text-domain} ), 'TN' => esc_html__( 'Tennessee', ${3:text-domain} ), 'TX' => esc_html__( 'Texas', ${3:text-domain} ), 'UT' => esc_html__( 'Utah', ${3:text-domain} ), 'VT' => esc_html__( 'Vermont', ${3:text-domain} ), 'VA' => esc_html__( 'Virginia', ${3:text-domain} ), 'WA' => esc_html__( 'Washington', ${3:text-domain} ), 'WV' => esc_html__( 'West Virginia', ${3:text-domain} ), 'WI' => esc_html__( 'Wisconsin', ${3:text-domain} ), 'WY' => esc_html__( 'Wyoming', ${3:text-domain} ), 'AS' => esc_html__( 'American Samoa', ${3:text-domain} ), 'AA' => esc_html__( 'Armed Forces America (except Canada)', ${3:text-domain} ), 'AE' => esc_html__( 'Armed Forces Africa/Canada/Europe/Middle East', ${3:text-domain} ), 'AP' => esc_html__( 'Armed Forces Pacific', ${3:text-domain} ), 'FM' => esc_html__( 'Federated States of Micronesia', ${3:text-domain} ), 'GU' => esc_html__( 'Guam', ${3:text-domain} ), 'MH' => esc_html__( 'Marshall Islands', ${3:text-domain} ), 'MP' => esc_html__( 'Northern Mariana Islands', ${3:text-domain} ), 'PR' => esc_html__( 'Puerto Rico', ${3:text-domain} ), 'PW' => esc_html__( 'Palau', ${3:text-domain} ), 'VI' => esc_html__( 'Virgin Islands', ${3:text-domain} ) ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerCanadianStates": "prefix": "wpccanada" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'AB' => esc_html__( 'Alberta', '${3:text-domain}' ), 'BC' => esc_html__( 'British Columbia', '${3:text-domain}' ), 'MB' => esc_html__( 'Manitoba', '${3:text-domain}' ), 'NB' => esc_html__( 'New Brunswick', '${3:text-domain}' ), 'NL' => esc_html__( 'Newfoundland and Labrador', '${3:text-domain}' ), 'NT' => esc_html__( 'Northwest Territories', '${3:text-domain}' ), 'NS' => esc_html__( 'Nova Scotia', '${3:text-domain}' ), 'NU' => esc_html__( 'Nunavut', '${3:text-domain}' ), 'ON' => esc_html__( 'Ontario', '${3:text-domain}' ), 'PE' => esc_html__( 'Prince Edward Island', '${3:text-domain}' ), 'QC' => esc_html__( 'Quebec', '${3:text-domain}' ), 'SK' => esc_html__( 'Saskatchewan', '${3:text-domain}' ), 'YT' => esc_html__( 'Yukon', '${3:text-domain}' ) ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerAustralianStates": "prefix": "wpcaus" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'ACT' => esc_html__( 'Australian Capital Territory', '${3:text-domain}' ), 'NSW' => esc_html__( 'New South Wales', '${3:text-domain}' ), 'NT' => esc_html__( 'Northern Territory', '${3:text-domain}' ), 'QLD' => esc_html__( 'Queensland', '${3:text-domain}' ), 'SA' => esc_html__( 'South Australia', '${3:text-domain}' ), 'TAS' => esc_html__( 'Tasmania', '${3:text-domain}' ), 'VIC' => esc_html__( 'Victoria', '${3:text-domain}' ), 'WA' => esc_html__( 'Western Australia', '${3:text-domain}' ) ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" ".source.js": "WPCustomizerBasicJS": "prefix": "wpcjs" "body": """// ${1:setting_name}. wp.customize( '${2:setting_id}', function( value ) { value.bind( function( to ) { $( '${3:id_or_class}' ).text( to ); } ); } );"""
true
".text.html.php, .source.php": "WPCustomizerPanel": "prefix": "wpcp" "body": """// ${1:panel_name} Panel $wp_customize->add_panel( '${2:panel_id}', array( 'capability' => 'edgepait_theme_options', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'priority' => 10, 'theme_supports' => '', 'title' => esc_html__( '${1:panel_name}', '${4:text-domain}' ), ) );""" "WPCustomizerSection": "prefix": "wpcs" "body": """// ${1:section_name} Section $wp_customize->add_section( '${2:section_id}', array( 'active_callback' => '${3:callback_function}', 'capability' => 'edit_theme_options', 'description' => esc_html__( '${4:description}', '${5:text-domain}' ), 'panel' => '${1:panel_id}', 'priority' => 10, 'theme_supports' => '', 'title' => esc_html__( '${1:section_name}', '${5:text-domain}' ), ) );""" "WPCustomizerText": "prefix": "wpct" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'text' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerURL": "prefix": "wpcu" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'url' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerEmail": "prefix": "wpce" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'sanitize_email', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'email' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerDate": "prefix": "wpcd" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'date' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerCheckbox": "prefix": "wpcc" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'absint', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'checkbox' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerPassword": "prefix": "wpcpw" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'password' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerRadios": "prefix": "wpcr" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '${3:choice1_id}', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( '${3:choice1_id}' => esc_html__( '${4:choice1_name}', '${5:text-domain}' ), ), 'description' => esc_html__( '${6:description}', '${5:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${5:text-domain}' ), 'priority' => 10, 'section' => '${7:section_id}', 'settings' => '${2:field_id}', 'type' => 'radio' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerSelect": "prefix": "wpcsel" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '${3:choice1_id}', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( '${3:choice1_id}' => esc_html__( '${4:choice1_name}', '${5:text-domain}' ), ), 'description' => esc_html__( '${6:description}', '${5:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${5:text-domain}' ), 'priority' => 10, 'section' => '${7:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerTextArea": "prefix": "wpcta" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_textarea', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'textarea' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerRange": "prefix": "wpcrange" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'intval', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${6:description}', '${5:text-domain}' ), 'input_attrs' => array( 'class' => 'range-field', 'max' => ${7:max_value}, 'min' => ${8:min_value}, 'step' => ${9:step_value}, 'style' => 'color: #020202' ), 'label' => esc_html__( '${1:field_name}', '${5:text-domain}' ), 'priority' => 10, 'section' => '${10:section_id}', 'settings' => '${2:field_id}', 'type' => 'range' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerPageSelect": "prefix": "wpcpage" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'dropdown-pages' ) ); $wp_customize->get_setting( 'dropdown-pages' )->transport = 'postMessage';""" "WPCustomizerColorChoose": "prefix": "wpccolor" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '#ffffff', 'sanitize_callback' => 'sanitize_hex_color', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerFileUpload": "prefix": "wpcfile" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) );""" "WPCustomizerImageUpload": "prefix": "wpcimg" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) );""" "WPCustomizerMediaUpload": "prefix": "wpcmedia" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Media_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}' ) ) );""" "WPCustomizerCroppedImage": "prefix": "wpccrop" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}' , array( 'capability' => 'edit_theme_options', 'default' => '', 'sanitize_callback' => 'esc_url_raw', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, '${2:field_id}', array( 'active_callback' => '', 'description' => esc_html__( '${3:description}', '${4:text-domain}' ), 'flex_height' => '${5:flex_height_true_or_false}', 'flex_width' => '${6:flex_width_true_or_false}', 'height' => '${7:height_in_pixels}', 'label' => esc_html__( '${1:field_name}', '${4:text-domain}' ), 'priority' => 10, 'section' => '${8:section_id}', 'settings' => '${2:field_id}', 'width' => '${9:width_in_pixels}' ) ) );""" "WPCustomizerCountriesList": "prefix": "wpccountry" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => 'US, 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'AF' => esc_html__( 'Afghanistan (‫افغانستان‬‎)', ${3:text-domain} ), 'AX' => esc_html__( 'Åland Islands (Åland)', ${3:text-domain} ), 'AL' => esc_html__( 'Albania (Shqipëri)', ${3:text-domain} ), 'DZ' => esc_html__( 'Algeria (‫الجزائر‬‎)', ${3:text-domain} ), 'AS' => esc_html__( 'American Samoa', ${3:text-domain} ), 'AD' => esc_html__( 'Andorra', ${3:text-domain} ), 'AO' => esc_html__( 'Angola', ${3:text-domain} ), 'AI' => esc_html__( 'Anguilla', ${3:text-domain} ), 'AQ' => esc_html__( 'Antarctica', ${3:text-domain} ), 'AG' => esc_html__( 'Antigua and Barbuda', ${3:text-domain} ), 'AR' => esc_html__( 'Argentina', ${3:text-domain} ), 'AM' => esc_html__( 'Armenia (Հայաստան)', ${3:text-domain} ), 'AW' => esc_html__( 'Aruba', ${3:text-domain} ), 'AC' => esc_html__( 'Ascension Island', ${3:text-domain} ), 'AU' => esc_html__( 'Australia', ${3:text-domain} ), 'AT' => esc_html__( 'Austria (Österreich)', ${3:text-domain} ), 'AZ' => esc_html__( 'Azerbaijan (Azərbaycan)', ${3:text-domain} ), 'BS' => esc_html__( 'Bahamas', ${3:text-domain} ), 'BH' => esc_html__( 'Bahrain (‫البحرين‬‎)', ${3:text-domain} ), 'BD' => esc_html__( 'Bangladesh (বাংলাদেশ)', ${3:text-domain} ), 'BB' => esc_html__( 'Barbados', ${3:text-domain} ), 'BY' => esc_html__( 'Belarus (Беларусь)', ${3:text-domain} ), 'BE' => esc_html__( 'Belgium (België)', ${3:text-domain} ), 'BZ' => esc_html__( 'Belize', ${3:text-domain} ), 'BJ' => esc_html__( 'Benin (Bénin)', ${3:text-domain} ), 'BM' => esc_html__( 'Bermuda', ${3:text-domain} ), 'BT' => esc_html__( 'Bhutan (འབྲུག)', ${3:text-domain} ), 'BO' => esc_html__( 'Bolivia', ${3:text-domain} ), 'BA' => esc_html__( 'Bosnia and Herzegovina (Босна и Херцеговина)', ${3:text-domain} ), 'BW' => esc_html__( 'Botswana', ${3:text-domain} ), 'BV' => esc_html__( 'Bouvet Island', ${3:text-domain} ), 'BR' => esc_html__( 'Brazil (Brasil)', ${3:text-domain} ), 'IO' => esc_html__( 'British Indian Ocean Territory', ${3:text-domain} ), 'VG' => esc_html__( 'British Virgin Islands', ${3:text-domain} ), 'BN' => esc_html__( 'Brunei', ${3:text-domain} ), 'BG' => esc_html__( 'Bulgaria (България)', ${3:text-domain} ), 'BF' => esc_html__( 'Burkina Faso', ${3:text-domain} ), 'BI' => esc_html__( 'Burundi (Uburundi)', ${3:text-domain} ), 'KH' => esc_html__( 'Cambodia (កម្ពុជា)', ${3:text-domain} ), 'CM' => esc_html__( 'Cameroon (Cameroun)', ${3:text-domain} ), 'CA' => esc_html__( 'Canada', ${3:text-domain} ), 'IC' => esc_html__( 'Canary Islands (islas Canarias)', ${3:text-domain} ), 'CV' => esc_html__( 'Cape Verde (Kabu Verdi)', ${3:text-domain} ), 'BQ' => esc_html__( 'Caribbean Netherlands', ${3:text-domain} ), 'KY' => esc_html__( 'Cayman Islands', ${3:text-domain} ), 'CF' => esc_html__( 'Central African Republic (République centrafricaine)', ${3:text-domain} ), 'EA' => esc_html__( 'Ceuta and Melilla (Ceuta y Melilla)', ${3:text-domain} ), 'TD' => esc_html__( 'Chad (Tchad)', ${3:text-domain} ), 'CL' => esc_html__( 'Chile', ${3:text-domain} ), 'CN' => esc_html__( 'China (中国)', ${3:text-domain} ), 'CX' => esc_html__( 'Christmas Island', ${3:text-domain} ), 'CP' => esc_html__( 'Clipperton Island', ${3:text-domain} ), 'CC' => esc_html__( 'Cocos (Keeling) Islands (Kepulauan Cocos (Keeling))', ${3:text-domain} ), 'CO' => esc_html__( 'Colombia', ${3:text-domain} ), 'KM' => esc_html__( 'Comoros (‫جزر القمر‬‎)', ${3:text-domain} ), 'CD' => esc_html__( 'Congo (DRC) (Jamhuri ya Kidemokrasia ya Kongo)', ${3:text-domain} ), 'CG' => esc_html__( 'Congo (Republic) (Congo-Brazzaville)', ${3:text-domain} ), 'CK' => esc_html__( 'Cook Islands', ${3:text-domain} ), 'CR' => esc_html__( 'Costa Rica', ${3:text-domain} ), 'CI' => esc_html__( 'Côte d’Ivoire', ${3:text-domain} ), 'HR' => esc_html__( 'Croatia (Hrvatska)', ${3:text-domain} ), 'CU' => esc_html__( 'Cuba', ${3:text-domain} ), 'CW' => esc_html__( 'Curaçao', ${3:text-domain} ), 'CY' => esc_html__( 'Cyprus (Κύπρος)', ${3:text-domain} ), 'CZ' => esc_html__( 'Czech Republic (Česká republika)', ${3:text-domain} ), 'DK' => esc_html__( 'Denmark (Danmark)', ${3:text-domain} ), 'DG' => esc_html__( 'DiePI:NAME:<NAME>END_PI', ${3:text-domain} ), 'DJ' => esc_html__( 'Djibouti', ${3:text-domain} ), 'DM' => esc_html__( 'Dominica', ${3:text-domain} ), 'DO' => esc_html__( 'Dominican Republic (República Dominicana)', ${3:text-domain} ), 'EC' => esc_html__( 'Ecuador', ${3:text-domain} ), 'EG' => esc_html__( 'Egypt (‫مصر‬‎)', ${3:text-domain} ), 'SV' => esc_html__( 'El Salvador', ${3:text-domain} ), 'GQ' => esc_html__( 'Equatorial Guinea (Guinea Ecuatorial)', ${3:text-domain} ), 'ER' => esc_html__( 'Eritrea', ${3:text-domain} ), 'EE' => esc_html__( 'Estonia (Eesti)', ${3:text-domain} ), 'ET' => esc_html__( 'Ethiopia', ${3:text-domain} ), 'FK' => esc_html__( 'Falkland Islands (Islas Malvinas)', ${3:text-domain} ), 'FO' => esc_html__( 'Faroe Islands (Føroyar)', ${3:text-domain} ), 'FJ' => esc_html__( 'Fiji', ${3:text-domain} ), 'FI' => esc_html__( 'Finland (Suomi)', ${3:text-domain} ), 'FR' => esc_html__( 'France', ${3:text-domain} ), 'GF' => esc_html__( 'French Guiana (Guyane française)', ${3:text-domain} ), 'PF' => esc_html__( 'French Polynesia (Polynésie française)', ${3:text-domain} ), 'TF' => esc_html__( 'French Southern Territories (Terres australes françaises)', ${3:text-domain} ), 'GA' => esc_html__( 'Gabon', ${3:text-domain} ), 'GM' => esc_html__( 'Gambia', ${3:text-domain} ), 'GE' => esc_html__( 'Georgia (საქართველო)', ${3:text-domain} ), 'DE' => esc_html__( 'Germany (Deutschland)', ${3:text-domain} ), 'GH' => esc_html__( 'Ghana (Gaana)', ${3:text-domain} ), 'GI' => esc_html__( 'Gibraltar', ${3:text-domain} ), 'GR' => esc_html__( 'Greece (Ελλάδα)', ${3:text-domain} ), 'GL' => esc_html__( 'Greenland (Kalaallit Nunaat)', ${3:text-domain} ), 'GD' => esc_html__( 'Grenada', ${3:text-domain} ), 'GP' => esc_html__( 'Guadeloupe', ${3:text-domain} ), 'GU' => esc_html__( 'Guam', ${3:text-domain} ), 'GT' => esc_html__( 'Guatemala', ${3:text-domain} ), 'GG' => esc_html__( 'Guernsey', ${3:text-domain} ), 'GN' => esc_html__( 'Guinea (Guinée)', ${3:text-domain} ), 'GW' => esc_html__( 'Guinea-Bissau (Guiné Bissau)', ${3:text-domain} ), 'GY' => esc_html__( 'Guyana', ${3:text-domain} ), 'HT' => esc_html__( 'Haiti', ${3:text-domain} ), 'HM' => esc_html__( 'Heard & McDonald Islands', ${3:text-domain} ), 'HN' => esc_html__( 'Honduras', ${3:text-domain} ), 'HK' => esc_html__( 'Hong Kong (香港)', ${3:text-domain} ), 'HU' => esc_html__( 'Hungary (Magyarország)', ${3:text-domain} ), 'IS' => esc_html__( 'Iceland (Ísland)', ${3:text-domain} ), 'IN' => esc_html__( 'India (भारत)', ${3:text-domain} ), 'ID' => esc_html__( 'Indonesia', ${3:text-domain} ), 'IR' => esc_html__( 'Iran (‫ایران‬‎)', ${3:text-domain} ), 'IQ' => esc_html__( 'Iraq (‫العراق‬‎)', ${3:text-domain} ), 'IE' => esc_html__( 'Ireland', ${3:text-domain} ), 'IM' => esc_html__( 'Isle of Man', ${3:text-domain} ), 'IL' => esc_html__( 'Israel (‫ישראל‬‎)', ${3:text-domain} ), 'IT' => esc_html__( 'Italy (Italia)', ${3:text-domain} ), 'JM' => esc_html__( 'Jamaica', ${3:text-domain} ), 'JP' => esc_html__( 'Japan (日本)', ${3:text-domain} ), 'JE' => esc_html__( 'Jersey', ${3:text-domain} ), 'JO' => esc_html__( 'Jordan (‫الأردن‬‎)', ${3:text-domain} ), 'KZ' => esc_html__( 'Kazakhstan (Казахстан)', ${3:text-domain} ), 'KE' => esc_html__( 'Kenya', ${3:text-domain} ), 'KI' => esc_html__( 'Kiribati', ${3:text-domain} ), 'XK' => esc_html__( 'Kosovo (Kosovë)', ${3:text-domain} ), 'KW' => esc_html__( 'Kuwait (‫الكويت‬‎)', ${3:text-domain} ), 'KG' => esc_html__( 'Kyrgyzstan (Кыргызстан)', ${3:text-domain} ), 'LA' => esc_html__( 'Laos (ລາວ)', ${3:text-domain} ), 'LV' => esc_html__( 'Latvia (Latvija)', ${3:text-domain} ), 'LB' => esc_html__( 'Lebanon (‫لبنان‬‎)', ${3:text-domain} ), 'LS' => esc_html__( 'Lesotho', ${3:text-domain} ), 'LR' => esc_html__( 'Liberia', ${3:text-domain} ), 'LY' => esc_html__( 'Libya (‫ليبيا‬‎)', ${3:text-domain} ), 'LI' => esc_html__( 'Liechtenstein', ${3:text-domain} ), 'LT' => esc_html__( 'Lithuania (Lietuva)', ${3:text-domain} ), 'LU' => esc_html__( 'Luxembourg', ${3:text-domain} ), 'MO' => esc_html__( 'Macau (澳門)', ${3:text-domain} ), 'MK' => esc_html__( 'Macedonia (FYROM) (Македонија)', ${3:text-domain} ), 'MG' => esc_html__( 'Madagascar (Madagasikara)', ${3:text-domain} ), 'MW' => esc_html__( 'Malawi', ${3:text-domain} ), 'MY' => esc_html__( 'Malaysia', ${3:text-domain} ), 'MV' => esc_html__( 'Maldives', ${3:text-domain} ), 'ML' => esc_html__( 'Mali', ${3:text-domain} ), 'MT' => esc_html__( 'Malta', ${3:text-domain} ), 'MH' => esc_html__( 'Marshall Islands', ${3:text-domain} ), 'MQ' => esc_html__( 'Martinique', ${3:text-domain} ), 'MR' => esc_html__( 'Mauritania (‫موريتانيا‬‎)', ${3:text-domain} ), 'MU' => esc_html__( 'Mauritius (Moris)', ${3:text-domain} ), 'YT' => esc_html__( 'Mayotte', ${3:text-domain} ), 'MX' => esc_html__( 'Mexico (México)', ${3:text-domain} ), 'FM' => esc_html__( 'Micronesia', ${3:text-domain} ), 'MD' => esc_html__( 'Moldova (Republica Moldova)', ${3:text-domain} ), 'MC' => esc_html__( 'Monaco', ${3:text-domain} ), 'MN' => esc_html__( 'Mongolia (Монгол)', ${3:text-domain} ), 'ME' => esc_html__( 'Montenegro (Crna Gora)', ${3:text-domain} ), 'MS' => esc_html__( 'Montserrat', ${3:text-domain} ), 'MA' => esc_html__( 'Morocco (‫المغرب‬‎)', ${3:text-domain} ), 'MZ' => esc_html__( 'Mozambique (Moçambique)', ${3:text-domain} ), 'MM' => esc_html__( 'Myanmar (Burma) (မြန်မာ)', ${3:text-domain} ), 'NA' => esc_html__( 'Namibia (Namibië)', ${3:text-domain} ), 'NR' => esc_html__( 'Nauru', ${3:text-domain} ), 'NP' => esc_html__( 'Nepal (नेपाल)', ${3:text-domain} ), 'NL' => esc_html__( 'Netherlands (Nederland)', ${3:text-domain} ), 'NC' => esc_html__( 'New Caledonia (Nouvelle-Calédonie)', ${3:text-domain} ), 'NZ' => esc_html__( 'New Zealand', ${3:text-domain} ), 'NI' => esc_html__( 'Nicaragua', ${3:text-domain} ), 'NE' => esc_html__( 'Niger (Nijar)', ${3:text-domain} ), 'NG' => esc_html__( 'Nigeria', ${3:text-domain} ), 'NU' => esc_html__( 'Niue', ${3:text-domain} ), 'NF' => esc_html__( 'Norfolk Island', ${3:text-domain} ), 'MP' => esc_html__( 'Northern Mariana Islands', ${3:text-domain} ), 'KP' => esc_html__( 'North Korea (조선 민주주의 인민 공화국)', ${3:text-domain} ), 'NO' => esc_html__( 'Norway (Norge)', ${3:text-domain} ), 'OM' => esc_html__( 'Oman (‫عُمان‬‎)', ${3:text-domain} ), 'PK' => esc_html__( 'Pakistan (‫پاکستان‬‎)', ${3:text-domain} ), 'PW' => esc_html__( 'Palau', ${3:text-domain} ), 'PS' => esc_html__( 'Palestine (‫فلسطين‬‎)', ${3:text-domain} ), 'PA' => esc_html__( 'Panama (Panamá)', ${3:text-domain} ), 'PG' => esc_html__( 'Papua New Guinea', ${3:text-domain} ), 'PY' => esc_html__( 'Paraguay', ${3:text-domain} ), 'PE' => esc_html__( 'Peru (Perú)', ${3:text-domain} ), 'PH' => esc_html__( 'Philippines', ${3:text-domain} ), 'PN' => esc_html__( 'Pitcairn Islands', ${3:text-domain} ), 'PL' => esc_html__( 'Poland (Polska)', ${3:text-domain} ), 'PT' => esc_html__( 'Portugal', ${3:text-domain} ), 'PR' => esc_html__( 'Puerto Rico', ${3:text-domain} ), 'QA' => esc_html__( 'Qatar (‫قطر‬‎)', ${3:text-domain} ), 'RE' => esc_html__( 'Réunion (La Réunion)', ${3:text-domain} ), 'RO' => esc_html__( 'Romania (România)', ${3:text-domain} ), 'RU' => esc_html__( 'Russia (Россия)', ${3:text-domain} ), 'RW' => esc_html__( 'Rwanda', ${3:text-domain} ), 'BL' => esc_html__( 'Saint Barthélemy (Saint-Barthélemy)', ${3:text-domain} ), 'SH' => esc_html__( 'Saint Helena', ${3:text-domain} ), 'KN' => esc_html__( 'Saint Kitts and Nevis', ${3:text-domain} ), 'LC' => esc_html__( 'Saint Lucia', ${3:text-domain} ), 'MF' => esc_html__( 'Saint Martin (Saint-Martin (partie française))', ${3:text-domain} ), 'PM' => esc_html__( 'Saint Pierre and Miquelon (Saint-Pierre-et-Miquelon)', ${3:text-domain} ), 'WS' => esc_html__( 'Samoa', ${3:text-domain} ), 'SM' => esc_html__( 'San Marino', ${3:text-domain} ), 'ST' => esc_html__( 'São Tomé and Príncipe (São Tomé e Príncipe)', ${3:text-domain} ), 'SA' => esc_html__( 'Saudi Arabia (‫المملكة العربية السعودية‬‎)', ${3:text-domain} ), 'SN' => esc_html__( 'Senegal (Sénégal)', ${3:text-domain} ), 'RS' => esc_html__( 'Serbia (Србија)', ${3:text-domain} ), 'SC' => esc_html__( 'Seychelles', ${3:text-domain} ), 'SL' => esc_html__( 'Sierra Leone', ${3:text-domain} ), 'SG' => esc_html__( 'Singapore', ${3:text-domain} ), 'SX' => esc_html__( 'Sint Maarten', ${3:text-domain} ), 'SK' => esc_html__( 'Slovakia (Slovensko)', ${3:text-domain} ), 'SI' => esc_html__( 'Slovenia (Slovenija)', ${3:text-domain} ), 'SB' => esc_html__( 'Solomon Islands', ${3:text-domain} ), 'SO' => esc_html__( 'Somalia (Soomaaliya)', ${3:text-domain} ), 'ZA' => esc_html__( 'South Africa', ${3:text-domain} ), 'GS' => esc_html__( 'South Georgia & South Sandwich Islands', ${3:text-domain} ), 'KR' => esc_html__( 'South Korea (대한민국)', ${3:text-domain} ), 'SS' => esc_html__( 'South Sudan (‫جنوب السودان‬‎)', ${3:text-domain} ), 'ES' => esc_html__( 'Spain (España)', ${3:text-domain} ), 'LK' => esc_html__( 'Sri Lanka (ශ්‍රී ලංකාව)', ${3:text-domain} ), 'VC' => esc_html__( 'St. Vincent & Grenadines', ${3:text-domain} ), 'SD' => esc_html__( 'Sudan (‫السودان‬‎)', ${3:text-domain} ), 'SR' => esc_html__( 'Suriname', ${3:text-domain} ), 'SJ' => esc_html__( 'Svalbard and Jan Mayen (Svalbard og Jan Mayen)', ${3:text-domain} ), 'SZ' => esc_html__( 'Swaziland', ${3:text-domain} ), 'SE' => esc_html__( 'Sweden (Sverige)', ${3:text-domain} ), 'CH' => esc_html__( 'Switzerland (Schweiz)', ${3:text-domain} ), 'SY' => esc_html__( 'Syria (‫سوريا‬‎)', ${3:text-domain} ), 'TW' => esc_html__( 'Taiwan (台灣)', ${3:text-domain} ), 'TJ' => esc_html__( 'Tajikistan', ${3:text-domain} ), 'TZ' => esc_html__( 'Tanzania', ${3:text-domain} ), 'TH' => esc_html__( 'Thailand (ไทย)', ${3:text-domain} ), 'TL' => esc_html__( 'Timor-Leste', ${3:text-domain} ), 'TG' => esc_html__( 'Togo', ${3:text-domain} ), 'TK' => esc_html__( 'Tokelau', ${3:text-domain} ), 'TO' => esc_html__( 'Tonga', ${3:text-domain} ), 'TT' => esc_html__( 'Trinidad and Tobago', ${3:text-domain} ), 'TA' => esc_html__( 'Tristan da Cunha', ${3:text-domain} ), 'TN' => esc_html__( 'Tunisia (‫تونس‬‎)', ${3:text-domain} ), 'TR' => esc_html__( 'Turkey (Türkiye)', ${3:text-domain} ), 'TM' => esc_html__( 'Turkmenistan', ${3:text-domain} ), 'TC' => esc_html__( 'Turks and Caicos Islands', ${3:text-domain} ), 'TV' => esc_html__( 'Tuvalu', ${3:text-domain} ), 'UM' => esc_html__( 'U.S. Outlying Islands', ${3:text-domain} ), 'VI' => esc_html__( 'U.S. Virgin Islands', ${3:text-domain} ), 'UG' => esc_html__( 'Uganda', ${3:text-domain} ), 'UA' => esc_html__( 'Ukraine (Україна)', ${3:text-domain} ), 'AE' => esc_html__( 'United Arab Emirates (‫الإمارات العربية المتحدة‬‎)', ${3:text-domain} ), 'GB' => esc_html__( 'United Kingdom', ${3:text-domain} ), 'US' => esc_html__( 'United States', ${3:text-domain} ), 'UY' => esc_html__( 'Uruguay', ${3:text-domain} ), 'UZ' => esc_html__( 'Uzbekistan (Oʻzbekiston)', ${3:text-domain} ), 'VU' => esc_html__( 'Vanuatu', ${3:text-domain} ), 'VA' => esc_html__( 'Vatican City (Città del Vaticano)', ${3:text-domain} ), 'VE' => esc_html__( 'Venezuela', ${3:text-domain} ), 'VN' => esc_html__( 'Vietnam (Việt Nam)', ${3:text-domain} ), 'WF' => esc_html__( 'Wallis and Futuna', ${3:text-domain} ), 'EH' => esc_html__( 'Western Sahara (‫الصحراء الغربية‬‎)', ${3:text-domain} ), 'YE' => esc_html__( 'Yemen (‫اليمن‬‎)', ${3:text-domain} ), 'ZM' => esc_html__( 'Zambia', ${3:text-domain} ), 'ZW' => esc_html__( 'Zimbabwe', ${3:text-domain} ), ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerUSStates": "prefix": "wpcus" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'AL' => esc_html__( 'Alabama', ${3:text-domain} ), 'AK' => esc_html__( 'Alaska', ${3:text-domain} ), 'AZ' => esc_html__( 'Arizona', ${3:text-domain} ), 'AR' => esc_html__( 'Arkansas', ${3:text-domain} ), 'CA' => esc_html__( 'California', ${3:text-domain} ), 'CO' => esc_html__( 'Colorado', ${3:text-domain} ), 'CT' => esc_html__( 'Connecticut', ${3:text-domain} ), 'DE' => esc_html__( 'Delaware', ${3:text-domain} ), 'DC' => esc_html__( 'District of Columbia', ${3:text-domain} ), 'FL' => esc_html__( 'Florida', ${3:text-domain} ), 'GA' => esc_html__( 'Georgia', ${3:text-domain} ), 'HI' => esc_html__( 'Hawaii', ${3:text-domain} ), 'ID' => esc_html__( 'Idaho', ${3:text-domain} ), 'IL' => esc_html__( 'Illinois', ${3:text-domain} ), 'IN' => esc_html__( 'Indiana', ${3:text-domain} ), 'IA' => esc_html__( 'Iowa', ${3:text-domain} ), 'KS' => esc_html__( 'Kansas', ${3:text-domain} ), 'KY' => esc_html__( 'Kentucky', ${3:text-domain} ), 'LA' => esc_html__( 'Louisiana', ${3:text-domain} ), 'ME' => esc_html__( 'Maine', ${3:text-domain} ), 'MD' => esc_html__( 'Maryland', ${3:text-domain} ), 'MA' => esc_html__( 'Massachusetts', ${3:text-domain} ), 'MI' => esc_html__( 'Michigan', ${3:text-domain} ), 'MN' => esc_html__( 'Minnesota', ${3:text-domain} ), 'MS' => esc_html__( 'Mississippi', ${3:text-domain} ), 'MO' => esc_html__( 'Missouri', ${3:text-domain} ), 'MT' => esc_html__( 'Montana', ${3:text-domain} ), 'NE' => esc_html__( 'Nebraska', ${3:text-domain} ), 'NV' => esc_html__( 'Nevada', ${3:text-domain} ), 'NH' => esc_html__( 'New Hampshire', ${3:text-domain} ), 'NJ' => esc_html__( 'New Jersey', ${3:text-domain} ), 'NM' => esc_html__( 'New Mexico', ${3:text-domain} ), 'NY' => esc_html__( 'New York', ${3:text-domain} ), 'NC' => esc_html__( 'North Carolina', ${3:text-domain} ), 'ND' => esc_html__( 'North Dakota', ${3:text-domain} ), 'OH' => esc_html__( 'Ohio', ${3:text-domain} ), 'OK' => esc_html__( 'Oklahoma', ${3:text-domain} ), 'OR' => esc_html__( 'Oregon', ${3:text-domain} ), 'PA' => esc_html__( 'Pennsylvania', ${3:text-domain} ), 'RI' => esc_html__( 'Rhode Island', ${3:text-domain} ), 'SC' => esc_html__( 'South Carolina', ${3:text-domain} ), 'SD' => esc_html__( 'South Dakota', ${3:text-domain} ), 'TN' => esc_html__( 'Tennessee', ${3:text-domain} ), 'TX' => esc_html__( 'Texas', ${3:text-domain} ), 'UT' => esc_html__( 'Utah', ${3:text-domain} ), 'VT' => esc_html__( 'Vermont', ${3:text-domain} ), 'VA' => esc_html__( 'Virginia', ${3:text-domain} ), 'WA' => esc_html__( 'Washington', ${3:text-domain} ), 'WV' => esc_html__( 'West Virginia', ${3:text-domain} ), 'WI' => esc_html__( 'Wisconsin', ${3:text-domain} ), 'WY' => esc_html__( 'Wyoming', ${3:text-domain} ), 'AS' => esc_html__( 'American Samoa', ${3:text-domain} ), 'AA' => esc_html__( 'Armed Forces America (except Canada)', ${3:text-domain} ), 'AE' => esc_html__( 'Armed Forces Africa/Canada/Europe/Middle East', ${3:text-domain} ), 'AP' => esc_html__( 'Armed Forces Pacific', ${3:text-domain} ), 'FM' => esc_html__( 'Federated States of Micronesia', ${3:text-domain} ), 'GU' => esc_html__( 'Guam', ${3:text-domain} ), 'MH' => esc_html__( 'Marshall Islands', ${3:text-domain} ), 'MP' => esc_html__( 'Northern Mariana Islands', ${3:text-domain} ), 'PR' => esc_html__( 'Puerto Rico', ${3:text-domain} ), 'PW' => esc_html__( 'Palau', ${3:text-domain} ), 'VI' => esc_html__( 'Virgin Islands', ${3:text-domain} ) ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerCanadianStates": "prefix": "wpccanada" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'AB' => esc_html__( 'Alberta', '${3:text-domain}' ), 'BC' => esc_html__( 'British Columbia', '${3:text-domain}' ), 'MB' => esc_html__( 'Manitoba', '${3:text-domain}' ), 'NB' => esc_html__( 'New Brunswick', '${3:text-domain}' ), 'NL' => esc_html__( 'Newfoundland and Labrador', '${3:text-domain}' ), 'NT' => esc_html__( 'Northwest Territories', '${3:text-domain}' ), 'NS' => esc_html__( 'Nova Scotia', '${3:text-domain}' ), 'NU' => esc_html__( 'Nunavut', '${3:text-domain}' ), 'ON' => esc_html__( 'Ontario', '${3:text-domain}' ), 'PE' => esc_html__( 'Prince Edward Island', '${3:text-domain}' ), 'QC' => esc_html__( 'Quebec', '${3:text-domain}' ), 'SK' => esc_html__( 'Saskatchewan', '${3:text-domain}' ), 'YT' => esc_html__( 'Yukon', '${3:text-domain}' ) ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" "WPCustomizerAustralianStates": "prefix": "wpcaus" "body": """// ${1:field_name} Field $wp_customize->add_setting( '${2:field_id}', array( 'capability' => 'edit_theme_options', 'default' => '', 'transport' => 'postMessage', 'type' => 'theme_mod' ) ); $wp_customize->add_control( '${2:field_id}', array( 'active_callback' => '', 'choices' => array( 'ACT' => esc_html__( 'Australian Capital Territory', '${3:text-domain}' ), 'NSW' => esc_html__( 'New South Wales', '${3:text-domain}' ), 'NT' => esc_html__( 'Northern Territory', '${3:text-domain}' ), 'QLD' => esc_html__( 'Queensland', '${3:text-domain}' ), 'SA' => esc_html__( 'South Australia', '${3:text-domain}' ), 'TAS' => esc_html__( 'Tasmania', '${3:text-domain}' ), 'VIC' => esc_html__( 'Victoria', '${3:text-domain}' ), 'WA' => esc_html__( 'Western Australia', '${3:text-domain}' ) ), 'description' => esc_html__( '${4:description}', '${3:text-domain}' ), 'label' => esc_html__( '${1:field_name}', '${3:text-domain}' ), 'priority' => 10, 'section' => '${5:section_id}', 'settings' => '${2:field_id}', 'type' => 'select' ) ); $wp_customize->get_setting( '${2:field_id}' )->transport = 'postMessage';""" ".source.js": "WPCustomizerBasicJS": "prefix": "wpcjs" "body": """// ${1:setting_name}. wp.customize( '${2:setting_id}', function( value ) { value.bind( function( to ) { $( '${3:id_or_class}' ).text( to ); } ); } );"""
[ { "context": "t {View} from './reducer.coffee'\n\neditPasscode = 'd3ef743cf28c7bf034bb6ca97c19028049c8bf135aa89974d62b62b8aabc072b'\n\n# import why from 'why-did-you-update'\n# why Re", "end": 622, "score": 0.9960765242576599, "start": 558, "tag": "PASSWORD", "value": "d3ef743cf28c7bf034bb6c...
app/containers/start/index.coffee
samerce/purplerepublic.us
1
import React from 'react' import Astrology from '../../components/Astrology/index.coffee' import Gaiaverse from '../../components/Gaiaverse/index.coffee' import Intro from '../../components/Intro' import Fruit from '../../components/Fruit/index.coffee' import { Root, } from './styled' import {setStartView} from './actions.coffee' import {canShowEditingTools} from '../../utils/nav' import sha256 from 'tiny-sha256' import {connect} from 'react-redux' import {addHashHandler} from '../App/actions' import {View} from './reducer.coffee' editPasscode = 'd3ef743cf28c7bf034bb6ca97c19028049c8bf135aa89974d62b62b8aabc072b' # import why from 'why-did-you-update' # why React export default connect((d) -> view: d.get('start').get('view'), portals: d.get('gaiaverse').get('portals'), ) class Start extends React.Component constructor: (props) -> super(props) props.dispatch addHashHandler { trigger: '#/', onEnter: @onHashChange, onChange: @onHashChange, onExit: ->, } if process.env.NODE_ENV is 'production' and canShowEditingTools() passcode = prompt('passcode, madam?') or '' if !passcode.length or sha256(passcode) isnt editPasscode alert('no entry fo yew.') window.location.href = window.location.href.replace('edit.', '') shouldComponentUpdate: -> no render: -> <Root> <Intro /> <Gaiaverse /> <Astrology /> <Fruit /> </Root> onHashChange: => {view, dispatch} = @props {hash} = window.location hashParts = hash.split '/' return unless hashParts.length > 1 return if view is View.intro if not hashParts[1] dispatch setStartView(View.cosmos) else energy = hashParts[1] if hashParts.length is 2 dispatch setStartView(View.triangle, {energy}) else quark = hashParts[2] dispatch setStartView(View.quark, { quark: quark, energy: energy, anchor: @findAnchor(quark), }) findAnchor: (quark) => anchor for spot, portal of @props.portals anchor = spot if portal.id is quark anchor
221005
import React from 'react' import Astrology from '../../components/Astrology/index.coffee' import Gaiaverse from '../../components/Gaiaverse/index.coffee' import Intro from '../../components/Intro' import Fruit from '../../components/Fruit/index.coffee' import { Root, } from './styled' import {setStartView} from './actions.coffee' import {canShowEditingTools} from '../../utils/nav' import sha256 from 'tiny-sha256' import {connect} from 'react-redux' import {addHashHandler} from '../App/actions' import {View} from './reducer.coffee' editPasscode = '<PASSWORD>' # import why from 'why-did-you-update' # why React export default connect((d) -> view: d.get('start').get('view'), portals: d.get('gaiaverse').get('portals'), ) class Start extends React.Component constructor: (props) -> super(props) props.dispatch addHashHandler { trigger: '#/', onEnter: @onHashChange, onChange: @onHashChange, onExit: ->, } if process.env.NODE_ENV is 'production' and canShowEditingTools() passcode = prompt('passcode, madam?') or '' if !passcode.length or sha256(passcode) isnt editPasscode alert('no entry fo yew.') window.location.href = window.location.href.replace('edit.', '') shouldComponentUpdate: -> no render: -> <Root> <Intro /> <Gaiaverse /> <Astrology /> <Fruit /> </Root> onHashChange: => {view, dispatch} = @props {hash} = window.location hashParts = hash.split '/' return unless hashParts.length > 1 return if view is View.intro if not hashParts[1] dispatch setStartView(View.cosmos) else energy = hashParts[1] if hashParts.length is 2 dispatch setStartView(View.triangle, {energy}) else quark = hashParts[2] dispatch setStartView(View.quark, { quark: quark, energy: energy, anchor: @findAnchor(quark), }) findAnchor: (quark) => anchor for spot, portal of @props.portals anchor = spot if portal.id is quark anchor
true
import React from 'react' import Astrology from '../../components/Astrology/index.coffee' import Gaiaverse from '../../components/Gaiaverse/index.coffee' import Intro from '../../components/Intro' import Fruit from '../../components/Fruit/index.coffee' import { Root, } from './styled' import {setStartView} from './actions.coffee' import {canShowEditingTools} from '../../utils/nav' import sha256 from 'tiny-sha256' import {connect} from 'react-redux' import {addHashHandler} from '../App/actions' import {View} from './reducer.coffee' editPasscode = 'PI:PASSWORD:<PASSWORD>END_PI' # import why from 'why-did-you-update' # why React export default connect((d) -> view: d.get('start').get('view'), portals: d.get('gaiaverse').get('portals'), ) class Start extends React.Component constructor: (props) -> super(props) props.dispatch addHashHandler { trigger: '#/', onEnter: @onHashChange, onChange: @onHashChange, onExit: ->, } if process.env.NODE_ENV is 'production' and canShowEditingTools() passcode = prompt('passcode, madam?') or '' if !passcode.length or sha256(passcode) isnt editPasscode alert('no entry fo yew.') window.location.href = window.location.href.replace('edit.', '') shouldComponentUpdate: -> no render: -> <Root> <Intro /> <Gaiaverse /> <Astrology /> <Fruit /> </Root> onHashChange: => {view, dispatch} = @props {hash} = window.location hashParts = hash.split '/' return unless hashParts.length > 1 return if view is View.intro if not hashParts[1] dispatch setStartView(View.cosmos) else energy = hashParts[1] if hashParts.length is 2 dispatch setStartView(View.triangle, {energy}) else quark = hashParts[2] dispatch setStartView(View.quark, { quark: quark, energy: energy, anchor: @findAnchor(quark), }) findAnchor: (quark) => anchor for spot, portal of @props.portals anchor = spot if portal.id is quark anchor
[ { "context": "sValid() returned false.) Reverting! Please notify team@codecombat.com.\")\n me.set 'savedEmployerFilterAlerts', me.p", "end": 5442, "score": 0.9999287724494934, "start": 5423, "tag": "EMAIL", "value": "team@codecombat.com" }, { "context": "s an error saving your f...
app/views/EmployersView.coffee
rodeofly/rodeofly.github.io
0
RootView = require 'views/kinds/RootView' template = require 'templates/employers' User = require 'models/User' {me} = require 'lib/auth' CocoCollection = require 'collections/CocoCollection' EmployerSignupModal = require 'views/modal/EmployerSignupModal' class CandidatesCollection extends CocoCollection url: '/db/user/x/candidates' model: User module.exports = class EmployersView extends RootView id: 'employers-view' template: template events: 'click #candidate-table': 'onCandidateClicked' 'click #logout-link': 'logoutAccount' 'change #filters input': 'onFilterChanged' 'change #select_all_checkbox': 'handleSelectAllChange' 'click .get-started-button': 'openSignupModal' 'click .navbar-brand': 'restoreBodyColor' 'click #login-link': 'onClickAuthButton' 'click #filter-link': 'swapFolderIcon' 'click #create-alert-button': 'createFilterAlert' 'click .deletion-col': 'deleteFilterAlert' constructor: (options) -> super options @candidates = @supermodel.loadCollection(new CandidatesCollection(), 'candidates').model @setFilterDefaults() onLoaded: -> super() @setUpScrolling() afterRender: -> super() @sortTable() if @candidates.models.length @renderSavedFilters() afterInsert: -> super() _.delay @checkForEmployerSignupHash, 500 #fairly hacky, change this in the future @originalBackgroundColor = $('body').css 'background-color' $('body').css 'background-color', '#B4B4B4' restoreBodyColor: -> $('body').css 'background-color', @originalBackgroundColor swapFolderIcon: -> $('#folder-icon').toggleClass('glyphicon-folder-close').toggleClass('glyphicon-folder-open') onFilterChanged: -> @resetFilters() that = @ $('#filters :input').each -> input = $(this) checked = input.prop 'checked' name = input.attr 'name' value = input.val() if name is 'phoneScreenFilter' value = JSON.parse(input.prop 'value') if checked that.filters[name] = _.union that.filters[name], [value] else that.filters[name] = _.difference that.filters[name], [value] for filterName, filterValues of @filters if filterValues.length is 0 @filters[filterName] = @defaultFilters[filterName] @applyFilters() openSignupModal: -> @openModalView new EmployerSignupModal handleSelectAllChange: (e) -> checkedState = e.currentTarget.checked $('#filters :input').each -> $(this).prop 'checked', checkedState @onFilterChanged() resetFilters: -> for filterName, filterValues of @filters @filters[filterName] = [] applyFilters: -> candidateList = _.sortBy @candidates.models, (c) -> c.get('jobProfile').updated candidateList = _.filter candidateList, (c) -> c.get('jobProfileApproved') filteredCandidates = candidateList for filterName, filterValues of @filters if filterName is 'visa' filteredCandidates = _.difference filteredCandidates, _.filter(filteredCandidates, (c) -> fieldValue = c.get('jobProfile').visa return not (_.contains filterValues, fieldValue) ) else filteredCandidates = _.difference filteredCandidates, _.filter(filteredCandidates, (c) -> unless c.get('jobProfile').curated then return true fieldValue = c.get('jobProfile').curated?[filterName] return not (_.contains filterValues, fieldValue) ) candidateIDsToShow = _.pluck filteredCandidates, 'id' $('#candidate-table tr').each -> $(this).hide() candidateIDsToShow.forEach (id) -> $("[data-candidate-id=#{id}]").show() $('#results').text(candidateIDsToShow.length + ' results') return filteredCandidates setFilterDefaults: -> @filters = phoneScreenFilter: [true, false] visa: ['Authorized to work in the US', 'Need visa sponsorship'] schoolFilter: ['Top School', 'Other'] locationFilter: ['Bay Area', 'New York', 'Other US', 'International'] roleFilter: ['Web Developer', 'Software Developer', 'Mobile Developer'] seniorityFilter: ['College Student', 'Recent Grad', 'Junior', 'Senior'] @defaultFilters = _.cloneDeep @filters candidatesInFilter: (filterName, filterValue) => candidates = @getActiveAndApprovedCandidates() if filterName and filterValue if filterName is 'visa' return (_.filter candidates, (c) -> c.get('jobProfile').visa is filterValue).length else return (_.filter candidates, (c) -> c.get('jobProfile').curated?[filterName] is filterValue).length else return Math.floor(Math.random() * 500) createFilterAlert: -> currentFilterSet = _.cloneDeep @filters currentSavedFilters = _.cloneDeep me.get('savedEmployerFilterAlerts') ? [] currentSavedFilters.push currentFilterSet @patchEmployerFilterAlerts currentSavedFilters, @renderSavedFilters deleteFilterAlert: (e) -> index = $(e.target).closest('tbody tr').data('filter-index') currentSavedFilters = me.get('savedEmployerFilterAlerts') currentSavedFilters.splice(index,1) @patchEmployerFilterAlerts currentSavedFilters, @renderSavedFilters patchEmployerFilterAlerts: (newFilters, cb) -> me.set('savedEmployerFilterAlerts',newFilters) unless me.isValid() alert("There was an error setting the filter(me.isValid() returned false.) Reverting! Please notify team@codecombat.com.") me.set 'savedEmployerFilterAlerts', me.previous('savedEmployerFilterAlerts') else triggerErrorAlert = -> alert("There was an error saving your filter alert! Please notify team@codecombat.com.") res = me.save {"savedEmployerFilterAlerts": newFilters}, {patch: true, type: 'PUT', success: cb, error: triggerErrorAlert} renderSavedFilters: => savedFilters = me.get('savedEmployerFilterAlerts') unless savedFilters?.length then return $("#saved-filter-table").hide() $("#saved-filter-table").show() $("#saved-filter-table").find("tbody tr").remove() for filter, index in savedFilters $("#saved-filter-table tbody").append("""<tr data-filter-index="#{index}"><td>#{@generateFilterAlertDescription(filter)}</td><td class="deletion-col"><a>✗</a></td></tr> """) generateFilterAlertDescription: (filter) => descriptionString = "" for key in _.keys(filter).sort() value = filter[key] if key is "filterActive" or _.without(@defaultFilters[key],value...).length is 0 then continue if descriptionString.length then descriptionString += ", " descriptionString += value.join(", ") if descriptionString.length is 0 then descriptionString = "Any new candidate" return descriptionString getActiveAndApprovedCandidates: => candidates = _.filter @candidates.models, (c) -> c.get('jobProfile').active return _.filter candidates, (c) -> c.get('jobProfileApproved') getRenderData: -> ctx = super() ctx.isEmployer = @isEmployer() #If you change the candidates displayed, change candidatesInFilter() ctx.candidates = _.sortBy @candidates.models, (c) -> -1 * c.get('jobProfile').experience ctx.candidates = _.sortBy ctx.candidates, (c) -> not c.get('jobProfile').curated? ctx.candidates = _.sortBy ctx.candidates, (c) -> c.get('jobProfile').curated?.featured ctx.activeCandidates = _.filter ctx.candidates, (c) -> c.get('jobProfile').active ctx.inactiveCandidates = _.reject ctx.candidates, (c) -> c.get('jobProfile').active ctx.featuredCandidates = _.filter ctx.activeCandidates, (c) -> c.get('jobProfileApproved') unless @isEmployer() or me.isAdmin() ctx.featuredCandidates = _.filter ctx.featuredCandidates, (c) -> c.get('jobProfile').curated ctx.featuredCandidates = ctx.featuredCandidates.slice(0,7) if me.isAdmin() ctx.featuredCandidates = ctx.candidates ctx.candidatesInFilter = @candidatesInFilter ctx.otherCandidates = _.reject ctx.activeCandidates, (c) -> c.get('jobProfileApproved') ctx.moment = moment ctx._ = _ ctx.numberOfCandidates = ctx.featuredCandidates.length ctx isEmployer: -> 'employer' in me.get('permissions', true) setUpScrolling: => $('.nano').nanoScroller() #if window.history?.state?.lastViewedCandidateID # $('.nano').nanoScroller({scrollTo: $('#' + window.history.state.lastViewedCandidateID)}) #else if window.location.hash.length is 25 # $('.nano').nanoScroller({scrollTo: $(window.location.hash)}) checkForEmployerSignupHash: => if window.location.hash is '#employerSignupLoggingIn' and not ('employer' in me.get('permissions', true)) and not me.isAdmin() @openModalView new EmployerSignupModal window.location.hash = '' sortTable: -> # http://mottie.github.io/tablesorter/docs/example-widget-bootstrap-theme.html $.extend $.tablesorter.themes.bootstrap, # these classes are added to the table. To see other table classes available, # look here: http://twitter.github.com/bootstrap/base-css.html#tables table: 'table table-bordered' caption: 'caption' header: 'bootstrap-header' # give the header a gradient background footerRow: '' footerCells: '' icons: '' # add 'icon-white' to make them white; this icon class is added to the <i> in the header sortNone: 'bootstrap-icon-unsorted' sortAsc: 'icon-chevron-up' # glyphicon glyphicon-chevron-up' # we are still using v2 icons sortDesc: 'icon-chevron-down' # glyphicon-chevron-down' # we are still using v2 icons active: '' # applied when column is sorted hover: '' # use custom css here - bootstrap class may not override it filterRow: '' # filter row class even: '' # odd row zebra striping odd: '' # even row zebra striping # e = exact text from cell # n = normalized value returned by the column parser # f = search filter input value # i = column index # $r = ??? filterSelectExactMatch = (e, n, f, i, $r) -> e is f # call the tablesorter plugin and apply the uitheme widget @$el.find('.tablesorter').tablesorter theme: 'bootstrap' widthFixed: true headerTemplate: '{content} {icon}' textSorter: 6: (a, b, direction, column, table) -> days = [] for s in [a, b] n = parseInt s n = 0 unless _.isNumber n n = 1 if /^a/.test s for [duration, factor] in [ [/second/i, 1/(86400*1000)] [/minute/i, 1/1440] [/hour/i, 1/24] [/week/i, 7] [/month/i, 30.42] [/year/i, 365.2425] ] if duration.test s n *= factor break if /^in /i.test s n *= -1 days.push n days[0] - days[1] sortList: if @isEmployer() or me.isAdmin() then [[6, 0]] else [[0, 1]] # widget code contained in the jquery.tablesorter.widgets.js file # use the zebra stripe widget if you plan on hiding any rows (filter widget) widgets: ['uitheme', 'zebra', 'filter'] widgetOptions: # using the default zebra striping class name, so it actually isn't included in the theme variable above # this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden zebra: ['even', 'odd'] # extra css class applied to the table row containing the filters & the inputs within that row filter_cssFilter: '' # If there are child rows in the table (rows with class name from 'cssChildRow' option) # and this option is true and a match is found anywhere in the child row, then it will make that row # visible; default is false filter_childRows: false # if true, filters are collapsed initially, but can be revealed by hovering over the grey bar immediately # below the header row. Additionally, tabbing through the document will open the filter row when an input gets focus filter_hideFilters: false # Set this option to false to make the searches case sensitive filter_ignoreCase: true # jQuery selector string of an element used to reset the filters filter_reset: '.reset' # Use the $.tablesorter.storage utility to save the most recent filters filter_saveFilters: true # Delay in milliseconds before the filter widget starts searching; This option prevents searching for # every character while typing and should make searching large tables faster. filter_searchDelay: 150 # Set this option to true to use the filter to find text from the start of the column # So typing in 'a' will find 'albert' but not 'frank', both have a's; default is false filter_startsWith: false filter_functions: 2: 'Full-time': filterSelectExactMatch 'Part-time': filterSelectExactMatch 'Contracting': filterSelectExactMatch 'Remote': filterSelectExactMatch 'Internship': filterSelectExactMatch 5: '0-1': (e, n, f, i, $r) -> n <= 1 '2-5': (e, n, f, i, $r) -> 2 <= n <= 5 '6+': (e, n, f, i, $r) -> 6 <= n 6: 'Last day': (e, n, f, i, $r) -> days = parseFloat $($r.find('td')[i]).data('profile-age') days <= 1 'Last week': (e, n, f, i, $r) -> days = parseFloat $($r.find('td')[i]).data('profile-age') days <= 7 'Last 4 weeks': (e, n, f, i, $r) -> days = parseFloat $($r.find('td')[i]).data('profile-age') days <= 28 8: '✓': filterSelectExactMatch '✗': filterSelectExactMatch logoutAccount: -> window.location.hash = '' super() onCandidateClicked: (e) -> id = $(e.target).closest('tr').data('candidate-id') if id and (@isEmployer() or me.isAdmin()) if window.history oldState = _.cloneDeep window.history.state ? {} oldState['lastViewedCandidateID'] = id window.history.replaceState(oldState, '') else window.location.hash = id url = "/account/profile/#{id}" window.open url, '_blank' else @openModalView new EmployerSignupModal
1190
RootView = require 'views/kinds/RootView' template = require 'templates/employers' User = require 'models/User' {me} = require 'lib/auth' CocoCollection = require 'collections/CocoCollection' EmployerSignupModal = require 'views/modal/EmployerSignupModal' class CandidatesCollection extends CocoCollection url: '/db/user/x/candidates' model: User module.exports = class EmployersView extends RootView id: 'employers-view' template: template events: 'click #candidate-table': 'onCandidateClicked' 'click #logout-link': 'logoutAccount' 'change #filters input': 'onFilterChanged' 'change #select_all_checkbox': 'handleSelectAllChange' 'click .get-started-button': 'openSignupModal' 'click .navbar-brand': 'restoreBodyColor' 'click #login-link': 'onClickAuthButton' 'click #filter-link': 'swapFolderIcon' 'click #create-alert-button': 'createFilterAlert' 'click .deletion-col': 'deleteFilterAlert' constructor: (options) -> super options @candidates = @supermodel.loadCollection(new CandidatesCollection(), 'candidates').model @setFilterDefaults() onLoaded: -> super() @setUpScrolling() afterRender: -> super() @sortTable() if @candidates.models.length @renderSavedFilters() afterInsert: -> super() _.delay @checkForEmployerSignupHash, 500 #fairly hacky, change this in the future @originalBackgroundColor = $('body').css 'background-color' $('body').css 'background-color', '#B4B4B4' restoreBodyColor: -> $('body').css 'background-color', @originalBackgroundColor swapFolderIcon: -> $('#folder-icon').toggleClass('glyphicon-folder-close').toggleClass('glyphicon-folder-open') onFilterChanged: -> @resetFilters() that = @ $('#filters :input').each -> input = $(this) checked = input.prop 'checked' name = input.attr 'name' value = input.val() if name is 'phoneScreenFilter' value = JSON.parse(input.prop 'value') if checked that.filters[name] = _.union that.filters[name], [value] else that.filters[name] = _.difference that.filters[name], [value] for filterName, filterValues of @filters if filterValues.length is 0 @filters[filterName] = @defaultFilters[filterName] @applyFilters() openSignupModal: -> @openModalView new EmployerSignupModal handleSelectAllChange: (e) -> checkedState = e.currentTarget.checked $('#filters :input').each -> $(this).prop 'checked', checkedState @onFilterChanged() resetFilters: -> for filterName, filterValues of @filters @filters[filterName] = [] applyFilters: -> candidateList = _.sortBy @candidates.models, (c) -> c.get('jobProfile').updated candidateList = _.filter candidateList, (c) -> c.get('jobProfileApproved') filteredCandidates = candidateList for filterName, filterValues of @filters if filterName is 'visa' filteredCandidates = _.difference filteredCandidates, _.filter(filteredCandidates, (c) -> fieldValue = c.get('jobProfile').visa return not (_.contains filterValues, fieldValue) ) else filteredCandidates = _.difference filteredCandidates, _.filter(filteredCandidates, (c) -> unless c.get('jobProfile').curated then return true fieldValue = c.get('jobProfile').curated?[filterName] return not (_.contains filterValues, fieldValue) ) candidateIDsToShow = _.pluck filteredCandidates, 'id' $('#candidate-table tr').each -> $(this).hide() candidateIDsToShow.forEach (id) -> $("[data-candidate-id=#{id}]").show() $('#results').text(candidateIDsToShow.length + ' results') return filteredCandidates setFilterDefaults: -> @filters = phoneScreenFilter: [true, false] visa: ['Authorized to work in the US', 'Need visa sponsorship'] schoolFilter: ['Top School', 'Other'] locationFilter: ['Bay Area', 'New York', 'Other US', 'International'] roleFilter: ['Web Developer', 'Software Developer', 'Mobile Developer'] seniorityFilter: ['College Student', 'Recent Grad', 'Junior', 'Senior'] @defaultFilters = _.cloneDeep @filters candidatesInFilter: (filterName, filterValue) => candidates = @getActiveAndApprovedCandidates() if filterName and filterValue if filterName is 'visa' return (_.filter candidates, (c) -> c.get('jobProfile').visa is filterValue).length else return (_.filter candidates, (c) -> c.get('jobProfile').curated?[filterName] is filterValue).length else return Math.floor(Math.random() * 500) createFilterAlert: -> currentFilterSet = _.cloneDeep @filters currentSavedFilters = _.cloneDeep me.get('savedEmployerFilterAlerts') ? [] currentSavedFilters.push currentFilterSet @patchEmployerFilterAlerts currentSavedFilters, @renderSavedFilters deleteFilterAlert: (e) -> index = $(e.target).closest('tbody tr').data('filter-index') currentSavedFilters = me.get('savedEmployerFilterAlerts') currentSavedFilters.splice(index,1) @patchEmployerFilterAlerts currentSavedFilters, @renderSavedFilters patchEmployerFilterAlerts: (newFilters, cb) -> me.set('savedEmployerFilterAlerts',newFilters) unless me.isValid() alert("There was an error setting the filter(me.isValid() returned false.) Reverting! Please notify <EMAIL>.") me.set 'savedEmployerFilterAlerts', me.previous('savedEmployerFilterAlerts') else triggerErrorAlert = -> alert("There was an error saving your filter alert! Please notify <EMAIL>.") res = me.save {"savedEmployerFilterAlerts": newFilters}, {patch: true, type: 'PUT', success: cb, error: triggerErrorAlert} renderSavedFilters: => savedFilters = me.get('savedEmployerFilterAlerts') unless savedFilters?.length then return $("#saved-filter-table").hide() $("#saved-filter-table").show() $("#saved-filter-table").find("tbody tr").remove() for filter, index in savedFilters $("#saved-filter-table tbody").append("""<tr data-filter-index="#{index}"><td>#{@generateFilterAlertDescription(filter)}</td><td class="deletion-col"><a>✗</a></td></tr> """) generateFilterAlertDescription: (filter) => descriptionString = "" for key in _.keys(filter).sort() value = filter[key] if key is "filterActive" or _.without(@defaultFilters[key],value...).length is 0 then continue if descriptionString.length then descriptionString += ", " descriptionString += value.join(", ") if descriptionString.length is 0 then descriptionString = "Any new candidate" return descriptionString getActiveAndApprovedCandidates: => candidates = _.filter @candidates.models, (c) -> c.get('jobProfile').active return _.filter candidates, (c) -> c.get('jobProfileApproved') getRenderData: -> ctx = super() ctx.isEmployer = @isEmployer() #If you change the candidates displayed, change candidatesInFilter() ctx.candidates = _.sortBy @candidates.models, (c) -> -1 * c.get('jobProfile').experience ctx.candidates = _.sortBy ctx.candidates, (c) -> not c.get('jobProfile').curated? ctx.candidates = _.sortBy ctx.candidates, (c) -> c.get('jobProfile').curated?.featured ctx.activeCandidates = _.filter ctx.candidates, (c) -> c.get('jobProfile').active ctx.inactiveCandidates = _.reject ctx.candidates, (c) -> c.get('jobProfile').active ctx.featuredCandidates = _.filter ctx.activeCandidates, (c) -> c.get('jobProfileApproved') unless @isEmployer() or me.isAdmin() ctx.featuredCandidates = _.filter ctx.featuredCandidates, (c) -> c.get('jobProfile').curated ctx.featuredCandidates = ctx.featuredCandidates.slice(0,7) if me.isAdmin() ctx.featuredCandidates = ctx.candidates ctx.candidatesInFilter = @candidatesInFilter ctx.otherCandidates = _.reject ctx.activeCandidates, (c) -> c.get('jobProfileApproved') ctx.moment = moment ctx._ = _ ctx.numberOfCandidates = ctx.featuredCandidates.length ctx isEmployer: -> 'employer' in me.get('permissions', true) setUpScrolling: => $('.nano').nanoScroller() #if window.history?.state?.lastViewedCandidateID # $('.nano').nanoScroller({scrollTo: $('#' + window.history.state.lastViewedCandidateID)}) #else if window.location.hash.length is 25 # $('.nano').nanoScroller({scrollTo: $(window.location.hash)}) checkForEmployerSignupHash: => if window.location.hash is '#employerSignupLoggingIn' and not ('employer' in me.get('permissions', true)) and not me.isAdmin() @openModalView new EmployerSignupModal window.location.hash = '' sortTable: -> # http://mottie.github.io/tablesorter/docs/example-widget-bootstrap-theme.html $.extend $.tablesorter.themes.bootstrap, # these classes are added to the table. To see other table classes available, # look here: http://twitter.github.com/bootstrap/base-css.html#tables table: 'table table-bordered' caption: 'caption' header: 'bootstrap-header' # give the header a gradient background footerRow: '' footerCells: '' icons: '' # add 'icon-white' to make them white; this icon class is added to the <i> in the header sortNone: 'bootstrap-icon-unsorted' sortAsc: 'icon-chevron-up' # glyphicon glyphicon-chevron-up' # we are still using v2 icons sortDesc: 'icon-chevron-down' # glyphicon-chevron-down' # we are still using v2 icons active: '' # applied when column is sorted hover: '' # use custom css here - bootstrap class may not override it filterRow: '' # filter row class even: '' # odd row zebra striping odd: '' # even row zebra striping # e = exact text from cell # n = normalized value returned by the column parser # f = search filter input value # i = column index # $r = ??? filterSelectExactMatch = (e, n, f, i, $r) -> e is f # call the tablesorter plugin and apply the uitheme widget @$el.find('.tablesorter').tablesorter theme: 'bootstrap' widthFixed: true headerTemplate: '{content} {icon}' textSorter: 6: (a, b, direction, column, table) -> days = [] for s in [a, b] n = parseInt s n = 0 unless _.isNumber n n = 1 if /^a/.test s for [duration, factor] in [ [/second/i, 1/(86400*1000)] [/minute/i, 1/1440] [/hour/i, 1/24] [/week/i, 7] [/month/i, 30.42] [/year/i, 365.2425] ] if duration.test s n *= factor break if /^in /i.test s n *= -1 days.push n days[0] - days[1] sortList: if @isEmployer() or me.isAdmin() then [[6, 0]] else [[0, 1]] # widget code contained in the jquery.tablesorter.widgets.js file # use the zebra stripe widget if you plan on hiding any rows (filter widget) widgets: ['uitheme', 'zebra', 'filter'] widgetOptions: # using the default zebra striping class name, so it actually isn't included in the theme variable above # this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden zebra: ['even', 'odd'] # extra css class applied to the table row containing the filters & the inputs within that row filter_cssFilter: '' # If there are child rows in the table (rows with class name from 'cssChildRow' option) # and this option is true and a match is found anywhere in the child row, then it will make that row # visible; default is false filter_childRows: false # if true, filters are collapsed initially, but can be revealed by hovering over the grey bar immediately # below the header row. Additionally, tabbing through the document will open the filter row when an input gets focus filter_hideFilters: false # Set this option to false to make the searches case sensitive filter_ignoreCase: true # jQuery selector string of an element used to reset the filters filter_reset: '.reset' # Use the $.tablesorter.storage utility to save the most recent filters filter_saveFilters: true # Delay in milliseconds before the filter widget starts searching; This option prevents searching for # every character while typing and should make searching large tables faster. filter_searchDelay: 150 # Set this option to true to use the filter to find text from the start of the column # So typing in 'a' will find '<NAME>' but not '<NAME>', both have a's; default is false filter_startsWith: false filter_functions: 2: 'Full-time': filterSelectExactMatch 'Part-time': filterSelectExactMatch 'Contracting': filterSelectExactMatch 'Remote': filterSelectExactMatch 'Internship': filterSelectExactMatch 5: '0-1': (e, n, f, i, $r) -> n <= 1 '2-5': (e, n, f, i, $r) -> 2 <= n <= 5 '6+': (e, n, f, i, $r) -> 6 <= n 6: 'Last day': (e, n, f, i, $r) -> days = parseFloat $($r.find('td')[i]).data('profile-age') days <= 1 'Last week': (e, n, f, i, $r) -> days = parseFloat $($r.find('td')[i]).data('profile-age') days <= 7 'Last 4 weeks': (e, n, f, i, $r) -> days = parseFloat $($r.find('td')[i]).data('profile-age') days <= 28 8: '✓': filterSelectExactMatch '✗': filterSelectExactMatch logoutAccount: -> window.location.hash = '' super() onCandidateClicked: (e) -> id = $(e.target).closest('tr').data('candidate-id') if id and (@isEmployer() or me.isAdmin()) if window.history oldState = _.cloneDeep window.history.state ? {} oldState['lastViewedCandidateID'] = id window.history.replaceState(oldState, '') else window.location.hash = id url = "/account/profile/#{id}" window.open url, '_blank' else @openModalView new EmployerSignupModal
true
RootView = require 'views/kinds/RootView' template = require 'templates/employers' User = require 'models/User' {me} = require 'lib/auth' CocoCollection = require 'collections/CocoCollection' EmployerSignupModal = require 'views/modal/EmployerSignupModal' class CandidatesCollection extends CocoCollection url: '/db/user/x/candidates' model: User module.exports = class EmployersView extends RootView id: 'employers-view' template: template events: 'click #candidate-table': 'onCandidateClicked' 'click #logout-link': 'logoutAccount' 'change #filters input': 'onFilterChanged' 'change #select_all_checkbox': 'handleSelectAllChange' 'click .get-started-button': 'openSignupModal' 'click .navbar-brand': 'restoreBodyColor' 'click #login-link': 'onClickAuthButton' 'click #filter-link': 'swapFolderIcon' 'click #create-alert-button': 'createFilterAlert' 'click .deletion-col': 'deleteFilterAlert' constructor: (options) -> super options @candidates = @supermodel.loadCollection(new CandidatesCollection(), 'candidates').model @setFilterDefaults() onLoaded: -> super() @setUpScrolling() afterRender: -> super() @sortTable() if @candidates.models.length @renderSavedFilters() afterInsert: -> super() _.delay @checkForEmployerSignupHash, 500 #fairly hacky, change this in the future @originalBackgroundColor = $('body').css 'background-color' $('body').css 'background-color', '#B4B4B4' restoreBodyColor: -> $('body').css 'background-color', @originalBackgroundColor swapFolderIcon: -> $('#folder-icon').toggleClass('glyphicon-folder-close').toggleClass('glyphicon-folder-open') onFilterChanged: -> @resetFilters() that = @ $('#filters :input').each -> input = $(this) checked = input.prop 'checked' name = input.attr 'name' value = input.val() if name is 'phoneScreenFilter' value = JSON.parse(input.prop 'value') if checked that.filters[name] = _.union that.filters[name], [value] else that.filters[name] = _.difference that.filters[name], [value] for filterName, filterValues of @filters if filterValues.length is 0 @filters[filterName] = @defaultFilters[filterName] @applyFilters() openSignupModal: -> @openModalView new EmployerSignupModal handleSelectAllChange: (e) -> checkedState = e.currentTarget.checked $('#filters :input').each -> $(this).prop 'checked', checkedState @onFilterChanged() resetFilters: -> for filterName, filterValues of @filters @filters[filterName] = [] applyFilters: -> candidateList = _.sortBy @candidates.models, (c) -> c.get('jobProfile').updated candidateList = _.filter candidateList, (c) -> c.get('jobProfileApproved') filteredCandidates = candidateList for filterName, filterValues of @filters if filterName is 'visa' filteredCandidates = _.difference filteredCandidates, _.filter(filteredCandidates, (c) -> fieldValue = c.get('jobProfile').visa return not (_.contains filterValues, fieldValue) ) else filteredCandidates = _.difference filteredCandidates, _.filter(filteredCandidates, (c) -> unless c.get('jobProfile').curated then return true fieldValue = c.get('jobProfile').curated?[filterName] return not (_.contains filterValues, fieldValue) ) candidateIDsToShow = _.pluck filteredCandidates, 'id' $('#candidate-table tr').each -> $(this).hide() candidateIDsToShow.forEach (id) -> $("[data-candidate-id=#{id}]").show() $('#results').text(candidateIDsToShow.length + ' results') return filteredCandidates setFilterDefaults: -> @filters = phoneScreenFilter: [true, false] visa: ['Authorized to work in the US', 'Need visa sponsorship'] schoolFilter: ['Top School', 'Other'] locationFilter: ['Bay Area', 'New York', 'Other US', 'International'] roleFilter: ['Web Developer', 'Software Developer', 'Mobile Developer'] seniorityFilter: ['College Student', 'Recent Grad', 'Junior', 'Senior'] @defaultFilters = _.cloneDeep @filters candidatesInFilter: (filterName, filterValue) => candidates = @getActiveAndApprovedCandidates() if filterName and filterValue if filterName is 'visa' return (_.filter candidates, (c) -> c.get('jobProfile').visa is filterValue).length else return (_.filter candidates, (c) -> c.get('jobProfile').curated?[filterName] is filterValue).length else return Math.floor(Math.random() * 500) createFilterAlert: -> currentFilterSet = _.cloneDeep @filters currentSavedFilters = _.cloneDeep me.get('savedEmployerFilterAlerts') ? [] currentSavedFilters.push currentFilterSet @patchEmployerFilterAlerts currentSavedFilters, @renderSavedFilters deleteFilterAlert: (e) -> index = $(e.target).closest('tbody tr').data('filter-index') currentSavedFilters = me.get('savedEmployerFilterAlerts') currentSavedFilters.splice(index,1) @patchEmployerFilterAlerts currentSavedFilters, @renderSavedFilters patchEmployerFilterAlerts: (newFilters, cb) -> me.set('savedEmployerFilterAlerts',newFilters) unless me.isValid() alert("There was an error setting the filter(me.isValid() returned false.) Reverting! Please notify PI:EMAIL:<EMAIL>END_PI.") me.set 'savedEmployerFilterAlerts', me.previous('savedEmployerFilterAlerts') else triggerErrorAlert = -> alert("There was an error saving your filter alert! Please notify PI:EMAIL:<EMAIL>END_PI.") res = me.save {"savedEmployerFilterAlerts": newFilters}, {patch: true, type: 'PUT', success: cb, error: triggerErrorAlert} renderSavedFilters: => savedFilters = me.get('savedEmployerFilterAlerts') unless savedFilters?.length then return $("#saved-filter-table").hide() $("#saved-filter-table").show() $("#saved-filter-table").find("tbody tr").remove() for filter, index in savedFilters $("#saved-filter-table tbody").append("""<tr data-filter-index="#{index}"><td>#{@generateFilterAlertDescription(filter)}</td><td class="deletion-col"><a>✗</a></td></tr> """) generateFilterAlertDescription: (filter) => descriptionString = "" for key in _.keys(filter).sort() value = filter[key] if key is "filterActive" or _.without(@defaultFilters[key],value...).length is 0 then continue if descriptionString.length then descriptionString += ", " descriptionString += value.join(", ") if descriptionString.length is 0 then descriptionString = "Any new candidate" return descriptionString getActiveAndApprovedCandidates: => candidates = _.filter @candidates.models, (c) -> c.get('jobProfile').active return _.filter candidates, (c) -> c.get('jobProfileApproved') getRenderData: -> ctx = super() ctx.isEmployer = @isEmployer() #If you change the candidates displayed, change candidatesInFilter() ctx.candidates = _.sortBy @candidates.models, (c) -> -1 * c.get('jobProfile').experience ctx.candidates = _.sortBy ctx.candidates, (c) -> not c.get('jobProfile').curated? ctx.candidates = _.sortBy ctx.candidates, (c) -> c.get('jobProfile').curated?.featured ctx.activeCandidates = _.filter ctx.candidates, (c) -> c.get('jobProfile').active ctx.inactiveCandidates = _.reject ctx.candidates, (c) -> c.get('jobProfile').active ctx.featuredCandidates = _.filter ctx.activeCandidates, (c) -> c.get('jobProfileApproved') unless @isEmployer() or me.isAdmin() ctx.featuredCandidates = _.filter ctx.featuredCandidates, (c) -> c.get('jobProfile').curated ctx.featuredCandidates = ctx.featuredCandidates.slice(0,7) if me.isAdmin() ctx.featuredCandidates = ctx.candidates ctx.candidatesInFilter = @candidatesInFilter ctx.otherCandidates = _.reject ctx.activeCandidates, (c) -> c.get('jobProfileApproved') ctx.moment = moment ctx._ = _ ctx.numberOfCandidates = ctx.featuredCandidates.length ctx isEmployer: -> 'employer' in me.get('permissions', true) setUpScrolling: => $('.nano').nanoScroller() #if window.history?.state?.lastViewedCandidateID # $('.nano').nanoScroller({scrollTo: $('#' + window.history.state.lastViewedCandidateID)}) #else if window.location.hash.length is 25 # $('.nano').nanoScroller({scrollTo: $(window.location.hash)}) checkForEmployerSignupHash: => if window.location.hash is '#employerSignupLoggingIn' and not ('employer' in me.get('permissions', true)) and not me.isAdmin() @openModalView new EmployerSignupModal window.location.hash = '' sortTable: -> # http://mottie.github.io/tablesorter/docs/example-widget-bootstrap-theme.html $.extend $.tablesorter.themes.bootstrap, # these classes are added to the table. To see other table classes available, # look here: http://twitter.github.com/bootstrap/base-css.html#tables table: 'table table-bordered' caption: 'caption' header: 'bootstrap-header' # give the header a gradient background footerRow: '' footerCells: '' icons: '' # add 'icon-white' to make them white; this icon class is added to the <i> in the header sortNone: 'bootstrap-icon-unsorted' sortAsc: 'icon-chevron-up' # glyphicon glyphicon-chevron-up' # we are still using v2 icons sortDesc: 'icon-chevron-down' # glyphicon-chevron-down' # we are still using v2 icons active: '' # applied when column is sorted hover: '' # use custom css here - bootstrap class may not override it filterRow: '' # filter row class even: '' # odd row zebra striping odd: '' # even row zebra striping # e = exact text from cell # n = normalized value returned by the column parser # f = search filter input value # i = column index # $r = ??? filterSelectExactMatch = (e, n, f, i, $r) -> e is f # call the tablesorter plugin and apply the uitheme widget @$el.find('.tablesorter').tablesorter theme: 'bootstrap' widthFixed: true headerTemplate: '{content} {icon}' textSorter: 6: (a, b, direction, column, table) -> days = [] for s in [a, b] n = parseInt s n = 0 unless _.isNumber n n = 1 if /^a/.test s for [duration, factor] in [ [/second/i, 1/(86400*1000)] [/minute/i, 1/1440] [/hour/i, 1/24] [/week/i, 7] [/month/i, 30.42] [/year/i, 365.2425] ] if duration.test s n *= factor break if /^in /i.test s n *= -1 days.push n days[0] - days[1] sortList: if @isEmployer() or me.isAdmin() then [[6, 0]] else [[0, 1]] # widget code contained in the jquery.tablesorter.widgets.js file # use the zebra stripe widget if you plan on hiding any rows (filter widget) widgets: ['uitheme', 'zebra', 'filter'] widgetOptions: # using the default zebra striping class name, so it actually isn't included in the theme variable above # this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden zebra: ['even', 'odd'] # extra css class applied to the table row containing the filters & the inputs within that row filter_cssFilter: '' # If there are child rows in the table (rows with class name from 'cssChildRow' option) # and this option is true and a match is found anywhere in the child row, then it will make that row # visible; default is false filter_childRows: false # if true, filters are collapsed initially, but can be revealed by hovering over the grey bar immediately # below the header row. Additionally, tabbing through the document will open the filter row when an input gets focus filter_hideFilters: false # Set this option to false to make the searches case sensitive filter_ignoreCase: true # jQuery selector string of an element used to reset the filters filter_reset: '.reset' # Use the $.tablesorter.storage utility to save the most recent filters filter_saveFilters: true # Delay in milliseconds before the filter widget starts searching; This option prevents searching for # every character while typing and should make searching large tables faster. filter_searchDelay: 150 # Set this option to true to use the filter to find text from the start of the column # So typing in 'a' will find 'PI:NAME:<NAME>END_PI' but not 'PI:NAME:<NAME>END_PI', both have a's; default is false filter_startsWith: false filter_functions: 2: 'Full-time': filterSelectExactMatch 'Part-time': filterSelectExactMatch 'Contracting': filterSelectExactMatch 'Remote': filterSelectExactMatch 'Internship': filterSelectExactMatch 5: '0-1': (e, n, f, i, $r) -> n <= 1 '2-5': (e, n, f, i, $r) -> 2 <= n <= 5 '6+': (e, n, f, i, $r) -> 6 <= n 6: 'Last day': (e, n, f, i, $r) -> days = parseFloat $($r.find('td')[i]).data('profile-age') days <= 1 'Last week': (e, n, f, i, $r) -> days = parseFloat $($r.find('td')[i]).data('profile-age') days <= 7 'Last 4 weeks': (e, n, f, i, $r) -> days = parseFloat $($r.find('td')[i]).data('profile-age') days <= 28 8: '✓': filterSelectExactMatch '✗': filterSelectExactMatch logoutAccount: -> window.location.hash = '' super() onCandidateClicked: (e) -> id = $(e.target).closest('tr').data('candidate-id') if id and (@isEmployer() or me.isAdmin()) if window.history oldState = _.cloneDeep window.history.state ? {} oldState['lastViewedCandidateID'] = id window.history.replaceState(oldState, '') else window.location.hash = id url = "/account/profile/#{id}" window.open url, '_blank' else @openModalView new EmployerSignupModal
[ { "context": "Example:**\n\t# \n\t# myCache.set \"myKey\", \"my_String Value\", ( err, success )->\n\t# console", "end": 1903, "score": 0.5033913254737854, "start": 1903, "tag": "KEY", "value": "" } ]
node_modules/node-cache/lib/node_cache.coffee
jeroen-corteville/izegem
2
_ = require( "underscore" ) EventEmitter = require('events').EventEmitter # generate superclass module.exports = class NodeCache extends EventEmitter constructor: ( @options = {} )-> # container for cached dtaa @data = {} # module options @options = _.extend( # convert all elements to string forceString: false # used standard size for calculating value size objectValueSize: 80 arrayValueSize: 40 # standard time to live in seconds. 0 = infinity; stdTTL: 0 # time in seconds to check all data and delete expired keys checkperiod: 600 , @options ) # statistics container @stats = hits: 0 misses: 0 keys: 0 ksize: 0 vsize: 0 # initalize checking period @_checkData() # ## get # # get a cached key and change the stats # # **Parameters:** # # * `key` ( String | String[] ): cache key or an array of keys # * `[cb]` ( Function ): Callback function # # **Example:** # # myCache.key "myKey", ( err, val )-> # console.log( err, val ) # get: ( keys, cb )=> # convert a string to an array of one key if _.isString( keys ) keys = [ keys ] # define return oRet = {} for key in keys # get data and incremet stats if @data[ key ]? and @_check( key, @data[ key ] ) @stats.hits++ oRet[ key ] = @_unwrap( @data[ key ] ) else # if not found return a error @stats.misses++ # return all found keys cb( null, oRet ) if cb? return oRet # ## set # # set a cached key and change the stats # # **Parameters:** # # * `key` ( String ): cache key # * `value` ( Any ): A element to cache. If the option `option.forceString` is `true` the module trys to translate it to a serialized JSON # * `[ ttl ]` ( Number | String ): ( optional ) The time to live in seconds. # * `[cb]` ( Function ): Callback function # # **Example:** # # myCache.set "myKey", "my_String Value", ( err, success )-> # console.log( err, success ) # # myCache.set "myKey", "my_String Value", "10h", ( err, success )-> # console.log( err, success ) # set: ( key, value, ttl, cb )=> # internal helper variables existend = false # force the data to string if @options.forceString and not _.isString( value ) value = JSON.stringify( value ) # remap the arguments if `ttl` is not passed if arguments.length is 3 and _.isFunction( ttl ) cb = ttl ttl = @options.stdTTL # remove existing data from stats if @data[ key ] existend = true @stats.vsize -= @_getValLength( @_unwrap( @data[ key ] ) ) # set the value @data[ key ] = @_wrap( value, ttl ) @stats.vsize += @_getValLength( value ) # only add the keys and key-size if the key is new if not existend @stats.ksize += @_getKeyLength( key ) @stats.keys++ @emit( "set", key, value ) # return true cb( null, true ) if cb? return true # ## del # # remove a key # # **Parameters:** # # * `key` ( String | String[] ): cache key to delete or a array of cache keys # * `[cb]` ( Function ): Callback function # # **Return** # # ( Number ): Number of deleted keys # # **Example:** # # myCache.del( "myKey" ) # # myCache.del( "myKey", ( err, success )-> # console.log( err, success ) # del: ( keys, cb )=> # convert a string to an array of one key if _.isString( keys ) keys = [ keys ] delCount = 0 for key in keys # only delete if existend if @data[ key ]? # calc the stats @stats.vsize -= @_getValLength( @_unwrap( @data[ key ] ) ) @stats.ksize -= @_getKeyLength( key ) @stats.keys-- delCount++ # delete the value delete @data[ key ] # return true @emit( "del", key ) else # if the key has not been found return an error @stats.misses++ cb( null, delCount ) if cb? return delCount # ## ttl # # reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 it's similar to `.del()` # # **Parameters:** # # * `key` ( String ): cache key to reset the ttl value # * `ttl` ( Number ): ( optional -> options.stdTTL || 0 ) The time to live in seconds # * `[cb]` ( Function ): Callback function # # **Return** # # ( Boolen ): key found and ttl set # # **Example:** # # myCache.ttl( "myKey" ) // will set ttl to default ttl # # myCache.ttl( "myKey", 1000, ( err, keyFound )-> # console.log( err, success ) # ttl: => # change args if only key and callback are passed [ key, args... ] = arguments for arg in args switch typeof arg when "number" then ttl = arg when "function" then cb = arg ttl or= @options.stdTTL if not key cb( null, false ) if cb? return false # check for existend data and update the ttl value if @data[ key ]? and @_check( key, @data[ key ] ) # on ttl = 0 delete the key. otherwise reset the value if ttl > 0 @data[ key ] = @_wrap( @data[ key ].v, ttl ) else @del( key ) cb( null, true ) if cb? return true else # return false if key has not been found cb( null, false ) if cb? return false return # ## getStats # # get the stats # # **Parameters:** # # - # # **Return** # # ( Object ): Stats data # # **Example:** # # myCache.getStats() # # { # # hits: 0, # # misses: 0, # # keys: 0, # # ksize: 0, # # vsize: 0 # # } # getStats: => @stats # ## flushAll # # flush the hole data and reset the stats # # **Example:** # # myCache.flushAll() # # myCache.getStats() # # { # # hits: 0, # # misses: 0, # # keys: 0, # # ksize: 0, # # vsize: 0 # # } # flushAll: ( _startPeriod = true )=> # parameter just for testing # set data empty @data = {} # reset stats @stats = hits: 0 misses: 0 keys: 0 ksize: 0 vsize: 0 # reset check period @_killCheckPeriod() @_checkData( _startPeriod ) @emit( "flush" ) return # ## _checkData # # internal Housekeeping mehtod. # Check all the cached data and delete the invalid values _checkData: ( startPeriod = true )=> # run the housekeeping method for key, value of @data @_check( key, value ) if startPeriod and @options.checkperiod > 0 @checkTimeout = setTimeout( @_checkData, ( @options.checkperiod * 1000 ) ) return # ## _killCheckPeriod # # stop the checkdata period. Only needed to abort the script in testing mode. _killCheckPeriod: -> clearTimeout( @checkTimeout ) if @checkTimeout? # ## _check # # internal method the check the value. If it's not valid any moe delete it _check: ( key, data )=> # data is invalid if the ttl is to old and is not 0 #console.log data.t < Date.now(), data.t, Date.now() if data.t isnt 0 and data.t < Date.now() @del( key ) @emit( "expired", key, @_unwrap(data) ) return false else return true # ## _wrap # # internal method to wrap a value in an object with some metadata _wrap: ( value, ttl )=> # define the time to live now = Date.now() livetime = 0 ttlMultiplicator = 1000 # use given ttl if ttl is 0 livetime = 0 else if ttl livetime = now + ( ttl * ttlMultiplicator ) else # use standard ttl if @options.stdTTL is 0 livetime = @options.stdTTL else livetime = now + ( @options.stdTTL * ttlMultiplicator ) # return teh wrapped value oReturn = t: livetime v: value # ## _unwrap # # internal method to extract get the value out of the wrapped value _unwrap: ( value )=> if value.v? return value.v return null # ## _getKeyLength # # internal method the calculate the key length _getKeyLength: ( key )=> key.length # ## _getValLength # # internal method to calculate the value length _getValLength: ( value )=> if _.isString( value ) # if the value is a String get the real length value.length else if @options.forceString # force string if it's defined and not passed JSON.stringify( value ).length else if _.isArray( value ) # if the data is an Array multiply each element with a defined default length @options.arrayValueSize * value.length else if _.isNumber( value ) 8 else if _.isObject( value ) # if the data is an Object multiply each element with a defined default length @options.objectValueSize * _.size( value ) else # default fallback 0 # ## _error # # internal method to handle an error message _error: ( type, data = {}, cb )=> # generate the error object error = new Error() error.name = type error.errorcode = type error.msg = "-" error.data = data if cb and _.isFunction( cb ) # return the error cb( error, null ) return else # if no callback is defined return the error object return error
156132
_ = require( "underscore" ) EventEmitter = require('events').EventEmitter # generate superclass module.exports = class NodeCache extends EventEmitter constructor: ( @options = {} )-> # container for cached dtaa @data = {} # module options @options = _.extend( # convert all elements to string forceString: false # used standard size for calculating value size objectValueSize: 80 arrayValueSize: 40 # standard time to live in seconds. 0 = infinity; stdTTL: 0 # time in seconds to check all data and delete expired keys checkperiod: 600 , @options ) # statistics container @stats = hits: 0 misses: 0 keys: 0 ksize: 0 vsize: 0 # initalize checking period @_checkData() # ## get # # get a cached key and change the stats # # **Parameters:** # # * `key` ( String | String[] ): cache key or an array of keys # * `[cb]` ( Function ): Callback function # # **Example:** # # myCache.key "myKey", ( err, val )-> # console.log( err, val ) # get: ( keys, cb )=> # convert a string to an array of one key if _.isString( keys ) keys = [ keys ] # define return oRet = {} for key in keys # get data and incremet stats if @data[ key ]? and @_check( key, @data[ key ] ) @stats.hits++ oRet[ key ] = @_unwrap( @data[ key ] ) else # if not found return a error @stats.misses++ # return all found keys cb( null, oRet ) if cb? return oRet # ## set # # set a cached key and change the stats # # **Parameters:** # # * `key` ( String ): cache key # * `value` ( Any ): A element to cache. If the option `option.forceString` is `true` the module trys to translate it to a serialized JSON # * `[ ttl ]` ( Number | String ): ( optional ) The time to live in seconds. # * `[cb]` ( Function ): Callback function # # **Example:** # # myCache.set "myKey", "my<KEY>_String Value", ( err, success )-> # console.log( err, success ) # # myCache.set "myKey", "my_String Value", "10h", ( err, success )-> # console.log( err, success ) # set: ( key, value, ttl, cb )=> # internal helper variables existend = false # force the data to string if @options.forceString and not _.isString( value ) value = JSON.stringify( value ) # remap the arguments if `ttl` is not passed if arguments.length is 3 and _.isFunction( ttl ) cb = ttl ttl = @options.stdTTL # remove existing data from stats if @data[ key ] existend = true @stats.vsize -= @_getValLength( @_unwrap( @data[ key ] ) ) # set the value @data[ key ] = @_wrap( value, ttl ) @stats.vsize += @_getValLength( value ) # only add the keys and key-size if the key is new if not existend @stats.ksize += @_getKeyLength( key ) @stats.keys++ @emit( "set", key, value ) # return true cb( null, true ) if cb? return true # ## del # # remove a key # # **Parameters:** # # * `key` ( String | String[] ): cache key to delete or a array of cache keys # * `[cb]` ( Function ): Callback function # # **Return** # # ( Number ): Number of deleted keys # # **Example:** # # myCache.del( "myKey" ) # # myCache.del( "myKey", ( err, success )-> # console.log( err, success ) # del: ( keys, cb )=> # convert a string to an array of one key if _.isString( keys ) keys = [ keys ] delCount = 0 for key in keys # only delete if existend if @data[ key ]? # calc the stats @stats.vsize -= @_getValLength( @_unwrap( @data[ key ] ) ) @stats.ksize -= @_getKeyLength( key ) @stats.keys-- delCount++ # delete the value delete @data[ key ] # return true @emit( "del", key ) else # if the key has not been found return an error @stats.misses++ cb( null, delCount ) if cb? return delCount # ## ttl # # reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 it's similar to `.del()` # # **Parameters:** # # * `key` ( String ): cache key to reset the ttl value # * `ttl` ( Number ): ( optional -> options.stdTTL || 0 ) The time to live in seconds # * `[cb]` ( Function ): Callback function # # **Return** # # ( Boolen ): key found and ttl set # # **Example:** # # myCache.ttl( "myKey" ) // will set ttl to default ttl # # myCache.ttl( "myKey", 1000, ( err, keyFound )-> # console.log( err, success ) # ttl: => # change args if only key and callback are passed [ key, args... ] = arguments for arg in args switch typeof arg when "number" then ttl = arg when "function" then cb = arg ttl or= @options.stdTTL if not key cb( null, false ) if cb? return false # check for existend data and update the ttl value if @data[ key ]? and @_check( key, @data[ key ] ) # on ttl = 0 delete the key. otherwise reset the value if ttl > 0 @data[ key ] = @_wrap( @data[ key ].v, ttl ) else @del( key ) cb( null, true ) if cb? return true else # return false if key has not been found cb( null, false ) if cb? return false return # ## getStats # # get the stats # # **Parameters:** # # - # # **Return** # # ( Object ): Stats data # # **Example:** # # myCache.getStats() # # { # # hits: 0, # # misses: 0, # # keys: 0, # # ksize: 0, # # vsize: 0 # # } # getStats: => @stats # ## flushAll # # flush the hole data and reset the stats # # **Example:** # # myCache.flushAll() # # myCache.getStats() # # { # # hits: 0, # # misses: 0, # # keys: 0, # # ksize: 0, # # vsize: 0 # # } # flushAll: ( _startPeriod = true )=> # parameter just for testing # set data empty @data = {} # reset stats @stats = hits: 0 misses: 0 keys: 0 ksize: 0 vsize: 0 # reset check period @_killCheckPeriod() @_checkData( _startPeriod ) @emit( "flush" ) return # ## _checkData # # internal Housekeeping mehtod. # Check all the cached data and delete the invalid values _checkData: ( startPeriod = true )=> # run the housekeeping method for key, value of @data @_check( key, value ) if startPeriod and @options.checkperiod > 0 @checkTimeout = setTimeout( @_checkData, ( @options.checkperiod * 1000 ) ) return # ## _killCheckPeriod # # stop the checkdata period. Only needed to abort the script in testing mode. _killCheckPeriod: -> clearTimeout( @checkTimeout ) if @checkTimeout? # ## _check # # internal method the check the value. If it's not valid any moe delete it _check: ( key, data )=> # data is invalid if the ttl is to old and is not 0 #console.log data.t < Date.now(), data.t, Date.now() if data.t isnt 0 and data.t < Date.now() @del( key ) @emit( "expired", key, @_unwrap(data) ) return false else return true # ## _wrap # # internal method to wrap a value in an object with some metadata _wrap: ( value, ttl )=> # define the time to live now = Date.now() livetime = 0 ttlMultiplicator = 1000 # use given ttl if ttl is 0 livetime = 0 else if ttl livetime = now + ( ttl * ttlMultiplicator ) else # use standard ttl if @options.stdTTL is 0 livetime = @options.stdTTL else livetime = now + ( @options.stdTTL * ttlMultiplicator ) # return teh wrapped value oReturn = t: livetime v: value # ## _unwrap # # internal method to extract get the value out of the wrapped value _unwrap: ( value )=> if value.v? return value.v return null # ## _getKeyLength # # internal method the calculate the key length _getKeyLength: ( key )=> key.length # ## _getValLength # # internal method to calculate the value length _getValLength: ( value )=> if _.isString( value ) # if the value is a String get the real length value.length else if @options.forceString # force string if it's defined and not passed JSON.stringify( value ).length else if _.isArray( value ) # if the data is an Array multiply each element with a defined default length @options.arrayValueSize * value.length else if _.isNumber( value ) 8 else if _.isObject( value ) # if the data is an Object multiply each element with a defined default length @options.objectValueSize * _.size( value ) else # default fallback 0 # ## _error # # internal method to handle an error message _error: ( type, data = {}, cb )=> # generate the error object error = new Error() error.name = type error.errorcode = type error.msg = "-" error.data = data if cb and _.isFunction( cb ) # return the error cb( error, null ) return else # if no callback is defined return the error object return error
true
_ = require( "underscore" ) EventEmitter = require('events').EventEmitter # generate superclass module.exports = class NodeCache extends EventEmitter constructor: ( @options = {} )-> # container for cached dtaa @data = {} # module options @options = _.extend( # convert all elements to string forceString: false # used standard size for calculating value size objectValueSize: 80 arrayValueSize: 40 # standard time to live in seconds. 0 = infinity; stdTTL: 0 # time in seconds to check all data and delete expired keys checkperiod: 600 , @options ) # statistics container @stats = hits: 0 misses: 0 keys: 0 ksize: 0 vsize: 0 # initalize checking period @_checkData() # ## get # # get a cached key and change the stats # # **Parameters:** # # * `key` ( String | String[] ): cache key or an array of keys # * `[cb]` ( Function ): Callback function # # **Example:** # # myCache.key "myKey", ( err, val )-> # console.log( err, val ) # get: ( keys, cb )=> # convert a string to an array of one key if _.isString( keys ) keys = [ keys ] # define return oRet = {} for key in keys # get data and incremet stats if @data[ key ]? and @_check( key, @data[ key ] ) @stats.hits++ oRet[ key ] = @_unwrap( @data[ key ] ) else # if not found return a error @stats.misses++ # return all found keys cb( null, oRet ) if cb? return oRet # ## set # # set a cached key and change the stats # # **Parameters:** # # * `key` ( String ): cache key # * `value` ( Any ): A element to cache. If the option `option.forceString` is `true` the module trys to translate it to a serialized JSON # * `[ ttl ]` ( Number | String ): ( optional ) The time to live in seconds. # * `[cb]` ( Function ): Callback function # # **Example:** # # myCache.set "myKey", "myPI:KEY:<KEY>END_PI_String Value", ( err, success )-> # console.log( err, success ) # # myCache.set "myKey", "my_String Value", "10h", ( err, success )-> # console.log( err, success ) # set: ( key, value, ttl, cb )=> # internal helper variables existend = false # force the data to string if @options.forceString and not _.isString( value ) value = JSON.stringify( value ) # remap the arguments if `ttl` is not passed if arguments.length is 3 and _.isFunction( ttl ) cb = ttl ttl = @options.stdTTL # remove existing data from stats if @data[ key ] existend = true @stats.vsize -= @_getValLength( @_unwrap( @data[ key ] ) ) # set the value @data[ key ] = @_wrap( value, ttl ) @stats.vsize += @_getValLength( value ) # only add the keys and key-size if the key is new if not existend @stats.ksize += @_getKeyLength( key ) @stats.keys++ @emit( "set", key, value ) # return true cb( null, true ) if cb? return true # ## del # # remove a key # # **Parameters:** # # * `key` ( String | String[] ): cache key to delete or a array of cache keys # * `[cb]` ( Function ): Callback function # # **Return** # # ( Number ): Number of deleted keys # # **Example:** # # myCache.del( "myKey" ) # # myCache.del( "myKey", ( err, success )-> # console.log( err, success ) # del: ( keys, cb )=> # convert a string to an array of one key if _.isString( keys ) keys = [ keys ] delCount = 0 for key in keys # only delete if existend if @data[ key ]? # calc the stats @stats.vsize -= @_getValLength( @_unwrap( @data[ key ] ) ) @stats.ksize -= @_getKeyLength( key ) @stats.keys-- delCount++ # delete the value delete @data[ key ] # return true @emit( "del", key ) else # if the key has not been found return an error @stats.misses++ cb( null, delCount ) if cb? return delCount # ## ttl # # reset or redefine the ttl of a key. If `ttl` is not passed or set to 0 it's similar to `.del()` # # **Parameters:** # # * `key` ( String ): cache key to reset the ttl value # * `ttl` ( Number ): ( optional -> options.stdTTL || 0 ) The time to live in seconds # * `[cb]` ( Function ): Callback function # # **Return** # # ( Boolen ): key found and ttl set # # **Example:** # # myCache.ttl( "myKey" ) // will set ttl to default ttl # # myCache.ttl( "myKey", 1000, ( err, keyFound )-> # console.log( err, success ) # ttl: => # change args if only key and callback are passed [ key, args... ] = arguments for arg in args switch typeof arg when "number" then ttl = arg when "function" then cb = arg ttl or= @options.stdTTL if not key cb( null, false ) if cb? return false # check for existend data and update the ttl value if @data[ key ]? and @_check( key, @data[ key ] ) # on ttl = 0 delete the key. otherwise reset the value if ttl > 0 @data[ key ] = @_wrap( @data[ key ].v, ttl ) else @del( key ) cb( null, true ) if cb? return true else # return false if key has not been found cb( null, false ) if cb? return false return # ## getStats # # get the stats # # **Parameters:** # # - # # **Return** # # ( Object ): Stats data # # **Example:** # # myCache.getStats() # # { # # hits: 0, # # misses: 0, # # keys: 0, # # ksize: 0, # # vsize: 0 # # } # getStats: => @stats # ## flushAll # # flush the hole data and reset the stats # # **Example:** # # myCache.flushAll() # # myCache.getStats() # # { # # hits: 0, # # misses: 0, # # keys: 0, # # ksize: 0, # # vsize: 0 # # } # flushAll: ( _startPeriod = true )=> # parameter just for testing # set data empty @data = {} # reset stats @stats = hits: 0 misses: 0 keys: 0 ksize: 0 vsize: 0 # reset check period @_killCheckPeriod() @_checkData( _startPeriod ) @emit( "flush" ) return # ## _checkData # # internal Housekeeping mehtod. # Check all the cached data and delete the invalid values _checkData: ( startPeriod = true )=> # run the housekeeping method for key, value of @data @_check( key, value ) if startPeriod and @options.checkperiod > 0 @checkTimeout = setTimeout( @_checkData, ( @options.checkperiod * 1000 ) ) return # ## _killCheckPeriod # # stop the checkdata period. Only needed to abort the script in testing mode. _killCheckPeriod: -> clearTimeout( @checkTimeout ) if @checkTimeout? # ## _check # # internal method the check the value. If it's not valid any moe delete it _check: ( key, data )=> # data is invalid if the ttl is to old and is not 0 #console.log data.t < Date.now(), data.t, Date.now() if data.t isnt 0 and data.t < Date.now() @del( key ) @emit( "expired", key, @_unwrap(data) ) return false else return true # ## _wrap # # internal method to wrap a value in an object with some metadata _wrap: ( value, ttl )=> # define the time to live now = Date.now() livetime = 0 ttlMultiplicator = 1000 # use given ttl if ttl is 0 livetime = 0 else if ttl livetime = now + ( ttl * ttlMultiplicator ) else # use standard ttl if @options.stdTTL is 0 livetime = @options.stdTTL else livetime = now + ( @options.stdTTL * ttlMultiplicator ) # return teh wrapped value oReturn = t: livetime v: value # ## _unwrap # # internal method to extract get the value out of the wrapped value _unwrap: ( value )=> if value.v? return value.v return null # ## _getKeyLength # # internal method the calculate the key length _getKeyLength: ( key )=> key.length # ## _getValLength # # internal method to calculate the value length _getValLength: ( value )=> if _.isString( value ) # if the value is a String get the real length value.length else if @options.forceString # force string if it's defined and not passed JSON.stringify( value ).length else if _.isArray( value ) # if the data is an Array multiply each element with a defined default length @options.arrayValueSize * value.length else if _.isNumber( value ) 8 else if _.isObject( value ) # if the data is an Object multiply each element with a defined default length @options.objectValueSize * _.size( value ) else # default fallback 0 # ## _error # # internal method to handle an error message _error: ( type, data = {}, cb )=> # generate the error object error = new Error() error.name = type error.errorcode = type error.msg = "-" error.data = data if cb and _.isFunction( cb ) # return the error cb( error, null ) return else # if no callback is defined return the error object return error
[ { "context": "s exports.Text extends Entity\n\n\tentity :\n\t\tname: \"Text\"\n\t\ttype: \"a-text\"\n\n\tconstructor: (options)->\n\t\tsu", "end": 106, "score": 0.9113867282867432, "start": 102, "tag": "NAME", "value": "Text" }, { "context": "ble'\n\t\tif options.text is undefined th...
src/Text.coffee
etiennepinchon/hologram
89
{entityAttribute, Entity} = require "./Entity" class exports.Text extends Entity entity : name: "Text" type: "a-text" constructor: (options)-> super # Double side entity if options.side is undefined then @side = 'double' if options.text is undefined then @text = 'Hello' # ---------------------------------------------------------------------------- # PROPERTIES @define "text", entityAttribute("text", "value", "") @define "width", entityAttribute("width", "width", null) @define "height", entityAttribute("height", "height", null) @define "align", entityAttribute("align", "align", "left") @define "anchor", entityAttribute("anchor", "anchor", "center") @define "baseline", entityAttribute("baseline", "baseline", "center") @define "font", entityAttribute("font", "font", null) @define "lineHeight", entityAttribute("lineHeight", "line-height", 0) @define "whitespace", entityAttribute("whitespace", "whitespace", "normal") @define "color", entityAttribute("color", "color", "#FFF") @define "zindex", entityAttribute("zindex", "zOffset", 0.001)
167101
{entityAttribute, Entity} = require "./Entity" class exports.Text extends Entity entity : name: "<NAME>" type: "a-text" constructor: (options)-> super # Double side entity if options.side is undefined then @side = 'double' if options.text is undefined then @text = '<NAME>' # ---------------------------------------------------------------------------- # PROPERTIES @define "text", entityAttribute("text", "value", "") @define "width", entityAttribute("width", "width", null) @define "height", entityAttribute("height", "height", null) @define "align", entityAttribute("align", "align", "left") @define "anchor", entityAttribute("anchor", "anchor", "center") @define "baseline", entityAttribute("baseline", "baseline", "center") @define "font", entityAttribute("font", "font", null) @define "lineHeight", entityAttribute("lineHeight", "line-height", 0) @define "whitespace", entityAttribute("whitespace", "whitespace", "normal") @define "color", entityAttribute("color", "color", "#FFF") @define "zindex", entityAttribute("zindex", "zOffset", 0.001)
true
{entityAttribute, Entity} = require "./Entity" class exports.Text extends Entity entity : name: "PI:NAME:<NAME>END_PI" type: "a-text" constructor: (options)-> super # Double side entity if options.side is undefined then @side = 'double' if options.text is undefined then @text = 'PI:NAME:<NAME>END_PI' # ---------------------------------------------------------------------------- # PROPERTIES @define "text", entityAttribute("text", "value", "") @define "width", entityAttribute("width", "width", null) @define "height", entityAttribute("height", "height", null) @define "align", entityAttribute("align", "align", "left") @define "anchor", entityAttribute("anchor", "anchor", "center") @define "baseline", entityAttribute("baseline", "baseline", "center") @define "font", entityAttribute("font", "font", null) @define "lineHeight", entityAttribute("lineHeight", "line-height", 0) @define "whitespace", entityAttribute("whitespace", "whitespace", "normal") @define "color", entityAttribute("color", "color", "#FFF") @define "zindex", entityAttribute("zindex", "zOffset", 0.001)
[ { "context": "\")\n .setValue(\"input[name='username']\", \"hamada\")\n .setValue(\"input[name='password']\", \"", "end": 1066, "score": 0.9996129274368286, "start": 1060, "tag": "USERNAME", "value": "hamada" }, { "context": "\")\n .setValue(\"input[name='p...
bin/js/test/loginTest-taiga.coffee
xpfriend/pocci
1
###global describe, it, before, after### ###jshint quotmark:true### "use strict" assert = require("chai").assert webdriver = require("pocci/webdriver.js") test = require("./resq.js") loginGitLab = require("./loginTest.js").loginGitLab loginUser = require("./loginTest.js").loginUser loginSonar = require("./loginTest.js").loginSonar describe "Login (taiga)", () -> @timeout(120000) browser = null before (done) -> test done, setup: -> yield webdriver.init() browser = webdriver.browser return after (done) -> test done, setup: -> yield browser.end() it "user", (done) -> test done, expect: -> yield loginUser(browser) it "sonar", (done) -> test done, expect: -> yield loginSonar(browser) it "gitlab", (done) -> test done, expect: -> yield loginGitLab(browser) it "taiga", (done) -> test done, when: -> yield browser .url(process.env.TAIGA_URL + "/login") .setValue("input[name='username']", "hamada") .setValue("input[name='password']", "password") .save("taiga-before-login") .click("button[title='Login']") .save("taiga-after-login") .pause(10000) then: -> text = yield browser .save("taiga-assert-login") .getText("a.user-avatar") assert.equal(text, "HAMADA, Kawao")
130426
###global describe, it, before, after### ###jshint quotmark:true### "use strict" assert = require("chai").assert webdriver = require("pocci/webdriver.js") test = require("./resq.js") loginGitLab = require("./loginTest.js").loginGitLab loginUser = require("./loginTest.js").loginUser loginSonar = require("./loginTest.js").loginSonar describe "Login (taiga)", () -> @timeout(120000) browser = null before (done) -> test done, setup: -> yield webdriver.init() browser = webdriver.browser return after (done) -> test done, setup: -> yield browser.end() it "user", (done) -> test done, expect: -> yield loginUser(browser) it "sonar", (done) -> test done, expect: -> yield loginSonar(browser) it "gitlab", (done) -> test done, expect: -> yield loginGitLab(browser) it "taiga", (done) -> test done, when: -> yield browser .url(process.env.TAIGA_URL + "/login") .setValue("input[name='username']", "hamada") .setValue("input[name='password']", "<PASSWORD>") .save("taiga-before-login") .click("button[title='Login']") .save("taiga-after-login") .pause(10000) then: -> text = yield browser .save("taiga-assert-login") .getText("a.user-avatar") assert.equal(text, "HAMADA, K<NAME>ao")
true
###global describe, it, before, after### ###jshint quotmark:true### "use strict" assert = require("chai").assert webdriver = require("pocci/webdriver.js") test = require("./resq.js") loginGitLab = require("./loginTest.js").loginGitLab loginUser = require("./loginTest.js").loginUser loginSonar = require("./loginTest.js").loginSonar describe "Login (taiga)", () -> @timeout(120000) browser = null before (done) -> test done, setup: -> yield webdriver.init() browser = webdriver.browser return after (done) -> test done, setup: -> yield browser.end() it "user", (done) -> test done, expect: -> yield loginUser(browser) it "sonar", (done) -> test done, expect: -> yield loginSonar(browser) it "gitlab", (done) -> test done, expect: -> yield loginGitLab(browser) it "taiga", (done) -> test done, when: -> yield browser .url(process.env.TAIGA_URL + "/login") .setValue("input[name='username']", "hamada") .setValue("input[name='password']", "PI:PASSWORD:<PASSWORD>END_PI") .save("taiga-before-login") .click("button[title='Login']") .save("taiga-after-login") .pause(10000) then: -> text = yield browser .save("taiga-assert-login") .getText("a.user-avatar") assert.equal(text, "HAMADA, KPI:NAME:<NAME>END_PIao")
[ { "context": " post = null\n poster =\n firstName: \"John\"\n lastName: \"Doe\"\n\n beforeEach ->\n ", "end": 329, "score": 0.9998449683189392, "start": 325, "tag": "NAME", "value": "John" }, { "context": "er =\n firstName: \"John\"\n lastNam...
source/javascripts/specs/model.js.coffee
petalmd/stem
0
describe "Model", -> describe "A simple model", -> class Post extends Stem.Model it "should implement Events", -> post = new Post (expect post["bind"]).toBeDefined() (expect post["trigger"]).toBeDefined() describe "with attributes", -> post = null poster = firstName: "John" lastName: "Doe" beforeEach -> post = new Post title: "title" poster: poster it "should be initialized with initial values", -> (expect post["attributes"]).toBeDefined() (expect post.attributes["title"]).toEqual "title" it "should use the initial values by reference (not cloned)", -> expect(post.get "poster").toBe poster it "should get an attribute", -> (expect post.get "title").toEqual "title" it "should set an attribute", -> post.set title: "new" (expect post.get "title").toEqual "new" it "should validate the arguments of the 'set' call", -> arraySet = -> post.set "title", "value" expect(arraySet).toThrow() objectSet = -> post.set "title": "value" expect(objectSet).not.toThrow() describe "events", -> post = null beforeEach -> post = new Post title: "title" it "should trigger a change event when any attributes change", -> callback = sinon.spy() post.bind "change", callback (expect callback).not.toHaveBeenCalled() post.set title: "new", foo: "bar" (expect callback).toHaveBeenCalledWith(post, ["title", "foo"]) it "should trigger a change event when specific attributes change", -> titleCallback = sinon.spy() post.bind "change:title", titleCallback fooCallback = sinon.spy() post.bind "change:foo", fooCallback (expect titleCallback).not.toHaveBeenCalled() (expect fooCallback).not.toHaveBeenCalled() post.set title: "new" (expect titleCallback).toHaveBeenCalledWith(post, "title", "new") (expect fooCallback).not.toHaveBeenCalled() it "should not trigger a specific change event for fields that are set but did not change", -> callback = sinon.spy() post.bind "change:title", callback (expect callback).not.toHaveBeenCalled() post.set title: "title" (expect callback).not.toHaveBeenCalled() it "should not trigger a global change event for fields that are set but did not change", -> callback = sinon.spy() post.bind "change", callback (expect callback).not.toHaveBeenCalled() post.set title: "title" (expect callback).not.toHaveBeenCalled() post.set title: "title", foo: "bar" (expect callback).toHaveBeenCalledWith(post, ["foo"]) describe "with defaults", -> poster = firstName: "John" lastName: "Doe" class PostWithDefaults extends Stem.Model defaults: title: "default" body: "body" poster: poster it "should initialize with its defaults", -> post = new PostWithDefaults (expect post.get "title").toEqual "default" (expect post.get "body").toEqual "body" it "should priorize attributes passed at the constructor over its defaults", -> post = new PostWithDefaults title: "overridden" (expect post.get "title").toEqual "overridden" (expect post.get "body").toEqual "body" it "should deep copy from its defaults when building an instance", -> post = new PostWithDefaults expect(post.get "poster").not.toBe poster expect(post.get "poster").toEqual poster describe "snapshots", -> it "should allow taking a snapshot of the current objects", -> post = new Stem.Model title: "new" expect(post.currentSnapshot).toBeUndefined() post.snapshot() expect(post.currentSnapshot).toBeDefined() expect(post.currentSnapshot["title"]).toEqual "new" it "should make deep copies for snapshots", -> poster = firstName: "John" lastName: "Smith" post = new Stem.Model title: "new" poster: poster expect(post.get "poster").toBe poster post.snapshot() expect(post.currentSnapshot["poster"]).not.toBe poster expect(post.currentSnapshot["poster"]).toEqual poster it "should allow restoring attributes from snapshots", -> post = new Stem.Model title: "new" post.snapshot() post.set title: "changed" post.restore "title" expect(post.get "title").toEqual "new" it "should allow restoring multiple attributes from snapshots", -> post = new Stem.Model title: "new" body: "body" post.snapshot() post.set title: "changed", body: "also changed" post.restore "title", "body" expect(post.get "title").toEqual "new" expect(post.get "body").toEqual "body" describe "A model with hooks", -> class Post extends Stem.Model beforeSet: (attributes) -> attributes.title = "intercepted" it "should allow to modify attributes before they are set (beforeSet)", -> post = new Post title: "new" post.set title: "changed" (expect post.get "title").toEqual "intercepted"
104393
describe "Model", -> describe "A simple model", -> class Post extends Stem.Model it "should implement Events", -> post = new Post (expect post["bind"]).toBeDefined() (expect post["trigger"]).toBeDefined() describe "with attributes", -> post = null poster = firstName: "<NAME>" lastName: "<NAME>" beforeEach -> post = new Post title: "title" poster: poster it "should be initialized with initial values", -> (expect post["attributes"]).toBeDefined() (expect post.attributes["title"]).toEqual "title" it "should use the initial values by reference (not cloned)", -> expect(post.get "poster").toBe poster it "should get an attribute", -> (expect post.get "title").toEqual "title" it "should set an attribute", -> post.set title: "new" (expect post.get "title").toEqual "new" it "should validate the arguments of the 'set' call", -> arraySet = -> post.set "title", "value" expect(arraySet).toThrow() objectSet = -> post.set "title": "value" expect(objectSet).not.toThrow() describe "events", -> post = null beforeEach -> post = new Post title: "title" it "should trigger a change event when any attributes change", -> callback = sinon.spy() post.bind "change", callback (expect callback).not.toHaveBeenCalled() post.set title: "new", foo: "bar" (expect callback).toHaveBeenCalledWith(post, ["title", "foo"]) it "should trigger a change event when specific attributes change", -> titleCallback = sinon.spy() post.bind "change:title", titleCallback fooCallback = sinon.spy() post.bind "change:foo", fooCallback (expect titleCallback).not.toHaveBeenCalled() (expect fooCallback).not.toHaveBeenCalled() post.set title: "new" (expect titleCallback).toHaveBeenCalledWith(post, "title", "new") (expect fooCallback).not.toHaveBeenCalled() it "should not trigger a specific change event for fields that are set but did not change", -> callback = sinon.spy() post.bind "change:title", callback (expect callback).not.toHaveBeenCalled() post.set title: "title" (expect callback).not.toHaveBeenCalled() it "should not trigger a global change event for fields that are set but did not change", -> callback = sinon.spy() post.bind "change", callback (expect callback).not.toHaveBeenCalled() post.set title: "title" (expect callback).not.toHaveBeenCalled() post.set title: "title", foo: "bar" (expect callback).toHaveBeenCalledWith(post, ["foo"]) describe "with defaults", -> poster = firstName: "<NAME>" lastName: "<NAME>" class PostWithDefaults extends Stem.Model defaults: title: "default" body: "body" poster: poster it "should initialize with its defaults", -> post = new PostWithDefaults (expect post.get "title").toEqual "default" (expect post.get "body").toEqual "body" it "should priorize attributes passed at the constructor over its defaults", -> post = new PostWithDefaults title: "overridden" (expect post.get "title").toEqual "overridden" (expect post.get "body").toEqual "body" it "should deep copy from its defaults when building an instance", -> post = new PostWithDefaults expect(post.get "poster").not.toBe poster expect(post.get "poster").toEqual poster describe "snapshots", -> it "should allow taking a snapshot of the current objects", -> post = new Stem.Model title: "new" expect(post.currentSnapshot).toBeUndefined() post.snapshot() expect(post.currentSnapshot).toBeDefined() expect(post.currentSnapshot["title"]).toEqual "new" it "should make deep copies for snapshots", -> poster = firstName: "<NAME>" lastName: "<NAME>" post = new Stem.Model title: "new" poster: poster expect(post.get "poster").toBe poster post.snapshot() expect(post.currentSnapshot["poster"]).not.toBe poster expect(post.currentSnapshot["poster"]).toEqual poster it "should allow restoring attributes from snapshots", -> post = new Stem.Model title: "new" post.snapshot() post.set title: "changed" post.restore "title" expect(post.get "title").toEqual "new" it "should allow restoring multiple attributes from snapshots", -> post = new Stem.Model title: "new" body: "body" post.snapshot() post.set title: "changed", body: "also changed" post.restore "title", "body" expect(post.get "title").toEqual "new" expect(post.get "body").toEqual "body" describe "A model with hooks", -> class Post extends Stem.Model beforeSet: (attributes) -> attributes.title = "intercepted" it "should allow to modify attributes before they are set (beforeSet)", -> post = new Post title: "new" post.set title: "changed" (expect post.get "title").toEqual "intercepted"
true
describe "Model", -> describe "A simple model", -> class Post extends Stem.Model it "should implement Events", -> post = new Post (expect post["bind"]).toBeDefined() (expect post["trigger"]).toBeDefined() describe "with attributes", -> post = null poster = firstName: "PI:NAME:<NAME>END_PI" lastName: "PI:NAME:<NAME>END_PI" beforeEach -> post = new Post title: "title" poster: poster it "should be initialized with initial values", -> (expect post["attributes"]).toBeDefined() (expect post.attributes["title"]).toEqual "title" it "should use the initial values by reference (not cloned)", -> expect(post.get "poster").toBe poster it "should get an attribute", -> (expect post.get "title").toEqual "title" it "should set an attribute", -> post.set title: "new" (expect post.get "title").toEqual "new" it "should validate the arguments of the 'set' call", -> arraySet = -> post.set "title", "value" expect(arraySet).toThrow() objectSet = -> post.set "title": "value" expect(objectSet).not.toThrow() describe "events", -> post = null beforeEach -> post = new Post title: "title" it "should trigger a change event when any attributes change", -> callback = sinon.spy() post.bind "change", callback (expect callback).not.toHaveBeenCalled() post.set title: "new", foo: "bar" (expect callback).toHaveBeenCalledWith(post, ["title", "foo"]) it "should trigger a change event when specific attributes change", -> titleCallback = sinon.spy() post.bind "change:title", titleCallback fooCallback = sinon.spy() post.bind "change:foo", fooCallback (expect titleCallback).not.toHaveBeenCalled() (expect fooCallback).not.toHaveBeenCalled() post.set title: "new" (expect titleCallback).toHaveBeenCalledWith(post, "title", "new") (expect fooCallback).not.toHaveBeenCalled() it "should not trigger a specific change event for fields that are set but did not change", -> callback = sinon.spy() post.bind "change:title", callback (expect callback).not.toHaveBeenCalled() post.set title: "title" (expect callback).not.toHaveBeenCalled() it "should not trigger a global change event for fields that are set but did not change", -> callback = sinon.spy() post.bind "change", callback (expect callback).not.toHaveBeenCalled() post.set title: "title" (expect callback).not.toHaveBeenCalled() post.set title: "title", foo: "bar" (expect callback).toHaveBeenCalledWith(post, ["foo"]) describe "with defaults", -> poster = firstName: "PI:NAME:<NAME>END_PI" lastName: "PI:NAME:<NAME>END_PI" class PostWithDefaults extends Stem.Model defaults: title: "default" body: "body" poster: poster it "should initialize with its defaults", -> post = new PostWithDefaults (expect post.get "title").toEqual "default" (expect post.get "body").toEqual "body" it "should priorize attributes passed at the constructor over its defaults", -> post = new PostWithDefaults title: "overridden" (expect post.get "title").toEqual "overridden" (expect post.get "body").toEqual "body" it "should deep copy from its defaults when building an instance", -> post = new PostWithDefaults expect(post.get "poster").not.toBe poster expect(post.get "poster").toEqual poster describe "snapshots", -> it "should allow taking a snapshot of the current objects", -> post = new Stem.Model title: "new" expect(post.currentSnapshot).toBeUndefined() post.snapshot() expect(post.currentSnapshot).toBeDefined() expect(post.currentSnapshot["title"]).toEqual "new" it "should make deep copies for snapshots", -> poster = firstName: "PI:NAME:<NAME>END_PI" lastName: "PI:NAME:<NAME>END_PI" post = new Stem.Model title: "new" poster: poster expect(post.get "poster").toBe poster post.snapshot() expect(post.currentSnapshot["poster"]).not.toBe poster expect(post.currentSnapshot["poster"]).toEqual poster it "should allow restoring attributes from snapshots", -> post = new Stem.Model title: "new" post.snapshot() post.set title: "changed" post.restore "title" expect(post.get "title").toEqual "new" it "should allow restoring multiple attributes from snapshots", -> post = new Stem.Model title: "new" body: "body" post.snapshot() post.set title: "changed", body: "also changed" post.restore "title", "body" expect(post.get "title").toEqual "new" expect(post.get "body").toEqual "body" describe "A model with hooks", -> class Post extends Stem.Model beforeSet: (attributes) -> attributes.title = "intercepted" it "should allow to modify attributes before they are set (beforeSet)", -> post = new Post title: "new" post.set title: "changed" (expect post.get "title").toEqual "intercepted"
[ { "context": "#\n# HelloIe main file\n#\n# Copyright (C) 2013 Nikolay Nemshilov\n#\n\ninclude 'src/hello_ie'\n\n# export your objects ", "end": 62, "score": 0.999882161617279, "start": 45, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
E002/hello-ie/main.coffee
lovely-io/lovely.io-show
1
# # HelloIe main file # # Copyright (C) 2013 Nikolay Nemshilov # include 'src/hello_ie' # export your objects in the module exports.version = '%{version}' exports.show = show exports.hide = hide try document.createElement('<input/>') window.attachEvent('onload', show) catch e
171825
# # HelloIe main file # # Copyright (C) 2013 <NAME> # include 'src/hello_ie' # export your objects in the module exports.version = '%{version}' exports.show = show exports.hide = hide try document.createElement('<input/>') window.attachEvent('onload', show) catch e
true
# # HelloIe main file # # Copyright (C) 2013 PI:NAME:<NAME>END_PI # include 'src/hello_ie' # export your objects in the module exports.version = '%{version}' exports.show = show exports.hide = hide try document.createElement('<input/>') window.attachEvent('onload', show) catch e
[ { "context": " treeHash: '154e26c78fd74d0c2c9b3cc4644191619dc4f2cd539ae2a74d5fd07957a3ee6a'\n\n expect(glacie", "end": 1779, "score": 0.5146382451057434, "start": 1778, "tag": "KEY", "value": "2" }, { "context": "reeHash: '154e26c78fd74d0c2c9b3cc4644191619dc4f2cd539ae2a74d5fd...
node_modules/grunt-aws/node_modules/aws-sdk/test/services/glacier.spec.coffee
wcharczuk/katrinacaspelich.com
1
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. helpers = require('../helpers') AWS = helpers.AWS Buffer = require('buffer').Buffer if AWS.util.isNode() require('../../lib/services/glacier') describe 'AWS.Glacier', -> glacier = null beforeEach -> glacier = new AWS.Glacier() describe 'building requests', -> it 'sets accountId to "-" if not set', -> req = glacier.listVaults() req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).toEqual('/-/vaults') it 'will not override accountId if set', -> req = glacier.listVaults(accountId: 'ABC123') req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).toEqual('/ABC123/vaults') describe 'computeChecksums', -> it 'returns correct linear and tree hash for buffer data', -> # compute a 5.5 megabyte chunk of data filled with '0' string (0 byte) # expected values taken from AWS SDK for Ruby data = new Buffer(1024 * 1024 * 5.5) data.fill('0') expected = linearHash: '68aff0c5a91aa0491752bfb96e3fef33eb74953804f6a2f7b708d5bcefa8ff6b', treeHash: '154e26c78fd74d0c2c9b3cc4644191619dc4f2cd539ae2a74d5fd07957a3ee6a' expect(glacier.computeChecksums(data)).toEqual(expected) describe 'initiateJob', -> it 'correctly builds the request', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' jobParameters: Format: 'foo' Type: 'bar' glacier.initiateJob params, (err, data) -> req = this.request.httpRequest expect(req.path).toEqual('/-/vaults/vault-name/jobs') expect(req.body).toEqual('{"Format":"foo","Type":"bar"}') describe 'uploadArchive', -> it 'passes the body along', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' body: 'abc' glacier.uploadArchive params, (err, data) -> req = this.request.httpRequest expect(req.method).toEqual('POST') expect(req.path).toEqual('/-/vaults/vault-name/archives') expect(req.body).toEqual('abc')
1246
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. helpers = require('../helpers') AWS = helpers.AWS Buffer = require('buffer').Buffer if AWS.util.isNode() require('../../lib/services/glacier') describe 'AWS.Glacier', -> glacier = null beforeEach -> glacier = new AWS.Glacier() describe 'building requests', -> it 'sets accountId to "-" if not set', -> req = glacier.listVaults() req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).toEqual('/-/vaults') it 'will not override accountId if set', -> req = glacier.listVaults(accountId: 'ABC123') req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).toEqual('/ABC123/vaults') describe 'computeChecksums', -> it 'returns correct linear and tree hash for buffer data', -> # compute a 5.5 megabyte chunk of data filled with '0' string (0 byte) # expected values taken from AWS SDK for Ruby data = new Buffer(1024 * 1024 * 5.5) data.fill('0') expected = linearHash: '68aff0c5a91aa0491752bfb96e3fef33eb74953804f6a2f7b708d5bcefa8ff6b', treeHash: '154e26c78fd74d0c2c9b3cc4644191619dc4f<KEY>cd<KEY>39ae2a74d<KEY>fd07957a3ee6a' expect(glacier.computeChecksums(data)).toEqual(expected) describe 'initiateJob', -> it 'correctly builds the request', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' jobParameters: Format: 'foo' Type: 'bar' glacier.initiateJob params, (err, data) -> req = this.request.httpRequest expect(req.path).toEqual('/-/vaults/vault-name/jobs') expect(req.body).toEqual('{"Format":"foo","Type":"bar"}') describe 'uploadArchive', -> it 'passes the body along', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' body: 'abc' glacier.uploadArchive params, (err, data) -> req = this.request.httpRequest expect(req.method).toEqual('POST') expect(req.path).toEqual('/-/vaults/vault-name/archives') expect(req.body).toEqual('abc')
true
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. helpers = require('../helpers') AWS = helpers.AWS Buffer = require('buffer').Buffer if AWS.util.isNode() require('../../lib/services/glacier') describe 'AWS.Glacier', -> glacier = null beforeEach -> glacier = new AWS.Glacier() describe 'building requests', -> it 'sets accountId to "-" if not set', -> req = glacier.listVaults() req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).toEqual('/-/vaults') it 'will not override accountId if set', -> req = glacier.listVaults(accountId: 'ABC123') req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).toEqual('/ABC123/vaults') describe 'computeChecksums', -> it 'returns correct linear and tree hash for buffer data', -> # compute a 5.5 megabyte chunk of data filled with '0' string (0 byte) # expected values taken from AWS SDK for Ruby data = new Buffer(1024 * 1024 * 5.5) data.fill('0') expected = linearHash: '68aff0c5a91aa0491752bfb96e3fef33eb74953804f6a2f7b708d5bcefa8ff6b', treeHash: '154e26c78fd74d0c2c9b3cc4644191619dc4fPI:KEY:<KEY>END_PIcdPI:KEY:<KEY>END_PI39ae2a74dPI:KEY:<KEY>END_PIfd07957a3ee6a' expect(glacier.computeChecksums(data)).toEqual(expected) describe 'initiateJob', -> it 'correctly builds the request', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' jobParameters: Format: 'foo' Type: 'bar' glacier.initiateJob params, (err, data) -> req = this.request.httpRequest expect(req.path).toEqual('/-/vaults/vault-name/jobs') expect(req.body).toEqual('{"Format":"foo","Type":"bar"}') describe 'uploadArchive', -> it 'passes the body along', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' body: 'abc' glacier.uploadArchive params, (err, data) -> req = this.request.httpRequest expect(req.method).toEqual('POST') expect(req.path).toEqual('/-/vaults/vault-name/archives') expect(req.body).toEqual('abc')
[ { "context": "e')\n {token} = challenge\n keyAuthorization = \"#{token}.#{@jws.thumbprint}\"\n\n # Create server to respon", "end": 1696, "score": 0.86882084608078, "start": 1686, "tag": "KEY", "value": "\"#{token}." }, { "context": " keyAuthorization = \"#{token}.#{@jws....
src/acme-protocol.coffee
themadcreator/acme-express
6
http = require 'http' Promise = require 'bluebird' chalk = require 'chalk' logger = require './logger' {JwsClient} = require './jws-client' class AcmeProtocol constructor : (@jws) -> getCertificate : (domain, certificateDER) -> return Promise.resolve() .then(@register) .then(=> @authorize(domain)) .then(@challengeResponse) .then(=> @sign(certificateDER)) register : => logger.info chalk.blue '\nRegistering account' return @jws.jwsRequest('/acme/new-reg', { resource : 'new-reg' agreement : 'https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf' }).then((res) -> switch res.statusCode when 201 then logger.info chalk.green 'OK' when 409 then logger.info chalk.green 'OK - already registered' else throw new Error("Registration failed #{res.statusCode}") ) authorize : (domain) => logger.info chalk.blue "\nAuthorizing domain '#{domain}'" return @jws.jwsRequest('/acme/new-authz', { resource : 'new-authz' identifier : type : 'dns' value : domain }).then((res) -> if res.statusCode isnt 201 then throw new Error("Authorization failed #{res.statusCode}") logger.info chalk.green 'OK' return JSON.parse(res.body.toString('utf8')) ) challengeResponse : (authorization) => logger.info chalk.blue '\nPerforming challenge/response' # Extract HTTP challenge token {challenges} = authorization challenge = challenges.filter((c) -> c.type is 'http-01')[0] if not challenge? then throw new Error('No HTTP challenge available') {token} = challenge keyAuthorization = "#{token}.#{@jws.thumbprint}" # Create server to respond to challenge logger.info ' Serving challenge token', chalk.yellow token wellknownChallengePath = "/.well-known/acme-challenge/#{token}" server = http.createServer((req, res)-> if req.url is wellknownChallengePath logger.info chalk.yellow ' Got request at token url...' res.statusCode = 200 res.end(keyAuthorization) else logger.info chalk.red ' Got request at unexpected url', req.url res.statusCode = 404 res.end() ) # Start server and inform CA we are ready for challenge server.listen(80, => logger.info ' Listening on port 80' @jws.jwsRequestUrl(challenge.uri, { resource : 'challenge' keyAuthorization : keyAuthorization }) ) # Poll status every 1 sec until we know if challenge succeeded return new Promise((resolve, reject) => pollStatus = => @jws.httpRequest(challenge.uri).then((res) -> {status} = JSON.parse(res.body.toString('utf8')) logger.info " Challenge status is '#{chalk.yellow status}'..." if status isnt 'pending' return server.close(-> logger.info ' Server stopped' if status is 'valid' logger.info chalk.green 'OK' resolve(status) else reject(new Error("Failed challenge/response with status '#{status}'. Make sure this server is accessible at the domain URL.")) ) setTimeout(pollStatus, 1000) ) pollStatus() ) sign : (certificateDER) -> logger.info chalk.blue '\nSigning certificate' return @jws.jwsRequest('/acme/new-cert', { resource : 'new-cert' csr : JwsClient.toBase64(certificateDER) }).then((res) -> if res.statusCode isnt 201 then throw new Error("Signing failed with code #{res.statusCode}") logger.info chalk.green 'OK' if res.headers.location? then logger.info 'Certificate available for download at', chalk.yellow res.headers.location certblock = res.body.toString('base64').replace(/(.{64})/g, '$1\n') return """ -----BEGIN CERTIFICATE----- #{certblock} -----END CERTIFICATE----- """ ) module.exports = {AcmeProtocol}
226011
http = require 'http' Promise = require 'bluebird' chalk = require 'chalk' logger = require './logger' {JwsClient} = require './jws-client' class AcmeProtocol constructor : (@jws) -> getCertificate : (domain, certificateDER) -> return Promise.resolve() .then(@register) .then(=> @authorize(domain)) .then(@challengeResponse) .then(=> @sign(certificateDER)) register : => logger.info chalk.blue '\nRegistering account' return @jws.jwsRequest('/acme/new-reg', { resource : 'new-reg' agreement : 'https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf' }).then((res) -> switch res.statusCode when 201 then logger.info chalk.green 'OK' when 409 then logger.info chalk.green 'OK - already registered' else throw new Error("Registration failed #{res.statusCode}") ) authorize : (domain) => logger.info chalk.blue "\nAuthorizing domain '#{domain}'" return @jws.jwsRequest('/acme/new-authz', { resource : 'new-authz' identifier : type : 'dns' value : domain }).then((res) -> if res.statusCode isnt 201 then throw new Error("Authorization failed #{res.statusCode}") logger.info chalk.green 'OK' return JSON.parse(res.body.toString('utf8')) ) challengeResponse : (authorization) => logger.info chalk.blue '\nPerforming challenge/response' # Extract HTTP challenge token {challenges} = authorization challenge = challenges.filter((c) -> c.type is 'http-01')[0] if not challenge? then throw new Error('No HTTP challenge available') {token} = challenge keyAuthorization = <KEY>#{@jws.thumbprint<KEY>}" # Create server to respond to challenge logger.info ' Serving challenge token', chalk.yellow token wellknownChallengePath = "/.well-known/acme-challenge/#{token}" server = http.createServer((req, res)-> if req.url is wellknownChallengePath logger.info chalk.yellow ' Got request at token url...' res.statusCode = 200 res.end(keyAuthorization) else logger.info chalk.red ' Got request at unexpected url', req.url res.statusCode = 404 res.end() ) # Start server and inform CA we are ready for challenge server.listen(80, => logger.info ' Listening on port 80' @jws.jwsRequestUrl(challenge.uri, { resource : 'challenge' keyAuthorization : keyAuthorization }) ) # Poll status every 1 sec until we know if challenge succeeded return new Promise((resolve, reject) => pollStatus = => @jws.httpRequest(challenge.uri).then((res) -> {status} = JSON.parse(res.body.toString('utf8')) logger.info " Challenge status is '#{chalk.yellow status}'..." if status isnt 'pending' return server.close(-> logger.info ' Server stopped' if status is 'valid' logger.info chalk.green 'OK' resolve(status) else reject(new Error("Failed challenge/response with status '#{status}'. Make sure this server is accessible at the domain URL.")) ) setTimeout(pollStatus, 1000) ) pollStatus() ) sign : (certificateDER) -> logger.info chalk.blue '\nSigning certificate' return @jws.jwsRequest('/acme/new-cert', { resource : 'new-cert' csr : JwsClient.toBase64(certificateDER) }).then((res) -> if res.statusCode isnt 201 then throw new Error("Signing failed with code #{res.statusCode}") logger.info chalk.green 'OK' if res.headers.location? then logger.info 'Certificate available for download at', chalk.yellow res.headers.location certblock = res.body.toString('base64').replace(/(.{64})/g, '$1\n') return """ -----BEGIN CERTIFICATE----- #{certblock} -----END CERTIFICATE----- """ ) module.exports = {AcmeProtocol}
true
http = require 'http' Promise = require 'bluebird' chalk = require 'chalk' logger = require './logger' {JwsClient} = require './jws-client' class AcmeProtocol constructor : (@jws) -> getCertificate : (domain, certificateDER) -> return Promise.resolve() .then(@register) .then(=> @authorize(domain)) .then(@challengeResponse) .then(=> @sign(certificateDER)) register : => logger.info chalk.blue '\nRegistering account' return @jws.jwsRequest('/acme/new-reg', { resource : 'new-reg' agreement : 'https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf' }).then((res) -> switch res.statusCode when 201 then logger.info chalk.green 'OK' when 409 then logger.info chalk.green 'OK - already registered' else throw new Error("Registration failed #{res.statusCode}") ) authorize : (domain) => logger.info chalk.blue "\nAuthorizing domain '#{domain}'" return @jws.jwsRequest('/acme/new-authz', { resource : 'new-authz' identifier : type : 'dns' value : domain }).then((res) -> if res.statusCode isnt 201 then throw new Error("Authorization failed #{res.statusCode}") logger.info chalk.green 'OK' return JSON.parse(res.body.toString('utf8')) ) challengeResponse : (authorization) => logger.info chalk.blue '\nPerforming challenge/response' # Extract HTTP challenge token {challenges} = authorization challenge = challenges.filter((c) -> c.type is 'http-01')[0] if not challenge? then throw new Error('No HTTP challenge available') {token} = challenge keyAuthorization = PI:KEY:<KEY>END_PI#{@jws.thumbprintPI:KEY:<KEY>END_PI}" # Create server to respond to challenge logger.info ' Serving challenge token', chalk.yellow token wellknownChallengePath = "/.well-known/acme-challenge/#{token}" server = http.createServer((req, res)-> if req.url is wellknownChallengePath logger.info chalk.yellow ' Got request at token url...' res.statusCode = 200 res.end(keyAuthorization) else logger.info chalk.red ' Got request at unexpected url', req.url res.statusCode = 404 res.end() ) # Start server and inform CA we are ready for challenge server.listen(80, => logger.info ' Listening on port 80' @jws.jwsRequestUrl(challenge.uri, { resource : 'challenge' keyAuthorization : keyAuthorization }) ) # Poll status every 1 sec until we know if challenge succeeded return new Promise((resolve, reject) => pollStatus = => @jws.httpRequest(challenge.uri).then((res) -> {status} = JSON.parse(res.body.toString('utf8')) logger.info " Challenge status is '#{chalk.yellow status}'..." if status isnt 'pending' return server.close(-> logger.info ' Server stopped' if status is 'valid' logger.info chalk.green 'OK' resolve(status) else reject(new Error("Failed challenge/response with status '#{status}'. Make sure this server is accessible at the domain URL.")) ) setTimeout(pollStatus, 1000) ) pollStatus() ) sign : (certificateDER) -> logger.info chalk.blue '\nSigning certificate' return @jws.jwsRequest('/acme/new-cert', { resource : 'new-cert' csr : JwsClient.toBase64(certificateDER) }).then((res) -> if res.statusCode isnt 201 then throw new Error("Signing failed with code #{res.statusCode}") logger.info chalk.green 'OK' if res.headers.location? then logger.info 'Certificate available for download at', chalk.yellow res.headers.location certblock = res.body.toString('base64').replace(/(.{64})/g, '$1\n') return """ -----BEGIN CERTIFICATE----- #{certblock} -----END CERTIFICATE----- """ ) module.exports = {AcmeProtocol}
[ { "context": " backbone-orm.js 0.7.14\n Copyright (c) 2013-2016 Vidigami\n License: MIT (http://www.opensource.org/license", "end": 63, "score": 0.9998822808265686, "start": 55, "tag": "NAME", "value": "Vidigami" }, { "context": "ses/mit-license.php)\n Source: https://github.com/...
src/lib/connection_pool.coffee
dk-dev/backbone-orm
54
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 Vidigami License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### MemoryStore = require '../cache/memory_store' module.exports = new MemoryStore({destroy: (url, connection) -> connection.destroy()})
217796
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 <NAME> License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### MemoryStore = require '../cache/memory_store' module.exports = new MemoryStore({destroy: (url, connection) -> connection.destroy()})
true
### backbone-orm.js 0.7.14 Copyright (c) 2013-2016 PI:NAME:<NAME>END_PI License: MIT (http://www.opensource.org/licenses/mit-license.php) Source: https://github.com/vidigami/backbone-orm Dependencies: Backbone.js and Underscore.js. ### MemoryStore = require '../cache/memory_store' module.exports = new MemoryStore({destroy: (url, connection) -> connection.destroy()})
[ { "context": "class @Options\n @key: 'drone-notifier'\n @defaults:\n host: 'drone.io'\n service: '", "end": 38, "score": 0.9961197376251221, "start": 24, "tag": "KEY", "value": "drone-notifier" } ]
app/scripts/options.coffee
akiomik/drone-notifier
0
class @Options @key: 'drone-notifier' @defaults: host: 'drone.io' service: 'github.com' repository: '' @fetch: -> item = localStorage.getItem @key JSON.parse item @init: -> options = Options.defaults Options.save options options @save: (options) -> item = JSON.stringify options localStorage.setItem @key, item
12449
class @Options @key: '<KEY>' @defaults: host: 'drone.io' service: 'github.com' repository: '' @fetch: -> item = localStorage.getItem @key JSON.parse item @init: -> options = Options.defaults Options.save options options @save: (options) -> item = JSON.stringify options localStorage.setItem @key, item
true
class @Options @key: 'PI:KEY:<KEY>END_PI' @defaults: host: 'drone.io' service: 'github.com' repository: '' @fetch: -> item = localStorage.getItem @key JSON.parse item @init: -> options = Options.defaults Options.save options options @save: (options) -> item = JSON.stringify options localStorage.setItem @key, item
[ { "context": "OFTWARE.\n\nangular-google-maps\nhttps://github.com/nlaplante/angular-google-maps\n\n@authors\nAdam Kreitals, krei", "end": 1154, "score": 0.6667580008506775, "start": 1146, "tag": "USERNAME", "value": "laplante" }, { "context": "ithub.com/nlaplante/angular-google-maps\...
bower_components/angular-google-maps-init/src/coffee/directives/control.coffee
aditioan/naturapass
1
### ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors Adam Kreitals, kreitals@hotmail.com ### ### mapControl directive This directive is used to create a custom control element on an existing map. This directive creates a new scope. {attribute template required} string url of the template to be used for the control {attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER {attribute controller optional} string controller to be applied to the template {attribute index optional} number index for controlling the order of similarly positioned mapControl elements ### angular.module("google-maps") .directive "mapControl", ["Control", (Control) -> new Control() ]
181745
### ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors <NAME>, <EMAIL> ### ### mapControl directive This directive is used to create a custom control element on an existing map. This directive creates a new scope. {attribute template required} string url of the template to be used for the control {attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER {attribute controller optional} string controller to be applied to the template {attribute index optional} number index for controlling the order of similarly positioned mapControl elements ### angular.module("google-maps") .directive "mapControl", ["Control", (Control) -> new Control() ]
true
### ! The MIT License Copyright (c) 2010-2013 Google, Inc. http://angularjs.org 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. angular-google-maps https://github.com/nlaplante/angular-google-maps @authors PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI ### ### mapControl directive This directive is used to create a custom control element on an existing map. This directive creates a new scope. {attribute template required} string url of the template to be used for the control {attribute position optional} string position of the control of the form top-left or TOP_LEFT defaults to TOP_CENTER {attribute controller optional} string controller to be applied to the template {attribute index optional} number index for controlling the order of similarly positioned mapControl elements ### angular.module("google-maps") .directive "mapControl", ["Control", (Control) -> new Control() ]
[ { "context": "= require 'os'\ncrypto = require 'crypto'\n\n# e.g. /var/folders/zm/jmjb49l172g6g_h1y8701spc0000gn/T/\nTMPDIR = os.tmpDir()\n\nfileExistSync = (filePath) ", "end": 181, "score": 0.9961585998535156, "start": 133, "tag": "KEY", "value": "var/folders/zm/jmjb49l172g6g_h1y8701spc000...
lib/cache.coffee
FGRibreau/piler
1
# # Don't uglify again files if they didn't change # fs = require 'fs' os = require 'os' crypto = require 'crypto' # e.g. /var/folders/zm/jmjb49l172g6g_h1y8701spc0000gn/T/ TMPDIR = os.tmpDir() fileExistSync = (filePath) -> try fs.statSync(filePath) catch err if err.code == 'ENOENT' return false return true # Return a compressed version (already cached or not) of `code`, this function is synchronous module.exports = (code, fnCompress) -> hash = crypto.createHash('sha1').update(code).digest('hex') file = TMPDIR+'/'+hash # if already in cache return fs.readFileSync(file, 'utf8') if fileExistSync(file) # if not: compress the code cache = fnCompress() # write the file fs.writeFileSync(file, cache, 'utf8') # .. and return the compressed version cache
189653
# # Don't uglify again files if they didn't change # fs = require 'fs' os = require 'os' crypto = require 'crypto' # e.g. /<KEY> TMPDIR = os.tmpDir() fileExistSync = (filePath) -> try fs.statSync(filePath) catch err if err.code == 'ENOENT' return false return true # Return a compressed version (already cached or not) of `code`, this function is synchronous module.exports = (code, fnCompress) -> hash = crypto.createHash('sha1').update(code).digest('hex') file = TMPDIR+'/'+hash # if already in cache return fs.readFileSync(file, 'utf8') if fileExistSync(file) # if not: compress the code cache = fnCompress() # write the file fs.writeFileSync(file, cache, 'utf8') # .. and return the compressed version cache
true
# # Don't uglify again files if they didn't change # fs = require 'fs' os = require 'os' crypto = require 'crypto' # e.g. /PI:KEY:<KEY>END_PI TMPDIR = os.tmpDir() fileExistSync = (filePath) -> try fs.statSync(filePath) catch err if err.code == 'ENOENT' return false return true # Return a compressed version (already cached or not) of `code`, this function is synchronous module.exports = (code, fnCompress) -> hash = crypto.createHash('sha1').update(code).digest('hex') file = TMPDIR+'/'+hash # if already in cache return fs.readFileSync(file, 'utf8') if fileExistSync(file) # if not: compress the code cache = fnCompress() # write the file fs.writeFileSync(file, cache, 'utf8') # .. and return the compressed version cache
[ { "context": "# @author Gianluigi Mango\n# Post Model\nmongoose = require 'mongoose'\n\nmodul", "end": 25, "score": 0.9998736381530762, "start": 10, "tag": "NAME", "value": "Gianluigi Mango" } ]
dev/server/models/postModel.coffee
knickatheart/mean-api
0
# @author Gianluigi Mango # Post Model mongoose = require 'mongoose' module.exports = mongoose.model 'Post', mongoose.Schema parent: String, data: String, active: Number, reactions: Array, comments: Array, createdAt: String 'posts'
215771
# @author <NAME> # Post Model mongoose = require 'mongoose' module.exports = mongoose.model 'Post', mongoose.Schema parent: String, data: String, active: Number, reactions: Array, comments: Array, createdAt: String 'posts'
true
# @author PI:NAME:<NAME>END_PI # Post Model mongoose = require 'mongoose' module.exports = mongoose.model 'Post', mongoose.Schema parent: String, data: String, active: Number, reactions: Array, comments: Array, createdAt: String 'posts'
[ { "context": "ser = robot.brain.userForId '1', {\n name: 'user'\n room: '#test'\n }\n\n adapter = r", "end": 635, "score": 0.5221601724624634, "start": 631, "tag": "NAME", "value": "user" }, { "context": "strings) ->\n expect(strings[0]).to.match /@user...
test/factoids_test.coffee
adglueck/hubot-factoids
4
chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' expect = chai.expect Robot = require 'hubot/src/robot' TextMessage = require('hubot/src/message').TextMessage describe 'factoids', -> robot = {} user = {} adapter = {} spies = {} beforeEach (done) -> # Create new robot, with http, using mock adapter robot = new Robot null, 'mock-adapter', false robot.adapter.on 'connected', => spies.hear = sinon.spy(robot, 'hear') spies.respond = sinon.spy(robot, 'respond') require('../src/factoids')(robot) user = robot.brain.userForId '1', { name: 'user' room: '#test' } adapter = robot.adapter robot.run() done() afterEach -> robot.shutdown() describe 'listeners', -> it 'registered hear !factoid', -> expect(spies.hear).to.have.been.calledWith(/^[!]([\w\s-]{2,}\w)( @.+)?/i) it 'registered respond learn', -> expect(spies.respond).to.have.been.calledWith(/learn (.{3,}) = ([^@].+)/i) it 'registered respond learn substitution', -> expect(spies.respond).to.have.been.calledWith(/learn (.{3,}) =~ s\/(.+)\/(.+)\/(.*)/i) it 'registered respond forget', -> expect(spies.respond).to.have.been.calledWith(/forget (.{3,})/i) it 'registered respond remember', -> expect(spies.respond).to.have.been.calledWith(/remember (.{3,})/i) it 'registered respond factoids', -> expect(spies.respond).to.have.been.calledWith(/factoids?/i) it 'registered respond search', -> expect(spies.respond).to.have.been.calledWith(/search (.{3,})/i) it 'registered respond alias', -> expect(spies.respond).to.have.been.calledWith(/alias (.{3,}) = (.{3,})/i) it 'registered respond drop', -> expect(spies.respond).to.have.been.calledWith(/drop (.{3,})/i) describe 'new factoids', -> it 'responds to learn', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo is now bar/ done() adapter.receive(new TextMessage user, 'hubot: learn foo = bar') describe 'existing factoids', -> beforeEach -> robot.brain.data.factoids.foo = value: 'bar' robot.brain.data.factoids.foobar = value: 'baz' robot.brain.data.factoids.barbaz = value: 'foo' robot.brain.data.factoids.qix = value: 'bar' robot.brain.data.factoids.qux = value: 'baz' it 'responds to !factoid', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.match /user: bar/ done() adapter.receive(new TextMessage user, '!foo') it 'responds to !factoid @mention', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.match /@user2: bar/ done() adapter.receive(new TextMessage user, '!foo @user2') it 'responds to learn substitution', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo is now qux/ done() adapter.receive(new TextMessage user, 'hubot: learn foo =~ s/bar/qux/i') it 'responds to forget', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, forgot foo/ done() adapter.receive(new TextMessage user, 'hubot: forget foo') it 'responds to search', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /.* the following factoids: .*!foobar/ expect(strings[0]).to.match /.* the following factoids: .*!barbaz/ expect(strings[0]).to.match /.* the following factoids: .*!qix/ expect(strings[0]).not.to.match /.* the following factoids: .*!qux/ done() adapter.receive(new TextMessage user, 'hubot: search bar') it 'responds to alias', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, aliased baz to foo/ done() adapter.receive(new TextMessage user, 'hubot: alias baz = foo') it 'responds to drop', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo has been dropped/ done() adapter.receive(new TextMessage user, 'hubot: drop foo') describe 'forgotten factoids', -> beforeEach -> robot.brain.data.factoids.foo = value: 'bar', forgotten: true it 'responds to remember', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo is bar/ done() adapter.receive(new TextMessage user, 'hubot: remember foo') it 'responds to factoids', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /http:\/\/not-yet-set\/.*\/factoids/ done() adapter.receive(new TextMessage user, 'hubot: factoids') describe 'list all factoids', -> beforeEach -> robot.brain.data.factoids.foo = value: 'bar', forgotten: true robot.brain.data.factoids.bas = value: 'baz', forgotten: false it 'responds to list all factoids', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /All factoids: \n!bas: baz\n/ done() adapter.receive(new TextMessage user, 'hubot: list all factoids') it 'responds to list all factoids, empty list', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /No factoids defined/ done() adapter.receive(new TextMessage user, 'hubot: list all factoids') it 'responds to invalid !factoid', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, '!foo') it 'responds to invalid learn substitution', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, 'hubot: learn foo =~ s/bar/baz/gi') it 'responds to invalid forget', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, 'hubot: forget foo') it 'responds to invalid drop', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, 'hubot: drop foo') describe 'factoids customization', -> robot = {} user = {} adapter = {} spies = {} beforeEach (done) -> process.env.HUBOT_FACTOID_PREFIX = '?' # Create new robot, with http, using mock adapter robot = new Robot null, 'mock-adapter', false robot.adapter.on 'connected', => spies.hear = sinon.spy(robot, 'hear') spies.respond = sinon.spy(robot, 'respond') require('../src/factoids')(robot) user = robot.brain.userForId '1', { name: 'user' room: '#test' } adapter = robot.adapter robot.run() done() afterEach -> robot.shutdown() it 'can override prefix', -> expect(spies.hear).to.have.been.calledWith(/^[?]([\w\s-]{2,}\w)( @.+)?/i)
197140
chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' expect = chai.expect Robot = require 'hubot/src/robot' TextMessage = require('hubot/src/message').TextMessage describe 'factoids', -> robot = {} user = {} adapter = {} spies = {} beforeEach (done) -> # Create new robot, with http, using mock adapter robot = new Robot null, 'mock-adapter', false robot.adapter.on 'connected', => spies.hear = sinon.spy(robot, 'hear') spies.respond = sinon.spy(robot, 'respond') require('../src/factoids')(robot) user = robot.brain.userForId '1', { name: '<NAME>' room: '#test' } adapter = robot.adapter robot.run() done() afterEach -> robot.shutdown() describe 'listeners', -> it 'registered hear !factoid', -> expect(spies.hear).to.have.been.calledWith(/^[!]([\w\s-]{2,}\w)( @.+)?/i) it 'registered respond learn', -> expect(spies.respond).to.have.been.calledWith(/learn (.{3,}) = ([^@].+)/i) it 'registered respond learn substitution', -> expect(spies.respond).to.have.been.calledWith(/learn (.{3,}) =~ s\/(.+)\/(.+)\/(.*)/i) it 'registered respond forget', -> expect(spies.respond).to.have.been.calledWith(/forget (.{3,})/i) it 'registered respond remember', -> expect(spies.respond).to.have.been.calledWith(/remember (.{3,})/i) it 'registered respond factoids', -> expect(spies.respond).to.have.been.calledWith(/factoids?/i) it 'registered respond search', -> expect(spies.respond).to.have.been.calledWith(/search (.{3,})/i) it 'registered respond alias', -> expect(spies.respond).to.have.been.calledWith(/alias (.{3,}) = (.{3,})/i) it 'registered respond drop', -> expect(spies.respond).to.have.been.calledWith(/drop (.{3,})/i) describe 'new factoids', -> it 'responds to learn', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo is now bar/ done() adapter.receive(new TextMessage user, 'hubot: learn foo = bar') describe 'existing factoids', -> beforeEach -> robot.brain.data.factoids.foo = value: 'bar' robot.brain.data.factoids.foobar = value: 'baz' robot.brain.data.factoids.barbaz = value: 'foo' robot.brain.data.factoids.qix = value: 'bar' robot.brain.data.factoids.qux = value: 'baz' it 'responds to !factoid', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.match /user: bar/ done() adapter.receive(new TextMessage user, '!foo') it 'responds to !factoid @mention', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.match /@user2: bar/ done() adapter.receive(new TextMessage user, '!foo @user2') it 'responds to learn substitution', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo is now qux/ done() adapter.receive(new TextMessage user, 'hubot: learn foo =~ s/bar/qux/i') it 'responds to forget', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, forgot foo/ done() adapter.receive(new TextMessage user, 'hubot: forget foo') it 'responds to search', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /.* the following factoids: .*!foobar/ expect(strings[0]).to.match /.* the following factoids: .*!barbaz/ expect(strings[0]).to.match /.* the following factoids: .*!qix/ expect(strings[0]).not.to.match /.* the following factoids: .*!qux/ done() adapter.receive(new TextMessage user, 'hubot: search bar') it 'responds to alias', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, aliased baz to foo/ done() adapter.receive(new TextMessage user, 'hubot: alias baz = foo') it 'responds to drop', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo has been dropped/ done() adapter.receive(new TextMessage user, 'hubot: drop foo') describe 'forgotten factoids', -> beforeEach -> robot.brain.data.factoids.foo = value: 'bar', forgotten: true it 'responds to remember', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo is bar/ done() adapter.receive(new TextMessage user, 'hubot: remember foo') it 'responds to factoids', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /http:\/\/not-yet-set\/.*\/factoids/ done() adapter.receive(new TextMessage user, 'hubot: factoids') describe 'list all factoids', -> beforeEach -> robot.brain.data.factoids.foo = value: 'bar', forgotten: true robot.brain.data.factoids.bas = value: 'baz', forgotten: false it 'responds to list all factoids', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /All factoids: \n!bas: baz\n/ done() adapter.receive(new TextMessage user, 'hubot: list all factoids') it 'responds to list all factoids, empty list', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /No factoids defined/ done() adapter.receive(new TextMessage user, 'hubot: list all factoids') it 'responds to invalid !factoid', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, '!foo') it 'responds to invalid learn substitution', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, 'hubot: learn foo =~ s/bar/baz/gi') it 'responds to invalid forget', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, 'hubot: forget foo') it 'responds to invalid drop', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, 'hubot: drop foo') describe 'factoids customization', -> robot = {} user = {} adapter = {} spies = {} beforeEach (done) -> process.env.HUBOT_FACTOID_PREFIX = '?' # Create new robot, with http, using mock adapter robot = new Robot null, 'mock-adapter', false robot.adapter.on 'connected', => spies.hear = sinon.spy(robot, 'hear') spies.respond = sinon.spy(robot, 'respond') require('../src/factoids')(robot) user = robot.brain.userForId '1', { name: 'user' room: '#test' } adapter = robot.adapter robot.run() done() afterEach -> robot.shutdown() it 'can override prefix', -> expect(spies.hear).to.have.been.calledWith(/^[?]([\w\s-]{2,}\w)( @.+)?/i)
true
chai = require 'chai' sinon = require 'sinon' chai.use require 'sinon-chai' expect = chai.expect Robot = require 'hubot/src/robot' TextMessage = require('hubot/src/message').TextMessage describe 'factoids', -> robot = {} user = {} adapter = {} spies = {} beforeEach (done) -> # Create new robot, with http, using mock adapter robot = new Robot null, 'mock-adapter', false robot.adapter.on 'connected', => spies.hear = sinon.spy(robot, 'hear') spies.respond = sinon.spy(robot, 'respond') require('../src/factoids')(robot) user = robot.brain.userForId '1', { name: 'PI:NAME:<NAME>END_PI' room: '#test' } adapter = robot.adapter robot.run() done() afterEach -> robot.shutdown() describe 'listeners', -> it 'registered hear !factoid', -> expect(spies.hear).to.have.been.calledWith(/^[!]([\w\s-]{2,}\w)( @.+)?/i) it 'registered respond learn', -> expect(spies.respond).to.have.been.calledWith(/learn (.{3,}) = ([^@].+)/i) it 'registered respond learn substitution', -> expect(spies.respond).to.have.been.calledWith(/learn (.{3,}) =~ s\/(.+)\/(.+)\/(.*)/i) it 'registered respond forget', -> expect(spies.respond).to.have.been.calledWith(/forget (.{3,})/i) it 'registered respond remember', -> expect(spies.respond).to.have.been.calledWith(/remember (.{3,})/i) it 'registered respond factoids', -> expect(spies.respond).to.have.been.calledWith(/factoids?/i) it 'registered respond search', -> expect(spies.respond).to.have.been.calledWith(/search (.{3,})/i) it 'registered respond alias', -> expect(spies.respond).to.have.been.calledWith(/alias (.{3,}) = (.{3,})/i) it 'registered respond drop', -> expect(spies.respond).to.have.been.calledWith(/drop (.{3,})/i) describe 'new factoids', -> it 'responds to learn', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo is now bar/ done() adapter.receive(new TextMessage user, 'hubot: learn foo = bar') describe 'existing factoids', -> beforeEach -> robot.brain.data.factoids.foo = value: 'bar' robot.brain.data.factoids.foobar = value: 'baz' robot.brain.data.factoids.barbaz = value: 'foo' robot.brain.data.factoids.qix = value: 'bar' robot.brain.data.factoids.qux = value: 'baz' it 'responds to !factoid', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.match /user: bar/ done() adapter.receive(new TextMessage user, '!foo') it 'responds to !factoid @mention', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.match /@user2: bar/ done() adapter.receive(new TextMessage user, '!foo @user2') it 'responds to learn substitution', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo is now qux/ done() adapter.receive(new TextMessage user, 'hubot: learn foo =~ s/bar/qux/i') it 'responds to forget', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, forgot foo/ done() adapter.receive(new TextMessage user, 'hubot: forget foo') it 'responds to search', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /.* the following factoids: .*!foobar/ expect(strings[0]).to.match /.* the following factoids: .*!barbaz/ expect(strings[0]).to.match /.* the following factoids: .*!qix/ expect(strings[0]).not.to.match /.* the following factoids: .*!qux/ done() adapter.receive(new TextMessage user, 'hubot: search bar') it 'responds to alias', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, aliased baz to foo/ done() adapter.receive(new TextMessage user, 'hubot: alias baz = foo') it 'responds to drop', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo has been dropped/ done() adapter.receive(new TextMessage user, 'hubot: drop foo') describe 'forgotten factoids', -> beforeEach -> robot.brain.data.factoids.foo = value: 'bar', forgotten: true it 'responds to remember', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /OK, foo is bar/ done() adapter.receive(new TextMessage user, 'hubot: remember foo') it 'responds to factoids', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /http:\/\/not-yet-set\/.*\/factoids/ done() adapter.receive(new TextMessage user, 'hubot: factoids') describe 'list all factoids', -> beforeEach -> robot.brain.data.factoids.foo = value: 'bar', forgotten: true robot.brain.data.factoids.bas = value: 'baz', forgotten: false it 'responds to list all factoids', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /All factoids: \n!bas: baz\n/ done() adapter.receive(new TextMessage user, 'hubot: list all factoids') it 'responds to list all factoids, empty list', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /No factoids defined/ done() adapter.receive(new TextMessage user, 'hubot: list all factoids') it 'responds to invalid !factoid', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, '!foo') it 'responds to invalid learn substitution', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, 'hubot: learn foo =~ s/bar/baz/gi') it 'responds to invalid forget', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, 'hubot: forget foo') it 'responds to invalid drop', (done) -> adapter.on 'reply', (envelope, strings) -> expect(strings[0]).to.match /Not a factoid/ done() adapter.receive(new TextMessage user, 'hubot: drop foo') describe 'factoids customization', -> robot = {} user = {} adapter = {} spies = {} beforeEach (done) -> process.env.HUBOT_FACTOID_PREFIX = '?' # Create new robot, with http, using mock adapter robot = new Robot null, 'mock-adapter', false robot.adapter.on 'connected', => spies.hear = sinon.spy(robot, 'hear') spies.respond = sinon.spy(robot, 'respond') require('../src/factoids')(robot) user = robot.brain.userForId '1', { name: 'user' room: '#test' } adapter = robot.adapter robot.run() done() afterEach -> robot.shutdown() it 'can override prefix', -> expect(spies.hear).to.have.been.calledWith(/^[?]([\w\s-]{2,}\w)( @.+)?/i)
[ { "context": "\"ISSN\"', _check\n\n API.mail.send\n to: 'alert@cottagelabs.com'\n subject: 'Scratch script complete'\n ", "end": 1270, "score": 0.9999260306358337, "start": 1249, "tag": "EMAIL", "value": "alert@cottagelabs.com" } ]
server/scripts/scratch.coffee
leviathanindustries/noddy
2
'''API.add 'scripts/scratch', get: authRequired: 'root' action: () -> res = {checked: 0, withissn: 0, journal: 0, crossref: 0, notfound: 0, dois: 0, publishers: 0} _publishers = [] _check = (rec) -> console.log res res.checked += 1 issn = false journal = false for snak in rec.snaks if snak.key is 'ISSN' issn = snak.value if snak.key is 'instance of' and snak.qid is 'Q5633421' journal = true if issn and journal break if journal res.journal += 1 if issn res.withissn += 1 inc = API.use.crossref.journals.issn issn if not inc? res.notfound += 1 else if inc.ISSN and inc.ISSN.length and inc.ISSN[0] is issn res.crossref += 1 if inc.counts?['total-dois']? res.dois += inc.counts['total-dois'] if inc.publisher? and inc.publisher.toLowerCase() not in _publishers _publishers.push inc.publisher.toLowerCase() res.publishers += 1 wikidata_record.each 'snaks.key.exact:"ISSN"', _check API.mail.send to: 'alert@cottagelabs.com' subject: 'Scratch script complete' text: JSON.stringify res, "", 2 return res '''
167174
'''API.add 'scripts/scratch', get: authRequired: 'root' action: () -> res = {checked: 0, withissn: 0, journal: 0, crossref: 0, notfound: 0, dois: 0, publishers: 0} _publishers = [] _check = (rec) -> console.log res res.checked += 1 issn = false journal = false for snak in rec.snaks if snak.key is 'ISSN' issn = snak.value if snak.key is 'instance of' and snak.qid is 'Q5633421' journal = true if issn and journal break if journal res.journal += 1 if issn res.withissn += 1 inc = API.use.crossref.journals.issn issn if not inc? res.notfound += 1 else if inc.ISSN and inc.ISSN.length and inc.ISSN[0] is issn res.crossref += 1 if inc.counts?['total-dois']? res.dois += inc.counts['total-dois'] if inc.publisher? and inc.publisher.toLowerCase() not in _publishers _publishers.push inc.publisher.toLowerCase() res.publishers += 1 wikidata_record.each 'snaks.key.exact:"ISSN"', _check API.mail.send to: '<EMAIL>' subject: 'Scratch script complete' text: JSON.stringify res, "", 2 return res '''
true
'''API.add 'scripts/scratch', get: authRequired: 'root' action: () -> res = {checked: 0, withissn: 0, journal: 0, crossref: 0, notfound: 0, dois: 0, publishers: 0} _publishers = [] _check = (rec) -> console.log res res.checked += 1 issn = false journal = false for snak in rec.snaks if snak.key is 'ISSN' issn = snak.value if snak.key is 'instance of' and snak.qid is 'Q5633421' journal = true if issn and journal break if journal res.journal += 1 if issn res.withissn += 1 inc = API.use.crossref.journals.issn issn if not inc? res.notfound += 1 else if inc.ISSN and inc.ISSN.length and inc.ISSN[0] is issn res.crossref += 1 if inc.counts?['total-dois']? res.dois += inc.counts['total-dois'] if inc.publisher? and inc.publisher.toLowerCase() not in _publishers _publishers.push inc.publisher.toLowerCase() res.publishers += 1 wikidata_record.each 'snaks.key.exact:"ISSN"', _check API.mail.send to: 'PI:EMAIL:<EMAIL>END_PI' subject: 'Scratch script complete' text: JSON.stringify res, "", 2 return res '''
[ { "context": "R_KEY = process.env.HUBOT_IDOBATA_PUSHER_KEY || '44ffe67af1c7035be764'\nAPI_TOKEN = process.env.HUBOT_IDOBATA_API_TOKE", "end": 297, "score": 0.9995789527893066, "start": 277, "tag": "KEY", "value": "44ffe67af1c7035be764" }, { "context": "ot.name}'.\n But th...
src/idobata.coffee
hrysd/hubot-idobata
0
Url = require('url') Request = require('request') Pusher = require('pusher-client') Hubot = require('hubot') Package = require('../package') IDOBATA_URL = process.env.HUBOT_IDOBATA_URL || 'https://idobata.io/' PUSHER_KEY = process.env.HUBOT_IDOBATA_PUSHER_KEY || '44ffe67af1c7035be764' API_TOKEN = process.env.HUBOT_IDOBATA_API_TOKEN class Idobata extends Hubot.Adapter send: (envelope, strings...) -> @_postMessage string, envelope.message.data.room_id for string in strings reply: (envelope, strings...) -> strings = strings.map (string) -> "@#{envelope.user.name} #{string}" @send envelope, strings... run: -> unless API_TOKEN @emit 'error', new Error(`'The environment variable \`\033[31mHUBOT_IDOBATA_API_TOKEN\033[39m\` is required.'`) options = url: Url.resolve(IDOBATA_URL, '/api/seed') headers: @_http_headers Request options, (error, response, body) => unless response.statusCode == 200 console.error `'Idobata returns (status=' + response.statusCode + '). Please check your \`\033[31mHUBOT_IDOBATA_API_TOKEN\033[39m\`.'` @emit 'error', error seed = JSON.parse(body) bot = @robot.brain.userForId(seed.records.bot.id, seed.records.bot) if seed.records.bot.name != @robot.name console.warn """ Your bot on Idobata is named as '#{seed.records.bot.name}'. But this hubot is named as '#{@robot.name}'. To respond to mention correctly, it is recommended that #{`'\033[33mHUBOT_NAME='`}#{seed.records.bot.name}#{`'\033[39m'`} is configured. """ pusher = new Pusher(PUSHER_KEY, encrypted: /^https/.test(IDOBATA_URL) authEndpoint: Url.resolve(IDOBATA_URL, '/pusher/auth') auth: headers: @_http_headers ) channel = pusher.subscribe(bot.channel_name) channel.bind 'message_created', (data) => {message} = data return if bot.id == message.sender_id user = @robot.brain.userForId(message.sender_id, name: message.sender_name) textMessage = new Hubot.TextMessage(user, message.body_plain, message.id) textMessage.data = message @receive textMessage @emit 'connected' _http_headers: 'X-API-Token': API_TOKEN 'User-Agent': "hubot-idobata / v#{Package.version}" _postMessage: (source, room_id) -> options = url: Url.resolve(IDOBATA_URL, '/api/messages') headers: @_http_headers form: message: {room_id, source} Request.post(options) exports.use = (robot) -> new Idobata(robot)
191155
Url = require('url') Request = require('request') Pusher = require('pusher-client') Hubot = require('hubot') Package = require('../package') IDOBATA_URL = process.env.HUBOT_IDOBATA_URL || 'https://idobata.io/' PUSHER_KEY = process.env.HUBOT_IDOBATA_PUSHER_KEY || '<KEY>' API_TOKEN = process.env.HUBOT_IDOBATA_API_TOKEN class Idobata extends Hubot.Adapter send: (envelope, strings...) -> @_postMessage string, envelope.message.data.room_id for string in strings reply: (envelope, strings...) -> strings = strings.map (string) -> "@#{envelope.user.name} #{string}" @send envelope, strings... run: -> unless API_TOKEN @emit 'error', new Error(`'The environment variable \`\033[31mHUBOT_IDOBATA_API_TOKEN\033[39m\` is required.'`) options = url: Url.resolve(IDOBATA_URL, '/api/seed') headers: @_http_headers Request options, (error, response, body) => unless response.statusCode == 200 console.error `'Idobata returns (status=' + response.statusCode + '). Please check your \`\033[31mHUBOT_IDOBATA_API_TOKEN\033[39m\`.'` @emit 'error', error seed = JSON.parse(body) bot = @robot.brain.userForId(seed.records.bot.id, seed.records.bot) if seed.records.bot.name != @robot.name console.warn """ Your bot on Idobata is named as '#{seed.records.bot.name}'. But this hubot is named as '#{@robot.name}'. To respond to mention correctly, it is recommended that #{`'\033[33mHUBOT_NAME='`}#{seed.records.bot.name}#{`'\033[39m'`} is configured. """ pusher = new Pusher(PUSHER_KEY, encrypted: /^https/.test(IDOBATA_URL) authEndpoint: Url.resolve(IDOBATA_URL, '/pusher/auth') auth: headers: @_http_headers ) channel = pusher.subscribe(bot.channel_name) channel.bind 'message_created', (data) => {message} = data return if bot.id == message.sender_id user = @robot.brain.userForId(message.sender_id, name: message.sender_name) textMessage = new Hubot.TextMessage(user, message.body_plain, message.id) textMessage.data = message @receive textMessage @emit 'connected' _http_headers: 'X-API-Token': API_TOKEN 'User-Agent': "hubot-idobata / v#{Package.version}" _postMessage: (source, room_id) -> options = url: Url.resolve(IDOBATA_URL, '/api/messages') headers: @_http_headers form: message: {room_id, source} Request.post(options) exports.use = (robot) -> new Idobata(robot)
true
Url = require('url') Request = require('request') Pusher = require('pusher-client') Hubot = require('hubot') Package = require('../package') IDOBATA_URL = process.env.HUBOT_IDOBATA_URL || 'https://idobata.io/' PUSHER_KEY = process.env.HUBOT_IDOBATA_PUSHER_KEY || 'PI:KEY:<KEY>END_PI' API_TOKEN = process.env.HUBOT_IDOBATA_API_TOKEN class Idobata extends Hubot.Adapter send: (envelope, strings...) -> @_postMessage string, envelope.message.data.room_id for string in strings reply: (envelope, strings...) -> strings = strings.map (string) -> "@#{envelope.user.name} #{string}" @send envelope, strings... run: -> unless API_TOKEN @emit 'error', new Error(`'The environment variable \`\033[31mHUBOT_IDOBATA_API_TOKEN\033[39m\` is required.'`) options = url: Url.resolve(IDOBATA_URL, '/api/seed') headers: @_http_headers Request options, (error, response, body) => unless response.statusCode == 200 console.error `'Idobata returns (status=' + response.statusCode + '). Please check your \`\033[31mHUBOT_IDOBATA_API_TOKEN\033[39m\`.'` @emit 'error', error seed = JSON.parse(body) bot = @robot.brain.userForId(seed.records.bot.id, seed.records.bot) if seed.records.bot.name != @robot.name console.warn """ Your bot on Idobata is named as '#{seed.records.bot.name}'. But this hubot is named as '#{@robot.name}'. To respond to mention correctly, it is recommended that #{`'\033[33mHUBOT_NAME='`}#{seed.records.bot.name}#{`'\033[39m'`} is configured. """ pusher = new Pusher(PUSHER_KEY, encrypted: /^https/.test(IDOBATA_URL) authEndpoint: Url.resolve(IDOBATA_URL, '/pusher/auth') auth: headers: @_http_headers ) channel = pusher.subscribe(bot.channel_name) channel.bind 'message_created', (data) => {message} = data return if bot.id == message.sender_id user = @robot.brain.userForId(message.sender_id, name: message.sender_name) textMessage = new Hubot.TextMessage(user, message.body_plain, message.id) textMessage.data = message @receive textMessage @emit 'connected' _http_headers: 'X-API-Token': API_TOKEN 'User-Agent': "hubot-idobata / v#{Package.version}" _postMessage: (source, room_id) -> options = url: Url.resolve(IDOBATA_URL, '/api/messages') headers: @_http_headers form: message: {room_id, source} Request.post(options) exports.use = (robot) -> new Idobata(robot)
[ { "context": "e 'googleapis'\nfs = require 'fs'\nkey = require './carbon-7615cf89f04e.json'\ndrive = google.drive 'v3'\njwtClient = new google", "end": 93, "score": 0.9962548613548279, "start": 69, "tag": "KEY", "value": "carbon-7615cf89f04e.json" } ]
src/server/modules/api/drive.coffee
mauriciodelrio/carbon
0
{ google } = require 'googleapis' fs = require 'fs' key = require './carbon-7615cf89f04e.json' drive = google.drive 'v3' jwtClient = new google.auth.JWT( key.client_email, key.client_id, key.private_key, ['https://www.googleapis.com/auth/drive'], null ) module.exports = () -> authorize: (req, res, cb) -> jwtClient.authorize (authErr) => if authErr console.log authErr return drive.files.list { auth: jwtClient }, (listErr, resp) => if listErr console.log listErr return resp.data.files.forEach (file) => console.log "#{file.name} (#{file.mimeType})", file uploadFile: (req, res, cb) -> jwtClient.authorize (authErr) => if authErr console.log authErr return console.log "req bodyyyyyyyyyyyyyyyy", req.body fileMetadata = { name: req.body.file.name parents:['1FmETv_GE8ZFregCQvLnu-89221hVBn9n'] } media = { mimeType: req.body.file.type, body: fs.createReadStream req.body.file } drive.files.create { auth: jwtClient, resource: fileMetadata, media, fields: 'id' }, (err, file) => if err cb? status: 'ERROR', data: 'ERROR al cargar el archivo' else cb? status: 'OK', data: "#{file.data.id}" downloadFile: (req, res, cb) -> fileId = '1DzQi__6if6Kak7W42jXTlsCc8UgRUWZA' drive.files.get { fileId: fileId auth: jwtClient }, (err, resp) -> if not err console.log "aaaaaaaaaaaaaa", resp.config, resp.data res.send status: 'OK', data: {headers: resp.config.headers, url: "#{resp.config.url}?alt=media", name: resp.data.name, mimeType: resp.data.mimeType} else res.send status: 'ERROR', data: 'ERROR al descargar el archivo'
20819
{ google } = require 'googleapis' fs = require 'fs' key = require './<KEY>' drive = google.drive 'v3' jwtClient = new google.auth.JWT( key.client_email, key.client_id, key.private_key, ['https://www.googleapis.com/auth/drive'], null ) module.exports = () -> authorize: (req, res, cb) -> jwtClient.authorize (authErr) => if authErr console.log authErr return drive.files.list { auth: jwtClient }, (listErr, resp) => if listErr console.log listErr return resp.data.files.forEach (file) => console.log "#{file.name} (#{file.mimeType})", file uploadFile: (req, res, cb) -> jwtClient.authorize (authErr) => if authErr console.log authErr return console.log "req bodyyyyyyyyyyyyyyyy", req.body fileMetadata = { name: req.body.file.name parents:['1FmETv_GE8ZFregCQvLnu-89221hVBn9n'] } media = { mimeType: req.body.file.type, body: fs.createReadStream req.body.file } drive.files.create { auth: jwtClient, resource: fileMetadata, media, fields: 'id' }, (err, file) => if err cb? status: 'ERROR', data: 'ERROR al cargar el archivo' else cb? status: 'OK', data: "#{file.data.id}" downloadFile: (req, res, cb) -> fileId = '1DzQi__6if6Kak7W42jXTlsCc8UgRUWZA' drive.files.get { fileId: fileId auth: jwtClient }, (err, resp) -> if not err console.log "aaaaaaaaaaaaaa", resp.config, resp.data res.send status: 'OK', data: {headers: resp.config.headers, url: "#{resp.config.url}?alt=media", name: resp.data.name, mimeType: resp.data.mimeType} else res.send status: 'ERROR', data: 'ERROR al descargar el archivo'
true
{ google } = require 'googleapis' fs = require 'fs' key = require './PI:KEY:<KEY>END_PI' drive = google.drive 'v3' jwtClient = new google.auth.JWT( key.client_email, key.client_id, key.private_key, ['https://www.googleapis.com/auth/drive'], null ) module.exports = () -> authorize: (req, res, cb) -> jwtClient.authorize (authErr) => if authErr console.log authErr return drive.files.list { auth: jwtClient }, (listErr, resp) => if listErr console.log listErr return resp.data.files.forEach (file) => console.log "#{file.name} (#{file.mimeType})", file uploadFile: (req, res, cb) -> jwtClient.authorize (authErr) => if authErr console.log authErr return console.log "req bodyyyyyyyyyyyyyyyy", req.body fileMetadata = { name: req.body.file.name parents:['1FmETv_GE8ZFregCQvLnu-89221hVBn9n'] } media = { mimeType: req.body.file.type, body: fs.createReadStream req.body.file } drive.files.create { auth: jwtClient, resource: fileMetadata, media, fields: 'id' }, (err, file) => if err cb? status: 'ERROR', data: 'ERROR al cargar el archivo' else cb? status: 'OK', data: "#{file.data.id}" downloadFile: (req, res, cb) -> fileId = '1DzQi__6if6Kak7W42jXTlsCc8UgRUWZA' drive.files.get { fileId: fileId auth: jwtClient }, (err, resp) -> if not err console.log "aaaaaaaaaaaaaa", resp.config, resp.data res.send status: 'OK', data: {headers: resp.config.headers, url: "#{resp.config.url}?alt=media", name: resp.data.name, mimeType: resp.data.mimeType} else res.send status: 'ERROR', data: 'ERROR al descargar el archivo'
[ { "context": "ct'\n args:\n input:\n username: '#login-username'\n password: '#login-passwd'\n subm", "end": 766, "score": 0.9990671873092651, "start": 750, "tag": "USERNAME", "value": "'#login-username" }, { "context": " username: '#login-usern...
src/js/extension/services/service_data.coffee
obi1kenobi/jester
2
# From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions quote = (str) -> return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') exact = (str) -> return new RegExp('^' + quote(str) + '$') startsWith = (str) -> return new RegExp('^' + quote(str) + '.*') # Service info specification: # Each service has two attributes: login, changePwd # Each of these has an url and type, and optional args. # If type == 'form_redirect', args has the element IDs of the necessary fields, # and if the submission is successful, the server will redirect to the specified URL ServiceData = Yahoo: login: url: 'https://login.yahoo.com/' type: 'form_redirect' args: input: username: '#login-username' password: '#login-passwd' submit: '#login-signin' onSuccessURL: exact('https://www.yahoo.com/') changePwd: url: 'https://edit.yahoo.com/config/change_pw' type: 'form_redirect' args: input: newPassword: '#password' confirmPassword: '#password-confirm' submit: '#primary-cta' onSuccessURL: startsWith('https://edit.yahoo.com/config/change_pw?.done=') 'Hacker News (YCombinator)': login: url: 'https://news.ycombinator.com/login' type: 'form_redirect' args: input: username: 'input[name="acct"]' password: 'input[name="pw"]' submit: 'input[value="login"]' onSuccessURL: exact('https://news.ycombinator.com/') changePwd: url: 'https://news.ycombinator.com/changepw' type: 'form_redirect' args: input: oldPassword: 'input[name="oldpw"]' newPassword: 'input[name="pw"]' submit: 'input[value="Change"]' onSuccessURL: exact('https://news.ycombinator.com/news') # Firebase: # login: # url: 'https://www.firebase.com/login/' # type: 'form_redirect' # args: # input: # username: '#login-email' # password: '#login-password' # submit: '#login-button' # onSuccessURL: exact('https://www.firebase.com/account/') # changePwd: # url: 'https://www.firebase.com/change_password.html' # type: 'same_page_element_exists' # args: # input: # oldPassword: '#current' # newPassword: '#password' # confirmPassword: '#confirm' # submit: 'input[value="Change Password"]' # onSuccessElement: 'p.alert.alert-success' + \ # ':contains("Password changed successfully.")' # DockerHub: # login: # url: 'https://hub.docker.com/login/' # type: 'form_redirect' # args: # input: # username: '.DUXInput-b__duxInput___l1DEO' + \ # '[data-reactid$=".1.0.1.0.0.0.0.0.1.0.0"]' # password: '.DUXInput-b__duxInput___l1DEO' + \ # '[data-reactid$=".1.0.1.0.0.0.0.0.2.0.0"]' # submit: '.button[data-reactid$=".1.0.1.0.0.0.0.0.3.0"]' # onSuccessURL: new RegExp('^' + quote('https://hub.docker.com/') + '$') # changePwd: # url: 'https://hub.docker.com/account/settings/' # type: 'form_redirect' # args: # input: # oldPassword: '.DUXInput__duxInput___10RXU' + \ # '[data-reactid$=".1.1.1.0.2.1.0.0.0.0.0.0.0"]' # newPassword: '.DUXInput__duxInput___10RXU' + \ # '[data-reactid$=".1.1.1.0.2.1.0.0.0.0.1.0.0"]' # confirmPassword: '.DUXInput__duxInput___10RXU' + \ # '[data-reactid$=".1.1.1.0.2.1.0.0.0.0.2.0.0"]' # submit: '.button[data-reactid$=".1.1.1.0.2.1.0.0.0.1.0.0.0"]' # onSuccessURL: new RegExp('^' + \ # quote('https://hub.docker.com/account/password-reset-confirm/success/') + \ # '$') module.exports = ServiceData
34828
# From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions quote = (str) -> return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') exact = (str) -> return new RegExp('^' + quote(str) + '$') startsWith = (str) -> return new RegExp('^' + quote(str) + '.*') # Service info specification: # Each service has two attributes: login, changePwd # Each of these has an url and type, and optional args. # If type == 'form_redirect', args has the element IDs of the necessary fields, # and if the submission is successful, the server will redirect to the specified URL ServiceData = Yahoo: login: url: 'https://login.yahoo.com/' type: 'form_redirect' args: input: username: '#login-username' password: <PASSWORD>' submit: '#login-signin' onSuccessURL: exact('https://www.yahoo.com/') changePwd: url: 'https://edit.yahoo.com/config/change_pw' type: 'form_redirect' args: input: newPassword: <PASSWORD>' confirmPassword: <PASSWORD>' submit: '#primary-cta' onSuccessURL: startsWith('https://edit.yahoo.com/config/change_pw?.done=') 'Hacker News (YCombinator)': login: url: 'https://news.ycombinator.com/login' type: 'form_redirect' args: input: username: 'input[name="acct"]' password: 'input[name="pw"]' submit: 'input[value="login"]' onSuccessURL: exact('https://news.ycombinator.com/') changePwd: url: 'https://news.ycombinator.com/changepw' type: 'form_redirect' args: input: oldPassword: 'input[name="oldpw"]' newPassword: 'input[name="pw"]' submit: 'input[value="Change"]' onSuccessURL: exact('https://news.ycombinator.com/news') # Firebase: # login: # url: 'https://www.firebase.com/login/' # type: 'form_redirect' # args: # input: # username: '#login-email' # password: <PASSWORD>' # submit: '#login-button' # onSuccessURL: exact('https://www.firebase.com/account/') # changePwd: # url: 'https://www.firebase.com/change_password.html' # type: 'same_page_element_exists' # args: # input: # oldPassword: <PASSWORD>' # newPassword: <PASSWORD>' # confirmPassword: <PASSWORD>' # submit: 'input[value="Change Password"]' # onSuccessElement: 'p.alert.alert-success' + \ # ':contains("Password changed successfully.")' # DockerHub: # login: # url: 'https://hub.docker.com/login/' # type: 'form_redirect' # args: # input: # username: '.DUXInput-b__duxInput___l1DEO' + \ # '[data-reactid$=".1.0.1.0.0.0.0.0.1.0.0"]' # password: <PASSWORD>' + \ # '[data-reactid$=".1.0.1.0.0.0.0.0.2.0.0"]' # submit: '.button[data-reactid$=".1.0.1.0.0.0.0.0.3.0"]' # onSuccessURL: new RegExp('^' + quote('https://hub.docker.com/') + '$') # changePwd: # url: 'https://hub.docker.com/account/settings/' # type: 'form_redirect' # args: # input: # oldPassword: <PASSWORD>' + \ # '[data-reactid$=".1.1.1.0.2.1.0.0.0.0.0.0.0"]' # newPassword: <PASSWORD>' + \ # '[data-reactid$=".1.1.1.0.2.1.0.0.0.0.1.0.0"]' # confirmPassword: <PASSWORD>' + \ # '[data-reactid$=".1.1.1.0.2.1.0.0.0.0.2.0.0"]' # submit: '.button[data-reactid$=".1.1.1.0.2.1.0.0.0.1.0.0.0"]' # onSuccessURL: new RegExp('^' + \ # quote('https://hub.docker.com/account/password-reset-confirm/success/') + \ # '$') module.exports = ServiceData
true
# From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions quote = (str) -> return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') exact = (str) -> return new RegExp('^' + quote(str) + '$') startsWith = (str) -> return new RegExp('^' + quote(str) + '.*') # Service info specification: # Each service has two attributes: login, changePwd # Each of these has an url and type, and optional args. # If type == 'form_redirect', args has the element IDs of the necessary fields, # and if the submission is successful, the server will redirect to the specified URL ServiceData = Yahoo: login: url: 'https://login.yahoo.com/' type: 'form_redirect' args: input: username: '#login-username' password: PI:PASSWORD:<PASSWORD>END_PI' submit: '#login-signin' onSuccessURL: exact('https://www.yahoo.com/') changePwd: url: 'https://edit.yahoo.com/config/change_pw' type: 'form_redirect' args: input: newPassword: PI:PASSWORD:<PASSWORD>END_PI' confirmPassword: PI:PASSWORD:<PASSWORD>END_PI' submit: '#primary-cta' onSuccessURL: startsWith('https://edit.yahoo.com/config/change_pw?.done=') 'Hacker News (YCombinator)': login: url: 'https://news.ycombinator.com/login' type: 'form_redirect' args: input: username: 'input[name="acct"]' password: 'input[name="pw"]' submit: 'input[value="login"]' onSuccessURL: exact('https://news.ycombinator.com/') changePwd: url: 'https://news.ycombinator.com/changepw' type: 'form_redirect' args: input: oldPassword: 'input[name="oldpw"]' newPassword: 'input[name="pw"]' submit: 'input[value="Change"]' onSuccessURL: exact('https://news.ycombinator.com/news') # Firebase: # login: # url: 'https://www.firebase.com/login/' # type: 'form_redirect' # args: # input: # username: '#login-email' # password: PI:PASSWORD:<PASSWORD>END_PI' # submit: '#login-button' # onSuccessURL: exact('https://www.firebase.com/account/') # changePwd: # url: 'https://www.firebase.com/change_password.html' # type: 'same_page_element_exists' # args: # input: # oldPassword: PI:PASSWORD:<PASSWORD>END_PI' # newPassword: PI:PASSWORD:<PASSWORD>END_PI' # confirmPassword: PI:PASSWORD:<PASSWORD>END_PI' # submit: 'input[value="Change Password"]' # onSuccessElement: 'p.alert.alert-success' + \ # ':contains("Password changed successfully.")' # DockerHub: # login: # url: 'https://hub.docker.com/login/' # type: 'form_redirect' # args: # input: # username: '.DUXInput-b__duxInput___l1DEO' + \ # '[data-reactid$=".1.0.1.0.0.0.0.0.1.0.0"]' # password: PI:PASSWORD:<PASSWORD>END_PI' + \ # '[data-reactid$=".1.0.1.0.0.0.0.0.2.0.0"]' # submit: '.button[data-reactid$=".1.0.1.0.0.0.0.0.3.0"]' # onSuccessURL: new RegExp('^' + quote('https://hub.docker.com/') + '$') # changePwd: # url: 'https://hub.docker.com/account/settings/' # type: 'form_redirect' # args: # input: # oldPassword: PI:PASSWORD:<PASSWORD>END_PI' + \ # '[data-reactid$=".1.1.1.0.2.1.0.0.0.0.0.0.0"]' # newPassword: PI:PASSWORD:<PASSWORD>END_PI' + \ # '[data-reactid$=".1.1.1.0.2.1.0.0.0.0.1.0.0"]' # confirmPassword: PI:PASSWORD:<PASSWORD>END_PI' + \ # '[data-reactid$=".1.1.1.0.2.1.0.0.0.0.2.0.0"]' # submit: '.button[data-reactid$=".1.1.1.0.2.1.0.0.0.1.0.0.0"]' # onSuccessURL: new RegExp('^' + \ # quote('https://hub.docker.com/account/password-reset-confirm/success/') + \ # '$') module.exports = ServiceData
[ { "context": " ->\n alice = yield new User(username: 'alice').save()\n photos = yield [\n ", "end": 446, "score": 0.9989082217216492, "start": 441, "tag": "USERNAME", "value": "alice" }, { "context": "b] = yield [\n new User(username: '...
test/relations/belongs_to.coffee
bgaeddert/bookshelf-schema
44
Bookshelf = require 'bookshelf' Schema = require '../../src/' init = require '../init' Fields = require '../../src/fields' Relations = require '../../src/relations' {StringField, IntField, EmailField} = Fields {HasMany, BelongsTo} = Relations describe "Relations", -> this.timeout 3000 db = null User = null Photo = null Inviter = null fixtures = alice: co -> alice = yield new User(username: 'alice').save() photos = yield [ new Photo(filename: 'photo1.jpg', user_id: alice.id).save() new Photo(filename: 'photo2.jpg', user_id: alice.id).save() ] [alice, photos] aliceAndBob: co -> [alice, bob] = yield [ new User(username: 'alice').save() new User(username: 'bob').save() ] inviter = yield new Inviter(greeting: 'Hello Bob!', user_id: alice.id).save() yield bob.save(inviter_id: inviter.id) [alice, bob, inviter] before co -> db = init.init() yield [ init.users(), init.photos() ] describe 'BelongsTo', -> describe 'plain', -> beforeEach -> class Photo extends db.Model tableName: 'photos' class User extends db.Model tableName: 'users' @schema [ StringField 'username' HasMany Photo ] Photo.schema [ StringField 'filename' BelongsTo User ] afterEach -> init.truncate 'users', 'photos' it 'creates accessor', co -> [alice, [photo1, _]] = yield fixtures.alice() photo1.user.should.be.a 'function' yield photo1.load 'user' photo1.$user.should.be.an.instanceof User photo1.$user.username.should.equal alice.username it 'can assign model', co -> [alice, [photo1, _]] = yield fixtures.alice() bob = yield new User(username: 'bob').save() yield photo1.$user.assign bob photo1 = yield Photo.forge(id: photo1.id).fetch(withRelated: 'user') photo1.user_id.should.equal bob.id photo1.$user.id.should.equal bob.id it 'can assign plain object', co -> [alice, [photo1, _]] = yield fixtures.alice() yield photo1.$user.assign {username: 'bob'} photo1 = yield Photo.forge(id: photo1.id).fetch(withRelated: 'user') photo1.$user.username.should.equal 'bob' it 'can assign by id', co -> [alice, [photo1, _]] = yield fixtures.alice() bob = yield new User(username: 'bob').save() yield photo1.$user.assign bob.id photo1 = yield Photo.forge(id: photo1.id).fetch(withRelated: 'user') photo1.user_id.should.equal bob.id photo1.$user.id.should.equal bob.id it 'can assign null as a related object', co -> [alice, [photo1, _]] = yield fixtures.alice() yield photo1.$user.assign(null) photo1 = yield Photo.forge(id: photo1.id).fetch() expect(photo1.user_id).to.be.null it 'can use custom foreign key and foreign key target', co -> class OtherPhoto extends db.Model tableName: 'photos' @schema [ StringField 'filename' StringField 'user_name' BelongsTo User, foreignKey: 'user_name', foreignKeyTarget: 'username' ] [alice, [photo1, _]] = yield fixtures.alice() photo2 = yield OtherPhoto.forge(id: photo1.id).fetch() photo2.user_name = alice.username yield photo2.save() yield photo2.load('user') photo2.$user.id.should.equal alice.id describe 'through', -> before -> init.inviters() beforeEach -> class Inviter extends db.Model tableName: 'inviters' class User extends db.Model tableName: 'users' @schema [ StringField 'username' BelongsTo User, name: 'inviter', through: Inviter ] Inviter.schema [ StringField 'greeting' ] afterEach -> init.truncate 'users', 'inviters' it 'can access related model', co -> [alice, bob, inviter] = yield fixtures.aliceAndBob() yield bob.load('inviter') bob.$inviter.should.be.an.instanceof User bob.$inviter.id.should.equal alice.id describe 'onDestroy', -> beforeEach -> class Photo extends db.Model tableName: 'photos' class User extends db.Model tableName: 'users' afterEach -> init.truncate 'users', 'photos' it 'can cascade-destroy dependent models', co -> Photo.schema [ BelongsTo User, onDestroy: 'cascade' ] [alice, [photo1, photo2]] = yield fixtures.alice() yield photo1.destroy().should.be.fulfilled [alice, photo2] = yield [ new User(id: alice.id).fetch() new Photo(id: photo2.id).fetch() ] expect(alice).to.be.null expect(photo2).not.to.be.null it 'can reject destroy when there is dependent model', co -> Photo.schema [ BelongsTo User, onDestroy: 'reject' ] [alice, [photo1, _]] = yield fixtures.alice() yield photo1.destroy().should.be.rejected yield photo1.$user.assign null photo1.destroy().should.be.fulfilled it 'can detach dependend models on destroy', co -> Photo.schema [ # this actually a no-op BelongsTo User, onDestroy: 'detach' ] [alice, [photo1, _]] = yield fixtures.alice() yield photo1.destroy().should.be.fulfilled describe 'tries to assign correct name to foreign key field', -> beforeEach -> class User extends db.Model tableName: 'users' class Photo extends db.Model tableName: 'photos' it 'uses <modelName>_id by default', -> Photo.schema [ BelongsTo User ] Photo.prototype.hasOwnProperty('user_id').should.be.true it 'uses foreign key if defined', -> Photo.schema [ BelongsTo User, foreignKey: 'userId' ] Photo.prototype.hasOwnProperty('userId').should.be.true
148106
Bookshelf = require 'bookshelf' Schema = require '../../src/' init = require '../init' Fields = require '../../src/fields' Relations = require '../../src/relations' {StringField, IntField, EmailField} = Fields {HasMany, BelongsTo} = Relations describe "Relations", -> this.timeout 3000 db = null User = null Photo = null Inviter = null fixtures = alice: co -> alice = yield new User(username: 'alice').save() photos = yield [ new Photo(filename: 'photo1.jpg', user_id: alice.id).save() new Photo(filename: 'photo2.jpg', user_id: alice.id).save() ] [alice, photos] aliceAndBob: co -> [alice, bob] = yield [ new User(username: 'alice').save() new User(username: 'bob').save() ] inviter = yield new Inviter(greeting: 'Hello <NAME>!', user_id: alice.id).save() yield bob.save(inviter_id: inviter.id) [alice, bob, inviter] before co -> db = init.init() yield [ init.users(), init.photos() ] describe 'BelongsTo', -> describe 'plain', -> beforeEach -> class Photo extends db.Model tableName: 'photos' class User extends db.Model tableName: 'users' @schema [ StringField 'username' HasMany Photo ] Photo.schema [ StringField 'filename' BelongsTo User ] afterEach -> init.truncate 'users', 'photos' it 'creates accessor', co -> [alice, [photo1, _]] = yield fixtures.alice() photo1.user.should.be.a 'function' yield photo1.load 'user' photo1.$user.should.be.an.instanceof User photo1.$user.username.should.equal alice.username it 'can assign model', co -> [alice, [photo1, _]] = yield fixtures.alice() bob = yield new User(username: 'bob').save() yield photo1.$user.assign bob photo1 = yield Photo.forge(id: photo1.id).fetch(withRelated: 'user') photo1.user_id.should.equal bob.id photo1.$user.id.should.equal bob.id it 'can assign plain object', co -> [alice, [photo1, _]] = yield fixtures.alice() yield photo1.$user.assign {username: 'bob'} photo1 = yield Photo.forge(id: photo1.id).fetch(withRelated: 'user') photo1.$user.username.should.equal 'bob' it 'can assign by id', co -> [alice, [photo1, _]] = yield fixtures.alice() bob = yield new User(username: 'bob').save() yield photo1.$user.assign bob.id photo1 = yield Photo.forge(id: photo1.id).fetch(withRelated: 'user') photo1.user_id.should.equal bob.id photo1.$user.id.should.equal bob.id it 'can assign null as a related object', co -> [alice, [photo1, _]] = yield fixtures.alice() yield photo1.$user.assign(null) photo1 = yield Photo.forge(id: photo1.id).fetch() expect(photo1.user_id).to.be.null it 'can use custom foreign key and foreign key target', co -> class OtherPhoto extends db.Model tableName: 'photos' @schema [ StringField 'filename' StringField 'user_name' BelongsTo User, foreignKey: 'user_name', foreignKeyTarget: 'username' ] [alice, [photo1, _]] = yield fixtures.alice() photo2 = yield OtherPhoto.forge(id: photo1.id).fetch() photo2.user_name = alice.username yield photo2.save() yield photo2.load('user') photo2.$user.id.should.equal alice.id describe 'through', -> before -> init.inviters() beforeEach -> class Inviter extends db.Model tableName: 'inviters' class User extends db.Model tableName: 'users' @schema [ StringField 'username' BelongsTo User, name: 'inviter', through: Inviter ] Inviter.schema [ StringField 'greeting' ] afterEach -> init.truncate 'users', 'inviters' it 'can access related model', co -> [alice, bob, inviter] = yield fixtures.aliceAndBob() yield bob.load('inviter') bob.$inviter.should.be.an.instanceof User bob.$inviter.id.should.equal alice.id describe 'onDestroy', -> beforeEach -> class Photo extends db.Model tableName: 'photos' class User extends db.Model tableName: 'users' afterEach -> init.truncate 'users', 'photos' it 'can cascade-destroy dependent models', co -> Photo.schema [ BelongsTo User, onDestroy: 'cascade' ] [alice, [photo1, photo2]] = yield fixtures.alice() yield photo1.destroy().should.be.fulfilled [alice, photo2] = yield [ new User(id: alice.id).fetch() new Photo(id: photo2.id).fetch() ] expect(alice).to.be.null expect(photo2).not.to.be.null it 'can reject destroy when there is dependent model', co -> Photo.schema [ BelongsTo User, onDestroy: 'reject' ] [alice, [photo1, _]] = yield fixtures.alice() yield photo1.destroy().should.be.rejected yield photo1.$user.assign null photo1.destroy().should.be.fulfilled it 'can detach dependend models on destroy', co -> Photo.schema [ # this actually a no-op BelongsTo User, onDestroy: 'detach' ] [alice, [photo1, _]] = yield fixtures.alice() yield photo1.destroy().should.be.fulfilled describe 'tries to assign correct name to foreign key field', -> beforeEach -> class User extends db.Model tableName: 'users' class Photo extends db.Model tableName: 'photos' it 'uses <modelName>_id by default', -> Photo.schema [ BelongsTo User ] Photo.prototype.hasOwnProperty('user_id').should.be.true it 'uses foreign key if defined', -> Photo.schema [ BelongsTo User, foreignKey: '<KEY>' ] Photo.prototype.hasOwnProperty('userId').should.be.true
true
Bookshelf = require 'bookshelf' Schema = require '../../src/' init = require '../init' Fields = require '../../src/fields' Relations = require '../../src/relations' {StringField, IntField, EmailField} = Fields {HasMany, BelongsTo} = Relations describe "Relations", -> this.timeout 3000 db = null User = null Photo = null Inviter = null fixtures = alice: co -> alice = yield new User(username: 'alice').save() photos = yield [ new Photo(filename: 'photo1.jpg', user_id: alice.id).save() new Photo(filename: 'photo2.jpg', user_id: alice.id).save() ] [alice, photos] aliceAndBob: co -> [alice, bob] = yield [ new User(username: 'alice').save() new User(username: 'bob').save() ] inviter = yield new Inviter(greeting: 'Hello PI:NAME:<NAME>END_PI!', user_id: alice.id).save() yield bob.save(inviter_id: inviter.id) [alice, bob, inviter] before co -> db = init.init() yield [ init.users(), init.photos() ] describe 'BelongsTo', -> describe 'plain', -> beforeEach -> class Photo extends db.Model tableName: 'photos' class User extends db.Model tableName: 'users' @schema [ StringField 'username' HasMany Photo ] Photo.schema [ StringField 'filename' BelongsTo User ] afterEach -> init.truncate 'users', 'photos' it 'creates accessor', co -> [alice, [photo1, _]] = yield fixtures.alice() photo1.user.should.be.a 'function' yield photo1.load 'user' photo1.$user.should.be.an.instanceof User photo1.$user.username.should.equal alice.username it 'can assign model', co -> [alice, [photo1, _]] = yield fixtures.alice() bob = yield new User(username: 'bob').save() yield photo1.$user.assign bob photo1 = yield Photo.forge(id: photo1.id).fetch(withRelated: 'user') photo1.user_id.should.equal bob.id photo1.$user.id.should.equal bob.id it 'can assign plain object', co -> [alice, [photo1, _]] = yield fixtures.alice() yield photo1.$user.assign {username: 'bob'} photo1 = yield Photo.forge(id: photo1.id).fetch(withRelated: 'user') photo1.$user.username.should.equal 'bob' it 'can assign by id', co -> [alice, [photo1, _]] = yield fixtures.alice() bob = yield new User(username: 'bob').save() yield photo1.$user.assign bob.id photo1 = yield Photo.forge(id: photo1.id).fetch(withRelated: 'user') photo1.user_id.should.equal bob.id photo1.$user.id.should.equal bob.id it 'can assign null as a related object', co -> [alice, [photo1, _]] = yield fixtures.alice() yield photo1.$user.assign(null) photo1 = yield Photo.forge(id: photo1.id).fetch() expect(photo1.user_id).to.be.null it 'can use custom foreign key and foreign key target', co -> class OtherPhoto extends db.Model tableName: 'photos' @schema [ StringField 'filename' StringField 'user_name' BelongsTo User, foreignKey: 'user_name', foreignKeyTarget: 'username' ] [alice, [photo1, _]] = yield fixtures.alice() photo2 = yield OtherPhoto.forge(id: photo1.id).fetch() photo2.user_name = alice.username yield photo2.save() yield photo2.load('user') photo2.$user.id.should.equal alice.id describe 'through', -> before -> init.inviters() beforeEach -> class Inviter extends db.Model tableName: 'inviters' class User extends db.Model tableName: 'users' @schema [ StringField 'username' BelongsTo User, name: 'inviter', through: Inviter ] Inviter.schema [ StringField 'greeting' ] afterEach -> init.truncate 'users', 'inviters' it 'can access related model', co -> [alice, bob, inviter] = yield fixtures.aliceAndBob() yield bob.load('inviter') bob.$inviter.should.be.an.instanceof User bob.$inviter.id.should.equal alice.id describe 'onDestroy', -> beforeEach -> class Photo extends db.Model tableName: 'photos' class User extends db.Model tableName: 'users' afterEach -> init.truncate 'users', 'photos' it 'can cascade-destroy dependent models', co -> Photo.schema [ BelongsTo User, onDestroy: 'cascade' ] [alice, [photo1, photo2]] = yield fixtures.alice() yield photo1.destroy().should.be.fulfilled [alice, photo2] = yield [ new User(id: alice.id).fetch() new Photo(id: photo2.id).fetch() ] expect(alice).to.be.null expect(photo2).not.to.be.null it 'can reject destroy when there is dependent model', co -> Photo.schema [ BelongsTo User, onDestroy: 'reject' ] [alice, [photo1, _]] = yield fixtures.alice() yield photo1.destroy().should.be.rejected yield photo1.$user.assign null photo1.destroy().should.be.fulfilled it 'can detach dependend models on destroy', co -> Photo.schema [ # this actually a no-op BelongsTo User, onDestroy: 'detach' ] [alice, [photo1, _]] = yield fixtures.alice() yield photo1.destroy().should.be.fulfilled describe 'tries to assign correct name to foreign key field', -> beforeEach -> class User extends db.Model tableName: 'users' class Photo extends db.Model tableName: 'photos' it 'uses <modelName>_id by default', -> Photo.schema [ BelongsTo User ] Photo.prototype.hasOwnProperty('user_id').should.be.true it 'uses foreign key if defined', -> Photo.schema [ BelongsTo User, foreignKey: 'PI:KEY:<KEY>END_PI' ] Photo.prototype.hasOwnProperty('userId').should.be.true
[ { "context": " if (insecurePlaintext)\n @set 'password', \"cleartext:#{password}\"\n @log.warn \"ALERT: Using insecure cleartex", "end": 999, "score": 0.8974241614341736, "start": 979, "tag": "PASSWORD", "value": "cleartext:#{password" }, { "context": " \":\" + hashedpass...
plugins/coffeekeep.model/user.coffee
leonexis/coffeekeep
0
_ = require 'lodash' {Mob, MobCollection} = require './mob' exports.User = class User extends Mob defaults: -> _.defaults Mob::defaults(), age: 0 # Player age in days wasAtLocation: null # Player location before last disconnect sysop: false # Have complete admin access idAttribute: 'name' toString: -> "[user #{@id}]" setPassword: (password) -> crypto = require 'crypto' # Set hashalgo to preferred hash algorithm. Algorithm names are the same as # output by "openssl list-message-digest-algorithms". When in doubt, the # default "whirlpool" algorithm is a good choice. If whirlpool is not # supported, use "sha512" hashalgo = 'whirlpool' # Setting insecurePlaintext to 1 will result in passwords being stored in # plaintext. This is VERY insecure and should not be enabled unless openssl # support cannot be added. insecurePlaintext = 0 if (insecurePlaintext) @set 'password', "cleartext:#{password}" @log.warn "ALERT: Using insecure cleartext password. Consider enabling hash storage." else passtohash = password salt = "" salt += Math.random().toString(36).substr(2) while salt.length < 8 salt = salt.substr 0,8 passtohash = salt + passtohash hashedpass = crypto.createHash(hashalgo).update(passtohash).digest('hex') hashedoutput = hashalgo + ":1:" + salt + ":" + hashedpass @set 'password', "#{hashedoutput}" checkPassword: (password) -> crypto = require 'crypto' realpass = @get 'password' passsegments = realpass.split ':' hashtype = passsegments[0] if (hashtype == "cleartext") # Using insecure cleartext password storage "cleartext:#{password}" == realpass else hashsalt = passsegments[2] hashcheck = passsegments[3] tohash = hashsalt + password hashoutput = crypto.createHash(hashtype).update(tohash).digest('hex') hashoutput == hashcheck exports.UserCollection = class UserCollection extends MobCollection model: User urlPart: 'users' create: (attributes, options={}, cb) -> cb ?= -> null # Check to see if this is the first user created. If so, make it the # sysop if @length is 0 if attributes instanceof User @log.notice "We have our first user! Making #{attributes.get 'name'} a sysop" attributes.set 'sysop', true else @log.notice "We have our first user! Making #{attributes.name} a sysop" attributes.sysop = true # TODO: notify the user somehow? super attributes, options, cb
188061
_ = require 'lodash' {Mob, MobCollection} = require './mob' exports.User = class User extends Mob defaults: -> _.defaults Mob::defaults(), age: 0 # Player age in days wasAtLocation: null # Player location before last disconnect sysop: false # Have complete admin access idAttribute: 'name' toString: -> "[user #{@id}]" setPassword: (password) -> crypto = require 'crypto' # Set hashalgo to preferred hash algorithm. Algorithm names are the same as # output by "openssl list-message-digest-algorithms". When in doubt, the # default "whirlpool" algorithm is a good choice. If whirlpool is not # supported, use "sha512" hashalgo = 'whirlpool' # Setting insecurePlaintext to 1 will result in passwords being stored in # plaintext. This is VERY insecure and should not be enabled unless openssl # support cannot be added. insecurePlaintext = 0 if (insecurePlaintext) @set 'password', "<PASSWORD>}" @log.warn "ALERT: Using insecure cleartext password. Consider enabling hash storage." else passtohash = password salt = "" salt += Math.random().toString(36).substr(2) while salt.length < 8 salt = salt.substr 0,8 passtohash = salt + passtohash hashedpass = crypto.createHash(hashalgo).update(passtohash).digest('hex') hashedoutput = hashalgo + ":1:" + salt + ":" + hashedpass @set 'password', "#{hashed<PASSWORD>}" checkPassword: (password) -> crypto = require 'crypto' realpass = @get 'password' passsegments = realpass.split ':' hashtype = passsegments[0] if (hashtype == "cleartext") # Using insecure cleartext password storage "cleartext:#{password}" == realpass else hashsalt = passsegments[2] hashcheck = passsegments[3] tohash = hashsalt + password hashoutput = crypto.createHash(hashtype).update(tohash).digest('hex') hashoutput == hashcheck exports.UserCollection = class UserCollection extends MobCollection model: User urlPart: 'users' create: (attributes, options={}, cb) -> cb ?= -> null # Check to see if this is the first user created. If so, make it the # sysop if @length is 0 if attributes instanceof User @log.notice "We have our first user! Making #{attributes.get 'name'} a sysop" attributes.set 'sysop', true else @log.notice "We have our first user! Making #{attributes.name} a sysop" attributes.sysop = true # TODO: notify the user somehow? super attributes, options, cb
true
_ = require 'lodash' {Mob, MobCollection} = require './mob' exports.User = class User extends Mob defaults: -> _.defaults Mob::defaults(), age: 0 # Player age in days wasAtLocation: null # Player location before last disconnect sysop: false # Have complete admin access idAttribute: 'name' toString: -> "[user #{@id}]" setPassword: (password) -> crypto = require 'crypto' # Set hashalgo to preferred hash algorithm. Algorithm names are the same as # output by "openssl list-message-digest-algorithms". When in doubt, the # default "whirlpool" algorithm is a good choice. If whirlpool is not # supported, use "sha512" hashalgo = 'whirlpool' # Setting insecurePlaintext to 1 will result in passwords being stored in # plaintext. This is VERY insecure and should not be enabled unless openssl # support cannot be added. insecurePlaintext = 0 if (insecurePlaintext) @set 'password', "PI:PASSWORD:<PASSWORD>END_PI}" @log.warn "ALERT: Using insecure cleartext password. Consider enabling hash storage." else passtohash = password salt = "" salt += Math.random().toString(36).substr(2) while salt.length < 8 salt = salt.substr 0,8 passtohash = salt + passtohash hashedpass = crypto.createHash(hashalgo).update(passtohash).digest('hex') hashedoutput = hashalgo + ":1:" + salt + ":" + hashedpass @set 'password', "#{hashedPI:PASSWORD:<PASSWORD>END_PI}" checkPassword: (password) -> crypto = require 'crypto' realpass = @get 'password' passsegments = realpass.split ':' hashtype = passsegments[0] if (hashtype == "cleartext") # Using insecure cleartext password storage "cleartext:#{password}" == realpass else hashsalt = passsegments[2] hashcheck = passsegments[3] tohash = hashsalt + password hashoutput = crypto.createHash(hashtype).update(tohash).digest('hex') hashoutput == hashcheck exports.UserCollection = class UserCollection extends MobCollection model: User urlPart: 'users' create: (attributes, options={}, cb) -> cb ?= -> null # Check to see if this is the first user created. If so, make it the # sysop if @length is 0 if attributes instanceof User @log.notice "We have our first user! Making #{attributes.get 'name'} a sysop" attributes.set 'sysop', true else @log.notice "We have our first user! Making #{attributes.name} a sysop" attributes.sysop = true # TODO: notify the user somehow? super attributes, options, cb
[ { "context": "r: null\n team: null\n\n studentKeys = ['guc_prefix', 'guc_suffix',\n 'team']\n studentsDisab", "end": 644, "score": 0.8437846899032593, "start": 634, "tag": "KEY", "value": "guc_prefix" }, { "context": " team: null\n\n studentKeys = ['guc_pre...
frontend/src/controllers/private/teacher/users.coffee
greysteil/evaluator
1
angular.module 'evaluator' .controller 'UsersController', ($scope, Pagination, defaultPageSize, UsersResource, User, deletedUserIds) -> $scope.studentsOnly = false $scope.teachersOnly = false $scope.superUser = false $scope.loading = true $scope.loadingUsers = false $scope.searchData = name: '' email: '' team: '' guc_prefix: '' guc_suffix: '' $scope.params = name: null email: null guc_suffix: null guc_prefix: null student: null super_user: null team: null studentKeys = ['guc_prefix', 'guc_suffix', 'team'] studentsDisabled = false $scope.userClasses = ['user-accent-one', 'user-accent-two', 'user-accent-three'] setIfValid = (value, key)-> if value && value.length > 0 $scope.params[key] = value disableStudentOnlyParams = -> studentsDisabled = true $scope.params[key] = null for key in studentKeys return enableStudentOnlyParams = -> studentsDisabled = false setIfValid($scope.searchData[key], key) for key in studentKeys return $scope.$watch 'searchData', (newValue) -> changed = false for key, value of newValue if !studentsDisabled or key not in studentKeys oldParamValue = $scope.params[key] if value && value.length > 0 $scope.params[key] = value else $scope.params[key] = null changed |= oldParamValue != $scope.params[key] $scope.reload() if changed return , true $scope.$watch 'superUser', (newValue) -> if newValue $scope.params.super_user = true else $scope.params.super_user = null $scope.reload() $scope.$watch 'teachersOnly', (newValue, oldValue) -> if newValue $scope.params.student = false disableStudentOnlyParams() $scope.reload() $scope.studentsOnly = false else enableStudentOnlyParams() if !$scope.studentsOnly $scope.params.student = null $scope.reload() $scope.$watch 'studentsOnly', (newValue, oldValue) -> if newValue $scope.params.student = true $scope.reload() $scope.teachersOnly = false else if !$scope.teachersOnly $scope.params.student = null $scope.reload() $scope.users = [] addUsersCallback = (newUsers) -> users = newUsers.filter (user) -> user.id not in deletedUserIds args = [0, $scope.users.length].concat users $scope.users.splice.apply $scope.users, args userDeletedCallback = (user) -> deletedUserIds.push user.id _.remove $scope.users, (e) -> e.id is user.id userFactory = (data) -> new User(data, userDeletedCallback) usersPagination = new Pagination UsersResource, 'users', $scope.params, userFactory, defaultPageSize $scope.currentPage = 1 $scope.reload = -> return if $scope.loadingUsers $scope.loadingUsers = true usersPagination.reload().then (users) -> $scope.loading = false $scope.loadingUsers = false addUsersCallback users loadUsersPage = (page) -> $scope.loadingUsers = true usersPagination.page(page).then (users) -> $scope.loading = false $scope.loadingUsers = false $scope.currentPage = page addUsersCallback users # Load first page loadUsersPage $scope.currentPage $scope.backDisabled = -> $scope.currentPage is 1 $scope.nextDisabled = -> $scope.currentPage >= usersPagination.totalPages $scope.next = -> if not $scope.nextDisabled() loadUsersPage($scope.currentPage + 1) $scope.back = -> if not $scope.backDisabled() loadUsersPage($scope.currentPage - 1)
56589
angular.module 'evaluator' .controller 'UsersController', ($scope, Pagination, defaultPageSize, UsersResource, User, deletedUserIds) -> $scope.studentsOnly = false $scope.teachersOnly = false $scope.superUser = false $scope.loading = true $scope.loadingUsers = false $scope.searchData = name: '' email: '' team: '' guc_prefix: '' guc_suffix: '' $scope.params = name: null email: null guc_suffix: null guc_prefix: null student: null super_user: null team: null studentKeys = ['<KEY>', 'g<KEY>', 'team'] studentsDisabled = false $scope.userClasses = ['user-accent-one', 'user-accent-two', 'user-accent-three'] setIfValid = (value, key)-> if value && value.length > 0 $scope.params[key] = value disableStudentOnlyParams = -> studentsDisabled = true $scope.params[key] = null for key in studentKeys return enableStudentOnlyParams = -> studentsDisabled = false setIfValid($scope.searchData[key], key) for key in studentKeys return $scope.$watch 'searchData', (newValue) -> changed = false for key, value of newValue if !studentsDisabled or key not in studentKeys oldParamValue = $scope.params[key] if value && value.length > 0 $scope.params[key] = value else $scope.params[key] = null changed |= oldParamValue != $scope.params[key] $scope.reload() if changed return , true $scope.$watch 'superUser', (newValue) -> if newValue $scope.params.super_user = true else $scope.params.super_user = null $scope.reload() $scope.$watch 'teachersOnly', (newValue, oldValue) -> if newValue $scope.params.student = false disableStudentOnlyParams() $scope.reload() $scope.studentsOnly = false else enableStudentOnlyParams() if !$scope.studentsOnly $scope.params.student = null $scope.reload() $scope.$watch 'studentsOnly', (newValue, oldValue) -> if newValue $scope.params.student = true $scope.reload() $scope.teachersOnly = false else if !$scope.teachersOnly $scope.params.student = null $scope.reload() $scope.users = [] addUsersCallback = (newUsers) -> users = newUsers.filter (user) -> user.id not in deletedUserIds args = [0, $scope.users.length].concat users $scope.users.splice.apply $scope.users, args userDeletedCallback = (user) -> deletedUserIds.push user.id _.remove $scope.users, (e) -> e.id is user.id userFactory = (data) -> new User(data, userDeletedCallback) usersPagination = new Pagination UsersResource, 'users', $scope.params, userFactory, defaultPageSize $scope.currentPage = 1 $scope.reload = -> return if $scope.loadingUsers $scope.loadingUsers = true usersPagination.reload().then (users) -> $scope.loading = false $scope.loadingUsers = false addUsersCallback users loadUsersPage = (page) -> $scope.loadingUsers = true usersPagination.page(page).then (users) -> $scope.loading = false $scope.loadingUsers = false $scope.currentPage = page addUsersCallback users # Load first page loadUsersPage $scope.currentPage $scope.backDisabled = -> $scope.currentPage is 1 $scope.nextDisabled = -> $scope.currentPage >= usersPagination.totalPages $scope.next = -> if not $scope.nextDisabled() loadUsersPage($scope.currentPage + 1) $scope.back = -> if not $scope.backDisabled() loadUsersPage($scope.currentPage - 1)
true
angular.module 'evaluator' .controller 'UsersController', ($scope, Pagination, defaultPageSize, UsersResource, User, deletedUserIds) -> $scope.studentsOnly = false $scope.teachersOnly = false $scope.superUser = false $scope.loading = true $scope.loadingUsers = false $scope.searchData = name: '' email: '' team: '' guc_prefix: '' guc_suffix: '' $scope.params = name: null email: null guc_suffix: null guc_prefix: null student: null super_user: null team: null studentKeys = ['PI:KEY:<KEY>END_PI', 'gPI:KEY:<KEY>END_PI', 'team'] studentsDisabled = false $scope.userClasses = ['user-accent-one', 'user-accent-two', 'user-accent-three'] setIfValid = (value, key)-> if value && value.length > 0 $scope.params[key] = value disableStudentOnlyParams = -> studentsDisabled = true $scope.params[key] = null for key in studentKeys return enableStudentOnlyParams = -> studentsDisabled = false setIfValid($scope.searchData[key], key) for key in studentKeys return $scope.$watch 'searchData', (newValue) -> changed = false for key, value of newValue if !studentsDisabled or key not in studentKeys oldParamValue = $scope.params[key] if value && value.length > 0 $scope.params[key] = value else $scope.params[key] = null changed |= oldParamValue != $scope.params[key] $scope.reload() if changed return , true $scope.$watch 'superUser', (newValue) -> if newValue $scope.params.super_user = true else $scope.params.super_user = null $scope.reload() $scope.$watch 'teachersOnly', (newValue, oldValue) -> if newValue $scope.params.student = false disableStudentOnlyParams() $scope.reload() $scope.studentsOnly = false else enableStudentOnlyParams() if !$scope.studentsOnly $scope.params.student = null $scope.reload() $scope.$watch 'studentsOnly', (newValue, oldValue) -> if newValue $scope.params.student = true $scope.reload() $scope.teachersOnly = false else if !$scope.teachersOnly $scope.params.student = null $scope.reload() $scope.users = [] addUsersCallback = (newUsers) -> users = newUsers.filter (user) -> user.id not in deletedUserIds args = [0, $scope.users.length].concat users $scope.users.splice.apply $scope.users, args userDeletedCallback = (user) -> deletedUserIds.push user.id _.remove $scope.users, (e) -> e.id is user.id userFactory = (data) -> new User(data, userDeletedCallback) usersPagination = new Pagination UsersResource, 'users', $scope.params, userFactory, defaultPageSize $scope.currentPage = 1 $scope.reload = -> return if $scope.loadingUsers $scope.loadingUsers = true usersPagination.reload().then (users) -> $scope.loading = false $scope.loadingUsers = false addUsersCallback users loadUsersPage = (page) -> $scope.loadingUsers = true usersPagination.page(page).then (users) -> $scope.loading = false $scope.loadingUsers = false $scope.currentPage = page addUsersCallback users # Load first page loadUsersPage $scope.currentPage $scope.backDisabled = -> $scope.currentPage is 1 $scope.nextDisabled = -> $scope.currentPage >= usersPagination.totalPages $scope.next = -> if not $scope.nextDisabled() loadUsersPage($scope.currentPage + 1) $scope.back = -> if not $scope.backDisabled() loadUsersPage($scope.currentPage - 1)
[ { "context": "\n\n # Names must be a valid object key\n name1 = 'test event'\n name2 = 89\n\n # Listeners can be anythin", "end": 180, "score": 0.613341748714447, "start": 176, "tag": "NAME", "value": "test" } ]
test/EventDispatcher.mocha.coffee
TheMonkeys/derby
0
{expect, calls} = require 'racer/test/util' EventDispatcher = require '../lib/EventDispatcher' describe 'EventDispatcher', -> # Names must be a valid object key name1 = 'test event' name2 = 89 # Listeners can be anything that is representable in plain JSON listener1 = [1, 2, 'qu"a"il', "'", {arr: ['x', 'y']}] listener2 = 0 listener3 = 'stuff' listener4 = true # The second and third parameters sent to trigger are simply passed through # to the callback function. They can be anything. value1 = 'test value' options1 = {option: 4} it 'should work without callbacks', -> dispatcher = new EventDispatcher dispatcher.bind name1, listener1 dispatcher.trigger name1, value1, options1 it 'calls onTrigger', calls 2, (done) -> dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> expect(listener).to.eql listener1 expect(value).to.equal value1 expect(options).to.equal options1 done() dispatcher.bind name1, listener1 dispatcher.trigger name1, value1, options1 dispatcher.trigger name1, value1, options1 it 'calls onTrigger without listener', calls 2, (done) -> dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> expect(listener).to.equal undefined expect(value).to.equal value1 expect(options).to.equal options1 done() dispatcher.bind name1 dispatcher.trigger name1, value1, options1 dispatcher.trigger name1, value1, options1 it 'calls onTrigger for multiple listeners', calls 1, (done) -> counts = {all: 0} beforeExit = -> expect(counts[listener2]).to.equal 1 expect(counts[listener3]).to.equal 3 expect(counts[listener4]).to.equal 1 done() dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> counts[listener] = (counts[listener] || 0) + 1 expect(value).to.equal value1 expect(options).to.equal options1 beforeExit() if ++counts.all == 5 dispatcher.bind name1, listener2 dispatcher.bind name1, listener3 dispatcher.bind name1, listener4 dispatcher.bind name2, listener3 dispatcher.trigger name1, value1, options1 dispatcher.trigger name2, value1, options1 dispatcher.trigger name2, value1, options1 it 'test EventDispatcher remove listener after failed trigger', calls 1, (done) -> dispatcher = new EventDispatcher onTrigger: -> done() return false dispatcher.bind name1 dispatcher.trigger name1 dispatcher.trigger name1 it 'test EventDispatcher do not trigger twice after double bind', calls 1, (done) -> dispatcher = new EventDispatcher onTrigger: done dispatcher.bind name1, listener1 dispatcher.bind name1, listener1 dispatcher.trigger name1 it 'test EventDispatcher bind callback', calls 3, (done) -> dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> expect(listener).to.eql listener1 expect(value).to.equal value1 expect(options).to.equal options1 done() onBind: (name, listener) -> expect(name).to.equal name1 expect(listener).to.eql listener1 done() dispatcher.bind name1, listener1 dispatcher.trigger name1, value1, options1 dispatcher.trigger name1, value1, options1
106259
{expect, calls} = require 'racer/test/util' EventDispatcher = require '../lib/EventDispatcher' describe 'EventDispatcher', -> # Names must be a valid object key name1 = '<NAME> event' name2 = 89 # Listeners can be anything that is representable in plain JSON listener1 = [1, 2, 'qu"a"il', "'", {arr: ['x', 'y']}] listener2 = 0 listener3 = 'stuff' listener4 = true # The second and third parameters sent to trigger are simply passed through # to the callback function. They can be anything. value1 = 'test value' options1 = {option: 4} it 'should work without callbacks', -> dispatcher = new EventDispatcher dispatcher.bind name1, listener1 dispatcher.trigger name1, value1, options1 it 'calls onTrigger', calls 2, (done) -> dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> expect(listener).to.eql listener1 expect(value).to.equal value1 expect(options).to.equal options1 done() dispatcher.bind name1, listener1 dispatcher.trigger name1, value1, options1 dispatcher.trigger name1, value1, options1 it 'calls onTrigger without listener', calls 2, (done) -> dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> expect(listener).to.equal undefined expect(value).to.equal value1 expect(options).to.equal options1 done() dispatcher.bind name1 dispatcher.trigger name1, value1, options1 dispatcher.trigger name1, value1, options1 it 'calls onTrigger for multiple listeners', calls 1, (done) -> counts = {all: 0} beforeExit = -> expect(counts[listener2]).to.equal 1 expect(counts[listener3]).to.equal 3 expect(counts[listener4]).to.equal 1 done() dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> counts[listener] = (counts[listener] || 0) + 1 expect(value).to.equal value1 expect(options).to.equal options1 beforeExit() if ++counts.all == 5 dispatcher.bind name1, listener2 dispatcher.bind name1, listener3 dispatcher.bind name1, listener4 dispatcher.bind name2, listener3 dispatcher.trigger name1, value1, options1 dispatcher.trigger name2, value1, options1 dispatcher.trigger name2, value1, options1 it 'test EventDispatcher remove listener after failed trigger', calls 1, (done) -> dispatcher = new EventDispatcher onTrigger: -> done() return false dispatcher.bind name1 dispatcher.trigger name1 dispatcher.trigger name1 it 'test EventDispatcher do not trigger twice after double bind', calls 1, (done) -> dispatcher = new EventDispatcher onTrigger: done dispatcher.bind name1, listener1 dispatcher.bind name1, listener1 dispatcher.trigger name1 it 'test EventDispatcher bind callback', calls 3, (done) -> dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> expect(listener).to.eql listener1 expect(value).to.equal value1 expect(options).to.equal options1 done() onBind: (name, listener) -> expect(name).to.equal name1 expect(listener).to.eql listener1 done() dispatcher.bind name1, listener1 dispatcher.trigger name1, value1, options1 dispatcher.trigger name1, value1, options1
true
{expect, calls} = require 'racer/test/util' EventDispatcher = require '../lib/EventDispatcher' describe 'EventDispatcher', -> # Names must be a valid object key name1 = 'PI:NAME:<NAME>END_PI event' name2 = 89 # Listeners can be anything that is representable in plain JSON listener1 = [1, 2, 'qu"a"il', "'", {arr: ['x', 'y']}] listener2 = 0 listener3 = 'stuff' listener4 = true # The second and third parameters sent to trigger are simply passed through # to the callback function. They can be anything. value1 = 'test value' options1 = {option: 4} it 'should work without callbacks', -> dispatcher = new EventDispatcher dispatcher.bind name1, listener1 dispatcher.trigger name1, value1, options1 it 'calls onTrigger', calls 2, (done) -> dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> expect(listener).to.eql listener1 expect(value).to.equal value1 expect(options).to.equal options1 done() dispatcher.bind name1, listener1 dispatcher.trigger name1, value1, options1 dispatcher.trigger name1, value1, options1 it 'calls onTrigger without listener', calls 2, (done) -> dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> expect(listener).to.equal undefined expect(value).to.equal value1 expect(options).to.equal options1 done() dispatcher.bind name1 dispatcher.trigger name1, value1, options1 dispatcher.trigger name1, value1, options1 it 'calls onTrigger for multiple listeners', calls 1, (done) -> counts = {all: 0} beforeExit = -> expect(counts[listener2]).to.equal 1 expect(counts[listener3]).to.equal 3 expect(counts[listener4]).to.equal 1 done() dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> counts[listener] = (counts[listener] || 0) + 1 expect(value).to.equal value1 expect(options).to.equal options1 beforeExit() if ++counts.all == 5 dispatcher.bind name1, listener2 dispatcher.bind name1, listener3 dispatcher.bind name1, listener4 dispatcher.bind name2, listener3 dispatcher.trigger name1, value1, options1 dispatcher.trigger name2, value1, options1 dispatcher.trigger name2, value1, options1 it 'test EventDispatcher remove listener after failed trigger', calls 1, (done) -> dispatcher = new EventDispatcher onTrigger: -> done() return false dispatcher.bind name1 dispatcher.trigger name1 dispatcher.trigger name1 it 'test EventDispatcher do not trigger twice after double bind', calls 1, (done) -> dispatcher = new EventDispatcher onTrigger: done dispatcher.bind name1, listener1 dispatcher.bind name1, listener1 dispatcher.trigger name1 it 'test EventDispatcher bind callback', calls 3, (done) -> dispatcher = new EventDispatcher onTrigger: (name, listener, value, options) -> expect(listener).to.eql listener1 expect(value).to.equal value1 expect(options).to.equal options1 done() onBind: (name, listener) -> expect(name).to.equal name1 expect(listener).to.eql listener1 done() dispatcher.bind name1, listener1 dispatcher.trigger name1, value1, options1 dispatcher.trigger name1, value1, options1
[ { "context": "ery UI checkbox editor 1.0.0\n\n Copyright (c) 2016 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-jquer", "end": 91, "score": 0.9998743534088135, "start": 75, "tag": "NAME", "value": "Tomasz Jakub Rup" }, { "context": "t (c) 2016 Tomasz Jakub Rup\n\n ...
src/checkbox.coffee
tomi77/backbone-forms-jquery-ui
0
### Backbone-Forms jQuery UI checkbox editor 1.0.0 Copyright (c) 2016 Tomasz Jakub Rup https://github.com/tomi77/backbone-forms-jquery-ui Released under the MIT license ### ((root, factory) -> ### istanbul ignore next ### switch when typeof define is 'function' and define.amd define ['backbone-forms', 'jquery-ui/widgets/checkboxradio'], factory when typeof exports is 'object' require('jquery-ui/widgets/checkboxradio') factory require('backbone-forms') else factory root.Backbone.Form return ) @, (Form) -> Form.editors['jqueryui.checkbox'] = Form.editors.Checkbox.extend className: 'bbf-jui-checkbox' initialize: (options) -> Form.editors.Checkbox::initialize.call @, options @editorOptions = @schema.editorOptions or {} [@$input, @$el, $label] = [@$el, Backbone.$('<div>'), Backbone.$("<label for='#{ @id }'>")] @el = @$el[0] $label.html('&nbsp;') @$el.html @$input @$el.append $label return render: () -> @$input.checkboxradio @editorOptions Form.editors.Checkbox::render.call @ getValue: () -> @$input.prop('checked') setValue: (value) -> @$input.prop('checked', value is true) return focus: () -> if @hasFocus then return @$input.focus() return blur: () -> if not @hasFocus then return @$input.blur() return return
11319
### Backbone-Forms jQuery UI checkbox editor 1.0.0 Copyright (c) 2016 <NAME> https://github.com/tomi77/backbone-forms-jquery-ui Released under the MIT license ### ((root, factory) -> ### istanbul ignore next ### switch when typeof define is 'function' and define.amd define ['backbone-forms', 'jquery-ui/widgets/checkboxradio'], factory when typeof exports is 'object' require('jquery-ui/widgets/checkboxradio') factory require('backbone-forms') else factory root.Backbone.Form return ) @, (Form) -> Form.editors['jqueryui.checkbox'] = Form.editors.Checkbox.extend className: 'bbf-jui-checkbox' initialize: (options) -> Form.editors.Checkbox::initialize.call @, options @editorOptions = @schema.editorOptions or {} [@$input, @$el, $label] = [@$el, Backbone.$('<div>'), Backbone.$("<label for='#{ @id }'>")] @el = @$el[0] $label.html('&nbsp;') @$el.html @$input @$el.append $label return render: () -> @$input.checkboxradio @editorOptions Form.editors.Checkbox::render.call @ getValue: () -> @$input.prop('checked') setValue: (value) -> @$input.prop('checked', value is true) return focus: () -> if @hasFocus then return @$input.focus() return blur: () -> if not @hasFocus then return @$input.blur() return return
true
### Backbone-Forms jQuery UI checkbox editor 1.0.0 Copyright (c) 2016 PI:NAME:<NAME>END_PI https://github.com/tomi77/backbone-forms-jquery-ui Released under the MIT license ### ((root, factory) -> ### istanbul ignore next ### switch when typeof define is 'function' and define.amd define ['backbone-forms', 'jquery-ui/widgets/checkboxradio'], factory when typeof exports is 'object' require('jquery-ui/widgets/checkboxradio') factory require('backbone-forms') else factory root.Backbone.Form return ) @, (Form) -> Form.editors['jqueryui.checkbox'] = Form.editors.Checkbox.extend className: 'bbf-jui-checkbox' initialize: (options) -> Form.editors.Checkbox::initialize.call @, options @editorOptions = @schema.editorOptions or {} [@$input, @$el, $label] = [@$el, Backbone.$('<div>'), Backbone.$("<label for='#{ @id }'>")] @el = @$el[0] $label.html('&nbsp;') @$el.html @$input @$el.append $label return render: () -> @$input.checkboxradio @editorOptions Form.editors.Checkbox::render.call @ getValue: () -> @$input.prop('checked') setValue: (value) -> @$input.prop('checked', value is true) return focus: () -> if @hasFocus then return @$input.focus() return blur: () -> if not @hasFocus then return @$input.blur() return return
[ { "context": "###\n Copyright (c) 2015 Abi Hafshin\n see README.md\n###\n\ndebug = require('debug')('ap", "end": 36, "score": 0.999877393245697, "start": 25, "tag": "NAME", "value": "Abi Hafshin" } ]
app/router.coffee
abihf/express-rad
0
### Copyright (c) 2015 Abi Hafshin see README.md ### debug = require('debug')('app:router') Path = require 'path' class Router ### ### constructor: (routes) -> @_basePath = '/' @_simpleRoutes = {} @_regexRoutes = [] @_names = {} for path,name of routes if path.match /:/ @_addRegexRoutes(path, name) else @_addSimpleRoutes(path, name) _addSimpleRoutes: (path, name) -> @_simpleRoutes[path] = name @_names[name] = path _matchSimpleRoutes: (path) -> path = path.replace(/\/{2,}/g, '/') if (path.length > 2) path = path.replace(/\/$/, '') if @_simpleRoutes[path] return {name: @_simpleRoutes[path], param: {}} _addRegexRoutes: (path, name) -> params = [] matchingParts = [] generatingParts = [] for t in path.split('/') colon_index = t.indexOf(':') if colon_index >= 0 param_name = t.substr(colon_index+1) regex = if colon_index is 0 then new RegExp("^#{t.substr(0, colon_index)}$") else /.*/ matchingParts.push(regex) params.push(param_name) generatingParts.push("{#{param_name}}") else matchingParts.push(t) generatingParts.push(t) @_regexRoutes.push {parts: matchingParts, params: params, name: name} @_names[name] = generatingParts.concat('/') _matchRegexRoutes: (path) -> parts = path.split('/') for route in @_regexRoutes match = true params = {} param_index = 0 i = 0 while match and i < route.parts.length p = route.parts[i] if typeof p is 'string' if p isnt parts[i] match = false else # if p instanceof RegExp if not parts[i].match(p) match = false else param_name = route.params[param_index++] params[param_name] = parts[i] i++ if match # really match return {name: route.name, params: params} return null matchUrl: (path) -> path = path.replace(/(^\/+)|(\/+$)/g, '').replace(/\/{2,}/g, '.') if res = @_matchSimpleRoutes(path) return res else if res = @_matchRegexRoutes(path) return res else name = path.replace(/\//g, '.') return {name: name, param: {}} createUrl: (name, params, relativePath) -> url = @_names[name] || name.replace(/\./g, '/') url = url.replace /\{\w\}/g, (p) -> if not params[p] debug('createUrl(%s) incomplete param %s', name, p) return params[p] return Path.join @_basePath, url handleRequest: (req, res, next) -> debug('handling request %', req.url) route = @matchUrl(req.path) if route debug('route name: %s', route.name) req.routeName = route.name for k,v of route.param req.param[k] = v else debug('unknown route name') _this = this res.createUrl = res.locals.url = (name, params) -> _this.createUrl(name, params, req.routeName) next() module.exports = (app, routes) -> debug('configuring...') router = new Router(routes || {}) app.routeManager = router return router.handleRequest.bind(router)
50694
### Copyright (c) 2015 <NAME> see README.md ### debug = require('debug')('app:router') Path = require 'path' class Router ### ### constructor: (routes) -> @_basePath = '/' @_simpleRoutes = {} @_regexRoutes = [] @_names = {} for path,name of routes if path.match /:/ @_addRegexRoutes(path, name) else @_addSimpleRoutes(path, name) _addSimpleRoutes: (path, name) -> @_simpleRoutes[path] = name @_names[name] = path _matchSimpleRoutes: (path) -> path = path.replace(/\/{2,}/g, '/') if (path.length > 2) path = path.replace(/\/$/, '') if @_simpleRoutes[path] return {name: @_simpleRoutes[path], param: {}} _addRegexRoutes: (path, name) -> params = [] matchingParts = [] generatingParts = [] for t in path.split('/') colon_index = t.indexOf(':') if colon_index >= 0 param_name = t.substr(colon_index+1) regex = if colon_index is 0 then new RegExp("^#{t.substr(0, colon_index)}$") else /.*/ matchingParts.push(regex) params.push(param_name) generatingParts.push("{#{param_name}}") else matchingParts.push(t) generatingParts.push(t) @_regexRoutes.push {parts: matchingParts, params: params, name: name} @_names[name] = generatingParts.concat('/') _matchRegexRoutes: (path) -> parts = path.split('/') for route in @_regexRoutes match = true params = {} param_index = 0 i = 0 while match and i < route.parts.length p = route.parts[i] if typeof p is 'string' if p isnt parts[i] match = false else # if p instanceof RegExp if not parts[i].match(p) match = false else param_name = route.params[param_index++] params[param_name] = parts[i] i++ if match # really match return {name: route.name, params: params} return null matchUrl: (path) -> path = path.replace(/(^\/+)|(\/+$)/g, '').replace(/\/{2,}/g, '.') if res = @_matchSimpleRoutes(path) return res else if res = @_matchRegexRoutes(path) return res else name = path.replace(/\//g, '.') return {name: name, param: {}} createUrl: (name, params, relativePath) -> url = @_names[name] || name.replace(/\./g, '/') url = url.replace /\{\w\}/g, (p) -> if not params[p] debug('createUrl(%s) incomplete param %s', name, p) return params[p] return Path.join @_basePath, url handleRequest: (req, res, next) -> debug('handling request %', req.url) route = @matchUrl(req.path) if route debug('route name: %s', route.name) req.routeName = route.name for k,v of route.param req.param[k] = v else debug('unknown route name') _this = this res.createUrl = res.locals.url = (name, params) -> _this.createUrl(name, params, req.routeName) next() module.exports = (app, routes) -> debug('configuring...') router = new Router(routes || {}) app.routeManager = router return router.handleRequest.bind(router)
true
### Copyright (c) 2015 PI:NAME:<NAME>END_PI see README.md ### debug = require('debug')('app:router') Path = require 'path' class Router ### ### constructor: (routes) -> @_basePath = '/' @_simpleRoutes = {} @_regexRoutes = [] @_names = {} for path,name of routes if path.match /:/ @_addRegexRoutes(path, name) else @_addSimpleRoutes(path, name) _addSimpleRoutes: (path, name) -> @_simpleRoutes[path] = name @_names[name] = path _matchSimpleRoutes: (path) -> path = path.replace(/\/{2,}/g, '/') if (path.length > 2) path = path.replace(/\/$/, '') if @_simpleRoutes[path] return {name: @_simpleRoutes[path], param: {}} _addRegexRoutes: (path, name) -> params = [] matchingParts = [] generatingParts = [] for t in path.split('/') colon_index = t.indexOf(':') if colon_index >= 0 param_name = t.substr(colon_index+1) regex = if colon_index is 0 then new RegExp("^#{t.substr(0, colon_index)}$") else /.*/ matchingParts.push(regex) params.push(param_name) generatingParts.push("{#{param_name}}") else matchingParts.push(t) generatingParts.push(t) @_regexRoutes.push {parts: matchingParts, params: params, name: name} @_names[name] = generatingParts.concat('/') _matchRegexRoutes: (path) -> parts = path.split('/') for route in @_regexRoutes match = true params = {} param_index = 0 i = 0 while match and i < route.parts.length p = route.parts[i] if typeof p is 'string' if p isnt parts[i] match = false else # if p instanceof RegExp if not parts[i].match(p) match = false else param_name = route.params[param_index++] params[param_name] = parts[i] i++ if match # really match return {name: route.name, params: params} return null matchUrl: (path) -> path = path.replace(/(^\/+)|(\/+$)/g, '').replace(/\/{2,}/g, '.') if res = @_matchSimpleRoutes(path) return res else if res = @_matchRegexRoutes(path) return res else name = path.replace(/\//g, '.') return {name: name, param: {}} createUrl: (name, params, relativePath) -> url = @_names[name] || name.replace(/\./g, '/') url = url.replace /\{\w\}/g, (p) -> if not params[p] debug('createUrl(%s) incomplete param %s', name, p) return params[p] return Path.join @_basePath, url handleRequest: (req, res, next) -> debug('handling request %', req.url) route = @matchUrl(req.path) if route debug('route name: %s', route.name) req.routeName = route.name for k,v of route.param req.param[k] = v else debug('unknown route name') _this = this res.createUrl = res.locals.url = (name, params) -> _this.createUrl(name, params, req.routeName) next() module.exports = (app, routes) -> debug('configuring...') router = new Router(routes || {}) app.routeManager = router return router.handleRequest.bind(router)
[ { "context": "e.username? and username.password?\n @username username.username\n @password username.password\n el", "end": 2445, "score": 0.845268726348877, "start": 2437, "tag": "USERNAME", "value": "username" }, { "context": " else if username? and password?\n @...
src/host.coffee
h2non/node-authrc
1
Actions = require './actions' crypto = require './crypto' hostMatch = require './hostMatch' { ALGORITHM } = require './constants' { parseUri, formatUri, isObject, cloneDeep, getEnvVar, isRegex, validRegex, isString, trim, lowerCase } = require './common' module.exports = class Host extends Actions file: null data: null host: null search: null constructor: (file, data, search = '') -> @file = file @data = data @search = search @host = hostMatch @data, search get: => if @data then cloneDeep @data[@host] else null set: (hostObj) => if isObject(hostObj) and hostObj.username? and hostObj.password? @data[@host] = cloneDeep hostObj yes else no exists: => @data? and @host isnt null and @get()?.password? isValid: => if @exists() and @username()? and @password()? if isRegex @host and not validRegex @host no else yes else no valid: Host::isValid user: (newValue) => return null if not @exists() @data[@host].username = newValue if newValue? and isString newValue @get().username or null username: Host::user getPasswordObj: => return null unless @exists() passwordObj = @get().password passwordObj = { value: passwordObj } if isString passwordObj passwordObj or null password: (newValue) => return null unless @exists() return @setPassword newValue if newValue? { password } = @get() if isObject password if password.envValue password = getEnvVar password.envValue else password = password.value password or null setPassword: (obj) => return null unless @exists() return null if not isObject(obj) and not isString obj @data[@host].password = cloneDeep obj obj passwordKey: => return null unless passwordObj = @getPasswordObj() key = getEnvVar passwordObj.envKey if passwordObj.envKey? key or null cipher: (cipher) => return null unless @exists() password = @getPasswordObj() return null if not isObject password password.cipher = cipher if cipher? and crypto.cipherExists cipher if password.cipher cipher = trim lowerCase(password.cipher) else if password.encrypted is true cipher = ALGORITHM cipher or null auth: (username, password) => if isObject(username) and username.username? and username.password? @username username.username @password username.password else if username? and password? @username username @password password return null unless @exists() { username, password } = @get() password = @password() { username: username, password: password } copy: (newHostStr) => if @exists() and not @data[newHostStr] and isString(newHostStr) @data[newHostStr] = cloneDeep @host yes else no authUrl: => return @search unless auth = @auth() url = parseUri @search url.auth = "#{auth.username}:#{auth.password}" formatUri(url) isEncrypted: => return no unless @exists() { password } = @get() return no if not isObject password return no if (not password.cipher or password.cipher is 'plain') and password.encrypted isnt true crypto.cipherExists @cipher() encrypted: Host::isEncrypted canDecrypt: => @isEncrypted() and @passwordKey()? # @throws Error, TypeError decrypt: (key = @passwordKey(), cipher = @cipher()) => throw new Error('The password value do not exists') unless @exists() throw new TypeError("Unsupported cipher algorithm: #{cipher}") unless crypto.cipherExists cipher return @password() if not @isEncrypted() throw new TypeError('Missing required key argument') if not isString key crypto.decrypt @password(), key, cipher # @throws Error, TypeError encrypt: (key = @passwordKey(), cipher = ALGORITHM) => throw new Error('The password value do not exists') unless @exists() throw new TypeError("Unsupported cipher algorithm: #{cipher}") unless crypto.cipherExists cipher throw new Error('The password is already encrypted') if @isEncrypted() throw new TypeError('Missing required key argument') if not isString key password = crypto.encrypt @password(), key, cipher @setPassword cipher: cipher value: password @
177144
Actions = require './actions' crypto = require './crypto' hostMatch = require './hostMatch' { ALGORITHM } = require './constants' { parseUri, formatUri, isObject, cloneDeep, getEnvVar, isRegex, validRegex, isString, trim, lowerCase } = require './common' module.exports = class Host extends Actions file: null data: null host: null search: null constructor: (file, data, search = '') -> @file = file @data = data @search = search @host = hostMatch @data, search get: => if @data then cloneDeep @data[@host] else null set: (hostObj) => if isObject(hostObj) and hostObj.username? and hostObj.password? @data[@host] = cloneDeep hostObj yes else no exists: => @data? and @host isnt null and @get()?.password? isValid: => if @exists() and @username()? and @password()? if isRegex @host and not validRegex @host no else yes else no valid: Host::isValid user: (newValue) => return null if not @exists() @data[@host].username = newValue if newValue? and isString newValue @get().username or null username: Host::user getPasswordObj: => return null unless @exists() passwordObj = @get().password passwordObj = { value: passwordObj } if isString passwordObj passwordObj or null password: (newValue) => return null unless @exists() return @setPassword newValue if newValue? { password } = @get() if isObject password if password.envValue password = getEnvVar password.envValue else password = password.value password or null setPassword: (obj) => return null unless @exists() return null if not isObject(obj) and not isString obj @data[@host].password = cloneDeep obj obj passwordKey: => return null unless passwordObj = @getPasswordObj() key = getEnvVar passwordObj.envKey if passwordObj.envKey? key or null cipher: (cipher) => return null unless @exists() password = @getPasswordObj() return null if not isObject password password.cipher = cipher if cipher? and crypto.cipherExists cipher if password.cipher cipher = trim lowerCase(password.cipher) else if password.encrypted is true cipher = ALGORITHM cipher or null auth: (username, password) => if isObject(username) and username.username? and username.password? @username username.username @password username.password else if username? and password? @username username @password password return null unless @exists() { username, password } = @get() password = @password() { username: username, password: <PASSWORD> } copy: (newHostStr) => if @exists() and not @data[newHostStr] and isString(newHostStr) @data[newHostStr] = cloneDeep @host yes else no authUrl: => return @search unless auth = @auth() url = parseUri @search url.auth = "#{auth.username}:#{auth.password}" formatUri(url) isEncrypted: => return no unless @exists() { password } = @get() return no if not isObject password return no if (not password.cipher or password.cipher is 'plain') and password.encrypted isnt true crypto.cipherExists @cipher() encrypted: Host::isEncrypted canDecrypt: => @isEncrypted() and @passwordKey()? # @throws Error, TypeError decrypt: (key = @passwordKey(), cipher = @cipher()) => throw new Error('The password value do not exists') unless @exists() throw new TypeError("Unsupported cipher algorithm: #{cipher}") unless crypto.cipherExists cipher return @password() if not @isEncrypted() throw new TypeError('Missing required key argument') if not isString key crypto.decrypt @password(), key, cipher # @throws Error, TypeError encrypt: (key = @passwordKey(), cipher = ALGORITHM) => throw new Error('The password value do not exists') unless @exists() throw new TypeError("Unsupported cipher algorithm: #{cipher}") unless crypto.cipherExists cipher throw new Error('The password is already encrypted') if @isEncrypted() throw new TypeError('Missing required key argument') if not isString key password = crypto.encrypt @password(), key, cipher @setPassword cipher: cipher value: password @
true
Actions = require './actions' crypto = require './crypto' hostMatch = require './hostMatch' { ALGORITHM } = require './constants' { parseUri, formatUri, isObject, cloneDeep, getEnvVar, isRegex, validRegex, isString, trim, lowerCase } = require './common' module.exports = class Host extends Actions file: null data: null host: null search: null constructor: (file, data, search = '') -> @file = file @data = data @search = search @host = hostMatch @data, search get: => if @data then cloneDeep @data[@host] else null set: (hostObj) => if isObject(hostObj) and hostObj.username? and hostObj.password? @data[@host] = cloneDeep hostObj yes else no exists: => @data? and @host isnt null and @get()?.password? isValid: => if @exists() and @username()? and @password()? if isRegex @host and not validRegex @host no else yes else no valid: Host::isValid user: (newValue) => return null if not @exists() @data[@host].username = newValue if newValue? and isString newValue @get().username or null username: Host::user getPasswordObj: => return null unless @exists() passwordObj = @get().password passwordObj = { value: passwordObj } if isString passwordObj passwordObj or null password: (newValue) => return null unless @exists() return @setPassword newValue if newValue? { password } = @get() if isObject password if password.envValue password = getEnvVar password.envValue else password = password.value password or null setPassword: (obj) => return null unless @exists() return null if not isObject(obj) and not isString obj @data[@host].password = cloneDeep obj obj passwordKey: => return null unless passwordObj = @getPasswordObj() key = getEnvVar passwordObj.envKey if passwordObj.envKey? key or null cipher: (cipher) => return null unless @exists() password = @getPasswordObj() return null if not isObject password password.cipher = cipher if cipher? and crypto.cipherExists cipher if password.cipher cipher = trim lowerCase(password.cipher) else if password.encrypted is true cipher = ALGORITHM cipher or null auth: (username, password) => if isObject(username) and username.username? and username.password? @username username.username @password username.password else if username? and password? @username username @password password return null unless @exists() { username, password } = @get() password = @password() { username: username, password: PI:PASSWORD:<PASSWORD>END_PI } copy: (newHostStr) => if @exists() and not @data[newHostStr] and isString(newHostStr) @data[newHostStr] = cloneDeep @host yes else no authUrl: => return @search unless auth = @auth() url = parseUri @search url.auth = "#{auth.username}:#{auth.password}" formatUri(url) isEncrypted: => return no unless @exists() { password } = @get() return no if not isObject password return no if (not password.cipher or password.cipher is 'plain') and password.encrypted isnt true crypto.cipherExists @cipher() encrypted: Host::isEncrypted canDecrypt: => @isEncrypted() and @passwordKey()? # @throws Error, TypeError decrypt: (key = @passwordKey(), cipher = @cipher()) => throw new Error('The password value do not exists') unless @exists() throw new TypeError("Unsupported cipher algorithm: #{cipher}") unless crypto.cipherExists cipher return @password() if not @isEncrypted() throw new TypeError('Missing required key argument') if not isString key crypto.decrypt @password(), key, cipher # @throws Error, TypeError encrypt: (key = @passwordKey(), cipher = ALGORITHM) => throw new Error('The password value do not exists') unless @exists() throw new TypeError("Unsupported cipher algorithm: #{cipher}") unless crypto.cipherExists cipher throw new Error('The password is already encrypted') if @isEncrypted() throw new TypeError('Missing required key argument') if not isString key password = crypto.encrypt @password(), key, cipher @setPassword cipher: cipher value: password @
[ { "context": "licked')\n\n my_user_name = jQuery('#username').val()\n my_user_password = jQuery", "end": 1388, "score": 0.8079220652580261, "start": 1380, "tag": "USERNAME", "value": "username" }, { "context": "val()\n my_user_password = j...
src/ui/js/dist/app.src.coffee
saeschdivara/SecretWhisperer-Desktop-Client
0
startUpWithWebChannel = () -> new QWebChannel(qt.webChannelTransport, (channel) -> mainFunction(channel.objects.chat) ) mainFunction = (chat) -> # Expose chat as global object window.chat = chat ############################ ## MESSAGES CALLBACKS ########################### onUserMessageReceived = (username, message) -> create_message_to_me( contact: username message: message ) onUserFileReceived = (username, message) -> create_file_message_to_me( contact: username message: message ) ############################# ## USER CALLBACKS ############################# onUserChosen = () -> username = jQuery('#other-username').val() chat.connectToUser(username) jQuery('#chatbox').show() onUserAdded = (username) -> _class_instance_MessageQueue.$publish('add-contact', username) jQuery('#chatbox').show() onContactsLoaded = (contactsString) -> contacts = contactsString.split('|') for contact in contacts onUserAdded(contact) onServerConnect = () -> console.log('Connected') jQuery('#submit-user-button').click( () -> console.log('on login button clicked') my_user_name = jQuery('#username').val() my_user_password = jQuery('#password').val() chat.chooseUserName(my_user_name, my_user_password) jQuery('#userbox').hide() jQuery('#submit-other-user-button').click(onUserChosen) chat.connectionToUserEstablished.connect(onUserAdded) chat.contactsLoaded.connect(onContactsLoaded) chat.receivedUserMessage.connect(onUserMessageReceived) chat.receivedUserFile.connect(onUserFileReceived) chat.loadContacts() ) onServerError = (error) -> console.log(error) chat.connected.connect(onServerConnect) chat.error.connect(onServerError) chat.connectToServer(window.CHAT_SERVER_URL, 8888) console.log('connected to the server') jQuery('#chatbox').hide() onDocumentReady = () -> # Starting first to connect to web channel startUpWithWebChannel() jQuery(document).ready(onDocumentReady) create_message_from_me = (message) -> _class_instance_MessageQueue.$publish('new-message-from-me', message) create_message_to_me = (message) -> _class_instance_MessageQueue.$publish('new-message-from-other', message) create_file_message_to_me = (message) -> _class_instance_MessageQueue.$publish('new-file-from-other', message) chatApp = angular.module('chatApp', []) chatApp.config(['$compileProvider', ($compileProvider) -> $compileProvider.aHrefSanitizationWhitelist(/^\s*(stream):/) $compileProvider.imgSrcSanitizationWhitelist(/^\s*(stream):/) ]) _class_instance_MessageQueue = null chatApp.factory('MessageQueue', [() -> class MessageQueue ######################## ## PRIVATE PROPERTIES ## ######################## _channels: {} ####################### ## PUBLIC PROPERTIES ## ####################### #################### ## PUBLIC METHODS ## #################### constructor: () -> ### ### $subscribe: (channel, subscriber) -> ### ### if not @_channels.hasOwnProperty(channel) @_channels[channel] = [] @_channels[channel].push(subscriber) $publish: (channel, message) -> ### ### if @_channels.hasOwnProperty(channel) for subscriber in @_channels[channel] subscriber(message) @$instance: () -> ### ### if not _class_instance_MessageQueue? # Create instance _class_instance_MessageQueue = new MessageQueue() return _class_instance_MessageQueue ##################### ## PRIVATE METHODS ## ##################### # Return the factory MessageQueue.$instance() ]) log = (message) -> jQuery('#message-board').append("<span>#{message}</span>") getRandomHexString = () -> ### Generates random hex number string @return {String} ### return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) _class_instance_ChatController = null chatApp.controller('ChatController', ['$rootScope', '$scope', '$sce', 'MessageQueue', ($rootScope, $scope, $sce, MessageQueue) -> class ChatMessage ######################## ## PRIVATE PROPERTIES ## ######################## ####################### ## PUBLIC PROPERTIES ## ####################### #################### ## PUBLIC METHODS ## #################### constructor: (message, from_me, from_contact, is_file) -> ### ### @DATA_TYPES = images: ['jpg', 'jpeg', 'png', 'gif'] audios: ['mp3'] movies: ['mp4', 'webm'] @message = message @is_from_me = from_me @is_from_contact = from_contact if @is_from_me @message_classes = ['my-message', 'blue', 'lighten-3'] else if @is_from_contact @message_classes = ['partner-message', 'blue', 'darken-1'] if is_file @message_type = @getType() else @message_type = 'text' getType: () -> ### ### if @_isType('images', @message) 'image' else if @_isType('audios', @message) 'audio' else if @_isType('movies', @message) 'movie' else 'downloadable' link: () -> ### ### @message image: () -> ### ### @message audio: () -> ### ### $sce.trustAsResourceUrl(@message) movie: () -> ### ### $sce.trustAsResourceUrl(@message) text: () -> ### ### @message _isType: (type_name, data_string) -> ### ### for type in @DATA_TYPES[type_name] if data_string.toLowerCase().indexOf("." + type) > -1 return true return false class ChatContact ######################## ## PRIVATE PROPERTIES ## ######################## ####################### ## PUBLIC PROPERTIES ## ####################### #################### ## PUBLIC METHODS ## #################### constructor: (@username) -> ### ### @messages = [] @active = true ################################################################ # STATIC CONTROLLER CLASS ################################################################ class ChatController ######################## ## PRIVATE PROPERTIES ## ######################## ####################### ## PUBLIC PROPERTIES ## ####################### contacts: [] current_contact: null current_messages: [] current_typed_message: '' #################### ## PUBLIC METHODS ## #################### constructor: () -> ### ### @contacts = [] @current_messages = [] @is_file_chosen = false onContactChanged: (contact) -> ### ### if @current_contact is contact return @current_contact.messages.length = 0 @current_contact.messages.push(message) for message in @current_messages @current_contact.active = false @current_contact = contact @current_messages.length = 0 @current_messages.push(message) for message in contact.messages @current_contact.active = true onMessageSend: () => ### ### message = @current_typed_message @current_typed_message.length = 0 @current_typed_message = '' chat.sendMessageToUser(@current_contact.username, message) create_message_from_me(message) onUploadFile: () => ### ### $file_input = jQuery('#file-input-button') $file_input.change( () => console.log('file chosen') reader = new FileReader() reader.onload = () => url = reader.result console.log(url) chat.sendMessageToUser(@current_contact.username, url) files = $file_input[0].files reader.readAsDataURL(files[0]) ) $file_input.click() onMessageFromMe: (message) => ### ### @current_messages.push( new ChatMessage(message, true, false) ) $scope.$apply() onMessageFromContact: (message) => ### ### username = message.contact message_text = message.message if @current_contact.username == username @current_messages.push( new ChatMessage(message_text, false, true, false) ) else for contact in @contacts if contact.username == username contact.messages.push(new ChatMessage(message_text, false, true, false)) $scope.$apply() onFileFromContact: (message) => ### ### username = message.contact message_text = message.message if @current_contact.username == username @current_messages.push( new ChatMessage(message_text, false, true, true) ) else for contact in @contacts if contact.username == username contact.messages.push(new ChatMessage(message_text, false, true, true)) $scope.$apply() onContactAdded: (username) => ### ### for contact in @contacts if contact.username == username return else contact.active = false contact = new ChatContact(username) @contacts.push(contact) @current_contact = contact $scope.$apply() @$instance: () -> ### ### if not _class_instance_ChatController? # Create instance _class_instance_ChatController = new ChatController() return _class_instance_ChatController ##################### ## PRIVATE METHODS ## ##################### ####################### ## CREATE CONTROLLER ## ####################### controller = ChatController.$instance() ################################################################ # CONFIGURE CONTROLLER ################################################################ MessageQueue.$subscribe('add-contact', controller.onContactAdded) MessageQueue.$subscribe('new-message-from-me', controller.onMessageFromMe) MessageQueue.$subscribe('new-message-from-other', controller.onMessageFromContact) MessageQueue.$subscribe('new-file-from-other', controller.onFileFromContact) ################################################################ # CONTROLLER SCOPE ################################################################ ################ ## INIT SCOPE ## ################ ################# ## WATCH SCOPE ## ################# ################################################################ # RETURN CONTROLLER ################################################################ return controller ])
128150
startUpWithWebChannel = () -> new QWebChannel(qt.webChannelTransport, (channel) -> mainFunction(channel.objects.chat) ) mainFunction = (chat) -> # Expose chat as global object window.chat = chat ############################ ## MESSAGES CALLBACKS ########################### onUserMessageReceived = (username, message) -> create_message_to_me( contact: username message: message ) onUserFileReceived = (username, message) -> create_file_message_to_me( contact: username message: message ) ############################# ## USER CALLBACKS ############################# onUserChosen = () -> username = jQuery('#other-username').val() chat.connectToUser(username) jQuery('#chatbox').show() onUserAdded = (username) -> _class_instance_MessageQueue.$publish('add-contact', username) jQuery('#chatbox').show() onContactsLoaded = (contactsString) -> contacts = contactsString.split('|') for contact in contacts onUserAdded(contact) onServerConnect = () -> console.log('Connected') jQuery('#submit-user-button').click( () -> console.log('on login button clicked') my_user_name = jQuery('#username').val() my_user_password = jQuery('#<PASSWORD>').val() chat.chooseUserName(my_user_name, my_user_password) jQuery('#userbox').hide() jQuery('#submit-other-user-button').click(onUserChosen) chat.connectionToUserEstablished.connect(onUserAdded) chat.contactsLoaded.connect(onContactsLoaded) chat.receivedUserMessage.connect(onUserMessageReceived) chat.receivedUserFile.connect(onUserFileReceived) chat.loadContacts() ) onServerError = (error) -> console.log(error) chat.connected.connect(onServerConnect) chat.error.connect(onServerError) chat.connectToServer(window.CHAT_SERVER_URL, 8888) console.log('connected to the server') jQuery('#chatbox').hide() onDocumentReady = () -> # Starting first to connect to web channel startUpWithWebChannel() jQuery(document).ready(onDocumentReady) create_message_from_me = (message) -> _class_instance_MessageQueue.$publish('new-message-from-me', message) create_message_to_me = (message) -> _class_instance_MessageQueue.$publish('new-message-from-other', message) create_file_message_to_me = (message) -> _class_instance_MessageQueue.$publish('new-file-from-other', message) chatApp = angular.module('chatApp', []) chatApp.config(['$compileProvider', ($compileProvider) -> $compileProvider.aHrefSanitizationWhitelist(/^\s*(stream):/) $compileProvider.imgSrcSanitizationWhitelist(/^\s*(stream):/) ]) _class_instance_MessageQueue = null chatApp.factory('MessageQueue', [() -> class MessageQueue ######################## ## PRIVATE PROPERTIES ## ######################## _channels: {} ####################### ## PUBLIC PROPERTIES ## ####################### #################### ## PUBLIC METHODS ## #################### constructor: () -> ### ### $subscribe: (channel, subscriber) -> ### ### if not @_channels.hasOwnProperty(channel) @_channels[channel] = [] @_channels[channel].push(subscriber) $publish: (channel, message) -> ### ### if @_channels.hasOwnProperty(channel) for subscriber in @_channels[channel] subscriber(message) @$instance: () -> ### ### if not _class_instance_MessageQueue? # Create instance _class_instance_MessageQueue = new MessageQueue() return _class_instance_MessageQueue ##################### ## PRIVATE METHODS ## ##################### # Return the factory MessageQueue.$instance() ]) log = (message) -> jQuery('#message-board').append("<span>#{message}</span>") getRandomHexString = () -> ### Generates random hex number string @return {String} ### return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) _class_instance_ChatController = null chatApp.controller('ChatController', ['$rootScope', '$scope', '$sce', 'MessageQueue', ($rootScope, $scope, $sce, MessageQueue) -> class ChatMessage ######################## ## PRIVATE PROPERTIES ## ######################## ####################### ## PUBLIC PROPERTIES ## ####################### #################### ## PUBLIC METHODS ## #################### constructor: (message, from_me, from_contact, is_file) -> ### ### @DATA_TYPES = images: ['jpg', 'jpeg', 'png', 'gif'] audios: ['mp3'] movies: ['mp4', 'webm'] @message = message @is_from_me = from_me @is_from_contact = from_contact if @is_from_me @message_classes = ['my-message', 'blue', 'lighten-3'] else if @is_from_contact @message_classes = ['partner-message', 'blue', 'darken-1'] if is_file @message_type = @getType() else @message_type = 'text' getType: () -> ### ### if @_isType('images', @message) 'image' else if @_isType('audios', @message) 'audio' else if @_isType('movies', @message) 'movie' else 'downloadable' link: () -> ### ### @message image: () -> ### ### @message audio: () -> ### ### $sce.trustAsResourceUrl(@message) movie: () -> ### ### $sce.trustAsResourceUrl(@message) text: () -> ### ### @message _isType: (type_name, data_string) -> ### ### for type in @DATA_TYPES[type_name] if data_string.toLowerCase().indexOf("." + type) > -1 return true return false class ChatContact ######################## ## PRIVATE PROPERTIES ## ######################## ####################### ## PUBLIC PROPERTIES ## ####################### #################### ## PUBLIC METHODS ## #################### constructor: (@username) -> ### ### @messages = [] @active = true ################################################################ # STATIC CONTROLLER CLASS ################################################################ class ChatController ######################## ## PRIVATE PROPERTIES ## ######################## ####################### ## PUBLIC PROPERTIES ## ####################### contacts: [] current_contact: null current_messages: [] current_typed_message: '' #################### ## PUBLIC METHODS ## #################### constructor: () -> ### ### @contacts = [] @current_messages = [] @is_file_chosen = false onContactChanged: (contact) -> ### ### if @current_contact is contact return @current_contact.messages.length = 0 @current_contact.messages.push(message) for message in @current_messages @current_contact.active = false @current_contact = contact @current_messages.length = 0 @current_messages.push(message) for message in contact.messages @current_contact.active = true onMessageSend: () => ### ### message = @current_typed_message @current_typed_message.length = 0 @current_typed_message = '' chat.sendMessageToUser(@current_contact.username, message) create_message_from_me(message) onUploadFile: () => ### ### $file_input = jQuery('#file-input-button') $file_input.change( () => console.log('file chosen') reader = new FileReader() reader.onload = () => url = reader.result console.log(url) chat.sendMessageToUser(@current_contact.username, url) files = $file_input[0].files reader.readAsDataURL(files[0]) ) $file_input.click() onMessageFromMe: (message) => ### ### @current_messages.push( new ChatMessage(message, true, false) ) $scope.$apply() onMessageFromContact: (message) => ### ### username = message.contact message_text = message.message if @current_contact.username == username @current_messages.push( new ChatMessage(message_text, false, true, false) ) else for contact in @contacts if contact.username == username contact.messages.push(new ChatMessage(message_text, false, true, false)) $scope.$apply() onFileFromContact: (message) => ### ### username = message.contact message_text = message.message if @current_contact.username == username @current_messages.push( new ChatMessage(message_text, false, true, true) ) else for contact in @contacts if contact.username == username contact.messages.push(new ChatMessage(message_text, false, true, true)) $scope.$apply() onContactAdded: (username) => ### ### for contact in @contacts if contact.username == username return else contact.active = false contact = new ChatContact(username) @contacts.push(contact) @current_contact = contact $scope.$apply() @$instance: () -> ### ### if not _class_instance_ChatController? # Create instance _class_instance_ChatController = new ChatController() return _class_instance_ChatController ##################### ## PRIVATE METHODS ## ##################### ####################### ## CREATE CONTROLLER ## ####################### controller = ChatController.$instance() ################################################################ # CONFIGURE CONTROLLER ################################################################ MessageQueue.$subscribe('add-contact', controller.onContactAdded) MessageQueue.$subscribe('new-message-from-me', controller.onMessageFromMe) MessageQueue.$subscribe('new-message-from-other', controller.onMessageFromContact) MessageQueue.$subscribe('new-file-from-other', controller.onFileFromContact) ################################################################ # CONTROLLER SCOPE ################################################################ ################ ## INIT SCOPE ## ################ ################# ## WATCH SCOPE ## ################# ################################################################ # RETURN CONTROLLER ################################################################ return controller ])
true
startUpWithWebChannel = () -> new QWebChannel(qt.webChannelTransport, (channel) -> mainFunction(channel.objects.chat) ) mainFunction = (chat) -> # Expose chat as global object window.chat = chat ############################ ## MESSAGES CALLBACKS ########################### onUserMessageReceived = (username, message) -> create_message_to_me( contact: username message: message ) onUserFileReceived = (username, message) -> create_file_message_to_me( contact: username message: message ) ############################# ## USER CALLBACKS ############################# onUserChosen = () -> username = jQuery('#other-username').val() chat.connectToUser(username) jQuery('#chatbox').show() onUserAdded = (username) -> _class_instance_MessageQueue.$publish('add-contact', username) jQuery('#chatbox').show() onContactsLoaded = (contactsString) -> contacts = contactsString.split('|') for contact in contacts onUserAdded(contact) onServerConnect = () -> console.log('Connected') jQuery('#submit-user-button').click( () -> console.log('on login button clicked') my_user_name = jQuery('#username').val() my_user_password = jQuery('#PI:PASSWORD:<PASSWORD>END_PI').val() chat.chooseUserName(my_user_name, my_user_password) jQuery('#userbox').hide() jQuery('#submit-other-user-button').click(onUserChosen) chat.connectionToUserEstablished.connect(onUserAdded) chat.contactsLoaded.connect(onContactsLoaded) chat.receivedUserMessage.connect(onUserMessageReceived) chat.receivedUserFile.connect(onUserFileReceived) chat.loadContacts() ) onServerError = (error) -> console.log(error) chat.connected.connect(onServerConnect) chat.error.connect(onServerError) chat.connectToServer(window.CHAT_SERVER_URL, 8888) console.log('connected to the server') jQuery('#chatbox').hide() onDocumentReady = () -> # Starting first to connect to web channel startUpWithWebChannel() jQuery(document).ready(onDocumentReady) create_message_from_me = (message) -> _class_instance_MessageQueue.$publish('new-message-from-me', message) create_message_to_me = (message) -> _class_instance_MessageQueue.$publish('new-message-from-other', message) create_file_message_to_me = (message) -> _class_instance_MessageQueue.$publish('new-file-from-other', message) chatApp = angular.module('chatApp', []) chatApp.config(['$compileProvider', ($compileProvider) -> $compileProvider.aHrefSanitizationWhitelist(/^\s*(stream):/) $compileProvider.imgSrcSanitizationWhitelist(/^\s*(stream):/) ]) _class_instance_MessageQueue = null chatApp.factory('MessageQueue', [() -> class MessageQueue ######################## ## PRIVATE PROPERTIES ## ######################## _channels: {} ####################### ## PUBLIC PROPERTIES ## ####################### #################### ## PUBLIC METHODS ## #################### constructor: () -> ### ### $subscribe: (channel, subscriber) -> ### ### if not @_channels.hasOwnProperty(channel) @_channels[channel] = [] @_channels[channel].push(subscriber) $publish: (channel, message) -> ### ### if @_channels.hasOwnProperty(channel) for subscriber in @_channels[channel] subscriber(message) @$instance: () -> ### ### if not _class_instance_MessageQueue? # Create instance _class_instance_MessageQueue = new MessageQueue() return _class_instance_MessageQueue ##################### ## PRIVATE METHODS ## ##################### # Return the factory MessageQueue.$instance() ]) log = (message) -> jQuery('#message-board').append("<span>#{message}</span>") getRandomHexString = () -> ### Generates random hex number string @return {String} ### return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) _class_instance_ChatController = null chatApp.controller('ChatController', ['$rootScope', '$scope', '$sce', 'MessageQueue', ($rootScope, $scope, $sce, MessageQueue) -> class ChatMessage ######################## ## PRIVATE PROPERTIES ## ######################## ####################### ## PUBLIC PROPERTIES ## ####################### #################### ## PUBLIC METHODS ## #################### constructor: (message, from_me, from_contact, is_file) -> ### ### @DATA_TYPES = images: ['jpg', 'jpeg', 'png', 'gif'] audios: ['mp3'] movies: ['mp4', 'webm'] @message = message @is_from_me = from_me @is_from_contact = from_contact if @is_from_me @message_classes = ['my-message', 'blue', 'lighten-3'] else if @is_from_contact @message_classes = ['partner-message', 'blue', 'darken-1'] if is_file @message_type = @getType() else @message_type = 'text' getType: () -> ### ### if @_isType('images', @message) 'image' else if @_isType('audios', @message) 'audio' else if @_isType('movies', @message) 'movie' else 'downloadable' link: () -> ### ### @message image: () -> ### ### @message audio: () -> ### ### $sce.trustAsResourceUrl(@message) movie: () -> ### ### $sce.trustAsResourceUrl(@message) text: () -> ### ### @message _isType: (type_name, data_string) -> ### ### for type in @DATA_TYPES[type_name] if data_string.toLowerCase().indexOf("." + type) > -1 return true return false class ChatContact ######################## ## PRIVATE PROPERTIES ## ######################## ####################### ## PUBLIC PROPERTIES ## ####################### #################### ## PUBLIC METHODS ## #################### constructor: (@username) -> ### ### @messages = [] @active = true ################################################################ # STATIC CONTROLLER CLASS ################################################################ class ChatController ######################## ## PRIVATE PROPERTIES ## ######################## ####################### ## PUBLIC PROPERTIES ## ####################### contacts: [] current_contact: null current_messages: [] current_typed_message: '' #################### ## PUBLIC METHODS ## #################### constructor: () -> ### ### @contacts = [] @current_messages = [] @is_file_chosen = false onContactChanged: (contact) -> ### ### if @current_contact is contact return @current_contact.messages.length = 0 @current_contact.messages.push(message) for message in @current_messages @current_contact.active = false @current_contact = contact @current_messages.length = 0 @current_messages.push(message) for message in contact.messages @current_contact.active = true onMessageSend: () => ### ### message = @current_typed_message @current_typed_message.length = 0 @current_typed_message = '' chat.sendMessageToUser(@current_contact.username, message) create_message_from_me(message) onUploadFile: () => ### ### $file_input = jQuery('#file-input-button') $file_input.change( () => console.log('file chosen') reader = new FileReader() reader.onload = () => url = reader.result console.log(url) chat.sendMessageToUser(@current_contact.username, url) files = $file_input[0].files reader.readAsDataURL(files[0]) ) $file_input.click() onMessageFromMe: (message) => ### ### @current_messages.push( new ChatMessage(message, true, false) ) $scope.$apply() onMessageFromContact: (message) => ### ### username = message.contact message_text = message.message if @current_contact.username == username @current_messages.push( new ChatMessage(message_text, false, true, false) ) else for contact in @contacts if contact.username == username contact.messages.push(new ChatMessage(message_text, false, true, false)) $scope.$apply() onFileFromContact: (message) => ### ### username = message.contact message_text = message.message if @current_contact.username == username @current_messages.push( new ChatMessage(message_text, false, true, true) ) else for contact in @contacts if contact.username == username contact.messages.push(new ChatMessage(message_text, false, true, true)) $scope.$apply() onContactAdded: (username) => ### ### for contact in @contacts if contact.username == username return else contact.active = false contact = new ChatContact(username) @contacts.push(contact) @current_contact = contact $scope.$apply() @$instance: () -> ### ### if not _class_instance_ChatController? # Create instance _class_instance_ChatController = new ChatController() return _class_instance_ChatController ##################### ## PRIVATE METHODS ## ##################### ####################### ## CREATE CONTROLLER ## ####################### controller = ChatController.$instance() ################################################################ # CONFIGURE CONTROLLER ################################################################ MessageQueue.$subscribe('add-contact', controller.onContactAdded) MessageQueue.$subscribe('new-message-from-me', controller.onMessageFromMe) MessageQueue.$subscribe('new-message-from-other', controller.onMessageFromContact) MessageQueue.$subscribe('new-file-from-other', controller.onFileFromContact) ################################################################ # CONTROLLER SCOPE ################################################################ ################ ## INIT SCOPE ## ################ ################# ## WATCH SCOPE ## ################# ################################################################ # RETURN CONTROLLER ################################################################ return controller ])
[ { "context": "der : 'Enter your name...'\n valeu : 'Fatih Acet'\n\n labeledInput = new spark.components.Labe", "end": 361, "score": 0.9996592998504639, "start": 351, "tag": "NAME", "value": "Fatih Acet" } ]
src/tests/components/inputs/test_labeledInput.coffee
dashersw/spark
1
goog = goog or goog = require: -> goog.require 'spark.components.LabeledInput' describe 'spark.components.LabeledInput', -> labeledInput = null element = null beforeEach -> options = labelOptions : label : 'Name' inputOptions : placeholder : 'Enter your name...' valeu : 'Fatih Acet' labeledInput = new spark.components.LabeledInput options element = labeledInput.getElement() it 'should extend spark.core.View', -> expect(labeledInput instanceof spark.core.View).toBeTruthy() it 'should have default options', -> li = new spark.components.LabeledInput null, null expect(li.getOptions().cssClass).toBeDefined() it 'should have label and input elements', -> expect(element.firstChild.tagName).toBe 'LABEL' expect(element.lastChild.tagName).toBe 'INPUT' it 'should have focus class', -> labeledInput.getInput().emit 'focus' expect(labeledInput.getInput().hasClass('focus')).toBeTruthy() labeledInput.getInput().emit 'blur' expect(labeledInput.getInput().hasClass('focus')).toBeFalsy() it 'should have for and id attributes the same', -> labelFor = labeledInput.getLabel().getAttribute 'for' inputId = labeledInput.getInput().getAttribute 'id' expect(labelFor).toBe inputId it 'should create input first if inputFirst passed as true', -> expect(element.firstChild.tagName).toBe 'LABEL' expect(element.lastChild.tagName).toBe 'INPUT' labeledInput = new spark.components.LabeledInput inputFirst: yes element = labeledInput.getElement() expect(element.firstChild.tagName).toBe 'INPUT' expect(element.lastChild.tagName).toBe 'LABEL' it 'should return input name and value', -> li = new spark.components.LabeledInput inputOptions: name : 'hello' value : 'world' labelOptions: label : 'hello world' expect(li.getName()).toBe 'hello' expect(li.getValue()).toBe 'world'
32023
goog = goog or goog = require: -> goog.require 'spark.components.LabeledInput' describe 'spark.components.LabeledInput', -> labeledInput = null element = null beforeEach -> options = labelOptions : label : 'Name' inputOptions : placeholder : 'Enter your name...' valeu : '<NAME>' labeledInput = new spark.components.LabeledInput options element = labeledInput.getElement() it 'should extend spark.core.View', -> expect(labeledInput instanceof spark.core.View).toBeTruthy() it 'should have default options', -> li = new spark.components.LabeledInput null, null expect(li.getOptions().cssClass).toBeDefined() it 'should have label and input elements', -> expect(element.firstChild.tagName).toBe 'LABEL' expect(element.lastChild.tagName).toBe 'INPUT' it 'should have focus class', -> labeledInput.getInput().emit 'focus' expect(labeledInput.getInput().hasClass('focus')).toBeTruthy() labeledInput.getInput().emit 'blur' expect(labeledInput.getInput().hasClass('focus')).toBeFalsy() it 'should have for and id attributes the same', -> labelFor = labeledInput.getLabel().getAttribute 'for' inputId = labeledInput.getInput().getAttribute 'id' expect(labelFor).toBe inputId it 'should create input first if inputFirst passed as true', -> expect(element.firstChild.tagName).toBe 'LABEL' expect(element.lastChild.tagName).toBe 'INPUT' labeledInput = new spark.components.LabeledInput inputFirst: yes element = labeledInput.getElement() expect(element.firstChild.tagName).toBe 'INPUT' expect(element.lastChild.tagName).toBe 'LABEL' it 'should return input name and value', -> li = new spark.components.LabeledInput inputOptions: name : 'hello' value : 'world' labelOptions: label : 'hello world' expect(li.getName()).toBe 'hello' expect(li.getValue()).toBe 'world'
true
goog = goog or goog = require: -> goog.require 'spark.components.LabeledInput' describe 'spark.components.LabeledInput', -> labeledInput = null element = null beforeEach -> options = labelOptions : label : 'Name' inputOptions : placeholder : 'Enter your name...' valeu : 'PI:NAME:<NAME>END_PI' labeledInput = new spark.components.LabeledInput options element = labeledInput.getElement() it 'should extend spark.core.View', -> expect(labeledInput instanceof spark.core.View).toBeTruthy() it 'should have default options', -> li = new spark.components.LabeledInput null, null expect(li.getOptions().cssClass).toBeDefined() it 'should have label and input elements', -> expect(element.firstChild.tagName).toBe 'LABEL' expect(element.lastChild.tagName).toBe 'INPUT' it 'should have focus class', -> labeledInput.getInput().emit 'focus' expect(labeledInput.getInput().hasClass('focus')).toBeTruthy() labeledInput.getInput().emit 'blur' expect(labeledInput.getInput().hasClass('focus')).toBeFalsy() it 'should have for and id attributes the same', -> labelFor = labeledInput.getLabel().getAttribute 'for' inputId = labeledInput.getInput().getAttribute 'id' expect(labelFor).toBe inputId it 'should create input first if inputFirst passed as true', -> expect(element.firstChild.tagName).toBe 'LABEL' expect(element.lastChild.tagName).toBe 'INPUT' labeledInput = new spark.components.LabeledInput inputFirst: yes element = labeledInput.getElement() expect(element.firstChild.tagName).toBe 'INPUT' expect(element.lastChild.tagName).toBe 'LABEL' it 'should return input name and value', -> li = new spark.components.LabeledInput inputOptions: name : 'hello' value : 'world' labelOptions: label : 'hello world' expect(li.getName()).toBe 'hello' expect(li.getValue()).toBe 'world'
[ { "context": " Return random gif from gifbin.com\n#\n# Author:\n# EnriqueVidal\n\ngifs = [\n \"http://i1.kym-cdn.com/photos/images/", "end": 215, "score": 0.9992547035217285, "start": 203, "tag": "NAME", "value": "EnriqueVidal" } ]
src/scripts/gangnam.coffee
Reelhouse/hubot-scripts
1,450
# Description: # Produces a random gangnam style gif # # Dependencies: # None # Configuration: # None # # Commands: # hubot oppa gangnam style - Return random gif from gifbin.com # # Author: # EnriqueVidal gifs = [ "http://i1.kym-cdn.com/photos/images/original/000/370/936/cb3.gif", "http://i3.kym-cdn.com/photos/images/original/000/363/835/32a.gif", "http://i3.kym-cdn.com/photos/images/original/000/388/760/3f3.gif", "http://i2.kym-cdn.com/photos/images/original/000/386/610/52d.gif", "https://a248.e.akamai.net/camo.github.com/fd39c2be2c139705edba5c52738a7c111be9ad37/687474703a2f2f7777772e726566696e65646775792e636f6d2f77702d636f6e74656e742f75706c6f6164732f323031322f31302f67616e676e616d2d7374796c652d737461722d776172732d6769662e676966", "https://a248.e.akamai.net/camo.github.com/0a7ede4e91eabd1d5e0a86901efb984136765410/687474703a2f2f696d67342e6a6f7972656163746f722e636f6d2f706963732f706f73742f6769662d737461722d776172732d67616e676e616d2d7374796c652d68616e2d736f6c6f2d3337303636342e676966", "https://a248.e.akamai.net/camo.github.com/d82d76a32a0d667c8f2f6d7bf0d9e0b1abe75399/687474703a2f2f7261636b2e302e6d736863646e2e636f6d2f6d656469612f5a676b794d4445794c7a45774c7a45344c7a4577587a4d31587a4134587a51794d6c396d6157786c2f6130376264663034" ] module.exports = (robot)-> robot.hear /gangnam style/i, (message)-> #changed gifbin message.send message.random gifs
222383
# Description: # Produces a random gangnam style gif # # Dependencies: # None # Configuration: # None # # Commands: # hubot oppa gangnam style - Return random gif from gifbin.com # # Author: # <NAME> gifs = [ "http://i1.kym-cdn.com/photos/images/original/000/370/936/cb3.gif", "http://i3.kym-cdn.com/photos/images/original/000/363/835/32a.gif", "http://i3.kym-cdn.com/photos/images/original/000/388/760/3f3.gif", "http://i2.kym-cdn.com/photos/images/original/000/386/610/52d.gif", "https://a248.e.akamai.net/camo.github.com/fd39c2be2c139705edba5c52738a7c111be9ad37/687474703a2f2f7777772e726566696e65646775792e636f6d2f77702d636f6e74656e742f75706c6f6164732f323031322f31302f67616e676e616d2d7374796c652d737461722d776172732d6769662e676966", "https://a248.e.akamai.net/camo.github.com/0a7ede4e91eabd1d5e0a86901efb984136765410/687474703a2f2f696d67342e6a6f7972656163746f722e636f6d2f706963732f706f73742f6769662d737461722d776172732d67616e676e616d2d7374796c652d68616e2d736f6c6f2d3337303636342e676966", "https://a248.e.akamai.net/camo.github.com/d82d76a32a0d667c8f2f6d7bf0d9e0b1abe75399/687474703a2f2f7261636b2e302e6d736863646e2e636f6d2f6d656469612f5a676b794d4445794c7a45774c7a45344c7a4577587a4d31587a4134587a51794d6c396d6157786c2f6130376264663034" ] module.exports = (robot)-> robot.hear /gangnam style/i, (message)-> #changed gifbin message.send message.random gifs
true
# Description: # Produces a random gangnam style gif # # Dependencies: # None # Configuration: # None # # Commands: # hubot oppa gangnam style - Return random gif from gifbin.com # # Author: # PI:NAME:<NAME>END_PI gifs = [ "http://i1.kym-cdn.com/photos/images/original/000/370/936/cb3.gif", "http://i3.kym-cdn.com/photos/images/original/000/363/835/32a.gif", "http://i3.kym-cdn.com/photos/images/original/000/388/760/3f3.gif", "http://i2.kym-cdn.com/photos/images/original/000/386/610/52d.gif", "https://a248.e.akamai.net/camo.github.com/fd39c2be2c139705edba5c52738a7c111be9ad37/687474703a2f2f7777772e726566696e65646775792e636f6d2f77702d636f6e74656e742f75706c6f6164732f323031322f31302f67616e676e616d2d7374796c652d737461722d776172732d6769662e676966", "https://a248.e.akamai.net/camo.github.com/0a7ede4e91eabd1d5e0a86901efb984136765410/687474703a2f2f696d67342e6a6f7972656163746f722e636f6d2f706963732f706f73742f6769662d737461722d776172732d67616e676e616d2d7374796c652d68616e2d736f6c6f2d3337303636342e676966", "https://a248.e.akamai.net/camo.github.com/d82d76a32a0d667c8f2f6d7bf0d9e0b1abe75399/687474703a2f2f7261636b2e302e6d736863646e2e636f6d2f6d656469612f5a676b794d4445794c7a45774c7a45344c7a4577587a4d31587a4134587a51794d6c396d6157786c2f6130376264663034" ] module.exports = (robot)-> robot.hear /gangnam style/i, (message)-> #changed gifbin message.send message.random gifs
[ { "context": " key = key.replace('khaus', '').toLowerCase()\n if typeof windo", "end": 12864, "score": 0.7390190958976746, "start": 12849, "tag": "KEY", "value": "'').toLowerCase" } ]
src/coffee/khausjs.coffee
Niucode/khausjs
0
do ($=jQuery) -> ### LIMPIA LOS ERRORES DEL FORMULARIO BOOTSTRAP # ========================================================================== # @param DOMElement form - formulario # ========================================================================== ### $.khausCleanFormErrors = (form) -> $(form).find(".form-group").removeClass "has-error has-feedback" $(form).find("span.form-control-feedback").remove() $(form).find("span.help-block").remove() $(form).find("span.form-control-feedback").remove() $(form).find(":input").tooltip "destroy" ### DESPLIEGA LOS ERRORES DE FORMULARIO # ========================================================================== # @param string type (block|tooltip) forma de mostrar errores # @param DOMElement form - formulario que realizo el envio # @param object errors - errores {'inputName':'Error Message'} # # En caso de que no se envie el parametro errors, buscara esos datos # dentro de la variable global khaus # ========================================================================== ### $.khausDisplayFormErrors = (settings)-> o = $.extend errorsType : 'block' form : null errors : window.khaus.errors resetForm : false , settings counter = 0 $.each o.errors, (key, value)-> if key.match /^khaus/ key = key.replace('khaus', '').toLowerCase() if typeof window.khaus[key] isnt 'undefined' window.khaus[key] = value return true if arr = key.match /\.([^.]+)/ key = key.replace(arr[0], "[#{arr[1]}]") counter++ input = $(o.form).find(":input[name='#{key}']") # if input.length isnt 1 # si no lo encuentra busca inputs array[] # input = $(o.form).find(":input[name^='#{key}[']") input.parents('.form-group').addClass "has-error" input.parents('.form-group').addClass "has-feedback" # si el input se encuentra dentro del un formulario tabulado inTab = input.parents('.tab-content') if inTab.length > 0 if counter is 1 $('ul.nav-tabs .badge').remove() page = input.parents('.tab-pane') pageName = page.attr 'id' #if not page.hasClass 'active' tab = $("ul.nav-tabs a[href=##{pageName}]") badge = tab.find '.badge' if badge.length is 0 badge = $('<span>', 'class':'badge').text 0 badge.appendTo tab badge.text parseInt(badge.text()) + 1 switch o.errorsType when 'block' pos = input.parents '.form-group' $("<span>", "class":"help-block").html(value).appendTo pos $("<span>", "class":"glyphicon glyphicon-remove form-control-feedback").appendTo pos when 'tooltip' input.tooltip( placement : "top" title : value container : "body" ) $.khausLaunchAlerts() if counter is 0 if o.resetForm $(o.form)[0].reset() ### MUESTRA LOS ERRORES ALMACENADOS EN LAS VARIABLES KHAUS # ========================================================================== # # ========================================================================== ### $.khausLaunchFormErrors = ()-> if !!window.khaus.errors and !!window.khaus.form form = $("form[name=#{window.khaus.form}]") $.khausDisplayFormErrors( errorsType: 'block' form: form ) ### # ========================================================================== # # ========================================================================== ### $.khausLaunchAlerts = (settings) -> o = $.extend title : default : "" primary : "" success : "El proceso ha finalizado" danger : "Ha ocurrido un error" warning : "Importante" info : "Informaci&oacute;n" , settings $.each o.title, (key, value)-> if !!window.khaus[key] template = key if key is 'default' template = 'alert' if key is 'danger' template = 'error' if key is 'info' template = 'info' if $.isPlainObject(window.khaus[key]) or $.isArray(window.khaus[key]) $.each window.khaus[key], (k, mensaje)-> new Noty( text: mensaje type: template ).show() else new Noty( text: window.khaus[key] type: template ).show() window.khaus[key] = '' ### # ========================================================================== # # ========================================================================== ### $.khausAjaxWait = (settings)-> o = $.extend type : 'cursor' , settings switch o.type when 'cursor' $.ajaxSetup beforeSend : ()-> $('body').addClass 'khaus-ajax-wait' complete : ()-> $('body').removeClass 'khaus-ajax-wait' success : ()-> $('body').removeClass 'khaus-ajax-wait' ### ADJUNTA AL FORMULARIO EL PARAMETRO NAME # ========================================================================== # Si el formulario tiene el atributo [name] activado # antes de realizar el envio de los parametros # agrega un input hidden name="_name" value="<nombre del formulario>" # ========================================================================== ### $.fn.khausAttachName = ()-> $.each @, ()-> $(@).on 'submit', (ev)-> if $(@).is('[name]') and $(@).find('input[name=_name]').length is 0 $('<input>', 'name':'_name' 'type':'hidden' 'value':$(@).attr('name') ).prependTo($(@)) ### CAPTURA EL EVENTO SUBMIT Y ENVIA UN MODAL KHAUS CONFIRM # ========================================================================== # @param object settings { # title : (string) - titulo de la ventana modal # message : (string) - mensaje de la ventana modal # } # Al presionar el boton aceptar del modal se realizara el submit del formulario # de lo contrario no se realizara ninguna accion # ========================================================================== ### $.fn.khausConfirmBeforeSubmit = -> $.each @, -> title = $(@).data 'khaus-title' || '' message = $(@).data 'khaus-confirm' || '' $(@).on 'submit', (ev)-> $(':focus').blur() ev.preventDefault() e = $(@) $.khausConfirm title, message, -> e.off 'submit' e.submit() ### # ========================================================================== # Envia un modal de alerta con las opciones aceptar y cancelar # Metodos de llamada: # - por codigo: $.khausAlert('Titulo', 'Mensaje'); # - por dom: <button data-khaus-alert="Mensaje" data-khaus-title="Opcional"> # El titulo es opcional en la llamada por dom # ========================================================================== ### $.khausAlert = (title, message) -> if $(".khaus-modal-alert").length > 0 $(".khaus-modal-alert").remove() modal_D1 = $("<div>", "class":"modal fade khaus-modal-alert") modal_D2 = $("<div>", "class":"modal-dialog").appendTo modal_D1 modal_D3 = $("<div>", "class":"modal-content").appendTo modal_D2 modal_header = $("<div>", "class":"modal-header").appendTo modal_D3 $("<h4>", "class":"modal-title").html(title).appendTo modal_header modal_body = $("<div>", "class":"modal-body").html(message).appendTo modal_D3 modal_footer = $("<div>", "class":"modal-footer").appendTo modal_D3 $("<button>", "type":"button", "class":"btn btn-primary", "data-dismiss":"modal").html("Aceptar").appendTo modal_footer modal_D1.modal "show" $.fn.khausAlert = -> @each -> $(@).on 'click', (ev)-> message = $(@).data 'khaus-alert' title = $(@).data 'khaus-title' || '' $.khausAlert(title, message) ### # ========================================================================== # # ========================================================================== ### $.khausPrompt = (title, message, defaultValue = "", callback = ->) -> if $(".khaus-modal-prompt").length > 0 $(".khaus-modal-prompt").remove() modal_D1 = $("<div>", "class":"modal fade khaus-modal-prompt") modal_D2 = $("<div>", "class":"modal-dialog").appendTo modal_D1 modal_D3 = $("<div>", "class":"modal-content").appendTo modal_D2 modal_header = $("<div>", "class":"modal-header").appendTo modal_D3 $("<h4>", "class":"modal-title").html(title).appendTo modal_header modal_body = $("<div>", "class":"modal-body").appendTo modal_D3 $("<h5>").css("font-weight":"bold").html(message).appendTo modal_body input_prompt = $("<input>", "type":"text", "class":"form-control").val(defaultValue).appendTo modal_body modal_footer = $("<div>", "class":"modal-footer").appendTo modal_D3 $("<button>", "type":"button", "class":"btn btn-default", "data-dismiss":"modal").html("Cancelar").appendTo modal_footer $("<button>", "type":"button", "class":"btn btn-primary", "data-dismiss":"modal") .html("Aceptar") .on "click", -> callback input_prompt.val() return .appendTo modal_footer modal_D1.modal "show" setTimeout -> input_prompt.select() , 200 ### # ========================================================================== # # ========================================================================== ### $.khausConfirm = (title, message, callback = ->) -> if $(".khaus-modal-confirm").length > 0 $(".khaus-modal-confirm").remove() modal_D1 = $("<div>", "class":"modal fade khaus-modal-confirm") modal_D2 = $("<div>", "class":"modal-dialog").appendTo modal_D1 modal_D3 = $("<div>", "class":"modal-content").appendTo modal_D2 modal_header = $("<div>", "class":"modal-header").appendTo modal_D3 $("<h4>", "class":"modal-title").html(title).appendTo modal_header modal_body = $("<div>", "class":"modal-body").html(message).appendTo modal_D3 modal_footer = $("<div>", "class":"modal-footer").appendTo modal_D3 $("<button>", "type":"button", "class":"btn btn-default", "data-dismiss":"modal").html("Cancelar").appendTo modal_footer btnAceptar = $("<button>", "type":"button", "class":"btn btn-primary", "data-dismiss":"modal") .html("Aceptar") .on "click", -> callback() return .appendTo modal_footer setTimeout(-> btnAceptar.focus() , 300) modal_D1.modal "show" ### CAMBIA EL FUNCIONAMIENTO DE LOS FORMULARIOS POR PETICIONES AJAX # ========================================================================== # # ========================================================================== ### $.fn.khausForm = (settings)-> o = $.extend( onSubmit: -> onSuccess: -> onError: -> , settings) $.each @, ()-> form = $(@) form.on 'submit', (ev)-> o.onSubmit(form, ev); form.ajaxForm delegation: true success: (response, status, xhr, $form)-> $.each response, (key, value)-> if key.match /^khaus/ key = key.replace('khaus', '').toLowerCase() if typeof window.khaus[key] isnt 'undefined' window.khaus[key] = value $.khausLaunchAlerts() if window.khaus.redirect isnt null if form.data('khaus-reset') || false $($form)[0].reset() if $.isArray(window.khaus.redirect) setTimeout(-> location = window.khaus.redirect[0] if not location.match(/^https?:\/\//i) location = window.baseURL + location; window.location = location , window.khaus.redirect[1]) else if $.isPlainObject(window.khaus.redirect) $.each window.khaus.redirect, (url, tiempo)-> setTimeout(-> location = url if not location.match(/^https?:\/\//i) location = window.baseURL + location; window.location = location , tiempo) else location = window.khaus.redirect if not location.match(/^https?:\/\//i) location = window.baseURL + location; window.location = location o.onSuccess($form, ev, response) error: (response, status, xhr, $form)-> $.khausCleanFormErrors($form) if typeof response.responseJSON isnt 'undefined' m = response.responseJSON else m = $.parseJSON(response.responseText) if m.message new Noty(text: m.message, type: 'error').show() $.khausDisplayFormErrors( errorsType: form.data('khaus-errortype') || 'block' form: $form errors: m.errors resetForm: form.data('khaus-reset') || false ) o.onError($form, ev, response) ### # ========================================================================== # # ========================================================================== ### $.fn.khausNumberFormat = ()-> replace = (number)-> number = number.replace /[^0-9]+/g, '' number = number.replace /\B(?=(\d{3})+(?!\d))/g, '.' @each ()-> if $(this).is(':input') number = replace $(this).val() $(this).val(number) else number = replace $(this).html() $(this).html(number) ### # ========================================================================== # # ========================================================================== ### $.khausLoadSelect = ($select, url, fk, selected)-> $select.attr 'disabled', true $select.text '' $.get "#{window.baseURL}#{url}/#{fk}.json", (r)-> $.each r, -> $('<option>', value:@id).text(@nombre).appendTo $select $select.removeAttr 'disabled' if $select.find("option[value=#{selected}]").length > 0 $select.val selected else $select.val($select.find('option:first').attr('value')) $.fn.khausLoadSelect = (settings)-> o = $.extend url : $(@).data 'khaus-url' select : $(@).data 'khaus-select' selected : $(@).data 'khaus-selected' or 1 , settings @each -> $select = $(o.select) if @value $.khausLoadSelect $select, o.url, @value, o.selected else $select.text '' $select.attr 'disabled', true $(@).on 'change', -> $.khausLoadSelect $select, o.url, @value, o.selected ### # ========================================================================== # # ========================================================================== ### $.fn.khausClone = -> @each -> $(@).on 'click', (ev)-> ev.preventDefault() selector = $(@).data 'khaus-clone' target = $(selector).last() clon = target.clone() clon.find(':input[name]').each -> name = $(@).attr('name') key = name.match(/\[(\d+)\]/) if !!key key = parseInt key[1] newName = name.replace "[#{key}]", "[#{key+1}]" $(@).attr 'name', newName clon.find('input').val '' clon.find('select option:first').attr 'selected', true clon.find(':button[data-khaus-removeparent]').khausRemoveParent() clon.insertAfter target ### # ========================================================================== # # ========================================================================== ### $.fn.khausRemoveParent = -> @each -> $(@).on 'click', (ev)-> ev.preventDefault() selector = $(@).data 'khaus-removeparent' target = $(this).parents(selector) target.remove() $ -> # noty defaults options Noty.overrideDefaults({ layout : 'bottomRight', theme : 'metroui', timeout : 8000, closeWith: ['click', 'button'], animation: { open : 'animated bounceInRight', close: 'animated bounceOutRight' } }); $('form').khausAttachName() $.khausLaunchFormErrors() $.khausLaunchAlerts() $('form.khaus-form').khausForm() $('form[data-khaus-confirm]').khausConfirmBeforeSubmit() $(':button[data-khaus-clone]').khausClone() $(':button[data-khaus-removeparent]').khausRemoveParent() $(':button[data-khaus-alert]').khausAlert() $('.khaus-numero').khausNumberFormat() $('select[data-khaus-select]').khausLoadSelect();
130652
do ($=jQuery) -> ### LIMPIA LOS ERRORES DEL FORMULARIO BOOTSTRAP # ========================================================================== # @param DOMElement form - formulario # ========================================================================== ### $.khausCleanFormErrors = (form) -> $(form).find(".form-group").removeClass "has-error has-feedback" $(form).find("span.form-control-feedback").remove() $(form).find("span.help-block").remove() $(form).find("span.form-control-feedback").remove() $(form).find(":input").tooltip "destroy" ### DESPLIEGA LOS ERRORES DE FORMULARIO # ========================================================================== # @param string type (block|tooltip) forma de mostrar errores # @param DOMElement form - formulario que realizo el envio # @param object errors - errores {'inputName':'Error Message'} # # En caso de que no se envie el parametro errors, buscara esos datos # dentro de la variable global khaus # ========================================================================== ### $.khausDisplayFormErrors = (settings)-> o = $.extend errorsType : 'block' form : null errors : window.khaus.errors resetForm : false , settings counter = 0 $.each o.errors, (key, value)-> if key.match /^khaus/ key = key.replace('khaus', '').toLowerCase() if typeof window.khaus[key] isnt 'undefined' window.khaus[key] = value return true if arr = key.match /\.([^.]+)/ key = key.replace(arr[0], "[#{arr[1]}]") counter++ input = $(o.form).find(":input[name='#{key}']") # if input.length isnt 1 # si no lo encuentra busca inputs array[] # input = $(o.form).find(":input[name^='#{key}[']") input.parents('.form-group').addClass "has-error" input.parents('.form-group').addClass "has-feedback" # si el input se encuentra dentro del un formulario tabulado inTab = input.parents('.tab-content') if inTab.length > 0 if counter is 1 $('ul.nav-tabs .badge').remove() page = input.parents('.tab-pane') pageName = page.attr 'id' #if not page.hasClass 'active' tab = $("ul.nav-tabs a[href=##{pageName}]") badge = tab.find '.badge' if badge.length is 0 badge = $('<span>', 'class':'badge').text 0 badge.appendTo tab badge.text parseInt(badge.text()) + 1 switch o.errorsType when 'block' pos = input.parents '.form-group' $("<span>", "class":"help-block").html(value).appendTo pos $("<span>", "class":"glyphicon glyphicon-remove form-control-feedback").appendTo pos when 'tooltip' input.tooltip( placement : "top" title : value container : "body" ) $.khausLaunchAlerts() if counter is 0 if o.resetForm $(o.form)[0].reset() ### MUESTRA LOS ERRORES ALMACENADOS EN LAS VARIABLES KHAUS # ========================================================================== # # ========================================================================== ### $.khausLaunchFormErrors = ()-> if !!window.khaus.errors and !!window.khaus.form form = $("form[name=#{window.khaus.form}]") $.khausDisplayFormErrors( errorsType: 'block' form: form ) ### # ========================================================================== # # ========================================================================== ### $.khausLaunchAlerts = (settings) -> o = $.extend title : default : "" primary : "" success : "El proceso ha finalizado" danger : "Ha ocurrido un error" warning : "Importante" info : "Informaci&oacute;n" , settings $.each o.title, (key, value)-> if !!window.khaus[key] template = key if key is 'default' template = 'alert' if key is 'danger' template = 'error' if key is 'info' template = 'info' if $.isPlainObject(window.khaus[key]) or $.isArray(window.khaus[key]) $.each window.khaus[key], (k, mensaje)-> new Noty( text: mensaje type: template ).show() else new Noty( text: window.khaus[key] type: template ).show() window.khaus[key] = '' ### # ========================================================================== # # ========================================================================== ### $.khausAjaxWait = (settings)-> o = $.extend type : 'cursor' , settings switch o.type when 'cursor' $.ajaxSetup beforeSend : ()-> $('body').addClass 'khaus-ajax-wait' complete : ()-> $('body').removeClass 'khaus-ajax-wait' success : ()-> $('body').removeClass 'khaus-ajax-wait' ### ADJUNTA AL FORMULARIO EL PARAMETRO NAME # ========================================================================== # Si el formulario tiene el atributo [name] activado # antes de realizar el envio de los parametros # agrega un input hidden name="_name" value="<nombre del formulario>" # ========================================================================== ### $.fn.khausAttachName = ()-> $.each @, ()-> $(@).on 'submit', (ev)-> if $(@).is('[name]') and $(@).find('input[name=_name]').length is 0 $('<input>', 'name':'_name' 'type':'hidden' 'value':$(@).attr('name') ).prependTo($(@)) ### CAPTURA EL EVENTO SUBMIT Y ENVIA UN MODAL KHAUS CONFIRM # ========================================================================== # @param object settings { # title : (string) - titulo de la ventana modal # message : (string) - mensaje de la ventana modal # } # Al presionar el boton aceptar del modal se realizara el submit del formulario # de lo contrario no se realizara ninguna accion # ========================================================================== ### $.fn.khausConfirmBeforeSubmit = -> $.each @, -> title = $(@).data 'khaus-title' || '' message = $(@).data 'khaus-confirm' || '' $(@).on 'submit', (ev)-> $(':focus').blur() ev.preventDefault() e = $(@) $.khausConfirm title, message, -> e.off 'submit' e.submit() ### # ========================================================================== # Envia un modal de alerta con las opciones aceptar y cancelar # Metodos de llamada: # - por codigo: $.khausAlert('Titulo', 'Mensaje'); # - por dom: <button data-khaus-alert="Mensaje" data-khaus-title="Opcional"> # El titulo es opcional en la llamada por dom # ========================================================================== ### $.khausAlert = (title, message) -> if $(".khaus-modal-alert").length > 0 $(".khaus-modal-alert").remove() modal_D1 = $("<div>", "class":"modal fade khaus-modal-alert") modal_D2 = $("<div>", "class":"modal-dialog").appendTo modal_D1 modal_D3 = $("<div>", "class":"modal-content").appendTo modal_D2 modal_header = $("<div>", "class":"modal-header").appendTo modal_D3 $("<h4>", "class":"modal-title").html(title).appendTo modal_header modal_body = $("<div>", "class":"modal-body").html(message).appendTo modal_D3 modal_footer = $("<div>", "class":"modal-footer").appendTo modal_D3 $("<button>", "type":"button", "class":"btn btn-primary", "data-dismiss":"modal").html("Aceptar").appendTo modal_footer modal_D1.modal "show" $.fn.khausAlert = -> @each -> $(@).on 'click', (ev)-> message = $(@).data 'khaus-alert' title = $(@).data 'khaus-title' || '' $.khausAlert(title, message) ### # ========================================================================== # # ========================================================================== ### $.khausPrompt = (title, message, defaultValue = "", callback = ->) -> if $(".khaus-modal-prompt").length > 0 $(".khaus-modal-prompt").remove() modal_D1 = $("<div>", "class":"modal fade khaus-modal-prompt") modal_D2 = $("<div>", "class":"modal-dialog").appendTo modal_D1 modal_D3 = $("<div>", "class":"modal-content").appendTo modal_D2 modal_header = $("<div>", "class":"modal-header").appendTo modal_D3 $("<h4>", "class":"modal-title").html(title).appendTo modal_header modal_body = $("<div>", "class":"modal-body").appendTo modal_D3 $("<h5>").css("font-weight":"bold").html(message).appendTo modal_body input_prompt = $("<input>", "type":"text", "class":"form-control").val(defaultValue).appendTo modal_body modal_footer = $("<div>", "class":"modal-footer").appendTo modal_D3 $("<button>", "type":"button", "class":"btn btn-default", "data-dismiss":"modal").html("Cancelar").appendTo modal_footer $("<button>", "type":"button", "class":"btn btn-primary", "data-dismiss":"modal") .html("Aceptar") .on "click", -> callback input_prompt.val() return .appendTo modal_footer modal_D1.modal "show" setTimeout -> input_prompt.select() , 200 ### # ========================================================================== # # ========================================================================== ### $.khausConfirm = (title, message, callback = ->) -> if $(".khaus-modal-confirm").length > 0 $(".khaus-modal-confirm").remove() modal_D1 = $("<div>", "class":"modal fade khaus-modal-confirm") modal_D2 = $("<div>", "class":"modal-dialog").appendTo modal_D1 modal_D3 = $("<div>", "class":"modal-content").appendTo modal_D2 modal_header = $("<div>", "class":"modal-header").appendTo modal_D3 $("<h4>", "class":"modal-title").html(title).appendTo modal_header modal_body = $("<div>", "class":"modal-body").html(message).appendTo modal_D3 modal_footer = $("<div>", "class":"modal-footer").appendTo modal_D3 $("<button>", "type":"button", "class":"btn btn-default", "data-dismiss":"modal").html("Cancelar").appendTo modal_footer btnAceptar = $("<button>", "type":"button", "class":"btn btn-primary", "data-dismiss":"modal") .html("Aceptar") .on "click", -> callback() return .appendTo modal_footer setTimeout(-> btnAceptar.focus() , 300) modal_D1.modal "show" ### CAMBIA EL FUNCIONAMIENTO DE LOS FORMULARIOS POR PETICIONES AJAX # ========================================================================== # # ========================================================================== ### $.fn.khausForm = (settings)-> o = $.extend( onSubmit: -> onSuccess: -> onError: -> , settings) $.each @, ()-> form = $(@) form.on 'submit', (ev)-> o.onSubmit(form, ev); form.ajaxForm delegation: true success: (response, status, xhr, $form)-> $.each response, (key, value)-> if key.match /^khaus/ key = key.replace('khaus', <KEY>() if typeof window.khaus[key] isnt 'undefined' window.khaus[key] = value $.khausLaunchAlerts() if window.khaus.redirect isnt null if form.data('khaus-reset') || false $($form)[0].reset() if $.isArray(window.khaus.redirect) setTimeout(-> location = window.khaus.redirect[0] if not location.match(/^https?:\/\//i) location = window.baseURL + location; window.location = location , window.khaus.redirect[1]) else if $.isPlainObject(window.khaus.redirect) $.each window.khaus.redirect, (url, tiempo)-> setTimeout(-> location = url if not location.match(/^https?:\/\//i) location = window.baseURL + location; window.location = location , tiempo) else location = window.khaus.redirect if not location.match(/^https?:\/\//i) location = window.baseURL + location; window.location = location o.onSuccess($form, ev, response) error: (response, status, xhr, $form)-> $.khausCleanFormErrors($form) if typeof response.responseJSON isnt 'undefined' m = response.responseJSON else m = $.parseJSON(response.responseText) if m.message new Noty(text: m.message, type: 'error').show() $.khausDisplayFormErrors( errorsType: form.data('khaus-errortype') || 'block' form: $form errors: m.errors resetForm: form.data('khaus-reset') || false ) o.onError($form, ev, response) ### # ========================================================================== # # ========================================================================== ### $.fn.khausNumberFormat = ()-> replace = (number)-> number = number.replace /[^0-9]+/g, '' number = number.replace /\B(?=(\d{3})+(?!\d))/g, '.' @each ()-> if $(this).is(':input') number = replace $(this).val() $(this).val(number) else number = replace $(this).html() $(this).html(number) ### # ========================================================================== # # ========================================================================== ### $.khausLoadSelect = ($select, url, fk, selected)-> $select.attr 'disabled', true $select.text '' $.get "#{window.baseURL}#{url}/#{fk}.json", (r)-> $.each r, -> $('<option>', value:@id).text(@nombre).appendTo $select $select.removeAttr 'disabled' if $select.find("option[value=#{selected}]").length > 0 $select.val selected else $select.val($select.find('option:first').attr('value')) $.fn.khausLoadSelect = (settings)-> o = $.extend url : $(@).data 'khaus-url' select : $(@).data 'khaus-select' selected : $(@).data 'khaus-selected' or 1 , settings @each -> $select = $(o.select) if @value $.khausLoadSelect $select, o.url, @value, o.selected else $select.text '' $select.attr 'disabled', true $(@).on 'change', -> $.khausLoadSelect $select, o.url, @value, o.selected ### # ========================================================================== # # ========================================================================== ### $.fn.khausClone = -> @each -> $(@).on 'click', (ev)-> ev.preventDefault() selector = $(@).data 'khaus-clone' target = $(selector).last() clon = target.clone() clon.find(':input[name]').each -> name = $(@).attr('name') key = name.match(/\[(\d+)\]/) if !!key key = parseInt key[1] newName = name.replace "[#{key}]", "[#{key+1}]" $(@).attr 'name', newName clon.find('input').val '' clon.find('select option:first').attr 'selected', true clon.find(':button[data-khaus-removeparent]').khausRemoveParent() clon.insertAfter target ### # ========================================================================== # # ========================================================================== ### $.fn.khausRemoveParent = -> @each -> $(@).on 'click', (ev)-> ev.preventDefault() selector = $(@).data 'khaus-removeparent' target = $(this).parents(selector) target.remove() $ -> # noty defaults options Noty.overrideDefaults({ layout : 'bottomRight', theme : 'metroui', timeout : 8000, closeWith: ['click', 'button'], animation: { open : 'animated bounceInRight', close: 'animated bounceOutRight' } }); $('form').khausAttachName() $.khausLaunchFormErrors() $.khausLaunchAlerts() $('form.khaus-form').khausForm() $('form[data-khaus-confirm]').khausConfirmBeforeSubmit() $(':button[data-khaus-clone]').khausClone() $(':button[data-khaus-removeparent]').khausRemoveParent() $(':button[data-khaus-alert]').khausAlert() $('.khaus-numero').khausNumberFormat() $('select[data-khaus-select]').khausLoadSelect();
true
do ($=jQuery) -> ### LIMPIA LOS ERRORES DEL FORMULARIO BOOTSTRAP # ========================================================================== # @param DOMElement form - formulario # ========================================================================== ### $.khausCleanFormErrors = (form) -> $(form).find(".form-group").removeClass "has-error has-feedback" $(form).find("span.form-control-feedback").remove() $(form).find("span.help-block").remove() $(form).find("span.form-control-feedback").remove() $(form).find(":input").tooltip "destroy" ### DESPLIEGA LOS ERRORES DE FORMULARIO # ========================================================================== # @param string type (block|tooltip) forma de mostrar errores # @param DOMElement form - formulario que realizo el envio # @param object errors - errores {'inputName':'Error Message'} # # En caso de que no se envie el parametro errors, buscara esos datos # dentro de la variable global khaus # ========================================================================== ### $.khausDisplayFormErrors = (settings)-> o = $.extend errorsType : 'block' form : null errors : window.khaus.errors resetForm : false , settings counter = 0 $.each o.errors, (key, value)-> if key.match /^khaus/ key = key.replace('khaus', '').toLowerCase() if typeof window.khaus[key] isnt 'undefined' window.khaus[key] = value return true if arr = key.match /\.([^.]+)/ key = key.replace(arr[0], "[#{arr[1]}]") counter++ input = $(o.form).find(":input[name='#{key}']") # if input.length isnt 1 # si no lo encuentra busca inputs array[] # input = $(o.form).find(":input[name^='#{key}[']") input.parents('.form-group').addClass "has-error" input.parents('.form-group').addClass "has-feedback" # si el input se encuentra dentro del un formulario tabulado inTab = input.parents('.tab-content') if inTab.length > 0 if counter is 1 $('ul.nav-tabs .badge').remove() page = input.parents('.tab-pane') pageName = page.attr 'id' #if not page.hasClass 'active' tab = $("ul.nav-tabs a[href=##{pageName}]") badge = tab.find '.badge' if badge.length is 0 badge = $('<span>', 'class':'badge').text 0 badge.appendTo tab badge.text parseInt(badge.text()) + 1 switch o.errorsType when 'block' pos = input.parents '.form-group' $("<span>", "class":"help-block").html(value).appendTo pos $("<span>", "class":"glyphicon glyphicon-remove form-control-feedback").appendTo pos when 'tooltip' input.tooltip( placement : "top" title : value container : "body" ) $.khausLaunchAlerts() if counter is 0 if o.resetForm $(o.form)[0].reset() ### MUESTRA LOS ERRORES ALMACENADOS EN LAS VARIABLES KHAUS # ========================================================================== # # ========================================================================== ### $.khausLaunchFormErrors = ()-> if !!window.khaus.errors and !!window.khaus.form form = $("form[name=#{window.khaus.form}]") $.khausDisplayFormErrors( errorsType: 'block' form: form ) ### # ========================================================================== # # ========================================================================== ### $.khausLaunchAlerts = (settings) -> o = $.extend title : default : "" primary : "" success : "El proceso ha finalizado" danger : "Ha ocurrido un error" warning : "Importante" info : "Informaci&oacute;n" , settings $.each o.title, (key, value)-> if !!window.khaus[key] template = key if key is 'default' template = 'alert' if key is 'danger' template = 'error' if key is 'info' template = 'info' if $.isPlainObject(window.khaus[key]) or $.isArray(window.khaus[key]) $.each window.khaus[key], (k, mensaje)-> new Noty( text: mensaje type: template ).show() else new Noty( text: window.khaus[key] type: template ).show() window.khaus[key] = '' ### # ========================================================================== # # ========================================================================== ### $.khausAjaxWait = (settings)-> o = $.extend type : 'cursor' , settings switch o.type when 'cursor' $.ajaxSetup beforeSend : ()-> $('body').addClass 'khaus-ajax-wait' complete : ()-> $('body').removeClass 'khaus-ajax-wait' success : ()-> $('body').removeClass 'khaus-ajax-wait' ### ADJUNTA AL FORMULARIO EL PARAMETRO NAME # ========================================================================== # Si el formulario tiene el atributo [name] activado # antes de realizar el envio de los parametros # agrega un input hidden name="_name" value="<nombre del formulario>" # ========================================================================== ### $.fn.khausAttachName = ()-> $.each @, ()-> $(@).on 'submit', (ev)-> if $(@).is('[name]') and $(@).find('input[name=_name]').length is 0 $('<input>', 'name':'_name' 'type':'hidden' 'value':$(@).attr('name') ).prependTo($(@)) ### CAPTURA EL EVENTO SUBMIT Y ENVIA UN MODAL KHAUS CONFIRM # ========================================================================== # @param object settings { # title : (string) - titulo de la ventana modal # message : (string) - mensaje de la ventana modal # } # Al presionar el boton aceptar del modal se realizara el submit del formulario # de lo contrario no se realizara ninguna accion # ========================================================================== ### $.fn.khausConfirmBeforeSubmit = -> $.each @, -> title = $(@).data 'khaus-title' || '' message = $(@).data 'khaus-confirm' || '' $(@).on 'submit', (ev)-> $(':focus').blur() ev.preventDefault() e = $(@) $.khausConfirm title, message, -> e.off 'submit' e.submit() ### # ========================================================================== # Envia un modal de alerta con las opciones aceptar y cancelar # Metodos de llamada: # - por codigo: $.khausAlert('Titulo', 'Mensaje'); # - por dom: <button data-khaus-alert="Mensaje" data-khaus-title="Opcional"> # El titulo es opcional en la llamada por dom # ========================================================================== ### $.khausAlert = (title, message) -> if $(".khaus-modal-alert").length > 0 $(".khaus-modal-alert").remove() modal_D1 = $("<div>", "class":"modal fade khaus-modal-alert") modal_D2 = $("<div>", "class":"modal-dialog").appendTo modal_D1 modal_D3 = $("<div>", "class":"modal-content").appendTo modal_D2 modal_header = $("<div>", "class":"modal-header").appendTo modal_D3 $("<h4>", "class":"modal-title").html(title).appendTo modal_header modal_body = $("<div>", "class":"modal-body").html(message).appendTo modal_D3 modal_footer = $("<div>", "class":"modal-footer").appendTo modal_D3 $("<button>", "type":"button", "class":"btn btn-primary", "data-dismiss":"modal").html("Aceptar").appendTo modal_footer modal_D1.modal "show" $.fn.khausAlert = -> @each -> $(@).on 'click', (ev)-> message = $(@).data 'khaus-alert' title = $(@).data 'khaus-title' || '' $.khausAlert(title, message) ### # ========================================================================== # # ========================================================================== ### $.khausPrompt = (title, message, defaultValue = "", callback = ->) -> if $(".khaus-modal-prompt").length > 0 $(".khaus-modal-prompt").remove() modal_D1 = $("<div>", "class":"modal fade khaus-modal-prompt") modal_D2 = $("<div>", "class":"modal-dialog").appendTo modal_D1 modal_D3 = $("<div>", "class":"modal-content").appendTo modal_D2 modal_header = $("<div>", "class":"modal-header").appendTo modal_D3 $("<h4>", "class":"modal-title").html(title).appendTo modal_header modal_body = $("<div>", "class":"modal-body").appendTo modal_D3 $("<h5>").css("font-weight":"bold").html(message).appendTo modal_body input_prompt = $("<input>", "type":"text", "class":"form-control").val(defaultValue).appendTo modal_body modal_footer = $("<div>", "class":"modal-footer").appendTo modal_D3 $("<button>", "type":"button", "class":"btn btn-default", "data-dismiss":"modal").html("Cancelar").appendTo modal_footer $("<button>", "type":"button", "class":"btn btn-primary", "data-dismiss":"modal") .html("Aceptar") .on "click", -> callback input_prompt.val() return .appendTo modal_footer modal_D1.modal "show" setTimeout -> input_prompt.select() , 200 ### # ========================================================================== # # ========================================================================== ### $.khausConfirm = (title, message, callback = ->) -> if $(".khaus-modal-confirm").length > 0 $(".khaus-modal-confirm").remove() modal_D1 = $("<div>", "class":"modal fade khaus-modal-confirm") modal_D2 = $("<div>", "class":"modal-dialog").appendTo modal_D1 modal_D3 = $("<div>", "class":"modal-content").appendTo modal_D2 modal_header = $("<div>", "class":"modal-header").appendTo modal_D3 $("<h4>", "class":"modal-title").html(title).appendTo modal_header modal_body = $("<div>", "class":"modal-body").html(message).appendTo modal_D3 modal_footer = $("<div>", "class":"modal-footer").appendTo modal_D3 $("<button>", "type":"button", "class":"btn btn-default", "data-dismiss":"modal").html("Cancelar").appendTo modal_footer btnAceptar = $("<button>", "type":"button", "class":"btn btn-primary", "data-dismiss":"modal") .html("Aceptar") .on "click", -> callback() return .appendTo modal_footer setTimeout(-> btnAceptar.focus() , 300) modal_D1.modal "show" ### CAMBIA EL FUNCIONAMIENTO DE LOS FORMULARIOS POR PETICIONES AJAX # ========================================================================== # # ========================================================================== ### $.fn.khausForm = (settings)-> o = $.extend( onSubmit: -> onSuccess: -> onError: -> , settings) $.each @, ()-> form = $(@) form.on 'submit', (ev)-> o.onSubmit(form, ev); form.ajaxForm delegation: true success: (response, status, xhr, $form)-> $.each response, (key, value)-> if key.match /^khaus/ key = key.replace('khaus', PI:KEY:<KEY>END_PI() if typeof window.khaus[key] isnt 'undefined' window.khaus[key] = value $.khausLaunchAlerts() if window.khaus.redirect isnt null if form.data('khaus-reset') || false $($form)[0].reset() if $.isArray(window.khaus.redirect) setTimeout(-> location = window.khaus.redirect[0] if not location.match(/^https?:\/\//i) location = window.baseURL + location; window.location = location , window.khaus.redirect[1]) else if $.isPlainObject(window.khaus.redirect) $.each window.khaus.redirect, (url, tiempo)-> setTimeout(-> location = url if not location.match(/^https?:\/\//i) location = window.baseURL + location; window.location = location , tiempo) else location = window.khaus.redirect if not location.match(/^https?:\/\//i) location = window.baseURL + location; window.location = location o.onSuccess($form, ev, response) error: (response, status, xhr, $form)-> $.khausCleanFormErrors($form) if typeof response.responseJSON isnt 'undefined' m = response.responseJSON else m = $.parseJSON(response.responseText) if m.message new Noty(text: m.message, type: 'error').show() $.khausDisplayFormErrors( errorsType: form.data('khaus-errortype') || 'block' form: $form errors: m.errors resetForm: form.data('khaus-reset') || false ) o.onError($form, ev, response) ### # ========================================================================== # # ========================================================================== ### $.fn.khausNumberFormat = ()-> replace = (number)-> number = number.replace /[^0-9]+/g, '' number = number.replace /\B(?=(\d{3})+(?!\d))/g, '.' @each ()-> if $(this).is(':input') number = replace $(this).val() $(this).val(number) else number = replace $(this).html() $(this).html(number) ### # ========================================================================== # # ========================================================================== ### $.khausLoadSelect = ($select, url, fk, selected)-> $select.attr 'disabled', true $select.text '' $.get "#{window.baseURL}#{url}/#{fk}.json", (r)-> $.each r, -> $('<option>', value:@id).text(@nombre).appendTo $select $select.removeAttr 'disabled' if $select.find("option[value=#{selected}]").length > 0 $select.val selected else $select.val($select.find('option:first').attr('value')) $.fn.khausLoadSelect = (settings)-> o = $.extend url : $(@).data 'khaus-url' select : $(@).data 'khaus-select' selected : $(@).data 'khaus-selected' or 1 , settings @each -> $select = $(o.select) if @value $.khausLoadSelect $select, o.url, @value, o.selected else $select.text '' $select.attr 'disabled', true $(@).on 'change', -> $.khausLoadSelect $select, o.url, @value, o.selected ### # ========================================================================== # # ========================================================================== ### $.fn.khausClone = -> @each -> $(@).on 'click', (ev)-> ev.preventDefault() selector = $(@).data 'khaus-clone' target = $(selector).last() clon = target.clone() clon.find(':input[name]').each -> name = $(@).attr('name') key = name.match(/\[(\d+)\]/) if !!key key = parseInt key[1] newName = name.replace "[#{key}]", "[#{key+1}]" $(@).attr 'name', newName clon.find('input').val '' clon.find('select option:first').attr 'selected', true clon.find(':button[data-khaus-removeparent]').khausRemoveParent() clon.insertAfter target ### # ========================================================================== # # ========================================================================== ### $.fn.khausRemoveParent = -> @each -> $(@).on 'click', (ev)-> ev.preventDefault() selector = $(@).data 'khaus-removeparent' target = $(this).parents(selector) target.remove() $ -> # noty defaults options Noty.overrideDefaults({ layout : 'bottomRight', theme : 'metroui', timeout : 8000, closeWith: ['click', 'button'], animation: { open : 'animated bounceInRight', close: 'animated bounceOutRight' } }); $('form').khausAttachName() $.khausLaunchFormErrors() $.khausLaunchAlerts() $('form.khaus-form').khausForm() $('form[data-khaus-confirm]').khausConfirmBeforeSubmit() $(':button[data-khaus-clone]').khausClone() $(':button[data-khaus-removeparent]').khausRemoveParent() $(':button[data-khaus-alert]').khausAlert() $('.khaus-numero').khausNumberFormat() $('select[data-khaus-select]').khausLoadSelect();
[ { "context": "angular: [\n { key: \"data.filename\" }\n]\n", "end": 34, "score": 0.9570100903511047, "start": 21, "tag": "KEY", "value": "data.filename" } ]
jobs/open-presentation/form.cson
jamesbulpin/meshblu-connector-powerpoint
1
angular: [ { key: "data.filename" } ]
150448
angular: [ { key: "<KEY>" } ]
true
angular: [ { key: "PI:KEY:<KEY>END_PI" } ]
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998459219932556, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai...
library/membrane/preflight.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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. ### _ = require "lodash" bower = require "bower" asciify = require "asciify" connect = require "connect" logger = require "winston" events = require "eventemitter2" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" https = require "https" path = require "path" http = require "http" util = require "util" {Barebones} = require "./skeleton" {Screenplay} = require "./visual" {Extending} = require "../nucleus/extends" {Composition} = require "../nucleus/compose" {Archetype} = require "../nucleus/arche" # This abstract base class service is an extension of the Screenplay # family that does some further environment initialization and set # up. These preparations will be nececessary no matter what sort of # Screenplay functionality you are going to implement. Currently the # purpose of preflight is drawing in the remotes and Bower packages. module.exports.Preflight = class Preflight extends Screenplay # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # This block define a set of meta tags that specify or tweak # the way a client browser treats the content that it has got # from the server site. Please refer to the HTML5 specification # for more information on the exact semantics of any meta tag. # Reference the `Preflight` for the implementation guidance. @metatag generator: "github.com/ts33kr/granite" # This block here defines a set of Bower dependencies that are # going to be necessary no matter what sort of functionality is # is going to be implemented. Most of these libraries required # by the internal implementations of the various subcomponents. # Refer to `BowerSupport` class implementation for information. @bower "eventemitter2" @bower "js-signals" @bower "platform" @bower "loglevel" @bower "lodash" @bower "jquery" @bower "jwerty" @bower "async" @bower "chai" # This block here defines a set of Bower dependencies that are # going to be necessary no matter what sort of functionality is # is going to be implemented. Most of these libraries required # by the internal implementations of the various subcomponents. # This blocks defines the directory-scopes deps, not bare ones. @bower "underscore.string#2.4.x" @bower "node-uuid", "uuid.js" @bower "toastr#2.0.x" # This block here defines a set of remote dependencies that are # going to be necessary no matter what sort of functionality is # is going to be implemented. Most of these libraries required # by the internal implementations of the various subcomponents. # Refer to `RToolkit` class implementation for the information. @transfer Composition @transfer Extending @transfer Archetype
50548
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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. ### _ = require "lodash" bower = require "bower" asciify = require "asciify" connect = require "connect" logger = require "winston" events = require "eventemitter2" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" https = require "https" path = require "path" http = require "http" util = require "util" {Barebones} = require "./skeleton" {Screenplay} = require "./visual" {Extending} = require "../nucleus/extends" {Composition} = require "../nucleus/compose" {Archetype} = require "../nucleus/arche" # This abstract base class service is an extension of the Screenplay # family that does some further environment initialization and set # up. These preparations will be nececessary no matter what sort of # Screenplay functionality you are going to implement. Currently the # purpose of preflight is drawing in the remotes and Bower packages. module.exports.Preflight = class Preflight extends Screenplay # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # This block define a set of meta tags that specify or tweak # the way a client browser treats the content that it has got # from the server site. Please refer to the HTML5 specification # for more information on the exact semantics of any meta tag. # Reference the `Preflight` for the implementation guidance. @metatag generator: "github.com/ts33kr/granite" # This block here defines a set of Bower dependencies that are # going to be necessary no matter what sort of functionality is # is going to be implemented. Most of these libraries required # by the internal implementations of the various subcomponents. # Refer to `BowerSupport` class implementation for information. @bower "eventemitter2" @bower "js-signals" @bower "platform" @bower "loglevel" @bower "lodash" @bower "jquery" @bower "jwerty" @bower "async" @bower "chai" # This block here defines a set of Bower dependencies that are # going to be necessary no matter what sort of functionality is # is going to be implemented. Most of these libraries required # by the internal implementations of the various subcomponents. # This blocks defines the directory-scopes deps, not bare ones. @bower "underscore.string#2.4.x" @bower "node-uuid", "uuid.js" @bower "toastr#2.0.x" # This block here defines a set of remote dependencies that are # going to be necessary no matter what sort of functionality is # is going to be implemented. Most of these libraries required # by the internal implementations of the various subcomponents. # Refer to `RToolkit` class implementation for the information. @transfer Composition @transfer Extending @transfer Archetype
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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. ### _ = require "lodash" bower = require "bower" asciify = require "asciify" connect = require "connect" logger = require "winston" events = require "eventemitter2" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" https = require "https" path = require "path" http = require "http" util = require "util" {Barebones} = require "./skeleton" {Screenplay} = require "./visual" {Extending} = require "../nucleus/extends" {Composition} = require "../nucleus/compose" {Archetype} = require "../nucleus/arche" # This abstract base class service is an extension of the Screenplay # family that does some further environment initialization and set # up. These preparations will be nececessary no matter what sort of # Screenplay functionality you are going to implement. Currently the # purpose of preflight is drawing in the remotes and Bower packages. module.exports.Preflight = class Preflight extends Screenplay # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # This block define a set of meta tags that specify or tweak # the way a client browser treats the content that it has got # from the server site. Please refer to the HTML5 specification # for more information on the exact semantics of any meta tag. # Reference the `Preflight` for the implementation guidance. @metatag generator: "github.com/ts33kr/granite" # This block here defines a set of Bower dependencies that are # going to be necessary no matter what sort of functionality is # is going to be implemented. Most of these libraries required # by the internal implementations of the various subcomponents. # Refer to `BowerSupport` class implementation for information. @bower "eventemitter2" @bower "js-signals" @bower "platform" @bower "loglevel" @bower "lodash" @bower "jquery" @bower "jwerty" @bower "async" @bower "chai" # This block here defines a set of Bower dependencies that are # going to be necessary no matter what sort of functionality is # is going to be implemented. Most of these libraries required # by the internal implementations of the various subcomponents. # This blocks defines the directory-scopes deps, not bare ones. @bower "underscore.string#2.4.x" @bower "node-uuid", "uuid.js" @bower "toastr#2.0.x" # This block here defines a set of remote dependencies that are # going to be necessary no matter what sort of functionality is # is going to be implemented. Most of these libraries required # by the internal implementations of the various subcomponents. # Refer to `RToolkit` class implementation for the information. @transfer Composition @transfer Extending @transfer Archetype
[ { "context": "#############\n#\n#\tMoocita collections\n# Created by Markus on 26/10/2015.\n#\n################################", "end": 99, "score": 0.9996089935302734, "start": 93, "tag": "NAME", "value": "Markus" } ]
server/publications/permissions.coffee
agottschalk10/worklearn
0
####################################################### # # Moocita collections # Created by Markus on 26/10/2015. # ####################################################### ####################################################### Meteor.publish "permissions", () -> user_id = this.userId if !user_id throw new Meteor.Error "Not permitted." if !Roles.userIsInRole user_id, "admin" throw new Meteor.Error "Not permitted." crs = Permissions.find() log_publication "Permissions", crs, {}, {}, "permissions", user_id return crs
95786
####################################################### # # Moocita collections # Created by <NAME> on 26/10/2015. # ####################################################### ####################################################### Meteor.publish "permissions", () -> user_id = this.userId if !user_id throw new Meteor.Error "Not permitted." if !Roles.userIsInRole user_id, "admin" throw new Meteor.Error "Not permitted." crs = Permissions.find() log_publication "Permissions", crs, {}, {}, "permissions", user_id return crs
true
####################################################### # # Moocita collections # Created by PI:NAME:<NAME>END_PI on 26/10/2015. # ####################################################### ####################################################### Meteor.publish "permissions", () -> user_id = this.userId if !user_id throw new Meteor.Error "Not permitted." if !Roles.userIsInRole user_id, "admin" throw new Meteor.Error "Not permitted." crs = Permissions.find() log_publication "Permissions", crs, {}, {}, "permissions", user_id return crs
[ { "context": "---\n---\n\n### Ben Scott # 2015-10-04 # Background ###\n\n'use strict'\n\n### ", "end": 22, "score": 0.999756395816803, "start": 13, "tag": "NAME", "value": "Ben Scott" } ]
js/background.coffee
evan-erdos/evan-erdos.github.io
1
--- --- ### Ben Scott # 2015-10-04 # Background ### 'use strict' ### `P5.js` Main class This is our instance of the main class in the `P5.js` library. The argument is the link between the library and this code, and the special functions we override in the class definition are callbacks for P5.js events. ### myp = new p5 (p)-> alt = false pi = p.PI [r_sl,g_sl,b_sl] = [null,null,null] [d_sl,s_sl,rand_sl] = [null,null,null] mouse = [p.mouseX,p.mouseY] img = null ### `P5.js` Events These functions are automatic callbacks for `P5.js` events: - `p.preload` is called once, immediately before `setup` - `p.setup` is called once, at the beginning of execution - `p.draw` is called as frequently as `p.framerate` - `p.keyPressed` is called on every key input event - `p.mousePressed` is called on mouse down - `p.remove` destroys everything in the sketch ### p.preload = -> img = p.loadImage("/rsc/colormap.gif") p.setup = -> p.createCanvas(p.windowWidth,p.windowHeight, p.WEBGL) p.noStroke() #p.setupUI() #p.setupWebGL() p.frameRate(60) p.draw = -> p.background(120) p.HexGrid(128,128) p.getInput() #p.drawUI() p.renderWebGL() p.keyPressed = -> alt = !alt if (p.keyCode is p.ALT) ### p.mousePressed = -> s = s_sl.value() [x,y] = [16*s,16*s] d = d_sl.value() rgb = p.color( r_sl.value()+p.random(d) g_sl.value()+p.random(d) b_sl.value()+p.random(d),127) rand = rand_sl.value() delta_size = p.random(s/2) if (alt) then p.fill(255) else p.fill(rgb) p.ellipse( mouse[0]+p.random(-rand,rand) mouse[1]+p.random(-rand,rand) x*delta_size,y*delta_size) ### #p.remove = -> p5 = null ### Library Functions These functions I've included from other files. They're the sort of generic utilities that would constitute a library. - `p.polygon` draws a regular polygon. - @x,@y: center - @r: radius - @n: number of points - @o: offset theta - `p.HexGrid` draws a grid of hexagons. - @x,@y: center - @r: radius - @s: size ### p.polygon = (x,y,r=1,n=3,o=0) -> theta = p.TWO_PI/n p.beginShape() for i in [0..p.TWO_PI] by theta p.vertex(x+p.cos(i+o)*r, y+p.sin(i+o)*r) p.endShape(p.CLOSE) p.HexGrid = (x=0,y=0,r=32,s=16) -> [pi_3,pi_6,h] = [p.PI/3, p.PI/6, p.sqrt(3)/2] for i in [0..s] for j in [0..s/4] if p.random(4)>3 p.fill(p.random(255)) else p.fill(255) p.polygon( x+(i*(h)*r*p.cos(pi_3))*2 y+(3.45*j*h*r)+((i%2)*(h)*r*p.sin(pi_3))*2 r, 6, pi_6) ### UI Functions These functions initialize the DOM objects in the sketch. - `p.setupUI` creates and positions the color sliders - `p.drawUI` renders the color sliders on every draw - `p.getInput` collects input data, processes it, and in the case of `p.mouseIsPressed`, it calls the mouse event callback (otherwise it single-clicks) ### p.setupUI = -> r_sl = p.createSlider(0,255,100) r_sl.position(16,16) g_sl = p.createSlider(0,255,0) g_sl.position(16,32) b_sl = p.createSlider(0,255,255) b_sl.position(16,48) s_sl = p.createSlider(1,8,4) s_sl.position(16,64) d_sl = p.createSlider(0,64,32) d_sl.position(16,80) rand_sl = p.createSlider(0,16,4) rand_sl.position(16,96) p.drawUI = -> p.fill(0) p.text("Red",150,16+4) p.text("Green",150,32+4) p.text("Blue",150,48+4) p.text("Size",150,64+4) p.text("Delta",150,80+4) p.text("Rand",150,96+4) p.image(img) p.getInput = -> mouse = [p.mouseX,p.mouseY] #p.mousePressed() if (p.mouseIsPressed) p.setupWebGL = -> p.move(0,2,0) p.renderWebGL = -> p.background(0) p.pointLight(250,250,250,0,0,0) p.translate(0,100,0) p.sphere(200) p.rotateZ(0.5) p.rotateY(p.frameCount * 0.01) p.translate(0,0,500) p.sphere(50) p.cylinder(100, 1)
151409
--- --- ### <NAME> # 2015-10-04 # Background ### 'use strict' ### `P5.js` Main class This is our instance of the main class in the `P5.js` library. The argument is the link between the library and this code, and the special functions we override in the class definition are callbacks for P5.js events. ### myp = new p5 (p)-> alt = false pi = p.PI [r_sl,g_sl,b_sl] = [null,null,null] [d_sl,s_sl,rand_sl] = [null,null,null] mouse = [p.mouseX,p.mouseY] img = null ### `P5.js` Events These functions are automatic callbacks for `P5.js` events: - `p.preload` is called once, immediately before `setup` - `p.setup` is called once, at the beginning of execution - `p.draw` is called as frequently as `p.framerate` - `p.keyPressed` is called on every key input event - `p.mousePressed` is called on mouse down - `p.remove` destroys everything in the sketch ### p.preload = -> img = p.loadImage("/rsc/colormap.gif") p.setup = -> p.createCanvas(p.windowWidth,p.windowHeight, p.WEBGL) p.noStroke() #p.setupUI() #p.setupWebGL() p.frameRate(60) p.draw = -> p.background(120) p.HexGrid(128,128) p.getInput() #p.drawUI() p.renderWebGL() p.keyPressed = -> alt = !alt if (p.keyCode is p.ALT) ### p.mousePressed = -> s = s_sl.value() [x,y] = [16*s,16*s] d = d_sl.value() rgb = p.color( r_sl.value()+p.random(d) g_sl.value()+p.random(d) b_sl.value()+p.random(d),127) rand = rand_sl.value() delta_size = p.random(s/2) if (alt) then p.fill(255) else p.fill(rgb) p.ellipse( mouse[0]+p.random(-rand,rand) mouse[1]+p.random(-rand,rand) x*delta_size,y*delta_size) ### #p.remove = -> p5 = null ### Library Functions These functions I've included from other files. They're the sort of generic utilities that would constitute a library. - `p.polygon` draws a regular polygon. - @x,@y: center - @r: radius - @n: number of points - @o: offset theta - `p.HexGrid` draws a grid of hexagons. - @x,@y: center - @r: radius - @s: size ### p.polygon = (x,y,r=1,n=3,o=0) -> theta = p.TWO_PI/n p.beginShape() for i in [0..p.TWO_PI] by theta p.vertex(x+p.cos(i+o)*r, y+p.sin(i+o)*r) p.endShape(p.CLOSE) p.HexGrid = (x=0,y=0,r=32,s=16) -> [pi_3,pi_6,h] = [p.PI/3, p.PI/6, p.sqrt(3)/2] for i in [0..s] for j in [0..s/4] if p.random(4)>3 p.fill(p.random(255)) else p.fill(255) p.polygon( x+(i*(h)*r*p.cos(pi_3))*2 y+(3.45*j*h*r)+((i%2)*(h)*r*p.sin(pi_3))*2 r, 6, pi_6) ### UI Functions These functions initialize the DOM objects in the sketch. - `p.setupUI` creates and positions the color sliders - `p.drawUI` renders the color sliders on every draw - `p.getInput` collects input data, processes it, and in the case of `p.mouseIsPressed`, it calls the mouse event callback (otherwise it single-clicks) ### p.setupUI = -> r_sl = p.createSlider(0,255,100) r_sl.position(16,16) g_sl = p.createSlider(0,255,0) g_sl.position(16,32) b_sl = p.createSlider(0,255,255) b_sl.position(16,48) s_sl = p.createSlider(1,8,4) s_sl.position(16,64) d_sl = p.createSlider(0,64,32) d_sl.position(16,80) rand_sl = p.createSlider(0,16,4) rand_sl.position(16,96) p.drawUI = -> p.fill(0) p.text("Red",150,16+4) p.text("Green",150,32+4) p.text("Blue",150,48+4) p.text("Size",150,64+4) p.text("Delta",150,80+4) p.text("Rand",150,96+4) p.image(img) p.getInput = -> mouse = [p.mouseX,p.mouseY] #p.mousePressed() if (p.mouseIsPressed) p.setupWebGL = -> p.move(0,2,0) p.renderWebGL = -> p.background(0) p.pointLight(250,250,250,0,0,0) p.translate(0,100,0) p.sphere(200) p.rotateZ(0.5) p.rotateY(p.frameCount * 0.01) p.translate(0,0,500) p.sphere(50) p.cylinder(100, 1)
true
--- --- ### PI:NAME:<NAME>END_PI # 2015-10-04 # Background ### 'use strict' ### `P5.js` Main class This is our instance of the main class in the `P5.js` library. The argument is the link between the library and this code, and the special functions we override in the class definition are callbacks for P5.js events. ### myp = new p5 (p)-> alt = false pi = p.PI [r_sl,g_sl,b_sl] = [null,null,null] [d_sl,s_sl,rand_sl] = [null,null,null] mouse = [p.mouseX,p.mouseY] img = null ### `P5.js` Events These functions are automatic callbacks for `P5.js` events: - `p.preload` is called once, immediately before `setup` - `p.setup` is called once, at the beginning of execution - `p.draw` is called as frequently as `p.framerate` - `p.keyPressed` is called on every key input event - `p.mousePressed` is called on mouse down - `p.remove` destroys everything in the sketch ### p.preload = -> img = p.loadImage("/rsc/colormap.gif") p.setup = -> p.createCanvas(p.windowWidth,p.windowHeight, p.WEBGL) p.noStroke() #p.setupUI() #p.setupWebGL() p.frameRate(60) p.draw = -> p.background(120) p.HexGrid(128,128) p.getInput() #p.drawUI() p.renderWebGL() p.keyPressed = -> alt = !alt if (p.keyCode is p.ALT) ### p.mousePressed = -> s = s_sl.value() [x,y] = [16*s,16*s] d = d_sl.value() rgb = p.color( r_sl.value()+p.random(d) g_sl.value()+p.random(d) b_sl.value()+p.random(d),127) rand = rand_sl.value() delta_size = p.random(s/2) if (alt) then p.fill(255) else p.fill(rgb) p.ellipse( mouse[0]+p.random(-rand,rand) mouse[1]+p.random(-rand,rand) x*delta_size,y*delta_size) ### #p.remove = -> p5 = null ### Library Functions These functions I've included from other files. They're the sort of generic utilities that would constitute a library. - `p.polygon` draws a regular polygon. - @x,@y: center - @r: radius - @n: number of points - @o: offset theta - `p.HexGrid` draws a grid of hexagons. - @x,@y: center - @r: radius - @s: size ### p.polygon = (x,y,r=1,n=3,o=0) -> theta = p.TWO_PI/n p.beginShape() for i in [0..p.TWO_PI] by theta p.vertex(x+p.cos(i+o)*r, y+p.sin(i+o)*r) p.endShape(p.CLOSE) p.HexGrid = (x=0,y=0,r=32,s=16) -> [pi_3,pi_6,h] = [p.PI/3, p.PI/6, p.sqrt(3)/2] for i in [0..s] for j in [0..s/4] if p.random(4)>3 p.fill(p.random(255)) else p.fill(255) p.polygon( x+(i*(h)*r*p.cos(pi_3))*2 y+(3.45*j*h*r)+((i%2)*(h)*r*p.sin(pi_3))*2 r, 6, pi_6) ### UI Functions These functions initialize the DOM objects in the sketch. - `p.setupUI` creates and positions the color sliders - `p.drawUI` renders the color sliders on every draw - `p.getInput` collects input data, processes it, and in the case of `p.mouseIsPressed`, it calls the mouse event callback (otherwise it single-clicks) ### p.setupUI = -> r_sl = p.createSlider(0,255,100) r_sl.position(16,16) g_sl = p.createSlider(0,255,0) g_sl.position(16,32) b_sl = p.createSlider(0,255,255) b_sl.position(16,48) s_sl = p.createSlider(1,8,4) s_sl.position(16,64) d_sl = p.createSlider(0,64,32) d_sl.position(16,80) rand_sl = p.createSlider(0,16,4) rand_sl.position(16,96) p.drawUI = -> p.fill(0) p.text("Red",150,16+4) p.text("Green",150,32+4) p.text("Blue",150,48+4) p.text("Size",150,64+4) p.text("Delta",150,80+4) p.text("Rand",150,96+4) p.image(img) p.getInput = -> mouse = [p.mouseX,p.mouseY] #p.mousePressed() if (p.mouseIsPressed) p.setupWebGL = -> p.move(0,2,0) p.renderWebGL = -> p.background(0) p.pointLight(250,250,250,0,0,0) p.translate(0,100,0) p.sphere(200) p.rotateZ(0.5) p.rotateY(p.frameCount * 0.01) p.translate(0,0,500) p.sphere(50) p.cylinder(100, 1)
[ { "context": "functions for React components detection\n# @author Yannick Croissant\n###\n'use strict'\n\n{getDeclarationAssignmentAncest", "end": 97, "score": 0.9998582005500793, "start": 80, "tag": "NAME", "value": "Yannick Croissant" }, { "context": "atch for babel-eslint to avoid...
src/util/react/variable.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Utility functions for React components detection # @author Yannick Croissant ### 'use strict' {getDeclarationAssignmentAncestor} = require '../ast-utils' ###* # Search a particular variable in a list # @param {Array} variables The variables list. # @param {Array} name The name of the variable to search. # @returns {Boolean} True if the variable was found, false if not. ### findVariable = (variables, name) -> variables.some (variable) -> variable.name is name ###* # Find and return a particular variable in a list # @param {Array} variables The variables list. # @param {Array} name The name of the variable to search. # @returns {Object} Variable if the variable was found, null if not. ### getVariable = (variables, name) -> variables.find (variable) -> variable.name is name ###* # List all variable in a given scope # # Contain a patch for babel-eslint to avoid https://github.com/babel/babel-eslint/issues/21 # # @param {Object} context The current rule context. # @returns {Array} The variables list ### variablesInScope = (context) -> scope = context.getScope() {variables} = scope while scope.type isnt 'global' scope = scope.upper variables = scope.variables.concat variables if scope.childScopes.length variables = scope.childScopes[0].variables.concat variables if scope.childScopes[0].childScopes.length variables = scope.childScopes[0].childScopes[0].variables.concat variables variables.reverse() variables ###* # Find a variable by name in the current scope. # @param {Object} context The current rule context. # @param {string} name Name of the variable to look for. # @returns {ASTNode|null} Return null if the variable could not be found, ASTNode otherwise. ### findVariableByName = (context, name) -> variable = getVariable variablesInScope(context), name return null unless node = variable?.defs[0]?.node return node.right if node.type is 'TypeAlias' return node.init if node.init? return node.parent.right if ( node.declaration and node.parent.type is 'AssignmentExpression' ) if node.type is 'Identifier' and node.declaration return getDeclarationAssignmentAncestor(node)?.right null module.exports = { findVariable findVariableByName getVariable variablesInScope }
67319
###* # @fileoverview Utility functions for React components detection # @author <NAME> ### 'use strict' {getDeclarationAssignmentAncestor} = require '../ast-utils' ###* # Search a particular variable in a list # @param {Array} variables The variables list. # @param {Array} name The name of the variable to search. # @returns {Boolean} True if the variable was found, false if not. ### findVariable = (variables, name) -> variables.some (variable) -> variable.name is name ###* # Find and return a particular variable in a list # @param {Array} variables The variables list. # @param {Array} name The name of the variable to search. # @returns {Object} Variable if the variable was found, null if not. ### getVariable = (variables, name) -> variables.find (variable) -> variable.name is name ###* # List all variable in a given scope # # Contain a patch for babel-eslint to avoid https://github.com/babel/babel-eslint/issues/21 # # @param {Object} context The current rule context. # @returns {Array} The variables list ### variablesInScope = (context) -> scope = context.getScope() {variables} = scope while scope.type isnt 'global' scope = scope.upper variables = scope.variables.concat variables if scope.childScopes.length variables = scope.childScopes[0].variables.concat variables if scope.childScopes[0].childScopes.length variables = scope.childScopes[0].childScopes[0].variables.concat variables variables.reverse() variables ###* # Find a variable by name in the current scope. # @param {Object} context The current rule context. # @param {string} name Name of the variable to look for. # @returns {ASTNode|null} Return null if the variable could not be found, ASTNode otherwise. ### findVariableByName = (context, name) -> variable = getVariable variablesInScope(context), name return null unless node = variable?.defs[0]?.node return node.right if node.type is 'TypeAlias' return node.init if node.init? return node.parent.right if ( node.declaration and node.parent.type is 'AssignmentExpression' ) if node.type is 'Identifier' and node.declaration return getDeclarationAssignmentAncestor(node)?.right null module.exports = { findVariable findVariableByName getVariable variablesInScope }
true
###* # @fileoverview Utility functions for React components detection # @author PI:NAME:<NAME>END_PI ### 'use strict' {getDeclarationAssignmentAncestor} = require '../ast-utils' ###* # Search a particular variable in a list # @param {Array} variables The variables list. # @param {Array} name The name of the variable to search. # @returns {Boolean} True if the variable was found, false if not. ### findVariable = (variables, name) -> variables.some (variable) -> variable.name is name ###* # Find and return a particular variable in a list # @param {Array} variables The variables list. # @param {Array} name The name of the variable to search. # @returns {Object} Variable if the variable was found, null if not. ### getVariable = (variables, name) -> variables.find (variable) -> variable.name is name ###* # List all variable in a given scope # # Contain a patch for babel-eslint to avoid https://github.com/babel/babel-eslint/issues/21 # # @param {Object} context The current rule context. # @returns {Array} The variables list ### variablesInScope = (context) -> scope = context.getScope() {variables} = scope while scope.type isnt 'global' scope = scope.upper variables = scope.variables.concat variables if scope.childScopes.length variables = scope.childScopes[0].variables.concat variables if scope.childScopes[0].childScopes.length variables = scope.childScopes[0].childScopes[0].variables.concat variables variables.reverse() variables ###* # Find a variable by name in the current scope. # @param {Object} context The current rule context. # @param {string} name Name of the variable to look for. # @returns {ASTNode|null} Return null if the variable could not be found, ASTNode otherwise. ### findVariableByName = (context, name) -> variable = getVariable variablesInScope(context), name return null unless node = variable?.defs[0]?.node return node.right if node.type is 'TypeAlias' return node.init if node.init? return node.parent.right if ( node.declaration and node.parent.type is 'AssignmentExpression' ) if node.type is 'Identifier' and node.declaration return getDeclarationAssignmentAncestor(node)?.right null module.exports = { findVariable findVariableByName getVariable variablesInScope }
[ { "context": " client.authorize {app_id: '75165984', app_key: '3e05c797ef193fee452b1ddf19defa74'}, (response) ->\n if response.is_success\n ", "end": 1203, "score": 0.9997119307518005, "start": 1171, "tag": "KEY", "value": "3e05c797ef193fee452b1ddf19defa74" }, { "context": "\...
src/client.coffee
BigDtrade/3scale_ws_api_for_nodejs
0
https = require 'https' querystring = require 'qs' libxml = require 'libxmljs' VERSION = require('../package.json').version Response = require './response' AuthorizeResponse = require './authorize_response' ### 3Scale client API Parameter: provider_key {String} Required default_host {String} Optional Example: Client = require('3scale').Client client = new Client(provider_key, [default_host]) ### module.exports = class Client DEFAULT_HEADERS: { "X-3scale-User-Agent": "plugin-node-v#{VERSION}" } constructor: (provider_key, default_host = "su1.3scale.net") -> unless provider_key? throw new Error("missing provider_key") @provider_key = provider_key @host = default_host ### Authorize a application Parameters: options is a Hash object with the following fields app_id Required app_key Required referrer Optional usage Optional callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.authorize {app_id: '75165984', app_key: '3e05c797ef193fee452b1ddf19defa74'}, (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### authorize: (options, callback) -> _self = this result = null if (typeof options isnt 'object') || (options.app_id is undefined) throw "missing app_id" url = "/transactions/authorize.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authorize] Server Error Code: #{response.statusCode}" request.end() ### OAuthorize an Application Parameters: options is a Hash object with the following fields app_id Required service_id Optional (In case of mmultiple services) callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.oauth_authorize {app_id: '75165984', (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### oauth_authorize: (options, callback) -> _self = this if (typeof options isnt 'object')|| (options.app_id is undefined) throw "missing app_id" url = "/transactions/oauth_authorize.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::oauth_authorize] Server Error Code: #{response.statusCode}" request.end() ### Authorize with user_key Parameters: options is a Hash object with the following fields user_key Required service_id Optional (In case of mmultiple services) callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.authorize_with_user_key {user_key: '123456', (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### authorize_with_user_key: (options, callback) -> _self = this if (typeof options isnt 'object') || (options.user_key is undefined) throw "missing user_key" url = "/transactions/authorize.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authorize_with_user_key] Server Error Code: #{response.statusCode}" request.end() ### Authorize and Report in single call options is a Hash object with the following fields app_id Required app_key, user_id, object, usage, no-body, service_id Optional callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.authrep {app_id: '75165984', (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### authrep: (options, callback) -> _self = this if (typeof options isnt 'object') || (options.app_id is undefined) throw "missing app_id" url = "/transactions/authrep.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authrep] Server Error Code: #{response.statusCode}" request.end() ### Authorize and Report with :user_key ### authrep_with_user_key: (options, callback) -> _self = this if (typeof options isnt 'object') || (options.user_key is undefined) throw "missing user_key" url = "/transactions/authrep.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authrep_with_user_key] Server Error Code: #{response.statusCode}" request.end() ### Report transaction(s). Parameters: service_id {String} Optional (required only if you have more than one service) trans {Array} each array element contain information of a transaction. That information is in a Hash in the form { app_id {String} Required usage {Hash} Required timestamp {String} any string parseable by the Data object } callback {Function} Function that recive the Response object which include a `is_success` method. Required Example: trans = [ { "app_id": "abc123", "usage": {"hits": 1}}, { "app_id": "abc123", "usage": {"hits": 1000}} ] client.report trans, (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### report: (service_id, trans, callback) -> _self = this if (typeof service_id is 'object') and (typeof trans is 'function') callback = trans trans = service_id service_id = undefined unless trans? throw new Error("no transactions to report") url = "/transactions.xml" params = {transactions: trans, provider_key: @provider_key} params.service_id = service_id if service_id query = querystring.stringify(params).replace(/\[/g, "%5B").replace(/\]/g, "%5D") req_opts = host: @host port: 443 path: url method: 'POST' headers: "host": @host "Content-Type": "application/x-www-form-urlencoded" "Content-Length": query.length req_opts.headers[key] = value for key, value of @DEFAULT_HEADERS request = https.request req_opts, (response) -> xml = "" response.on "data", (data) -> xml += data response.on 'end', () -> if response.statusCode == 202 response = new Response() response.success() callback response else if response.statusCode in [400...422] callback _self._build_error_response xml request.write query request.end() ### Signup Express Parameters: options {Array} each array element contain information of a transaction. That information is in a Hash in the form { org_name (required) Organization Name of the buyer account. username (required) Username of the admin user (on the new buyer account). email (required) Email of the admin user. password (required) Password of the admin user. account_plan_id (optional) id of the account plan - if not assigned default will be used instead. service_plan_id (optional) id of the service plan - if not assigned default will be used instead. application_plan_id (optional) id of the application plan (if not assigned default will be used instead. additional_fields (Additional fields have to be name and value. You can add as many as you want.) additional_field2 additional_field3 ... } callback {Function} Function that recive the Response object which include a `is_success` method. Required ### signup: (options, callback) -> _self = this url = "/admin/api/signup.xml" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url method: 'POST' headers: "host": @host "Content-Type": "application/x-www-form-urlencoded" "Content-Length": query.length req_opts.headers[key] = value for key, value of @DEFAULT_HEADERS request = https.request req_opts, (response) -> xml = "" response.on "data", (data) -> xml += data response.on 'end', () -> if response.statusCode == 201 callback xml else callback _self._build_error_response xml request.write query request.end() # privates methods _build_success_authorize_response: (xml) -> response = new AuthorizeResponse() doc = libxml.parseXml xml authorize = doc.get('//authorized').text() plan = doc.get('//plan').text() if authorize is 'true' response.success() else reason = doc.get('//reason').text() response.error(reason) usage_reports = doc.get '//usage_reports' if usage_reports for index, usage_report of usage_reports.childNodes() do (usage_report) -> report = period: usage_report.attr('period').value() metric: usage_report.attr('metric').value() period_start: if @period is not 'eternity' then usage_report.get('period_start').text() period_end: if @period is not 'eternity' then usage_report.get('period_end').text() current_value: usage_report.get('current_value').text() max_value: usage_report.get('max_value').text() response.add_usage_reports report response _build_error_response: (xml) -> response = new AuthorizeResponse() doc = libxml.parseXml xml error = doc.get '/error' response = new Response() response.error error.text(), error.attr('code').value() response
225842
https = require 'https' querystring = require 'qs' libxml = require 'libxmljs' VERSION = require('../package.json').version Response = require './response' AuthorizeResponse = require './authorize_response' ### 3Scale client API Parameter: provider_key {String} Required default_host {String} Optional Example: Client = require('3scale').Client client = new Client(provider_key, [default_host]) ### module.exports = class Client DEFAULT_HEADERS: { "X-3scale-User-Agent": "plugin-node-v#{VERSION}" } constructor: (provider_key, default_host = "su1.3scale.net") -> unless provider_key? throw new Error("missing provider_key") @provider_key = provider_key @host = default_host ### Authorize a application Parameters: options is a Hash object with the following fields app_id Required app_key Required referrer Optional usage Optional callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.authorize {app_id: '75165984', app_key: '<KEY>'}, (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### authorize: (options, callback) -> _self = this result = null if (typeof options isnt 'object') || (options.app_id is undefined) throw "missing app_id" url = "/transactions/authorize.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authorize] Server Error Code: #{response.statusCode}" request.end() ### OAuthorize an Application Parameters: options is a Hash object with the following fields app_id Required service_id Optional (In case of mmultiple services) callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.oauth_authorize {app_id: '75165984', (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### oauth_authorize: (options, callback) -> _self = this if (typeof options isnt 'object')|| (options.app_id is undefined) throw "missing app_id" url = "/transactions/oauth_authorize.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::oauth_authorize] Server Error Code: #{response.statusCode}" request.end() ### Authorize with user_key Parameters: options is a Hash object with the following fields user_key Required service_id Optional (In case of mmultiple services) callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.authorize_with_user_key {user_key: '<KEY>', (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### authorize_with_user_key: (options, callback) -> _self = this if (typeof options isnt 'object') || (options.user_key is undefined) throw "missing user_key" url = "/transactions/authorize.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authorize_with_user_key] Server Error Code: #{response.statusCode}" request.end() ### Authorize and Report in single call options is a Hash object with the following fields app_id Required app_key, user_id, object, usage, no-body, service_id Optional callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.authrep {app_id: '75165984', (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### authrep: (options, callback) -> _self = this if (typeof options isnt 'object') || (options.app_id is undefined) throw "missing app_id" url = "/transactions/authrep.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authrep] Server Error Code: #{response.statusCode}" request.end() ### Authorize and Report with :user_key ### authrep_with_user_key: (options, callback) -> _self = this if (typeof options isnt 'object') || (options.user_key is undefined) throw "missing user_key" url = "/transactions/authrep.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authrep_with_user_key] Server Error Code: #{response.statusCode}" request.end() ### Report transaction(s). Parameters: service_id {String} Optional (required only if you have more than one service) trans {Array} each array element contain information of a transaction. That information is in a Hash in the form { app_id {String} Required usage {Hash} Required timestamp {String} any string parseable by the Data object } callback {Function} Function that recive the Response object which include a `is_success` method. Required Example: trans = [ { "app_id": "abc123", "usage": {"hits": 1}}, { "app_id": "abc123", "usage": {"hits": 1000}} ] client.report trans, (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### report: (service_id, trans, callback) -> _self = this if (typeof service_id is 'object') and (typeof trans is 'function') callback = trans trans = service_id service_id = undefined unless trans? throw new Error("no transactions to report") url = "/transactions.xml" params = {transactions: trans, provider_key: @provider_key} params.service_id = service_id if service_id query = querystring.stringify(params).replace(/\[/g, "%5B").replace(/\]/g, "%5D") req_opts = host: @host port: 443 path: url method: 'POST' headers: "host": @host "Content-Type": "application/x-www-form-urlencoded" "Content-Length": query.length req_opts.headers[key] = value for key, value of @DEFAULT_HEADERS request = https.request req_opts, (response) -> xml = "" response.on "data", (data) -> xml += data response.on 'end', () -> if response.statusCode == 202 response = new Response() response.success() callback response else if response.statusCode in [400...422] callback _self._build_error_response xml request.write query request.end() ### Signup Express Parameters: options {Array} each array element contain information of a transaction. That information is in a Hash in the form { org_name (required) Organization Name of the buyer account. username (required) Username of the admin user (on the new buyer account). email (required) Email of the admin user. password (required) <PASSWORD> of the <PASSWORD>. account_plan_id (optional) id of the account plan - if not assigned default will be used instead. service_plan_id (optional) id of the service plan - if not assigned default will be used instead. application_plan_id (optional) id of the application plan (if not assigned default will be used instead. additional_fields (Additional fields have to be name and value. You can add as many as you want.) additional_field2 additional_field3 ... } callback {Function} Function that recive the Response object which include a `is_success` method. Required ### signup: (options, callback) -> _self = this url = "/admin/api/signup.xml" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url method: 'POST' headers: "host": @host "Content-Type": "application/x-www-form-urlencoded" "Content-Length": query.length req_opts.headers[key] = value for key, value of @DEFAULT_HEADERS request = https.request req_opts, (response) -> xml = "" response.on "data", (data) -> xml += data response.on 'end', () -> if response.statusCode == 201 callback xml else callback _self._build_error_response xml request.write query request.end() # privates methods _build_success_authorize_response: (xml) -> response = new AuthorizeResponse() doc = libxml.parseXml xml authorize = doc.get('//authorized').text() plan = doc.get('//plan').text() if authorize is 'true' response.success() else reason = doc.get('//reason').text() response.error(reason) usage_reports = doc.get '//usage_reports' if usage_reports for index, usage_report of usage_reports.childNodes() do (usage_report) -> report = period: usage_report.attr('period').value() metric: usage_report.attr('metric').value() period_start: if @period is not 'eternity' then usage_report.get('period_start').text() period_end: if @period is not 'eternity' then usage_report.get('period_end').text() current_value: usage_report.get('current_value').text() max_value: usage_report.get('max_value').text() response.add_usage_reports report response _build_error_response: (xml) -> response = new AuthorizeResponse() doc = libxml.parseXml xml error = doc.get '/error' response = new Response() response.error error.text(), error.attr('code').value() response
true
https = require 'https' querystring = require 'qs' libxml = require 'libxmljs' VERSION = require('../package.json').version Response = require './response' AuthorizeResponse = require './authorize_response' ### 3Scale client API Parameter: provider_key {String} Required default_host {String} Optional Example: Client = require('3scale').Client client = new Client(provider_key, [default_host]) ### module.exports = class Client DEFAULT_HEADERS: { "X-3scale-User-Agent": "plugin-node-v#{VERSION}" } constructor: (provider_key, default_host = "su1.3scale.net") -> unless provider_key? throw new Error("missing provider_key") @provider_key = provider_key @host = default_host ### Authorize a application Parameters: options is a Hash object with the following fields app_id Required app_key Required referrer Optional usage Optional callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.authorize {app_id: '75165984', app_key: 'PI:KEY:<KEY>END_PI'}, (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### authorize: (options, callback) -> _self = this result = null if (typeof options isnt 'object') || (options.app_id is undefined) throw "missing app_id" url = "/transactions/authorize.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authorize] Server Error Code: #{response.statusCode}" request.end() ### OAuthorize an Application Parameters: options is a Hash object with the following fields app_id Required service_id Optional (In case of mmultiple services) callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.oauth_authorize {app_id: '75165984', (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### oauth_authorize: (options, callback) -> _self = this if (typeof options isnt 'object')|| (options.app_id is undefined) throw "missing app_id" url = "/transactions/oauth_authorize.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::oauth_authorize] Server Error Code: #{response.statusCode}" request.end() ### Authorize with user_key Parameters: options is a Hash object with the following fields user_key Required service_id Optional (In case of mmultiple services) callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.authorize_with_user_key {user_key: 'PI:KEY:<KEY>END_PI', (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### authorize_with_user_key: (options, callback) -> _self = this if (typeof options isnt 'object') || (options.user_key is undefined) throw "missing user_key" url = "/transactions/authorize.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authorize_with_user_key] Server Error Code: #{response.statusCode}" request.end() ### Authorize and Report in single call options is a Hash object with the following fields app_id Required app_key, user_id, object, usage, no-body, service_id Optional callback {Function} Is the callback function that receives the Response object which includes `is_success` method to determine the status of the response Example: client.authrep {app_id: '75165984', (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### authrep: (options, callback) -> _self = this if (typeof options isnt 'object') || (options.app_id is undefined) throw "missing app_id" url = "/transactions/authrep.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authrep] Server Error Code: #{response.statusCode}" request.end() ### Authorize and Report with :user_key ### authrep_with_user_key: (options, callback) -> _self = this if (typeof options isnt 'object') || (options.user_key is undefined) throw "missing user_key" url = "/transactions/authrep.xml?" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url + query method: 'GET' headers: @DEFAULT_HEADERS request = https.request req_opts, (response) -> response.setEncoding 'utf8' xml = "" response.on 'data', (chunk) -> xml += chunk response.on 'end', -> if response.statusCode == 200 || response.statusCode == 409 callback _self._build_success_authorize_response xml else if response.statusCode in [400...409] callback _self._build_error_response xml else throw "[Client::authrep_with_user_key] Server Error Code: #{response.statusCode}" request.end() ### Report transaction(s). Parameters: service_id {String} Optional (required only if you have more than one service) trans {Array} each array element contain information of a transaction. That information is in a Hash in the form { app_id {String} Required usage {Hash} Required timestamp {String} any string parseable by the Data object } callback {Function} Function that recive the Response object which include a `is_success` method. Required Example: trans = [ { "app_id": "abc123", "usage": {"hits": 1}}, { "app_id": "abc123", "usage": {"hits": 1000}} ] client.report trans, (response) -> if response.is_success # All Ok else sys.puts "#{response.error_message} with code: #{response.error_code}" ### report: (service_id, trans, callback) -> _self = this if (typeof service_id is 'object') and (typeof trans is 'function') callback = trans trans = service_id service_id = undefined unless trans? throw new Error("no transactions to report") url = "/transactions.xml" params = {transactions: trans, provider_key: @provider_key} params.service_id = service_id if service_id query = querystring.stringify(params).replace(/\[/g, "%5B").replace(/\]/g, "%5D") req_opts = host: @host port: 443 path: url method: 'POST' headers: "host": @host "Content-Type": "application/x-www-form-urlencoded" "Content-Length": query.length req_opts.headers[key] = value for key, value of @DEFAULT_HEADERS request = https.request req_opts, (response) -> xml = "" response.on "data", (data) -> xml += data response.on 'end', () -> if response.statusCode == 202 response = new Response() response.success() callback response else if response.statusCode in [400...422] callback _self._build_error_response xml request.write query request.end() ### Signup Express Parameters: options {Array} each array element contain information of a transaction. That information is in a Hash in the form { org_name (required) Organization Name of the buyer account. username (required) Username of the admin user (on the new buyer account). email (required) Email of the admin user. password (required) PI:PASSWORD:<PASSWORD>END_PI of the PI:PASSWORD:<PASSWORD>END_PI. account_plan_id (optional) id of the account plan - if not assigned default will be used instead. service_plan_id (optional) id of the service plan - if not assigned default will be used instead. application_plan_id (optional) id of the application plan (if not assigned default will be used instead. additional_fields (Additional fields have to be name and value. You can add as many as you want.) additional_field2 additional_field3 ... } callback {Function} Function that recive the Response object which include a `is_success` method. Required ### signup: (options, callback) -> _self = this url = "/admin/api/signup.xml" query = querystring.stringify options query += '&' + querystring.stringify {provider_key: @provider_key} req_opts = host: @host port: 443 path: url method: 'POST' headers: "host": @host "Content-Type": "application/x-www-form-urlencoded" "Content-Length": query.length req_opts.headers[key] = value for key, value of @DEFAULT_HEADERS request = https.request req_opts, (response) -> xml = "" response.on "data", (data) -> xml += data response.on 'end', () -> if response.statusCode == 201 callback xml else callback _self._build_error_response xml request.write query request.end() # privates methods _build_success_authorize_response: (xml) -> response = new AuthorizeResponse() doc = libxml.parseXml xml authorize = doc.get('//authorized').text() plan = doc.get('//plan').text() if authorize is 'true' response.success() else reason = doc.get('//reason').text() response.error(reason) usage_reports = doc.get '//usage_reports' if usage_reports for index, usage_report of usage_reports.childNodes() do (usage_report) -> report = period: usage_report.attr('period').value() metric: usage_report.attr('metric').value() period_start: if @period is not 'eternity' then usage_report.get('period_start').text() period_end: if @period is not 'eternity' then usage_report.get('period_end').text() current_value: usage_report.get('current_value').text() max_value: usage_report.get('max_value').text() response.add_usage_reports report response _build_error_response: (xml) -> response = new AuthorizeResponse() doc = libxml.parseXml xml error = doc.get '/error' response = new Response() response.error error.text(), error.attr('code').value() response
[ { "context": "unction f\n f\n else if isFieldKey(f) \n key = toFieldKey(f)\n (value) ->\n fieldValue = valu", "end": 17482, "score": 0.5730386972427368, "start": 17480, "tag": "KEY", "value": "to" } ]
src/Bacon.coffee
pihvi/bacon.js
0
(this.jQuery || this.Zepto)?.fn.asEventStream = (eventName) -> element = this new EventStream (sink) -> handler = (event) -> reply = sink (next event) if (reply == Bacon.noMore) unbind() unbind = -> element.unbind(eventName, handler) element.bind(eventName, handler) unbind Bacon = @Bacon = { taste : "delicious" } Bacon.fromPromise = (promise) -> new Bacon.EventStream( (sink) -> onSuccess = (value) -> sink (new Next value) sink (new End) onError = (e) -> sink (new Error e) sink (new End) promise.then(onSuccess, onError) nop ) Bacon.noMore = "veggies" Bacon.more = "moar bacon!" Bacon.never = => new EventStream (sink) => => nop Bacon.later = (delay, value) -> Bacon.sequentially(delay, [value]) Bacon.sequentially = (delay, values) -> Bacon.repeatedly(delay, values).take(filter(((e) -> e.hasValue()), map(toEvent, values)).length) Bacon.repeatedly = (delay, values) -> index = -1 poll = -> index++ toEvent values[index % values.length] Bacon.fromPoll(delay, poll) Bacon.fromPoll = (delay, poll) -> new EventStream (sink) -> id = undefined handler = -> value = poll() reply = sink value if (reply == Bacon.noMore or value.isEnd()) unbind() unbind = -> clearInterval id id = setInterval(handler, delay) unbind # Wrap DOM EventTarget or Node EventEmitter as EventStream # # target - EventTarget or EventEmitter, source of events # eventName - event name to bind # # Examples # # Bacon.fromEventTarget(document.body, "click") # # => EventStream # # Bacon.fromEventTarget (new EventEmitter(), "data") # # => EventStream # # Returns EventStream Bacon.fromEventTarget = (target, eventName) -> new EventStream (sink) -> handler = (event) -> reply = sink (next event) if reply == Bacon.noMore unbind() if target.addEventListener unbind = -> target.removeEventListener(eventName, handler, false) target.addEventListener(eventName, handler, false) else unbind = -> target.removeListener(eventName, handler) target.addListener(eventName, handler) unbind Bacon.interval = (delay, value) -> value = {} unless value? poll = -> next(value) Bacon.fromPoll(delay, poll) Bacon.constant = (value) -> new Property (sink) -> sink(initial(value)) sink(end()) nop Bacon.combineAll = (streams, f) -> assertArray streams stream = head streams for next in (tail streams) stream = f(stream, next) stream Bacon.mergeAll = (streams) -> Bacon.combineAll(streams, (s1, s2) -> s1.merge(s2)) Bacon.combineAsArray = (streams) -> toArray = (x) -> if x? then (if (x instanceof Array) then x else [x]) else [] concatArrays = (a1, a2) -> toArray(a1).concat(toArray(a2)) Bacon.combineAll(streams, (s1, s2) -> s1.toProperty().combine(s2, concatArrays)) Bacon.combineWith = (streams, f) -> Bacon.combineAll(streams, (s1, s2) -> s1.toProperty().combine(s2, f)) Bacon.latestValue = (src) -> latest = undefined src.subscribe (event) -> latest = event.value if event.hasValue() => latest class Event isEvent: -> true isEnd: -> false isInitial: -> false isNext: -> false isError: -> false hasValue: -> false filter: (f) -> true getOriginalEvent: -> if @sourceEvent? @sourceEvent.getOriginalEvent() else this onDone : (listener) -> listener() class Next extends Event constructor: (@value, sourceEvent) -> isNext: -> true hasValue: -> true fmap: (f) -> @apply(f(this.value)) apply: (value) -> next(value, @getOriginalEvent()) filter: (f) -> f(@value) class Initial extends Next isInitial: -> true isNext: -> false apply: (value) -> initial(value, @getOriginalEvent()) class End extends Event isEnd: -> true fmap: -> this apply: -> this class Error extends Event constructor: (@error) -> isError: -> true fmap: -> this apply: -> this class Observable onValue: (f) -> @subscribe (event) -> f event.value if event.hasValue() onError: (f) -> @subscribe (event) -> f event.error if event.isError() onEnd: (f) -> @subscribe (event) -> f() if event.isEnd() errors: -> @filter(-> false) filter: (f) -> f = toExtractor(f) @withHandler (event) -> if event.filter(f) @push event else Bacon.more takeWhile: (f) -> f = toExtractor(f) @withHandler (event) -> if event.filter(f) @push event else @push end() Bacon.noMore endOnError: -> @withHandler (event) -> if event.isError() @push event @push end() else @push event take: (count) -> assert "take: count must >= 1", (count>=1) @withHandler (event) -> if !event.hasValue() @push event else if (count == 1) @push event @push end() Bacon.noMore else count-- @push event map: (f) -> f = toExtractor(f) @withHandler (event) -> @push event.fmap(f) mapError : (f) -> f = toExtractor(f) @withHandler (event) -> if event.isError() @push next (f event.error) else @push event do: (f) -> f = toExtractor(f) @withHandler (event) -> f(event.value) if event.hasValue() @push event takeUntil: (stopper) => src = this @withSubscribe (sink) -> unsubscribed = false unsubSrc = nop unsubStopper = nop unsubBoth = -> unsubSrc() ; unsubStopper() ; unsubscribed = true srcSink = (event) -> if event.isEnd() unsubStopper() sink event Bacon.noMore else event.getOriginalEvent().onDone -> if !unsubscribed reply = sink event if reply == Bacon.noMore unsubBoth() Bacon.more stopperSink = (event) -> if event.isError() Bacon.more else if event.isEnd() Bacon.noMore else unsubSrc() sink end() Bacon.noMore unsubSrc = src.subscribe(srcSink) unsubStopper = stopper.subscribe(stopperSink) unless unsubscribed unsubBoth skip : (count) -> assert "skip: count must >= 0", (count>=0) @withHandler (event) -> if !event.hasValue() @push event else if (count > 0) count-- Bacon.more else @push event distinctUntilChanged: -> @skipDuplicates() skipDuplicates: -> @withStateMachine undefined, (prev, event) -> if !event.hasValue() [prev, [event]] else if prev isnt event.value [event.value, [event]] else [prev, []] withStateMachine: (initState, f) -> state = initState @withHandler (event) -> fromF = f(state, event) assertArray fromF [newState, outputs] = fromF assertArray outputs state = newState reply = Bacon.more for output in outputs reply = @push output if reply == Bacon.noMore return reply reply class EventStream extends Observable constructor: (subscribe) -> assertFunction subscribe dispatcher = new Dispatcher(subscribe) @subscribe = dispatcher.subscribe @hasSubscribers = dispatcher.hasSubscribers flatMap: (f) -> root = this new EventStream (sink) -> children = [] rootEnd = false unsubRoot = -> unbind = -> unsubRoot() for unsubChild in children unsubChild() children = [] checkEnd = -> if rootEnd and (children.length == 0) sink end() spawner = (event) -> if event.isEnd() rootEnd = true checkEnd() else if event.isError() sink event else child = f event.value unsubChild = undefined removeChild = -> remove(unsubChild, children) if unsubChild? checkEnd() handler = (event) -> if event.isEnd() removeChild() Bacon.noMore else reply = sink event if reply == Bacon.noMore unbind() reply unsubChild = child.subscribe handler children.push unsubChild unsubRoot = root.subscribe(spawner) unbind switch: (f) => @flatMap (value) => f(value).takeUntil(this) delay: (delay) -> @flatMap (value) -> Bacon.later delay, value throttle: (delay) -> @switch (value) -> Bacon.later delay, value bufferWithTime: (delay) -> values = [] storeAndMaybeTrigger = (value) -> values.push value values.length == 1 flush = -> output = values values = [] output buffer = -> Bacon.later(delay).map(flush) @filter(storeAndMaybeTrigger).flatMap(buffer) bufferWithCount: (count) -> values = [] @withHandler (event) -> flush = => @push next(values, event) values = [] if event.isError() @push event else if event.isEnd() flush() @push event else values.push(event.value) flush() if values.length == count merge: (right) -> left = this new EventStream (sink) -> unsubLeft = nop unsubRight = nop unsubscribed = false unsubBoth = -> unsubLeft() ; unsubRight() ; unsubscribed = true ends = 0 smartSink = (event) -> if event.isEnd() ends++ if ends == 2 sink end() else Bacon.more else reply = sink event unsubBoth() if reply == Bacon.noMore reply unsubLeft = left.subscribe(smartSink) unsubRight = right.subscribe(smartSink) unless unsubscribed unsubBoth toProperty: (initValue) -> @scan(initValue, latter) scan: (seed, f) -> f = toCombinator(f) acc = seed handleEvent = (event) -> acc = f(acc, event.value) if event.hasValue() @push event.apply(acc) d = new Dispatcher(@subscribe, handleEvent) subscribe = (sink) -> reply = sink initial(acc) if acc? d.subscribe(sink) unless reply == Bacon.noMore new Property(subscribe) decorateWith: (label, property) -> property.sampledBy(this, (propertyValue, streamValue) -> result = cloneObject(streamValue) result[label] = propertyValue result ) mapEnd : (f) -> f = toExtractor(f) @withHandler (event) -> if (event.isEnd()) @push next(f(event)) @push end() Bacon.noMore else @push event withHandler: (handler) -> dispatcher = new Dispatcher(@subscribe, handler) new EventStream(dispatcher.subscribe) withSubscribe: (subscribe) -> new EventStream(subscribe) class Property extends Observable constructor: (@subscribe) -> combine = (other, leftSink, rightSink) => myVal = undefined otherVal = undefined new Property (sink) => unsubscribed = false unsubMe = nop unsubOther = nop unsubBoth = -> unsubMe() ; unsubOther() ; unsubscribed = true myEnd = false otherEnd = false checkEnd = -> if myEnd and otherEnd reply = sink end() unsubBoth() if reply == Bacon.noMore reply initialSent = false combiningSink = (markEnd, setValue, thisSink) => (event) => if (event.isEnd()) markEnd() checkEnd() Bacon.noMore else if event.isError() reply = sink event unsubBoth if reply == Bacon.noMore reply else setValue(event.value) if (myVal? and otherVal?) if initialSent and event.isInitial() # don't send duplicate Initial Bacon.more else initialSent = true reply = thisSink(sink, event, myVal, otherVal) unsubBoth if reply == Bacon.noMore reply else Bacon.more mySink = combiningSink (-> myEnd = true), ((value) -> myVal = value), leftSink otherSink = combiningSink (-> otherEnd = true), ((value) -> otherVal = value), rightSink unsubMe = this.subscribe mySink unsubOther = other.subscribe otherSink unless unsubscribed unsubBoth @combine = (other, f) => combinator = toCombinator(f) combineAndPush = (sink, event, myVal, otherVal) -> sink(event.apply(combinator(myVal, otherVal))) combine(other, combineAndPush, combineAndPush) @sampledBy = (sampler, combinator = former) => pushPropertyValue = (sink, event, propertyVal, streamVal) -> sink(event.apply(combinator(propertyVal, streamVal))) combine(sampler, nop, pushPropertyValue).changes().takeUntil(sampler.filter(false).mapEnd()) sample: (interval) => @sampledBy Bacon.interval(interval, {}) changes: => new EventStream (sink) => @subscribe (event) => sink event unless event.isInitial() withHandler: (handler) -> new Property(new PropertyDispatcher(@subscribe, handler).subscribe) withSubscribe: (subscribe) -> new Property(new PropertyDispatcher(subscribe).subscribe) toProperty: => this class Dispatcher constructor: (subscribe, handleEvent) -> subscribe ?= -> nop sinks = [] @hasSubscribers = -> sinks.length > 0 unsubscribeFromSource = nop removeSink = (sink) -> remove(sink, sinks) @push = (event) => waiters = undefined done = -> if waiters? ws = waiters waiters = undefined w() for w in ws event.onDone = Event.prototype.onDone event.onDone = (listener) -> if waiters? and not contains(waiters, listener) waiters.push(listener) else waiters = [listener] assertEvent event for sink in (cloneArray(sinks)) reply = sink event removeSink sink if reply == Bacon.noMore or event.isEnd() done() if @hasSubscribers() then Bacon.more else Bacon.noMore handleEvent ?= (event) -> @push event @handleEvent = (event) => assertEvent event handleEvent.apply(this, [event]) @subscribe = (sink) => assertFunction sink sinks.push(sink) if sinks.length == 1 unsubscribeFromSource = subscribe @handleEvent assertFunction unsubscribeFromSource => removeSink sink unsubscribeFromSource() unless @hasSubscribers() class PropertyDispatcher extends Dispatcher constructor: (subscribe, handleEvent) -> super(subscribe, handleEvent) current = undefined push = @push subscribe = @subscribe @push = (event) => if event.hasValue() current = event.value push.apply(this, [event]) @subscribe = (sink) => if @hasSubscribers() and current? reply = sink initial(current) if reply == Bacon.noMore return nop subscribe.apply(this, [sink]) class Bus extends EventStream constructor: -> sink = undefined unsubFuncs = [] inputs = [] guardedSink = (input) => (event) => if (event.isEnd()) remove(input, inputs) Bacon.noMore else sink event unsubAll = => f() for f in unsubFuncs unsubFuncs = [] subscribeAll = (newSink) => sink = newSink unsubFuncs = [] for input in inputs unsubFuncs.push(input.subscribe(guardedSink(input))) unsubAll dispatcher = new Dispatcher(subscribeAll) subscribeThis = (sink) => dispatcher.subscribe(sink) super(subscribeThis) @plug = (inputStream) => inputs.push(inputStream) if (sink?) unsubFuncs.push(inputStream.subscribe(guardedSink(inputStream))) @push = (value) => sink next(value) if sink? @error = (error) => sink new Error(error) if sink? @end = => unsubAll() sink end() if sink? Bacon.EventStream = EventStream Bacon.Property = Property Bacon.Bus = Bus Bacon.Initial = Initial Bacon.Next = Next Bacon.End = End Bacon.Error = Error nop = -> latter = (_, x) -> x former = (x, _) -> x initial = (value) -> new Initial(value) next = (value) -> new Next(value) end = -> new End() isEvent = (x) -> x? and x.isEvent? and x.isEvent() toEvent = (x) -> if isEvent x x else next x empty = (xs) -> xs.length == 0 head = (xs) -> xs[0] tail = (xs) -> xs[1...xs.length] filter = (f, xs) -> filtered = [] for x in xs filtered.push(x) if f(x) filtered map = (f, xs) -> f(x) for x in xs cloneArray = (xs) -> xs.slice(0) cloneObject = (src) -> clone = {} for key, value of src clone[key] = value clone remove = (x, xs) -> i = xs.indexOf(x) if i >= 0 xs.splice(i, 1) contains = (xs, x) -> xs.indexOf(x) >= 0 assert = (message, condition) -> throw message unless condition assertEvent = (event) -> assert "not an event : " + event, event.isEvent? ; assert "not event", event.isEvent() assertFunction = (f) -> assert "not a function : " + f, isFunction(f) isFunction = (f) -> typeof f == "function" assertArray = (xs) -> assert "not an array : " + xs, xs instanceof Array always = (x) -> (-> x) toExtractor = (f) -> if isFunction f f else if isFieldKey(f) key = toFieldKey(f) (value) -> fieldValue = value[key] if isFunction(fieldValue) value[key]() else fieldValue else always f isFieldKey = (f) -> (typeof f == "string") and f.length > 1 and f[0] == "." toFieldKey = (f) -> f.slice(1) toCombinator = (f) -> if isFunction f f else if isFieldKey f key = toFieldKey(f) (left, right) -> left[key](right) else assert "not a function or a field key: " + f, false
106126
(this.jQuery || this.Zepto)?.fn.asEventStream = (eventName) -> element = this new EventStream (sink) -> handler = (event) -> reply = sink (next event) if (reply == Bacon.noMore) unbind() unbind = -> element.unbind(eventName, handler) element.bind(eventName, handler) unbind Bacon = @Bacon = { taste : "delicious" } Bacon.fromPromise = (promise) -> new Bacon.EventStream( (sink) -> onSuccess = (value) -> sink (new Next value) sink (new End) onError = (e) -> sink (new Error e) sink (new End) promise.then(onSuccess, onError) nop ) Bacon.noMore = "veggies" Bacon.more = "moar bacon!" Bacon.never = => new EventStream (sink) => => nop Bacon.later = (delay, value) -> Bacon.sequentially(delay, [value]) Bacon.sequentially = (delay, values) -> Bacon.repeatedly(delay, values).take(filter(((e) -> e.hasValue()), map(toEvent, values)).length) Bacon.repeatedly = (delay, values) -> index = -1 poll = -> index++ toEvent values[index % values.length] Bacon.fromPoll(delay, poll) Bacon.fromPoll = (delay, poll) -> new EventStream (sink) -> id = undefined handler = -> value = poll() reply = sink value if (reply == Bacon.noMore or value.isEnd()) unbind() unbind = -> clearInterval id id = setInterval(handler, delay) unbind # Wrap DOM EventTarget or Node EventEmitter as EventStream # # target - EventTarget or EventEmitter, source of events # eventName - event name to bind # # Examples # # Bacon.fromEventTarget(document.body, "click") # # => EventStream # # Bacon.fromEventTarget (new EventEmitter(), "data") # # => EventStream # # Returns EventStream Bacon.fromEventTarget = (target, eventName) -> new EventStream (sink) -> handler = (event) -> reply = sink (next event) if reply == Bacon.noMore unbind() if target.addEventListener unbind = -> target.removeEventListener(eventName, handler, false) target.addEventListener(eventName, handler, false) else unbind = -> target.removeListener(eventName, handler) target.addListener(eventName, handler) unbind Bacon.interval = (delay, value) -> value = {} unless value? poll = -> next(value) Bacon.fromPoll(delay, poll) Bacon.constant = (value) -> new Property (sink) -> sink(initial(value)) sink(end()) nop Bacon.combineAll = (streams, f) -> assertArray streams stream = head streams for next in (tail streams) stream = f(stream, next) stream Bacon.mergeAll = (streams) -> Bacon.combineAll(streams, (s1, s2) -> s1.merge(s2)) Bacon.combineAsArray = (streams) -> toArray = (x) -> if x? then (if (x instanceof Array) then x else [x]) else [] concatArrays = (a1, a2) -> toArray(a1).concat(toArray(a2)) Bacon.combineAll(streams, (s1, s2) -> s1.toProperty().combine(s2, concatArrays)) Bacon.combineWith = (streams, f) -> Bacon.combineAll(streams, (s1, s2) -> s1.toProperty().combine(s2, f)) Bacon.latestValue = (src) -> latest = undefined src.subscribe (event) -> latest = event.value if event.hasValue() => latest class Event isEvent: -> true isEnd: -> false isInitial: -> false isNext: -> false isError: -> false hasValue: -> false filter: (f) -> true getOriginalEvent: -> if @sourceEvent? @sourceEvent.getOriginalEvent() else this onDone : (listener) -> listener() class Next extends Event constructor: (@value, sourceEvent) -> isNext: -> true hasValue: -> true fmap: (f) -> @apply(f(this.value)) apply: (value) -> next(value, @getOriginalEvent()) filter: (f) -> f(@value) class Initial extends Next isInitial: -> true isNext: -> false apply: (value) -> initial(value, @getOriginalEvent()) class End extends Event isEnd: -> true fmap: -> this apply: -> this class Error extends Event constructor: (@error) -> isError: -> true fmap: -> this apply: -> this class Observable onValue: (f) -> @subscribe (event) -> f event.value if event.hasValue() onError: (f) -> @subscribe (event) -> f event.error if event.isError() onEnd: (f) -> @subscribe (event) -> f() if event.isEnd() errors: -> @filter(-> false) filter: (f) -> f = toExtractor(f) @withHandler (event) -> if event.filter(f) @push event else Bacon.more takeWhile: (f) -> f = toExtractor(f) @withHandler (event) -> if event.filter(f) @push event else @push end() Bacon.noMore endOnError: -> @withHandler (event) -> if event.isError() @push event @push end() else @push event take: (count) -> assert "take: count must >= 1", (count>=1) @withHandler (event) -> if !event.hasValue() @push event else if (count == 1) @push event @push end() Bacon.noMore else count-- @push event map: (f) -> f = toExtractor(f) @withHandler (event) -> @push event.fmap(f) mapError : (f) -> f = toExtractor(f) @withHandler (event) -> if event.isError() @push next (f event.error) else @push event do: (f) -> f = toExtractor(f) @withHandler (event) -> f(event.value) if event.hasValue() @push event takeUntil: (stopper) => src = this @withSubscribe (sink) -> unsubscribed = false unsubSrc = nop unsubStopper = nop unsubBoth = -> unsubSrc() ; unsubStopper() ; unsubscribed = true srcSink = (event) -> if event.isEnd() unsubStopper() sink event Bacon.noMore else event.getOriginalEvent().onDone -> if !unsubscribed reply = sink event if reply == Bacon.noMore unsubBoth() Bacon.more stopperSink = (event) -> if event.isError() Bacon.more else if event.isEnd() Bacon.noMore else unsubSrc() sink end() Bacon.noMore unsubSrc = src.subscribe(srcSink) unsubStopper = stopper.subscribe(stopperSink) unless unsubscribed unsubBoth skip : (count) -> assert "skip: count must >= 0", (count>=0) @withHandler (event) -> if !event.hasValue() @push event else if (count > 0) count-- Bacon.more else @push event distinctUntilChanged: -> @skipDuplicates() skipDuplicates: -> @withStateMachine undefined, (prev, event) -> if !event.hasValue() [prev, [event]] else if prev isnt event.value [event.value, [event]] else [prev, []] withStateMachine: (initState, f) -> state = initState @withHandler (event) -> fromF = f(state, event) assertArray fromF [newState, outputs] = fromF assertArray outputs state = newState reply = Bacon.more for output in outputs reply = @push output if reply == Bacon.noMore return reply reply class EventStream extends Observable constructor: (subscribe) -> assertFunction subscribe dispatcher = new Dispatcher(subscribe) @subscribe = dispatcher.subscribe @hasSubscribers = dispatcher.hasSubscribers flatMap: (f) -> root = this new EventStream (sink) -> children = [] rootEnd = false unsubRoot = -> unbind = -> unsubRoot() for unsubChild in children unsubChild() children = [] checkEnd = -> if rootEnd and (children.length == 0) sink end() spawner = (event) -> if event.isEnd() rootEnd = true checkEnd() else if event.isError() sink event else child = f event.value unsubChild = undefined removeChild = -> remove(unsubChild, children) if unsubChild? checkEnd() handler = (event) -> if event.isEnd() removeChild() Bacon.noMore else reply = sink event if reply == Bacon.noMore unbind() reply unsubChild = child.subscribe handler children.push unsubChild unsubRoot = root.subscribe(spawner) unbind switch: (f) => @flatMap (value) => f(value).takeUntil(this) delay: (delay) -> @flatMap (value) -> Bacon.later delay, value throttle: (delay) -> @switch (value) -> Bacon.later delay, value bufferWithTime: (delay) -> values = [] storeAndMaybeTrigger = (value) -> values.push value values.length == 1 flush = -> output = values values = [] output buffer = -> Bacon.later(delay).map(flush) @filter(storeAndMaybeTrigger).flatMap(buffer) bufferWithCount: (count) -> values = [] @withHandler (event) -> flush = => @push next(values, event) values = [] if event.isError() @push event else if event.isEnd() flush() @push event else values.push(event.value) flush() if values.length == count merge: (right) -> left = this new EventStream (sink) -> unsubLeft = nop unsubRight = nop unsubscribed = false unsubBoth = -> unsubLeft() ; unsubRight() ; unsubscribed = true ends = 0 smartSink = (event) -> if event.isEnd() ends++ if ends == 2 sink end() else Bacon.more else reply = sink event unsubBoth() if reply == Bacon.noMore reply unsubLeft = left.subscribe(smartSink) unsubRight = right.subscribe(smartSink) unless unsubscribed unsubBoth toProperty: (initValue) -> @scan(initValue, latter) scan: (seed, f) -> f = toCombinator(f) acc = seed handleEvent = (event) -> acc = f(acc, event.value) if event.hasValue() @push event.apply(acc) d = new Dispatcher(@subscribe, handleEvent) subscribe = (sink) -> reply = sink initial(acc) if acc? d.subscribe(sink) unless reply == Bacon.noMore new Property(subscribe) decorateWith: (label, property) -> property.sampledBy(this, (propertyValue, streamValue) -> result = cloneObject(streamValue) result[label] = propertyValue result ) mapEnd : (f) -> f = toExtractor(f) @withHandler (event) -> if (event.isEnd()) @push next(f(event)) @push end() Bacon.noMore else @push event withHandler: (handler) -> dispatcher = new Dispatcher(@subscribe, handler) new EventStream(dispatcher.subscribe) withSubscribe: (subscribe) -> new EventStream(subscribe) class Property extends Observable constructor: (@subscribe) -> combine = (other, leftSink, rightSink) => myVal = undefined otherVal = undefined new Property (sink) => unsubscribed = false unsubMe = nop unsubOther = nop unsubBoth = -> unsubMe() ; unsubOther() ; unsubscribed = true myEnd = false otherEnd = false checkEnd = -> if myEnd and otherEnd reply = sink end() unsubBoth() if reply == Bacon.noMore reply initialSent = false combiningSink = (markEnd, setValue, thisSink) => (event) => if (event.isEnd()) markEnd() checkEnd() Bacon.noMore else if event.isError() reply = sink event unsubBoth if reply == Bacon.noMore reply else setValue(event.value) if (myVal? and otherVal?) if initialSent and event.isInitial() # don't send duplicate Initial Bacon.more else initialSent = true reply = thisSink(sink, event, myVal, otherVal) unsubBoth if reply == Bacon.noMore reply else Bacon.more mySink = combiningSink (-> myEnd = true), ((value) -> myVal = value), leftSink otherSink = combiningSink (-> otherEnd = true), ((value) -> otherVal = value), rightSink unsubMe = this.subscribe mySink unsubOther = other.subscribe otherSink unless unsubscribed unsubBoth @combine = (other, f) => combinator = toCombinator(f) combineAndPush = (sink, event, myVal, otherVal) -> sink(event.apply(combinator(myVal, otherVal))) combine(other, combineAndPush, combineAndPush) @sampledBy = (sampler, combinator = former) => pushPropertyValue = (sink, event, propertyVal, streamVal) -> sink(event.apply(combinator(propertyVal, streamVal))) combine(sampler, nop, pushPropertyValue).changes().takeUntil(sampler.filter(false).mapEnd()) sample: (interval) => @sampledBy Bacon.interval(interval, {}) changes: => new EventStream (sink) => @subscribe (event) => sink event unless event.isInitial() withHandler: (handler) -> new Property(new PropertyDispatcher(@subscribe, handler).subscribe) withSubscribe: (subscribe) -> new Property(new PropertyDispatcher(subscribe).subscribe) toProperty: => this class Dispatcher constructor: (subscribe, handleEvent) -> subscribe ?= -> nop sinks = [] @hasSubscribers = -> sinks.length > 0 unsubscribeFromSource = nop removeSink = (sink) -> remove(sink, sinks) @push = (event) => waiters = undefined done = -> if waiters? ws = waiters waiters = undefined w() for w in ws event.onDone = Event.prototype.onDone event.onDone = (listener) -> if waiters? and not contains(waiters, listener) waiters.push(listener) else waiters = [listener] assertEvent event for sink in (cloneArray(sinks)) reply = sink event removeSink sink if reply == Bacon.noMore or event.isEnd() done() if @hasSubscribers() then Bacon.more else Bacon.noMore handleEvent ?= (event) -> @push event @handleEvent = (event) => assertEvent event handleEvent.apply(this, [event]) @subscribe = (sink) => assertFunction sink sinks.push(sink) if sinks.length == 1 unsubscribeFromSource = subscribe @handleEvent assertFunction unsubscribeFromSource => removeSink sink unsubscribeFromSource() unless @hasSubscribers() class PropertyDispatcher extends Dispatcher constructor: (subscribe, handleEvent) -> super(subscribe, handleEvent) current = undefined push = @push subscribe = @subscribe @push = (event) => if event.hasValue() current = event.value push.apply(this, [event]) @subscribe = (sink) => if @hasSubscribers() and current? reply = sink initial(current) if reply == Bacon.noMore return nop subscribe.apply(this, [sink]) class Bus extends EventStream constructor: -> sink = undefined unsubFuncs = [] inputs = [] guardedSink = (input) => (event) => if (event.isEnd()) remove(input, inputs) Bacon.noMore else sink event unsubAll = => f() for f in unsubFuncs unsubFuncs = [] subscribeAll = (newSink) => sink = newSink unsubFuncs = [] for input in inputs unsubFuncs.push(input.subscribe(guardedSink(input))) unsubAll dispatcher = new Dispatcher(subscribeAll) subscribeThis = (sink) => dispatcher.subscribe(sink) super(subscribeThis) @plug = (inputStream) => inputs.push(inputStream) if (sink?) unsubFuncs.push(inputStream.subscribe(guardedSink(inputStream))) @push = (value) => sink next(value) if sink? @error = (error) => sink new Error(error) if sink? @end = => unsubAll() sink end() if sink? Bacon.EventStream = EventStream Bacon.Property = Property Bacon.Bus = Bus Bacon.Initial = Initial Bacon.Next = Next Bacon.End = End Bacon.Error = Error nop = -> latter = (_, x) -> x former = (x, _) -> x initial = (value) -> new Initial(value) next = (value) -> new Next(value) end = -> new End() isEvent = (x) -> x? and x.isEvent? and x.isEvent() toEvent = (x) -> if isEvent x x else next x empty = (xs) -> xs.length == 0 head = (xs) -> xs[0] tail = (xs) -> xs[1...xs.length] filter = (f, xs) -> filtered = [] for x in xs filtered.push(x) if f(x) filtered map = (f, xs) -> f(x) for x in xs cloneArray = (xs) -> xs.slice(0) cloneObject = (src) -> clone = {} for key, value of src clone[key] = value clone remove = (x, xs) -> i = xs.indexOf(x) if i >= 0 xs.splice(i, 1) contains = (xs, x) -> xs.indexOf(x) >= 0 assert = (message, condition) -> throw message unless condition assertEvent = (event) -> assert "not an event : " + event, event.isEvent? ; assert "not event", event.isEvent() assertFunction = (f) -> assert "not a function : " + f, isFunction(f) isFunction = (f) -> typeof f == "function" assertArray = (xs) -> assert "not an array : " + xs, xs instanceof Array always = (x) -> (-> x) toExtractor = (f) -> if isFunction f f else if isFieldKey(f) key = <KEY>FieldKey(f) (value) -> fieldValue = value[key] if isFunction(fieldValue) value[key]() else fieldValue else always f isFieldKey = (f) -> (typeof f == "string") and f.length > 1 and f[0] == "." toFieldKey = (f) -> f.slice(1) toCombinator = (f) -> if isFunction f f else if isFieldKey f key = toFieldKey(f) (left, right) -> left[key](right) else assert "not a function or a field key: " + f, false
true
(this.jQuery || this.Zepto)?.fn.asEventStream = (eventName) -> element = this new EventStream (sink) -> handler = (event) -> reply = sink (next event) if (reply == Bacon.noMore) unbind() unbind = -> element.unbind(eventName, handler) element.bind(eventName, handler) unbind Bacon = @Bacon = { taste : "delicious" } Bacon.fromPromise = (promise) -> new Bacon.EventStream( (sink) -> onSuccess = (value) -> sink (new Next value) sink (new End) onError = (e) -> sink (new Error e) sink (new End) promise.then(onSuccess, onError) nop ) Bacon.noMore = "veggies" Bacon.more = "moar bacon!" Bacon.never = => new EventStream (sink) => => nop Bacon.later = (delay, value) -> Bacon.sequentially(delay, [value]) Bacon.sequentially = (delay, values) -> Bacon.repeatedly(delay, values).take(filter(((e) -> e.hasValue()), map(toEvent, values)).length) Bacon.repeatedly = (delay, values) -> index = -1 poll = -> index++ toEvent values[index % values.length] Bacon.fromPoll(delay, poll) Bacon.fromPoll = (delay, poll) -> new EventStream (sink) -> id = undefined handler = -> value = poll() reply = sink value if (reply == Bacon.noMore or value.isEnd()) unbind() unbind = -> clearInterval id id = setInterval(handler, delay) unbind # Wrap DOM EventTarget or Node EventEmitter as EventStream # # target - EventTarget or EventEmitter, source of events # eventName - event name to bind # # Examples # # Bacon.fromEventTarget(document.body, "click") # # => EventStream # # Bacon.fromEventTarget (new EventEmitter(), "data") # # => EventStream # # Returns EventStream Bacon.fromEventTarget = (target, eventName) -> new EventStream (sink) -> handler = (event) -> reply = sink (next event) if reply == Bacon.noMore unbind() if target.addEventListener unbind = -> target.removeEventListener(eventName, handler, false) target.addEventListener(eventName, handler, false) else unbind = -> target.removeListener(eventName, handler) target.addListener(eventName, handler) unbind Bacon.interval = (delay, value) -> value = {} unless value? poll = -> next(value) Bacon.fromPoll(delay, poll) Bacon.constant = (value) -> new Property (sink) -> sink(initial(value)) sink(end()) nop Bacon.combineAll = (streams, f) -> assertArray streams stream = head streams for next in (tail streams) stream = f(stream, next) stream Bacon.mergeAll = (streams) -> Bacon.combineAll(streams, (s1, s2) -> s1.merge(s2)) Bacon.combineAsArray = (streams) -> toArray = (x) -> if x? then (if (x instanceof Array) then x else [x]) else [] concatArrays = (a1, a2) -> toArray(a1).concat(toArray(a2)) Bacon.combineAll(streams, (s1, s2) -> s1.toProperty().combine(s2, concatArrays)) Bacon.combineWith = (streams, f) -> Bacon.combineAll(streams, (s1, s2) -> s1.toProperty().combine(s2, f)) Bacon.latestValue = (src) -> latest = undefined src.subscribe (event) -> latest = event.value if event.hasValue() => latest class Event isEvent: -> true isEnd: -> false isInitial: -> false isNext: -> false isError: -> false hasValue: -> false filter: (f) -> true getOriginalEvent: -> if @sourceEvent? @sourceEvent.getOriginalEvent() else this onDone : (listener) -> listener() class Next extends Event constructor: (@value, sourceEvent) -> isNext: -> true hasValue: -> true fmap: (f) -> @apply(f(this.value)) apply: (value) -> next(value, @getOriginalEvent()) filter: (f) -> f(@value) class Initial extends Next isInitial: -> true isNext: -> false apply: (value) -> initial(value, @getOriginalEvent()) class End extends Event isEnd: -> true fmap: -> this apply: -> this class Error extends Event constructor: (@error) -> isError: -> true fmap: -> this apply: -> this class Observable onValue: (f) -> @subscribe (event) -> f event.value if event.hasValue() onError: (f) -> @subscribe (event) -> f event.error if event.isError() onEnd: (f) -> @subscribe (event) -> f() if event.isEnd() errors: -> @filter(-> false) filter: (f) -> f = toExtractor(f) @withHandler (event) -> if event.filter(f) @push event else Bacon.more takeWhile: (f) -> f = toExtractor(f) @withHandler (event) -> if event.filter(f) @push event else @push end() Bacon.noMore endOnError: -> @withHandler (event) -> if event.isError() @push event @push end() else @push event take: (count) -> assert "take: count must >= 1", (count>=1) @withHandler (event) -> if !event.hasValue() @push event else if (count == 1) @push event @push end() Bacon.noMore else count-- @push event map: (f) -> f = toExtractor(f) @withHandler (event) -> @push event.fmap(f) mapError : (f) -> f = toExtractor(f) @withHandler (event) -> if event.isError() @push next (f event.error) else @push event do: (f) -> f = toExtractor(f) @withHandler (event) -> f(event.value) if event.hasValue() @push event takeUntil: (stopper) => src = this @withSubscribe (sink) -> unsubscribed = false unsubSrc = nop unsubStopper = nop unsubBoth = -> unsubSrc() ; unsubStopper() ; unsubscribed = true srcSink = (event) -> if event.isEnd() unsubStopper() sink event Bacon.noMore else event.getOriginalEvent().onDone -> if !unsubscribed reply = sink event if reply == Bacon.noMore unsubBoth() Bacon.more stopperSink = (event) -> if event.isError() Bacon.more else if event.isEnd() Bacon.noMore else unsubSrc() sink end() Bacon.noMore unsubSrc = src.subscribe(srcSink) unsubStopper = stopper.subscribe(stopperSink) unless unsubscribed unsubBoth skip : (count) -> assert "skip: count must >= 0", (count>=0) @withHandler (event) -> if !event.hasValue() @push event else if (count > 0) count-- Bacon.more else @push event distinctUntilChanged: -> @skipDuplicates() skipDuplicates: -> @withStateMachine undefined, (prev, event) -> if !event.hasValue() [prev, [event]] else if prev isnt event.value [event.value, [event]] else [prev, []] withStateMachine: (initState, f) -> state = initState @withHandler (event) -> fromF = f(state, event) assertArray fromF [newState, outputs] = fromF assertArray outputs state = newState reply = Bacon.more for output in outputs reply = @push output if reply == Bacon.noMore return reply reply class EventStream extends Observable constructor: (subscribe) -> assertFunction subscribe dispatcher = new Dispatcher(subscribe) @subscribe = dispatcher.subscribe @hasSubscribers = dispatcher.hasSubscribers flatMap: (f) -> root = this new EventStream (sink) -> children = [] rootEnd = false unsubRoot = -> unbind = -> unsubRoot() for unsubChild in children unsubChild() children = [] checkEnd = -> if rootEnd and (children.length == 0) sink end() spawner = (event) -> if event.isEnd() rootEnd = true checkEnd() else if event.isError() sink event else child = f event.value unsubChild = undefined removeChild = -> remove(unsubChild, children) if unsubChild? checkEnd() handler = (event) -> if event.isEnd() removeChild() Bacon.noMore else reply = sink event if reply == Bacon.noMore unbind() reply unsubChild = child.subscribe handler children.push unsubChild unsubRoot = root.subscribe(spawner) unbind switch: (f) => @flatMap (value) => f(value).takeUntil(this) delay: (delay) -> @flatMap (value) -> Bacon.later delay, value throttle: (delay) -> @switch (value) -> Bacon.later delay, value bufferWithTime: (delay) -> values = [] storeAndMaybeTrigger = (value) -> values.push value values.length == 1 flush = -> output = values values = [] output buffer = -> Bacon.later(delay).map(flush) @filter(storeAndMaybeTrigger).flatMap(buffer) bufferWithCount: (count) -> values = [] @withHandler (event) -> flush = => @push next(values, event) values = [] if event.isError() @push event else if event.isEnd() flush() @push event else values.push(event.value) flush() if values.length == count merge: (right) -> left = this new EventStream (sink) -> unsubLeft = nop unsubRight = nop unsubscribed = false unsubBoth = -> unsubLeft() ; unsubRight() ; unsubscribed = true ends = 0 smartSink = (event) -> if event.isEnd() ends++ if ends == 2 sink end() else Bacon.more else reply = sink event unsubBoth() if reply == Bacon.noMore reply unsubLeft = left.subscribe(smartSink) unsubRight = right.subscribe(smartSink) unless unsubscribed unsubBoth toProperty: (initValue) -> @scan(initValue, latter) scan: (seed, f) -> f = toCombinator(f) acc = seed handleEvent = (event) -> acc = f(acc, event.value) if event.hasValue() @push event.apply(acc) d = new Dispatcher(@subscribe, handleEvent) subscribe = (sink) -> reply = sink initial(acc) if acc? d.subscribe(sink) unless reply == Bacon.noMore new Property(subscribe) decorateWith: (label, property) -> property.sampledBy(this, (propertyValue, streamValue) -> result = cloneObject(streamValue) result[label] = propertyValue result ) mapEnd : (f) -> f = toExtractor(f) @withHandler (event) -> if (event.isEnd()) @push next(f(event)) @push end() Bacon.noMore else @push event withHandler: (handler) -> dispatcher = new Dispatcher(@subscribe, handler) new EventStream(dispatcher.subscribe) withSubscribe: (subscribe) -> new EventStream(subscribe) class Property extends Observable constructor: (@subscribe) -> combine = (other, leftSink, rightSink) => myVal = undefined otherVal = undefined new Property (sink) => unsubscribed = false unsubMe = nop unsubOther = nop unsubBoth = -> unsubMe() ; unsubOther() ; unsubscribed = true myEnd = false otherEnd = false checkEnd = -> if myEnd and otherEnd reply = sink end() unsubBoth() if reply == Bacon.noMore reply initialSent = false combiningSink = (markEnd, setValue, thisSink) => (event) => if (event.isEnd()) markEnd() checkEnd() Bacon.noMore else if event.isError() reply = sink event unsubBoth if reply == Bacon.noMore reply else setValue(event.value) if (myVal? and otherVal?) if initialSent and event.isInitial() # don't send duplicate Initial Bacon.more else initialSent = true reply = thisSink(sink, event, myVal, otherVal) unsubBoth if reply == Bacon.noMore reply else Bacon.more mySink = combiningSink (-> myEnd = true), ((value) -> myVal = value), leftSink otherSink = combiningSink (-> otherEnd = true), ((value) -> otherVal = value), rightSink unsubMe = this.subscribe mySink unsubOther = other.subscribe otherSink unless unsubscribed unsubBoth @combine = (other, f) => combinator = toCombinator(f) combineAndPush = (sink, event, myVal, otherVal) -> sink(event.apply(combinator(myVal, otherVal))) combine(other, combineAndPush, combineAndPush) @sampledBy = (sampler, combinator = former) => pushPropertyValue = (sink, event, propertyVal, streamVal) -> sink(event.apply(combinator(propertyVal, streamVal))) combine(sampler, nop, pushPropertyValue).changes().takeUntil(sampler.filter(false).mapEnd()) sample: (interval) => @sampledBy Bacon.interval(interval, {}) changes: => new EventStream (sink) => @subscribe (event) => sink event unless event.isInitial() withHandler: (handler) -> new Property(new PropertyDispatcher(@subscribe, handler).subscribe) withSubscribe: (subscribe) -> new Property(new PropertyDispatcher(subscribe).subscribe) toProperty: => this class Dispatcher constructor: (subscribe, handleEvent) -> subscribe ?= -> nop sinks = [] @hasSubscribers = -> sinks.length > 0 unsubscribeFromSource = nop removeSink = (sink) -> remove(sink, sinks) @push = (event) => waiters = undefined done = -> if waiters? ws = waiters waiters = undefined w() for w in ws event.onDone = Event.prototype.onDone event.onDone = (listener) -> if waiters? and not contains(waiters, listener) waiters.push(listener) else waiters = [listener] assertEvent event for sink in (cloneArray(sinks)) reply = sink event removeSink sink if reply == Bacon.noMore or event.isEnd() done() if @hasSubscribers() then Bacon.more else Bacon.noMore handleEvent ?= (event) -> @push event @handleEvent = (event) => assertEvent event handleEvent.apply(this, [event]) @subscribe = (sink) => assertFunction sink sinks.push(sink) if sinks.length == 1 unsubscribeFromSource = subscribe @handleEvent assertFunction unsubscribeFromSource => removeSink sink unsubscribeFromSource() unless @hasSubscribers() class PropertyDispatcher extends Dispatcher constructor: (subscribe, handleEvent) -> super(subscribe, handleEvent) current = undefined push = @push subscribe = @subscribe @push = (event) => if event.hasValue() current = event.value push.apply(this, [event]) @subscribe = (sink) => if @hasSubscribers() and current? reply = sink initial(current) if reply == Bacon.noMore return nop subscribe.apply(this, [sink]) class Bus extends EventStream constructor: -> sink = undefined unsubFuncs = [] inputs = [] guardedSink = (input) => (event) => if (event.isEnd()) remove(input, inputs) Bacon.noMore else sink event unsubAll = => f() for f in unsubFuncs unsubFuncs = [] subscribeAll = (newSink) => sink = newSink unsubFuncs = [] for input in inputs unsubFuncs.push(input.subscribe(guardedSink(input))) unsubAll dispatcher = new Dispatcher(subscribeAll) subscribeThis = (sink) => dispatcher.subscribe(sink) super(subscribeThis) @plug = (inputStream) => inputs.push(inputStream) if (sink?) unsubFuncs.push(inputStream.subscribe(guardedSink(inputStream))) @push = (value) => sink next(value) if sink? @error = (error) => sink new Error(error) if sink? @end = => unsubAll() sink end() if sink? Bacon.EventStream = EventStream Bacon.Property = Property Bacon.Bus = Bus Bacon.Initial = Initial Bacon.Next = Next Bacon.End = End Bacon.Error = Error nop = -> latter = (_, x) -> x former = (x, _) -> x initial = (value) -> new Initial(value) next = (value) -> new Next(value) end = -> new End() isEvent = (x) -> x? and x.isEvent? and x.isEvent() toEvent = (x) -> if isEvent x x else next x empty = (xs) -> xs.length == 0 head = (xs) -> xs[0] tail = (xs) -> xs[1...xs.length] filter = (f, xs) -> filtered = [] for x in xs filtered.push(x) if f(x) filtered map = (f, xs) -> f(x) for x in xs cloneArray = (xs) -> xs.slice(0) cloneObject = (src) -> clone = {} for key, value of src clone[key] = value clone remove = (x, xs) -> i = xs.indexOf(x) if i >= 0 xs.splice(i, 1) contains = (xs, x) -> xs.indexOf(x) >= 0 assert = (message, condition) -> throw message unless condition assertEvent = (event) -> assert "not an event : " + event, event.isEvent? ; assert "not event", event.isEvent() assertFunction = (f) -> assert "not a function : " + f, isFunction(f) isFunction = (f) -> typeof f == "function" assertArray = (xs) -> assert "not an array : " + xs, xs instanceof Array always = (x) -> (-> x) toExtractor = (f) -> if isFunction f f else if isFieldKey(f) key = PI:KEY:<KEY>END_PIFieldKey(f) (value) -> fieldValue = value[key] if isFunction(fieldValue) value[key]() else fieldValue else always f isFieldKey = (f) -> (typeof f == "string") and f.length > 1 and f[0] == "." toFieldKey = (f) -> f.slice(1) toCombinator = (f) -> if isFunction f f else if isFieldKey f key = toFieldKey(f) (left, right) -> left[key](right) else assert "not a function or a field key: " + f, false
[ { "context": "e', ->\n @timeout 500000\n\t\n user = [\n {name: 'user1', email: 'user1@abc.com'}\n {name: 'user2', ema", "end": 130, "score": 0.9994434118270874, "start": 125, "tag": "USERNAME", "value": "user1" }, { "context": "t 500000\n\t\n user = [\n {name: 'user1', em...
test/unit/0-model/1-File.coffee
twhtanghk/restfile
0
_ = require 'lodash' fs = require 'fs' path = require 'path' describe 'File', -> @timeout 500000 user = [ {name: 'user1', email: 'user1@abc.com'} {name: 'user2', email: 'user2@abc.com'} ] files = [ '/usr/src/app/LICENSE' '/usr/src/app/README.md' '/usr/src/app/Dockerfile' '/usr/src/app/package.json' '/usr/src/app/app.js' ] it "check non-existence of #{path.dirname files[0]}", (done) -> sails.models.file .exist path.dirname(files[0]) .then -> done new Error 'unexpected result' .catch -> done() it "mkdir #{path.dirname files[0]}", (done) -> sails.models.file .mkdir path.dirname(files[0]), user[0].email .then -> done() .catch done it "upload #{files[0]}", (done) -> sails.models.file .upload files[0], user[0].email, fs.createReadStream(files[0]) .then -> sails.models.file .findOne filename: 'app' .populateAll() .then (dir) -> if dir.acl.length == 0 Promise.reject 'no default acl' done() .catch done it "upload #{files[0]}", (done) -> sails.models.file .upload files[0], user[0].email, fs.createReadStream(files[1]) .then -> done() .catch done it "download #{files[0]}", (done) -> sails.models.file .download files[0], user[0].email .then (fstream) -> fstream.pipe fs.createWriteStream "/tmp/#{path.basename files[1]}" .on 'finish', -> done() .on 'error', done .catch done it "download #{files[0]}", (done) -> sails.models.file .download files[0], user[0].email, -2 .then (fstream) -> fstream.pipe fs.createWriteStream "/tmp/#{path.basename files[0]}" .on 'finish', -> done() .on 'error', done .catch done it "check existence of #{path.dirname files[0]}", (done) -> sails.models.file .exist path.dirname(files[0]), user[0].email .then (exist) -> if exist done() else Promise.reject 'unexpected result' .catch done it "list file #{path.dirname files[0]}", (done) -> sails.models.file .exist path.dirname files[0] .then (file) -> if file.child.length != 1 return done new Error 'unexpected result' done() .catch done it "recursive delete dir /usr", (done) -> sails.models.file .rm '/usr', user[0].email .then -> sails.models.file.findPath files[0] .then -> Promise.reject 'unexpected result' .catch -> done() .catch done
126763
_ = require 'lodash' fs = require 'fs' path = require 'path' describe 'File', -> @timeout 500000 user = [ {name: 'user1', email: '<EMAIL>'} {name: 'user2', email: '<EMAIL>'} ] files = [ '/usr/src/app/LICENSE' '/usr/src/app/README.md' '/usr/src/app/Dockerfile' '/usr/src/app/package.json' '/usr/src/app/app.js' ] it "check non-existence of #{path.dirname files[0]}", (done) -> sails.models.file .exist path.dirname(files[0]) .then -> done new Error 'unexpected result' .catch -> done() it "mkdir #{path.dirname files[0]}", (done) -> sails.models.file .mkdir path.dirname(files[0]), user[0].email .then -> done() .catch done it "upload #{files[0]}", (done) -> sails.models.file .upload files[0], user[0].email, fs.createReadStream(files[0]) .then -> sails.models.file .findOne filename: 'app' .populateAll() .then (dir) -> if dir.acl.length == 0 Promise.reject 'no default acl' done() .catch done it "upload #{files[0]}", (done) -> sails.models.file .upload files[0], user[0].email, fs.createReadStream(files[1]) .then -> done() .catch done it "download #{files[0]}", (done) -> sails.models.file .download files[0], user[0].email .then (fstream) -> fstream.pipe fs.createWriteStream "/tmp/#{path.basename files[1]}" .on 'finish', -> done() .on 'error', done .catch done it "download #{files[0]}", (done) -> sails.models.file .download files[0], user[0].email, -2 .then (fstream) -> fstream.pipe fs.createWriteStream "/tmp/#{path.basename files[0]}" .on 'finish', -> done() .on 'error', done .catch done it "check existence of #{path.dirname files[0]}", (done) -> sails.models.file .exist path.dirname(files[0]), user[0].email .then (exist) -> if exist done() else Promise.reject 'unexpected result' .catch done it "list file #{path.dirname files[0]}", (done) -> sails.models.file .exist path.dirname files[0] .then (file) -> if file.child.length != 1 return done new Error 'unexpected result' done() .catch done it "recursive delete dir /usr", (done) -> sails.models.file .rm '/usr', user[0].email .then -> sails.models.file.findPath files[0] .then -> Promise.reject 'unexpected result' .catch -> done() .catch done
true
_ = require 'lodash' fs = require 'fs' path = require 'path' describe 'File', -> @timeout 500000 user = [ {name: 'user1', email: 'PI:EMAIL:<EMAIL>END_PI'} {name: 'user2', email: 'PI:EMAIL:<EMAIL>END_PI'} ] files = [ '/usr/src/app/LICENSE' '/usr/src/app/README.md' '/usr/src/app/Dockerfile' '/usr/src/app/package.json' '/usr/src/app/app.js' ] it "check non-existence of #{path.dirname files[0]}", (done) -> sails.models.file .exist path.dirname(files[0]) .then -> done new Error 'unexpected result' .catch -> done() it "mkdir #{path.dirname files[0]}", (done) -> sails.models.file .mkdir path.dirname(files[0]), user[0].email .then -> done() .catch done it "upload #{files[0]}", (done) -> sails.models.file .upload files[0], user[0].email, fs.createReadStream(files[0]) .then -> sails.models.file .findOne filename: 'app' .populateAll() .then (dir) -> if dir.acl.length == 0 Promise.reject 'no default acl' done() .catch done it "upload #{files[0]}", (done) -> sails.models.file .upload files[0], user[0].email, fs.createReadStream(files[1]) .then -> done() .catch done it "download #{files[0]}", (done) -> sails.models.file .download files[0], user[0].email .then (fstream) -> fstream.pipe fs.createWriteStream "/tmp/#{path.basename files[1]}" .on 'finish', -> done() .on 'error', done .catch done it "download #{files[0]}", (done) -> sails.models.file .download files[0], user[0].email, -2 .then (fstream) -> fstream.pipe fs.createWriteStream "/tmp/#{path.basename files[0]}" .on 'finish', -> done() .on 'error', done .catch done it "check existence of #{path.dirname files[0]}", (done) -> sails.models.file .exist path.dirname(files[0]), user[0].email .then (exist) -> if exist done() else Promise.reject 'unexpected result' .catch done it "list file #{path.dirname files[0]}", (done) -> sails.models.file .exist path.dirname files[0] .then (file) -> if file.child.length != 1 return done new Error 'unexpected result' done() .catch done it "recursive delete dir /usr", (done) -> sails.models.file .rm '/usr', user[0].email .then -> sails.models.file.findPath files[0] .then -> Promise.reject 'unexpected result' .catch -> done() .catch done
[ { "context": " \"battle.stale\", @turnOrder\n @broadcast \"Thalynas, The Goddess of Destruction And Stopping Battle", "end": 11563, "score": 0.6696962118148804, "start": 11561, "tag": "NAME", "value": "yn" } ]
src/event/Battle.coffee
sadbear-/IdleLands
0
MessageCreator = require "../system/MessageCreator" Player = require "../character/player/Player" BattleCache = require "./BattleCache" Constants = require "../system/Constants" _ = require "lodash" _.str = require "underscore.string" chance = (new require "chance")() class Battle BAD_TURN_THRESHOLD: 100 constructor: (@game, @parties, @suppress = Constants.defaults.battle.suppress, @battleUrl = Constants.defaults.battle.showUrl) -> return if @parties.length < 2 @game.battle = @ @startBattle() return @cleanUpGlobals() if @isBad @endBattle() startBattle: -> @setupParties() return if @isBad @badTurns = 0 @battleCache = new BattleCache @game, @parties @game.currentBattle = @ @initializePlayers() @link = Constants.defaults.battle.urlFormat.replace /%name/g, @battleCache.name.split(' ').join("%20") @playerNames = @getAllPlayerNames() @startMessage() if @suppress @beginTakingTurns() startMessage: -> if @battleUrl message = ">>> BATTLE: #{@battleCache.name} has occurred involving #{@playerNames}. Check it out here: #{@link}" else message = "#{@getAllStatStrings().join ' VS '}" @broadcast message, {}, yes, no setupParties: -> _.each @parties, (party) => if not party @game.errorHandler.captureException new Error "INVALID PARTY ??? ABORTING" console.error @parties @isBad = yes return party.currentBattle = @ fixStats: -> _.each @turnOrder, (player) -> player.recalculateStats() player.clearAffectingSpells() # somehow, I got NaN MP once, so this is to prevent misc. mistakes player.hp.__current = 0 player.mp.__current = 0 player.fled = false try player.hp?.toMaximum() player.mp?.toMaximum() catch e @game.errorHandler.captureException e initializePlayers: -> @calculateTurnOrder() @fixStats() calculateTurnOrder: -> playerList = _.reduce @parties, ((prev, party) -> prev.concat party.players), [] @turnOrder = _.sortBy playerList, (player) -> player.calc.stat 'agi' .reverse() getRelevantStats: (player) -> stats = name: "<player.name>#{player.name}</player.name>" stats.hp = player.hp if player.hp.maximum isnt 0 stats.mp = player.mp if player.mp.maximum isnt 0 stats.special = player.special if player.special.maximum isnt 0 stats stringifyStats: (player, stats) -> string = stats.name if stats.hp or stats.mp or stats.special if stats.hp.atMin() string += " [DEAD" else if player.fled string += " [FLED" else string += " [ " string += "<stats.hp>HP #{stats.hp.getValue()}/#{stats.hp.maximum}</stats.hp> " if stats.hp string += "<stats.mp>MP #{stats.mp.getValue()}/#{stats.mp.maximum}</stats.mp> " if stats.mp string += "<stats.sp>#{stats.special.name or "SP"} #{stats.special.getValue()}/#{stats.special.maximum}</stats.sp> " if stats.special string += "]" string getAllPlayerNames: -> names = _.map @parties, (party) => @getAllPlayersInPartyNames party _.str.toSentenceSerial _.flatten names getAllPlayersInPartyNames: (party) -> _.map party.players, (player) -> "<player.name>#{player.name}</player.name>" getAllPlayersInPartyStatStrings: (party) -> _.map party.players, (player) => @stringifyStats player, @getRelevantStats player getAllStatStrings: -> _.map @parties, (party) => "#{(@getAllPlayersInPartyStatStrings party).join ', '}" broadcast: (message, player = {}, ignoreSuppress = no, postToCache = yes) -> @battleCache.addMessage message if postToCache return if @suppress and not ignoreSuppress message = MessageCreator.genericMessage message, player @game.broadcast message playersAlive: -> parties = _.uniq _.pluck @turnOrder, 'party' aliveParties = _.reduce parties, (alive, party) -> currentAlive = _.reduce party.players, (count, player) -> count+((not player.hp.atMin()) and (not player.fled)) , 0 alive.concat if currentAlive>0 then [party.name] else [] , [] 1 < aliveParties.length checkIfOpponentHasBattleEffect: (turntaker, effect) -> 0 < _.reduce (_.difference @turnOrder, turntaker.party.players), ((prev, player) -> prev+player.calc[effect]()), 0 beginTakingTurns: -> @emitEventToAll "battle.start", @turnOrder @currentTurn = 1 while @playersAlive() @turnPosition = @turnPosition or 0 return if @badTurns > @BAD_TURN_THRESHOLD if @turnPosition is 0 @broadcast "ROUND #{@currentTurn} STATUS: #{@getAllStatStrings().join ' VS '}" @emitEventToAll "round.start", @turnOrder @emitEventToAll "turn.start", player player = @turnOrder[@turnPosition] @takeTurn player @emitEventToAll "turn.end", player @turnPosition++ if @turnPosition is @turnOrder.length @emitEventToAll "round.end", @turnOrder @turnPosition = 0 @currentTurn++ takeTurn: (player) -> return if player.hp.atMin() or player.fled player.hp.add player.calc.stat "hpregen" player.mp.add player.calc.stat "mpregen" if (@checkIfOpponentHasBattleEffect player, "mindwipe") and (chance.bool {likelihood: 1}) @broadcast "#{player.name} was attacked by mindwipe! All personalities have now been turned off!" player.removeAllPersonalities() return if @currentTurn is 1 and @checkIfOpponentHasBattleEffect player, "startle" message = "#{player.name} is startled!" @broadcast message @emitEventToAll "startled", player return if player.calc.cantAct() > 0 affectingCauses = player.calc.cantActMessages() message = MessageCreator.doStringReplace "#{_.str.toSentence affectingCauses}!", player @broadcast message return if (chance.bool {likelihood: player.calc.fleePercent()}) and not @checkIfOpponentHasBattleEffect player, "fear" @broadcast "<player.name>#{player.name}</player.name> has fled from combat!", player player.fled = true @emitEventToAll "flee", player return availableSpells = @game.spellManager.getSpellsAvailableFor player spellChosen = _.sample availableSpells if chance.bool({likelihood: player.calc.physicalAttackChance()}) or availableSpells.length is 0 @doPhysicalAttack player else @doMagicalAttack player, spellChosen tryParry: (defender, attacker) -> defenderParry = defender.calc.parry() parryChance = Math.max 0, Math.min 100, 100 - defenderParry*10 return if (chance.bool {likelihood: parryChance}) @doPhysicalAttack defender, attacker, yes doPhysicalAttack: (player, target = null, isCounter = no) -> if not target enemies = _.reject @turnOrder, (target) -> (player.party is target.party) or target.hp.atMin() or target.fled targets = player.calc.physicalAttackTargets enemies, @turnOrder target = _.sample targets return if not target battleMessage = (message, player) => @broadcast MessageCreator.doStringReplace message, player message = "<player.name>#{player.name}</player.name> is #{if isCounter then "COUNTER-" else ""}attacking <player.name>#{target.name}</player.name>" [dodgeMin, dodgeMax] = [-target.calc.dodge(), player.calc.beatDodge()] dodgeChance = chance.integer {min: dodgeMin, max: Math.max dodgeMin+1, dodgeMax} if dodgeChance <= 0 message += ", but <player.name>#{target.name}</player.name> dodged!" battleMessage message, target @emitEvents "dodge", "dodged", target, player @tryParry target, player @badTurns++ return [hitMin, hitMax] = [-target.calc.hit(), player.calc.beatHit()] hitChance = chance.integer {min: hitMin, max: Math.max hitMin+1, hitMax} if -(target.calc.stat 'luck') <= hitChance <= 0 message += ", but <player.name>#{player.name}</player.name> missed!" battleMessage message, target @emitEvents "miss", "missed", player, target @tryParry target, player @badTurns++ return if hitChance < -(target.calc.stat 'luck') deflectItem = _.sample target.equipment message += ", but <player.name>#{target.name}</player.name> deflected it with %hisher <event.item.#{deflectItem.itemClass}>#{deflectItem.getName()}</event.item.#{deflectItem.itemClass}>!" battleMessage message, target @emitEvents "deflect", "deflected", target, player @tryParry target, player @badTurns++ return maxDamage = player.calc.damage() damage = chance.integer {min: player.calc.minDamage(), max: maxDamage} critRoll = chance.integer {min: 1, max: 10000} if critRoll <= player.calc.criticalChance() and not target.calc.aegis() damage = maxDamage if damage is maxDamage and player.calc.lethal() damage *= 1.5 damage = target.calcDamageTaken damage damageType = if damage < 0 then "healing" else "damage" realDamage = Math.abs damage weapon = _.findWhere player.equipment, {type: "mainhand"} weapon = {itemClass: "basic", getName: -> return "claw"} if not weapon message += ", and #{if damage is maxDamage then "CRITICALLY " else ""}hit with %hisher <event.item.#{weapon.itemClass}>#{weapon.getName()}</event.item.#{weapon.itemClass}> for <damage.hp>#{realDamage}</damage.hp> HP #{damageType}" fatal = no if target.hp.getValue() - damage <= 0 and not target.calc.sturdy() message += " -- a fatal blow!" fatal = yes else message += "!" battleMessage message, player @takeStatFrom player, target, damage, "physical", "hp" @checkBattleEffects player, target if not fatal @emitEvents "target", "targeted", player, target @emitEvents "attack", "attacked", player, target @emitEvents "critical", "criticalled", player, target if damage is maxDamage (@emitEvents "kill", "killed", player, target, {dead: target}) if fatal doMagicalAttack: (player, spellClass) -> spell = @game.spellManager.modifySpell new spellClass @game, player spell.prepareCast() checkBattleEffects: (attacker, defender) -> effects = [] effects.push "Prone" if attacker.calc.prone() and chance.bool(likelihood: 15) effects.push "Shatter" if attacker.calc.shatter() and chance.bool(likelihood: 10) effects.push "Poison" if attacker.calc.poison() and chance.bool(likelihood: 20) effects.push "Venom" if attacker.calc.venom() and chance.bool(likelihood: 5) effects.push "Vampire" if attacker.calc.vampire() and chance.bool(likelihood: 10) return if effects.length is 0 @doBattleEffects effects, attacker, defender doBattleEffects: (effects, attacker, defender) -> findSpell = (name) => _.findWhere @game.spellManager.spells, name: name eventMap = "Prone": ['effect.prone', 'effect.proned'] "Shatter": ['effect.shatter', 'effect.shattered'] "Poison": ['effect.poison', 'effect.poisoned'] "Venom": ['effect.venom', 'effect.venomed'] "Vampire": ['effect.vampire', 'effect.vampired'] _.each effects, (effect) => spellProto = findSpell effect [aEvent, dEvent] = eventMap[effect] @emitEvents aEvent, dEvent, attacker, defender spellInst = new spellProto @game, attacker, defender spellInst.prepareCast() endBattle: -> if @badTurns > @BAD_TURN_THRESHOLD @emitEventToAll "battle.stale", @turnOrder @broadcast "Thalynas, The Goddess of Destruction And Stopping Battles Prematurely decided that you mortals were taking too long. Try better to amuse her next time!", {}, not @battleUrl @cleanUp() return @emitEventToAll "battle.end", @turnOrder randomWinningPlayer = _.sample(_.filter @turnOrder, (player) -> (not player.hp.atMin()) and (not player.fled)) if not randomWinningPlayer @broadcast "Everyone died! The battle was a tie! You get nothing!", {}, not @battleUrl @cleanUp() return @winningParty = randomWinningPlayer.party winnerName = @winningParty.getPartyName() @losingPlayers = _.reject (_.difference @turnOrder, @winningParty.players), (player) -> player.fled @winningParty.players = _.reject @winningParty.players, (player) -> player.fled @emitEventsTo "party.lose", @losingPlayers, @winningParty.players @emitEventsTo "party.win", @winningParty.players, @losingPlayers @broadcast "The battle was won by <event.partyName>#{winnerName}</event.partyName>.", {}, not @battleUrl @divvyXp() @cleanUp() notifyParticipants: (e, docs) -> _.chain(@turnOrder) .filter (entity) -> entity instanceof Player .each (player) => @game.eventHandler.broadcastEvent sendMessage: no extra: {battleId: docs[0]._id, linkTitle: @battleCache.name} player: player message: ">>> BATTLE: #{@battleCache.name} has occurred involving #{@playerNames}. Check it out here: #{@link}" type: "combat" link: @link divvyXp: -> deadVariables = {} deadVariables.deadPlayers = _.where @losingPlayers, {fled: false} deadVariables.numDead = deadVariables.deadPlayers.length deadVariables.deadPlayerTotalXp = _.reduce deadVariables.deadPlayers, ((prev, player) -> prev + player.xp.maximum), 0 deadVariables.deadPlayerAverageXP = deadVariables.deadPlayerTotalXp / deadVariables.numDead deadVariables.winningParty = @winningParty combatWinners = _.where deadVariables.winningParty.players, {fled: false} winMessages = [] loseMessages = [] xpMap = {} # winning player xp distribution _.each combatWinners, (player) -> return if player.isMonster basePct = chance.integer min: 1, max: Math.max 1, 6+player.calc.royal() basePctValue = Math.floor player.xp.maximum * (basePct/100) xpGain = player.personalityReduce 'combatEndXpGain', [player, deadVariables], basePctValue xpGain = player.calcXpGain xpGain gainPct = (xpGain/player.xp.maximum)*100 pct = +((gainPct).toFixed 3) winMessages.push "<player.name>#{player.name}</player.name> gained <event.xp>#{xpGain}</event.xp>xp [<event.xp>#{pct}</event.xp>%]" xpMap[player] = xpGain @broadcast (_.str.toSentence winMessages)+"!", {}, not @battleUrl if winMessages.length > 0 _.each combatWinners.players, (player) -> player.gainXp xpMap[player] # winning player gold distribution winMessages = [] _.each combatWinners, (player) -> return if player.isMonster goldGain = player.personalityReduce 'combatEndGoldGain', [player, deadVariables] goldGain = player.calcGoldGain goldGain if goldGain > 0 player.gainGold goldGain winMessages.push "<player.name>#{player.name}</player.name> gained <event.gold>#{goldGain}</event.gold> gold" @broadcast (_.str.toSentence winMessages)+"!", {}, not @battleUrl if winMessages.length > 0 # end winning #losing player xp distribution _.each deadVariables.deadPlayers, (player) -> return if player.isMonster basePct = chance.integer min: 1, max: 6 basePctValue = Math.floor player.xp.maximum * (basePct/100) xpLoss = player.personalityReduce 'combatEndXpLoss', [player, deadVariables], basePctValue xpLoss = player.calcXpGain xpLoss pct = +((xpLoss/player.xp.maximum)*100).toFixed 3 loseMessages.push "<player.name>#{player.name}</player.name> lost <event.xp>#{xpLoss}</event.xp>xp [<event.xp>#{pct}</event.xp>%]" xpMap[player] = xpLoss @broadcast (_.str.toSentence loseMessages)+"!", {}, not @battleUrl if loseMessages.length > 0 _.each deadVariables.deadPlayers, (player) -> player.gainXp -xpMap[player] #losing player gold distribution loseMessages = [] _.each deadVariables.deadPlayers, (player) -> return if player.isMonster goldLoss = player.personalityReduce 'combatEndGoldLoss', [player, deadVariables] goldLoss = player.calcGoldGain goldLoss if goldLoss > 0 player.gainGold -goldLoss loseMessages.push "<player.name>#{player.name}</player.name> lost <event.gold>#{goldLoss}</event.gold> gold" @broadcast (_.str.toSentence loseMessages)+"!", {}, not @battleUrl if loseMessages.length > 0 # end losing cleanUp: -> _.each @parties, (party) => _.each party.players, (player) -> player.clearAffectingSpells() if party.isMonsterParty or party.shouldDisband (if party is @winningParty then 25 else 50) party.disband() else party.finishAfterBattle() @cleanUpGlobals() @fixStats() @battleCache.finalize @notifyParticipants.bind @ @game.currentBattle = null cleanUpGlobals: -> @game.battle = null @game.inBattle = false takeHp: (attacker, defender, damage, type, spell, message) -> @takeStatFrom attacker, defender, damage, type, "hp", spell, message takeMp: (attacker, defender, damage, type, spell, message) -> @takeStatFrom attacker, defender, damage, type, "mp", spell, message takeStatFrom: (attacker, defender, damage, type, damageType = "hp", spell, message = null, doPropagate = no) -> damage += attacker.calc.absolute() darksideDamage = Math.round damage*(attacker.calc.darkside()*10/100) damage += darksideDamage if darksideDamage > 0 damage -= defender.calc?.damageTaken attacker, damage, type, spell, damageType damage = Math.round damage canFireSturdy = defender.hp.gtePercent 10 defender[damageType]?.sub damage defenderPunishDamage = Math.round damage*(defender.calc.punish()*5/100) if damageType is "hp" if damage < 0 @emitEvents "heal", "healed", attacker, defender, type: type, damage: damage else @emitEvents "damage", "damaged", attacker, defender, type: type, damage: damage if defender.calc.sturdy() and defender.hp.atMin() and canFireSturdy defender.hp.set 1 if defender.hp.atMin() defender.clearAffectingSpells() message = "#{message} [FATAL]" if message if damage is 0 @badTurns++ else @badTurns = 0 else if damageType is "mp" if damage < 0 @emitEvents "energize", "energized", attacker, defender, type: type, damage: damage else @emitEvents "vitiate", "vitiated", attacker, defender, type: type, damage: damage extra = damage: Math.abs damage message = MessageCreator.doStringReplace message, attacker, extra @broadcast message if message and typeof message is "string" if defenderPunishDamage > 0 and not doPropagate refmsg = "<player.name>#{defender.name}</player.name> reflected <damage.hp>#{defenderPunishDamage}</damage.hp> damage back at <player.name>#{attacker.name}</player.name>!" @takeStatFrom defender, attacker, defenderPunishDamage, type, damageType, spell, refmsg, yes @emitEvents "punish", "punished", defender, attacker if darksideDamage > 0 and not doPropagate refmsg = "<player.name>#{attacker.name}</player.name> took <damage.hp>#{darksideDamage}</damage.hp> damage due to darkside!" @takeStatFrom attacker, attacker, darksideDamage, type, damageType, spell, refmsg, yes @emitEventToAll "darkside", attacker emitEventToAll: (event, data) -> _.forEach @turnOrder, (player) -> if player is data player.emit "combat.self.#{event}", data else if data instanceof Player and player.party is data.party player.emit "combat.ally.#{event}", data else if data instanceof Player and player.party isnt data.party player.emit "combat.enemy.#{event}", data else if event and event not in ['turn.end', 'turn.start', 'flee'] player.emit "combat.#{event}", data emitEventsTo: (event, to, data) -> _.forEach to, (player) -> player.emit "combat.#{event}", data emitEvents: (attackerEvent, defenderEvent, attacker, defender, extra = {}) -> return if (not defender) or (not attacker) or (not defender.party) or (not attacker.party) attacker.emit "combat.self.#{attackerEvent}", defender, extra _.forEach (_.without attacker.party.players, attacker), (partyMate) -> partyMate.emit "combat.ally.#{attackerEvent}", attacker, defender, extra _.forEach (_.intersection @turnOrder, attacker.party.players), (foe) -> foe.emit "combat.enemy.#{attackerEvent}", attacker, defender, extra defender.emit "combat.self.#{defenderEvent}", attacker, extra _.forEach (_.without defender.party.players, defender), (partyMate) -> partyMate.emit "combat.ally.#{defenderEvent}", defender, attacker, extra _.forEach (_.intersection @turnOrder, defender.party.players), (foe) -> foe.emit "combat.enemy.#{defenderEvent}", attacker, defender, extra module.exports = exports = Battle
58862
MessageCreator = require "../system/MessageCreator" Player = require "../character/player/Player" BattleCache = require "./BattleCache" Constants = require "../system/Constants" _ = require "lodash" _.str = require "underscore.string" chance = (new require "chance")() class Battle BAD_TURN_THRESHOLD: 100 constructor: (@game, @parties, @suppress = Constants.defaults.battle.suppress, @battleUrl = Constants.defaults.battle.showUrl) -> return if @parties.length < 2 @game.battle = @ @startBattle() return @cleanUpGlobals() if @isBad @endBattle() startBattle: -> @setupParties() return if @isBad @badTurns = 0 @battleCache = new BattleCache @game, @parties @game.currentBattle = @ @initializePlayers() @link = Constants.defaults.battle.urlFormat.replace /%name/g, @battleCache.name.split(' ').join("%20") @playerNames = @getAllPlayerNames() @startMessage() if @suppress @beginTakingTurns() startMessage: -> if @battleUrl message = ">>> BATTLE: #{@battleCache.name} has occurred involving #{@playerNames}. Check it out here: #{@link}" else message = "#{@getAllStatStrings().join ' VS '}" @broadcast message, {}, yes, no setupParties: -> _.each @parties, (party) => if not party @game.errorHandler.captureException new Error "INVALID PARTY ??? ABORTING" console.error @parties @isBad = yes return party.currentBattle = @ fixStats: -> _.each @turnOrder, (player) -> player.recalculateStats() player.clearAffectingSpells() # somehow, I got NaN MP once, so this is to prevent misc. mistakes player.hp.__current = 0 player.mp.__current = 0 player.fled = false try player.hp?.toMaximum() player.mp?.toMaximum() catch e @game.errorHandler.captureException e initializePlayers: -> @calculateTurnOrder() @fixStats() calculateTurnOrder: -> playerList = _.reduce @parties, ((prev, party) -> prev.concat party.players), [] @turnOrder = _.sortBy playerList, (player) -> player.calc.stat 'agi' .reverse() getRelevantStats: (player) -> stats = name: "<player.name>#{player.name}</player.name>" stats.hp = player.hp if player.hp.maximum isnt 0 stats.mp = player.mp if player.mp.maximum isnt 0 stats.special = player.special if player.special.maximum isnt 0 stats stringifyStats: (player, stats) -> string = stats.name if stats.hp or stats.mp or stats.special if stats.hp.atMin() string += " [DEAD" else if player.fled string += " [FLED" else string += " [ " string += "<stats.hp>HP #{stats.hp.getValue()}/#{stats.hp.maximum}</stats.hp> " if stats.hp string += "<stats.mp>MP #{stats.mp.getValue()}/#{stats.mp.maximum}</stats.mp> " if stats.mp string += "<stats.sp>#{stats.special.name or "SP"} #{stats.special.getValue()}/#{stats.special.maximum}</stats.sp> " if stats.special string += "]" string getAllPlayerNames: -> names = _.map @parties, (party) => @getAllPlayersInPartyNames party _.str.toSentenceSerial _.flatten names getAllPlayersInPartyNames: (party) -> _.map party.players, (player) -> "<player.name>#{player.name}</player.name>" getAllPlayersInPartyStatStrings: (party) -> _.map party.players, (player) => @stringifyStats player, @getRelevantStats player getAllStatStrings: -> _.map @parties, (party) => "#{(@getAllPlayersInPartyStatStrings party).join ', '}" broadcast: (message, player = {}, ignoreSuppress = no, postToCache = yes) -> @battleCache.addMessage message if postToCache return if @suppress and not ignoreSuppress message = MessageCreator.genericMessage message, player @game.broadcast message playersAlive: -> parties = _.uniq _.pluck @turnOrder, 'party' aliveParties = _.reduce parties, (alive, party) -> currentAlive = _.reduce party.players, (count, player) -> count+((not player.hp.atMin()) and (not player.fled)) , 0 alive.concat if currentAlive>0 then [party.name] else [] , [] 1 < aliveParties.length checkIfOpponentHasBattleEffect: (turntaker, effect) -> 0 < _.reduce (_.difference @turnOrder, turntaker.party.players), ((prev, player) -> prev+player.calc[effect]()), 0 beginTakingTurns: -> @emitEventToAll "battle.start", @turnOrder @currentTurn = 1 while @playersAlive() @turnPosition = @turnPosition or 0 return if @badTurns > @BAD_TURN_THRESHOLD if @turnPosition is 0 @broadcast "ROUND #{@currentTurn} STATUS: #{@getAllStatStrings().join ' VS '}" @emitEventToAll "round.start", @turnOrder @emitEventToAll "turn.start", player player = @turnOrder[@turnPosition] @takeTurn player @emitEventToAll "turn.end", player @turnPosition++ if @turnPosition is @turnOrder.length @emitEventToAll "round.end", @turnOrder @turnPosition = 0 @currentTurn++ takeTurn: (player) -> return if player.hp.atMin() or player.fled player.hp.add player.calc.stat "hpregen" player.mp.add player.calc.stat "mpregen" if (@checkIfOpponentHasBattleEffect player, "mindwipe") and (chance.bool {likelihood: 1}) @broadcast "#{player.name} was attacked by mindwipe! All personalities have now been turned off!" player.removeAllPersonalities() return if @currentTurn is 1 and @checkIfOpponentHasBattleEffect player, "startle" message = "#{player.name} is startled!" @broadcast message @emitEventToAll "startled", player return if player.calc.cantAct() > 0 affectingCauses = player.calc.cantActMessages() message = MessageCreator.doStringReplace "#{_.str.toSentence affectingCauses}!", player @broadcast message return if (chance.bool {likelihood: player.calc.fleePercent()}) and not @checkIfOpponentHasBattleEffect player, "fear" @broadcast "<player.name>#{player.name}</player.name> has fled from combat!", player player.fled = true @emitEventToAll "flee", player return availableSpells = @game.spellManager.getSpellsAvailableFor player spellChosen = _.sample availableSpells if chance.bool({likelihood: player.calc.physicalAttackChance()}) or availableSpells.length is 0 @doPhysicalAttack player else @doMagicalAttack player, spellChosen tryParry: (defender, attacker) -> defenderParry = defender.calc.parry() parryChance = Math.max 0, Math.min 100, 100 - defenderParry*10 return if (chance.bool {likelihood: parryChance}) @doPhysicalAttack defender, attacker, yes doPhysicalAttack: (player, target = null, isCounter = no) -> if not target enemies = _.reject @turnOrder, (target) -> (player.party is target.party) or target.hp.atMin() or target.fled targets = player.calc.physicalAttackTargets enemies, @turnOrder target = _.sample targets return if not target battleMessage = (message, player) => @broadcast MessageCreator.doStringReplace message, player message = "<player.name>#{player.name}</player.name> is #{if isCounter then "COUNTER-" else ""}attacking <player.name>#{target.name}</player.name>" [dodgeMin, dodgeMax] = [-target.calc.dodge(), player.calc.beatDodge()] dodgeChance = chance.integer {min: dodgeMin, max: Math.max dodgeMin+1, dodgeMax} if dodgeChance <= 0 message += ", but <player.name>#{target.name}</player.name> dodged!" battleMessage message, target @emitEvents "dodge", "dodged", target, player @tryParry target, player @badTurns++ return [hitMin, hitMax] = [-target.calc.hit(), player.calc.beatHit()] hitChance = chance.integer {min: hitMin, max: Math.max hitMin+1, hitMax} if -(target.calc.stat 'luck') <= hitChance <= 0 message += ", but <player.name>#{player.name}</player.name> missed!" battleMessage message, target @emitEvents "miss", "missed", player, target @tryParry target, player @badTurns++ return if hitChance < -(target.calc.stat 'luck') deflectItem = _.sample target.equipment message += ", but <player.name>#{target.name}</player.name> deflected it with %hisher <event.item.#{deflectItem.itemClass}>#{deflectItem.getName()}</event.item.#{deflectItem.itemClass}>!" battleMessage message, target @emitEvents "deflect", "deflected", target, player @tryParry target, player @badTurns++ return maxDamage = player.calc.damage() damage = chance.integer {min: player.calc.minDamage(), max: maxDamage} critRoll = chance.integer {min: 1, max: 10000} if critRoll <= player.calc.criticalChance() and not target.calc.aegis() damage = maxDamage if damage is maxDamage and player.calc.lethal() damage *= 1.5 damage = target.calcDamageTaken damage damageType = if damage < 0 then "healing" else "damage" realDamage = Math.abs damage weapon = _.findWhere player.equipment, {type: "mainhand"} weapon = {itemClass: "basic", getName: -> return "claw"} if not weapon message += ", and #{if damage is maxDamage then "CRITICALLY " else ""}hit with %hisher <event.item.#{weapon.itemClass}>#{weapon.getName()}</event.item.#{weapon.itemClass}> for <damage.hp>#{realDamage}</damage.hp> HP #{damageType}" fatal = no if target.hp.getValue() - damage <= 0 and not target.calc.sturdy() message += " -- a fatal blow!" fatal = yes else message += "!" battleMessage message, player @takeStatFrom player, target, damage, "physical", "hp" @checkBattleEffects player, target if not fatal @emitEvents "target", "targeted", player, target @emitEvents "attack", "attacked", player, target @emitEvents "critical", "criticalled", player, target if damage is maxDamage (@emitEvents "kill", "killed", player, target, {dead: target}) if fatal doMagicalAttack: (player, spellClass) -> spell = @game.spellManager.modifySpell new spellClass @game, player spell.prepareCast() checkBattleEffects: (attacker, defender) -> effects = [] effects.push "Prone" if attacker.calc.prone() and chance.bool(likelihood: 15) effects.push "Shatter" if attacker.calc.shatter() and chance.bool(likelihood: 10) effects.push "Poison" if attacker.calc.poison() and chance.bool(likelihood: 20) effects.push "Venom" if attacker.calc.venom() and chance.bool(likelihood: 5) effects.push "Vampire" if attacker.calc.vampire() and chance.bool(likelihood: 10) return if effects.length is 0 @doBattleEffects effects, attacker, defender doBattleEffects: (effects, attacker, defender) -> findSpell = (name) => _.findWhere @game.spellManager.spells, name: name eventMap = "Prone": ['effect.prone', 'effect.proned'] "Shatter": ['effect.shatter', 'effect.shattered'] "Poison": ['effect.poison', 'effect.poisoned'] "Venom": ['effect.venom', 'effect.venomed'] "Vampire": ['effect.vampire', 'effect.vampired'] _.each effects, (effect) => spellProto = findSpell effect [aEvent, dEvent] = eventMap[effect] @emitEvents aEvent, dEvent, attacker, defender spellInst = new spellProto @game, attacker, defender spellInst.prepareCast() endBattle: -> if @badTurns > @BAD_TURN_THRESHOLD @emitEventToAll "battle.stale", @turnOrder @broadcast "Thal<NAME>as, The Goddess of Destruction And Stopping Battles Prematurely decided that you mortals were taking too long. Try better to amuse her next time!", {}, not @battleUrl @cleanUp() return @emitEventToAll "battle.end", @turnOrder randomWinningPlayer = _.sample(_.filter @turnOrder, (player) -> (not player.hp.atMin()) and (not player.fled)) if not randomWinningPlayer @broadcast "Everyone died! The battle was a tie! You get nothing!", {}, not @battleUrl @cleanUp() return @winningParty = randomWinningPlayer.party winnerName = @winningParty.getPartyName() @losingPlayers = _.reject (_.difference @turnOrder, @winningParty.players), (player) -> player.fled @winningParty.players = _.reject @winningParty.players, (player) -> player.fled @emitEventsTo "party.lose", @losingPlayers, @winningParty.players @emitEventsTo "party.win", @winningParty.players, @losingPlayers @broadcast "The battle was won by <event.partyName>#{winnerName}</event.partyName>.", {}, not @battleUrl @divvyXp() @cleanUp() notifyParticipants: (e, docs) -> _.chain(@turnOrder) .filter (entity) -> entity instanceof Player .each (player) => @game.eventHandler.broadcastEvent sendMessage: no extra: {battleId: docs[0]._id, linkTitle: @battleCache.name} player: player message: ">>> BATTLE: #{@battleCache.name} has occurred involving #{@playerNames}. Check it out here: #{@link}" type: "combat" link: @link divvyXp: -> deadVariables = {} deadVariables.deadPlayers = _.where @losingPlayers, {fled: false} deadVariables.numDead = deadVariables.deadPlayers.length deadVariables.deadPlayerTotalXp = _.reduce deadVariables.deadPlayers, ((prev, player) -> prev + player.xp.maximum), 0 deadVariables.deadPlayerAverageXP = deadVariables.deadPlayerTotalXp / deadVariables.numDead deadVariables.winningParty = @winningParty combatWinners = _.where deadVariables.winningParty.players, {fled: false} winMessages = [] loseMessages = [] xpMap = {} # winning player xp distribution _.each combatWinners, (player) -> return if player.isMonster basePct = chance.integer min: 1, max: Math.max 1, 6+player.calc.royal() basePctValue = Math.floor player.xp.maximum * (basePct/100) xpGain = player.personalityReduce 'combatEndXpGain', [player, deadVariables], basePctValue xpGain = player.calcXpGain xpGain gainPct = (xpGain/player.xp.maximum)*100 pct = +((gainPct).toFixed 3) winMessages.push "<player.name>#{player.name}</player.name> gained <event.xp>#{xpGain}</event.xp>xp [<event.xp>#{pct}</event.xp>%]" xpMap[player] = xpGain @broadcast (_.str.toSentence winMessages)+"!", {}, not @battleUrl if winMessages.length > 0 _.each combatWinners.players, (player) -> player.gainXp xpMap[player] # winning player gold distribution winMessages = [] _.each combatWinners, (player) -> return if player.isMonster goldGain = player.personalityReduce 'combatEndGoldGain', [player, deadVariables] goldGain = player.calcGoldGain goldGain if goldGain > 0 player.gainGold goldGain winMessages.push "<player.name>#{player.name}</player.name> gained <event.gold>#{goldGain}</event.gold> gold" @broadcast (_.str.toSentence winMessages)+"!", {}, not @battleUrl if winMessages.length > 0 # end winning #losing player xp distribution _.each deadVariables.deadPlayers, (player) -> return if player.isMonster basePct = chance.integer min: 1, max: 6 basePctValue = Math.floor player.xp.maximum * (basePct/100) xpLoss = player.personalityReduce 'combatEndXpLoss', [player, deadVariables], basePctValue xpLoss = player.calcXpGain xpLoss pct = +((xpLoss/player.xp.maximum)*100).toFixed 3 loseMessages.push "<player.name>#{player.name}</player.name> lost <event.xp>#{xpLoss}</event.xp>xp [<event.xp>#{pct}</event.xp>%]" xpMap[player] = xpLoss @broadcast (_.str.toSentence loseMessages)+"!", {}, not @battleUrl if loseMessages.length > 0 _.each deadVariables.deadPlayers, (player) -> player.gainXp -xpMap[player] #losing player gold distribution loseMessages = [] _.each deadVariables.deadPlayers, (player) -> return if player.isMonster goldLoss = player.personalityReduce 'combatEndGoldLoss', [player, deadVariables] goldLoss = player.calcGoldGain goldLoss if goldLoss > 0 player.gainGold -goldLoss loseMessages.push "<player.name>#{player.name}</player.name> lost <event.gold>#{goldLoss}</event.gold> gold" @broadcast (_.str.toSentence loseMessages)+"!", {}, not @battleUrl if loseMessages.length > 0 # end losing cleanUp: -> _.each @parties, (party) => _.each party.players, (player) -> player.clearAffectingSpells() if party.isMonsterParty or party.shouldDisband (if party is @winningParty then 25 else 50) party.disband() else party.finishAfterBattle() @cleanUpGlobals() @fixStats() @battleCache.finalize @notifyParticipants.bind @ @game.currentBattle = null cleanUpGlobals: -> @game.battle = null @game.inBattle = false takeHp: (attacker, defender, damage, type, spell, message) -> @takeStatFrom attacker, defender, damage, type, "hp", spell, message takeMp: (attacker, defender, damage, type, spell, message) -> @takeStatFrom attacker, defender, damage, type, "mp", spell, message takeStatFrom: (attacker, defender, damage, type, damageType = "hp", spell, message = null, doPropagate = no) -> damage += attacker.calc.absolute() darksideDamage = Math.round damage*(attacker.calc.darkside()*10/100) damage += darksideDamage if darksideDamage > 0 damage -= defender.calc?.damageTaken attacker, damage, type, spell, damageType damage = Math.round damage canFireSturdy = defender.hp.gtePercent 10 defender[damageType]?.sub damage defenderPunishDamage = Math.round damage*(defender.calc.punish()*5/100) if damageType is "hp" if damage < 0 @emitEvents "heal", "healed", attacker, defender, type: type, damage: damage else @emitEvents "damage", "damaged", attacker, defender, type: type, damage: damage if defender.calc.sturdy() and defender.hp.atMin() and canFireSturdy defender.hp.set 1 if defender.hp.atMin() defender.clearAffectingSpells() message = "#{message} [FATAL]" if message if damage is 0 @badTurns++ else @badTurns = 0 else if damageType is "mp" if damage < 0 @emitEvents "energize", "energized", attacker, defender, type: type, damage: damage else @emitEvents "vitiate", "vitiated", attacker, defender, type: type, damage: damage extra = damage: Math.abs damage message = MessageCreator.doStringReplace message, attacker, extra @broadcast message if message and typeof message is "string" if defenderPunishDamage > 0 and not doPropagate refmsg = "<player.name>#{defender.name}</player.name> reflected <damage.hp>#{defenderPunishDamage}</damage.hp> damage back at <player.name>#{attacker.name}</player.name>!" @takeStatFrom defender, attacker, defenderPunishDamage, type, damageType, spell, refmsg, yes @emitEvents "punish", "punished", defender, attacker if darksideDamage > 0 and not doPropagate refmsg = "<player.name>#{attacker.name}</player.name> took <damage.hp>#{darksideDamage}</damage.hp> damage due to darkside!" @takeStatFrom attacker, attacker, darksideDamage, type, damageType, spell, refmsg, yes @emitEventToAll "darkside", attacker emitEventToAll: (event, data) -> _.forEach @turnOrder, (player) -> if player is data player.emit "combat.self.#{event}", data else if data instanceof Player and player.party is data.party player.emit "combat.ally.#{event}", data else if data instanceof Player and player.party isnt data.party player.emit "combat.enemy.#{event}", data else if event and event not in ['turn.end', 'turn.start', 'flee'] player.emit "combat.#{event}", data emitEventsTo: (event, to, data) -> _.forEach to, (player) -> player.emit "combat.#{event}", data emitEvents: (attackerEvent, defenderEvent, attacker, defender, extra = {}) -> return if (not defender) or (not attacker) or (not defender.party) or (not attacker.party) attacker.emit "combat.self.#{attackerEvent}", defender, extra _.forEach (_.without attacker.party.players, attacker), (partyMate) -> partyMate.emit "combat.ally.#{attackerEvent}", attacker, defender, extra _.forEach (_.intersection @turnOrder, attacker.party.players), (foe) -> foe.emit "combat.enemy.#{attackerEvent}", attacker, defender, extra defender.emit "combat.self.#{defenderEvent}", attacker, extra _.forEach (_.without defender.party.players, defender), (partyMate) -> partyMate.emit "combat.ally.#{defenderEvent}", defender, attacker, extra _.forEach (_.intersection @turnOrder, defender.party.players), (foe) -> foe.emit "combat.enemy.#{defenderEvent}", attacker, defender, extra module.exports = exports = Battle
true
MessageCreator = require "../system/MessageCreator" Player = require "../character/player/Player" BattleCache = require "./BattleCache" Constants = require "../system/Constants" _ = require "lodash" _.str = require "underscore.string" chance = (new require "chance")() class Battle BAD_TURN_THRESHOLD: 100 constructor: (@game, @parties, @suppress = Constants.defaults.battle.suppress, @battleUrl = Constants.defaults.battle.showUrl) -> return if @parties.length < 2 @game.battle = @ @startBattle() return @cleanUpGlobals() if @isBad @endBattle() startBattle: -> @setupParties() return if @isBad @badTurns = 0 @battleCache = new BattleCache @game, @parties @game.currentBattle = @ @initializePlayers() @link = Constants.defaults.battle.urlFormat.replace /%name/g, @battleCache.name.split(' ').join("%20") @playerNames = @getAllPlayerNames() @startMessage() if @suppress @beginTakingTurns() startMessage: -> if @battleUrl message = ">>> BATTLE: #{@battleCache.name} has occurred involving #{@playerNames}. Check it out here: #{@link}" else message = "#{@getAllStatStrings().join ' VS '}" @broadcast message, {}, yes, no setupParties: -> _.each @parties, (party) => if not party @game.errorHandler.captureException new Error "INVALID PARTY ??? ABORTING" console.error @parties @isBad = yes return party.currentBattle = @ fixStats: -> _.each @turnOrder, (player) -> player.recalculateStats() player.clearAffectingSpells() # somehow, I got NaN MP once, so this is to prevent misc. mistakes player.hp.__current = 0 player.mp.__current = 0 player.fled = false try player.hp?.toMaximum() player.mp?.toMaximum() catch e @game.errorHandler.captureException e initializePlayers: -> @calculateTurnOrder() @fixStats() calculateTurnOrder: -> playerList = _.reduce @parties, ((prev, party) -> prev.concat party.players), [] @turnOrder = _.sortBy playerList, (player) -> player.calc.stat 'agi' .reverse() getRelevantStats: (player) -> stats = name: "<player.name>#{player.name}</player.name>" stats.hp = player.hp if player.hp.maximum isnt 0 stats.mp = player.mp if player.mp.maximum isnt 0 stats.special = player.special if player.special.maximum isnt 0 stats stringifyStats: (player, stats) -> string = stats.name if stats.hp or stats.mp or stats.special if stats.hp.atMin() string += " [DEAD" else if player.fled string += " [FLED" else string += " [ " string += "<stats.hp>HP #{stats.hp.getValue()}/#{stats.hp.maximum}</stats.hp> " if stats.hp string += "<stats.mp>MP #{stats.mp.getValue()}/#{stats.mp.maximum}</stats.mp> " if stats.mp string += "<stats.sp>#{stats.special.name or "SP"} #{stats.special.getValue()}/#{stats.special.maximum}</stats.sp> " if stats.special string += "]" string getAllPlayerNames: -> names = _.map @parties, (party) => @getAllPlayersInPartyNames party _.str.toSentenceSerial _.flatten names getAllPlayersInPartyNames: (party) -> _.map party.players, (player) -> "<player.name>#{player.name}</player.name>" getAllPlayersInPartyStatStrings: (party) -> _.map party.players, (player) => @stringifyStats player, @getRelevantStats player getAllStatStrings: -> _.map @parties, (party) => "#{(@getAllPlayersInPartyStatStrings party).join ', '}" broadcast: (message, player = {}, ignoreSuppress = no, postToCache = yes) -> @battleCache.addMessage message if postToCache return if @suppress and not ignoreSuppress message = MessageCreator.genericMessage message, player @game.broadcast message playersAlive: -> parties = _.uniq _.pluck @turnOrder, 'party' aliveParties = _.reduce parties, (alive, party) -> currentAlive = _.reduce party.players, (count, player) -> count+((not player.hp.atMin()) and (not player.fled)) , 0 alive.concat if currentAlive>0 then [party.name] else [] , [] 1 < aliveParties.length checkIfOpponentHasBattleEffect: (turntaker, effect) -> 0 < _.reduce (_.difference @turnOrder, turntaker.party.players), ((prev, player) -> prev+player.calc[effect]()), 0 beginTakingTurns: -> @emitEventToAll "battle.start", @turnOrder @currentTurn = 1 while @playersAlive() @turnPosition = @turnPosition or 0 return if @badTurns > @BAD_TURN_THRESHOLD if @turnPosition is 0 @broadcast "ROUND #{@currentTurn} STATUS: #{@getAllStatStrings().join ' VS '}" @emitEventToAll "round.start", @turnOrder @emitEventToAll "turn.start", player player = @turnOrder[@turnPosition] @takeTurn player @emitEventToAll "turn.end", player @turnPosition++ if @turnPosition is @turnOrder.length @emitEventToAll "round.end", @turnOrder @turnPosition = 0 @currentTurn++ takeTurn: (player) -> return if player.hp.atMin() or player.fled player.hp.add player.calc.stat "hpregen" player.mp.add player.calc.stat "mpregen" if (@checkIfOpponentHasBattleEffect player, "mindwipe") and (chance.bool {likelihood: 1}) @broadcast "#{player.name} was attacked by mindwipe! All personalities have now been turned off!" player.removeAllPersonalities() return if @currentTurn is 1 and @checkIfOpponentHasBattleEffect player, "startle" message = "#{player.name} is startled!" @broadcast message @emitEventToAll "startled", player return if player.calc.cantAct() > 0 affectingCauses = player.calc.cantActMessages() message = MessageCreator.doStringReplace "#{_.str.toSentence affectingCauses}!", player @broadcast message return if (chance.bool {likelihood: player.calc.fleePercent()}) and not @checkIfOpponentHasBattleEffect player, "fear" @broadcast "<player.name>#{player.name}</player.name> has fled from combat!", player player.fled = true @emitEventToAll "flee", player return availableSpells = @game.spellManager.getSpellsAvailableFor player spellChosen = _.sample availableSpells if chance.bool({likelihood: player.calc.physicalAttackChance()}) or availableSpells.length is 0 @doPhysicalAttack player else @doMagicalAttack player, spellChosen tryParry: (defender, attacker) -> defenderParry = defender.calc.parry() parryChance = Math.max 0, Math.min 100, 100 - defenderParry*10 return if (chance.bool {likelihood: parryChance}) @doPhysicalAttack defender, attacker, yes doPhysicalAttack: (player, target = null, isCounter = no) -> if not target enemies = _.reject @turnOrder, (target) -> (player.party is target.party) or target.hp.atMin() or target.fled targets = player.calc.physicalAttackTargets enemies, @turnOrder target = _.sample targets return if not target battleMessage = (message, player) => @broadcast MessageCreator.doStringReplace message, player message = "<player.name>#{player.name}</player.name> is #{if isCounter then "COUNTER-" else ""}attacking <player.name>#{target.name}</player.name>" [dodgeMin, dodgeMax] = [-target.calc.dodge(), player.calc.beatDodge()] dodgeChance = chance.integer {min: dodgeMin, max: Math.max dodgeMin+1, dodgeMax} if dodgeChance <= 0 message += ", but <player.name>#{target.name}</player.name> dodged!" battleMessage message, target @emitEvents "dodge", "dodged", target, player @tryParry target, player @badTurns++ return [hitMin, hitMax] = [-target.calc.hit(), player.calc.beatHit()] hitChance = chance.integer {min: hitMin, max: Math.max hitMin+1, hitMax} if -(target.calc.stat 'luck') <= hitChance <= 0 message += ", but <player.name>#{player.name}</player.name> missed!" battleMessage message, target @emitEvents "miss", "missed", player, target @tryParry target, player @badTurns++ return if hitChance < -(target.calc.stat 'luck') deflectItem = _.sample target.equipment message += ", but <player.name>#{target.name}</player.name> deflected it with %hisher <event.item.#{deflectItem.itemClass}>#{deflectItem.getName()}</event.item.#{deflectItem.itemClass}>!" battleMessage message, target @emitEvents "deflect", "deflected", target, player @tryParry target, player @badTurns++ return maxDamage = player.calc.damage() damage = chance.integer {min: player.calc.minDamage(), max: maxDamage} critRoll = chance.integer {min: 1, max: 10000} if critRoll <= player.calc.criticalChance() and not target.calc.aegis() damage = maxDamage if damage is maxDamage and player.calc.lethal() damage *= 1.5 damage = target.calcDamageTaken damage damageType = if damage < 0 then "healing" else "damage" realDamage = Math.abs damage weapon = _.findWhere player.equipment, {type: "mainhand"} weapon = {itemClass: "basic", getName: -> return "claw"} if not weapon message += ", and #{if damage is maxDamage then "CRITICALLY " else ""}hit with %hisher <event.item.#{weapon.itemClass}>#{weapon.getName()}</event.item.#{weapon.itemClass}> for <damage.hp>#{realDamage}</damage.hp> HP #{damageType}" fatal = no if target.hp.getValue() - damage <= 0 and not target.calc.sturdy() message += " -- a fatal blow!" fatal = yes else message += "!" battleMessage message, player @takeStatFrom player, target, damage, "physical", "hp" @checkBattleEffects player, target if not fatal @emitEvents "target", "targeted", player, target @emitEvents "attack", "attacked", player, target @emitEvents "critical", "criticalled", player, target if damage is maxDamage (@emitEvents "kill", "killed", player, target, {dead: target}) if fatal doMagicalAttack: (player, spellClass) -> spell = @game.spellManager.modifySpell new spellClass @game, player spell.prepareCast() checkBattleEffects: (attacker, defender) -> effects = [] effects.push "Prone" if attacker.calc.prone() and chance.bool(likelihood: 15) effects.push "Shatter" if attacker.calc.shatter() and chance.bool(likelihood: 10) effects.push "Poison" if attacker.calc.poison() and chance.bool(likelihood: 20) effects.push "Venom" if attacker.calc.venom() and chance.bool(likelihood: 5) effects.push "Vampire" if attacker.calc.vampire() and chance.bool(likelihood: 10) return if effects.length is 0 @doBattleEffects effects, attacker, defender doBattleEffects: (effects, attacker, defender) -> findSpell = (name) => _.findWhere @game.spellManager.spells, name: name eventMap = "Prone": ['effect.prone', 'effect.proned'] "Shatter": ['effect.shatter', 'effect.shattered'] "Poison": ['effect.poison', 'effect.poisoned'] "Venom": ['effect.venom', 'effect.venomed'] "Vampire": ['effect.vampire', 'effect.vampired'] _.each effects, (effect) => spellProto = findSpell effect [aEvent, dEvent] = eventMap[effect] @emitEvents aEvent, dEvent, attacker, defender spellInst = new spellProto @game, attacker, defender spellInst.prepareCast() endBattle: -> if @badTurns > @BAD_TURN_THRESHOLD @emitEventToAll "battle.stale", @turnOrder @broadcast "ThalPI:NAME:<NAME>END_PIas, The Goddess of Destruction And Stopping Battles Prematurely decided that you mortals were taking too long. Try better to amuse her next time!", {}, not @battleUrl @cleanUp() return @emitEventToAll "battle.end", @turnOrder randomWinningPlayer = _.sample(_.filter @turnOrder, (player) -> (not player.hp.atMin()) and (not player.fled)) if not randomWinningPlayer @broadcast "Everyone died! The battle was a tie! You get nothing!", {}, not @battleUrl @cleanUp() return @winningParty = randomWinningPlayer.party winnerName = @winningParty.getPartyName() @losingPlayers = _.reject (_.difference @turnOrder, @winningParty.players), (player) -> player.fled @winningParty.players = _.reject @winningParty.players, (player) -> player.fled @emitEventsTo "party.lose", @losingPlayers, @winningParty.players @emitEventsTo "party.win", @winningParty.players, @losingPlayers @broadcast "The battle was won by <event.partyName>#{winnerName}</event.partyName>.", {}, not @battleUrl @divvyXp() @cleanUp() notifyParticipants: (e, docs) -> _.chain(@turnOrder) .filter (entity) -> entity instanceof Player .each (player) => @game.eventHandler.broadcastEvent sendMessage: no extra: {battleId: docs[0]._id, linkTitle: @battleCache.name} player: player message: ">>> BATTLE: #{@battleCache.name} has occurred involving #{@playerNames}. Check it out here: #{@link}" type: "combat" link: @link divvyXp: -> deadVariables = {} deadVariables.deadPlayers = _.where @losingPlayers, {fled: false} deadVariables.numDead = deadVariables.deadPlayers.length deadVariables.deadPlayerTotalXp = _.reduce deadVariables.deadPlayers, ((prev, player) -> prev + player.xp.maximum), 0 deadVariables.deadPlayerAverageXP = deadVariables.deadPlayerTotalXp / deadVariables.numDead deadVariables.winningParty = @winningParty combatWinners = _.where deadVariables.winningParty.players, {fled: false} winMessages = [] loseMessages = [] xpMap = {} # winning player xp distribution _.each combatWinners, (player) -> return if player.isMonster basePct = chance.integer min: 1, max: Math.max 1, 6+player.calc.royal() basePctValue = Math.floor player.xp.maximum * (basePct/100) xpGain = player.personalityReduce 'combatEndXpGain', [player, deadVariables], basePctValue xpGain = player.calcXpGain xpGain gainPct = (xpGain/player.xp.maximum)*100 pct = +((gainPct).toFixed 3) winMessages.push "<player.name>#{player.name}</player.name> gained <event.xp>#{xpGain}</event.xp>xp [<event.xp>#{pct}</event.xp>%]" xpMap[player] = xpGain @broadcast (_.str.toSentence winMessages)+"!", {}, not @battleUrl if winMessages.length > 0 _.each combatWinners.players, (player) -> player.gainXp xpMap[player] # winning player gold distribution winMessages = [] _.each combatWinners, (player) -> return if player.isMonster goldGain = player.personalityReduce 'combatEndGoldGain', [player, deadVariables] goldGain = player.calcGoldGain goldGain if goldGain > 0 player.gainGold goldGain winMessages.push "<player.name>#{player.name}</player.name> gained <event.gold>#{goldGain}</event.gold> gold" @broadcast (_.str.toSentence winMessages)+"!", {}, not @battleUrl if winMessages.length > 0 # end winning #losing player xp distribution _.each deadVariables.deadPlayers, (player) -> return if player.isMonster basePct = chance.integer min: 1, max: 6 basePctValue = Math.floor player.xp.maximum * (basePct/100) xpLoss = player.personalityReduce 'combatEndXpLoss', [player, deadVariables], basePctValue xpLoss = player.calcXpGain xpLoss pct = +((xpLoss/player.xp.maximum)*100).toFixed 3 loseMessages.push "<player.name>#{player.name}</player.name> lost <event.xp>#{xpLoss}</event.xp>xp [<event.xp>#{pct}</event.xp>%]" xpMap[player] = xpLoss @broadcast (_.str.toSentence loseMessages)+"!", {}, not @battleUrl if loseMessages.length > 0 _.each deadVariables.deadPlayers, (player) -> player.gainXp -xpMap[player] #losing player gold distribution loseMessages = [] _.each deadVariables.deadPlayers, (player) -> return if player.isMonster goldLoss = player.personalityReduce 'combatEndGoldLoss', [player, deadVariables] goldLoss = player.calcGoldGain goldLoss if goldLoss > 0 player.gainGold -goldLoss loseMessages.push "<player.name>#{player.name}</player.name> lost <event.gold>#{goldLoss}</event.gold> gold" @broadcast (_.str.toSentence loseMessages)+"!", {}, not @battleUrl if loseMessages.length > 0 # end losing cleanUp: -> _.each @parties, (party) => _.each party.players, (player) -> player.clearAffectingSpells() if party.isMonsterParty or party.shouldDisband (if party is @winningParty then 25 else 50) party.disband() else party.finishAfterBattle() @cleanUpGlobals() @fixStats() @battleCache.finalize @notifyParticipants.bind @ @game.currentBattle = null cleanUpGlobals: -> @game.battle = null @game.inBattle = false takeHp: (attacker, defender, damage, type, spell, message) -> @takeStatFrom attacker, defender, damage, type, "hp", spell, message takeMp: (attacker, defender, damage, type, spell, message) -> @takeStatFrom attacker, defender, damage, type, "mp", spell, message takeStatFrom: (attacker, defender, damage, type, damageType = "hp", spell, message = null, doPropagate = no) -> damage += attacker.calc.absolute() darksideDamage = Math.round damage*(attacker.calc.darkside()*10/100) damage += darksideDamage if darksideDamage > 0 damage -= defender.calc?.damageTaken attacker, damage, type, spell, damageType damage = Math.round damage canFireSturdy = defender.hp.gtePercent 10 defender[damageType]?.sub damage defenderPunishDamage = Math.round damage*(defender.calc.punish()*5/100) if damageType is "hp" if damage < 0 @emitEvents "heal", "healed", attacker, defender, type: type, damage: damage else @emitEvents "damage", "damaged", attacker, defender, type: type, damage: damage if defender.calc.sturdy() and defender.hp.atMin() and canFireSturdy defender.hp.set 1 if defender.hp.atMin() defender.clearAffectingSpells() message = "#{message} [FATAL]" if message if damage is 0 @badTurns++ else @badTurns = 0 else if damageType is "mp" if damage < 0 @emitEvents "energize", "energized", attacker, defender, type: type, damage: damage else @emitEvents "vitiate", "vitiated", attacker, defender, type: type, damage: damage extra = damage: Math.abs damage message = MessageCreator.doStringReplace message, attacker, extra @broadcast message if message and typeof message is "string" if defenderPunishDamage > 0 and not doPropagate refmsg = "<player.name>#{defender.name}</player.name> reflected <damage.hp>#{defenderPunishDamage}</damage.hp> damage back at <player.name>#{attacker.name}</player.name>!" @takeStatFrom defender, attacker, defenderPunishDamage, type, damageType, spell, refmsg, yes @emitEvents "punish", "punished", defender, attacker if darksideDamage > 0 and not doPropagate refmsg = "<player.name>#{attacker.name}</player.name> took <damage.hp>#{darksideDamage}</damage.hp> damage due to darkside!" @takeStatFrom attacker, attacker, darksideDamage, type, damageType, spell, refmsg, yes @emitEventToAll "darkside", attacker emitEventToAll: (event, data) -> _.forEach @turnOrder, (player) -> if player is data player.emit "combat.self.#{event}", data else if data instanceof Player and player.party is data.party player.emit "combat.ally.#{event}", data else if data instanceof Player and player.party isnt data.party player.emit "combat.enemy.#{event}", data else if event and event not in ['turn.end', 'turn.start', 'flee'] player.emit "combat.#{event}", data emitEventsTo: (event, to, data) -> _.forEach to, (player) -> player.emit "combat.#{event}", data emitEvents: (attackerEvent, defenderEvent, attacker, defender, extra = {}) -> return if (not defender) or (not attacker) or (not defender.party) or (not attacker.party) attacker.emit "combat.self.#{attackerEvent}", defender, extra _.forEach (_.without attacker.party.players, attacker), (partyMate) -> partyMate.emit "combat.ally.#{attackerEvent}", attacker, defender, extra _.forEach (_.intersection @turnOrder, attacker.party.players), (foe) -> foe.emit "combat.enemy.#{attackerEvent}", attacker, defender, extra defender.emit "combat.self.#{defenderEvent}", attacker, extra _.forEach (_.without defender.party.players, defender), (partyMate) -> partyMate.emit "combat.ally.#{defenderEvent}", defender, attacker, extra _.forEach (_.intersection @turnOrder, defender.party.players), (foe) -> foe.emit "combat.enemy.#{defenderEvent}", attacker, defender, extra module.exports = exports = Battle
[ { "context": " # XXX: should I release it manually?\n\nAPI_KEY = 'XUNLEI_LIXIAN_WEB'\n\nmodule.exports = (api) ->\n\tevery_window (w) ->\n", "end": 558, "score": 0.997516930103302, "start": 541, "tag": "KEY", "value": "XUNLEI_LIXIAN_WEB" } ]
firefox/lib/api.coffee
yineric/xunlei-lixian-web
23
every_window = (callback) -> for w in require('sdk/window/utils').windows() if w.document.documentElement.getAttribute('windowtype') == 'navigator:browser' and w.location.href == 'chrome://browser/content/browser.xul' callback w require('sdk/system/events').on 'toplevel-window-ready', (event) -> w = event.subject if w.document.documentElement.getAttribute('windowtype') == 'navigator:browser' and w.location.href == 'chrome://browser/content/browser.xul' callback w , true # XXX: should I release it manually? API_KEY = 'XUNLEI_LIXIAN_WEB' module.exports = (api) -> every_window (w) -> w[API_KEY] = api
208664
every_window = (callback) -> for w in require('sdk/window/utils').windows() if w.document.documentElement.getAttribute('windowtype') == 'navigator:browser' and w.location.href == 'chrome://browser/content/browser.xul' callback w require('sdk/system/events').on 'toplevel-window-ready', (event) -> w = event.subject if w.document.documentElement.getAttribute('windowtype') == 'navigator:browser' and w.location.href == 'chrome://browser/content/browser.xul' callback w , true # XXX: should I release it manually? API_KEY = '<KEY>' module.exports = (api) -> every_window (w) -> w[API_KEY] = api
true
every_window = (callback) -> for w in require('sdk/window/utils').windows() if w.document.documentElement.getAttribute('windowtype') == 'navigator:browser' and w.location.href == 'chrome://browser/content/browser.xul' callback w require('sdk/system/events').on 'toplevel-window-ready', (event) -> w = event.subject if w.document.documentElement.getAttribute('windowtype') == 'navigator:browser' and w.location.href == 'chrome://browser/content/browser.xul' callback w , true # XXX: should I release it manually? API_KEY = 'PI:KEY:<KEY>END_PI' module.exports = (api) -> every_window (w) -> w[API_KEY] = api
[ { "context": "sponseId: 'its-electric'\n auth: uuid: 'electric-eels'\n messageType: 'received'\n ", "end": 2136, "score": 0.9534174799919128, "start": 2123, "tag": "USERNAME", "value": "electric-eels" }, { "context": "sponseId: 'its-electric'\n ...
test/deliver-webhook-spec.coffee
octoblu/meshblu-core-task-message-webhook
0
mongojs = require 'mongojs' async = require 'async' RedisNS = require '@octoblu/redis-ns' Redis = require 'ioredis' Datastore = require 'meshblu-core-datastore' {beforeEach, context, describe, it, sinon} = global {expect} = require 'chai' DeliverWebhook = require '../' describe 'DeliverWebhook', -> beforeEach (done) -> client = new Redis 'localhost', dropBufferSupport: true client.on 'ready', => @redis = new RedisNS 'test-webhooker', client @redis.del 'webhooks', done beforeEach (done) -> client = new Redis 'localhost', dropBufferSupport: true client.on 'ready', => @redisClient = new RedisNS 'test-webhooker', client @redisClient.del 'webhooks', done beforeEach -> @datastore = new Datastore database: mongojs 'token-manager-test' collection: 'things' @pepper = 'im-a-pepper' @privateKey = 'private-key' @uuidAliasResolver = resolve: (_uuid, callback) => callback(null, _uuid) options = { @privateKey, @datastore @uuidAliasResolver @pepper @redisClient } @sut = new DeliverWebhook options describe '->do', -> context 'when given webhook when the queue length is too long', -> beforeEach (done) -> async.times 1001, (n, next) => @redis.lpush 'webhooks', '{"some":"thing"}', next , done beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 503', -> expectedResponse = metadata: responseId: 'its-electric' code: 503 status: 'Service Unavailable' expect(@response).to.deep.equal expectedResponse context 'when given a valid webhook', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'received' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should not have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.not.exist it 'should not have signRequest', -> expect(@data.signRequest).to.be.false context 'when given a route and forwardedRoutes', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'message.received' route: [{from: 'electric-eels', to: 'electric-feels', type: 'message.received'}] forwardedRoutes: [] options: url: "http://example.com" rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'message.received' 'X-MESHBLU-ROUTE': '[{"from":"electric-eels","to":"electric-feels","type":"message.received"}]' 'X-MESHBLU-FORWARDED-ROUTES': '[]' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should not have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.not.exist it 'should not have signRequest', -> expect(@data.signRequest).to.be.false context 'when generating credentials', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" generateAndForwardMeshbluCredentials: true rawData: '{"devices":"*"}' @sut.tokenManager._generateToken = sinon.stub().returns 'abc123' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal auth: bearer: "ZWxlY3RyaWMtZWVsczphYmMxMjM=" url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'received' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.deep.equal 'abc123' it 'should not have signRequest', -> expect(@data.signRequest).to.be.false context 'when signRequest', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" signRequest: true rawData: '{"devices":"*"}' @sut.tokenManager._generateToken = sinon.stub().returns 'abc123' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'received' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should not have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.not.exist it 'should have signRequest true', -> expect(@data.signRequest).to.be.true
119072
mongojs = require 'mongojs' async = require 'async' RedisNS = require '@octoblu/redis-ns' Redis = require 'ioredis' Datastore = require 'meshblu-core-datastore' {beforeEach, context, describe, it, sinon} = global {expect} = require 'chai' DeliverWebhook = require '../' describe 'DeliverWebhook', -> beforeEach (done) -> client = new Redis 'localhost', dropBufferSupport: true client.on 'ready', => @redis = new RedisNS 'test-webhooker', client @redis.del 'webhooks', done beforeEach (done) -> client = new Redis 'localhost', dropBufferSupport: true client.on 'ready', => @redisClient = new RedisNS 'test-webhooker', client @redisClient.del 'webhooks', done beforeEach -> @datastore = new Datastore database: mongojs 'token-manager-test' collection: 'things' @pepper = 'im-a-pepper' @privateKey = 'private-key' @uuidAliasResolver = resolve: (_uuid, callback) => callback(null, _uuid) options = { @privateKey, @datastore @uuidAliasResolver @pepper @redisClient } @sut = new DeliverWebhook options describe '->do', -> context 'when given webhook when the queue length is too long', -> beforeEach (done) -> async.times 1001, (n, next) => @redis.lpush 'webhooks', '{"some":"thing"}', next , done beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 503', -> expectedResponse = metadata: responseId: 'its-electric' code: 503 status: 'Service Unavailable' expect(@response).to.deep.equal expectedResponse context 'when given a valid webhook', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'received' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should not have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.not.exist it 'should not have signRequest', -> expect(@data.signRequest).to.be.false context 'when given a route and forwardedRoutes', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'message.received' route: [{from: 'electric-eels', to: 'electric-feels', type: 'message.received'}] forwardedRoutes: [] options: url: "http://example.com" rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'message.received' 'X-MESHBLU-ROUTE': '[{"from":"electric-eels","to":"electric-feels","type":"message.received"}]' 'X-MESHBLU-FORWARDED-ROUTES': '[]' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should not have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.not.exist it 'should not have signRequest', -> expect(@data.signRequest).to.be.false context 'when generating credentials', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" generateAndForwardMeshbluCredentials: true rawData: '{"devices":"*"}' @sut.tokenManager._generateToken = sinon.stub().returns '<KEY>123' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal auth: bearer: "ZWxlY3RyaWMtZWVsczphYmMxMjM=" url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'received' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.deep.equal 'abc<PASSWORD>' it 'should not have signRequest', -> expect(@data.signRequest).to.be.false context 'when signRequest', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" signRequest: true rawData: '{"devices":"*"}' @sut.tokenManager._generateToken = sinon.stub().returns 'abc123' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'received' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should not have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.not.exist it 'should have signRequest true', -> expect(@data.signRequest).to.be.true
true
mongojs = require 'mongojs' async = require 'async' RedisNS = require '@octoblu/redis-ns' Redis = require 'ioredis' Datastore = require 'meshblu-core-datastore' {beforeEach, context, describe, it, sinon} = global {expect} = require 'chai' DeliverWebhook = require '../' describe 'DeliverWebhook', -> beforeEach (done) -> client = new Redis 'localhost', dropBufferSupport: true client.on 'ready', => @redis = new RedisNS 'test-webhooker', client @redis.del 'webhooks', done beforeEach (done) -> client = new Redis 'localhost', dropBufferSupport: true client.on 'ready', => @redisClient = new RedisNS 'test-webhooker', client @redisClient.del 'webhooks', done beforeEach -> @datastore = new Datastore database: mongojs 'token-manager-test' collection: 'things' @pepper = 'im-a-pepper' @privateKey = 'private-key' @uuidAliasResolver = resolve: (_uuid, callback) => callback(null, _uuid) options = { @privateKey, @datastore @uuidAliasResolver @pepper @redisClient } @sut = new DeliverWebhook options describe '->do', -> context 'when given webhook when the queue length is too long', -> beforeEach (done) -> async.times 1001, (n, next) => @redis.lpush 'webhooks', '{"some":"thing"}', next , done beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 503', -> expectedResponse = metadata: responseId: 'its-electric' code: 503 status: 'Service Unavailable' expect(@response).to.deep.equal expectedResponse context 'when given a valid webhook', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'received' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should not have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.not.exist it 'should not have signRequest', -> expect(@data.signRequest).to.be.false context 'when given a route and forwardedRoutes', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'message.received' route: [{from: 'electric-eels', to: 'electric-feels', type: 'message.received'}] forwardedRoutes: [] options: url: "http://example.com" rawData: '{"devices":"*"}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'message.received' 'X-MESHBLU-ROUTE': '[{"from":"electric-eels","to":"electric-feels","type":"message.received"}]' 'X-MESHBLU-FORWARDED-ROUTES': '[]' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should not have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.not.exist it 'should not have signRequest', -> expect(@data.signRequest).to.be.false context 'when generating credentials', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" generateAndForwardMeshbluCredentials: true rawData: '{"devices":"*"}' @sut.tokenManager._generateToken = sinon.stub().returns 'PI:KEY:<KEY>END_PI123' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal auth: bearer: "ZWxlY3RyaWMtZWVsczphYmMxMjM=" url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'received' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.deep.equal 'abcPI:PASSWORD:<PASSWORD>END_PI' it 'should not have signRequest', -> expect(@data.signRequest).to.be.false context 'when signRequest', -> beforeEach (done) -> request = metadata: responseId: 'its-electric' auth: uuid: 'electric-eels' messageType: 'received' options: url: "http://example.com" signRequest: true rawData: '{"devices":"*"}' @sut.tokenManager._generateToken = sinon.stub().returns 'abc123' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse describe 'when pulling out the job', -> beforeEach (done) -> @redis.brpop 'webhooks', 1, (error, result) => return done error if error? return done new Error 'request timeout' unless result? @data = JSON.parse result[1] done null return # redis fix it 'should have the request options', -> expect(@data.requestOptions).to.deep.equal url: 'http://example.com' headers: 'X-MESHBLU-MESSAGE-TYPE': 'received' 'X-MESHBLU-UUID': 'electric-eels' json: devices: '*' forever: true gzip: true it 'should have a revokeOptions.uuid', -> expect(@data.revokeOptions.uuid).to.exist it 'should not have a revokeOptions.token', -> expect(@data.revokeOptions.token).to.not.exist it 'should have signRequest true', -> expect(@data.signRequest).to.be.true
[ { "context": "e.\n# Used for logging to STDOUT/FILE.\n#\n# @author: Daniele Gazzelloni <daniele@danielegazzelloni.com>\n#################", "end": 86, "score": 0.9998916983604431, "start": 68, "tag": "NAME", "value": "Daniele Gazzelloni" }, { "context": " to STDOUT/FILE.\n#\n# @autho...
backend/src/logger.coffee
danielegazzelloni/barbershop-challenge
0
## # Logger module. # Used for logging to STDOUT/FILE. # # @author: Daniele Gazzelloni <daniele@danielegazzelloni.com> ###################################################################### config = require './config' # Log out on console in a specific format data log = (type, message) -> if type.length>1 process.stdout.write("[#{currentTime()}] #{type.substr(0, 1)} #{config.appName}: #{message}") else console.log("[%s] %s %s: %s", currentTime(), type, config.appName, message) # Formats current time to: 'hh24:mi:ss' currentTime = () -> date = new Date() h = date.getHours() mi = date.getMinutes() s = date.getSeconds() # Not the easiest syntax to read, I know... "#{if h>9 then h else "0"}h:#{if mi>9 then mi else "0#{mi}"}:#{ if s>9 then s else "0#{s}"}" # Module exports exports.log = log
60238
## # Logger module. # Used for logging to STDOUT/FILE. # # @author: <NAME> <<EMAIL>> ###################################################################### config = require './config' # Log out on console in a specific format data log = (type, message) -> if type.length>1 process.stdout.write("[#{currentTime()}] #{type.substr(0, 1)} #{config.appName}: #{message}") else console.log("[%s] %s %s: %s", currentTime(), type, config.appName, message) # Formats current time to: 'hh24:mi:ss' currentTime = () -> date = new Date() h = date.getHours() mi = date.getMinutes() s = date.getSeconds() # Not the easiest syntax to read, I know... "#{if h>9 then h else "0"}h:#{if mi>9 then mi else "0#{mi}"}:#{ if s>9 then s else "0#{s}"}" # Module exports exports.log = log
true
## # Logger module. # Used for logging to STDOUT/FILE. # # @author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ###################################################################### config = require './config' # Log out on console in a specific format data log = (type, message) -> if type.length>1 process.stdout.write("[#{currentTime()}] #{type.substr(0, 1)} #{config.appName}: #{message}") else console.log("[%s] %s %s: %s", currentTime(), type, config.appName, message) # Formats current time to: 'hh24:mi:ss' currentTime = () -> date = new Date() h = date.getHours() mi = date.getMinutes() s = date.getSeconds() # Not the easiest syntax to read, I know... "#{if h>9 then h else "0"}h:#{if mi>9 then mi else "0#{mi}"}:#{ if s>9 then s else "0#{s}"}" # Module exports exports.log = log
[ { "context": "################\n# filename: data.coffee\n# author: trollear\n# date: 2017/2/18\n#################\n\n############", "end": 60, "score": 0.9997284412384033, "start": 52, "tag": "USERNAME", "value": "trollear" }, { "context": "#############\n# Configs\n#################...
src/coffee/data.coffee
roslairy/tumdown
1
################# # filename: data.coffee # author: trollear # date: 2017/2/18 ################# ################# # Preparation ################# if not window.TD then window.TD = {} ################# # Configs ################# KEY = 'TD_DATA' ################# # Data ################# TD.data = storage: {} # create a new download and save to storage saveDownload: (id, name, url, state)-> download = id: id name: name, url: url, state: state, @storage.downloads.push download # flush storage to localStorage @_flush() # delete a download with name deleteDownload: (name)-> downloads = @storage.downloads for num in [0..downloads.length - 1] if downloads[num] isnt undefined and downloads[num].name is name # remove item downloads.splice num, 1 break # flush storage to localStorage @_flush() # update download state with id updateDownload: (id, state)-> @storage.downloads.forEach (elem, index, arr)-> if elem and elem.id is id arr[index].state = state # flush storage to localStorage @_flush() # if download of particular name is already downloaded isDownloadExist: (name)-> for download in @storage.downloads if download and download.name is name return true return false # return collection of downloading items getDownloadings: ()-> @_reload() return @_getDownloadsOfState "downloading" # return collection of failed items getFaileds: ()-> @_reload() return @_getDownloadsOfState "failed" # return collection of completed items getCompleteds: ()-> @_reload() return @_getDownloadsOfState "completed" # save a pair of config to storage setConfig: (name, val)-> @storage.configs[name] = val @_flush() # load value of key from storage getConfig: (name)-> @_reload() @storage.configs[name] # return collection of particular state _getDownloadsOfState: (state)-> downloads = [] for download in @storage.downloads if download and download.state is state downloads.push download return downloads # flush storage to localStorage _flush: ()-> window.localStorage.setItem KEY, JSON.stringify @storage # reload storage from localStorage _reload: ()-> TD.data.storage = JSON.parse(window.localStorage.getItem(KEY)) || { configs: [], downloads: [] } ################# # init ################# # Check if localStorage is supported if not window.localStorage console.error 'local storage is not supported.' return # Ensure a valid storage try TD.data.storage = JSON.parse(window.localStorage.getItem(KEY)) catch error TD.data.storage = null finally if not TD.data.storage TD.data.storage = { configs: [], downloads: [] }
782
################# # filename: data.coffee # author: trollear # date: 2017/2/18 ################# ################# # Preparation ################# if not window.TD then window.TD = {} ################# # Configs ################# KEY = '<KEY>' ################# # Data ################# TD.data = storage: {} # create a new download and save to storage saveDownload: (id, name, url, state)-> download = id: id name: name, url: url, state: state, @storage.downloads.push download # flush storage to localStorage @_flush() # delete a download with name deleteDownload: (name)-> downloads = @storage.downloads for num in [0..downloads.length - 1] if downloads[num] isnt undefined and downloads[num].name is name # remove item downloads.splice num, 1 break # flush storage to localStorage @_flush() # update download state with id updateDownload: (id, state)-> @storage.downloads.forEach (elem, index, arr)-> if elem and elem.id is id arr[index].state = state # flush storage to localStorage @_flush() # if download of particular name is already downloaded isDownloadExist: (name)-> for download in @storage.downloads if download and download.name is name return true return false # return collection of downloading items getDownloadings: ()-> @_reload() return @_getDownloadsOfState "downloading" # return collection of failed items getFaileds: ()-> @_reload() return @_getDownloadsOfState "failed" # return collection of completed items getCompleteds: ()-> @_reload() return @_getDownloadsOfState "completed" # save a pair of config to storage setConfig: (name, val)-> @storage.configs[name] = val @_flush() # load value of key from storage getConfig: (name)-> @_reload() @storage.configs[name] # return collection of particular state _getDownloadsOfState: (state)-> downloads = [] for download in @storage.downloads if download and download.state is state downloads.push download return downloads # flush storage to localStorage _flush: ()-> window.localStorage.setItem KEY, JSON.stringify @storage # reload storage from localStorage _reload: ()-> TD.data.storage = JSON.parse(window.localStorage.getItem(KEY)) || { configs: [], downloads: [] } ################# # init ################# # Check if localStorage is supported if not window.localStorage console.error 'local storage is not supported.' return # Ensure a valid storage try TD.data.storage = JSON.parse(window.localStorage.getItem(KEY)) catch error TD.data.storage = null finally if not TD.data.storage TD.data.storage = { configs: [], downloads: [] }
true
################# # filename: data.coffee # author: trollear # date: 2017/2/18 ################# ################# # Preparation ################# if not window.TD then window.TD = {} ################# # Configs ################# KEY = 'PI:KEY:<KEY>END_PI' ################# # Data ################# TD.data = storage: {} # create a new download and save to storage saveDownload: (id, name, url, state)-> download = id: id name: name, url: url, state: state, @storage.downloads.push download # flush storage to localStorage @_flush() # delete a download with name deleteDownload: (name)-> downloads = @storage.downloads for num in [0..downloads.length - 1] if downloads[num] isnt undefined and downloads[num].name is name # remove item downloads.splice num, 1 break # flush storage to localStorage @_flush() # update download state with id updateDownload: (id, state)-> @storage.downloads.forEach (elem, index, arr)-> if elem and elem.id is id arr[index].state = state # flush storage to localStorage @_flush() # if download of particular name is already downloaded isDownloadExist: (name)-> for download in @storage.downloads if download and download.name is name return true return false # return collection of downloading items getDownloadings: ()-> @_reload() return @_getDownloadsOfState "downloading" # return collection of failed items getFaileds: ()-> @_reload() return @_getDownloadsOfState "failed" # return collection of completed items getCompleteds: ()-> @_reload() return @_getDownloadsOfState "completed" # save a pair of config to storage setConfig: (name, val)-> @storage.configs[name] = val @_flush() # load value of key from storage getConfig: (name)-> @_reload() @storage.configs[name] # return collection of particular state _getDownloadsOfState: (state)-> downloads = [] for download in @storage.downloads if download and download.state is state downloads.push download return downloads # flush storage to localStorage _flush: ()-> window.localStorage.setItem KEY, JSON.stringify @storage # reload storage from localStorage _reload: ()-> TD.data.storage = JSON.parse(window.localStorage.getItem(KEY)) || { configs: [], downloads: [] } ################# # init ################# # Check if localStorage is supported if not window.localStorage console.error 'local storage is not supported.' return # Ensure a valid storage try TD.data.storage = JSON.parse(window.localStorage.getItem(KEY)) catch error TD.data.storage = null finally if not TD.data.storage TD.data.storage = { configs: [], downloads: [] }
[ { "context": ".\n if not process.env.RUNNING_APP\n key = _generateCacheKey(url)\n if fs.existsSync(LIB_DIR + key)\n ", "end": 474, "score": 0.9747936129570007, "start": 457, "tag": "KEY", "value": "_generateCacheKey" }, { "context": "(LIB_DIR)\n fs.mkdirSyn...
src/cache.coffee
marquee/proto
7
crypto = require 'crypto' fs = require 'fs' rest = require 'restler' util = require 'util' { PRODUCTION, LIB_DIR } = require './SETTINGS' _generateCacheKey = (url) -> url_hash = crypto.createHash('md5') url_hash.update(url) ext = url.split('.').pop() return url_hash.digest('hex') + '.' + ext getCacheKey = (url) -> # Cache only works if running the local `proto` command. if not process.env.RUNNING_APP key = _generateCacheKey(url) if fs.existsSync(LIB_DIR + key) return key else return null else return null cacheFileFromURL = (remote_path) -> if not fs.existsSync(LIB_DIR) fs.mkdirSync(LIB_DIR) key = _generateCacheKey(remote_path) target_path = LIB_DIR + key util.log("Getting: #{ remote_path }") get_req = rest.get(remote_path) get_req.on 'complete', (data, response) -> if response.statusCode is 200 fs.writeFile target_path, data, (err) -> if err? util.log("Error saving #{ remote_path }: #{ err }") else util.log("Saved: #{ remote_path }") else util.log("Error: #{ response.statusCode }") util.log(data) loadFromCache = (key, cb=null) -> if cb? fs.readFile(LIB_DIR + key, 'utf8', cb) else return fs.readFileSync(LIB_DIR + key, 'utf8') module.exports = getCacheKey : getCacheKey cacheFileFromURL : cacheFileFromURL loadFromCache : loadFromCache
201607
crypto = require 'crypto' fs = require 'fs' rest = require 'restler' util = require 'util' { PRODUCTION, LIB_DIR } = require './SETTINGS' _generateCacheKey = (url) -> url_hash = crypto.createHash('md5') url_hash.update(url) ext = url.split('.').pop() return url_hash.digest('hex') + '.' + ext getCacheKey = (url) -> # Cache only works if running the local `proto` command. if not process.env.RUNNING_APP key = <KEY>(url) if fs.existsSync(LIB_DIR + key) return key else return null else return null cacheFileFromURL = (remote_path) -> if not fs.existsSync(LIB_DIR) fs.mkdirSync(LIB_DIR) key = <KEY>(remote_path) target_path = LIB_DIR + key util.log("Getting: #{ remote_path }") get_req = rest.get(remote_path) get_req.on 'complete', (data, response) -> if response.statusCode is 200 fs.writeFile target_path, data, (err) -> if err? util.log("Error saving #{ remote_path }: #{ err }") else util.log("Saved: #{ remote_path }") else util.log("Error: #{ response.statusCode }") util.log(data) loadFromCache = (key, cb=null) -> if cb? fs.readFile(LIB_DIR + key, 'utf8', cb) else return fs.readFileSync(LIB_DIR + key, 'utf8') module.exports = getCacheKey : getCacheKey cacheFileFromURL : cacheFileFromURL loadFromCache : loadFromCache
true
crypto = require 'crypto' fs = require 'fs' rest = require 'restler' util = require 'util' { PRODUCTION, LIB_DIR } = require './SETTINGS' _generateCacheKey = (url) -> url_hash = crypto.createHash('md5') url_hash.update(url) ext = url.split('.').pop() return url_hash.digest('hex') + '.' + ext getCacheKey = (url) -> # Cache only works if running the local `proto` command. if not process.env.RUNNING_APP key = PI:KEY:<KEY>END_PI(url) if fs.existsSync(LIB_DIR + key) return key else return null else return null cacheFileFromURL = (remote_path) -> if not fs.existsSync(LIB_DIR) fs.mkdirSync(LIB_DIR) key = PI:KEY:<KEY>END_PI(remote_path) target_path = LIB_DIR + key util.log("Getting: #{ remote_path }") get_req = rest.get(remote_path) get_req.on 'complete', (data, response) -> if response.statusCode is 200 fs.writeFile target_path, data, (err) -> if err? util.log("Error saving #{ remote_path }: #{ err }") else util.log("Saved: #{ remote_path }") else util.log("Error: #{ response.statusCode }") util.log(data) loadFromCache = (key, cb=null) -> if cb? fs.readFile(LIB_DIR + key, 'utf8', cb) else return fs.readFileSync(LIB_DIR + key, 'utf8') module.exports = getCacheKey : getCacheKey cacheFileFromURL : cacheFileFromURL loadFromCache : loadFromCache
[ { "context": "pe\": \"application/json\"\n \"trakt-api-key\": \"9823361b8f87af7e623796bb16cee09c8e8b026fb399e0b073ae32ce9ab951b5\"\n \"trakt-api-version\": \"2\"\n success = (", "end": 932, "score": 0.999773383140564, "start": 868, "tag": "KEY", "value": "9823361b8f87af7e623...
app/javascripts/services.coffee
riencroonenborghs/streamingTV
1
app = angular.module "streamingTV.services", [] app.service "TraktTVAPI", [ "$q", "$http", ($q, $http) -> apiPath: "https://api.trakt.tv" searchTvShows: (query) -> @_sendRequest "#{@apiPath}/search/show?query=#{query}&extended=full" tvShow: (tvShowId) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}?extended=full" tvShowSeasons: (tvShowId) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}/seasons?extended=full" tvShowSeason: (tvShowId, season) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}/seasons/#{season}?extended=full" tvShowEpisode: (tvShowId, season, episode) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}/seasons/#{season}/episodes/#{episode}?extended=full" _sendRequest: (url) -> deferred = $q.defer() options = method: "GET" url: url headers: "Content-Type": "application/json" "trakt-api-key": "9823361b8f87af7e623796bb16cee09c8e8b026fb399e0b073ae32ce9ab951b5" "trakt-api-version": "2" success = (response) => deferred.resolve response.data return failure = (response) -> deferred.reject response.data return $http(options).then(success, failure) return deferred.promise ]
91312
app = angular.module "streamingTV.services", [] app.service "TraktTVAPI", [ "$q", "$http", ($q, $http) -> apiPath: "https://api.trakt.tv" searchTvShows: (query) -> @_sendRequest "#{@apiPath}/search/show?query=#{query}&extended=full" tvShow: (tvShowId) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}?extended=full" tvShowSeasons: (tvShowId) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}/seasons?extended=full" tvShowSeason: (tvShowId, season) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}/seasons/#{season}?extended=full" tvShowEpisode: (tvShowId, season, episode) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}/seasons/#{season}/episodes/#{episode}?extended=full" _sendRequest: (url) -> deferred = $q.defer() options = method: "GET" url: url headers: "Content-Type": "application/json" "trakt-api-key": "<KEY>" "trakt-api-version": "2" success = (response) => deferred.resolve response.data return failure = (response) -> deferred.reject response.data return $http(options).then(success, failure) return deferred.promise ]
true
app = angular.module "streamingTV.services", [] app.service "TraktTVAPI", [ "$q", "$http", ($q, $http) -> apiPath: "https://api.trakt.tv" searchTvShows: (query) -> @_sendRequest "#{@apiPath}/search/show?query=#{query}&extended=full" tvShow: (tvShowId) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}?extended=full" tvShowSeasons: (tvShowId) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}/seasons?extended=full" tvShowSeason: (tvShowId, season) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}/seasons/#{season}?extended=full" tvShowEpisode: (tvShowId, season, episode) -> @_sendRequest "#{@apiPath}/shows/#{tvShowId}/seasons/#{season}/episodes/#{episode}?extended=full" _sendRequest: (url) -> deferred = $q.defer() options = method: "GET" url: url headers: "Content-Type": "application/json" "trakt-api-key": "PI:KEY:<KEY>END_PI" "trakt-api-version": "2" success = (response) => deferred.resolve response.data return failure = (response) -> deferred.reject response.data return $http(options).then(success, failure) return deferred.promise ]
[ { "context": "collection_name]\n\nHouston._session = () ->\n key = Houston._houstonize(arguments[0])\n if arguments.length == 1\n retur", "end": 929, "score": 0.9358378648757935, "start": 909, "tag": "KEY", "value": "Houston._houstonize(" } ]
client/zma_helpers.coffee
matteodem/houston
1
if Handlebars? Handlebars.registerHelper('onHoustonPage', -> window.location.pathname.indexOf('/admin') == 0) Houston._collections ?= {} # regardless of what version of meteor we are using, # get the right LocalCollection Houston._get_collection = (collection_name) -> unless Houston._collections[collection_name] try # you can only instantiate a collection once Houston._collections[collection_name] = new Meteor.Collection(collection_name) catch e try # works for 0.6.6.2+ Houston._collections[collection_name] = \ Meteor.connection._mongo_livedata_collections[collection_name] catch e # old versions of meteor (older than 0.6.6.2) Houston._collections[collection_name] = Meteor._LocalCollectionDriver.collections[collection_name] return Houston._collections[collection_name] Houston._session = () -> key = Houston._houstonize(arguments[0]) if arguments.length == 1 return Session.get(key) else if arguments.length == 2 Session.set(key, arguments[1]) Houston._call = (name, args...) -> Meteor.call(Houston._houstonize(name), args...) Houston._nested_field_lookup = (object, path) -> return '' unless object? return object._id._str if path =='_id'and typeof object._id == 'object' result = object for part in path.split(".") result = result[part] return '' unless result? # quit if you can't find anything here # Return date objects and other non-object types if typeof result isnt 'object' or result instanceof Date return result else return ''
20504
if Handlebars? Handlebars.registerHelper('onHoustonPage', -> window.location.pathname.indexOf('/admin') == 0) Houston._collections ?= {} # regardless of what version of meteor we are using, # get the right LocalCollection Houston._get_collection = (collection_name) -> unless Houston._collections[collection_name] try # you can only instantiate a collection once Houston._collections[collection_name] = new Meteor.Collection(collection_name) catch e try # works for 0.6.6.2+ Houston._collections[collection_name] = \ Meteor.connection._mongo_livedata_collections[collection_name] catch e # old versions of meteor (older than 0.6.6.2) Houston._collections[collection_name] = Meteor._LocalCollectionDriver.collections[collection_name] return Houston._collections[collection_name] Houston._session = () -> key = <KEY>arguments[0]) if arguments.length == 1 return Session.get(key) else if arguments.length == 2 Session.set(key, arguments[1]) Houston._call = (name, args...) -> Meteor.call(Houston._houstonize(name), args...) Houston._nested_field_lookup = (object, path) -> return '' unless object? return object._id._str if path =='_id'and typeof object._id == 'object' result = object for part in path.split(".") result = result[part] return '' unless result? # quit if you can't find anything here # Return date objects and other non-object types if typeof result isnt 'object' or result instanceof Date return result else return ''
true
if Handlebars? Handlebars.registerHelper('onHoustonPage', -> window.location.pathname.indexOf('/admin') == 0) Houston._collections ?= {} # regardless of what version of meteor we are using, # get the right LocalCollection Houston._get_collection = (collection_name) -> unless Houston._collections[collection_name] try # you can only instantiate a collection once Houston._collections[collection_name] = new Meteor.Collection(collection_name) catch e try # works for 0.6.6.2+ Houston._collections[collection_name] = \ Meteor.connection._mongo_livedata_collections[collection_name] catch e # old versions of meteor (older than 0.6.6.2) Houston._collections[collection_name] = Meteor._LocalCollectionDriver.collections[collection_name] return Houston._collections[collection_name] Houston._session = () -> key = PI:KEY:<KEY>END_PIarguments[0]) if arguments.length == 1 return Session.get(key) else if arguments.length == 2 Session.set(key, arguments[1]) Houston._call = (name, args...) -> Meteor.call(Houston._houstonize(name), args...) Houston._nested_field_lookup = (object, path) -> return '' unless object? return object._id._str if path =='_id'and typeof object._id == 'object' result = object for part in path.split(".") result = result[part] return '' unless result? # quit if you can't find anything here # Return date objects and other non-object types if typeof result isnt 'object' or result instanceof Date return result else return ''