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": " links\n\n\t\t\t\t\t# First : app -> other app\n\t\t\t\t\tkey = \"#{call.caller}:#{call.called}:#{call.starttime}\"\n\n\t\t\t\t\tif not links[key]?\n\t\t\t\t\t\tlinks[key] = new L",
"end": 12347,
"score": 0.9380872249603271,
"start": 12298,
"tag": "KEY",
"value": "\"#{call.caller}:#{call.called}:#{call.starttime}\""
},
{
"context": ".value)\n\n\n\t\t\t\t\t# Next : app->services\n\n\t\t\t\t\tkey = \"#{call.service}:#{call.starttime}\"\n\t\t\t\t\tif not links[key]?\n\t\t\t\t\t\tlinks[key] = new Li",
"end": 12528,
"score": 0.9823643565177917,
"start": 12493,
"tag": "KEY",
"value": "\"#{call.service}:#{call.starttime}\""
},
{
"context": ".value)\n\n\t\t\t\t\t# Next : service->method\n\n\t\t\t\t\tkey = \"#{call.service}:#{method}:#{call.starttime}\"\n\n\t\t\t\t\tif not links[key]?\n\t\t\t\t\t\tlinks[key] = new L",
"end": 12757,
"score": 0.9790834784507751,
"start": 12712,
"tag": "KEY",
"value": "\"#{call.service}:#{method}:#{call.starttime}\""
}
] | modules/postgresConnector/PostgresConnector.coffee | ggeoffrey/Choregraphie | 1 | pg = require 'pg'
async = require 'async'
Call = require './Call'
Node = require './Node'
Link = require './Link'
Event = require './Event'
appConfig = require '../../config'
#
# Connect to a PostgreSQL database according to the local config file.
#
class Connector
# Read config, connect to Postgre and ensure the cache is flushed at least every 10 minutes
# @param config [Object] config given by index.coffee
constructor : ( config ) ->
@cache = {}
if not @connectionString?
@connectionString = "postgres://#{config.user}"
if config.pass?
@connectionString += ":#{config.pass}"
@connectionString += "@#{config.host}/#{config.databaseName}"
# Empty cache every 10 minutes
setInterval ->
cache = {}
, 600
# Get a client from the connections pool
# @param callback [Function] callback called with **[client, doneCallback]**. Call the doneCallback to release the connexion to the pool.
getClient : (callback)->
pg.connect @connectionString, (err, client, done)->
if err?
console.warn(err)
else
callback(client, done)
#
# Hold all the methods used to communicate with database.
#
# These methods are, except a few of them, the same as API methods
class Connector.PostgresConnector
# Create a PostgresConnector containing a raw node-pg instance
constructor : (config)->
@connector = new Connector(config)
# Get applications from database
# @param forceUpdate [Boolean] ignore cache and update it
getApplications : (callback, forceUpdate) ->
# Read from config if data are limited to it
if appConfig.limitDataToConfigSpecifiedList is true
callback(appConfig.apps or [])
else
# read from database if config allows it
queryText = "
SELECT DISTINCT codeapp
FROM ccol.appli
ORDER BY codeapp;
"
if not @connector.cache.applications? or forceUpdate is on
@connector.getClient (client, done)=>
query = client.query queryText
result = []
query.on 'row', (row)-> result.push row.codeapp
query.on 'end', =>
callback(result)
done()
@connector.cache.applications = result
query.on 'error', (err) -> console.log(err)
else
callback(@connector.cache.applications)
# Get an array of corridors name from database
# @param forceUpdate [Boolean] ignore cache and update it
getCorridors : (callback, forceUpdate)->
# Read from config if data are limited to it
if appConfig.limitDataToConfigSpecifiedList is true
callback(appConfig.corridors or [])
else
# read from database if config allows it
queryText = "
SELECT DISTINCT couloir
FROM ccol.appli
ORDER BY couloir
;
"
if not @connector.cache.corridors? or forceUpdate is on
@connector.getClient (client, done)=>
query = client.query queryText
result = []
query.on 'row', (row)-> result.push row.couloir
query.on 'end', =>
callback(result)
done()
@connector.cache.corridors = result
query.on 'error', (err) -> console.log(err)
else
callback(@connector.cache.corridors)
# Get an Array of Events from db
# @param forceUpdate [Boolean] ignore cache and update it
getEvents : (callback, forceUpdate)->
queryText = "
SELECT codeapp, couloir, codetype, start_time, seen, deleted, old_value, value, diff_stddev, type, id
FROM ccol.metric_events
GROUP BY start_time, codeapp, couloir, type, codetype, seen, deleted, old_value, value, diff_stddev, type, id
ORDER BY start_time DESC;
"
if not @connector.cache.events? or forceUpdate is on
@connector.getClient (client, done)=>
query = client.query queryText
result = []
query.on 'row', (row)-> result.push new Event(row)
query.on 'end', =>
callback(result)
done()
@connector.cache.events = result
query.on 'error', (err) -> console.log(err)
else
callback(@connector.cache.events)
# UPDATE an event in database, tracking by event.id
#
# Only event.seen and event.deleted are UPDATEed
# @param event [Object] Event to persist
setEvent : (callback, event) ->
queryText = "
UPDATE ccol.metric_events
SET seen = $1, deleted = $2
WHERE id = $3
;
"
@connector.getClient (client, done)=>
query = client.query queryText, [event.seen, event.deleted, event.id]
query.on 'end', (result)=>
callback(result.rowCount > 0)
delete @connector.cache.events
done()
query.on 'error', (err)->
throw err
# Get an OverviewData Object from database
# @param forceUpdate [Boolean] ignore cache and update it
getOverviewData : (callback, forceUpdate)->
queryText = "
SELECT mv.codeapp, mv.couloir, mv.codetype, mv.start_time, SUM(mv.value) AS value, ms.sante
FROM metric_value mv, metric_stats ms
WHERE mv.couloir LIKE 'X_%'
AND mv.couloir = ms.couloir
AND mv.codeapp = ms.codeapp
AND mv.start_time >= (
SELECT max(start_time) as start_time from metric_stats
)
AND mv.start_time::date = ms.start_time::date
GROUP by mv.couloir, mv.codeapp, mv.codetype, mv.start_time, ms.sante
;
"
if @connector.cache.overviewData? and not forceUpdate?
callback(@connector.cache.overviewData)
else
@connector.getClient (client, done)=>
query = client.query(queryText)
result = []
query.on 'row', (row)-> result.push(row)
query.on 'error', (err)-> console.warn(err)
query.on 'end', ->
groupByApplication(result)
done()
computeAbsMax = (array)->
max = -Infinity
absVal = 0
for item in array
absVal = Math.abs(item)
if absVal > max
max = absVal
return max
groupByApplication = (data)=>
mapper = {}
listResult = []
types = {}
if data.length > 0
for item in data
types[item.codetype] = item.codetype
if not mapper[item.codeapp]?
mapper[item.codeapp] = item
item.detailSante = []
item.types = {}
if not mapper[item.codeapp].types[item.codetype]?
typeStat =
value : 0
detailSante : []
resSante : null
mapper[item.codeapp].types[item.codetype] = typeStat
mapper[item.codeapp].types[item.codetype].value += parseInt(item.value, 10)
mapper[item.codeapp].types[item.codetype].detailSante.push(item.sante)
mapper[item.codeapp].detailSante.push(item.sante)
for codeapp, item of mapper
absMax = null
for codetype, stats of item.types
mapper[codeapp].types[codetype].resSante = computeAbsMax(stats.detailSante)
delete mapper[codeapp].types[codetype].detailSante
for codetype, v of types
if mapper[codeapp].types? and not mapper[codeapp].types[codetype]?
mapper[codeapp].types[codetype] =
value: 0
detailSante: []
resSante: null
mapper[codeapp].resSante = computeAbsMax(item.detailSante)
delete mapper[codeapp].detailSante
listResult.push(mapper[codeapp])
callback(listResult)
@connector.cache.overviewData = listResult
# Get an array of Values
# @param forceUpdate [Boolean] ignore cache and update it
# @param options [Object]
# @option app [String] app's name
# @option corridor [String] corridor's name
getHistory : (callback, forceUpdate, options)->
if options.app is 'all' and options.corridor is 'all'
options.app = '%'
options.corridor = '%'
if not options.limit?
options.limit = null
queryTextRecords = "
SELECT codeapp, couloir, start_time as startTime, code, codetype, value
FROM ccol.metric_value
WHERE code <> 'INCONNUE'
AND codetype NOT LIKE 'nb_appelFI'
AND codeapp LIKE $1
AND couloir LIKE $2
ORDER BY startTime ASC
LIMIT $3
;
"
getRecords = (next)=>
@connector.getClient (client, done)=>
query = client.query(queryTextRecords, [options.app, options.corridor, options.limit])
result = []
query.on 'row', (row)-> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(null, result)
done()
queryTextCalls = "
SELECT codeapp, couloir, start_time as startTime, code, codetype, value
FROM ccol.metric_value
WHERE code <> 'INCONNUE'
AND codetype LIKE 'nb_transaction_http'
AND codeapp LIKE $1
AND couloir LIKE $2
ORDER BY startTime ASC
LIMIT $3
;
"
getCalls = (next)=>
@connector.getClient (client, done)->
query = client.query(queryTextCalls, [options.app, options.corridor, options.limit])
result = []
query.on 'row', (row) -> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(null, result)
done()
async.parallel
reports: getRecords
calls: getCalls
, (err, result)->
callsMapper = {}
{reports, calls} = result
for call in calls
index = call.starttime
if callsMapper[index]?
callsMapper[index] += call.value
else
callsMapper[index] = call.value
for report in reports
index = report.starttime
if callsMapper[index]?
report.http = callsMapper[index]
callback(reports)
# Get an array of Values
# @param forceUpdate [Boolean] ignore cache and update it
# @param options [Object]
# @option app [String] app's name
# @option corridor [String] corridor's name
getTrend : (callback, forceUpdate, options)->
queryText = "
SELECT codetype, start_time as starttime, somme, average, stddev, sante
FROM ccol.metric_stats
WHERE codeapp = $1
AND couloir = $2
;
"
@connector.getClient (client, done)=>
query = client.query(queryText, [options.app, options.corridor])
result = []
query.on 'row', (row) -> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(result)
done()
next = (result)->
mapper = {}
for record in result
key = record.codetype
formatedRecord =
somme: record.somme
average: record.average
stddev: record.stddev
starttime: record.starttime
if not mapper[key]?
mapper[key] = []
mapper[key].push(formatedRecord)
callback(mapper)
# Get a callTree
# @param forceUpdate [Boolean] ignore cache and update it
getCalls : (callback, forceUpdate)->
queryText = "
SELECT codeapp, code, couloir, sum(value) as value, codetype, extract(epoch FROM date_trunc('day', start_time))*1000::bigint as starttime
FROM metric_value
WHERE codetype LIKE 'nb_appelFI%'
AND code LIKE '0%'
GROUP BY codeapp, starttime, code, couloir, codetype
ORDER BY starttime
;
"
if @connector.cache.calls? and not forceUpdate?
callback(@connector.cache.calls)
else
@connector.getClient (client, done)=>
query = client.query(queryText)
result = []
query.on 'row', (row) -> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(result)
done()
next = (data)->
calls = []
for row in data
{codeapp, codetype, code, couloir, value, starttime} = row
call = new Call(codeapp, codetype, code, couloir, value, starttime)
calls.push(call)
createCallTree(calls)
createCallTree = (calls)=>
nodes = {}
links = {}
for call in calls
# Caller node
leafName = call.caller
if not nodes[leafName]?
nodes[leafName] = new Node(leafName, 'Application')
# Called node
leafName = call.called
if not nodes[leafName]?
nodes[leafName] = new Node(leafName, 'Application')
# Service (of the called node)
service = call.service
if not nodes[service]?
nodes[service] = new Node(service, 'Service')
# Method (of the called node)
method = "#{call.service}::#{call.method}"
if not nodes[method]?
nodes[method] = new Node(method, 'Method', 0)
else
nodes[method].add(call.value)
# Now we have nodes, we need to build the links
# First : app -> other app
key = "#{call.caller}:#{call.called}:#{call.starttime}"
if not links[key]?
links[key] = new Link(call)
else
links[key].add(call.value)
# Next : app->services
key = "#{call.service}:#{call.starttime}"
if not links[key]?
links[key] = new Link(call)
links[key].target = call.service
else
links[key].add(call.value)
# Next : service->method
key = "#{call.service}:#{method}:#{call.starttime}"
if not links[key]?
links[key] = new Link(call)
links[key].source = call.service
links[key].target = method
else
links[key].add(call.value)
# convert links from object to array
linksArray = []
for key, link of links
linksArray.push(link)
delete links[key] # will help the GC
# we put all in a single object
mapper =
nodes: nodes
links: linksArray
callback(mapper)
@connector.cache.calls = mapper
module.exports = Connector.PostgresConnector | 129754 | pg = require 'pg'
async = require 'async'
Call = require './Call'
Node = require './Node'
Link = require './Link'
Event = require './Event'
appConfig = require '../../config'
#
# Connect to a PostgreSQL database according to the local config file.
#
class Connector
# Read config, connect to Postgre and ensure the cache is flushed at least every 10 minutes
# @param config [Object] config given by index.coffee
constructor : ( config ) ->
@cache = {}
if not @connectionString?
@connectionString = "postgres://#{config.user}"
if config.pass?
@connectionString += ":#{config.pass}"
@connectionString += "@#{config.host}/#{config.databaseName}"
# Empty cache every 10 minutes
setInterval ->
cache = {}
, 600
# Get a client from the connections pool
# @param callback [Function] callback called with **[client, doneCallback]**. Call the doneCallback to release the connexion to the pool.
getClient : (callback)->
pg.connect @connectionString, (err, client, done)->
if err?
console.warn(err)
else
callback(client, done)
#
# Hold all the methods used to communicate with database.
#
# These methods are, except a few of them, the same as API methods
class Connector.PostgresConnector
# Create a PostgresConnector containing a raw node-pg instance
constructor : (config)->
@connector = new Connector(config)
# Get applications from database
# @param forceUpdate [Boolean] ignore cache and update it
getApplications : (callback, forceUpdate) ->
# Read from config if data are limited to it
if appConfig.limitDataToConfigSpecifiedList is true
callback(appConfig.apps or [])
else
# read from database if config allows it
queryText = "
SELECT DISTINCT codeapp
FROM ccol.appli
ORDER BY codeapp;
"
if not @connector.cache.applications? or forceUpdate is on
@connector.getClient (client, done)=>
query = client.query queryText
result = []
query.on 'row', (row)-> result.push row.codeapp
query.on 'end', =>
callback(result)
done()
@connector.cache.applications = result
query.on 'error', (err) -> console.log(err)
else
callback(@connector.cache.applications)
# Get an array of corridors name from database
# @param forceUpdate [Boolean] ignore cache and update it
getCorridors : (callback, forceUpdate)->
# Read from config if data are limited to it
if appConfig.limitDataToConfigSpecifiedList is true
callback(appConfig.corridors or [])
else
# read from database if config allows it
queryText = "
SELECT DISTINCT couloir
FROM ccol.appli
ORDER BY couloir
;
"
if not @connector.cache.corridors? or forceUpdate is on
@connector.getClient (client, done)=>
query = client.query queryText
result = []
query.on 'row', (row)-> result.push row.couloir
query.on 'end', =>
callback(result)
done()
@connector.cache.corridors = result
query.on 'error', (err) -> console.log(err)
else
callback(@connector.cache.corridors)
# Get an Array of Events from db
# @param forceUpdate [Boolean] ignore cache and update it
getEvents : (callback, forceUpdate)->
queryText = "
SELECT codeapp, couloir, codetype, start_time, seen, deleted, old_value, value, diff_stddev, type, id
FROM ccol.metric_events
GROUP BY start_time, codeapp, couloir, type, codetype, seen, deleted, old_value, value, diff_stddev, type, id
ORDER BY start_time DESC;
"
if not @connector.cache.events? or forceUpdate is on
@connector.getClient (client, done)=>
query = client.query queryText
result = []
query.on 'row', (row)-> result.push new Event(row)
query.on 'end', =>
callback(result)
done()
@connector.cache.events = result
query.on 'error', (err) -> console.log(err)
else
callback(@connector.cache.events)
# UPDATE an event in database, tracking by event.id
#
# Only event.seen and event.deleted are UPDATEed
# @param event [Object] Event to persist
setEvent : (callback, event) ->
queryText = "
UPDATE ccol.metric_events
SET seen = $1, deleted = $2
WHERE id = $3
;
"
@connector.getClient (client, done)=>
query = client.query queryText, [event.seen, event.deleted, event.id]
query.on 'end', (result)=>
callback(result.rowCount > 0)
delete @connector.cache.events
done()
query.on 'error', (err)->
throw err
# Get an OverviewData Object from database
# @param forceUpdate [Boolean] ignore cache and update it
getOverviewData : (callback, forceUpdate)->
queryText = "
SELECT mv.codeapp, mv.couloir, mv.codetype, mv.start_time, SUM(mv.value) AS value, ms.sante
FROM metric_value mv, metric_stats ms
WHERE mv.couloir LIKE 'X_%'
AND mv.couloir = ms.couloir
AND mv.codeapp = ms.codeapp
AND mv.start_time >= (
SELECT max(start_time) as start_time from metric_stats
)
AND mv.start_time::date = ms.start_time::date
GROUP by mv.couloir, mv.codeapp, mv.codetype, mv.start_time, ms.sante
;
"
if @connector.cache.overviewData? and not forceUpdate?
callback(@connector.cache.overviewData)
else
@connector.getClient (client, done)=>
query = client.query(queryText)
result = []
query.on 'row', (row)-> result.push(row)
query.on 'error', (err)-> console.warn(err)
query.on 'end', ->
groupByApplication(result)
done()
computeAbsMax = (array)->
max = -Infinity
absVal = 0
for item in array
absVal = Math.abs(item)
if absVal > max
max = absVal
return max
groupByApplication = (data)=>
mapper = {}
listResult = []
types = {}
if data.length > 0
for item in data
types[item.codetype] = item.codetype
if not mapper[item.codeapp]?
mapper[item.codeapp] = item
item.detailSante = []
item.types = {}
if not mapper[item.codeapp].types[item.codetype]?
typeStat =
value : 0
detailSante : []
resSante : null
mapper[item.codeapp].types[item.codetype] = typeStat
mapper[item.codeapp].types[item.codetype].value += parseInt(item.value, 10)
mapper[item.codeapp].types[item.codetype].detailSante.push(item.sante)
mapper[item.codeapp].detailSante.push(item.sante)
for codeapp, item of mapper
absMax = null
for codetype, stats of item.types
mapper[codeapp].types[codetype].resSante = computeAbsMax(stats.detailSante)
delete mapper[codeapp].types[codetype].detailSante
for codetype, v of types
if mapper[codeapp].types? and not mapper[codeapp].types[codetype]?
mapper[codeapp].types[codetype] =
value: 0
detailSante: []
resSante: null
mapper[codeapp].resSante = computeAbsMax(item.detailSante)
delete mapper[codeapp].detailSante
listResult.push(mapper[codeapp])
callback(listResult)
@connector.cache.overviewData = listResult
# Get an array of Values
# @param forceUpdate [Boolean] ignore cache and update it
# @param options [Object]
# @option app [String] app's name
# @option corridor [String] corridor's name
getHistory : (callback, forceUpdate, options)->
if options.app is 'all' and options.corridor is 'all'
options.app = '%'
options.corridor = '%'
if not options.limit?
options.limit = null
queryTextRecords = "
SELECT codeapp, couloir, start_time as startTime, code, codetype, value
FROM ccol.metric_value
WHERE code <> 'INCONNUE'
AND codetype NOT LIKE 'nb_appelFI'
AND codeapp LIKE $1
AND couloir LIKE $2
ORDER BY startTime ASC
LIMIT $3
;
"
getRecords = (next)=>
@connector.getClient (client, done)=>
query = client.query(queryTextRecords, [options.app, options.corridor, options.limit])
result = []
query.on 'row', (row)-> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(null, result)
done()
queryTextCalls = "
SELECT codeapp, couloir, start_time as startTime, code, codetype, value
FROM ccol.metric_value
WHERE code <> 'INCONNUE'
AND codetype LIKE 'nb_transaction_http'
AND codeapp LIKE $1
AND couloir LIKE $2
ORDER BY startTime ASC
LIMIT $3
;
"
getCalls = (next)=>
@connector.getClient (client, done)->
query = client.query(queryTextCalls, [options.app, options.corridor, options.limit])
result = []
query.on 'row', (row) -> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(null, result)
done()
async.parallel
reports: getRecords
calls: getCalls
, (err, result)->
callsMapper = {}
{reports, calls} = result
for call in calls
index = call.starttime
if callsMapper[index]?
callsMapper[index] += call.value
else
callsMapper[index] = call.value
for report in reports
index = report.starttime
if callsMapper[index]?
report.http = callsMapper[index]
callback(reports)
# Get an array of Values
# @param forceUpdate [Boolean] ignore cache and update it
# @param options [Object]
# @option app [String] app's name
# @option corridor [String] corridor's name
getTrend : (callback, forceUpdate, options)->
queryText = "
SELECT codetype, start_time as starttime, somme, average, stddev, sante
FROM ccol.metric_stats
WHERE codeapp = $1
AND couloir = $2
;
"
@connector.getClient (client, done)=>
query = client.query(queryText, [options.app, options.corridor])
result = []
query.on 'row', (row) -> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(result)
done()
next = (result)->
mapper = {}
for record in result
key = record.codetype
formatedRecord =
somme: record.somme
average: record.average
stddev: record.stddev
starttime: record.starttime
if not mapper[key]?
mapper[key] = []
mapper[key].push(formatedRecord)
callback(mapper)
# Get a callTree
# @param forceUpdate [Boolean] ignore cache and update it
getCalls : (callback, forceUpdate)->
queryText = "
SELECT codeapp, code, couloir, sum(value) as value, codetype, extract(epoch FROM date_trunc('day', start_time))*1000::bigint as starttime
FROM metric_value
WHERE codetype LIKE 'nb_appelFI%'
AND code LIKE '0%'
GROUP BY codeapp, starttime, code, couloir, codetype
ORDER BY starttime
;
"
if @connector.cache.calls? and not forceUpdate?
callback(@connector.cache.calls)
else
@connector.getClient (client, done)=>
query = client.query(queryText)
result = []
query.on 'row', (row) -> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(result)
done()
next = (data)->
calls = []
for row in data
{codeapp, codetype, code, couloir, value, starttime} = row
call = new Call(codeapp, codetype, code, couloir, value, starttime)
calls.push(call)
createCallTree(calls)
createCallTree = (calls)=>
nodes = {}
links = {}
for call in calls
# Caller node
leafName = call.caller
if not nodes[leafName]?
nodes[leafName] = new Node(leafName, 'Application')
# Called node
leafName = call.called
if not nodes[leafName]?
nodes[leafName] = new Node(leafName, 'Application')
# Service (of the called node)
service = call.service
if not nodes[service]?
nodes[service] = new Node(service, 'Service')
# Method (of the called node)
method = "#{call.service}::#{call.method}"
if not nodes[method]?
nodes[method] = new Node(method, 'Method', 0)
else
nodes[method].add(call.value)
# Now we have nodes, we need to build the links
# First : app -> other app
key = <KEY>
if not links[key]?
links[key] = new Link(call)
else
links[key].add(call.value)
# Next : app->services
key = <KEY>
if not links[key]?
links[key] = new Link(call)
links[key].target = call.service
else
links[key].add(call.value)
# Next : service->method
key = <KEY>
if not links[key]?
links[key] = new Link(call)
links[key].source = call.service
links[key].target = method
else
links[key].add(call.value)
# convert links from object to array
linksArray = []
for key, link of links
linksArray.push(link)
delete links[key] # will help the GC
# we put all in a single object
mapper =
nodes: nodes
links: linksArray
callback(mapper)
@connector.cache.calls = mapper
module.exports = Connector.PostgresConnector | true | pg = require 'pg'
async = require 'async'
Call = require './Call'
Node = require './Node'
Link = require './Link'
Event = require './Event'
appConfig = require '../../config'
#
# Connect to a PostgreSQL database according to the local config file.
#
class Connector
# Read config, connect to Postgre and ensure the cache is flushed at least every 10 minutes
# @param config [Object] config given by index.coffee
constructor : ( config ) ->
@cache = {}
if not @connectionString?
@connectionString = "postgres://#{config.user}"
if config.pass?
@connectionString += ":#{config.pass}"
@connectionString += "@#{config.host}/#{config.databaseName}"
# Empty cache every 10 minutes
setInterval ->
cache = {}
, 600
# Get a client from the connections pool
# @param callback [Function] callback called with **[client, doneCallback]**. Call the doneCallback to release the connexion to the pool.
getClient : (callback)->
pg.connect @connectionString, (err, client, done)->
if err?
console.warn(err)
else
callback(client, done)
#
# Hold all the methods used to communicate with database.
#
# These methods are, except a few of them, the same as API methods
class Connector.PostgresConnector
# Create a PostgresConnector containing a raw node-pg instance
constructor : (config)->
@connector = new Connector(config)
# Get applications from database
# @param forceUpdate [Boolean] ignore cache and update it
getApplications : (callback, forceUpdate) ->
# Read from config if data are limited to it
if appConfig.limitDataToConfigSpecifiedList is true
callback(appConfig.apps or [])
else
# read from database if config allows it
queryText = "
SELECT DISTINCT codeapp
FROM ccol.appli
ORDER BY codeapp;
"
if not @connector.cache.applications? or forceUpdate is on
@connector.getClient (client, done)=>
query = client.query queryText
result = []
query.on 'row', (row)-> result.push row.codeapp
query.on 'end', =>
callback(result)
done()
@connector.cache.applications = result
query.on 'error', (err) -> console.log(err)
else
callback(@connector.cache.applications)
# Get an array of corridors name from database
# @param forceUpdate [Boolean] ignore cache and update it
getCorridors : (callback, forceUpdate)->
# Read from config if data are limited to it
if appConfig.limitDataToConfigSpecifiedList is true
callback(appConfig.corridors or [])
else
# read from database if config allows it
queryText = "
SELECT DISTINCT couloir
FROM ccol.appli
ORDER BY couloir
;
"
if not @connector.cache.corridors? or forceUpdate is on
@connector.getClient (client, done)=>
query = client.query queryText
result = []
query.on 'row', (row)-> result.push row.couloir
query.on 'end', =>
callback(result)
done()
@connector.cache.corridors = result
query.on 'error', (err) -> console.log(err)
else
callback(@connector.cache.corridors)
# Get an Array of Events from db
# @param forceUpdate [Boolean] ignore cache and update it
getEvents : (callback, forceUpdate)->
queryText = "
SELECT codeapp, couloir, codetype, start_time, seen, deleted, old_value, value, diff_stddev, type, id
FROM ccol.metric_events
GROUP BY start_time, codeapp, couloir, type, codetype, seen, deleted, old_value, value, diff_stddev, type, id
ORDER BY start_time DESC;
"
if not @connector.cache.events? or forceUpdate is on
@connector.getClient (client, done)=>
query = client.query queryText
result = []
query.on 'row', (row)-> result.push new Event(row)
query.on 'end', =>
callback(result)
done()
@connector.cache.events = result
query.on 'error', (err) -> console.log(err)
else
callback(@connector.cache.events)
# UPDATE an event in database, tracking by event.id
#
# Only event.seen and event.deleted are UPDATEed
# @param event [Object] Event to persist
setEvent : (callback, event) ->
queryText = "
UPDATE ccol.metric_events
SET seen = $1, deleted = $2
WHERE id = $3
;
"
@connector.getClient (client, done)=>
query = client.query queryText, [event.seen, event.deleted, event.id]
query.on 'end', (result)=>
callback(result.rowCount > 0)
delete @connector.cache.events
done()
query.on 'error', (err)->
throw err
# Get an OverviewData Object from database
# @param forceUpdate [Boolean] ignore cache and update it
getOverviewData : (callback, forceUpdate)->
queryText = "
SELECT mv.codeapp, mv.couloir, mv.codetype, mv.start_time, SUM(mv.value) AS value, ms.sante
FROM metric_value mv, metric_stats ms
WHERE mv.couloir LIKE 'X_%'
AND mv.couloir = ms.couloir
AND mv.codeapp = ms.codeapp
AND mv.start_time >= (
SELECT max(start_time) as start_time from metric_stats
)
AND mv.start_time::date = ms.start_time::date
GROUP by mv.couloir, mv.codeapp, mv.codetype, mv.start_time, ms.sante
;
"
if @connector.cache.overviewData? and not forceUpdate?
callback(@connector.cache.overviewData)
else
@connector.getClient (client, done)=>
query = client.query(queryText)
result = []
query.on 'row', (row)-> result.push(row)
query.on 'error', (err)-> console.warn(err)
query.on 'end', ->
groupByApplication(result)
done()
computeAbsMax = (array)->
max = -Infinity
absVal = 0
for item in array
absVal = Math.abs(item)
if absVal > max
max = absVal
return max
groupByApplication = (data)=>
mapper = {}
listResult = []
types = {}
if data.length > 0
for item in data
types[item.codetype] = item.codetype
if not mapper[item.codeapp]?
mapper[item.codeapp] = item
item.detailSante = []
item.types = {}
if not mapper[item.codeapp].types[item.codetype]?
typeStat =
value : 0
detailSante : []
resSante : null
mapper[item.codeapp].types[item.codetype] = typeStat
mapper[item.codeapp].types[item.codetype].value += parseInt(item.value, 10)
mapper[item.codeapp].types[item.codetype].detailSante.push(item.sante)
mapper[item.codeapp].detailSante.push(item.sante)
for codeapp, item of mapper
absMax = null
for codetype, stats of item.types
mapper[codeapp].types[codetype].resSante = computeAbsMax(stats.detailSante)
delete mapper[codeapp].types[codetype].detailSante
for codetype, v of types
if mapper[codeapp].types? and not mapper[codeapp].types[codetype]?
mapper[codeapp].types[codetype] =
value: 0
detailSante: []
resSante: null
mapper[codeapp].resSante = computeAbsMax(item.detailSante)
delete mapper[codeapp].detailSante
listResult.push(mapper[codeapp])
callback(listResult)
@connector.cache.overviewData = listResult
# Get an array of Values
# @param forceUpdate [Boolean] ignore cache and update it
# @param options [Object]
# @option app [String] app's name
# @option corridor [String] corridor's name
getHistory : (callback, forceUpdate, options)->
if options.app is 'all' and options.corridor is 'all'
options.app = '%'
options.corridor = '%'
if not options.limit?
options.limit = null
queryTextRecords = "
SELECT codeapp, couloir, start_time as startTime, code, codetype, value
FROM ccol.metric_value
WHERE code <> 'INCONNUE'
AND codetype NOT LIKE 'nb_appelFI'
AND codeapp LIKE $1
AND couloir LIKE $2
ORDER BY startTime ASC
LIMIT $3
;
"
getRecords = (next)=>
@connector.getClient (client, done)=>
query = client.query(queryTextRecords, [options.app, options.corridor, options.limit])
result = []
query.on 'row', (row)-> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(null, result)
done()
queryTextCalls = "
SELECT codeapp, couloir, start_time as startTime, code, codetype, value
FROM ccol.metric_value
WHERE code <> 'INCONNUE'
AND codetype LIKE 'nb_transaction_http'
AND codeapp LIKE $1
AND couloir LIKE $2
ORDER BY startTime ASC
LIMIT $3
;
"
getCalls = (next)=>
@connector.getClient (client, done)->
query = client.query(queryTextCalls, [options.app, options.corridor, options.limit])
result = []
query.on 'row', (row) -> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(null, result)
done()
async.parallel
reports: getRecords
calls: getCalls
, (err, result)->
callsMapper = {}
{reports, calls} = result
for call in calls
index = call.starttime
if callsMapper[index]?
callsMapper[index] += call.value
else
callsMapper[index] = call.value
for report in reports
index = report.starttime
if callsMapper[index]?
report.http = callsMapper[index]
callback(reports)
# Get an array of Values
# @param forceUpdate [Boolean] ignore cache and update it
# @param options [Object]
# @option app [String] app's name
# @option corridor [String] corridor's name
getTrend : (callback, forceUpdate, options)->
queryText = "
SELECT codetype, start_time as starttime, somme, average, stddev, sante
FROM ccol.metric_stats
WHERE codeapp = $1
AND couloir = $2
;
"
@connector.getClient (client, done)=>
query = client.query(queryText, [options.app, options.corridor])
result = []
query.on 'row', (row) -> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(result)
done()
next = (result)->
mapper = {}
for record in result
key = record.codetype
formatedRecord =
somme: record.somme
average: record.average
stddev: record.stddev
starttime: record.starttime
if not mapper[key]?
mapper[key] = []
mapper[key].push(formatedRecord)
callback(mapper)
# Get a callTree
# @param forceUpdate [Boolean] ignore cache and update it
getCalls : (callback, forceUpdate)->
queryText = "
SELECT codeapp, code, couloir, sum(value) as value, codetype, extract(epoch FROM date_trunc('day', start_time))*1000::bigint as starttime
FROM metric_value
WHERE codetype LIKE 'nb_appelFI%'
AND code LIKE '0%'
GROUP BY codeapp, starttime, code, couloir, codetype
ORDER BY starttime
;
"
if @connector.cache.calls? and not forceUpdate?
callback(@connector.cache.calls)
else
@connector.getClient (client, done)=>
query = client.query(queryText)
result = []
query.on 'row', (row) -> result.push(row)
query.on 'error', (error)-> console.warn(error)
query.on 'end', ->
next(result)
done()
next = (data)->
calls = []
for row in data
{codeapp, codetype, code, couloir, value, starttime} = row
call = new Call(codeapp, codetype, code, couloir, value, starttime)
calls.push(call)
createCallTree(calls)
createCallTree = (calls)=>
nodes = {}
links = {}
for call in calls
# Caller node
leafName = call.caller
if not nodes[leafName]?
nodes[leafName] = new Node(leafName, 'Application')
# Called node
leafName = call.called
if not nodes[leafName]?
nodes[leafName] = new Node(leafName, 'Application')
# Service (of the called node)
service = call.service
if not nodes[service]?
nodes[service] = new Node(service, 'Service')
# Method (of the called node)
method = "#{call.service}::#{call.method}"
if not nodes[method]?
nodes[method] = new Node(method, 'Method', 0)
else
nodes[method].add(call.value)
# Now we have nodes, we need to build the links
# First : app -> other app
key = PI:KEY:<KEY>END_PI
if not links[key]?
links[key] = new Link(call)
else
links[key].add(call.value)
# Next : app->services
key = PI:KEY:<KEY>END_PI
if not links[key]?
links[key] = new Link(call)
links[key].target = call.service
else
links[key].add(call.value)
# Next : service->method
key = PI:KEY:<KEY>END_PI
if not links[key]?
links[key] = new Link(call)
links[key].source = call.service
links[key].target = method
else
links[key].add(call.value)
# convert links from object to array
linksArray = []
for key, link of links
linksArray.push(link)
delete links[key] # will help the GC
# we put all in a single object
mapper =
nodes: nodes
links: linksArray
callback(mapper)
@connector.cache.calls = mapper
module.exports = Connector.PostgresConnector |
[
{
"context": "styles` directory for available options.\n key = \"css-#{variables}-#{styles}\"\n if cache[key] then return done null, ca",
"end": 3622,
"score": 0.9189561009407043,
"start": 3603,
"tag": "KEY",
"value": "css-#{variables}-#{"
},
{
"context": "ilable options.\n key = \"css-#{variables}-#{styles}\"\n if cache[key] then return done null, cache[key]",
"end": 3628,
"score": 0.5458217263221741,
"start": 3628,
"tag": "KEY",
"value": ""
},
{
"context": " necessary, and cache it for future use.\n key = \"template-#{name}\"\n\n # Check if it is cached in memory. If not, the",
"end": 6311,
"score": 0.9985243082046509,
"start": 6294,
"tag": "KEY",
"value": "template-#{name}\""
}
] | src/main.coffee | googoid/aglio-theme-smartaxi | 0 | crypto = require 'crypto'
fs = require 'fs'
hljs = require 'highlight.js'
jade = require 'jade'
less = require 'less'
markdownIt = require 'markdown-it'
moment = require 'moment'
path = require 'path'
querystring = require 'querystring'
# The root directory of this project
ROOT = path.dirname __dirname
cache = {}
# Utility for benchmarking
benchmark =
start: (message) -> if process.env.BENCHMARK then console.time message
end: (message) -> if process.env.BENCHMARK then console.timeEnd message
# Extend an error's message. Returns the modified error.
errMsg = (message, err) ->
err.message = "#{message}: #{err.message}"
return err
# Generate a SHA1 hash
sha1 = (value) ->
crypto.createHash('sha1').update(value.toString()).digest('hex')
# A function to create ID-safe slugs. If `unique` is passed, then
# unique slugs are returned for the same input. The cache is just
# a plain object where the keys are the sluggified name.
slug = (cache={}, value='', unique=false) ->
sluggified = value.toLowerCase()
.replace(/[ \t\n\\<>"'=:/]/g, '-')
.replace(/-+/g, '-')
.replace(/^-/, '')
if unique
while cache[sluggified]
# Already exists, so let's try to make it unique.
if sluggified.match /\d+$/
sluggified = sluggified.replace /\d+$/, (value) ->
parseInt(value) + 1
else
sluggified = sluggified + '-1'
cache[sluggified] = true
return sluggified
# A function to highlight snippets of code. lang is optional and
# if given, is used to set the code language. If lang is no-highlight
# then no highlighting is performed.
highlight = (code, lang, subset) ->
benchmark.start "highlight #{lang}"
response = switch lang
when 'no-highlight' then code
when undefined, null, ''
hljs.highlightAuto(code, subset).value
else hljs.highlight(lang, code).value
benchmark.end "highlight #{lang}"
return response.trim()
getCached = (key, compiledPath, sources, load, done) ->
# Disable the template/css caching?
if process.env.NOCACHE then return done null
# Already loaded? Just return it!
if cache[key] then return done null, cache[key]
# Next, try to check if the compiled path exists and is newer than all of
# the sources. If so, load the compiled path into the in-memory cache.
try
if fs.existsSync compiledPath
compiledStats = fs.statSync compiledPath
for source in sources
sourceStats = fs.statSync source
if sourceStats.mtime > compiledStats.mtime
# There is a newer source file, so we ignore the compiled
# version on disk. It'll be regenerated later.
return done null
try
load compiledPath, (err, item) ->
if err then return done(errMsg 'Error loading cached resource', err)
cache[key] = item
done null, cache[key]
catch loadErr
return done(errMsg 'Error loading cached resource', loadErr)
else
done null
catch err
done err
getCss = (variables, styles, verbose, done) ->
# Get the CSS for the given variables and style. This method caches
# its output, so subsequent calls will be extremely fast but will
# not reload potentially changed data from disk.
# The CSS is generated via a dummy LESS file with imports to the
# default variables, any custom override variables, and the given
# layout style. Both variables and style support special values,
# for example `flatly` might load `styles/variables-flatly.less`.
# See the `styles` directory for available options.
key = "css-#{variables}-#{styles}"
if cache[key] then return done null, cache[key]
# Not cached in memory, but maybe it's already compiled on disk?
compiledPath = path.join ROOT, 'cache',
"#{sha1 key}.css"
defaultVariablePath = path.join ROOT, 'styles', 'variables-default.less'
sources = [defaultVariablePath]
if not Array.isArray(variables) then variables = [variables]
if not Array.isArray(styles) then styles = [styles]
variablePaths = [defaultVariablePath]
for item in variables
if item isnt 'default'
customPath = path.join ROOT, 'styles', "variables-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
variablePaths.push customPath
sources.push customPath
stylePaths = []
for item in styles
customPath = path.join ROOT, 'styles', "layout-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
stylePaths.push customPath
sources.push customPath
load = (filename, loadDone) ->
fs.readFile filename, 'utf-8', loadDone
if verbose
console.log "Using variables #{variablePaths}"
console.log "Using styles #{stylePaths}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, sources, load, (err, css) ->
if err then return done err
if css
if verbose then console.log 'Cached version loaded'
return done null, css
# Not cached, so let's create the file.
if verbose
console.log 'Not cached or out of date. Generating CSS...'
tmp = ''
for customPath in variablePaths
tmp += "@import \"#{customPath}\";\n"
for customPath in stylePaths
tmp += "@import \"#{customPath}\";\n"
benchmark.start 'less-compile'
less.render tmp, compress: true, (err, result) ->
if err then return done(msgErr 'Error processing LESS -> CSS', err)
try
css = result.css
fs.writeFileSync compiledPath, css, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached CSS to file', writeErr)
benchmark.end 'less-compile'
cache[key] = css
done null, cache[key]
compileTemplate = (filename, options) ->
compiled = """
var jade = require('jade/runtime');
#{jade.compileFileClient filename, options}
module.exports = compiledFunc;
"""
getTemplate = (name, verbose, done) ->
# Get the template function for the given path. This will load and
# compile the template if necessary, and cache it for future use.
key = "template-#{name}"
# Check if it is cached in memory. If not, then we'll check the disk.
if cache[key] then return done null, cache[key]
# Check if it is compiled on disk and not older than the template file.
# If not present or outdated, then we'll need to compile it.
compiledPath = path.join ROOT, 'cache', "#{sha1 key}.js"
load = (filename, loadDone) ->
try
loaded = require(filename)
catch loadErr
return loadDone(errMsg 'Unable to load template', loadErr)
loadDone null, require(filename)
if verbose
console.log "Using template #{name}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, [name], load, (err, template) ->
if err then return done err
if template
if verbose then console.log 'Cached version loaded'
return done null, template
if verbose
console.log 'Not cached or out of date. Generating template JS...'
# We need to compile the template, then cache it. This is interesting
# because we are compiling to a client-side template, then adding some
# module-specific code to make it work here. This allows us to save time
# in the future by just loading the generated javascript function.
benchmark.start 'jade-compile'
compileOptions =
filename: name
name: 'compiledFunc'
self: true
compileDebug: false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
if compiled.indexOf('self.') is -1
# Not using self, so we probably need to recompile into compatibility
# mode. This is slower, but keeps things working with Jade files
# designed for Aglio 1.x.
compileOptions.self = false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
try
fs.writeFileSync compiledPath, compiled, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached template file', writeErr)
benchmark.end 'jade-compile'
cache[key] = require(compiledPath)
done null, cache[key]
modifyUriTemplate = (templateUri, parameters) ->
# Modify a URI template to only include the parameter names from
# the given parameters. For example:
# URI template: /pages/{id}{?verbose}
# Parameters contains a single `id` parameter
# Output: /pages/{id}
parameterValidator = (b) ->
# Compare the names, removing the special `*` operator
parameters.indexOf(querystring.unescape b.replace(/^\*|\*$/, '')) isnt -1
parameters = (param.name for param in parameters)
parameterBlocks = []
lastIndex = index = 0
while (index = templateUri.indexOf("{", index)) isnt - 1
parameterBlocks.push templateUri.substring(lastIndex, index)
block = {}
closeIndex = templateUri.indexOf("}", index)
block.querySet = templateUri.indexOf("{?", index) is index
block.formSet = templateUri.indexOf("{&", index) is index
block.reservedSet = templateUri.indexOf("{+", index) is index
lastIndex = closeIndex + 1
index++
index++ if block.querySet
parameterSet = templateUri.substring(index, closeIndex)
block.parameters = parameterSet.split(",").filter(parameterValidator)
parameterBlocks.push block if block.parameters.length
parameterBlocks.push templateUri.substring(lastIndex, templateUri.length)
parameterBlocks.reduce((uri, v) ->
if typeof v is "string"
uri.push v
else
segment = ["{"]
segment.push "?" if v.querySet
segment.push "&" if v.formSet
segment.push "+" if v.reservedSet
segment.push v.parameters.join()
segment.push "}"
uri.push segment.join("")
uri
, []).join('').replace(/\/+/g, '/').replace(/\/$/, '')
decorate = (api, md, slugCache) ->
# Decorate an API Blueprint AST with various pieces of information that
# will be useful for the theme. Anything that would significantly
# complicate the Jade template should probably live here instead!
# Use the slug caching mechanism
slugify = slug.bind slug, slugCache
# API overview description
if api.description
api.descriptionHtml = md.render api.description
api.navItems = slugCache._nav
slugCache._nav = []
for resourceGroup in api.resourceGroups or []
# Element ID and link
resourceGroup.elementId = slugify resourceGroup.name, true
resourceGroup.elementLink = "##{resourceGroup.elementId}"
# Description
if resourceGroup.description
resourceGroup.descriptionHtml = md.render resourceGroup.description
resourceGroup.navItems = slugCache._nav
slugCache._nav = []
for resource in resourceGroup.resources or []
# Element ID and link
resource.elementId = slugify(
"#{resourceGroup.name}-#{resource.name}", true)
resource.elementLink = "##{resource.elementId}"
for action in resource.actions or []
# Element ID and link
action.elementId = slugify(
"#{resourceGroup.name}-#{resource.name}-#{action.method}", true)
action.elementLink = "##{action.elementId}"
# Lowercase HTTP method name
action.methodLower = action.method.toLowerCase()
# Parameters may be defined on the action or on the
# parent resource. Resource parameters should be concatenated
# to the action-specific parameters if set.
if not action.parameters or not action.parameters.length
action.parameters = resource.parameters
else if resource.parameters
action.parameters = resource.parameters.concat(action.parameters)
# Remove any duplicates! This gives precedence to the parameters
# defined on the action.
knownParams = {}
newParams = []
reversed = (action.parameters or []).concat([]).reverse()
for param in reversed
if knownParams[param.name] then continue
knownParams[param.name] = true
newParams.push param
action.parameters = newParams.reverse()
# Set up the action's template URI
action.uriTemplate = modifyUriTemplate(
(action.attributes or {}).uriTemplate or resource.uriTemplate or '',
action.parameters)
# Examples have a content section only if they have a
# description, headers, body, or schema.
for example in action.examples or []
for name in ['requests', 'responses']
for item in example[name] or []
item.hasContent = item.description or \
Object.keys(item.headers).length or \
item.body or \
item.schema
# If possible, make the body/schema pretty
try
if item.body
item.body = JSON.stringify(JSON.parse(item.body), null, 2)
if item.schema
item.schema = JSON.stringify(JSON.parse(item.schema), null, 2)
catch err
false
# Get the theme's configuration, used by Aglio to present available
# options and confirm that the input blueprint is a supported
# version.
exports.getConfig = ->
formats: ['1A']
options: [
{name: 'variables',
description: 'Color scheme name or path to custom variables',
default: 'default'},
{name: 'condense-nav', description: 'Condense navigation links',
boolean: true, default: true},
{name: 'full-width', description: 'Use full window width',
boolean: true, default: false},
{name: 'template', description: 'Template name or path to custom template',
default: 'default'},
{name: 'style',
description: 'Layout style name or path to custom stylesheet'}
]
# Render the blueprint with the given options using Jade and LESS
exports.render = (input, options, done) ->
if not done?
done = options
options = {}
# Disable the template/css caching?
if process.env.NOCACHE then cache = {}
# This is purely for backward-compatibility
if options.condenseNav then options.themeCondenseNav = options.condenseNav
if options.fullWidth then options.themeFullWidth = options.fullWidth
# Setup defaults
options.themeVariables ?= 'default'
options.themeStyle ?= 'default'
options.themeTemplate ?= 'default'
options.themeCondenseNav ?= true
options.themeFullWidth ?= false
# Transform built-in layout names to paths
if options.themeTemplate is 'default'
options.themeTemplate = path.join ROOT, 'templates', 'index.jade'
# Setup markdown with code highlighting and smartypants. This also enables
# automatically inserting permalinks for headers.
slugCache =
_nav: []
md = markdownIt(
html: true
linkify: true
typographer: true
highlight: highlight
).use(require('markdown-it-anchor'),
slugify: (value) ->
output = "header-#{slug(slugCache, value, true)}"
slugCache._nav.push [value, "##{output}"]
return output
permalink: true
permalinkClass: 'permalink'
).use(require('markdown-it-checkbox')
).use(require('markdown-it-container'), 'note'
).use(require('markdown-it-container'), 'warning')
#).use(require('markdown-it-emoji'))
# Enable code highlighting for unfenced code blocks
md.renderer.rules.code_block = md.renderer.rules.fence
benchmark.start 'decorate'
decorate input, md, slugCache
benchmark.end 'decorate'
benchmark.start 'css-total'
{themeVariables, themeStyle, verbose} = options
getCss themeVariables, themeStyle, verbose, (err, css) ->
if err then return done(errMsg 'Could not get CSS', err)
benchmark.end 'css-total'
locals =
api: input
condenseNav: options.themeCondenseNav
css: css
fullWidth: options.themeFullWidth
date: moment
hash: (value) ->
crypto.createHash('md5').update(value.toString()).digest('hex')
highlight: highlight
markdown: (content) -> md.render content
slug: slug.bind(slug, slugCache)
urldec: (value) -> querystring.unescape(value)
for key, value of options.locals or {}
locals[key] = value
benchmark.start 'get-template'
getTemplate options.themeTemplate, verbose, (getTemplateErr, renderer) ->
if getTemplateErr
return done(errMsg 'Could not get template', getTemplateErr)
benchmark.end 'get-template'
benchmark.start 'call-template'
try html = renderer locals
catch err
return done(errMsg 'Error calling template during rendering', err)
benchmark.end 'call-template'
done null, html
| 194529 | crypto = require 'crypto'
fs = require 'fs'
hljs = require 'highlight.js'
jade = require 'jade'
less = require 'less'
markdownIt = require 'markdown-it'
moment = require 'moment'
path = require 'path'
querystring = require 'querystring'
# The root directory of this project
ROOT = path.dirname __dirname
cache = {}
# Utility for benchmarking
benchmark =
start: (message) -> if process.env.BENCHMARK then console.time message
end: (message) -> if process.env.BENCHMARK then console.timeEnd message
# Extend an error's message. Returns the modified error.
errMsg = (message, err) ->
err.message = "#{message}: #{err.message}"
return err
# Generate a SHA1 hash
sha1 = (value) ->
crypto.createHash('sha1').update(value.toString()).digest('hex')
# A function to create ID-safe slugs. If `unique` is passed, then
# unique slugs are returned for the same input. The cache is just
# a plain object where the keys are the sluggified name.
slug = (cache={}, value='', unique=false) ->
sluggified = value.toLowerCase()
.replace(/[ \t\n\\<>"'=:/]/g, '-')
.replace(/-+/g, '-')
.replace(/^-/, '')
if unique
while cache[sluggified]
# Already exists, so let's try to make it unique.
if sluggified.match /\d+$/
sluggified = sluggified.replace /\d+$/, (value) ->
parseInt(value) + 1
else
sluggified = sluggified + '-1'
cache[sluggified] = true
return sluggified
# A function to highlight snippets of code. lang is optional and
# if given, is used to set the code language. If lang is no-highlight
# then no highlighting is performed.
highlight = (code, lang, subset) ->
benchmark.start "highlight #{lang}"
response = switch lang
when 'no-highlight' then code
when undefined, null, ''
hljs.highlightAuto(code, subset).value
else hljs.highlight(lang, code).value
benchmark.end "highlight #{lang}"
return response.trim()
getCached = (key, compiledPath, sources, load, done) ->
# Disable the template/css caching?
if process.env.NOCACHE then return done null
# Already loaded? Just return it!
if cache[key] then return done null, cache[key]
# Next, try to check if the compiled path exists and is newer than all of
# the sources. If so, load the compiled path into the in-memory cache.
try
if fs.existsSync compiledPath
compiledStats = fs.statSync compiledPath
for source in sources
sourceStats = fs.statSync source
if sourceStats.mtime > compiledStats.mtime
# There is a newer source file, so we ignore the compiled
# version on disk. It'll be regenerated later.
return done null
try
load compiledPath, (err, item) ->
if err then return done(errMsg 'Error loading cached resource', err)
cache[key] = item
done null, cache[key]
catch loadErr
return done(errMsg 'Error loading cached resource', loadErr)
else
done null
catch err
done err
getCss = (variables, styles, verbose, done) ->
# Get the CSS for the given variables and style. This method caches
# its output, so subsequent calls will be extremely fast but will
# not reload potentially changed data from disk.
# The CSS is generated via a dummy LESS file with imports to the
# default variables, any custom override variables, and the given
# layout style. Both variables and style support special values,
# for example `flatly` might load `styles/variables-flatly.less`.
# See the `styles` directory for available options.
key = "<KEY>styles<KEY>}"
if cache[key] then return done null, cache[key]
# Not cached in memory, but maybe it's already compiled on disk?
compiledPath = path.join ROOT, 'cache',
"#{sha1 key}.css"
defaultVariablePath = path.join ROOT, 'styles', 'variables-default.less'
sources = [defaultVariablePath]
if not Array.isArray(variables) then variables = [variables]
if not Array.isArray(styles) then styles = [styles]
variablePaths = [defaultVariablePath]
for item in variables
if item isnt 'default'
customPath = path.join ROOT, 'styles', "variables-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
variablePaths.push customPath
sources.push customPath
stylePaths = []
for item in styles
customPath = path.join ROOT, 'styles', "layout-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
stylePaths.push customPath
sources.push customPath
load = (filename, loadDone) ->
fs.readFile filename, 'utf-8', loadDone
if verbose
console.log "Using variables #{variablePaths}"
console.log "Using styles #{stylePaths}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, sources, load, (err, css) ->
if err then return done err
if css
if verbose then console.log 'Cached version loaded'
return done null, css
# Not cached, so let's create the file.
if verbose
console.log 'Not cached or out of date. Generating CSS...'
tmp = ''
for customPath in variablePaths
tmp += "@import \"#{customPath}\";\n"
for customPath in stylePaths
tmp += "@import \"#{customPath}\";\n"
benchmark.start 'less-compile'
less.render tmp, compress: true, (err, result) ->
if err then return done(msgErr 'Error processing LESS -> CSS', err)
try
css = result.css
fs.writeFileSync compiledPath, css, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached CSS to file', writeErr)
benchmark.end 'less-compile'
cache[key] = css
done null, cache[key]
compileTemplate = (filename, options) ->
compiled = """
var jade = require('jade/runtime');
#{jade.compileFileClient filename, options}
module.exports = compiledFunc;
"""
getTemplate = (name, verbose, done) ->
# Get the template function for the given path. This will load and
# compile the template if necessary, and cache it for future use.
key = "<KEY>
# Check if it is cached in memory. If not, then we'll check the disk.
if cache[key] then return done null, cache[key]
# Check if it is compiled on disk and not older than the template file.
# If not present or outdated, then we'll need to compile it.
compiledPath = path.join ROOT, 'cache', "#{sha1 key}.js"
load = (filename, loadDone) ->
try
loaded = require(filename)
catch loadErr
return loadDone(errMsg 'Unable to load template', loadErr)
loadDone null, require(filename)
if verbose
console.log "Using template #{name}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, [name], load, (err, template) ->
if err then return done err
if template
if verbose then console.log 'Cached version loaded'
return done null, template
if verbose
console.log 'Not cached or out of date. Generating template JS...'
# We need to compile the template, then cache it. This is interesting
# because we are compiling to a client-side template, then adding some
# module-specific code to make it work here. This allows us to save time
# in the future by just loading the generated javascript function.
benchmark.start 'jade-compile'
compileOptions =
filename: name
name: 'compiledFunc'
self: true
compileDebug: false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
if compiled.indexOf('self.') is -1
# Not using self, so we probably need to recompile into compatibility
# mode. This is slower, but keeps things working with Jade files
# designed for Aglio 1.x.
compileOptions.self = false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
try
fs.writeFileSync compiledPath, compiled, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached template file', writeErr)
benchmark.end 'jade-compile'
cache[key] = require(compiledPath)
done null, cache[key]
modifyUriTemplate = (templateUri, parameters) ->
# Modify a URI template to only include the parameter names from
# the given parameters. For example:
# URI template: /pages/{id}{?verbose}
# Parameters contains a single `id` parameter
# Output: /pages/{id}
parameterValidator = (b) ->
# Compare the names, removing the special `*` operator
parameters.indexOf(querystring.unescape b.replace(/^\*|\*$/, '')) isnt -1
parameters = (param.name for param in parameters)
parameterBlocks = []
lastIndex = index = 0
while (index = templateUri.indexOf("{", index)) isnt - 1
parameterBlocks.push templateUri.substring(lastIndex, index)
block = {}
closeIndex = templateUri.indexOf("}", index)
block.querySet = templateUri.indexOf("{?", index) is index
block.formSet = templateUri.indexOf("{&", index) is index
block.reservedSet = templateUri.indexOf("{+", index) is index
lastIndex = closeIndex + 1
index++
index++ if block.querySet
parameterSet = templateUri.substring(index, closeIndex)
block.parameters = parameterSet.split(",").filter(parameterValidator)
parameterBlocks.push block if block.parameters.length
parameterBlocks.push templateUri.substring(lastIndex, templateUri.length)
parameterBlocks.reduce((uri, v) ->
if typeof v is "string"
uri.push v
else
segment = ["{"]
segment.push "?" if v.querySet
segment.push "&" if v.formSet
segment.push "+" if v.reservedSet
segment.push v.parameters.join()
segment.push "}"
uri.push segment.join("")
uri
, []).join('').replace(/\/+/g, '/').replace(/\/$/, '')
decorate = (api, md, slugCache) ->
# Decorate an API Blueprint AST with various pieces of information that
# will be useful for the theme. Anything that would significantly
# complicate the Jade template should probably live here instead!
# Use the slug caching mechanism
slugify = slug.bind slug, slugCache
# API overview description
if api.description
api.descriptionHtml = md.render api.description
api.navItems = slugCache._nav
slugCache._nav = []
for resourceGroup in api.resourceGroups or []
# Element ID and link
resourceGroup.elementId = slugify resourceGroup.name, true
resourceGroup.elementLink = "##{resourceGroup.elementId}"
# Description
if resourceGroup.description
resourceGroup.descriptionHtml = md.render resourceGroup.description
resourceGroup.navItems = slugCache._nav
slugCache._nav = []
for resource in resourceGroup.resources or []
# Element ID and link
resource.elementId = slugify(
"#{resourceGroup.name}-#{resource.name}", true)
resource.elementLink = "##{resource.elementId}"
for action in resource.actions or []
# Element ID and link
action.elementId = slugify(
"#{resourceGroup.name}-#{resource.name}-#{action.method}", true)
action.elementLink = "##{action.elementId}"
# Lowercase HTTP method name
action.methodLower = action.method.toLowerCase()
# Parameters may be defined on the action or on the
# parent resource. Resource parameters should be concatenated
# to the action-specific parameters if set.
if not action.parameters or not action.parameters.length
action.parameters = resource.parameters
else if resource.parameters
action.parameters = resource.parameters.concat(action.parameters)
# Remove any duplicates! This gives precedence to the parameters
# defined on the action.
knownParams = {}
newParams = []
reversed = (action.parameters or []).concat([]).reverse()
for param in reversed
if knownParams[param.name] then continue
knownParams[param.name] = true
newParams.push param
action.parameters = newParams.reverse()
# Set up the action's template URI
action.uriTemplate = modifyUriTemplate(
(action.attributes or {}).uriTemplate or resource.uriTemplate or '',
action.parameters)
# Examples have a content section only if they have a
# description, headers, body, or schema.
for example in action.examples or []
for name in ['requests', 'responses']
for item in example[name] or []
item.hasContent = item.description or \
Object.keys(item.headers).length or \
item.body or \
item.schema
# If possible, make the body/schema pretty
try
if item.body
item.body = JSON.stringify(JSON.parse(item.body), null, 2)
if item.schema
item.schema = JSON.stringify(JSON.parse(item.schema), null, 2)
catch err
false
# Get the theme's configuration, used by Aglio to present available
# options and confirm that the input blueprint is a supported
# version.
exports.getConfig = ->
formats: ['1A']
options: [
{name: 'variables',
description: 'Color scheme name or path to custom variables',
default: 'default'},
{name: 'condense-nav', description: 'Condense navigation links',
boolean: true, default: true},
{name: 'full-width', description: 'Use full window width',
boolean: true, default: false},
{name: 'template', description: 'Template name or path to custom template',
default: 'default'},
{name: 'style',
description: 'Layout style name or path to custom stylesheet'}
]
# Render the blueprint with the given options using Jade and LESS
exports.render = (input, options, done) ->
if not done?
done = options
options = {}
# Disable the template/css caching?
if process.env.NOCACHE then cache = {}
# This is purely for backward-compatibility
if options.condenseNav then options.themeCondenseNav = options.condenseNav
if options.fullWidth then options.themeFullWidth = options.fullWidth
# Setup defaults
options.themeVariables ?= 'default'
options.themeStyle ?= 'default'
options.themeTemplate ?= 'default'
options.themeCondenseNav ?= true
options.themeFullWidth ?= false
# Transform built-in layout names to paths
if options.themeTemplate is 'default'
options.themeTemplate = path.join ROOT, 'templates', 'index.jade'
# Setup markdown with code highlighting and smartypants. This also enables
# automatically inserting permalinks for headers.
slugCache =
_nav: []
md = markdownIt(
html: true
linkify: true
typographer: true
highlight: highlight
).use(require('markdown-it-anchor'),
slugify: (value) ->
output = "header-#{slug(slugCache, value, true)}"
slugCache._nav.push [value, "##{output}"]
return output
permalink: true
permalinkClass: 'permalink'
).use(require('markdown-it-checkbox')
).use(require('markdown-it-container'), 'note'
).use(require('markdown-it-container'), 'warning')
#).use(require('markdown-it-emoji'))
# Enable code highlighting for unfenced code blocks
md.renderer.rules.code_block = md.renderer.rules.fence
benchmark.start 'decorate'
decorate input, md, slugCache
benchmark.end 'decorate'
benchmark.start 'css-total'
{themeVariables, themeStyle, verbose} = options
getCss themeVariables, themeStyle, verbose, (err, css) ->
if err then return done(errMsg 'Could not get CSS', err)
benchmark.end 'css-total'
locals =
api: input
condenseNav: options.themeCondenseNav
css: css
fullWidth: options.themeFullWidth
date: moment
hash: (value) ->
crypto.createHash('md5').update(value.toString()).digest('hex')
highlight: highlight
markdown: (content) -> md.render content
slug: slug.bind(slug, slugCache)
urldec: (value) -> querystring.unescape(value)
for key, value of options.locals or {}
locals[key] = value
benchmark.start 'get-template'
getTemplate options.themeTemplate, verbose, (getTemplateErr, renderer) ->
if getTemplateErr
return done(errMsg 'Could not get template', getTemplateErr)
benchmark.end 'get-template'
benchmark.start 'call-template'
try html = renderer locals
catch err
return done(errMsg 'Error calling template during rendering', err)
benchmark.end 'call-template'
done null, html
| true | crypto = require 'crypto'
fs = require 'fs'
hljs = require 'highlight.js'
jade = require 'jade'
less = require 'less'
markdownIt = require 'markdown-it'
moment = require 'moment'
path = require 'path'
querystring = require 'querystring'
# The root directory of this project
ROOT = path.dirname __dirname
cache = {}
# Utility for benchmarking
benchmark =
start: (message) -> if process.env.BENCHMARK then console.time message
end: (message) -> if process.env.BENCHMARK then console.timeEnd message
# Extend an error's message. Returns the modified error.
errMsg = (message, err) ->
err.message = "#{message}: #{err.message}"
return err
# Generate a SHA1 hash
sha1 = (value) ->
crypto.createHash('sha1').update(value.toString()).digest('hex')
# A function to create ID-safe slugs. If `unique` is passed, then
# unique slugs are returned for the same input. The cache is just
# a plain object where the keys are the sluggified name.
slug = (cache={}, value='', unique=false) ->
sluggified = value.toLowerCase()
.replace(/[ \t\n\\<>"'=:/]/g, '-')
.replace(/-+/g, '-')
.replace(/^-/, '')
if unique
while cache[sluggified]
# Already exists, so let's try to make it unique.
if sluggified.match /\d+$/
sluggified = sluggified.replace /\d+$/, (value) ->
parseInt(value) + 1
else
sluggified = sluggified + '-1'
cache[sluggified] = true
return sluggified
# A function to highlight snippets of code. lang is optional and
# if given, is used to set the code language. If lang is no-highlight
# then no highlighting is performed.
highlight = (code, lang, subset) ->
benchmark.start "highlight #{lang}"
response = switch lang
when 'no-highlight' then code
when undefined, null, ''
hljs.highlightAuto(code, subset).value
else hljs.highlight(lang, code).value
benchmark.end "highlight #{lang}"
return response.trim()
getCached = (key, compiledPath, sources, load, done) ->
# Disable the template/css caching?
if process.env.NOCACHE then return done null
# Already loaded? Just return it!
if cache[key] then return done null, cache[key]
# Next, try to check if the compiled path exists and is newer than all of
# the sources. If so, load the compiled path into the in-memory cache.
try
if fs.existsSync compiledPath
compiledStats = fs.statSync compiledPath
for source in sources
sourceStats = fs.statSync source
if sourceStats.mtime > compiledStats.mtime
# There is a newer source file, so we ignore the compiled
# version on disk. It'll be regenerated later.
return done null
try
load compiledPath, (err, item) ->
if err then return done(errMsg 'Error loading cached resource', err)
cache[key] = item
done null, cache[key]
catch loadErr
return done(errMsg 'Error loading cached resource', loadErr)
else
done null
catch err
done err
getCss = (variables, styles, verbose, done) ->
# Get the CSS for the given variables and style. This method caches
# its output, so subsequent calls will be extremely fast but will
# not reload potentially changed data from disk.
# The CSS is generated via a dummy LESS file with imports to the
# default variables, any custom override variables, and the given
# layout style. Both variables and style support special values,
# for example `flatly` might load `styles/variables-flatly.less`.
# See the `styles` directory for available options.
key = "PI:KEY:<KEY>END_PIstylesPI:KEY:<KEY>END_PI}"
if cache[key] then return done null, cache[key]
# Not cached in memory, but maybe it's already compiled on disk?
compiledPath = path.join ROOT, 'cache',
"#{sha1 key}.css"
defaultVariablePath = path.join ROOT, 'styles', 'variables-default.less'
sources = [defaultVariablePath]
if not Array.isArray(variables) then variables = [variables]
if not Array.isArray(styles) then styles = [styles]
variablePaths = [defaultVariablePath]
for item in variables
if item isnt 'default'
customPath = path.join ROOT, 'styles', "variables-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
variablePaths.push customPath
sources.push customPath
stylePaths = []
for item in styles
customPath = path.join ROOT, 'styles', "layout-#{item}.less"
if not fs.existsSync customPath
customPath = item
if not fs.existsSync customPath
return done new Error "#{customPath} does not exist!"
stylePaths.push customPath
sources.push customPath
load = (filename, loadDone) ->
fs.readFile filename, 'utf-8', loadDone
if verbose
console.log "Using variables #{variablePaths}"
console.log "Using styles #{stylePaths}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, sources, load, (err, css) ->
if err then return done err
if css
if verbose then console.log 'Cached version loaded'
return done null, css
# Not cached, so let's create the file.
if verbose
console.log 'Not cached or out of date. Generating CSS...'
tmp = ''
for customPath in variablePaths
tmp += "@import \"#{customPath}\";\n"
for customPath in stylePaths
tmp += "@import \"#{customPath}\";\n"
benchmark.start 'less-compile'
less.render tmp, compress: true, (err, result) ->
if err then return done(msgErr 'Error processing LESS -> CSS', err)
try
css = result.css
fs.writeFileSync compiledPath, css, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached CSS to file', writeErr)
benchmark.end 'less-compile'
cache[key] = css
done null, cache[key]
compileTemplate = (filename, options) ->
compiled = """
var jade = require('jade/runtime');
#{jade.compileFileClient filename, options}
module.exports = compiledFunc;
"""
getTemplate = (name, verbose, done) ->
# Get the template function for the given path. This will load and
# compile the template if necessary, and cache it for future use.
key = "PI:KEY:<KEY>END_PI
# Check if it is cached in memory. If not, then we'll check the disk.
if cache[key] then return done null, cache[key]
# Check if it is compiled on disk and not older than the template file.
# If not present or outdated, then we'll need to compile it.
compiledPath = path.join ROOT, 'cache', "#{sha1 key}.js"
load = (filename, loadDone) ->
try
loaded = require(filename)
catch loadErr
return loadDone(errMsg 'Unable to load template', loadErr)
loadDone null, require(filename)
if verbose
console.log "Using template #{name}"
console.log "Checking cache #{compiledPath}"
getCached key, compiledPath, [name], load, (err, template) ->
if err then return done err
if template
if verbose then console.log 'Cached version loaded'
return done null, template
if verbose
console.log 'Not cached or out of date. Generating template JS...'
# We need to compile the template, then cache it. This is interesting
# because we are compiling to a client-side template, then adding some
# module-specific code to make it work here. This allows us to save time
# in the future by just loading the generated javascript function.
benchmark.start 'jade-compile'
compileOptions =
filename: name
name: 'compiledFunc'
self: true
compileDebug: false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
if compiled.indexOf('self.') is -1
# Not using self, so we probably need to recompile into compatibility
# mode. This is slower, but keeps things working with Jade files
# designed for Aglio 1.x.
compileOptions.self = false
try
compiled = compileTemplate name, compileOptions
catch compileErr
return done(errMsg 'Error compiling template', compileErr)
try
fs.writeFileSync compiledPath, compiled, 'utf-8'
catch writeErr
return done(errMsg 'Error writing cached template file', writeErr)
benchmark.end 'jade-compile'
cache[key] = require(compiledPath)
done null, cache[key]
modifyUriTemplate = (templateUri, parameters) ->
# Modify a URI template to only include the parameter names from
# the given parameters. For example:
# URI template: /pages/{id}{?verbose}
# Parameters contains a single `id` parameter
# Output: /pages/{id}
parameterValidator = (b) ->
# Compare the names, removing the special `*` operator
parameters.indexOf(querystring.unescape b.replace(/^\*|\*$/, '')) isnt -1
parameters = (param.name for param in parameters)
parameterBlocks = []
lastIndex = index = 0
while (index = templateUri.indexOf("{", index)) isnt - 1
parameterBlocks.push templateUri.substring(lastIndex, index)
block = {}
closeIndex = templateUri.indexOf("}", index)
block.querySet = templateUri.indexOf("{?", index) is index
block.formSet = templateUri.indexOf("{&", index) is index
block.reservedSet = templateUri.indexOf("{+", index) is index
lastIndex = closeIndex + 1
index++
index++ if block.querySet
parameterSet = templateUri.substring(index, closeIndex)
block.parameters = parameterSet.split(",").filter(parameterValidator)
parameterBlocks.push block if block.parameters.length
parameterBlocks.push templateUri.substring(lastIndex, templateUri.length)
parameterBlocks.reduce((uri, v) ->
if typeof v is "string"
uri.push v
else
segment = ["{"]
segment.push "?" if v.querySet
segment.push "&" if v.formSet
segment.push "+" if v.reservedSet
segment.push v.parameters.join()
segment.push "}"
uri.push segment.join("")
uri
, []).join('').replace(/\/+/g, '/').replace(/\/$/, '')
decorate = (api, md, slugCache) ->
# Decorate an API Blueprint AST with various pieces of information that
# will be useful for the theme. Anything that would significantly
# complicate the Jade template should probably live here instead!
# Use the slug caching mechanism
slugify = slug.bind slug, slugCache
# API overview description
if api.description
api.descriptionHtml = md.render api.description
api.navItems = slugCache._nav
slugCache._nav = []
for resourceGroup in api.resourceGroups or []
# Element ID and link
resourceGroup.elementId = slugify resourceGroup.name, true
resourceGroup.elementLink = "##{resourceGroup.elementId}"
# Description
if resourceGroup.description
resourceGroup.descriptionHtml = md.render resourceGroup.description
resourceGroup.navItems = slugCache._nav
slugCache._nav = []
for resource in resourceGroup.resources or []
# Element ID and link
resource.elementId = slugify(
"#{resourceGroup.name}-#{resource.name}", true)
resource.elementLink = "##{resource.elementId}"
for action in resource.actions or []
# Element ID and link
action.elementId = slugify(
"#{resourceGroup.name}-#{resource.name}-#{action.method}", true)
action.elementLink = "##{action.elementId}"
# Lowercase HTTP method name
action.methodLower = action.method.toLowerCase()
# Parameters may be defined on the action or on the
# parent resource. Resource parameters should be concatenated
# to the action-specific parameters if set.
if not action.parameters or not action.parameters.length
action.parameters = resource.parameters
else if resource.parameters
action.parameters = resource.parameters.concat(action.parameters)
# Remove any duplicates! This gives precedence to the parameters
# defined on the action.
knownParams = {}
newParams = []
reversed = (action.parameters or []).concat([]).reverse()
for param in reversed
if knownParams[param.name] then continue
knownParams[param.name] = true
newParams.push param
action.parameters = newParams.reverse()
# Set up the action's template URI
action.uriTemplate = modifyUriTemplate(
(action.attributes or {}).uriTemplate or resource.uriTemplate or '',
action.parameters)
# Examples have a content section only if they have a
# description, headers, body, or schema.
for example in action.examples or []
for name in ['requests', 'responses']
for item in example[name] or []
item.hasContent = item.description or \
Object.keys(item.headers).length or \
item.body or \
item.schema
# If possible, make the body/schema pretty
try
if item.body
item.body = JSON.stringify(JSON.parse(item.body), null, 2)
if item.schema
item.schema = JSON.stringify(JSON.parse(item.schema), null, 2)
catch err
false
# Get the theme's configuration, used by Aglio to present available
# options and confirm that the input blueprint is a supported
# version.
exports.getConfig = ->
formats: ['1A']
options: [
{name: 'variables',
description: 'Color scheme name or path to custom variables',
default: 'default'},
{name: 'condense-nav', description: 'Condense navigation links',
boolean: true, default: true},
{name: 'full-width', description: 'Use full window width',
boolean: true, default: false},
{name: 'template', description: 'Template name or path to custom template',
default: 'default'},
{name: 'style',
description: 'Layout style name or path to custom stylesheet'}
]
# Render the blueprint with the given options using Jade and LESS
exports.render = (input, options, done) ->
if not done?
done = options
options = {}
# Disable the template/css caching?
if process.env.NOCACHE then cache = {}
# This is purely for backward-compatibility
if options.condenseNav then options.themeCondenseNav = options.condenseNav
if options.fullWidth then options.themeFullWidth = options.fullWidth
# Setup defaults
options.themeVariables ?= 'default'
options.themeStyle ?= 'default'
options.themeTemplate ?= 'default'
options.themeCondenseNav ?= true
options.themeFullWidth ?= false
# Transform built-in layout names to paths
if options.themeTemplate is 'default'
options.themeTemplate = path.join ROOT, 'templates', 'index.jade'
# Setup markdown with code highlighting and smartypants. This also enables
# automatically inserting permalinks for headers.
slugCache =
_nav: []
md = markdownIt(
html: true
linkify: true
typographer: true
highlight: highlight
).use(require('markdown-it-anchor'),
slugify: (value) ->
output = "header-#{slug(slugCache, value, true)}"
slugCache._nav.push [value, "##{output}"]
return output
permalink: true
permalinkClass: 'permalink'
).use(require('markdown-it-checkbox')
).use(require('markdown-it-container'), 'note'
).use(require('markdown-it-container'), 'warning')
#).use(require('markdown-it-emoji'))
# Enable code highlighting for unfenced code blocks
md.renderer.rules.code_block = md.renderer.rules.fence
benchmark.start 'decorate'
decorate input, md, slugCache
benchmark.end 'decorate'
benchmark.start 'css-total'
{themeVariables, themeStyle, verbose} = options
getCss themeVariables, themeStyle, verbose, (err, css) ->
if err then return done(errMsg 'Could not get CSS', err)
benchmark.end 'css-total'
locals =
api: input
condenseNav: options.themeCondenseNav
css: css
fullWidth: options.themeFullWidth
date: moment
hash: (value) ->
crypto.createHash('md5').update(value.toString()).digest('hex')
highlight: highlight
markdown: (content) -> md.render content
slug: slug.bind(slug, slugCache)
urldec: (value) -> querystring.unescape(value)
for key, value of options.locals or {}
locals[key] = value
benchmark.start 'get-template'
getTemplate options.themeTemplate, verbose, (getTemplateErr, renderer) ->
if getTemplateErr
return done(errMsg 'Could not get template', getTemplateErr)
benchmark.end 'get-template'
benchmark.start 'call-template'
try html = renderer locals
catch err
return done(errMsg 'Error calling template during rendering', err)
benchmark.end 'call-template'
done null, html
|
[
{
"context": "///\nCopyright 2016 Anthony Shaw, Dimension Data\n\nLicensed under the Apache Licens",
"end": 31,
"score": 0.9998396039009094,
"start": 19,
"tag": "NAME",
"value": "Anthony Shaw"
}
] | src/spark.coffee | viveksyngh/hubot-spark | 14 | ///
Copyright 2016 Anthony Shaw, Dimension Data
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
///
Bluebird = require('bluebird')
Adapter = require('hubot').Adapter
TextMessage = require('hubot').TextMessage
EventEmitter = require('events').EventEmitter
SparkApi = require('./spark-api')
class SparkAdapter extends Adapter
constructor: (robot) ->
super
send: (envelope, strings...) ->
user = if envelope.user then envelope.user else envelope.room
strings.forEach (str) =>
@prepare_string str, (message) =>
@bot.send user, message
reply: (envelope, strings...) ->
user = if envelope.user then envelope.user else envelope
strings.forEach (str) =>
@prepare_string str,(message) =>
@bot.reply user, message
prepare_string: (str, callback) ->
text = str
messages = [str]
messages.forEach (message) =>
callback message
run: ->
self = @
options =
api_uri: process.env.HUBOT_SPARK_API_URI or "https://api.ciscospark.com/v1"
refresh: process.env.HUBOT_SPARK_REFRESH or 10000
access_token: process.env.HUBOT_SPARK_ACCESS_TOKEN
rooms : process.env.HUBOT_SPARK_ROOMS
bot = new SparkRealtime(options, @robot)
bot.init(options, @robot).then((roomIds) ->
self.robot.logger.debug "Created bot, setting up listeners"
roomIds.forEach((roomId) ->
bot.listen roomId, new Date().toISOString(), (messages, roomId) =>
self.robot.logger.debug "Fired listener callback for #{roomId}"
messages.forEach (message) =>
text = message.text
user =
name: message.personEmail
id: message.personId
roomId: message.roomId
self.robot.logger.debug "Received #{text} from #{user.name}"
# self.robot.send user, text
self.robot.receive new TextMessage user, text
)
self.robot.logger.debug "Done with custom bot logic"
self.bot = bot
self.emit 'connected'
)
class SparkRealtime extends EventEmitter
self = @
logger = undefined
spark = undefined
constructor: (options, robot) ->
@room_ids = []
if not options.access_token?
throw new Error "Not enough parameters provided. I need an access token"
@refresh = parseInt(options.refresh)
init: (options, robot) ->
@robot = robot
logger = @robot.logger
logger.info "Trying connection to #{options.api_uri}"
spark = new SparkApi
uri: options.api_uri
token: options.access_token
return spark.init().then(() ->
logger.debug "Connected as a bot? #{spark.isBot()}"
logger.info "Created connection instance to Spark"
roomIds = []
options.rooms.split(',').forEach (roomId) =>
roomIds.push roomId
logger.debug "Completed adding rooms to list"
Bluebird.resolve(roomIds)
).catch((err) ->
throw new Error "Failed to connect to Spark: #{err}"
)
## Spark API call methods
listen: (roomId, date, callback) ->
newDate = new Date().toISOString()
spark.getMessages(roomId: roomId).then((msges) =>
@robot.logger.debug "Messages recived: ", msges.length
msges.forEach((msg) =>
if Date.parse(msg.created) > Date.parse(date)
@robot.logger.debug "Matched new message #{msg.text}"
@robot.logger.debug "Message Object: ", msg
callback [msg], roomId
)
).catch((err) =>
@robot.logger.debug "There was an error while getting messages for roomId #{roomId}"
newDate = date
)
setTimeout (=>
@listen roomId, newDate, callback
), @refresh
send: (user, message) ->
@robot.logger.debug user
@robot.logger.debug "Send message to room #{user.roomId} with text #{message}"
spark.sendMessage
roomId: user.roomId
text: message
reply: (user, message) ->
@robot.logger.debug "Replying to message for #{user}"
if user
@robot.logger.debug "reply message to #{user} with text #{message}"
spark.sendMessage
text: message
toPersonEmail: user
exports.use = (robot) ->
new SparkAdapter robot
| 77831 | ///
Copyright 2016 <NAME>, Dimension Data
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
///
Bluebird = require('bluebird')
Adapter = require('hubot').Adapter
TextMessage = require('hubot').TextMessage
EventEmitter = require('events').EventEmitter
SparkApi = require('./spark-api')
class SparkAdapter extends Adapter
constructor: (robot) ->
super
send: (envelope, strings...) ->
user = if envelope.user then envelope.user else envelope.room
strings.forEach (str) =>
@prepare_string str, (message) =>
@bot.send user, message
reply: (envelope, strings...) ->
user = if envelope.user then envelope.user else envelope
strings.forEach (str) =>
@prepare_string str,(message) =>
@bot.reply user, message
prepare_string: (str, callback) ->
text = str
messages = [str]
messages.forEach (message) =>
callback message
run: ->
self = @
options =
api_uri: process.env.HUBOT_SPARK_API_URI or "https://api.ciscospark.com/v1"
refresh: process.env.HUBOT_SPARK_REFRESH or 10000
access_token: process.env.HUBOT_SPARK_ACCESS_TOKEN
rooms : process.env.HUBOT_SPARK_ROOMS
bot = new SparkRealtime(options, @robot)
bot.init(options, @robot).then((roomIds) ->
self.robot.logger.debug "Created bot, setting up listeners"
roomIds.forEach((roomId) ->
bot.listen roomId, new Date().toISOString(), (messages, roomId) =>
self.robot.logger.debug "Fired listener callback for #{roomId}"
messages.forEach (message) =>
text = message.text
user =
name: message.personEmail
id: message.personId
roomId: message.roomId
self.robot.logger.debug "Received #{text} from #{user.name}"
# self.robot.send user, text
self.robot.receive new TextMessage user, text
)
self.robot.logger.debug "Done with custom bot logic"
self.bot = bot
self.emit 'connected'
)
class SparkRealtime extends EventEmitter
self = @
logger = undefined
spark = undefined
constructor: (options, robot) ->
@room_ids = []
if not options.access_token?
throw new Error "Not enough parameters provided. I need an access token"
@refresh = parseInt(options.refresh)
init: (options, robot) ->
@robot = robot
logger = @robot.logger
logger.info "Trying connection to #{options.api_uri}"
spark = new SparkApi
uri: options.api_uri
token: options.access_token
return spark.init().then(() ->
logger.debug "Connected as a bot? #{spark.isBot()}"
logger.info "Created connection instance to Spark"
roomIds = []
options.rooms.split(',').forEach (roomId) =>
roomIds.push roomId
logger.debug "Completed adding rooms to list"
Bluebird.resolve(roomIds)
).catch((err) ->
throw new Error "Failed to connect to Spark: #{err}"
)
## Spark API call methods
listen: (roomId, date, callback) ->
newDate = new Date().toISOString()
spark.getMessages(roomId: roomId).then((msges) =>
@robot.logger.debug "Messages recived: ", msges.length
msges.forEach((msg) =>
if Date.parse(msg.created) > Date.parse(date)
@robot.logger.debug "Matched new message #{msg.text}"
@robot.logger.debug "Message Object: ", msg
callback [msg], roomId
)
).catch((err) =>
@robot.logger.debug "There was an error while getting messages for roomId #{roomId}"
newDate = date
)
setTimeout (=>
@listen roomId, newDate, callback
), @refresh
send: (user, message) ->
@robot.logger.debug user
@robot.logger.debug "Send message to room #{user.roomId} with text #{message}"
spark.sendMessage
roomId: user.roomId
text: message
reply: (user, message) ->
@robot.logger.debug "Replying to message for #{user}"
if user
@robot.logger.debug "reply message to #{user} with text #{message}"
spark.sendMessage
text: message
toPersonEmail: user
exports.use = (robot) ->
new SparkAdapter robot
| true | ///
Copyright 2016 PI:NAME:<NAME>END_PI, Dimension Data
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
///
Bluebird = require('bluebird')
Adapter = require('hubot').Adapter
TextMessage = require('hubot').TextMessage
EventEmitter = require('events').EventEmitter
SparkApi = require('./spark-api')
class SparkAdapter extends Adapter
constructor: (robot) ->
super
send: (envelope, strings...) ->
user = if envelope.user then envelope.user else envelope.room
strings.forEach (str) =>
@prepare_string str, (message) =>
@bot.send user, message
reply: (envelope, strings...) ->
user = if envelope.user then envelope.user else envelope
strings.forEach (str) =>
@prepare_string str,(message) =>
@bot.reply user, message
prepare_string: (str, callback) ->
text = str
messages = [str]
messages.forEach (message) =>
callback message
run: ->
self = @
options =
api_uri: process.env.HUBOT_SPARK_API_URI or "https://api.ciscospark.com/v1"
refresh: process.env.HUBOT_SPARK_REFRESH or 10000
access_token: process.env.HUBOT_SPARK_ACCESS_TOKEN
rooms : process.env.HUBOT_SPARK_ROOMS
bot = new SparkRealtime(options, @robot)
bot.init(options, @robot).then((roomIds) ->
self.robot.logger.debug "Created bot, setting up listeners"
roomIds.forEach((roomId) ->
bot.listen roomId, new Date().toISOString(), (messages, roomId) =>
self.robot.logger.debug "Fired listener callback for #{roomId}"
messages.forEach (message) =>
text = message.text
user =
name: message.personEmail
id: message.personId
roomId: message.roomId
self.robot.logger.debug "Received #{text} from #{user.name}"
# self.robot.send user, text
self.robot.receive new TextMessage user, text
)
self.robot.logger.debug "Done with custom bot logic"
self.bot = bot
self.emit 'connected'
)
class SparkRealtime extends EventEmitter
self = @
logger = undefined
spark = undefined
constructor: (options, robot) ->
@room_ids = []
if not options.access_token?
throw new Error "Not enough parameters provided. I need an access token"
@refresh = parseInt(options.refresh)
init: (options, robot) ->
@robot = robot
logger = @robot.logger
logger.info "Trying connection to #{options.api_uri}"
spark = new SparkApi
uri: options.api_uri
token: options.access_token
return spark.init().then(() ->
logger.debug "Connected as a bot? #{spark.isBot()}"
logger.info "Created connection instance to Spark"
roomIds = []
options.rooms.split(',').forEach (roomId) =>
roomIds.push roomId
logger.debug "Completed adding rooms to list"
Bluebird.resolve(roomIds)
).catch((err) ->
throw new Error "Failed to connect to Spark: #{err}"
)
## Spark API call methods
listen: (roomId, date, callback) ->
newDate = new Date().toISOString()
spark.getMessages(roomId: roomId).then((msges) =>
@robot.logger.debug "Messages recived: ", msges.length
msges.forEach((msg) =>
if Date.parse(msg.created) > Date.parse(date)
@robot.logger.debug "Matched new message #{msg.text}"
@robot.logger.debug "Message Object: ", msg
callback [msg], roomId
)
).catch((err) =>
@robot.logger.debug "There was an error while getting messages for roomId #{roomId}"
newDate = date
)
setTimeout (=>
@listen roomId, newDate, callback
), @refresh
send: (user, message) ->
@robot.logger.debug user
@robot.logger.debug "Send message to room #{user.roomId} with text #{message}"
spark.sendMessage
roomId: user.roomId
text: message
reply: (user, message) ->
@robot.logger.debug "Replying to message for #{user}"
if user
@robot.logger.debug "reply message to #{user} with text #{message}"
spark.sendMessage
text: message
toPersonEmail: user
exports.use = (robot) ->
new SparkAdapter robot
|
[
{
"context": "{\n title: \"welcome to lemon\"\n}\n",
"end": 28,
"score": 0.8254252672195435,
"start": 23,
"tag": "NAME",
"value": "lemon"
}
] | data/index.cson | lemon/default.lemonjs.org | 0 | {
title: "welcome to lemon"
}
| 82269 | {
title: "welcome to <NAME>"
}
| true | {
title: "welcome to PI:NAME:<NAME>END_PI"
}
|
[
{
"context": " type: 'text'\n placeholder: 'Ivan Ivanov'\n value: @state.name\n ",
"end": 3879,
"score": 0.9997580647468567,
"start": 3868,
"tag": "NAME",
"value": "Ivan Ivanov"
},
{
"context": " type: 'text'\n placeholder: '1488'\n value: @state.money\n ",
"end": 4041,
"score": 0.4547407925128937,
"start": 4040,
"tag": "NAME",
"value": "8"
}
] | main/static/main/js/main.coffee | FeodorM/splitmoney | 0 | render = ReactDOM.render
{div, button, form, input, br} = React.DOM
# Нагугленная херня, которая заработала
getCookie = (name) ->
cookieValue = null
if document.cookie and document.cookie != ''
cookies = document.cookie.split(';')
i = 0
while i < cookies.length
cookie = jQuery.trim(cookies[i])
# Does this cookie string begin with the name we want?
if cookie.substring(0, name.length + 1) == name + '='
cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
break
i++
cookieValue
csrftoken = getCookie('csrftoken')
csrfSafeMethod = (method) ->
# these HTTP methods do not require CSRF protection
/^(GET|HEAD|OPTIONS|TRACE)$/.test method
$.ajaxSetup beforeSend: (xhr, settings) ->
if not csrfSafeMethod(settings.type) and not @crossDomain
xhr.setRequestHeader 'X-CSRFToken', csrftoken
start = () ->
render(
InputList {}
$('#main')[0]
)
class InputList extends React.Component
constructor: (props) ->
super props
@state =
users: [
{
name: ''
money: ''
num: 0
}
]
addInput: (e) =>
e.preventDefault()
users = @state.users
newUsers = users.concat [
{
name: ''
money: ''
num: users.length
}
]
@setState
users: newUsers
isInt: (value) =>
if parseFloat(value) == parseInt(value) and not isNaN(value)
true
else
false
usersAreValid: (users) =>
for user in users
return false unless user.name.length and @isInt user.money
true
# TODO: ajax
handleSubmit: (e) =>
e.preventDefault()
users = @state.users
unless @usersAreValid users
alert 'Wrong Data.'
else
$.ajax
url: '/ajax/'
method: 'POST'
dataType: 'json'
# contentType: 'application/json; charset=utf-8'
# processData: false
data:
users: JSON.stringify users
#JSON.stringify
success: (data, textStatus, jqXHR) ->
render(
Output {data}
$('#main')[0]
)
error: (jqXHR, textStatus, errorThrown) ->
alert "Something went wrong!\nError: #{errorThrown}"
console.log 'Something went wrong!'
valueChanged: (value, name, num) =>
users = @state.users
users[num][name] = value
@setState
users: users
createInput: (user) =>
Input
num: user.num
key: user.num
valueChanged: @valueChanged
render: ->
inputs = @state.users.map @createInput
form { className: 'InputList', onSubmit: @handleSubmit }, inputs.concat [
Button { text: '+', onClick: @addInput }
br {}
Button { text: 'Split Money', type: 'submit'}
]
InputList = React.createFactory InputList
class Input extends React.Component
constructor: (props) ->
super props
@state =
name: ''
money: ''
handleNameChange: (e) =>
value = e.target.value
@props.valueChanged value, 'name', @props.num
@setState
name: value
handleMoneyChange: (e) =>
value = e.target.value
@props.valueChanged value, 'money', @props.num
@setState
money: value
render: ->
div { className: 'Input' }, [
# br {}
input
type: 'text'
placeholder: 'Ivan Ivanov'
value: @state.name
onChange: @handleNameChange
input
type: 'text'
placeholder: '1488'
value: @state.money
onChange: @handleMoneyChange
]
Input = React.createFactory Input
class Button extends React.Component
render: ->
button
className: 'Button'
type: @props.type ? 'button'
onClick: @props.onClick ? () ->,
@props.text
Button = React.createFactory Button
class Output extends React.Component
prettify: (user) ->
toPay = parseInt user.to_pay
whatToDo =
if toPay > 0
"-> #{toPay}"
else if toPay == 0
"owes nothing"
else
"<- #{Math.abs toPay}"
OutputItem { text: "#{user.name} #{whatToDo}" }
render: ->
div { className: 'Output' }, @props.data.map(@prettify).concat [
Button { onClick: start, text: 'Start Again' }
]
Output = React.createFactory Output
class OutputItem extends React.Component
render: ->
div { className: 'OutputItem' }, @props.text
OutputItem = React.createFactory OutputItem
render(
Button
onClick: start
text: 'Start',
$('#main')[0]
)
# some old code:
# out = exports ? this
#
# out.addPerson = () ->
# input = document.getElementById('input')
# tags = (child for own key, child of input.childNodes when child.nodeName != '#text')[-3..]
# # console.log tags
# [inName, inMoney, br] = (node.cloneNode() for node in tags)
#
# # inName.setAttribute('name', 'name' + (parseInt(inName.name[4..]) + 1))
# inName.name = 'name' + (parseInt(inName.name[4..]) + 1)
# inMoney.name = 'money' + (parseInt(inMoney.name[5..]) + 1)
#
# for node in [inName, inMoney, br]
# input.appendChild node
# # console.log inName, inMoney, br
# console.log 'addPerson created'
| 74585 | render = ReactDOM.render
{div, button, form, input, br} = React.DOM
# Нагугленная херня, которая заработала
getCookie = (name) ->
cookieValue = null
if document.cookie and document.cookie != ''
cookies = document.cookie.split(';')
i = 0
while i < cookies.length
cookie = jQuery.trim(cookies[i])
# Does this cookie string begin with the name we want?
if cookie.substring(0, name.length + 1) == name + '='
cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
break
i++
cookieValue
csrftoken = getCookie('csrftoken')
csrfSafeMethod = (method) ->
# these HTTP methods do not require CSRF protection
/^(GET|HEAD|OPTIONS|TRACE)$/.test method
$.ajaxSetup beforeSend: (xhr, settings) ->
if not csrfSafeMethod(settings.type) and not @crossDomain
xhr.setRequestHeader 'X-CSRFToken', csrftoken
start = () ->
render(
InputList {}
$('#main')[0]
)
class InputList extends React.Component
constructor: (props) ->
super props
@state =
users: [
{
name: ''
money: ''
num: 0
}
]
addInput: (e) =>
e.preventDefault()
users = @state.users
newUsers = users.concat [
{
name: ''
money: ''
num: users.length
}
]
@setState
users: newUsers
isInt: (value) =>
if parseFloat(value) == parseInt(value) and not isNaN(value)
true
else
false
usersAreValid: (users) =>
for user in users
return false unless user.name.length and @isInt user.money
true
# TODO: ajax
handleSubmit: (e) =>
e.preventDefault()
users = @state.users
unless @usersAreValid users
alert 'Wrong Data.'
else
$.ajax
url: '/ajax/'
method: 'POST'
dataType: 'json'
# contentType: 'application/json; charset=utf-8'
# processData: false
data:
users: JSON.stringify users
#JSON.stringify
success: (data, textStatus, jqXHR) ->
render(
Output {data}
$('#main')[0]
)
error: (jqXHR, textStatus, errorThrown) ->
alert "Something went wrong!\nError: #{errorThrown}"
console.log 'Something went wrong!'
valueChanged: (value, name, num) =>
users = @state.users
users[num][name] = value
@setState
users: users
createInput: (user) =>
Input
num: user.num
key: user.num
valueChanged: @valueChanged
render: ->
inputs = @state.users.map @createInput
form { className: 'InputList', onSubmit: @handleSubmit }, inputs.concat [
Button { text: '+', onClick: @addInput }
br {}
Button { text: 'Split Money', type: 'submit'}
]
InputList = React.createFactory InputList
class Input extends React.Component
constructor: (props) ->
super props
@state =
name: ''
money: ''
handleNameChange: (e) =>
value = e.target.value
@props.valueChanged value, 'name', @props.num
@setState
name: value
handleMoneyChange: (e) =>
value = e.target.value
@props.valueChanged value, 'money', @props.num
@setState
money: value
render: ->
div { className: 'Input' }, [
# br {}
input
type: 'text'
placeholder: '<NAME>'
value: @state.name
onChange: @handleNameChange
input
type: 'text'
placeholder: '148<NAME>'
value: @state.money
onChange: @handleMoneyChange
]
Input = React.createFactory Input
class Button extends React.Component
render: ->
button
className: 'Button'
type: @props.type ? 'button'
onClick: @props.onClick ? () ->,
@props.text
Button = React.createFactory Button
class Output extends React.Component
prettify: (user) ->
toPay = parseInt user.to_pay
whatToDo =
if toPay > 0
"-> #{toPay}"
else if toPay == 0
"owes nothing"
else
"<- #{Math.abs toPay}"
OutputItem { text: "#{user.name} #{whatToDo}" }
render: ->
div { className: 'Output' }, @props.data.map(@prettify).concat [
Button { onClick: start, text: 'Start Again' }
]
Output = React.createFactory Output
class OutputItem extends React.Component
render: ->
div { className: 'OutputItem' }, @props.text
OutputItem = React.createFactory OutputItem
render(
Button
onClick: start
text: 'Start',
$('#main')[0]
)
# some old code:
# out = exports ? this
#
# out.addPerson = () ->
# input = document.getElementById('input')
# tags = (child for own key, child of input.childNodes when child.nodeName != '#text')[-3..]
# # console.log tags
# [inName, inMoney, br] = (node.cloneNode() for node in tags)
#
# # inName.setAttribute('name', 'name' + (parseInt(inName.name[4..]) + 1))
# inName.name = 'name' + (parseInt(inName.name[4..]) + 1)
# inMoney.name = 'money' + (parseInt(inMoney.name[5..]) + 1)
#
# for node in [inName, inMoney, br]
# input.appendChild node
# # console.log inName, inMoney, br
# console.log 'addPerson created'
| true | render = ReactDOM.render
{div, button, form, input, br} = React.DOM
# Нагугленная херня, которая заработала
getCookie = (name) ->
cookieValue = null
if document.cookie and document.cookie != ''
cookies = document.cookie.split(';')
i = 0
while i < cookies.length
cookie = jQuery.trim(cookies[i])
# Does this cookie string begin with the name we want?
if cookie.substring(0, name.length + 1) == name + '='
cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
break
i++
cookieValue
csrftoken = getCookie('csrftoken')
csrfSafeMethod = (method) ->
# these HTTP methods do not require CSRF protection
/^(GET|HEAD|OPTIONS|TRACE)$/.test method
$.ajaxSetup beforeSend: (xhr, settings) ->
if not csrfSafeMethod(settings.type) and not @crossDomain
xhr.setRequestHeader 'X-CSRFToken', csrftoken
start = () ->
render(
InputList {}
$('#main')[0]
)
class InputList extends React.Component
constructor: (props) ->
super props
@state =
users: [
{
name: ''
money: ''
num: 0
}
]
addInput: (e) =>
e.preventDefault()
users = @state.users
newUsers = users.concat [
{
name: ''
money: ''
num: users.length
}
]
@setState
users: newUsers
isInt: (value) =>
if parseFloat(value) == parseInt(value) and not isNaN(value)
true
else
false
usersAreValid: (users) =>
for user in users
return false unless user.name.length and @isInt user.money
true
# TODO: ajax
handleSubmit: (e) =>
e.preventDefault()
users = @state.users
unless @usersAreValid users
alert 'Wrong Data.'
else
$.ajax
url: '/ajax/'
method: 'POST'
dataType: 'json'
# contentType: 'application/json; charset=utf-8'
# processData: false
data:
users: JSON.stringify users
#JSON.stringify
success: (data, textStatus, jqXHR) ->
render(
Output {data}
$('#main')[0]
)
error: (jqXHR, textStatus, errorThrown) ->
alert "Something went wrong!\nError: #{errorThrown}"
console.log 'Something went wrong!'
valueChanged: (value, name, num) =>
users = @state.users
users[num][name] = value
@setState
users: users
createInput: (user) =>
Input
num: user.num
key: user.num
valueChanged: @valueChanged
render: ->
inputs = @state.users.map @createInput
form { className: 'InputList', onSubmit: @handleSubmit }, inputs.concat [
Button { text: '+', onClick: @addInput }
br {}
Button { text: 'Split Money', type: 'submit'}
]
InputList = React.createFactory InputList
class Input extends React.Component
constructor: (props) ->
super props
@state =
name: ''
money: ''
handleNameChange: (e) =>
value = e.target.value
@props.valueChanged value, 'name', @props.num
@setState
name: value
handleMoneyChange: (e) =>
value = e.target.value
@props.valueChanged value, 'money', @props.num
@setState
money: value
render: ->
div { className: 'Input' }, [
# br {}
input
type: 'text'
placeholder: 'PI:NAME:<NAME>END_PI'
value: @state.name
onChange: @handleNameChange
input
type: 'text'
placeholder: '148PI:NAME:<NAME>END_PI'
value: @state.money
onChange: @handleMoneyChange
]
Input = React.createFactory Input
class Button extends React.Component
render: ->
button
className: 'Button'
type: @props.type ? 'button'
onClick: @props.onClick ? () ->,
@props.text
Button = React.createFactory Button
class Output extends React.Component
prettify: (user) ->
toPay = parseInt user.to_pay
whatToDo =
if toPay > 0
"-> #{toPay}"
else if toPay == 0
"owes nothing"
else
"<- #{Math.abs toPay}"
OutputItem { text: "#{user.name} #{whatToDo}" }
render: ->
div { className: 'Output' }, @props.data.map(@prettify).concat [
Button { onClick: start, text: 'Start Again' }
]
Output = React.createFactory Output
class OutputItem extends React.Component
render: ->
div { className: 'OutputItem' }, @props.text
OutputItem = React.createFactory OutputItem
render(
Button
onClick: start
text: 'Start',
$('#main')[0]
)
# some old code:
# out = exports ? this
#
# out.addPerson = () ->
# input = document.getElementById('input')
# tags = (child for own key, child of input.childNodes when child.nodeName != '#text')[-3..]
# # console.log tags
# [inName, inMoney, br] = (node.cloneNode() for node in tags)
#
# # inName.setAttribute('name', 'name' + (parseInt(inName.name[4..]) + 1))
# inName.name = 'name' + (parseInt(inName.name[4..]) + 1)
# inMoney.name = 'money' + (parseInt(inMoney.name[5..]) + 1)
#
# for node in [inName, inMoney, br]
# input.appendChild node
# # console.log inName, inMoney, br
# console.log 'addPerson created'
|
[
{
"context": " email: faker.internet.email()\n password: '1234568878'\n\n Accounts.createUser doc, (err) ->\n ",
"end": 1148,
"score": 0.9993352890014648,
"start": 1138,
"tag": "PASSWORD",
"value": "1234568878"
},
{
"context": "c =\n email: sharedEmail\n password: '12345678'\n profile:\n first_name: faker.nam",
"end": 1469,
"score": 0.9993400573730469,
"start": 1461,
"tag": "PASSWORD",
"value": "12345678"
},
{
"context": "c =\n email: sharedEmail\n password: '123123123'\n profile:\n first_name: faker.nam",
"end": 1907,
"score": 0.9993540644645691,
"start": 1898,
"tag": "PASSWORD",
"value": "123123123"
},
{
"context": " email: faker.internet.email()\n password: '123123123'\n profile:\n first_name: faker.nam",
"end": 3061,
"score": 0.9993125200271606,
"start": 3052,
"tag": "PASSWORD",
"value": "123123123"
},
{
"context": " before( (done) ->\n doc =\n email: 'footdavid@hotmail.com'\n password: '12345678'\n profile:\n ",
"end": 6637,
"score": 0.9999120831489563,
"start": 6616,
"tag": "EMAIL",
"value": "footdavid@hotmail.com"
},
{
"context": "email: 'footdavid@hotmail.com'\n password: '12345678'\n profile:\n first_name: faker.nam",
"end": 6666,
"score": 0.9993677735328674,
"start": 6658,
"tag": "PASSWORD",
"value": "12345678"
},
{
"context": "()).to.not.exist\n\n Meteor.loginWithPassword 'footdavidmomo@hotmail.com', '12345678', (err) ->\n expect(err).to.hav",
"end": 7148,
"score": 0.9998688101768494,
"start": 7123,
"tag": "EMAIL",
"value": "footdavidmomo@hotmail.com"
},
{
"context": "r.loginWithPassword 'footdavidmomo@hotmail.com', '12345678', (err) ->\n expect(err).to.have.propert",
"end": 7157,
"score": 0.7958844900131226,
"start": 7152,
"tag": "PASSWORD",
"value": "12345"
},
{
"context": "nWithPassword 'footdavidmomo@hotmail.com', '12345678', (err) ->\n expect(err).to.have.property('",
"end": 7160,
"score": 0.6546220779418945,
"start": 7158,
"tag": "PASSWORD",
"value": "78"
},
{
"context": "()).to.not.exist\n\n Meteor.loginWithPassword 'footdavid@hotmail.com', '12345asdf', (err) ->\n expect(err).to.ha",
"end": 7385,
"score": 0.9998654723167419,
"start": 7364,
"tag": "EMAIL",
"value": "footdavid@hotmail.com"
},
{
"context": "eteor.loginWithPassword 'footdavid@hotmail.com', '12345asdf', (err) ->\n expect(err).to.have.property('",
"end": 7398,
"score": 0.9950770735740662,
"start": 7389,
"tag": "PASSWORD",
"value": "12345asdf"
},
{
"context": "()).to.not.exist\n\n Meteor.loginWithPassword 'footdavid@hotmail.com', '12345678', (err) ->\n expect(err).to.not",
"end": 7623,
"score": 0.9998777508735657,
"start": 7602,
"tag": "EMAIL",
"value": "footdavid@hotmail.com"
},
{
"context": "eteor.loginWithPassword 'footdavid@hotmail.com', '12345678', (err) ->\n expect(err).to.not.exist\n ",
"end": 7635,
"score": 0.9873778820037842,
"start": 7627,
"tag": "PASSWORD",
"value": "12345678"
},
{
"context": " new user', (done) ->\n doc =\n email: 'example@hotmail.com'\n password: '12345678'\n profile:\n ",
"end": 8023,
"score": 0.9999198913574219,
"start": 8004,
"tag": "EMAIL",
"value": "example@hotmail.com"
},
{
"context": " email: 'example@hotmail.com'\n password: '12345678'\n profile:\n first_name: faker.nam",
"end": 8052,
"score": 0.9994029998779297,
"start": 8044,
"tag": "PASSWORD",
"value": "12345678"
},
{
"context": "err).to.not.exist\n doc =\n email: 'example2@hotmail.com'\n password: '12345678'\n profile",
"end": 8716,
"score": 0.9999263286590576,
"start": 8696,
"tag": "EMAIL",
"value": "example2@hotmail.com"
},
{
"context": "mail: 'example2@hotmail.com'\n password: '12345678'\n profile:\n first_name: faker",
"end": 8747,
"score": 0.9992601871490479,
"start": 8739,
"tag": "PASSWORD",
"value": "12345678"
},
{
"context": " user', (done) ->\n Meteor.loginWithPassword 'example@hotmail.com', '12345678', (err) ->\n expect(err).to.not",
"end": 9142,
"score": 0.9999216198921204,
"start": 9123,
"tag": "EMAIL",
"value": "example@hotmail.com"
},
{
"context": " emails:\n [\n address: 'example2@hotmail.com'\n ]\n profile:\n fir",
"end": 9302,
"score": 0.9999255537986755,
"start": 9282,
"tag": "EMAIL",
"value": "example2@hotmail.com"
},
{
"context": "r).to.not.exist\n Meteor.loginWithPassword 'example2@hotmail.com', '12345678', (err) ->\n expect(err).to.n",
"end": 9977,
"score": 0.9999248385429382,
"start": 9957,
"tag": "EMAIL",
"value": "example2@hotmail.com"
},
{
"context": "r).to.not.exist\n Meteor.loginWithPassword 'example@hotmail.com', '12345678', (err) ->\n expect(err).to.n",
"end": 10820,
"score": 0.999917209148407,
"start": 10801,
"tag": "EMAIL",
"value": "example@hotmail.com"
},
{
"context": "r).to.not.exist\n Meteor.loginWithPassword 'example2@hotmail.com', '12345678', (err) ->\n expect(err).to.n",
"end": 13043,
"score": 0.9997467994689941,
"start": 13023,
"tag": "EMAIL",
"value": "example2@hotmail.com"
},
{
"context": "r).to.not.exist\n Meteor.loginWithPassword 'example@hotmail.com', '12345678', (err) ->\n expect(err).to.n",
"end": 14505,
"score": 0.9999097585678101,
"start": 14486,
"tag": "EMAIL",
"value": "example@hotmail.com"
},
{
"context": "r).to.not.exist\n Meteor.loginWithPassword 'example2@hotmail.com', '12345678', (err) ->\n expect(err).to.n",
"end": 15657,
"score": 0.9999009966850281,
"start": 15637,
"tag": "EMAIL",
"value": "example2@hotmail.com"
},
{
"context": "r).to.not.exist\n Meteor.loginWithPassword 'example@hotmail.com', '12345678', (err) ->\n expect(err).to.n",
"end": 16485,
"score": 0.999916672706604,
"start": 16466,
"tag": "EMAIL",
"value": "example@hotmail.com"
},
{
"context": "xistent user', (done) ->\n\n update_user_id = \"nonono\"\n organization_id = Organizations.findOne().",
"end": 16645,
"score": 0.9989430904388428,
"start": 16639,
"tag": "USERNAME",
"value": "nonono"
},
{
"context": "not in organ', (done) ->\n\n update_user_id = \"nonono\"\n organization_id = Organizations.findOne().",
"end": 16951,
"score": 0.9986305236816406,
"start": 16945,
"tag": "USERNAME",
"value": "nonono"
},
{
"context": "move correct', (done) ->\n\n update_user_id = \"nonono\"\n organization_id = Organizations.findOne().",
"end": 17870,
"score": 0.9990222454071045,
"start": 17864,
"tag": "USERNAME",
"value": "nonono"
},
{
"context": " before( (done) ->\n doc =\n email: 'footdavid@hotmail.com'\n password: '12345678'\n profile:\n ",
"end": 18598,
"score": 0.9999263882637024,
"start": 18577,
"tag": "EMAIL",
"value": "footdavid@hotmail.com"
},
{
"context": "email: 'footdavid@hotmail.com'\n password: '12345678'\n profile:\n first_name: faker.nam",
"end": 18627,
"score": 0.9991535544395447,
"start": 18619,
"tag": "PASSWORD",
"value": "12345678"
}
] | app_tests/client/user.app-tests.coffee | Phaze1D/SA-Units | 0 | faker = require 'faker'
{ chai, assert, expect } = require 'meteor/practicalmeteor:chai'
{ Meteor } = require 'meteor/meteor'
{ Accounts } = require 'meteor/accounts-base'
{ resetDatabase } = require 'meteor/xolvio:cleaner'
{ _ } = require 'meteor/underscore'
{ Organizations } = require '../../imports/api/collections/organizations/organizations.coffee'
{
inviteUser
updatePermission
removeFromOrganization
updateProfile
} = require '../../imports/api/collections/users/methods.coffee'
{ insert } = require '../../imports/api/collections/organizations/methods.coffee'
xdescribe 'User Full App Tests Client', () ->
before( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
after( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
sharedEmail = faker.internet.email()
describe 'User sign up flow', () ->
after( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
it 'User simple schema fail validations', (done) ->
expect(Meteor.user()).to.not.exist
doc =
email: faker.internet.email()
password: '1234568878'
Accounts.createUser doc, (err) ->
expect(err).to.have.property('error', 'validation-error');
done()
return
return
it 'User simple schema success validations', (done) ->
expect(Meteor.user()).to.not.exist
doc =
email: sharedEmail
password: '12345678'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
expect(error).to.not.exist
Meteor.logout( (err) ->
done()
)
return
return
it 'User simple schema duplicate emails', (done) ->
expect(Meteor.user()).to.not.exist
doc =
email: sharedEmail
password: '123123123'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
expect(error).to.have.property('reason', 'Email already exists.')
done()
return
return
describe 'Invite user to organization', ->
after( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
it 'Invite nonexistent user to new organization not logged in', (done) ->
expect(Meteor.user()).to.not.exist
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = 'Dont Own'
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
expect ->
inviteUser.call {invited_user_doc, organization_id, permission}
.to.Throw('notLoggedIn')
doc =
email: faker.internet.email()
password: '123123123'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
expect(error).to.not.exist
done()
return
it 'Invite nonexistent user to new organization not Auth', (done) ->
expect(Meteor.user()).to.exist
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = 'AijWjNwoih4aB7mLK'
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc , organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized');
done()
return
shared_organization =
it 'Invite nonexistent user to new organization', (done) ->
expect(Meteor.user()).to.exist
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
insert.call organ_doc, (err, res) ->
expect(err).to.not.exist
return
shared_organization = Organizations.findOne()._id
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = shared_organization
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
currentUser = Meteor.userId()
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(currentUser).to.equal(Meteor.userId())
done()
return
it 'Invite existent user to organization' , (done) ->
expect(Meteor.user()).to.exist
invited_user_doc =
emails:
[
address: sharedEmail
]
profile:
first_name: faker.name.firstName()
organization_id = shared_organization
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
console.log err
expect(err).to.not.exist
done()
it 'Invite without correct permission', (done) ->
Meteor.loginWithPassword sharedEmail, '12345678', (err) ->
expect(err).to.not.exist
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = shared_organization
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error','permissionDenied')
done()
describe 'User Login flow', ->
before( (done) ->
doc =
email: 'footdavid@hotmail.com'
password: '12345678'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
Meteor.logout( (err) ->
done()
)
return
)
after( (done) ->
Meteor.logout( (err) ->
)
@timeout(20000)
setTimeout(done, 10000)
)
it 'Invalid email', (done) ->
expect(Meteor.user()).to.not.exist
Meteor.loginWithPassword 'footdavidmomo@hotmail.com', '12345678', (err) ->
expect(err).to.have.property('reason', 'User not found')
done()
it 'Invalid Password', (done) ->
expect(Meteor.user()).to.not.exist
Meteor.loginWithPassword 'footdavid@hotmail.com', '12345asdf', (err) ->
expect(err).to.have.property('reason', 'Incorrect password')
done()
it 'Correct User', (done) ->
expect(Meteor.user()).to.not.exist
Meteor.loginWithPassword 'footdavid@hotmail.com', '12345678', (err) ->
expect(err).to.not.exist
expect(Meteor.user()).to.exist
done()
describe 'User update permission', ->
before( (done) ->
callbacks =
onStop: () ->
onReady: () ->
done()
Meteor.subscribe("organizations", callbacks)
)
it 'Create new user', (done) ->
doc =
email: 'example@hotmail.com'
password: '12345678'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (err) ->
expect(err).to.not.exist
done()
organization_id00 = ''
it 'Create organization', (done) ->
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
insert.call organ_doc, (err, res) ->
expect(err).to.not.exist
organization_id00 = res
done()
it 'Log Out and create new user log out again', (done) ->
Meteor.logout((err) ->
expect(err).to.not.exist
doc =
email: 'example2@hotmail.com'
password: '12345678'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (err) ->
expect(err).to.not.exist
Meteor.logout( (err) ->
expect(err).to.not.exist
done()
)
)
it 'Login and invite user', (done) ->
Meteor.loginWithPassword 'example@hotmail.com', '12345678', (err) ->
expect(err).to.not.exist
invited_user_doc =
emails:
[
address: 'example2@hotmail.com'
]
profile:
first_name: faker.name.firstName()
organization_id = organization_id00
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
done()
it 'Log out and login with non auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'example2@hotmail.com', '12345678', (err) ->
expect(err).to.not.exist
done()
)
updateUser = ''
it 'Is not owner or user manager but belongs to organ', (done) ->
updateUser = Meteor.userId()
update_user_id = updateUser
organization_id = organization_id00
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'permissionDenied')
done()
it 'Log out and login with auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'example@hotmail.com', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Is auth user update permission other user', (done) ->
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(false)
update_user_id = updateUser
organization_id = organization_id00
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(true)
done()
it 'Is auth user update permission same user', (done) ->
expect(Organizations.findOne().hasUser(Meteor.userId()).permission.owner).to.equal(true)
update_user_id = Meteor.userId()
organization_id = organization_id00
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
done()
it 'Is auth user update permission other user', (done) ->
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(true)
update_user_id = updateUser
organization_id = organization_id00
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(false)
done()
it 'Log out and login with auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'example2@hotmail.com', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Is user manager only, setting owner ', (done) ->
expect(Organizations.findOne().hasUser(Meteor.userId()).permission.owner).to.equal(false)
update_user_id = Meteor.userId()
organization_id = organization_id00
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'permissionDenied')
done()
it 'Is user manager only, setting other', (done) ->
update_user_id = Meteor.userId()
organization_id = organization_id00
permission =
owner: false
viewer: true
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(Organizations.findOne().hasUser(Meteor.userId()).permission.viewer).to.equal(true)
done()
it 'Log out and login with auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'example@hotmail.com', '12345678', (err) ->
expect(err).to.not.exist
done()
)
organization_id01 = ''
it 'Create new organization', (done) ->
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
insert.call organ_doc, (err, res) ->
expect(err).to.not.exist
organization_id01 = res
done()
it 'Update nonexistent user of organization', (done) ->
this.timeout(50000);
setTimeout(done, 10000);
update_user_id = updateUser
organization_id = organization_id01
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error','notAuthorized')
it 'Log out and login with non auth user', (done) ->
updateUser = Meteor.userId()
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'example2@hotmail.com', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Update existent user of non auth organization', (done) ->
update_user_id = updateUser
organization_id = organization_id01
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error','permissionDenied')
done()
describe 'Remove user from organization', ->
it 'Log out and login with owner', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'example@hotmail.com', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Remove nonexistent user', (done) ->
update_user_id = "nonono"
organization_id = Organizations.findOne()._id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
done()
it 'Remove existent user but not in organ', (done) ->
update_user_id = "nonono"
organization_id = Organizations.findOne()._id
Organizations.find().forEach (doc) ->
if doc.ousers.length > 1
for ouser in doc.ousers
if ouser.user_id isnt Meteor.userId()
update_user_id = ouser.user_id
else
organization_id = doc._id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
done()
it 'Try to remove owner', (done) ->
update_user_id = Meteor.userId()
organization_id = Organizations.findOne()._id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
expect(err).to.have.property('reason', 'an owner cannot remove themselves')
done()
it 'Remove correct', (done) ->
update_user_id = "nonono"
organization_id = Organizations.findOne()._id
length = ''
Organizations.find().forEach (doc) ->
if doc.ousers.length > 1
organization_id = doc._id
length = doc.ousers.length
for ouser in doc.ousers
if ouser.user_id isnt Meteor.userId()
update_user_id = ouser.user_id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
doc = Organizations.findOne(organization_id)
expect(length).to.be.above(doc.ousers.length)
expect(doc.hasUser(update_user_id)).to.not.exist
done()
describe 'Updating User profile', ->
before( (done) ->
doc =
email: 'footdavid@hotmail.com'
password: '12345678'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
done()
)
it 'Invalid profile doc', (done) ->
expect(Meteor.user()).to.exist
profile_doc =
nono: faker.name.firstName()
last_name: faker.name.lastName()
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.have.property('error', 'validation-error')
done()
it 'Valid profile doc update', (done) ->
expect(Meteor.user()).to.exist
firstName = Meteor.user().profile.first_name
profile_doc =
first_name: faker.name.firstName()
last_name: faker.name.lastName()
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.not.exist
expect(Meteor.user().profile.first_name).to.not.equal(firstName)
done()
it 'Valid profile doc with address update', (done) ->
expect(Meteor.user()).to.exist
firstName = Meteor.user().profile.first_name
address =
street: faker.address.streetAddress()
city: faker.address.city()
state: faker.address.state()
zip_code: faker.address.zipCode()
country: faker.address.country()
profile_doc =
first_name: faker.name.firstName()
last_name: faker.name.lastName()
addresses: [
address
]
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.not.exist
expect(Meteor.user().profile.first_name).to.not.equal(firstName)
expect(Meteor.user().profile.addresses.length).to.be.at.least(1)
console.log Meteor.user()
done()
it 'Valid profile doc with invalid address update', (done) ->
expect(Meteor.user()).to.exist
firstName = Meteor.user().profile.first_name
address =
city: faker.address.city()
state: faker.address.state()
zip_code: faker.address.zipCode()
country: faker.address.country()
profile_doc =
first_name: faker.name.firstName()
last_name: faker.name.lastName()
addresses: [
address
]
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.have.property('error','validation-error')
done()
| 215300 | faker = require 'faker'
{ chai, assert, expect } = require 'meteor/practicalmeteor:chai'
{ Meteor } = require 'meteor/meteor'
{ Accounts } = require 'meteor/accounts-base'
{ resetDatabase } = require 'meteor/xolvio:cleaner'
{ _ } = require 'meteor/underscore'
{ Organizations } = require '../../imports/api/collections/organizations/organizations.coffee'
{
inviteUser
updatePermission
removeFromOrganization
updateProfile
} = require '../../imports/api/collections/users/methods.coffee'
{ insert } = require '../../imports/api/collections/organizations/methods.coffee'
xdescribe 'User Full App Tests Client', () ->
before( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
after( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
sharedEmail = faker.internet.email()
describe 'User sign up flow', () ->
after( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
it 'User simple schema fail validations', (done) ->
expect(Meteor.user()).to.not.exist
doc =
email: faker.internet.email()
password: '<PASSWORD>'
Accounts.createUser doc, (err) ->
expect(err).to.have.property('error', 'validation-error');
done()
return
return
it 'User simple schema success validations', (done) ->
expect(Meteor.user()).to.not.exist
doc =
email: sharedEmail
password: '<PASSWORD>'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
expect(error).to.not.exist
Meteor.logout( (err) ->
done()
)
return
return
it 'User simple schema duplicate emails', (done) ->
expect(Meteor.user()).to.not.exist
doc =
email: sharedEmail
password: '<PASSWORD>'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
expect(error).to.have.property('reason', 'Email already exists.')
done()
return
return
describe 'Invite user to organization', ->
after( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
it 'Invite nonexistent user to new organization not logged in', (done) ->
expect(Meteor.user()).to.not.exist
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = 'Dont Own'
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
expect ->
inviteUser.call {invited_user_doc, organization_id, permission}
.to.Throw('notLoggedIn')
doc =
email: faker.internet.email()
password: '<PASSWORD>'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
expect(error).to.not.exist
done()
return
it 'Invite nonexistent user to new organization not Auth', (done) ->
expect(Meteor.user()).to.exist
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = 'AijWjNwoih4aB7mLK'
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc , organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized');
done()
return
shared_organization =
it 'Invite nonexistent user to new organization', (done) ->
expect(Meteor.user()).to.exist
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
insert.call organ_doc, (err, res) ->
expect(err).to.not.exist
return
shared_organization = Organizations.findOne()._id
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = shared_organization
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
currentUser = Meteor.userId()
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(currentUser).to.equal(Meteor.userId())
done()
return
it 'Invite existent user to organization' , (done) ->
expect(Meteor.user()).to.exist
invited_user_doc =
emails:
[
address: sharedEmail
]
profile:
first_name: faker.name.firstName()
organization_id = shared_organization
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
console.log err
expect(err).to.not.exist
done()
it 'Invite without correct permission', (done) ->
Meteor.loginWithPassword sharedEmail, '12345678', (err) ->
expect(err).to.not.exist
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = shared_organization
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error','permissionDenied')
done()
describe 'User Login flow', ->
before( (done) ->
doc =
email: '<EMAIL>'
password: '<PASSWORD>'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
Meteor.logout( (err) ->
done()
)
return
)
after( (done) ->
Meteor.logout( (err) ->
)
@timeout(20000)
setTimeout(done, 10000)
)
it 'Invalid email', (done) ->
expect(Meteor.user()).to.not.exist
Meteor.loginWithPassword '<EMAIL>', '<PASSWORD>6<PASSWORD>', (err) ->
expect(err).to.have.property('reason', 'User not found')
done()
it 'Invalid Password', (done) ->
expect(Meteor.user()).to.not.exist
Meteor.loginWithPassword '<EMAIL>', '<PASSWORD>', (err) ->
expect(err).to.have.property('reason', 'Incorrect password')
done()
it 'Correct User', (done) ->
expect(Meteor.user()).to.not.exist
Meteor.loginWithPassword '<EMAIL>', '<PASSWORD>', (err) ->
expect(err).to.not.exist
expect(Meteor.user()).to.exist
done()
describe 'User update permission', ->
before( (done) ->
callbacks =
onStop: () ->
onReady: () ->
done()
Meteor.subscribe("organizations", callbacks)
)
it 'Create new user', (done) ->
doc =
email: '<EMAIL>'
password: '<PASSWORD>'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (err) ->
expect(err).to.not.exist
done()
organization_id00 = ''
it 'Create organization', (done) ->
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
insert.call organ_doc, (err, res) ->
expect(err).to.not.exist
organization_id00 = res
done()
it 'Log Out and create new user log out again', (done) ->
Meteor.logout((err) ->
expect(err).to.not.exist
doc =
email: '<EMAIL>'
password: '<PASSWORD>'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (err) ->
expect(err).to.not.exist
Meteor.logout( (err) ->
expect(err).to.not.exist
done()
)
)
it 'Login and invite user', (done) ->
Meteor.loginWithPassword '<EMAIL>', '12345678', (err) ->
expect(err).to.not.exist
invited_user_doc =
emails:
[
address: '<EMAIL>'
]
profile:
first_name: faker.name.firstName()
organization_id = organization_id00
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
done()
it 'Log out and login with non auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword '<EMAIL>', '12345678', (err) ->
expect(err).to.not.exist
done()
)
updateUser = ''
it 'Is not owner or user manager but belongs to organ', (done) ->
updateUser = Meteor.userId()
update_user_id = updateUser
organization_id = organization_id00
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'permissionDenied')
done()
it 'Log out and login with auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword '<EMAIL>', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Is auth user update permission other user', (done) ->
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(false)
update_user_id = updateUser
organization_id = organization_id00
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(true)
done()
it 'Is auth user update permission same user', (done) ->
expect(Organizations.findOne().hasUser(Meteor.userId()).permission.owner).to.equal(true)
update_user_id = Meteor.userId()
organization_id = organization_id00
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
done()
it 'Is auth user update permission other user', (done) ->
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(true)
update_user_id = updateUser
organization_id = organization_id00
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(false)
done()
it 'Log out and login with auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword '<EMAIL>', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Is user manager only, setting owner ', (done) ->
expect(Organizations.findOne().hasUser(Meteor.userId()).permission.owner).to.equal(false)
update_user_id = Meteor.userId()
organization_id = organization_id00
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'permissionDenied')
done()
it 'Is user manager only, setting other', (done) ->
update_user_id = Meteor.userId()
organization_id = organization_id00
permission =
owner: false
viewer: true
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(Organizations.findOne().hasUser(Meteor.userId()).permission.viewer).to.equal(true)
done()
it 'Log out and login with auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword '<EMAIL>', '12345678', (err) ->
expect(err).to.not.exist
done()
)
organization_id01 = ''
it 'Create new organization', (done) ->
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
insert.call organ_doc, (err, res) ->
expect(err).to.not.exist
organization_id01 = res
done()
it 'Update nonexistent user of organization', (done) ->
this.timeout(50000);
setTimeout(done, 10000);
update_user_id = updateUser
organization_id = organization_id01
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error','notAuthorized')
it 'Log out and login with non auth user', (done) ->
updateUser = Meteor.userId()
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword '<EMAIL>', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Update existent user of non auth organization', (done) ->
update_user_id = updateUser
organization_id = organization_id01
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error','permissionDenied')
done()
describe 'Remove user from organization', ->
it 'Log out and login with owner', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword '<EMAIL>', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Remove nonexistent user', (done) ->
update_user_id = "nonono"
organization_id = Organizations.findOne()._id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
done()
it 'Remove existent user but not in organ', (done) ->
update_user_id = "nonono"
organization_id = Organizations.findOne()._id
Organizations.find().forEach (doc) ->
if doc.ousers.length > 1
for ouser in doc.ousers
if ouser.user_id isnt Meteor.userId()
update_user_id = ouser.user_id
else
organization_id = doc._id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
done()
it 'Try to remove owner', (done) ->
update_user_id = Meteor.userId()
organization_id = Organizations.findOne()._id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
expect(err).to.have.property('reason', 'an owner cannot remove themselves')
done()
it 'Remove correct', (done) ->
update_user_id = "nonono"
organization_id = Organizations.findOne()._id
length = ''
Organizations.find().forEach (doc) ->
if doc.ousers.length > 1
organization_id = doc._id
length = doc.ousers.length
for ouser in doc.ousers
if ouser.user_id isnt Meteor.userId()
update_user_id = ouser.user_id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
doc = Organizations.findOne(organization_id)
expect(length).to.be.above(doc.ousers.length)
expect(doc.hasUser(update_user_id)).to.not.exist
done()
describe 'Updating User profile', ->
before( (done) ->
doc =
email: '<EMAIL>'
password: '<PASSWORD>'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
done()
)
it 'Invalid profile doc', (done) ->
expect(Meteor.user()).to.exist
profile_doc =
nono: faker.name.firstName()
last_name: faker.name.lastName()
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.have.property('error', 'validation-error')
done()
it 'Valid profile doc update', (done) ->
expect(Meteor.user()).to.exist
firstName = Meteor.user().profile.first_name
profile_doc =
first_name: faker.name.firstName()
last_name: faker.name.lastName()
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.not.exist
expect(Meteor.user().profile.first_name).to.not.equal(firstName)
done()
it 'Valid profile doc with address update', (done) ->
expect(Meteor.user()).to.exist
firstName = Meteor.user().profile.first_name
address =
street: faker.address.streetAddress()
city: faker.address.city()
state: faker.address.state()
zip_code: faker.address.zipCode()
country: faker.address.country()
profile_doc =
first_name: faker.name.firstName()
last_name: faker.name.lastName()
addresses: [
address
]
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.not.exist
expect(Meteor.user().profile.first_name).to.not.equal(firstName)
expect(Meteor.user().profile.addresses.length).to.be.at.least(1)
console.log Meteor.user()
done()
it 'Valid profile doc with invalid address update', (done) ->
expect(Meteor.user()).to.exist
firstName = Meteor.user().profile.first_name
address =
city: faker.address.city()
state: faker.address.state()
zip_code: faker.address.zipCode()
country: faker.address.country()
profile_doc =
first_name: faker.name.firstName()
last_name: faker.name.lastName()
addresses: [
address
]
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.have.property('error','validation-error')
done()
| true | faker = require 'faker'
{ chai, assert, expect } = require 'meteor/practicalmeteor:chai'
{ Meteor } = require 'meteor/meteor'
{ Accounts } = require 'meteor/accounts-base'
{ resetDatabase } = require 'meteor/xolvio:cleaner'
{ _ } = require 'meteor/underscore'
{ Organizations } = require '../../imports/api/collections/organizations/organizations.coffee'
{
inviteUser
updatePermission
removeFromOrganization
updateProfile
} = require '../../imports/api/collections/users/methods.coffee'
{ insert } = require '../../imports/api/collections/organizations/methods.coffee'
xdescribe 'User Full App Tests Client', () ->
before( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
after( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
sharedEmail = faker.internet.email()
describe 'User sign up flow', () ->
after( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
it 'User simple schema fail validations', (done) ->
expect(Meteor.user()).to.not.exist
doc =
email: faker.internet.email()
password: 'PI:PASSWORD:<PASSWORD>END_PI'
Accounts.createUser doc, (err) ->
expect(err).to.have.property('error', 'validation-error');
done()
return
return
it 'User simple schema success validations', (done) ->
expect(Meteor.user()).to.not.exist
doc =
email: sharedEmail
password: 'PI:PASSWORD:<PASSWORD>END_PI'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
expect(error).to.not.exist
Meteor.logout( (err) ->
done()
)
return
return
it 'User simple schema duplicate emails', (done) ->
expect(Meteor.user()).to.not.exist
doc =
email: sharedEmail
password: 'PI:PASSWORD:<PASSWORD>END_PI'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
expect(error).to.have.property('reason', 'Email already exists.')
done()
return
return
describe 'Invite user to organization', ->
after( (done) ->
Meteor.logout( (err) ->
done()
)
return
)
it 'Invite nonexistent user to new organization not logged in', (done) ->
expect(Meteor.user()).to.not.exist
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = 'Dont Own'
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
expect ->
inviteUser.call {invited_user_doc, organization_id, permission}
.to.Throw('notLoggedIn')
doc =
email: faker.internet.email()
password: 'PI:PASSWORD:<PASSWORD>END_PI'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
expect(error).to.not.exist
done()
return
it 'Invite nonexistent user to new organization not Auth', (done) ->
expect(Meteor.user()).to.exist
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = 'AijWjNwoih4aB7mLK'
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc , organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized');
done()
return
shared_organization =
it 'Invite nonexistent user to new organization', (done) ->
expect(Meteor.user()).to.exist
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
insert.call organ_doc, (err, res) ->
expect(err).to.not.exist
return
shared_organization = Organizations.findOne()._id
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = shared_organization
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
currentUser = Meteor.userId()
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(currentUser).to.equal(Meteor.userId())
done()
return
it 'Invite existent user to organization' , (done) ->
expect(Meteor.user()).to.exist
invited_user_doc =
emails:
[
address: sharedEmail
]
profile:
first_name: faker.name.firstName()
organization_id = shared_organization
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
console.log err
expect(err).to.not.exist
done()
it 'Invite without correct permission', (done) ->
Meteor.loginWithPassword sharedEmail, '12345678', (err) ->
expect(err).to.not.exist
invited_user_doc =
emails:
[
address: faker.internet.email()
]
profile:
first_name: faker.name.firstName()
organization_id = shared_organization
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error','permissionDenied')
done()
describe 'User Login flow', ->
before( (done) ->
doc =
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
Meteor.logout( (err) ->
done()
)
return
)
after( (done) ->
Meteor.logout( (err) ->
)
@timeout(20000)
setTimeout(done, 10000)
)
it 'Invalid email', (done) ->
expect(Meteor.user()).to.not.exist
Meteor.loginWithPassword 'PI:EMAIL:<EMAIL>END_PI', 'PI:PASSWORD:<PASSWORD>END_PI6PI:PASSWORD:<PASSWORD>END_PI', (err) ->
expect(err).to.have.property('reason', 'User not found')
done()
it 'Invalid Password', (done) ->
expect(Meteor.user()).to.not.exist
Meteor.loginWithPassword 'PI:EMAIL:<EMAIL>END_PI', 'PI:PASSWORD:<PASSWORD>END_PI', (err) ->
expect(err).to.have.property('reason', 'Incorrect password')
done()
it 'Correct User', (done) ->
expect(Meteor.user()).to.not.exist
Meteor.loginWithPassword 'PI:EMAIL:<EMAIL>END_PI', 'PI:PASSWORD:<PASSWORD>END_PI', (err) ->
expect(err).to.not.exist
expect(Meteor.user()).to.exist
done()
describe 'User update permission', ->
before( (done) ->
callbacks =
onStop: () ->
onReady: () ->
done()
Meteor.subscribe("organizations", callbacks)
)
it 'Create new user', (done) ->
doc =
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (err) ->
expect(err).to.not.exist
done()
organization_id00 = ''
it 'Create organization', (done) ->
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
insert.call organ_doc, (err, res) ->
expect(err).to.not.exist
organization_id00 = res
done()
it 'Log Out and create new user log out again', (done) ->
Meteor.logout((err) ->
expect(err).to.not.exist
doc =
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (err) ->
expect(err).to.not.exist
Meteor.logout( (err) ->
expect(err).to.not.exist
done()
)
)
it 'Login and invite user', (done) ->
Meteor.loginWithPassword 'PI:EMAIL:<EMAIL>END_PI', '12345678', (err) ->
expect(err).to.not.exist
invited_user_doc =
emails:
[
address: 'PI:EMAIL:<EMAIL>END_PI'
]
profile:
first_name: faker.name.firstName()
organization_id = organization_id00
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
inviteUser.call {invited_user_doc, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
done()
it 'Log out and login with non auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'PI:EMAIL:<EMAIL>END_PI', '12345678', (err) ->
expect(err).to.not.exist
done()
)
updateUser = ''
it 'Is not owner or user manager but belongs to organ', (done) ->
updateUser = Meteor.userId()
update_user_id = updateUser
organization_id = organization_id00
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'permissionDenied')
done()
it 'Log out and login with auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'PI:EMAIL:<EMAIL>END_PI', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Is auth user update permission other user', (done) ->
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(false)
update_user_id = updateUser
organization_id = organization_id00
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(true)
done()
it 'Is auth user update permission same user', (done) ->
expect(Organizations.findOne().hasUser(Meteor.userId()).permission.owner).to.equal(true)
update_user_id = Meteor.userId()
organization_id = organization_id00
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
done()
it 'Is auth user update permission other user', (done) ->
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(true)
update_user_id = updateUser
organization_id = organization_id00
permission =
owner: false
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(Organizations.findOne().hasUser(updateUser).permission.owner).to.equal(false)
done()
it 'Log out and login with auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'PI:EMAIL:<EMAIL>END_PI', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Is user manager only, setting owner ', (done) ->
expect(Organizations.findOne().hasUser(Meteor.userId()).permission.owner).to.equal(false)
update_user_id = Meteor.userId()
organization_id = organization_id00
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error', 'permissionDenied')
done()
it 'Is user manager only, setting other', (done) ->
update_user_id = Meteor.userId()
organization_id = organization_id00
permission =
owner: false
viewer: true
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: true
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.not.exist
expect(Organizations.findOne().hasUser(Meteor.userId()).permission.viewer).to.equal(true)
done()
it 'Log out and login with auth user', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'PI:EMAIL:<EMAIL>END_PI', '12345678', (err) ->
expect(err).to.not.exist
done()
)
organization_id01 = ''
it 'Create new organization', (done) ->
organ_doc =
name: faker.company.companyName()
email: faker.internet.email()
insert.call organ_doc, (err, res) ->
expect(err).to.not.exist
organization_id01 = res
done()
it 'Update nonexistent user of organization', (done) ->
this.timeout(50000);
setTimeout(done, 10000);
update_user_id = updateUser
organization_id = organization_id01
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error','notAuthorized')
it 'Log out and login with non auth user', (done) ->
updateUser = Meteor.userId()
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'PI:EMAIL:<EMAIL>END_PI', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Update existent user of non auth organization', (done) ->
update_user_id = updateUser
organization_id = organization_id01
permission =
owner: true
viewer: false
expenses_manager: false
sells_manager: false
units_manager: false
inventories_manager: true
users_manager: false
updatePermission.call {update_user_id, organization_id, permission}, (err, res) ->
expect(err).to.have.property('error','permissionDenied')
done()
describe 'Remove user from organization', ->
it 'Log out and login with owner', (done) ->
Meteor.logout( (err) ->
expect(err).to.not.exist
Meteor.loginWithPassword 'PI:EMAIL:<EMAIL>END_PI', '12345678', (err) ->
expect(err).to.not.exist
done()
)
it 'Remove nonexistent user', (done) ->
update_user_id = "nonono"
organization_id = Organizations.findOne()._id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
done()
it 'Remove existent user but not in organ', (done) ->
update_user_id = "nonono"
organization_id = Organizations.findOne()._id
Organizations.find().forEach (doc) ->
if doc.ousers.length > 1
for ouser in doc.ousers
if ouser.user_id isnt Meteor.userId()
update_user_id = ouser.user_id
else
organization_id = doc._id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
done()
it 'Try to remove owner', (done) ->
update_user_id = Meteor.userId()
organization_id = Organizations.findOne()._id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
expect(err).to.have.property('error', 'notAuthorized')
expect(err).to.have.property('reason', 'an owner cannot remove themselves')
done()
it 'Remove correct', (done) ->
update_user_id = "nonono"
organization_id = Organizations.findOne()._id
length = ''
Organizations.find().forEach (doc) ->
if doc.ousers.length > 1
organization_id = doc._id
length = doc.ousers.length
for ouser in doc.ousers
if ouser.user_id isnt Meteor.userId()
update_user_id = ouser.user_id
removeFromOrganization.call {update_user_id, organization_id}, (err, res) ->
doc = Organizations.findOne(organization_id)
expect(length).to.be.above(doc.ousers.length)
expect(doc.hasUser(update_user_id)).to.not.exist
done()
describe 'Updating User profile', ->
before( (done) ->
doc =
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
profile:
first_name: faker.name.firstName()
last_name: faker.name.lastName()
Accounts.createUser doc, (error) ->
done()
)
it 'Invalid profile doc', (done) ->
expect(Meteor.user()).to.exist
profile_doc =
nono: faker.name.firstName()
last_name: faker.name.lastName()
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.have.property('error', 'validation-error')
done()
it 'Valid profile doc update', (done) ->
expect(Meteor.user()).to.exist
firstName = Meteor.user().profile.first_name
profile_doc =
first_name: faker.name.firstName()
last_name: faker.name.lastName()
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.not.exist
expect(Meteor.user().profile.first_name).to.not.equal(firstName)
done()
it 'Valid profile doc with address update', (done) ->
expect(Meteor.user()).to.exist
firstName = Meteor.user().profile.first_name
address =
street: faker.address.streetAddress()
city: faker.address.city()
state: faker.address.state()
zip_code: faker.address.zipCode()
country: faker.address.country()
profile_doc =
first_name: faker.name.firstName()
last_name: faker.name.lastName()
addresses: [
address
]
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.not.exist
expect(Meteor.user().profile.first_name).to.not.equal(firstName)
expect(Meteor.user().profile.addresses.length).to.be.at.least(1)
console.log Meteor.user()
done()
it 'Valid profile doc with invalid address update', (done) ->
expect(Meteor.user()).to.exist
firstName = Meteor.user().profile.first_name
address =
city: faker.address.city()
state: faker.address.state()
zip_code: faker.address.zipCode()
country: faker.address.country()
profile_doc =
first_name: faker.name.firstName()
last_name: faker.name.lastName()
addresses: [
address
]
updateProfile.call {profile_doc}, (err, res) ->
expect(err).to.have.property('error','validation-error')
done()
|
[
{
"context": "nt/main-client\n start everything\n\n copyright mark hahn 2013\n MIT license\n https://github.com/mark-",
"end": 79,
"score": 0.99976646900177,
"start": 70,
"tag": "NAME",
"value": "mark hahn"
},
{
"context": " hahn 2013\n MIT license\n https://github.com/mark-hahn/bace/\n###\n\n\nbace \t = (window.bace\t\t?= {})\nmain ",
"end": 133,
"score": 0.9997121095657349,
"start": 124,
"tag": "USERNAME",
"value": "mark-hahn"
}
] | src/client/main-client.coffee | mark-hahn/bace | 1 | ###
file: src/client/main-client
start everything
copyright mark hahn 2013
MIT license
https://github.com/mark-hahn/bace/
###
bace = (window.bace ?= {})
main = (bace.main ?= {})
header = (bace.header ?= {})
multibox = (bace.multibox ?= {})
edit = (bace.edit ?= {})
{render, div,img,table,tr,td,text} = teacup
$main = null
main.init = ->
bace.$page.append render ->
div id:'pageMain', ->
div id:'editor', ->
$main = $ '#pageMain', bace.$page
edit.init $main
bace.barsAtTop = yes
main.resize = (w, h) ->
bace.$page.css width: w-1, height: h
if (hdrHgt = header.resize? w, h)
$main?.css
width: w - 18
height: h - hdrHgt
if bace.barsAtTop then $main?.css bottom: 0 \
else $main?.css top: 0
| 25855 | ###
file: src/client/main-client
start everything
copyright <NAME> 2013
MIT license
https://github.com/mark-hahn/bace/
###
bace = (window.bace ?= {})
main = (bace.main ?= {})
header = (bace.header ?= {})
multibox = (bace.multibox ?= {})
edit = (bace.edit ?= {})
{render, div,img,table,tr,td,text} = teacup
$main = null
main.init = ->
bace.$page.append render ->
div id:'pageMain', ->
div id:'editor', ->
$main = $ '#pageMain', bace.$page
edit.init $main
bace.barsAtTop = yes
main.resize = (w, h) ->
bace.$page.css width: w-1, height: h
if (hdrHgt = header.resize? w, h)
$main?.css
width: w - 18
height: h - hdrHgt
if bace.barsAtTop then $main?.css bottom: 0 \
else $main?.css top: 0
| true | ###
file: src/client/main-client
start everything
copyright PI:NAME:<NAME>END_PI 2013
MIT license
https://github.com/mark-hahn/bace/
###
bace = (window.bace ?= {})
main = (bace.main ?= {})
header = (bace.header ?= {})
multibox = (bace.multibox ?= {})
edit = (bace.edit ?= {})
{render, div,img,table,tr,td,text} = teacup
$main = null
main.init = ->
bace.$page.append render ->
div id:'pageMain', ->
div id:'editor', ->
$main = $ '#pageMain', bace.$page
edit.init $main
bace.barsAtTop = yes
main.resize = (w, h) ->
bace.$page.css width: w-1, height: h
if (hdrHgt = header.resize? w, h)
$main?.css
width: w - 18
height: h - hdrHgt
if bace.barsAtTop then $main?.css bottom: 0 \
else $main?.css top: 0
|
[
{
"context": " this.user.set_validated_attrs(['password', 'confirm_password'])\n this.set_validity(false)\n ",
"end": 891,
"score": 0.9088647365570068,
"start": 875,
"tag": "PASSWORD",
"value": "confirm_password"
}
] | pages/auth/change_password/auth_change_password.coffee | signonsridhar/sridhar_hbs | 0 | define(['bases/page',
'models/user/user',
'css!pages/auth/change_password/auth_change_password'
], (BasePage, User)->
BasePage.extend({
LANG:()->
LANG = {}
LANG.title = 'Reset your password'
LANG.subtitle = ''
LANG.errors = {}
LANG.errors.confirm_password = {}
LANG.errors.confirm_password[VALID.ERROR.EQUAL] = 'Password has to be the same'
LANG.errors.password = {}
LANG.errors.password[VALID.ERROR.REQUIRED] = 'Password is required'
return LANG
}, {
init:(elem, options)->
this.access_key = can.route.attr('access_key')
#alert('need to have an access key to be able to reset password') if not this.access_key?
this.options.user = this.user = new User()
this.user.set_validated_attrs(['password', 'confirm_password'])
this.set_validity(false)
this.render('auth/change_password/auth_change_password', {user: this.user})
this.bind_view(this.user)
this.on()
'form submit':()->
this.options.user.set_password(this.access_key).then(()=>
window.location = can.route.url({ main:'error',sub:'reset_password_success'})
setTimeout(()=>
window.location = can.route.url({ main:'auth',sub:'login'})
, 5000)
).fail((resp)->
window.location = can.route.url({ main:'error',sub:'account_locked'})
)
return false
'{user} change':()->
this.set_validity(this.user.valid())
})
) | 50992 | define(['bases/page',
'models/user/user',
'css!pages/auth/change_password/auth_change_password'
], (BasePage, User)->
BasePage.extend({
LANG:()->
LANG = {}
LANG.title = 'Reset your password'
LANG.subtitle = ''
LANG.errors = {}
LANG.errors.confirm_password = {}
LANG.errors.confirm_password[VALID.ERROR.EQUAL] = 'Password has to be the same'
LANG.errors.password = {}
LANG.errors.password[VALID.ERROR.REQUIRED] = 'Password is required'
return LANG
}, {
init:(elem, options)->
this.access_key = can.route.attr('access_key')
#alert('need to have an access key to be able to reset password') if not this.access_key?
this.options.user = this.user = new User()
this.user.set_validated_attrs(['password', '<PASSWORD>'])
this.set_validity(false)
this.render('auth/change_password/auth_change_password', {user: this.user})
this.bind_view(this.user)
this.on()
'form submit':()->
this.options.user.set_password(this.access_key).then(()=>
window.location = can.route.url({ main:'error',sub:'reset_password_success'})
setTimeout(()=>
window.location = can.route.url({ main:'auth',sub:'login'})
, 5000)
).fail((resp)->
window.location = can.route.url({ main:'error',sub:'account_locked'})
)
return false
'{user} change':()->
this.set_validity(this.user.valid())
})
) | true | define(['bases/page',
'models/user/user',
'css!pages/auth/change_password/auth_change_password'
], (BasePage, User)->
BasePage.extend({
LANG:()->
LANG = {}
LANG.title = 'Reset your password'
LANG.subtitle = ''
LANG.errors = {}
LANG.errors.confirm_password = {}
LANG.errors.confirm_password[VALID.ERROR.EQUAL] = 'Password has to be the same'
LANG.errors.password = {}
LANG.errors.password[VALID.ERROR.REQUIRED] = 'Password is required'
return LANG
}, {
init:(elem, options)->
this.access_key = can.route.attr('access_key')
#alert('need to have an access key to be able to reset password') if not this.access_key?
this.options.user = this.user = new User()
this.user.set_validated_attrs(['password', 'PI:PASSWORD:<PASSWORD>END_PI'])
this.set_validity(false)
this.render('auth/change_password/auth_change_password', {user: this.user})
this.bind_view(this.user)
this.on()
'form submit':()->
this.options.user.set_password(this.access_key).then(()=>
window.location = can.route.url({ main:'error',sub:'reset_password_success'})
setTimeout(()=>
window.location = can.route.url({ main:'auth',sub:'login'})
, 5000)
).fail((resp)->
window.location = can.route.url({ main:'error',sub:'account_locked'})
)
return false
'{user} change':()->
this.set_validity(this.user.valid())
})
) |
[
{
"context": "to play\n community: \"Społeczność\"\n editor: \"Edytor\"\n blog: \"Blog\"\n forum: \"Forum\"\n account:",
"end": 1334,
"score": 0.9885063767433167,
"start": 1328,
"tag": "NAME",
"value": "Edytor"
},
{
"context": "e an admin\n home: \"Główna\"\n contribute: \"Współpraca\"\n legal: \"Nota prawna\"\n about: \"O nas\"\n ",
"end": 1558,
"score": 0.9184995889663696,
"start": 1551,
"tag": "NAME",
"value": "ółpraca"
},
{
"context": "Nota prawna\"\n about: \"O nas\"\n contact: \"Kontakt\"\n twitter_follow: \"Subskrybuj\"\n teachers: \"",
"end": 1625,
"score": 0.5431899428367615,
"start": 1622,
"tag": "NAME",
"value": "akt"
},
{
"context": " nas\"\n contact: \"Kontakt\"\n twitter_follow: \"Subskrybuj\"\n teachers: \"Nauczyciele\"\n# careers: \"Caree",
"end": 1658,
"score": 0.9995602369308472,
"start": 1648,
"tag": "USERNAME",
"value": "Subskrybuj"
},
{
"context": " twitter_follow: \"Subskrybuj\"\n teachers: \"Nauczyciele\"\n# careers: \"Careers\"\n\n modal:\n close: \"Za",
"end": 1686,
"score": 0.7697011232376099,
"start": 1677,
"tag": "NAME",
"value": "uczyciele"
},
{
"context": "_required: \"Wymagana subskrypcja\"\n anonymous: \"Anonimowy gracz\"\n level_difficulty: \"Poziom trudności: \"\n c",
"end": 3803,
"score": 0.909832775592804,
"start": 3788,
"tag": "NAME",
"value": "Anonimowy gracz"
},
{
"context": "\n log_out: \"Wyloguj się\"\n forgot_password: \"Nie pamiętasz hasła?\"\n authenticate_gplus: \"Autoryzuj G+\"\n load_p",
"end": 5034,
"score": 0.997024416923523,
"start": 5015,
"tag": "PASSWORD",
"value": "Nie pamiętasz hasła"
},
{
"context": "count_title: \"Odzyskaj konto\"\n send_password: \"Wyślij hasło tymczasowe\"\n recovery_sent: \"Email do dozyskania hasła zo",
"end": 5728,
"score": 0.9993709921836853,
"start": 5705,
"tag": "PASSWORD",
"value": "Wyślij hasło tymczasowe"
},
{
"context": "apisz zmiany\"\n\n general:\n and: \"i\"\n name: \"Nazwa\"\n date: \"Data\"\n body: \"Zawartość\"\n versi",
"end": 6662,
"score": 0.9926396012306213,
"start": 6657,
"tag": "NAME",
"value": "Nazwa"
},
{
"context": "Reject\"\n# withdraw: \"Withdraw\"\n submitter: \"Przesyłający\"\n submitted: \"Przesłano\"\n commit_msg: \"Wiad",
"end": 6925,
"score": 0.9986917972564697,
"start": 6913,
"tag": "NAME",
"value": "Przesyłający"
},
{
"context": "ubject: \"Temat\"\n email: \"Email\"\n password: \"Hasło\"\n message: \"Wiadomość\"\n code: \"Kod\"\n lad",
"end": 7463,
"score": 0.9987010955810547,
"start": 7458,
"tag": "PASSWORD",
"value": "Hasło"
},
{
"context": "dder: \"Drabinka\"\n when: \"kiedy\"\n opponent: \"Przeciwnik\"\n rank: \"Ranking\"\n score: \"Wynik\"\n win: ",
"end": 7572,
"score": 0.980793297290802,
"start": 7562,
"tag": "NAME",
"value": "Przeciwnik"
},
{
"context": " medium: \"Średni\"\n hard: \"Trudny\"\n player: \"Gracz\"\n player_level: \"Poziom\" # Like player level 5",
"end": 7747,
"score": 0.8606278896331787,
"start": 7742,
"tag": "NAME",
"value": "Gracz"
},
{
"context": "t like level: Dungeons of Kithgard\n warrior: \"Wojownik\"\n ranger: \"Łucznik\"\n wizard: \"Czarodziej\"\n\n",
"end": 7858,
"score": 0.6764597296714783,
"start": 7851,
"tag": "NAME",
"value": "ojownik"
},
{
"context": "ędzy teorią a praktyką. W praktyce jednak, jest. - Yogi Berra\"\n tip_error_free: \"Są dwa sposoby by napisać p",
"end": 13283,
"score": 0.999791145324707,
"start": 13273,
"tag": "NAME",
"value": "Yogi Berra"
},
{
"context": "napisać program bez błędów. Tylko trzeci działa. - Alan Perlis\"\n tip_debugging_program: \"Jeżeli debugowanie j",
"end": 13386,
"score": 0.9998903870582581,
"start": 13375,
"tag": "NAME",
"value": "Alan Perlis"
},
{
"context": "rogramowanie musi być procesem umieszczania ich. - Edsger W. Dijkstra\"\n tip_forums: \"Udaj się na forum i powiedz nam",
"end": 13539,
"score": 0.9998879432678223,
"start": 13521,
"tag": "NAME",
"value": "Edsger W. Dijkstra"
},
{
"context": "e wygląda na niemożliwe zanim zostanie zrobione. - Nelson Mandela\"\n tip_talk_is_cheap: \"Gadać jest łatwo. Pokażc",
"end": 14636,
"score": 0.9998833537101746,
"start": 14622,
"tag": "NAME",
"value": "Nelson Mandela"
},
{
"context": "lk_is_cheap: \"Gadać jest łatwo. Pokażcie mi kod. - Linus Torvalds\"\n tip_first_language: \"Najbardziej zgubną rzec",
"end": 14713,
"score": 0.9998842477798462,
"start": 14699,
"tag": "NAME",
"value": "Linus Torvalds"
},
{
"context": " nauczyć jest twój pierwszy język programowania. - Alan Kay\"\n tip_hardware_problem: \"P: Ilu programistów p",
"end": 14842,
"score": 0.9998098611831665,
"start": 14834,
"tag": "NAME",
"value": "Alan Kay"
},
{
"context": "to problem sprzętowy.\"\n tip_hofstadters_law: \"Prawo Hofstadtera: Każdy projekt zabiera więcej czasu, niż planujes",
"end": 14999,
"score": 0.726624071598053,
"start": 14983,
"tag": "NAME",
"value": "rawo Hofstadtera"
},
{
"context": "\"Premature optimization is the root of all evil. - Donald Knuth\"\n# tip_brute_force: \"When in doubt, use brute ",
"end": 15208,
"score": 0.9996526837348938,
"start": 15196,
"tag": "NAME",
"value": "Donald Knuth"
},
{
"context": "ip_brute_force: \"When in doubt, use brute force. - Ken Thompson\"\n# tip_extrapolation: \"There are only two kind",
"end": 15279,
"score": 0.9998437166213989,
"start": 15267,
"tag": "NAME",
"value": "Ken Thompson"
},
{
"context": " you have the right to control your own destiny. - Linus Torvalds\"\n# tip_no_code: \"No code is faster than no cod",
"end": 15582,
"score": 0.9999011754989624,
"start": 15568,
"tag": "NAME",
"value": "Linus Torvalds"
},
{
"context": "r_lies: \"Code never lies, comments sometimes do. — Ron Jeffries\"\n# tip_reusable_software: \"Before software can",
"end": 15717,
"score": 0.9999004602432251,
"start": 15705,
"tag": "NAME",
"value": "Ron Jeffries"
},
{
"context": " measuring aircraft building progress by weight. — Bill Gates\"\n# tip_source_code: \"I want to change the worl",
"end": 16081,
"score": 0.9998924136161804,
"start": 16071,
"tag": "NAME",
"value": "Bill Gates"
},
{
"context": "a: \"Java is to JavaScript what Car is to Carpet. - Chris Heilmann\"\n# tip_move_forward: \"Whatever you do, keep mo",
"end": 16266,
"score": 0.9998822808265686,
"start": 16252,
"tag": "NAME",
"value": "Chris Heilmann"
},
{
"context": "_forward: \"Whatever you do, keep moving forward. - Martin Luther King Jr.\"\n# tip_google: \"Have a problem you can't sol",
"end": 16352,
"score": 0.9894734025001526,
"start": 16332,
"tag": "NAME",
"value": "Martin Luther King J"
},
{
"context": "ers. What they really hate is lousy programmers. - Larry Niven\"\n# tip_open_source_contribute: \"You can help C",
"end": 16610,
"score": 0.9998946785926819,
"start": 16599,
"tag": "NAME",
"value": "Larry Niven"
},
{
"context": "ecurse: \"To iterate is human, to recurse divine. - L. Peter Deutsch\"\n# tip_free_your_mind: \"You have to let it all",
"end": 16757,
"score": 0.9998738169670105,
"start": 16741,
"tag": "NAME",
"value": "L. Peter Deutsch"
},
{
"context": "he strongest of opponents always has a weakness. - Itachi Uchiha\"\n# tip_paper_and_pen: \"Before you start coding",
"end": 16971,
"score": 0.9999011158943176,
"start": 16958,
"tag": "NAME",
"value": "Itachi Uchiha"
},
{
"context": "\"First, solve the problem. Then, write the code. - John Johnson\"\n\n game_menu:\n inventory_tab: \"Ekwipunek\"\n ",
"end": 17167,
"score": 0.9997977614402771,
"start": 17155,
"tag": "NAME",
"value": "John Johnson"
},
{
"context": " scott_title: \"Współzałożyciel\"\n scott_blurb: \"Jedyny Rozsądny\"\n nick_title: \"Współzałożyciel\"\n nick_blurb",
"end": 29167,
"score": 0.9998137950897217,
"start": 29152,
"tag": "NAME",
"value": "Jedyny Rozsądny"
},
{
"context": " scott_blurb: \"Jedyny Rozsądny\"\n nick_title: \"Współzałożyciel\"\n nick_blurb: \"Guru Motywacji\"\n michael_tit",
"end": 29201,
"score": 0.9990542531013489,
"start": 29186,
"tag": "NAME",
"value": "Współzałożyciel"
},
{
"context": "yślij wiadomość\"\n contact_candidate: \"Kontakt z kandydatem\" # Deprecated\n# recruitment_reminder: \"Use th",
"end": 35644,
"score": 0.5801152586936951,
"start": 35635,
"tag": "USERNAME",
"value": "kandydate"
},
{
"context": "wrong_email: \"Błędny e-mail\"\n wrong_password: \"Błędne zdjęcie\"\n upload_picture: \"Wgraj zdjęcie\"\n delete_t",
"end": 36351,
"score": 0.9993668794631958,
"start": 36337,
"tag": "PASSWORD",
"value": "Błędne zdjęcie"
},
{
"context": "ia\"\n admin: \"Administrator\"\n new_password: \"Nowe hasło\"\n new_password_verify: \"Zweryfikuj\"\n type_i",
"end": 36581,
"score": 0.9993175864219666,
"start": 36571,
"tag": "PASSWORD",
"value": "Nowe hasło"
},
{
"context": "_password: \"Nowe hasło\"\n new_password_verify: \"Zweryfikuj\"\n type_in_email: \"Wpisz swój email, aby potwie",
"end": 36619,
"score": 0.999325156211853,
"start": 36609,
"tag": "PASSWORD",
"value": "Zweryfikuj"
},
{
"context": "wierdzić usunięcie konta.\"\n type_in_password: \"Wpisz również swoje hasło.\"\n email_subscriptions: \"Powiadomienia e",
"end": 36735,
"score": 0.8196966052055359,
"start": 36716,
"tag": "PASSWORD",
"value": "Wpisz również swoje"
},
{
"context": " saved: \"Zmiany zapisane\"\n password_mismatch: \"Hasła róznią się od siebie\"\n password_repeat: \"Powtórz swoje hasło.\"\n ",
"end": 37909,
"score": 0.9981266856193542,
"start": 37883,
"tag": "PASSWORD",
"value": "Hasła róznią się od siebie"
},
{
"context": "Hasła róznią się od siebie\"\n password_repeat: \"Powtórz swoje hasło.\"\n job_profile: \"Profil zatrudnienia\" # Rest of ",
"end": 37952,
"score": 0.9977008104324341,
"start": 37933,
"tag": "PASSWORD",
"value": "Powtórz swoje hasło"
},
{
"context": "lub CodeCombat na Facebooku\"\n social_twitter: \"Obserwuj CodeCombat na Twitterze\"\n social_gplus: \"Doł",
"end": 40657,
"score": 0.8937963843345642,
"start": 40651,
"tag": "USERNAME",
"value": "Obserw"
},
{
"context": "Combat na Facebooku\"\n social_twitter: \"Obserwuj CodeCombat na Twitterze\"\n social_gplus: \"Dołącz do CodeCo",
"end": 40670,
"score": 0.7925074100494385,
"start": 40660,
"tag": "USERNAME",
"value": "CodeCombat"
},
{
"context": " clan: \"Klan\"\n clans: \"Klany\"\n new_name: \"Nazwa nowego klanu\"\n new_description: \"Opis nowego k",
"end": 40931,
"score": 0.7784416079521179,
"start": 40926,
"tag": "NAME",
"value": "Nazwa"
},
{
"context": "klany\"\n my_clans: \"Moje klany\"\n clan_name: \"Nazwa klanu\"\n name: \"Nazwa\"\n chieftain: \"Dowódca\"\n t",
"end": 41221,
"score": 0.7026622891426086,
"start": 41210,
"tag": "NAME",
"value": "Nazwa klanu"
},
{
"context": "je klany\"\n clan_name: \"Nazwa klanu\"\n name: \"Nazwa\"\n chieftain: \"Dowódca\"\n type: \"Typ\"\n edi",
"end": 41239,
"score": 0.8635988235473633,
"start": 41234,
"tag": "NAME",
"value": "Nazwa"
},
{
"context": "by do klanu wysyłając im ten link.\"\n members: \"Członkowie\"\n progress: \"Postęp\"\n not_started_1",
"end": 41774,
"score": 0.5464706420898438,
"start": 41772,
"tag": "USERNAME",
"value": "Cz"
},
{
"context": " do klanu wysyłając im ten link.\"\n members: \"Członkowie\"\n progress: \"Postęp\"\n not_started_1: \"niero",
"end": 41782,
"score": 0.7411290407180786,
"start": 41774,
"tag": "NAME",
"value": "łonkowie"
},
{
"context": "ziomami z przyjaciółmi i innymi graczami. Zostań Rzemieślnikiem, który pomaga w uczeniu innych sztuki p",
"end": 47651,
"score": 0.6638267636299133,
"start": 47648,
"tag": "NAME",
"value": "zem"
},
{
"context": " sztuki programowania.\"\n adventurer_title: \"Podróżnik\"\n adventurer_title_description: \"(playtester)\"",
"end": 47748,
"score": 0.6097037196159363,
"start": 47742,
"tag": "NAME",
"value": "różnik"
},
{
"context": "y zanim zostaną opublikowane.\"\n scribe_title: \"Skryba\"\n scribe_title_description: \"(twórca artykułów",
"end": 47996,
"score": 0.9230501055717468,
"start": 47990,
"tag": "NAME",
"value": "Skryba"
},
{
"context": "jszy, cierpliwość wraz z naszym Podróżnikiem. Nasz Edytor Poziomów jest jest strasznie prymitywny i frustrujący w uż",
"end": 55448,
"score": 0.7989595532417297,
"start": 55433,
"tag": "NAME",
"value": "Edytor Poziomów"
},
{
"context": "sa jest dla ciebie.\"\n adventurer_attribute_1: \"Głód wiedzy. Chcesz nauczyć się programować, a my chcemy ci t",
"end": 56509,
"score": 0.9536111354827881,
"start": 56498,
"tag": "NAME",
"value": "Głód wiedzy"
},
{
"context": "zasu stroną uczącą.\"\n adventurer_attribute_2: \"Charyzma. Bądź uprzejmy, ale wyraźnie określaj, co wymaga ",
"end": 56697,
"score": 0.9891124963760376,
"start": 56689,
"tag": "NAME",
"value": "Charyzma"
},
{
"context": " Session\"\n article: \"Artykuł\"\n user_names: \"Nazwy użytkowników\"\n thang_names: \"Nazwy obiektów\"\n files: \"Pl",
"end": 69605,
"score": 0.9863746762275696,
"start": 69587,
"tag": "NAME",
"value": "Nazwy użytkowników"
},
{
"context": " sprite_sheet: \"Sprite Sheet\"\n employers: \"Pracodawcy\"\n candidates: \"Kandydaci\"\n# candidate_sessi",
"end": 69829,
"score": 0.9061715006828308,
"start": 69821,
"tag": "NAME",
"value": "acodawcy"
},
{
"context": "et\"\n employers: \"Pracodawcy\"\n candidates: \"Kandydaci\"\n# candidate_sessions: \"Candidate Sessions\"\n# ",
"end": 69857,
"score": 0.7893297076225281,
"start": 69849,
"tag": "NAME",
"value": "andydaci"
},
{
"context": "\n# last_updated: \"Last updated:\"\n contact: \"Kontakt\"\n# active: \"Looking for interview offers now\"\n",
"end": 79163,
"score": 0.9978896379470825,
"start": 79156,
"tag": "NAME",
"value": "Kontakt"
},
{
"context": "header: \"Fill in your name\"\n# name_anonymous: \"Anonymous Developer\"\n# name_help: \"Name you want employers to see,",
"end": 81310,
"score": 0.7963881492614746,
"start": 81291,
"tag": "NAME",
"value": "Anonymous Developer"
},
{
"context": "name_help: \"Name you want employers to see, like 'Nick Winter'.\"\n# short_description_header: \"Write a short ",
"end": 81378,
"score": 0.9998653531074524,
"start": 81367,
"tag": "NAME",
"value": "Nick Winter"
}
] | app/locale/pl.coffee | SaintRamzes/codecombat | 1 | module.exports = nativeDescription: "polski", englishDescription: "Polish", translation:
home:
slogan: "Naucz się programowania grając"
no_ie: "CodeCombat nie działa na Internet Explorer 8 i starszych. Przepraszamy!" # Warning that only shows up in IE8 and older
no_mobile: "CodeCombat nie został zaprojektowany dla urządzeń przenośnych, więc mogą występować pewne problemy w jego działaniu!" # Warning that shows up on mobile devices
play: "Graj" # The big play button that opens up the campaign view.
old_browser: "Wygląda na to, że twoja przeglądarka jest zbyt stara, by obsłużyć CodeCombat. Wybacz..." # Warning that shows up on really old Firefox/Chrome/Safari
old_browser_suffix: "Mimo tego możesz spróbować, ale prawdopodobnie gra nie będzie działać."
ipad_browser: "Zła wiadomość: CodeCombat nie działa na przeglądarce w iPadzie. Dobra wiadomość: nasza aplikacja na iPada czeka na akceptację od Apple."
campaign: "Kampania"
for_beginners: "Dla początkujących"
multiplayer: "Multiplayer" # Not currently shown on home page
for_developers: "Dla developerów" # Not currently shown on home page.
or_ipad: "Albo ściągnij na swojego iPada"
nav:
play: "Poziomy" # The top nav bar entry where players choose which levels to play
community: "Społeczność"
editor: "Edytor"
blog: "Blog"
forum: "Forum"
account: "Konto"
profile: "Profil"
stats: "Statystyki"
code: "Kod"
admin: "Admin" # Only shows up when you are an admin
home: "Główna"
contribute: "Współpraca"
legal: "Nota prawna"
about: "O nas"
contact: "Kontakt"
twitter_follow: "Subskrybuj"
teachers: "Nauczyciele"
# careers: "Careers"
modal:
close: "Zamknij"
okay: "OK"
not_found:
page_not_found: "Strona nie istnieje"
diplomat_suggestion:
title: "Pomóż w tłumaczeniu CodeCombat!" # This shows up when a player switches to a non-English language using the language selector.
sub_heading: "Potrzebujemy twoich zdolności językowych."
pitch_body: "Tworzymy CodeCombat w języku angielskim, jednak nasi gracze pochodzą z całego świata. Wielu z nich chciałoby zagrać w swoim języku, ponieważ nie znają angielskiego, więc jeśli znasz oba języki zostań Dyplomatą i pomóż w tłumaczeniu strony CodeCombat, jak i samej gry."
missing_translations: "Dopóki nie przetłumaczymy wszystkiego na polski, będziesz widział niektóre napisy w języku angielskim."
learn_more: "Dowiedz się więcej o Dyplomatach"
subscribe_as_diplomat: "Dołącz do Dyplomatów"
play:
play_as: "Graj jako " # Ladder page
spectate: "Oglądaj" # Ladder page
players: "graczy" # Hover over a level on /play
hours_played: "rozegranych godzin" # Hover over a level on /play
items: "Przedmioty" # Tooltip on item shop button from /play
unlock: "Odblokuj" # For purchasing items and heroes
confirm: "Potwierdź"
owned: "Posiadane" # For items you own
locked: "Zablokowane"
purchasable: "Można kupić" # For a hero you unlocked but haven't purchased
available: "Dostępny"
skills_granted: "Zdobyte umiejętności" # Property documentation details
heroes: "Bohaterowie" # Tooltip on hero shop button from /play
achievements: "Osiągnięcia" # Tooltip on achievement list button from /play
account: "Konto" # Tooltip on account button from /play
settings: "Opcje" # Tooltip on settings button from /play
poll: "Ankieta" # Tooltip on poll button from /play
next: "Dalej" # Go from choose hero to choose inventory before playing a level
change_hero: "Wybierz bohatera" # Go back from choose inventory to choose hero
choose_inventory: "Załóż przedmioty"
buy_gems: "Kup klejnoty"
subscription_required: "Wymagana subskrypcja"
anonymous: "Anonimowy gracz"
level_difficulty: "Poziom trudności: "
campaign_beginner: "Kampania dla początkujących"
awaiting_levels_adventurer_prefix: "Wydajemy pięć poziomów na tydzień." # {change}
awaiting_levels_adventurer: "Zapisz się jako Podróżnik,"
awaiting_levels_adventurer_suffix: "aby jako pierwszy grać w nowe poziomy."
adjust_volume: "Dopasuj głośność"
campaign_multiplayer: "Kampania dla wielu graczy"
campaign_multiplayer_description: "... w której konkurujesz z innymi graczami."
campaign_old_multiplayer: "(Nie używane) Stare areny multiplayer"
campaign_old_multiplayer_description: "Relikt bardziej cywilizowanej epoki. Nie są już prowadzone żadne symulacje dla tych starych aren."
share_progress_modal:
blurb: "Robisz coraz to większe postępy! Pokaż swoim rodzicom jak wiele nauczyłeś się z CodeCombat."
email_invalid: "Błędny adres e-mail."
form_blurb: "Wpisz adres email swich rodziców, a my ich o tym poinformujemy!"
form_label: "Adres email"
placeholder: "adres email"
title: "Wspaniała robota, Adepcie"
login:
sign_up: "Stwórz konto"
log_in: "Zaloguj się"
logging_in: "Logowanie..."
log_out: "Wyloguj się"
forgot_password: "Nie pamiętasz hasła?"
authenticate_gplus: "Autoryzuj G+"
load_profile: "Wczytaj Profil G+"
finishing: "Kończenie"
sign_in_with_facebook: "Logowanie z Facebookiem"
sign_in_with_gplus: "Logowanie z Google+"
signup_switch: "Chcesz stworzyć konto?"
signup:
email_announcements: "Otrzymuj powiadomienia na e-mail"
creating: "Tworzenie konta..."
sign_up: "Zarejestruj się"
log_in: "Zaloguj się używając hasła"
social_signup: "lub zaloguj się używając konta Facebook lub G+:"
required: "Musisz się zalogować zanim przejdziesz dalej."
login_switch: "Masz już konto?"
recover:
recover_account_title: "Odzyskaj konto"
send_password: "Wyślij hasło tymczasowe"
recovery_sent: "Email do dozyskania hasła został wysłany."
items:
primary: "Główne"
secondary: "Drugorzędne"
armor: "Zbroja"
accessories: "Akcesoria"
misc: "Różne"
books: "Książki"
common:
back: "Wstecz" # When used as an action verb, like "Navigate backward"
continue: "Dalej" # When used as an action verb, like "Continue forward"
loading: "Ładowanie..."
saving: "Zapisywanie..."
sending: "Wysyłanie…"
send: "Wyślij"
cancel: "Anuluj"
save: "Zapisz"
publish: "Opublikuj"
create: "Stwórz"
fork: "Fork"
play: "Zagraj" # When used as an action verb, like "Play next level"
retry: "Ponów"
actions: "Akcje"
info: "Informacje"
help: "Pomoc"
watch: "Obserwuj"
unwatch: "Nie obserwuj"
submit_patch: "Prześlij łatkę"
submit_changes: "Prześlij zmiany"
save_changes: "Zapisz zmiany"
general:
and: "i"
name: "Nazwa"
date: "Data"
body: "Zawartość"
version: "Wersja"
pending: "W trakcie"
accepted: "Przyjęto"
rejected: "Odrzucono"
withdrawn: "Wycofano"
# accept: "Accept"
# reject: "Reject"
# withdraw: "Withdraw"
submitter: "Przesyłający"
submitted: "Przesłano"
commit_msg: "Wiadomość do commitu"
version_history: "Historia wersji"
version_history_for: "Historia wersji dla: "
select_changes: "Zaznacz dwie zmiany poniżej aby zobaczyć różnice."
undo_prefix: "Cofnij"
undo_shortcut: "(Ctrl+Z)"
redo_prefix: "Ponów"
redo_shortcut: "(Ctrl+Shift+Z)"
play_preview: "Odtwórz podgląd obecnego poziomu"
result: "Wynik"
results: "Wyniki"
description: "Opis"
or: "lub"
subject: "Temat"
email: "Email"
password: "Hasło"
message: "Wiadomość"
code: "Kod"
ladder: "Drabinka"
when: "kiedy"
opponent: "Przeciwnik"
rank: "Ranking"
score: "Wynik"
win: "Wygrana"
loss: "Przegrana"
tie: "Remis"
easy: "Łatwy"
medium: "Średni"
hard: "Trudny"
player: "Gracz"
player_level: "Poziom" # Like player level 5, not like level: Dungeons of Kithgard
warrior: "Wojownik"
ranger: "Łucznik"
wizard: "Czarodziej"
units:
second: "sekunda"
seconds: "sekund"
minute: "minuta"
minutes: "minut"
hour: "godzina"
hours: "godzin"
day: "dzień"
days: "dni"
week: "tydzień"
weeks: "tygodni"
month: "miesiąc"
months: "miesięcy"
year: "rok"
years: "lat"
play_level:
done: "Zrobione"
# next_game: "Next game"
# show_menu: "Show game menu"
home: "Strona główna" # Not used any more, will be removed soon.
level: "Poziom" # Like "Level: Dungeons of Kithgard"
skip: "Pomiń"
game_menu: "Menu gry"
guide: "Przewodnik"
restart: "Zacznij od nowa"
goals: "Cele"
goal: "Cel"
running: "Symulowanie..."
success: "Sukces!"
incomplete: "Niekompletne"
timed_out: "Czas minął"
failing: "Niepowodzenie"
action_timeline: "Oś czasu"
click_to_select: "Kliknij jednostkę, by ją zaznaczyć."
control_bar_multiplayer: "Multiplayer"
control_bar_join_game: "Dołącz do gry"
reload: "Wczytaj ponownie"
reload_title: "Przywrócić cały kod?"
reload_really: "Czy jesteś pewien, że chcesz przywrócić kod startowy tego poziomu?"
reload_confirm: "Przywróć cały kod"
victory: "Zwycięstwo"
victory_title_prefix: ""
victory_title_suffix: " ukończony"
victory_sign_up: "Zarejestruj się, by zapisać postępy"
victory_sign_up_poke: "Chcesz zapisać swój kod? Stwórz bezpłatne konto!"
victory_rate_the_level: "Oceń poziom: " # Only in old-style levels.
victory_return_to_ladder: "Powrót do drabinki"
victory_play_continue: "Dalej"
victory_saving_progress: "Zapisywanie postępów"
victory_go_home: "Powrót do strony głównej"
victory_review: "Powiedz nam coś więcej!"
victory_review_placeholder: "Jak ci się podobał poziom?"
victory_hour_of_code_done: "Skończyłeś już?"
victory_hour_of_code_done_yes: "Tak, skończyłem moją Godzinę Kodu."
victory_experience_gained: "Doświadczenie zdobyte"
victory_gems_gained: "Klejnoty zdobyte"
victory_new_item: "Nowy przedmiot"
victory_viking_code_school: "O jejku, trudny był ten poziom, co? Jeśli jeszcze nie jesteś twórcą oprogramowania, możesz nim już zostać. Złóż swoje podanie o przyjęcie do Viking Code School, a z ich pomocą w zostaniesz na pewno w pełni profesjonalnym programistą."
victory_become_a_viking: "Zostań wikingiem"
# victory_bloc: "Great work! Your skills are improving, and someone's taking notice. If you've considered becoming a software developer, this may be your lucky day. Bloc is an online bootcamp that pairs you 1-on-1 with an expert mentor who will help train you into a professional developer! By beating A Mayhem of Munchkins, you're now eligible for a $500 price reduction with the code: CCRULES"
# victory_bloc_cta: "Meet your mentor – learn about Bloc"
guide_title: "Przewodnik"
tome_minion_spells: "Czary twojego podopiecznego" # Only in old-style levels.
tome_read_only_spells: "Czary tylko do odczytu" # Only in old-style levels.
tome_other_units: "Inne jednostki" # Only in old-style levels.
tome_cast_button_run: "Uruchom"
tome_cast_button_running: "Uruchomiono"
tome_cast_button_ran: "Uruchomiono"
tome_submit_button: "Prześlij"
tome_reload_method: "Wczytaj oryginalny kod dla tej metody" # Title text for individual method reload button.
tome_select_method: "Wybierz metode"
tome_see_all_methods: "Zobacz wszystkie metody możliwe do edycji" # Title text for method list selector (shown when there are multiple programmable methods).
tome_select_a_thang: "Wybierz kogoś do "
tome_available_spells: "Dostępne czary"
tome_your_skills: "Twoje umiejętności"
tome_current_method: "Obecna Metoda"
hud_continue_short: "Kontynuuj"
code_saved: "Kod zapisano"
skip_tutorial: "Pomiń (esc)"
keyboard_shortcuts: "Skróty klawiszowe"
loading_ready: "Gotowy!"
loading_start: "Rozpocznij poziom"
problem_alert_title: "Popraw swój kod"
time_current: "Teraz:"
time_total: "Maksymalnie:"
time_goto: "Idź do:"
non_user_code_problem_title: "Błąd podczas ładowania poziomu"
infinite_loop_title: "Wykryto niekończącą się pętlę"
infinite_loop_description: "Kod źródłowy, który miał stworzył ten świat nigdy nie przestał działać. Albo działa bardzo wolno, albo ma w sobie niekończącą sie pętlę. Albo też gdzieś jest błąd systemu. Możesz spróbować uruchomić go jeszcze raz, albo przywrócić domyślny kod. Jeśli nic nie pomoże daj nam o tym znać."
check_dev_console: "Możesz też otworzyć konsolę deweloperska i sprawdzić w czym tkwi problem."
check_dev_console_link: "(instrukcje)"
infinite_loop_try_again: "Próbuj ponownie"
infinite_loop_reset_level: "Resetuj poziom"
infinite_loop_comment_out: "Comment Out My Code"
tip_toggle_play: "Włącz/zatrzymaj grę naciskając Ctrl+P."
tip_scrub_shortcut: "Ctrl+[ i Ctrl+] przesuwają czas." # {change}
tip_guide_exists: "Klikając Przewodnik u góry strony uzyskasz przydatne informacje."
tip_open_source: "CodeCombat ma w 100% otwarty kod!"
tip_tell_friends: "Podoba ci się CodeCombat? Opowiedz o nas swoim znajomym!"
tip_beta_launch: "CodeCombat uruchomił fazę beta w październiku 2013."
tip_think_solution: "Myśl nad rozwiązaniem, nie problemem."
tip_theory_practice: "W teorii nie ma różnicy między teorią a praktyką. W praktyce jednak, jest. - Yogi Berra"
tip_error_free: "Są dwa sposoby by napisać program bez błędów. Tylko trzeci działa. - Alan Perlis"
tip_debugging_program: "Jeżeli debugowanie jest procesem usuwania błędów, to programowanie musi być procesem umieszczania ich. - Edsger W. Dijkstra"
tip_forums: "Udaj się na forum i powiedz nam co myślisz!"
tip_baby_coders: "W przyszłości, każde dziecko będzie Arcymagiem."
tip_morale_improves: "Ładowanie będzie kontynuowane gdy wzrośnie morale."
tip_all_species: "Wierzymy w równe szanse nauki programowania dla wszystkich gatunków."
tip_reticulating: "Siatkowanie kolców."
tip_harry: "Jesteś czarodziejem "
tip_great_responsibility: "Z wielką mocą programowania wiąże się wielka odpowiedzialność debugowania."
tip_munchkin: "Jeśli nie będziesz jadł warzyw, Munchkin przyjdzie po Ciebie w nocy."
tip_binary: "Jest tylko 10 typów ludzi na świecie: Ci którzy rozumieją kod binarny i ci którzy nie."
tip_commitment_yoda: "Programista musi najgłębsze zaangażowanie okazać. Umysł najpoważniejszy. ~ Yoda"
tip_no_try: "Rób. Lub nie rób. Nie ma próbowania. - Yoda"
tip_patience: "Cierpliwość musisz mieć, młody Padawanie. - Yoda"
tip_documented_bug: "Udokumentowany błąd nie jest błędem. Jest funkcją."
tip_impossible: "To zawsze wygląda na niemożliwe zanim zostanie zrobione. - Nelson Mandela"
tip_talk_is_cheap: "Gadać jest łatwo. Pokażcie mi kod. - Linus Torvalds"
tip_first_language: "Najbardziej zgubną rzeczą jakiej możesz się nauczyć jest twój pierwszy język programowania. - Alan Kay"
tip_hardware_problem: "P: Ilu programistów potrzeba by wymienić żarówkę? O: Żadnego,to problem sprzętowy."
tip_hofstadters_law: "Prawo Hofstadtera: Każdy projekt zabiera więcej czasu, niż planujesz, nawet jeśli przy planowaniu uwzględnisz prawo Hofstadtera."
# tip_premature_optimization: "Premature optimization is the root of all evil. - Donald Knuth"
# tip_brute_force: "When in doubt, use brute force. - Ken Thompson"
# tip_extrapolation: "There are only two kinds of people: those that can extrapolate from incomplete data..."
# tip_superpower: "Coding is the closest thing we have to a superpower."
# tip_control_destiny: "In real open source, you have the right to control your own destiny. - Linus Torvalds"
# tip_no_code: "No code is faster than no code."
# tip_code_never_lies: "Code never lies, comments sometimes do. — Ron Jeffries"
# tip_reusable_software: "Before software can be reusable it first has to be usable."
tip_optimization_operator: "Każdy język programowania ma operator optymalizujący. W większości z nich tym operatorem jest ‘//’"
# tip_lines_of_code: "Measuring programming progress by lines of code is like measuring aircraft building progress by weight. — Bill Gates"
# tip_source_code: "I want to change the world but they would not give me the source code."
# tip_javascript_java: "Java is to JavaScript what Car is to Carpet. - Chris Heilmann"
# tip_move_forward: "Whatever you do, keep moving forward. - Martin Luther King Jr."
# tip_google: "Have a problem you can't solve? Google it!"
# tip_adding_evil: "Adding a pinch of evil."
# tip_hate_computers: "That's the thing about people who think they hate computers. What they really hate is lousy programmers. - Larry Niven"
# tip_open_source_contribute: "You can help CodeCombat improve!"
# tip_recurse: "To iterate is human, to recurse divine. - L. Peter Deutsch"
# tip_free_your_mind: "You have to let it all go, Neo. Fear, doubt, and disbelief. Free your mind. - Morpheus"
# tip_strong_opponents: "Even the strongest of opponents always has a weakness. - Itachi Uchiha"
# tip_paper_and_pen: "Before you start coding, you can always plan with a sheet of paper and a pen."
# tip_solve_then_write: "First, solve the problem. Then, write the code. - John Johnson"
game_menu:
inventory_tab: "Ekwipunek"
save_load_tab: "Zapisz/Wczytaj"
options_tab: "Opcje"
guide_tab: "Przewodnik"
guide_video_tutorial: "Wideo poradnik"
guide_tips: "Wskazówki"
multiplayer_tab: "Multiplayer"
auth_tab: "Zarejestruj się"
inventory_caption: "Wyposaż swojego bohatera"
choose_hero_caption: "Wybierz bohatera, język"
save_load_caption: "... i przejrzyj historię"
options_caption: "Ustaw opcje"
guide_caption: "Dokumenty i wskazówki"
multiplayer_caption: "Graj ze znajomymi!"
auth_caption: "Zapisz swój postęp."
leaderboard:
leaderboard: "Najlepsze wyniki"
view_other_solutions: "Pokaż tablicę wyników"
scores: "Wyniki"
top_players: "Najlepsi gracze"
day: "Dziś"
week: "W tym tygodniu"
all: "Zawsze"
time: "Czas"
damage_taken: "Obrażenia otrzymane"
damage_dealt: "Obrażenia zadane"
difficulty: "Trudność"
gold_collected: "Złoto zebrane"
inventory:
choose_inventory: "Załóż przedmioty"
equipped_item: "Założone"
required_purchase_title: "Wymagane"
available_item: "Dostępne"
restricted_title: "Zabronione"
should_equip: "(kliknij podwójnie, aby założyć)"
equipped: "(założone)"
locked: "(zablokowane)"
restricted: "(zabronione)"
equip: "Załóż"
unequip: "Zdejmij"
buy_gems:
few_gems: "Kilka klejnotów"
pile_gems: "Stos klejnotów"
chest_gems: "Skrzynia z klejnotami"
purchasing: "Kupowanie..."
declined: "Karta została odrzucona"
retrying: "Błąd serwera, ponawiam."
prompt_title: "Za mało klejnotów"
prompt_body: "Chcesz zdobyć więcej?"
prompt_button: "Wejdź do sklepu"
recovered: "Przywrócono poprzednie zakupy. Prosze odświeżyć stronę."
price: "x3500 / mieś."
subscribe:
comparison_blurb: "Popraw swoje umiejętności z subskrypcją CodeCombat!"
feature1: "Ponad 100 poziomów w 4 różnych śwoatach" # {change}
feature2: "10 potężnych, <strong>nowych bohaterów</strong> z unikalnymi umiejętnościami!" # {change}
feature3: "Ponad 70 bonusowych poziomów" # {change}
feature4: "Dodatkowe <strong>3500 klejnotów</strong> co miesiąc!"
feature5: "Poradniki wideo"
feature6: "Priorytetowe wsparcie przez e-mail"
feature7: "Prywatne <strong>Klany</strong>"
free: "Darmowo"
month: "miesięcznie"
# must_be_logged: "You must be logged in first. Please create an account or log in from the menu above."
subscribe_title: "Zapisz się"
unsubscribe: "Wypisz się"
confirm_unsubscribe: "Potwierdź wypisanie się"
never_mind: "Nie ważne, i tak cię kocham"
thank_you_months_prefix: ""
thank_you_months_suffix: " - przez tyle miesięcy nas wspierałeś. Dziękujemy!"
thank_you: "Dziękujemy za wsparcie CodeCombat."
# sorry_to_see_you_go: "Sorry to see you go! Please let us know what we could have done better."
# unsubscribe_feedback_placeholder: "O, what have we done?"
# parent_button: "Ask your parent"
# parent_email_description: "We'll email them so they can buy you a CodeCombat subscription."
# parent_email_input_invalid: "Email address invalid."
# parent_email_input_label: "Parent email address"
# parent_email_input_placeholder: "Enter parent email"
# parent_email_send: "Send Email"
# parent_email_sent: "Email sent!"
# parent_email_title: "What's your parent's email?"
# parents: "For Parents"
# parents_title: "Dear Parent: Your child is learning to code. Will you help them continue?"
# parents_blurb1: "Your child has played __nLevels__ levels and learned programming basics. Help cultivate their interest and buy them a subscription so they can keep playing."
# parents_blurb1a: "Computer programming is an essential skill that your child will undoubtedly use as an adult. By 2020, basic software skills will be needed by 77% of jobs, and software engineers are in high demand across the world. Did you know that Computer Science is the highest-paid university degree?"
# parents_blurb2: "For $9.99 USD/mo, your child will get new challenges every week and personal email support from professional programmers."
# parents_blurb3: "No Risk: 100% money back guarantee, easy 1-click unsubscribe."
# payment_methods: "Payment Methods"
# payment_methods_title: "Accepted Payment Methods"
# payment_methods_blurb1: "We currently accept credit cards and Alipay."
# payment_methods_blurb2: "If you require an alternate form of payment, please contact"
# sale_already_subscribed: "You're already subscribed!"
# sale_blurb1: "Save 35%"
# sale_blurb2: "off regular subscription price of $120 for a whole year!"
# sale_button: "Sale!"
# sale_button_title: "Save 35% when you purchase a 1 year subscription"
# sale_click_here: "Click Here"
# sale_ends: "Ends"
# sale_extended: "*Existing subscriptions will be extended by 1 year."
# sale_feature_here: "Here's what you'll get:"
# sale_feature2: "Access to 9 powerful <strong>new heroes</strong> with unique skills!"
# sale_feature4: "<strong>42,000 bonus gems</strong> awarded immediately!"
# sale_continue: "Ready to continue adventuring?"
# sale_limited_time: "Limited time offer!"
# sale_new_heroes: "New heroes!"
# sale_title: "Back to School Sale"
# sale_view_button: "Buy 1 year subscription for"
# stripe_description: "Monthly Subscription"
# stripe_description_year_sale: "1 Year Subscription (35% discount)"
# subscription_required_to_play: "You'll need a subscription to play this level."
# unlock_help_videos: "Subscribe to unlock all video tutorials."
# personal_sub: "Personal Subscription" # Accounts Subscription View below
# loading_info: "Loading subscription information..."
# managed_by: "Managed by"
# will_be_cancelled: "Will be cancelled on"
# currently_free: "You currently have a free subscription"
# currently_free_until: "You currently have a subscription until"
# was_free_until: "You had a free subscription until"
# managed_subs: "Managed Subscriptions"
# managed_subs_desc: "Add subscriptions for other players (students, children, etc.)"
# managed_subs_desc_2: "Recipients must have a CodeCombat account associated with the email address you provide."
# group_discounts: "Group discounts"
# group_discounts_1: "We also offer group discounts for bulk subscriptions."
# group_discounts_1st: "1st subscription"
# group_discounts_full: "Full price"
# group_discounts_2nd: "Subscriptions 2-11"
# group_discounts_20: "20% off"
# group_discounts_12th: "Subscriptions 12+"
# group_discounts_40: "40% off"
# subscribing: "Subscribing..."
# recipient_emails_placeholder: "Enter email address to subscribe, one per line."
# subscribe_users: "Subscribe Users"
# users_subscribed: "Users subscribed:"
# no_users_subscribed: "No users subscribed, please double check your email addresses."
# current_recipients: "Current Recipients"
# unsubscribing: "Unsubscribing"
# subscribe_prepaid: "Click Subscribe to use prepaid code"
# using_prepaid: "Using prepaid code for monthly subscription"
choose_hero:
choose_hero: "Wybierz swojego bohatera"
programming_language: "Język programowania"
programming_language_description: "Którego języka programowania chcesz używać?"
default: "domyślny"
experimental: "Eksperymentalny"
python_blurb: "Prosty ale potężny."
javascript_blurb: "Język internetu."
coffeescript_blurb: "Przyjemniejsza składnia JavaScript."
clojure_blurb: "Nowoczesny Lisp."
lua_blurb: "Język skryptowy gier."
io_blurb: "Prosty lecz nieznany."
status: "Status"
hero_type: "Typ"
weapons: "Bronie"
weapons_warrior: "Miecze - Krótki zasięg, Brak magii"
weapons_ranger: "Kusze, Pistolety - Daleki zasięg, Brak magii"
weapons_wizard: "Różdżki, Laski - Daleki zasięg, Magia"
attack: "Obrażenia" # Can also translate as "Attack"
health: "Życie"
speed: "Szybkość"
regeneration: "Regenaracja"
range: "Zasięg" # As in "attack or visual range"
blocks: "Blok" # As in "this shield blocks this much damage"
backstab: "Cios" # As in "this dagger does this much backstab damage"
skills: "Umiejętności"
attack_1: "Zadaje"
# attack_2: "of listed"
attack_3: "obrażeń od broni."
health_1: "Zdobywa"
# health_2: "of listed"
health_3: "wytrzymałości pancerza."
speed_1: "Idzie do"
speed_2: "metrów na sekundę."
available_for_purchase: "Można wynająć" # Shows up when you have unlocked, but not purchased, a hero in the hero store
level_to_unlock: "Musisz odblokować poziom:" # 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: "Tylko nieliczni bohaterowie mogą brać udział w tym poziomie."
skill_docs:
writable: "zapisywalny" # Hover over "attack" in Your Skills while playing a level to see most of this
read_only: "tylko do odczytu"
# action: "Action"
# spell: "Spell"
action_name: "nazwa"
action_cooldown: "Zajmuje"
action_specific_cooldown: "Odpoczynek"
action_damage: "Obrażenia"
action_range: "Zasięg"
action_radius: "Promień"
action_duration: "Czas trwania"
example: "Przykład"
ex: "np." # Abbreviation of "example"
current_value: "Aktualna wartość"
default_value: "Domyślna wartość"
parameters: "Parametry"
returns: "Zwraca"
granted_by: "Zdobyte dzięki:"
save_load:
granularity_saved_games: "Zapisano"
granularity_change_history: "Historia"
options:
general_options: "Opcje ogólne" # Check out the Options tab in the Game Menu while playing a level
volume_label: "Głośność"
music_label: "Muzyka"
music_description: "Wł/Wył muzykę w tle."
editor_config_title: "Konfiguracja edytora"
editor_config_keybindings_label: "Przypisania klawiszy"
editor_config_keybindings_default: "Domyślny (Ace)"
editor_config_keybindings_description: "Dodaje skróty znane z popularnych edytorów."
editor_config_livecompletion_label: "Podpowiedzi na żywo"
editor_config_livecompletion_description: "Wyświetl sugestie autouzupełnienia podczas pisania."
editor_config_invisibles_label: "Pokaż białe znaki"
editor_config_invisibles_description: "Wyświetla białe znaki takie jak spacja czy tabulator."
editor_config_indentguides_label: "Pokaż linijki wcięć"
editor_config_indentguides_description: "Wyświetla pionowe linie, by lepiej zaznaczyć wcięcia."
editor_config_behaviors_label: "Inteligentne zachowania"
editor_config_behaviors_description: "Autouzupełnianie nawiasów, klamer i cudzysłowów."
about:
why_codecombat: "Dlaczego CodeCombat?"
why_paragraph_1: "Chcesz nauczyć się programowania? Nie potrzeba ci lekcji. Potrzeba ci pisania dużej ilości kodu w sposób sprawiający ci przyjemność."
why_paragraph_2_prefix: "O to chodzi w programowaniu - musi sprawiać radość. Nie radość w stylu"
why_paragraph_2_italic: "hura, nowa odznaka"
why_paragraph_2_center: ", ale radości w stylu"
why_paragraph_2_italic_caps: "NIE MAMO, MUSZĘ DOKOŃCZYĆ TEN POZIOM!"
why_paragraph_2_suffix: "Dlatego właśnie CodeCombat to gra multiplayer, a nie kurs oparty na zgamifikowanych lekcjach. Nie przestaniemy, dopóki ty nie będziesz mógł przestać--tym razem jednak w pozytywnym sensie."
why_paragraph_3: "Jeśli planujesz uzależnić się od jakiejś gry, uzależnij się od tej i zostań jednym z czarodziejów czasu technologii."
press_title: "Blogerzy/Prasa"
press_paragraph_1_prefix: "Chcesz o nas napisać? Śmiało możesz pobrać iu wykorzystać wszystkie informację dostępne w naszym"
press_paragraph_1_link: "pakiecie prasowym "
press_paragraph_1_suffix: ". Wszystkie loga i obrazki mogą zostać wykorzystane bez naszej wiedzy."
team: "Zespół"
george_title: "Współzałożyciel"
george_blurb: "Pan Prezes"
scott_title: "Współzałożyciel"
scott_blurb: "Jedyny Rozsądny"
nick_title: "Współzałożyciel"
nick_blurb: "Guru Motywacji"
michael_title: "Programista"
michael_blurb: "Sys Admin"
matt_title: "Programista"
matt_blurb: "Rowerzysta"
cat_title: "Główny Rzemieślnik"
cat_blurb: "Airbender"
josh_title: "Projektant Gier"
josh_blurb: "Podłoga to lawa"
jose_title: "Muzyka"
jose_blurb: "Odnosi Sukces"
retrostyle_title: "Ilustracje"
retrostyle_blurb: "RetroStyle Games"
teachers:
more_info: "Informacja dla nauczycieli"
# intro_1: "CodeCombat is an online game that teaches programming. Students write code in real programming languages."
# intro_2: "No experience required!"
# free_title: "How much does it cost?"
# cost_premium_server: "CodeCombat is free for the first five levels, after which it costs $9.99 USD per month for access to our other 190+ levels on our exclusive country-specific servers."
# free_1: "There are 110+ FREE levels which cover every concept."
# free_2: "A monthly subscription provides access to video tutorials and extra practice levels."
# teacher_subs_title: "Teachers get free subscriptions!"
# teacher_subs_0: "We offer free subscriptions to teachers for evaluation purposes."
# teacher_subs_1: "Please fill out our"
# teacher_subs_2: "Teacher Survey"
# teacher_subs_3: "to set up your subscription."
# sub_includes_title: "What is included in the subscription?"
# sub_includes_1: "In addition to the 110+ basic levels, students with a monthly subscription get access to these additional features:"
# sub_includes_2: "80+ practice levels"
# sub_includes_3: "Video tutorials"
# sub_includes_4: "Premium email support"
# sub_includes_5: "10 new heroes with unique skills to master"
# sub_includes_6: "3500 bonus gems every month"
# sub_includes_7: "Private Clans"
# monitor_progress_title: "How do I monitor student progress?"
# monitor_progress_1: "Student progress can be monitored by creating a"
# monitor_progress_2: "for your class."
# monitor_progress_3: "To add a student, send them the invite link for your Clan, which is on the"
# monitor_progress_4: "page."
# monitor_progress_5: "After they join, you will see a summary of the student's progress on your Clan's page."
# private_clans_1: "Private Clans provide increased privacy and detailed progress information for each student."
# private_clans_2: "To create a private Clan, check the 'Make clan private' checkbox when creating a"
# private_clans_3: "."
# who_for_title: "Who is CodeCombat for?"
# who_for_1: "We recommend CodeCombat for students aged 9 and up. No prior programming experience is needed."
# who_for_2: "We've designed CodeCombat to appeal to both boys and girls."
# material_title: "How much material is there?"
# material_premium_server: "Approximately 50 hours of gameplay spread over 190+ subscriber-only levels so far."
# material_1: "Approximately 25 hours of free content and an additional 15 hours of subscriber content."
# concepts_title: "What concepts are covered?"
# how_much_title: "How much does a monthly subscription cost?"
# how_much_1: "A"
# how_much_2: "monthly subscription"
# how_much_3: "costs $9.99, and can be cancelled anytime."
# how_much_4: "Additionally, we provide discounts for larger groups:"
# how_much_5: "We accept discounted one-time purchases and yearly subscription purchases for groups, such as a class or school. Please contact"
# how_much_6: "for more details."
# more_info_title: "Where can I find more information?"
# more_info_1: "Our"
# more_info_2: "teachers forum"
# more_info_3: "is a good place to connect with fellow educators who are using CodeCombat."
# sys_requirements_title: "System Requirements"
# sys_requirements_1: "A modern web browser. Newer versions of Chrome, Firefox, or Safari. Internet Explorer 9 or later."
# sys_requirements_2: "CodeCombat is not supported on iPad yet."
teachers_survey:
title: "Ankieta dla nauczycieli"
# must_be_logged: "You must be logged in first. Please create an account or log in from the menu above."
# retrieving: "Retrieving information..."
# being_reviewed_1: "Your application for a free trial subscription is being"
# being_reviewed_2: "reviewed."
# approved_1: "Your application for a free trial subscription was"
# approved_2: "approved."
# approved_3: "Further instructions have been sent to"
# denied_1: "Your application for a free trial subscription has been"
# denied_2: "denied."
# contact_1: "Please contact"
# contact_2: "if you have further questions."
# description_1: "We offer free subscriptions to teachers for evaluation purposes. You can find more information on our"
# description_2: "teachers"
# description_3: "page."
# description_4: "Please fill out this quick survey and we’ll email you setup instructions."
# email: "Email Address"
# school: "Name of School"
# location: "Name of City"
# age_students: "How old are your students?"
# under: "Under"
# other: "Other:"
# amount_students: "How many students do you teach?"
# hear_about: "How did you hear about CodeCombat?"
# fill_fields: "Please fill out all fields."
# thanks: "Thanks! We'll send you setup instructions shortly."
versions:
save_version_title: "Zapisz nową wersję"
new_major_version: "Nowa wersja główna"
submitting_patch: "Przesyłanie łatki..."
cla_prefix: "Aby zapisać zmiany, musisz najpierw zaakceptować naszą"
cla_url: "umowę licencyjną dla współtwórców (CLA)"
cla_suffix: "."
cla_agree: "AKCEPTUJĘ"
owner_approve: "Przed pojawieniem się zmian, właściciel musi je zatwierdzić."
contact:
contact_us: "Kontakt z CodeCombat"
welcome: "Miło Cię widzieć! Użyj tego formularza, żeby wysłać do nas wiadomość. "
forum_prefix: "W sprawach ogólnych, skorzystaj z "
forum_page: "naszego forum"
forum_suffix: "."
faq_prefix: "Jest też"
faq: "FAQ"
subscribe_prefix: "Jeśli masz jakiś problem z rozwiązaniem poziomu,"
subscribe: "wykup subskrypcję CodeCombat,"
subscribe_suffix: "a my z radością ci pomożemy."
subscriber_support: "Jako, że będziesz subskrybentem CodeCombat, twoje e-maile będą miały najwyższy priorytet."
screenshot_included: "Dołączymy zrzuty ekranu."
where_reply: "Gdzie mamy odpisać?"
send: "Wyślij wiadomość"
contact_candidate: "Kontakt z kandydatem" # Deprecated
# recruitment_reminder: "Use this form to reach out to candidates you are interested in interviewing. Remember that CodeCombat charges 15% of first-year salary. The fee is due upon hiring the employee and is refundable for 90 days if the employee does not remain employed. Part time, remote, and contract employees are free, as are interns." # Deprecated
account_settings:
title: "Ustawienia Konta"
not_logged_in: "Zaloguj się lub stwórz konto, by dostosować ustawienia."
autosave: "Zmiany zapisują się automatycznie"
me_tab: "Ja"
picture_tab: "Zdjęcie"
delete_account_tab: "Usuń swoje konto"
wrong_email: "Błędny e-mail"
wrong_password: "Błędne zdjęcie"
upload_picture: "Wgraj zdjęcie"
delete_this_account: "Usuń to konto całkowicie"
god_mode: "TRYB BOGA"
password_tab: "Hasło"
emails_tab: "Powiadomienia"
admin: "Administrator"
new_password: "Nowe hasło"
new_password_verify: "Zweryfikuj"
type_in_email: "Wpisz swój email, aby potwierdzić usunięcie konta."
type_in_password: "Wpisz również swoje hasło."
email_subscriptions: "Powiadomienia email"
email_subscriptions_none: "Brak powiadomień e-mail."
email_announcements: "Ogłoszenia"
email_announcements_description: "Otrzymuj powiadomienia o najnowszych wiadomościach i zmianach w CodeCombat."
email_notifications: "Powiadomienia"
email_notifications_summary: "Ustawienia spersonalizowanych, automatycznych powiadomień mailowych zależnych od twojej aktywności w CodeCombat."
email_any_notes: "Wszystkie powiadomienia"
email_any_notes_description: "Odznacz by wyłączyć wszystkie powiadomienia email."
email_news: "Nowości"
email_recruit_notes: "Możliwości zatrudnienia"
email_recruit_notes_description: "Jeżeli grasz naprawdę dobrze, możemy się z tobą skontaktować by zaoferować (lepszą) pracę."
contributor_emails: "Powiadomienia asystentów"
contribute_prefix: "Szukamy osób, które chciałyby do nas dołączyć! Sprawdź "
contribute_page: "stronę współpracy"
contribute_suffix: ", aby dowiedzieć się więcej."
email_toggle: "Zmień wszystkie"
error_saving: "Błąd zapisywania"
saved: "Zmiany zapisane"
password_mismatch: "Hasła róznią się od siebie"
password_repeat: "Powtórz swoje hasło."
job_profile: "Profil zatrudnienia" # Rest of this section (the job profile stuff and wizard stuff) is deprecated
job_profile_approved: "Twój profil zatrudnienia został zaakceptowany przez CodeCombat. Pracodawcy będą mogli go widzieć dopóki nie oznaczysz go jako nieaktywny lub nie będzie on zmieniany przez 4 tygodnie."
job_profile_explanation: "Witaj! Wypełnij to, a będziemy w kontakcie w sprawie znalezienie dla Ciebe pracy twórcy oprogramowania."
sample_profile: "Zobacz przykładowy profil"
view_profile: "Zobacz swój profil"
keyboard_shortcuts:
keyboard_shortcuts: "Skróty klawiszowe"
space: "Spacja"
enter: "Enter"
press_enter: "naciśnij enter"
escape: "Escape"
shift: "Shift"
run_code: "Uruchom obecny kod."
run_real_time: "Uruchom \"na żywo\"."
continue_script: "Kontynuuj ostatni skrypt."
skip_scripts: "Pomiń wszystkie pomijalne skrypty."
toggle_playback: "Graj/pauzuj."
# scrub_playback: "Scrub back and forward through time."
# single_scrub_playback: "Scrub back and forward through time by a single frame."
# scrub_execution: "Scrub through current spell execution."
# toggle_debug: "Toggle debug display."
# toggle_grid: "Toggle grid overlay."
# toggle_pathfinding: "Toggle pathfinding overlay."
# beautify: "Beautify your code by standardizing its formatting."
maximize_editor: "Maksymalizuj/minimalizuj edytor kodu."
community:
main_title: "Społeczność CodeCombat"
# introduction: "Check out the ways you can get involved below and decide what sounds the most fun. We look forward to working with you!"
# level_editor_prefix: "Use the CodeCombat"
# level_editor_suffix: "to create and edit levels. Users have created levels for their classes, friends, hackathons, students, and siblings. If create a new level sounds intimidating you can start by forking one of ours!"
# thang_editor_prefix: "We call units within the game 'thangs'. Use the"
# thang_editor_suffix: "to modify the CodeCombat source artwork. Allow units to throw projectiles, alter the direction of an animation, change a unit's hit points, or upload your own vector sprites."
# article_editor_prefix: "See a mistake in some of our docs? Want to make some instructions for your own creations? Check out the"
# article_editor_suffix: "and help CodeCombat players get the most out of their playtime."
find_us: "Znajdź nas na tych stronach"
social_github: "Przejrzyj cały nasz kod na platformie GitHub"
social_blog: "Przeczytaj blog CodeCombat na Sett"
social_discource: "Dołącz do dyskusji na naszym forum"
social_facebook: "Polub CodeCombat na Facebooku"
social_twitter: "Obserwuj CodeCombat na Twitterze"
social_gplus: "Dołącz do CodeCombat na Google+"
social_hipchat: "Pogadaj z nami na pblicznym czacie HipChat"
contribute_to_the_project: "Zostań współtwórcą CodeCombat"
clans:
clan: "Klan"
clans: "Klany"
new_name: "Nazwa nowego klanu"
new_description: "Opis nowego klanu"
make_private: "Stwórz prywatny klan"
subs_only: "tylko subskrybenci"
create_clan: "Stwórz nowy klan"
private_preview: "Podgląd"
public_clans: "Publiczne klany"
my_clans: "Moje klany"
clan_name: "Nazwa klanu"
name: "Nazwa"
chieftain: "Dowódca"
type: "Typ"
edit_clan_name: "Edytuj nazwe klanu"
edit_clan_description: "Edytuj opis klanu"
edit_name: "edytuj nazwe"
edit_description: "edytuj opis"
private: "(prywatny)"
summary: "Podsumowanie"
average_level: "Średni poziom"
average_achievements: "Średnio osiągnięć"
delete_clan: "Usuń klan"
leave_clan: "Opuść klan"
join_clan: "Dołacz do klanu"
invite_1: "Zaproszenie:"
invite_2: "*Zaproś nowe osoby do klanu wysyłając im ten link."
members: "Członkowie"
progress: "Postęp"
not_started_1: "nierozpoczęty"
started_1: "rozpoczęty"
complete_1: "ukończony"
exp_levels: "Rozwiń poziomy"
rem_hero: "Usuń bohatera"
status: "Status"
complete_2: "Ukończony"
started_2: "Rozpoczęto"
not_started_2: "Nie rozpoczęto"
view_solution: "Kliknij, aby obejrzeć rozwiązanie."
latest_achievement: "Ostatnie osiągnięcia"
playtime: "Czas gyr"
last_played: "Ostatnio grany"
# leagues_explanation: "Play in a league against other clan members in these multiplayer arena instances."
# track_concepts1: "Track concepts"
# track_concepts2a: "learned by each student"
# track_concepts2b: "learned by each member"
# track_concepts3a: "Track levels completed for each student"
# track_concepts3b: "Track levels completed for each member"
# track_concepts4a: "See your students'"
# track_concepts4b: "See your members'"
# track_concepts5: "solutions"
# track_concepts6a: "Sort students by name or progress"
# track_concepts6b: "Sort members by name or progress"
# track_concepts7: "Requires invitation"
# track_concepts8: "to join"
# private_require_sub: "Private clans require a subscription to create or join."
# courses:
# course: "Course"
# courses: "courses"
# not_enrolled: "You are not enrolled in this course."
# visit_pref: "Please visit the"
# visit_suf: "page to enroll."
# select_class: "Select one of your classes"
# unnamed: "*unnamed*"
# select: "Select"
# unnamed_class: "Unnamed Class"
# edit_settings: "edit class settings"
# edit_settings1: "Edit Class Settings"
# progress: "Class Progress"
# add_students: "Add Students"
# stats: "Statistics"
# total_students: "Total students:"
# average_time: "Average level play time:"
# total_time: "Total play time:"
# average_levels: "Average levels completed:"
# total_levels: "Total levels completed:"
# furthest_level: "Furthest level completed:"
# concepts_covered: "Concepts Covered"
# students: "Students"
# students1: "students"
# expand_details: "Expand details"
# concepts: "Concepts"
# levels: "levels"
# played: "Played"
# play_time: "Play time:"
# completed: "Completed:"
# invite_students: "Invite students to join this class."
# invite_link_header: "Link to join course"
# invite_link_p_1: "Give this link to students you would like to have join the course."
# invite_link_p_2: "Or have us email them directly:"
# capacity_used: "Course slots used:"
# enter_emails: "Enter student emails to invite, one per line"
# send_invites: "Send Invites"
# title: "Title"
# description: "Description"
# languages_available: "Select programming languages available to the class:"
# all_lang: "All Languages"
# show_progress: "Show student progress to everyone in the class"
# creating_class: "Creating class..."
# purchasing_course: "Purchasing course..."
# buy_course: "Buy Course"
# buy_course1: "Buy this course"
# create_class: "Create Class"
# select_all_courses: "Select 'All Courses' for a 50% discount!"
# all_courses: "All Courses"
# number_students: "Number of students"
# enter_number_students: "Enter the number of students you need for this class."
# name_class: "Name your class"
# displayed_course_page: "This will be displayed on the course page for you and your students. It can be changed later."
# buy: "Buy"
# purchasing_for: "You are purchasing a license for"
# creating_for: "You are creating a class for"
# for: "for" # Like in 'for 30 students'
# receive_code: "Afterwards you will receive an unlock code to distribute to your students, which they can use to enroll in your class."
# free_trial: "Free trial for teachers!"
# get_access: "to get individual access to all courses for evalutaion purposes."
# questions: "Questions?"
# faq: "Courses FAQ"
# question: "Q:" # Like in 'Question'
# question1: "What's the difference between these courses and the single player game?"
# answer: "A:" # Like in 'Answer'
# answer1: "The single player game is designed for individuals, while the courses are designed for classes."
# answer2: "The single player game has items, gems, hero selection, leveling up, and in-app purchases. Courses have classroom management features and streamlined student-focused level pacing."
# teachers_click: "Teachers Click Here"
# students_click: "Students Click Here"
# courses_on_coco: "Courses on CodeCombat"
# designed_to: "Courses are designed to introduce computer science concepts using CodeCombat's fun and engaging environment. CodeCombat levels are organized around key topics to encourage progressive learning, over the course of 5 hours."
# more_in_less: "Learn more in less time"
# no_experience: "No coding experience necesssary"
# easy_monitor: "Easily monitor student progress"
# purchase_for_class: "Purchase a course for your entire class. It's easy to sign up your students!"
# see_the: "See the"
# more_info: "for more information."
# choose_course: "Choose Your Course:"
# enter_code: "Enter an unlock code to join an existing class"
# enter_code1: "Enter unlock code"
# enroll: "Enroll"
# pick_from_classes: "Pick from your current classes"
# enter: "Enter"
# or: "Or"
# topics: "Topics"
# hours_content: "Hours of content:"
# get_free: "Get FREE course"
classes:
archmage_title: "Arcymag"
archmage_title_description: "(programista)"
archmage_summary: "Jesteś programistą zainteresowanym tworzeniem gier edukacyjnych? Zostań Arcymagiem i pomóż nam ulepszyć CodeCombat!"
artisan_title: "Rzemieślnik"
artisan_title_description: "(twórca poziomów)"
artisan_summary: "Buduj i dziel się poziomami z przyjaciółmi i innymi graczami. Zostań Rzemieślnikiem, który pomaga w uczeniu innych sztuki programowania."
adventurer_title: "Podróżnik"
adventurer_title_description: "(playtester)"
adventurer_summary: "Zagraj w nasze nowe poziomy (nawet te dla subskrybentów) za darmo przez ich wydaniem i pomóż nam znaleźć w nich błędy zanim zostaną opublikowane."
scribe_title: "Skryba"
scribe_title_description: "(twórca artykułów)"
scribe_summary: "Dobry kod wymaga dobrej dokumentacji. Pisz, edytuj i ulepszaj dokumentację czytana przez miliony graczy na całym świecie."
diplomat_title: "Dyplomata"
diplomat_title_description: "(tłumacz)"
diplomat_summary: "CodeCombat jest tłumaczone na ponad 45 języków. Dołącz do naszch Dyplomatów i pomóż im w dalszych pracach."
ambassador_title: "Ambasador"
ambassador_title_description: "(wsparcie)"
ambassador_summary: "Okiełznaj naszych użytkowników na forum, udzielaj odpowiedzi na pytania i wspieraj ich. Nasi Ambasadorzy reprezentują CodeCombat przed całym światem."
editor:
main_title: "Edytory CodeCombat"
article_title: "Edytor artykułów"
thang_title: "Edytor obiektów"
level_title: "Edytor poziomów"
achievement_title: "Edytor osiągnięć"
poll_title: "Edytor ankiet"
back: "Wstecz"
revert: "Przywróć"
revert_models: "Przywróć wersję"
pick_a_terrain: "Wybierz teren"
dungeon: "Loch"
indoor: "Wnętrze"
desert: "Pustynia"
grassy: "Trawa"
mountain: "Góry"
glacier: "Lodowiec"
small: "Mały"
large: "Duży"
fork_title: "Forkuj nowa wersję"
fork_creating: "Tworzenie Forka..."
generate_terrain: "Generuj teren"
more: "Więcej"
wiki: "Wiki"
live_chat: "Czat na żywo"
thang_main: "Główna"
# thang_spritesheets: "Spritesheets"
thang_colors: "Kolory"
level_some_options: "Trochę opcji?"
level_tab_thangs: "Obiekty"
level_tab_scripts: "Skrypty"
level_tab_settings: "Ustawienia"
level_tab_components: "Komponenty"
level_tab_systems: "Systemy"
level_tab_docs: "Documentacja"
level_tab_thangs_title: "Aktualne obiekty"
level_tab_thangs_all: "Wszystkie"
level_tab_thangs_conditions: "Warunki początkowe"
level_tab_thangs_add: "Dodaj obiekty"
level_tab_thangs_search: "Przeszukaj obiekty"
add_components: "Dodaj komponenty"
component_configs: "Konfiguracja komponentów"
config_thang: "Kliknij dwukrotnie, aby skonfigurować obiekt"
delete: "Usuń"
duplicate: "Powiel"
stop_duplicate: "Przestań powielać"
rotate: "Obróć"
level_settings_title: "Ustawienia"
level_component_tab_title: "Aktualne komponenty"
level_component_btn_new: "Stwórz nowy komponent"
level_systems_tab_title: "Aktualne systemy"
level_systems_btn_new: "Stwórz nowy system"
level_systems_btn_add: "Dodaj system"
level_components_title: "Powrót do listy obiektów"
level_components_type: "Typ"
level_component_edit_title: "Edytuj komponent"
level_component_config_schema: "Schemat konfiguracji"
level_component_settings: "Ustawienia"
level_system_edit_title: "Edytuj system"
create_system_title: "Stwórz nowy system"
new_component_title: "Stwórz nowy komponent"
new_component_field_system: "System"
new_article_title: "Stwórz nowy artykuł"
new_thang_title: "Stwórz nowy typ obiektu"
new_level_title: "Stwórz nowy poziom"
new_article_title_login: "Zaloguj się, aby stworzyć nowy artykuł"
new_thang_title_login: "Zaloguj się, aby stworzyć nowy typ obiektu"
new_level_title_login: "Zaloguj się, aby stworzyć nowy poziom"
new_achievement_title: "Stwórz nowe osiągnięcie"
new_achievement_title_login: "Zaloguj się, aby stworzyć nowy osiągnięcie"
new_poll_title: "Stwórz nową ankietę"
new_poll_title_login: "Zaloguj się aby stworzyć nową ankietę"
article_search_title: "Przeszukaj artykuły"
thang_search_title: "Przeszukaj obiekty"
level_search_title: "Przeszukaj poziomy"
achievement_search_title: "Szukaj osiągnięcia"
poll_search_title: "Szukaj ankiety"
read_only_warning2: "Uwaga: nie możesz zapisać żadnych zmian, ponieważ nie jesteś zalogowany."
no_achievements: "Dla tego poziomu nie ma żadnych osiągnięć."
# achievement_query_misc: "Key achievement off of miscellanea"
# achievement_query_goals: "Key achievement off of level goals"
level_completion: "Ukończenie poziomu"
pop_i18n: "Uzupełnij I18N"
tasks: "Zadania"
clear_storage: "Usuń swoje lokalne zmiany"
# add_system_title: "Add Systems to Level"
done_adding: "Zakończono dodawanie"
article:
edit_btn_preview: "Podgląd"
edit_article_title: "Edytuj artykuł"
polls:
priority: "Priorytet"
contribute:
page_title: "Współpraca"
# intro_blurb: "CodeCombat is 100% open source! Hundreds of dedicated players have helped us build the game into what it is today. Join us and write the next chapter in CodeCombat's quest to teach the world to code!"
alert_account_message_intro: "Hej tam!"
alert_account_message: "Musisz się najpierw zalogować, jeśli chcesz zapisać się na klasowe e-maile."
archmage_introduction: "Jedną z najlepszych rzeczy w tworzeniu gier jest to, że syntetyzują one tak wiele różnych spraw. Grafika, dźwięk, łączność w czasie rzeczywistym, social networking i oczywiście wiele innych, bardziej popularnych, aspektów programowania, od niskopoziomowego zarządzania bazami danych i administracji serwerem do interfejsu użytkownika i jego tworzenia. Jest wiele do zrobienia i jeśli jesteś doświadczonym programistą z zacięciem, by zajrzeć do sedna CodeCombat, ta klasa może być dla ciebie. Bylibyśmy niezmiernie szczęśliwi mając twoją pomoc przy budowaniu najlepszej programistycznej gry wszech czasów."
class_attributes: "Atrybuty klasowe"
archmage_attribute_1_pref: "Znajomość "
archmage_attribute_1_suf: " lub chęć do nauki. Większość naszego kodu napisana jest w tym języku. Jeśli jesteś fanem Ruby czy Pythona, poczujesz się jak w domu. To po prostu JavaScript, tyle że z przyjemniejszą składnią."
archmage_attribute_2: "Pewne doświadczenie w programowaniu i własna inicjatywa. Pomożemy ci się połapać, ale nie możemy spędzić zbyt dużo czasu na szkoleniu cię."
how_to_join: "Jak dołączyć"
join_desc_1: "Każdy może pomóc! Zerknij po prostu na nasz "
join_desc_2: ", aby rozpocząć i zaznacz kratkę poniżej, aby określić sie jako mężny Arcymag oraz otrzymywać najświeższe wiadomości przez e-mail. Chcesz porozmawiać na temat tego, co robić lub w jaki sposób dołączyć do współpracy jeszcze wyraźniej? "
join_desc_3: " lub zajrzyj do naszego "
join_desc_4: ", a dowiesz się wszystkiego!"
join_url_email: "Napisz do nas"
join_url_hipchat: "publicznego pokoju HipChat"
archmage_subscribe_desc: "Otrzymuj e-maile dotyczące nowych okazji programistycznych oraz ogłoszeń."
artisan_introduction_pref: "Musimy stworzyć dodatkowe poziomy! Ludzie będą oczekiwać nowych zasobów, a my mamy ograniczone możliwości co do naszych mocy przerobowych. Obecnie, twoja stacja robocza jest na poziomie pierwszym; nasz edytor poziomów jest ledwo używalny nawet przez jego twórców - bądź tego świadom. Jeśli masz wizję nowych kampanii, od pętli typu for do"
artisan_introduction_suf: ", ta klasa może być dla ciebie."
artisan_attribute_1: "Jakiekolwiek doświadczenie w tworzeniu zasobów tego typu byłoby przydatne, na przykład używając edytora poziomów dostarczonego przez Blizzard. Nie jest to jednak wymagane."
artisan_attribute_2: "Zacięcie do całej masy testowania i iteracji. Aby tworzyć dobre poziomy, musisz dostarczyć je innym i obserwować jak grają oraz być przygotowanym na wprowadzanie mnóstwa poprawek."
artisan_attribute_3: "Na dzień dzisiejszy, cierpliwość wraz z naszym Podróżnikiem. Nasz Edytor Poziomów jest jest strasznie prymitywny i frustrujący w użyciu. Zostałeś ostrzeżony!"
artisan_join_desc: "Używaj Edytora Poziomów mniej-więcej zgodnie z poniższymi krokami:"
artisan_join_step1: "Przeczytaj dokumentację."
artisan_join_step2: "Stwórz nowy poziom i przejrzyj istniejące poziomy."
artisan_join_step3: "Zajrzyj do naszego publicznego pokoju HipChat, aby uzyskać pomoc."
artisan_join_step4: "Pokaż swoje poziomy na forum, aby uzyskać opinie."
artisan_subscribe_desc: "Otrzymuj e-maile dotyczące aktualności w tworzeniu poziomów i ogłoszeń."
adventurer_introduction: "Bądźmy szczerzy co do twojej roli: jesteś tankiem. Będziesz przyjmował ciężkie obrażenia. Potrzebujemy ludzi do testowania nowych poziomów i pomocy w rozpoznawaniu ulepszeń, które będzie można do nich zastosować. Będzie to bolesny proces; tworzenie dobrych gier to długi proces i nikt nie trafia w dziesiątkę za pierwszym razem. Jeśli jesteś wytrzymały i masz wysoki wskaźnik constitution (D&D), ta klasa jest dla ciebie."
adventurer_attribute_1: "Głód wiedzy. Chcesz nauczyć się programować, a my chcemy ci to umożliwić. Prawdopodobnie w tym przypadku, to ty będziesz jednak przez wiele czasu stroną uczącą."
adventurer_attribute_2: "Charyzma. Bądź uprzejmy, ale wyraźnie określaj, co wymaga poprawy, oferując sugestie co do sposobu jej uzyskania."
adventurer_join_pref: "Zapoznaj się z Rzemieślnikiem (lub rekrutuj go!), aby wspólnie pracować lub też zaznacz kratkę poniżej, aby otrzymywać e-maile, kiedy pojawią się nowe poziomy do testowania. Będziemy również pisać o poziomach do sprawdzenia na naszych stronach w sieciach społecznościowych jak"
adventurer_forum_url: "nasze forum"
adventurer_join_suf: "więc jeśli wolałbyś być informowany w ten sposób, zarejestruj się na nich!"
adventurer_subscribe_desc: "Otrzymuj e-maile, gdy pojawią się nowe poziomy do tesotwania."
scribe_introduction_pref: "CodeCombat nie będzie tylko zbieraniną poziomów. Będzie też zawierać źródło wiedzy, wiki programistycznych idei, na której będzie można oprzeć poziomy. Dzięki temu, każdy z Rzemieślników zamiast opisywać ze szczegółami, czym jest operator porónania, będzie mógł po prostu podać graczowi w swoim poziomie link do artykułu opisującego go. Mamy na myśli coś podobnego do "
scribe_introduction_url_mozilla: "Mozilla Developer Network"
scribe_introduction_suf: ". Jeśli twoją definicją zabawy jest artykułowanie idei programistycznych przy pomocy składni Markdown, ta klasa może być dla ciebie."
scribe_attribute_1: "Umiejętne posługiwanie się słowem to właściwie wszystko, czego potrzebujesz. Nie tylko gramatyka i ortografia, ale również umiejętnośc tłumaczenia trudnego materiału innym."
contact_us_url: "Skontaktuj się z nami"
scribe_join_description: "powiedz nam coś o sobie, swoim doświadczeniu w programowaniu i rzeczach, o których chciałbyś pisać, a chętnie to z tobą uzgodnimy!"
scribe_subscribe_desc: "Otrzymuj e-maile na temat ogłoszeń dotyczących pisania artykułów."
diplomat_introduction_pref: "Jeśli dowiedzieliśmy jednej rzeczy z naszego "
diplomat_launch_url: "otwarcia w październiku"
diplomat_introduction_suf: ", to jest nią informacja o znacznym zainteresowaniu CodeCombat w innych krajach. Tworzymy zespół tłumaczy chętnych do przemieniania zestawów słów w inne zestawy słów, aby CodeCombat było tak dostępne dla całego świata, jak to tylko możliwe. Jeśli chciabyś mieć wgląd w nadchodzącą zawartość i umożliwić swoim krajanom granie w najnowsze poziomy, ta klasa może być dla ciebie."
diplomat_attribute_1: "Biegła znajomość angielskiego oraz języka, na który chciałbyś tłumaczyć. Kiedy przekazujesz skomplikowane idee, dobrze mieć płynność w obu z nich!"
diplomat_i18n_page_prefix: "Możesz zacząć tłumaczyć nasze poziomy przechodząc na naszą"
diplomat_i18n_page: "stronę tłumaczeń"
diplomat_i18n_page_suffix: ", albo nasz interfejs i stronę na GitHub."
diplomat_join_pref_github: "Znajdź plik lokalizacyjny dla wybranego języka "
diplomat_github_url: "na GitHubie"
diplomat_join_suf_github: ", edytuj go online i wyślij pull request. Do tego, zaznacz kratkę poniżej, aby być na bieżąco z naszym międzynarodowym rozwojem!"
diplomat_subscribe_desc: "Otrzymuj e-maile na temat postępów i18n i poziomów do tłumaczenia."
ambassador_introduction: "Oto społeczność, którą budujemy, a ty jesteś jej łącznikiem. Mamy czaty, e-maile i strony w sieciach społecznościowych oraz wielu ludzi potrzebujących pomocy w zapoznaniu się z grą oraz uczeniu się za jej pomocą. Jeśli chcesz pomóc ludziom, by do nas dołączyli i dobrze się bawili oraz mieć pełne poczucie tętna CodeCombat oraz kierunku, w którym zmierzamy, ta klasa może być dla ciebie."
ambassador_attribute_1: "Umiejętność komunikacji. Musisz umieć rozpoznać problemy, które mają gracze i pomóc im je rozwiązać. Do tego, informuj resztę z nas, co mówią gracze - na co się skarżą, a czego chcą jeszcze więcej!"
ambassador_join_desc: "powiedz nam coś o sobie, jakie masz doświadczenie i czym byłbyś zainteresowany. Chętnie z tobą porozmawiamy!"
ambassador_join_note_strong: "Uwaga"
ambassador_join_note_desc: "Jednym z naszych priorytetów jest zbudowanie trybu multiplayer, gdzie gracze mający problem z rozwiązywaniem poziomów będą mogli wezwać czarodziejów wyższego poziomu, by im pomogli. Będzie to świetna okazja dla Ambasadorów. Spodziewajcie się ogłoszenia w tej sprawie!"
ambassador_subscribe_desc: "Otrzymuj e-maile dotyczące aktualizacji wsparcia oraz rozwoju trybu multiplayer."
changes_auto_save: "Zmiany zapisują się automatycznie po kliknięci kratki."
diligent_scribes: "Nasi pilni Skrybowie:"
powerful_archmages: "Nasi potężni Arcymagowie:"
creative_artisans: "Nasi kreatywni Rzemieślnicy:"
brave_adventurers: "Nasi dzielni Podróżnicy:"
translating_diplomats: "Nasi tłumaczący Dyplomaci:"
helpful_ambassadors: "Nasi pomocni Ambasadorzy:"
ladder:
please_login: "Przed rozpoczęciem gry rankingowej musisz się zalogować."
my_matches: "Moje pojedynki"
simulate: "Symuluj"
simulation_explanation: "Symulując gry możesz szybciej uzyskać ocenę swojej gry!"
# simulation_explanation_leagues: "You will mainly help simulate games for allied players in your clans and courses."
simulate_games: "Symuluj gry!"
games_simulated_by: "Gry symulowane przez Ciebie:"
games_simulated_for: "Gry symulowane dla Ciebie:"
# games_in_queue: "Games currently in the queue:"
games_simulated: "Gier zasymulowanych"
games_played: "Gier rozegranych"
ratio: "Proporcje"
leaderboard: "Tabela rankingowa"
battle_as: "Walcz jako "
summary_your: "Twój "
summary_matches: "Pojedynki - "
summary_wins: " Wygrane, "
summary_losses: " Przegrane"
rank_no_code: "Brak nowego kodu do oceny"
rank_my_game: "Oceń moją grę!"
rank_submitting: "Wysyłanie..."
rank_submitted: "Wysłano do oceny"
rank_failed: "Błąd oceniania"
rank_being_ranked: "Aktualnie oceniane gry"
rank_last_submitted: "przesłano "
help_simulate: "Pomóc w symulowaniu gier?"
code_being_simulated: "Twój nowy kod jest aktualnie symulowany przez innych graczy w celu oceny. W miarę pojawiania sie nowych pojedynków, nastąpi odświeżenie."
no_ranked_matches_pre: "Brak ocenionych pojedynków dla drużyny "
no_ranked_matches_post: " ! Zagraj przeciwko kilku oponentom i wróc tutaj, aby uzyskać ocenę gry."
choose_opponent: "Wybierz przeciwnika"
select_your_language: "Wybierz swój język!"
tutorial_play: "Rozegraj samouczek"
tutorial_recommended: "Zalecane, jeśli wcześniej nie grałeś"
tutorial_skip: "Pomiń samouczek"
tutorial_not_sure: "Nie wiesz, co się dzieje?"
tutorial_play_first: "Rozegraj najpierw samouczek."
simple_ai: "Proste AI"
warmup: "Rozgrzewka"
friends_playing: "Przyjaciele w grze"
log_in_for_friends: "Zaloguj się by grać ze swoimi znajomymi!"
social_connect_blurb: "Połącz konta i rywalizuj z przyjaciółmi!"
invite_friends_to_battle: "Zaproś przyjaciół do wspólnej walki!"
fight: "Walcz!"
watch_victory: "Obejrzyj swoje zwycięstwo"
defeat_the: "Pokonaj"
# watch_battle: "Watch the battle"
tournament_started: ", rozpoczęto"
# tournament_ends: "Tournament ends"
# tournament_ended: "Tournament ended"
# tournament_rules: "Tournament Rules"
# tournament_blurb: "Write code, collect gold, build armies, crush foes, win prizes, and upgrade your career in our $40,000 Greed tournament! Check out the details"
# tournament_blurb_criss_cross: "Win bids, construct paths, outwit opponents, grab gems, and upgrade your career in our Criss-Cross tournament! Check out the details"
# tournament_blurb_zero_sum: "Unleash your coding creativity in both gold gathering and battle tactics in this alpine mirror match between red sorcerer and blue sorcerer. The tournament began on Friday, March 27 and will run until Monday, April 6 at 5PM PDT. Compete for fun and glory! Check out the details"
# tournament_blurb_ace_of_coders: "Battle it out in the frozen glacier in this domination-style mirror match! The tournament began on Wednesday, September 16 and will run until Wednesday, October 14 at 5PM PDT. Check out the details"
# tournament_blurb_blog: "on our blog"
rules: "Zasady"
winners: "Zwycięzcy"
# league: "League"
# red_ai: "Red AI" # "Red AI Wins", at end of multiplayer match playback
# blue_ai: "Blue AI"
# wins: "Wins" # At end of multiplayer match playback
# humans: "Red" # Ladder page display team name
# ogres: "Blue"
user:
stats: "Statystyki"
singleplayer_title: "Poziomy jednoosobowe"
multiplayer_title: "Poziomy multiplayer"
achievements_title: "Osiągnięcia"
last_played: "Ostatnio grany"
status: "Status"
status_completed: "Ukończono"
status_unfinished: "Nie ukończono"
no_singleplayer: "Nie rozegrał żadnej gry jednoosobowej."
no_multiplayer: "Nie rozegrał żadnej gry multiplayer."
no_achievements: "Nie zdobył żadnych osiągnięć."
favorite_prefix: "Ulubiony język to "
favorite_postfix: "."
not_member_of_clans: "Nie jest członkiem żadnego klanu."
achievements:
last_earned: "Ostatnio zdobyty"
amount_achieved: "Ilość"
achievement: "Osiągnięcie"
category_contributor: "Współtwórca"
category_ladder: "Drabinka"
category_level: "Poziom"
category_miscellaneous: "Różne"
category_levels: "Poziomy"
category_undefined: "Poza kategorią"
# current_xp_prefix: ""
# current_xp_postfix: " in total"
new_xp_prefix: "zdobyto "
new_xp_postfix: ""
left_xp_prefix: ""
left_xp_infix: " brakuje do poziomu "
left_xp_postfix: ""
account:
recently_played: "Ostatnio grane"
# no_recent_games: "No games played during the past two weeks."
payments: "Płatności"
# prepaid_codes: "Prepaid Codes"
purchased: "Zakupiono"
# sale: "Sale"
subscription: "Subskrypcje"
invoices: "Faktury"
# service_apple: "Apple"
# service_web: "Web"
# paid_on: "Paid On"
# service: "Service"
price: "Cena"
gems: "Klejnoty"
active: "Aktywna"
subscribed: "Subskrybujesz"
unsubscribed: "Anulowano"
active_until: "Aktywna do"
cost: "Koszt"
next_payment: "Następna płatność"
card: "Karta"
# status_unsubscribed_active: "You're not subscribed and won't be billed, but your account is still active for now."
# status_unsubscribed: "Get access to new levels, heroes, items, and bonus gems with a CodeCombat subscription!"
account_invoices:
amount: "Kwota w dolarach"
declined: "Karta została odrzucona"
invalid_amount: "Proszę podać kwotę w dolarach."
not_logged_in: "Zaloguj się, albo stwórz konto, żeby przejrzeć faktury."
pay: "Opłać fakturę"
purchasing: "Kupowanie..."
retrying: "Błąd serwera, ponawiam."
success: "Zapłacono. Dziękujemy!"
# account_prepaid:
# purchase_code: "Purchase a Subscription Code"
# purchase_code1: "Subscription Codes can be redeemed to add premium subscription time to one or more CodeCombat accounts."
# purchase_code2: "Each CodeCombat account can only redeem a particular Subscription Code once."
# purchase_code3: "Subscription Code months will be added to the end of any existing subscription on the account."
# users: "Users"
# months: "Months"
# purchase_total: "Total"
# purchase_button: "Submit Purchase"
# your_codes: "Your Codes"
# redeem_codes: "Redeem a Subscription Code"
# prepaid_code: "Prepaid Code"
# lookup_code: "Lookup prepaid code"
# apply_account: "Apply to your account"
# copy_link: "You can copy the code's link and send it to someone."
# quantity: "Quantity"
# redeemed: "Redeemed"
# no_codes: "No codes yet!"
loading_error:
could_not_load: "Błąd podczas ładowania danych z serwera"
connection_failure: "Błąd połączenia."
unauthorized: "Musisz być zalogowany. Masz może wyłączone ciasteczka?"
forbidden: "Brak autoryzacji."
not_found: "Nie znaleziono."
not_allowed: "Metoda nie dozwolona."
timeout: "Serwer nie odpowiada."
conflict: "Błąd zasobów."
bad_input: "Złe dane wejściowe."
server_error: "Błąd serwera."
unknown: "Nieznany błąd."
# error: "ERROR"
resources:
sessions: "Sesje"
your_sessions: "Twoje sesje"
level: "Poziom"
# social_network_apis: "Social Network APIs"
# facebook_status: "Facebook Status"
# facebook_friends: "Facebook Friends"
# facebook_friend_sessions: "Facebook Friend Sessions"
# gplus_friends: "G+ Friends"
# gplus_friend_sessions: "G+ Friend Sessions"
# leaderboard: "Leaderboard"
# user_schema: "User Schema"
user_profile: "Profil użytkownika"
patch: "Łatka"
patches: "Łatki"
patched_model: "Dokument źródłowy"
model: "Model"
# system: "System"
# systems: "Systems"
component: "Komponent"
components: "Komponenty"
thang: "Obiekt"
thangs: "Obiekty"
# level_session: "Your Session"
# opponent_session: "Opponent Session"
article: "Artykuł"
user_names: "Nazwy użytkowników"
thang_names: "Nazwy obiektów"
files: "Pliki"
top_simulators: "Najlepsi symulatorzy"
source_document: "Dokument źródłowy"
document: "Dokument"
# sprite_sheet: "Sprite Sheet"
employers: "Pracodawcy"
candidates: "Kandydaci"
# candidate_sessions: "Candidate Sessions"
# user_remark: "User Remark"
# user_remarks: "User Remarks"
versions: "Wersje"
items: "Przedmioty"
hero: "Bohater"
heroes: "Bohaterowie"
achievement: "Osiągnięcie"
# clas: "CLAs"
play_counts: "Liczba gier"
feedback: "Wsparcie"
payment_info: "Info o płatnościach"
campaigns: "Kampanie"
poll: "Ankieta"
user_polls_record: "Historia oddanych głosów"
concepts:
advanced_strings: "Zaawansowane napisy"
algorithms: "Algorytmy"
arguments: "Argumenty"
arithmetic: "Arytmetyka"
arrays: "Tablice"
basic_syntax: "Podstawy składni"
boolean_logic: "Algebra Boole'a"
break_statements: "Klauzula 'break'"
classes: "Klasy"
# continue_statements: "Continue Statements"
for_loops: "Pętle 'for'"
functions: "Funkcje"
# graphics: "Graphics"
if_statements: "Wyrażenia warunkowe"
input_handling: "Zarządzanie wejściami"
math_operations: "Operacje matematyczne"
object_literals: "Operacje na obiektach"
# parameters: "Parameters"
strings: "Ciągi znaków"
variables: "Zmienne"
vectors: "Wektory"
while_loops: "Pętle"
recursion: "Rekurencja"
delta:
added: "Dodano"
modified: "Zmieniono"
not_modified: "Nie zmianiono"
deleted: "Usunięto"
moved_index: "Przesunięto Index"
# text_diff: "Text Diff"
# merge_conflict_with: "MERGE CONFLICT WITH"
no_changes: "Brak zmian"
multiplayer:
multiplayer_title: "Ustawienia multiplayer" # We'll be changing this around significantly soon. Until then, it's not important to translate.
multiplayer_toggle: "Aktywuj multiplayer"
multiplayer_toggle_description: "Pozwól innym dołączyć do twojej gry."
multiplayer_link_description: "Przekaż ten link, jeśli chcesz, by ktoś do ciebie dołączył."
multiplayer_hint_label: "Podpowiedź:"
multiplayer_hint: "Kliknij link by zaznaczyć wszystko, potem wciśnij Cmd-C lub Ctrl-C by skopiować ten link."
multiplayer_coming_soon: "Wkrótce więcej opcji multiplayer"
multiplayer_sign_in_leaderboard: "Zaloguj się lub zarejestruj by umieścić wynik na tablicy wyników."
legal:
page_title: "Nota prawna"
opensource_intro: "CodeCombat jest całkowicie darmowe i całkowicie open source."
opensource_description_prefix: "Zajrzyj na "
github_url: "nasz GitHub"
opensource_description_center: "i pomóż, jeśli tylko masz ochotę! CodeCombat bazuje na dziesiątkach projektów open source - kochamy je wszystkie. Wpadnij na "
archmage_wiki_url: "naszą wiki dla Arcymagów"
opensource_description_suffix: ", by zobaczyć listę oprogramowania, dzięki któremu niniejsza gra może istnieć."
practices_title: "Ludzkim językiem"
practices_description: "Oto nasze obietnice wobec ciebie, gracza, wyrażone po polsku, bez prawniczego żargonu."
privacy_title: "Prywatność"
privacy_description: "Nie sprzedamy żadnej z Twoich prywatnych informacji."
security_title: "Bezpieczeństwo"
security_description: "Z całych sił staramy się zabezpieczyć twoje prywatne informacje. Jako że jesteśmy projektem open source, każdy może sprawdzić i ulepszyć nasz system zabezpieczeń."
email_title: "E-mail"
email_description_prefix: "Nie będziemy nękać cię spamem. Poprzez"
email_settings_url: "twoje ustawienia e-mail"
email_description_suffix: "lub poprzez linki w e-mailach, które wysyłamy, możesz zmienić swoje ustawienia i w prosty sposób wypisać się z subskrypcji w dowolnym momencie."
cost_title: "Koszty"
cost_description: "W tym momencie CodeCombat jest w stu procentach darmowe! Jednym z naszych głównych celów jest, by utrzymać taki stan rzeczy, aby jak najwięcej ludzi miało dostęp do gry, bez względu na ich zasobność. Jeśli nadejdą gorsze dni, dopuszczamy możliwość wprowadzenia płatnych subskrypcji lub pobierania opłat za część zawartości, ale wolelibyśmy, by tak się nie stało. Przy odrobinie szczęścia, uda nam się podtrzymać obecną sytuację dzięki:"
copyrights_title: "Prawa autorskie i licencje"
contributor_title: "Umowa licencyjna dla współtwórców (CLA)"
contributor_description_prefix: "Wszyscy współtwórcy, zarówno ci ze strony jak i ci z GitHuba, podlegają naszemu"
cla_url: "CLA"
contributor_description_suffix: ", na które powinieneś wyrazić zgodę przed dodaniem swojego wkładu."
code_title: "Kod - MIT"
code_description_prefix: "Całość kodu posiadanego przez CodeCombat lub hostowanego na codecombat.com, zarówno w repozytorium GitHub, jak i bazie codecombat.com, podlega licencji"
mit_license_url: "Licencja MIT"
code_description_suffix: "Zawiera się w tym całość kodu w systemach i komponentach, które są udostępnione przez CodeCombat w celu tworzenia poziomów."
art_title: "Grafika/muzyka - Creative Commons "
art_description_prefix: "Całość ogólnej treści dostępna jest pod licencją"
cc_license_url: "Międzynarodowa Licencja Creative Commons Attribution 4.0"
art_description_suffix: "Zawartość ogólna to wszystko, co zostało publicznie udostępnione przez CodeCombat w celu tworzenia poziomów. Wchodzą w to:"
art_music: "Muzyka"
art_sound: "Dźwięki"
art_artwork: "Artworki"
art_sprites: "Sprite'y"
art_other: "Dowolne inne prace niezwiązane z kodem, które są dostępne podczas tworzenia poziomów."
art_access: "Obecnie nie ma uniwersalnego, prostego sposobu, by pozyskać te zasoby. Możesz wejść w ich posiadanie poprzez URL-e, z których korzysta strona, skontaktować się z nami w celu uzyskania pomocy bądź pomóc nam w ulepszeniu strony, aby zasoby te stały się łatwiej dostępne."
art_paragraph_1: "W celu uznania autorstwa, wymień z nazwy i podaj link do codecombat.com w pobliżu miejsca, gdzie znajduje się użyty zasób bądź w miejscu odpowiednim dla twojego medium. Na przykład:"
use_list_1: "W przypadku użycia w filmie lub innej grze, zawrzyj codecombat.com w napisach końcowych."
use_list_2: "W przypadku użycia na stronie internetowej, zawrzyj link w pobliżu miejsca użycia, na przykład po obrazkiem lub na ogólnej stronie poświęconej uznaniu twórców, gdzie możesz również wspomnieć o innych pracach licencjonowanych przy użyciu Creative Commons oraz oprogramowaniu open source używanym na stronie. Coś, co samo w sobie jednoznacznie odnosi się do CodeCombat, na przykład wpis na blogu dotyczący CodeCombat, nie wymaga już dodatkowego uznania autorstwa."
art_paragraph_2: "Jeśli użyte przez ciebie zasoby zostały stworzone nie przez CodeCombat, ale jednego z naszych użytkowników, uznanie autorstwa należy się jemu - postępuj wówczas zgodnie z zasadami uznania autorstwa dostarczonymi wraz z rzeczonym zasobem (o ile takowe występują)."
rights_title: "Prawa zastrzeżone"
rights_desc: "Wszelkie prawa są zastrzeżone dla poziomów jako takich. Zawierają się w tym:"
rights_scripts: "Skrypty"
rights_unit: "Konfiguracje jednostek"
rights_description: "Opisy"
rights_writings: "Teksty"
rights_media: "Multimedia (dźwięki, muzyka) i jakiekolwiek inne typy prac i zasobów stworzonych specjalnie dla danego poziomu, które nie zostały publicznie udostępnione do tworzenia poziomów."
rights_clarification: "Gwoli wyjaśnienia, wszystko, co jest dostępne w Edytorze Poziomów w celu tworzenia nowych poziomów, podlega licencji CC, podczas gdy zasoby stworzone w Edytorze Poziomów lub przesłane w toku tworzenia poziomu - nie."
nutshell_title: "W skrócie"
nutshell_description: "Wszelkie zasoby, które dostarczamy w Edytorze Poziomów są darmowe w użyciu w jakikolwiek sposób w celu tworzenia poziomów. Jednocześnie, zastrzegamy sobie prawo do ograniczenia rozpowszechniania poziomów (stworzonych przez codecombat.com) jako takich, aby mogła być za nie w przyszłości pobierana opłata, jeśli dojdzie do takiej konieczności."
canonical: "Angielska wersja tego dokumentu jest ostateczna, kanoniczną wersją. Jeśli zachodzą jakieś rozbieżności pomiędzy tłumaczeniami, dokument anglojęzyczny ma pierwszeństwo."
# ladder_prizes:
# title: "Tournament Prizes" # This section was for an old tournament and doesn't need new translations now.
# blurb_1: "These prizes will be awarded according to"
# blurb_2: "the tournament rules"
# blurb_3: "to the top human and ogre players."
# blurb_4: "Two teams means double the prizes!"
# blurb_5: "(There will be two first place winners, two second-place winners, etc.)"
# rank: "Rank"
# prizes: "Prizes"
# total_value: "Total Value"
# in_cash: "in cash"
# custom_wizard: "Custom CodeCombat Wizard"
# custom_avatar: "Custom CodeCombat avatar"
# heap: "for six months of \"Startup\" access"
# credits: "credits"
# one_month_coupon: "coupon: choose either Rails or HTML"
# one_month_discount: "discount, 30% off: choose either Rails or HTML"
# license: "license"
# oreilly: "ebook of your choice"
account_profile:
settings: "Ustawienia" # We are not actively recruiting right now, so there's no need to add new translations for this section.
edit_profile: "Edytuj Profil"
done_editing: "Edycja wykonana"
profile_for_prefix: "Profil "
profile_for_suffix: ""
# featured: "Featured"
# not_featured: "Not Featured"
# looking_for: "Looking for:"
# last_updated: "Last updated:"
contact: "Kontakt"
# active: "Looking for interview offers now"
# inactive: "Not looking for offers right now"
# complete: "complete"
next: "Nastepny"
next_city: "miasto?"
next_country: "wybierz kraj."
next_name: "imię?"
# next_short_description: "write a short description."
# next_long_description: "describe your desired position."
# next_skills: "list at least five skills."
# next_work: "chronicle your work history."
# next_education: "recount your educational ordeals."
# next_projects: "show off up to three projects you've worked on."
# next_links: "add any personal or social links."
# next_photo: "add an optional professional photo."
# next_active: "mark yourself open to offers to show up in searches."
# example_blog: "Blog"
# example_personal_site: "Personal Site"
# links_header: "Personal Links"
# links_blurb: "Link any other sites or profiles you want to highlight, like your GitHub, your LinkedIn, or your blog."
# links_name: "Link Name"
# links_name_help: "What are you linking to?"
# links_link_blurb: "Link URL"
# basics_header: "Update basic info"
# basics_active: "Open to Offers"
# basics_active_help: "Want interview offers right now?"
# basics_job_title: "Desired Job Title"
# basics_job_title_help: "What role are you looking for?"
# basics_city: "City"
# basics_city_help: "City you want to work in (or live in now)."
# basics_country: "Country"
# basics_country_help: "Country you want to work in (or live in now)."
# basics_visa: "US Work Status"
# basics_visa_help: "Are you authorized to work in the US, or do you need visa sponsorship? (If you live in Canada or Australia, mark authorized.)"
# basics_looking_for: "Looking For"
# basics_looking_for_full_time: "Full-time"
# basics_looking_for_part_time: "Part-time"
# basics_looking_for_remote: "Remote"
# basics_looking_for_contracting: "Contracting"
# basics_looking_for_internship: "Internship"
# basics_looking_for_help: "What kind of developer position do you want?"
# name_header: "Fill in your name"
# name_anonymous: "Anonymous Developer"
# name_help: "Name you want employers to see, like 'Nick Winter'."
# short_description_header: "Write a short description of yourself"
# short_description_blurb: "Add a tagline to help an employer quickly learn more about you."
# short_description: "Tagline"
# short_description_help: "Who are you, and what are you looking for? 140 characters max."
# skills_header: "Skills"
# skills_help: "Tag relevant developer skills in order of proficiency."
# long_description_header: "Describe your desired position"
# long_description_blurb: "Tell employers how awesome you are and what role you want."
# long_description: "Self Description"
# long_description_help: "Describe yourself to potential employers. Keep it short and to the point. We recommend outlining the position that would most interest you. Tasteful markdown okay; 600 characters max."
# work_experience: "Work Experience"
# work_header: "Chronicle your work history"
# work_years: "Years of Experience"
# work_years_help: "How many years of professional experience (getting paid) developing software do you have?"
# work_blurb: "List your relevant work experience, most recent first."
# work_employer: "Employer"
# work_employer_help: "Name of your employer."
# work_role: "Job Title"
# work_role_help: "What was your job title or role?"
# work_duration: "Duration"
# work_duration_help: "When did you hold this gig?"
# work_description: "Description"
# work_description_help: "What did you do there? (140 chars; optional)"
# education: "Education"
# education_header: "Recount your academic ordeals"
# education_blurb: "List your academic ordeals."
# education_school: "School"
# education_school_help: "Name of your school."
# education_degree: "Degree"
# education_degree_help: "What was your degree and field of study?"
# education_duration: "Dates"
# education_duration_help: "When?"
# education_description: "Description"
# education_description_help: "Highlight anything about this educational experience. (140 chars; optional)"
# our_notes: "CodeCombat's Notes"
# remarks: "Remarks"
# projects: "Projects"
# projects_header: "Add 3 projects"
# projects_header_2: "Projects (Top 3)"
# projects_blurb: "Highlight your projects to amaze employers."
# project_name: "Project Name"
# project_name_help: "What was the project called?"
# project_description: "Description"
# project_description_help: "Briefly describe the project."
# project_picture: "Picture"
# project_picture_help: "Upload a 230x115px or larger image showing off the project."
# project_link: "Link"
# project_link_help: "Link to the project."
# player_code: "Player Code"
# employers:
# deprecation_warning_title: "Sorry, CodeCombat is not recruiting right now."
# deprecation_warning: "We are focusing on beginner levels instead of finding expert developers for the time being."
# hire_developers_not_credentials: "Hire developers, not credentials." # We are not actively recruiting right now, so there's no need to add new translations for the rest of this section.
# get_started: "Get Started"
# already_screened: "We've already technically screened all our candidates"
# filter_further: ", but you can also filter further:"
# filter_visa: "Visa"
# filter_visa_yes: "US Authorized"
# filter_visa_no: "Not Authorized"
# filter_education_top: "Top School"
# filter_education_other: "Other"
# filter_role_web_developer: "Web Developer"
# filter_role_software_developer: "Software Developer"
# filter_role_mobile_developer: "Mobile Developer"
# filter_experience: "Experience"
# filter_experience_senior: "Senior"
# filter_experience_junior: "Junior"
# filter_experience_recent_grad: "Recent Grad"
# filter_experience_student: "College Student"
# filter_results: "results"
# start_hiring: "Start hiring."
# reasons: "Three reasons you should hire through us:"
# everyone_looking: "Everyone here is looking for their next opportunity."
# everyone_looking_blurb: "Forget about 20% LinkedIn InMail response rates. Everyone that we list on this site wants to find their next position and will respond to your request for an introduction."
# weeding: "Sit back; we've done the weeding for you."
# weeding_blurb: "Every player that we list has been screened for technical ability. We also perform phone screens for select candidates and make notes on their profiles to save you time."
# pass_screen: "They will pass your technical screen."
# pass_screen_blurb: "Review each candidate's code before reaching out. One employer found that 5x as many of our devs passed their technical screen than hiring from Hacker News."
# make_hiring_easier: "Make my hiring easier, please."
# what: "What is CodeCombat?"
# what_blurb: "CodeCombat is a multiplayer browser programming game. Players write code to control their forces in battle against other developers. Our players have experience with all major tech stacks."
# cost: "How much do we charge?"
# cost_blurb: "We charge 15% of first year's salary and offer a 100% money back guarantee for 90 days. We don't charge for candidates who are already actively being interviewed at your company."
# candidate_name: "Name"
# candidate_location: "Location"
# candidate_looking_for: "Looking For"
# candidate_role: "Role"
# candidate_top_skills: "Top Skills"
# candidate_years_experience: "Yrs Exp"
# candidate_last_updated: "Last Updated"
# candidate_who: "Who"
# featured_developers: "Featured Developers"
# other_developers: "Other Developers"
# inactive_developers: "Inactive Developers"
admin:
# av_espionage: "Espionage" # Really not important to translate /admin controls.
# av_espionage_placeholder: "Email or username"
# av_usersearch: "User Search"
# av_usersearch_placeholder: "Email, username, name, whatever"
# av_usersearch_search: "Search"
av_title: "Panel administracyjny"
av_entities_sub_title: "Podmioty"
av_entities_users_url: "Użytkownicy"
av_entities_active_instances_url: "Aktywne podmioty"
# av_entities_employer_list_url: "Employer List"
# av_entities_candidates_list_url: "Candidate List"
# av_entities_user_code_problems_list_url: "User Code Problems List"
av_other_sub_title: "Inne"
av_other_debug_base_url: "Baza (do debuggingu base.jade)"
u_title: "Lista użytkowników"
# ucp_title: "User Code Problems"
lg_title: "Ostatnie gry"
# clas: "CLAs"
| 130880 | module.exports = nativeDescription: "polski", englishDescription: "Polish", translation:
home:
slogan: "Naucz się programowania grając"
no_ie: "CodeCombat nie działa na Internet Explorer 8 i starszych. Przepraszamy!" # Warning that only shows up in IE8 and older
no_mobile: "CodeCombat nie został zaprojektowany dla urządzeń przenośnych, więc mogą występować pewne problemy w jego działaniu!" # Warning that shows up on mobile devices
play: "Graj" # The big play button that opens up the campaign view.
old_browser: "Wygląda na to, że twoja przeglądarka jest zbyt stara, by obsłużyć CodeCombat. Wybacz..." # Warning that shows up on really old Firefox/Chrome/Safari
old_browser_suffix: "Mimo tego możesz spróbować, ale prawdopodobnie gra nie będzie działać."
ipad_browser: "Zła wiadomość: CodeCombat nie działa na przeglądarce w iPadzie. Dobra wiadomość: nasza aplikacja na iPada czeka na akceptację od Apple."
campaign: "Kampania"
for_beginners: "Dla początkujących"
multiplayer: "Multiplayer" # Not currently shown on home page
for_developers: "Dla developerów" # Not currently shown on home page.
or_ipad: "Albo ściągnij na swojego iPada"
nav:
play: "Poziomy" # The top nav bar entry where players choose which levels to play
community: "Społeczność"
editor: "<NAME>"
blog: "Blog"
forum: "Forum"
account: "Konto"
profile: "Profil"
stats: "Statystyki"
code: "Kod"
admin: "Admin" # Only shows up when you are an admin
home: "Główna"
contribute: "Wsp<NAME>"
legal: "Nota prawna"
about: "O nas"
contact: "Kont<NAME>"
twitter_follow: "Subskrybuj"
teachers: "Na<NAME>"
# careers: "Careers"
modal:
close: "Zamknij"
okay: "OK"
not_found:
page_not_found: "Strona nie istnieje"
diplomat_suggestion:
title: "Pomóż w tłumaczeniu CodeCombat!" # This shows up when a player switches to a non-English language using the language selector.
sub_heading: "Potrzebujemy twoich zdolności językowych."
pitch_body: "Tworzymy CodeCombat w języku angielskim, jednak nasi gracze pochodzą z całego świata. Wielu z nich chciałoby zagrać w swoim języku, ponieważ nie znają angielskiego, więc jeśli znasz oba języki zostań Dyplomatą i pomóż w tłumaczeniu strony CodeCombat, jak i samej gry."
missing_translations: "Dopóki nie przetłumaczymy wszystkiego na polski, będziesz widział niektóre napisy w języku angielskim."
learn_more: "Dowiedz się więcej o Dyplomatach"
subscribe_as_diplomat: "Dołącz do Dyplomatów"
play:
play_as: "Graj jako " # Ladder page
spectate: "Oglądaj" # Ladder page
players: "graczy" # Hover over a level on /play
hours_played: "rozegranych godzin" # Hover over a level on /play
items: "Przedmioty" # Tooltip on item shop button from /play
unlock: "Odblokuj" # For purchasing items and heroes
confirm: "Potwierdź"
owned: "Posiadane" # For items you own
locked: "Zablokowane"
purchasable: "Można kupić" # For a hero you unlocked but haven't purchased
available: "Dostępny"
skills_granted: "Zdobyte umiejętności" # Property documentation details
heroes: "Bohaterowie" # Tooltip on hero shop button from /play
achievements: "Osiągnięcia" # Tooltip on achievement list button from /play
account: "Konto" # Tooltip on account button from /play
settings: "Opcje" # Tooltip on settings button from /play
poll: "Ankieta" # Tooltip on poll button from /play
next: "Dalej" # Go from choose hero to choose inventory before playing a level
change_hero: "Wybierz bohatera" # Go back from choose inventory to choose hero
choose_inventory: "Załóż przedmioty"
buy_gems: "Kup klejnoty"
subscription_required: "Wymagana subskrypcja"
anonymous: "<NAME>"
level_difficulty: "Poziom trudności: "
campaign_beginner: "Kampania dla początkujących"
awaiting_levels_adventurer_prefix: "Wydajemy pięć poziomów na tydzień." # {change}
awaiting_levels_adventurer: "Zapisz się jako Podróżnik,"
awaiting_levels_adventurer_suffix: "aby jako pierwszy grać w nowe poziomy."
adjust_volume: "Dopasuj głośność"
campaign_multiplayer: "Kampania dla wielu graczy"
campaign_multiplayer_description: "... w której konkurujesz z innymi graczami."
campaign_old_multiplayer: "(Nie używane) Stare areny multiplayer"
campaign_old_multiplayer_description: "Relikt bardziej cywilizowanej epoki. Nie są już prowadzone żadne symulacje dla tych starych aren."
share_progress_modal:
blurb: "Robisz coraz to większe postępy! Pokaż swoim rodzicom jak wiele nauczyłeś się z CodeCombat."
email_invalid: "Błędny adres e-mail."
form_blurb: "Wpisz adres email swich rodziców, a my ich o tym poinformujemy!"
form_label: "Adres email"
placeholder: "adres email"
title: "Wspaniała robota, Adepcie"
login:
sign_up: "Stwórz konto"
log_in: "Zaloguj się"
logging_in: "Logowanie..."
log_out: "Wyloguj się"
forgot_password: "<PASSWORD>?"
authenticate_gplus: "Autoryzuj G+"
load_profile: "Wczytaj Profil G+"
finishing: "Kończenie"
sign_in_with_facebook: "Logowanie z Facebookiem"
sign_in_with_gplus: "Logowanie z Google+"
signup_switch: "Chcesz stworzyć konto?"
signup:
email_announcements: "Otrzymuj powiadomienia na e-mail"
creating: "Tworzenie konta..."
sign_up: "Zarejestruj się"
log_in: "Zaloguj się używając hasła"
social_signup: "lub zaloguj się używając konta Facebook lub G+:"
required: "Musisz się zalogować zanim przejdziesz dalej."
login_switch: "Masz już konto?"
recover:
recover_account_title: "Odzyskaj konto"
send_password: "<PASSWORD>"
recovery_sent: "Email do dozyskania hasła został wysłany."
items:
primary: "Główne"
secondary: "Drugorzędne"
armor: "Zbroja"
accessories: "Akcesoria"
misc: "Różne"
books: "Książki"
common:
back: "Wstecz" # When used as an action verb, like "Navigate backward"
continue: "Dalej" # When used as an action verb, like "Continue forward"
loading: "Ładowanie..."
saving: "Zapisywanie..."
sending: "Wysyłanie…"
send: "Wyślij"
cancel: "Anuluj"
save: "Zapisz"
publish: "Opublikuj"
create: "Stwórz"
fork: "Fork"
play: "Zagraj" # When used as an action verb, like "Play next level"
retry: "Ponów"
actions: "Akcje"
info: "Informacje"
help: "Pomoc"
watch: "Obserwuj"
unwatch: "Nie obserwuj"
submit_patch: "Prześlij łatkę"
submit_changes: "Prześlij zmiany"
save_changes: "Zapisz zmiany"
general:
and: "i"
name: "<NAME>"
date: "Data"
body: "Zawartość"
version: "Wersja"
pending: "W trakcie"
accepted: "Przyjęto"
rejected: "Odrzucono"
withdrawn: "Wycofano"
# accept: "Accept"
# reject: "Reject"
# withdraw: "Withdraw"
submitter: "<NAME>"
submitted: "Przesłano"
commit_msg: "Wiadomość do commitu"
version_history: "Historia wersji"
version_history_for: "Historia wersji dla: "
select_changes: "Zaznacz dwie zmiany poniżej aby zobaczyć różnice."
undo_prefix: "Cofnij"
undo_shortcut: "(Ctrl+Z)"
redo_prefix: "Ponów"
redo_shortcut: "(Ctrl+Shift+Z)"
play_preview: "Odtwórz podgląd obecnego poziomu"
result: "Wynik"
results: "Wyniki"
description: "Opis"
or: "lub"
subject: "Temat"
email: "Email"
password: "<PASSWORD>"
message: "Wiadomość"
code: "Kod"
ladder: "Drabinka"
when: "kiedy"
opponent: "<NAME>"
rank: "Ranking"
score: "Wynik"
win: "Wygrana"
loss: "Przegrana"
tie: "Remis"
easy: "Łatwy"
medium: "Średni"
hard: "Trudny"
player: "<NAME>"
player_level: "Poziom" # Like player level 5, not like level: Dungeons of Kithgard
warrior: "W<NAME>"
ranger: "Łucznik"
wizard: "Czarodziej"
units:
second: "sekunda"
seconds: "sekund"
minute: "minuta"
minutes: "minut"
hour: "godzina"
hours: "godzin"
day: "dzień"
days: "dni"
week: "tydzień"
weeks: "tygodni"
month: "miesiąc"
months: "miesięcy"
year: "rok"
years: "lat"
play_level:
done: "Zrobione"
# next_game: "Next game"
# show_menu: "Show game menu"
home: "Strona główna" # Not used any more, will be removed soon.
level: "Poziom" # Like "Level: Dungeons of Kithgard"
skip: "Pomiń"
game_menu: "Menu gry"
guide: "Przewodnik"
restart: "Zacznij od nowa"
goals: "Cele"
goal: "Cel"
running: "Symulowanie..."
success: "Sukces!"
incomplete: "Niekompletne"
timed_out: "Czas minął"
failing: "Niepowodzenie"
action_timeline: "Oś czasu"
click_to_select: "Kliknij jednostkę, by ją zaznaczyć."
control_bar_multiplayer: "Multiplayer"
control_bar_join_game: "Dołącz do gry"
reload: "Wczytaj ponownie"
reload_title: "Przywrócić cały kod?"
reload_really: "Czy jesteś pewien, że chcesz przywrócić kod startowy tego poziomu?"
reload_confirm: "Przywróć cały kod"
victory: "Zwycięstwo"
victory_title_prefix: ""
victory_title_suffix: " ukończony"
victory_sign_up: "Zarejestruj się, by zapisać postępy"
victory_sign_up_poke: "Chcesz zapisać swój kod? Stwórz bezpłatne konto!"
victory_rate_the_level: "Oceń poziom: " # Only in old-style levels.
victory_return_to_ladder: "Powrót do drabinki"
victory_play_continue: "Dalej"
victory_saving_progress: "Zapisywanie postępów"
victory_go_home: "Powrót do strony głównej"
victory_review: "Powiedz nam coś więcej!"
victory_review_placeholder: "Jak ci się podobał poziom?"
victory_hour_of_code_done: "Skończyłeś już?"
victory_hour_of_code_done_yes: "Tak, skończyłem moją Godzinę Kodu."
victory_experience_gained: "Doświadczenie zdobyte"
victory_gems_gained: "Klejnoty zdobyte"
victory_new_item: "Nowy przedmiot"
victory_viking_code_school: "O jejku, trudny był ten poziom, co? Jeśli jeszcze nie jesteś twórcą oprogramowania, możesz nim już zostać. Złóż swoje podanie o przyjęcie do Viking Code School, a z ich pomocą w zostaniesz na pewno w pełni profesjonalnym programistą."
victory_become_a_viking: "Zostań wikingiem"
# victory_bloc: "Great work! Your skills are improving, and someone's taking notice. If you've considered becoming a software developer, this may be your lucky day. Bloc is an online bootcamp that pairs you 1-on-1 with an expert mentor who will help train you into a professional developer! By beating A Mayhem of Munchkins, you're now eligible for a $500 price reduction with the code: CCRULES"
# victory_bloc_cta: "Meet your mentor – learn about Bloc"
guide_title: "Przewodnik"
tome_minion_spells: "Czary twojego podopiecznego" # Only in old-style levels.
tome_read_only_spells: "Czary tylko do odczytu" # Only in old-style levels.
tome_other_units: "Inne jednostki" # Only in old-style levels.
tome_cast_button_run: "Uruchom"
tome_cast_button_running: "Uruchomiono"
tome_cast_button_ran: "Uruchomiono"
tome_submit_button: "Prześlij"
tome_reload_method: "Wczytaj oryginalny kod dla tej metody" # Title text for individual method reload button.
tome_select_method: "Wybierz metode"
tome_see_all_methods: "Zobacz wszystkie metody możliwe do edycji" # Title text for method list selector (shown when there are multiple programmable methods).
tome_select_a_thang: "Wybierz kogoś do "
tome_available_spells: "Dostępne czary"
tome_your_skills: "Twoje umiejętności"
tome_current_method: "Obecna Metoda"
hud_continue_short: "Kontynuuj"
code_saved: "Kod zapisano"
skip_tutorial: "Pomiń (esc)"
keyboard_shortcuts: "Skróty klawiszowe"
loading_ready: "Gotowy!"
loading_start: "Rozpocznij poziom"
problem_alert_title: "Popraw swój kod"
time_current: "Teraz:"
time_total: "Maksymalnie:"
time_goto: "Idź do:"
non_user_code_problem_title: "Błąd podczas ładowania poziomu"
infinite_loop_title: "Wykryto niekończącą się pętlę"
infinite_loop_description: "Kod źródłowy, który miał stworzył ten świat nigdy nie przestał działać. Albo działa bardzo wolno, albo ma w sobie niekończącą sie pętlę. Albo też gdzieś jest błąd systemu. Możesz spróbować uruchomić go jeszcze raz, albo przywrócić domyślny kod. Jeśli nic nie pomoże daj nam o tym znać."
check_dev_console: "Możesz też otworzyć konsolę deweloperska i sprawdzić w czym tkwi problem."
check_dev_console_link: "(instrukcje)"
infinite_loop_try_again: "Próbuj ponownie"
infinite_loop_reset_level: "Resetuj poziom"
infinite_loop_comment_out: "Comment Out My Code"
tip_toggle_play: "Włącz/zatrzymaj grę naciskając Ctrl+P."
tip_scrub_shortcut: "Ctrl+[ i Ctrl+] przesuwają czas." # {change}
tip_guide_exists: "Klikając Przewodnik u góry strony uzyskasz przydatne informacje."
tip_open_source: "CodeCombat ma w 100% otwarty kod!"
tip_tell_friends: "Podoba ci się CodeCombat? Opowiedz o nas swoim znajomym!"
tip_beta_launch: "CodeCombat uruchomił fazę beta w październiku 2013."
tip_think_solution: "Myśl nad rozwiązaniem, nie problemem."
tip_theory_practice: "W teorii nie ma różnicy między teorią a praktyką. W praktyce jednak, jest. - <NAME>"
tip_error_free: "Są dwa sposoby by napisać program bez błędów. Tylko trzeci działa. - <NAME>"
tip_debugging_program: "Jeżeli debugowanie jest procesem usuwania błędów, to programowanie musi być procesem umieszczania ich. - <NAME>"
tip_forums: "Udaj się na forum i powiedz nam co myślisz!"
tip_baby_coders: "W przyszłości, każde dziecko będzie Arcymagiem."
tip_morale_improves: "Ładowanie będzie kontynuowane gdy wzrośnie morale."
tip_all_species: "Wierzymy w równe szanse nauki programowania dla wszystkich gatunków."
tip_reticulating: "Siatkowanie kolców."
tip_harry: "Jesteś czarodziejem "
tip_great_responsibility: "Z wielką mocą programowania wiąże się wielka odpowiedzialność debugowania."
tip_munchkin: "Jeśli nie będziesz jadł warzyw, Munchkin przyjdzie po Ciebie w nocy."
tip_binary: "Jest tylko 10 typów ludzi na świecie: Ci którzy rozumieją kod binarny i ci którzy nie."
tip_commitment_yoda: "Programista musi najgłębsze zaangażowanie okazać. Umysł najpoważniejszy. ~ Yoda"
tip_no_try: "Rób. Lub nie rób. Nie ma próbowania. - Yoda"
tip_patience: "Cierpliwość musisz mieć, młody Padawanie. - Yoda"
tip_documented_bug: "Udokumentowany błąd nie jest błędem. Jest funkcją."
tip_impossible: "To zawsze wygląda na niemożliwe zanim zostanie zrobione. - <NAME>"
tip_talk_is_cheap: "Gadać jest łatwo. Pokażcie mi kod. - <NAME>"
tip_first_language: "Najbardziej zgubną rzeczą jakiej możesz się nauczyć jest twój pierwszy język programowania. - <NAME>"
tip_hardware_problem: "P: Ilu programistów potrzeba by wymienić żarówkę? O: Żadnego,to problem sprzętowy."
tip_hofstadters_law: "P<NAME>: Każdy projekt zabiera więcej czasu, niż planujesz, nawet jeśli przy planowaniu uwzględnisz prawo Hofstadtera."
# tip_premature_optimization: "Premature optimization is the root of all evil. - <NAME>"
# tip_brute_force: "When in doubt, use brute force. - <NAME>"
# tip_extrapolation: "There are only two kinds of people: those that can extrapolate from incomplete data..."
# tip_superpower: "Coding is the closest thing we have to a superpower."
# tip_control_destiny: "In real open source, you have the right to control your own destiny. - <NAME>"
# tip_no_code: "No code is faster than no code."
# tip_code_never_lies: "Code never lies, comments sometimes do. — <NAME>"
# tip_reusable_software: "Before software can be reusable it first has to be usable."
tip_optimization_operator: "Każdy język programowania ma operator optymalizujący. W większości z nich tym operatorem jest ‘//’"
# tip_lines_of_code: "Measuring programming progress by lines of code is like measuring aircraft building progress by weight. — <NAME>"
# tip_source_code: "I want to change the world but they would not give me the source code."
# tip_javascript_java: "Java is to JavaScript what Car is to Carpet. - <NAME>"
# tip_move_forward: "Whatever you do, keep moving forward. - <NAME>r."
# tip_google: "Have a problem you can't solve? Google it!"
# tip_adding_evil: "Adding a pinch of evil."
# tip_hate_computers: "That's the thing about people who think they hate computers. What they really hate is lousy programmers. - <NAME>"
# tip_open_source_contribute: "You can help CodeCombat improve!"
# tip_recurse: "To iterate is human, to recurse divine. - <NAME>"
# tip_free_your_mind: "You have to let it all go, Neo. Fear, doubt, and disbelief. Free your mind. - Morpheus"
# tip_strong_opponents: "Even the strongest of opponents always has a weakness. - <NAME>"
# tip_paper_and_pen: "Before you start coding, you can always plan with a sheet of paper and a pen."
# tip_solve_then_write: "First, solve the problem. Then, write the code. - <NAME>"
game_menu:
inventory_tab: "Ekwipunek"
save_load_tab: "Zapisz/Wczytaj"
options_tab: "Opcje"
guide_tab: "Przewodnik"
guide_video_tutorial: "Wideo poradnik"
guide_tips: "Wskazówki"
multiplayer_tab: "Multiplayer"
auth_tab: "Zarejestruj się"
inventory_caption: "Wyposaż swojego bohatera"
choose_hero_caption: "Wybierz bohatera, język"
save_load_caption: "... i przejrzyj historię"
options_caption: "Ustaw opcje"
guide_caption: "Dokumenty i wskazówki"
multiplayer_caption: "Graj ze znajomymi!"
auth_caption: "Zapisz swój postęp."
leaderboard:
leaderboard: "Najlepsze wyniki"
view_other_solutions: "Pokaż tablicę wyników"
scores: "Wyniki"
top_players: "Najlepsi gracze"
day: "Dziś"
week: "W tym tygodniu"
all: "Zawsze"
time: "Czas"
damage_taken: "Obrażenia otrzymane"
damage_dealt: "Obrażenia zadane"
difficulty: "Trudność"
gold_collected: "Złoto zebrane"
inventory:
choose_inventory: "Załóż przedmioty"
equipped_item: "Założone"
required_purchase_title: "Wymagane"
available_item: "Dostępne"
restricted_title: "Zabronione"
should_equip: "(kliknij podwójnie, aby założyć)"
equipped: "(założone)"
locked: "(zablokowane)"
restricted: "(zabronione)"
equip: "Załóż"
unequip: "Zdejmij"
buy_gems:
few_gems: "Kilka klejnotów"
pile_gems: "Stos klejnotów"
chest_gems: "Skrzynia z klejnotami"
purchasing: "Kupowanie..."
declined: "Karta została odrzucona"
retrying: "Błąd serwera, ponawiam."
prompt_title: "Za mało klejnotów"
prompt_body: "Chcesz zdobyć więcej?"
prompt_button: "Wejdź do sklepu"
recovered: "Przywrócono poprzednie zakupy. Prosze odświeżyć stronę."
price: "x3500 / mieś."
subscribe:
comparison_blurb: "Popraw swoje umiejętności z subskrypcją CodeCombat!"
feature1: "Ponad 100 poziomów w 4 różnych śwoatach" # {change}
feature2: "10 potężnych, <strong>nowych bohaterów</strong> z unikalnymi umiejętnościami!" # {change}
feature3: "Ponad 70 bonusowych poziomów" # {change}
feature4: "Dodatkowe <strong>3500 klejnotów</strong> co miesiąc!"
feature5: "Poradniki wideo"
feature6: "Priorytetowe wsparcie przez e-mail"
feature7: "Prywatne <strong>Klany</strong>"
free: "Darmowo"
month: "miesięcznie"
# must_be_logged: "You must be logged in first. Please create an account or log in from the menu above."
subscribe_title: "Zapisz się"
unsubscribe: "Wypisz się"
confirm_unsubscribe: "Potwierdź wypisanie się"
never_mind: "Nie ważne, i tak cię kocham"
thank_you_months_prefix: ""
thank_you_months_suffix: " - przez tyle miesięcy nas wspierałeś. Dziękujemy!"
thank_you: "Dziękujemy za wsparcie CodeCombat."
# sorry_to_see_you_go: "Sorry to see you go! Please let us know what we could have done better."
# unsubscribe_feedback_placeholder: "O, what have we done?"
# parent_button: "Ask your parent"
# parent_email_description: "We'll email them so they can buy you a CodeCombat subscription."
# parent_email_input_invalid: "Email address invalid."
# parent_email_input_label: "Parent email address"
# parent_email_input_placeholder: "Enter parent email"
# parent_email_send: "Send Email"
# parent_email_sent: "Email sent!"
# parent_email_title: "What's your parent's email?"
# parents: "For Parents"
# parents_title: "Dear Parent: Your child is learning to code. Will you help them continue?"
# parents_blurb1: "Your child has played __nLevels__ levels and learned programming basics. Help cultivate their interest and buy them a subscription so they can keep playing."
# parents_blurb1a: "Computer programming is an essential skill that your child will undoubtedly use as an adult. By 2020, basic software skills will be needed by 77% of jobs, and software engineers are in high demand across the world. Did you know that Computer Science is the highest-paid university degree?"
# parents_blurb2: "For $9.99 USD/mo, your child will get new challenges every week and personal email support from professional programmers."
# parents_blurb3: "No Risk: 100% money back guarantee, easy 1-click unsubscribe."
# payment_methods: "Payment Methods"
# payment_methods_title: "Accepted Payment Methods"
# payment_methods_blurb1: "We currently accept credit cards and Alipay."
# payment_methods_blurb2: "If you require an alternate form of payment, please contact"
# sale_already_subscribed: "You're already subscribed!"
# sale_blurb1: "Save 35%"
# sale_blurb2: "off regular subscription price of $120 for a whole year!"
# sale_button: "Sale!"
# sale_button_title: "Save 35% when you purchase a 1 year subscription"
# sale_click_here: "Click Here"
# sale_ends: "Ends"
# sale_extended: "*Existing subscriptions will be extended by 1 year."
# sale_feature_here: "Here's what you'll get:"
# sale_feature2: "Access to 9 powerful <strong>new heroes</strong> with unique skills!"
# sale_feature4: "<strong>42,000 bonus gems</strong> awarded immediately!"
# sale_continue: "Ready to continue adventuring?"
# sale_limited_time: "Limited time offer!"
# sale_new_heroes: "New heroes!"
# sale_title: "Back to School Sale"
# sale_view_button: "Buy 1 year subscription for"
# stripe_description: "Monthly Subscription"
# stripe_description_year_sale: "1 Year Subscription (35% discount)"
# subscription_required_to_play: "You'll need a subscription to play this level."
# unlock_help_videos: "Subscribe to unlock all video tutorials."
# personal_sub: "Personal Subscription" # Accounts Subscription View below
# loading_info: "Loading subscription information..."
# managed_by: "Managed by"
# will_be_cancelled: "Will be cancelled on"
# currently_free: "You currently have a free subscription"
# currently_free_until: "You currently have a subscription until"
# was_free_until: "You had a free subscription until"
# managed_subs: "Managed Subscriptions"
# managed_subs_desc: "Add subscriptions for other players (students, children, etc.)"
# managed_subs_desc_2: "Recipients must have a CodeCombat account associated with the email address you provide."
# group_discounts: "Group discounts"
# group_discounts_1: "We also offer group discounts for bulk subscriptions."
# group_discounts_1st: "1st subscription"
# group_discounts_full: "Full price"
# group_discounts_2nd: "Subscriptions 2-11"
# group_discounts_20: "20% off"
# group_discounts_12th: "Subscriptions 12+"
# group_discounts_40: "40% off"
# subscribing: "Subscribing..."
# recipient_emails_placeholder: "Enter email address to subscribe, one per line."
# subscribe_users: "Subscribe Users"
# users_subscribed: "Users subscribed:"
# no_users_subscribed: "No users subscribed, please double check your email addresses."
# current_recipients: "Current Recipients"
# unsubscribing: "Unsubscribing"
# subscribe_prepaid: "Click Subscribe to use prepaid code"
# using_prepaid: "Using prepaid code for monthly subscription"
choose_hero:
choose_hero: "Wybierz swojego bohatera"
programming_language: "Język programowania"
programming_language_description: "Którego języka programowania chcesz używać?"
default: "domyślny"
experimental: "Eksperymentalny"
python_blurb: "Prosty ale potężny."
javascript_blurb: "Język internetu."
coffeescript_blurb: "Przyjemniejsza składnia JavaScript."
clojure_blurb: "Nowoczesny Lisp."
lua_blurb: "Język skryptowy gier."
io_blurb: "Prosty lecz nieznany."
status: "Status"
hero_type: "Typ"
weapons: "Bronie"
weapons_warrior: "Miecze - Krótki zasięg, Brak magii"
weapons_ranger: "Kusze, Pistolety - Daleki zasięg, Brak magii"
weapons_wizard: "Różdżki, Laski - Daleki zasięg, Magia"
attack: "Obrażenia" # Can also translate as "Attack"
health: "Życie"
speed: "Szybkość"
regeneration: "Regenaracja"
range: "Zasięg" # As in "attack or visual range"
blocks: "Blok" # As in "this shield blocks this much damage"
backstab: "Cios" # As in "this dagger does this much backstab damage"
skills: "Umiejętności"
attack_1: "Zadaje"
# attack_2: "of listed"
attack_3: "obrażeń od broni."
health_1: "Zdobywa"
# health_2: "of listed"
health_3: "wytrzymałości pancerza."
speed_1: "Idzie do"
speed_2: "metrów na sekundę."
available_for_purchase: "Można wynająć" # Shows up when you have unlocked, but not purchased, a hero in the hero store
level_to_unlock: "Musisz odblokować poziom:" # 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: "Tylko nieliczni bohaterowie mogą brać udział w tym poziomie."
skill_docs:
writable: "zapisywalny" # Hover over "attack" in Your Skills while playing a level to see most of this
read_only: "tylko do odczytu"
# action: "Action"
# spell: "Spell"
action_name: "nazwa"
action_cooldown: "Zajmuje"
action_specific_cooldown: "Odpoczynek"
action_damage: "Obrażenia"
action_range: "Zasięg"
action_radius: "Promień"
action_duration: "Czas trwania"
example: "Przykład"
ex: "np." # Abbreviation of "example"
current_value: "Aktualna wartość"
default_value: "Domyślna wartość"
parameters: "Parametry"
returns: "Zwraca"
granted_by: "Zdobyte dzięki:"
save_load:
granularity_saved_games: "Zapisano"
granularity_change_history: "Historia"
options:
general_options: "Opcje ogólne" # Check out the Options tab in the Game Menu while playing a level
volume_label: "Głośność"
music_label: "Muzyka"
music_description: "Wł/Wył muzykę w tle."
editor_config_title: "Konfiguracja edytora"
editor_config_keybindings_label: "Przypisania klawiszy"
editor_config_keybindings_default: "Domyślny (Ace)"
editor_config_keybindings_description: "Dodaje skróty znane z popularnych edytorów."
editor_config_livecompletion_label: "Podpowiedzi na żywo"
editor_config_livecompletion_description: "Wyświetl sugestie autouzupełnienia podczas pisania."
editor_config_invisibles_label: "Pokaż białe znaki"
editor_config_invisibles_description: "Wyświetla białe znaki takie jak spacja czy tabulator."
editor_config_indentguides_label: "Pokaż linijki wcięć"
editor_config_indentguides_description: "Wyświetla pionowe linie, by lepiej zaznaczyć wcięcia."
editor_config_behaviors_label: "Inteligentne zachowania"
editor_config_behaviors_description: "Autouzupełnianie nawiasów, klamer i cudzysłowów."
about:
why_codecombat: "Dlaczego CodeCombat?"
why_paragraph_1: "Chcesz nauczyć się programowania? Nie potrzeba ci lekcji. Potrzeba ci pisania dużej ilości kodu w sposób sprawiający ci przyjemność."
why_paragraph_2_prefix: "O to chodzi w programowaniu - musi sprawiać radość. Nie radość w stylu"
why_paragraph_2_italic: "hura, nowa odznaka"
why_paragraph_2_center: ", ale radości w stylu"
why_paragraph_2_italic_caps: "NIE MAMO, MUSZĘ DOKOŃCZYĆ TEN POZIOM!"
why_paragraph_2_suffix: "Dlatego właśnie CodeCombat to gra multiplayer, a nie kurs oparty na zgamifikowanych lekcjach. Nie przestaniemy, dopóki ty nie będziesz mógł przestać--tym razem jednak w pozytywnym sensie."
why_paragraph_3: "Jeśli planujesz uzależnić się od jakiejś gry, uzależnij się od tej i zostań jednym z czarodziejów czasu technologii."
press_title: "Blogerzy/Prasa"
press_paragraph_1_prefix: "Chcesz o nas napisać? Śmiało możesz pobrać iu wykorzystać wszystkie informację dostępne w naszym"
press_paragraph_1_link: "pakiecie prasowym "
press_paragraph_1_suffix: ". Wszystkie loga i obrazki mogą zostać wykorzystane bez naszej wiedzy."
team: "Zespół"
george_title: "Współzałożyciel"
george_blurb: "Pan Prezes"
scott_title: "Współzałożyciel"
scott_blurb: "<NAME>"
nick_title: "<NAME>"
nick_blurb: "Guru Motywacji"
michael_title: "Programista"
michael_blurb: "Sys Admin"
matt_title: "Programista"
matt_blurb: "Rowerzysta"
cat_title: "Główny Rzemieślnik"
cat_blurb: "Airbender"
josh_title: "Projektant Gier"
josh_blurb: "Podłoga to lawa"
jose_title: "Muzyka"
jose_blurb: "Odnosi Sukces"
retrostyle_title: "Ilustracje"
retrostyle_blurb: "RetroStyle Games"
teachers:
more_info: "Informacja dla nauczycieli"
# intro_1: "CodeCombat is an online game that teaches programming. Students write code in real programming languages."
# intro_2: "No experience required!"
# free_title: "How much does it cost?"
# cost_premium_server: "CodeCombat is free for the first five levels, after which it costs $9.99 USD per month for access to our other 190+ levels on our exclusive country-specific servers."
# free_1: "There are 110+ FREE levels which cover every concept."
# free_2: "A monthly subscription provides access to video tutorials and extra practice levels."
# teacher_subs_title: "Teachers get free subscriptions!"
# teacher_subs_0: "We offer free subscriptions to teachers for evaluation purposes."
# teacher_subs_1: "Please fill out our"
# teacher_subs_2: "Teacher Survey"
# teacher_subs_3: "to set up your subscription."
# sub_includes_title: "What is included in the subscription?"
# sub_includes_1: "In addition to the 110+ basic levels, students with a monthly subscription get access to these additional features:"
# sub_includes_2: "80+ practice levels"
# sub_includes_3: "Video tutorials"
# sub_includes_4: "Premium email support"
# sub_includes_5: "10 new heroes with unique skills to master"
# sub_includes_6: "3500 bonus gems every month"
# sub_includes_7: "Private Clans"
# monitor_progress_title: "How do I monitor student progress?"
# monitor_progress_1: "Student progress can be monitored by creating a"
# monitor_progress_2: "for your class."
# monitor_progress_3: "To add a student, send them the invite link for your Clan, which is on the"
# monitor_progress_4: "page."
# monitor_progress_5: "After they join, you will see a summary of the student's progress on your Clan's page."
# private_clans_1: "Private Clans provide increased privacy and detailed progress information for each student."
# private_clans_2: "To create a private Clan, check the 'Make clan private' checkbox when creating a"
# private_clans_3: "."
# who_for_title: "Who is CodeCombat for?"
# who_for_1: "We recommend CodeCombat for students aged 9 and up. No prior programming experience is needed."
# who_for_2: "We've designed CodeCombat to appeal to both boys and girls."
# material_title: "How much material is there?"
# material_premium_server: "Approximately 50 hours of gameplay spread over 190+ subscriber-only levels so far."
# material_1: "Approximately 25 hours of free content and an additional 15 hours of subscriber content."
# concepts_title: "What concepts are covered?"
# how_much_title: "How much does a monthly subscription cost?"
# how_much_1: "A"
# how_much_2: "monthly subscription"
# how_much_3: "costs $9.99, and can be cancelled anytime."
# how_much_4: "Additionally, we provide discounts for larger groups:"
# how_much_5: "We accept discounted one-time purchases and yearly subscription purchases for groups, such as a class or school. Please contact"
# how_much_6: "for more details."
# more_info_title: "Where can I find more information?"
# more_info_1: "Our"
# more_info_2: "teachers forum"
# more_info_3: "is a good place to connect with fellow educators who are using CodeCombat."
# sys_requirements_title: "System Requirements"
# sys_requirements_1: "A modern web browser. Newer versions of Chrome, Firefox, or Safari. Internet Explorer 9 or later."
# sys_requirements_2: "CodeCombat is not supported on iPad yet."
teachers_survey:
title: "Ankieta dla nauczycieli"
# must_be_logged: "You must be logged in first. Please create an account or log in from the menu above."
# retrieving: "Retrieving information..."
# being_reviewed_1: "Your application for a free trial subscription is being"
# being_reviewed_2: "reviewed."
# approved_1: "Your application for a free trial subscription was"
# approved_2: "approved."
# approved_3: "Further instructions have been sent to"
# denied_1: "Your application for a free trial subscription has been"
# denied_2: "denied."
# contact_1: "Please contact"
# contact_2: "if you have further questions."
# description_1: "We offer free subscriptions to teachers for evaluation purposes. You can find more information on our"
# description_2: "teachers"
# description_3: "page."
# description_4: "Please fill out this quick survey and we’ll email you setup instructions."
# email: "Email Address"
# school: "Name of School"
# location: "Name of City"
# age_students: "How old are your students?"
# under: "Under"
# other: "Other:"
# amount_students: "How many students do you teach?"
# hear_about: "How did you hear about CodeCombat?"
# fill_fields: "Please fill out all fields."
# thanks: "Thanks! We'll send you setup instructions shortly."
versions:
save_version_title: "Zapisz nową wersję"
new_major_version: "Nowa wersja główna"
submitting_patch: "Przesyłanie łatki..."
cla_prefix: "Aby zapisać zmiany, musisz najpierw zaakceptować naszą"
cla_url: "umowę licencyjną dla współtwórców (CLA)"
cla_suffix: "."
cla_agree: "AKCEPTUJĘ"
owner_approve: "Przed pojawieniem się zmian, właściciel musi je zatwierdzić."
contact:
contact_us: "Kontakt z CodeCombat"
welcome: "Miło Cię widzieć! Użyj tego formularza, żeby wysłać do nas wiadomość. "
forum_prefix: "W sprawach ogólnych, skorzystaj z "
forum_page: "naszego forum"
forum_suffix: "."
faq_prefix: "Jest też"
faq: "FAQ"
subscribe_prefix: "Jeśli masz jakiś problem z rozwiązaniem poziomu,"
subscribe: "wykup subskrypcję CodeCombat,"
subscribe_suffix: "a my z radością ci pomożemy."
subscriber_support: "Jako, że będziesz subskrybentem CodeCombat, twoje e-maile będą miały najwyższy priorytet."
screenshot_included: "Dołączymy zrzuty ekranu."
where_reply: "Gdzie mamy odpisać?"
send: "Wyślij wiadomość"
contact_candidate: "Kontakt z kandydatem" # Deprecated
# recruitment_reminder: "Use this form to reach out to candidates you are interested in interviewing. Remember that CodeCombat charges 15% of first-year salary. The fee is due upon hiring the employee and is refundable for 90 days if the employee does not remain employed. Part time, remote, and contract employees are free, as are interns." # Deprecated
account_settings:
title: "Ustawienia Konta"
not_logged_in: "Zaloguj się lub stwórz konto, by dostosować ustawienia."
autosave: "Zmiany zapisują się automatycznie"
me_tab: "Ja"
picture_tab: "Zdjęcie"
delete_account_tab: "Usuń swoje konto"
wrong_email: "Błędny e-mail"
wrong_password: "<PASSWORD>"
upload_picture: "Wgraj zdjęcie"
delete_this_account: "Usuń to konto całkowicie"
god_mode: "TRYB BOGA"
password_tab: "Hasło"
emails_tab: "Powiadomienia"
admin: "Administrator"
new_password: "<PASSWORD>"
new_password_verify: "<PASSWORD>"
type_in_email: "Wpisz swój email, aby potwierdzić usunięcie konta."
type_in_password: "<PASSWORD> hasło."
email_subscriptions: "Powiadomienia email"
email_subscriptions_none: "Brak powiadomień e-mail."
email_announcements: "Ogłoszenia"
email_announcements_description: "Otrzymuj powiadomienia o najnowszych wiadomościach i zmianach w CodeCombat."
email_notifications: "Powiadomienia"
email_notifications_summary: "Ustawienia spersonalizowanych, automatycznych powiadomień mailowych zależnych od twojej aktywności w CodeCombat."
email_any_notes: "Wszystkie powiadomienia"
email_any_notes_description: "Odznacz by wyłączyć wszystkie powiadomienia email."
email_news: "Nowości"
email_recruit_notes: "Możliwości zatrudnienia"
email_recruit_notes_description: "Jeżeli grasz naprawdę dobrze, możemy się z tobą skontaktować by zaoferować (lepszą) pracę."
contributor_emails: "Powiadomienia asystentów"
contribute_prefix: "Szukamy osób, które chciałyby do nas dołączyć! Sprawdź "
contribute_page: "stronę współpracy"
contribute_suffix: ", aby dowiedzieć się więcej."
email_toggle: "Zmień wszystkie"
error_saving: "Błąd zapisywania"
saved: "Zmiany zapisane"
password_mismatch: "<PASSWORD>"
password_repeat: "<PASSWORD>."
job_profile: "Profil zatrudnienia" # Rest of this section (the job profile stuff and wizard stuff) is deprecated
job_profile_approved: "Twój profil zatrudnienia został zaakceptowany przez CodeCombat. Pracodawcy będą mogli go widzieć dopóki nie oznaczysz go jako nieaktywny lub nie będzie on zmieniany przez 4 tygodnie."
job_profile_explanation: "Witaj! Wypełnij to, a będziemy w kontakcie w sprawie znalezienie dla Ciebe pracy twórcy oprogramowania."
sample_profile: "Zobacz przykładowy profil"
view_profile: "Zobacz swój profil"
keyboard_shortcuts:
keyboard_shortcuts: "Skróty klawiszowe"
space: "Spacja"
enter: "Enter"
press_enter: "naciśnij enter"
escape: "Escape"
shift: "Shift"
run_code: "Uruchom obecny kod."
run_real_time: "Uruchom \"na żywo\"."
continue_script: "Kontynuuj ostatni skrypt."
skip_scripts: "Pomiń wszystkie pomijalne skrypty."
toggle_playback: "Graj/pauzuj."
# scrub_playback: "Scrub back and forward through time."
# single_scrub_playback: "Scrub back and forward through time by a single frame."
# scrub_execution: "Scrub through current spell execution."
# toggle_debug: "Toggle debug display."
# toggle_grid: "Toggle grid overlay."
# toggle_pathfinding: "Toggle pathfinding overlay."
# beautify: "Beautify your code by standardizing its formatting."
maximize_editor: "Maksymalizuj/minimalizuj edytor kodu."
community:
main_title: "Społeczność CodeCombat"
# introduction: "Check out the ways you can get involved below and decide what sounds the most fun. We look forward to working with you!"
# level_editor_prefix: "Use the CodeCombat"
# level_editor_suffix: "to create and edit levels. Users have created levels for their classes, friends, hackathons, students, and siblings. If create a new level sounds intimidating you can start by forking one of ours!"
# thang_editor_prefix: "We call units within the game 'thangs'. Use the"
# thang_editor_suffix: "to modify the CodeCombat source artwork. Allow units to throw projectiles, alter the direction of an animation, change a unit's hit points, or upload your own vector sprites."
# article_editor_prefix: "See a mistake in some of our docs? Want to make some instructions for your own creations? Check out the"
# article_editor_suffix: "and help CodeCombat players get the most out of their playtime."
find_us: "Znajdź nas na tych stronach"
social_github: "Przejrzyj cały nasz kod na platformie GitHub"
social_blog: "Przeczytaj blog CodeCombat na Sett"
social_discource: "Dołącz do dyskusji na naszym forum"
social_facebook: "Polub CodeCombat na Facebooku"
social_twitter: "Obserwuj CodeCombat na Twitterze"
social_gplus: "Dołącz do CodeCombat na Google+"
social_hipchat: "Pogadaj z nami na pblicznym czacie HipChat"
contribute_to_the_project: "Zostań współtwórcą CodeCombat"
clans:
clan: "Klan"
clans: "Klany"
new_name: "<NAME> nowego klanu"
new_description: "Opis nowego klanu"
make_private: "Stwórz prywatny klan"
subs_only: "tylko subskrybenci"
create_clan: "Stwórz nowy klan"
private_preview: "Podgląd"
public_clans: "Publiczne klany"
my_clans: "Moje klany"
clan_name: "<NAME>"
name: "<NAME>"
chieftain: "Dowódca"
type: "Typ"
edit_clan_name: "Edytuj nazwe klanu"
edit_clan_description: "Edytuj opis klanu"
edit_name: "edytuj nazwe"
edit_description: "edytuj opis"
private: "(prywatny)"
summary: "Podsumowanie"
average_level: "Średni poziom"
average_achievements: "Średnio osiągnięć"
delete_clan: "Usuń klan"
leave_clan: "Opuść klan"
join_clan: "Dołacz do klanu"
invite_1: "Zaproszenie:"
invite_2: "*Zaproś nowe osoby do klanu wysyłając im ten link."
members: "Cz<NAME>"
progress: "Postęp"
not_started_1: "nierozpoczęty"
started_1: "rozpoczęty"
complete_1: "ukończony"
exp_levels: "Rozwiń poziomy"
rem_hero: "Usuń bohatera"
status: "Status"
complete_2: "Ukończony"
started_2: "Rozpoczęto"
not_started_2: "Nie rozpoczęto"
view_solution: "Kliknij, aby obejrzeć rozwiązanie."
latest_achievement: "Ostatnie osiągnięcia"
playtime: "Czas gyr"
last_played: "Ostatnio grany"
# leagues_explanation: "Play in a league against other clan members in these multiplayer arena instances."
# track_concepts1: "Track concepts"
# track_concepts2a: "learned by each student"
# track_concepts2b: "learned by each member"
# track_concepts3a: "Track levels completed for each student"
# track_concepts3b: "Track levels completed for each member"
# track_concepts4a: "See your students'"
# track_concepts4b: "See your members'"
# track_concepts5: "solutions"
# track_concepts6a: "Sort students by name or progress"
# track_concepts6b: "Sort members by name or progress"
# track_concepts7: "Requires invitation"
# track_concepts8: "to join"
# private_require_sub: "Private clans require a subscription to create or join."
# courses:
# course: "Course"
# courses: "courses"
# not_enrolled: "You are not enrolled in this course."
# visit_pref: "Please visit the"
# visit_suf: "page to enroll."
# select_class: "Select one of your classes"
# unnamed: "*unnamed*"
# select: "Select"
# unnamed_class: "Unnamed Class"
# edit_settings: "edit class settings"
# edit_settings1: "Edit Class Settings"
# progress: "Class Progress"
# add_students: "Add Students"
# stats: "Statistics"
# total_students: "Total students:"
# average_time: "Average level play time:"
# total_time: "Total play time:"
# average_levels: "Average levels completed:"
# total_levels: "Total levels completed:"
# furthest_level: "Furthest level completed:"
# concepts_covered: "Concepts Covered"
# students: "Students"
# students1: "students"
# expand_details: "Expand details"
# concepts: "Concepts"
# levels: "levels"
# played: "Played"
# play_time: "Play time:"
# completed: "Completed:"
# invite_students: "Invite students to join this class."
# invite_link_header: "Link to join course"
# invite_link_p_1: "Give this link to students you would like to have join the course."
# invite_link_p_2: "Or have us email them directly:"
# capacity_used: "Course slots used:"
# enter_emails: "Enter student emails to invite, one per line"
# send_invites: "Send Invites"
# title: "Title"
# description: "Description"
# languages_available: "Select programming languages available to the class:"
# all_lang: "All Languages"
# show_progress: "Show student progress to everyone in the class"
# creating_class: "Creating class..."
# purchasing_course: "Purchasing course..."
# buy_course: "Buy Course"
# buy_course1: "Buy this course"
# create_class: "Create Class"
# select_all_courses: "Select 'All Courses' for a 50% discount!"
# all_courses: "All Courses"
# number_students: "Number of students"
# enter_number_students: "Enter the number of students you need for this class."
# name_class: "Name your class"
# displayed_course_page: "This will be displayed on the course page for you and your students. It can be changed later."
# buy: "Buy"
# purchasing_for: "You are purchasing a license for"
# creating_for: "You are creating a class for"
# for: "for" # Like in 'for 30 students'
# receive_code: "Afterwards you will receive an unlock code to distribute to your students, which they can use to enroll in your class."
# free_trial: "Free trial for teachers!"
# get_access: "to get individual access to all courses for evalutaion purposes."
# questions: "Questions?"
# faq: "Courses FAQ"
# question: "Q:" # Like in 'Question'
# question1: "What's the difference between these courses and the single player game?"
# answer: "A:" # Like in 'Answer'
# answer1: "The single player game is designed for individuals, while the courses are designed for classes."
# answer2: "The single player game has items, gems, hero selection, leveling up, and in-app purchases. Courses have classroom management features and streamlined student-focused level pacing."
# teachers_click: "Teachers Click Here"
# students_click: "Students Click Here"
# courses_on_coco: "Courses on CodeCombat"
# designed_to: "Courses are designed to introduce computer science concepts using CodeCombat's fun and engaging environment. CodeCombat levels are organized around key topics to encourage progressive learning, over the course of 5 hours."
# more_in_less: "Learn more in less time"
# no_experience: "No coding experience necesssary"
# easy_monitor: "Easily monitor student progress"
# purchase_for_class: "Purchase a course for your entire class. It's easy to sign up your students!"
# see_the: "See the"
# more_info: "for more information."
# choose_course: "Choose Your Course:"
# enter_code: "Enter an unlock code to join an existing class"
# enter_code1: "Enter unlock code"
# enroll: "Enroll"
# pick_from_classes: "Pick from your current classes"
# enter: "Enter"
# or: "Or"
# topics: "Topics"
# hours_content: "Hours of content:"
# get_free: "Get FREE course"
classes:
archmage_title: "Arcymag"
archmage_title_description: "(programista)"
archmage_summary: "Jesteś programistą zainteresowanym tworzeniem gier edukacyjnych? Zostań Arcymagiem i pomóż nam ulepszyć CodeCombat!"
artisan_title: "Rzemieślnik"
artisan_title_description: "(twórca poziomów)"
artisan_summary: "Buduj i dziel się poziomami z przyjaciółmi i innymi graczami. Zostań R<NAME>ieślnikiem, który pomaga w uczeniu innych sztuki programowania."
adventurer_title: "Pod<NAME>"
adventurer_title_description: "(playtester)"
adventurer_summary: "Zagraj w nasze nowe poziomy (nawet te dla subskrybentów) za darmo przez ich wydaniem i pomóż nam znaleźć w nich błędy zanim zostaną opublikowane."
scribe_title: "<NAME>"
scribe_title_description: "(twórca artykułów)"
scribe_summary: "Dobry kod wymaga dobrej dokumentacji. Pisz, edytuj i ulepszaj dokumentację czytana przez miliony graczy na całym świecie."
diplomat_title: "Dyplomata"
diplomat_title_description: "(tłumacz)"
diplomat_summary: "CodeCombat jest tłumaczone na ponad 45 języków. Dołącz do naszch Dyplomatów i pomóż im w dalszych pracach."
ambassador_title: "Ambasador"
ambassador_title_description: "(wsparcie)"
ambassador_summary: "Okiełznaj naszych użytkowników na forum, udzielaj odpowiedzi na pytania i wspieraj ich. Nasi Ambasadorzy reprezentują CodeCombat przed całym światem."
editor:
main_title: "Edytory CodeCombat"
article_title: "Edytor artykułów"
thang_title: "Edytor obiektów"
level_title: "Edytor poziomów"
achievement_title: "Edytor osiągnięć"
poll_title: "Edytor ankiet"
back: "Wstecz"
revert: "Przywróć"
revert_models: "Przywróć wersję"
pick_a_terrain: "Wybierz teren"
dungeon: "Loch"
indoor: "Wnętrze"
desert: "Pustynia"
grassy: "Trawa"
mountain: "Góry"
glacier: "Lodowiec"
small: "Mały"
large: "Duży"
fork_title: "Forkuj nowa wersję"
fork_creating: "Tworzenie Forka..."
generate_terrain: "Generuj teren"
more: "Więcej"
wiki: "Wiki"
live_chat: "Czat na żywo"
thang_main: "Główna"
# thang_spritesheets: "Spritesheets"
thang_colors: "Kolory"
level_some_options: "Trochę opcji?"
level_tab_thangs: "Obiekty"
level_tab_scripts: "Skrypty"
level_tab_settings: "Ustawienia"
level_tab_components: "Komponenty"
level_tab_systems: "Systemy"
level_tab_docs: "Documentacja"
level_tab_thangs_title: "Aktualne obiekty"
level_tab_thangs_all: "Wszystkie"
level_tab_thangs_conditions: "Warunki początkowe"
level_tab_thangs_add: "Dodaj obiekty"
level_tab_thangs_search: "Przeszukaj obiekty"
add_components: "Dodaj komponenty"
component_configs: "Konfiguracja komponentów"
config_thang: "Kliknij dwukrotnie, aby skonfigurować obiekt"
delete: "Usuń"
duplicate: "Powiel"
stop_duplicate: "Przestań powielać"
rotate: "Obróć"
level_settings_title: "Ustawienia"
level_component_tab_title: "Aktualne komponenty"
level_component_btn_new: "Stwórz nowy komponent"
level_systems_tab_title: "Aktualne systemy"
level_systems_btn_new: "Stwórz nowy system"
level_systems_btn_add: "Dodaj system"
level_components_title: "Powrót do listy obiektów"
level_components_type: "Typ"
level_component_edit_title: "Edytuj komponent"
level_component_config_schema: "Schemat konfiguracji"
level_component_settings: "Ustawienia"
level_system_edit_title: "Edytuj system"
create_system_title: "Stwórz nowy system"
new_component_title: "Stwórz nowy komponent"
new_component_field_system: "System"
new_article_title: "Stwórz nowy artykuł"
new_thang_title: "Stwórz nowy typ obiektu"
new_level_title: "Stwórz nowy poziom"
new_article_title_login: "Zaloguj się, aby stworzyć nowy artykuł"
new_thang_title_login: "Zaloguj się, aby stworzyć nowy typ obiektu"
new_level_title_login: "Zaloguj się, aby stworzyć nowy poziom"
new_achievement_title: "Stwórz nowe osiągnięcie"
new_achievement_title_login: "Zaloguj się, aby stworzyć nowy osiągnięcie"
new_poll_title: "Stwórz nową ankietę"
new_poll_title_login: "Zaloguj się aby stworzyć nową ankietę"
article_search_title: "Przeszukaj artykuły"
thang_search_title: "Przeszukaj obiekty"
level_search_title: "Przeszukaj poziomy"
achievement_search_title: "Szukaj osiągnięcia"
poll_search_title: "Szukaj ankiety"
read_only_warning2: "Uwaga: nie możesz zapisać żadnych zmian, ponieważ nie jesteś zalogowany."
no_achievements: "Dla tego poziomu nie ma żadnych osiągnięć."
# achievement_query_misc: "Key achievement off of miscellanea"
# achievement_query_goals: "Key achievement off of level goals"
level_completion: "Ukończenie poziomu"
pop_i18n: "Uzupełnij I18N"
tasks: "Zadania"
clear_storage: "Usuń swoje lokalne zmiany"
# add_system_title: "Add Systems to Level"
done_adding: "Zakończono dodawanie"
article:
edit_btn_preview: "Podgląd"
edit_article_title: "Edytuj artykuł"
polls:
priority: "Priorytet"
contribute:
page_title: "Współpraca"
# intro_blurb: "CodeCombat is 100% open source! Hundreds of dedicated players have helped us build the game into what it is today. Join us and write the next chapter in CodeCombat's quest to teach the world to code!"
alert_account_message_intro: "Hej tam!"
alert_account_message: "Musisz się najpierw zalogować, jeśli chcesz zapisać się na klasowe e-maile."
archmage_introduction: "Jedną z najlepszych rzeczy w tworzeniu gier jest to, że syntetyzują one tak wiele różnych spraw. Grafika, dźwięk, łączność w czasie rzeczywistym, social networking i oczywiście wiele innych, bardziej popularnych, aspektów programowania, od niskopoziomowego zarządzania bazami danych i administracji serwerem do interfejsu użytkownika i jego tworzenia. Jest wiele do zrobienia i jeśli jesteś doświadczonym programistą z zacięciem, by zajrzeć do sedna CodeCombat, ta klasa może być dla ciebie. Bylibyśmy niezmiernie szczęśliwi mając twoją pomoc przy budowaniu najlepszej programistycznej gry wszech czasów."
class_attributes: "Atrybuty klasowe"
archmage_attribute_1_pref: "Znajomość "
archmage_attribute_1_suf: " lub chęć do nauki. Większość naszego kodu napisana jest w tym języku. Jeśli jesteś fanem Ruby czy Pythona, poczujesz się jak w domu. To po prostu JavaScript, tyle że z przyjemniejszą składnią."
archmage_attribute_2: "Pewne doświadczenie w programowaniu i własna inicjatywa. Pomożemy ci się połapać, ale nie możemy spędzić zbyt dużo czasu na szkoleniu cię."
how_to_join: "Jak dołączyć"
join_desc_1: "Każdy może pomóc! Zerknij po prostu na nasz "
join_desc_2: ", aby rozpocząć i zaznacz kratkę poniżej, aby określić sie jako mężny Arcymag oraz otrzymywać najświeższe wiadomości przez e-mail. Chcesz porozmawiać na temat tego, co robić lub w jaki sposób dołączyć do współpracy jeszcze wyraźniej? "
join_desc_3: " lub zajrzyj do naszego "
join_desc_4: ", a dowiesz się wszystkiego!"
join_url_email: "Napisz do nas"
join_url_hipchat: "publicznego pokoju HipChat"
archmage_subscribe_desc: "Otrzymuj e-maile dotyczące nowych okazji programistycznych oraz ogłoszeń."
artisan_introduction_pref: "Musimy stworzyć dodatkowe poziomy! Ludzie będą oczekiwać nowych zasobów, a my mamy ograniczone możliwości co do naszych mocy przerobowych. Obecnie, twoja stacja robocza jest na poziomie pierwszym; nasz edytor poziomów jest ledwo używalny nawet przez jego twórców - bądź tego świadom. Jeśli masz wizję nowych kampanii, od pętli typu for do"
artisan_introduction_suf: ", ta klasa może być dla ciebie."
artisan_attribute_1: "Jakiekolwiek doświadczenie w tworzeniu zasobów tego typu byłoby przydatne, na przykład używając edytora poziomów dostarczonego przez Blizzard. Nie jest to jednak wymagane."
artisan_attribute_2: "Zacięcie do całej masy testowania i iteracji. Aby tworzyć dobre poziomy, musisz dostarczyć je innym i obserwować jak grają oraz być przygotowanym na wprowadzanie mnóstwa poprawek."
artisan_attribute_3: "Na dzień dzisiejszy, cierpliwość wraz z naszym Podróżnikiem. Nasz <NAME> jest jest strasznie prymitywny i frustrujący w użyciu. Zostałeś ostrzeżony!"
artisan_join_desc: "Używaj Edytora Poziomów mniej-więcej zgodnie z poniższymi krokami:"
artisan_join_step1: "Przeczytaj dokumentację."
artisan_join_step2: "Stwórz nowy poziom i przejrzyj istniejące poziomy."
artisan_join_step3: "Zajrzyj do naszego publicznego pokoju HipChat, aby uzyskać pomoc."
artisan_join_step4: "Pokaż swoje poziomy na forum, aby uzyskać opinie."
artisan_subscribe_desc: "Otrzymuj e-maile dotyczące aktualności w tworzeniu poziomów i ogłoszeń."
adventurer_introduction: "Bądźmy szczerzy co do twojej roli: jesteś tankiem. Będziesz przyjmował ciężkie obrażenia. Potrzebujemy ludzi do testowania nowych poziomów i pomocy w rozpoznawaniu ulepszeń, które będzie można do nich zastosować. Będzie to bolesny proces; tworzenie dobrych gier to długi proces i nikt nie trafia w dziesiątkę za pierwszym razem. Jeśli jesteś wytrzymały i masz wysoki wskaźnik constitution (D&D), ta klasa jest dla ciebie."
adventurer_attribute_1: "<NAME>. Chcesz nauczyć się programować, a my chcemy ci to umożliwić. Prawdopodobnie w tym przypadku, to ty będziesz jednak przez wiele czasu stroną uczącą."
adventurer_attribute_2: "<NAME>. Bądź uprzejmy, ale wyraźnie określaj, co wymaga poprawy, oferując sugestie co do sposobu jej uzyskania."
adventurer_join_pref: "Zapoznaj się z Rzemieślnikiem (lub rekrutuj go!), aby wspólnie pracować lub też zaznacz kratkę poniżej, aby otrzymywać e-maile, kiedy pojawią się nowe poziomy do testowania. Będziemy również pisać o poziomach do sprawdzenia na naszych stronach w sieciach społecznościowych jak"
adventurer_forum_url: "nasze forum"
adventurer_join_suf: "więc jeśli wolałbyś być informowany w ten sposób, zarejestruj się na nich!"
adventurer_subscribe_desc: "Otrzymuj e-maile, gdy pojawią się nowe poziomy do tesotwania."
scribe_introduction_pref: "CodeCombat nie będzie tylko zbieraniną poziomów. Będzie też zawierać źródło wiedzy, wiki programistycznych idei, na której będzie można oprzeć poziomy. Dzięki temu, każdy z Rzemieślników zamiast opisywać ze szczegółami, czym jest operator porónania, będzie mógł po prostu podać graczowi w swoim poziomie link do artykułu opisującego go. Mamy na myśli coś podobnego do "
scribe_introduction_url_mozilla: "Mozilla Developer Network"
scribe_introduction_suf: ". Jeśli twoją definicją zabawy jest artykułowanie idei programistycznych przy pomocy składni Markdown, ta klasa może być dla ciebie."
scribe_attribute_1: "Umiejętne posługiwanie się słowem to właściwie wszystko, czego potrzebujesz. Nie tylko gramatyka i ortografia, ale również umiejętnośc tłumaczenia trudnego materiału innym."
contact_us_url: "Skontaktuj się z nami"
scribe_join_description: "powiedz nam coś o sobie, swoim doświadczeniu w programowaniu i rzeczach, o których chciałbyś pisać, a chętnie to z tobą uzgodnimy!"
scribe_subscribe_desc: "Otrzymuj e-maile na temat ogłoszeń dotyczących pisania artykułów."
diplomat_introduction_pref: "Jeśli dowiedzieliśmy jednej rzeczy z naszego "
diplomat_launch_url: "otwarcia w październiku"
diplomat_introduction_suf: ", to jest nią informacja o znacznym zainteresowaniu CodeCombat w innych krajach. Tworzymy zespół tłumaczy chętnych do przemieniania zestawów słów w inne zestawy słów, aby CodeCombat było tak dostępne dla całego świata, jak to tylko możliwe. Jeśli chciabyś mieć wgląd w nadchodzącą zawartość i umożliwić swoim krajanom granie w najnowsze poziomy, ta klasa może być dla ciebie."
diplomat_attribute_1: "Biegła znajomość angielskiego oraz języka, na który chciałbyś tłumaczyć. Kiedy przekazujesz skomplikowane idee, dobrze mieć płynność w obu z nich!"
diplomat_i18n_page_prefix: "Możesz zacząć tłumaczyć nasze poziomy przechodząc na naszą"
diplomat_i18n_page: "stronę tłumaczeń"
diplomat_i18n_page_suffix: ", albo nasz interfejs i stronę na GitHub."
diplomat_join_pref_github: "Znajdź plik lokalizacyjny dla wybranego języka "
diplomat_github_url: "na GitHubie"
diplomat_join_suf_github: ", edytuj go online i wyślij pull request. Do tego, zaznacz kratkę poniżej, aby być na bieżąco z naszym międzynarodowym rozwojem!"
diplomat_subscribe_desc: "Otrzymuj e-maile na temat postępów i18n i poziomów do tłumaczenia."
ambassador_introduction: "Oto społeczność, którą budujemy, a ty jesteś jej łącznikiem. Mamy czaty, e-maile i strony w sieciach społecznościowych oraz wielu ludzi potrzebujących pomocy w zapoznaniu się z grą oraz uczeniu się za jej pomocą. Jeśli chcesz pomóc ludziom, by do nas dołączyli i dobrze się bawili oraz mieć pełne poczucie tętna CodeCombat oraz kierunku, w którym zmierzamy, ta klasa może być dla ciebie."
ambassador_attribute_1: "Umiejętność komunikacji. Musisz umieć rozpoznać problemy, które mają gracze i pomóc im je rozwiązać. Do tego, informuj resztę z nas, co mówią gracze - na co się skarżą, a czego chcą jeszcze więcej!"
ambassador_join_desc: "powiedz nam coś o sobie, jakie masz doświadczenie i czym byłbyś zainteresowany. Chętnie z tobą porozmawiamy!"
ambassador_join_note_strong: "Uwaga"
ambassador_join_note_desc: "Jednym z naszych priorytetów jest zbudowanie trybu multiplayer, gdzie gracze mający problem z rozwiązywaniem poziomów będą mogli wezwać czarodziejów wyższego poziomu, by im pomogli. Będzie to świetna okazja dla Ambasadorów. Spodziewajcie się ogłoszenia w tej sprawie!"
ambassador_subscribe_desc: "Otrzymuj e-maile dotyczące aktualizacji wsparcia oraz rozwoju trybu multiplayer."
changes_auto_save: "Zmiany zapisują się automatycznie po kliknięci kratki."
diligent_scribes: "Nasi pilni Skrybowie:"
powerful_archmages: "Nasi potężni Arcymagowie:"
creative_artisans: "Nasi kreatywni Rzemieślnicy:"
brave_adventurers: "Nasi dzielni Podróżnicy:"
translating_diplomats: "Nasi tłumaczący Dyplomaci:"
helpful_ambassadors: "Nasi pomocni Ambasadorzy:"
ladder:
please_login: "Przed rozpoczęciem gry rankingowej musisz się zalogować."
my_matches: "Moje pojedynki"
simulate: "Symuluj"
simulation_explanation: "Symulując gry możesz szybciej uzyskać ocenę swojej gry!"
# simulation_explanation_leagues: "You will mainly help simulate games for allied players in your clans and courses."
simulate_games: "Symuluj gry!"
games_simulated_by: "Gry symulowane przez Ciebie:"
games_simulated_for: "Gry symulowane dla Ciebie:"
# games_in_queue: "Games currently in the queue:"
games_simulated: "Gier zasymulowanych"
games_played: "Gier rozegranych"
ratio: "Proporcje"
leaderboard: "Tabela rankingowa"
battle_as: "Walcz jako "
summary_your: "Twój "
summary_matches: "Pojedynki - "
summary_wins: " Wygrane, "
summary_losses: " Przegrane"
rank_no_code: "Brak nowego kodu do oceny"
rank_my_game: "Oceń moją grę!"
rank_submitting: "Wysyłanie..."
rank_submitted: "Wysłano do oceny"
rank_failed: "Błąd oceniania"
rank_being_ranked: "Aktualnie oceniane gry"
rank_last_submitted: "przesłano "
help_simulate: "Pomóc w symulowaniu gier?"
code_being_simulated: "Twój nowy kod jest aktualnie symulowany przez innych graczy w celu oceny. W miarę pojawiania sie nowych pojedynków, nastąpi odświeżenie."
no_ranked_matches_pre: "Brak ocenionych pojedynków dla drużyny "
no_ranked_matches_post: " ! Zagraj przeciwko kilku oponentom i wróc tutaj, aby uzyskać ocenę gry."
choose_opponent: "Wybierz przeciwnika"
select_your_language: "Wybierz swój język!"
tutorial_play: "Rozegraj samouczek"
tutorial_recommended: "Zalecane, jeśli wcześniej nie grałeś"
tutorial_skip: "Pomiń samouczek"
tutorial_not_sure: "Nie wiesz, co się dzieje?"
tutorial_play_first: "Rozegraj najpierw samouczek."
simple_ai: "Proste AI"
warmup: "Rozgrzewka"
friends_playing: "Przyjaciele w grze"
log_in_for_friends: "Zaloguj się by grać ze swoimi znajomymi!"
social_connect_blurb: "Połącz konta i rywalizuj z przyjaciółmi!"
invite_friends_to_battle: "Zaproś przyjaciół do wspólnej walki!"
fight: "Walcz!"
watch_victory: "Obejrzyj swoje zwycięstwo"
defeat_the: "Pokonaj"
# watch_battle: "Watch the battle"
tournament_started: ", rozpoczęto"
# tournament_ends: "Tournament ends"
# tournament_ended: "Tournament ended"
# tournament_rules: "Tournament Rules"
# tournament_blurb: "Write code, collect gold, build armies, crush foes, win prizes, and upgrade your career in our $40,000 Greed tournament! Check out the details"
# tournament_blurb_criss_cross: "Win bids, construct paths, outwit opponents, grab gems, and upgrade your career in our Criss-Cross tournament! Check out the details"
# tournament_blurb_zero_sum: "Unleash your coding creativity in both gold gathering and battle tactics in this alpine mirror match between red sorcerer and blue sorcerer. The tournament began on Friday, March 27 and will run until Monday, April 6 at 5PM PDT. Compete for fun and glory! Check out the details"
# tournament_blurb_ace_of_coders: "Battle it out in the frozen glacier in this domination-style mirror match! The tournament began on Wednesday, September 16 and will run until Wednesday, October 14 at 5PM PDT. Check out the details"
# tournament_blurb_blog: "on our blog"
rules: "Zasady"
winners: "Zwycięzcy"
# league: "League"
# red_ai: "Red AI" # "Red AI Wins", at end of multiplayer match playback
# blue_ai: "Blue AI"
# wins: "Wins" # At end of multiplayer match playback
# humans: "Red" # Ladder page display team name
# ogres: "Blue"
user:
stats: "Statystyki"
singleplayer_title: "Poziomy jednoosobowe"
multiplayer_title: "Poziomy multiplayer"
achievements_title: "Osiągnięcia"
last_played: "Ostatnio grany"
status: "Status"
status_completed: "Ukończono"
status_unfinished: "Nie ukończono"
no_singleplayer: "Nie rozegrał żadnej gry jednoosobowej."
no_multiplayer: "Nie rozegrał żadnej gry multiplayer."
no_achievements: "Nie zdobył żadnych osiągnięć."
favorite_prefix: "Ulubiony język to "
favorite_postfix: "."
not_member_of_clans: "Nie jest członkiem żadnego klanu."
achievements:
last_earned: "Ostatnio zdobyty"
amount_achieved: "Ilość"
achievement: "Osiągnięcie"
category_contributor: "Współtwórca"
category_ladder: "Drabinka"
category_level: "Poziom"
category_miscellaneous: "Różne"
category_levels: "Poziomy"
category_undefined: "Poza kategorią"
# current_xp_prefix: ""
# current_xp_postfix: " in total"
new_xp_prefix: "zdobyto "
new_xp_postfix: ""
left_xp_prefix: ""
left_xp_infix: " brakuje do poziomu "
left_xp_postfix: ""
account:
recently_played: "Ostatnio grane"
# no_recent_games: "No games played during the past two weeks."
payments: "Płatności"
# prepaid_codes: "Prepaid Codes"
purchased: "Zakupiono"
# sale: "Sale"
subscription: "Subskrypcje"
invoices: "Faktury"
# service_apple: "Apple"
# service_web: "Web"
# paid_on: "Paid On"
# service: "Service"
price: "Cena"
gems: "Klejnoty"
active: "Aktywna"
subscribed: "Subskrybujesz"
unsubscribed: "Anulowano"
active_until: "Aktywna do"
cost: "Koszt"
next_payment: "Następna płatność"
card: "Karta"
# status_unsubscribed_active: "You're not subscribed and won't be billed, but your account is still active for now."
# status_unsubscribed: "Get access to new levels, heroes, items, and bonus gems with a CodeCombat subscription!"
account_invoices:
amount: "Kwota w dolarach"
declined: "Karta została odrzucona"
invalid_amount: "Proszę podać kwotę w dolarach."
not_logged_in: "Zaloguj się, albo stwórz konto, żeby przejrzeć faktury."
pay: "Opłać fakturę"
purchasing: "Kupowanie..."
retrying: "Błąd serwera, ponawiam."
success: "Zapłacono. Dziękujemy!"
# account_prepaid:
# purchase_code: "Purchase a Subscription Code"
# purchase_code1: "Subscription Codes can be redeemed to add premium subscription time to one or more CodeCombat accounts."
# purchase_code2: "Each CodeCombat account can only redeem a particular Subscription Code once."
# purchase_code3: "Subscription Code months will be added to the end of any existing subscription on the account."
# users: "Users"
# months: "Months"
# purchase_total: "Total"
# purchase_button: "Submit Purchase"
# your_codes: "Your Codes"
# redeem_codes: "Redeem a Subscription Code"
# prepaid_code: "Prepaid Code"
# lookup_code: "Lookup prepaid code"
# apply_account: "Apply to your account"
# copy_link: "You can copy the code's link and send it to someone."
# quantity: "Quantity"
# redeemed: "Redeemed"
# no_codes: "No codes yet!"
loading_error:
could_not_load: "Błąd podczas ładowania danych z serwera"
connection_failure: "Błąd połączenia."
unauthorized: "Musisz być zalogowany. Masz może wyłączone ciasteczka?"
forbidden: "Brak autoryzacji."
not_found: "Nie znaleziono."
not_allowed: "Metoda nie dozwolona."
timeout: "Serwer nie odpowiada."
conflict: "Błąd zasobów."
bad_input: "Złe dane wejściowe."
server_error: "Błąd serwera."
unknown: "Nieznany błąd."
# error: "ERROR"
resources:
sessions: "Sesje"
your_sessions: "Twoje sesje"
level: "Poziom"
# social_network_apis: "Social Network APIs"
# facebook_status: "Facebook Status"
# facebook_friends: "Facebook Friends"
# facebook_friend_sessions: "Facebook Friend Sessions"
# gplus_friends: "G+ Friends"
# gplus_friend_sessions: "G+ Friend Sessions"
# leaderboard: "Leaderboard"
# user_schema: "User Schema"
user_profile: "Profil użytkownika"
patch: "Łatka"
patches: "Łatki"
patched_model: "Dokument źródłowy"
model: "Model"
# system: "System"
# systems: "Systems"
component: "Komponent"
components: "Komponenty"
thang: "Obiekt"
thangs: "Obiekty"
# level_session: "Your Session"
# opponent_session: "Opponent Session"
article: "Artykuł"
user_names: "<NAME>"
thang_names: "Nazwy obiektów"
files: "Pliki"
top_simulators: "Najlepsi symulatorzy"
source_document: "Dokument źródłowy"
document: "Dokument"
# sprite_sheet: "Sprite Sheet"
employers: "Pr<NAME>"
candidates: "K<NAME>"
# candidate_sessions: "Candidate Sessions"
# user_remark: "User Remark"
# user_remarks: "User Remarks"
versions: "Wersje"
items: "Przedmioty"
hero: "Bohater"
heroes: "Bohaterowie"
achievement: "Osiągnięcie"
# clas: "CLAs"
play_counts: "Liczba gier"
feedback: "Wsparcie"
payment_info: "Info o płatnościach"
campaigns: "Kampanie"
poll: "Ankieta"
user_polls_record: "Historia oddanych głosów"
concepts:
advanced_strings: "Zaawansowane napisy"
algorithms: "Algorytmy"
arguments: "Argumenty"
arithmetic: "Arytmetyka"
arrays: "Tablice"
basic_syntax: "Podstawy składni"
boolean_logic: "Algebra Boole'a"
break_statements: "Klauzula 'break'"
classes: "Klasy"
# continue_statements: "Continue Statements"
for_loops: "Pętle 'for'"
functions: "Funkcje"
# graphics: "Graphics"
if_statements: "Wyrażenia warunkowe"
input_handling: "Zarządzanie wejściami"
math_operations: "Operacje matematyczne"
object_literals: "Operacje na obiektach"
# parameters: "Parameters"
strings: "Ciągi znaków"
variables: "Zmienne"
vectors: "Wektory"
while_loops: "Pętle"
recursion: "Rekurencja"
delta:
added: "Dodano"
modified: "Zmieniono"
not_modified: "Nie zmianiono"
deleted: "Usunięto"
moved_index: "Przesunięto Index"
# text_diff: "Text Diff"
# merge_conflict_with: "MERGE CONFLICT WITH"
no_changes: "Brak zmian"
multiplayer:
multiplayer_title: "Ustawienia multiplayer" # We'll be changing this around significantly soon. Until then, it's not important to translate.
multiplayer_toggle: "Aktywuj multiplayer"
multiplayer_toggle_description: "Pozwól innym dołączyć do twojej gry."
multiplayer_link_description: "Przekaż ten link, jeśli chcesz, by ktoś do ciebie dołączył."
multiplayer_hint_label: "Podpowiedź:"
multiplayer_hint: "Kliknij link by zaznaczyć wszystko, potem wciśnij Cmd-C lub Ctrl-C by skopiować ten link."
multiplayer_coming_soon: "Wkrótce więcej opcji multiplayer"
multiplayer_sign_in_leaderboard: "Zaloguj się lub zarejestruj by umieścić wynik na tablicy wyników."
legal:
page_title: "Nota prawna"
opensource_intro: "CodeCombat jest całkowicie darmowe i całkowicie open source."
opensource_description_prefix: "Zajrzyj na "
github_url: "nasz GitHub"
opensource_description_center: "i pomóż, jeśli tylko masz ochotę! CodeCombat bazuje na dziesiątkach projektów open source - kochamy je wszystkie. Wpadnij na "
archmage_wiki_url: "naszą wiki dla Arcymagów"
opensource_description_suffix: ", by zobaczyć listę oprogramowania, dzięki któremu niniejsza gra może istnieć."
practices_title: "Ludzkim językiem"
practices_description: "Oto nasze obietnice wobec ciebie, gracza, wyrażone po polsku, bez prawniczego żargonu."
privacy_title: "Prywatność"
privacy_description: "Nie sprzedamy żadnej z Twoich prywatnych informacji."
security_title: "Bezpieczeństwo"
security_description: "Z całych sił staramy się zabezpieczyć twoje prywatne informacje. Jako że jesteśmy projektem open source, każdy może sprawdzić i ulepszyć nasz system zabezpieczeń."
email_title: "E-mail"
email_description_prefix: "Nie będziemy nękać cię spamem. Poprzez"
email_settings_url: "twoje ustawienia e-mail"
email_description_suffix: "lub poprzez linki w e-mailach, które wysyłamy, możesz zmienić swoje ustawienia i w prosty sposób wypisać się z subskrypcji w dowolnym momencie."
cost_title: "Koszty"
cost_description: "W tym momencie CodeCombat jest w stu procentach darmowe! Jednym z naszych głównych celów jest, by utrzymać taki stan rzeczy, aby jak najwięcej ludzi miało dostęp do gry, bez względu na ich zasobność. Jeśli nadejdą gorsze dni, dopuszczamy możliwość wprowadzenia płatnych subskrypcji lub pobierania opłat za część zawartości, ale wolelibyśmy, by tak się nie stało. Przy odrobinie szczęścia, uda nam się podtrzymać obecną sytuację dzięki:"
copyrights_title: "Prawa autorskie i licencje"
contributor_title: "Umowa licencyjna dla współtwórców (CLA)"
contributor_description_prefix: "Wszyscy współtwórcy, zarówno ci ze strony jak i ci z GitHuba, podlegają naszemu"
cla_url: "CLA"
contributor_description_suffix: ", na które powinieneś wyrazić zgodę przed dodaniem swojego wkładu."
code_title: "Kod - MIT"
code_description_prefix: "Całość kodu posiadanego przez CodeCombat lub hostowanego na codecombat.com, zarówno w repozytorium GitHub, jak i bazie codecombat.com, podlega licencji"
mit_license_url: "Licencja MIT"
code_description_suffix: "Zawiera się w tym całość kodu w systemach i komponentach, które są udostępnione przez CodeCombat w celu tworzenia poziomów."
art_title: "Grafika/muzyka - Creative Commons "
art_description_prefix: "Całość ogólnej treści dostępna jest pod licencją"
cc_license_url: "Międzynarodowa Licencja Creative Commons Attribution 4.0"
art_description_suffix: "Zawartość ogólna to wszystko, co zostało publicznie udostępnione przez CodeCombat w celu tworzenia poziomów. Wchodzą w to:"
art_music: "Muzyka"
art_sound: "Dźwięki"
art_artwork: "Artworki"
art_sprites: "Sprite'y"
art_other: "Dowolne inne prace niezwiązane z kodem, które są dostępne podczas tworzenia poziomów."
art_access: "Obecnie nie ma uniwersalnego, prostego sposobu, by pozyskać te zasoby. Możesz wejść w ich posiadanie poprzez URL-e, z których korzysta strona, skontaktować się z nami w celu uzyskania pomocy bądź pomóc nam w ulepszeniu strony, aby zasoby te stały się łatwiej dostępne."
art_paragraph_1: "W celu uznania autorstwa, wymień z nazwy i podaj link do codecombat.com w pobliżu miejsca, gdzie znajduje się użyty zasób bądź w miejscu odpowiednim dla twojego medium. Na przykład:"
use_list_1: "W przypadku użycia w filmie lub innej grze, zawrzyj codecombat.com w napisach końcowych."
use_list_2: "W przypadku użycia na stronie internetowej, zawrzyj link w pobliżu miejsca użycia, na przykład po obrazkiem lub na ogólnej stronie poświęconej uznaniu twórców, gdzie możesz również wspomnieć o innych pracach licencjonowanych przy użyciu Creative Commons oraz oprogramowaniu open source używanym na stronie. Coś, co samo w sobie jednoznacznie odnosi się do CodeCombat, na przykład wpis na blogu dotyczący CodeCombat, nie wymaga już dodatkowego uznania autorstwa."
art_paragraph_2: "Jeśli użyte przez ciebie zasoby zostały stworzone nie przez CodeCombat, ale jednego z naszych użytkowników, uznanie autorstwa należy się jemu - postępuj wówczas zgodnie z zasadami uznania autorstwa dostarczonymi wraz z rzeczonym zasobem (o ile takowe występują)."
rights_title: "Prawa zastrzeżone"
rights_desc: "Wszelkie prawa są zastrzeżone dla poziomów jako takich. Zawierają się w tym:"
rights_scripts: "Skrypty"
rights_unit: "Konfiguracje jednostek"
rights_description: "Opisy"
rights_writings: "Teksty"
rights_media: "Multimedia (dźwięki, muzyka) i jakiekolwiek inne typy prac i zasobów stworzonych specjalnie dla danego poziomu, które nie zostały publicznie udostępnione do tworzenia poziomów."
rights_clarification: "Gwoli wyjaśnienia, wszystko, co jest dostępne w Edytorze Poziomów w celu tworzenia nowych poziomów, podlega licencji CC, podczas gdy zasoby stworzone w Edytorze Poziomów lub przesłane w toku tworzenia poziomu - nie."
nutshell_title: "W skrócie"
nutshell_description: "Wszelkie zasoby, które dostarczamy w Edytorze Poziomów są darmowe w użyciu w jakikolwiek sposób w celu tworzenia poziomów. Jednocześnie, zastrzegamy sobie prawo do ograniczenia rozpowszechniania poziomów (stworzonych przez codecombat.com) jako takich, aby mogła być za nie w przyszłości pobierana opłata, jeśli dojdzie do takiej konieczności."
canonical: "Angielska wersja tego dokumentu jest ostateczna, kanoniczną wersją. Jeśli zachodzą jakieś rozbieżności pomiędzy tłumaczeniami, dokument anglojęzyczny ma pierwszeństwo."
# ladder_prizes:
# title: "Tournament Prizes" # This section was for an old tournament and doesn't need new translations now.
# blurb_1: "These prizes will be awarded according to"
# blurb_2: "the tournament rules"
# blurb_3: "to the top human and ogre players."
# blurb_4: "Two teams means double the prizes!"
# blurb_5: "(There will be two first place winners, two second-place winners, etc.)"
# rank: "Rank"
# prizes: "Prizes"
# total_value: "Total Value"
# in_cash: "in cash"
# custom_wizard: "Custom CodeCombat Wizard"
# custom_avatar: "Custom CodeCombat avatar"
# heap: "for six months of \"Startup\" access"
# credits: "credits"
# one_month_coupon: "coupon: choose either Rails or HTML"
# one_month_discount: "discount, 30% off: choose either Rails or HTML"
# license: "license"
# oreilly: "ebook of your choice"
account_profile:
settings: "Ustawienia" # We are not actively recruiting right now, so there's no need to add new translations for this section.
edit_profile: "Edytuj Profil"
done_editing: "Edycja wykonana"
profile_for_prefix: "Profil "
profile_for_suffix: ""
# featured: "Featured"
# not_featured: "Not Featured"
# looking_for: "Looking for:"
# last_updated: "Last updated:"
contact: "<NAME>"
# active: "Looking for interview offers now"
# inactive: "Not looking for offers right now"
# complete: "complete"
next: "Nastepny"
next_city: "miasto?"
next_country: "wybierz kraj."
next_name: "imię?"
# next_short_description: "write a short description."
# next_long_description: "describe your desired position."
# next_skills: "list at least five skills."
# next_work: "chronicle your work history."
# next_education: "recount your educational ordeals."
# next_projects: "show off up to three projects you've worked on."
# next_links: "add any personal or social links."
# next_photo: "add an optional professional photo."
# next_active: "mark yourself open to offers to show up in searches."
# example_blog: "Blog"
# example_personal_site: "Personal Site"
# links_header: "Personal Links"
# links_blurb: "Link any other sites or profiles you want to highlight, like your GitHub, your LinkedIn, or your blog."
# links_name: "Link Name"
# links_name_help: "What are you linking to?"
# links_link_blurb: "Link URL"
# basics_header: "Update basic info"
# basics_active: "Open to Offers"
# basics_active_help: "Want interview offers right now?"
# basics_job_title: "Desired Job Title"
# basics_job_title_help: "What role are you looking for?"
# basics_city: "City"
# basics_city_help: "City you want to work in (or live in now)."
# basics_country: "Country"
# basics_country_help: "Country you want to work in (or live in now)."
# basics_visa: "US Work Status"
# basics_visa_help: "Are you authorized to work in the US, or do you need visa sponsorship? (If you live in Canada or Australia, mark authorized.)"
# basics_looking_for: "Looking For"
# basics_looking_for_full_time: "Full-time"
# basics_looking_for_part_time: "Part-time"
# basics_looking_for_remote: "Remote"
# basics_looking_for_contracting: "Contracting"
# basics_looking_for_internship: "Internship"
# basics_looking_for_help: "What kind of developer position do you want?"
# name_header: "Fill in your name"
# name_anonymous: "<NAME>"
# name_help: "Name you want employers to see, like '<NAME>'."
# short_description_header: "Write a short description of yourself"
# short_description_blurb: "Add a tagline to help an employer quickly learn more about you."
# short_description: "Tagline"
# short_description_help: "Who are you, and what are you looking for? 140 characters max."
# skills_header: "Skills"
# skills_help: "Tag relevant developer skills in order of proficiency."
# long_description_header: "Describe your desired position"
# long_description_blurb: "Tell employers how awesome you are and what role you want."
# long_description: "Self Description"
# long_description_help: "Describe yourself to potential employers. Keep it short and to the point. We recommend outlining the position that would most interest you. Tasteful markdown okay; 600 characters max."
# work_experience: "Work Experience"
# work_header: "Chronicle your work history"
# work_years: "Years of Experience"
# work_years_help: "How many years of professional experience (getting paid) developing software do you have?"
# work_blurb: "List your relevant work experience, most recent first."
# work_employer: "Employer"
# work_employer_help: "Name of your employer."
# work_role: "Job Title"
# work_role_help: "What was your job title or role?"
# work_duration: "Duration"
# work_duration_help: "When did you hold this gig?"
# work_description: "Description"
# work_description_help: "What did you do there? (140 chars; optional)"
# education: "Education"
# education_header: "Recount your academic ordeals"
# education_blurb: "List your academic ordeals."
# education_school: "School"
# education_school_help: "Name of your school."
# education_degree: "Degree"
# education_degree_help: "What was your degree and field of study?"
# education_duration: "Dates"
# education_duration_help: "When?"
# education_description: "Description"
# education_description_help: "Highlight anything about this educational experience. (140 chars; optional)"
# our_notes: "CodeCombat's Notes"
# remarks: "Remarks"
# projects: "Projects"
# projects_header: "Add 3 projects"
# projects_header_2: "Projects (Top 3)"
# projects_blurb: "Highlight your projects to amaze employers."
# project_name: "Project Name"
# project_name_help: "What was the project called?"
# project_description: "Description"
# project_description_help: "Briefly describe the project."
# project_picture: "Picture"
# project_picture_help: "Upload a 230x115px or larger image showing off the project."
# project_link: "Link"
# project_link_help: "Link to the project."
# player_code: "Player Code"
# employers:
# deprecation_warning_title: "Sorry, CodeCombat is not recruiting right now."
# deprecation_warning: "We are focusing on beginner levels instead of finding expert developers for the time being."
# hire_developers_not_credentials: "Hire developers, not credentials." # We are not actively recruiting right now, so there's no need to add new translations for the rest of this section.
# get_started: "Get Started"
# already_screened: "We've already technically screened all our candidates"
# filter_further: ", but you can also filter further:"
# filter_visa: "Visa"
# filter_visa_yes: "US Authorized"
# filter_visa_no: "Not Authorized"
# filter_education_top: "Top School"
# filter_education_other: "Other"
# filter_role_web_developer: "Web Developer"
# filter_role_software_developer: "Software Developer"
# filter_role_mobile_developer: "Mobile Developer"
# filter_experience: "Experience"
# filter_experience_senior: "Senior"
# filter_experience_junior: "Junior"
# filter_experience_recent_grad: "Recent Grad"
# filter_experience_student: "College Student"
# filter_results: "results"
# start_hiring: "Start hiring."
# reasons: "Three reasons you should hire through us:"
# everyone_looking: "Everyone here is looking for their next opportunity."
# everyone_looking_blurb: "Forget about 20% LinkedIn InMail response rates. Everyone that we list on this site wants to find their next position and will respond to your request for an introduction."
# weeding: "Sit back; we've done the weeding for you."
# weeding_blurb: "Every player that we list has been screened for technical ability. We also perform phone screens for select candidates and make notes on their profiles to save you time."
# pass_screen: "They will pass your technical screen."
# pass_screen_blurb: "Review each candidate's code before reaching out. One employer found that 5x as many of our devs passed their technical screen than hiring from Hacker News."
# make_hiring_easier: "Make my hiring easier, please."
# what: "What is CodeCombat?"
# what_blurb: "CodeCombat is a multiplayer browser programming game. Players write code to control their forces in battle against other developers. Our players have experience with all major tech stacks."
# cost: "How much do we charge?"
# cost_blurb: "We charge 15% of first year's salary and offer a 100% money back guarantee for 90 days. We don't charge for candidates who are already actively being interviewed at your company."
# candidate_name: "Name"
# candidate_location: "Location"
# candidate_looking_for: "Looking For"
# candidate_role: "Role"
# candidate_top_skills: "Top Skills"
# candidate_years_experience: "Yrs Exp"
# candidate_last_updated: "Last Updated"
# candidate_who: "Who"
# featured_developers: "Featured Developers"
# other_developers: "Other Developers"
# inactive_developers: "Inactive Developers"
admin:
# av_espionage: "Espionage" # Really not important to translate /admin controls.
# av_espionage_placeholder: "Email or username"
# av_usersearch: "User Search"
# av_usersearch_placeholder: "Email, username, name, whatever"
# av_usersearch_search: "Search"
av_title: "Panel administracyjny"
av_entities_sub_title: "Podmioty"
av_entities_users_url: "Użytkownicy"
av_entities_active_instances_url: "Aktywne podmioty"
# av_entities_employer_list_url: "Employer List"
# av_entities_candidates_list_url: "Candidate List"
# av_entities_user_code_problems_list_url: "User Code Problems List"
av_other_sub_title: "Inne"
av_other_debug_base_url: "Baza (do debuggingu base.jade)"
u_title: "Lista użytkowników"
# ucp_title: "User Code Problems"
lg_title: "Ostatnie gry"
# clas: "CLAs"
| true | module.exports = nativeDescription: "polski", englishDescription: "Polish", translation:
home:
slogan: "Naucz się programowania grając"
no_ie: "CodeCombat nie działa na Internet Explorer 8 i starszych. Przepraszamy!" # Warning that only shows up in IE8 and older
no_mobile: "CodeCombat nie został zaprojektowany dla urządzeń przenośnych, więc mogą występować pewne problemy w jego działaniu!" # Warning that shows up on mobile devices
play: "Graj" # The big play button that opens up the campaign view.
old_browser: "Wygląda na to, że twoja przeglądarka jest zbyt stara, by obsłużyć CodeCombat. Wybacz..." # Warning that shows up on really old Firefox/Chrome/Safari
old_browser_suffix: "Mimo tego możesz spróbować, ale prawdopodobnie gra nie będzie działać."
ipad_browser: "Zła wiadomość: CodeCombat nie działa na przeglądarce w iPadzie. Dobra wiadomość: nasza aplikacja na iPada czeka na akceptację od Apple."
campaign: "Kampania"
for_beginners: "Dla początkujących"
multiplayer: "Multiplayer" # Not currently shown on home page
for_developers: "Dla developerów" # Not currently shown on home page.
or_ipad: "Albo ściągnij na swojego iPada"
nav:
play: "Poziomy" # The top nav bar entry where players choose which levels to play
community: "Społeczność"
editor: "PI:NAME:<NAME>END_PI"
blog: "Blog"
forum: "Forum"
account: "Konto"
profile: "Profil"
stats: "Statystyki"
code: "Kod"
admin: "Admin" # Only shows up when you are an admin
home: "Główna"
contribute: "WspPI:NAME:<NAME>END_PI"
legal: "Nota prawna"
about: "O nas"
contact: "KontPI:NAME:<NAME>END_PI"
twitter_follow: "Subskrybuj"
teachers: "NaPI:NAME:<NAME>END_PI"
# careers: "Careers"
modal:
close: "Zamknij"
okay: "OK"
not_found:
page_not_found: "Strona nie istnieje"
diplomat_suggestion:
title: "Pomóż w tłumaczeniu CodeCombat!" # This shows up when a player switches to a non-English language using the language selector.
sub_heading: "Potrzebujemy twoich zdolności językowych."
pitch_body: "Tworzymy CodeCombat w języku angielskim, jednak nasi gracze pochodzą z całego świata. Wielu z nich chciałoby zagrać w swoim języku, ponieważ nie znają angielskiego, więc jeśli znasz oba języki zostań Dyplomatą i pomóż w tłumaczeniu strony CodeCombat, jak i samej gry."
missing_translations: "Dopóki nie przetłumaczymy wszystkiego na polski, będziesz widział niektóre napisy w języku angielskim."
learn_more: "Dowiedz się więcej o Dyplomatach"
subscribe_as_diplomat: "Dołącz do Dyplomatów"
play:
play_as: "Graj jako " # Ladder page
spectate: "Oglądaj" # Ladder page
players: "graczy" # Hover over a level on /play
hours_played: "rozegranych godzin" # Hover over a level on /play
items: "Przedmioty" # Tooltip on item shop button from /play
unlock: "Odblokuj" # For purchasing items and heroes
confirm: "Potwierdź"
owned: "Posiadane" # For items you own
locked: "Zablokowane"
purchasable: "Można kupić" # For a hero you unlocked but haven't purchased
available: "Dostępny"
skills_granted: "Zdobyte umiejętności" # Property documentation details
heroes: "Bohaterowie" # Tooltip on hero shop button from /play
achievements: "Osiągnięcia" # Tooltip on achievement list button from /play
account: "Konto" # Tooltip on account button from /play
settings: "Opcje" # Tooltip on settings button from /play
poll: "Ankieta" # Tooltip on poll button from /play
next: "Dalej" # Go from choose hero to choose inventory before playing a level
change_hero: "Wybierz bohatera" # Go back from choose inventory to choose hero
choose_inventory: "Załóż przedmioty"
buy_gems: "Kup klejnoty"
subscription_required: "Wymagana subskrypcja"
anonymous: "PI:NAME:<NAME>END_PI"
level_difficulty: "Poziom trudności: "
campaign_beginner: "Kampania dla początkujących"
awaiting_levels_adventurer_prefix: "Wydajemy pięć poziomów na tydzień." # {change}
awaiting_levels_adventurer: "Zapisz się jako Podróżnik,"
awaiting_levels_adventurer_suffix: "aby jako pierwszy grać w nowe poziomy."
adjust_volume: "Dopasuj głośność"
campaign_multiplayer: "Kampania dla wielu graczy"
campaign_multiplayer_description: "... w której konkurujesz z innymi graczami."
campaign_old_multiplayer: "(Nie używane) Stare areny multiplayer"
campaign_old_multiplayer_description: "Relikt bardziej cywilizowanej epoki. Nie są już prowadzone żadne symulacje dla tych starych aren."
share_progress_modal:
blurb: "Robisz coraz to większe postępy! Pokaż swoim rodzicom jak wiele nauczyłeś się z CodeCombat."
email_invalid: "Błędny adres e-mail."
form_blurb: "Wpisz adres email swich rodziców, a my ich o tym poinformujemy!"
form_label: "Adres email"
placeholder: "adres email"
title: "Wspaniała robota, Adepcie"
login:
sign_up: "Stwórz konto"
log_in: "Zaloguj się"
logging_in: "Logowanie..."
log_out: "Wyloguj się"
forgot_password: "PI:PASSWORD:<PASSWORD>END_PI?"
authenticate_gplus: "Autoryzuj G+"
load_profile: "Wczytaj Profil G+"
finishing: "Kończenie"
sign_in_with_facebook: "Logowanie z Facebookiem"
sign_in_with_gplus: "Logowanie z Google+"
signup_switch: "Chcesz stworzyć konto?"
signup:
email_announcements: "Otrzymuj powiadomienia na e-mail"
creating: "Tworzenie konta..."
sign_up: "Zarejestruj się"
log_in: "Zaloguj się używając hasła"
social_signup: "lub zaloguj się używając konta Facebook lub G+:"
required: "Musisz się zalogować zanim przejdziesz dalej."
login_switch: "Masz już konto?"
recover:
recover_account_title: "Odzyskaj konto"
send_password: "PI:PASSWORD:<PASSWORD>END_PI"
recovery_sent: "Email do dozyskania hasła został wysłany."
items:
primary: "Główne"
secondary: "Drugorzędne"
armor: "Zbroja"
accessories: "Akcesoria"
misc: "Różne"
books: "Książki"
common:
back: "Wstecz" # When used as an action verb, like "Navigate backward"
continue: "Dalej" # When used as an action verb, like "Continue forward"
loading: "Ładowanie..."
saving: "Zapisywanie..."
sending: "Wysyłanie…"
send: "Wyślij"
cancel: "Anuluj"
save: "Zapisz"
publish: "Opublikuj"
create: "Stwórz"
fork: "Fork"
play: "Zagraj" # When used as an action verb, like "Play next level"
retry: "Ponów"
actions: "Akcje"
info: "Informacje"
help: "Pomoc"
watch: "Obserwuj"
unwatch: "Nie obserwuj"
submit_patch: "Prześlij łatkę"
submit_changes: "Prześlij zmiany"
save_changes: "Zapisz zmiany"
general:
and: "i"
name: "PI:NAME:<NAME>END_PI"
date: "Data"
body: "Zawartość"
version: "Wersja"
pending: "W trakcie"
accepted: "Przyjęto"
rejected: "Odrzucono"
withdrawn: "Wycofano"
# accept: "Accept"
# reject: "Reject"
# withdraw: "Withdraw"
submitter: "PI:NAME:<NAME>END_PI"
submitted: "Przesłano"
commit_msg: "Wiadomość do commitu"
version_history: "Historia wersji"
version_history_for: "Historia wersji dla: "
select_changes: "Zaznacz dwie zmiany poniżej aby zobaczyć różnice."
undo_prefix: "Cofnij"
undo_shortcut: "(Ctrl+Z)"
redo_prefix: "Ponów"
redo_shortcut: "(Ctrl+Shift+Z)"
play_preview: "Odtwórz podgląd obecnego poziomu"
result: "Wynik"
results: "Wyniki"
description: "Opis"
or: "lub"
subject: "Temat"
email: "Email"
password: "PI:PASSWORD:<PASSWORD>END_PI"
message: "Wiadomość"
code: "Kod"
ladder: "Drabinka"
when: "kiedy"
opponent: "PI:NAME:<NAME>END_PI"
rank: "Ranking"
score: "Wynik"
win: "Wygrana"
loss: "Przegrana"
tie: "Remis"
easy: "Łatwy"
medium: "Średni"
hard: "Trudny"
player: "PI:NAME:<NAME>END_PI"
player_level: "Poziom" # Like player level 5, not like level: Dungeons of Kithgard
warrior: "WPI:NAME:<NAME>END_PI"
ranger: "Łucznik"
wizard: "Czarodziej"
units:
second: "sekunda"
seconds: "sekund"
minute: "minuta"
minutes: "minut"
hour: "godzina"
hours: "godzin"
day: "dzień"
days: "dni"
week: "tydzień"
weeks: "tygodni"
month: "miesiąc"
months: "miesięcy"
year: "rok"
years: "lat"
play_level:
done: "Zrobione"
# next_game: "Next game"
# show_menu: "Show game menu"
home: "Strona główna" # Not used any more, will be removed soon.
level: "Poziom" # Like "Level: Dungeons of Kithgard"
skip: "Pomiń"
game_menu: "Menu gry"
guide: "Przewodnik"
restart: "Zacznij od nowa"
goals: "Cele"
goal: "Cel"
running: "Symulowanie..."
success: "Sukces!"
incomplete: "Niekompletne"
timed_out: "Czas minął"
failing: "Niepowodzenie"
action_timeline: "Oś czasu"
click_to_select: "Kliknij jednostkę, by ją zaznaczyć."
control_bar_multiplayer: "Multiplayer"
control_bar_join_game: "Dołącz do gry"
reload: "Wczytaj ponownie"
reload_title: "Przywrócić cały kod?"
reload_really: "Czy jesteś pewien, że chcesz przywrócić kod startowy tego poziomu?"
reload_confirm: "Przywróć cały kod"
victory: "Zwycięstwo"
victory_title_prefix: ""
victory_title_suffix: " ukończony"
victory_sign_up: "Zarejestruj się, by zapisać postępy"
victory_sign_up_poke: "Chcesz zapisać swój kod? Stwórz bezpłatne konto!"
victory_rate_the_level: "Oceń poziom: " # Only in old-style levels.
victory_return_to_ladder: "Powrót do drabinki"
victory_play_continue: "Dalej"
victory_saving_progress: "Zapisywanie postępów"
victory_go_home: "Powrót do strony głównej"
victory_review: "Powiedz nam coś więcej!"
victory_review_placeholder: "Jak ci się podobał poziom?"
victory_hour_of_code_done: "Skończyłeś już?"
victory_hour_of_code_done_yes: "Tak, skończyłem moją Godzinę Kodu."
victory_experience_gained: "Doświadczenie zdobyte"
victory_gems_gained: "Klejnoty zdobyte"
victory_new_item: "Nowy przedmiot"
victory_viking_code_school: "O jejku, trudny był ten poziom, co? Jeśli jeszcze nie jesteś twórcą oprogramowania, możesz nim już zostać. Złóż swoje podanie o przyjęcie do Viking Code School, a z ich pomocą w zostaniesz na pewno w pełni profesjonalnym programistą."
victory_become_a_viking: "Zostań wikingiem"
# victory_bloc: "Great work! Your skills are improving, and someone's taking notice. If you've considered becoming a software developer, this may be your lucky day. Bloc is an online bootcamp that pairs you 1-on-1 with an expert mentor who will help train you into a professional developer! By beating A Mayhem of Munchkins, you're now eligible for a $500 price reduction with the code: CCRULES"
# victory_bloc_cta: "Meet your mentor – learn about Bloc"
guide_title: "Przewodnik"
tome_minion_spells: "Czary twojego podopiecznego" # Only in old-style levels.
tome_read_only_spells: "Czary tylko do odczytu" # Only in old-style levels.
tome_other_units: "Inne jednostki" # Only in old-style levels.
tome_cast_button_run: "Uruchom"
tome_cast_button_running: "Uruchomiono"
tome_cast_button_ran: "Uruchomiono"
tome_submit_button: "Prześlij"
tome_reload_method: "Wczytaj oryginalny kod dla tej metody" # Title text for individual method reload button.
tome_select_method: "Wybierz metode"
tome_see_all_methods: "Zobacz wszystkie metody możliwe do edycji" # Title text for method list selector (shown when there are multiple programmable methods).
tome_select_a_thang: "Wybierz kogoś do "
tome_available_spells: "Dostępne czary"
tome_your_skills: "Twoje umiejętności"
tome_current_method: "Obecna Metoda"
hud_continue_short: "Kontynuuj"
code_saved: "Kod zapisano"
skip_tutorial: "Pomiń (esc)"
keyboard_shortcuts: "Skróty klawiszowe"
loading_ready: "Gotowy!"
loading_start: "Rozpocznij poziom"
problem_alert_title: "Popraw swój kod"
time_current: "Teraz:"
time_total: "Maksymalnie:"
time_goto: "Idź do:"
non_user_code_problem_title: "Błąd podczas ładowania poziomu"
infinite_loop_title: "Wykryto niekończącą się pętlę"
infinite_loop_description: "Kod źródłowy, który miał stworzył ten świat nigdy nie przestał działać. Albo działa bardzo wolno, albo ma w sobie niekończącą sie pętlę. Albo też gdzieś jest błąd systemu. Możesz spróbować uruchomić go jeszcze raz, albo przywrócić domyślny kod. Jeśli nic nie pomoże daj nam o tym znać."
check_dev_console: "Możesz też otworzyć konsolę deweloperska i sprawdzić w czym tkwi problem."
check_dev_console_link: "(instrukcje)"
infinite_loop_try_again: "Próbuj ponownie"
infinite_loop_reset_level: "Resetuj poziom"
infinite_loop_comment_out: "Comment Out My Code"
tip_toggle_play: "Włącz/zatrzymaj grę naciskając Ctrl+P."
tip_scrub_shortcut: "Ctrl+[ i Ctrl+] przesuwają czas." # {change}
tip_guide_exists: "Klikając Przewodnik u góry strony uzyskasz przydatne informacje."
tip_open_source: "CodeCombat ma w 100% otwarty kod!"
tip_tell_friends: "Podoba ci się CodeCombat? Opowiedz o nas swoim znajomym!"
tip_beta_launch: "CodeCombat uruchomił fazę beta w październiku 2013."
tip_think_solution: "Myśl nad rozwiązaniem, nie problemem."
tip_theory_practice: "W teorii nie ma różnicy między teorią a praktyką. W praktyce jednak, jest. - PI:NAME:<NAME>END_PI"
tip_error_free: "Są dwa sposoby by napisać program bez błędów. Tylko trzeci działa. - PI:NAME:<NAME>END_PI"
tip_debugging_program: "Jeżeli debugowanie jest procesem usuwania błędów, to programowanie musi być procesem umieszczania ich. - PI:NAME:<NAME>END_PI"
tip_forums: "Udaj się na forum i powiedz nam co myślisz!"
tip_baby_coders: "W przyszłości, każde dziecko będzie Arcymagiem."
tip_morale_improves: "Ładowanie będzie kontynuowane gdy wzrośnie morale."
tip_all_species: "Wierzymy w równe szanse nauki programowania dla wszystkich gatunków."
tip_reticulating: "Siatkowanie kolców."
tip_harry: "Jesteś czarodziejem "
tip_great_responsibility: "Z wielką mocą programowania wiąże się wielka odpowiedzialność debugowania."
tip_munchkin: "Jeśli nie będziesz jadł warzyw, Munchkin przyjdzie po Ciebie w nocy."
tip_binary: "Jest tylko 10 typów ludzi na świecie: Ci którzy rozumieją kod binarny i ci którzy nie."
tip_commitment_yoda: "Programista musi najgłębsze zaangażowanie okazać. Umysł najpoważniejszy. ~ Yoda"
tip_no_try: "Rób. Lub nie rób. Nie ma próbowania. - Yoda"
tip_patience: "Cierpliwość musisz mieć, młody Padawanie. - Yoda"
tip_documented_bug: "Udokumentowany błąd nie jest błędem. Jest funkcją."
tip_impossible: "To zawsze wygląda na niemożliwe zanim zostanie zrobione. - PI:NAME:<NAME>END_PI"
tip_talk_is_cheap: "Gadać jest łatwo. Pokażcie mi kod. - PI:NAME:<NAME>END_PI"
tip_first_language: "Najbardziej zgubną rzeczą jakiej możesz się nauczyć jest twój pierwszy język programowania. - PI:NAME:<NAME>END_PI"
tip_hardware_problem: "P: Ilu programistów potrzeba by wymienić żarówkę? O: Żadnego,to problem sprzętowy."
tip_hofstadters_law: "PPI:NAME:<NAME>END_PI: Każdy projekt zabiera więcej czasu, niż planujesz, nawet jeśli przy planowaniu uwzględnisz prawo Hofstadtera."
# tip_premature_optimization: "Premature optimization is the root of all evil. - PI:NAME:<NAME>END_PI"
# tip_brute_force: "When in doubt, use brute force. - PI:NAME:<NAME>END_PI"
# tip_extrapolation: "There are only two kinds of people: those that can extrapolate from incomplete data..."
# tip_superpower: "Coding is the closest thing we have to a superpower."
# tip_control_destiny: "In real open source, you have the right to control your own destiny. - PI:NAME:<NAME>END_PI"
# tip_no_code: "No code is faster than no code."
# tip_code_never_lies: "Code never lies, comments sometimes do. — PI:NAME:<NAME>END_PI"
# tip_reusable_software: "Before software can be reusable it first has to be usable."
tip_optimization_operator: "Każdy język programowania ma operator optymalizujący. W większości z nich tym operatorem jest ‘//’"
# tip_lines_of_code: "Measuring programming progress by lines of code is like measuring aircraft building progress by weight. — PI:NAME:<NAME>END_PI"
# tip_source_code: "I want to change the world but they would not give me the source code."
# tip_javascript_java: "Java is to JavaScript what Car is to Carpet. - PI:NAME:<NAME>END_PI"
# tip_move_forward: "Whatever you do, keep moving forward. - PI:NAME:<NAME>END_PIr."
# tip_google: "Have a problem you can't solve? Google it!"
# tip_adding_evil: "Adding a pinch of evil."
# tip_hate_computers: "That's the thing about people who think they hate computers. What they really hate is lousy programmers. - PI:NAME:<NAME>END_PI"
# tip_open_source_contribute: "You can help CodeCombat improve!"
# tip_recurse: "To iterate is human, to recurse divine. - PI:NAME:<NAME>END_PI"
# tip_free_your_mind: "You have to let it all go, Neo. Fear, doubt, and disbelief. Free your mind. - Morpheus"
# tip_strong_opponents: "Even the strongest of opponents always has a weakness. - PI:NAME:<NAME>END_PI"
# tip_paper_and_pen: "Before you start coding, you can always plan with a sheet of paper and a pen."
# tip_solve_then_write: "First, solve the problem. Then, write the code. - PI:NAME:<NAME>END_PI"
game_menu:
inventory_tab: "Ekwipunek"
save_load_tab: "Zapisz/Wczytaj"
options_tab: "Opcje"
guide_tab: "Przewodnik"
guide_video_tutorial: "Wideo poradnik"
guide_tips: "Wskazówki"
multiplayer_tab: "Multiplayer"
auth_tab: "Zarejestruj się"
inventory_caption: "Wyposaż swojego bohatera"
choose_hero_caption: "Wybierz bohatera, język"
save_load_caption: "... i przejrzyj historię"
options_caption: "Ustaw opcje"
guide_caption: "Dokumenty i wskazówki"
multiplayer_caption: "Graj ze znajomymi!"
auth_caption: "Zapisz swój postęp."
leaderboard:
leaderboard: "Najlepsze wyniki"
view_other_solutions: "Pokaż tablicę wyników"
scores: "Wyniki"
top_players: "Najlepsi gracze"
day: "Dziś"
week: "W tym tygodniu"
all: "Zawsze"
time: "Czas"
damage_taken: "Obrażenia otrzymane"
damage_dealt: "Obrażenia zadane"
difficulty: "Trudność"
gold_collected: "Złoto zebrane"
inventory:
choose_inventory: "Załóż przedmioty"
equipped_item: "Założone"
required_purchase_title: "Wymagane"
available_item: "Dostępne"
restricted_title: "Zabronione"
should_equip: "(kliknij podwójnie, aby założyć)"
equipped: "(założone)"
locked: "(zablokowane)"
restricted: "(zabronione)"
equip: "Załóż"
unequip: "Zdejmij"
buy_gems:
few_gems: "Kilka klejnotów"
pile_gems: "Stos klejnotów"
chest_gems: "Skrzynia z klejnotami"
purchasing: "Kupowanie..."
declined: "Karta została odrzucona"
retrying: "Błąd serwera, ponawiam."
prompt_title: "Za mało klejnotów"
prompt_body: "Chcesz zdobyć więcej?"
prompt_button: "Wejdź do sklepu"
recovered: "Przywrócono poprzednie zakupy. Prosze odświeżyć stronę."
price: "x3500 / mieś."
subscribe:
comparison_blurb: "Popraw swoje umiejętności z subskrypcją CodeCombat!"
feature1: "Ponad 100 poziomów w 4 różnych śwoatach" # {change}
feature2: "10 potężnych, <strong>nowych bohaterów</strong> z unikalnymi umiejętnościami!" # {change}
feature3: "Ponad 70 bonusowych poziomów" # {change}
feature4: "Dodatkowe <strong>3500 klejnotów</strong> co miesiąc!"
feature5: "Poradniki wideo"
feature6: "Priorytetowe wsparcie przez e-mail"
feature7: "Prywatne <strong>Klany</strong>"
free: "Darmowo"
month: "miesięcznie"
# must_be_logged: "You must be logged in first. Please create an account or log in from the menu above."
subscribe_title: "Zapisz się"
unsubscribe: "Wypisz się"
confirm_unsubscribe: "Potwierdź wypisanie się"
never_mind: "Nie ważne, i tak cię kocham"
thank_you_months_prefix: ""
thank_you_months_suffix: " - przez tyle miesięcy nas wspierałeś. Dziękujemy!"
thank_you: "Dziękujemy za wsparcie CodeCombat."
# sorry_to_see_you_go: "Sorry to see you go! Please let us know what we could have done better."
# unsubscribe_feedback_placeholder: "O, what have we done?"
# parent_button: "Ask your parent"
# parent_email_description: "We'll email them so they can buy you a CodeCombat subscription."
# parent_email_input_invalid: "Email address invalid."
# parent_email_input_label: "Parent email address"
# parent_email_input_placeholder: "Enter parent email"
# parent_email_send: "Send Email"
# parent_email_sent: "Email sent!"
# parent_email_title: "What's your parent's email?"
# parents: "For Parents"
# parents_title: "Dear Parent: Your child is learning to code. Will you help them continue?"
# parents_blurb1: "Your child has played __nLevels__ levels and learned programming basics. Help cultivate their interest and buy them a subscription so they can keep playing."
# parents_blurb1a: "Computer programming is an essential skill that your child will undoubtedly use as an adult. By 2020, basic software skills will be needed by 77% of jobs, and software engineers are in high demand across the world. Did you know that Computer Science is the highest-paid university degree?"
# parents_blurb2: "For $9.99 USD/mo, your child will get new challenges every week and personal email support from professional programmers."
# parents_blurb3: "No Risk: 100% money back guarantee, easy 1-click unsubscribe."
# payment_methods: "Payment Methods"
# payment_methods_title: "Accepted Payment Methods"
# payment_methods_blurb1: "We currently accept credit cards and Alipay."
# payment_methods_blurb2: "If you require an alternate form of payment, please contact"
# sale_already_subscribed: "You're already subscribed!"
# sale_blurb1: "Save 35%"
# sale_blurb2: "off regular subscription price of $120 for a whole year!"
# sale_button: "Sale!"
# sale_button_title: "Save 35% when you purchase a 1 year subscription"
# sale_click_here: "Click Here"
# sale_ends: "Ends"
# sale_extended: "*Existing subscriptions will be extended by 1 year."
# sale_feature_here: "Here's what you'll get:"
# sale_feature2: "Access to 9 powerful <strong>new heroes</strong> with unique skills!"
# sale_feature4: "<strong>42,000 bonus gems</strong> awarded immediately!"
# sale_continue: "Ready to continue adventuring?"
# sale_limited_time: "Limited time offer!"
# sale_new_heroes: "New heroes!"
# sale_title: "Back to School Sale"
# sale_view_button: "Buy 1 year subscription for"
# stripe_description: "Monthly Subscription"
# stripe_description_year_sale: "1 Year Subscription (35% discount)"
# subscription_required_to_play: "You'll need a subscription to play this level."
# unlock_help_videos: "Subscribe to unlock all video tutorials."
# personal_sub: "Personal Subscription" # Accounts Subscription View below
# loading_info: "Loading subscription information..."
# managed_by: "Managed by"
# will_be_cancelled: "Will be cancelled on"
# currently_free: "You currently have a free subscription"
# currently_free_until: "You currently have a subscription until"
# was_free_until: "You had a free subscription until"
# managed_subs: "Managed Subscriptions"
# managed_subs_desc: "Add subscriptions for other players (students, children, etc.)"
# managed_subs_desc_2: "Recipients must have a CodeCombat account associated with the email address you provide."
# group_discounts: "Group discounts"
# group_discounts_1: "We also offer group discounts for bulk subscriptions."
# group_discounts_1st: "1st subscription"
# group_discounts_full: "Full price"
# group_discounts_2nd: "Subscriptions 2-11"
# group_discounts_20: "20% off"
# group_discounts_12th: "Subscriptions 12+"
# group_discounts_40: "40% off"
# subscribing: "Subscribing..."
# recipient_emails_placeholder: "Enter email address to subscribe, one per line."
# subscribe_users: "Subscribe Users"
# users_subscribed: "Users subscribed:"
# no_users_subscribed: "No users subscribed, please double check your email addresses."
# current_recipients: "Current Recipients"
# unsubscribing: "Unsubscribing"
# subscribe_prepaid: "Click Subscribe to use prepaid code"
# using_prepaid: "Using prepaid code for monthly subscription"
choose_hero:
choose_hero: "Wybierz swojego bohatera"
programming_language: "Język programowania"
programming_language_description: "Którego języka programowania chcesz używać?"
default: "domyślny"
experimental: "Eksperymentalny"
python_blurb: "Prosty ale potężny."
javascript_blurb: "Język internetu."
coffeescript_blurb: "Przyjemniejsza składnia JavaScript."
clojure_blurb: "Nowoczesny Lisp."
lua_blurb: "Język skryptowy gier."
io_blurb: "Prosty lecz nieznany."
status: "Status"
hero_type: "Typ"
weapons: "Bronie"
weapons_warrior: "Miecze - Krótki zasięg, Brak magii"
weapons_ranger: "Kusze, Pistolety - Daleki zasięg, Brak magii"
weapons_wizard: "Różdżki, Laski - Daleki zasięg, Magia"
attack: "Obrażenia" # Can also translate as "Attack"
health: "Życie"
speed: "Szybkość"
regeneration: "Regenaracja"
range: "Zasięg" # As in "attack or visual range"
blocks: "Blok" # As in "this shield blocks this much damage"
backstab: "Cios" # As in "this dagger does this much backstab damage"
skills: "Umiejętności"
attack_1: "Zadaje"
# attack_2: "of listed"
attack_3: "obrażeń od broni."
health_1: "Zdobywa"
# health_2: "of listed"
health_3: "wytrzymałości pancerza."
speed_1: "Idzie do"
speed_2: "metrów na sekundę."
available_for_purchase: "Można wynająć" # Shows up when you have unlocked, but not purchased, a hero in the hero store
level_to_unlock: "Musisz odblokować poziom:" # 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: "Tylko nieliczni bohaterowie mogą brać udział w tym poziomie."
skill_docs:
writable: "zapisywalny" # Hover over "attack" in Your Skills while playing a level to see most of this
read_only: "tylko do odczytu"
# action: "Action"
# spell: "Spell"
action_name: "nazwa"
action_cooldown: "Zajmuje"
action_specific_cooldown: "Odpoczynek"
action_damage: "Obrażenia"
action_range: "Zasięg"
action_radius: "Promień"
action_duration: "Czas trwania"
example: "Przykład"
ex: "np." # Abbreviation of "example"
current_value: "Aktualna wartość"
default_value: "Domyślna wartość"
parameters: "Parametry"
returns: "Zwraca"
granted_by: "Zdobyte dzięki:"
save_load:
granularity_saved_games: "Zapisano"
granularity_change_history: "Historia"
options:
general_options: "Opcje ogólne" # Check out the Options tab in the Game Menu while playing a level
volume_label: "Głośność"
music_label: "Muzyka"
music_description: "Wł/Wył muzykę w tle."
editor_config_title: "Konfiguracja edytora"
editor_config_keybindings_label: "Przypisania klawiszy"
editor_config_keybindings_default: "Domyślny (Ace)"
editor_config_keybindings_description: "Dodaje skróty znane z popularnych edytorów."
editor_config_livecompletion_label: "Podpowiedzi na żywo"
editor_config_livecompletion_description: "Wyświetl sugestie autouzupełnienia podczas pisania."
editor_config_invisibles_label: "Pokaż białe znaki"
editor_config_invisibles_description: "Wyświetla białe znaki takie jak spacja czy tabulator."
editor_config_indentguides_label: "Pokaż linijki wcięć"
editor_config_indentguides_description: "Wyświetla pionowe linie, by lepiej zaznaczyć wcięcia."
editor_config_behaviors_label: "Inteligentne zachowania"
editor_config_behaviors_description: "Autouzupełnianie nawiasów, klamer i cudzysłowów."
about:
why_codecombat: "Dlaczego CodeCombat?"
why_paragraph_1: "Chcesz nauczyć się programowania? Nie potrzeba ci lekcji. Potrzeba ci pisania dużej ilości kodu w sposób sprawiający ci przyjemność."
why_paragraph_2_prefix: "O to chodzi w programowaniu - musi sprawiać radość. Nie radość w stylu"
why_paragraph_2_italic: "hura, nowa odznaka"
why_paragraph_2_center: ", ale radości w stylu"
why_paragraph_2_italic_caps: "NIE MAMO, MUSZĘ DOKOŃCZYĆ TEN POZIOM!"
why_paragraph_2_suffix: "Dlatego właśnie CodeCombat to gra multiplayer, a nie kurs oparty na zgamifikowanych lekcjach. Nie przestaniemy, dopóki ty nie będziesz mógł przestać--tym razem jednak w pozytywnym sensie."
why_paragraph_3: "Jeśli planujesz uzależnić się od jakiejś gry, uzależnij się od tej i zostań jednym z czarodziejów czasu technologii."
press_title: "Blogerzy/Prasa"
press_paragraph_1_prefix: "Chcesz o nas napisać? Śmiało możesz pobrać iu wykorzystać wszystkie informację dostępne w naszym"
press_paragraph_1_link: "pakiecie prasowym "
press_paragraph_1_suffix: ". Wszystkie loga i obrazki mogą zostać wykorzystane bez naszej wiedzy."
team: "Zespół"
george_title: "Współzałożyciel"
george_blurb: "Pan Prezes"
scott_title: "Współzałożyciel"
scott_blurb: "PI:NAME:<NAME>END_PI"
nick_title: "PI:NAME:<NAME>END_PI"
nick_blurb: "Guru Motywacji"
michael_title: "Programista"
michael_blurb: "Sys Admin"
matt_title: "Programista"
matt_blurb: "Rowerzysta"
cat_title: "Główny Rzemieślnik"
cat_blurb: "Airbender"
josh_title: "Projektant Gier"
josh_blurb: "Podłoga to lawa"
jose_title: "Muzyka"
jose_blurb: "Odnosi Sukces"
retrostyle_title: "Ilustracje"
retrostyle_blurb: "RetroStyle Games"
teachers:
more_info: "Informacja dla nauczycieli"
# intro_1: "CodeCombat is an online game that teaches programming. Students write code in real programming languages."
# intro_2: "No experience required!"
# free_title: "How much does it cost?"
# cost_premium_server: "CodeCombat is free for the first five levels, after which it costs $9.99 USD per month for access to our other 190+ levels on our exclusive country-specific servers."
# free_1: "There are 110+ FREE levels which cover every concept."
# free_2: "A monthly subscription provides access to video tutorials and extra practice levels."
# teacher_subs_title: "Teachers get free subscriptions!"
# teacher_subs_0: "We offer free subscriptions to teachers for evaluation purposes."
# teacher_subs_1: "Please fill out our"
# teacher_subs_2: "Teacher Survey"
# teacher_subs_3: "to set up your subscription."
# sub_includes_title: "What is included in the subscription?"
# sub_includes_1: "In addition to the 110+ basic levels, students with a monthly subscription get access to these additional features:"
# sub_includes_2: "80+ practice levels"
# sub_includes_3: "Video tutorials"
# sub_includes_4: "Premium email support"
# sub_includes_5: "10 new heroes with unique skills to master"
# sub_includes_6: "3500 bonus gems every month"
# sub_includes_7: "Private Clans"
# monitor_progress_title: "How do I monitor student progress?"
# monitor_progress_1: "Student progress can be monitored by creating a"
# monitor_progress_2: "for your class."
# monitor_progress_3: "To add a student, send them the invite link for your Clan, which is on the"
# monitor_progress_4: "page."
# monitor_progress_5: "After they join, you will see a summary of the student's progress on your Clan's page."
# private_clans_1: "Private Clans provide increased privacy and detailed progress information for each student."
# private_clans_2: "To create a private Clan, check the 'Make clan private' checkbox when creating a"
# private_clans_3: "."
# who_for_title: "Who is CodeCombat for?"
# who_for_1: "We recommend CodeCombat for students aged 9 and up. No prior programming experience is needed."
# who_for_2: "We've designed CodeCombat to appeal to both boys and girls."
# material_title: "How much material is there?"
# material_premium_server: "Approximately 50 hours of gameplay spread over 190+ subscriber-only levels so far."
# material_1: "Approximately 25 hours of free content and an additional 15 hours of subscriber content."
# concepts_title: "What concepts are covered?"
# how_much_title: "How much does a monthly subscription cost?"
# how_much_1: "A"
# how_much_2: "monthly subscription"
# how_much_3: "costs $9.99, and can be cancelled anytime."
# how_much_4: "Additionally, we provide discounts for larger groups:"
# how_much_5: "We accept discounted one-time purchases and yearly subscription purchases for groups, such as a class or school. Please contact"
# how_much_6: "for more details."
# more_info_title: "Where can I find more information?"
# more_info_1: "Our"
# more_info_2: "teachers forum"
# more_info_3: "is a good place to connect with fellow educators who are using CodeCombat."
# sys_requirements_title: "System Requirements"
# sys_requirements_1: "A modern web browser. Newer versions of Chrome, Firefox, or Safari. Internet Explorer 9 or later."
# sys_requirements_2: "CodeCombat is not supported on iPad yet."
teachers_survey:
title: "Ankieta dla nauczycieli"
# must_be_logged: "You must be logged in first. Please create an account or log in from the menu above."
# retrieving: "Retrieving information..."
# being_reviewed_1: "Your application for a free trial subscription is being"
# being_reviewed_2: "reviewed."
# approved_1: "Your application for a free trial subscription was"
# approved_2: "approved."
# approved_3: "Further instructions have been sent to"
# denied_1: "Your application for a free trial subscription has been"
# denied_2: "denied."
# contact_1: "Please contact"
# contact_2: "if you have further questions."
# description_1: "We offer free subscriptions to teachers for evaluation purposes. You can find more information on our"
# description_2: "teachers"
# description_3: "page."
# description_4: "Please fill out this quick survey and we’ll email you setup instructions."
# email: "Email Address"
# school: "Name of School"
# location: "Name of City"
# age_students: "How old are your students?"
# under: "Under"
# other: "Other:"
# amount_students: "How many students do you teach?"
# hear_about: "How did you hear about CodeCombat?"
# fill_fields: "Please fill out all fields."
# thanks: "Thanks! We'll send you setup instructions shortly."
versions:
save_version_title: "Zapisz nową wersję"
new_major_version: "Nowa wersja główna"
submitting_patch: "Przesyłanie łatki..."
cla_prefix: "Aby zapisać zmiany, musisz najpierw zaakceptować naszą"
cla_url: "umowę licencyjną dla współtwórców (CLA)"
cla_suffix: "."
cla_agree: "AKCEPTUJĘ"
owner_approve: "Przed pojawieniem się zmian, właściciel musi je zatwierdzić."
contact:
contact_us: "Kontakt z CodeCombat"
welcome: "Miło Cię widzieć! Użyj tego formularza, żeby wysłać do nas wiadomość. "
forum_prefix: "W sprawach ogólnych, skorzystaj z "
forum_page: "naszego forum"
forum_suffix: "."
faq_prefix: "Jest też"
faq: "FAQ"
subscribe_prefix: "Jeśli masz jakiś problem z rozwiązaniem poziomu,"
subscribe: "wykup subskrypcję CodeCombat,"
subscribe_suffix: "a my z radością ci pomożemy."
subscriber_support: "Jako, że będziesz subskrybentem CodeCombat, twoje e-maile będą miały najwyższy priorytet."
screenshot_included: "Dołączymy zrzuty ekranu."
where_reply: "Gdzie mamy odpisać?"
send: "Wyślij wiadomość"
contact_candidate: "Kontakt z kandydatem" # Deprecated
# recruitment_reminder: "Use this form to reach out to candidates you are interested in interviewing. Remember that CodeCombat charges 15% of first-year salary. The fee is due upon hiring the employee and is refundable for 90 days if the employee does not remain employed. Part time, remote, and contract employees are free, as are interns." # Deprecated
account_settings:
title: "Ustawienia Konta"
not_logged_in: "Zaloguj się lub stwórz konto, by dostosować ustawienia."
autosave: "Zmiany zapisują się automatycznie"
me_tab: "Ja"
picture_tab: "Zdjęcie"
delete_account_tab: "Usuń swoje konto"
wrong_email: "Błędny e-mail"
wrong_password: "PI:PASSWORD:<PASSWORD>END_PI"
upload_picture: "Wgraj zdjęcie"
delete_this_account: "Usuń to konto całkowicie"
god_mode: "TRYB BOGA"
password_tab: "Hasło"
emails_tab: "Powiadomienia"
admin: "Administrator"
new_password: "PI:PASSWORD:<PASSWORD>END_PI"
new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI"
type_in_email: "Wpisz swój email, aby potwierdzić usunięcie konta."
type_in_password: "PI:PASSWORD:<PASSWORD>END_PI hasło."
email_subscriptions: "Powiadomienia email"
email_subscriptions_none: "Brak powiadomień e-mail."
email_announcements: "Ogłoszenia"
email_announcements_description: "Otrzymuj powiadomienia o najnowszych wiadomościach i zmianach w CodeCombat."
email_notifications: "Powiadomienia"
email_notifications_summary: "Ustawienia spersonalizowanych, automatycznych powiadomień mailowych zależnych od twojej aktywności w CodeCombat."
email_any_notes: "Wszystkie powiadomienia"
email_any_notes_description: "Odznacz by wyłączyć wszystkie powiadomienia email."
email_news: "Nowości"
email_recruit_notes: "Możliwości zatrudnienia"
email_recruit_notes_description: "Jeżeli grasz naprawdę dobrze, możemy się z tobą skontaktować by zaoferować (lepszą) pracę."
contributor_emails: "Powiadomienia asystentów"
contribute_prefix: "Szukamy osób, które chciałyby do nas dołączyć! Sprawdź "
contribute_page: "stronę współpracy"
contribute_suffix: ", aby dowiedzieć się więcej."
email_toggle: "Zmień wszystkie"
error_saving: "Błąd zapisywania"
saved: "Zmiany zapisane"
password_mismatch: "PI:PASSWORD:<PASSWORD>END_PI"
password_repeat: "PI:PASSWORD:<PASSWORD>END_PI."
job_profile: "Profil zatrudnienia" # Rest of this section (the job profile stuff and wizard stuff) is deprecated
job_profile_approved: "Twój profil zatrudnienia został zaakceptowany przez CodeCombat. Pracodawcy będą mogli go widzieć dopóki nie oznaczysz go jako nieaktywny lub nie będzie on zmieniany przez 4 tygodnie."
job_profile_explanation: "Witaj! Wypełnij to, a będziemy w kontakcie w sprawie znalezienie dla Ciebe pracy twórcy oprogramowania."
sample_profile: "Zobacz przykładowy profil"
view_profile: "Zobacz swój profil"
keyboard_shortcuts:
keyboard_shortcuts: "Skróty klawiszowe"
space: "Spacja"
enter: "Enter"
press_enter: "naciśnij enter"
escape: "Escape"
shift: "Shift"
run_code: "Uruchom obecny kod."
run_real_time: "Uruchom \"na żywo\"."
continue_script: "Kontynuuj ostatni skrypt."
skip_scripts: "Pomiń wszystkie pomijalne skrypty."
toggle_playback: "Graj/pauzuj."
# scrub_playback: "Scrub back and forward through time."
# single_scrub_playback: "Scrub back and forward through time by a single frame."
# scrub_execution: "Scrub through current spell execution."
# toggle_debug: "Toggle debug display."
# toggle_grid: "Toggle grid overlay."
# toggle_pathfinding: "Toggle pathfinding overlay."
# beautify: "Beautify your code by standardizing its formatting."
maximize_editor: "Maksymalizuj/minimalizuj edytor kodu."
community:
main_title: "Społeczność CodeCombat"
# introduction: "Check out the ways you can get involved below and decide what sounds the most fun. We look forward to working with you!"
# level_editor_prefix: "Use the CodeCombat"
# level_editor_suffix: "to create and edit levels. Users have created levels for their classes, friends, hackathons, students, and siblings. If create a new level sounds intimidating you can start by forking one of ours!"
# thang_editor_prefix: "We call units within the game 'thangs'. Use the"
# thang_editor_suffix: "to modify the CodeCombat source artwork. Allow units to throw projectiles, alter the direction of an animation, change a unit's hit points, or upload your own vector sprites."
# article_editor_prefix: "See a mistake in some of our docs? Want to make some instructions for your own creations? Check out the"
# article_editor_suffix: "and help CodeCombat players get the most out of their playtime."
find_us: "Znajdź nas na tych stronach"
social_github: "Przejrzyj cały nasz kod na platformie GitHub"
social_blog: "Przeczytaj blog CodeCombat na Sett"
social_discource: "Dołącz do dyskusji na naszym forum"
social_facebook: "Polub CodeCombat na Facebooku"
social_twitter: "Obserwuj CodeCombat na Twitterze"
social_gplus: "Dołącz do CodeCombat na Google+"
social_hipchat: "Pogadaj z nami na pblicznym czacie HipChat"
contribute_to_the_project: "Zostań współtwórcą CodeCombat"
clans:
clan: "Klan"
clans: "Klany"
new_name: "PI:NAME:<NAME>END_PI nowego klanu"
new_description: "Opis nowego klanu"
make_private: "Stwórz prywatny klan"
subs_only: "tylko subskrybenci"
create_clan: "Stwórz nowy klan"
private_preview: "Podgląd"
public_clans: "Publiczne klany"
my_clans: "Moje klany"
clan_name: "PI:NAME:<NAME>END_PI"
name: "PI:NAME:<NAME>END_PI"
chieftain: "Dowódca"
type: "Typ"
edit_clan_name: "Edytuj nazwe klanu"
edit_clan_description: "Edytuj opis klanu"
edit_name: "edytuj nazwe"
edit_description: "edytuj opis"
private: "(prywatny)"
summary: "Podsumowanie"
average_level: "Średni poziom"
average_achievements: "Średnio osiągnięć"
delete_clan: "Usuń klan"
leave_clan: "Opuść klan"
join_clan: "Dołacz do klanu"
invite_1: "Zaproszenie:"
invite_2: "*Zaproś nowe osoby do klanu wysyłając im ten link."
members: "CzPI:NAME:<NAME>END_PI"
progress: "Postęp"
not_started_1: "nierozpoczęty"
started_1: "rozpoczęty"
complete_1: "ukończony"
exp_levels: "Rozwiń poziomy"
rem_hero: "Usuń bohatera"
status: "Status"
complete_2: "Ukończony"
started_2: "Rozpoczęto"
not_started_2: "Nie rozpoczęto"
view_solution: "Kliknij, aby obejrzeć rozwiązanie."
latest_achievement: "Ostatnie osiągnięcia"
playtime: "Czas gyr"
last_played: "Ostatnio grany"
# leagues_explanation: "Play in a league against other clan members in these multiplayer arena instances."
# track_concepts1: "Track concepts"
# track_concepts2a: "learned by each student"
# track_concepts2b: "learned by each member"
# track_concepts3a: "Track levels completed for each student"
# track_concepts3b: "Track levels completed for each member"
# track_concepts4a: "See your students'"
# track_concepts4b: "See your members'"
# track_concepts5: "solutions"
# track_concepts6a: "Sort students by name or progress"
# track_concepts6b: "Sort members by name or progress"
# track_concepts7: "Requires invitation"
# track_concepts8: "to join"
# private_require_sub: "Private clans require a subscription to create or join."
# courses:
# course: "Course"
# courses: "courses"
# not_enrolled: "You are not enrolled in this course."
# visit_pref: "Please visit the"
# visit_suf: "page to enroll."
# select_class: "Select one of your classes"
# unnamed: "*unnamed*"
# select: "Select"
# unnamed_class: "Unnamed Class"
# edit_settings: "edit class settings"
# edit_settings1: "Edit Class Settings"
# progress: "Class Progress"
# add_students: "Add Students"
# stats: "Statistics"
# total_students: "Total students:"
# average_time: "Average level play time:"
# total_time: "Total play time:"
# average_levels: "Average levels completed:"
# total_levels: "Total levels completed:"
# furthest_level: "Furthest level completed:"
# concepts_covered: "Concepts Covered"
# students: "Students"
# students1: "students"
# expand_details: "Expand details"
# concepts: "Concepts"
# levels: "levels"
# played: "Played"
# play_time: "Play time:"
# completed: "Completed:"
# invite_students: "Invite students to join this class."
# invite_link_header: "Link to join course"
# invite_link_p_1: "Give this link to students you would like to have join the course."
# invite_link_p_2: "Or have us email them directly:"
# capacity_used: "Course slots used:"
# enter_emails: "Enter student emails to invite, one per line"
# send_invites: "Send Invites"
# title: "Title"
# description: "Description"
# languages_available: "Select programming languages available to the class:"
# all_lang: "All Languages"
# show_progress: "Show student progress to everyone in the class"
# creating_class: "Creating class..."
# purchasing_course: "Purchasing course..."
# buy_course: "Buy Course"
# buy_course1: "Buy this course"
# create_class: "Create Class"
# select_all_courses: "Select 'All Courses' for a 50% discount!"
# all_courses: "All Courses"
# number_students: "Number of students"
# enter_number_students: "Enter the number of students you need for this class."
# name_class: "Name your class"
# displayed_course_page: "This will be displayed on the course page for you and your students. It can be changed later."
# buy: "Buy"
# purchasing_for: "You are purchasing a license for"
# creating_for: "You are creating a class for"
# for: "for" # Like in 'for 30 students'
# receive_code: "Afterwards you will receive an unlock code to distribute to your students, which they can use to enroll in your class."
# free_trial: "Free trial for teachers!"
# get_access: "to get individual access to all courses for evalutaion purposes."
# questions: "Questions?"
# faq: "Courses FAQ"
# question: "Q:" # Like in 'Question'
# question1: "What's the difference between these courses and the single player game?"
# answer: "A:" # Like in 'Answer'
# answer1: "The single player game is designed for individuals, while the courses are designed for classes."
# answer2: "The single player game has items, gems, hero selection, leveling up, and in-app purchases. Courses have classroom management features and streamlined student-focused level pacing."
# teachers_click: "Teachers Click Here"
# students_click: "Students Click Here"
# courses_on_coco: "Courses on CodeCombat"
# designed_to: "Courses are designed to introduce computer science concepts using CodeCombat's fun and engaging environment. CodeCombat levels are organized around key topics to encourage progressive learning, over the course of 5 hours."
# more_in_less: "Learn more in less time"
# no_experience: "No coding experience necesssary"
# easy_monitor: "Easily monitor student progress"
# purchase_for_class: "Purchase a course for your entire class. It's easy to sign up your students!"
# see_the: "See the"
# more_info: "for more information."
# choose_course: "Choose Your Course:"
# enter_code: "Enter an unlock code to join an existing class"
# enter_code1: "Enter unlock code"
# enroll: "Enroll"
# pick_from_classes: "Pick from your current classes"
# enter: "Enter"
# or: "Or"
# topics: "Topics"
# hours_content: "Hours of content:"
# get_free: "Get FREE course"
classes:
archmage_title: "Arcymag"
archmage_title_description: "(programista)"
archmage_summary: "Jesteś programistą zainteresowanym tworzeniem gier edukacyjnych? Zostań Arcymagiem i pomóż nam ulepszyć CodeCombat!"
artisan_title: "Rzemieślnik"
artisan_title_description: "(twórca poziomów)"
artisan_summary: "Buduj i dziel się poziomami z przyjaciółmi i innymi graczami. Zostań RPI:NAME:<NAME>END_PIieślnikiem, który pomaga w uczeniu innych sztuki programowania."
adventurer_title: "PodPI:NAME:<NAME>END_PI"
adventurer_title_description: "(playtester)"
adventurer_summary: "Zagraj w nasze nowe poziomy (nawet te dla subskrybentów) za darmo przez ich wydaniem i pomóż nam znaleźć w nich błędy zanim zostaną opublikowane."
scribe_title: "PI:NAME:<NAME>END_PI"
scribe_title_description: "(twórca artykułów)"
scribe_summary: "Dobry kod wymaga dobrej dokumentacji. Pisz, edytuj i ulepszaj dokumentację czytana przez miliony graczy na całym świecie."
diplomat_title: "Dyplomata"
diplomat_title_description: "(tłumacz)"
diplomat_summary: "CodeCombat jest tłumaczone na ponad 45 języków. Dołącz do naszch Dyplomatów i pomóż im w dalszych pracach."
ambassador_title: "Ambasador"
ambassador_title_description: "(wsparcie)"
ambassador_summary: "Okiełznaj naszych użytkowników na forum, udzielaj odpowiedzi na pytania i wspieraj ich. Nasi Ambasadorzy reprezentują CodeCombat przed całym światem."
editor:
main_title: "Edytory CodeCombat"
article_title: "Edytor artykułów"
thang_title: "Edytor obiektów"
level_title: "Edytor poziomów"
achievement_title: "Edytor osiągnięć"
poll_title: "Edytor ankiet"
back: "Wstecz"
revert: "Przywróć"
revert_models: "Przywróć wersję"
pick_a_terrain: "Wybierz teren"
dungeon: "Loch"
indoor: "Wnętrze"
desert: "Pustynia"
grassy: "Trawa"
mountain: "Góry"
glacier: "Lodowiec"
small: "Mały"
large: "Duży"
fork_title: "Forkuj nowa wersję"
fork_creating: "Tworzenie Forka..."
generate_terrain: "Generuj teren"
more: "Więcej"
wiki: "Wiki"
live_chat: "Czat na żywo"
thang_main: "Główna"
# thang_spritesheets: "Spritesheets"
thang_colors: "Kolory"
level_some_options: "Trochę opcji?"
level_tab_thangs: "Obiekty"
level_tab_scripts: "Skrypty"
level_tab_settings: "Ustawienia"
level_tab_components: "Komponenty"
level_tab_systems: "Systemy"
level_tab_docs: "Documentacja"
level_tab_thangs_title: "Aktualne obiekty"
level_tab_thangs_all: "Wszystkie"
level_tab_thangs_conditions: "Warunki początkowe"
level_tab_thangs_add: "Dodaj obiekty"
level_tab_thangs_search: "Przeszukaj obiekty"
add_components: "Dodaj komponenty"
component_configs: "Konfiguracja komponentów"
config_thang: "Kliknij dwukrotnie, aby skonfigurować obiekt"
delete: "Usuń"
duplicate: "Powiel"
stop_duplicate: "Przestań powielać"
rotate: "Obróć"
level_settings_title: "Ustawienia"
level_component_tab_title: "Aktualne komponenty"
level_component_btn_new: "Stwórz nowy komponent"
level_systems_tab_title: "Aktualne systemy"
level_systems_btn_new: "Stwórz nowy system"
level_systems_btn_add: "Dodaj system"
level_components_title: "Powrót do listy obiektów"
level_components_type: "Typ"
level_component_edit_title: "Edytuj komponent"
level_component_config_schema: "Schemat konfiguracji"
level_component_settings: "Ustawienia"
level_system_edit_title: "Edytuj system"
create_system_title: "Stwórz nowy system"
new_component_title: "Stwórz nowy komponent"
new_component_field_system: "System"
new_article_title: "Stwórz nowy artykuł"
new_thang_title: "Stwórz nowy typ obiektu"
new_level_title: "Stwórz nowy poziom"
new_article_title_login: "Zaloguj się, aby stworzyć nowy artykuł"
new_thang_title_login: "Zaloguj się, aby stworzyć nowy typ obiektu"
new_level_title_login: "Zaloguj się, aby stworzyć nowy poziom"
new_achievement_title: "Stwórz nowe osiągnięcie"
new_achievement_title_login: "Zaloguj się, aby stworzyć nowy osiągnięcie"
new_poll_title: "Stwórz nową ankietę"
new_poll_title_login: "Zaloguj się aby stworzyć nową ankietę"
article_search_title: "Przeszukaj artykuły"
thang_search_title: "Przeszukaj obiekty"
level_search_title: "Przeszukaj poziomy"
achievement_search_title: "Szukaj osiągnięcia"
poll_search_title: "Szukaj ankiety"
read_only_warning2: "Uwaga: nie możesz zapisać żadnych zmian, ponieważ nie jesteś zalogowany."
no_achievements: "Dla tego poziomu nie ma żadnych osiągnięć."
# achievement_query_misc: "Key achievement off of miscellanea"
# achievement_query_goals: "Key achievement off of level goals"
level_completion: "Ukończenie poziomu"
pop_i18n: "Uzupełnij I18N"
tasks: "Zadania"
clear_storage: "Usuń swoje lokalne zmiany"
# add_system_title: "Add Systems to Level"
done_adding: "Zakończono dodawanie"
article:
edit_btn_preview: "Podgląd"
edit_article_title: "Edytuj artykuł"
polls:
priority: "Priorytet"
contribute:
page_title: "Współpraca"
# intro_blurb: "CodeCombat is 100% open source! Hundreds of dedicated players have helped us build the game into what it is today. Join us and write the next chapter in CodeCombat's quest to teach the world to code!"
alert_account_message_intro: "Hej tam!"
alert_account_message: "Musisz się najpierw zalogować, jeśli chcesz zapisać się na klasowe e-maile."
archmage_introduction: "Jedną z najlepszych rzeczy w tworzeniu gier jest to, że syntetyzują one tak wiele różnych spraw. Grafika, dźwięk, łączność w czasie rzeczywistym, social networking i oczywiście wiele innych, bardziej popularnych, aspektów programowania, od niskopoziomowego zarządzania bazami danych i administracji serwerem do interfejsu użytkownika i jego tworzenia. Jest wiele do zrobienia i jeśli jesteś doświadczonym programistą z zacięciem, by zajrzeć do sedna CodeCombat, ta klasa może być dla ciebie. Bylibyśmy niezmiernie szczęśliwi mając twoją pomoc przy budowaniu najlepszej programistycznej gry wszech czasów."
class_attributes: "Atrybuty klasowe"
archmage_attribute_1_pref: "Znajomość "
archmage_attribute_1_suf: " lub chęć do nauki. Większość naszego kodu napisana jest w tym języku. Jeśli jesteś fanem Ruby czy Pythona, poczujesz się jak w domu. To po prostu JavaScript, tyle że z przyjemniejszą składnią."
archmage_attribute_2: "Pewne doświadczenie w programowaniu i własna inicjatywa. Pomożemy ci się połapać, ale nie możemy spędzić zbyt dużo czasu na szkoleniu cię."
how_to_join: "Jak dołączyć"
join_desc_1: "Każdy może pomóc! Zerknij po prostu na nasz "
join_desc_2: ", aby rozpocząć i zaznacz kratkę poniżej, aby określić sie jako mężny Arcymag oraz otrzymywać najświeższe wiadomości przez e-mail. Chcesz porozmawiać na temat tego, co robić lub w jaki sposób dołączyć do współpracy jeszcze wyraźniej? "
join_desc_3: " lub zajrzyj do naszego "
join_desc_4: ", a dowiesz się wszystkiego!"
join_url_email: "Napisz do nas"
join_url_hipchat: "publicznego pokoju HipChat"
archmage_subscribe_desc: "Otrzymuj e-maile dotyczące nowych okazji programistycznych oraz ogłoszeń."
artisan_introduction_pref: "Musimy stworzyć dodatkowe poziomy! Ludzie będą oczekiwać nowych zasobów, a my mamy ograniczone możliwości co do naszych mocy przerobowych. Obecnie, twoja stacja robocza jest na poziomie pierwszym; nasz edytor poziomów jest ledwo używalny nawet przez jego twórców - bądź tego świadom. Jeśli masz wizję nowych kampanii, od pętli typu for do"
artisan_introduction_suf: ", ta klasa może być dla ciebie."
artisan_attribute_1: "Jakiekolwiek doświadczenie w tworzeniu zasobów tego typu byłoby przydatne, na przykład używając edytora poziomów dostarczonego przez Blizzard. Nie jest to jednak wymagane."
artisan_attribute_2: "Zacięcie do całej masy testowania i iteracji. Aby tworzyć dobre poziomy, musisz dostarczyć je innym i obserwować jak grają oraz być przygotowanym na wprowadzanie mnóstwa poprawek."
artisan_attribute_3: "Na dzień dzisiejszy, cierpliwość wraz z naszym Podróżnikiem. Nasz PI:NAME:<NAME>END_PI jest jest strasznie prymitywny i frustrujący w użyciu. Zostałeś ostrzeżony!"
artisan_join_desc: "Używaj Edytora Poziomów mniej-więcej zgodnie z poniższymi krokami:"
artisan_join_step1: "Przeczytaj dokumentację."
artisan_join_step2: "Stwórz nowy poziom i przejrzyj istniejące poziomy."
artisan_join_step3: "Zajrzyj do naszego publicznego pokoju HipChat, aby uzyskać pomoc."
artisan_join_step4: "Pokaż swoje poziomy na forum, aby uzyskać opinie."
artisan_subscribe_desc: "Otrzymuj e-maile dotyczące aktualności w tworzeniu poziomów i ogłoszeń."
adventurer_introduction: "Bądźmy szczerzy co do twojej roli: jesteś tankiem. Będziesz przyjmował ciężkie obrażenia. Potrzebujemy ludzi do testowania nowych poziomów i pomocy w rozpoznawaniu ulepszeń, które będzie można do nich zastosować. Będzie to bolesny proces; tworzenie dobrych gier to długi proces i nikt nie trafia w dziesiątkę za pierwszym razem. Jeśli jesteś wytrzymały i masz wysoki wskaźnik constitution (D&D), ta klasa jest dla ciebie."
adventurer_attribute_1: "PI:NAME:<NAME>END_PI. Chcesz nauczyć się programować, a my chcemy ci to umożliwić. Prawdopodobnie w tym przypadku, to ty będziesz jednak przez wiele czasu stroną uczącą."
adventurer_attribute_2: "PI:NAME:<NAME>END_PI. Bądź uprzejmy, ale wyraźnie określaj, co wymaga poprawy, oferując sugestie co do sposobu jej uzyskania."
adventurer_join_pref: "Zapoznaj się z Rzemieślnikiem (lub rekrutuj go!), aby wspólnie pracować lub też zaznacz kratkę poniżej, aby otrzymywać e-maile, kiedy pojawią się nowe poziomy do testowania. Będziemy również pisać o poziomach do sprawdzenia na naszych stronach w sieciach społecznościowych jak"
adventurer_forum_url: "nasze forum"
adventurer_join_suf: "więc jeśli wolałbyś być informowany w ten sposób, zarejestruj się na nich!"
adventurer_subscribe_desc: "Otrzymuj e-maile, gdy pojawią się nowe poziomy do tesotwania."
scribe_introduction_pref: "CodeCombat nie będzie tylko zbieraniną poziomów. Będzie też zawierać źródło wiedzy, wiki programistycznych idei, na której będzie można oprzeć poziomy. Dzięki temu, każdy z Rzemieślników zamiast opisywać ze szczegółami, czym jest operator porónania, będzie mógł po prostu podać graczowi w swoim poziomie link do artykułu opisującego go. Mamy na myśli coś podobnego do "
scribe_introduction_url_mozilla: "Mozilla Developer Network"
scribe_introduction_suf: ". Jeśli twoją definicją zabawy jest artykułowanie idei programistycznych przy pomocy składni Markdown, ta klasa może być dla ciebie."
scribe_attribute_1: "Umiejętne posługiwanie się słowem to właściwie wszystko, czego potrzebujesz. Nie tylko gramatyka i ortografia, ale również umiejętnośc tłumaczenia trudnego materiału innym."
contact_us_url: "Skontaktuj się z nami"
scribe_join_description: "powiedz nam coś o sobie, swoim doświadczeniu w programowaniu i rzeczach, o których chciałbyś pisać, a chętnie to z tobą uzgodnimy!"
scribe_subscribe_desc: "Otrzymuj e-maile na temat ogłoszeń dotyczących pisania artykułów."
diplomat_introduction_pref: "Jeśli dowiedzieliśmy jednej rzeczy z naszego "
diplomat_launch_url: "otwarcia w październiku"
diplomat_introduction_suf: ", to jest nią informacja o znacznym zainteresowaniu CodeCombat w innych krajach. Tworzymy zespół tłumaczy chętnych do przemieniania zestawów słów w inne zestawy słów, aby CodeCombat było tak dostępne dla całego świata, jak to tylko możliwe. Jeśli chciabyś mieć wgląd w nadchodzącą zawartość i umożliwić swoim krajanom granie w najnowsze poziomy, ta klasa może być dla ciebie."
diplomat_attribute_1: "Biegła znajomość angielskiego oraz języka, na który chciałbyś tłumaczyć. Kiedy przekazujesz skomplikowane idee, dobrze mieć płynność w obu z nich!"
diplomat_i18n_page_prefix: "Możesz zacząć tłumaczyć nasze poziomy przechodząc na naszą"
diplomat_i18n_page: "stronę tłumaczeń"
diplomat_i18n_page_suffix: ", albo nasz interfejs i stronę na GitHub."
diplomat_join_pref_github: "Znajdź plik lokalizacyjny dla wybranego języka "
diplomat_github_url: "na GitHubie"
diplomat_join_suf_github: ", edytuj go online i wyślij pull request. Do tego, zaznacz kratkę poniżej, aby być na bieżąco z naszym międzynarodowym rozwojem!"
diplomat_subscribe_desc: "Otrzymuj e-maile na temat postępów i18n i poziomów do tłumaczenia."
ambassador_introduction: "Oto społeczność, którą budujemy, a ty jesteś jej łącznikiem. Mamy czaty, e-maile i strony w sieciach społecznościowych oraz wielu ludzi potrzebujących pomocy w zapoznaniu się z grą oraz uczeniu się za jej pomocą. Jeśli chcesz pomóc ludziom, by do nas dołączyli i dobrze się bawili oraz mieć pełne poczucie tętna CodeCombat oraz kierunku, w którym zmierzamy, ta klasa może być dla ciebie."
ambassador_attribute_1: "Umiejętność komunikacji. Musisz umieć rozpoznać problemy, które mają gracze i pomóc im je rozwiązać. Do tego, informuj resztę z nas, co mówią gracze - na co się skarżą, a czego chcą jeszcze więcej!"
ambassador_join_desc: "powiedz nam coś o sobie, jakie masz doświadczenie i czym byłbyś zainteresowany. Chętnie z tobą porozmawiamy!"
ambassador_join_note_strong: "Uwaga"
ambassador_join_note_desc: "Jednym z naszych priorytetów jest zbudowanie trybu multiplayer, gdzie gracze mający problem z rozwiązywaniem poziomów będą mogli wezwać czarodziejów wyższego poziomu, by im pomogli. Będzie to świetna okazja dla Ambasadorów. Spodziewajcie się ogłoszenia w tej sprawie!"
ambassador_subscribe_desc: "Otrzymuj e-maile dotyczące aktualizacji wsparcia oraz rozwoju trybu multiplayer."
changes_auto_save: "Zmiany zapisują się automatycznie po kliknięci kratki."
diligent_scribes: "Nasi pilni Skrybowie:"
powerful_archmages: "Nasi potężni Arcymagowie:"
creative_artisans: "Nasi kreatywni Rzemieślnicy:"
brave_adventurers: "Nasi dzielni Podróżnicy:"
translating_diplomats: "Nasi tłumaczący Dyplomaci:"
helpful_ambassadors: "Nasi pomocni Ambasadorzy:"
ladder:
please_login: "Przed rozpoczęciem gry rankingowej musisz się zalogować."
my_matches: "Moje pojedynki"
simulate: "Symuluj"
simulation_explanation: "Symulując gry możesz szybciej uzyskać ocenę swojej gry!"
# simulation_explanation_leagues: "You will mainly help simulate games for allied players in your clans and courses."
simulate_games: "Symuluj gry!"
games_simulated_by: "Gry symulowane przez Ciebie:"
games_simulated_for: "Gry symulowane dla Ciebie:"
# games_in_queue: "Games currently in the queue:"
games_simulated: "Gier zasymulowanych"
games_played: "Gier rozegranych"
ratio: "Proporcje"
leaderboard: "Tabela rankingowa"
battle_as: "Walcz jako "
summary_your: "Twój "
summary_matches: "Pojedynki - "
summary_wins: " Wygrane, "
summary_losses: " Przegrane"
rank_no_code: "Brak nowego kodu do oceny"
rank_my_game: "Oceń moją grę!"
rank_submitting: "Wysyłanie..."
rank_submitted: "Wysłano do oceny"
rank_failed: "Błąd oceniania"
rank_being_ranked: "Aktualnie oceniane gry"
rank_last_submitted: "przesłano "
help_simulate: "Pomóc w symulowaniu gier?"
code_being_simulated: "Twój nowy kod jest aktualnie symulowany przez innych graczy w celu oceny. W miarę pojawiania sie nowych pojedynków, nastąpi odświeżenie."
no_ranked_matches_pre: "Brak ocenionych pojedynków dla drużyny "
no_ranked_matches_post: " ! Zagraj przeciwko kilku oponentom i wróc tutaj, aby uzyskać ocenę gry."
choose_opponent: "Wybierz przeciwnika"
select_your_language: "Wybierz swój język!"
tutorial_play: "Rozegraj samouczek"
tutorial_recommended: "Zalecane, jeśli wcześniej nie grałeś"
tutorial_skip: "Pomiń samouczek"
tutorial_not_sure: "Nie wiesz, co się dzieje?"
tutorial_play_first: "Rozegraj najpierw samouczek."
simple_ai: "Proste AI"
warmup: "Rozgrzewka"
friends_playing: "Przyjaciele w grze"
log_in_for_friends: "Zaloguj się by grać ze swoimi znajomymi!"
social_connect_blurb: "Połącz konta i rywalizuj z przyjaciółmi!"
invite_friends_to_battle: "Zaproś przyjaciół do wspólnej walki!"
fight: "Walcz!"
watch_victory: "Obejrzyj swoje zwycięstwo"
defeat_the: "Pokonaj"
# watch_battle: "Watch the battle"
tournament_started: ", rozpoczęto"
# tournament_ends: "Tournament ends"
# tournament_ended: "Tournament ended"
# tournament_rules: "Tournament Rules"
# tournament_blurb: "Write code, collect gold, build armies, crush foes, win prizes, and upgrade your career in our $40,000 Greed tournament! Check out the details"
# tournament_blurb_criss_cross: "Win bids, construct paths, outwit opponents, grab gems, and upgrade your career in our Criss-Cross tournament! Check out the details"
# tournament_blurb_zero_sum: "Unleash your coding creativity in both gold gathering and battle tactics in this alpine mirror match between red sorcerer and blue sorcerer. The tournament began on Friday, March 27 and will run until Monday, April 6 at 5PM PDT. Compete for fun and glory! Check out the details"
# tournament_blurb_ace_of_coders: "Battle it out in the frozen glacier in this domination-style mirror match! The tournament began on Wednesday, September 16 and will run until Wednesday, October 14 at 5PM PDT. Check out the details"
# tournament_blurb_blog: "on our blog"
rules: "Zasady"
winners: "Zwycięzcy"
# league: "League"
# red_ai: "Red AI" # "Red AI Wins", at end of multiplayer match playback
# blue_ai: "Blue AI"
# wins: "Wins" # At end of multiplayer match playback
# humans: "Red" # Ladder page display team name
# ogres: "Blue"
user:
stats: "Statystyki"
singleplayer_title: "Poziomy jednoosobowe"
multiplayer_title: "Poziomy multiplayer"
achievements_title: "Osiągnięcia"
last_played: "Ostatnio grany"
status: "Status"
status_completed: "Ukończono"
status_unfinished: "Nie ukończono"
no_singleplayer: "Nie rozegrał żadnej gry jednoosobowej."
no_multiplayer: "Nie rozegrał żadnej gry multiplayer."
no_achievements: "Nie zdobył żadnych osiągnięć."
favorite_prefix: "Ulubiony język to "
favorite_postfix: "."
not_member_of_clans: "Nie jest członkiem żadnego klanu."
achievements:
last_earned: "Ostatnio zdobyty"
amount_achieved: "Ilość"
achievement: "Osiągnięcie"
category_contributor: "Współtwórca"
category_ladder: "Drabinka"
category_level: "Poziom"
category_miscellaneous: "Różne"
category_levels: "Poziomy"
category_undefined: "Poza kategorią"
# current_xp_prefix: ""
# current_xp_postfix: " in total"
new_xp_prefix: "zdobyto "
new_xp_postfix: ""
left_xp_prefix: ""
left_xp_infix: " brakuje do poziomu "
left_xp_postfix: ""
account:
recently_played: "Ostatnio grane"
# no_recent_games: "No games played during the past two weeks."
payments: "Płatności"
# prepaid_codes: "Prepaid Codes"
purchased: "Zakupiono"
# sale: "Sale"
subscription: "Subskrypcje"
invoices: "Faktury"
# service_apple: "Apple"
# service_web: "Web"
# paid_on: "Paid On"
# service: "Service"
price: "Cena"
gems: "Klejnoty"
active: "Aktywna"
subscribed: "Subskrybujesz"
unsubscribed: "Anulowano"
active_until: "Aktywna do"
cost: "Koszt"
next_payment: "Następna płatność"
card: "Karta"
# status_unsubscribed_active: "You're not subscribed and won't be billed, but your account is still active for now."
# status_unsubscribed: "Get access to new levels, heroes, items, and bonus gems with a CodeCombat subscription!"
account_invoices:
amount: "Kwota w dolarach"
declined: "Karta została odrzucona"
invalid_amount: "Proszę podać kwotę w dolarach."
not_logged_in: "Zaloguj się, albo stwórz konto, żeby przejrzeć faktury."
pay: "Opłać fakturę"
purchasing: "Kupowanie..."
retrying: "Błąd serwera, ponawiam."
success: "Zapłacono. Dziękujemy!"
# account_prepaid:
# purchase_code: "Purchase a Subscription Code"
# purchase_code1: "Subscription Codes can be redeemed to add premium subscription time to one or more CodeCombat accounts."
# purchase_code2: "Each CodeCombat account can only redeem a particular Subscription Code once."
# purchase_code3: "Subscription Code months will be added to the end of any existing subscription on the account."
# users: "Users"
# months: "Months"
# purchase_total: "Total"
# purchase_button: "Submit Purchase"
# your_codes: "Your Codes"
# redeem_codes: "Redeem a Subscription Code"
# prepaid_code: "Prepaid Code"
# lookup_code: "Lookup prepaid code"
# apply_account: "Apply to your account"
# copy_link: "You can copy the code's link and send it to someone."
# quantity: "Quantity"
# redeemed: "Redeemed"
# no_codes: "No codes yet!"
loading_error:
could_not_load: "Błąd podczas ładowania danych z serwera"
connection_failure: "Błąd połączenia."
unauthorized: "Musisz być zalogowany. Masz może wyłączone ciasteczka?"
forbidden: "Brak autoryzacji."
not_found: "Nie znaleziono."
not_allowed: "Metoda nie dozwolona."
timeout: "Serwer nie odpowiada."
conflict: "Błąd zasobów."
bad_input: "Złe dane wejściowe."
server_error: "Błąd serwera."
unknown: "Nieznany błąd."
# error: "ERROR"
resources:
sessions: "Sesje"
your_sessions: "Twoje sesje"
level: "Poziom"
# social_network_apis: "Social Network APIs"
# facebook_status: "Facebook Status"
# facebook_friends: "Facebook Friends"
# facebook_friend_sessions: "Facebook Friend Sessions"
# gplus_friends: "G+ Friends"
# gplus_friend_sessions: "G+ Friend Sessions"
# leaderboard: "Leaderboard"
# user_schema: "User Schema"
user_profile: "Profil użytkownika"
patch: "Łatka"
patches: "Łatki"
patched_model: "Dokument źródłowy"
model: "Model"
# system: "System"
# systems: "Systems"
component: "Komponent"
components: "Komponenty"
thang: "Obiekt"
thangs: "Obiekty"
# level_session: "Your Session"
# opponent_session: "Opponent Session"
article: "Artykuł"
user_names: "PI:NAME:<NAME>END_PI"
thang_names: "Nazwy obiektów"
files: "Pliki"
top_simulators: "Najlepsi symulatorzy"
source_document: "Dokument źródłowy"
document: "Dokument"
# sprite_sheet: "Sprite Sheet"
employers: "PrPI:NAME:<NAME>END_PI"
candidates: "KPI:NAME:<NAME>END_PI"
# candidate_sessions: "Candidate Sessions"
# user_remark: "User Remark"
# user_remarks: "User Remarks"
versions: "Wersje"
items: "Przedmioty"
hero: "Bohater"
heroes: "Bohaterowie"
achievement: "Osiągnięcie"
# clas: "CLAs"
play_counts: "Liczba gier"
feedback: "Wsparcie"
payment_info: "Info o płatnościach"
campaigns: "Kampanie"
poll: "Ankieta"
user_polls_record: "Historia oddanych głosów"
concepts:
advanced_strings: "Zaawansowane napisy"
algorithms: "Algorytmy"
arguments: "Argumenty"
arithmetic: "Arytmetyka"
arrays: "Tablice"
basic_syntax: "Podstawy składni"
boolean_logic: "Algebra Boole'a"
break_statements: "Klauzula 'break'"
classes: "Klasy"
# continue_statements: "Continue Statements"
for_loops: "Pętle 'for'"
functions: "Funkcje"
# graphics: "Graphics"
if_statements: "Wyrażenia warunkowe"
input_handling: "Zarządzanie wejściami"
math_operations: "Operacje matematyczne"
object_literals: "Operacje na obiektach"
# parameters: "Parameters"
strings: "Ciągi znaków"
variables: "Zmienne"
vectors: "Wektory"
while_loops: "Pętle"
recursion: "Rekurencja"
delta:
added: "Dodano"
modified: "Zmieniono"
not_modified: "Nie zmianiono"
deleted: "Usunięto"
moved_index: "Przesunięto Index"
# text_diff: "Text Diff"
# merge_conflict_with: "MERGE CONFLICT WITH"
no_changes: "Brak zmian"
multiplayer:
multiplayer_title: "Ustawienia multiplayer" # We'll be changing this around significantly soon. Until then, it's not important to translate.
multiplayer_toggle: "Aktywuj multiplayer"
multiplayer_toggle_description: "Pozwól innym dołączyć do twojej gry."
multiplayer_link_description: "Przekaż ten link, jeśli chcesz, by ktoś do ciebie dołączył."
multiplayer_hint_label: "Podpowiedź:"
multiplayer_hint: "Kliknij link by zaznaczyć wszystko, potem wciśnij Cmd-C lub Ctrl-C by skopiować ten link."
multiplayer_coming_soon: "Wkrótce więcej opcji multiplayer"
multiplayer_sign_in_leaderboard: "Zaloguj się lub zarejestruj by umieścić wynik na tablicy wyników."
legal:
page_title: "Nota prawna"
opensource_intro: "CodeCombat jest całkowicie darmowe i całkowicie open source."
opensource_description_prefix: "Zajrzyj na "
github_url: "nasz GitHub"
opensource_description_center: "i pomóż, jeśli tylko masz ochotę! CodeCombat bazuje na dziesiątkach projektów open source - kochamy je wszystkie. Wpadnij na "
archmage_wiki_url: "naszą wiki dla Arcymagów"
opensource_description_suffix: ", by zobaczyć listę oprogramowania, dzięki któremu niniejsza gra może istnieć."
practices_title: "Ludzkim językiem"
practices_description: "Oto nasze obietnice wobec ciebie, gracza, wyrażone po polsku, bez prawniczego żargonu."
privacy_title: "Prywatność"
privacy_description: "Nie sprzedamy żadnej z Twoich prywatnych informacji."
security_title: "Bezpieczeństwo"
security_description: "Z całych sił staramy się zabezpieczyć twoje prywatne informacje. Jako że jesteśmy projektem open source, każdy może sprawdzić i ulepszyć nasz system zabezpieczeń."
email_title: "E-mail"
email_description_prefix: "Nie będziemy nękać cię spamem. Poprzez"
email_settings_url: "twoje ustawienia e-mail"
email_description_suffix: "lub poprzez linki w e-mailach, które wysyłamy, możesz zmienić swoje ustawienia i w prosty sposób wypisać się z subskrypcji w dowolnym momencie."
cost_title: "Koszty"
cost_description: "W tym momencie CodeCombat jest w stu procentach darmowe! Jednym z naszych głównych celów jest, by utrzymać taki stan rzeczy, aby jak najwięcej ludzi miało dostęp do gry, bez względu na ich zasobność. Jeśli nadejdą gorsze dni, dopuszczamy możliwość wprowadzenia płatnych subskrypcji lub pobierania opłat za część zawartości, ale wolelibyśmy, by tak się nie stało. Przy odrobinie szczęścia, uda nam się podtrzymać obecną sytuację dzięki:"
copyrights_title: "Prawa autorskie i licencje"
contributor_title: "Umowa licencyjna dla współtwórców (CLA)"
contributor_description_prefix: "Wszyscy współtwórcy, zarówno ci ze strony jak i ci z GitHuba, podlegają naszemu"
cla_url: "CLA"
contributor_description_suffix: ", na które powinieneś wyrazić zgodę przed dodaniem swojego wkładu."
code_title: "Kod - MIT"
code_description_prefix: "Całość kodu posiadanego przez CodeCombat lub hostowanego na codecombat.com, zarówno w repozytorium GitHub, jak i bazie codecombat.com, podlega licencji"
mit_license_url: "Licencja MIT"
code_description_suffix: "Zawiera się w tym całość kodu w systemach i komponentach, które są udostępnione przez CodeCombat w celu tworzenia poziomów."
art_title: "Grafika/muzyka - Creative Commons "
art_description_prefix: "Całość ogólnej treści dostępna jest pod licencją"
cc_license_url: "Międzynarodowa Licencja Creative Commons Attribution 4.0"
art_description_suffix: "Zawartość ogólna to wszystko, co zostało publicznie udostępnione przez CodeCombat w celu tworzenia poziomów. Wchodzą w to:"
art_music: "Muzyka"
art_sound: "Dźwięki"
art_artwork: "Artworki"
art_sprites: "Sprite'y"
art_other: "Dowolne inne prace niezwiązane z kodem, które są dostępne podczas tworzenia poziomów."
art_access: "Obecnie nie ma uniwersalnego, prostego sposobu, by pozyskać te zasoby. Możesz wejść w ich posiadanie poprzez URL-e, z których korzysta strona, skontaktować się z nami w celu uzyskania pomocy bądź pomóc nam w ulepszeniu strony, aby zasoby te stały się łatwiej dostępne."
art_paragraph_1: "W celu uznania autorstwa, wymień z nazwy i podaj link do codecombat.com w pobliżu miejsca, gdzie znajduje się użyty zasób bądź w miejscu odpowiednim dla twojego medium. Na przykład:"
use_list_1: "W przypadku użycia w filmie lub innej grze, zawrzyj codecombat.com w napisach końcowych."
use_list_2: "W przypadku użycia na stronie internetowej, zawrzyj link w pobliżu miejsca użycia, na przykład po obrazkiem lub na ogólnej stronie poświęconej uznaniu twórców, gdzie możesz również wspomnieć o innych pracach licencjonowanych przy użyciu Creative Commons oraz oprogramowaniu open source używanym na stronie. Coś, co samo w sobie jednoznacznie odnosi się do CodeCombat, na przykład wpis na blogu dotyczący CodeCombat, nie wymaga już dodatkowego uznania autorstwa."
art_paragraph_2: "Jeśli użyte przez ciebie zasoby zostały stworzone nie przez CodeCombat, ale jednego z naszych użytkowników, uznanie autorstwa należy się jemu - postępuj wówczas zgodnie z zasadami uznania autorstwa dostarczonymi wraz z rzeczonym zasobem (o ile takowe występują)."
rights_title: "Prawa zastrzeżone"
rights_desc: "Wszelkie prawa są zastrzeżone dla poziomów jako takich. Zawierają się w tym:"
rights_scripts: "Skrypty"
rights_unit: "Konfiguracje jednostek"
rights_description: "Opisy"
rights_writings: "Teksty"
rights_media: "Multimedia (dźwięki, muzyka) i jakiekolwiek inne typy prac i zasobów stworzonych specjalnie dla danego poziomu, które nie zostały publicznie udostępnione do tworzenia poziomów."
rights_clarification: "Gwoli wyjaśnienia, wszystko, co jest dostępne w Edytorze Poziomów w celu tworzenia nowych poziomów, podlega licencji CC, podczas gdy zasoby stworzone w Edytorze Poziomów lub przesłane w toku tworzenia poziomu - nie."
nutshell_title: "W skrócie"
nutshell_description: "Wszelkie zasoby, które dostarczamy w Edytorze Poziomów są darmowe w użyciu w jakikolwiek sposób w celu tworzenia poziomów. Jednocześnie, zastrzegamy sobie prawo do ograniczenia rozpowszechniania poziomów (stworzonych przez codecombat.com) jako takich, aby mogła być za nie w przyszłości pobierana opłata, jeśli dojdzie do takiej konieczności."
canonical: "Angielska wersja tego dokumentu jest ostateczna, kanoniczną wersją. Jeśli zachodzą jakieś rozbieżności pomiędzy tłumaczeniami, dokument anglojęzyczny ma pierwszeństwo."
# ladder_prizes:
# title: "Tournament Prizes" # This section was for an old tournament and doesn't need new translations now.
# blurb_1: "These prizes will be awarded according to"
# blurb_2: "the tournament rules"
# blurb_3: "to the top human and ogre players."
# blurb_4: "Two teams means double the prizes!"
# blurb_5: "(There will be two first place winners, two second-place winners, etc.)"
# rank: "Rank"
# prizes: "Prizes"
# total_value: "Total Value"
# in_cash: "in cash"
# custom_wizard: "Custom CodeCombat Wizard"
# custom_avatar: "Custom CodeCombat avatar"
# heap: "for six months of \"Startup\" access"
# credits: "credits"
# one_month_coupon: "coupon: choose either Rails or HTML"
# one_month_discount: "discount, 30% off: choose either Rails or HTML"
# license: "license"
# oreilly: "ebook of your choice"
account_profile:
settings: "Ustawienia" # We are not actively recruiting right now, so there's no need to add new translations for this section.
edit_profile: "Edytuj Profil"
done_editing: "Edycja wykonana"
profile_for_prefix: "Profil "
profile_for_suffix: ""
# featured: "Featured"
# not_featured: "Not Featured"
# looking_for: "Looking for:"
# last_updated: "Last updated:"
contact: "PI:NAME:<NAME>END_PI"
# active: "Looking for interview offers now"
# inactive: "Not looking for offers right now"
# complete: "complete"
next: "Nastepny"
next_city: "miasto?"
next_country: "wybierz kraj."
next_name: "imię?"
# next_short_description: "write a short description."
# next_long_description: "describe your desired position."
# next_skills: "list at least five skills."
# next_work: "chronicle your work history."
# next_education: "recount your educational ordeals."
# next_projects: "show off up to three projects you've worked on."
# next_links: "add any personal or social links."
# next_photo: "add an optional professional photo."
# next_active: "mark yourself open to offers to show up in searches."
# example_blog: "Blog"
# example_personal_site: "Personal Site"
# links_header: "Personal Links"
# links_blurb: "Link any other sites or profiles you want to highlight, like your GitHub, your LinkedIn, or your blog."
# links_name: "Link Name"
# links_name_help: "What are you linking to?"
# links_link_blurb: "Link URL"
# basics_header: "Update basic info"
# basics_active: "Open to Offers"
# basics_active_help: "Want interview offers right now?"
# basics_job_title: "Desired Job Title"
# basics_job_title_help: "What role are you looking for?"
# basics_city: "City"
# basics_city_help: "City you want to work in (or live in now)."
# basics_country: "Country"
# basics_country_help: "Country you want to work in (or live in now)."
# basics_visa: "US Work Status"
# basics_visa_help: "Are you authorized to work in the US, or do you need visa sponsorship? (If you live in Canada or Australia, mark authorized.)"
# basics_looking_for: "Looking For"
# basics_looking_for_full_time: "Full-time"
# basics_looking_for_part_time: "Part-time"
# basics_looking_for_remote: "Remote"
# basics_looking_for_contracting: "Contracting"
# basics_looking_for_internship: "Internship"
# basics_looking_for_help: "What kind of developer position do you want?"
# name_header: "Fill in your name"
# name_anonymous: "PI:NAME:<NAME>END_PI"
# name_help: "Name you want employers to see, like 'PI:NAME:<NAME>END_PI'."
# short_description_header: "Write a short description of yourself"
# short_description_blurb: "Add a tagline to help an employer quickly learn more about you."
# short_description: "Tagline"
# short_description_help: "Who are you, and what are you looking for? 140 characters max."
# skills_header: "Skills"
# skills_help: "Tag relevant developer skills in order of proficiency."
# long_description_header: "Describe your desired position"
# long_description_blurb: "Tell employers how awesome you are and what role you want."
# long_description: "Self Description"
# long_description_help: "Describe yourself to potential employers. Keep it short and to the point. We recommend outlining the position that would most interest you. Tasteful markdown okay; 600 characters max."
# work_experience: "Work Experience"
# work_header: "Chronicle your work history"
# work_years: "Years of Experience"
# work_years_help: "How many years of professional experience (getting paid) developing software do you have?"
# work_blurb: "List your relevant work experience, most recent first."
# work_employer: "Employer"
# work_employer_help: "Name of your employer."
# work_role: "Job Title"
# work_role_help: "What was your job title or role?"
# work_duration: "Duration"
# work_duration_help: "When did you hold this gig?"
# work_description: "Description"
# work_description_help: "What did you do there? (140 chars; optional)"
# education: "Education"
# education_header: "Recount your academic ordeals"
# education_blurb: "List your academic ordeals."
# education_school: "School"
# education_school_help: "Name of your school."
# education_degree: "Degree"
# education_degree_help: "What was your degree and field of study?"
# education_duration: "Dates"
# education_duration_help: "When?"
# education_description: "Description"
# education_description_help: "Highlight anything about this educational experience. (140 chars; optional)"
# our_notes: "CodeCombat's Notes"
# remarks: "Remarks"
# projects: "Projects"
# projects_header: "Add 3 projects"
# projects_header_2: "Projects (Top 3)"
# projects_blurb: "Highlight your projects to amaze employers."
# project_name: "Project Name"
# project_name_help: "What was the project called?"
# project_description: "Description"
# project_description_help: "Briefly describe the project."
# project_picture: "Picture"
# project_picture_help: "Upload a 230x115px or larger image showing off the project."
# project_link: "Link"
# project_link_help: "Link to the project."
# player_code: "Player Code"
# employers:
# deprecation_warning_title: "Sorry, CodeCombat is not recruiting right now."
# deprecation_warning: "We are focusing on beginner levels instead of finding expert developers for the time being."
# hire_developers_not_credentials: "Hire developers, not credentials." # We are not actively recruiting right now, so there's no need to add new translations for the rest of this section.
# get_started: "Get Started"
# already_screened: "We've already technically screened all our candidates"
# filter_further: ", but you can also filter further:"
# filter_visa: "Visa"
# filter_visa_yes: "US Authorized"
# filter_visa_no: "Not Authorized"
# filter_education_top: "Top School"
# filter_education_other: "Other"
# filter_role_web_developer: "Web Developer"
# filter_role_software_developer: "Software Developer"
# filter_role_mobile_developer: "Mobile Developer"
# filter_experience: "Experience"
# filter_experience_senior: "Senior"
# filter_experience_junior: "Junior"
# filter_experience_recent_grad: "Recent Grad"
# filter_experience_student: "College Student"
# filter_results: "results"
# start_hiring: "Start hiring."
# reasons: "Three reasons you should hire through us:"
# everyone_looking: "Everyone here is looking for their next opportunity."
# everyone_looking_blurb: "Forget about 20% LinkedIn InMail response rates. Everyone that we list on this site wants to find their next position and will respond to your request for an introduction."
# weeding: "Sit back; we've done the weeding for you."
# weeding_blurb: "Every player that we list has been screened for technical ability. We also perform phone screens for select candidates and make notes on their profiles to save you time."
# pass_screen: "They will pass your technical screen."
# pass_screen_blurb: "Review each candidate's code before reaching out. One employer found that 5x as many of our devs passed their technical screen than hiring from Hacker News."
# make_hiring_easier: "Make my hiring easier, please."
# what: "What is CodeCombat?"
# what_blurb: "CodeCombat is a multiplayer browser programming game. Players write code to control their forces in battle against other developers. Our players have experience with all major tech stacks."
# cost: "How much do we charge?"
# cost_blurb: "We charge 15% of first year's salary and offer a 100% money back guarantee for 90 days. We don't charge for candidates who are already actively being interviewed at your company."
# candidate_name: "Name"
# candidate_location: "Location"
# candidate_looking_for: "Looking For"
# candidate_role: "Role"
# candidate_top_skills: "Top Skills"
# candidate_years_experience: "Yrs Exp"
# candidate_last_updated: "Last Updated"
# candidate_who: "Who"
# featured_developers: "Featured Developers"
# other_developers: "Other Developers"
# inactive_developers: "Inactive Developers"
admin:
# av_espionage: "Espionage" # Really not important to translate /admin controls.
# av_espionage_placeholder: "Email or username"
# av_usersearch: "User Search"
# av_usersearch_placeholder: "Email, username, name, whatever"
# av_usersearch_search: "Search"
av_title: "Panel administracyjny"
av_entities_sub_title: "Podmioty"
av_entities_users_url: "Użytkownicy"
av_entities_active_instances_url: "Aktywne podmioty"
# av_entities_employer_list_url: "Employer List"
# av_entities_candidates_list_url: "Candidate List"
# av_entities_user_code_problems_list_url: "User Code Problems List"
av_other_sub_title: "Inne"
av_other_debug_base_url: "Baza (do debuggingu base.jade)"
u_title: "Lista użytkowników"
# ucp_title: "User Code Problems"
lg_title: "Ostatnie gry"
# clas: "CLAs"
|
[
{
"context": "\n variables = ko.observableArray()\n\n randomKey = Math.random()\n\n register = (variable) ->\n variable.refere",
"end": 352,
"score": 0.9921773076057434,
"start": 341,
"tag": "KEY",
"value": "Math.random"
}
] | app/assets/javascripts/models/data/variable.js.coffee | evenstensberg/earthdata-search | 1 | ns = @edsc.models.data
ns.Variable = do (ko
DetailsModel = @edsc.models.DetailsModel
extend=jQuery.extend
ajax = @edsc.util.xhr.ajax
dateUtil = @edsc.util.date
config = @edsc.config
) ->
variables = ko.observableArray()
randomKey = Math.random()
register = (variable) ->
variable.reference()
variables.push(variable)
variable
class Variable extends DetailsModel
@awaitDatasources: (variables, callback) ->
callback(variables)
@findOrCreate: (jsonData, query) ->
id = jsonData.meta['concept-id']
for variable in variables()
if variable.meta()['concept-id'] == id
if (jsonData.umm?.Name? && !variable.hasAtomData())
variable.fromJson(jsonData)
return variable.reference()
register(new Variable(jsonData, query, randomKey))
constructor: (jsonData, @query, inKey) ->
throw "Variables should not be constructed directly" unless inKey == randomKey
@granuleCount = ko.observable(0)
@hasAtomData = ko.observable(false)
@fromJson(jsonData)
notifyRenderers: (action) ->
@_loadRenderers()
if @_loading
@_pendingRenderActions.push(action)
else
for renderer in @_renderers
renderer[action]?()
displayName: ->
@umm()?['LongName'] || @umm()?['Name']
fromJson: (jsonObj) ->
@json = jsonObj
@hasAtomData(jsonObj.umm?.Name?)
@_setObservable('meta', jsonObj)
@_setObservable('umm', jsonObj)
@_setObservable('associations', jsonObj)
for own key, value of jsonObj
this[key] = value unless ko.isObservable(this[key])
# @_loadDatasource()
_setObservable: (prop, jsonObj) =>
this[prop] ?= ko.observable(undefined)
this[prop](jsonObj[prop] ? this[prop]())
exports = Variable
| 167861 | ns = @edsc.models.data
ns.Variable = do (ko
DetailsModel = @edsc.models.DetailsModel
extend=jQuery.extend
ajax = @edsc.util.xhr.ajax
dateUtil = @edsc.util.date
config = @edsc.config
) ->
variables = ko.observableArray()
randomKey = <KEY>()
register = (variable) ->
variable.reference()
variables.push(variable)
variable
class Variable extends DetailsModel
@awaitDatasources: (variables, callback) ->
callback(variables)
@findOrCreate: (jsonData, query) ->
id = jsonData.meta['concept-id']
for variable in variables()
if variable.meta()['concept-id'] == id
if (jsonData.umm?.Name? && !variable.hasAtomData())
variable.fromJson(jsonData)
return variable.reference()
register(new Variable(jsonData, query, randomKey))
constructor: (jsonData, @query, inKey) ->
throw "Variables should not be constructed directly" unless inKey == randomKey
@granuleCount = ko.observable(0)
@hasAtomData = ko.observable(false)
@fromJson(jsonData)
notifyRenderers: (action) ->
@_loadRenderers()
if @_loading
@_pendingRenderActions.push(action)
else
for renderer in @_renderers
renderer[action]?()
displayName: ->
@umm()?['LongName'] || @umm()?['Name']
fromJson: (jsonObj) ->
@json = jsonObj
@hasAtomData(jsonObj.umm?.Name?)
@_setObservable('meta', jsonObj)
@_setObservable('umm', jsonObj)
@_setObservable('associations', jsonObj)
for own key, value of jsonObj
this[key] = value unless ko.isObservable(this[key])
# @_loadDatasource()
_setObservable: (prop, jsonObj) =>
this[prop] ?= ko.observable(undefined)
this[prop](jsonObj[prop] ? this[prop]())
exports = Variable
| true | ns = @edsc.models.data
ns.Variable = do (ko
DetailsModel = @edsc.models.DetailsModel
extend=jQuery.extend
ajax = @edsc.util.xhr.ajax
dateUtil = @edsc.util.date
config = @edsc.config
) ->
variables = ko.observableArray()
randomKey = PI:KEY:<KEY>END_PI()
register = (variable) ->
variable.reference()
variables.push(variable)
variable
class Variable extends DetailsModel
@awaitDatasources: (variables, callback) ->
callback(variables)
@findOrCreate: (jsonData, query) ->
id = jsonData.meta['concept-id']
for variable in variables()
if variable.meta()['concept-id'] == id
if (jsonData.umm?.Name? && !variable.hasAtomData())
variable.fromJson(jsonData)
return variable.reference()
register(new Variable(jsonData, query, randomKey))
constructor: (jsonData, @query, inKey) ->
throw "Variables should not be constructed directly" unless inKey == randomKey
@granuleCount = ko.observable(0)
@hasAtomData = ko.observable(false)
@fromJson(jsonData)
notifyRenderers: (action) ->
@_loadRenderers()
if @_loading
@_pendingRenderActions.push(action)
else
for renderer in @_renderers
renderer[action]?()
displayName: ->
@umm()?['LongName'] || @umm()?['Name']
fromJson: (jsonObj) ->
@json = jsonObj
@hasAtomData(jsonObj.umm?.Name?)
@_setObservable('meta', jsonObj)
@_setObservable('umm', jsonObj)
@_setObservable('associations', jsonObj)
for own key, value of jsonObj
this[key] = value unless ko.isObservable(this[key])
# @_loadDatasource()
_setObservable: (prop, jsonObj) =>
this[prop] ?= ko.observable(undefined)
this[prop](jsonObj[prop] ? this[prop]())
exports = Variable
|
[
{
"context": "down 'emphasis/simple', \"That's **all** to say. _(Alex)_\", null, true, cb\n\n it \"should make examples ",
"end": 366,
"score": 0.8890059590339661,
"start": 362,
"tag": "NAME",
"value": "Alex"
}
] | test/mocha/element/emphasis.coffee | alinex/node-report | 1 | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
test = require '../test'
async = require 'async'
Report = require '../../../src'
before (cb) -> Report.init cb
describe "emphasis", ->
describe "examples", ->
@timeout 30000
it "should make examples", (cb) ->
test.markdown 'emphasis/simple', "That's **all** to say. _(Alex)_", null, true, cb
it "should make examples with combined", (cb) ->
test.markdown 'emphasis/combined', """
Only italic _here_\\
Only strong **here**\\
And both **_here_**
You _can **also**_ put them into each other.
""", null, true, cb
describe "api", ->
it "should create emphasis in paragraph", (cb) ->
# create report
report = new Report()
report.paragraph true
report.emphasis 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create emphasis in multiple steps", (cb) ->
# create report
report = new Report()
report.paragraph true
report.emphasis true
report.text 'foo'
report.emphasis false
report.paragraph false
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create emphasis in paragraph (shorthand call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.em 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create emphasis in paragraph (alternative call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.italic 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should fail emphasis if not in inline element", (cb) ->
# create report
report = new Report()
expect(-> report.emphasis 'code').to.throw Error
cb()
it "should do nothing without content in emphasis", (cb) ->
# create report
report = new Report()
report.paragraph true
report.emphasis()
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in paragraph", (cb) ->
# create report
report = new Report()
report.paragraph true
report.strong 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in multiple steps", (cb) ->
# create report
report = new Report()
report.paragraph true
report.strong true
report.text 'foo'
report.strong false
report.paragraph false
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in paragraph (shorthand call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.b 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in paragraph (alternative call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.bold 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should fail strong if not in inline element", (cb) ->
# create report
report = new Report()
expect(-> report.strong 'code').to.throw Error
cb()
it "should do nothing without content in strong", (cb) ->
# create report
report = new Report()
report.paragraph true
report.strong()
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
| 172397 | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
test = require '../test'
async = require 'async'
Report = require '../../../src'
before (cb) -> Report.init cb
describe "emphasis", ->
describe "examples", ->
@timeout 30000
it "should make examples", (cb) ->
test.markdown 'emphasis/simple', "That's **all** to say. _(<NAME>)_", null, true, cb
it "should make examples with combined", (cb) ->
test.markdown 'emphasis/combined', """
Only italic _here_\\
Only strong **here**\\
And both **_here_**
You _can **also**_ put them into each other.
""", null, true, cb
describe "api", ->
it "should create emphasis in paragraph", (cb) ->
# create report
report = new Report()
report.paragraph true
report.emphasis 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create emphasis in multiple steps", (cb) ->
# create report
report = new Report()
report.paragraph true
report.emphasis true
report.text 'foo'
report.emphasis false
report.paragraph false
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create emphasis in paragraph (shorthand call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.em 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create emphasis in paragraph (alternative call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.italic 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should fail emphasis if not in inline element", (cb) ->
# create report
report = new Report()
expect(-> report.emphasis 'code').to.throw Error
cb()
it "should do nothing without content in emphasis", (cb) ->
# create report
report = new Report()
report.paragraph true
report.emphasis()
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in paragraph", (cb) ->
# create report
report = new Report()
report.paragraph true
report.strong 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in multiple steps", (cb) ->
# create report
report = new Report()
report.paragraph true
report.strong true
report.text 'foo'
report.strong false
report.paragraph false
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in paragraph (shorthand call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.b 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in paragraph (alternative call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.bold 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should fail strong if not in inline element", (cb) ->
# create report
report = new Report()
expect(-> report.strong 'code').to.throw Error
cb()
it "should do nothing without content in strong", (cb) ->
# create report
report = new Report()
report.paragraph true
report.strong()
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
| true | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
test = require '../test'
async = require 'async'
Report = require '../../../src'
before (cb) -> Report.init cb
describe "emphasis", ->
describe "examples", ->
@timeout 30000
it "should make examples", (cb) ->
test.markdown 'emphasis/simple', "That's **all** to say. _(PI:NAME:<NAME>END_PI)_", null, true, cb
it "should make examples with combined", (cb) ->
test.markdown 'emphasis/combined', """
Only italic _here_\\
Only strong **here**\\
And both **_here_**
You _can **also**_ put them into each other.
""", null, true, cb
describe "api", ->
it "should create emphasis in paragraph", (cb) ->
# create report
report = new Report()
report.paragraph true
report.emphasis 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create emphasis in multiple steps", (cb) ->
# create report
report = new Report()
report.paragraph true
report.emphasis true
report.text 'foo'
report.emphasis false
report.paragraph false
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create emphasis in paragraph (shorthand call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.em 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create emphasis in paragraph (alternative call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.italic 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'emphasis', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'emphasis', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should fail emphasis if not in inline element", (cb) ->
# create report
report = new Report()
expect(-> report.emphasis 'code').to.throw Error
cb()
it "should do nothing without content in emphasis", (cb) ->
# create report
report = new Report()
report.paragraph true
report.emphasis()
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in paragraph", (cb) ->
# create report
report = new Report()
report.paragraph true
report.strong 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in multiple steps", (cb) ->
# create report
report = new Report()
report.paragraph true
report.strong true
report.text 'foo'
report.strong false
report.paragraph false
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in paragraph (shorthand call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.b 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should create strong in paragraph (alternative call)", (cb) ->
# create report
report = new Report()
report.paragraph true
report.bold 'foo'
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'strong', nesting: 1}
{type: 'text', content: 'foo'}
{type: 'strong', nesting: -1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
it "should fail strong if not in inline element", (cb) ->
# create report
report = new Report()
expect(-> report.strong 'code').to.throw Error
cb()
it "should do nothing without content in strong", (cb) ->
# create report
report = new Report()
report.paragraph true
report.strong()
# check it
test.report null, report, [
{type: 'document', nesting: 1}
{type: 'paragraph', nesting: 1}
{type: 'paragraph', nesting: -1}
{type: 'document', nesting: -1}
], null, cb
|
[
{
"context": "ingify({\n file : metadata.file\n key : new Buffer(metadata.key).toString('base64')\n nonce : new",
"end": 528,
"score": 0.9190530776977539,
"start": 517,
"tag": "KEY",
"value": "new Buffer("
},
{
"context": "etadata.file\n key : new Buffer(metadata.key).toString('base64')\n nonce : new Buffer(metadata.nonce",
"end": 550,
"score": 0.9457582831382751,
"start": 542,
"tag": "KEY",
"value": "toString"
},
{
"context": " key : new Buffer(metadata.key).toString('base64')\n nonce : new Buffer(metadata.nonce).toStri",
"end": 558,
"score": 0.8953136205673218,
"start": 556,
"tag": "KEY",
"value": "64"
}
] | src/scrambler.coffee | themadcreator/scrmblr | 0 | fs = require 'fs'
path = require 'path'
nacl = require('js-nacl').instantiate()
sodium = require 'libsodium-wrappers'
chunkThrough = require './chunk-through'
xorThrough = require './xor-through'
takeThrough = require './take-through'
class Scrambler
@DEFAULT_CHUNK_SIZE : 512
@FORMAT_PREFIX : new Buffer('SCRMBLR', 'ASCII')
constructor : (@context) ->
serializeHeader : (metadata) ->
serializedMetadata = JSON.stringify({
file : metadata.file
key : new Buffer(metadata.key).toString('base64')
nonce : new Buffer(metadata.nonce).toString('base64')
chunk : metadata.chunk
})
sealedMetadata = sodium.crypto_box_seal(nacl.encode_utf8(serializedMetadata), @context.boxPk)
fields = [
Scrambler.FORMAT_PREFIX
new Buffer(Uint32Array.of(sealedMetadata.byteLength).buffer)
new Buffer(sealedMetadata.buffer)
]
return Buffer.concat(fields)
parseHeader : (buffer) ->
if not buffer.slice(0, Scrambler.FORMAT_PREFIX.length).equals(Scrambler.FORMAT_PREFIX)
throw new Error("not a scrmblr file")
buffer = buffer.slice(Scrambler.FORMAT_PREFIX.length)
sealedMetadataLength = Uint32Array.from(buffer)[0]
buffer = buffer.slice(4)
serializedMetadata = nacl.decode_utf8(sodium.crypto_box_seal_open(buffer, @context.boxPk, @context.boxSk))
metadata = JSON.parse(serializedMetadata)
return {
file : metadata.file
key : Uint8Array.from(new Buffer(metadata.key, 'base64'))
nonce : Uint8Array.from(new Buffer(metadata.nonce, 'base64'))
chunk : metadata.chunk
}
extractHeader : (input, metadataCallback) ->
x = input.pipe(takeThrough(Scrambler.FORMAT_PREFIX.length, (prefix) ->
if not prefix.equals(Scrambler.FORMAT_PREFIX) then throw new Error("not a scrmblr file")
)).pipe(takeThrough(4, (b) =>
sealedMetadataByteLength = Uint32Array.from(b)[0]
remainder = x.pipe(takeThrough(sealedMetadataByteLength, (sealedMetadata) =>
serializedMetadata = nacl.decode_utf8(sodium.crypto_box_seal_open(Uint8Array.from(sealedMetadata), @context.boxPk, @context.boxSk))
metadata = JSON.parse(serializedMetadata)
metadataCallback(remainder, {
file : metadata.file
key : Uint8Array.from(new Buffer(metadata.key, 'base64'))
nonce : Uint8Array.from(new Buffer(metadata.nonce, 'base64'))
chunk : metadata.chunk
})
))
))
return
scramble : (filePath) ->
# generate metadata
metadata =
file : path.basename(filePath)
key : nacl.random_bytes(nacl.crypto_stream_KEYBYTES)
nonce : nacl.crypto_stream_random_nonce()
chunk : Scrambler.DEFAULT_CHUNK_SIZE
name = new Buffer(nacl.random_bytes(16)).toString('hex')
output = fs.createWriteStream("#{name}.scrmblr")
output.write(@serializeHeader(metadata))
input = fs.createReadStream(filePath)
input
.pipe(chunkThrough(metadata.chunk))
.pipe(xorThrough(metadata.nonce, metadata.key))
.pipe(output)
unscramble : (filePath) ->
@extractHeader(fs.createReadStream(filePath), (remainder, metadata) ->
output = fs.createWriteStream('unscrambled.bin') # use metadata.file
remainder
.pipe(chunkThrough(metadata.chunk))
.pipe(xorThrough(metadata.nonce, metadata.key))
.pipe(output)
)
module.exports = Scrambler
| 92659 | fs = require 'fs'
path = require 'path'
nacl = require('js-nacl').instantiate()
sodium = require 'libsodium-wrappers'
chunkThrough = require './chunk-through'
xorThrough = require './xor-through'
takeThrough = require './take-through'
class Scrambler
@DEFAULT_CHUNK_SIZE : 512
@FORMAT_PREFIX : new Buffer('SCRMBLR', 'ASCII')
constructor : (@context) ->
serializeHeader : (metadata) ->
serializedMetadata = JSON.stringify({
file : metadata.file
key : <KEY>metadata.key).<KEY>('base<KEY>')
nonce : new Buffer(metadata.nonce).toString('base64')
chunk : metadata.chunk
})
sealedMetadata = sodium.crypto_box_seal(nacl.encode_utf8(serializedMetadata), @context.boxPk)
fields = [
Scrambler.FORMAT_PREFIX
new Buffer(Uint32Array.of(sealedMetadata.byteLength).buffer)
new Buffer(sealedMetadata.buffer)
]
return Buffer.concat(fields)
parseHeader : (buffer) ->
if not buffer.slice(0, Scrambler.FORMAT_PREFIX.length).equals(Scrambler.FORMAT_PREFIX)
throw new Error("not a scrmblr file")
buffer = buffer.slice(Scrambler.FORMAT_PREFIX.length)
sealedMetadataLength = Uint32Array.from(buffer)[0]
buffer = buffer.slice(4)
serializedMetadata = nacl.decode_utf8(sodium.crypto_box_seal_open(buffer, @context.boxPk, @context.boxSk))
metadata = JSON.parse(serializedMetadata)
return {
file : metadata.file
key : Uint8Array.from(new Buffer(metadata.key, 'base64'))
nonce : Uint8Array.from(new Buffer(metadata.nonce, 'base64'))
chunk : metadata.chunk
}
extractHeader : (input, metadataCallback) ->
x = input.pipe(takeThrough(Scrambler.FORMAT_PREFIX.length, (prefix) ->
if not prefix.equals(Scrambler.FORMAT_PREFIX) then throw new Error("not a scrmblr file")
)).pipe(takeThrough(4, (b) =>
sealedMetadataByteLength = Uint32Array.from(b)[0]
remainder = x.pipe(takeThrough(sealedMetadataByteLength, (sealedMetadata) =>
serializedMetadata = nacl.decode_utf8(sodium.crypto_box_seal_open(Uint8Array.from(sealedMetadata), @context.boxPk, @context.boxSk))
metadata = JSON.parse(serializedMetadata)
metadataCallback(remainder, {
file : metadata.file
key : Uint8Array.from(new Buffer(metadata.key, 'base64'))
nonce : Uint8Array.from(new Buffer(metadata.nonce, 'base64'))
chunk : metadata.chunk
})
))
))
return
scramble : (filePath) ->
# generate metadata
metadata =
file : path.basename(filePath)
key : nacl.random_bytes(nacl.crypto_stream_KEYBYTES)
nonce : nacl.crypto_stream_random_nonce()
chunk : Scrambler.DEFAULT_CHUNK_SIZE
name = new Buffer(nacl.random_bytes(16)).toString('hex')
output = fs.createWriteStream("#{name}.scrmblr")
output.write(@serializeHeader(metadata))
input = fs.createReadStream(filePath)
input
.pipe(chunkThrough(metadata.chunk))
.pipe(xorThrough(metadata.nonce, metadata.key))
.pipe(output)
unscramble : (filePath) ->
@extractHeader(fs.createReadStream(filePath), (remainder, metadata) ->
output = fs.createWriteStream('unscrambled.bin') # use metadata.file
remainder
.pipe(chunkThrough(metadata.chunk))
.pipe(xorThrough(metadata.nonce, metadata.key))
.pipe(output)
)
module.exports = Scrambler
| true | fs = require 'fs'
path = require 'path'
nacl = require('js-nacl').instantiate()
sodium = require 'libsodium-wrappers'
chunkThrough = require './chunk-through'
xorThrough = require './xor-through'
takeThrough = require './take-through'
class Scrambler
@DEFAULT_CHUNK_SIZE : 512
@FORMAT_PREFIX : new Buffer('SCRMBLR', 'ASCII')
constructor : (@context) ->
serializeHeader : (metadata) ->
serializedMetadata = JSON.stringify({
file : metadata.file
key : PI:KEY:<KEY>END_PImetadata.key).PI:KEY:<KEY>END_PI('basePI:KEY:<KEY>END_PI')
nonce : new Buffer(metadata.nonce).toString('base64')
chunk : metadata.chunk
})
sealedMetadata = sodium.crypto_box_seal(nacl.encode_utf8(serializedMetadata), @context.boxPk)
fields = [
Scrambler.FORMAT_PREFIX
new Buffer(Uint32Array.of(sealedMetadata.byteLength).buffer)
new Buffer(sealedMetadata.buffer)
]
return Buffer.concat(fields)
parseHeader : (buffer) ->
if not buffer.slice(0, Scrambler.FORMAT_PREFIX.length).equals(Scrambler.FORMAT_PREFIX)
throw new Error("not a scrmblr file")
buffer = buffer.slice(Scrambler.FORMAT_PREFIX.length)
sealedMetadataLength = Uint32Array.from(buffer)[0]
buffer = buffer.slice(4)
serializedMetadata = nacl.decode_utf8(sodium.crypto_box_seal_open(buffer, @context.boxPk, @context.boxSk))
metadata = JSON.parse(serializedMetadata)
return {
file : metadata.file
key : Uint8Array.from(new Buffer(metadata.key, 'base64'))
nonce : Uint8Array.from(new Buffer(metadata.nonce, 'base64'))
chunk : metadata.chunk
}
extractHeader : (input, metadataCallback) ->
x = input.pipe(takeThrough(Scrambler.FORMAT_PREFIX.length, (prefix) ->
if not prefix.equals(Scrambler.FORMAT_PREFIX) then throw new Error("not a scrmblr file")
)).pipe(takeThrough(4, (b) =>
sealedMetadataByteLength = Uint32Array.from(b)[0]
remainder = x.pipe(takeThrough(sealedMetadataByteLength, (sealedMetadata) =>
serializedMetadata = nacl.decode_utf8(sodium.crypto_box_seal_open(Uint8Array.from(sealedMetadata), @context.boxPk, @context.boxSk))
metadata = JSON.parse(serializedMetadata)
metadataCallback(remainder, {
file : metadata.file
key : Uint8Array.from(new Buffer(metadata.key, 'base64'))
nonce : Uint8Array.from(new Buffer(metadata.nonce, 'base64'))
chunk : metadata.chunk
})
))
))
return
scramble : (filePath) ->
# generate metadata
metadata =
file : path.basename(filePath)
key : nacl.random_bytes(nacl.crypto_stream_KEYBYTES)
nonce : nacl.crypto_stream_random_nonce()
chunk : Scrambler.DEFAULT_CHUNK_SIZE
name = new Buffer(nacl.random_bytes(16)).toString('hex')
output = fs.createWriteStream("#{name}.scrmblr")
output.write(@serializeHeader(metadata))
input = fs.createReadStream(filePath)
input
.pipe(chunkThrough(metadata.chunk))
.pipe(xorThrough(metadata.nonce, metadata.key))
.pipe(output)
unscramble : (filePath) ->
@extractHeader(fs.createReadStream(filePath), (remainder, metadata) ->
output = fs.createWriteStream('unscrambled.bin') # use metadata.file
remainder
.pipe(chunkThrough(metadata.chunk))
.pipe(xorThrough(metadata.nonce, metadata.key))
.pipe(output)
)
module.exports = Scrambler
|
[
{
"context": "is 'values: 0 1 2 3 4 5 6 7 8 9'\n\nobj: {\n name: 'Joe'\n hi: -> \"Hello $@name.\"\n cya: -> \"Hello $@name",
"end": 1746,
"score": 0.9964148998260498,
"start": 1743,
"tag": "NAME",
"value": "Joe"
},
{
"context": "replace('Hello','Goodbye')\n}\nok obj.hi() is \"Hello Joe.\"\nok obj.cya() is \"Goodbye Joe.\"\n\nok \"With ${\"quo",
"end": 1853,
"score": 0.8507941961288452,
"start": 1850,
"tag": "NAME",
"value": "Joe"
},
{
"context": "k \"Hello ${\"${\"${obj[\"name\"]}\" + '!'}\"}\" is 'Hello Joe!'\n\na: 1\nb: 2\nc: 3\nok \"$a$b$c\" is '123'\n\nresult: n",
"end": 2251,
"score": 0.7668595314025879,
"start": 2248,
"tag": "NAME",
"value": "Joe"
}
] | test/test_string_interpolation.coffee | rpl/coffee-script | 1 | hello: 'Hello'
world: 'World'
ok '$hello $world!' is '$hello $world!'
ok '${hello} ${world}!' is '${hello} ${world}!'
ok "$hello $world!" is 'Hello World!'
ok "${hello} ${world}!" is 'Hello World!'
ok "[$hello$world]" is '[HelloWorld]'
ok "[${hello}${world}]" is '[HelloWorld]'
ok "$hello$$world" is 'Hello$World'
ok "${hello}$${world}" is 'Hello$World'
ok "Hello ${ 1 + 2 } World" is 'Hello 3 World'
ok "$hello ${ 1 + 2 } $world" is "Hello 3 World"
[s, t, r, i, n, g]: ['s', 't', 'r', 'i', 'n', 'g']
ok "$s$t$r$i$n$g" is 'string'
ok "${s}${t}${r}${i}${n}${g}" is 'string'
ok "\$s\$t\$r\$i\$n\$g" is '$s$t$r$i$n$g'
ok "\\$s\\$t\\$r\\$i\\$n\\$g" is '\\s\\t\\r\\i\\n\\g'
ok "\${s}\${t}\${r}\${i}\${n}\${g}" is '${s}${t}${r}${i}${n}${g}'
ok "\$string" is '$string'
ok "\${string}" is '${string}'
ok "\$Escaping first" is '$Escaping first'
ok "\${Escaping} first" is '${Escaping} first'
ok "Escaping \$in middle" is 'Escaping $in middle'
ok "Escaping \${in} middle" is 'Escaping ${in} middle'
ok "Escaping \$last" is 'Escaping $last'
ok "Escaping \${last}" is 'Escaping ${last}'
ok "$$" is '$$'
ok "${}" is ''
ok "${}A${} ${} ${}B${}" is 'A B'
ok "\\\\\$$" is '\\\\\$$'
ok "\\\${}" is '\\${}'
ok "I won $20 last night." is 'I won $20 last night.'
ok "I won $${20} last night." is 'I won $20 last night.'
ok "I won $#20 last night." is 'I won $#20 last night.'
ok "I won $${'#20'} last night." is 'I won $#20 last night.'
ok "${hello + world}" is 'HelloWorld'
ok "${hello + ' ' + world + '!'}" is 'Hello World!'
list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ok "values: ${list.join(', ')}, length: ${list.length}." is 'values: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, length: 10.'
ok "values: ${list.join ' '}" is 'values: 0 1 2 3 4 5 6 7 8 9'
obj: {
name: 'Joe'
hi: -> "Hello $@name."
cya: -> "Hello $@name.".replace('Hello','Goodbye')
}
ok obj.hi() is "Hello Joe."
ok obj.cya() is "Goodbye Joe."
ok "With ${"quotes"}" is 'With quotes'
ok 'With ${"quotes"}' is 'With ${"quotes"}'
ok "Where is ${obj["name"] + '?'}" is 'Where is Joe?'
ok "Where is $obj.name?" is 'Where is Joe?'
ok "Where is ${"the nested ${obj["name"]}"}?" is 'Where is the nested Joe?'
ok "Hello ${world ? "$hello"}" is 'Hello World'
ok "Hello ${"${"${obj["name"]}" + '!'}"}" is 'Hello Joe!'
a: 1
b: 2
c: 3
ok "$a$b$c" is '123'
result: null
stash: (str) -> result: str
stash "a ${ ('aa').replace /a/g, 'b' } c"
ok result is 'a bb c' | 88069 | hello: 'Hello'
world: 'World'
ok '$hello $world!' is '$hello $world!'
ok '${hello} ${world}!' is '${hello} ${world}!'
ok "$hello $world!" is 'Hello World!'
ok "${hello} ${world}!" is 'Hello World!'
ok "[$hello$world]" is '[HelloWorld]'
ok "[${hello}${world}]" is '[HelloWorld]'
ok "$hello$$world" is 'Hello$World'
ok "${hello}$${world}" is 'Hello$World'
ok "Hello ${ 1 + 2 } World" is 'Hello 3 World'
ok "$hello ${ 1 + 2 } $world" is "Hello 3 World"
[s, t, r, i, n, g]: ['s', 't', 'r', 'i', 'n', 'g']
ok "$s$t$r$i$n$g" is 'string'
ok "${s}${t}${r}${i}${n}${g}" is 'string'
ok "\$s\$t\$r\$i\$n\$g" is '$s$t$r$i$n$g'
ok "\\$s\\$t\\$r\\$i\\$n\\$g" is '\\s\\t\\r\\i\\n\\g'
ok "\${s}\${t}\${r}\${i}\${n}\${g}" is '${s}${t}${r}${i}${n}${g}'
ok "\$string" is '$string'
ok "\${string}" is '${string}'
ok "\$Escaping first" is '$Escaping first'
ok "\${Escaping} first" is '${Escaping} first'
ok "Escaping \$in middle" is 'Escaping $in middle'
ok "Escaping \${in} middle" is 'Escaping ${in} middle'
ok "Escaping \$last" is 'Escaping $last'
ok "Escaping \${last}" is 'Escaping ${last}'
ok "$$" is '$$'
ok "${}" is ''
ok "${}A${} ${} ${}B${}" is 'A B'
ok "\\\\\$$" is '\\\\\$$'
ok "\\\${}" is '\\${}'
ok "I won $20 last night." is 'I won $20 last night.'
ok "I won $${20} last night." is 'I won $20 last night.'
ok "I won $#20 last night." is 'I won $#20 last night.'
ok "I won $${'#20'} last night." is 'I won $#20 last night.'
ok "${hello + world}" is 'HelloWorld'
ok "${hello + ' ' + world + '!'}" is 'Hello World!'
list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ok "values: ${list.join(', ')}, length: ${list.length}." is 'values: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, length: 10.'
ok "values: ${list.join ' '}" is 'values: 0 1 2 3 4 5 6 7 8 9'
obj: {
name: '<NAME>'
hi: -> "Hello $@name."
cya: -> "Hello $@name.".replace('Hello','Goodbye')
}
ok obj.hi() is "Hello <NAME>."
ok obj.cya() is "Goodbye Joe."
ok "With ${"quotes"}" is 'With quotes'
ok 'With ${"quotes"}' is 'With ${"quotes"}'
ok "Where is ${obj["name"] + '?'}" is 'Where is Joe?'
ok "Where is $obj.name?" is 'Where is Joe?'
ok "Where is ${"the nested ${obj["name"]}"}?" is 'Where is the nested Joe?'
ok "Hello ${world ? "$hello"}" is 'Hello World'
ok "Hello ${"${"${obj["name"]}" + '!'}"}" is 'Hello <NAME>!'
a: 1
b: 2
c: 3
ok "$a$b$c" is '123'
result: null
stash: (str) -> result: str
stash "a ${ ('aa').replace /a/g, 'b' } c"
ok result is 'a bb c' | true | hello: 'Hello'
world: 'World'
ok '$hello $world!' is '$hello $world!'
ok '${hello} ${world}!' is '${hello} ${world}!'
ok "$hello $world!" is 'Hello World!'
ok "${hello} ${world}!" is 'Hello World!'
ok "[$hello$world]" is '[HelloWorld]'
ok "[${hello}${world}]" is '[HelloWorld]'
ok "$hello$$world" is 'Hello$World'
ok "${hello}$${world}" is 'Hello$World'
ok "Hello ${ 1 + 2 } World" is 'Hello 3 World'
ok "$hello ${ 1 + 2 } $world" is "Hello 3 World"
[s, t, r, i, n, g]: ['s', 't', 'r', 'i', 'n', 'g']
ok "$s$t$r$i$n$g" is 'string'
ok "${s}${t}${r}${i}${n}${g}" is 'string'
ok "\$s\$t\$r\$i\$n\$g" is '$s$t$r$i$n$g'
ok "\\$s\\$t\\$r\\$i\\$n\\$g" is '\\s\\t\\r\\i\\n\\g'
ok "\${s}\${t}\${r}\${i}\${n}\${g}" is '${s}${t}${r}${i}${n}${g}'
ok "\$string" is '$string'
ok "\${string}" is '${string}'
ok "\$Escaping first" is '$Escaping first'
ok "\${Escaping} first" is '${Escaping} first'
ok "Escaping \$in middle" is 'Escaping $in middle'
ok "Escaping \${in} middle" is 'Escaping ${in} middle'
ok "Escaping \$last" is 'Escaping $last'
ok "Escaping \${last}" is 'Escaping ${last}'
ok "$$" is '$$'
ok "${}" is ''
ok "${}A${} ${} ${}B${}" is 'A B'
ok "\\\\\$$" is '\\\\\$$'
ok "\\\${}" is '\\${}'
ok "I won $20 last night." is 'I won $20 last night.'
ok "I won $${20} last night." is 'I won $20 last night.'
ok "I won $#20 last night." is 'I won $#20 last night.'
ok "I won $${'#20'} last night." is 'I won $#20 last night.'
ok "${hello + world}" is 'HelloWorld'
ok "${hello + ' ' + world + '!'}" is 'Hello World!'
list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ok "values: ${list.join(', ')}, length: ${list.length}." is 'values: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, length: 10.'
ok "values: ${list.join ' '}" is 'values: 0 1 2 3 4 5 6 7 8 9'
obj: {
name: 'PI:NAME:<NAME>END_PI'
hi: -> "Hello $@name."
cya: -> "Hello $@name.".replace('Hello','Goodbye')
}
ok obj.hi() is "Hello PI:NAME:<NAME>END_PI."
ok obj.cya() is "Goodbye Joe."
ok "With ${"quotes"}" is 'With quotes'
ok 'With ${"quotes"}' is 'With ${"quotes"}'
ok "Where is ${obj["name"] + '?'}" is 'Where is Joe?'
ok "Where is $obj.name?" is 'Where is Joe?'
ok "Where is ${"the nested ${obj["name"]}"}?" is 'Where is the nested Joe?'
ok "Hello ${world ? "$hello"}" is 'Hello World'
ok "Hello ${"${"${obj["name"]}" + '!'}"}" is 'Hello PI:NAME:<NAME>END_PI!'
a: 1
b: 2
c: 3
ok "$a$b$c" is '123'
result: null
stash: (str) -> result: str
stash "a ${ ('aa').replace /a/g, 'b' } c"
ok result is 'a bb c' |
[
{
"context": "ire 'lodash'\nBintray = require '../'\n\nusername = 'username'\napikey = 'apikey'\norganization = 'organization'\n",
"end": 92,
"score": 0.9993847012519836,
"start": 84,
"tag": "USERNAME",
"value": "username"
},
{
"context": " = require '../'\n\nusername = 'username'\napikey = 'apikey'\norganization = 'organization'\nrepository = 'repo",
"end": 110,
"score": 0.8770810961723328,
"start": 104,
"tag": "KEY",
"value": "apikey"
},
{
"context": "/localhost:8882'\n\nclient = new Bintray { username: username, apikey: apikey, organization: organization, repo",
"end": 242,
"score": 0.9989082217216492,
"start": 234,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ould get the user', (done) ->\n client.getUser('beaker')\n .then (response) ->\n try\n ",
"end": 422,
"score": 0.9965711236000061,
"start": 416,
"tag": "USERNAME",
"value": "beaker"
},
{
"context": " 200'\n assert.equal response.data.name, 'beaker', 'The user name is the expected'\n done(",
"end": 577,
"score": 0.9941308498382568,
"start": 571,
"tag": "USERNAME",
"value": "beaker"
},
{
"context": "llowers', (done) -> \n client.getUserFollowers('beaker')\n .then (response) ->\n try \n ",
"end": 802,
"score": 0.995725154876709,
"start": 796,
"tag": "USERNAME",
"value": "beaker"
}
] | test/usersSpec.coffee | h2non/node-bintray | 4 | assert = require 'assert'
_ = require 'lodash'
Bintray = require '../'
username = 'username'
apikey = 'apikey'
organization = 'organization'
repository = 'repo'
apiBaseUrl = 'http://localhost:8882'
client = new Bintray { username: username, apikey: apikey, organization: organization, repository: repository, baseUrl: apiBaseUrl }
describe 'Users:', ->
it 'should get the user', (done) ->
client.getUser('beaker')
.then (response) ->
try
assert.equal response.code, 200, 'Code status is 200'
assert.equal response.data.name, 'beaker', 'The user name is the expected'
done()
catch e
done e
, (error) ->
done new Error error.data
it 'should get the user followers', (done) ->
client.getUserFollowers('beaker')
.then (response) ->
try
assert.equal response.code, 200, 'Code status is 200'
assert.equal _.isArray(response.data), true, 'Body response is an Array'
assert.equal response.data.length, 2, 'User has 2 followers'
done()
catch e
done e
, (error) ->
done new Error error.data | 48756 | assert = require 'assert'
_ = require 'lodash'
Bintray = require '../'
username = 'username'
apikey = '<KEY>'
organization = 'organization'
repository = 'repo'
apiBaseUrl = 'http://localhost:8882'
client = new Bintray { username: username, apikey: apikey, organization: organization, repository: repository, baseUrl: apiBaseUrl }
describe 'Users:', ->
it 'should get the user', (done) ->
client.getUser('beaker')
.then (response) ->
try
assert.equal response.code, 200, 'Code status is 200'
assert.equal response.data.name, 'beaker', 'The user name is the expected'
done()
catch e
done e
, (error) ->
done new Error error.data
it 'should get the user followers', (done) ->
client.getUserFollowers('beaker')
.then (response) ->
try
assert.equal response.code, 200, 'Code status is 200'
assert.equal _.isArray(response.data), true, 'Body response is an Array'
assert.equal response.data.length, 2, 'User has 2 followers'
done()
catch e
done e
, (error) ->
done new Error error.data | true | assert = require 'assert'
_ = require 'lodash'
Bintray = require '../'
username = 'username'
apikey = 'PI:KEY:<KEY>END_PI'
organization = 'organization'
repository = 'repo'
apiBaseUrl = 'http://localhost:8882'
client = new Bintray { username: username, apikey: apikey, organization: organization, repository: repository, baseUrl: apiBaseUrl }
describe 'Users:', ->
it 'should get the user', (done) ->
client.getUser('beaker')
.then (response) ->
try
assert.equal response.code, 200, 'Code status is 200'
assert.equal response.data.name, 'beaker', 'The user name is the expected'
done()
catch e
done e
, (error) ->
done new Error error.data
it 'should get the user followers', (done) ->
client.getUserFollowers('beaker')
.then (response) ->
try
assert.equal response.code, 200, 'Code status is 200'
assert.equal _.isArray(response.data), true, 'Body response is an Array'
assert.equal response.data.length, 2, 'User has 2 followers'
done()
catch e
done e
, (error) ->
done new Error error.data |
[
{
"context": " Entities()\n\npool = mysql.createPool {\n host: '192.168.99.100'\n user: 'root'\n password: 'mysql'\n}\n\nwrite ",
"end": 483,
"score": 0.9996863007545471,
"start": 469,
"tag": "IP_ADDRESS",
"value": "192.168.99.100"
},
{
"context": " '192.168.99.100'\n user: 'root'\n password: 'mysql'\n}\n\nwrite = (pathname, text)->\n (done)->\n ",
"end": 522,
"score": 0.99957275390625,
"start": 517,
"tag": "PASSWORD",
"value": "mysql"
}
] | src/backend/router.coffee | miniEggRoll/SQLaaS | 0 | _ = require 'underscore'
co = require 'co'
fs = require 'fs'
path = require 'path'
router = require 'koa-trie-router'
uuid = require 'node-uuid'
mysql = require 'mysql'
Mustache = require 'mustache'
Entities = new require('html-entities').XmlEntities
index = fs.readFileSync path.join(__dirname, 'view/index.mustache'), {encoding: 'utf8'}
entities = new Entities()
pool = mysql.createPool {
host: '192.168.99.100'
user: 'root'
password: 'mysql'
}
write = (pathname, text)->
(done)->
fs.writeFile pathname, text, (err)->
done err, err?
readFile = (filename)->
pathname = path.join "#{__dirname}/sql", filename
(done)->
fs.readFile pathname, {encoding: 'utf8'}, (err, template)->
done err if err
id = path.basename filename, '.mustache'
done null, {id, template}
readdir = (dirname)->
(done)->
fs.readdir dirname, done
render = (ctx)->
Mustache.render index, ctx
execQuery = (sqlID, query)->
(done)->
co ->
{template} = yield readFile "#{sqlID}.mustache"
test = _.chain(query)
.map (q, key)-> [key, mysql.escape q]
.object()
.value()
escape = entities.decode Mustache.render(template, test)
pool.query escape, (err, rows, fields)->
if err? then done err else done null, rows.map (r)-> {json: JSON.stringify r}
.catch done
module.exports = (app)->
app.use router app
app.route(['/', '/sql'])
.get (next)->
fileNames = yield readdir path.join(__dirname, 'sql')
list = yield fileNames.map readFile
sql = []
@body = render {list, sql}
yield next
app.route('/sql/:sqlID')
.get (next)->
{sqlID} = @params
fileNames = yield readdir path.join(__dirname, 'sql')
list = yield fileNames.map readFile
sql = _.filter list, ({id})->
id is sqlID
@body = render {list, sql}
yield next
app.route('/sql')
.put (next)->
{valid, template} = @sqlaas.create
if valid
sqlID = uuid.v1()
pathname = path.join __dirname, 'sql', sqlID, '.mustache'
yield write pathname, template
@status = 200
list = yield readdir path.join(__dirname, 'sql')
sql = [{template, sqlID}]
@body = render {list, sql}
yield next
app.route('/exec/:sqlID')
.get (next)->
{sqlID} = @params
fileNames = yield readdir path.join(__dirname, 'sql')
list = yield fileNames.map readFile
sql = _.findWhere list, {id: sqlID}
exec = if sql? then yield execQuery(sqlID, @query) else []
@body = render {list, sql:[sql], exec}
yield next
| 77032 | _ = require 'underscore'
co = require 'co'
fs = require 'fs'
path = require 'path'
router = require 'koa-trie-router'
uuid = require 'node-uuid'
mysql = require 'mysql'
Mustache = require 'mustache'
Entities = new require('html-entities').XmlEntities
index = fs.readFileSync path.join(__dirname, 'view/index.mustache'), {encoding: 'utf8'}
entities = new Entities()
pool = mysql.createPool {
host: '192.168.99.100'
user: 'root'
password: '<PASSWORD>'
}
write = (pathname, text)->
(done)->
fs.writeFile pathname, text, (err)->
done err, err?
readFile = (filename)->
pathname = path.join "#{__dirname}/sql", filename
(done)->
fs.readFile pathname, {encoding: 'utf8'}, (err, template)->
done err if err
id = path.basename filename, '.mustache'
done null, {id, template}
readdir = (dirname)->
(done)->
fs.readdir dirname, done
render = (ctx)->
Mustache.render index, ctx
execQuery = (sqlID, query)->
(done)->
co ->
{template} = yield readFile "#{sqlID}.mustache"
test = _.chain(query)
.map (q, key)-> [key, mysql.escape q]
.object()
.value()
escape = entities.decode Mustache.render(template, test)
pool.query escape, (err, rows, fields)->
if err? then done err else done null, rows.map (r)-> {json: JSON.stringify r}
.catch done
module.exports = (app)->
app.use router app
app.route(['/', '/sql'])
.get (next)->
fileNames = yield readdir path.join(__dirname, 'sql')
list = yield fileNames.map readFile
sql = []
@body = render {list, sql}
yield next
app.route('/sql/:sqlID')
.get (next)->
{sqlID} = @params
fileNames = yield readdir path.join(__dirname, 'sql')
list = yield fileNames.map readFile
sql = _.filter list, ({id})->
id is sqlID
@body = render {list, sql}
yield next
app.route('/sql')
.put (next)->
{valid, template} = @sqlaas.create
if valid
sqlID = uuid.v1()
pathname = path.join __dirname, 'sql', sqlID, '.mustache'
yield write pathname, template
@status = 200
list = yield readdir path.join(__dirname, 'sql')
sql = [{template, sqlID}]
@body = render {list, sql}
yield next
app.route('/exec/:sqlID')
.get (next)->
{sqlID} = @params
fileNames = yield readdir path.join(__dirname, 'sql')
list = yield fileNames.map readFile
sql = _.findWhere list, {id: sqlID}
exec = if sql? then yield execQuery(sqlID, @query) else []
@body = render {list, sql:[sql], exec}
yield next
| true | _ = require 'underscore'
co = require 'co'
fs = require 'fs'
path = require 'path'
router = require 'koa-trie-router'
uuid = require 'node-uuid'
mysql = require 'mysql'
Mustache = require 'mustache'
Entities = new require('html-entities').XmlEntities
index = fs.readFileSync path.join(__dirname, 'view/index.mustache'), {encoding: 'utf8'}
entities = new Entities()
pool = mysql.createPool {
host: '192.168.99.100'
user: 'root'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
}
write = (pathname, text)->
(done)->
fs.writeFile pathname, text, (err)->
done err, err?
readFile = (filename)->
pathname = path.join "#{__dirname}/sql", filename
(done)->
fs.readFile pathname, {encoding: 'utf8'}, (err, template)->
done err if err
id = path.basename filename, '.mustache'
done null, {id, template}
readdir = (dirname)->
(done)->
fs.readdir dirname, done
render = (ctx)->
Mustache.render index, ctx
execQuery = (sqlID, query)->
(done)->
co ->
{template} = yield readFile "#{sqlID}.mustache"
test = _.chain(query)
.map (q, key)-> [key, mysql.escape q]
.object()
.value()
escape = entities.decode Mustache.render(template, test)
pool.query escape, (err, rows, fields)->
if err? then done err else done null, rows.map (r)-> {json: JSON.stringify r}
.catch done
module.exports = (app)->
app.use router app
app.route(['/', '/sql'])
.get (next)->
fileNames = yield readdir path.join(__dirname, 'sql')
list = yield fileNames.map readFile
sql = []
@body = render {list, sql}
yield next
app.route('/sql/:sqlID')
.get (next)->
{sqlID} = @params
fileNames = yield readdir path.join(__dirname, 'sql')
list = yield fileNames.map readFile
sql = _.filter list, ({id})->
id is sqlID
@body = render {list, sql}
yield next
app.route('/sql')
.put (next)->
{valid, template} = @sqlaas.create
if valid
sqlID = uuid.v1()
pathname = path.join __dirname, 'sql', sqlID, '.mustache'
yield write pathname, template
@status = 200
list = yield readdir path.join(__dirname, 'sql')
sql = [{template, sqlID}]
@body = render {list, sql}
yield next
app.route('/exec/:sqlID')
.get (next)->
{sqlID} = @params
fileNames = yield readdir path.join(__dirname, 'sql')
list = yield fileNames.map readFile
sql = _.findWhere list, {id: sqlID}
exec = if sql? then yield execQuery(sqlID, @query) else []
@body = render {list, sql:[sql], exec}
yield next
|
[
{
"context": "t']\n res.superObj.should.be.deep.equal key1:'hi', key2:'world'\n res.superStr.should.be.equal",
"end": 6272,
"score": 0.8922060132026672,
"start": 6270,
"tag": "KEY",
"value": "hi"
},
{
"context": "es.superObj.should.be.deep.equal key1:'hi', key2:'world'\n res.superStr.should.be.equal 'hi'\n re",
"end": 6286,
"score": 0.9507102370262146,
"start": 6281,
"tag": "KEY",
"value": "world"
},
{
"context": "t']\n res.superObj.should.be.deep.equal key1:'HI', key2:'world', key3:'append'\n res.superStr.",
"end": 6690,
"score": 0.6433818936347961,
"start": 6688,
"tag": "KEY",
"value": "HI"
},
{
"context": "es.superObj.should.be.deep.equal key1:'HI', key2:'world', key3:'append'\n res.superStr.should.be.equa",
"end": 6704,
"score": 0.9420874714851379,
"start": 6699,
"tag": "KEY",
"value": "world"
},
{
"context": "ould.be.deep.equal key1:'HI', key2:'world', key3:'append'\n res.superStr.should.be.equal 'hi world'\n ",
"end": 6719,
"score": 0.5301517248153687,
"start": 6713,
"tag": "KEY",
"value": "append"
}
] | test/index-test.coffee | snowyu/resource-file.js | 0 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
should = chai.should()
expect = chai.expect
assert = chai.assert
chai.use(sinonChai)
setPrototypeOf = require 'inherits-ex/lib/setPrototypeOf'
loadCfgFile = require 'load-config-file'
loadCfgFolder = require 'load-config-folder'
yaml = require('gray-matter/lib/parsers').yaml
fmatterMarkdown = require 'front-matter-markdown'
extend = require 'util-ex/lib/_extend'
fs = require 'fs'
fs.cwd = process.cwd
fs.path = require 'path.js'
Resource = require '../src'
setImmediate = setImmediate || process.nextTick
Resource.setFileSystem fs
filterBehaviorTest = require 'custom-file/test/filter'
path = fs.path
buildTree = (aContents, result)->
aContents.forEach (i)->
if i.isDirectory() and i.contents
result.push v = {}
v[i.inspect()] = buildTree i.contents, []
else
result.push i.inspect()
result
describe 'ResourceFile', ->
loadCfgFile.register 'yml', yaml
loadCfgFolder.register 'yml', yaml
loadCfgFolder.register 'md', fmatterMarkdown
loadCfgFolder.addConfig ['_config', 'INDEX', 'index', 'README']
it 'should setFileSystem to load-config-file and load-config-folder', ->
fakeFS = extend {}, fs
Resource.setFileSystem fakeFS
expect(loadCfgFile::fs).to.be.equal fakeFS
expect(loadCfgFolder::fs).to.be.equal fakeFS
Resource.setFileSystem fs
it 'should get a resource', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.should.be.instanceOf Resource
expect(res.isDirectory()).to.be.true
describe '#loadSync', ->
it 'should load a resource folder', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', '_config'
res.contents.should.have.length 5
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Fixture'
it 'should load a resource folder with summary', ->
res = Resource 'fixture/folder', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', 'README'
res.contents.should.have.length 4
expect(res.summary).to.be.equal '\nthis is README.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Folder'
it 'should load a resource file', ->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', 'file0'
expect(res.summary).to.be.not.exist
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 0'
it 'should load a resource file with summary', ->
res = Resource 'fixture/folder/file10.md', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', 'file10'
expect(res.summary).to.be.equal 'this is a summary.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 10'
it 'should not get title and date from a resource file if property exists', ->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
vDate = new Date()
vTtile = 'Custom title'
res.title = vTtile
res.date = vDate
res.loadSync(read:true)
res.should.have.property 'config', 'file0'
expect(res.date).to.be.deep.equals vDate
expect(res.title).to.be.equal vTtile
it 'should load a resource folder recursively', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.loadSync(read:true, recursive:true)
should.exist res.contents
res.should.have.property 'config', '_config'
res.contents.should.have.length 5 # the unknown file is not loaded.
res.contents[2].getContentSync()
res.contents.should.have.length 4
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Fixture'
result = buildTree(res.contents, [])
expected = [
'<File? "fixture/file0.md">'
'<Folder "fixture/folder">': [
'<File? "fixture/folder/file10.md">'
'<Folder "fixture/folder/folder1">': []
,
'<Folder "fixture/folder/folder2">': [
'<File? "fixture/folder/folder2/test.md">'
]
'<File? "fixture/folder/vfolder1.md">'
]
'<File "fixture/unknown">'
'<File? "fixture/vfolder.md">'
]
if path.isWindows
expected = [
'<File? "fixture\\file0.md">'
'<Folder "fixture\\folder">': [
'<File? "fixture\\folder\\file10.md">'
'<Folder "fixture\\folder\\folder1">': []
,
'<Folder "fixture\\folder\\folder2">': [
'<File? "fixture\\folder\\folder2\\test.md">'
]
'<File? "fixture\\folder\\vfolder1.md">'
]
'<File "fixture\\unknown">'
'<File? "fixture\\vfolder.md">'
]
result.should.be.deep.equal expected
it 'should load a resource virtual folder', ->
res = Resource 'vfolder.md', cwd: __dirname, base: 'fixture', load:true,read:true
should.exist res, 'res'
res.isDirectory().should.be.true
should.exist res.contents, 'res.contents'
expect(res.date).to.be.deep.equal new Date('2011-01-11T11:11:00Z')
expect(res.title).to.be.equal 'Virtual Folder'
result = res.contents
expect(result[0].title).to.be.equal 'File Zero'
result = buildTree(result, [])
result.should.be.deep.equal ['<File? "file0.md">']
it 'should inherit the parent\'s config', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', '_config'
res.contents.should.have.length 5
res.contents[0].getContentSync()
res.should.have.ownProperty 'superLst'
res.should.have.ownProperty 'superObj'
res.should.have.ownProperty 'superStr'
res.should.have.ownProperty 'superNum'
res.superLst.should.be.deep.equal ['as', 'it']
res.superObj.should.be.deep.equal key1:'hi', key2:'world'
res.superStr.should.be.equal 'hi'
res.superNum.should.be.equal 123
res = res.contents[0]
res.should.have.ownProperty 'superLst'
res.should.have.ownProperty 'superObj'
res.should.have.ownProperty 'superStr'
res.should.have.ownProperty 'superNum'
res.superLst.should.be.deep.equal ['add1','add2','as', 'it']
res.superObj.should.be.deep.equal key1:'HI', key2:'world', key3:'append'
res.superStr.should.be.equal 'hi world'
res.superNum.should.be.equal 126
it 'should load a resource file with getContent', ->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
result = res.getContentSync()
res.should.have.property 'config', 'file0'
expect(res.skipSize).to.be.at.least 104
describe '#load', ->
it 'should load a resource folder', (done)->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', '_config'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Fixture'
done()
it 'should load a resource folder with summary', (done)->
res = Resource 'fixture/folder', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'README'
expect(res.contents).have.length 4
expect(res.summary).to.be.equal '\nthis is README.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Folder'
done()
it 'should load a resource file', (done)->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'file0'
expect(res.summary).to.be.not.exist
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 0'
done()
it 'should load a resource file with summary', (done)->
res = Resource 'fixture/folder/file10.md', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'file10'
expect(res.summary).to.be.equal 'this is a summary.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 10'
done()
it 'should not get title and date from a resource file if property exists', (done)->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
vDate = new Date()
vTtile = 'Custom title'
res.title = vTtile
res.date = vDate
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'file0'
expect(res.date).to.be.deep.equals vDate
expect(res.title).to.be.equal vTtile
done()
it 'should load a resource file with a configuration file', (done)->
res = Resource '.', cwd: __dirname, base:'fixture', load:true,read:true
expect(res).be.exist
should.exist res.contents, 'res.contents'
for file in res.contents
break if file.relative is 'unknown'
expect(file).have.property 'relative', 'unknown'
expect(file.parent).be.equal res
file.load read:true, (err, result)->
return done(err) if err
file.should.have.property 'config', 'unknown'
done()
it 'should load a resource folder recursively', (done)->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.load read:true, recursive:true, (err, contents)->
return done(err) if err
should.exist contents
res.should.have.property 'config', '_config'
contents.should.have.length 5
# the "unknown" file
res.contents[2].getContent (err)->
res.contents.should.have.length 4
result = buildTree(res.contents, [])
expected = [
'<File? "fixture/file0.md">'
'<Folder "fixture/folder">': [
'<File? "fixture/folder/file10.md">'
'<Folder "fixture/folder/folder1">': []
,
'<Folder "fixture/folder/folder2">': [
'<File? "fixture/folder/folder2/test.md">'
]
'<File? "fixture/folder/vfolder1.md">'
]
'<File "fixture/unknown">'
'<File? "fixture/vfolder.md">'
]
if path.isWindows
expected = [
'<File? "fixture\\file0.md">'
'<Folder "fixture\\folder">': [
'<File? "fixture\\folder\\file10.md">'
'<Folder "fixture\\folder\\folder1">': []
,
'<Folder "fixture\\folder\\folder2">': [
'<File? "fixture\\folder\\folder2\\test.md">'
]
'<File? "fixture\\folder\\vfolder1.md">'
]
'<File "fixture\\unknown">'
'<File? "fixture\\vfolder.md">'
]
result.should.be.deep.equal expected
done()
it 'should load a resource virtual folder', (done)->
res = Resource 'vfolder.md', cwd: __dirname, base: 'fixture'
should.exist res, 'res'
res.load read:true, (err, result)->
unless err
res.isDirectory().should.be.true
should.exist res.contents, 'res.contents'
expect(res.date).to.be.deep.equal new Date('2011-01-11T11:11:00Z')
expect(res.title).to.be.equal 'Virtual Folder'
expect(result[0].title).to.be.equal 'File Zero'
result = buildTree(result, [])
result.should.be.deep.equal ['<File? "file0.md">']
done(err)
it 'should load a resource file with getContent', (done)->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
res.getContent (err, result)->
return done(err) if err
res.should.have.property 'config', 'file0'
expect(res.skipSize).to.be.at.least 104
done()
describe '#toObject', ->
it 'should convert a resource to a plain object', ->
res = Resource 'fixture', cwd: __dirname, load:false
should.exist res
result = res.toObject()
result.should.be.deep.equal
cwd: __dirname
base: __dirname
path: path.join __dirname, 'fixture'
f = {}
setPrototypeOf f, res
res.loadSync(read:true)
result = res.toObject()
result.should.have.ownProperty 'stat'
result.should.have.ownProperty 'contents'
result = f.toObject()
result.should.not.have.ownProperty 'stat'
result.should.not.have.ownProperty 'contents'
it 'should convert a resource to a plain object and exclude', ->
res = Resource 'fixture', cwd: __dirname, load:false
should.exist res
result = res.toObject(null, 'base')
result.should.be.deep.equal
cwd: __dirname
path: path.join __dirname, 'fixture'
result = res.toObject(null, ['base', 'path'])
result.should.be.deep.equal
cwd: __dirname
#TODO: only supports buffer!! the filter should be run after loading config.
# describe '#filter', filterBehaviorTest Resource,
# {path:path.join(__dirname, 'fixture/folder'), base: __dirname},
# (file)->
# console.log file, path.basename(file.path) is 'file10.md'
# path.basename(file.path) is 'file10.md'
# ,[path.join 'fixture','folder','file10.md']
| 172827 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
should = chai.should()
expect = chai.expect
assert = chai.assert
chai.use(sinonChai)
setPrototypeOf = require 'inherits-ex/lib/setPrototypeOf'
loadCfgFile = require 'load-config-file'
loadCfgFolder = require 'load-config-folder'
yaml = require('gray-matter/lib/parsers').yaml
fmatterMarkdown = require 'front-matter-markdown'
extend = require 'util-ex/lib/_extend'
fs = require 'fs'
fs.cwd = process.cwd
fs.path = require 'path.js'
Resource = require '../src'
setImmediate = setImmediate || process.nextTick
Resource.setFileSystem fs
filterBehaviorTest = require 'custom-file/test/filter'
path = fs.path
buildTree = (aContents, result)->
aContents.forEach (i)->
if i.isDirectory() and i.contents
result.push v = {}
v[i.inspect()] = buildTree i.contents, []
else
result.push i.inspect()
result
describe 'ResourceFile', ->
loadCfgFile.register 'yml', yaml
loadCfgFolder.register 'yml', yaml
loadCfgFolder.register 'md', fmatterMarkdown
loadCfgFolder.addConfig ['_config', 'INDEX', 'index', 'README']
it 'should setFileSystem to load-config-file and load-config-folder', ->
fakeFS = extend {}, fs
Resource.setFileSystem fakeFS
expect(loadCfgFile::fs).to.be.equal fakeFS
expect(loadCfgFolder::fs).to.be.equal fakeFS
Resource.setFileSystem fs
it 'should get a resource', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.should.be.instanceOf Resource
expect(res.isDirectory()).to.be.true
describe '#loadSync', ->
it 'should load a resource folder', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', '_config'
res.contents.should.have.length 5
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Fixture'
it 'should load a resource folder with summary', ->
res = Resource 'fixture/folder', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', 'README'
res.contents.should.have.length 4
expect(res.summary).to.be.equal '\nthis is README.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Folder'
it 'should load a resource file', ->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', 'file0'
expect(res.summary).to.be.not.exist
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 0'
it 'should load a resource file with summary', ->
res = Resource 'fixture/folder/file10.md', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', 'file10'
expect(res.summary).to.be.equal 'this is a summary.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 10'
it 'should not get title and date from a resource file if property exists', ->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
vDate = new Date()
vTtile = 'Custom title'
res.title = vTtile
res.date = vDate
res.loadSync(read:true)
res.should.have.property 'config', 'file0'
expect(res.date).to.be.deep.equals vDate
expect(res.title).to.be.equal vTtile
it 'should load a resource folder recursively', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.loadSync(read:true, recursive:true)
should.exist res.contents
res.should.have.property 'config', '_config'
res.contents.should.have.length 5 # the unknown file is not loaded.
res.contents[2].getContentSync()
res.contents.should.have.length 4
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Fixture'
result = buildTree(res.contents, [])
expected = [
'<File? "fixture/file0.md">'
'<Folder "fixture/folder">': [
'<File? "fixture/folder/file10.md">'
'<Folder "fixture/folder/folder1">': []
,
'<Folder "fixture/folder/folder2">': [
'<File? "fixture/folder/folder2/test.md">'
]
'<File? "fixture/folder/vfolder1.md">'
]
'<File "fixture/unknown">'
'<File? "fixture/vfolder.md">'
]
if path.isWindows
expected = [
'<File? "fixture\\file0.md">'
'<Folder "fixture\\folder">': [
'<File? "fixture\\folder\\file10.md">'
'<Folder "fixture\\folder\\folder1">': []
,
'<Folder "fixture\\folder\\folder2">': [
'<File? "fixture\\folder\\folder2\\test.md">'
]
'<File? "fixture\\folder\\vfolder1.md">'
]
'<File "fixture\\unknown">'
'<File? "fixture\\vfolder.md">'
]
result.should.be.deep.equal expected
it 'should load a resource virtual folder', ->
res = Resource 'vfolder.md', cwd: __dirname, base: 'fixture', load:true,read:true
should.exist res, 'res'
res.isDirectory().should.be.true
should.exist res.contents, 'res.contents'
expect(res.date).to.be.deep.equal new Date('2011-01-11T11:11:00Z')
expect(res.title).to.be.equal 'Virtual Folder'
result = res.contents
expect(result[0].title).to.be.equal 'File Zero'
result = buildTree(result, [])
result.should.be.deep.equal ['<File? "file0.md">']
it 'should inherit the parent\'s config', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', '_config'
res.contents.should.have.length 5
res.contents[0].getContentSync()
res.should.have.ownProperty 'superLst'
res.should.have.ownProperty 'superObj'
res.should.have.ownProperty 'superStr'
res.should.have.ownProperty 'superNum'
res.superLst.should.be.deep.equal ['as', 'it']
res.superObj.should.be.deep.equal key1:'<KEY>', key2:'<KEY>'
res.superStr.should.be.equal 'hi'
res.superNum.should.be.equal 123
res = res.contents[0]
res.should.have.ownProperty 'superLst'
res.should.have.ownProperty 'superObj'
res.should.have.ownProperty 'superStr'
res.should.have.ownProperty 'superNum'
res.superLst.should.be.deep.equal ['add1','add2','as', 'it']
res.superObj.should.be.deep.equal key1:'<KEY>', key2:'<KEY>', key3:'<KEY>'
res.superStr.should.be.equal 'hi world'
res.superNum.should.be.equal 126
it 'should load a resource file with getContent', ->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
result = res.getContentSync()
res.should.have.property 'config', 'file0'
expect(res.skipSize).to.be.at.least 104
describe '#load', ->
it 'should load a resource folder', (done)->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', '_config'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Fixture'
done()
it 'should load a resource folder with summary', (done)->
res = Resource 'fixture/folder', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'README'
expect(res.contents).have.length 4
expect(res.summary).to.be.equal '\nthis is README.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Folder'
done()
it 'should load a resource file', (done)->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'file0'
expect(res.summary).to.be.not.exist
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 0'
done()
it 'should load a resource file with summary', (done)->
res = Resource 'fixture/folder/file10.md', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'file10'
expect(res.summary).to.be.equal 'this is a summary.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 10'
done()
it 'should not get title and date from a resource file if property exists', (done)->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
vDate = new Date()
vTtile = 'Custom title'
res.title = vTtile
res.date = vDate
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'file0'
expect(res.date).to.be.deep.equals vDate
expect(res.title).to.be.equal vTtile
done()
it 'should load a resource file with a configuration file', (done)->
res = Resource '.', cwd: __dirname, base:'fixture', load:true,read:true
expect(res).be.exist
should.exist res.contents, 'res.contents'
for file in res.contents
break if file.relative is 'unknown'
expect(file).have.property 'relative', 'unknown'
expect(file.parent).be.equal res
file.load read:true, (err, result)->
return done(err) if err
file.should.have.property 'config', 'unknown'
done()
it 'should load a resource folder recursively', (done)->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.load read:true, recursive:true, (err, contents)->
return done(err) if err
should.exist contents
res.should.have.property 'config', '_config'
contents.should.have.length 5
# the "unknown" file
res.contents[2].getContent (err)->
res.contents.should.have.length 4
result = buildTree(res.contents, [])
expected = [
'<File? "fixture/file0.md">'
'<Folder "fixture/folder">': [
'<File? "fixture/folder/file10.md">'
'<Folder "fixture/folder/folder1">': []
,
'<Folder "fixture/folder/folder2">': [
'<File? "fixture/folder/folder2/test.md">'
]
'<File? "fixture/folder/vfolder1.md">'
]
'<File "fixture/unknown">'
'<File? "fixture/vfolder.md">'
]
if path.isWindows
expected = [
'<File? "fixture\\file0.md">'
'<Folder "fixture\\folder">': [
'<File? "fixture\\folder\\file10.md">'
'<Folder "fixture\\folder\\folder1">': []
,
'<Folder "fixture\\folder\\folder2">': [
'<File? "fixture\\folder\\folder2\\test.md">'
]
'<File? "fixture\\folder\\vfolder1.md">'
]
'<File "fixture\\unknown">'
'<File? "fixture\\vfolder.md">'
]
result.should.be.deep.equal expected
done()
it 'should load a resource virtual folder', (done)->
res = Resource 'vfolder.md', cwd: __dirname, base: 'fixture'
should.exist res, 'res'
res.load read:true, (err, result)->
unless err
res.isDirectory().should.be.true
should.exist res.contents, 'res.contents'
expect(res.date).to.be.deep.equal new Date('2011-01-11T11:11:00Z')
expect(res.title).to.be.equal 'Virtual Folder'
expect(result[0].title).to.be.equal 'File Zero'
result = buildTree(result, [])
result.should.be.deep.equal ['<File? "file0.md">']
done(err)
it 'should load a resource file with getContent', (done)->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
res.getContent (err, result)->
return done(err) if err
res.should.have.property 'config', 'file0'
expect(res.skipSize).to.be.at.least 104
done()
describe '#toObject', ->
it 'should convert a resource to a plain object', ->
res = Resource 'fixture', cwd: __dirname, load:false
should.exist res
result = res.toObject()
result.should.be.deep.equal
cwd: __dirname
base: __dirname
path: path.join __dirname, 'fixture'
f = {}
setPrototypeOf f, res
res.loadSync(read:true)
result = res.toObject()
result.should.have.ownProperty 'stat'
result.should.have.ownProperty 'contents'
result = f.toObject()
result.should.not.have.ownProperty 'stat'
result.should.not.have.ownProperty 'contents'
it 'should convert a resource to a plain object and exclude', ->
res = Resource 'fixture', cwd: __dirname, load:false
should.exist res
result = res.toObject(null, 'base')
result.should.be.deep.equal
cwd: __dirname
path: path.join __dirname, 'fixture'
result = res.toObject(null, ['base', 'path'])
result.should.be.deep.equal
cwd: __dirname
#TODO: only supports buffer!! the filter should be run after loading config.
# describe '#filter', filterBehaviorTest Resource,
# {path:path.join(__dirname, 'fixture/folder'), base: __dirname},
# (file)->
# console.log file, path.basename(file.path) is 'file10.md'
# path.basename(file.path) is 'file10.md'
# ,[path.join 'fixture','folder','file10.md']
| true | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
should = chai.should()
expect = chai.expect
assert = chai.assert
chai.use(sinonChai)
setPrototypeOf = require 'inherits-ex/lib/setPrototypeOf'
loadCfgFile = require 'load-config-file'
loadCfgFolder = require 'load-config-folder'
yaml = require('gray-matter/lib/parsers').yaml
fmatterMarkdown = require 'front-matter-markdown'
extend = require 'util-ex/lib/_extend'
fs = require 'fs'
fs.cwd = process.cwd
fs.path = require 'path.js'
Resource = require '../src'
setImmediate = setImmediate || process.nextTick
Resource.setFileSystem fs
filterBehaviorTest = require 'custom-file/test/filter'
path = fs.path
buildTree = (aContents, result)->
aContents.forEach (i)->
if i.isDirectory() and i.contents
result.push v = {}
v[i.inspect()] = buildTree i.contents, []
else
result.push i.inspect()
result
describe 'ResourceFile', ->
loadCfgFile.register 'yml', yaml
loadCfgFolder.register 'yml', yaml
loadCfgFolder.register 'md', fmatterMarkdown
loadCfgFolder.addConfig ['_config', 'INDEX', 'index', 'README']
it 'should setFileSystem to load-config-file and load-config-folder', ->
fakeFS = extend {}, fs
Resource.setFileSystem fakeFS
expect(loadCfgFile::fs).to.be.equal fakeFS
expect(loadCfgFolder::fs).to.be.equal fakeFS
Resource.setFileSystem fs
it 'should get a resource', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.should.be.instanceOf Resource
expect(res.isDirectory()).to.be.true
describe '#loadSync', ->
it 'should load a resource folder', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', '_config'
res.contents.should.have.length 5
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Fixture'
it 'should load a resource folder with summary', ->
res = Resource 'fixture/folder', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', 'README'
res.contents.should.have.length 4
expect(res.summary).to.be.equal '\nthis is README.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Folder'
it 'should load a resource file', ->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', 'file0'
expect(res.summary).to.be.not.exist
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 0'
it 'should load a resource file with summary', ->
res = Resource 'fixture/folder/file10.md', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', 'file10'
expect(res.summary).to.be.equal 'this is a summary.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 10'
it 'should not get title and date from a resource file if property exists', ->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
vDate = new Date()
vTtile = 'Custom title'
res.title = vTtile
res.date = vDate
res.loadSync(read:true)
res.should.have.property 'config', 'file0'
expect(res.date).to.be.deep.equals vDate
expect(res.title).to.be.equal vTtile
it 'should load a resource folder recursively', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.loadSync(read:true, recursive:true)
should.exist res.contents
res.should.have.property 'config', '_config'
res.contents.should.have.length 5 # the unknown file is not loaded.
res.contents[2].getContentSync()
res.contents.should.have.length 4
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Fixture'
result = buildTree(res.contents, [])
expected = [
'<File? "fixture/file0.md">'
'<Folder "fixture/folder">': [
'<File? "fixture/folder/file10.md">'
'<Folder "fixture/folder/folder1">': []
,
'<Folder "fixture/folder/folder2">': [
'<File? "fixture/folder/folder2/test.md">'
]
'<File? "fixture/folder/vfolder1.md">'
]
'<File "fixture/unknown">'
'<File? "fixture/vfolder.md">'
]
if path.isWindows
expected = [
'<File? "fixture\\file0.md">'
'<Folder "fixture\\folder">': [
'<File? "fixture\\folder\\file10.md">'
'<Folder "fixture\\folder\\folder1">': []
,
'<Folder "fixture\\folder\\folder2">': [
'<File? "fixture\\folder\\folder2\\test.md">'
]
'<File? "fixture\\folder\\vfolder1.md">'
]
'<File "fixture\\unknown">'
'<File? "fixture\\vfolder.md">'
]
result.should.be.deep.equal expected
it 'should load a resource virtual folder', ->
res = Resource 'vfolder.md', cwd: __dirname, base: 'fixture', load:true,read:true
should.exist res, 'res'
res.isDirectory().should.be.true
should.exist res.contents, 'res.contents'
expect(res.date).to.be.deep.equal new Date('2011-01-11T11:11:00Z')
expect(res.title).to.be.equal 'Virtual Folder'
result = res.contents
expect(result[0].title).to.be.equal 'File Zero'
result = buildTree(result, [])
result.should.be.deep.equal ['<File? "file0.md">']
it 'should inherit the parent\'s config', ->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.loadSync(read:true)
res.should.have.property 'config', '_config'
res.contents.should.have.length 5
res.contents[0].getContentSync()
res.should.have.ownProperty 'superLst'
res.should.have.ownProperty 'superObj'
res.should.have.ownProperty 'superStr'
res.should.have.ownProperty 'superNum'
res.superLst.should.be.deep.equal ['as', 'it']
res.superObj.should.be.deep.equal key1:'PI:KEY:<KEY>END_PI', key2:'PI:KEY:<KEY>END_PI'
res.superStr.should.be.equal 'hi'
res.superNum.should.be.equal 123
res = res.contents[0]
res.should.have.ownProperty 'superLst'
res.should.have.ownProperty 'superObj'
res.should.have.ownProperty 'superStr'
res.should.have.ownProperty 'superNum'
res.superLst.should.be.deep.equal ['add1','add2','as', 'it']
res.superObj.should.be.deep.equal key1:'PI:KEY:<KEY>END_PI', key2:'PI:KEY:<KEY>END_PI', key3:'PI:KEY:<KEY>END_PI'
res.superStr.should.be.equal 'hi world'
res.superNum.should.be.equal 126
it 'should load a resource file with getContent', ->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
result = res.getContentSync()
res.should.have.property 'config', 'file0'
expect(res.skipSize).to.be.at.least 104
describe '#load', ->
it 'should load a resource folder', (done)->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', '_config'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Fixture'
done()
it 'should load a resource folder with summary', (done)->
res = Resource 'fixture/folder', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'README'
expect(res.contents).have.length 4
expect(res.summary).to.be.equal '\nthis is README.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'Folder'
done()
it 'should load a resource file', (done)->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'file0'
expect(res.summary).to.be.not.exist
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 0'
done()
it 'should load a resource file with summary', (done)->
res = Resource 'fixture/folder/file10.md', cwd: __dirname
should.exist res
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'file10'
expect(res.summary).to.be.equal 'this is a summary.'
expect(res.date).to.be.an.instanceOf Date
expect(res.title).to.be.equal 'File 10'
done()
it 'should not get title and date from a resource file if property exists', (done)->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
vDate = new Date()
vTtile = 'Custom title'
res.title = vTtile
res.date = vDate
res.load read:true, (err, result)->
return done(err) if err
res.should.have.property 'config', 'file0'
expect(res.date).to.be.deep.equals vDate
expect(res.title).to.be.equal vTtile
done()
it 'should load a resource file with a configuration file', (done)->
res = Resource '.', cwd: __dirname, base:'fixture', load:true,read:true
expect(res).be.exist
should.exist res.contents, 'res.contents'
for file in res.contents
break if file.relative is 'unknown'
expect(file).have.property 'relative', 'unknown'
expect(file.parent).be.equal res
file.load read:true, (err, result)->
return done(err) if err
file.should.have.property 'config', 'unknown'
done()
it 'should load a resource folder recursively', (done)->
res = Resource 'fixture', cwd: __dirname
should.exist res
res.load read:true, recursive:true, (err, contents)->
return done(err) if err
should.exist contents
res.should.have.property 'config', '_config'
contents.should.have.length 5
# the "unknown" file
res.contents[2].getContent (err)->
res.contents.should.have.length 4
result = buildTree(res.contents, [])
expected = [
'<File? "fixture/file0.md">'
'<Folder "fixture/folder">': [
'<File? "fixture/folder/file10.md">'
'<Folder "fixture/folder/folder1">': []
,
'<Folder "fixture/folder/folder2">': [
'<File? "fixture/folder/folder2/test.md">'
]
'<File? "fixture/folder/vfolder1.md">'
]
'<File "fixture/unknown">'
'<File? "fixture/vfolder.md">'
]
if path.isWindows
expected = [
'<File? "fixture\\file0.md">'
'<Folder "fixture\\folder">': [
'<File? "fixture\\folder\\file10.md">'
'<Folder "fixture\\folder\\folder1">': []
,
'<Folder "fixture\\folder\\folder2">': [
'<File? "fixture\\folder\\folder2\\test.md">'
]
'<File? "fixture\\folder\\vfolder1.md">'
]
'<File "fixture\\unknown">'
'<File? "fixture\\vfolder.md">'
]
result.should.be.deep.equal expected
done()
it 'should load a resource virtual folder', (done)->
res = Resource 'vfolder.md', cwd: __dirname, base: 'fixture'
should.exist res, 'res'
res.load read:true, (err, result)->
unless err
res.isDirectory().should.be.true
should.exist res.contents, 'res.contents'
expect(res.date).to.be.deep.equal new Date('2011-01-11T11:11:00Z')
expect(res.title).to.be.equal 'Virtual Folder'
expect(result[0].title).to.be.equal 'File Zero'
result = buildTree(result, [])
result.should.be.deep.equal ['<File? "file0.md">']
done(err)
it 'should load a resource file with getContent', (done)->
res = Resource 'fixture/file0.md', cwd: __dirname
should.exist res
res.getContent (err, result)->
return done(err) if err
res.should.have.property 'config', 'file0'
expect(res.skipSize).to.be.at.least 104
done()
describe '#toObject', ->
it 'should convert a resource to a plain object', ->
res = Resource 'fixture', cwd: __dirname, load:false
should.exist res
result = res.toObject()
result.should.be.deep.equal
cwd: __dirname
base: __dirname
path: path.join __dirname, 'fixture'
f = {}
setPrototypeOf f, res
res.loadSync(read:true)
result = res.toObject()
result.should.have.ownProperty 'stat'
result.should.have.ownProperty 'contents'
result = f.toObject()
result.should.not.have.ownProperty 'stat'
result.should.not.have.ownProperty 'contents'
it 'should convert a resource to a plain object and exclude', ->
res = Resource 'fixture', cwd: __dirname, load:false
should.exist res
result = res.toObject(null, 'base')
result.should.be.deep.equal
cwd: __dirname
path: path.join __dirname, 'fixture'
result = res.toObject(null, ['base', 'path'])
result.should.be.deep.equal
cwd: __dirname
#TODO: only supports buffer!! the filter should be run after loading config.
# describe '#filter', filterBehaviorTest Resource,
# {path:path.join(__dirname, 'fixture/folder'), base: __dirname},
# (file)->
# console.log file, path.basename(file.path) is 'file10.md'
# path.basename(file.path) is 'file10.md'
# ,[path.join 'fixture','folder','file10.md']
|
[
{
"context": " (done) ->\n auth.login(server, {username: \"test@test.com\", password:\"password\"}, 200, \n (res)->",
"end": 601,
"score": 0.9999243021011353,
"start": 588,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": "gin(server, {username: \"test@test.com\", password:\"password\"}, 200, \n (res)->\n cook",
"end": 622,
"score": 0.9994524121284485,
"start": 614,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " user.search(server,cookies,{username:\"test@test.com\"},200,\n (res) ->\n ",
"end": 792,
"score": 0.9999219179153442,
"start": 779,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": " \"widgets\": [{\n \"name\": \"someName\",\n \"type\": \"someType\",\n ",
"end": 1154,
"score": 0.7989828586578369,
"start": 1146,
"tag": "NAME",
"value": "someName"
},
{
"context": " \"widgets\": [{\n \"name\": \"Updated someName\",\n \"type\": \"Updated someT",
"end": 2589,
"score": 0.9956364035606384,
"start": 2582,
"tag": "NAME",
"value": "Updated"
},
{
"context": " \"widgets\": [{\n \"name\": \"Updated someName\",\n \"type\": \"Updated someType\",\n ",
"end": 2598,
"score": 0.9744162559509277,
"start": 2590,
"tag": "NAME",
"value": "someName"
},
{
"context": "\"AAAAA\"}\n },{\n \"name\": \"Updated someName\",\n \"type\": \"Updated someT",
"end": 3186,
"score": 0.997029185295105,
"start": 3179,
"tag": "NAME",
"value": "Updated"
},
{
"context": "}\n },{\n \"name\": \"Updated someName\",\n \"type\": \"Updated someType\",\n ",
"end": 3195,
"score": 0.9764604568481445,
"start": 3187,
"tag": "NAME",
"value": "someName"
},
{
"context": " res.body.widgets[0].name.should.be.equal \"Updated someName\"\n res.body.widgets[0].typ",
"end": 4214,
"score": 0.9364570379257202,
"start": 4207,
"tag": "NAME",
"value": "Updated"
},
{
"context": " res.body.widgets[0].name.should.be.equal \"Updated someName\"\n res.body.widgets[0].type.should.",
"end": 4223,
"score": 0.7625589370727539,
"start": 4215,
"tag": "NAME",
"value": "someName"
},
{
"context": "->\n payload = {\n \"user\": operator._id,\n \"widgets\": [{\n ",
"end": 4775,
"score": 0.6122475266456604,
"start": 4767,
"tag": "USERNAME",
"value": "operator"
},
{
"context": " \"widgets\": [{\n \"name\": \"someName\",\n \"type\": \"asdfasdfasdf\",\n ",
"end": 4848,
"score": 0.872407853603363,
"start": 4840,
"tag": "NAME",
"value": "someName"
}
] | test/services_tests/test_dashboard_services.coffee | ureport-web/ureport-s | 3 | #load application models
server = require('../../app')
_ = require('underscore');
dashboard = require('../api_objects/dashboard_api_object')
auth = require('../api_objects/auth_api_object')
user = require('../api_objects/user_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User with operator permission', ->
cookies = undefined;
operator = undefined;
create_dashboard_id = undefined
before (done) ->
auth.login(server, {username: "test@test.com", password:"password"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
user.search(server,cookies,{username:"test@test.com"},200,
(res) ->
operator = res.body[0]
done()
)
)
return
it 'should create a new dashboard', (done) ->
payload = {
"user": operator._id,
"name": "Created from test"
"widgets": [{
"name": "someName",
"type": "someType",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
200,
(res) ->
create_dashboard_id = res.body._id
res.body.name.should.equal 'Created from test'
res.body.user.should.equal operator._id
res.body.widgets.should.be.an 'Array'
res.body.widgets.length.should.equal 1
res.body.widgets[0].name.should.be.equal "someName"
res.body.widgets[0].type.should.be.equal "someType"
res.body.widgets[0].pattern.should.exists
done()
)
return
it 'should update a new dashboard', (done) ->
payload = {
"user": operator._id,
"_id": create_dashboard_id,
"name": "Updated Created from test"
"widgets": [{
"name": "Updated someName",
"type": "Updated someType",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
},{
"name": "Updated someName",
"type": "Updated someType",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
200,
(res) ->
create_dashboard_id = res.body._id
res.body.name.should.equal 'Updated Created from test'
res.body.user.should.equal operator._id
res.body.widgets.should.be.an 'Array'
res.body.widgets.length.should.equal 2
res.body.widgets[0].name.should.be.equal "Updated someName"
res.body.widgets[0].type.should.be.equal "Updated someType"
res.body.widgets[0].pattern.should.exists
done()
)
return
after (done) ->
dashboard.delete(server,cookies, create_dashboard_id, {user: operator._id}, 200,
(res) ->
res.body.ok.should.be.equal 1
done()
)
return
describe 'with missing params', ->
it 'should not create a new dashboard at all', (done) ->
payload = {
"user": operator._id,
"widgets": [{
"name": "someName",
"type": "asdfasdfasdf",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
500,
(res) ->
res.body.error.should.be.an 'Object'
res.body.error.name.should.equal 'ValidationError'
done()
)
return
| 127778 | #load application models
server = require('../../app')
_ = require('underscore');
dashboard = require('../api_objects/dashboard_api_object')
auth = require('../api_objects/auth_api_object')
user = require('../api_objects/user_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User with operator permission', ->
cookies = undefined;
operator = undefined;
create_dashboard_id = undefined
before (done) ->
auth.login(server, {username: "<EMAIL>", password:"<PASSWORD>"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
user.search(server,cookies,{username:"<EMAIL>"},200,
(res) ->
operator = res.body[0]
done()
)
)
return
it 'should create a new dashboard', (done) ->
payload = {
"user": operator._id,
"name": "Created from test"
"widgets": [{
"name": "<NAME>",
"type": "someType",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
200,
(res) ->
create_dashboard_id = res.body._id
res.body.name.should.equal 'Created from test'
res.body.user.should.equal operator._id
res.body.widgets.should.be.an 'Array'
res.body.widgets.length.should.equal 1
res.body.widgets[0].name.should.be.equal "someName"
res.body.widgets[0].type.should.be.equal "someType"
res.body.widgets[0].pattern.should.exists
done()
)
return
it 'should update a new dashboard', (done) ->
payload = {
"user": operator._id,
"_id": create_dashboard_id,
"name": "Updated Created from test"
"widgets": [{
"name": "<NAME> <NAME>",
"type": "Updated someType",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
},{
"name": "<NAME> <NAME>",
"type": "Updated someType",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
200,
(res) ->
create_dashboard_id = res.body._id
res.body.name.should.equal 'Updated Created from test'
res.body.user.should.equal operator._id
res.body.widgets.should.be.an 'Array'
res.body.widgets.length.should.equal 2
res.body.widgets[0].name.should.be.equal "<NAME> <NAME>"
res.body.widgets[0].type.should.be.equal "Updated someType"
res.body.widgets[0].pattern.should.exists
done()
)
return
after (done) ->
dashboard.delete(server,cookies, create_dashboard_id, {user: operator._id}, 200,
(res) ->
res.body.ok.should.be.equal 1
done()
)
return
describe 'with missing params', ->
it 'should not create a new dashboard at all', (done) ->
payload = {
"user": operator._id,
"widgets": [{
"name": "<NAME>",
"type": "asdfasdfasdf",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
500,
(res) ->
res.body.error.should.be.an 'Object'
res.body.error.name.should.equal 'ValidationError'
done()
)
return
| true | #load application models
server = require('../../app')
_ = require('underscore');
dashboard = require('../api_objects/dashboard_api_object')
auth = require('../api_objects/auth_api_object')
user = require('../api_objects/user_api_object')
mongoose = require('mongoose')
chai = require('chai')
chaiHttp = require('chai-http')
moment = require('moment')
should = chai.should()
chai.use chaiHttp
describe 'User with operator permission', ->
cookies = undefined;
operator = undefined;
create_dashboard_id = undefined
before (done) ->
auth.login(server, {username: "PI:EMAIL:<EMAIL>END_PI", password:"PI:PASSWORD:<PASSWORD>END_PI"}, 200,
(res)->
cookies = res.headers['set-cookie'].pop().split(';')[0];
user.search(server,cookies,{username:"PI:EMAIL:<EMAIL>END_PI"},200,
(res) ->
operator = res.body[0]
done()
)
)
return
it 'should create a new dashboard', (done) ->
payload = {
"user": operator._id,
"name": "Created from test"
"widgets": [{
"name": "PI:NAME:<NAME>END_PI",
"type": "someType",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
200,
(res) ->
create_dashboard_id = res.body._id
res.body.name.should.equal 'Created from test'
res.body.user.should.equal operator._id
res.body.widgets.should.be.an 'Array'
res.body.widgets.length.should.equal 1
res.body.widgets[0].name.should.be.equal "someName"
res.body.widgets[0].type.should.be.equal "someType"
res.body.widgets[0].pattern.should.exists
done()
)
return
it 'should update a new dashboard', (done) ->
payload = {
"user": operator._id,
"_id": create_dashboard_id,
"name": "Updated Created from test"
"widgets": [{
"name": "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI",
"type": "Updated someType",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
},{
"name": "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI",
"type": "Updated someType",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
200,
(res) ->
create_dashboard_id = res.body._id
res.body.name.should.equal 'Updated Created from test'
res.body.user.should.equal operator._id
res.body.widgets.should.be.an 'Array'
res.body.widgets.length.should.equal 2
res.body.widgets[0].name.should.be.equal "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
res.body.widgets[0].type.should.be.equal "Updated someType"
res.body.widgets[0].pattern.should.exists
done()
)
return
after (done) ->
dashboard.delete(server,cookies, create_dashboard_id, {user: operator._id}, 200,
(res) ->
res.body.ok.should.be.equal 1
done()
)
return
describe 'with missing params', ->
it 'should not create a new dashboard at all', (done) ->
payload = {
"user": operator._id,
"widgets": [{
"name": "PI:NAME:<NAME>END_PI",
"type": "asdfasdfasdf",
"cols": 1, "rows": 1, "y": 11, "x": 8, "dragEnabled": false, "resizeEnabled": false,
"pattern": {
"status": {
"all": true,
"rerun": false,
"pass": false,
"fail": false,
"skip": false,
"ki": false
},
"relations" : {},
},
"status": {"name" : "AAAAA"}
}]
}
dashboard.create(server, cookies,
payload,
500,
(res) ->
res.body.error.should.be.an 'Object'
res.body.error.name.should.equal 'ValidationError'
done()
)
return
|
[
{
"context": " = (storyName, secretKey) ->\n {\n branch_key: 'key_live_haoXB4nBJ0AHZj0o1OFOGjafzFa8nQOG'\n channel: 'sms'\n feature: 'sharing'\n da",
"end": 447,
"score": 0.999681830406189,
"start": 406,
"tag": "KEY",
"value": "key_live_haoXB4nBJ0AHZj0o1OFOGjafzFa8nQOG"
}
] | src/utils/utils.coffee | arif2009/Gobi-Web-Integration | 0 | qrDataToDataUrl = (qrData) ->
new (promise_polyfill_1.default)((resolve, reject) ->
canvas = document.createElement('canvas')
qrcode_1.default.toCanvas canvas, qrData, (error) ->
if error
console.error error
reject error
dataUrl = canvas.toDataURL()
resolve dataUrl
return
return
)
makeBranchQueryData = (storyName, secretKey) ->
{
branch_key: 'key_live_haoXB4nBJ0AHZj0o1OFOGjafzFa8nQOG'
channel: 'sms'
feature: 'sharing'
data:
'~creation_source': 3
'$ios_url': 'https://itunes.apple.com/us/app/gobi-send-snaps-in-groups!/id1025344825?mt=8'
$desktop_url: 'http://www.gobiapp.com'
$identity_id: '624199976595486526'
$og_image_url: 'https://gobiapp.com/img/gobi_blue.png'
'$og_description': 'Create videos in this story :)'
$canonical_identifier: 'group/' + storyName
$og_title: 'Gobi'
$one_time_use: false
$publicly_indexable: false
action: 'groupAdd'
username: ''
group: storyName
id: 'auto-' + secretKey
source: 'Gobi-Web-Integration'
}
makeViewKey = (secretKey) ->
execd = secretKey.match('^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$')
if !execd
throw new Error('secretKey malformed')
uuidNodePart = execd[5]
uuidNodePartInt = parseInt(uuidNodePart, 0x10)
nodeInBase58 = base58_1.int_to_base58(uuidNodePartInt)
node8Characters = nodeInBase58.slice(-8)
node8Characters
makeRandomStorySecretKey = ->
gobiUuid = v5_1.default('gobistories.co', v5_1.default.DNS)
storySecretKey = uuid_1.default.v4(gobiUuid)
storySecretKey
getBranchLink = (data) ->
url = 'https://api2.branch.io/v1/url'
fetching = fetch(url,
method: 'POST'
mode: 'cors'
headers: 'Content-Type': 'application/json'
body: JSON.stringify(data)).then((response) ->
response.json()
)
fetching
addPrefixToClassName = (list, prefix) ->
max = list.length
elem = undefined
i = 0
while i < max
elem = list[i]
elem.className = prefix + elem.className
i++
return
returnHighestZIndex = ->
elems = document.body.querySelectorAll('*')
maxZIndex = 1
currentZIndex = 0
i = elems.length
while i--
currentZIndex = Number(window.getComputedStyle(elems[i]).zIndex)
if maxZIndex < currentZIndex
maxZIndex = currentZIndex
maxZIndex
fetchAvatarAndTitleGivenViewKey = (viewKey) ->
url = 'https://live.gobiapp.com/api/v4/story/by_view_key/' + viewKey
inner url, viewKey
fetchAvatarAndTitleGivenStoryId = (storyId) ->
url = 'https://live.gobiapp.com/projector/player/stories/' + storyId
inner url, storyId
inner = (url, key_or_id) ->
new (promise_polyfill_1.default)((resolve, reject) ->
xhr = new XMLHttpRequest
xhr.open 'GET', url, true
xhr.send()
xhr.onload = ->
if @status < 400
response = JSON.parse(@responseText)
if response and response.videos and response.videos[0]
src = response.videos[0].poster
title = response.title or response.videos[0].title
resolve
src: src
title: title
else
reject Error('No video[0] for story ' + url + ' -- ' + xhr.statusText)
else
reject Error('Error loading info for story ' + url + ' -- ' + xhr.statusText)
return
xhr.onerror = ->
reject Error('Error xhr-ing info for url ' + url)
return
return
)
'use strict'
Object.defineProperty exports, '__esModule', value: true
tslib_1 = require('tslib')
promise_polyfill_1 = tslib_1.__importDefault(require('promise-polyfill'))
uuid_1 = tslib_1.__importDefault(require('uuid'))
v5_1 = tslib_1.__importDefault(require('uuid/v5'))
base58_1 = require('@/base58')
qrcode_1 = tslib_1.__importDefault(require('qrcode'))
exports.qrDataToDataUrl = qrDataToDataUrl
exports.makeBranchQueryData = makeBranchQueryData
exports.makeViewKey = makeViewKey
exports.makeRandomStorySecretKey = makeRandomStorySecretKey
exports.getBranchLink = getBranchLink
exports.addPrefixToClassName = addPrefixToClassName
exports.returnHighestZIndex = returnHighestZIndex
exports.scrollDisabler =
scrollTop: 0
bodyOverflow: ''
htmlOverflow: ''
disable: ->
if @isIOS then @IOSDisable() else @classicDisable()
return
enable: ->
if @isIOS then @IOSEnable() else @classicEnable()
return
classicDisable: ->
@bodyOverflow = document.body.style.overflow
@htmlOverflow = document.documentElement.style.overflow
document.documentElement.style.overflow = 'hidden'
document.body.style.overflow = 'hidden'
return
classicEnable: ->
document.documentElement.style.overflow = @htmlOverflow
document.body.style.overflow = @bodyOverflow
return
IOSEnable: ->
document.documentElement.classList.remove 'disabled-scroll'
document.body.classList.remove 'disabled-scroll'
window.scrollTo 0, @scrollTop
return
IOSDisable: ->
@scrollTop = window.pageYOffset
document.documentElement.classList.add 'disabled-scroll'
document.body.classList.add 'disabled-scroll'
return
isIOS: /iPad|iPhone|iPod/.test(navigator.userAgent)
exports.fetchAvatarAndTitleGivenViewKey = fetchAvatarAndTitleGivenViewKey
exports.fetchAvatarAndTitleGivenStoryId = fetchAvatarAndTitleGivenStoryId
| 75287 | qrDataToDataUrl = (qrData) ->
new (promise_polyfill_1.default)((resolve, reject) ->
canvas = document.createElement('canvas')
qrcode_1.default.toCanvas canvas, qrData, (error) ->
if error
console.error error
reject error
dataUrl = canvas.toDataURL()
resolve dataUrl
return
return
)
makeBranchQueryData = (storyName, secretKey) ->
{
branch_key: '<KEY>'
channel: 'sms'
feature: 'sharing'
data:
'~creation_source': 3
'$ios_url': 'https://itunes.apple.com/us/app/gobi-send-snaps-in-groups!/id1025344825?mt=8'
$desktop_url: 'http://www.gobiapp.com'
$identity_id: '624199976595486526'
$og_image_url: 'https://gobiapp.com/img/gobi_blue.png'
'$og_description': 'Create videos in this story :)'
$canonical_identifier: 'group/' + storyName
$og_title: 'Gobi'
$one_time_use: false
$publicly_indexable: false
action: 'groupAdd'
username: ''
group: storyName
id: 'auto-' + secretKey
source: 'Gobi-Web-Integration'
}
makeViewKey = (secretKey) ->
execd = secretKey.match('^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$')
if !execd
throw new Error('secretKey malformed')
uuidNodePart = execd[5]
uuidNodePartInt = parseInt(uuidNodePart, 0x10)
nodeInBase58 = base58_1.int_to_base58(uuidNodePartInt)
node8Characters = nodeInBase58.slice(-8)
node8Characters
makeRandomStorySecretKey = ->
gobiUuid = v5_1.default('gobistories.co', v5_1.default.DNS)
storySecretKey = uuid_1.default.v4(gobiUuid)
storySecretKey
getBranchLink = (data) ->
url = 'https://api2.branch.io/v1/url'
fetching = fetch(url,
method: 'POST'
mode: 'cors'
headers: 'Content-Type': 'application/json'
body: JSON.stringify(data)).then((response) ->
response.json()
)
fetching
addPrefixToClassName = (list, prefix) ->
max = list.length
elem = undefined
i = 0
while i < max
elem = list[i]
elem.className = prefix + elem.className
i++
return
returnHighestZIndex = ->
elems = document.body.querySelectorAll('*')
maxZIndex = 1
currentZIndex = 0
i = elems.length
while i--
currentZIndex = Number(window.getComputedStyle(elems[i]).zIndex)
if maxZIndex < currentZIndex
maxZIndex = currentZIndex
maxZIndex
fetchAvatarAndTitleGivenViewKey = (viewKey) ->
url = 'https://live.gobiapp.com/api/v4/story/by_view_key/' + viewKey
inner url, viewKey
fetchAvatarAndTitleGivenStoryId = (storyId) ->
url = 'https://live.gobiapp.com/projector/player/stories/' + storyId
inner url, storyId
inner = (url, key_or_id) ->
new (promise_polyfill_1.default)((resolve, reject) ->
xhr = new XMLHttpRequest
xhr.open 'GET', url, true
xhr.send()
xhr.onload = ->
if @status < 400
response = JSON.parse(@responseText)
if response and response.videos and response.videos[0]
src = response.videos[0].poster
title = response.title or response.videos[0].title
resolve
src: src
title: title
else
reject Error('No video[0] for story ' + url + ' -- ' + xhr.statusText)
else
reject Error('Error loading info for story ' + url + ' -- ' + xhr.statusText)
return
xhr.onerror = ->
reject Error('Error xhr-ing info for url ' + url)
return
return
)
'use strict'
Object.defineProperty exports, '__esModule', value: true
tslib_1 = require('tslib')
promise_polyfill_1 = tslib_1.__importDefault(require('promise-polyfill'))
uuid_1 = tslib_1.__importDefault(require('uuid'))
v5_1 = tslib_1.__importDefault(require('uuid/v5'))
base58_1 = require('@/base58')
qrcode_1 = tslib_1.__importDefault(require('qrcode'))
exports.qrDataToDataUrl = qrDataToDataUrl
exports.makeBranchQueryData = makeBranchQueryData
exports.makeViewKey = makeViewKey
exports.makeRandomStorySecretKey = makeRandomStorySecretKey
exports.getBranchLink = getBranchLink
exports.addPrefixToClassName = addPrefixToClassName
exports.returnHighestZIndex = returnHighestZIndex
exports.scrollDisabler =
scrollTop: 0
bodyOverflow: ''
htmlOverflow: ''
disable: ->
if @isIOS then @IOSDisable() else @classicDisable()
return
enable: ->
if @isIOS then @IOSEnable() else @classicEnable()
return
classicDisable: ->
@bodyOverflow = document.body.style.overflow
@htmlOverflow = document.documentElement.style.overflow
document.documentElement.style.overflow = 'hidden'
document.body.style.overflow = 'hidden'
return
classicEnable: ->
document.documentElement.style.overflow = @htmlOverflow
document.body.style.overflow = @bodyOverflow
return
IOSEnable: ->
document.documentElement.classList.remove 'disabled-scroll'
document.body.classList.remove 'disabled-scroll'
window.scrollTo 0, @scrollTop
return
IOSDisable: ->
@scrollTop = window.pageYOffset
document.documentElement.classList.add 'disabled-scroll'
document.body.classList.add 'disabled-scroll'
return
isIOS: /iPad|iPhone|iPod/.test(navigator.userAgent)
exports.fetchAvatarAndTitleGivenViewKey = fetchAvatarAndTitleGivenViewKey
exports.fetchAvatarAndTitleGivenStoryId = fetchAvatarAndTitleGivenStoryId
| true | qrDataToDataUrl = (qrData) ->
new (promise_polyfill_1.default)((resolve, reject) ->
canvas = document.createElement('canvas')
qrcode_1.default.toCanvas canvas, qrData, (error) ->
if error
console.error error
reject error
dataUrl = canvas.toDataURL()
resolve dataUrl
return
return
)
makeBranchQueryData = (storyName, secretKey) ->
{
branch_key: 'PI:KEY:<KEY>END_PI'
channel: 'sms'
feature: 'sharing'
data:
'~creation_source': 3
'$ios_url': 'https://itunes.apple.com/us/app/gobi-send-snaps-in-groups!/id1025344825?mt=8'
$desktop_url: 'http://www.gobiapp.com'
$identity_id: '624199976595486526'
$og_image_url: 'https://gobiapp.com/img/gobi_blue.png'
'$og_description': 'Create videos in this story :)'
$canonical_identifier: 'group/' + storyName
$og_title: 'Gobi'
$one_time_use: false
$publicly_indexable: false
action: 'groupAdd'
username: ''
group: storyName
id: 'auto-' + secretKey
source: 'Gobi-Web-Integration'
}
makeViewKey = (secretKey) ->
execd = secretKey.match('^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$')
if !execd
throw new Error('secretKey malformed')
uuidNodePart = execd[5]
uuidNodePartInt = parseInt(uuidNodePart, 0x10)
nodeInBase58 = base58_1.int_to_base58(uuidNodePartInt)
node8Characters = nodeInBase58.slice(-8)
node8Characters
makeRandomStorySecretKey = ->
gobiUuid = v5_1.default('gobistories.co', v5_1.default.DNS)
storySecretKey = uuid_1.default.v4(gobiUuid)
storySecretKey
getBranchLink = (data) ->
url = 'https://api2.branch.io/v1/url'
fetching = fetch(url,
method: 'POST'
mode: 'cors'
headers: 'Content-Type': 'application/json'
body: JSON.stringify(data)).then((response) ->
response.json()
)
fetching
addPrefixToClassName = (list, prefix) ->
max = list.length
elem = undefined
i = 0
while i < max
elem = list[i]
elem.className = prefix + elem.className
i++
return
returnHighestZIndex = ->
elems = document.body.querySelectorAll('*')
maxZIndex = 1
currentZIndex = 0
i = elems.length
while i--
currentZIndex = Number(window.getComputedStyle(elems[i]).zIndex)
if maxZIndex < currentZIndex
maxZIndex = currentZIndex
maxZIndex
fetchAvatarAndTitleGivenViewKey = (viewKey) ->
url = 'https://live.gobiapp.com/api/v4/story/by_view_key/' + viewKey
inner url, viewKey
fetchAvatarAndTitleGivenStoryId = (storyId) ->
url = 'https://live.gobiapp.com/projector/player/stories/' + storyId
inner url, storyId
inner = (url, key_or_id) ->
new (promise_polyfill_1.default)((resolve, reject) ->
xhr = new XMLHttpRequest
xhr.open 'GET', url, true
xhr.send()
xhr.onload = ->
if @status < 400
response = JSON.parse(@responseText)
if response and response.videos and response.videos[0]
src = response.videos[0].poster
title = response.title or response.videos[0].title
resolve
src: src
title: title
else
reject Error('No video[0] for story ' + url + ' -- ' + xhr.statusText)
else
reject Error('Error loading info for story ' + url + ' -- ' + xhr.statusText)
return
xhr.onerror = ->
reject Error('Error xhr-ing info for url ' + url)
return
return
)
'use strict'
Object.defineProperty exports, '__esModule', value: true
tslib_1 = require('tslib')
promise_polyfill_1 = tslib_1.__importDefault(require('promise-polyfill'))
uuid_1 = tslib_1.__importDefault(require('uuid'))
v5_1 = tslib_1.__importDefault(require('uuid/v5'))
base58_1 = require('@/base58')
qrcode_1 = tslib_1.__importDefault(require('qrcode'))
exports.qrDataToDataUrl = qrDataToDataUrl
exports.makeBranchQueryData = makeBranchQueryData
exports.makeViewKey = makeViewKey
exports.makeRandomStorySecretKey = makeRandomStorySecretKey
exports.getBranchLink = getBranchLink
exports.addPrefixToClassName = addPrefixToClassName
exports.returnHighestZIndex = returnHighestZIndex
exports.scrollDisabler =
scrollTop: 0
bodyOverflow: ''
htmlOverflow: ''
disable: ->
if @isIOS then @IOSDisable() else @classicDisable()
return
enable: ->
if @isIOS then @IOSEnable() else @classicEnable()
return
classicDisable: ->
@bodyOverflow = document.body.style.overflow
@htmlOverflow = document.documentElement.style.overflow
document.documentElement.style.overflow = 'hidden'
document.body.style.overflow = 'hidden'
return
classicEnable: ->
document.documentElement.style.overflow = @htmlOverflow
document.body.style.overflow = @bodyOverflow
return
IOSEnable: ->
document.documentElement.classList.remove 'disabled-scroll'
document.body.classList.remove 'disabled-scroll'
window.scrollTo 0, @scrollTop
return
IOSDisable: ->
@scrollTop = window.pageYOffset
document.documentElement.classList.add 'disabled-scroll'
document.body.classList.add 'disabled-scroll'
return
isIOS: /iPad|iPhone|iPod/.test(navigator.userAgent)
exports.fetchAvatarAndTitleGivenViewKey = fetchAvatarAndTitleGivenViewKey
exports.fetchAvatarAndTitleGivenStoryId = fetchAvatarAndTitleGivenStoryId
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9993535876274109,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-writeint.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# * Tests to verify we're writing signed integers correctly
#
test8 = (clazz) ->
buffer = new clazz(2)
buffer.writeInt8 0x23, 0
buffer.writeInt8 -5, 1
ASSERT.equal 0x23, buffer[0]
ASSERT.equal 0xfb, buffer[1]
# Make sure we handle truncation correctly
ASSERT.throws ->
buffer.writeInt8 0xabc, 0
return
ASSERT.throws ->
buffer.writeInt8 0xabc, 0
return
# Make sure we handle min/max correctly
buffer.writeInt8 0x7f, 0
buffer.writeInt8 -0x80, 1
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0x80, buffer[1]
ASSERT.throws ->
buffer.writeInt8 0x7f + 1, 0
return
ASSERT.throws ->
buffer.writeInt8 -0x80 - 1, 0
return
return
test16 = (clazz) ->
buffer = new clazz(6)
buffer.writeInt16BE 0x0023, 0
buffer.writeInt16LE 0x0023, 2
ASSERT.equal 0x00, buffer[0]
ASSERT.equal 0x23, buffer[1]
ASSERT.equal 0x23, buffer[2]
ASSERT.equal 0x00, buffer[3]
buffer.writeInt16BE -5, 0
buffer.writeInt16LE -5, 2
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xfb, buffer[1]
ASSERT.equal 0xfb, buffer[2]
ASSERT.equal 0xff, buffer[3]
buffer.writeInt16BE -1679, 1
buffer.writeInt16LE -1679, 3
ASSERT.equal 0xf9, buffer[1]
ASSERT.equal 0x71, buffer[2]
ASSERT.equal 0x71, buffer[3]
ASSERT.equal 0xf9, buffer[4]
# Make sure we handle min/max correctly
buffer.writeInt16BE 0x7fff, 0
buffer.writeInt16BE -0x8000, 2
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0x80, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.throws ->
buffer.writeInt16BE 0x7fff + 1, 0
return
ASSERT.throws ->
buffer.writeInt16BE -0x8000 - 1, 0
return
buffer.writeInt16LE 0x7fff, 0
buffer.writeInt16LE -0x8000, 2
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0x7f, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x80, buffer[3]
ASSERT.throws ->
buffer.writeInt16LE 0x7fff + 1, 0
return
ASSERT.throws ->
buffer.writeInt16LE -0x8000 - 1, 0
return
return
test32 = (clazz) ->
buffer = new clazz(8)
buffer.writeInt32BE 0x23, 0
buffer.writeInt32LE 0x23, 4
ASSERT.equal 0x00, buffer[0]
ASSERT.equal 0x00, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x23, buffer[3]
ASSERT.equal 0x23, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
buffer.writeInt32BE -5, 0
buffer.writeInt32LE -5, 4
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xfb, buffer[3]
ASSERT.equal 0xfb, buffer[4]
ASSERT.equal 0xff, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xff, buffer[7]
buffer.writeInt32BE -805306713, 0
buffer.writeInt32LE -805306713, 4
ASSERT.equal 0xcf, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xfe, buffer[2]
ASSERT.equal 0xa7, buffer[3]
ASSERT.equal 0xa7, buffer[4]
ASSERT.equal 0xfe, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xcf, buffer[7]
# Make sure we handle min/max correctly
buffer.writeInt32BE 0x7fffffff, 0
buffer.writeInt32BE -0x80000000, 4
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xff, buffer[3]
ASSERT.equal 0x80, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.throws ->
buffer.writeInt32BE 0x7fffffff + 1, 0
return
ASSERT.throws ->
buffer.writeInt32BE -0x80000000 - 1, 0
return
buffer.writeInt32LE 0x7fffffff, 0
buffer.writeInt32LE -0x80000000, 4
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0x7f, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x80, buffer[7]
ASSERT.throws ->
buffer.writeInt32LE 0x7fffffff + 1, 0
return
ASSERT.throws ->
buffer.writeInt32LE -0x80000000 - 1, 0
return
return
common = require("../common")
ASSERT = require("assert")
test8 Buffer
test16 Buffer
test32 Buffer
| 120445 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# * Tests to verify we're writing signed integers correctly
#
test8 = (clazz) ->
buffer = new clazz(2)
buffer.writeInt8 0x23, 0
buffer.writeInt8 -5, 1
ASSERT.equal 0x23, buffer[0]
ASSERT.equal 0xfb, buffer[1]
# Make sure we handle truncation correctly
ASSERT.throws ->
buffer.writeInt8 0xabc, 0
return
ASSERT.throws ->
buffer.writeInt8 0xabc, 0
return
# Make sure we handle min/max correctly
buffer.writeInt8 0x7f, 0
buffer.writeInt8 -0x80, 1
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0x80, buffer[1]
ASSERT.throws ->
buffer.writeInt8 0x7f + 1, 0
return
ASSERT.throws ->
buffer.writeInt8 -0x80 - 1, 0
return
return
test16 = (clazz) ->
buffer = new clazz(6)
buffer.writeInt16BE 0x0023, 0
buffer.writeInt16LE 0x0023, 2
ASSERT.equal 0x00, buffer[0]
ASSERT.equal 0x23, buffer[1]
ASSERT.equal 0x23, buffer[2]
ASSERT.equal 0x00, buffer[3]
buffer.writeInt16BE -5, 0
buffer.writeInt16LE -5, 2
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xfb, buffer[1]
ASSERT.equal 0xfb, buffer[2]
ASSERT.equal 0xff, buffer[3]
buffer.writeInt16BE -1679, 1
buffer.writeInt16LE -1679, 3
ASSERT.equal 0xf9, buffer[1]
ASSERT.equal 0x71, buffer[2]
ASSERT.equal 0x71, buffer[3]
ASSERT.equal 0xf9, buffer[4]
# Make sure we handle min/max correctly
buffer.writeInt16BE 0x7fff, 0
buffer.writeInt16BE -0x8000, 2
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0x80, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.throws ->
buffer.writeInt16BE 0x7fff + 1, 0
return
ASSERT.throws ->
buffer.writeInt16BE -0x8000 - 1, 0
return
buffer.writeInt16LE 0x7fff, 0
buffer.writeInt16LE -0x8000, 2
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0x7f, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x80, buffer[3]
ASSERT.throws ->
buffer.writeInt16LE 0x7fff + 1, 0
return
ASSERT.throws ->
buffer.writeInt16LE -0x8000 - 1, 0
return
return
test32 = (clazz) ->
buffer = new clazz(8)
buffer.writeInt32BE 0x23, 0
buffer.writeInt32LE 0x23, 4
ASSERT.equal 0x00, buffer[0]
ASSERT.equal 0x00, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x23, buffer[3]
ASSERT.equal 0x23, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
buffer.writeInt32BE -5, 0
buffer.writeInt32LE -5, 4
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xfb, buffer[3]
ASSERT.equal 0xfb, buffer[4]
ASSERT.equal 0xff, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xff, buffer[7]
buffer.writeInt32BE -805306713, 0
buffer.writeInt32LE -805306713, 4
ASSERT.equal 0xcf, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xfe, buffer[2]
ASSERT.equal 0xa7, buffer[3]
ASSERT.equal 0xa7, buffer[4]
ASSERT.equal 0xfe, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xcf, buffer[7]
# Make sure we handle min/max correctly
buffer.writeInt32BE 0x7fffffff, 0
buffer.writeInt32BE -0x80000000, 4
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xff, buffer[3]
ASSERT.equal 0x80, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.throws ->
buffer.writeInt32BE 0x7fffffff + 1, 0
return
ASSERT.throws ->
buffer.writeInt32BE -0x80000000 - 1, 0
return
buffer.writeInt32LE 0x7fffffff, 0
buffer.writeInt32LE -0x80000000, 4
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0x7f, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x80, buffer[7]
ASSERT.throws ->
buffer.writeInt32LE 0x7fffffff + 1, 0
return
ASSERT.throws ->
buffer.writeInt32LE -0x80000000 - 1, 0
return
return
common = require("../common")
ASSERT = require("assert")
test8 Buffer
test16 Buffer
test32 Buffer
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# * Tests to verify we're writing signed integers correctly
#
test8 = (clazz) ->
buffer = new clazz(2)
buffer.writeInt8 0x23, 0
buffer.writeInt8 -5, 1
ASSERT.equal 0x23, buffer[0]
ASSERT.equal 0xfb, buffer[1]
# Make sure we handle truncation correctly
ASSERT.throws ->
buffer.writeInt8 0xabc, 0
return
ASSERT.throws ->
buffer.writeInt8 0xabc, 0
return
# Make sure we handle min/max correctly
buffer.writeInt8 0x7f, 0
buffer.writeInt8 -0x80, 1
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0x80, buffer[1]
ASSERT.throws ->
buffer.writeInt8 0x7f + 1, 0
return
ASSERT.throws ->
buffer.writeInt8 -0x80 - 1, 0
return
return
test16 = (clazz) ->
buffer = new clazz(6)
buffer.writeInt16BE 0x0023, 0
buffer.writeInt16LE 0x0023, 2
ASSERT.equal 0x00, buffer[0]
ASSERT.equal 0x23, buffer[1]
ASSERT.equal 0x23, buffer[2]
ASSERT.equal 0x00, buffer[3]
buffer.writeInt16BE -5, 0
buffer.writeInt16LE -5, 2
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xfb, buffer[1]
ASSERT.equal 0xfb, buffer[2]
ASSERT.equal 0xff, buffer[3]
buffer.writeInt16BE -1679, 1
buffer.writeInt16LE -1679, 3
ASSERT.equal 0xf9, buffer[1]
ASSERT.equal 0x71, buffer[2]
ASSERT.equal 0x71, buffer[3]
ASSERT.equal 0xf9, buffer[4]
# Make sure we handle min/max correctly
buffer.writeInt16BE 0x7fff, 0
buffer.writeInt16BE -0x8000, 2
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0x80, buffer[2]
ASSERT.equal 0x00, buffer[3]
ASSERT.throws ->
buffer.writeInt16BE 0x7fff + 1, 0
return
ASSERT.throws ->
buffer.writeInt16BE -0x8000 - 1, 0
return
buffer.writeInt16LE 0x7fff, 0
buffer.writeInt16LE -0x8000, 2
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0x7f, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x80, buffer[3]
ASSERT.throws ->
buffer.writeInt16LE 0x7fff + 1, 0
return
ASSERT.throws ->
buffer.writeInt16LE -0x8000 - 1, 0
return
return
test32 = (clazz) ->
buffer = new clazz(8)
buffer.writeInt32BE 0x23, 0
buffer.writeInt32LE 0x23, 4
ASSERT.equal 0x00, buffer[0]
ASSERT.equal 0x00, buffer[1]
ASSERT.equal 0x00, buffer[2]
ASSERT.equal 0x23, buffer[3]
ASSERT.equal 0x23, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
buffer.writeInt32BE -5, 0
buffer.writeInt32LE -5, 4
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xfb, buffer[3]
ASSERT.equal 0xfb, buffer[4]
ASSERT.equal 0xff, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xff, buffer[7]
buffer.writeInt32BE -805306713, 0
buffer.writeInt32LE -805306713, 4
ASSERT.equal 0xcf, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xfe, buffer[2]
ASSERT.equal 0xa7, buffer[3]
ASSERT.equal 0xa7, buffer[4]
ASSERT.equal 0xfe, buffer[5]
ASSERT.equal 0xff, buffer[6]
ASSERT.equal 0xcf, buffer[7]
# Make sure we handle min/max correctly
buffer.writeInt32BE 0x7fffffff, 0
buffer.writeInt32BE -0x80000000, 4
ASSERT.equal 0x7f, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0xff, buffer[3]
ASSERT.equal 0x80, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x00, buffer[7]
ASSERT.throws ->
buffer.writeInt32BE 0x7fffffff + 1, 0
return
ASSERT.throws ->
buffer.writeInt32BE -0x80000000 - 1, 0
return
buffer.writeInt32LE 0x7fffffff, 0
buffer.writeInt32LE -0x80000000, 4
ASSERT.equal 0xff, buffer[0]
ASSERT.equal 0xff, buffer[1]
ASSERT.equal 0xff, buffer[2]
ASSERT.equal 0x7f, buffer[3]
ASSERT.equal 0x00, buffer[4]
ASSERT.equal 0x00, buffer[5]
ASSERT.equal 0x00, buffer[6]
ASSERT.equal 0x80, buffer[7]
ASSERT.throws ->
buffer.writeInt32LE 0x7fffffff + 1, 0
return
ASSERT.throws ->
buffer.writeInt32LE -0x80000000 - 1, 0
return
return
common = require("../common")
ASSERT = require("assert")
test8 Buffer
test16 Buffer
test32 Buffer
|
[
{
"context": " env variable 'REQUEST='{headers: {x-api-token: \\\"234678k2jk3\\\"} }' to pass custom requestdata to the request obj",
"end": 355,
"score": 0.9548976421356201,
"start": 342,
"tag": "KEY",
"value": "234678k2jk3\\\""
}
] | app/server/webhook.coffee | coderofsalvation/express-api-user-management-signup | 1 | module.exports = (app,router,requestdata) ->
# initializing default request settings
if !requestdata
if !process.env.REQUEST
process.env.REQUEST = "{}"
console.log "using 'request' npm lib without any basic http authentication or auth-tokens"
console.log "HINT: set env variable 'REQUEST='{headers: {x-api-token: \"234678k2jk3\"} }' to pass custom requestdata to the request object"
requestdata = JSON.parse(process.env.REQUEST)
if !process.env.WEBHOOK_URL
process.env.WEBHOOK_URL = "http://localhost:9991/account"
console.warn 'environment variable \'WEBHOOK_URL\' not set, default to value "'+process.env.WEBHOOK_URL+'"'
console.log 'using webhook url: '+process.env.WEBHOOK_URL
console.log 'warning: use webhooks only in an secure (https) intranet environment, you have been warned :)'
request = require("request")
callWebhook = (method, url, data) ->
delete data["pass"] if data.pass
payload = requestdata
payload.url = process.env.WEBHOOK_URL+url
payload.body = data
payload.json = true
request[method] payload, (err,response,body) ->
console.log "triggering webhook: "+method+" "+payload.url
router.AM.event.on 'addNewAccount', (data) ->
callWebhook "post", "/add", data
router.AM.event.on 'updateAccount', (data) ->
callWebhook "post", "/update", data
router.AM.event.on 'updatePassword', (data) ->
callWebhook "post", "/update/pass", data
router.AM.event.on 'updateApikey', (data) ->
callWebhook "post", "/update/apikey", data
router.AM.event.on 'login', (data) ->
callWebhook "post", "/login", data
router.EM.event.on 'resetPasswordLink', (data) ->
callWebhook "post", "/reset/pass", data
| 160065 | module.exports = (app,router,requestdata) ->
# initializing default request settings
if !requestdata
if !process.env.REQUEST
process.env.REQUEST = "{}"
console.log "using 'request' npm lib without any basic http authentication or auth-tokens"
console.log "HINT: set env variable 'REQUEST='{headers: {x-api-token: \"<KEY>} }' to pass custom requestdata to the request object"
requestdata = JSON.parse(process.env.REQUEST)
if !process.env.WEBHOOK_URL
process.env.WEBHOOK_URL = "http://localhost:9991/account"
console.warn 'environment variable \'WEBHOOK_URL\' not set, default to value "'+process.env.WEBHOOK_URL+'"'
console.log 'using webhook url: '+process.env.WEBHOOK_URL
console.log 'warning: use webhooks only in an secure (https) intranet environment, you have been warned :)'
request = require("request")
callWebhook = (method, url, data) ->
delete data["pass"] if data.pass
payload = requestdata
payload.url = process.env.WEBHOOK_URL+url
payload.body = data
payload.json = true
request[method] payload, (err,response,body) ->
console.log "triggering webhook: "+method+" "+payload.url
router.AM.event.on 'addNewAccount', (data) ->
callWebhook "post", "/add", data
router.AM.event.on 'updateAccount', (data) ->
callWebhook "post", "/update", data
router.AM.event.on 'updatePassword', (data) ->
callWebhook "post", "/update/pass", data
router.AM.event.on 'updateApikey', (data) ->
callWebhook "post", "/update/apikey", data
router.AM.event.on 'login', (data) ->
callWebhook "post", "/login", data
router.EM.event.on 'resetPasswordLink', (data) ->
callWebhook "post", "/reset/pass", data
| true | module.exports = (app,router,requestdata) ->
# initializing default request settings
if !requestdata
if !process.env.REQUEST
process.env.REQUEST = "{}"
console.log "using 'request' npm lib without any basic http authentication or auth-tokens"
console.log "HINT: set env variable 'REQUEST='{headers: {x-api-token: \"PI:KEY:<KEY>END_PI} }' to pass custom requestdata to the request object"
requestdata = JSON.parse(process.env.REQUEST)
if !process.env.WEBHOOK_URL
process.env.WEBHOOK_URL = "http://localhost:9991/account"
console.warn 'environment variable \'WEBHOOK_URL\' not set, default to value "'+process.env.WEBHOOK_URL+'"'
console.log 'using webhook url: '+process.env.WEBHOOK_URL
console.log 'warning: use webhooks only in an secure (https) intranet environment, you have been warned :)'
request = require("request")
callWebhook = (method, url, data) ->
delete data["pass"] if data.pass
payload = requestdata
payload.url = process.env.WEBHOOK_URL+url
payload.body = data
payload.json = true
request[method] payload, (err,response,body) ->
console.log "triggering webhook: "+method+" "+payload.url
router.AM.event.on 'addNewAccount', (data) ->
callWebhook "post", "/add", data
router.AM.event.on 'updateAccount', (data) ->
callWebhook "post", "/update", data
router.AM.event.on 'updatePassword', (data) ->
callWebhook "post", "/update/pass", data
router.AM.event.on 'updateApikey', (data) ->
callWebhook "post", "/update/apikey", data
router.AM.event.on 'login', (data) ->
callWebhook "post", "/login", data
router.EM.event.on 'resetPasswordLink', (data) ->
callWebhook "post", "/reset/pass", data
|
[
{
"context": " server client.io handler for bace\n\n copyright mark hahn 2013\n MIT license\n https://github.com/mark-",
"end": 96,
"score": 0.9997302293777466,
"start": 87,
"tag": "NAME",
"value": "mark hahn"
},
{
"context": " hahn 2013\n MIT license\n https://github.com/mark-hahn/bace/\n###\n\nfs = require 'fs'\n_ = require '",
"end": 150,
"score": 0.9997315406799316,
"start": 141,
"tag": "USERNAME",
"value": "mark-hahn"
}
] | src/server/socket-srvr.coffee | mark-hahn/bace | 1 | ###
file: src/server/client-srvr
server client.io handler for bace
copyright mark hahn 2013
MIT license
https://github.com/mark-hahn/bace/
###
fs = require 'fs'
_ = require 'underscore'
_.mixin require('underscore.string').exports()
require 'colors'
settings = require './settings-srvr'
user = require './user-srvr'
cmdbox = require './cmdbox-srvr'
dirbox = require './dirbox-srvr'
sock = exports
clientList = {}
sock.startup = (srvr) ->
io = require('socket.io').listen srvr, log:no
# io.set 'log level', 3
io.sockets.on 'connection', (client) ->
client.emit 'connected'
clientList[client.id] = client
user.init client
settings.init client
cmdbox.init client
dirbox.init client
client.on 'disconnect', -> delete clientList[client.id]
refreshAllClients = ->
console.log 'ss: refreshAllClients', _.size clientList
for id, client of clientList
client.emit 'refresh'
if fs.existsSync 'src'
# for debugging but can be used in production
fs.watch 'lib/page.css', refreshAllClients
fs.watch 'src/client', refreshAllClients
| 159333 | ###
file: src/server/client-srvr
server client.io handler for bace
copyright <NAME> 2013
MIT license
https://github.com/mark-hahn/bace/
###
fs = require 'fs'
_ = require 'underscore'
_.mixin require('underscore.string').exports()
require 'colors'
settings = require './settings-srvr'
user = require './user-srvr'
cmdbox = require './cmdbox-srvr'
dirbox = require './dirbox-srvr'
sock = exports
clientList = {}
sock.startup = (srvr) ->
io = require('socket.io').listen srvr, log:no
# io.set 'log level', 3
io.sockets.on 'connection', (client) ->
client.emit 'connected'
clientList[client.id] = client
user.init client
settings.init client
cmdbox.init client
dirbox.init client
client.on 'disconnect', -> delete clientList[client.id]
refreshAllClients = ->
console.log 'ss: refreshAllClients', _.size clientList
for id, client of clientList
client.emit 'refresh'
if fs.existsSync 'src'
# for debugging but can be used in production
fs.watch 'lib/page.css', refreshAllClients
fs.watch 'src/client', refreshAllClients
| true | ###
file: src/server/client-srvr
server client.io handler for bace
copyright PI:NAME:<NAME>END_PI 2013
MIT license
https://github.com/mark-hahn/bace/
###
fs = require 'fs'
_ = require 'underscore'
_.mixin require('underscore.string').exports()
require 'colors'
settings = require './settings-srvr'
user = require './user-srvr'
cmdbox = require './cmdbox-srvr'
dirbox = require './dirbox-srvr'
sock = exports
clientList = {}
sock.startup = (srvr) ->
io = require('socket.io').listen srvr, log:no
# io.set 'log level', 3
io.sockets.on 'connection', (client) ->
client.emit 'connected'
clientList[client.id] = client
user.init client
settings.init client
cmdbox.init client
dirbox.init client
client.on 'disconnect', -> delete clientList[client.id]
refreshAllClients = ->
console.log 'ss: refreshAllClients', _.size clientList
for id, client of clientList
client.emit 'refresh'
if fs.existsSync 'src'
# for debugging but can be used in production
fs.watch 'lib/page.css', refreshAllClients
fs.watch 'src/client', refreshAllClients
|
[
{
"context": "r, rendered) ->\n expected = \"<p>Sent email to John Doe at john@doe.com.</p>\"\n expect(rendered).toEq",
"end": 1814,
"score": 0.9995788335800171,
"start": 1806,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " ->\n expected = \"<p>Sent email to John Doe at john@doe.com.</p>\"\n expect(rendered).toEqual expected\n ",
"end": 1830,
"score": 0.9998120665550232,
"start": 1818,
"tag": "EMAIL",
"value": "john@doe.com"
}
] | spec/server/transformers/template-spec.coffee | groupon/gleemail | 89 | ###
Copyright (c) 2014, Groupon, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of GROUPON nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
renderTemplate = require "../../../src/server/transformers/template"
describe "rendering template values", ->
html = "<p>Sent email to {{ name }} at {{ email }}.</p>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<p>Sent email to John Doe at john@doe.com.</p>"
expect(rendered).toEqual expected
done()
it "uses mustache renderer when renderer=mustache", (done) ->
renderTemplate html, "test-example", renderer: "mustache", (err, rendered) ->
expected = "<p>Sent email to {{ name }} at {{ mappedEmail }}.</p>"
expect(rendered).toEqual expected
done()
it "uses eloqua renderer when renderer=eloqua", (done) ->
renderTemplate html, "test-example", renderer: "eloqua", (err, rendered) ->
expected = "<p>Sent email to <span class='eloquaemail'>name</span> at <span class='eloquaemail'>mappedEmail</span>.</p>"
expect(rendered).toEqual expected
done()
it "uses freemarker renderer when renderer=freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = "<p>Sent email to ${name} at ${mappedEmail}.</p>"
expect(rendered).toEqual expected
done()
it "uses mailchimp renderer when renderer=mailchimp", (done) ->
renderTemplate html, "test-example", renderer: "mailchimp", (err, rendered) ->
expected = "<p>Sent email to *|name|* at *|mappedEmail|*.</p>"
expect(rendered).toEqual expected
done()
describe "rendering conditional statements", ->
html = "<p>Delivered: {{# delivered }}Yes{{/ delivered }}{{^ delivered }}No{{/ delivered}}.</p>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<p>Delivered: Yes.</p>"
expect(rendered).toEqual expected
done()
it "throws when renderer=eloqua", (done) ->
renderTemplate html, "test-example", renderer: "eloqua", (err, rendered) ->
expect(err.message).toEqual "Eloqua does not support conditionals"
done()
it "uses mustache conditionals when renderer=mustache", (done) ->
renderTemplate html, "test-example", renderer: "mustache", (err, rendered) ->
expected = "<p>Delivered: {{# delivered }}Yes{{/ delivered }}{{^ delivered }}No{{/ delivered }}.</p>"
expect(rendered).toEqual expected
done()
xit "uses freemarker conditionals when renderer=freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = "<p>Delivered: <#if delivered?? && delivered != '' && delivered != false>Yes</#if><#if !(delivered?? && delivered != '' && delivered != false)>No</#if>.</p>"
expect(rendered).toEqual expected
done()
it "uses mailchimp conditionals when renderer=mailchimp", (done) ->
renderTemplate html, "test-example", renderer: "mailchimp", (err, rendered) ->
expected = "<p>Delivered: *|IF:delivered|*Yes*|END:IF|**|IFNOT:delivered|*No*|END:IF|*.</p>"
expect(rendered).toEqual expected
done()
describe "rendering loops", ->
html = "<ul>{{# interests }}<li>{{ name }}</li>{{/ interests }}</ul>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<ul><li>Archery</li><li>Badminton</li><li>Cards</li></ul>"
expect(rendered).toEqual expected
done()
it "works with freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = """
<ul><#if interests?is_enumerable>
<#assign interests_arr = interests>
<#elseif interests?? && interests != '' && interests != false>
<#assign interests_arr = [interests]>
<#else>
<#assign interests_arr = []>
</#if>
<#list interests_arr as interests_arr_item>
<li>${(interests_arr_item.name)!name}</li>
</#list></ul>
"""
expect(rendered).toEqual expected
done()
describe "rendering sections", ->
html = "<p>{{# company }}{{ name }} at {{ location }}{{/ company }}</p>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<p>Acme at 123 Main</p>"
expect(rendered).toEqual expected
done()
it "works with freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = """
<p><#if company?is_enumerable>
<#assign company_arr = company>
<#elseif company?? && company != '' && company != false>
<#assign company_arr = [company]>
<#else>
<#assign company_arr = []>
</#if>
<#list company_arr as company_arr_item>
${(company_arr_item.name)!name} at ${(company_arr_item.location)!location}
</#list></p>
"""
expect(rendered).toEqual expected
done()
| 57264 | ###
Copyright (c) 2014, Groupon, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of GROUPON nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
renderTemplate = require "../../../src/server/transformers/template"
describe "rendering template values", ->
html = "<p>Sent email to {{ name }} at {{ email }}.</p>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<p>Sent email to <NAME> at <EMAIL>.</p>"
expect(rendered).toEqual expected
done()
it "uses mustache renderer when renderer=mustache", (done) ->
renderTemplate html, "test-example", renderer: "mustache", (err, rendered) ->
expected = "<p>Sent email to {{ name }} at {{ mappedEmail }}.</p>"
expect(rendered).toEqual expected
done()
it "uses eloqua renderer when renderer=eloqua", (done) ->
renderTemplate html, "test-example", renderer: "eloqua", (err, rendered) ->
expected = "<p>Sent email to <span class='eloquaemail'>name</span> at <span class='eloquaemail'>mappedEmail</span>.</p>"
expect(rendered).toEqual expected
done()
it "uses freemarker renderer when renderer=freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = "<p>Sent email to ${name} at ${mappedEmail}.</p>"
expect(rendered).toEqual expected
done()
it "uses mailchimp renderer when renderer=mailchimp", (done) ->
renderTemplate html, "test-example", renderer: "mailchimp", (err, rendered) ->
expected = "<p>Sent email to *|name|* at *|mappedEmail|*.</p>"
expect(rendered).toEqual expected
done()
describe "rendering conditional statements", ->
html = "<p>Delivered: {{# delivered }}Yes{{/ delivered }}{{^ delivered }}No{{/ delivered}}.</p>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<p>Delivered: Yes.</p>"
expect(rendered).toEqual expected
done()
it "throws when renderer=eloqua", (done) ->
renderTemplate html, "test-example", renderer: "eloqua", (err, rendered) ->
expect(err.message).toEqual "Eloqua does not support conditionals"
done()
it "uses mustache conditionals when renderer=mustache", (done) ->
renderTemplate html, "test-example", renderer: "mustache", (err, rendered) ->
expected = "<p>Delivered: {{# delivered }}Yes{{/ delivered }}{{^ delivered }}No{{/ delivered }}.</p>"
expect(rendered).toEqual expected
done()
xit "uses freemarker conditionals when renderer=freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = "<p>Delivered: <#if delivered?? && delivered != '' && delivered != false>Yes</#if><#if !(delivered?? && delivered != '' && delivered != false)>No</#if>.</p>"
expect(rendered).toEqual expected
done()
it "uses mailchimp conditionals when renderer=mailchimp", (done) ->
renderTemplate html, "test-example", renderer: "mailchimp", (err, rendered) ->
expected = "<p>Delivered: *|IF:delivered|*Yes*|END:IF|**|IFNOT:delivered|*No*|END:IF|*.</p>"
expect(rendered).toEqual expected
done()
describe "rendering loops", ->
html = "<ul>{{# interests }}<li>{{ name }}</li>{{/ interests }}</ul>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<ul><li>Archery</li><li>Badminton</li><li>Cards</li></ul>"
expect(rendered).toEqual expected
done()
it "works with freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = """
<ul><#if interests?is_enumerable>
<#assign interests_arr = interests>
<#elseif interests?? && interests != '' && interests != false>
<#assign interests_arr = [interests]>
<#else>
<#assign interests_arr = []>
</#if>
<#list interests_arr as interests_arr_item>
<li>${(interests_arr_item.name)!name}</li>
</#list></ul>
"""
expect(rendered).toEqual expected
done()
describe "rendering sections", ->
html = "<p>{{# company }}{{ name }} at {{ location }}{{/ company }}</p>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<p>Acme at 123 Main</p>"
expect(rendered).toEqual expected
done()
it "works with freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = """
<p><#if company?is_enumerable>
<#assign company_arr = company>
<#elseif company?? && company != '' && company != false>
<#assign company_arr = [company]>
<#else>
<#assign company_arr = []>
</#if>
<#list company_arr as company_arr_item>
${(company_arr_item.name)!name} at ${(company_arr_item.location)!location}
</#list></p>
"""
expect(rendered).toEqual expected
done()
| true | ###
Copyright (c) 2014, Groupon, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Neither the name of GROUPON nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
renderTemplate = require "../../../src/server/transformers/template"
describe "rendering template values", ->
html = "<p>Sent email to {{ name }} at {{ email }}.</p>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<p>Sent email to PI:NAME:<NAME>END_PI at PI:EMAIL:<EMAIL>END_PI.</p>"
expect(rendered).toEqual expected
done()
it "uses mustache renderer when renderer=mustache", (done) ->
renderTemplate html, "test-example", renderer: "mustache", (err, rendered) ->
expected = "<p>Sent email to {{ name }} at {{ mappedEmail }}.</p>"
expect(rendered).toEqual expected
done()
it "uses eloqua renderer when renderer=eloqua", (done) ->
renderTemplate html, "test-example", renderer: "eloqua", (err, rendered) ->
expected = "<p>Sent email to <span class='eloquaemail'>name</span> at <span class='eloquaemail'>mappedEmail</span>.</p>"
expect(rendered).toEqual expected
done()
it "uses freemarker renderer when renderer=freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = "<p>Sent email to ${name} at ${mappedEmail}.</p>"
expect(rendered).toEqual expected
done()
it "uses mailchimp renderer when renderer=mailchimp", (done) ->
renderTemplate html, "test-example", renderer: "mailchimp", (err, rendered) ->
expected = "<p>Sent email to *|name|* at *|mappedEmail|*.</p>"
expect(rendered).toEqual expected
done()
describe "rendering conditional statements", ->
html = "<p>Delivered: {{# delivered }}Yes{{/ delivered }}{{^ delivered }}No{{/ delivered}}.</p>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<p>Delivered: Yes.</p>"
expect(rendered).toEqual expected
done()
it "throws when renderer=eloqua", (done) ->
renderTemplate html, "test-example", renderer: "eloqua", (err, rendered) ->
expect(err.message).toEqual "Eloqua does not support conditionals"
done()
it "uses mustache conditionals when renderer=mustache", (done) ->
renderTemplate html, "test-example", renderer: "mustache", (err, rendered) ->
expected = "<p>Delivered: {{# delivered }}Yes{{/ delivered }}{{^ delivered }}No{{/ delivered }}.</p>"
expect(rendered).toEqual expected
done()
xit "uses freemarker conditionals when renderer=freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = "<p>Delivered: <#if delivered?? && delivered != '' && delivered != false>Yes</#if><#if !(delivered?? && delivered != '' && delivered != false)>No</#if>.</p>"
expect(rendered).toEqual expected
done()
it "uses mailchimp conditionals when renderer=mailchimp", (done) ->
renderTemplate html, "test-example", renderer: "mailchimp", (err, rendered) ->
expected = "<p>Delivered: *|IF:delivered|*Yes*|END:IF|**|IFNOT:delivered|*No*|END:IF|*.</p>"
expect(rendered).toEqual expected
done()
describe "rendering loops", ->
html = "<ul>{{# interests }}<li>{{ name }}</li>{{/ interests }}</ul>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<ul><li>Archery</li><li>Badminton</li><li>Cards</li></ul>"
expect(rendered).toEqual expected
done()
it "works with freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = """
<ul><#if interests?is_enumerable>
<#assign interests_arr = interests>
<#elseif interests?? && interests != '' && interests != false>
<#assign interests_arr = [interests]>
<#else>
<#assign interests_arr = []>
</#if>
<#list interests_arr as interests_arr_item>
<li>${(interests_arr_item.name)!name}</li>
</#list></ul>
"""
expect(rendered).toEqual expected
done()
describe "rendering sections", ->
html = "<p>{{# company }}{{ name }} at {{ location }}{{/ company }}</p>"
it "defaults to rendering with data from data.json", (done) ->
renderTemplate html, "test-example", {}, (err, rendered) ->
expected = "<p>Acme at 123 Main</p>"
expect(rendered).toEqual expected
done()
it "works with freemarker", (done) ->
renderTemplate html, "test-example", renderer: "freemarker", (err, rendered) ->
expected = """
<p><#if company?is_enumerable>
<#assign company_arr = company>
<#elseif company?? && company != '' && company != false>
<#assign company_arr = [company]>
<#else>
<#assign company_arr = []>
</#if>
<#list company_arr as company_arr_item>
${(company_arr_item.name)!name} at ${(company_arr_item.location)!location}
</#list></p>
"""
expect(rendered).toEqual expected
done()
|
[
{
"context": "ould merge two objects', ->\n expected = {dog: 'Ben', cat: 'Anne'}\n result = util.merge {dog: 'Ben",
"end": 282,
"score": 0.9977778792381287,
"start": 279,
"tag": "NAME",
"value": "Ben"
},
{
"context": "wo objects', ->\n expected = {dog: 'Ben', cat: 'Anne'}\n result = util.merge {dog: 'Ben'}, {cat: 'An",
"end": 295,
"score": 0.7897738218307495,
"start": 291,
"tag": "NAME",
"value": "Anne"
},
{
"context": "Ben', cat: 'Anne'}\n result = util.merge {dog: 'Ben'}, {cat: 'Anne'}\n expect(result).to.deep.equal",
"end": 332,
"score": 0.9975326061248779,
"start": 329,
"tag": "NAME",
"value": "Ben"
},
{
"context": "'}\n result = util.merge {dog: 'Ben'}, {cat: 'Anne'}\n expect(result).to.deep.equal expected\n\n it",
"end": 347,
"score": 0.7959621548652649,
"start": 345,
"tag": "NAME",
"value": "ne"
},
{
"context": "de existing object keys', ->\n expected = {dog:'Ridley', cat: 'Anne'}\n result = util.merge {dog: 'Ben",
"end": 468,
"score": 0.9970095753669739,
"start": 462,
"tag": "NAME",
"value": "Ridley"
},
{
"context": "t keys', ->\n expected = {dog:'Ridley', cat: 'Anne'}\n result = util.merge {dog: 'Ben', 'cat': 'An",
"end": 481,
"score": 0.6561259627342224,
"start": 479,
"tag": "NAME",
"value": "ne"
},
{
"context": "ley', cat: 'Anne'}\n result = util.merge {dog: 'Ben', 'cat': 'Anne'}, {dog: 'Ridley'}\n expect(resu",
"end": 518,
"score": 0.9982686638832092,
"start": 515,
"tag": "NAME",
"value": "Ben"
},
{
"context": " = util.merge {dog: 'Ben', 'cat': 'Anne'}, {dog: 'Ridley'}\n expect(result).to.deep.equal expected",
"end": 550,
"score": 0.9952953457832336,
"start": 544,
"tag": "NAME",
"value": "Ridley"
}
] | test/util-test.coffee | jimeh/hubot-fleep | 0 | chai = require 'chai'
util = require '../src/util'
expect = chai.expect
chai.should()
describe 'merge', ->
it 'should return an empty object if inputs are empty', ->
util.merge({}, {}, {}).should.be.empty()
it 'should merge two objects', ->
expected = {dog: 'Ben', cat: 'Anne'}
result = util.merge {dog: 'Ben'}, {cat: 'Anne'}
expect(result).to.deep.equal expected
it 'should override existing object keys', ->
expected = {dog:'Ridley', cat: 'Anne'}
result = util.merge {dog: 'Ben', 'cat': 'Anne'}, {dog: 'Ridley'}
expect(result).to.deep.equal expected | 75290 | chai = require 'chai'
util = require '../src/util'
expect = chai.expect
chai.should()
describe 'merge', ->
it 'should return an empty object if inputs are empty', ->
util.merge({}, {}, {}).should.be.empty()
it 'should merge two objects', ->
expected = {dog: '<NAME>', cat: '<NAME>'}
result = util.merge {dog: '<NAME>'}, {cat: 'An<NAME>'}
expect(result).to.deep.equal expected
it 'should override existing object keys', ->
expected = {dog:'<NAME>', cat: 'An<NAME>'}
result = util.merge {dog: '<NAME>', 'cat': 'Anne'}, {dog: '<NAME>'}
expect(result).to.deep.equal expected | true | chai = require 'chai'
util = require '../src/util'
expect = chai.expect
chai.should()
describe 'merge', ->
it 'should return an empty object if inputs are empty', ->
util.merge({}, {}, {}).should.be.empty()
it 'should merge two objects', ->
expected = {dog: 'PI:NAME:<NAME>END_PI', cat: 'PI:NAME:<NAME>END_PI'}
result = util.merge {dog: 'PI:NAME:<NAME>END_PI'}, {cat: 'AnPI:NAME:<NAME>END_PI'}
expect(result).to.deep.equal expected
it 'should override existing object keys', ->
expected = {dog:'PI:NAME:<NAME>END_PI', cat: 'AnPI:NAME:<NAME>END_PI'}
result = util.merge {dog: 'PI:NAME:<NAME>END_PI', 'cat': 'Anne'}, {dog: 'PI:NAME:<NAME>END_PI'}
expect(result).to.deep.equal expected |
[
{
"context": "otherUser = Meteor.users.findOne('profile.name': \"Sean Stanley Producer Role\")\n#\n# expect Meteor.users.find(",
"end": 363,
"score": 0.7635929584503174,
"start": 351,
"tag": "NAME",
"value": "Sean Stanley"
},
{
"context": "ers\"\n#\n# product =\n# {\n# name: 'Peaches',\n# producer: otherUser._id,\n# pr",
"end": 641,
"score": 0.9802207946777344,
"start": 634,
"tag": "NAME",
"value": "Peaches"
},
{
"context": "id\n#\n# expect p.producerName\n# .toBe \"Sean Stanley Producer Role\"\n#\n# done()\n#\n#\n#\n",
"end": 1173,
"score": 0.73611980676651,
"start": 1169,
"tag": "NAME",
"value": "Sean"
}
] | tests/jasmine/client-disabled/integration/Product.hooks.spec.coffee | redhead-web/meteor-foodcoop | 11 | #
# describe "product upload on behalf as an admin", ->
# beforeEach (done) ->
# Meteor.subscribe 'list-of-producers', ->
# console.log('subscribed to producers')
# done()
#
# it "should auto correct the producer name on insert", (done) ->
# console.log "starting tests"
# otherUser = Meteor.users.findOne('profile.name': "Sean Stanley Producer Role")
#
# expect Meteor.users.find().count()
# .toBe 2
#
# expect otherUser
# .toBeDefined()
#
# expect otherUser._id
# .not.toBe Meteor.userId()
#
# console.log "finished testing users"
#
# product =
# {
# name: 'Peaches',
# producer: otherUser._id,
# producerName: Meteor.user().profile.name,
# price: 5,
# unitOfMeasure: "kg",
# category: "produce",
# stocklevel: 50,
# published: true
# }
#
# Products.insert product, (err, id) ->
# expect(err).toBeUndefined()
# console.log "inserted Product"
#
# expect(id).toBeDefined()
#
# p = Products.findOne(id)
#
# expect p.producer
# .toBe otherUser._id
#
# expect p.producerName
# .toBe "Sean Stanley Producer Role"
#
# done()
#
#
#
| 54761 | #
# describe "product upload on behalf as an admin", ->
# beforeEach (done) ->
# Meteor.subscribe 'list-of-producers', ->
# console.log('subscribed to producers')
# done()
#
# it "should auto correct the producer name on insert", (done) ->
# console.log "starting tests"
# otherUser = Meteor.users.findOne('profile.name': "<NAME> Producer Role")
#
# expect Meteor.users.find().count()
# .toBe 2
#
# expect otherUser
# .toBeDefined()
#
# expect otherUser._id
# .not.toBe Meteor.userId()
#
# console.log "finished testing users"
#
# product =
# {
# name: '<NAME>',
# producer: otherUser._id,
# producerName: Meteor.user().profile.name,
# price: 5,
# unitOfMeasure: "kg",
# category: "produce",
# stocklevel: 50,
# published: true
# }
#
# Products.insert product, (err, id) ->
# expect(err).toBeUndefined()
# console.log "inserted Product"
#
# expect(id).toBeDefined()
#
# p = Products.findOne(id)
#
# expect p.producer
# .toBe otherUser._id
#
# expect p.producerName
# .toBe "<NAME> Stanley Producer Role"
#
# done()
#
#
#
| true | #
# describe "product upload on behalf as an admin", ->
# beforeEach (done) ->
# Meteor.subscribe 'list-of-producers', ->
# console.log('subscribed to producers')
# done()
#
# it "should auto correct the producer name on insert", (done) ->
# console.log "starting tests"
# otherUser = Meteor.users.findOne('profile.name': "PI:NAME:<NAME>END_PI Producer Role")
#
# expect Meteor.users.find().count()
# .toBe 2
#
# expect otherUser
# .toBeDefined()
#
# expect otherUser._id
# .not.toBe Meteor.userId()
#
# console.log "finished testing users"
#
# product =
# {
# name: 'PI:NAME:<NAME>END_PI',
# producer: otherUser._id,
# producerName: Meteor.user().profile.name,
# price: 5,
# unitOfMeasure: "kg",
# category: "produce",
# stocklevel: 50,
# published: true
# }
#
# Products.insert product, (err, id) ->
# expect(err).toBeUndefined()
# console.log "inserted Product"
#
# expect(id).toBeDefined()
#
# p = Products.findOne(id)
#
# expect p.producer
# .toBe otherUser._id
#
# expect p.producerName
# .toBe "PI:NAME:<NAME>END_PI Stanley Producer Role"
#
# done()
#
#
#
|
[
{
"context": "ot of scantwo results (2-dim, 2-QTL genome scan)\n# Karl W Broman\n\nHTMLWidgets.widget({\n\n name: \"iplotScantwo\",\n",
"end": 94,
"score": 0.9998483657836914,
"start": 81,
"tag": "NAME",
"value": "Karl W Broman"
}
] | inst/htmlwidgets/iplotScantwo.coffee | cran/qtlcharts | 64 | # iplotScantwo: interactive plot of scantwo results (2-dim, 2-QTL genome scan)
# Karl W Broman
HTMLWidgets.widget({
name: "iplotScantwo",
type: "output",
initialize: (widgetdiv, width, height) ->
d3.select(widgetdiv).append("svg")
.attr("class", "qtlcharts")
.attr("width", width)
.attr("height", height-24) # 24 = form div height
renderValue: (widgetdiv, x) ->
svg = d3.select(widgetdiv).select("svg")
# clear svg and remove tool tips
svg.selectAll("*").remove()
widgetid = d3.select(widgetdiv).attr('id')
d3.selectAll("g.d3panels-tooltip.#{widgetid}").remove()
chartOpts = x.chartOpts ? {}
chartOpts.width = chartOpts?.width ? svg.attr("width")
chartOpts.height = chartOpts?.height ? +svg.attr("height")+24 # 24 = form height
chartOpts.height -= 24 # 24 = form height
svg.attr("width", chartOpts.width)
svg.attr("height", chartOpts.height)
iplotScantwo(widgetdiv, x.scantwo_data, x.phenogeno_data, chartOpts)
resize: (widgetdiv, width, height) ->
d3.select(widgetdiv).select("svg")
.attr("width", width)
.attr("height", height)
})
| 91373 | # iplotScantwo: interactive plot of scantwo results (2-dim, 2-QTL genome scan)
# <NAME>
HTMLWidgets.widget({
name: "iplotScantwo",
type: "output",
initialize: (widgetdiv, width, height) ->
d3.select(widgetdiv).append("svg")
.attr("class", "qtlcharts")
.attr("width", width)
.attr("height", height-24) # 24 = form div height
renderValue: (widgetdiv, x) ->
svg = d3.select(widgetdiv).select("svg")
# clear svg and remove tool tips
svg.selectAll("*").remove()
widgetid = d3.select(widgetdiv).attr('id')
d3.selectAll("g.d3panels-tooltip.#{widgetid}").remove()
chartOpts = x.chartOpts ? {}
chartOpts.width = chartOpts?.width ? svg.attr("width")
chartOpts.height = chartOpts?.height ? +svg.attr("height")+24 # 24 = form height
chartOpts.height -= 24 # 24 = form height
svg.attr("width", chartOpts.width)
svg.attr("height", chartOpts.height)
iplotScantwo(widgetdiv, x.scantwo_data, x.phenogeno_data, chartOpts)
resize: (widgetdiv, width, height) ->
d3.select(widgetdiv).select("svg")
.attr("width", width)
.attr("height", height)
})
| true | # iplotScantwo: interactive plot of scantwo results (2-dim, 2-QTL genome scan)
# PI:NAME:<NAME>END_PI
HTMLWidgets.widget({
name: "iplotScantwo",
type: "output",
initialize: (widgetdiv, width, height) ->
d3.select(widgetdiv).append("svg")
.attr("class", "qtlcharts")
.attr("width", width)
.attr("height", height-24) # 24 = form div height
renderValue: (widgetdiv, x) ->
svg = d3.select(widgetdiv).select("svg")
# clear svg and remove tool tips
svg.selectAll("*").remove()
widgetid = d3.select(widgetdiv).attr('id')
d3.selectAll("g.d3panels-tooltip.#{widgetid}").remove()
chartOpts = x.chartOpts ? {}
chartOpts.width = chartOpts?.width ? svg.attr("width")
chartOpts.height = chartOpts?.height ? +svg.attr("height")+24 # 24 = form height
chartOpts.height -= 24 # 24 = form height
svg.attr("width", chartOpts.width)
svg.attr("height", chartOpts.height)
iplotScantwo(widgetdiv, x.scantwo_data, x.phenogeno_data, chartOpts)
resize: (widgetdiv, width, height) ->
d3.select(widgetdiv).select("svg")
.attr("width", width)
.attr("height", height)
})
|
[
{
"context": " provides storage service.\n * @function\n * @author İsmail Demirbilek\n###\nangular.module 'esef.frontend.storage', []",
"end": 188,
"score": 0.9998912811279297,
"start": 171,
"tag": "NAME",
"value": "İsmail Demirbilek"
}
] | src/storage/coffee/app.coffee | egemsoft/esef-frontend | 0 | 'use strict'
###*
* @ngdoc overview
* @name esef.frontend.storage
* @description
* Storage module for esef-frontend provides storage service.
* @function
* @author İsmail Demirbilek
###
angular.module 'esef.frontend.storage', [] | 61887 | 'use strict'
###*
* @ngdoc overview
* @name esef.frontend.storage
* @description
* Storage module for esef-frontend provides storage service.
* @function
* @author <NAME>
###
angular.module 'esef.frontend.storage', [] | true | 'use strict'
###*
* @ngdoc overview
* @name esef.frontend.storage
* @description
* Storage module for esef-frontend provides storage service.
* @function
* @author PI:NAME:<NAME>END_PI
###
angular.module 'esef.frontend.storage', [] |
[
{
"context": "}\n keyless.addLink { bucket: 'bucket', key: 'test2', tag: '_' }\n keyless.addLink { bucket: 'buc",
"end": 1766,
"score": 0.9664300680160522,
"start": 1761,
"tag": "KEY",
"value": "test2"
},
{
"context": "}\n keyless.addLink { bucket: 'bucket', key: 'test', tag: 'tag' }\n keyless.addLink { bucket: 'b",
"end": 1977,
"score": 0.938571035861969,
"start": 1973,
"tag": "KEY",
"value": "test"
},
{
"context": "}\n keyless.addLink { bucket: 'bucket', key: 'test2', tag: '_' }\n keyless.addLink { bucket: 'buc",
"end": 2046,
"score": 0.9894065856933594,
"start": 2041,
"tag": "KEY",
"value": "test2"
},
{
"context": "}\n keyless.addLink { bucket: 'bucket', key: 'test2' } # no tag or '_' are equivalent\n \n ke",
"end": 2113,
"score": 0.9861656427383423,
"start": 2108,
"tag": "KEY",
"value": "test2"
},
{
"context": "eyless.links, [\n { bucket: 'bucket', key: 'test' }\n { bucket: 'bucket', key: 'test2', tag:",
"end": 2640,
"score": 0.525189995765686,
"start": 2636,
"tag": "KEY",
"value": "test"
},
{
"context": ", key: 'test' }\n { bucket: 'bucket', key: 'test2', tag: '_' }\n { bucket: 'bucket', key: 'te",
"end": 2683,
"score": 0.937308132648468,
"start": 2678,
"tag": "KEY",
"value": "test2"
},
{
"context": "t2', tag: '_' }\n { bucket: 'bucket', key: 'test', tag: 'tag' }\n ]\n \n 'links can be rem",
"end": 2735,
"score": 0.6282932758331299,
"start": 2731,
"tag": "KEY",
"value": "test"
},
{
"context": " keyless.removeLink { bucket: 'bucket', key: 'test', tag: 'tag' }\n assert.equal keyless.links.l",
"end": 2962,
"score": 0.6150159239768982,
"start": 2958,
"tag": "KEY",
"value": "test"
},
{
"context": " keyless.removeLink { bucket: 'bucket', key: 'test2' } # should treat tag '_' as non-existent\n a",
"end": 3077,
"score": 0.7471407055854797,
"start": 3072,
"tag": "KEY",
"value": "test2"
}
] | spec/test_meta.coffee | geeklist/riak-js-geeklist | 1 | vows = require 'vows'
assert = require 'assert'
Meta = require '../src/meta'
full = {}
vows.describe('Meta').addBatch(
'an empty meta':
topic: ->
new Meta 'bucket', 'empty'
'has its basic properties set': (empty) ->
assert.equal 'bucket', empty.bucket
assert.equal 'empty', empty.key
assert.equal null, empty.vclock
assert.equal false, empty.binary
'falls back to defaults from non-set properties': (empty) ->
assert.deepEqual empty.links, Meta.defaults.links
assert.equal empty.raw, Meta.defaults.raw
assert.equal empty.clientId, Meta.defaults.clientId
assert.equal empty.host, Meta.defaults.host
'a full meta':
topic: ->
full = new Meta 'bucket', 'full'
contentType: 'png'
data: 'd32n92390XMIW0'
vclock: 123
custom: 'abc'
# calling encodeData() resolves to the correct content type and binary state
full.encodeData()
full
'has its basic properties set': (full) ->
assert.equal 'bucket', full.bucket
assert.equal 'full', full.key
assert.equal 123, full.vclock
assert.equal 'image/png', full.contentType
assert.equal 'abc', full.usermeta.custom
assert.equal true, full.binary
'can be updated': (full) ->
full.contentType = 'xml'
full.data = "<a>test</a>"
full.encodeData()
assert.equal 'text/xml', full.contentType
assert.equal false, full.binary
'a keyless meta':
topic: ->
keyless = new Meta 'bucket'
keyless.addLink { bucket: 'bucket', key: 'test' }
keyless.addLink { bucket: 'bucket', key: 'test2', tag: '_' }
keyless.addLink { bucket: 'bucket', key: 'test', tag: 'tag' }
# dupes
keyless.addLink { bucket: 'bucket', key: 'test' }
keyless.addLink { bucket: 'bucket', key: 'test', tag: 'tag' }
keyless.addLink { bucket: 'bucket', key: 'test2', tag: '_' }
keyless.addLink { bucket: 'bucket', key: 'test2' } # no tag or '_' are equivalent
keyless.data = 'some text'
keyless.encodeData()
keyless
'hasn\'t got a key': (keyless) ->
assert.equal undefined, keyless.key
'usermeta is empty': (keyless) ->
assert.deepEqual {}, keyless.usermeta
'data is plain text': (keyless) ->
assert.equal keyless.contentType, 'text/plain'
'duplicate links are ignored': (keyless) ->
assert.deepEqual keyless.links, [
{ bucket: 'bucket', key: 'test' }
{ bucket: 'bucket', key: 'test2', tag: '_' }
{ bucket: 'bucket', key: 'test', tag: 'tag' }
]
'links can be removed': (keyless) ->
keyless.removeLink { bucket: 'bucket', key: 'test' }
assert.equal keyless.links.length, 2
keyless.removeLink { bucket: 'bucket', key: 'test', tag: 'tag' }
assert.equal keyless.links.length, 1
keyless.removeLink { bucket: 'bucket', key: 'test2' } # should treat tag '_' as non-existent
assert.equal keyless.links.length, 0
'a meta provided with a Javascript object as data':
topic: ->
meta = new Meta 'bucket', 'key', {
data: {a: 1, b: 2}
}
meta.encodeData()
meta
'has content type json when encoded': (meta) ->
assert.equal meta.contentType, "application/json"
).export module | 193975 | vows = require 'vows'
assert = require 'assert'
Meta = require '../src/meta'
full = {}
vows.describe('Meta').addBatch(
'an empty meta':
topic: ->
new Meta 'bucket', 'empty'
'has its basic properties set': (empty) ->
assert.equal 'bucket', empty.bucket
assert.equal 'empty', empty.key
assert.equal null, empty.vclock
assert.equal false, empty.binary
'falls back to defaults from non-set properties': (empty) ->
assert.deepEqual empty.links, Meta.defaults.links
assert.equal empty.raw, Meta.defaults.raw
assert.equal empty.clientId, Meta.defaults.clientId
assert.equal empty.host, Meta.defaults.host
'a full meta':
topic: ->
full = new Meta 'bucket', 'full'
contentType: 'png'
data: 'd32n92390XMIW0'
vclock: 123
custom: 'abc'
# calling encodeData() resolves to the correct content type and binary state
full.encodeData()
full
'has its basic properties set': (full) ->
assert.equal 'bucket', full.bucket
assert.equal 'full', full.key
assert.equal 123, full.vclock
assert.equal 'image/png', full.contentType
assert.equal 'abc', full.usermeta.custom
assert.equal true, full.binary
'can be updated': (full) ->
full.contentType = 'xml'
full.data = "<a>test</a>"
full.encodeData()
assert.equal 'text/xml', full.contentType
assert.equal false, full.binary
'a keyless meta':
topic: ->
keyless = new Meta 'bucket'
keyless.addLink { bucket: 'bucket', key: 'test' }
keyless.addLink { bucket: 'bucket', key: '<KEY>', tag: '_' }
keyless.addLink { bucket: 'bucket', key: 'test', tag: 'tag' }
# dupes
keyless.addLink { bucket: 'bucket', key: 'test' }
keyless.addLink { bucket: 'bucket', key: '<KEY>', tag: 'tag' }
keyless.addLink { bucket: 'bucket', key: '<KEY>', tag: '_' }
keyless.addLink { bucket: 'bucket', key: '<KEY>' } # no tag or '_' are equivalent
keyless.data = 'some text'
keyless.encodeData()
keyless
'hasn\'t got a key': (keyless) ->
assert.equal undefined, keyless.key
'usermeta is empty': (keyless) ->
assert.deepEqual {}, keyless.usermeta
'data is plain text': (keyless) ->
assert.equal keyless.contentType, 'text/plain'
'duplicate links are ignored': (keyless) ->
assert.deepEqual keyless.links, [
{ bucket: 'bucket', key: '<KEY>' }
{ bucket: 'bucket', key: '<KEY>', tag: '_' }
{ bucket: 'bucket', key: '<KEY>', tag: 'tag' }
]
'links can be removed': (keyless) ->
keyless.removeLink { bucket: 'bucket', key: 'test' }
assert.equal keyless.links.length, 2
keyless.removeLink { bucket: 'bucket', key: '<KEY>', tag: 'tag' }
assert.equal keyless.links.length, 1
keyless.removeLink { bucket: 'bucket', key: '<KEY>' } # should treat tag '_' as non-existent
assert.equal keyless.links.length, 0
'a meta provided with a Javascript object as data':
topic: ->
meta = new Meta 'bucket', 'key', {
data: {a: 1, b: 2}
}
meta.encodeData()
meta
'has content type json when encoded': (meta) ->
assert.equal meta.contentType, "application/json"
).export module | true | vows = require 'vows'
assert = require 'assert'
Meta = require '../src/meta'
full = {}
vows.describe('Meta').addBatch(
'an empty meta':
topic: ->
new Meta 'bucket', 'empty'
'has its basic properties set': (empty) ->
assert.equal 'bucket', empty.bucket
assert.equal 'empty', empty.key
assert.equal null, empty.vclock
assert.equal false, empty.binary
'falls back to defaults from non-set properties': (empty) ->
assert.deepEqual empty.links, Meta.defaults.links
assert.equal empty.raw, Meta.defaults.raw
assert.equal empty.clientId, Meta.defaults.clientId
assert.equal empty.host, Meta.defaults.host
'a full meta':
topic: ->
full = new Meta 'bucket', 'full'
contentType: 'png'
data: 'd32n92390XMIW0'
vclock: 123
custom: 'abc'
# calling encodeData() resolves to the correct content type and binary state
full.encodeData()
full
'has its basic properties set': (full) ->
assert.equal 'bucket', full.bucket
assert.equal 'full', full.key
assert.equal 123, full.vclock
assert.equal 'image/png', full.contentType
assert.equal 'abc', full.usermeta.custom
assert.equal true, full.binary
'can be updated': (full) ->
full.contentType = 'xml'
full.data = "<a>test</a>"
full.encodeData()
assert.equal 'text/xml', full.contentType
assert.equal false, full.binary
'a keyless meta':
topic: ->
keyless = new Meta 'bucket'
keyless.addLink { bucket: 'bucket', key: 'test' }
keyless.addLink { bucket: 'bucket', key: 'PI:KEY:<KEY>END_PI', tag: '_' }
keyless.addLink { bucket: 'bucket', key: 'test', tag: 'tag' }
# dupes
keyless.addLink { bucket: 'bucket', key: 'test' }
keyless.addLink { bucket: 'bucket', key: 'PI:KEY:<KEY>END_PI', tag: 'tag' }
keyless.addLink { bucket: 'bucket', key: 'PI:KEY:<KEY>END_PI', tag: '_' }
keyless.addLink { bucket: 'bucket', key: 'PI:KEY:<KEY>END_PI' } # no tag or '_' are equivalent
keyless.data = 'some text'
keyless.encodeData()
keyless
'hasn\'t got a key': (keyless) ->
assert.equal undefined, keyless.key
'usermeta is empty': (keyless) ->
assert.deepEqual {}, keyless.usermeta
'data is plain text': (keyless) ->
assert.equal keyless.contentType, 'text/plain'
'duplicate links are ignored': (keyless) ->
assert.deepEqual keyless.links, [
{ bucket: 'bucket', key: 'PI:KEY:<KEY>END_PI' }
{ bucket: 'bucket', key: 'PI:KEY:<KEY>END_PI', tag: '_' }
{ bucket: 'bucket', key: 'PI:KEY:<KEY>END_PI', tag: 'tag' }
]
'links can be removed': (keyless) ->
keyless.removeLink { bucket: 'bucket', key: 'test' }
assert.equal keyless.links.length, 2
keyless.removeLink { bucket: 'bucket', key: 'PI:KEY:<KEY>END_PI', tag: 'tag' }
assert.equal keyless.links.length, 1
keyless.removeLink { bucket: 'bucket', key: 'PI:KEY:<KEY>END_PI' } # should treat tag '_' as non-existent
assert.equal keyless.links.length, 0
'a meta provided with a Javascript object as data':
topic: ->
meta = new Meta 'bucket', 'key', {
data: {a: 1, b: 2}
}
meta.encodeData()
meta
'has content type json when encoded': (meta) ->
assert.equal meta.contentType, "application/json"
).export module |
[
{
"context": "views\n\t\t\tpagename: 'awesome people'\n\t\t\tauthors: ['Paul', 'Jim', 'Jane']\n\t\tres.template \"views/templates/",
"end": 328,
"score": 0.9998048543930054,
"start": 324,
"tag": "NAME",
"value": "Paul"
},
{
"context": "\tpagename: 'awesome people'\n\t\t\tauthors: ['Paul', 'Jim', 'Jane']\n\t\tres.template \"views/templates/view.ht",
"end": 335,
"score": 0.9997777938842773,
"start": 332,
"tag": "NAME",
"value": "Jim"
},
{
"context": "me: 'awesome people'\n\t\t\tauthors: ['Paul', 'Jim', 'Jane']\n\t\tres.template \"views/templates/view.html\", con",
"end": 343,
"score": 0.9995418787002563,
"start": 339,
"tag": "NAME",
"value": "Jane"
}
] | project/controllers/controllers.coffee | stanislavfeldman/wheels | 1 | class MyController
get: (req, res) ->
#translator = new kiss.views.Translator()
#console.log translator.translate req, "hello"
#console.log translator.translate req, 'hello, {0}', "Стас"
req.session.views ?= 0
req.session.views++
context =
foo: req.session.views
pagename: 'awesome people'
authors: ['Paul', 'Jim', 'Jane']
res.template "views/templates/view.html", context
post: (req, res) ->
res.text "hello from post"
exports.MyController = MyController
| 172380 | class MyController
get: (req, res) ->
#translator = new kiss.views.Translator()
#console.log translator.translate req, "hello"
#console.log translator.translate req, 'hello, {0}', "Стас"
req.session.views ?= 0
req.session.views++
context =
foo: req.session.views
pagename: 'awesome people'
authors: ['<NAME>', '<NAME>', '<NAME>']
res.template "views/templates/view.html", context
post: (req, res) ->
res.text "hello from post"
exports.MyController = MyController
| true | class MyController
get: (req, res) ->
#translator = new kiss.views.Translator()
#console.log translator.translate req, "hello"
#console.log translator.translate req, 'hello, {0}', "Стас"
req.session.views ?= 0
req.session.views++
context =
foo: req.session.views
pagename: 'awesome people'
authors: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']
res.template "views/templates/view.html", context
post: (req, res) ->
res.text "hello from post"
exports.MyController = MyController
|
[
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 2720,
"score": 0.9990534782409668,
"start": 2713,
"tag": "NAME",
"value": "Patient"
},
{
"context": " }\n }, {\n \"name\" : \"InDemographic\",\n \"context\" : \"Patient\",\n ",
"end": 3093,
"score": 0.9859412908554077,
"start": 3091,
"tag": "NAME",
"value": "In"
},
{
"context": " }\n }, {\n \"name\" : \"InDemographic\",\n \"context\" : \"Patient\",\n ",
"end": 3097,
"score": 0.6172151565551758,
"start": 3093,
"tag": "USERNAME",
"value": "Demo"
},
{
"context": " }\n }, {\n \"name\" : \"InDemographic\",\n \"context\" : \"Patient\",\n ",
"end": 3104,
"score": 0.5976396799087524,
"start": 3097,
"tag": "NAME",
"value": "graphic"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 7681,
"score": 0.9986839890480042,
"start": 7674,
"tag": "NAME",
"value": "Patient"
},
{
"context": " }\n }, {\n \"name\" : \"InDemographic\",\n \"context\" : \"Patient\",\n ",
"end": 8054,
"score": 0.9513428211212158,
"start": 8052,
"tag": "NAME",
"value": "In"
},
{
"context": " }\n }, {\n \"name\" : \"InDemographic\",\n \"context\" : \"Patient\",\n ",
"end": 8065,
"score": 0.8874133825302124,
"start": 8054,
"tag": "USERNAME",
"value": "Demographic"
},
{
"context": " }\n }, {\n \"name\" : \"foo\",\n \"context\" : \"Patient\",\n ",
"end": 10151,
"score": 0.9974172711372375,
"start": 10148,
"tag": "NAME",
"value": "foo"
},
{
"context": " \"operand\" : [ {\n \"name\" : \"a\",\n \"type\" : \"OperandRef\"\n ",
"end": 10383,
"score": 0.9106749296188354,
"start": 10382,
"tag": "NAME",
"value": "a"
},
{
"context": "\"\n }, {\n \"name\" : \"b\",\n \"type\" : \"OperandRef\"\n ",
"end": 10475,
"score": 0.6967365741729736,
"start": 10474,
"tag": "NAME",
"value": "b"
},
{
"context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n \"schema",
"end": 11465,
"score": 0.8681011199951172,
"start": 11454,
"tag": "USERNAME",
"value": "TestSnippet"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 13708,
"score": 0.9993552565574646,
"start": 13701,
"tag": "NAME",
"value": "Patient"
},
{
"context": " }\n }, {\n \"name\" : \"ID\",\n \"context\" : \"Patient\",\n ",
"end": 14081,
"score": 0.9990739822387695,
"start": 14079,
"tag": "NAME",
"value": "ID"
},
{
"context": " \"expression\" : {\n \"name\" : \"InDemographic\",\n \"libraryName\" : \"common\",\n ",
"end": 14224,
"score": 0.9904850125312805,
"start": 14211,
"tag": "NAME",
"value": "InDemographic"
},
{
"context": " }\n }, {\n \"name\" : \"L\",\n \"context\" : \"Patient\",\n ",
"end": 14359,
"score": 0.9988917708396912,
"start": 14358,
"tag": "NAME",
"value": "L"
},
{
"context": " }\n }, {\n \"name\" : \"FuncTest\",\n \"context\" : \"Patient\",\n ",
"end": 15578,
"score": 0.8390215635299683,
"start": 15570,
"tag": "NAME",
"value": "FuncTest"
},
{
"context": " \"expression\" : {\n \"name\" : \"foo\",\n \"libraryName\" : \"common\",\n ",
"end": 15711,
"score": 0.969704806804657,
"start": 15708,
"tag": "NAME",
"value": "foo"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"SomeNumber\",\n \"accessLevel\" : \"Public\",\n ",
"end": 17239,
"score": 0.7053031325340271,
"start": 17229,
"tag": "NAME",
"value": "SomeNumber"
},
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 17546,
"score": 0.8759270310401917,
"start": 17539,
"tag": "NAME",
"value": "Patient"
},
{
"context": " } ]\n }, {\n \"name\" : \"square\",\n \"context\" : \"Patient\",\n ",
"end": 19784,
"score": 0.6053617596626282,
"start": 19778,
"tag": "NAME",
"value": "square"
},
{
"context": " } ]\n }, {\n \"name\" : \"TwoTimesThree\",\n \"context\" : \"Patient\",\n ",
"end": 20512,
"score": 0.6570842266082764,
"start": 20509,
"tag": "NAME",
"value": "Two"
},
{
"context": " } ]\n }, {\n \"name\" : \"TwoTimesThree\",\n \"context\" : \"Patient\",\n ",
"end": 20522,
"score": 0.9859492778778076,
"start": 20512,
"tag": "USERNAME",
"value": "TimesThree"
},
{
"context": " }\n }, {\n \"name\" : \"Two\",\n \"context\" : \"Patient\",\n ",
"end": 21103,
"score": 0.9386868476867676,
"start": 21100,
"tag": "NAME",
"value": "Two"
},
{
"context": " }\n }, {\n \"name\" : \"addTwo\",\n \"context\" : \"Patient\",\n ",
"end": 21391,
"score": 0.8075283765792847,
"start": 21388,
"tag": "NAME",
"value": "add"
},
{
"context": " }\n }, {\n \"name\" : \"addTwo\",\n \"context\" : \"Patient\",\n ",
"end": 21394,
"score": 0.7893957495689392,
"start": 21391,
"tag": "USERNAME",
"value": "Two"
},
{
"context": " \"operand\" : [ {\n \"name\" : \"a\",\n \"type\" : \"OperandRef\"\n ",
"end": 21626,
"score": 0.6569693088531494,
"start": 21625,
"tag": "NAME",
"value": "a"
},
{
"context": "\"\n }, {\n \"name\" : \"Two\",\n \"type\" : \"ExpressionRef\"\n ",
"end": 21720,
"score": 0.9859600067138672,
"start": 21717,
"tag": "NAME",
"value": "Two"
},
{
"context": " } ]\n }, {\n \"name\" : \"TwoPlusOne\",\n \"context\" : \"Patient\",\n ",
"end": 22083,
"score": 0.6855385303497314,
"start": 22080,
"tag": "NAME",
"value": "Two"
},
{
"context": " } ]\n }, {\n \"name\" : \"TwoPlusOne\",\n \"context\" : \"Patient\",\n ",
"end": 22090,
"score": 0.9472503662109375,
"start": 22083,
"tag": "USERNAME",
"value": "PlusOne"
},
{
"context": " \"operand\" : [ {\n \"name\" : \"Two\",\n \"type\" : \"ExpressionRef\"\n ",
"end": 22288,
"score": 0.9902480244636536,
"start": 22285,
"tag": "NAME",
"value": "Two"
},
{
"context": " }\n }, {\n \"name\" : \"SortUsingFunction\",\n \"context\" : \"Patient\",",
"end": 22566,
"score": 0.5177991986274719,
"start": 22562,
"tag": "NAME",
"value": "Sort"
},
{
"context": " }\n }, {\n \"name\" : \"SortUsingFunction\",\n \"context\" : \"Patient\",\n ",
"end": 22579,
"score": 0.9443299174308777,
"start": 22566,
"tag": "USERNAME",
"value": "UsingFunction"
}
] | Src/coffeescript/cql-execution/test/elm/library/data.coffee | MeasureAuthoringTool/clinical_quality_language | 2 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### In Age Demographic
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define InDemographic:
AgeInYearsAt(start of MeasurementPeriod) >= 2 and AgeInYearsAt(start of MeasurementPeriod) < 18
###
module.exports['In Age Demographic'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "InDemographic",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "GreaterOrEqual",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}, {
"type" : "Less",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "18",
"type" : "Literal"
} ]
} ]
}
} ]
}
}
}
### CommonLib
library Common
using QUICK
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define InDemographic:
AgeInYearsAt(start of MeasurementPeriod) >= 2 and AgeInYearsAt(start of MeasurementPeriod) < 18
define function foo (a Integer, b Integer) :
a + b
###
module.exports['CommonLib'] = {
"library" : {
"identifier" : {
"id" : "Common"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "InDemographic",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "GreaterOrEqual",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}, {
"type" : "Less",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "18",
"type" : "Literal"
} ]
} ]
}
}, {
"name" : "foo",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "a",
"type" : "OperandRef"
}, {
"name" : "b",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"name" : "b",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
} ]
}
}
}
### Using CommonLib
library TestSnippet version '1'
using QUICK
include Common called common
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define ID: common.InDemographic
define L : Length(Patient.name[0].given[0])
define FuncTest : common.foo(2, 5)
###
module.exports['Using CommonLib'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"includes" : {
"def" : [ {
"localIdentifier" : "common",
"path" : "Common"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "ID",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "InDemographic",
"libraryName" : "common",
"type" : "ExpressionRef"
}
}, {
"name" : "L",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Length",
"operand" : {
"type" : "Indexer",
"operand" : [ {
"path" : "given",
"type" : "Property",
"source" : {
"type" : "Indexer",
"operand" : [ {
"path" : "name",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
} ]
}
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
} ]
}
}
}, {
"name" : "FuncTest",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "foo",
"libraryName" : "common",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
} ]
}
}
}
### CommonLib2
library Common2
using QUICK
parameter SomeNumber default 17
context Patient
define TheParameter:
SomeNumber
define function addToParameter(a Integer):
SomeNumber + a
define function multiply(a Integer, b Integer) :
a * b
define function square(a Integer):
multiply(a, a)
define TwoTimesThree:
multiply(2, 3)
define Two:
2
define function addTwo(a Integer):
a + Two
define TwoPlusOne:
Two + 1
define SortUsingFunction:
({1, 3, 2, 5, 4}) N return Tuple{N: N} sort by square(N)
###
module.exports['CommonLib2'] = {
"library" : {
"identifier" : {
"id" : "Common2"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "SomeNumber",
"accessLevel" : "Public",
"default" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "17",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "TheParameter",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "SomeNumber",
"type" : "ParameterRef"
}
}, {
"name" : "addToParameter",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "SomeNumber",
"type" : "ParameterRef"
}, {
"name" : "a",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "multiply",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Multiply",
"operand" : [ {
"name" : "a",
"type" : "OperandRef"
}, {
"name" : "b",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"name" : "b",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "square",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"name" : "multiply",
"type" : "FunctionRef",
"operand" : [ {
"name" : "a",
"type" : "OperandRef"
}, {
"name" : "a",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "TwoTimesThree",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "multiply",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "3",
"type" : "Literal"
} ]
}
}, {
"name" : "Two",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}
}, {
"name" : "addTwo",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "a",
"type" : "OperandRef"
}, {
"name" : "Two",
"type" : "ExpressionRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "TwoPlusOne",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "Two",
"type" : "ExpressionRef"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
} ]
}
}, {
"name" : "SortUsingFunction",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "N",
"expression" : {
"type" : "List",
"element" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "3",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "4",
"type" : "Literal"
} ]
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "N",
"value" : {
"name" : "N",
"type" : "AliasRef"
}
} ]
}
},
"sort" : {
"by" : [ {
"direction" : "asc",
"type" : "ByExpression",
"expression" : {
"name" : "square",
"type" : "FunctionRef",
"operand" : [ {
"name" : "N",
"type" : "IdentifierRef"
} ]
}
} ]
}
}
} ]
}
}
}
### Using CommonLib2
library TestSnippet version '1'
using QUICK
include Common2 called common2
context Patient
define ExprUsesParam: common2.TheParameter
define FuncUsesParam: common2.addToParameter(5)
define ExprCallsFunc: common2.TwoTimesThree
define FuncCallsFunc: common2.square(5)
define ExprUsesExpr: common2.TwoPlusOne
define FuncUsesExpr: common2.addTwo(5)
define ExprSortsOnFunc: common2.SortUsingFunction
###
module.exports['Using CommonLib2'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"includes" : {
"def" : [ {
"localIdentifier" : "common2",
"path" : "Common2"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "ExprUsesParam",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "TheParameter",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
}, {
"name" : "FuncUsesParam",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "addToParameter",
"libraryName" : "common2",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
}, {
"name" : "ExprCallsFunc",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "TwoTimesThree",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
}, {
"name" : "FuncCallsFunc",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "square",
"libraryName" : "common2",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
}, {
"name" : "ExprUsesExpr",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "TwoPlusOne",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
}, {
"name" : "FuncUsesExpr",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "addTwo",
"libraryName" : "common2",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
}, {
"name" : "ExprSortsOnFunc",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "SortUsingFunction",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
} ]
}
}
}
| 216996 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### In Age Demographic
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define InDemographic:
AgeInYearsAt(start of MeasurementPeriod) >= 2 and AgeInYearsAt(start of MeasurementPeriod) < 18
###
module.exports['In Age Demographic'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>Demo<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "GreaterOrEqual",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}, {
"type" : "Less",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "18",
"type" : "Literal"
} ]
} ]
}
} ]
}
}
}
### CommonLib
library Common
using QUICK
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define InDemographic:
AgeInYearsAt(start of MeasurementPeriod) >= 2 and AgeInYearsAt(start of MeasurementPeriod) < 18
define function foo (a Integer, b Integer) :
a + b
###
module.exports['CommonLib'] = {
"library" : {
"identifier" : {
"id" : "Common"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>Demographic",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "GreaterOrEqual",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}, {
"type" : "Less",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "18",
"type" : "Literal"
} ]
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "<NAME>",
"type" : "OperandRef"
}, {
"name" : "<NAME>",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"name" : "b",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
} ]
}
}
}
### Using CommonLib
library TestSnippet version '1'
using QUICK
include Common called common
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define ID: common.InDemographic
define L : Length(Patient.name[0].given[0])
define FuncTest : common.foo(2, 5)
###
module.exports['Using CommonLib'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"includes" : {
"def" : [ {
"localIdentifier" : "common",
"path" : "Common"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "<NAME>",
"libraryName" : "common",
"type" : "ExpressionRef"
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Length",
"operand" : {
"type" : "Indexer",
"operand" : [ {
"path" : "given",
"type" : "Property",
"source" : {
"type" : "Indexer",
"operand" : [ {
"path" : "name",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
} ]
}
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
} ]
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "<NAME>",
"libraryName" : "common",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
} ]
}
}
}
### CommonLib2
library Common2
using QUICK
parameter SomeNumber default 17
context Patient
define TheParameter:
SomeNumber
define function addToParameter(a Integer):
SomeNumber + a
define function multiply(a Integer, b Integer) :
a * b
define function square(a Integer):
multiply(a, a)
define TwoTimesThree:
multiply(2, 3)
define Two:
2
define function addTwo(a Integer):
a + Two
define TwoPlusOne:
Two + 1
define SortUsingFunction:
({1, 3, 2, 5, 4}) N return Tuple{N: N} sort by square(N)
###
module.exports['CommonLib2'] = {
"library" : {
"identifier" : {
"id" : "Common2"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "<NAME>",
"accessLevel" : "Public",
"default" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "17",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "TheParameter",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "SomeNumber",
"type" : "ParameterRef"
}
}, {
"name" : "addToParameter",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "SomeNumber",
"type" : "ParameterRef"
}, {
"name" : "a",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "multiply",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Multiply",
"operand" : [ {
"name" : "a",
"type" : "OperandRef"
}, {
"name" : "b",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"name" : "b",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"name" : "multiply",
"type" : "FunctionRef",
"operand" : [ {
"name" : "a",
"type" : "OperandRef"
}, {
"name" : "a",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "<NAME>TimesThree",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "multiply",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "3",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}
}, {
"name" : "<NAME>Two",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "<NAME>",
"type" : "OperandRef"
}, {
"name" : "<NAME>",
"type" : "ExpressionRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "<NAME>PlusOne",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "<NAME>",
"type" : "ExpressionRef"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
} ]
}
}, {
"name" : "<NAME>UsingFunction",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "N",
"expression" : {
"type" : "List",
"element" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "3",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "4",
"type" : "Literal"
} ]
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "N",
"value" : {
"name" : "N",
"type" : "AliasRef"
}
} ]
}
},
"sort" : {
"by" : [ {
"direction" : "asc",
"type" : "ByExpression",
"expression" : {
"name" : "square",
"type" : "FunctionRef",
"operand" : [ {
"name" : "N",
"type" : "IdentifierRef"
} ]
}
} ]
}
}
} ]
}
}
}
### Using CommonLib2
library TestSnippet version '1'
using QUICK
include Common2 called common2
context Patient
define ExprUsesParam: common2.TheParameter
define FuncUsesParam: common2.addToParameter(5)
define ExprCallsFunc: common2.TwoTimesThree
define FuncCallsFunc: common2.square(5)
define ExprUsesExpr: common2.TwoPlusOne
define FuncUsesExpr: common2.addTwo(5)
define ExprSortsOnFunc: common2.SortUsingFunction
###
module.exports['Using CommonLib2'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"includes" : {
"def" : [ {
"localIdentifier" : "common2",
"path" : "Common2"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "ExprUsesParam",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "TheParameter",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
}, {
"name" : "FuncUsesParam",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "addToParameter",
"libraryName" : "common2",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
}, {
"name" : "ExprCallsFunc",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "TwoTimesThree",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
}, {
"name" : "FuncCallsFunc",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "square",
"libraryName" : "common2",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
}, {
"name" : "ExprUsesExpr",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "TwoPlusOne",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
}, {
"name" : "FuncUsesExpr",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "addTwo",
"libraryName" : "common2",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
}, {
"name" : "ExprSortsOnFunc",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "SortUsingFunction",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
} ]
}
}
}
| true | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### In Age Demographic
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define InDemographic:
AgeInYearsAt(start of MeasurementPeriod) >= 2 and AgeInYearsAt(start of MeasurementPeriod) < 18
###
module.exports['In Age Demographic'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PIDemoPI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "GreaterOrEqual",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}, {
"type" : "Less",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "18",
"type" : "Literal"
} ]
} ]
}
} ]
}
}
}
### CommonLib
library Common
using QUICK
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define InDemographic:
AgeInYearsAt(start of MeasurementPeriod) >= 2 and AgeInYearsAt(start of MeasurementPeriod) < 18
define function foo (a Integer, b Integer) :
a + b
###
module.exports['CommonLib'] = {
"library" : {
"identifier" : {
"id" : "Common"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PIDemographic",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "GreaterOrEqual",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}, {
"type" : "Less",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "18",
"type" : "Literal"
} ]
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "OperandRef"
}, {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"name" : "b",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
} ]
}
}
}
### Using CommonLib
library TestSnippet version '1'
using QUICK
include Common called common
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define ID: common.InDemographic
define L : Length(Patient.name[0].given[0])
define FuncTest : common.foo(2, 5)
###
module.exports['Using CommonLib'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"includes" : {
"def" : [ {
"localIdentifier" : "common",
"path" : "Common"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "PI:NAME:<NAME>END_PI",
"libraryName" : "common",
"type" : "ExpressionRef"
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Length",
"operand" : {
"type" : "Indexer",
"operand" : [ {
"path" : "given",
"type" : "Property",
"source" : {
"type" : "Indexer",
"operand" : [ {
"path" : "name",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
} ]
}
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
} ]
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "PI:NAME:<NAME>END_PI",
"libraryName" : "common",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
} ]
}
}
}
### CommonLib2
library Common2
using QUICK
parameter SomeNumber default 17
context Patient
define TheParameter:
SomeNumber
define function addToParameter(a Integer):
SomeNumber + a
define function multiply(a Integer, b Integer) :
a * b
define function square(a Integer):
multiply(a, a)
define TwoTimesThree:
multiply(2, 3)
define Two:
2
define function addTwo(a Integer):
a + Two
define TwoPlusOne:
Two + 1
define SortUsingFunction:
({1, 3, 2, 5, 4}) N return Tuple{N: N} sort by square(N)
###
module.exports['CommonLib2'] = {
"library" : {
"identifier" : {
"id" : "Common2"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"default" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "17",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "TheParameter",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "SomeNumber",
"type" : "ParameterRef"
}
}, {
"name" : "addToParameter",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "SomeNumber",
"type" : "ParameterRef"
}, {
"name" : "a",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "multiply",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Multiply",
"operand" : [ {
"name" : "a",
"type" : "OperandRef"
}, {
"name" : "b",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"name" : "b",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"name" : "multiply",
"type" : "FunctionRef",
"operand" : [ {
"name" : "a",
"type" : "OperandRef"
}, {
"name" : "a",
"type" : "OperandRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "PI:NAME:<NAME>END_PITimesThree",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "multiply",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "3",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}
}, {
"name" : "PI:NAME:<NAME>END_PITwo",
"context" : "Patient",
"accessLevel" : "Public",
"type" : "FunctionDef",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "OperandRef"
}, {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ExpressionRef"
} ]
},
"operand" : [ {
"name" : "a",
"operandTypeSpecifier" : {
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}, {
"name" : "PI:NAME:<NAME>END_PIPlusOne",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Add",
"operand" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ExpressionRef"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PIUsingFunction",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "Query",
"source" : [ {
"alias" : "N",
"expression" : {
"type" : "List",
"element" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "3",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "4",
"type" : "Literal"
} ]
}
} ],
"relationship" : [ ],
"return" : {
"expression" : {
"type" : "Tuple",
"element" : [ {
"name" : "N",
"value" : {
"name" : "N",
"type" : "AliasRef"
}
} ]
}
},
"sort" : {
"by" : [ {
"direction" : "asc",
"type" : "ByExpression",
"expression" : {
"name" : "square",
"type" : "FunctionRef",
"operand" : [ {
"name" : "N",
"type" : "IdentifierRef"
} ]
}
} ]
}
}
} ]
}
}
}
### Using CommonLib2
library TestSnippet version '1'
using QUICK
include Common2 called common2
context Patient
define ExprUsesParam: common2.TheParameter
define FuncUsesParam: common2.addToParameter(5)
define ExprCallsFunc: common2.TwoTimesThree
define FuncCallsFunc: common2.square(5)
define ExprUsesExpr: common2.TwoPlusOne
define FuncUsesExpr: common2.addTwo(5)
define ExprSortsOnFunc: common2.SortUsingFunction
###
module.exports['Using CommonLib2'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"includes" : {
"def" : [ {
"localIdentifier" : "common2",
"path" : "Common2"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "ExprUsesParam",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "TheParameter",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
}, {
"name" : "FuncUsesParam",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "addToParameter",
"libraryName" : "common2",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
}, {
"name" : "ExprCallsFunc",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "TwoTimesThree",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
}, {
"name" : "FuncCallsFunc",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "square",
"libraryName" : "common2",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
}, {
"name" : "ExprUsesExpr",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "TwoPlusOne",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
}, {
"name" : "FuncUsesExpr",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "addTwo",
"libraryName" : "common2",
"type" : "FunctionRef",
"operand" : [ {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
} ]
}
}, {
"name" : "ExprSortsOnFunc",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"name" : "SortUsingFunction",
"libraryName" : "common2",
"type" : "ExpressionRef"
}
} ]
}
}
}
|
[
{
"context": "isdom I guild buff increases Wisdom.\n *\n * @name Wisdom I\n * @requirement {gold} 4000\n * @requirement {gu",
"end": 115,
"score": 0.760959267616272,
"start": 107,
"tag": "NAME",
"value": "Wisdom I"
},
{
"context": "sdom II guild buff increases Wisdom.\n *\n * @name Wisdom II\n * @requirement {gold} 9000\n * @requirement ",
"end": 375,
"score": 0.7273475527763367,
"start": 369,
"tag": "NAME",
"value": "Wisdom"
},
{
"context": "dom III guild buff increases Wisdom.\n *\n * @name Wisdom III\n * @requirement {gold} 16000\n * @requiremen",
"end": 650,
"score": 0.7015158534049988,
"start": 644,
"tag": "NAME",
"value": "Wisdom"
},
{
"context": "sdom IV guild buff increases Wisdom.\n *\n * @name Wisdom IV\n * @requirement {gold} 25000\n * @requirement",
"end": 917,
"score": 0.6958208084106445,
"start": 911,
"tag": "NAME",
"value": "Wisdom"
},
{
"context": "isdom V guild buff increases Wisdom.\n *\n * @name Wisdom V\n * @requirement {gold} 36000\n * @requirement ",
"end": 1192,
"score": 0.725290834903717,
"start": 1186,
"tag": "NAME",
"value": "Wisdom"
},
{
"context": "sdom VI guild buff increases Wisdom.\n *\n * @name Wisdom VI\n * @requirement {gold} 49000\n * @requirem",
"end": 1454,
"score": 0.7228773832321167,
"start": 1451,
"tag": "NAME",
"value": "Wis"
},
{
"context": "dom VII guild buff increases Wisdom.\n *\n * @name Wisdom VII\n * @requirement {gold} 64000\n * @requi",
"end": 1729,
"score": 0.9113858938217163,
"start": 1728,
"tag": "NAME",
"value": "W"
},
{
"context": "om VIII guild buff increases Wisdom.\n *\n * @name Wisdom VIII\n * @requirement {gold} 81000\n * @requ",
"end": 1999,
"score": 0.8621973991394043,
"start": 1998,
"tag": "NAME",
"value": "W"
},
{
"context": "sdom IX guild buff increases Wisdom.\n *\n * @name Wisdom IX\n * @requirement {gold} 100000\n * @requi",
"end": 2278,
"score": 0.8342551589012146,
"start": 2277,
"tag": "NAME",
"value": "W"
},
{
"context": " @tiers = GuildWisdom::tiers = [null,\n {name: \"Wisdom I\", level: 20, members: 1, cost: 4000, durat",
"end": 2569,
"score": 0.7535461783409119,
"start": 2568,
"tag": "NAME",
"value": "W"
},
{
"context": " 1, cost: 4000, duration: {days: 1}},\n {name: \"Wisdom II\", level: 30, members: 1, cost: 9000, dura",
"end": 2649,
"score": 0.8114827275276184,
"start": 2648,
"tag": "NAME",
"value": "W"
},
{
"context": "000, duration: {days: 1, hours: 12}},\n {name: \"Wisdom III\", level: 40, members: 4, cost: 16000, du",
"end": 2741,
"score": 0.7171693444252014,
"start": 2740,
"tag": "NAME",
"value": "W"
},
{
"context": "4, cost: 16000, duration: {days: 2}},\n {name: \"Wisdom IV\", level: 50, members: 4, cost: 25000, duration: {",
"end": 2832,
"score": 0.9992262125015259,
"start": 2823,
"tag": "NAME",
"value": "Wisdom IV"
},
{
"context": "000, duration: {days: 2, hours: 12}},\n {name: \"Wisdom V\", level: 60, members: 9, cost: 36000, duration: {",
"end": 2924,
"score": 0.9991101622581482,
"start": 2916,
"tag": "NAME",
"value": "Wisdom V"
},
{
"context": "9, cost: 36000, duration: {days: 3}},\n {name: \"Wisdom VI\", level: 70, members: 9, cost: 49000, duration: {",
"end": 3006,
"score": 0.9988914728164673,
"start": 2997,
"tag": "NAME",
"value": "Wisdom VI"
},
{
"context": "000, duration: {days: 3, hours: 12}},\n {name: \"Wisdom VII\", level: 80, members: 15, cost: 64000, duration: ",
"end": 3100,
"score": 0.9975169897079468,
"start": 3090,
"tag": "NAME",
"value": "Wisdom VII"
},
{
"context": "5, cost: 64000, duration: {days: 4}},\n {name: \"Wisdom VIII\", level: 90, members: 15, cost: 81000, duration: ",
"end": 3185,
"score": 0.99763023853302,
"start": 3174,
"tag": "NAME",
"value": "Wisdom VIII"
},
{
"context": "000, duration: {days: 4, hours: 12}},\n {name: \"Wisdom IX\", level: 100, members: 20, cost: 100000, duration",
"end": 3279,
"score": 0.9979168772697449,
"start": 3270,
"tag": "NAME",
"value": "Wisdom IX"
}
] | src/character/guildBuffs/GuildWisdom.coffee | sadbear-/IdleLands | 0 |
GuildBuff = require "../base/GuildBuff"
`/**
* The Wisdom I guild buff increases Wisdom.
*
* @name Wisdom I
* @requirement {gold} 4000
* @requirement {guild level} 20
* @requirement {guild members} 1
* @effect +5% WIS
* @duration 1 day
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom II guild buff increases Wisdom.
*
* @name Wisdom II
* @requirement {gold} 9000
* @requirement {guild level} 30
* @requirement {guild members} 1
* @effect +10% WIS
* @duration 1 day, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom III guild buff increases Wisdom.
*
* @name Wisdom III
* @requirement {gold} 16000
* @requirement {guild level} 40
* @requirement {guild members} 4
* @effect +15% WIS
* @duration 2 days
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom IV guild buff increases Wisdom.
*
* @name Wisdom IV
* @requirement {gold} 25000
* @requirement {guild level} 50
* @requirement {guild members} 4
* @effect +20% WIS
* @duration 2 days, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom V guild buff increases Wisdom.
*
* @name Wisdom V
* @requirement {gold} 36000
* @requirement {guild level} 60
* @requirement {guild members} 9
* @effect +25% WIS
* @duration 3 days
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom VI guild buff increases Wisdom.
*
* @name Wisdom VI
* @requirement {gold} 49000
* @requirement {guild level} 80
* @requirement {guild members} 9
* @effect +30% WIS
* @duration 3 days, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom VII guild buff increases Wisdom.
*
* @name Wisdom VII
* @requirement {gold} 64000
* @requirement {guild level} 80
* @requirement {guild members} 15
* @effect +35% WIS
* @duration 4 days
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom VIII guild buff increases Wisdom.
*
* @name Wisdom VIII
* @requirement {gold} 81000
* @requirement {guild level} 90
* @requirement {guild members} 15
* @effect +40% WIS
* @duration 4 days, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom IX guild buff increases Wisdom.
*
* @name Wisdom IX
* @requirement {gold} 100000
* @requirement {guild level} 100
* @requirement {guild members} 20
* @effect +45% WIS
* @duration 5 days
* @category Wisdom
* @package GuildBuffs
*/`
class GuildWisdom extends GuildBuff
@tiers = GuildWisdom::tiers = [null,
{name: "Wisdom I", level: 20, members: 1, cost: 4000, duration: {days: 1}},
{name: "Wisdom II", level: 30, members: 1, cost: 9000, duration: {days: 1, hours: 12}},
{name: "Wisdom III", level: 40, members: 4, cost: 16000, duration: {days: 2}},
{name: "Wisdom IV", level: 50, members: 4, cost: 25000, duration: {days: 2, hours: 12}},
{name: "Wisdom V", level: 60, members: 9, cost: 36000, duration: {days: 3}},
{name: "Wisdom VI", level: 70, members: 9, cost: 49000, duration: {days: 3, hours: 12}},
{name: "Wisdom VII", level: 80, members: 15, cost: 64000, duration: {days: 4}},
{name: "Wisdom VIII", level: 90, members: 15, cost: 81000, duration: {days: 4, hours: 12}},
{name: "Wisdom IX", level: 100, members: 20, cost: 100000, duration: {days: 5}}
]
constructor: (@tier = 1) ->
@type = 'Wisdom'
super()
wisPercent: -> @tier*5
module.exports = exports = GuildWisdom | 133719 |
GuildBuff = require "../base/GuildBuff"
`/**
* The Wisdom I guild buff increases Wisdom.
*
* @name <NAME>
* @requirement {gold} 4000
* @requirement {guild level} 20
* @requirement {guild members} 1
* @effect +5% WIS
* @duration 1 day
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom II guild buff increases Wisdom.
*
* @name <NAME> II
* @requirement {gold} 9000
* @requirement {guild level} 30
* @requirement {guild members} 1
* @effect +10% WIS
* @duration 1 day, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom III guild buff increases Wisdom.
*
* @name <NAME> III
* @requirement {gold} 16000
* @requirement {guild level} 40
* @requirement {guild members} 4
* @effect +15% WIS
* @duration 2 days
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom IV guild buff increases Wisdom.
*
* @name <NAME> IV
* @requirement {gold} 25000
* @requirement {guild level} 50
* @requirement {guild members} 4
* @effect +20% WIS
* @duration 2 days, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom V guild buff increases Wisdom.
*
* @name <NAME> V
* @requirement {gold} 36000
* @requirement {guild level} 60
* @requirement {guild members} 9
* @effect +25% WIS
* @duration 3 days
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom VI guild buff increases Wisdom.
*
* @name <NAME>dom VI
* @requirement {gold} 49000
* @requirement {guild level} 80
* @requirement {guild members} 9
* @effect +30% WIS
* @duration 3 days, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom VII guild buff increases Wisdom.
*
* @name <NAME>isdom VII
* @requirement {gold} 64000
* @requirement {guild level} 80
* @requirement {guild members} 15
* @effect +35% WIS
* @duration 4 days
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom VIII guild buff increases Wisdom.
*
* @name <NAME>isdom VIII
* @requirement {gold} 81000
* @requirement {guild level} 90
* @requirement {guild members} 15
* @effect +40% WIS
* @duration 4 days, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom IX guild buff increases Wisdom.
*
* @name <NAME>isdom IX
* @requirement {gold} 100000
* @requirement {guild level} 100
* @requirement {guild members} 20
* @effect +45% WIS
* @duration 5 days
* @category Wisdom
* @package GuildBuffs
*/`
class GuildWisdom extends GuildBuff
@tiers = GuildWisdom::tiers = [null,
{name: "<NAME>isdom I", level: 20, members: 1, cost: 4000, duration: {days: 1}},
{name: "<NAME>isdom II", level: 30, members: 1, cost: 9000, duration: {days: 1, hours: 12}},
{name: "<NAME>isdom III", level: 40, members: 4, cost: 16000, duration: {days: 2}},
{name: "<NAME>", level: 50, members: 4, cost: 25000, duration: {days: 2, hours: 12}},
{name: "<NAME>", level: 60, members: 9, cost: 36000, duration: {days: 3}},
{name: "<NAME>", level: 70, members: 9, cost: 49000, duration: {days: 3, hours: 12}},
{name: "<NAME>", level: 80, members: 15, cost: 64000, duration: {days: 4}},
{name: "<NAME>", level: 90, members: 15, cost: 81000, duration: {days: 4, hours: 12}},
{name: "<NAME>", level: 100, members: 20, cost: 100000, duration: {days: 5}}
]
constructor: (@tier = 1) ->
@type = 'Wisdom'
super()
wisPercent: -> @tier*5
module.exports = exports = GuildWisdom | true |
GuildBuff = require "../base/GuildBuff"
`/**
* The Wisdom I guild buff increases Wisdom.
*
* @name PI:NAME:<NAME>END_PI
* @requirement {gold} 4000
* @requirement {guild level} 20
* @requirement {guild members} 1
* @effect +5% WIS
* @duration 1 day
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom II guild buff increases Wisdom.
*
* @name PI:NAME:<NAME>END_PI II
* @requirement {gold} 9000
* @requirement {guild level} 30
* @requirement {guild members} 1
* @effect +10% WIS
* @duration 1 day, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom III guild buff increases Wisdom.
*
* @name PI:NAME:<NAME>END_PI III
* @requirement {gold} 16000
* @requirement {guild level} 40
* @requirement {guild members} 4
* @effect +15% WIS
* @duration 2 days
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom IV guild buff increases Wisdom.
*
* @name PI:NAME:<NAME>END_PI IV
* @requirement {gold} 25000
* @requirement {guild level} 50
* @requirement {guild members} 4
* @effect +20% WIS
* @duration 2 days, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom V guild buff increases Wisdom.
*
* @name PI:NAME:<NAME>END_PI V
* @requirement {gold} 36000
* @requirement {guild level} 60
* @requirement {guild members} 9
* @effect +25% WIS
* @duration 3 days
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom VI guild buff increases Wisdom.
*
* @name PI:NAME:<NAME>END_PIdom VI
* @requirement {gold} 49000
* @requirement {guild level} 80
* @requirement {guild members} 9
* @effect +30% WIS
* @duration 3 days, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom VII guild buff increases Wisdom.
*
* @name PI:NAME:<NAME>END_PIisdom VII
* @requirement {gold} 64000
* @requirement {guild level} 80
* @requirement {guild members} 15
* @effect +35% WIS
* @duration 4 days
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom VIII guild buff increases Wisdom.
*
* @name PI:NAME:<NAME>END_PIisdom VIII
* @requirement {gold} 81000
* @requirement {guild level} 90
* @requirement {guild members} 15
* @effect +40% WIS
* @duration 4 days, 12 hours
* @category Wisdom
* @package GuildBuffs
*/`
`/**
* The Wisdom IX guild buff increases Wisdom.
*
* @name PI:NAME:<NAME>END_PIisdom IX
* @requirement {gold} 100000
* @requirement {guild level} 100
* @requirement {guild members} 20
* @effect +45% WIS
* @duration 5 days
* @category Wisdom
* @package GuildBuffs
*/`
class GuildWisdom extends GuildBuff
@tiers = GuildWisdom::tiers = [null,
{name: "PI:NAME:<NAME>END_PIisdom I", level: 20, members: 1, cost: 4000, duration: {days: 1}},
{name: "PI:NAME:<NAME>END_PIisdom II", level: 30, members: 1, cost: 9000, duration: {days: 1, hours: 12}},
{name: "PI:NAME:<NAME>END_PIisdom III", level: 40, members: 4, cost: 16000, duration: {days: 2}},
{name: "PI:NAME:<NAME>END_PI", level: 50, members: 4, cost: 25000, duration: {days: 2, hours: 12}},
{name: "PI:NAME:<NAME>END_PI", level: 60, members: 9, cost: 36000, duration: {days: 3}},
{name: "PI:NAME:<NAME>END_PI", level: 70, members: 9, cost: 49000, duration: {days: 3, hours: 12}},
{name: "PI:NAME:<NAME>END_PI", level: 80, members: 15, cost: 64000, duration: {days: 4}},
{name: "PI:NAME:<NAME>END_PI", level: 90, members: 15, cost: 81000, duration: {days: 4, hours: 12}},
{name: "PI:NAME:<NAME>END_PI", level: 100, members: 20, cost: 100000, duration: {days: 5}}
]
constructor: (@tier = 1) ->
@type = 'Wisdom'
super()
wisPercent: -> @tier*5
module.exports = exports = GuildWisdom |
[
{
"context": " else if program.sha\n password = '{SHA}' + module.exports.sha1 password\n else\n ",
"end": 1150,
"score": 0.6488337516784668,
"start": 1147,
"tag": "PASSWORD",
"value": "SHA"
},
{
"context": "ts.sha1 password\n else\n password = md5(password)\n # Return result.\n password",
"end": 1221,
"score": 0.9561734199523926,
"start": 1218,
"tag": "PASSWORD",
"value": "md5"
}
] | src/node_modules/http-auth/node_modules/htpasswd/src/utils.coffee | sisense-dev/kibana | 4 | # Importing crypto module.
crypto = require 'crypto'
# Importing apache-md5 module.
md5 = require 'apache-md5'
# Importing apache-crypt module.
crypt = require 'apache-crypt'
# Module for utility functionalities.
module.exports =
# Crypt method.
crypt3: (password, hash) ->
crypt password, hash
# Generates sha1 hash of password.
sha1: (password) ->
hash = crypto.createHash 'sha1'
hash.update password
hash.digest 'base64'
# Verifies if password is correct.
verify: (hash, password) ->
if (hash.substr 0, 5) is '{SHA}'
hash = hash.substr 5
hash is module.exports.sha1 password
else if (hash.substr 0, 6) is '$apr1$'
hash is md5(password, hash)
else
(hash is password) or ((module.exports.crypt3 password, hash) is hash)
# Encodes password hash for output.
encode: (program) ->
if not program.delete
# Get username and password.
password = program.args[program.args.length - 1]
# Encode.
if not program.plaintext
if program.crypt
password = (module.exports.crypt3 password)
else if program.sha
password = '{SHA}' + module.exports.sha1 password
else
password = md5(password)
# Return result.
password | 219569 | # Importing crypto module.
crypto = require 'crypto'
# Importing apache-md5 module.
md5 = require 'apache-md5'
# Importing apache-crypt module.
crypt = require 'apache-crypt'
# Module for utility functionalities.
module.exports =
# Crypt method.
crypt3: (password, hash) ->
crypt password, hash
# Generates sha1 hash of password.
sha1: (password) ->
hash = crypto.createHash 'sha1'
hash.update password
hash.digest 'base64'
# Verifies if password is correct.
verify: (hash, password) ->
if (hash.substr 0, 5) is '{SHA}'
hash = hash.substr 5
hash is module.exports.sha1 password
else if (hash.substr 0, 6) is '$apr1$'
hash is md5(password, hash)
else
(hash is password) or ((module.exports.crypt3 password, hash) is hash)
# Encodes password hash for output.
encode: (program) ->
if not program.delete
# Get username and password.
password = program.args[program.args.length - 1]
# Encode.
if not program.plaintext
if program.crypt
password = (module.exports.crypt3 password)
else if program.sha
password = '{<PASSWORD>}' + module.exports.sha1 password
else
password = <PASSWORD>(password)
# Return result.
password | true | # Importing crypto module.
crypto = require 'crypto'
# Importing apache-md5 module.
md5 = require 'apache-md5'
# Importing apache-crypt module.
crypt = require 'apache-crypt'
# Module for utility functionalities.
module.exports =
# Crypt method.
crypt3: (password, hash) ->
crypt password, hash
# Generates sha1 hash of password.
sha1: (password) ->
hash = crypto.createHash 'sha1'
hash.update password
hash.digest 'base64'
# Verifies if password is correct.
verify: (hash, password) ->
if (hash.substr 0, 5) is '{SHA}'
hash = hash.substr 5
hash is module.exports.sha1 password
else if (hash.substr 0, 6) is '$apr1$'
hash is md5(password, hash)
else
(hash is password) or ((module.exports.crypt3 password, hash) is hash)
# Encodes password hash for output.
encode: (program) ->
if not program.delete
# Get username and password.
password = program.args[program.args.length - 1]
# Encode.
if not program.plaintext
if program.crypt
password = (module.exports.crypt3 password)
else if program.sha
password = '{PI:PASSWORD:<PASSWORD>END_PI}' + module.exports.sha1 password
else
password = PI:PASSWORD:<PASSWORD>END_PI(password)
# Return result.
password |
[
{
"context": "nds Marionette.Module\n onStart: ->\n apiKey = 'JQfSXfyNsMd9hupTfhZRyQ'\n src = \"http://widget.uservoice.com/#{apiKey}",
"end": 179,
"score": 0.9997158050537109,
"start": 157,
"tag": "KEY",
"value": "JQfSXfyNsMd9hupTfhZRyQ"
}
] | app/modules/feedback/module.coffee | sabakaio/topdeck.pro | 0 | $ = require 'jquery'
Marionette = require 'backbone.marionette'
module.exports = class FeedbackModule extends Marionette.Module
onStart: ->
apiKey = 'JQfSXfyNsMd9hupTfhZRyQ'
src = "http://widget.uservoice.com/#{apiKey}.js"
$.getScript src, ->
UserVoice.push ['set',
accent_color: '#448dd6'
trigger_color: 'white'
trigger_background_color: '#e23a39'
]
UserVoice.push ['addTrigger',
mode: 'contact',
trigger_position: 'bottom-right'
]
| 192353 | $ = require 'jquery'
Marionette = require 'backbone.marionette'
module.exports = class FeedbackModule extends Marionette.Module
onStart: ->
apiKey = '<KEY>'
src = "http://widget.uservoice.com/#{apiKey}.js"
$.getScript src, ->
UserVoice.push ['set',
accent_color: '#448dd6'
trigger_color: 'white'
trigger_background_color: '#e23a39'
]
UserVoice.push ['addTrigger',
mode: 'contact',
trigger_position: 'bottom-right'
]
| true | $ = require 'jquery'
Marionette = require 'backbone.marionette'
module.exports = class FeedbackModule extends Marionette.Module
onStart: ->
apiKey = 'PI:KEY:<KEY>END_PI'
src = "http://widget.uservoice.com/#{apiKey}.js"
$.getScript src, ->
UserVoice.push ['set',
accent_color: '#448dd6'
trigger_color: 'white'
trigger_background_color: '#e23a39'
]
UserVoice.push ['addTrigger',
mode: 'contact',
trigger_position: 'bottom-right'
]
|
[
{
"context": "# it 'Should create a new user', (done)=>\n # (@testUser = new API.User).save {username:'test.user',passwo",
"end": 497,
"score": 0.8982911109924316,
"start": 489,
"tag": "USERNAME",
"value": "testUser"
},
{
"context": "\n # (@testUser = new API.User).save {username:'test.user',password:'sParseTest'},\n # success:(m,r,o)=",
"end": 539,
"score": 0.9996746182441711,
"start": 530,
"tag": "USERNAME",
"value": "test.user"
},
{
"context": "ew API.User).save {username:'test.user',password:'sParseTest'},\n # success:(m,r,o)=>\n # done()\n #",
"end": 561,
"score": 0.9991795420646667,
"start": 551,
"tag": "PASSWORD",
"value": "sParseTest"
},
{
"context": " # it 'Should be able to login', (done)=>\n # @testUser.login (@testUser.get 'username'), (@testUser.",
"end": 662,
"score": 0.825359582901001,
"start": 658,
"tag": "USERNAME",
"value": "test"
},
{
"context": " be able to login', (done)=>\n # @testUser.login (@testUser.get 'username'), (@testUser.get 'password'),\n ",
"end": 683,
"score": 0.9976136684417725,
"start": 673,
"tag": "USERNAME",
"value": "(@testUser"
},
{
"context": "', (done)=>\n # @testUser.login (@testUser.get 'username'), (@testUser.get 'password'),\n # success:(m",
"end": 697,
"score": 0.6035821437835693,
"start": 689,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\n # @testUser.login (@testUser.get 'username'), (@testUser.get 'password'),\n # success:(m,r,o)=>\n ",
"end": 711,
"score": 0.844305694103241,
"start": 701,
"tag": "USERNAME",
"value": "(@testUser"
},
{
"context": "te itself', (done)=>\n # @testUser.save email: 'a.user+changed@email.com',\n # success:(m,r,o)=>\n # done()\n ",
"end": 976,
"score": 0.9998388290405273,
"start": 952,
"tag": "EMAIL",
"value": "a.user+changed@email.com"
},
{
"context": "# @testUser.logout()\n # @testUser.save email: 'a.user@email.com',\n # error:(m,r,o)=>\n # done()\n # it",
"end": 1184,
"score": 0.9998847246170044,
"start": 1168,
"tag": "EMAIL",
"value": "a.user@email.com"
},
{
"context": "to be destroyed', (done)=>\n # @testUser.login 'test.user', 'sParseTest',\n # success:(m,r,o)=>\n ",
"end": 1310,
"score": 0.9996355175971985,
"start": 1301,
"tag": "USERNAME",
"value": "test.user"
},
{
"context": "ed', (done)=>\n # @testUser.login 'test.user', 'sParseTest',\n # success:(m,r,o)=>\n # @testUser.d",
"end": 1324,
"score": 0.9682130813598633,
"start": 1314,
"tag": "PASSWORD",
"value": "sParseTest"
}
] | test/server/node_modules/api-hero/node_modules/rikki-tikki-client/test/user.coffee | vancarney/apihero-module-socket.io | 0 | # fs = require 'fs'
# (chai = require 'chai').should()
# _ = (require 'underscore')._
# Backbone = require 'backbone'
# Backbone.$ = require 'jQuery'
# {RikkiTikki} = require '../index'
# jsonData = require './data.json'
# server = true
# API = RikkiTikki.createScope 'api'
# API.PORT = 3000
#
# describe 'API.User lifecycle', ->
# @timeout 15000
# it 'Should create a new user', (done)=>
# (@testUser = new API.User).save {username:'test.user',password:'sParseTest'},
# success:(m,r,o)=>
# done()
# it 'Should be able to login', (done)=>
# @testUser.login (@testUser.get 'username'), (@testUser.get 'password'),
# success:(m,r,o)=>
# done()
# it 'Should have set SESSION_TOKEN after login', ->
# API.SESSION_TOKEN.should.be.a 'string'
# it 'Should be able to update itself', (done)=>
# @testUser.save email: 'a.user+changed@email.com',
# success:(m,r,o)=>
# done()
# error:(m,r,o)=>
# console.log r
# it 'Should be able to logout', (done)=>
# @testUser.logout()
# @testUser.save email: 'a.user@email.com',
# error:(m,r,o)=>
# done()
# it 'Should be able to be destroyed', (done)=>
# @testUser.login 'test.user', 'sParseTest',
# success:(m,r,o)=>
# @testUser.destroy
# success:(m,r,o)=>
# done() | 49445 | # fs = require 'fs'
# (chai = require 'chai').should()
# _ = (require 'underscore')._
# Backbone = require 'backbone'
# Backbone.$ = require 'jQuery'
# {RikkiTikki} = require '../index'
# jsonData = require './data.json'
# server = true
# API = RikkiTikki.createScope 'api'
# API.PORT = 3000
#
# describe 'API.User lifecycle', ->
# @timeout 15000
# it 'Should create a new user', (done)=>
# (@testUser = new API.User).save {username:'test.user',password:'<PASSWORD>'},
# success:(m,r,o)=>
# done()
# it 'Should be able to login', (done)=>
# @testUser.login (@testUser.get 'username'), (@testUser.get 'password'),
# success:(m,r,o)=>
# done()
# it 'Should have set SESSION_TOKEN after login', ->
# API.SESSION_TOKEN.should.be.a 'string'
# it 'Should be able to update itself', (done)=>
# @testUser.save email: '<EMAIL>',
# success:(m,r,o)=>
# done()
# error:(m,r,o)=>
# console.log r
# it 'Should be able to logout', (done)=>
# @testUser.logout()
# @testUser.save email: '<EMAIL>',
# error:(m,r,o)=>
# done()
# it 'Should be able to be destroyed', (done)=>
# @testUser.login 'test.user', '<PASSWORD>',
# success:(m,r,o)=>
# @testUser.destroy
# success:(m,r,o)=>
# done() | true | # fs = require 'fs'
# (chai = require 'chai').should()
# _ = (require 'underscore')._
# Backbone = require 'backbone'
# Backbone.$ = require 'jQuery'
# {RikkiTikki} = require '../index'
# jsonData = require './data.json'
# server = true
# API = RikkiTikki.createScope 'api'
# API.PORT = 3000
#
# describe 'API.User lifecycle', ->
# @timeout 15000
# it 'Should create a new user', (done)=>
# (@testUser = new API.User).save {username:'test.user',password:'PI:PASSWORD:<PASSWORD>END_PI'},
# success:(m,r,o)=>
# done()
# it 'Should be able to login', (done)=>
# @testUser.login (@testUser.get 'username'), (@testUser.get 'password'),
# success:(m,r,o)=>
# done()
# it 'Should have set SESSION_TOKEN after login', ->
# API.SESSION_TOKEN.should.be.a 'string'
# it 'Should be able to update itself', (done)=>
# @testUser.save email: 'PI:EMAIL:<EMAIL>END_PI',
# success:(m,r,o)=>
# done()
# error:(m,r,o)=>
# console.log r
# it 'Should be able to logout', (done)=>
# @testUser.logout()
# @testUser.save email: 'PI:EMAIL:<EMAIL>END_PI',
# error:(m,r,o)=>
# done()
# it 'Should be able to be destroyed', (done)=>
# @testUser.login 'test.user', 'PI:PASSWORD:<PASSWORD>END_PI',
# success:(m,r,o)=>
# @testUser.destroy
# success:(m,r,o)=>
# done() |
[
{
"context": "\t\tcontinue if key is 'get'\n\t\t\tcontinue if key is 'stringArray' # TODO\n\t\t\treturn key if @[key] v\n\t\tconsole.",
"end": 139,
"score": 0.6044160723686218,
"start": 133,
"tag": "KEY",
"value": "string"
}
] | src/helpers/isType.coffee | rapid-build/rapid-build | 5 | module.exports =
# type
# ====
get: (v) -> # :string | void
for own key of @
continue if key is 'get'
continue if key is 'stringArray' # TODO
return key if @[key] v
console.log new Error("type not in lib: #{v}").message.warn
undefined
# types (all return :boolean)
# =====
array: (v) ->
Array.isArray v
boolean: (v) ->
typeof v is 'boolean'
error: (v) ->
v instanceof Error
function: (v) ->
typeof v is 'function'
int: (v) ->
return false unless @number v
v % 1 is 0
null: (v) ->
v is null
number: (v) ->
return false if @null v
return false if @array v
return false if @string v
return false if @boolean v
not isNaN v
object: (v) ->
return false if typeof v isnt 'object'
return false if v is null
return false if @array v
true
string: (v) ->
typeof v is 'string'
stringArray: (v) -> # v should be an array of strings
return false unless @array v
for val in v
return false unless @string val
true
undefined: (v) ->
v is undefined
| 196681 | module.exports =
# type
# ====
get: (v) -> # :string | void
for own key of @
continue if key is 'get'
continue if key is '<KEY>Array' # TODO
return key if @[key] v
console.log new Error("type not in lib: #{v}").message.warn
undefined
# types (all return :boolean)
# =====
array: (v) ->
Array.isArray v
boolean: (v) ->
typeof v is 'boolean'
error: (v) ->
v instanceof Error
function: (v) ->
typeof v is 'function'
int: (v) ->
return false unless @number v
v % 1 is 0
null: (v) ->
v is null
number: (v) ->
return false if @null v
return false if @array v
return false if @string v
return false if @boolean v
not isNaN v
object: (v) ->
return false if typeof v isnt 'object'
return false if v is null
return false if @array v
true
string: (v) ->
typeof v is 'string'
stringArray: (v) -> # v should be an array of strings
return false unless @array v
for val in v
return false unless @string val
true
undefined: (v) ->
v is undefined
| true | module.exports =
# type
# ====
get: (v) -> # :string | void
for own key of @
continue if key is 'get'
continue if key is 'PI:KEY:<KEY>END_PIArray' # TODO
return key if @[key] v
console.log new Error("type not in lib: #{v}").message.warn
undefined
# types (all return :boolean)
# =====
array: (v) ->
Array.isArray v
boolean: (v) ->
typeof v is 'boolean'
error: (v) ->
v instanceof Error
function: (v) ->
typeof v is 'function'
int: (v) ->
return false unless @number v
v % 1 is 0
null: (v) ->
v is null
number: (v) ->
return false if @null v
return false if @array v
return false if @string v
return false if @boolean v
not isNaN v
object: (v) ->
return false if typeof v isnt 'object'
return false if v is null
return false if @array v
true
string: (v) ->
typeof v is 'string'
stringArray: (v) -> # v should be an array of strings
return false unless @array v
for val in v
return false unless @string val
true
undefined: (v) ->
v is undefined
|
[
{
"context": "port:\"1234\"\n\t\t\t\t\thost:\"somewhere\"\n\t\t\t\t\tpassword: \"password\"\n\t\t@rclient =\n\t\t\tincr: sinon.stub()\n\t\t\tget: sinon",
"end": 375,
"score": 0.9994921088218689,
"start": 367,
"tag": "PASSWORD",
"value": "password"
}
] | test/UnitTests/coffee/infrastructure/RateLimterTests.coffee | HasanSanli/web-sharelatex | 0 | assert = require("chai").assert
sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/infrastructure/RateLimiter.js"
SandboxedModule = require('sandboxed-module')
describe "RateLimiter", ->
beforeEach ->
@settings =
redis:
web:
port:"1234"
host:"somewhere"
password: "password"
@rclient =
incr: sinon.stub()
get: sinon.stub()
expire: sinon.stub()
exec: sinon.stub()
@rclient.multi = sinon.stub().returns(@rclient)
@RedisWrapper =
client: sinon.stub().returns(@rclient)
@limiterFn = sinon.stub()
@RollingRateLimiter = (opts) =>
return @limiterFn
@limiter = SandboxedModule.require modulePath, requires:
"rolling-rate-limiter": @RollingRateLimiter
"settings-sharelatex":@settings
"logger-sharelatex" : @logger = {log:sinon.stub(), err:sinon.stub()}
"./RedisWrapper": @RedisWrapper
@endpointName = "compiles"
@subject = "some-project-id"
@timeInterval = 20
@throttleLimit = 5
@details =
endpointName: @endpointName
subjectName: @subject
throttle: @throttleLimit
timeInterval: @timeInterval
@key = "RateLimiter:#{@endpointName}:{#{@subject}}"
describe 'when action is permitted', ->
beforeEach ->
@limiterFn = sinon.stub().callsArgWith(1, null, 0, 22)
it 'should not produce and error', (done) ->
@limiter.addCount {}, (err, should) ->
expect(err).to.equal null
done()
it 'should callback with true', (done) ->
@limiter.addCount {}, (err, should) ->
expect(should).to.equal true
done()
describe 'when action is not permitted', ->
beforeEach ->
@limiterFn = sinon.stub().callsArgWith(1, null, 4000, 0)
it 'should not produce and error', (done) ->
@limiter.addCount {}, (err, should) ->
expect(err).to.equal null
done()
it 'should callback with false', (done) ->
@limiter.addCount {}, (err, should) ->
expect(should).to.equal false
done()
describe 'when limiter produces an error', ->
beforeEach ->
@limiterFn = sinon.stub().callsArgWith(1, new Error('woops'))
it 'should produce and error', (done) ->
@limiter.addCount {}, (err, should) ->
expect(err).to.not.equal null
expect(err).to.be.instanceof Error
done()
| 194647 | assert = require("chai").assert
sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/infrastructure/RateLimiter.js"
SandboxedModule = require('sandboxed-module')
describe "RateLimiter", ->
beforeEach ->
@settings =
redis:
web:
port:"1234"
host:"somewhere"
password: "<PASSWORD>"
@rclient =
incr: sinon.stub()
get: sinon.stub()
expire: sinon.stub()
exec: sinon.stub()
@rclient.multi = sinon.stub().returns(@rclient)
@RedisWrapper =
client: sinon.stub().returns(@rclient)
@limiterFn = sinon.stub()
@RollingRateLimiter = (opts) =>
return @limiterFn
@limiter = SandboxedModule.require modulePath, requires:
"rolling-rate-limiter": @RollingRateLimiter
"settings-sharelatex":@settings
"logger-sharelatex" : @logger = {log:sinon.stub(), err:sinon.stub()}
"./RedisWrapper": @RedisWrapper
@endpointName = "compiles"
@subject = "some-project-id"
@timeInterval = 20
@throttleLimit = 5
@details =
endpointName: @endpointName
subjectName: @subject
throttle: @throttleLimit
timeInterval: @timeInterval
@key = "RateLimiter:#{@endpointName}:{#{@subject}}"
describe 'when action is permitted', ->
beforeEach ->
@limiterFn = sinon.stub().callsArgWith(1, null, 0, 22)
it 'should not produce and error', (done) ->
@limiter.addCount {}, (err, should) ->
expect(err).to.equal null
done()
it 'should callback with true', (done) ->
@limiter.addCount {}, (err, should) ->
expect(should).to.equal true
done()
describe 'when action is not permitted', ->
beforeEach ->
@limiterFn = sinon.stub().callsArgWith(1, null, 4000, 0)
it 'should not produce and error', (done) ->
@limiter.addCount {}, (err, should) ->
expect(err).to.equal null
done()
it 'should callback with false', (done) ->
@limiter.addCount {}, (err, should) ->
expect(should).to.equal false
done()
describe 'when limiter produces an error', ->
beforeEach ->
@limiterFn = sinon.stub().callsArgWith(1, new Error('woops'))
it 'should produce and error', (done) ->
@limiter.addCount {}, (err, should) ->
expect(err).to.not.equal null
expect(err).to.be.instanceof Error
done()
| true | assert = require("chai").assert
sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/infrastructure/RateLimiter.js"
SandboxedModule = require('sandboxed-module')
describe "RateLimiter", ->
beforeEach ->
@settings =
redis:
web:
port:"1234"
host:"somewhere"
password: "PI:PASSWORD:<PASSWORD>END_PI"
@rclient =
incr: sinon.stub()
get: sinon.stub()
expire: sinon.stub()
exec: sinon.stub()
@rclient.multi = sinon.stub().returns(@rclient)
@RedisWrapper =
client: sinon.stub().returns(@rclient)
@limiterFn = sinon.stub()
@RollingRateLimiter = (opts) =>
return @limiterFn
@limiter = SandboxedModule.require modulePath, requires:
"rolling-rate-limiter": @RollingRateLimiter
"settings-sharelatex":@settings
"logger-sharelatex" : @logger = {log:sinon.stub(), err:sinon.stub()}
"./RedisWrapper": @RedisWrapper
@endpointName = "compiles"
@subject = "some-project-id"
@timeInterval = 20
@throttleLimit = 5
@details =
endpointName: @endpointName
subjectName: @subject
throttle: @throttleLimit
timeInterval: @timeInterval
@key = "RateLimiter:#{@endpointName}:{#{@subject}}"
describe 'when action is permitted', ->
beforeEach ->
@limiterFn = sinon.stub().callsArgWith(1, null, 0, 22)
it 'should not produce and error', (done) ->
@limiter.addCount {}, (err, should) ->
expect(err).to.equal null
done()
it 'should callback with true', (done) ->
@limiter.addCount {}, (err, should) ->
expect(should).to.equal true
done()
describe 'when action is not permitted', ->
beforeEach ->
@limiterFn = sinon.stub().callsArgWith(1, null, 4000, 0)
it 'should not produce and error', (done) ->
@limiter.addCount {}, (err, should) ->
expect(err).to.equal null
done()
it 'should callback with false', (done) ->
@limiter.addCount {}, (err, should) ->
expect(should).to.equal false
done()
describe 'when limiter produces an error', ->
beforeEach ->
@limiterFn = sinon.stub().callsArgWith(1, new Error('woops'))
it 'should produce and error', (done) ->
@limiter.addCount {}, (err, should) ->
expect(err).to.not.equal null
expect(err).to.be.instanceof Error
done()
|
[
{
"context": " rounds: @draftEdit.draft_rounds\n password: @draftEdit.draft_password\n using_depth_charts: @draftEdit.using_depth_",
"end": 4497,
"score": 0.9987133145332336,
"start": 4472,
"tag": "PASSWORD",
"value": "@draftEdit.draft_password"
}
] | app/coffee/controllers/commish/draft_edit.coffee | justinpyvis/phpdraft | 0 | class DraftEditController extends BaseController
@register 'DraftEditController'
@inject '$scope',
'$loading',
'subscriptionKeys',
'workingModalService',
'api',
'messageService',
'depthChartPositionService'
initialize: ->
@draftEdit =
using_depth_charts: false
depthChartPositions: []
@depthChartPositionIndex = -1
@draftLoading = true
@draftLoaded = false
@sportChangeListenerRegistered = false
@draftError = false
@deregister = @$scope.$on @subscriptionKeys.loadDraftDependentData, (event, args) =>
if args.draft? and args.draft.setting_up == true
#Ensure we only get draft data once, assumption is that there's only 1 person editing it at a given time
if not @draftLoaded
@deregister()
@_loadCommishDraft(args.draft.draft_id)
else if args.draft? and (args.draft.in_progress == true || args.draft.complete == true)
@messageService.showWarning "Unable to edit draft: draft has already started or has completed"
@deregister()
@sendToPreviousPath()
@draftError = true
@$scope.$on @subscriptionKeys.scopeDestroy, (event, args) =>
@deregister()
# The change of the initial data causes issues, so we only listen for these once the draft has been loaded.
_bindDraftSpecificListeners: ->
@$scope.$watch =>
@draftEdit.depthChartPositions
, =>
@hasNonstandardPositions = @depthChartPositionService.calculateRoundsFromPositions(@draftEdit)
@depthChartsUnique = @depthChartPositionService.getDepthChartPositionValidity(@draftEdit)
, true
@$scope.$watch =>
@draftEdit.using_depth_charts
, =>
@hasNonstandardPositions = @depthChartPositionService.calculateRoundsFromPositions(@draftEdit)
@depthChartsUnique = @depthChartPositionService.getDepthChartPositionValidity(@draftEdit)
if @draftEdit.using_depth_charts and @sportChangeListenerRegistered and @draftEdit.depthChartPositions.length == 0
@sportChanged()
@$scope.$watch 'draftEditCtrl.draftEdit.draft_sport', =>
@sportChanged()
@$scope.$watch 'draftEditCtrl.depthChartPositionIndex', =>
@deleteDepthChartPosition()
_loadCommishDraft: (draft_id) ->
@draftLoaded = true
draftInitializeSuccess = (data) =>
angular.merge(@draftEdit, data)
@draftLoading = false
@_bindDraftSpecificListeners()
draftInitializeErrorHandler = () =>
@draftLoading = false
@draftError = true
@messageService.showError "Unable to load draft"
@api.Draft.commishGet({ draft_id: draft_id }, draftInitializeSuccess, draftInitializeErrorHandler)
sportChanged: ->
positionsSuccess = (data) =>
positionResetCallback = =>
@$loading.finish('load_data')
@depthChartPositionService.createPositionsBySport(@draftEdit, data.positions, positionResetCallback)
positionsError = =>
@$loading.finish('load_data')
@messageService.showError "Unable to load positions for the given draft sport"
if @draftEdit?.draft_sport?.length == 0
return
#Angular triggers a change when the listenered is registered regardless, so we must ignore the first one ourselves:
if not @sportChangeListenerRegistered
@sportChangeListenerRegistered = true
return
@$loading.start('load_data')
@api.DepthChartPosition.getPositions {draft_sport: @draftEdit.draft_sport}, positionsSuccess, positionsError
editClicked: =>
if not @editFormIsInvalid()
@_edit()
addDepthChartPosition: ->
@depthChartPositionService.addDepthChartPosition(@draftEdit)
deleteDepthChartPosition: ->
if @editInProgress or @depthChartPositionIndex is -1
return
@depthChartPositionService.deleteDepthChartPosition(@draftEdit, @depthChartPositionIndex)
@hasNonstandardPositions = @depthChartPositionService.calculateRoundsFromPositions(@draftEdit)
@depthChartsUnique = @depthChartPositionService.getDepthChartPositionValidity(@draftEdit)
editFormIsInvalid: =>
if @editInProgress or not @form.$valid
return true
if @draftEdit.using_depth_charts
return not @depthChartsUnique
else
return false
_edit: =>
@workingModalService.openModal()
editModel =
draft_id: @draftEdit.draft_id
name: @draftEdit.draft_name
sport: @draftEdit.draft_sport
style: @draftEdit.draft_style
rounds: @draftEdit.draft_rounds
password: @draftEdit.draft_password
using_depth_charts: @draftEdit.using_depth_charts
depthChartPositions: @draftEdit.depthChartPositions
@editInProgress = true
@messageService.closeToasts()
editSuccessHandler = (response) =>
@editInProgress = false
@workingModalService.closeModal()
@form.$setPristine()
@messageService.showSuccess "#{response.draft.draft_name} edited!"
@$location.path "/draft/#{@draftEdit.draft_id}"
editFailureHandler = (response) =>
@editInProgress = false
@workingModalService.closeModal()
if response?.status is 400
registerError = response.data?.errors?.join('\n')
else
registerError = "Whoops! We hit a snag - looks like it's on our end (#{response.data.status})"
@messageService.showError "#{registerError}", 'Unable to edit draft'
@api.Draft.update(editModel, editSuccessHandler, editFailureHandler)
| 106301 | class DraftEditController extends BaseController
@register 'DraftEditController'
@inject '$scope',
'$loading',
'subscriptionKeys',
'workingModalService',
'api',
'messageService',
'depthChartPositionService'
initialize: ->
@draftEdit =
using_depth_charts: false
depthChartPositions: []
@depthChartPositionIndex = -1
@draftLoading = true
@draftLoaded = false
@sportChangeListenerRegistered = false
@draftError = false
@deregister = @$scope.$on @subscriptionKeys.loadDraftDependentData, (event, args) =>
if args.draft? and args.draft.setting_up == true
#Ensure we only get draft data once, assumption is that there's only 1 person editing it at a given time
if not @draftLoaded
@deregister()
@_loadCommishDraft(args.draft.draft_id)
else if args.draft? and (args.draft.in_progress == true || args.draft.complete == true)
@messageService.showWarning "Unable to edit draft: draft has already started or has completed"
@deregister()
@sendToPreviousPath()
@draftError = true
@$scope.$on @subscriptionKeys.scopeDestroy, (event, args) =>
@deregister()
# The change of the initial data causes issues, so we only listen for these once the draft has been loaded.
_bindDraftSpecificListeners: ->
@$scope.$watch =>
@draftEdit.depthChartPositions
, =>
@hasNonstandardPositions = @depthChartPositionService.calculateRoundsFromPositions(@draftEdit)
@depthChartsUnique = @depthChartPositionService.getDepthChartPositionValidity(@draftEdit)
, true
@$scope.$watch =>
@draftEdit.using_depth_charts
, =>
@hasNonstandardPositions = @depthChartPositionService.calculateRoundsFromPositions(@draftEdit)
@depthChartsUnique = @depthChartPositionService.getDepthChartPositionValidity(@draftEdit)
if @draftEdit.using_depth_charts and @sportChangeListenerRegistered and @draftEdit.depthChartPositions.length == 0
@sportChanged()
@$scope.$watch 'draftEditCtrl.draftEdit.draft_sport', =>
@sportChanged()
@$scope.$watch 'draftEditCtrl.depthChartPositionIndex', =>
@deleteDepthChartPosition()
_loadCommishDraft: (draft_id) ->
@draftLoaded = true
draftInitializeSuccess = (data) =>
angular.merge(@draftEdit, data)
@draftLoading = false
@_bindDraftSpecificListeners()
draftInitializeErrorHandler = () =>
@draftLoading = false
@draftError = true
@messageService.showError "Unable to load draft"
@api.Draft.commishGet({ draft_id: draft_id }, draftInitializeSuccess, draftInitializeErrorHandler)
sportChanged: ->
positionsSuccess = (data) =>
positionResetCallback = =>
@$loading.finish('load_data')
@depthChartPositionService.createPositionsBySport(@draftEdit, data.positions, positionResetCallback)
positionsError = =>
@$loading.finish('load_data')
@messageService.showError "Unable to load positions for the given draft sport"
if @draftEdit?.draft_sport?.length == 0
return
#Angular triggers a change when the listenered is registered regardless, so we must ignore the first one ourselves:
if not @sportChangeListenerRegistered
@sportChangeListenerRegistered = true
return
@$loading.start('load_data')
@api.DepthChartPosition.getPositions {draft_sport: @draftEdit.draft_sport}, positionsSuccess, positionsError
editClicked: =>
if not @editFormIsInvalid()
@_edit()
addDepthChartPosition: ->
@depthChartPositionService.addDepthChartPosition(@draftEdit)
deleteDepthChartPosition: ->
if @editInProgress or @depthChartPositionIndex is -1
return
@depthChartPositionService.deleteDepthChartPosition(@draftEdit, @depthChartPositionIndex)
@hasNonstandardPositions = @depthChartPositionService.calculateRoundsFromPositions(@draftEdit)
@depthChartsUnique = @depthChartPositionService.getDepthChartPositionValidity(@draftEdit)
editFormIsInvalid: =>
if @editInProgress or not @form.$valid
return true
if @draftEdit.using_depth_charts
return not @depthChartsUnique
else
return false
_edit: =>
@workingModalService.openModal()
editModel =
draft_id: @draftEdit.draft_id
name: @draftEdit.draft_name
sport: @draftEdit.draft_sport
style: @draftEdit.draft_style
rounds: @draftEdit.draft_rounds
password: <PASSWORD>
using_depth_charts: @draftEdit.using_depth_charts
depthChartPositions: @draftEdit.depthChartPositions
@editInProgress = true
@messageService.closeToasts()
editSuccessHandler = (response) =>
@editInProgress = false
@workingModalService.closeModal()
@form.$setPristine()
@messageService.showSuccess "#{response.draft.draft_name} edited!"
@$location.path "/draft/#{@draftEdit.draft_id}"
editFailureHandler = (response) =>
@editInProgress = false
@workingModalService.closeModal()
if response?.status is 400
registerError = response.data?.errors?.join('\n')
else
registerError = "Whoops! We hit a snag - looks like it's on our end (#{response.data.status})"
@messageService.showError "#{registerError}", 'Unable to edit draft'
@api.Draft.update(editModel, editSuccessHandler, editFailureHandler)
| true | class DraftEditController extends BaseController
@register 'DraftEditController'
@inject '$scope',
'$loading',
'subscriptionKeys',
'workingModalService',
'api',
'messageService',
'depthChartPositionService'
initialize: ->
@draftEdit =
using_depth_charts: false
depthChartPositions: []
@depthChartPositionIndex = -1
@draftLoading = true
@draftLoaded = false
@sportChangeListenerRegistered = false
@draftError = false
@deregister = @$scope.$on @subscriptionKeys.loadDraftDependentData, (event, args) =>
if args.draft? and args.draft.setting_up == true
#Ensure we only get draft data once, assumption is that there's only 1 person editing it at a given time
if not @draftLoaded
@deregister()
@_loadCommishDraft(args.draft.draft_id)
else if args.draft? and (args.draft.in_progress == true || args.draft.complete == true)
@messageService.showWarning "Unable to edit draft: draft has already started or has completed"
@deregister()
@sendToPreviousPath()
@draftError = true
@$scope.$on @subscriptionKeys.scopeDestroy, (event, args) =>
@deregister()
# The change of the initial data causes issues, so we only listen for these once the draft has been loaded.
_bindDraftSpecificListeners: ->
@$scope.$watch =>
@draftEdit.depthChartPositions
, =>
@hasNonstandardPositions = @depthChartPositionService.calculateRoundsFromPositions(@draftEdit)
@depthChartsUnique = @depthChartPositionService.getDepthChartPositionValidity(@draftEdit)
, true
@$scope.$watch =>
@draftEdit.using_depth_charts
, =>
@hasNonstandardPositions = @depthChartPositionService.calculateRoundsFromPositions(@draftEdit)
@depthChartsUnique = @depthChartPositionService.getDepthChartPositionValidity(@draftEdit)
if @draftEdit.using_depth_charts and @sportChangeListenerRegistered and @draftEdit.depthChartPositions.length == 0
@sportChanged()
@$scope.$watch 'draftEditCtrl.draftEdit.draft_sport', =>
@sportChanged()
@$scope.$watch 'draftEditCtrl.depthChartPositionIndex', =>
@deleteDepthChartPosition()
_loadCommishDraft: (draft_id) ->
@draftLoaded = true
draftInitializeSuccess = (data) =>
angular.merge(@draftEdit, data)
@draftLoading = false
@_bindDraftSpecificListeners()
draftInitializeErrorHandler = () =>
@draftLoading = false
@draftError = true
@messageService.showError "Unable to load draft"
@api.Draft.commishGet({ draft_id: draft_id }, draftInitializeSuccess, draftInitializeErrorHandler)
sportChanged: ->
positionsSuccess = (data) =>
positionResetCallback = =>
@$loading.finish('load_data')
@depthChartPositionService.createPositionsBySport(@draftEdit, data.positions, positionResetCallback)
positionsError = =>
@$loading.finish('load_data')
@messageService.showError "Unable to load positions for the given draft sport"
if @draftEdit?.draft_sport?.length == 0
return
#Angular triggers a change when the listenered is registered regardless, so we must ignore the first one ourselves:
if not @sportChangeListenerRegistered
@sportChangeListenerRegistered = true
return
@$loading.start('load_data')
@api.DepthChartPosition.getPositions {draft_sport: @draftEdit.draft_sport}, positionsSuccess, positionsError
editClicked: =>
if not @editFormIsInvalid()
@_edit()
addDepthChartPosition: ->
@depthChartPositionService.addDepthChartPosition(@draftEdit)
deleteDepthChartPosition: ->
if @editInProgress or @depthChartPositionIndex is -1
return
@depthChartPositionService.deleteDepthChartPosition(@draftEdit, @depthChartPositionIndex)
@hasNonstandardPositions = @depthChartPositionService.calculateRoundsFromPositions(@draftEdit)
@depthChartsUnique = @depthChartPositionService.getDepthChartPositionValidity(@draftEdit)
editFormIsInvalid: =>
if @editInProgress or not @form.$valid
return true
if @draftEdit.using_depth_charts
return not @depthChartsUnique
else
return false
_edit: =>
@workingModalService.openModal()
editModel =
draft_id: @draftEdit.draft_id
name: @draftEdit.draft_name
sport: @draftEdit.draft_sport
style: @draftEdit.draft_style
rounds: @draftEdit.draft_rounds
password: PI:PASSWORD:<PASSWORD>END_PI
using_depth_charts: @draftEdit.using_depth_charts
depthChartPositions: @draftEdit.depthChartPositions
@editInProgress = true
@messageService.closeToasts()
editSuccessHandler = (response) =>
@editInProgress = false
@workingModalService.closeModal()
@form.$setPristine()
@messageService.showSuccess "#{response.draft.draft_name} edited!"
@$location.path "/draft/#{@draftEdit.draft_id}"
editFailureHandler = (response) =>
@editInProgress = false
@workingModalService.closeModal()
if response?.status is 400
registerError = response.data?.errors?.join('\n')
else
registerError = "Whoops! We hit a snag - looks like it's on our end (#{response.data.status})"
@messageService.showError "#{registerError}", 'Unable to edit draft'
@api.Draft.update(editModel, editSuccessHandler, editFailureHandler)
|
[
{
"context": "alt\": \"'#{salt}'\"\n\n \"gitcrypt.pass\": \"'#{pass}'\"\n\n \"gitcrypt.cipher\": \"'#{cipher}'\"\n\n ",
"end": 6477,
"score": 0.7101157903671265,
"start": 6477,
"tag": "PASSWORD",
"value": ""
}
] | lib/main.coffee | joaoafrmartins/spaghetty-gitcrypt | 0 | async = require 'async'
{ EOL } = require 'os'
{ resolve } = require 'path'
stash = require 'png-stash'
ACliCommand = require 'a-cli-command'
class Gitcrypt extends ACliCommand
command:
name: "gitcrypt"
options:
salt:
type: "string"
description: [
"the salt used for encrypting",
"the repository"
]
pass:
type: "string"
description: [
"the encryption password"
]
cipher:
type: "string"
default: "aes-256-ecb"
description: [
"the cipher type used by openssl"
]
doodle:
type: "string"
description: [
"save a configuration object",
"inside a '.png' using lsb",
"steganography"
]
templates:
type: "array"
default: ["package-init-readme"]
description: [
"calls package-init in order",
"to force the creation of a",
"README.md and a doodle.png",
"file used for saving the",
"configuration for seamless",
"decryption"
]
force:
type: "boolean"
description: [
"defines whether or not",
"the command should be called",
"in interactive mode"
]
extensions:
type: "array"
default: ["*.coffee", "*.json", "*.cson", "*.js", "*.less", "*.css", "*.html", "*.hbs"]
description: [
"an array of files extensions wich",
"should be marked for encryption"
]
gitattributes:
type: "string"
default: ".git/info/attributes"
description: [
"the gitattributes file location",
"defaults to '.git/info/attributes'",
"but can also be specified as a",
"'.gitattributes' file"
]
gitconfig:
type: "boolean"
description: [
"configure git repository",
"for seamless encryption and",
"descryption"
]
commit:
type: "boolean"
description: [
"specifies if the repository",
"should be pushed after configuration"
]
encrypt:
type: "boolean"
triggers: ["salt", "pass", "cipher", "templates", "extensions", "doodle", "gitattributes", "gitconfig"]
description: [
"encrypt a git repository",
"using openssl"
]
decrypt:
type: "boolean"
triggers: ["doodle", "gitattributes", "gitconfig"]
description: [
"reset repository head",
"in order to decrypt files"
]
"salt?": (command, next) ->
@shell
if not test "-d", resolve ".git"
return next "error: not a git repository", null
{ salt } = command.args
if salt then return next null, "salt: #{salt}"
md5 = "$(which md5 2>/dev/null || which md5sum 2>/dev/null)"
bin = "head -c 10 < /dev/random | #{md5} | cut -c-16"
@exec
bin: bin
silent: true
, (err, salt) ->
salt = salt.replace /\n$/, ''
if err then return next "error generating salt: #{err}"
command.args.salt = salt
next null, "salt: #{salt}"
"pass?": (command, next) ->
{ pass } = command.args
if pass then return next null, "pass: #{pass}"
chars = "!@#$%^&*()_A-Z-a-z-0-9"
bin = "cat /dev/urandom | LC_ALL='C' tr -dc '#{chars}' | head -c32"
@exec
bin: bin
silent: true
, (err, pass) ->
pass = pass.replace /\n$/, ''
if err then return next "error generating pass: #{err}"
command.args.pass = pass
next null, "pass: #{pass}"
"templates?": (command, next) ->
@shell
{ templates, force, doodle } = command.args
if not templates then return next "error generating doodle: #{doodle}", null
args = ["init", "--templates", JSON.stringify templates]
if force then args.push "--force"
@cli.run args, next
"doodle?": (command, next) ->
@shell
doodletemplate = resolve pwd(), 'doodle.png'
if doodle
doodle = resolve doodle
if not test "-e", doodle
mv doodletemplate, doodle
else if not doodle then doodle = doodletemplate
if test "-e", doodle
command.args.doodle = doodle
else return next "error doodle: #{doodle}"
{ encrypt, decrypt, doodle } = command.args
if encrypt
{ extensions, salt, pass, cipher } = command.args
stash doodle, (err, payload) ->
if err then return next "error reading doodle: #{err}"
data = JSON.stringify
salt: salt
pass: pass
cipher: cipher
extensions: extensions
data = "#{data.length}#{data}"
payload.write data
payload.save (err) ->
if err then return next "error saving doodle: payload #{err}", null
next null, "payload: #{data}"
else if decrypt
stash doodle, (err, payload) ->
try
length = payload.read 0, 3
data = payload.read(3, Number(length.toString())).toString()
data = JSON.parse data
for k, v of data then command.args[k] = v
return next null, "payload: #{data}"
catch err then return next err, null
else return next "error configuring doodle data: #{doodle}", null
"gitconfig?": (command, next) ->
@shell
if not test "-d", resolve ".git"
return next "error: not a git repository", null
{ extensions, salt, pass, cipher, gitattributes, commit } = command.args
gitattributes = resolve gitattributes
data = [""]
for extension in extensions
data.push "#{extension} filter=encrypt diff=encrypt"
data.push "[merge]"
data.push "\trenormalize=true"
if test "-f", gitattributes
if contents = cat(gitattributes)
data.unshift contents
data.push ""
data = data.join EOL
data.to gitattributes
_salt = "$(git config gitcrypt.salt)"
_pass = "$(git config gitcrypt.pass)"
_cipher = "$(git config gitcrypt.cipher)"
clean = "openssl enc -base64 -#{_cipher} -S #{_salt} -k #{_pass}"
smudge = "openssl enc -d -base64 -#{_cipher} -k #{_pass} 2> /dev/null || cat"
diff = "openssl enc -d -base64 -$CIPHER -k #{_pass} -in $1 2> /dev/null || cat $1"
config =
"gitcrypt.salt": "'#{salt}'"
"gitcrypt.pass": "'#{pass}'"
"gitcrypt.cipher": "'#{cipher}'"
"filter.encrypt.smudge": "'#{smudge}'"
"filter.encrypt.clean": "'#{clean}'"
"diff.encrypt.textconv": "'#{diff}'"
series = []
Object.keys(config).map (name) =>
value = config[name]
series.push (done) =>
@exec
bin: "git config --add #{name} #{value}"
silent: true
, (err, res) =>
if err then return done err, null
done null, res
return async.series series, next
"execute?": (command, next) ->
@shell
if not test "-d", resolve ".git"
return next "error: not a git repository", null
{ encrypt, decrypt } = command.args
if encrypt
{ commit } = command.args
if commit
series = []
series.push (done) =>
@exec
bin: "git add .",
, (err, res) =>
if err then return done err, null
done null, res
series.push (done) =>
@exec
bin: "git commit -am 'R.I.P.'",
, (err, res) =>
if err then return done err, null
done null, res
series.push (done) =>
@exec
bin: "git push origin master",
, (err, res) =>
if err then return done err, null
done null, res
return async.series series, next
else if decrypt
bin = "git reset --hard HEAD"
@exec bin, (err, res) ->
if err then return next err, null
next null, res
else return next "error configuring gitcrypt", null
module.exports = Gitcrypt
| 116331 | async = require 'async'
{ EOL } = require 'os'
{ resolve } = require 'path'
stash = require 'png-stash'
ACliCommand = require 'a-cli-command'
class Gitcrypt extends ACliCommand
command:
name: "gitcrypt"
options:
salt:
type: "string"
description: [
"the salt used for encrypting",
"the repository"
]
pass:
type: "string"
description: [
"the encryption password"
]
cipher:
type: "string"
default: "aes-256-ecb"
description: [
"the cipher type used by openssl"
]
doodle:
type: "string"
description: [
"save a configuration object",
"inside a '.png' using lsb",
"steganography"
]
templates:
type: "array"
default: ["package-init-readme"]
description: [
"calls package-init in order",
"to force the creation of a",
"README.md and a doodle.png",
"file used for saving the",
"configuration for seamless",
"decryption"
]
force:
type: "boolean"
description: [
"defines whether or not",
"the command should be called",
"in interactive mode"
]
extensions:
type: "array"
default: ["*.coffee", "*.json", "*.cson", "*.js", "*.less", "*.css", "*.html", "*.hbs"]
description: [
"an array of files extensions wich",
"should be marked for encryption"
]
gitattributes:
type: "string"
default: ".git/info/attributes"
description: [
"the gitattributes file location",
"defaults to '.git/info/attributes'",
"but can also be specified as a",
"'.gitattributes' file"
]
gitconfig:
type: "boolean"
description: [
"configure git repository",
"for seamless encryption and",
"descryption"
]
commit:
type: "boolean"
description: [
"specifies if the repository",
"should be pushed after configuration"
]
encrypt:
type: "boolean"
triggers: ["salt", "pass", "cipher", "templates", "extensions", "doodle", "gitattributes", "gitconfig"]
description: [
"encrypt a git repository",
"using openssl"
]
decrypt:
type: "boolean"
triggers: ["doodle", "gitattributes", "gitconfig"]
description: [
"reset repository head",
"in order to decrypt files"
]
"salt?": (command, next) ->
@shell
if not test "-d", resolve ".git"
return next "error: not a git repository", null
{ salt } = command.args
if salt then return next null, "salt: #{salt}"
md5 = "$(which md5 2>/dev/null || which md5sum 2>/dev/null)"
bin = "head -c 10 < /dev/random | #{md5} | cut -c-16"
@exec
bin: bin
silent: true
, (err, salt) ->
salt = salt.replace /\n$/, ''
if err then return next "error generating salt: #{err}"
command.args.salt = salt
next null, "salt: #{salt}"
"pass?": (command, next) ->
{ pass } = command.args
if pass then return next null, "pass: #{pass}"
chars = "!@#$%^&*()_A-Z-a-z-0-9"
bin = "cat /dev/urandom | LC_ALL='C' tr -dc '#{chars}' | head -c32"
@exec
bin: bin
silent: true
, (err, pass) ->
pass = pass.replace /\n$/, ''
if err then return next "error generating pass: #{err}"
command.args.pass = pass
next null, "pass: #{pass}"
"templates?": (command, next) ->
@shell
{ templates, force, doodle } = command.args
if not templates then return next "error generating doodle: #{doodle}", null
args = ["init", "--templates", JSON.stringify templates]
if force then args.push "--force"
@cli.run args, next
"doodle?": (command, next) ->
@shell
doodletemplate = resolve pwd(), 'doodle.png'
if doodle
doodle = resolve doodle
if not test "-e", doodle
mv doodletemplate, doodle
else if not doodle then doodle = doodletemplate
if test "-e", doodle
command.args.doodle = doodle
else return next "error doodle: #{doodle}"
{ encrypt, decrypt, doodle } = command.args
if encrypt
{ extensions, salt, pass, cipher } = command.args
stash doodle, (err, payload) ->
if err then return next "error reading doodle: #{err}"
data = JSON.stringify
salt: salt
pass: pass
cipher: cipher
extensions: extensions
data = "#{data.length}#{data}"
payload.write data
payload.save (err) ->
if err then return next "error saving doodle: payload #{err}", null
next null, "payload: #{data}"
else if decrypt
stash doodle, (err, payload) ->
try
length = payload.read 0, 3
data = payload.read(3, Number(length.toString())).toString()
data = JSON.parse data
for k, v of data then command.args[k] = v
return next null, "payload: #{data}"
catch err then return next err, null
else return next "error configuring doodle data: #{doodle}", null
"gitconfig?": (command, next) ->
@shell
if not test "-d", resolve ".git"
return next "error: not a git repository", null
{ extensions, salt, pass, cipher, gitattributes, commit } = command.args
gitattributes = resolve gitattributes
data = [""]
for extension in extensions
data.push "#{extension} filter=encrypt diff=encrypt"
data.push "[merge]"
data.push "\trenormalize=true"
if test "-f", gitattributes
if contents = cat(gitattributes)
data.unshift contents
data.push ""
data = data.join EOL
data.to gitattributes
_salt = "$(git config gitcrypt.salt)"
_pass = "$(git config gitcrypt.pass)"
_cipher = "$(git config gitcrypt.cipher)"
clean = "openssl enc -base64 -#{_cipher} -S #{_salt} -k #{_pass}"
smudge = "openssl enc -d -base64 -#{_cipher} -k #{_pass} 2> /dev/null || cat"
diff = "openssl enc -d -base64 -$CIPHER -k #{_pass} -in $1 2> /dev/null || cat $1"
config =
"gitcrypt.salt": "'#{salt}'"
"gitcrypt.pass": "'#{pass<PASSWORD>}'"
"gitcrypt.cipher": "'#{cipher}'"
"filter.encrypt.smudge": "'#{smudge}'"
"filter.encrypt.clean": "'#{clean}'"
"diff.encrypt.textconv": "'#{diff}'"
series = []
Object.keys(config).map (name) =>
value = config[name]
series.push (done) =>
@exec
bin: "git config --add #{name} #{value}"
silent: true
, (err, res) =>
if err then return done err, null
done null, res
return async.series series, next
"execute?": (command, next) ->
@shell
if not test "-d", resolve ".git"
return next "error: not a git repository", null
{ encrypt, decrypt } = command.args
if encrypt
{ commit } = command.args
if commit
series = []
series.push (done) =>
@exec
bin: "git add .",
, (err, res) =>
if err then return done err, null
done null, res
series.push (done) =>
@exec
bin: "git commit -am 'R.I.P.'",
, (err, res) =>
if err then return done err, null
done null, res
series.push (done) =>
@exec
bin: "git push origin master",
, (err, res) =>
if err then return done err, null
done null, res
return async.series series, next
else if decrypt
bin = "git reset --hard HEAD"
@exec bin, (err, res) ->
if err then return next err, null
next null, res
else return next "error configuring gitcrypt", null
module.exports = Gitcrypt
| true | async = require 'async'
{ EOL } = require 'os'
{ resolve } = require 'path'
stash = require 'png-stash'
ACliCommand = require 'a-cli-command'
class Gitcrypt extends ACliCommand
command:
name: "gitcrypt"
options:
salt:
type: "string"
description: [
"the salt used for encrypting",
"the repository"
]
pass:
type: "string"
description: [
"the encryption password"
]
cipher:
type: "string"
default: "aes-256-ecb"
description: [
"the cipher type used by openssl"
]
doodle:
type: "string"
description: [
"save a configuration object",
"inside a '.png' using lsb",
"steganography"
]
templates:
type: "array"
default: ["package-init-readme"]
description: [
"calls package-init in order",
"to force the creation of a",
"README.md and a doodle.png",
"file used for saving the",
"configuration for seamless",
"decryption"
]
force:
type: "boolean"
description: [
"defines whether or not",
"the command should be called",
"in interactive mode"
]
extensions:
type: "array"
default: ["*.coffee", "*.json", "*.cson", "*.js", "*.less", "*.css", "*.html", "*.hbs"]
description: [
"an array of files extensions wich",
"should be marked for encryption"
]
gitattributes:
type: "string"
default: ".git/info/attributes"
description: [
"the gitattributes file location",
"defaults to '.git/info/attributes'",
"but can also be specified as a",
"'.gitattributes' file"
]
gitconfig:
type: "boolean"
description: [
"configure git repository",
"for seamless encryption and",
"descryption"
]
commit:
type: "boolean"
description: [
"specifies if the repository",
"should be pushed after configuration"
]
encrypt:
type: "boolean"
triggers: ["salt", "pass", "cipher", "templates", "extensions", "doodle", "gitattributes", "gitconfig"]
description: [
"encrypt a git repository",
"using openssl"
]
decrypt:
type: "boolean"
triggers: ["doodle", "gitattributes", "gitconfig"]
description: [
"reset repository head",
"in order to decrypt files"
]
"salt?": (command, next) ->
@shell
if not test "-d", resolve ".git"
return next "error: not a git repository", null
{ salt } = command.args
if salt then return next null, "salt: #{salt}"
md5 = "$(which md5 2>/dev/null || which md5sum 2>/dev/null)"
bin = "head -c 10 < /dev/random | #{md5} | cut -c-16"
@exec
bin: bin
silent: true
, (err, salt) ->
salt = salt.replace /\n$/, ''
if err then return next "error generating salt: #{err}"
command.args.salt = salt
next null, "salt: #{salt}"
"pass?": (command, next) ->
{ pass } = command.args
if pass then return next null, "pass: #{pass}"
chars = "!@#$%^&*()_A-Z-a-z-0-9"
bin = "cat /dev/urandom | LC_ALL='C' tr -dc '#{chars}' | head -c32"
@exec
bin: bin
silent: true
, (err, pass) ->
pass = pass.replace /\n$/, ''
if err then return next "error generating pass: #{err}"
command.args.pass = pass
next null, "pass: #{pass}"
"templates?": (command, next) ->
@shell
{ templates, force, doodle } = command.args
if not templates then return next "error generating doodle: #{doodle}", null
args = ["init", "--templates", JSON.stringify templates]
if force then args.push "--force"
@cli.run args, next
"doodle?": (command, next) ->
@shell
doodletemplate = resolve pwd(), 'doodle.png'
if doodle
doodle = resolve doodle
if not test "-e", doodle
mv doodletemplate, doodle
else if not doodle then doodle = doodletemplate
if test "-e", doodle
command.args.doodle = doodle
else return next "error doodle: #{doodle}"
{ encrypt, decrypt, doodle } = command.args
if encrypt
{ extensions, salt, pass, cipher } = command.args
stash doodle, (err, payload) ->
if err then return next "error reading doodle: #{err}"
data = JSON.stringify
salt: salt
pass: pass
cipher: cipher
extensions: extensions
data = "#{data.length}#{data}"
payload.write data
payload.save (err) ->
if err then return next "error saving doodle: payload #{err}", null
next null, "payload: #{data}"
else if decrypt
stash doodle, (err, payload) ->
try
length = payload.read 0, 3
data = payload.read(3, Number(length.toString())).toString()
data = JSON.parse data
for k, v of data then command.args[k] = v
return next null, "payload: #{data}"
catch err then return next err, null
else return next "error configuring doodle data: #{doodle}", null
"gitconfig?": (command, next) ->
@shell
if not test "-d", resolve ".git"
return next "error: not a git repository", null
{ extensions, salt, pass, cipher, gitattributes, commit } = command.args
gitattributes = resolve gitattributes
data = [""]
for extension in extensions
data.push "#{extension} filter=encrypt diff=encrypt"
data.push "[merge]"
data.push "\trenormalize=true"
if test "-f", gitattributes
if contents = cat(gitattributes)
data.unshift contents
data.push ""
data = data.join EOL
data.to gitattributes
_salt = "$(git config gitcrypt.salt)"
_pass = "$(git config gitcrypt.pass)"
_cipher = "$(git config gitcrypt.cipher)"
clean = "openssl enc -base64 -#{_cipher} -S #{_salt} -k #{_pass}"
smudge = "openssl enc -d -base64 -#{_cipher} -k #{_pass} 2> /dev/null || cat"
diff = "openssl enc -d -base64 -$CIPHER -k #{_pass} -in $1 2> /dev/null || cat $1"
config =
"gitcrypt.salt": "'#{salt}'"
"gitcrypt.pass": "'#{passPI:PASSWORD:<PASSWORD>END_PI}'"
"gitcrypt.cipher": "'#{cipher}'"
"filter.encrypt.smudge": "'#{smudge}'"
"filter.encrypt.clean": "'#{clean}'"
"diff.encrypt.textconv": "'#{diff}'"
series = []
Object.keys(config).map (name) =>
value = config[name]
series.push (done) =>
@exec
bin: "git config --add #{name} #{value}"
silent: true
, (err, res) =>
if err then return done err, null
done null, res
return async.series series, next
"execute?": (command, next) ->
@shell
if not test "-d", resolve ".git"
return next "error: not a git repository", null
{ encrypt, decrypt } = command.args
if encrypt
{ commit } = command.args
if commit
series = []
series.push (done) =>
@exec
bin: "git add .",
, (err, res) =>
if err then return done err, null
done null, res
series.push (done) =>
@exec
bin: "git commit -am 'R.I.P.'",
, (err, res) =>
if err then return done err, null
done null, res
series.push (done) =>
@exec
bin: "git push origin master",
, (err, res) =>
if err then return done err, null
done null, res
return async.series series, next
else if decrypt
bin = "git reset --hard HEAD"
@exec bin, (err, res) ->
if err then return next err, null
next null, res
else return next "error configuring gitcrypt", null
module.exports = Gitcrypt
|
[
{
"context": "scopeName: 'source.coccinelle'\nname: 'Coccinelle'\ntype: 'tree-sitter'\nparser: 'tree-sitter-coccine",
"end": 48,
"score": 0.9997287392616272,
"start": 38,
"tag": "NAME",
"value": "Coccinelle"
}
] | grammars/coccinelle.cson | eugmes/language-coccinelle | 0 | scopeName: 'source.coccinelle'
name: 'Coccinelle'
type: 'tree-sitter'
parser: 'tree-sitter-coccinelle'
fileTypes: [
'cocci'
]
comments:
start: '// '
folds: [
{
type: 'comment'
}
{
type: 'changeset'
}
{
type: 'prolog'
}
]
scopes:
'comment': 'comment.block'
"""
include > "#include",
using > "using",
virtual > "virtual"
""": 'keyword.control.directive'
'virtual > pure_ident': 'constant.other'
"""
script_metavariables > "script",
script_metavariables > "initialize",
script_metavariables > "finalize",
""": 'keyword.control.directive'
'language': 'constant.other'
"""
metavariables > "@",
metavariables > "@@",
script_metavariables > "@",
script_metavariables > "@@",
""": 'keyword.control.other'
"""
"any",
"assignment",
"attribute",
"binary",
"comments",
"constant",
"declaration",
"declarer",
"depends",
"disable",
"error",
"ever",
"exists",
"expression",
"extends",
"field",
"file",
"finalize",
"forall",
"format",
"fresh",
"function",
"global",
"identifier",
"idexpression",
"in",
"initialiser",
"initialize",
"initializer",
"iterator",
"list",
"local",
"merge",
"metavariable",
"name",
"never",
"on",
"operator",
"parameter",
"position",
"script",
"statement",
"symbol",
"type",
"typedef",
"using",
"virtual",
"when"
""": 'keyword.control'
'"struct"': 'keyword.control'
'"enum"': 'keyword.control'
'"union"': 'keyword.control'
'"signed"': 'support.storage.type'
'"unsigned"': 'support.storage.type'
'"short"': 'support.storage.type'
'"long"': 'support.storage.type'
'"const"': 'storage.modifier'
'"volatile"': 'storage.modifier'
"""
"char",
"int",
"float",
"double",
"size_t",
"ssize_t",
"ptrdiff_t",
"decimal",
"typeof"
""": 'support.storage.type'
'";"': 'punctuation.terminator.statement'
'"["': 'punctuation.definition.begin.bracket.square'
'"]"': 'punctuation.definition.end.bracket.square'
'","': 'punctuation.separator.delimiter'
'"{"': 'punctuation.section.block.begin.bracket.curly'
'"}"': 'punctuation.section.block.end.bracket.curly'
'"("': 'punctuation.section.parens.begin.bracket.round'
'")"': 'punctuation.section.parens.end.bracket.round'
'"."': 'keyword.operator.member'
'"*"': 'keyword.operator'
'"-"': 'keyword.operator'
'"+"': 'keyword.operator'
'"/"': 'keyword.operator'
'"%"': 'keyword.operator'
'"++"': 'keyword.operator'
'"--"': 'keyword.operator'
'"=="': 'keyword.operator'
'"!"': 'keyword.operator'
'"!="': 'keyword.operator'
'"<"': 'keyword.operator'
'">"': 'keyword.operator'
'">="': 'keyword.operator'
'"<="': 'keyword.operator'
'"&&"': 'keyword.operator'
'"||"': 'keyword.operator'
'"&"': 'keyword.operator'
'"|"': 'keyword.operator'
'"^"': 'keyword.operator'
'"~"': 'keyword.operator'
'"<<"': 'keyword.operator'
'">>"': 'keyword.operator'
'"="': 'keyword.operator'
'"+="': 'keyword.operator'
'"-="': 'keyword.operator'
'"*="': 'keyword.operator'
'"/="': 'keyword.operator'
'"%="': 'keyword.operator'
'"<<="': 'keyword.operator'
'">>="': 'keyword.operator'
'"&="': 'keyword.operator'
'"^="': 'keyword.operator'
'"|="': 'keyword.operator'
'"?"': 'keyword.operator'
'":"': 'keyword.operator'
'"=~"': 'keyword.operator'
'"!~"': 'keyword.operator'
"""
"<?", ">?", ">?=", "<?="
""": 'keyword.operator'
'string': 'string.quoted.double'
'pathIsoFile': 'string.quoted.other'
'int': 'constant.numeric.decimal'
'rule_name': 'entity.name.function'
'pure_ident': 'variable.other'
| 118964 | scopeName: 'source.coccinelle'
name: '<NAME>'
type: 'tree-sitter'
parser: 'tree-sitter-coccinelle'
fileTypes: [
'cocci'
]
comments:
start: '// '
folds: [
{
type: 'comment'
}
{
type: 'changeset'
}
{
type: 'prolog'
}
]
scopes:
'comment': 'comment.block'
"""
include > "#include",
using > "using",
virtual > "virtual"
""": 'keyword.control.directive'
'virtual > pure_ident': 'constant.other'
"""
script_metavariables > "script",
script_metavariables > "initialize",
script_metavariables > "finalize",
""": 'keyword.control.directive'
'language': 'constant.other'
"""
metavariables > "@",
metavariables > "@@",
script_metavariables > "@",
script_metavariables > "@@",
""": 'keyword.control.other'
"""
"any",
"assignment",
"attribute",
"binary",
"comments",
"constant",
"declaration",
"declarer",
"depends",
"disable",
"error",
"ever",
"exists",
"expression",
"extends",
"field",
"file",
"finalize",
"forall",
"format",
"fresh",
"function",
"global",
"identifier",
"idexpression",
"in",
"initialiser",
"initialize",
"initializer",
"iterator",
"list",
"local",
"merge",
"metavariable",
"name",
"never",
"on",
"operator",
"parameter",
"position",
"script",
"statement",
"symbol",
"type",
"typedef",
"using",
"virtual",
"when"
""": 'keyword.control'
'"struct"': 'keyword.control'
'"enum"': 'keyword.control'
'"union"': 'keyword.control'
'"signed"': 'support.storage.type'
'"unsigned"': 'support.storage.type'
'"short"': 'support.storage.type'
'"long"': 'support.storage.type'
'"const"': 'storage.modifier'
'"volatile"': 'storage.modifier'
"""
"char",
"int",
"float",
"double",
"size_t",
"ssize_t",
"ptrdiff_t",
"decimal",
"typeof"
""": 'support.storage.type'
'";"': 'punctuation.terminator.statement'
'"["': 'punctuation.definition.begin.bracket.square'
'"]"': 'punctuation.definition.end.bracket.square'
'","': 'punctuation.separator.delimiter'
'"{"': 'punctuation.section.block.begin.bracket.curly'
'"}"': 'punctuation.section.block.end.bracket.curly'
'"("': 'punctuation.section.parens.begin.bracket.round'
'")"': 'punctuation.section.parens.end.bracket.round'
'"."': 'keyword.operator.member'
'"*"': 'keyword.operator'
'"-"': 'keyword.operator'
'"+"': 'keyword.operator'
'"/"': 'keyword.operator'
'"%"': 'keyword.operator'
'"++"': 'keyword.operator'
'"--"': 'keyword.operator'
'"=="': 'keyword.operator'
'"!"': 'keyword.operator'
'"!="': 'keyword.operator'
'"<"': 'keyword.operator'
'">"': 'keyword.operator'
'">="': 'keyword.operator'
'"<="': 'keyword.operator'
'"&&"': 'keyword.operator'
'"||"': 'keyword.operator'
'"&"': 'keyword.operator'
'"|"': 'keyword.operator'
'"^"': 'keyword.operator'
'"~"': 'keyword.operator'
'"<<"': 'keyword.operator'
'">>"': 'keyword.operator'
'"="': 'keyword.operator'
'"+="': 'keyword.operator'
'"-="': 'keyword.operator'
'"*="': 'keyword.operator'
'"/="': 'keyword.operator'
'"%="': 'keyword.operator'
'"<<="': 'keyword.operator'
'">>="': 'keyword.operator'
'"&="': 'keyword.operator'
'"^="': 'keyword.operator'
'"|="': 'keyword.operator'
'"?"': 'keyword.operator'
'":"': 'keyword.operator'
'"=~"': 'keyword.operator'
'"!~"': 'keyword.operator'
"""
"<?", ">?", ">?=", "<?="
""": 'keyword.operator'
'string': 'string.quoted.double'
'pathIsoFile': 'string.quoted.other'
'int': 'constant.numeric.decimal'
'rule_name': 'entity.name.function'
'pure_ident': 'variable.other'
| true | scopeName: 'source.coccinelle'
name: 'PI:NAME:<NAME>END_PI'
type: 'tree-sitter'
parser: 'tree-sitter-coccinelle'
fileTypes: [
'cocci'
]
comments:
start: '// '
folds: [
{
type: 'comment'
}
{
type: 'changeset'
}
{
type: 'prolog'
}
]
scopes:
'comment': 'comment.block'
"""
include > "#include",
using > "using",
virtual > "virtual"
""": 'keyword.control.directive'
'virtual > pure_ident': 'constant.other'
"""
script_metavariables > "script",
script_metavariables > "initialize",
script_metavariables > "finalize",
""": 'keyword.control.directive'
'language': 'constant.other'
"""
metavariables > "@",
metavariables > "@@",
script_metavariables > "@",
script_metavariables > "@@",
""": 'keyword.control.other'
"""
"any",
"assignment",
"attribute",
"binary",
"comments",
"constant",
"declaration",
"declarer",
"depends",
"disable",
"error",
"ever",
"exists",
"expression",
"extends",
"field",
"file",
"finalize",
"forall",
"format",
"fresh",
"function",
"global",
"identifier",
"idexpression",
"in",
"initialiser",
"initialize",
"initializer",
"iterator",
"list",
"local",
"merge",
"metavariable",
"name",
"never",
"on",
"operator",
"parameter",
"position",
"script",
"statement",
"symbol",
"type",
"typedef",
"using",
"virtual",
"when"
""": 'keyword.control'
'"struct"': 'keyword.control'
'"enum"': 'keyword.control'
'"union"': 'keyword.control'
'"signed"': 'support.storage.type'
'"unsigned"': 'support.storage.type'
'"short"': 'support.storage.type'
'"long"': 'support.storage.type'
'"const"': 'storage.modifier'
'"volatile"': 'storage.modifier'
"""
"char",
"int",
"float",
"double",
"size_t",
"ssize_t",
"ptrdiff_t",
"decimal",
"typeof"
""": 'support.storage.type'
'";"': 'punctuation.terminator.statement'
'"["': 'punctuation.definition.begin.bracket.square'
'"]"': 'punctuation.definition.end.bracket.square'
'","': 'punctuation.separator.delimiter'
'"{"': 'punctuation.section.block.begin.bracket.curly'
'"}"': 'punctuation.section.block.end.bracket.curly'
'"("': 'punctuation.section.parens.begin.bracket.round'
'")"': 'punctuation.section.parens.end.bracket.round'
'"."': 'keyword.operator.member'
'"*"': 'keyword.operator'
'"-"': 'keyword.operator'
'"+"': 'keyword.operator'
'"/"': 'keyword.operator'
'"%"': 'keyword.operator'
'"++"': 'keyword.operator'
'"--"': 'keyword.operator'
'"=="': 'keyword.operator'
'"!"': 'keyword.operator'
'"!="': 'keyword.operator'
'"<"': 'keyword.operator'
'">"': 'keyword.operator'
'">="': 'keyword.operator'
'"<="': 'keyword.operator'
'"&&"': 'keyword.operator'
'"||"': 'keyword.operator'
'"&"': 'keyword.operator'
'"|"': 'keyword.operator'
'"^"': 'keyword.operator'
'"~"': 'keyword.operator'
'"<<"': 'keyword.operator'
'">>"': 'keyword.operator'
'"="': 'keyword.operator'
'"+="': 'keyword.operator'
'"-="': 'keyword.operator'
'"*="': 'keyword.operator'
'"/="': 'keyword.operator'
'"%="': 'keyword.operator'
'"<<="': 'keyword.operator'
'">>="': 'keyword.operator'
'"&="': 'keyword.operator'
'"^="': 'keyword.operator'
'"|="': 'keyword.operator'
'"?"': 'keyword.operator'
'":"': 'keyword.operator'
'"=~"': 'keyword.operator'
'"!~"': 'keyword.operator'
"""
"<?", ">?", ">?=", "<?="
""": 'keyword.operator'
'string': 'string.quoted.double'
'pathIsoFile': 'string.quoted.other'
'int': 'constant.numeric.decimal'
'rule_name': 'entity.name.function'
'pure_ident': 'variable.other'
|
[
{
"context": "lized into JSON\", ->\n asset = new Asset(name: \"Johnson me!\")\n JSON.stringify(asset.attributes()).should.",
"end": 2226,
"score": 0.8626589179039001,
"start": 2216,
"tag": "NAME",
"value": "Johnson me"
},
{
"context": "ify(asset.attributes()).should.equal \"{\\\"name\\\":\\\"Johnson me!\\\"}\"\n\n it \"can be deserialized from JSON\", ->",
"end": 2302,
"score": 0.9839779138565063,
"start": 2295,
"tag": "NAME",
"value": "Johnson"
},
{
"context": "N\", ->\n asset = Asset.fromJSON(\"{\\\"name\\\":\\\"Un-Johnson me!\\\"}\")\n asset.name.should.equal \"Un-Johnson ",
"end": 2403,
"score": 0.49486294388771057,
"start": 2396,
"tag": "NAME",
"value": "Johnson"
},
{
"context": "nson me!\\\"}\")\n asset.name.should.equal \"Un-Johnson me!\"\n assets = Asset.fromJSON(\"[{\\\"name\\\":\\\"Un",
"end": 2452,
"score": 0.626494824886322,
"start": 2449,
"tag": "NAME",
"value": "son"
},
{
"context": "me!\"\n assets = Asset.fromJSON(\"[{\\\"name\\\":\\\"Un-Johnson me!\\\"}]\")\n assets[0] and assets[0].name.should",
"end": 2510,
"score": 0.7969930171966553,
"start": 2503,
"tag": "NAME",
"value": "Johnson"
},
{
"context": "assets[0] and assets[0].name.should.equal \"Un-Johnson me!\"\n\n it \"can validate\", ->\n Asset.include v",
"end": 2578,
"score": 0.6321672201156616,
"start": 2575,
"tag": "NAME",
"value": "son"
},
{
"context": "1]\n\n asset = new Asset()\n asset.load name: \"Javi Jimenez\"\n asset.first_name.should.equal \"Javi\"\n ass",
"end": 3464,
"score": 0.9998094439506531,
"start": 3452,
"tag": "NAME",
"value": "Javi Jimenez"
},
{
"context": "\"Javi Jimenez\"\n asset.first_name.should.equal \"Javi\"\n asset.last_name.should.equal \"Jimenez\"\n\n it",
"end": 3505,
"score": 0.998802900314331,
"start": 3501,
"tag": "NAME",
"value": "Javi"
},
{
"context": "ld.equal \"Javi\"\n asset.last_name.should.equal \"Jimenez\"\n\n it \"attributes() respecting getters/setters\",",
"end": 3548,
"score": 0.9839024543762207,
"start": 3541,
"tag": "NAME",
"value": "Jimenez"
},
{
"context": "rs/setters\", ->\n Asset.include name: ->\n \"Bob\"\n\n asset = new Asset()\n _.isEqual(asset.att",
"end": 3639,
"score": 0.9995110034942627,
"start": 3636,
"tag": "NAME",
"value": "Bob"
},
{
"context": " Asset()\n _.isEqual(asset.attributes(), name: \"Bob\").should.be.true\n\n it \"can generate UID\", ->\n ",
"end": 3710,
"score": 0.9995332360267639,
"start": 3707,
"tag": "NAME",
"value": "Bob"
},
{
"context": "te unique cIDs\", ->\n Asset.create\n name: \"Bob\"\n id: 3\n\n Asset.create\n name: \"Bob\"\n",
"end": 4927,
"score": 0.999764621257782,
"start": 4924,
"tag": "NAME",
"value": "Bob"
},
{
"context": " \"Bob\"\n id: 3\n\n Asset.create\n name: \"Bob\"\n id: 2 \n\n Asset.all()[0].uid.should.not",
"end": 4975,
"score": 0.9997978806495667,
"start": 4972,
"tag": "NAME",
"value": "Bob"
},
{
"context": " i = 0\n while i < 12\n Asset.create name: \"Bob\"\n i++\n \n Asset.count().should.equal 12\n",
"end": 5149,
"score": 0.9998489022254944,
"start": 5146,
"tag": "NAME",
"value": "Bob"
},
{
"context": " 0\n \n while i < 12\n Asset.create name: \"Bob\", uid: i\n i++\n \n Asset.count().should.e",
"end": 5313,
"score": 0.9982367157936096,
"start": 5310,
"tag": "NAME",
"value": "Bob"
}
] | spec/model_spec.coffee | ryggrad/Ryggrad | 0 | describe "Model", ->
Asset = undefined
beforeEach ->
class Asset extends Ryggrad.Model
@configure("Asset", "name")
it "can create records", ->
asset = Asset.create name: "test.pdf"
# Compare this way because JS is annoying
Asset.all()[0].id.should.equal asset.id
Asset.all()[0].uid.should.equal asset.uid
Asset.all()[0].name.should.equal asset.name
it "can update records", ->
asset = Asset.create(name: "test.pdf")
Asset.all()[0].name.should.equal "test.pdf"
asset.name = "wem.pdf"
asset.save()
Asset.all()[0].name.should.equal "wem.pdf"
it "can destroy records", ->
asset = Asset.create(name: "test.pdf")
Asset.all()[0].uid.should.equal asset.uid
asset.destroy()
expect(Asset.all()[0]).to.be.undefined
it "can find records", ->
asset = Asset.create(name: "test.pdf")
Asset.find(asset.id).should.not.be.null
Asset.find(asset.id).className.should.be("Asset")
asset.destroy()
expect( ->
Asset.find(asset.uid)
).to.throw(Error)
it "can find records by attribute", ->
asset = Asset.create name: "test.pdf"
asset_found = Asset.findBy("name", "test.pdf")
asset_found.name.should.equal asset.name
asset.destroy()
it "can check existence", ->
asset = Asset.create name: "test.pdf"
asset.exists().should.be.truthy
Asset.exists(asset.uid).should.be.truthy
asset_uid = _.clone(asset.uid)
asset.destroy()
expect(Asset.exists(asset_uid)).to.be.falsey
it "can select records", ->
asset1 = Asset.create(name: "test.pdf")
asset2 = Asset.create(name: "foo.pdf")
selected = Asset.select((rec) ->
rec.name is "foo.pdf"
)
selected[0].name.should.equal asset2.name
it "can return all records", ->
asset1 = Asset.create(name: "test.pdf")
asset2 = Asset.create(name: "foo.pdf")
Asset.all()[0].name.should.equal asset1.name
Asset.all()[1].name.should.equal asset2.name
it "can destroy all records", ->
Asset.create name: "foo.pdf"
Asset.create name: "foo.pdf"
Asset.count().should.equal 2
Asset.destroyAll()
Asset.count().should.equal 0
it "can be serialized into JSON", ->
asset = new Asset(name: "Johnson me!")
JSON.stringify(asset.attributes()).should.equal "{\"name\":\"Johnson me!\"}"
it "can be deserialized from JSON", ->
asset = Asset.fromJSON("{\"name\":\"Un-Johnson me!\"}")
asset.name.should.equal "Un-Johnson me!"
assets = Asset.fromJSON("[{\"name\":\"Un-Johnson me!\"}]")
assets[0] and assets[0].name.should.equal "Un-Johnson me!"
it "can validate", ->
Asset.include validate: ->
"Name required" unless @name
Asset.create(name: "").should.be.false
Asset.create(name: "Yo big dog").should.be.truthy
it "has attribute hash", ->
asset = new Asset(name: "wazzzup!")
_.isEqual(asset.attributes(), name: "wazzzup!").should.be.true
it "attributes() should not return undefined atts", ->
asset = new Asset()
_.isEqual(asset.attributes(), {}).should.be.true
it "can load attributes()", ->
asset = new Asset()
result = asset.load(name: "In da' house")
result.should.equal asset
asset.name.should.equal "In da' house"
it "can load() attributes respecting getters/setters", ->
Asset.include name: (value) ->
ref = value.split(" ", 2)
@first_name = ref[0]
@last_name = ref[1]
asset = new Asset()
asset.load name: "Javi Jimenez"
asset.first_name.should.equal "Javi"
asset.last_name.should.equal "Jimenez"
it "attributes() respecting getters/setters", ->
Asset.include name: ->
"Bob"
asset = new Asset()
_.isEqual(asset.attributes(), name: "Bob").should.be.true
it "can generate UID", ->
asset = Asset.create name: "who's in the house?"
asset.uid.should.not.be null
it "can be cloned", ->
asset = Asset.create name: "what's cooler than cool?"
asset.clone().__proto__.should.not.be Asset::
it "clones are dynamic", ->
asset = Asset.create name: "hotel california"
clone = Asset.find(asset.uid)
asset.name = "checkout anytime"
asset.save()
clone.name.should.equal "checkout anytime"
it "should return a clone from create or save", ->
asset = Asset.create name: "what's cooler than cool?"
asset.__proto__.should.not.be Asset::
asset.__proto__.__proto__.should.be Asset::
it "should be able to change ID", ->
asset = Asset.create name: "hotel california"
asset.uid.should.not.be null
asset.changeUID "foo"
asset.uid.should.equal "foo"
Asset.exists("foo").should.be.truthy
asset.changeID "cat"
asset.id.should.equal "cat"
Asset.exists("cat").should.be.truthy
it "new records should not be eql", ->
asset1 = new Asset
asset2 = new Asset
_.isEqual(asset1, asset2).should.be.false
it "should generate unique cIDs", ->
Asset.create
name: "Bob"
id: 3
Asset.create
name: "Bob"
id: 2
Asset.all()[0].uid.should.not.equal Asset.all()[1].uid
it "should create multiple assets", ->
i = 0
while i < 12
Asset.create name: "Bob"
i++
Asset.count().should.equal 12
it "should handle more than 10 cIDs correctly", ->
i = 0
while i < 12
Asset.create name: "Bob", uid: i
i++
Asset.count().should.equal 12
describe "with spy", ->
it "can interate over records", ->
asset1 = Asset.create name: "test.pdf"
asset2 = Asset.create name: "foo.pdf"
spy = sinon.spy()
Asset.each spy
spy.should.have.been.calledWith asset1
spy.should.have.been.calledWith asset2
| 77802 | describe "Model", ->
Asset = undefined
beforeEach ->
class Asset extends Ryggrad.Model
@configure("Asset", "name")
it "can create records", ->
asset = Asset.create name: "test.pdf"
# Compare this way because JS is annoying
Asset.all()[0].id.should.equal asset.id
Asset.all()[0].uid.should.equal asset.uid
Asset.all()[0].name.should.equal asset.name
it "can update records", ->
asset = Asset.create(name: "test.pdf")
Asset.all()[0].name.should.equal "test.pdf"
asset.name = "wem.pdf"
asset.save()
Asset.all()[0].name.should.equal "wem.pdf"
it "can destroy records", ->
asset = Asset.create(name: "test.pdf")
Asset.all()[0].uid.should.equal asset.uid
asset.destroy()
expect(Asset.all()[0]).to.be.undefined
it "can find records", ->
asset = Asset.create(name: "test.pdf")
Asset.find(asset.id).should.not.be.null
Asset.find(asset.id).className.should.be("Asset")
asset.destroy()
expect( ->
Asset.find(asset.uid)
).to.throw(Error)
it "can find records by attribute", ->
asset = Asset.create name: "test.pdf"
asset_found = Asset.findBy("name", "test.pdf")
asset_found.name.should.equal asset.name
asset.destroy()
it "can check existence", ->
asset = Asset.create name: "test.pdf"
asset.exists().should.be.truthy
Asset.exists(asset.uid).should.be.truthy
asset_uid = _.clone(asset.uid)
asset.destroy()
expect(Asset.exists(asset_uid)).to.be.falsey
it "can select records", ->
asset1 = Asset.create(name: "test.pdf")
asset2 = Asset.create(name: "foo.pdf")
selected = Asset.select((rec) ->
rec.name is "foo.pdf"
)
selected[0].name.should.equal asset2.name
it "can return all records", ->
asset1 = Asset.create(name: "test.pdf")
asset2 = Asset.create(name: "foo.pdf")
Asset.all()[0].name.should.equal asset1.name
Asset.all()[1].name.should.equal asset2.name
it "can destroy all records", ->
Asset.create name: "foo.pdf"
Asset.create name: "foo.pdf"
Asset.count().should.equal 2
Asset.destroyAll()
Asset.count().should.equal 0
it "can be serialized into JSON", ->
asset = new Asset(name: "<NAME>!")
JSON.stringify(asset.attributes()).should.equal "{\"name\":\"<NAME> me!\"}"
it "can be deserialized from JSON", ->
asset = Asset.fromJSON("{\"name\":\"Un-<NAME> me!\"}")
asset.name.should.equal "Un-John<NAME> me!"
assets = Asset.fromJSON("[{\"name\":\"Un-<NAME> me!\"}]")
assets[0] and assets[0].name.should.equal "Un-John<NAME> me!"
it "can validate", ->
Asset.include validate: ->
"Name required" unless @name
Asset.create(name: "").should.be.false
Asset.create(name: "Yo big dog").should.be.truthy
it "has attribute hash", ->
asset = new Asset(name: "wazzzup!")
_.isEqual(asset.attributes(), name: "wazzzup!").should.be.true
it "attributes() should not return undefined atts", ->
asset = new Asset()
_.isEqual(asset.attributes(), {}).should.be.true
it "can load attributes()", ->
asset = new Asset()
result = asset.load(name: "In da' house")
result.should.equal asset
asset.name.should.equal "In da' house"
it "can load() attributes respecting getters/setters", ->
Asset.include name: (value) ->
ref = value.split(" ", 2)
@first_name = ref[0]
@last_name = ref[1]
asset = new Asset()
asset.load name: "<NAME>"
asset.first_name.should.equal "<NAME>"
asset.last_name.should.equal "<NAME>"
it "attributes() respecting getters/setters", ->
Asset.include name: ->
"<NAME>"
asset = new Asset()
_.isEqual(asset.attributes(), name: "<NAME>").should.be.true
it "can generate UID", ->
asset = Asset.create name: "who's in the house?"
asset.uid.should.not.be null
it "can be cloned", ->
asset = Asset.create name: "what's cooler than cool?"
asset.clone().__proto__.should.not.be Asset::
it "clones are dynamic", ->
asset = Asset.create name: "hotel california"
clone = Asset.find(asset.uid)
asset.name = "checkout anytime"
asset.save()
clone.name.should.equal "checkout anytime"
it "should return a clone from create or save", ->
asset = Asset.create name: "what's cooler than cool?"
asset.__proto__.should.not.be Asset::
asset.__proto__.__proto__.should.be Asset::
it "should be able to change ID", ->
asset = Asset.create name: "hotel california"
asset.uid.should.not.be null
asset.changeUID "foo"
asset.uid.should.equal "foo"
Asset.exists("foo").should.be.truthy
asset.changeID "cat"
asset.id.should.equal "cat"
Asset.exists("cat").should.be.truthy
it "new records should not be eql", ->
asset1 = new Asset
asset2 = new Asset
_.isEqual(asset1, asset2).should.be.false
it "should generate unique cIDs", ->
Asset.create
name: "<NAME>"
id: 3
Asset.create
name: "<NAME>"
id: 2
Asset.all()[0].uid.should.not.equal Asset.all()[1].uid
it "should create multiple assets", ->
i = 0
while i < 12
Asset.create name: "<NAME>"
i++
Asset.count().should.equal 12
it "should handle more than 10 cIDs correctly", ->
i = 0
while i < 12
Asset.create name: "<NAME>", uid: i
i++
Asset.count().should.equal 12
describe "with spy", ->
it "can interate over records", ->
asset1 = Asset.create name: "test.pdf"
asset2 = Asset.create name: "foo.pdf"
spy = sinon.spy()
Asset.each spy
spy.should.have.been.calledWith asset1
spy.should.have.been.calledWith asset2
| true | describe "Model", ->
Asset = undefined
beforeEach ->
class Asset extends Ryggrad.Model
@configure("Asset", "name")
it "can create records", ->
asset = Asset.create name: "test.pdf"
# Compare this way because JS is annoying
Asset.all()[0].id.should.equal asset.id
Asset.all()[0].uid.should.equal asset.uid
Asset.all()[0].name.should.equal asset.name
it "can update records", ->
asset = Asset.create(name: "test.pdf")
Asset.all()[0].name.should.equal "test.pdf"
asset.name = "wem.pdf"
asset.save()
Asset.all()[0].name.should.equal "wem.pdf"
it "can destroy records", ->
asset = Asset.create(name: "test.pdf")
Asset.all()[0].uid.should.equal asset.uid
asset.destroy()
expect(Asset.all()[0]).to.be.undefined
it "can find records", ->
asset = Asset.create(name: "test.pdf")
Asset.find(asset.id).should.not.be.null
Asset.find(asset.id).className.should.be("Asset")
asset.destroy()
expect( ->
Asset.find(asset.uid)
).to.throw(Error)
it "can find records by attribute", ->
asset = Asset.create name: "test.pdf"
asset_found = Asset.findBy("name", "test.pdf")
asset_found.name.should.equal asset.name
asset.destroy()
it "can check existence", ->
asset = Asset.create name: "test.pdf"
asset.exists().should.be.truthy
Asset.exists(asset.uid).should.be.truthy
asset_uid = _.clone(asset.uid)
asset.destroy()
expect(Asset.exists(asset_uid)).to.be.falsey
it "can select records", ->
asset1 = Asset.create(name: "test.pdf")
asset2 = Asset.create(name: "foo.pdf")
selected = Asset.select((rec) ->
rec.name is "foo.pdf"
)
selected[0].name.should.equal asset2.name
it "can return all records", ->
asset1 = Asset.create(name: "test.pdf")
asset2 = Asset.create(name: "foo.pdf")
Asset.all()[0].name.should.equal asset1.name
Asset.all()[1].name.should.equal asset2.name
it "can destroy all records", ->
Asset.create name: "foo.pdf"
Asset.create name: "foo.pdf"
Asset.count().should.equal 2
Asset.destroyAll()
Asset.count().should.equal 0
it "can be serialized into JSON", ->
asset = new Asset(name: "PI:NAME:<NAME>END_PI!")
JSON.stringify(asset.attributes()).should.equal "{\"name\":\"PI:NAME:<NAME>END_PI me!\"}"
it "can be deserialized from JSON", ->
asset = Asset.fromJSON("{\"name\":\"Un-PI:NAME:<NAME>END_PI me!\"}")
asset.name.should.equal "Un-JohnPI:NAME:<NAME>END_PI me!"
assets = Asset.fromJSON("[{\"name\":\"Un-PI:NAME:<NAME>END_PI me!\"}]")
assets[0] and assets[0].name.should.equal "Un-JohnPI:NAME:<NAME>END_PI me!"
it "can validate", ->
Asset.include validate: ->
"Name required" unless @name
Asset.create(name: "").should.be.false
Asset.create(name: "Yo big dog").should.be.truthy
it "has attribute hash", ->
asset = new Asset(name: "wazzzup!")
_.isEqual(asset.attributes(), name: "wazzzup!").should.be.true
it "attributes() should not return undefined atts", ->
asset = new Asset()
_.isEqual(asset.attributes(), {}).should.be.true
it "can load attributes()", ->
asset = new Asset()
result = asset.load(name: "In da' house")
result.should.equal asset
asset.name.should.equal "In da' house"
it "can load() attributes respecting getters/setters", ->
Asset.include name: (value) ->
ref = value.split(" ", 2)
@first_name = ref[0]
@last_name = ref[1]
asset = new Asset()
asset.load name: "PI:NAME:<NAME>END_PI"
asset.first_name.should.equal "PI:NAME:<NAME>END_PI"
asset.last_name.should.equal "PI:NAME:<NAME>END_PI"
it "attributes() respecting getters/setters", ->
Asset.include name: ->
"PI:NAME:<NAME>END_PI"
asset = new Asset()
_.isEqual(asset.attributes(), name: "PI:NAME:<NAME>END_PI").should.be.true
it "can generate UID", ->
asset = Asset.create name: "who's in the house?"
asset.uid.should.not.be null
it "can be cloned", ->
asset = Asset.create name: "what's cooler than cool?"
asset.clone().__proto__.should.not.be Asset::
it "clones are dynamic", ->
asset = Asset.create name: "hotel california"
clone = Asset.find(asset.uid)
asset.name = "checkout anytime"
asset.save()
clone.name.should.equal "checkout anytime"
it "should return a clone from create or save", ->
asset = Asset.create name: "what's cooler than cool?"
asset.__proto__.should.not.be Asset::
asset.__proto__.__proto__.should.be Asset::
it "should be able to change ID", ->
asset = Asset.create name: "hotel california"
asset.uid.should.not.be null
asset.changeUID "foo"
asset.uid.should.equal "foo"
Asset.exists("foo").should.be.truthy
asset.changeID "cat"
asset.id.should.equal "cat"
Asset.exists("cat").should.be.truthy
it "new records should not be eql", ->
asset1 = new Asset
asset2 = new Asset
_.isEqual(asset1, asset2).should.be.false
it "should generate unique cIDs", ->
Asset.create
name: "PI:NAME:<NAME>END_PI"
id: 3
Asset.create
name: "PI:NAME:<NAME>END_PI"
id: 2
Asset.all()[0].uid.should.not.equal Asset.all()[1].uid
it "should create multiple assets", ->
i = 0
while i < 12
Asset.create name: "PI:NAME:<NAME>END_PI"
i++
Asset.count().should.equal 12
it "should handle more than 10 cIDs correctly", ->
i = 0
while i < 12
Asset.create name: "PI:NAME:<NAME>END_PI", uid: i
i++
Asset.count().should.equal 12
describe "with spy", ->
it "can interate over records", ->
asset1 = Asset.create name: "test.pdf"
asset2 = Asset.create name: "foo.pdf"
spy = sinon.spy()
Asset.each spy
spy.should.have.been.calledWith asset1
spy.should.have.been.calledWith asset2
|
[
{
"context": "f5bb9215039d87329e\"\n },\n \"first_name\": \"First Name\",\n \"last_name\": \"Last Name\",\n \"admin\": ",
"end": 194,
"score": 0.999608039855957,
"start": 184,
"tag": "NAME",
"value": "First Name"
},
{
"context": " \"first_name\": \"First Name\",\n \"last_name\": \"Last Name\",\n \"admin\": false,\n \"approved\": false,\n",
"end": 226,
"score": 0.9996875524520874,
"start": 217,
"tag": "NAME",
"value": "Last Name"
},
{
"context": ": false,\n \"approved\": false,\n \"email\": \"good@email.com\"\n }\n @user = new Thorax.Models.User userJso",
"end": 306,
"score": 0.9999243021011353,
"start": 292,
"tag": "EMAIL",
"value": "good@email.com"
},
{
"context": "rJson, parse: true\n\n it 'revert', ->\n expect(@user).toBeDefined()\n expect(@user.get('email')).toB",
"end": 406,
"score": 0.8716496229171753,
"start": 402,
"tag": "USERNAME",
"value": "user"
},
{
"context": "rt', ->\n expect(@user).toBeDefined()\n expect(@user.get('email')).toBe('good@email.com')\n expect(@",
"end": 438,
"score": 0.8028032779693604,
"start": 433,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "oBeDefined()\n expect(@user.get('email')).toBe('good@email.com')\n expect(@user.changed).toEqual({})\n @user",
"end": 473,
"score": 0.9999235272407532,
"start": 459,
"tag": "EMAIL",
"value": "good@email.com"
},
{
"context": ".get('email')).toBe('good@email.com')\n expect(@user.changed).toEqual({})\n @user.set('email', 'anot",
"end": 492,
"score": 0.8160114884376526,
"start": 488,
"tag": "USERNAME",
"value": "user"
},
{
"context": "user.changed).toEqual({})\n @user.set('email', 'another@email.com')\n expect(@user.changed).not.toEqual({})\n e",
"end": 555,
"score": 0.9999210238456726,
"start": 538,
"tag": "EMAIL",
"value": "another@email.com"
},
{
"context": "expect(@user.changed).not.toEqual({})\n expect(@user.get('email')).toBe('another@email.com')\n @user",
"end": 616,
"score": 0.8208034038543701,
"start": 612,
"tag": "USERNAME",
"value": "user"
},
{
"context": ".toEqual({})\n expect(@user.get('email')).toBe('another@email.com')\n @user.revert({\"email\": \"good@email.com\"})\n ",
"end": 654,
"score": 0.9999189376831055,
"start": 637,
"tag": "EMAIL",
"value": "another@email.com"
},
{
"context": "('another@email.com')\n @user.revert({\"email\": \"good@email.com\"})\n expect(@user.get('email')).toBe('good@emai",
"end": 699,
"score": 0.9999197125434875,
"start": 685,
"tag": "EMAIL",
"value": "good@email.com"
},
{
"context": "r.revert({\"email\": \"good@email.com\"})\n expect(@user.get('email')).toBe('good@email.com')\n expect(@",
"end": 719,
"score": 0.9812940955162048,
"start": 715,
"tag": "USERNAME",
"value": "user"
},
{
"context": "email.com\"})\n expect(@user.get('email')).toBe('good@email.com')\n expect(@user.changed).toEqual({})\n",
"end": 754,
"score": 0.9999260902404785,
"start": 740,
"tag": "EMAIL",
"value": "good@email.com"
},
{
"context": ".get('email')).toBe('good@email.com')\n expect(@user.changed).toEqual({})\n",
"end": 773,
"score": 0.8206768035888672,
"start": 769,
"tag": "USERNAME",
"value": "user"
}
] | spec/javascripts/models/user_spec.js.coffee | projectcypress/bonnie | 0 | describe 'User', ->
beforeAll ->
jasmine.getJSONFixtures().clearCache()
userJson = {
"_id": {
"$oid": "5c8037f5bb9215039d87329e"
},
"first_name": "First Name",
"last_name": "Last Name",
"admin": false,
"approved": false,
"email": "good@email.com"
}
@user = new Thorax.Models.User userJson, parse: true
it 'revert', ->
expect(@user).toBeDefined()
expect(@user.get('email')).toBe('good@email.com')
expect(@user.changed).toEqual({})
@user.set('email', 'another@email.com')
expect(@user.changed).not.toEqual({})
expect(@user.get('email')).toBe('another@email.com')
@user.revert({"email": "good@email.com"})
expect(@user.get('email')).toBe('good@email.com')
expect(@user.changed).toEqual({})
| 77555 | describe 'User', ->
beforeAll ->
jasmine.getJSONFixtures().clearCache()
userJson = {
"_id": {
"$oid": "5c8037f5bb9215039d87329e"
},
"first_name": "<NAME>",
"last_name": "<NAME>",
"admin": false,
"approved": false,
"email": "<EMAIL>"
}
@user = new Thorax.Models.User userJson, parse: true
it 'revert', ->
expect(@user).toBeDefined()
expect(@user.get('email')).toBe('<EMAIL>')
expect(@user.changed).toEqual({})
@user.set('email', '<EMAIL>')
expect(@user.changed).not.toEqual({})
expect(@user.get('email')).toBe('<EMAIL>')
@user.revert({"email": "<EMAIL>"})
expect(@user.get('email')).toBe('<EMAIL>')
expect(@user.changed).toEqual({})
| true | describe 'User', ->
beforeAll ->
jasmine.getJSONFixtures().clearCache()
userJson = {
"_id": {
"$oid": "5c8037f5bb9215039d87329e"
},
"first_name": "PI:NAME:<NAME>END_PI",
"last_name": "PI:NAME:<NAME>END_PI",
"admin": false,
"approved": false,
"email": "PI:EMAIL:<EMAIL>END_PI"
}
@user = new Thorax.Models.User userJson, parse: true
it 'revert', ->
expect(@user).toBeDefined()
expect(@user.get('email')).toBe('PI:EMAIL:<EMAIL>END_PI')
expect(@user.changed).toEqual({})
@user.set('email', 'PI:EMAIL:<EMAIL>END_PI')
expect(@user.changed).not.toEqual({})
expect(@user.get('email')).toBe('PI:EMAIL:<EMAIL>END_PI')
@user.revert({"email": "PI:EMAIL:<EMAIL>END_PI"})
expect(@user.get('email')).toBe('PI:EMAIL:<EMAIL>END_PI')
expect(@user.changed).toEqual({})
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991421103477478,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-http-client-readable.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
FakeAgent = ->
http.Agent.call this
return
common = require("../common")
assert = require("assert")
http = require("http")
util = require("util")
Duplex = require("stream").Duplex
util.inherits FakeAgent, http.Agent
FakeAgent::createConnection = createConnection = ->
s = new Duplex()
once = false
s._read = read = ->
return @push(null) if once
once = true
@push "HTTP/1.1 200 Ok\r\nTransfer-Encoding: chunked\r\n\r\n"
@push "b\r\nhello world\r\n"
@readable = false
@push "0\r\n\r\n"
return
# Blackhole
s._write = write = (data, enc, cb) ->
cb()
return
s.destroy = s.destroySoon = destroy = ->
@writable = false
return
s
received = ""
ended = 0
req = http.request(
agent: new FakeAgent()
, (res) ->
res.on "data", (chunk) ->
received += chunk
return
res.on "end", ->
ended++
return
return
)
req.end()
process.on "exit", ->
assert.equal received, "hello world"
assert.equal ended, 1
return
| 171175 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
FakeAgent = ->
http.Agent.call this
return
common = require("../common")
assert = require("assert")
http = require("http")
util = require("util")
Duplex = require("stream").Duplex
util.inherits FakeAgent, http.Agent
FakeAgent::createConnection = createConnection = ->
s = new Duplex()
once = false
s._read = read = ->
return @push(null) if once
once = true
@push "HTTP/1.1 200 Ok\r\nTransfer-Encoding: chunked\r\n\r\n"
@push "b\r\nhello world\r\n"
@readable = false
@push "0\r\n\r\n"
return
# Blackhole
s._write = write = (data, enc, cb) ->
cb()
return
s.destroy = s.destroySoon = destroy = ->
@writable = false
return
s
received = ""
ended = 0
req = http.request(
agent: new FakeAgent()
, (res) ->
res.on "data", (chunk) ->
received += chunk
return
res.on "end", ->
ended++
return
return
)
req.end()
process.on "exit", ->
assert.equal received, "hello world"
assert.equal ended, 1
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
FakeAgent = ->
http.Agent.call this
return
common = require("../common")
assert = require("assert")
http = require("http")
util = require("util")
Duplex = require("stream").Duplex
util.inherits FakeAgent, http.Agent
FakeAgent::createConnection = createConnection = ->
s = new Duplex()
once = false
s._read = read = ->
return @push(null) if once
once = true
@push "HTTP/1.1 200 Ok\r\nTransfer-Encoding: chunked\r\n\r\n"
@push "b\r\nhello world\r\n"
@readable = false
@push "0\r\n\r\n"
return
# Blackhole
s._write = write = (data, enc, cb) ->
cb()
return
s.destroy = s.destroySoon = destroy = ->
@writable = false
return
s
received = ""
ended = 0
req = http.request(
agent: new FakeAgent()
, (res) ->
res.on "data", (chunk) ->
received += chunk
return
res.on "end", ->
ended++
return
return
)
req.end()
process.on "exit", ->
assert.equal received, "hello world"
assert.equal ended, 1
return
|
[
{
"context": "wfds.apps.googleusercontent.com\n clientSecret: 1wnchd7Xjs-d7ucnJHSXJK\n\n Leave empty to keep previous values\n\n\"\"\"\n s",
"end": 2958,
"score": 0.9989084005355835,
"start": 2936,
"tag": "KEY",
"value": "1wnchd7Xjs-d7ucnJHSXJK"
},
{
"context": " csup v0.0.2 (cloud storage uploader), (c) 2014 by Philipp Staender\n\n Usage: csup (switch) (-option|--option)\n\n ",
"end": 4730,
"score": 0.9998185038566589,
"start": 4714,
"tag": "NAME",
"value": "Philipp Staender"
}
] | src/csuplib.coffee | pstaender/csup | 2 | YAML = require('yamljs')
_ = require('underscore')
fs = require('fs')
googleapis = require("googleapis")
argv = require('optimist').argv
GoogleTokenProvider = require("refresh-token").GoogleTokenProvider
_rl = null
absPath = (p) ->
home = process.env['HOME'] or process.env['USERPROFILE']
p?.replace(/\~\//g, home+"/")#?.replace(/^\.\//, process.argv[1]+'/')
mask = (s) ->
return '***' unless typeof s is 'string'
if s.length > 2
s[0] + Array(s.length-1).join('*') + s[s.length-1]
else
Array(s.length+1).join('*')
exports.log = (verbosity = 0, msg) ->
if exports.config.verbosity >= verbosity
console.log(msg) if msg isnt null or undefined
true
else
false
exports.configFile = argv.c or argv.config or '~/.csup'
exports.configFile = absPath(exports.configFile)
exports.rl = ->
return _rl if _rl
_rl = require("readline").createInterface { input: process.stdin, output: process.stdout }
exports.defaultOptions =
scope: "https://www.googleapis.com/auth/drive.file"
authCode: ""
accessToken: ""
clientID: ""
clientSecret: ""
redirectURL: 'http://localhost'
refreshToken: ""
defaultFilename: 'file_{timestamp}' # possible is {date|DATE|timestamp|TIMESTAMP}
exports.loadConfig = ->
unless fs.existsSync(exports.configFile)
null
else
_.defaults(YAML.load(exports.configFile) or {}, exports.defaultOptions)
exports.config = exports.loadConfig() or {}
exports.defaultFilename = ->
s = exports.config.defaultFilename?.trim() or exports.defaultOptions.defaultFilename
s.replace('{timestamp}', new Date().getTime()).replace('{TIMESTAMP}', Math.round((new Date().getTime())/1000)).replace('{date}', String(new Date())).replace('{DATE}', String(new Date()).replace(/\s+/g,'_'))
exports.storeConfig = (cb) ->
c = exports.loadConfig() or {}
# only store some specific values
c.authCode = exports.config.authCode or null
c.accessToken = exports.config.accessToken or null
c.clientID = exports.config.clientID or null
c.clientSecret = exports.config.clientSecret or null
c.accessToken = exports.config.accessToken or null
c.refreshToken = exports.config.refreshToken or null
c.tokenType = exports.config.tokenType or null
if typeof cb is 'function'
fs.writeFile(exports.configFile, YAML.stringify(c, 2), cb)
else
fs.writeFileSync(exports.configFile, YAML.stringify(c, 2))
exports.credentials = ->
{ access_token: exports.config.accessToken, refresh_token: exports.config.refreshToken, token_type: exports.config.tokenType }
exports.setup = ->
exports.config = _.defaults(exports.loadConfig() or {}, exports.defaultOptions)
console.log """
** SETUP CLIENT_ID AND CLIENT_SECRET **
For more informations how to create api keys visit:
https://developers.google.com/console/help/#generatingdevkeys
Examples:
clientID: 123455-abc38rwfds.apps.googleusercontent.com
clientSecret: 1wnchd7Xjs-d7ucnJHSXJK
Leave empty to keep previous values
"""
setupClientTokens = ->
rl = exports.rl()
rl.question "clientID: ", (clientID) ->
exports.config.clientID = clientID if clientID
rl.question "clientSecret: ", (clientSecret) ->
exports.config.clientSecret = clientSecret if clientSecret
console.log """
clientSecret: '#{exports.config.clientSecret}'
clientID: '#{exports.config.clientID}'
"""
rl.question "Is that correct? (Y/n) ", (yesOrNo) ->
if /^\s*[nN]+\s*/.test(yesOrNo) or not exports.config.clientSecret or not exports.config.clientID
console.error('ERROR: clientID and clientSecret must be a valid value\n') if not exports.config.clientSecret or not exports.config.clientID
setupClientTokens()
else
exports.storeConfig()
console.log "Values stored in '#{exports.configFile}'"
rl.question "Do want to start the auth process? (Y/n) ", (yesOrNo) ->
if /^\s*[nN]+\s*/.test(yesOrNo)
process.exit(0)
else
require('./auth')
setupClientTokens()
exports.checkConfig = ->
unless exports.config.clientID or not exports.config.clientSecret
console.error "Couldn't read config file '#{exports.configFile}'."
console.error "Run setup with:\ncsup setup"
process.exit(1)
else
try
unless exports.config
return exports.loadConfig()
else
return exports.config
catch e
console.error "Could't parse yaml config file '#{exports.configFile}':", e?.message or e, "Please fix or remove config file."
process.exit(1)
exports.help = ->
"""
csup v0.0.2 (cloud storage uploader), (c) 2014 by Philipp Staender
Usage: csup (switch) (-option|--option)
switches:
auth receives `accessToken` from Google API (interactive)
setup setups `clientID` + `clientSecret` (interactive)
options:
-h --help displays help
-n --name filename for cloud storage e.g. -n filename.txt
-t --type force a specific filetype e.g. -t 'application/zip'
-v -vv -vvv verbosity
"""
exports.establishAPIConnection = (cb) ->
googleapis = require("googleapis")
config = exports.config
tokenProvider = new GoogleTokenProvider
'refresh_token': config.refreshToken
'client_id': config.clientID
'client_secret': config.clientSecret
tokenProvider.getToken (err, accessToken) ->
config.accessToken = accessToken
unless accessToken
console.error """
Couldn't get valid accesstoken. Please run again:
csup auth
"""
process.exit(1)
# store asnyc
exports.storeConfig (err) ->
console.error("Couldn't store config", err?.message or err) if err
auth = new googleapis.OAuth2Client(config.clientID, config.clientSecret, config.redirectURL)
cb(err, googleapis, auth)
| 54634 | YAML = require('yamljs')
_ = require('underscore')
fs = require('fs')
googleapis = require("googleapis")
argv = require('optimist').argv
GoogleTokenProvider = require("refresh-token").GoogleTokenProvider
_rl = null
absPath = (p) ->
home = process.env['HOME'] or process.env['USERPROFILE']
p?.replace(/\~\//g, home+"/")#?.replace(/^\.\//, process.argv[1]+'/')
mask = (s) ->
return '***' unless typeof s is 'string'
if s.length > 2
s[0] + Array(s.length-1).join('*') + s[s.length-1]
else
Array(s.length+1).join('*')
exports.log = (verbosity = 0, msg) ->
if exports.config.verbosity >= verbosity
console.log(msg) if msg isnt null or undefined
true
else
false
exports.configFile = argv.c or argv.config or '~/.csup'
exports.configFile = absPath(exports.configFile)
exports.rl = ->
return _rl if _rl
_rl = require("readline").createInterface { input: process.stdin, output: process.stdout }
exports.defaultOptions =
scope: "https://www.googleapis.com/auth/drive.file"
authCode: ""
accessToken: ""
clientID: ""
clientSecret: ""
redirectURL: 'http://localhost'
refreshToken: ""
defaultFilename: 'file_{timestamp}' # possible is {date|DATE|timestamp|TIMESTAMP}
exports.loadConfig = ->
unless fs.existsSync(exports.configFile)
null
else
_.defaults(YAML.load(exports.configFile) or {}, exports.defaultOptions)
exports.config = exports.loadConfig() or {}
exports.defaultFilename = ->
s = exports.config.defaultFilename?.trim() or exports.defaultOptions.defaultFilename
s.replace('{timestamp}', new Date().getTime()).replace('{TIMESTAMP}', Math.round((new Date().getTime())/1000)).replace('{date}', String(new Date())).replace('{DATE}', String(new Date()).replace(/\s+/g,'_'))
exports.storeConfig = (cb) ->
c = exports.loadConfig() or {}
# only store some specific values
c.authCode = exports.config.authCode or null
c.accessToken = exports.config.accessToken or null
c.clientID = exports.config.clientID or null
c.clientSecret = exports.config.clientSecret or null
c.accessToken = exports.config.accessToken or null
c.refreshToken = exports.config.refreshToken or null
c.tokenType = exports.config.tokenType or null
if typeof cb is 'function'
fs.writeFile(exports.configFile, YAML.stringify(c, 2), cb)
else
fs.writeFileSync(exports.configFile, YAML.stringify(c, 2))
exports.credentials = ->
{ access_token: exports.config.accessToken, refresh_token: exports.config.refreshToken, token_type: exports.config.tokenType }
exports.setup = ->
exports.config = _.defaults(exports.loadConfig() or {}, exports.defaultOptions)
console.log """
** SETUP CLIENT_ID AND CLIENT_SECRET **
For more informations how to create api keys visit:
https://developers.google.com/console/help/#generatingdevkeys
Examples:
clientID: 123455-abc38rwfds.apps.googleusercontent.com
clientSecret: <KEY>
Leave empty to keep previous values
"""
setupClientTokens = ->
rl = exports.rl()
rl.question "clientID: ", (clientID) ->
exports.config.clientID = clientID if clientID
rl.question "clientSecret: ", (clientSecret) ->
exports.config.clientSecret = clientSecret if clientSecret
console.log """
clientSecret: '#{exports.config.clientSecret}'
clientID: '#{exports.config.clientID}'
"""
rl.question "Is that correct? (Y/n) ", (yesOrNo) ->
if /^\s*[nN]+\s*/.test(yesOrNo) or not exports.config.clientSecret or not exports.config.clientID
console.error('ERROR: clientID and clientSecret must be a valid value\n') if not exports.config.clientSecret or not exports.config.clientID
setupClientTokens()
else
exports.storeConfig()
console.log "Values stored in '#{exports.configFile}'"
rl.question "Do want to start the auth process? (Y/n) ", (yesOrNo) ->
if /^\s*[nN]+\s*/.test(yesOrNo)
process.exit(0)
else
require('./auth')
setupClientTokens()
exports.checkConfig = ->
unless exports.config.clientID or not exports.config.clientSecret
console.error "Couldn't read config file '#{exports.configFile}'."
console.error "Run setup with:\ncsup setup"
process.exit(1)
else
try
unless exports.config
return exports.loadConfig()
else
return exports.config
catch e
console.error "Could't parse yaml config file '#{exports.configFile}':", e?.message or e, "Please fix or remove config file."
process.exit(1)
exports.help = ->
"""
csup v0.0.2 (cloud storage uploader), (c) 2014 by <NAME>
Usage: csup (switch) (-option|--option)
switches:
auth receives `accessToken` from Google API (interactive)
setup setups `clientID` + `clientSecret` (interactive)
options:
-h --help displays help
-n --name filename for cloud storage e.g. -n filename.txt
-t --type force a specific filetype e.g. -t 'application/zip'
-v -vv -vvv verbosity
"""
exports.establishAPIConnection = (cb) ->
googleapis = require("googleapis")
config = exports.config
tokenProvider = new GoogleTokenProvider
'refresh_token': config.refreshToken
'client_id': config.clientID
'client_secret': config.clientSecret
tokenProvider.getToken (err, accessToken) ->
config.accessToken = accessToken
unless accessToken
console.error """
Couldn't get valid accesstoken. Please run again:
csup auth
"""
process.exit(1)
# store asnyc
exports.storeConfig (err) ->
console.error("Couldn't store config", err?.message or err) if err
auth = new googleapis.OAuth2Client(config.clientID, config.clientSecret, config.redirectURL)
cb(err, googleapis, auth)
| true | YAML = require('yamljs')
_ = require('underscore')
fs = require('fs')
googleapis = require("googleapis")
argv = require('optimist').argv
GoogleTokenProvider = require("refresh-token").GoogleTokenProvider
_rl = null
absPath = (p) ->
home = process.env['HOME'] or process.env['USERPROFILE']
p?.replace(/\~\//g, home+"/")#?.replace(/^\.\//, process.argv[1]+'/')
mask = (s) ->
return '***' unless typeof s is 'string'
if s.length > 2
s[0] + Array(s.length-1).join('*') + s[s.length-1]
else
Array(s.length+1).join('*')
exports.log = (verbosity = 0, msg) ->
if exports.config.verbosity >= verbosity
console.log(msg) if msg isnt null or undefined
true
else
false
exports.configFile = argv.c or argv.config or '~/.csup'
exports.configFile = absPath(exports.configFile)
exports.rl = ->
return _rl if _rl
_rl = require("readline").createInterface { input: process.stdin, output: process.stdout }
exports.defaultOptions =
scope: "https://www.googleapis.com/auth/drive.file"
authCode: ""
accessToken: ""
clientID: ""
clientSecret: ""
redirectURL: 'http://localhost'
refreshToken: ""
defaultFilename: 'file_{timestamp}' # possible is {date|DATE|timestamp|TIMESTAMP}
exports.loadConfig = ->
unless fs.existsSync(exports.configFile)
null
else
_.defaults(YAML.load(exports.configFile) or {}, exports.defaultOptions)
exports.config = exports.loadConfig() or {}
exports.defaultFilename = ->
s = exports.config.defaultFilename?.trim() or exports.defaultOptions.defaultFilename
s.replace('{timestamp}', new Date().getTime()).replace('{TIMESTAMP}', Math.round((new Date().getTime())/1000)).replace('{date}', String(new Date())).replace('{DATE}', String(new Date()).replace(/\s+/g,'_'))
exports.storeConfig = (cb) ->
c = exports.loadConfig() or {}
# only store some specific values
c.authCode = exports.config.authCode or null
c.accessToken = exports.config.accessToken or null
c.clientID = exports.config.clientID or null
c.clientSecret = exports.config.clientSecret or null
c.accessToken = exports.config.accessToken or null
c.refreshToken = exports.config.refreshToken or null
c.tokenType = exports.config.tokenType or null
if typeof cb is 'function'
fs.writeFile(exports.configFile, YAML.stringify(c, 2), cb)
else
fs.writeFileSync(exports.configFile, YAML.stringify(c, 2))
exports.credentials = ->
{ access_token: exports.config.accessToken, refresh_token: exports.config.refreshToken, token_type: exports.config.tokenType }
exports.setup = ->
exports.config = _.defaults(exports.loadConfig() or {}, exports.defaultOptions)
console.log """
** SETUP CLIENT_ID AND CLIENT_SECRET **
For more informations how to create api keys visit:
https://developers.google.com/console/help/#generatingdevkeys
Examples:
clientID: 123455-abc38rwfds.apps.googleusercontent.com
clientSecret: PI:KEY:<KEY>END_PI
Leave empty to keep previous values
"""
setupClientTokens = ->
rl = exports.rl()
rl.question "clientID: ", (clientID) ->
exports.config.clientID = clientID if clientID
rl.question "clientSecret: ", (clientSecret) ->
exports.config.clientSecret = clientSecret if clientSecret
console.log """
clientSecret: '#{exports.config.clientSecret}'
clientID: '#{exports.config.clientID}'
"""
rl.question "Is that correct? (Y/n) ", (yesOrNo) ->
if /^\s*[nN]+\s*/.test(yesOrNo) or not exports.config.clientSecret or not exports.config.clientID
console.error('ERROR: clientID and clientSecret must be a valid value\n') if not exports.config.clientSecret or not exports.config.clientID
setupClientTokens()
else
exports.storeConfig()
console.log "Values stored in '#{exports.configFile}'"
rl.question "Do want to start the auth process? (Y/n) ", (yesOrNo) ->
if /^\s*[nN]+\s*/.test(yesOrNo)
process.exit(0)
else
require('./auth')
setupClientTokens()
exports.checkConfig = ->
unless exports.config.clientID or not exports.config.clientSecret
console.error "Couldn't read config file '#{exports.configFile}'."
console.error "Run setup with:\ncsup setup"
process.exit(1)
else
try
unless exports.config
return exports.loadConfig()
else
return exports.config
catch e
console.error "Could't parse yaml config file '#{exports.configFile}':", e?.message or e, "Please fix or remove config file."
process.exit(1)
exports.help = ->
"""
csup v0.0.2 (cloud storage uploader), (c) 2014 by PI:NAME:<NAME>END_PI
Usage: csup (switch) (-option|--option)
switches:
auth receives `accessToken` from Google API (interactive)
setup setups `clientID` + `clientSecret` (interactive)
options:
-h --help displays help
-n --name filename for cloud storage e.g. -n filename.txt
-t --type force a specific filetype e.g. -t 'application/zip'
-v -vv -vvv verbosity
"""
exports.establishAPIConnection = (cb) ->
googleapis = require("googleapis")
config = exports.config
tokenProvider = new GoogleTokenProvider
'refresh_token': config.refreshToken
'client_id': config.clientID
'client_secret': config.clientSecret
tokenProvider.getToken (err, accessToken) ->
config.accessToken = accessToken
unless accessToken
console.error """
Couldn't get valid accesstoken. Please run again:
csup auth
"""
process.exit(1)
# store asnyc
exports.storeConfig (err) ->
console.error("Couldn't store config", err?.message or err) if err
auth = new googleapis.OAuth2Client(config.clientID, config.clientSecret, config.redirectURL)
cb(err, googleapis, auth)
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9992077946662903,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": "ire(\"crypto\")\ncommon = require(\"../common\")\nkeys = crypto.randomBytes(48)\nserverLog = []\nticketLog = []\nserverCount = 0",
"end": 2190,
"score": 0.9036828279495239,
"start": 2172,
"tag": "KEY",
"value": "crypto.randomBytes"
},
{
"context": " = require(\"../common\")\nkeys = crypto.randomBytes(48)\nserverLog = []\nticketLog = []\nserverCount = 0\nse",
"end": 2193,
"score": 0.9596131443977356,
"start": 2191,
"tag": "KEY",
"value": "48"
}
] | test/simple/test-tls-ticket.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
createServer = ->
id = serverCount++
server = tls.createServer(
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
ticketKeys: keys
, (c) ->
serverLog.push id
c.end()
return
)
server
# Create one TCP server and balance sockets to multiple TLS server instances
start = (callback) ->
connect = ->
s = tls.connect(common.PORT,
session: sess
rejectUnauthorized: false
, ->
sess = s.getSession() or sess
ticketLog.push s.getTLSTicket().toString("hex")
return
)
s.on "close", ->
if --left is 0
callback()
else
connect()
return
return
sess = null
left = servers.length
connect()
return
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
assert = require("assert")
fs = require("fs")
net = require("net")
tls = require("tls")
crypto = require("crypto")
common = require("../common")
keys = crypto.randomBytes(48)
serverLog = []
ticketLog = []
serverCount = 0
servers = [
createServer()
createServer()
createServer()
createServer()
createServer()
createServer()
]
shared = net.createServer((c) ->
servers.shift().emit "connection", c
return
).listen(common.PORT, ->
start ->
shared.close()
return
return
)
process.on "exit", ->
assert.equal ticketLog.length, serverLog.length
i = 0
while i < serverLog.length - 1
assert.notEqual serverLog[i], serverLog[i + 1]
assert.equal ticketLog[i], ticketLog[i + 1]
i++
return
| 129338 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
createServer = ->
id = serverCount++
server = tls.createServer(
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
ticketKeys: keys
, (c) ->
serverLog.push id
c.end()
return
)
server
# Create one TCP server and balance sockets to multiple TLS server instances
start = (callback) ->
connect = ->
s = tls.connect(common.PORT,
session: sess
rejectUnauthorized: false
, ->
sess = s.getSession() or sess
ticketLog.push s.getTLSTicket().toString("hex")
return
)
s.on "close", ->
if --left is 0
callback()
else
connect()
return
return
sess = null
left = servers.length
connect()
return
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
assert = require("assert")
fs = require("fs")
net = require("net")
tls = require("tls")
crypto = require("crypto")
common = require("../common")
keys = <KEY>(<KEY>)
serverLog = []
ticketLog = []
serverCount = 0
servers = [
createServer()
createServer()
createServer()
createServer()
createServer()
createServer()
]
shared = net.createServer((c) ->
servers.shift().emit "connection", c
return
).listen(common.PORT, ->
start ->
shared.close()
return
return
)
process.on "exit", ->
assert.equal ticketLog.length, serverLog.length
i = 0
while i < serverLog.length - 1
assert.notEqual serverLog[i], serverLog[i + 1]
assert.equal ticketLog[i], ticketLog[i + 1]
i++
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
createServer = ->
id = serverCount++
server = tls.createServer(
key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem")
cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem")
ticketKeys: keys
, (c) ->
serverLog.push id
c.end()
return
)
server
# Create one TCP server and balance sockets to multiple TLS server instances
start = (callback) ->
connect = ->
s = tls.connect(common.PORT,
session: sess
rejectUnauthorized: false
, ->
sess = s.getSession() or sess
ticketLog.push s.getTLSTicket().toString("hex")
return
)
s.on "close", ->
if --left is 0
callback()
else
connect()
return
return
sess = null
left = servers.length
connect()
return
unless process.versions.openssl
console.error "Skipping because node compiled without OpenSSL."
process.exit 0
assert = require("assert")
fs = require("fs")
net = require("net")
tls = require("tls")
crypto = require("crypto")
common = require("../common")
keys = PI:KEY:<KEY>END_PI(PI:KEY:<KEY>END_PI)
serverLog = []
ticketLog = []
serverCount = 0
servers = [
createServer()
createServer()
createServer()
createServer()
createServer()
createServer()
]
shared = net.createServer((c) ->
servers.shift().emit "connection", c
return
).listen(common.PORT, ->
start ->
shared.close()
return
return
)
process.on "exit", ->
assert.equal ticketLog.length, serverLog.length
i = 0
while i < serverLog.length - 1
assert.notEqual serverLog[i], serverLog[i + 1]
assert.equal ticketLog[i], ticketLog[i + 1]
i++
return
|
[
{
"context": "ase\n\t\t\tuser: config.database.username\n\t\t\tpassword: config.database.password\n\t\tpool:\n\t\t\tmin: 2\n\t\t\tmax: 10\n\t\tmigrations:\n\t\t\ttab",
"end": 290,
"score": 0.930867075920105,
"start": 266,
"tag": "PASSWORD",
"value": "config.database.password"
}
] | knexfile.coffee | joepie91/pdfy2 | 11 | # Update with your config settings.
config = require "./config.json"
module.exports =
# TODO: Do we need an environment name here?
development:
client: "mysql2"
connection:
database: config.database.database
user: config.database.username
password: config.database.password
pool:
min: 2
max: 10
migrations:
tableName: "knex_migrations"
| 185168 | # Update with your config settings.
config = require "./config.json"
module.exports =
# TODO: Do we need an environment name here?
development:
client: "mysql2"
connection:
database: config.database.database
user: config.database.username
password: <PASSWORD>
pool:
min: 2
max: 10
migrations:
tableName: "knex_migrations"
| true | # Update with your config settings.
config = require "./config.json"
module.exports =
# TODO: Do we need an environment name here?
development:
client: "mysql2"
connection:
database: config.database.database
user: config.database.username
password: PI:PASSWORD:<PASSWORD>END_PI
pool:
min: 2
max: 10
migrations:
tableName: "knex_migrations"
|
[
{
"context": " href=\"https://peoplefinder.service.gov.uk/people/john-smith\">John Smith</a>' +\n '</body>')\n $(doc",
"end": 330,
"score": 0.996716320514679,
"start": 320,
"tag": "USERNAME",
"value": "john-smith"
},
{
"context": "://peoplefinder.service.gov.uk/people/john-smith\">John Smith</a>' +\n '</body>')\n $(document.body).",
"end": 342,
"score": 0.9994345903396606,
"start": 332,
"tag": "NAME",
"value": "John Smith"
}
] | spec/javascripts/analytics/virtual_pageview_spec.coffee | cybersquirrel/peoplefinder | 16 | //= require modules/virtual_pageview
describe 'VirtualPageview', ->
element = null
describe 'given "data-virtual-pageview" anchor link', ->
setUpPage = (page_url) ->
element = $('<body>' +
'<a id="a_link" data-virtual-pageview="' + page_url + '" href="https://peoplefinder.service.gov.uk/people/john-smith">John Smith</a>' +
'</body>')
$(document.body).append(element)
new window.VirtualPageview.bindLinks()
afterEach ->
element.remove()
element = null
describe 'with single page url', ->
beforeEach ->
setUpPage('/top-3-search-result')
describe 'on first click', ->
it 'dispatches pageview', ->
spyOn window, 'dispatchPageView'
$('#a_link').trigger 'click'
expect(window.dispatchPageView).toHaveBeenCalledWith('/top-3-search-result')
describe 'with comma list of page urls', ->
beforeEach ->
setUpPage('/search-result,/top-3-search-result')
describe 'on first click', ->
it 'dispatches pageview for each url', ->
spyOn window, 'dispatchPageView'
$('#a_link').trigger 'click'
expect(window.dispatchPageView).toHaveBeenCalledWith('/search-result')
expect(window.dispatchPageView).toHaveBeenCalledWith('/top-3-search-result')
| 84274 | //= require modules/virtual_pageview
describe 'VirtualPageview', ->
element = null
describe 'given "data-virtual-pageview" anchor link', ->
setUpPage = (page_url) ->
element = $('<body>' +
'<a id="a_link" data-virtual-pageview="' + page_url + '" href="https://peoplefinder.service.gov.uk/people/john-smith"><NAME></a>' +
'</body>')
$(document.body).append(element)
new window.VirtualPageview.bindLinks()
afterEach ->
element.remove()
element = null
describe 'with single page url', ->
beforeEach ->
setUpPage('/top-3-search-result')
describe 'on first click', ->
it 'dispatches pageview', ->
spyOn window, 'dispatchPageView'
$('#a_link').trigger 'click'
expect(window.dispatchPageView).toHaveBeenCalledWith('/top-3-search-result')
describe 'with comma list of page urls', ->
beforeEach ->
setUpPage('/search-result,/top-3-search-result')
describe 'on first click', ->
it 'dispatches pageview for each url', ->
spyOn window, 'dispatchPageView'
$('#a_link').trigger 'click'
expect(window.dispatchPageView).toHaveBeenCalledWith('/search-result')
expect(window.dispatchPageView).toHaveBeenCalledWith('/top-3-search-result')
| true | //= require modules/virtual_pageview
describe 'VirtualPageview', ->
element = null
describe 'given "data-virtual-pageview" anchor link', ->
setUpPage = (page_url) ->
element = $('<body>' +
'<a id="a_link" data-virtual-pageview="' + page_url + '" href="https://peoplefinder.service.gov.uk/people/john-smith">PI:NAME:<NAME>END_PI</a>' +
'</body>')
$(document.body).append(element)
new window.VirtualPageview.bindLinks()
afterEach ->
element.remove()
element = null
describe 'with single page url', ->
beforeEach ->
setUpPage('/top-3-search-result')
describe 'on first click', ->
it 'dispatches pageview', ->
spyOn window, 'dispatchPageView'
$('#a_link').trigger 'click'
expect(window.dispatchPageView).toHaveBeenCalledWith('/top-3-search-result')
describe 'with comma list of page urls', ->
beforeEach ->
setUpPage('/search-result,/top-3-search-result')
describe 'on first click', ->
it 'dispatches pageview for each url', ->
spyOn window, 'dispatchPageView'
$('#a_link').trigger 'click'
expect(window.dispatchPageView).toHaveBeenCalledWith('/search-result')
expect(window.dispatchPageView).toHaveBeenCalledWith('/top-3-search-result')
|
[
{
"context": "mfabrik GmbH\n * MIT Licence\n * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org\n#",
"end": 166,
"score": 0.9901421070098877,
"start": 152,
"tag": "USERNAME",
"value": "programmfabrik"
},
{
"context": "pload\n\t__registerEvents: (type) ->\n\t\tkeys = [\n\t\t\t\"loadStart\"\n\t\t\t\"progress\"\n\t\t\t\"abort\"\n\t\t\t\"error\"\n\t\t\t\"load\"\n\t\t",
"end": 2148,
"score": 0.8074697256088257,
"start": 2139,
"tag": "KEY",
"value": "loadStart"
},
{
"context": "erEvents: (type) ->\n\t\tkeys = [\n\t\t\t\"loadStart\"\n\t\t\t\"progress\"\n\t\t\t\"abort\"\n\t\t\t\"error\"\n\t\t\t\"load\"\n\t\t\t\"loadend\"\n\t\t\t",
"end": 2162,
"score": 0.6800362467765808,
"start": 2154,
"tag": "KEY",
"value": "progress"
},
{
"context": "load\"\n\t\t\txhr = @__xhr.upload\n\t\telse\n\t\t\tkeys.push(\"readyStateChange\")\n\t\t\txhr = @__xhr\n\n\t\tfor k in keys\n\t\t\tfn = \"__\"+t",
"end": 2308,
"score": 0.794954776763916,
"start": 2292,
"tag": "KEY",
"value": "readyStateChange"
}
] | src/base/XHR/XHR.coffee | programmfabrik/coffeescript-ui | 10 | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
class CUI.XHR extends CUI.Element
getGroup: ->
"Core"
initOpts: ->
super()
@addOpts
method:
mandatory: true
default: "GET"
check: ["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"]
url:
mandatory: true
check: String
check: (v) ->
v.trim().length > 0
user:
check: String
password:
check: String
responseType:
mandatory: true
default: "json"
check: ["", "text", "json", "blob", "arraybuffer"]
timeout:
check: (v) ->
v >= 0
form:
check: "PlainObject"
url_data:
check: "PlainObject"
body: {}
json_data: {} # can be anything
json_pretty:
default: false
check: (v) ->
v == false or v == true or CUI.util.isString(v)
headers:
mandatory: true
default: {}
check: "PlainObject"
withCredentials:
mandatory: true
default: false
check: Boolean
@
@readyStates:
0: "UNSENT"
1: "OPENED"
2: "HEADERS_RECEIVED"
3: "LOADING"
4: "DONE"
@statusText:
"-1": "abort"
"-2": "timeout"
"-3": "network_failure"
readOpts: ->
super()
@__xhr = new XMLHttpRequest()
@__xhr.withCredentials = @_withCredentials
# console.debug "XHR.readOpts", @
@__readyStatesSeen = [@readyState()]
@__registerEvents("download")
@__registerEvents("upload")
@__headers = {}
for k, v of @_headers
@__headers[k.toLowerCase()] = v
if @_form
if not @opts.method
@_method = "POST"
if @_url_data
@__url = CUI.appendToUrl(@_url, @_url_data)
else
@__url = @_url
set = 0
if @_form
set = set + 1
if @_json_data
set = set + 1
if @__headers['content-type'] == undefined
@__headers['content-type'] = 'application/json; charset=utf-8'
if @_body
set = set + 1
CUI.util.assert(set <= 1, "new CUI.XHR", "opts.form, opts.json_data, opts.body are mutually exclusive.")
@
# type: xhr / upload
__registerEvents: (type) ->
keys = [
"loadStart"
"progress"
"abort"
"error"
"load"
"loadend"
"timeout"
]
if type == "upload"
xhr = @__xhr.upload
else
keys.push("readyStateChange")
xhr = @__xhr
for k in keys
fn = "__"+type+"_"+k
if not @[fn]
continue
do (fn, k) =>
# console.debug "register", type, k, fn
xhr.addEventListener k.toLowerCase(), (ev) =>
# console.debug ev.type, type # , ev
@[fn](ev)
@
__setStatus: (@__status) ->
@__xhr.CUI_status = @__status
@__xhr.CUI_statusText = @statusText()
__download_abort: ->
@__setStatus(-1)
# console.warn("Aborted:", @__readyStatesSeen, @)
__download_timeout: ->
@__setStatus(-2)
# console.warn("Timeout:", @__readyStatesSeen, @)
__download_loadend: ->
# console.info("Loadend:", @__readyStatesSeen, @__status, @status())
if @isSuccess()
@__dfr.resolve(@response(), @status(), @statusText())
else
if not @status() and not @__status
# check ready states if we can determine a pseudo status
@__setStatus(-3)
console.debug("XHR.__download_loadend", @getXHR())
@__dfr.reject(@response(), @status(), @statusText())
@
__download_readyStateChange: ->
CUI.util.pushOntoArray(@readyState(), @__readyStatesSeen)
__progress: (ev, type) ->
if @readyState() == "DONE"
return
loaded = ev.loaded
total = ev.total
if ev.lengthComputable
percent = Math.floor(loaded / total * 100)
else
percent = -1
@__dfr.notify(type, loaded, total, percent)
@
__upload_progress: (ev) ->
@__progress(ev, "upload")
__download_progress: (ev) ->
@__progress(ev, "download")
abort: ->
@__xhr.abort()
isSuccess: ->
if @__url.startsWith("file:///") and @__readyStatesSeen.join(",") == "UNSENT,OPENED,HEADERS_RECEIVED,LOADING,DONE"
true
else
@__xhr.status >= 200 and @__xhr.status < 300 or @__xhr.status == 304
status: ->
if @__status < 0
@__status
else
@__xhr.status
statusText: ->
if @__status < 0
CUI.XHR.statusText[@__status+""]
else
@__xhr.statusText
response: ->
if @_responseType == "json" and @__xhr.responseType == ""
# Internet Explorer needs some help here
try
res = JSON.parse(@__xhr.response)
catch e
res = @__xhr.response
else
res = @__xhr.response
if @_responseType == "json"
# be more compatible with jQuery
@__xhr.responseJSON = res
res
start: ->
@__xhr.open(@_method, @__url, true, @_user, @_password)
for k, v of @__headers
@__xhr.setRequestHeader(k, v)
@__xhr.responseType = @_responseType
@__xhr.timeout = @_timeout
# console.debug "URL:", @__xhr.responseType, @__url, @_form, @_json_data
if @_form
data = new FormData()
for k, v of @_form
data.append(k, v)
send_data = data
# let the browser set the content-type
else if @_json_data
if @_json_pretty
if @_json_pretty == true
send_data = JSON.stringify(@_json_data, null, "\t")
else
send_data = JSON.stringify(@_json_data, null, @_json_pretty)
else
send_data = JSON.stringify(@_json_data)
else if @_body
send_data = @_body
else
send_data = undefined
@__dfr = new CUI.Deferred()
@__xhr.send(send_data)
# console.debug @__xhr, @getAllResponseHeaders()
@__dfr.promise()
getXHR: ->
@__xhr
getAllResponseHeaders: ->
headers = []
for header in @__xhr.getAllResponseHeaders().split("\r\n")
if header.trim().length == 0
continue
headers.push(header)
headers
getResponseHeaders: ->
map = {}
for header in @getAllResponseHeaders()
match = header.match(/^(.*?): (.*)$/)
key = match[1].toLowerCase()
if not map[key]
map[key] = []
map[key].push(match[2])
map
getResponseHeader: (key) ->
@getResponseHeaders()[key.toLowerCase()]?[0]
readyState: ->
CUI.XHR.readyStates[@__xhr.readyState]
| 9156 | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
class CUI.XHR extends CUI.Element
getGroup: ->
"Core"
initOpts: ->
super()
@addOpts
method:
mandatory: true
default: "GET"
check: ["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"]
url:
mandatory: true
check: String
check: (v) ->
v.trim().length > 0
user:
check: String
password:
check: String
responseType:
mandatory: true
default: "json"
check: ["", "text", "json", "blob", "arraybuffer"]
timeout:
check: (v) ->
v >= 0
form:
check: "PlainObject"
url_data:
check: "PlainObject"
body: {}
json_data: {} # can be anything
json_pretty:
default: false
check: (v) ->
v == false or v == true or CUI.util.isString(v)
headers:
mandatory: true
default: {}
check: "PlainObject"
withCredentials:
mandatory: true
default: false
check: Boolean
@
@readyStates:
0: "UNSENT"
1: "OPENED"
2: "HEADERS_RECEIVED"
3: "LOADING"
4: "DONE"
@statusText:
"-1": "abort"
"-2": "timeout"
"-3": "network_failure"
readOpts: ->
super()
@__xhr = new XMLHttpRequest()
@__xhr.withCredentials = @_withCredentials
# console.debug "XHR.readOpts", @
@__readyStatesSeen = [@readyState()]
@__registerEvents("download")
@__registerEvents("upload")
@__headers = {}
for k, v of @_headers
@__headers[k.toLowerCase()] = v
if @_form
if not @opts.method
@_method = "POST"
if @_url_data
@__url = CUI.appendToUrl(@_url, @_url_data)
else
@__url = @_url
set = 0
if @_form
set = set + 1
if @_json_data
set = set + 1
if @__headers['content-type'] == undefined
@__headers['content-type'] = 'application/json; charset=utf-8'
if @_body
set = set + 1
CUI.util.assert(set <= 1, "new CUI.XHR", "opts.form, opts.json_data, opts.body are mutually exclusive.")
@
# type: xhr / upload
__registerEvents: (type) ->
keys = [
"<KEY>"
"<KEY>"
"abort"
"error"
"load"
"loadend"
"timeout"
]
if type == "upload"
xhr = @__xhr.upload
else
keys.push("<KEY>")
xhr = @__xhr
for k in keys
fn = "__"+type+"_"+k
if not @[fn]
continue
do (fn, k) =>
# console.debug "register", type, k, fn
xhr.addEventListener k.toLowerCase(), (ev) =>
# console.debug ev.type, type # , ev
@[fn](ev)
@
__setStatus: (@__status) ->
@__xhr.CUI_status = @__status
@__xhr.CUI_statusText = @statusText()
__download_abort: ->
@__setStatus(-1)
# console.warn("Aborted:", @__readyStatesSeen, @)
__download_timeout: ->
@__setStatus(-2)
# console.warn("Timeout:", @__readyStatesSeen, @)
__download_loadend: ->
# console.info("Loadend:", @__readyStatesSeen, @__status, @status())
if @isSuccess()
@__dfr.resolve(@response(), @status(), @statusText())
else
if not @status() and not @__status
# check ready states if we can determine a pseudo status
@__setStatus(-3)
console.debug("XHR.__download_loadend", @getXHR())
@__dfr.reject(@response(), @status(), @statusText())
@
__download_readyStateChange: ->
CUI.util.pushOntoArray(@readyState(), @__readyStatesSeen)
__progress: (ev, type) ->
if @readyState() == "DONE"
return
loaded = ev.loaded
total = ev.total
if ev.lengthComputable
percent = Math.floor(loaded / total * 100)
else
percent = -1
@__dfr.notify(type, loaded, total, percent)
@
__upload_progress: (ev) ->
@__progress(ev, "upload")
__download_progress: (ev) ->
@__progress(ev, "download")
abort: ->
@__xhr.abort()
isSuccess: ->
if @__url.startsWith("file:///") and @__readyStatesSeen.join(",") == "UNSENT,OPENED,HEADERS_RECEIVED,LOADING,DONE"
true
else
@__xhr.status >= 200 and @__xhr.status < 300 or @__xhr.status == 304
status: ->
if @__status < 0
@__status
else
@__xhr.status
statusText: ->
if @__status < 0
CUI.XHR.statusText[@__status+""]
else
@__xhr.statusText
response: ->
if @_responseType == "json" and @__xhr.responseType == ""
# Internet Explorer needs some help here
try
res = JSON.parse(@__xhr.response)
catch e
res = @__xhr.response
else
res = @__xhr.response
if @_responseType == "json"
# be more compatible with jQuery
@__xhr.responseJSON = res
res
start: ->
@__xhr.open(@_method, @__url, true, @_user, @_password)
for k, v of @__headers
@__xhr.setRequestHeader(k, v)
@__xhr.responseType = @_responseType
@__xhr.timeout = @_timeout
# console.debug "URL:", @__xhr.responseType, @__url, @_form, @_json_data
if @_form
data = new FormData()
for k, v of @_form
data.append(k, v)
send_data = data
# let the browser set the content-type
else if @_json_data
if @_json_pretty
if @_json_pretty == true
send_data = JSON.stringify(@_json_data, null, "\t")
else
send_data = JSON.stringify(@_json_data, null, @_json_pretty)
else
send_data = JSON.stringify(@_json_data)
else if @_body
send_data = @_body
else
send_data = undefined
@__dfr = new CUI.Deferred()
@__xhr.send(send_data)
# console.debug @__xhr, @getAllResponseHeaders()
@__dfr.promise()
getXHR: ->
@__xhr
getAllResponseHeaders: ->
headers = []
for header in @__xhr.getAllResponseHeaders().split("\r\n")
if header.trim().length == 0
continue
headers.push(header)
headers
getResponseHeaders: ->
map = {}
for header in @getAllResponseHeaders()
match = header.match(/^(.*?): (.*)$/)
key = match[1].toLowerCase()
if not map[key]
map[key] = []
map[key].push(match[2])
map
getResponseHeader: (key) ->
@getResponseHeaders()[key.toLowerCase()]?[0]
readyState: ->
CUI.XHR.readyStates[@__xhr.readyState]
| true | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
class CUI.XHR extends CUI.Element
getGroup: ->
"Core"
initOpts: ->
super()
@addOpts
method:
mandatory: true
default: "GET"
check: ["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"]
url:
mandatory: true
check: String
check: (v) ->
v.trim().length > 0
user:
check: String
password:
check: String
responseType:
mandatory: true
default: "json"
check: ["", "text", "json", "blob", "arraybuffer"]
timeout:
check: (v) ->
v >= 0
form:
check: "PlainObject"
url_data:
check: "PlainObject"
body: {}
json_data: {} # can be anything
json_pretty:
default: false
check: (v) ->
v == false or v == true or CUI.util.isString(v)
headers:
mandatory: true
default: {}
check: "PlainObject"
withCredentials:
mandatory: true
default: false
check: Boolean
@
@readyStates:
0: "UNSENT"
1: "OPENED"
2: "HEADERS_RECEIVED"
3: "LOADING"
4: "DONE"
@statusText:
"-1": "abort"
"-2": "timeout"
"-3": "network_failure"
readOpts: ->
super()
@__xhr = new XMLHttpRequest()
@__xhr.withCredentials = @_withCredentials
# console.debug "XHR.readOpts", @
@__readyStatesSeen = [@readyState()]
@__registerEvents("download")
@__registerEvents("upload")
@__headers = {}
for k, v of @_headers
@__headers[k.toLowerCase()] = v
if @_form
if not @opts.method
@_method = "POST"
if @_url_data
@__url = CUI.appendToUrl(@_url, @_url_data)
else
@__url = @_url
set = 0
if @_form
set = set + 1
if @_json_data
set = set + 1
if @__headers['content-type'] == undefined
@__headers['content-type'] = 'application/json; charset=utf-8'
if @_body
set = set + 1
CUI.util.assert(set <= 1, "new CUI.XHR", "opts.form, opts.json_data, opts.body are mutually exclusive.")
@
# type: xhr / upload
__registerEvents: (type) ->
keys = [
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"abort"
"error"
"load"
"loadend"
"timeout"
]
if type == "upload"
xhr = @__xhr.upload
else
keys.push("PI:KEY:<KEY>END_PI")
xhr = @__xhr
for k in keys
fn = "__"+type+"_"+k
if not @[fn]
continue
do (fn, k) =>
# console.debug "register", type, k, fn
xhr.addEventListener k.toLowerCase(), (ev) =>
# console.debug ev.type, type # , ev
@[fn](ev)
@
__setStatus: (@__status) ->
@__xhr.CUI_status = @__status
@__xhr.CUI_statusText = @statusText()
__download_abort: ->
@__setStatus(-1)
# console.warn("Aborted:", @__readyStatesSeen, @)
__download_timeout: ->
@__setStatus(-2)
# console.warn("Timeout:", @__readyStatesSeen, @)
__download_loadend: ->
# console.info("Loadend:", @__readyStatesSeen, @__status, @status())
if @isSuccess()
@__dfr.resolve(@response(), @status(), @statusText())
else
if not @status() and not @__status
# check ready states if we can determine a pseudo status
@__setStatus(-3)
console.debug("XHR.__download_loadend", @getXHR())
@__dfr.reject(@response(), @status(), @statusText())
@
__download_readyStateChange: ->
CUI.util.pushOntoArray(@readyState(), @__readyStatesSeen)
__progress: (ev, type) ->
if @readyState() == "DONE"
return
loaded = ev.loaded
total = ev.total
if ev.lengthComputable
percent = Math.floor(loaded / total * 100)
else
percent = -1
@__dfr.notify(type, loaded, total, percent)
@
__upload_progress: (ev) ->
@__progress(ev, "upload")
__download_progress: (ev) ->
@__progress(ev, "download")
abort: ->
@__xhr.abort()
isSuccess: ->
if @__url.startsWith("file:///") and @__readyStatesSeen.join(",") == "UNSENT,OPENED,HEADERS_RECEIVED,LOADING,DONE"
true
else
@__xhr.status >= 200 and @__xhr.status < 300 or @__xhr.status == 304
status: ->
if @__status < 0
@__status
else
@__xhr.status
statusText: ->
if @__status < 0
CUI.XHR.statusText[@__status+""]
else
@__xhr.statusText
response: ->
if @_responseType == "json" and @__xhr.responseType == ""
# Internet Explorer needs some help here
try
res = JSON.parse(@__xhr.response)
catch e
res = @__xhr.response
else
res = @__xhr.response
if @_responseType == "json"
# be more compatible with jQuery
@__xhr.responseJSON = res
res
start: ->
@__xhr.open(@_method, @__url, true, @_user, @_password)
for k, v of @__headers
@__xhr.setRequestHeader(k, v)
@__xhr.responseType = @_responseType
@__xhr.timeout = @_timeout
# console.debug "URL:", @__xhr.responseType, @__url, @_form, @_json_data
if @_form
data = new FormData()
for k, v of @_form
data.append(k, v)
send_data = data
# let the browser set the content-type
else if @_json_data
if @_json_pretty
if @_json_pretty == true
send_data = JSON.stringify(@_json_data, null, "\t")
else
send_data = JSON.stringify(@_json_data, null, @_json_pretty)
else
send_data = JSON.stringify(@_json_data)
else if @_body
send_data = @_body
else
send_data = undefined
@__dfr = new CUI.Deferred()
@__xhr.send(send_data)
# console.debug @__xhr, @getAllResponseHeaders()
@__dfr.promise()
getXHR: ->
@__xhr
getAllResponseHeaders: ->
headers = []
for header in @__xhr.getAllResponseHeaders().split("\r\n")
if header.trim().length == 0
continue
headers.push(header)
headers
getResponseHeaders: ->
map = {}
for header in @getAllResponseHeaders()
match = header.match(/^(.*?): (.*)$/)
key = match[1].toLowerCase()
if not map[key]
map[key] = []
map[key].push(match[2])
map
getResponseHeader: (key) ->
@getResponseHeaders()[key.toLowerCase()]?[0]
readyState: ->
CUI.XHR.readyStates[@__xhr.readyState]
|
[
{
"context": "tmq-node-js-mqtt-and-amqp/\n\nurl = 'amqp://meshblu:some-random-development-password@octoblu.dev:5672/mqtt'\n\nconnection = amqp.createConnection({ ",
"end": 340,
"score": 0.8884672522544861,
"start": 296,
"tag": "EMAIL",
"value": "some-random-development-password@octoblu.dev"
}
] | test.coffee | octoblu/meshblu-core-worker-mqtt | 0 | amqp = require 'amqp'
debug = require('debug')('meshblu-core-worker-amqp:worker')
RedisPooledJobManager = require 'meshblu-core-redis-pooled-job-manager'
#http://blog.airasoul.io/the-internet-of-things-with-rabbitmq-node-js-mqtt-and-amqp/
url = 'amqp://meshblu:some-random-development-password@octoblu.dev:5672/mqtt'
connection = amqp.createConnection({ url: url }, defaultExchangeName: 'amq.topic')
connection.on 'ready', ->
console.log 'ready'
connection.queue 'meshblu.queue', {
durable: true
autoDelete: false
}, attachMeshbluQueue
attachMeshbluQueue = (q) ->
console.log 'queue connected'
q.bind 'meshblu.request'
q.bind 'meshblu.cache-auth'
q.bind 'meshblu.reply-to'
q.subscribe {
ack: true
prefetchCount: 1
}, (message, headers, deliveryInfo, messageObject) ->
console.log 'received message', message.data.toString()
msg = JSON.parse message.data
replyTo = msg.jobInfo.replyTo
console.log {deliveryInfo}
connection.publish(replyTo, {
callbackId: msg.jobInfo.callbackId
data: {'hello':'world'}
}) if replyTo?
q.shift()
| 51120 | amqp = require 'amqp'
debug = require('debug')('meshblu-core-worker-amqp:worker')
RedisPooledJobManager = require 'meshblu-core-redis-pooled-job-manager'
#http://blog.airasoul.io/the-internet-of-things-with-rabbitmq-node-js-mqtt-and-amqp/
url = 'amqp://meshblu:<EMAIL>:5672/mqtt'
connection = amqp.createConnection({ url: url }, defaultExchangeName: 'amq.topic')
connection.on 'ready', ->
console.log 'ready'
connection.queue 'meshblu.queue', {
durable: true
autoDelete: false
}, attachMeshbluQueue
attachMeshbluQueue = (q) ->
console.log 'queue connected'
q.bind 'meshblu.request'
q.bind 'meshblu.cache-auth'
q.bind 'meshblu.reply-to'
q.subscribe {
ack: true
prefetchCount: 1
}, (message, headers, deliveryInfo, messageObject) ->
console.log 'received message', message.data.toString()
msg = JSON.parse message.data
replyTo = msg.jobInfo.replyTo
console.log {deliveryInfo}
connection.publish(replyTo, {
callbackId: msg.jobInfo.callbackId
data: {'hello':'world'}
}) if replyTo?
q.shift()
| true | amqp = require 'amqp'
debug = require('debug')('meshblu-core-worker-amqp:worker')
RedisPooledJobManager = require 'meshblu-core-redis-pooled-job-manager'
#http://blog.airasoul.io/the-internet-of-things-with-rabbitmq-node-js-mqtt-and-amqp/
url = 'amqp://meshblu:PI:EMAIL:<EMAIL>END_PI:5672/mqtt'
connection = amqp.createConnection({ url: url }, defaultExchangeName: 'amq.topic')
connection.on 'ready', ->
console.log 'ready'
connection.queue 'meshblu.queue', {
durable: true
autoDelete: false
}, attachMeshbluQueue
attachMeshbluQueue = (q) ->
console.log 'queue connected'
q.bind 'meshblu.request'
q.bind 'meshblu.cache-auth'
q.bind 'meshblu.reply-to'
q.subscribe {
ack: true
prefetchCount: 1
}, (message, headers, deliveryInfo, messageObject) ->
console.log 'received message', message.data.toString()
msg = JSON.parse message.data
replyTo = msg.jobInfo.replyTo
console.log {deliveryInfo}
connection.publish(replyTo, {
callbackId: msg.jobInfo.callbackId
data: {'hello':'world'}
}) if replyTo?
q.shift()
|
[
{
"context": "d see what answers'\n version: '0.2'\n authors: ['Tunnecino @ ignitae.com']",
"end": 1238,
"score": 0.9795308709144592,
"start": 1229,
"tag": "USERNAME",
"value": "Tunnecino"
},
{
"context": "answers'\n version: '0.2'\n authors: ['Tunnecino @ ignitae.com']",
"end": 1252,
"score": 0.9989809989929199,
"start": 1241,
"tag": "EMAIL",
"value": "ignitae.com"
}
] | plugins/eightball.coffee | Arrogance/nerdobot | 1 |
answers = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes – definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy, try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"
]
module.exports = ->
@addCommand '8ball',
description: 'Ask something to the 8Ball and see what answers',
help: 'Play with the black ball as a children'
(from, message, channel) =>
if not channel?
@notice from, 'This command only works in channels'
return
banner = (message) =>
"#{@color 'black'}The #{@BOLD}8-Ball#{@RESET} #{message}"
if not message?
@say channel, banner 'can\'t answer to the silence, moron...'
return
answer = answers[Math.floor(Math.random()*answers.length)];
@say channel,
banner "#{@color 'black'}answers... #{@BOLD}#{answer}#{@RESET}"
name: '8Ball Game'
description: 'Ask something to the 8Ball and see what answers'
version: '0.2'
authors: ['Tunnecino @ ignitae.com'] | 161719 |
answers = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes – definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy, try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"
]
module.exports = ->
@addCommand '8ball',
description: 'Ask something to the 8Ball and see what answers',
help: 'Play with the black ball as a children'
(from, message, channel) =>
if not channel?
@notice from, 'This command only works in channels'
return
banner = (message) =>
"#{@color 'black'}The #{@BOLD}8-Ball#{@RESET} #{message}"
if not message?
@say channel, banner 'can\'t answer to the silence, moron...'
return
answer = answers[Math.floor(Math.random()*answers.length)];
@say channel,
banner "#{@color 'black'}answers... #{@BOLD}#{answer}#{@RESET}"
name: '8Ball Game'
description: 'Ask something to the 8Ball and see what answers'
version: '0.2'
authors: ['Tunnecino @ <EMAIL>'] | true |
answers = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes – definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy, try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful"
]
module.exports = ->
@addCommand '8ball',
description: 'Ask something to the 8Ball and see what answers',
help: 'Play with the black ball as a children'
(from, message, channel) =>
if not channel?
@notice from, 'This command only works in channels'
return
banner = (message) =>
"#{@color 'black'}The #{@BOLD}8-Ball#{@RESET} #{message}"
if not message?
@say channel, banner 'can\'t answer to the silence, moron...'
return
answer = answers[Math.floor(Math.random()*answers.length)];
@say channel,
banner "#{@color 'black'}answers... #{@BOLD}#{answer}#{@RESET}"
name: '8Ball Game'
description: 'Ask something to the 8Ball and see what answers'
version: '0.2'
authors: ['Tunnecino @ PI:EMAIL:<EMAIL>END_PI'] |
[
{
"context": "dev =\n name: \"localhost\",\n imdoneKeyA: 'NjbOJJ42rA4zdkEE8gs-D_USeA-_iUa9tpZLOFwKcGEh9PymSSP9zw=='\n imdoneKeyB: 'ZHpAmF5D8S_7lVuDNP--hgJGncY='\n pu",
"end": 99,
"score": 0.9997687935829163,
"start": 42,
"tag": "KEY",
"value": "NjbOJJ42rA4zdkEE8gs-D_USeA-_iUa9tpZLOFwKcGEh9PymSSP9zw=='"
},
{
"context": "SeA-_iUa9tpZLOFwKcGEh9PymSSP9zw=='\n imdoneKeyB: 'ZHpAmF5D8S_7lVuDNP--hgJGncY='\n pusherKey: '64354707585286cfe58f'\n pusherChan",
"end": 144,
"score": 0.9997471570968628,
"start": 115,
"tag": "KEY",
"value": "ZHpAmF5D8S_7lVuDNP--hgJGncY='"
},
{
"context": "yB: 'ZHpAmF5D8S_7lVuDNP--hgJGncY='\n pusherKey: '64354707585286cfe58f'\n pusherChannelPrefix: 'private-imdoneio-dev'\n ",
"end": 180,
"score": 0.9996935725212097,
"start": 160,
"tag": "KEY",
"value": "64354707585286cfe58f"
},
{
"context": "'\n\nbeta =\n name: 'beta.imdone.io'\n imdoneKeyA: 'WFuE-QDFbrN5lip0gdHyYAdXDMdZPerXFey02k93dn-HOYJXoAAdBA=='\n imdoneKeyB: 'ALnfTYYEtghJBailJ1n-7tx4hIo='\n pu",
"end": 368,
"score": 0.9997777938842773,
"start": 311,
"tag": "KEY",
"value": "WFuE-QDFbrN5lip0gdHyYAdXDMdZPerXFey02k93dn-HOYJXoAAdBA=='"
},
{
"context": "XDMdZPerXFey02k93dn-HOYJXoAAdBA=='\n imdoneKeyB: 'ALnfTYYEtghJBailJ1n-7tx4hIo='\n pusherKey: '0a4f9a6c45def222ab08'\n pusherChan",
"end": 413,
"score": 0.999760091304779,
"start": 384,
"tag": "KEY",
"value": "ALnfTYYEtghJBailJ1n-7tx4hIo='"
},
{
"context": "yB: 'ALnfTYYEtghJBailJ1n-7tx4hIo='\n pusherKey: '0a4f9a6c45def222ab08'\n pusherChannelPrefix: 'private-imdoneio-beta'\n ",
"end": 449,
"score": 0.9997615814208984,
"start": 429,
"tag": "KEY",
"value": "0a4f9a6c45def222ab08"
},
{
"context": "1 id:11\nprod =\n name: 'imdone.io'\n imdoneKeyA: 'X8aukodrNNHKGkMKGhtcU8lI4KvNdMxCkYUiKOjh3JjH1-zj0qIDPA=='\n imdoneKeyB: '7Bo_oUdtzJxeFhdnGrrVrtGHTy8='\n pu",
"end": 695,
"score": 0.9997800588607788,
"start": 638,
"tag": "KEY",
"value": "X8aukodrNNHKGkMKGhtcU8lI4KvNdMxCkYUiKOjh3JjH1-zj0qIDPA=='"
},
{
"context": "I4KvNdMxCkYUiKOjh3JjH1-zj0qIDPA=='\n imdoneKeyB: '7Bo_oUdtzJxeFhdnGrrVrtGHTy8='\n pusherKey: 'ba1f2dde238cb1f5944e'\n baseUrl: ",
"end": 740,
"score": 0.999760627746582,
"start": 711,
"tag": "KEY",
"value": "7Bo_oUdtzJxeFhdnGrrVrtGHTy8='"
},
{
"context": "yB: '7Bo_oUdtzJxeFhdnGrrVrtGHTy8='\n pusherKey: 'ba1f2dde238cb1f5944e'\n baseUrl: 'https://imdone.io'\n pusherChanne",
"end": 776,
"score": 0.9997574687004089,
"start": 756,
"tag": "KEY",
"value": "ba1f2dde238cb1f5944e"
}
] | config/index.coffee | robbynshaw/imdone-atom | 0 | dev =
name: "localhost",
imdoneKeyA: 'NjbOJJ42rA4zdkEE8gs-D_USeA-_iUa9tpZLOFwKcGEh9PymSSP9zw=='
imdoneKeyB: 'ZHpAmF5D8S_7lVuDNP--hgJGncY='
pusherKey: '64354707585286cfe58f'
pusherChannelPrefix: 'private-imdoneio-dev'
baseUrl: 'http://localhost:3000'
beta =
name: 'beta.imdone.io'
imdoneKeyA: 'WFuE-QDFbrN5lip0gdHyYAdXDMdZPerXFey02k93dn-HOYJXoAAdBA=='
imdoneKeyB: 'ALnfTYYEtghJBailJ1n-7tx4hIo='
pusherKey: '0a4f9a6c45def222ab08'
pusherChannelPrefix: 'private-imdoneio-beta'
baseUrl: 'https://beta.imdone.io'
# DONE: Change these prior to release +chore gh:161 id:11
prod =
name: 'imdone.io'
imdoneKeyA: 'X8aukodrNNHKGkMKGhtcU8lI4KvNdMxCkYUiKOjh3JjH1-zj0qIDPA=='
imdoneKeyB: '7Bo_oUdtzJxeFhdnGrrVrtGHTy8='
pusherKey: 'ba1f2dde238cb1f5944e'
baseUrl: 'https://imdone.io'
pusherChannelPrefix: 'private-imdoneio'
module.exports = prod;
# DONE: Merge imdone-atom-beta with imdone-atom and publish +chore gh:162 id:12
| 1457 | dev =
name: "localhost",
imdoneKeyA: '<KEY>
imdoneKeyB: '<KEY>
pusherKey: '<KEY>'
pusherChannelPrefix: 'private-imdoneio-dev'
baseUrl: 'http://localhost:3000'
beta =
name: 'beta.imdone.io'
imdoneKeyA: '<KEY>
imdoneKeyB: '<KEY>
pusherKey: '<KEY>'
pusherChannelPrefix: 'private-imdoneio-beta'
baseUrl: 'https://beta.imdone.io'
# DONE: Change these prior to release +chore gh:161 id:11
prod =
name: 'imdone.io'
imdoneKeyA: '<KEY>
imdoneKeyB: '<KEY>
pusherKey: '<KEY>'
baseUrl: 'https://imdone.io'
pusherChannelPrefix: 'private-imdoneio'
module.exports = prod;
# DONE: Merge imdone-atom-beta with imdone-atom and publish +chore gh:162 id:12
| true | dev =
name: "localhost",
imdoneKeyA: 'PI:KEY:<KEY>END_PI
imdoneKeyB: 'PI:KEY:<KEY>END_PI
pusherKey: 'PI:KEY:<KEY>END_PI'
pusherChannelPrefix: 'private-imdoneio-dev'
baseUrl: 'http://localhost:3000'
beta =
name: 'beta.imdone.io'
imdoneKeyA: 'PI:KEY:<KEY>END_PI
imdoneKeyB: 'PI:KEY:<KEY>END_PI
pusherKey: 'PI:KEY:<KEY>END_PI'
pusherChannelPrefix: 'private-imdoneio-beta'
baseUrl: 'https://beta.imdone.io'
# DONE: Change these prior to release +chore gh:161 id:11
prod =
name: 'imdone.io'
imdoneKeyA: 'PI:KEY:<KEY>END_PI
imdoneKeyB: 'PI:KEY:<KEY>END_PI
pusherKey: 'PI:KEY:<KEY>END_PI'
baseUrl: 'https://imdone.io'
pusherChannelPrefix: 'private-imdoneio'
module.exports = prod;
# DONE: Merge imdone-atom-beta with imdone-atom and publish +chore gh:162 id:12
|
[
{
"context": " requestkey: requestKey\n username: user\n password: user\n else\n ",
"end": 4008,
"score": 0.9941661357879639,
"start": 4004,
"tag": "USERNAME",
"value": "user"
},
{
"context": "y\n username: user\n password: user\n else\n throw Error(\"Error while r",
"end": 4035,
"score": 0.9992327690124512,
"start": 4031,
"tag": "PASSWORD",
"value": "user"
},
{
"context": "p://frisbyjs.com/docs/api/ and https://github.com/vlucas/frisby/blob/master/lib/frisby.js\n # for complete",
"end": 4836,
"score": 0.8784405589103699,
"start": 4830,
"tag": "USERNAME",
"value": "vlucas"
},
{
"context": "orm the request as logged in user user\n withUser: (@_user) -> @\n # Simulates an AJAX request\n withAJAX: -",
"end": 6874,
"score": 0.9985742568969727,
"start": 6867,
"tag": "USERNAME",
"value": "(@_user"
}
] | tests/api/utils.coffee | christophetd/courseadvisor | 19 | ###
api/utils.coffee
Utilities framework for API testing. This file must be required by all test files.
###
# Dependencies
frisby = require 'frisby'
request = require 'request'
Q = require 'q'
shared = require '../utils-shared.coffee'
# Sets up global parameters
Q.longStackSupport = true
frisby.globalSetup
request:
headers: {}
timeout: 30000
# Entry point
{fail} = utils = module.exports =
###
# Aborts the test case immediately for some `reason`
###
fail: (reason) -> expect("Test aborted. Reason: #{reason}").toBeUndefined()
###
# Starts a new test case definition.
# see @TestCaseBuilder
###
test: (desc) -> new TestCaseBuilder({_desc: desc}, ROOT_BUILDER)
# Extends common utilities (see ../utils-shared.coffee)
shared.extend(utils, shared)
###
# private
# Session represents an HTTP navigation session with persistent cookie jar.
#
# @request is a request object bound to the session. Use @get and @post for promisified
# get and post requests.
#
# see also:
# https://github.com/request/request
###
class Session
constructor: ->
# request object bound to the session
@request = request.defaults jar: request.jar()
# promise for get request on this session
@get = Q.denodeify @request
# promise for post request on this session
@post = Q.denodeify @request.post
# csrf token associated with this session
@csrf = null
###
# private
# SessionStore is used for caching sessions.
# This saves the cost of fetching CSRF tokens and logging users in.
# Sessions are cached per user (seems to work with the way laravel generates csrf tokens).
###
SessionStore =
# Returns a promise holding a Session object appropriate for the provided test
# Concretely, sessions are bound to users.
getSessionForTestCase: (test) ->
params = test.getParams()
if !params.user?
Q.Promise (resolve) => resolve(@getDefaultSession())
else if @hasUserSession(params.user)
Q.Promise (resolve) => resolve(@getUserSession(params.user))
else
session = new Session()
Q.Promise (resolve) -> resolve(null)
.then => @_authenticate(session, params.user) if params.user?
.then => @_getCSRF(session)
.then => @_store[params.user] = session
# Returns the session for unauthenticated navigation
getDefaultSession: ->
Q.Promise (resolve) => resolve(@_defaultSession)
.then (session) =>
if !session?
session = new Session()
@_getCSRF(session).then -> session
else
session
.then (session) => @_defaultSession = session
# Returns true if the store already holds a session for that user
hasUserSession: (user) -> @_store[user]?
# Returns the session associated to that user or undefined if it doesn't exist
getUserSession: (user) -> @_store[user]
# Actual store
_defaultSession: null
_store: {}
# Returns a promise populating the session's csrf token.
# session.csrf is set to the csrf token before the promise resolves but the
# resolved value is undefined
_getCSRF: (session) ->
session.get url: utils.url('/api/csrf_token')
.then ([res]) ->
if res.statusCode != 200 then throw Error("Bad response from /api/csrf_token. Status: #{res.statusCode}")
if !(matches = res.body.match(/TOKEN = (\w+)/i))? then throw Error("Bad response from /api/csrf_token. Body: #{res.body}")
session.csrf = matches[1]
# Authenticates the provided session with the provided user in a promise.
# The promise's resolved value is undefined.
_authenticate: (session, user) ->
session.get url: utils.url('/en/login'), followRedirect: false
.then ([res]) ->
if (res.statusCode == 307 || res.statusCode == 302)
location = res.headers['location']
requestKey = location.split('=')[1];
base = location.substr(0, location.lastIndexOf('/'))
session.post url: "#{base}/login", followRedirect: false, form:
requestkey: requestKey
username: user
password: user
else
throw Error("Error while requesting login page. Status is #{res.statusCode}")
.then ([res]) ->
if (res.statusCode == 307 || res.statusCode == 302)
session.get url: res.headers['location']
else
throw Error("Invalid status code: #{res.statusCode} on /login response")
###
# Test case with fixed parameters. Ensures some boilerplate parameters
# for running frisby tests
###
class TestCase
constructor: ({@_user, @_url, @_desc, @_reqParams, @_useCSRF, @_useAJAX}) ->
# Executes cb passing a prepared frisby as only argument
# The frisby can be used normally according to the official doc.
# All boilerplate options specified in the test case are taken care of.
# see http://frisbyjs.com/docs/api/ and https://github.com/vlucas/frisby/blob/master/lib/frisby.js
# for complete documentation.
is: (cb) ->
describe "test case", =>
it "should prepare #{@}", =>
done = false
runs =>
SessionStore.getSessionForTestCase @
.then @_prepareRq
.then (rq) =>
cb(rq)
return rq
.then (rq) => rq.toss()
.catch (err) -> fail("#{err} #{err.stack}")
.done -> done = true
waitsFor (-> done), "test case completion"
@
# Returns cleaned hash of this test case's parameters
getParams: ->
url: @_url
desc: @_desc
user: @_user
csrf: @_useCSRF
ajax: @_useAJAX
reqParams: @_reqParams
# Returns a human readable string of this test case's parameters
toString: -> "TestCase: " + JSON.stringify @getParams()
# Prepares a request for use in this test case
_prepareRq: (session) =>
# shallow copy parameters
params = utils.extend({}, @_reqParams)
# Expand url
url = utils.url @_url
rq = frisby.create @_desc
# extract interesting parameters
{method = 'GET', body = {}} = params
delete params.body
# Inject session request for use by frisby `rq`
if params.mock? then return fail("Cannot use the mock param.")
params.mock = session.request
# Inject CSRF body parameter
if @_useCSRF then body._token = session.csrf
# Perform actual request
method = method.toUpperCase()
rq._request.apply rq, [method].concat([url, body, params])
# Inject AJAX header to fake AJAX
if (@_useAJAX) then rq.addHeaders "X-Requested-With": "XMLHttpRequest"
return rq
###
# Builder used to prepare a frisbyjs test case with the proper session attributes.
#
# Use .on once to specify the HTTP request to test. Optionnaly use .withXXX methods
# to add more properties to the request.
###
class TestCaseBuilder
constructor: ({@_useAJAX, @_user, @_url, @_desc, @_reqParams = {}, @_useCSRF}, @_parent) ->
# Perform the request as logged in user user
withUser: (@_user) -> @
# Simulates an AJAX request
withAJAX: -> new TestCaseBuilder({_useAJAX: true}, @)
# Provides the correct CSRF token in POST|PUT|PATCH|UPDATE request as "_token" parameter
withCSRF: -> new TestCaseBuilder({_useCSRF: true}, @)
# Specifies the target request for this test case. This method has two forms:
# .on(url, reqParams)
# - url: The target url
# - reqParams: options passed to the request library
# .on( verb: url, reqParams)
# Shorthand for .on(url, {method: verb} U reqParams)
on: (url, reqParams) ->
if typeof url != 'string'
reqParams = url
for verb in ['post', 'get', 'update', 'delete', 'patch', 'put']
if reqParams[verb]?
url = reqParams[verb]
reqParams.method = verb
delete reqParams[verb]
@_url = url
@_reqParams = reqParams || {}
@
# Returns the test case built with the current parameters
build: ->
@_inheritProperties()
new TestCase(@)
# Executes cb in the context of the current TestCase
# see: @TestCase.is
is: (cb) ->
tc = @build()
tc.is(cb)
_inheritProperties: ->
if !@_parent? then return
@_parent._inheritProperties()
utils.extend(@_reqParams, @_parent._reqParams)
utils.extend(@, @_parent)
# Default values for TestCaseBuilder
ROOT_BUILDER = new TestCaseBuilder(
_useAJAX: false
_user: null
_url: null
_desc: null
_reqParams: {}
_useCSRF: false
)
| 1351 | ###
api/utils.coffee
Utilities framework for API testing. This file must be required by all test files.
###
# Dependencies
frisby = require 'frisby'
request = require 'request'
Q = require 'q'
shared = require '../utils-shared.coffee'
# Sets up global parameters
Q.longStackSupport = true
frisby.globalSetup
request:
headers: {}
timeout: 30000
# Entry point
{fail} = utils = module.exports =
###
# Aborts the test case immediately for some `reason`
###
fail: (reason) -> expect("Test aborted. Reason: #{reason}").toBeUndefined()
###
# Starts a new test case definition.
# see @TestCaseBuilder
###
test: (desc) -> new TestCaseBuilder({_desc: desc}, ROOT_BUILDER)
# Extends common utilities (see ../utils-shared.coffee)
shared.extend(utils, shared)
###
# private
# Session represents an HTTP navigation session with persistent cookie jar.
#
# @request is a request object bound to the session. Use @get and @post for promisified
# get and post requests.
#
# see also:
# https://github.com/request/request
###
class Session
constructor: ->
# request object bound to the session
@request = request.defaults jar: request.jar()
# promise for get request on this session
@get = Q.denodeify @request
# promise for post request on this session
@post = Q.denodeify @request.post
# csrf token associated with this session
@csrf = null
###
# private
# SessionStore is used for caching sessions.
# This saves the cost of fetching CSRF tokens and logging users in.
# Sessions are cached per user (seems to work with the way laravel generates csrf tokens).
###
SessionStore =
# Returns a promise holding a Session object appropriate for the provided test
# Concretely, sessions are bound to users.
getSessionForTestCase: (test) ->
params = test.getParams()
if !params.user?
Q.Promise (resolve) => resolve(@getDefaultSession())
else if @hasUserSession(params.user)
Q.Promise (resolve) => resolve(@getUserSession(params.user))
else
session = new Session()
Q.Promise (resolve) -> resolve(null)
.then => @_authenticate(session, params.user) if params.user?
.then => @_getCSRF(session)
.then => @_store[params.user] = session
# Returns the session for unauthenticated navigation
getDefaultSession: ->
Q.Promise (resolve) => resolve(@_defaultSession)
.then (session) =>
if !session?
session = new Session()
@_getCSRF(session).then -> session
else
session
.then (session) => @_defaultSession = session
# Returns true if the store already holds a session for that user
hasUserSession: (user) -> @_store[user]?
# Returns the session associated to that user or undefined if it doesn't exist
getUserSession: (user) -> @_store[user]
# Actual store
_defaultSession: null
_store: {}
# Returns a promise populating the session's csrf token.
# session.csrf is set to the csrf token before the promise resolves but the
# resolved value is undefined
_getCSRF: (session) ->
session.get url: utils.url('/api/csrf_token')
.then ([res]) ->
if res.statusCode != 200 then throw Error("Bad response from /api/csrf_token. Status: #{res.statusCode}")
if !(matches = res.body.match(/TOKEN = (\w+)/i))? then throw Error("Bad response from /api/csrf_token. Body: #{res.body}")
session.csrf = matches[1]
# Authenticates the provided session with the provided user in a promise.
# The promise's resolved value is undefined.
_authenticate: (session, user) ->
session.get url: utils.url('/en/login'), followRedirect: false
.then ([res]) ->
if (res.statusCode == 307 || res.statusCode == 302)
location = res.headers['location']
requestKey = location.split('=')[1];
base = location.substr(0, location.lastIndexOf('/'))
session.post url: "#{base}/login", followRedirect: false, form:
requestkey: requestKey
username: user
password: <PASSWORD>
else
throw Error("Error while requesting login page. Status is #{res.statusCode}")
.then ([res]) ->
if (res.statusCode == 307 || res.statusCode == 302)
session.get url: res.headers['location']
else
throw Error("Invalid status code: #{res.statusCode} on /login response")
###
# Test case with fixed parameters. Ensures some boilerplate parameters
# for running frisby tests
###
class TestCase
constructor: ({@_user, @_url, @_desc, @_reqParams, @_useCSRF, @_useAJAX}) ->
# Executes cb passing a prepared frisby as only argument
# The frisby can be used normally according to the official doc.
# All boilerplate options specified in the test case are taken care of.
# see http://frisbyjs.com/docs/api/ and https://github.com/vlucas/frisby/blob/master/lib/frisby.js
# for complete documentation.
is: (cb) ->
describe "test case", =>
it "should prepare #{@}", =>
done = false
runs =>
SessionStore.getSessionForTestCase @
.then @_prepareRq
.then (rq) =>
cb(rq)
return rq
.then (rq) => rq.toss()
.catch (err) -> fail("#{err} #{err.stack}")
.done -> done = true
waitsFor (-> done), "test case completion"
@
# Returns cleaned hash of this test case's parameters
getParams: ->
url: @_url
desc: @_desc
user: @_user
csrf: @_useCSRF
ajax: @_useAJAX
reqParams: @_reqParams
# Returns a human readable string of this test case's parameters
toString: -> "TestCase: " + JSON.stringify @getParams()
# Prepares a request for use in this test case
_prepareRq: (session) =>
# shallow copy parameters
params = utils.extend({}, @_reqParams)
# Expand url
url = utils.url @_url
rq = frisby.create @_desc
# extract interesting parameters
{method = 'GET', body = {}} = params
delete params.body
# Inject session request for use by frisby `rq`
if params.mock? then return fail("Cannot use the mock param.")
params.mock = session.request
# Inject CSRF body parameter
if @_useCSRF then body._token = session.csrf
# Perform actual request
method = method.toUpperCase()
rq._request.apply rq, [method].concat([url, body, params])
# Inject AJAX header to fake AJAX
if (@_useAJAX) then rq.addHeaders "X-Requested-With": "XMLHttpRequest"
return rq
###
# Builder used to prepare a frisbyjs test case with the proper session attributes.
#
# Use .on once to specify the HTTP request to test. Optionnaly use .withXXX methods
# to add more properties to the request.
###
class TestCaseBuilder
constructor: ({@_useAJAX, @_user, @_url, @_desc, @_reqParams = {}, @_useCSRF}, @_parent) ->
# Perform the request as logged in user user
withUser: (@_user) -> @
# Simulates an AJAX request
withAJAX: -> new TestCaseBuilder({_useAJAX: true}, @)
# Provides the correct CSRF token in POST|PUT|PATCH|UPDATE request as "_token" parameter
withCSRF: -> new TestCaseBuilder({_useCSRF: true}, @)
# Specifies the target request for this test case. This method has two forms:
# .on(url, reqParams)
# - url: The target url
# - reqParams: options passed to the request library
# .on( verb: url, reqParams)
# Shorthand for .on(url, {method: verb} U reqParams)
on: (url, reqParams) ->
if typeof url != 'string'
reqParams = url
for verb in ['post', 'get', 'update', 'delete', 'patch', 'put']
if reqParams[verb]?
url = reqParams[verb]
reqParams.method = verb
delete reqParams[verb]
@_url = url
@_reqParams = reqParams || {}
@
# Returns the test case built with the current parameters
build: ->
@_inheritProperties()
new TestCase(@)
# Executes cb in the context of the current TestCase
# see: @TestCase.is
is: (cb) ->
tc = @build()
tc.is(cb)
_inheritProperties: ->
if !@_parent? then return
@_parent._inheritProperties()
utils.extend(@_reqParams, @_parent._reqParams)
utils.extend(@, @_parent)
# Default values for TestCaseBuilder
ROOT_BUILDER = new TestCaseBuilder(
_useAJAX: false
_user: null
_url: null
_desc: null
_reqParams: {}
_useCSRF: false
)
| true | ###
api/utils.coffee
Utilities framework for API testing. This file must be required by all test files.
###
# Dependencies
frisby = require 'frisby'
request = require 'request'
Q = require 'q'
shared = require '../utils-shared.coffee'
# Sets up global parameters
Q.longStackSupport = true
frisby.globalSetup
request:
headers: {}
timeout: 30000
# Entry point
{fail} = utils = module.exports =
###
# Aborts the test case immediately for some `reason`
###
fail: (reason) -> expect("Test aborted. Reason: #{reason}").toBeUndefined()
###
# Starts a new test case definition.
# see @TestCaseBuilder
###
test: (desc) -> new TestCaseBuilder({_desc: desc}, ROOT_BUILDER)
# Extends common utilities (see ../utils-shared.coffee)
shared.extend(utils, shared)
###
# private
# Session represents an HTTP navigation session with persistent cookie jar.
#
# @request is a request object bound to the session. Use @get and @post for promisified
# get and post requests.
#
# see also:
# https://github.com/request/request
###
class Session
constructor: ->
# request object bound to the session
@request = request.defaults jar: request.jar()
# promise for get request on this session
@get = Q.denodeify @request
# promise for post request on this session
@post = Q.denodeify @request.post
# csrf token associated with this session
@csrf = null
###
# private
# SessionStore is used for caching sessions.
# This saves the cost of fetching CSRF tokens and logging users in.
# Sessions are cached per user (seems to work with the way laravel generates csrf tokens).
###
SessionStore =
# Returns a promise holding a Session object appropriate for the provided test
# Concretely, sessions are bound to users.
getSessionForTestCase: (test) ->
params = test.getParams()
if !params.user?
Q.Promise (resolve) => resolve(@getDefaultSession())
else if @hasUserSession(params.user)
Q.Promise (resolve) => resolve(@getUserSession(params.user))
else
session = new Session()
Q.Promise (resolve) -> resolve(null)
.then => @_authenticate(session, params.user) if params.user?
.then => @_getCSRF(session)
.then => @_store[params.user] = session
# Returns the session for unauthenticated navigation
getDefaultSession: ->
Q.Promise (resolve) => resolve(@_defaultSession)
.then (session) =>
if !session?
session = new Session()
@_getCSRF(session).then -> session
else
session
.then (session) => @_defaultSession = session
# Returns true if the store already holds a session for that user
hasUserSession: (user) -> @_store[user]?
# Returns the session associated to that user or undefined if it doesn't exist
getUserSession: (user) -> @_store[user]
# Actual store
_defaultSession: null
_store: {}
# Returns a promise populating the session's csrf token.
# session.csrf is set to the csrf token before the promise resolves but the
# resolved value is undefined
_getCSRF: (session) ->
session.get url: utils.url('/api/csrf_token')
.then ([res]) ->
if res.statusCode != 200 then throw Error("Bad response from /api/csrf_token. Status: #{res.statusCode}")
if !(matches = res.body.match(/TOKEN = (\w+)/i))? then throw Error("Bad response from /api/csrf_token. Body: #{res.body}")
session.csrf = matches[1]
# Authenticates the provided session with the provided user in a promise.
# The promise's resolved value is undefined.
_authenticate: (session, user) ->
session.get url: utils.url('/en/login'), followRedirect: false
.then ([res]) ->
if (res.statusCode == 307 || res.statusCode == 302)
location = res.headers['location']
requestKey = location.split('=')[1];
base = location.substr(0, location.lastIndexOf('/'))
session.post url: "#{base}/login", followRedirect: false, form:
requestkey: requestKey
username: user
password: PI:PASSWORD:<PASSWORD>END_PI
else
throw Error("Error while requesting login page. Status is #{res.statusCode}")
.then ([res]) ->
if (res.statusCode == 307 || res.statusCode == 302)
session.get url: res.headers['location']
else
throw Error("Invalid status code: #{res.statusCode} on /login response")
###
# Test case with fixed parameters. Ensures some boilerplate parameters
# for running frisby tests
###
class TestCase
constructor: ({@_user, @_url, @_desc, @_reqParams, @_useCSRF, @_useAJAX}) ->
# Executes cb passing a prepared frisby as only argument
# The frisby can be used normally according to the official doc.
# All boilerplate options specified in the test case are taken care of.
# see http://frisbyjs.com/docs/api/ and https://github.com/vlucas/frisby/blob/master/lib/frisby.js
# for complete documentation.
is: (cb) ->
describe "test case", =>
it "should prepare #{@}", =>
done = false
runs =>
SessionStore.getSessionForTestCase @
.then @_prepareRq
.then (rq) =>
cb(rq)
return rq
.then (rq) => rq.toss()
.catch (err) -> fail("#{err} #{err.stack}")
.done -> done = true
waitsFor (-> done), "test case completion"
@
# Returns cleaned hash of this test case's parameters
getParams: ->
url: @_url
desc: @_desc
user: @_user
csrf: @_useCSRF
ajax: @_useAJAX
reqParams: @_reqParams
# Returns a human readable string of this test case's parameters
toString: -> "TestCase: " + JSON.stringify @getParams()
# Prepares a request for use in this test case
_prepareRq: (session) =>
# shallow copy parameters
params = utils.extend({}, @_reqParams)
# Expand url
url = utils.url @_url
rq = frisby.create @_desc
# extract interesting parameters
{method = 'GET', body = {}} = params
delete params.body
# Inject session request for use by frisby `rq`
if params.mock? then return fail("Cannot use the mock param.")
params.mock = session.request
# Inject CSRF body parameter
if @_useCSRF then body._token = session.csrf
# Perform actual request
method = method.toUpperCase()
rq._request.apply rq, [method].concat([url, body, params])
# Inject AJAX header to fake AJAX
if (@_useAJAX) then rq.addHeaders "X-Requested-With": "XMLHttpRequest"
return rq
###
# Builder used to prepare a frisbyjs test case with the proper session attributes.
#
# Use .on once to specify the HTTP request to test. Optionnaly use .withXXX methods
# to add more properties to the request.
###
class TestCaseBuilder
constructor: ({@_useAJAX, @_user, @_url, @_desc, @_reqParams = {}, @_useCSRF}, @_parent) ->
# Perform the request as logged in user user
withUser: (@_user) -> @
# Simulates an AJAX request
withAJAX: -> new TestCaseBuilder({_useAJAX: true}, @)
# Provides the correct CSRF token in POST|PUT|PATCH|UPDATE request as "_token" parameter
withCSRF: -> new TestCaseBuilder({_useCSRF: true}, @)
# Specifies the target request for this test case. This method has two forms:
# .on(url, reqParams)
# - url: The target url
# - reqParams: options passed to the request library
# .on( verb: url, reqParams)
# Shorthand for .on(url, {method: verb} U reqParams)
on: (url, reqParams) ->
if typeof url != 'string'
reqParams = url
for verb in ['post', 'get', 'update', 'delete', 'patch', 'put']
if reqParams[verb]?
url = reqParams[verb]
reqParams.method = verb
delete reqParams[verb]
@_url = url
@_reqParams = reqParams || {}
@
# Returns the test case built with the current parameters
build: ->
@_inheritProperties()
new TestCase(@)
# Executes cb in the context of the current TestCase
# see: @TestCase.is
is: (cb) ->
tc = @build()
tc.is(cb)
_inheritProperties: ->
if !@_parent? then return
@_parent._inheritProperties()
utils.extend(@_reqParams, @_parent._reqParams)
utils.extend(@, @_parent)
# Default values for TestCaseBuilder
ROOT_BUILDER = new TestCaseBuilder(
_useAJAX: false
_user: null
_url: null
_desc: null
_reqParams: {}
_useCSRF: false
)
|
[
{
"context": "pi\n# A NodeJS interface for the Public Bitly API\n# Nathaniel Kirby <nate@projectspong.com\n# https://github.com/nkirb",
"end": 132,
"score": 0.9998870491981506,
"start": 117,
"tag": "NAME",
"value": "Nathaniel Kirby"
},
{
"context": "rface for the Public Bitly API\n# Nathaniel Kirby <nate@projectspong.com\n# https://github.com/nkirby/node-bitlyapi\n#######",
"end": 155,
"score": 0.9999333620071411,
"start": 134,
"tag": "EMAIL",
"value": "nate@projectspong.com"
},
{
"context": "Kirby <nate@projectspong.com\n# https://github.com/nkirby/node-bitlyapi\n###################################",
"end": 183,
"score": 0.9991951584815979,
"start": 177,
"tag": "USERNAME",
"value": "nkirby"
},
{
"context": "\t\tform:\n\t\t\t\t\tgrant_type: \"password\"\n\t\t\t\t\tusername: username\n\t\t\t\t\tpassword: password\n\t\t\t}\n\t\t\t(error, response,",
"end": 1523,
"score": 0.9890401363372803,
"start": 1515,
"tag": "USERNAME",
"value": "username"
},
{
"context": " \"password\"\n\t\t\t\t\tusername: username\n\t\t\t\t\tpassword: password\n\t\t\t}\n\t\t\t(error, response, body) ->\n\t\t\t\tif error\n\t",
"end": 1547,
"score": 0.9992583394050598,
"start": 1539,
"tag": "PASSWORD",
"value": "password"
}
] | src/Bitly.coffee | nkirby/node-bitlyapi | 30 | ####################################################
# node-bitlyapi
# A NodeJS interface for the Public Bitly API
# Nathaniel Kirby <nate@projectspong.com
# https://github.com/nkirby/node-bitlyapi
####################################################
btoa = require 'btoa'
request = require 'request'
querystring = require 'querystring'
class BitlyAPI
request_config:
endpoint: "https://api-ssl.bitly.com"
constructor: (@config) ->
setAccessToken: (@access_token) ->
return this
####################################################
get: (path, params = {}, callback) ->
if not params.access_token and @access_token
params.access_token = @access_token
request(
{
uri:@request_config.endpoint+path+"?"+querystring.stringify(params),
method: "GET"
}
(error, response, body) ->
if callback
callback error, body
)
####################################################
# Authentication
####################################################
# POST: /oauth/access_token
authenticate: (username, password, callback) ->
if not @config or not @config.client_id or not @config.client_secret
throw "Bitly config error: you must specify a client_id and client_secret before authenticating a user."
auth = "Basic "+btoa(@config.client_id+":"+@config.client_secret)
console.log auth
request(
{
uri:@request_config.endpoint+"/oauth/access_token"
headers:
"Authorization": auth
method: "POST"
form:
grant_type: "password"
username: username
password: password
}
(error, response, body) ->
if error
callback error, null
else
responseObj = JSON.parse(body)
callback null, responseObj.access_token
)
####################################################
# Objects
####################################################
user: (login) ->
new BitlyUser login, this
####################################################
# Helpers
####################################################
shortenLink: (link, callback) ->
@shorten {longUrl:link}, callback
####################################################
# API Calls
####################################################
####################################################
# Data APIs
# GET /v3/highvalue
getHighvalueLinks: (params, callback) ->
@get "/v3/highvalue", params, callback
####################################################
# GET /v3/search
search: (params, callback) ->
@get "/v3/search", params, callback
####################################################
# GET /v3/realtime/bursting_phrases
getRealtimeBurstingPhrases: (params, callback) ->
@get "/v3/realtime/bursting_phrases", params, callback
####################################################
# GET /v3/realtime/hot_phrases
getRealtimeHotPhrases: (params, callback) ->
@get "/v3/realtime/hot_phrases", params, callback
####################################################
# GET /v3/realtime/clickrate
getRealtimeClickrate: (params, callback) ->
@get "/v3/realtime/clickrate", params, callback
####################################################
# GET /v3/link/info
getLinkFullInfo: (params, callback) ->
@get "/v3/link/info", params, callback
####################################################
# GET /v3/link/content
getLinkContent: (params, callback) ->
@get "/v3/link/content", params, callback
####################################################
# GET /v3/link/category
getLinkCategory: (params, callback) ->
@get "/v3/link/category", params, callback
####################################################
# GET /v3/link/social
getLinkSocial: (params, callback) ->
@get "/v3/link/social", params, callback
####################################################
# GET /v3/link/location
getLinkLocation: (params, callback) ->
@get "/v3/link/location", params, callback
####################################################
# GET /v3/link/language
getLinkLanguage: (params, callback) ->
@get "/v3/link/language", params, callback
####################################################
# Links
# GET /v3/expand
expand: (params, callback) ->
@get "/v3/expand", params, callback
####################################################
# GET /v3/info
getLinkInfo: (params, callback) ->
@get "/v3/info", params, callback
####################################################
# GET /v3/link/lookup
linkLookup: (params, callback) ->
@get "/v3/link/lookup", params, callback
####################################################
# GET /v3/shorten
shorten: (params, callback) ->
@get "/v3/shorten", params, callback
####################################################
# GET /v3/user/link_edit
userEditLink: (params, callback) ->
@get "/v3/user/link_edit", params, callback
####################################################
# GET /v3/user/link_lookup
userLookupLink: (params, callback) ->
@get "/v3/user/link_lookup", params, callback
####################################################
# GET /v3/user/link_save
userSaveLink: (params, callback) ->
@get "/v3/user/link_save", params, callback
####################################################
# GET /v3/user/save_custom_domain_keyword
userSaveCustomDomainKeyword: (params, callback) ->
@get "/v3/user/save_custom_domain_keyword", params, callback
####################################################
# Link Metrics
# GET /v3/link/clicks
getLinkClicks: (params, callback) ->
@get "/v3/link/clicks", params, callback
####################################################
# GET /v3/link/countries
getLinkCountries: (params, callback) ->
@get "/v3/link/countries", params, callback
####################################################
# GET /v3/link/encoders
getLinkEncoders: (params, callback) ->
@get "/v3/link/encoders", params, callback
####################################################
# GET /v3/link/encoders_by_count
getLinkEncodersByCount: (params, callback) ->
@get "/v3/link/encoders_by_count", params, callback
####################################################
# GET /v3/link/encoders_count
getLinkEncodersCount: (params, callback) ->
@get "/v3/link/encoders_count", params, callback
####################################################
# GET /v3/link/referrers
getLinkReferrers: (params, callback) ->
@get "/v3/link/referrers", params, callback
####################################################
# GET /v3/link/referrers_by_domain
getLinkReferrersByDomain: (params, callback) ->
@get "/v3/link/referrers_by_domain", params, callback
####################################################
# GET /v3/link/referring_domains
getLinkReferringDomains: (params, callback) ->
@get "/v3/link/referring_domains", params, callback
####################################################
# GET /v3/link/shares
getLinkShares: (params, callback) ->
@get "/v3/link/shares", params, callback
####################################################
# -- User Info/History --
# GET: /v3/oauth/app
getAppInfo: (params, callback) ->
@get "/v3/oauth/app", params, callback
####################################################
# GET /v3/user/info
getUserInfo: (login, callback) ->
@get "/v3/user/info", login, callback
####################################################
# GET /v3/user/link_history
getUserLinkHistory: (params, callback) ->
@get "/v3/user/link_history", params, callback
####################################################
# GET /v3/user/network_history
getUserNetworkHistory: (params, callback) ->
@get "/v3/user/network_history", params, callback
####################################################
# GET /v3/user/tracking_domain_list
getUserTrackingDomains: (params, callback) ->
@get "/v3/user/tracking_domain_list", params, callback
####################################################
# -- User Metrics --
# GET /v3/user/clicks
getUserClicks: (params, callback) ->
@get "/v3/user/clicks", params, callback
####################################################
# GET /v3/user/countries
getUserCountries: (params, callback) ->
@get "/v3/user/countries", params, callback
####################################################
# GET /v3/user/popular_earned_by_clicks
getUserPopularEarnedByClicks: (params, callback) ->
@get "/v3/user/popular_earned_by_clicks", params, callback
####################################################
# GET /v3/user/popular_earned_by_shortens
getUserPopularEarnedByShortens: (params, callback) ->
@get "/v3/user/popular_earned_by_shortens", params, callback
####################################################
# GET /v3/user/popular_links
getUserPopularLinks: (params, callback) ->
@get "/v3/user/popular_links", params, callback
####################################################
# GET /v3/user/popular_owned_by_clicks
getUserPopularOwnedByClicks: (params, callback) ->
@get "/v3/user/popular_owned_by_clicks", params, callback
####################################################
# GET /v3/user/popular_owned_by_shortens
getUserPopularOwnedByShortens: (params, callback) ->
@get "/v3/user/popular_owned_by_shortens", params, callback
####################################################
# GET /v3/user/referrers
getUserReferrers: (params, callback) ->
@get "/v3/user/referrers", params, callback
####################################################
# GET /v3/user/referring_domains
getUserReferringDomains: (params, callback) ->
@get "/v3/user/referring_domains", params, callback
####################################################
# GET /v3/user/share_counts
getUserShareCounts: (params, callback) ->
@get "/v3/user/share_counts", params, callback
####################################################
# GET /v3/user/share_counts_by_share_type
getUserShareCountsByShareType: (params, callback) ->
@get "/v3/user/share_counts_by_share_type", params, callback
####################################################
# GET /v3/user/shorten_counts
getUserShortenCounts: (params, callback) ->
@get "/v3/user/shorten_counts", params, callback
####################################################
# -- Organization Metrics --
# GET /v3/organization/brand_messages
getOrganizationBrandMessages: (params, callback) ->
@get "/v3/organization/brand_messages", params, callback
####################################################
# GET /v3/organization/intersecting_links
getOrganizationIntersectingLinks: (params, callback) ->
@get "/v3/organization/intersecting_links", params, callback
####################################################
# GET /v3/organization/leaderboard
getOrganizationLeaderboard: (params, callback) ->
@get "/v3/organization/leaderboard", params, callback
####################################################
# GET /v3/organization/missed_opportunities
getOrganizationMissedOpportunities: (params, callback) ->
@get "/v3/organization/missed_opportunities", params, callback
####################################################
# -- Bundles --
# GET /v3/bundle/archive
archiveBundle: (params, callback) ->
@get "/v3/bundle/archive", params, callback
####################################################
# GET /v3/bundle/bundles_by_user
bundlesByUser: (params, callback) ->
@get "/v3/bundle/bundles_by_user", params, callback
####################################################
# GET /v3/bundle/clone
cloneBundle: (params, callback) ->
@get "/v3/bundle/clone", params, callback
####################################################
# GET /v3/bundle/collaborator_add
addCollaboratorToBundle: (params, callback) ->
@get "/v3/bundle/collaborator_add", params, callback
####################################################
# GET /v3/bundle/collaborator_remove
removeCollaboratorFromBundle: (params, callback) ->
@get "/v3/bundle/collaborator_remove", params, callback
####################################################
# GET /v3/bundle/contents
getBundleContents: (params, callback) ->
@get "/v3/bundle/contents", params, callback
####################################################
# GET /v3/bundle/create
createBundle: (params, callback) ->
@get "/v3/bundle/create", params, callback
####################################################
# GET /v3/bundle/edit
editBundle: (params, callback) ->
@get "/v3/bundle/edit", params, callback
####################################################
# GET /v3/bundle/link_add
addLinkToBundle: (params, callback) ->
@get "/v3/bundle/link_add", params, callback
####################################################
# GET /v3/bundle/link_comment_add
addCommentToBundleLink: (params, callback) ->
@get "/v3/bundle/link_comment_add", params, callback
####################################################
# GET /v3/bundle/link_comment_edit
editBundleLinkComment: (params, callback) ->
@get "/v3/bundle/link_comment_edit", params, callback
####################################################
# GET /v3/bundle/link_comment_remove
removeBundleLinkComment: (params, callback) ->
@get "/v3/bundle/link_comment_remove", params, callback
####################################################
# GET /v3/bundle/link_edit
editBundleLink: (params, callback) ->
@get "/v3/bundle/link_edit", params, callback
####################################################
# GET /v3/bundle/link_remove
removeBundleLink: (params, callback) ->
@get "/v3/bundle/link_remove", params, callback
####################################################
# GET /v3/bundle/link_reorder
reorderBundleLink: (params, callback) ->
@get "/v3/bundle/link_reorder", params, callback
####################################################
# GET /v3/bundle/pending_collaborator_remove
removePendingCollaboratorFromBundle: (params, callback) ->
@get "/v3/bundle/pending_collaborator_remove", params, callback
####################################################
# GET /v3/bundle/reorder
reorderBundle: (params, callback) ->
@get "/v3/bundle/reorder", params, callback
####################################################
# GET /v3/bundle/view_count
getBundleViewCount: (params, callback) ->
@get "/v3/bundle/view_count", params, callback
####################################################
# GET /v3/user/bundle_history
getUserBundleHistory: (params, callback) ->
@get "/v3/user/bundle_history", params, callback
####################################################
# -- Domains --
# GET /v3/bitly_pro_domain
getBitlyProDomain: (params, callback) ->
@get "/v3/bitly_pro_domain", params, callback
####################################################
# GET /v3/user/tracking_domain_clicks
getTrackingDomainClicks: (params, callback) ->
@get "/v3/user/tracking_domain_clicks", params, callback
####################################################
# GET /v3/user/tracking_domain_shorten_counts
getTrackingDomainShortens: (params, callback) ->
@get "/v3/user/tracking_domain_shorten_counts", params, callback
module.exports = BitlyAPI; | 70538 | ####################################################
# node-bitlyapi
# A NodeJS interface for the Public Bitly API
# <NAME> <<EMAIL>
# https://github.com/nkirby/node-bitlyapi
####################################################
btoa = require 'btoa'
request = require 'request'
querystring = require 'querystring'
class BitlyAPI
request_config:
endpoint: "https://api-ssl.bitly.com"
constructor: (@config) ->
setAccessToken: (@access_token) ->
return this
####################################################
get: (path, params = {}, callback) ->
if not params.access_token and @access_token
params.access_token = @access_token
request(
{
uri:@request_config.endpoint+path+"?"+querystring.stringify(params),
method: "GET"
}
(error, response, body) ->
if callback
callback error, body
)
####################################################
# Authentication
####################################################
# POST: /oauth/access_token
authenticate: (username, password, callback) ->
if not @config or not @config.client_id or not @config.client_secret
throw "Bitly config error: you must specify a client_id and client_secret before authenticating a user."
auth = "Basic "+btoa(@config.client_id+":"+@config.client_secret)
console.log auth
request(
{
uri:@request_config.endpoint+"/oauth/access_token"
headers:
"Authorization": auth
method: "POST"
form:
grant_type: "password"
username: username
password: <PASSWORD>
}
(error, response, body) ->
if error
callback error, null
else
responseObj = JSON.parse(body)
callback null, responseObj.access_token
)
####################################################
# Objects
####################################################
user: (login) ->
new BitlyUser login, this
####################################################
# Helpers
####################################################
shortenLink: (link, callback) ->
@shorten {longUrl:link}, callback
####################################################
# API Calls
####################################################
####################################################
# Data APIs
# GET /v3/highvalue
getHighvalueLinks: (params, callback) ->
@get "/v3/highvalue", params, callback
####################################################
# GET /v3/search
search: (params, callback) ->
@get "/v3/search", params, callback
####################################################
# GET /v3/realtime/bursting_phrases
getRealtimeBurstingPhrases: (params, callback) ->
@get "/v3/realtime/bursting_phrases", params, callback
####################################################
# GET /v3/realtime/hot_phrases
getRealtimeHotPhrases: (params, callback) ->
@get "/v3/realtime/hot_phrases", params, callback
####################################################
# GET /v3/realtime/clickrate
getRealtimeClickrate: (params, callback) ->
@get "/v3/realtime/clickrate", params, callback
####################################################
# GET /v3/link/info
getLinkFullInfo: (params, callback) ->
@get "/v3/link/info", params, callback
####################################################
# GET /v3/link/content
getLinkContent: (params, callback) ->
@get "/v3/link/content", params, callback
####################################################
# GET /v3/link/category
getLinkCategory: (params, callback) ->
@get "/v3/link/category", params, callback
####################################################
# GET /v3/link/social
getLinkSocial: (params, callback) ->
@get "/v3/link/social", params, callback
####################################################
# GET /v3/link/location
getLinkLocation: (params, callback) ->
@get "/v3/link/location", params, callback
####################################################
# GET /v3/link/language
getLinkLanguage: (params, callback) ->
@get "/v3/link/language", params, callback
####################################################
# Links
# GET /v3/expand
expand: (params, callback) ->
@get "/v3/expand", params, callback
####################################################
# GET /v3/info
getLinkInfo: (params, callback) ->
@get "/v3/info", params, callback
####################################################
# GET /v3/link/lookup
linkLookup: (params, callback) ->
@get "/v3/link/lookup", params, callback
####################################################
# GET /v3/shorten
shorten: (params, callback) ->
@get "/v3/shorten", params, callback
####################################################
# GET /v3/user/link_edit
userEditLink: (params, callback) ->
@get "/v3/user/link_edit", params, callback
####################################################
# GET /v3/user/link_lookup
userLookupLink: (params, callback) ->
@get "/v3/user/link_lookup", params, callback
####################################################
# GET /v3/user/link_save
userSaveLink: (params, callback) ->
@get "/v3/user/link_save", params, callback
####################################################
# GET /v3/user/save_custom_domain_keyword
userSaveCustomDomainKeyword: (params, callback) ->
@get "/v3/user/save_custom_domain_keyword", params, callback
####################################################
# Link Metrics
# GET /v3/link/clicks
getLinkClicks: (params, callback) ->
@get "/v3/link/clicks", params, callback
####################################################
# GET /v3/link/countries
getLinkCountries: (params, callback) ->
@get "/v3/link/countries", params, callback
####################################################
# GET /v3/link/encoders
getLinkEncoders: (params, callback) ->
@get "/v3/link/encoders", params, callback
####################################################
# GET /v3/link/encoders_by_count
getLinkEncodersByCount: (params, callback) ->
@get "/v3/link/encoders_by_count", params, callback
####################################################
# GET /v3/link/encoders_count
getLinkEncodersCount: (params, callback) ->
@get "/v3/link/encoders_count", params, callback
####################################################
# GET /v3/link/referrers
getLinkReferrers: (params, callback) ->
@get "/v3/link/referrers", params, callback
####################################################
# GET /v3/link/referrers_by_domain
getLinkReferrersByDomain: (params, callback) ->
@get "/v3/link/referrers_by_domain", params, callback
####################################################
# GET /v3/link/referring_domains
getLinkReferringDomains: (params, callback) ->
@get "/v3/link/referring_domains", params, callback
####################################################
# GET /v3/link/shares
getLinkShares: (params, callback) ->
@get "/v3/link/shares", params, callback
####################################################
# -- User Info/History --
# GET: /v3/oauth/app
getAppInfo: (params, callback) ->
@get "/v3/oauth/app", params, callback
####################################################
# GET /v3/user/info
getUserInfo: (login, callback) ->
@get "/v3/user/info", login, callback
####################################################
# GET /v3/user/link_history
getUserLinkHistory: (params, callback) ->
@get "/v3/user/link_history", params, callback
####################################################
# GET /v3/user/network_history
getUserNetworkHistory: (params, callback) ->
@get "/v3/user/network_history", params, callback
####################################################
# GET /v3/user/tracking_domain_list
getUserTrackingDomains: (params, callback) ->
@get "/v3/user/tracking_domain_list", params, callback
####################################################
# -- User Metrics --
# GET /v3/user/clicks
getUserClicks: (params, callback) ->
@get "/v3/user/clicks", params, callback
####################################################
# GET /v3/user/countries
getUserCountries: (params, callback) ->
@get "/v3/user/countries", params, callback
####################################################
# GET /v3/user/popular_earned_by_clicks
getUserPopularEarnedByClicks: (params, callback) ->
@get "/v3/user/popular_earned_by_clicks", params, callback
####################################################
# GET /v3/user/popular_earned_by_shortens
getUserPopularEarnedByShortens: (params, callback) ->
@get "/v3/user/popular_earned_by_shortens", params, callback
####################################################
# GET /v3/user/popular_links
getUserPopularLinks: (params, callback) ->
@get "/v3/user/popular_links", params, callback
####################################################
# GET /v3/user/popular_owned_by_clicks
getUserPopularOwnedByClicks: (params, callback) ->
@get "/v3/user/popular_owned_by_clicks", params, callback
####################################################
# GET /v3/user/popular_owned_by_shortens
getUserPopularOwnedByShortens: (params, callback) ->
@get "/v3/user/popular_owned_by_shortens", params, callback
####################################################
# GET /v3/user/referrers
getUserReferrers: (params, callback) ->
@get "/v3/user/referrers", params, callback
####################################################
# GET /v3/user/referring_domains
getUserReferringDomains: (params, callback) ->
@get "/v3/user/referring_domains", params, callback
####################################################
# GET /v3/user/share_counts
getUserShareCounts: (params, callback) ->
@get "/v3/user/share_counts", params, callback
####################################################
# GET /v3/user/share_counts_by_share_type
getUserShareCountsByShareType: (params, callback) ->
@get "/v3/user/share_counts_by_share_type", params, callback
####################################################
# GET /v3/user/shorten_counts
getUserShortenCounts: (params, callback) ->
@get "/v3/user/shorten_counts", params, callback
####################################################
# -- Organization Metrics --
# GET /v3/organization/brand_messages
getOrganizationBrandMessages: (params, callback) ->
@get "/v3/organization/brand_messages", params, callback
####################################################
# GET /v3/organization/intersecting_links
getOrganizationIntersectingLinks: (params, callback) ->
@get "/v3/organization/intersecting_links", params, callback
####################################################
# GET /v3/organization/leaderboard
getOrganizationLeaderboard: (params, callback) ->
@get "/v3/organization/leaderboard", params, callback
####################################################
# GET /v3/organization/missed_opportunities
getOrganizationMissedOpportunities: (params, callback) ->
@get "/v3/organization/missed_opportunities", params, callback
####################################################
# -- Bundles --
# GET /v3/bundle/archive
archiveBundle: (params, callback) ->
@get "/v3/bundle/archive", params, callback
####################################################
# GET /v3/bundle/bundles_by_user
bundlesByUser: (params, callback) ->
@get "/v3/bundle/bundles_by_user", params, callback
####################################################
# GET /v3/bundle/clone
cloneBundle: (params, callback) ->
@get "/v3/bundle/clone", params, callback
####################################################
# GET /v3/bundle/collaborator_add
addCollaboratorToBundle: (params, callback) ->
@get "/v3/bundle/collaborator_add", params, callback
####################################################
# GET /v3/bundle/collaborator_remove
removeCollaboratorFromBundle: (params, callback) ->
@get "/v3/bundle/collaborator_remove", params, callback
####################################################
# GET /v3/bundle/contents
getBundleContents: (params, callback) ->
@get "/v3/bundle/contents", params, callback
####################################################
# GET /v3/bundle/create
createBundle: (params, callback) ->
@get "/v3/bundle/create", params, callback
####################################################
# GET /v3/bundle/edit
editBundle: (params, callback) ->
@get "/v3/bundle/edit", params, callback
####################################################
# GET /v3/bundle/link_add
addLinkToBundle: (params, callback) ->
@get "/v3/bundle/link_add", params, callback
####################################################
# GET /v3/bundle/link_comment_add
addCommentToBundleLink: (params, callback) ->
@get "/v3/bundle/link_comment_add", params, callback
####################################################
# GET /v3/bundle/link_comment_edit
editBundleLinkComment: (params, callback) ->
@get "/v3/bundle/link_comment_edit", params, callback
####################################################
# GET /v3/bundle/link_comment_remove
removeBundleLinkComment: (params, callback) ->
@get "/v3/bundle/link_comment_remove", params, callback
####################################################
# GET /v3/bundle/link_edit
editBundleLink: (params, callback) ->
@get "/v3/bundle/link_edit", params, callback
####################################################
# GET /v3/bundle/link_remove
removeBundleLink: (params, callback) ->
@get "/v3/bundle/link_remove", params, callback
####################################################
# GET /v3/bundle/link_reorder
reorderBundleLink: (params, callback) ->
@get "/v3/bundle/link_reorder", params, callback
####################################################
# GET /v3/bundle/pending_collaborator_remove
removePendingCollaboratorFromBundle: (params, callback) ->
@get "/v3/bundle/pending_collaborator_remove", params, callback
####################################################
# GET /v3/bundle/reorder
reorderBundle: (params, callback) ->
@get "/v3/bundle/reorder", params, callback
####################################################
# GET /v3/bundle/view_count
getBundleViewCount: (params, callback) ->
@get "/v3/bundle/view_count", params, callback
####################################################
# GET /v3/user/bundle_history
getUserBundleHistory: (params, callback) ->
@get "/v3/user/bundle_history", params, callback
####################################################
# -- Domains --
# GET /v3/bitly_pro_domain
getBitlyProDomain: (params, callback) ->
@get "/v3/bitly_pro_domain", params, callback
####################################################
# GET /v3/user/tracking_domain_clicks
getTrackingDomainClicks: (params, callback) ->
@get "/v3/user/tracking_domain_clicks", params, callback
####################################################
# GET /v3/user/tracking_domain_shorten_counts
getTrackingDomainShortens: (params, callback) ->
@get "/v3/user/tracking_domain_shorten_counts", params, callback
module.exports = BitlyAPI; | true | ####################################################
# node-bitlyapi
# A NodeJS interface for the Public Bitly API
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI
# https://github.com/nkirby/node-bitlyapi
####################################################
btoa = require 'btoa'
request = require 'request'
querystring = require 'querystring'
class BitlyAPI
request_config:
endpoint: "https://api-ssl.bitly.com"
constructor: (@config) ->
setAccessToken: (@access_token) ->
return this
####################################################
get: (path, params = {}, callback) ->
if not params.access_token and @access_token
params.access_token = @access_token
request(
{
uri:@request_config.endpoint+path+"?"+querystring.stringify(params),
method: "GET"
}
(error, response, body) ->
if callback
callback error, body
)
####################################################
# Authentication
####################################################
# POST: /oauth/access_token
authenticate: (username, password, callback) ->
if not @config or not @config.client_id or not @config.client_secret
throw "Bitly config error: you must specify a client_id and client_secret before authenticating a user."
auth = "Basic "+btoa(@config.client_id+":"+@config.client_secret)
console.log auth
request(
{
uri:@request_config.endpoint+"/oauth/access_token"
headers:
"Authorization": auth
method: "POST"
form:
grant_type: "password"
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
}
(error, response, body) ->
if error
callback error, null
else
responseObj = JSON.parse(body)
callback null, responseObj.access_token
)
####################################################
# Objects
####################################################
user: (login) ->
new BitlyUser login, this
####################################################
# Helpers
####################################################
shortenLink: (link, callback) ->
@shorten {longUrl:link}, callback
####################################################
# API Calls
####################################################
####################################################
# Data APIs
# GET /v3/highvalue
getHighvalueLinks: (params, callback) ->
@get "/v3/highvalue", params, callback
####################################################
# GET /v3/search
search: (params, callback) ->
@get "/v3/search", params, callback
####################################################
# GET /v3/realtime/bursting_phrases
getRealtimeBurstingPhrases: (params, callback) ->
@get "/v3/realtime/bursting_phrases", params, callback
####################################################
# GET /v3/realtime/hot_phrases
getRealtimeHotPhrases: (params, callback) ->
@get "/v3/realtime/hot_phrases", params, callback
####################################################
# GET /v3/realtime/clickrate
getRealtimeClickrate: (params, callback) ->
@get "/v3/realtime/clickrate", params, callback
####################################################
# GET /v3/link/info
getLinkFullInfo: (params, callback) ->
@get "/v3/link/info", params, callback
####################################################
# GET /v3/link/content
getLinkContent: (params, callback) ->
@get "/v3/link/content", params, callback
####################################################
# GET /v3/link/category
getLinkCategory: (params, callback) ->
@get "/v3/link/category", params, callback
####################################################
# GET /v3/link/social
getLinkSocial: (params, callback) ->
@get "/v3/link/social", params, callback
####################################################
# GET /v3/link/location
getLinkLocation: (params, callback) ->
@get "/v3/link/location", params, callback
####################################################
# GET /v3/link/language
getLinkLanguage: (params, callback) ->
@get "/v3/link/language", params, callback
####################################################
# Links
# GET /v3/expand
expand: (params, callback) ->
@get "/v3/expand", params, callback
####################################################
# GET /v3/info
getLinkInfo: (params, callback) ->
@get "/v3/info", params, callback
####################################################
# GET /v3/link/lookup
linkLookup: (params, callback) ->
@get "/v3/link/lookup", params, callback
####################################################
# GET /v3/shorten
shorten: (params, callback) ->
@get "/v3/shorten", params, callback
####################################################
# GET /v3/user/link_edit
userEditLink: (params, callback) ->
@get "/v3/user/link_edit", params, callback
####################################################
# GET /v3/user/link_lookup
userLookupLink: (params, callback) ->
@get "/v3/user/link_lookup", params, callback
####################################################
# GET /v3/user/link_save
userSaveLink: (params, callback) ->
@get "/v3/user/link_save", params, callback
####################################################
# GET /v3/user/save_custom_domain_keyword
userSaveCustomDomainKeyword: (params, callback) ->
@get "/v3/user/save_custom_domain_keyword", params, callback
####################################################
# Link Metrics
# GET /v3/link/clicks
getLinkClicks: (params, callback) ->
@get "/v3/link/clicks", params, callback
####################################################
# GET /v3/link/countries
getLinkCountries: (params, callback) ->
@get "/v3/link/countries", params, callback
####################################################
# GET /v3/link/encoders
getLinkEncoders: (params, callback) ->
@get "/v3/link/encoders", params, callback
####################################################
# GET /v3/link/encoders_by_count
getLinkEncodersByCount: (params, callback) ->
@get "/v3/link/encoders_by_count", params, callback
####################################################
# GET /v3/link/encoders_count
getLinkEncodersCount: (params, callback) ->
@get "/v3/link/encoders_count", params, callback
####################################################
# GET /v3/link/referrers
getLinkReferrers: (params, callback) ->
@get "/v3/link/referrers", params, callback
####################################################
# GET /v3/link/referrers_by_domain
getLinkReferrersByDomain: (params, callback) ->
@get "/v3/link/referrers_by_domain", params, callback
####################################################
# GET /v3/link/referring_domains
getLinkReferringDomains: (params, callback) ->
@get "/v3/link/referring_domains", params, callback
####################################################
# GET /v3/link/shares
getLinkShares: (params, callback) ->
@get "/v3/link/shares", params, callback
####################################################
# -- User Info/History --
# GET: /v3/oauth/app
getAppInfo: (params, callback) ->
@get "/v3/oauth/app", params, callback
####################################################
# GET /v3/user/info
getUserInfo: (login, callback) ->
@get "/v3/user/info", login, callback
####################################################
# GET /v3/user/link_history
getUserLinkHistory: (params, callback) ->
@get "/v3/user/link_history", params, callback
####################################################
# GET /v3/user/network_history
getUserNetworkHistory: (params, callback) ->
@get "/v3/user/network_history", params, callback
####################################################
# GET /v3/user/tracking_domain_list
getUserTrackingDomains: (params, callback) ->
@get "/v3/user/tracking_domain_list", params, callback
####################################################
# -- User Metrics --
# GET /v3/user/clicks
getUserClicks: (params, callback) ->
@get "/v3/user/clicks", params, callback
####################################################
# GET /v3/user/countries
getUserCountries: (params, callback) ->
@get "/v3/user/countries", params, callback
####################################################
# GET /v3/user/popular_earned_by_clicks
getUserPopularEarnedByClicks: (params, callback) ->
@get "/v3/user/popular_earned_by_clicks", params, callback
####################################################
# GET /v3/user/popular_earned_by_shortens
getUserPopularEarnedByShortens: (params, callback) ->
@get "/v3/user/popular_earned_by_shortens", params, callback
####################################################
# GET /v3/user/popular_links
getUserPopularLinks: (params, callback) ->
@get "/v3/user/popular_links", params, callback
####################################################
# GET /v3/user/popular_owned_by_clicks
getUserPopularOwnedByClicks: (params, callback) ->
@get "/v3/user/popular_owned_by_clicks", params, callback
####################################################
# GET /v3/user/popular_owned_by_shortens
getUserPopularOwnedByShortens: (params, callback) ->
@get "/v3/user/popular_owned_by_shortens", params, callback
####################################################
# GET /v3/user/referrers
getUserReferrers: (params, callback) ->
@get "/v3/user/referrers", params, callback
####################################################
# GET /v3/user/referring_domains
getUserReferringDomains: (params, callback) ->
@get "/v3/user/referring_domains", params, callback
####################################################
# GET /v3/user/share_counts
getUserShareCounts: (params, callback) ->
@get "/v3/user/share_counts", params, callback
####################################################
# GET /v3/user/share_counts_by_share_type
getUserShareCountsByShareType: (params, callback) ->
@get "/v3/user/share_counts_by_share_type", params, callback
####################################################
# GET /v3/user/shorten_counts
getUserShortenCounts: (params, callback) ->
@get "/v3/user/shorten_counts", params, callback
####################################################
# -- Organization Metrics --
# GET /v3/organization/brand_messages
getOrganizationBrandMessages: (params, callback) ->
@get "/v3/organization/brand_messages", params, callback
####################################################
# GET /v3/organization/intersecting_links
getOrganizationIntersectingLinks: (params, callback) ->
@get "/v3/organization/intersecting_links", params, callback
####################################################
# GET /v3/organization/leaderboard
getOrganizationLeaderboard: (params, callback) ->
@get "/v3/organization/leaderboard", params, callback
####################################################
# GET /v3/organization/missed_opportunities
getOrganizationMissedOpportunities: (params, callback) ->
@get "/v3/organization/missed_opportunities", params, callback
####################################################
# -- Bundles --
# GET /v3/bundle/archive
archiveBundle: (params, callback) ->
@get "/v3/bundle/archive", params, callback
####################################################
# GET /v3/bundle/bundles_by_user
bundlesByUser: (params, callback) ->
@get "/v3/bundle/bundles_by_user", params, callback
####################################################
# GET /v3/bundle/clone
cloneBundle: (params, callback) ->
@get "/v3/bundle/clone", params, callback
####################################################
# GET /v3/bundle/collaborator_add
addCollaboratorToBundle: (params, callback) ->
@get "/v3/bundle/collaborator_add", params, callback
####################################################
# GET /v3/bundle/collaborator_remove
removeCollaboratorFromBundle: (params, callback) ->
@get "/v3/bundle/collaborator_remove", params, callback
####################################################
# GET /v3/bundle/contents
getBundleContents: (params, callback) ->
@get "/v3/bundle/contents", params, callback
####################################################
# GET /v3/bundle/create
createBundle: (params, callback) ->
@get "/v3/bundle/create", params, callback
####################################################
# GET /v3/bundle/edit
editBundle: (params, callback) ->
@get "/v3/bundle/edit", params, callback
####################################################
# GET /v3/bundle/link_add
addLinkToBundle: (params, callback) ->
@get "/v3/bundle/link_add", params, callback
####################################################
# GET /v3/bundle/link_comment_add
addCommentToBundleLink: (params, callback) ->
@get "/v3/bundle/link_comment_add", params, callback
####################################################
# GET /v3/bundle/link_comment_edit
editBundleLinkComment: (params, callback) ->
@get "/v3/bundle/link_comment_edit", params, callback
####################################################
# GET /v3/bundle/link_comment_remove
removeBundleLinkComment: (params, callback) ->
@get "/v3/bundle/link_comment_remove", params, callback
####################################################
# GET /v3/bundle/link_edit
editBundleLink: (params, callback) ->
@get "/v3/bundle/link_edit", params, callback
####################################################
# GET /v3/bundle/link_remove
removeBundleLink: (params, callback) ->
@get "/v3/bundle/link_remove", params, callback
####################################################
# GET /v3/bundle/link_reorder
reorderBundleLink: (params, callback) ->
@get "/v3/bundle/link_reorder", params, callback
####################################################
# GET /v3/bundle/pending_collaborator_remove
removePendingCollaboratorFromBundle: (params, callback) ->
@get "/v3/bundle/pending_collaborator_remove", params, callback
####################################################
# GET /v3/bundle/reorder
reorderBundle: (params, callback) ->
@get "/v3/bundle/reorder", params, callback
####################################################
# GET /v3/bundle/view_count
getBundleViewCount: (params, callback) ->
@get "/v3/bundle/view_count", params, callback
####################################################
# GET /v3/user/bundle_history
getUserBundleHistory: (params, callback) ->
@get "/v3/user/bundle_history", params, callback
####################################################
# -- Domains --
# GET /v3/bitly_pro_domain
getBitlyProDomain: (params, callback) ->
@get "/v3/bitly_pro_domain", params, callback
####################################################
# GET /v3/user/tracking_domain_clicks
getTrackingDomainClicks: (params, callback) ->
@get "/v3/user/tracking_domain_clicks", params, callback
####################################################
# GET /v3/user/tracking_domain_shorten_counts
getTrackingDomainShortens: (params, callback) ->
@get "/v3/user/tracking_domain_shorten_counts", params, callback
module.exports = BitlyAPI; |
[
{
"context": "eanu-shirt' + (randomToken 2)\n name: 'Sad Keanu T-shirt'\n price: 2500\n currency: 'US",
"end": 188,
"score": 0.7585844397544861,
"start": 171,
"tag": "NAME",
"value": "Sad Keanu T-shirt"
},
{
"context": "keanu-shirt-' + (randomToken 2)\n name: 'Sad Keanu T-shirt (Medium)'\n price: 2000\n cur",
"end": 593,
"score": 0.7037705183029175,
"start": 584,
"tag": "NAME",
"value": "Sad Keanu"
}
] | test/server/variant.coffee | hanzo-io/hanzo.js | 147 | describe 'Api.variant', ->
variant = null
before ->
product = yield api.product.create
slug: 'sad-keanu-shirt' + (randomToken 2)
name: 'Sad Keanu T-shirt'
price: 2500
currency: 'USD'
headline: 'Oh Keanu'
description: 'Sad Keanu is sad.'
options: [
name: 'size'
values: ['small', 'medium', 'large']
,
name: 'color'
values: ['dark', 'light']
]
variant =
productId: product.id
sku: 'sad-keanu-shirt-' + (randomToken 2)
name: 'Sad Keanu T-shirt (Medium)'
price: 2000
currency: 'USD'
options: [
name: 'size'
value: 'medium'
,
name: 'color'
value: 'dark'
]
describe '.create', ->
it 'should create variants', ->
p = yield api.variant.create variant
p.price.should.eq variant.price
variant.sku = p.sku
describe '.get', ->
it 'should get variant', ->
p = yield api.variant.get variant.sku
p.price.should.eq 2000
describe '.list', ->
it 'should list variants', ->
{count, models} = yield api.variant.list()
models.length.should.be.gt 0
count.should.be.gt 0
describe '.update', ->
it 'should update variants', ->
p = yield api.variant.update sku: variant.sku, price: 3500
p.price.should.eq 3500
describe '.delete', ->
it 'should delete variants', ->
yield api.variant.delete variant.sku
| 61372 | describe 'Api.variant', ->
variant = null
before ->
product = yield api.product.create
slug: 'sad-keanu-shirt' + (randomToken 2)
name: '<NAME>'
price: 2500
currency: 'USD'
headline: 'Oh Keanu'
description: 'Sad Keanu is sad.'
options: [
name: 'size'
values: ['small', 'medium', 'large']
,
name: 'color'
values: ['dark', 'light']
]
variant =
productId: product.id
sku: 'sad-keanu-shirt-' + (randomToken 2)
name: '<NAME> T-shirt (Medium)'
price: 2000
currency: 'USD'
options: [
name: 'size'
value: 'medium'
,
name: 'color'
value: 'dark'
]
describe '.create', ->
it 'should create variants', ->
p = yield api.variant.create variant
p.price.should.eq variant.price
variant.sku = p.sku
describe '.get', ->
it 'should get variant', ->
p = yield api.variant.get variant.sku
p.price.should.eq 2000
describe '.list', ->
it 'should list variants', ->
{count, models} = yield api.variant.list()
models.length.should.be.gt 0
count.should.be.gt 0
describe '.update', ->
it 'should update variants', ->
p = yield api.variant.update sku: variant.sku, price: 3500
p.price.should.eq 3500
describe '.delete', ->
it 'should delete variants', ->
yield api.variant.delete variant.sku
| true | describe 'Api.variant', ->
variant = null
before ->
product = yield api.product.create
slug: 'sad-keanu-shirt' + (randomToken 2)
name: 'PI:NAME:<NAME>END_PI'
price: 2500
currency: 'USD'
headline: 'Oh Keanu'
description: 'Sad Keanu is sad.'
options: [
name: 'size'
values: ['small', 'medium', 'large']
,
name: 'color'
values: ['dark', 'light']
]
variant =
productId: product.id
sku: 'sad-keanu-shirt-' + (randomToken 2)
name: 'PI:NAME:<NAME>END_PI T-shirt (Medium)'
price: 2000
currency: 'USD'
options: [
name: 'size'
value: 'medium'
,
name: 'color'
value: 'dark'
]
describe '.create', ->
it 'should create variants', ->
p = yield api.variant.create variant
p.price.should.eq variant.price
variant.sku = p.sku
describe '.get', ->
it 'should get variant', ->
p = yield api.variant.get variant.sku
p.price.should.eq 2000
describe '.list', ->
it 'should list variants', ->
{count, models} = yield api.variant.list()
models.length.should.be.gt 0
count.should.be.gt 0
describe '.update', ->
it 'should update variants', ->
p = yield api.variant.update sku: variant.sku, price: 3500
p.price.should.eq 3500
describe '.delete', ->
it 'should delete variants', ->
yield api.variant.delete variant.sku
|
[
{
"context": ":\n admin:\n uid: 'toto'\n gid: 'toto'\n ta",
"end": 3906,
"score": 0.5749356746673584,
"start": 3903,
"tag": "USERNAME",
"value": "oto"
},
{
"context": "to'\n task:\n uid: 'toto'\n gid: 'toto'\n cpu:",
"end": 5266,
"score": 0.8768101930618286,
"start": 5262,
"tag": "USERNAME",
"value": "toto"
},
{
"context": "m:\n admin:\n uid: 'bibi'\n gid: 'bibi'\n ta",
"end": 5545,
"score": 0.687759518623352,
"start": 5541,
"tag": "USERNAME",
"value": "bibi"
},
{
"context": "m:\n admin:\n uid: 'toto'\n gid: 'toto'\n ta",
"end": 7390,
"score": 0.9105813503265381,
"start": 7386,
"tag": "USERNAME",
"value": "toto"
},
{
"context": "to'\n task:\n uid: 'toto'\n gid: 'toto'\n cpu:",
"end": 7472,
"score": 0.6246039867401123,
"start": 7468,
"tag": "USERNAME",
"value": "toto"
},
{
"context": "m:\n admin:\n uid: 'bibi'\n gid: 'bibi'\n ta",
"end": 7751,
"score": 0.8265080451965332,
"start": 7747,
"tag": "USERNAME",
"value": "bibi"
},
{
"context": " uid: 'bibi'\n gid: 'bibi'\n task:\n uid: 'bi",
"end": 7781,
"score": 0.686850368976593,
"start": 7780,
"tag": "USERNAME",
"value": "i"
},
{
"context": "\n task:\n uid: 'bibi'\n gid: 'bibi'\n cpu:",
"end": 7833,
"score": 0.7298324108123779,
"start": 7832,
"tag": "USERNAME",
"value": "i"
},
{
"context": " perm {\n admin {\n uid = toto;\n gid = toto;\n }\n ",
"end": 8387,
"score": 0.5663865804672241,
"start": 8383,
"tag": "USERNAME",
"value": "toto"
},
{
"context": "perm {\n admin {\n uid = bibi;\n gid = bibi;\n }\n ",
"end": 8761,
"score": 0.7179100513458252,
"start": 8760,
"tag": "USERNAME",
"value": "i"
},
{
"context": "perm:\n admin:\n uid: 'toto'\n gid: 'toto'\n task:\n",
"end": 14351,
"score": 0.5720985531806946,
"start": 14348,
"tag": "USERNAME",
"value": "oto"
},
{
"context": "rm:\n admin:\n uid: 'bibi'\n gid: 'bibi'\n task:\n",
"end": 14688,
"score": 0.6559063196182251,
"start": 14687,
"tag": "USERNAME",
"value": "i"
},
{
"context": " perm:\n admin:\n uid: 'toto'\n gid: 'toto'\n task:\n",
"end": 16858,
"score": 0.8693252801895142,
"start": 16854,
"tag": "USERNAME",
"value": "toto"
},
{
"context": " perm:\n admin:\n uid: 'bibi'\n gid: 'bibi'\n task:\n",
"end": 17195,
"score": 0.8496989607810974,
"start": 17191,
"tag": "USERNAME",
"value": "bibi"
},
{
"context": "rm:\n admin:\n uid: 'bibi'\n gid: 'bibi'\n task:\n",
"end": 17535,
"score": 0.6580061912536621,
"start": 17534,
"tag": "USERNAME",
"value": "i"
},
{
"context": " perm {\n admin {\n uid = bibi;\n gid = bibi;\n }\n ",
"end": 18694,
"score": 0.7854920625686646,
"start": 18690,
"tag": "USERNAME",
"value": "bibi"
},
{
"context": " perm {\n admin {\n uid = bibi;\n gid = bibi;\n }\n ",
"end": 19071,
"score": 0.5372241139411926,
"start": 19067,
"tag": "USERNAME",
"value": "bibi"
},
{
"context": " }\n task {\n uid = bibi;\n gid = bibi;\n }\n ",
"end": 19155,
"score": 0.6558141708374023,
"start": 19152,
"tag": "NAME",
"value": "bib"
},
{
"context": "erm: '0775'\n uid: 'root'\n gid: 'nikita'\n age: '10s'\n argu: '-'\n c",
"end": 20893,
"score": 0.9134261608123779,
"start": 20887,
"tag": "USERNAME",
"value": "nikita"
},
{
"context": "un/file_1'\n perm: '0775'\n uid: 'root'\n gid: 'nikita'\n age: '10s'\n ",
"end": 21195,
"score": 0.7913141846656799,
"start": 21191,
"tag": "USERNAME",
"value": "root"
},
{
"context": "erm: '0775'\n uid: 'root'\n gid: 'nikita'\n age: '10s'\n argu: '-'\n m",
"end": 21219,
"score": 0.9606437683105469,
"start": 21213,
"tag": "USERNAME",
"value": "nikita"
},
{
"context": "un/file_1'\n perm: '0775'\n uid: 'root'\n gid: 'nikita'\n misc.tmpfs.stringi",
"end": 21567,
"score": 0.8098450899124146,
"start": 21563,
"tag": "USERNAME",
"value": "root"
},
{
"context": "erm: '0775'\n uid: 'root'\n gid: 'nikita'\n misc.tmpfs.stringify(obj).should.eql \"\"\"\n ",
"end": 21591,
"score": 0.9016774296760559,
"start": 21585,
"tag": "USERNAME",
"value": "nikita"
},
{
"context": "un/file_1'\n perm: '0775'\n uid: 'root'\n gid: 'nikita'\n '/var/run/file_2",
"end": 21876,
"score": 0.9087077379226685,
"start": 21872,
"tag": "USERNAME",
"value": "root"
},
{
"context": "erm: '0775'\n uid: 'root'\n gid: 'nikita'\n '/var/run/file_2':\n type: 'd'\n ",
"end": 21900,
"score": 0.9371004700660706,
"start": 21894,
"tag": "USERNAME",
"value": "nikita"
},
{
"context": "un/file_2'\n perm: '0775'\n uid: 'root'\n gid: 'nikita'\n misc.tmpfs.stringi",
"end": 22027,
"score": 0.9022115468978882,
"start": 22023,
"tag": "USERNAME",
"value": "root"
},
{
"context": "erm: '0775'\n uid: 'root'\n gid: 'nikita'\n misc.tmpfs.stringify(obj).should.eql \"\"\"\n ",
"end": 22051,
"score": 0.9479115009307861,
"start": 22045,
"tag": "USERNAME",
"value": "nikita"
}
] | packages/core/test/misc/misc.coffee | chibanemourad/node-nikita | 1 |
misc = require '../../src/misc'
{tags} = require '../test'
return unless tags.api
describe 'misc', ->
describe 'object', ->
describe 'equals', ->
it 'two objects', ->
misc.object.equals({a: '1', b: '2'}, {a: '1', b: '2'}).should.be.true()
misc.object.equals({a: '1', b: '1'}, {a: '2', b: '2'}).should.be.false()
misc.object.equals({a: '1', b: '2', c: '3'}, {a: '1', b: '2', c: '3'}, ['a', 'c']).should.be.true()
misc.object.equals({a: '1', b: '-', c: '3'}, {a: '1', b: '+', c: '3'}, ['a', 'c']).should.be.true()
misc.object.equals({a: '1', b: '-', c: '3'}, {a: '1', b: '+', c: '3'}, ['a', 'b']).should.be.false()
describe 'diff', ->
it 'two objects', ->
misc.object.diff({a: '1', b: '2', c: '3'}, {a: '1', b: '2', c: '3'}, ['a', 'c']).should.eql {}
misc.object.diff({a: '1', b: '21', c: '3'}, {a: '1', b: '22', c: '3'}, ['a', 'c']).should.eql {}
misc.object.diff({a: '11', b: '2', c: '3'}, {a: '12', b: '2', c: '3'}, ['a', 'c']).should.eql {'a': ['11', '12']}
it 'two objects without keys', ->
misc.object.diff({a: '1', b: '2', c: '3'}, {a: '1', b: '2', c: '3'}).should.eql {}
misc.object.diff({a: '11', b: '2', c: '3'}, {a: '12', b: '2', c: '3'}).should.eql {'a': ['11', '12']}
describe 'cgconfig', ->
it 'parse mount only file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups: {}
}
it 'parse multiple file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
mount {
cpuset = /cgroup/cpusetbis;
cpu = /cgroup/cpubis;
cpuacct = /cgroup/cpuacctbis;
memory = /cgroup/memorybis;
devices = /cgroup/devicesbis;
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
,
type: 'cpuset'
path: '/cgroup/cpusetbis'
,
type: 'cpu'
path: '/cgroup/cpubis'
,
type: 'cpuacct'
path: '/cgroup/cpuacctbis'
,
type: 'memory'
path: '/cgroup/memorybis'
,
type: 'devices'
path: '/cgroup/devicesbis'
]
groups: {}
}
it 'parse group only file', ->
mount_obj = """
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: []
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'parse multiple groups file', ->
mount_obj = """
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: []
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'parse mount and groups file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'parse mount and groups and default file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
default {
perm {
admin {
uid = root;
gid = root;
}
task {
uid = root;
gid = root;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
'':
perm:
admin:
uid: 'root'
gid: 'root'
task:
uid: 'root'
gid: 'root'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'stringify a mount only object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
"""
it 'stringify a group only object', ->
cgroups =
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
it 'stringify a mount and group object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
it 'stringify a mount and multiple group object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
it 'stringify a mount and multiple group and default object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
,
type: 'cpuset'
path: '/cgroup/cpusetbis'
,
type: 'cpu'
path: '/cgroup/cpubis'
,
type: 'cpuacct'
path: '/cgroup/cpuacctbis'
,
type: 'memory'
path: '/cgroup/memorybis'
,
type: 'devices'
path: '/cgroup/devicesbis'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
default:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
cpuset = /cgroup/cpusetbis;
cpu = /cgroup/cpubis;
cpuacct = /cgroup/cpuacctbis;
memory = /cgroup/memorybis;
devices = /cgroup/devicesbis;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
default {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
describe 'tmpfs', ->
it 'parse single complete line file', ->
obj = """
# screen needs directory in /var/run
d /var/run/file_1 0775 root nikita 10s -
"""
expected =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
content = misc.tmpfs.parse obj
content.should.eql expected
it 'parse uncomplete complete line file', ->
obj = """
# screen needs directory in /var/run
d /var/run/file_1 0775 root nikita
"""
expected =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '-'
argu: '-'
content = misc.tmpfs.parse obj
content.should.eql expected
it 'parse multiple complete line file', ->
obj = """
# nikita needs directory in /var/run
d /var/run/file_1 0775 root nikita 10s -
# an other comment ^^
d /var/run/file_2 0775 root nikita 10s -
"""
expected =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
'/var/run/file_2':
type: 'd'
mount: '/var/run/file_2'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
content = misc.tmpfs.parse obj
content.should.eql expected
it 'stringify single complete object file', ->
obj =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
misc.tmpfs.stringify(obj).should.eql """
d /var/run/file_1 0775 root nikita 10s -
"""
it 'stringify not defined by omission value file', ->
obj =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
misc.tmpfs.stringify(obj).should.eql """
d /var/run/file_1 0775 root nikita - -
"""
it 'stringify multiple files', ->
obj =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
'/var/run/file_2':
type: 'd'
mount: '/var/run/file_2'
perm: '0775'
uid: 'root'
gid: 'nikita'
misc.tmpfs.stringify(obj).should.eql """
d /var/run/file_1 0775 root nikita - -
d /var/run/file_2 0775 root nikita - -
"""
| 91271 |
misc = require '../../src/misc'
{tags} = require '../test'
return unless tags.api
describe 'misc', ->
describe 'object', ->
describe 'equals', ->
it 'two objects', ->
misc.object.equals({a: '1', b: '2'}, {a: '1', b: '2'}).should.be.true()
misc.object.equals({a: '1', b: '1'}, {a: '2', b: '2'}).should.be.false()
misc.object.equals({a: '1', b: '2', c: '3'}, {a: '1', b: '2', c: '3'}, ['a', 'c']).should.be.true()
misc.object.equals({a: '1', b: '-', c: '3'}, {a: '1', b: '+', c: '3'}, ['a', 'c']).should.be.true()
misc.object.equals({a: '1', b: '-', c: '3'}, {a: '1', b: '+', c: '3'}, ['a', 'b']).should.be.false()
describe 'diff', ->
it 'two objects', ->
misc.object.diff({a: '1', b: '2', c: '3'}, {a: '1', b: '2', c: '3'}, ['a', 'c']).should.eql {}
misc.object.diff({a: '1', b: '21', c: '3'}, {a: '1', b: '22', c: '3'}, ['a', 'c']).should.eql {}
misc.object.diff({a: '11', b: '2', c: '3'}, {a: '12', b: '2', c: '3'}, ['a', 'c']).should.eql {'a': ['11', '12']}
it 'two objects without keys', ->
misc.object.diff({a: '1', b: '2', c: '3'}, {a: '1', b: '2', c: '3'}).should.eql {}
misc.object.diff({a: '11', b: '2', c: '3'}, {a: '12', b: '2', c: '3'}).should.eql {'a': ['11', '12']}
describe 'cgconfig', ->
it 'parse mount only file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups: {}
}
it 'parse multiple file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
mount {
cpuset = /cgroup/cpusetbis;
cpu = /cgroup/cpubis;
cpuacct = /cgroup/cpuacctbis;
memory = /cgroup/memorybis;
devices = /cgroup/devicesbis;
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
,
type: 'cpuset'
path: '/cgroup/cpusetbis'
,
type: 'cpu'
path: '/cgroup/cpubis'
,
type: 'cpuacct'
path: '/cgroup/cpuacctbis'
,
type: 'memory'
path: '/cgroup/memorybis'
,
type: 'devices'
path: '/cgroup/devicesbis'
]
groups: {}
}
it 'parse group only file', ->
mount_obj = """
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: []
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'parse multiple groups file', ->
mount_obj = """
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: []
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'parse mount and groups file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'parse mount and groups and default file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
default {
perm {
admin {
uid = root;
gid = root;
}
task {
uid = root;
gid = root;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
'':
perm:
admin:
uid: 'root'
gid: 'root'
task:
uid: 'root'
gid: 'root'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'stringify a mount only object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
"""
it 'stringify a group only object', ->
cgroups =
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
it 'stringify a mount and group object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
it 'stringify a mount and multiple group object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
it 'stringify a mount and multiple group and default object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
,
type: 'cpuset'
path: '/cgroup/cpusetbis'
,
type: 'cpu'
path: '/cgroup/cpubis'
,
type: 'cpuacct'
path: '/cgroup/cpuacctbis'
,
type: 'memory'
path: '/cgroup/memorybis'
,
type: 'devices'
path: '/cgroup/devicesbis'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
default:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
cpuset = /cgroup/cpusetbis;
cpu = /cgroup/cpubis;
cpuacct = /cgroup/cpuacctbis;
memory = /cgroup/memorybis;
devices = /cgroup/devicesbis;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
default {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = <NAME>i;
gid = bibi;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
describe 'tmpfs', ->
it 'parse single complete line file', ->
obj = """
# screen needs directory in /var/run
d /var/run/file_1 0775 root nikita 10s -
"""
expected =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
content = misc.tmpfs.parse obj
content.should.eql expected
it 'parse uncomplete complete line file', ->
obj = """
# screen needs directory in /var/run
d /var/run/file_1 0775 root nikita
"""
expected =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '-'
argu: '-'
content = misc.tmpfs.parse obj
content.should.eql expected
it 'parse multiple complete line file', ->
obj = """
# nikita needs directory in /var/run
d /var/run/file_1 0775 root nikita 10s -
# an other comment ^^
d /var/run/file_2 0775 root nikita 10s -
"""
expected =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
'/var/run/file_2':
type: 'd'
mount: '/var/run/file_2'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
content = misc.tmpfs.parse obj
content.should.eql expected
it 'stringify single complete object file', ->
obj =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
misc.tmpfs.stringify(obj).should.eql """
d /var/run/file_1 0775 root nikita 10s -
"""
it 'stringify not defined by omission value file', ->
obj =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
misc.tmpfs.stringify(obj).should.eql """
d /var/run/file_1 0775 root nikita - -
"""
it 'stringify multiple files', ->
obj =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
'/var/run/file_2':
type: 'd'
mount: '/var/run/file_2'
perm: '0775'
uid: 'root'
gid: 'nikita'
misc.tmpfs.stringify(obj).should.eql """
d /var/run/file_1 0775 root nikita - -
d /var/run/file_2 0775 root nikita - -
"""
| true |
misc = require '../../src/misc'
{tags} = require '../test'
return unless tags.api
describe 'misc', ->
describe 'object', ->
describe 'equals', ->
it 'two objects', ->
misc.object.equals({a: '1', b: '2'}, {a: '1', b: '2'}).should.be.true()
misc.object.equals({a: '1', b: '1'}, {a: '2', b: '2'}).should.be.false()
misc.object.equals({a: '1', b: '2', c: '3'}, {a: '1', b: '2', c: '3'}, ['a', 'c']).should.be.true()
misc.object.equals({a: '1', b: '-', c: '3'}, {a: '1', b: '+', c: '3'}, ['a', 'c']).should.be.true()
misc.object.equals({a: '1', b: '-', c: '3'}, {a: '1', b: '+', c: '3'}, ['a', 'b']).should.be.false()
describe 'diff', ->
it 'two objects', ->
misc.object.diff({a: '1', b: '2', c: '3'}, {a: '1', b: '2', c: '3'}, ['a', 'c']).should.eql {}
misc.object.diff({a: '1', b: '21', c: '3'}, {a: '1', b: '22', c: '3'}, ['a', 'c']).should.eql {}
misc.object.diff({a: '11', b: '2', c: '3'}, {a: '12', b: '2', c: '3'}, ['a', 'c']).should.eql {'a': ['11', '12']}
it 'two objects without keys', ->
misc.object.diff({a: '1', b: '2', c: '3'}, {a: '1', b: '2', c: '3'}).should.eql {}
misc.object.diff({a: '11', b: '2', c: '3'}, {a: '12', b: '2', c: '3'}).should.eql {'a': ['11', '12']}
describe 'cgconfig', ->
it 'parse mount only file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups: {}
}
it 'parse multiple file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
mount {
cpuset = /cgroup/cpusetbis;
cpu = /cgroup/cpubis;
cpuacct = /cgroup/cpuacctbis;
memory = /cgroup/memorybis;
devices = /cgroup/devicesbis;
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
,
type: 'cpuset'
path: '/cgroup/cpusetbis'
,
type: 'cpu'
path: '/cgroup/cpubis'
,
type: 'cpuacct'
path: '/cgroup/cpuacctbis'
,
type: 'memory'
path: '/cgroup/memorybis'
,
type: 'devices'
path: '/cgroup/devicesbis'
]
groups: {}
}
it 'parse group only file', ->
mount_obj = """
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: []
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'parse multiple groups file', ->
mount_obj = """
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: []
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'parse mount and groups file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'parse mount and groups and default file', ->
mount_obj = """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
default {
perm {
admin {
uid = root;
gid = root;
}
task {
uid = root;
gid = root;
}
}
cpu {
cpu.rt_period_us="1000000";
cpu.rt_runtime_us="0";
cpu.cfs_period_us="100000";
}
}
"""
misc.cgconfig.parse(mount_obj).should.eql {
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
'':
perm:
admin:
uid: 'root'
gid: 'root'
task:
uid: 'root'
gid: 'root'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
}
it 'stringify a mount only object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
"""
it 'stringify a group only object', ->
cgroups =
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
it 'stringify a mount and group object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
it 'stringify a mount and multiple group object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
it 'stringify a mount and multiple group and default object', ->
cgroups =
mounts: [
type: 'cpuset'
path: '/cgroup/cpuset'
,
type: 'cpu'
path: '/cgroup/cpu'
,
type: 'cpuacct'
path: '/cgroup/cpuacct'
,
type: 'memory'
path: '/cgroup/memory'
,
type: 'devices'
path: '/cgroup/devices'
,
type: 'cpuset'
path: '/cgroup/cpusetbis'
,
type: 'cpu'
path: '/cgroup/cpubis'
,
type: 'cpuacct'
path: '/cgroup/cpuacctbis'
,
type: 'memory'
path: '/cgroup/memorybis'
,
type: 'devices'
path: '/cgroup/devicesbis'
]
groups:
toto:
perm:
admin:
uid: 'toto'
gid: 'toto'
task:
uid: 'toto'
gid: 'toto'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
bibi:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
default:
perm:
admin:
uid: 'bibi'
gid: 'bibi'
task:
uid: 'bibi'
gid: 'bibi'
cpu:
'cpu.rt_period_us': '"1000000"'
'cpu.rt_runtime_us': '"0"'
'cpu.cfs_period_us': '"100000"'
misc.cgconfig.stringify(cgroups).should.eql """
mount {
cpuset = /cgroup/cpuset;
cpu = /cgroup/cpu;
cpuacct = /cgroup/cpuacct;
memory = /cgroup/memory;
devices = /cgroup/devices;
cpuset = /cgroup/cpusetbis;
cpu = /cgroup/cpubis;
cpuacct = /cgroup/cpuacctbis;
memory = /cgroup/memorybis;
devices = /cgroup/devicesbis;
}
group toto {
perm {
admin {
uid = toto;
gid = toto;
}
task {
uid = toto;
gid = toto;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
group bibi {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = bibi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
default {
perm {
admin {
uid = bibi;
gid = bibi;
}
task {
uid = PI:NAME:<NAME>END_PIi;
gid = bibi;
}
}
cpu {
cpu.rt_period_us = "1000000";
cpu.rt_runtime_us = "0";
cpu.cfs_period_us = "100000";
}
}
"""
describe 'tmpfs', ->
it 'parse single complete line file', ->
obj = """
# screen needs directory in /var/run
d /var/run/file_1 0775 root nikita 10s -
"""
expected =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
content = misc.tmpfs.parse obj
content.should.eql expected
it 'parse uncomplete complete line file', ->
obj = """
# screen needs directory in /var/run
d /var/run/file_1 0775 root nikita
"""
expected =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '-'
argu: '-'
content = misc.tmpfs.parse obj
content.should.eql expected
it 'parse multiple complete line file', ->
obj = """
# nikita needs directory in /var/run
d /var/run/file_1 0775 root nikita 10s -
# an other comment ^^
d /var/run/file_2 0775 root nikita 10s -
"""
expected =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
'/var/run/file_2':
type: 'd'
mount: '/var/run/file_2'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
content = misc.tmpfs.parse obj
content.should.eql expected
it 'stringify single complete object file', ->
obj =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
age: '10s'
argu: '-'
misc.tmpfs.stringify(obj).should.eql """
d /var/run/file_1 0775 root nikita 10s -
"""
it 'stringify not defined by omission value file', ->
obj =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
misc.tmpfs.stringify(obj).should.eql """
d /var/run/file_1 0775 root nikita - -
"""
it 'stringify multiple files', ->
obj =
'/var/run/file_1':
type: 'd'
mount: '/var/run/file_1'
perm: '0775'
uid: 'root'
gid: 'nikita'
'/var/run/file_2':
type: 'd'
mount: '/var/run/file_2'
perm: '0775'
uid: 'root'
gid: 'nikita'
misc.tmpfs.stringify(obj).should.eql """
d /var/run/file_1 0775 root nikita - -
d /var/run/file_2 0775 root nikita - -
"""
|
[
{
"context": "\n @swig.renderFile(lpath, { locals: { author: \"Jeff Escalante\" } })\n .catch(should.not.exist)\n .done(",
"end": 3971,
"score": 0.9998670816421509,
"start": 3957,
"tag": "NAME",
"value": "Jeff Escalante"
},
{
"context": "ustache.render(\"Why hello, {{ name }}!\", { name: 'dogeudle' })\n .catch(should.not.exist)\n .done((r",
"end": 19748,
"score": 0.9907150864601135,
"start": 19740,
"tag": "USERNAME",
"value": "dogeudle"
},
{
"context": "dlebars.render('Hello there {{ name }}', { name: 'homie' })\n .catch(should.not.exist)\n .done((r",
"end": 23050,
"score": 0.9920750260353088,
"start": 23045,
"tag": "NAME",
"value": "homie"
},
{
"context": "> should.match_expected(@handlebars, res({ name: 'my friend' }), path.join(@path, 'pstring.hbs'), done))\n\n i",
"end": 23639,
"score": 0.6956573724746704,
"start": 23630,
"tag": "NAME",
"value": "my friend"
},
{
"context": "should.match_expected(@handlebars, res({ friend: 'r kelly' }), lpath, done))\n\n it 'should client-compile a",
"end": 23917,
"score": 0.9027475714683533,
"start": 23910,
"tag": "NAME",
"value": "r kelly"
},
{
"context": "l.render('%div.foo= \"Whats up \" + name', { name: 'mang' })\n .catch(should.not.exist)\n .done((r",
"end": 31585,
"score": 0.820496678352356,
"start": 31581,
"tag": "NAME",
"value": "mang"
},
{
"context": "res) => should.match_expected(@haml, res({ name: 'my friend' }), path.join(@path, 'pstring.haml'), done))\n\n ",
"end": 32143,
"score": 0.6022297143936157,
"start": 32134,
"tag": "NAME",
"value": "my friend"
}
] | node_modules/gulp-stylus/node_modules/accord/test/test.coffee | richgilbank/test | 0 | should = require 'should'
path = require 'path'
accord = require '../'
require('./helpers')(should)
describe 'base functions', ->
it 'supports should work', ->
accord.supports('jade').should.be.ok
accord.supports('markdown').should.be.ok
accord.supports('marked').should.be.ok
accord.supports('blargh').should.not.be.ok
it 'load should work', ->
(-> accord.load('jade')).should.not.throw()
(-> accord.load('blargh')).should.throw()
it 'load should accept a custom path', ->
(-> accord.load('jade', path.join(__dirname, '../node_modules/jade'))).should.not.throw()
it 'all should return all adapters', ->
accord.all().should.be.type('object')
describe 'jade', ->
before ->
@jade = accord.load('jade')
@path = path.join(__dirname, 'fixtures', 'jade')
it 'should expose name, extensions, output, and compiler', ->
@jade.extensions.should.be.an.instanceOf(Array)
@jade.output.should.be.type('string')
@jade.compiler.should.be.ok
@jade.name.should.be.ok
it 'should render a string', (done) ->
@jade.render('p BLAHHHHH\np= foo', { foo: 'such options' })
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, path.join(@path, 'rstring.jade'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.jade')
@jade.renderFile(lpath, { foo: 'such options' })
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, lpath, done))
it 'should compile a string', (done) ->
@jade.compile("p why cant I shot web?\np= foo")
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res({foo: 'such options'}), path.join(@path, 'pstring.jade'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.jade')
@jade.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res({foo: 'such options'}), lpath, done))
it 'should client-compile a string', (done) ->
@jade.compileClient("p imma firin mah lazer!\np= foo", {foo: 'such options'})
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, path.join(@path, 'cstring.jade'), done))
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.jade')
@jade.compileFileClient(lpath, {foo: 'such options'})
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.jade')
@jade.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.jade')
@jade.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@jade.clientHelpers()}#{res}; template({ wow: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@jade, tpl, lpath, done)
it 'should correctly handle errors', (done) ->
@jade.render("!= nonexistantfunction()")
.done(should.not.exist, (-> done()))
describe 'swig', ->
before ->
@swig = accord.load('swig')
@path = path.join(__dirname, 'fixtures', 'swig')
it 'should expose name, extensions, output, and compiler', ->
@swig.extensions.should.be.an.instanceOf(Array)
@swig.output.should.be.type('string')
@swig.compiler.should.be.ok
@swig.name.should.be.ok
it 'should render a string', (done) ->
@swig.render('<h1>{% if foo %}Bar{% endif %}</h1>', { locals: { foo: true } })
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, path.join(@path, 'string.swig'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.swig')
@swig.renderFile(lpath, { locals: { author: "Jeff Escalante" } })
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should compile a string', (done) ->
@swig.compile("<h1>{{ title }}</h1>")
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res({title: 'Hello!'}), path.join(@path, 'pstring.swig'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.swig')
@swig.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res({title: 'Hello!'}), lpath, done))
it 'should client-compile a string', (done) ->
@swig.compileClient("<h1>{% if foo %}Bar{% endif %}</h1>", {foo: true})
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, path.join(@path, 'cstring.swig'), done))
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.swig')
@swig.compileFileClient(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.swig')
@swig.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.swig')
@swig.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "window = {}; #{@swig.clientHelpers()};\n var tpl = (#{res});"
should.match_expected(@swig, tpl_string, lpath, done)
describe 'coffeescript', ->
before ->
@coffee = accord.load('coffee-script')
@path = path.join(__dirname, 'fixtures', 'coffee')
it 'should expose name, extensions, output, and compiler', ->
@coffee.extensions.should.be.an.instanceOf(Array)
@coffee.output.should.be.type('string')
@coffee.compiler.should.be.ok
@coffee.name.should.be.ok
it 'should render a string', (done) ->
@coffee.render('console.log "test"', { bare: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@coffee, res, path.join(@path, 'string.coffee'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.coffee')
@coffee.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@coffee, res, lpath, done))
it 'should not be able to compile', (done) ->
@coffee.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@coffee.render("! ---@#$$@%#$")
.done(should.not.exist, (-> done()))
describe 'stylus', ->
before ->
@stylus = accord.load('stylus')
@path = path.join(__dirname, 'fixtures', 'stylus')
it 'should expose name, extensions, output, and compiler', ->
@stylus.extensions.should.be.an.instanceOf(Array)
@stylus.output.should.be.type('string')
@stylus.compiler.should.be.ok
@stylus.name.should.be.ok
it 'should render a string', (done) ->
@stylus.render('.test\n foo: bar')
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'string.styl'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.styl')
@stylus.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should not be able to compile', (done) ->
@stylus.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should set normal options', (done) ->
opts =
paths: ['pluginz']
foo: 'bar'
lpath = path.join(@path, 'include1.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set defines', (done) ->
opts =
define: { foo: 'bar', baz: 'quux' }
@stylus.render('.test\n test: foo', opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'defines.styl'), done))
it 'should set includes', (done) ->
opts =
include: 'pluginz'
lpath = path.join(@path, 'include1.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set multiple includes', (done) ->
opts =
include: ['pluginz', 'extra_plugin']
lpath = path.join(@path, 'include2.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set imports', (done) ->
opts =
import: 'pluginz/lib'
lpath = path.join(@path, 'import1.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set multiple imports', (done) ->
opts =
import: ['pluginz/lib', 'pluginz/lib2']
lpath = path.join(@path, 'import2.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set plugins', (done) ->
opts =
use: (style) ->
style.define('main-width', 500)
@stylus.render('.test\n foo: main-width', opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'plugins1.styl'), done))
it 'should set multiple plugins', (done) ->
opts =
use: [
((style) -> style.define('main-width', 500)),
((style) -> style.define('main-height', 200)),
]
@stylus.render('.test\n foo: main-width\n bar: main-height', opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'plugins2.styl'), done))
it 'should correctly handle errors', (done) ->
@stylus.render("214m2/3l")
.done(should.not.exist, (-> done()))
describe 'ejs', ->
before ->
@ejs = accord.load('ejs')
@path = path.join(__dirname, 'fixtures', 'ejs')
it 'should expose name, extensions, output, and compiler', ->
@ejs.extensions.should.be.an.instanceOf(Array)
@ejs.output.should.be.type('string')
@ejs.compiler.should.be.ok
@ejs.name.should.be.ok
it 'should render a string', (done) ->
@ejs.render('<p>ejs yah</p><p><%= foo%></p>', { foo: 'wow opts' })
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, path.join(@path, 'rstring.ejs'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.ejs')
@ejs.renderFile(lpath, { foo: 'wow opts' })
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, lpath, done))
it 'should compile a string', (done) ->
@ejs.compile("<p>precompilez</p><p><%= foo %></p>")
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res({foo: 'wow opts'}), path.join(@path, 'pstring.ejs'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.ejs')
@ejs.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res({foo: 'wow opts'}), lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.ejs')
@ejs.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, lpath, done))
it 'should client-compile a string', (done) ->
@ejs.compileClient("Woah look, a <%= thing %>")
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, path.join(@path, 'cstring.ejs'), done))
# ejs writes the filename to the function, which makes this
# not work cross-system as expected
it.skip 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.ejs')
@ejs.compileFileClient(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.ejs')
@ejs.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@ejs.clientHelpers()}; var tpl = #{res}; tpl({ foo: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@ejs, tpl, lpath, done)
it 'should correctly handle errors', (done) ->
@ejs.render("<%= wow() %>")
.done(should.not.exist, (-> done()))
describe 'markdown', ->
before ->
@markdown = accord.load('markdown')
@path = path.join(__dirname, 'fixtures', 'markdown')
it 'should expose name, extensions, output, and compiler', ->
@markdown.extensions.should.be.an.instanceOf(Array)
@markdown.output.should.be.type('string')
@markdown.compiler.should.be.ok
@markdown.name.should.be.ok
it 'should render a string', (done) ->
@markdown.render('hello **world**')
.catch(should.not.exist)
.done((res) => should.match_expected(@markdown, res, path.join(@path, 'string.md'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.md')
@markdown.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@markdown, res, lpath, done))
it 'should render with options', (done) ->
lpath = path.join(@path, 'opts.md')
@markdown.renderFile(lpath, {sanitize: true})
.catch(should.not.exist)
.done((res) => should.match_expected(@markdown, res, lpath, done))
it 'should not be able to compile', (done) ->
@markdown.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
describe 'minify-js', ->
before ->
@minifyjs = accord.load('minify-js')
@path = path.join(__dirname, 'fixtures', 'minify-js')
it 'should expose name, extensions, output, and compiler', ->
@minifyjs.extensions.should.be.an.instanceOf(Array)
@minifyjs.output.should.be.type('string')
@minifyjs.compiler.should.be.ok
@minifyjs.name.should.be.ok
it 'should minify a string', (done) ->
@minifyjs.render('var foo = "foobar";\nconsole.log(foo)')
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyjs, res, path.join(@path, 'string.js'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.js')
@minifyjs.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyjs, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.js')
@minifyjs.renderFile(lpath, { compress: false })
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyjs, res, lpath, done))
it 'should not be able to compile', (done) ->
@minifyjs.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@minifyjs.render("@#$%#I$$N%NI#$%I$PQ")
.done(should.not.exist, (-> done()))
describe 'minify-css', ->
before ->
@minifycss = accord.load('minify-css')
@path = path.join(__dirname, 'fixtures', 'minify-css')
it 'should expose name, extensions, output, and compiler', ->
@minifycss.extensions.should.be.an.instanceOf(Array)
@minifycss.output.should.be.type('string')
@minifycss.compiler.should.be.ok
@minifycss.name.should.be.ok
it 'should minify a string', (done) ->
@minifycss.render('.test {\n foo: bar;\n}')
.catch(should.not.exist)
.done((res) => should.match_expected(@minifycss, res, path.join(@path, 'string.css'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.css')
@minifycss.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@minifycss, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.css')
@minifycss.renderFile(lpath, { keepBreaks: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@minifycss, res, lpath, done))
it 'should not be able to compile', (done) ->
@minifycss.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@minifycss.render("FMWT$SP#TPO%M@#@#M!@@@")
.done(should.not.exist, (-> done()))
describe 'minify-html', ->
before ->
@minifyhtml = accord.load('minify-html')
@path = path.join(__dirname, 'fixtures', 'minify-html')
it 'should expose name, extensions, output, and compiler', ->
@minifyhtml.extensions.should.be.an.instanceOf(Array)
@minifyhtml.output.should.be.type('string')
@minifyhtml.compiler.should.be.ok
@minifyhtml.name.should.be.ok
it 'should minify a string', (done) ->
@minifyhtml.render('<div class="hi" id="">\n <p>hello</p>\n</div>')
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyhtml, res, path.join(@path, 'string.html'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.html')
@minifyhtml.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyhtml, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.html')
@minifyhtml.renderFile(lpath, { collapseWhitespace: false })
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyhtml, res, lpath, done))
it 'should not be able to compile', (done) ->
@minifyhtml.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@minifyhtml.render("<<<{@$@#$")
.done(should.not.exist, (-> done()))
describe 'csso', ->
before ->
@csso = accord.load('csso')
@path = path.join(__dirname, 'fixtures', 'csso')
it 'should expose name, extensions, output, and compiler', ->
@csso.extensions.should.be.an.instanceOf(Array)
@csso.output.should.be.type('string')
@csso.compiler.should.be.ok
@csso.name.should.be.ok
it 'should minify a string', (done) ->
@csso.render(".hello { foo: bar; }\n .hello { color: green }")
.catch(should.not.exist)
.done((res) => should.match_expected(@csso, res, path.join(@path, 'string.css'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.css')
@csso.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@csso, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.css')
@csso.renderFile(lpath, { noRestructure: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@csso, res, lpath, done))
it 'should not be able to compile', (done) ->
@csso.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@csso.render("wow")
.done(should.not.exist, (-> done()))
describe 'mustache', ->
before ->
@mustache = accord.load('mustache')
@path = path.join(__dirname, 'fixtures', 'mustache')
it 'should expose name, extensions, output, and compiler', ->
@mustache.extensions.should.be.an.instanceOf(Array)
@mustache.output.should.be.type('string')
@mustache.compiler.should.be.ok
@mustache.name.should.be.ok
it 'should render a string', (done) ->
@mustache.render("Why hello, {{ name }}!", { name: 'dogeudle' })
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res, path.join(@path, 'string.mustache'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.mustache')
@mustache.renderFile(lpath, { name: 'doge', winner: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res, lpath, done))
it 'should compile a string', (done) ->
@mustache.compile("Wow, such {{ noun }}")
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res.render({noun: 'compile'}), path.join(@path, 'pstring.mustache'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.mustache')
@mustache.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res.render({name: 'foo'}), lpath, done))
it 'client compile should work', (done) ->
lpath = path.join(@path, 'client-complex.mustache')
@mustache.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@mustache.clientHelpers()}; var tpl = #{res} tpl.render({ wow: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@mustache, tpl, lpath, done)
it 'should handle partials', (done) ->
lpath = path.join(@path, 'partial.mustache')
@mustache.renderFile(lpath, { foo: 'bar', partials: { partial: 'foo {{ foo }}' } })
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res, lpath, done))
it 'should correctly handle errors', (done) ->
@mustache.render("{{# !@{!# }}")
.done(should.not.exist, (-> done()))
describe 'dogescript', ->
before ->
@doge = accord.load('dogescript')
@path = path.join(__dirname, 'fixtures', 'dogescript')
it 'should expose name, extensions, output, and compiler', ->
@doge.extensions.should.be.an.instanceOf(Array)
@doge.output.should.be.type('string')
@doge.compiler.should.be.ok
@doge.name.should.be.ok
it 'should render a string', (done) ->
@doge.render("console dose loge with 'wow'", { beautify: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@doge, res, path.join(@path, 'string.djs'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.djs')
@doge.renderFile(lpath, { trueDoge: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@doge, res, lpath, done))
it 'should not be able to compile', (done) ->
@doge.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
# it turns out that it's impossible for dogescript to throw an error
# which, honestly, is how it should be. so no test here.
describe 'handlebars', ->
before ->
@handlebars = accord.load('handlebars')
@path = path.join(__dirname, 'fixtures', 'handlebars')
it 'should expose name, extensions, output, and compiler', ->
@handlebars.extensions.should.be.an.instanceOf(Array)
@handlebars.output.should.be.type('string')
@handlebars.compiler.should.be.ok
@handlebars.name.should.be.ok
it 'should render a string', (done) ->
@handlebars.render('Hello there {{ name }}', { name: 'homie' })
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, path.join(@path, 'rstring.hbs'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.hbs')
@handlebars.renderFile(lpath, { compiler: 'handlebars' })
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, lpath, done))
it 'should compile a string', (done) ->
@handlebars.compile('Hello there {{ name }}')
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res({ name: 'my friend' }), path.join(@path, 'pstring.hbs'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.hbs')
@handlebars.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res({ friend: 'r kelly' }), lpath, done))
it 'should client-compile a string', (done) ->
@handlebars.compileClient("Here comes the {{ thing }}")
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, path.join(@path, 'cstring.hbs'), done))
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.hbs')
@handlebars.compileFileClient(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.hbs')
@handlebars.renderFile(lpath, { partials: { foo: "<p>hello from a partial!</p>" }})
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.hbs')
@handlebars.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@handlebars.clientHelpers()}; var tpl = #{res}; tpl({ wow: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@handlebars, tpl, lpath, done)
it 'should correctly handle errors', (done) ->
@handlebars.render("{{# !@{!# }}")
.done(should.not.exist, (-> done()))
describe 'scss', ->
before ->
@scss = accord.load('scss')
@path = path.join(__dirname, 'fixtures', 'scss')
it 'should expose name, extensions, output, and compiler', ->
@scss.extensions.should.be.an.instanceOf(Array)
@scss.output.should.be.type('string')
@scss.compiler.should.be.ok
@scss.name.should.be.ok
it 'should render a string', (done) ->
@scss.render("$wow: 'red'; foo { bar: $wow; }")
.catch(should.not.exist)
.done((res) => should.match_expected(@scss, res, path.join(@path, 'string.scss'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.scss')
@scss.renderFile(lpath, { trueDoge: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@scss, res, lpath, done))
it 'should include external files', (done) ->
lpath = path.join(@path, 'external.scss')
@scss.renderFile(lpath, { includePaths: [@path] })
.catch(should.not.exist)
.done((res) => should.match_expected(@scss, res, lpath, done))
it 'should not be able to compile', (done) ->
@scss.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@scss.render("!@##%#$#^$")
.done(should.not.exist, (-> done()))
describe 'less', ->
before ->
@less = accord.load('less')
@path = path.join(__dirname, 'fixtures', 'less')
it 'should expose name, extensions, output, and compiler', ->
@less.extensions.should.be.an.instanceOf(Array)
@less.output.should.be.type('string')
@less.compiler.should.be.ok
@less.name.should.be.ok
it 'should render a string', (done) ->
@less.render(".foo { width: 100 + 20 }")
.catch(should.not.exist)
.done((res) => should.match_expected(@less, res, path.join(@path, 'string.less'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.less')
@less.renderFile(lpath, { trueDoge: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@less, res, lpath, done))
it 'should include external files', (done) ->
lpath = path.join(@path, 'external.less')
@less.renderFile(lpath, { paths: [@path] })
.catch(should.not.exist)
.done((res) => should.match_expected(@less, res, lpath, done))
it 'should not be able to compile', (done) ->
@less.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@less.render("!@##%#$#^$")
.done(should.not.exist, (-> done()))
describe 'coco', ->
before ->
@coco = accord.load('coco')
@path = path.join(__dirname, 'fixtures', 'coco')
it 'should expose name, extensions, output, and compiler', ->
@coco.extensions.should.be.an.instanceOf(Array)
@coco.output.should.be.type('string')
@coco.compiler.should.be.ok
@coco.name.should.be.ok
it 'should render a string', (done) ->
@coco.render("function test\n console.log('foo')", { bare: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@coco, res, path.join(@path, 'string.co'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.co')
@coco.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@coco, res, lpath, done))
it 'should not be able to compile', (done) ->
@coco.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@coco.render("!! --- )I%$_(I(YRTO")
.done(should.not.exist, (-> done()))
describe 'livescript', ->
before ->
@livescript = accord.load('LiveScript')
@path = path.join(__dirname, 'fixtures', 'livescript')
it 'should expose name, extensions, output, and compiler', ->
@livescript.extensions.should.be.an.instanceOf(Array)
@livescript.output.should.be.type('string')
@livescript.compiler.should.be.ok
@livescript.name.should.be.ok
it 'should render a string', (done) ->
@livescript.render("test = ~> console.log('foo')", { bare: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@livescript, res, path.join(@path, 'string.ls'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.ls')
@livescript.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@livescript, res, lpath, done))
it 'should not be able to compile', (done) ->
@livescript.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@livescript.render("!! --- )I%$_(I(YRTO")
.done(should.not.exist, (-> done()))
describe 'myth', ->
before ->
@myth = accord.load('myth')
@path = path.join(__dirname, 'fixtures', 'myth')
it 'should expose name, extensions, output, and compiler', ->
@myth.extensions.should.be.an.instanceOf(Array)
@myth.output.should.be.type('string')
@myth.compiler.should.be.ok
@myth.name.should.be.ok
it 'should render a string', (done) ->
@myth.render(".foo { transition: all 1s ease; }")
.catch(should.not.exist)
.done((res) => should.match_expected(@myth, res, path.join(@path, 'string.myth'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.myth')
@myth.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@myth, res, lpath, done))
it 'should not be able to compile', (done) ->
@myth.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@myth.render("!! --- )I%$_(I(YRTO")
.done(should.not.exist, (-> done()))
describe 'haml', ->
before ->
@haml = accord.load('haml')
@path = path.join(__dirname, 'fixtures', 'haml')
it 'should expose name, extensions, output, and compiler', ->
@haml.extensions.should.be.an.instanceOf(Array)
@haml.output.should.be.type('string')
@haml.compiler.should.be.ok
@haml.name.should.be.ok
it 'should render a string', (done) ->
@haml.render('%div.foo= "Whats up " + name', { name: 'mang' })
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res, path.join(@path, 'rstring.haml'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.haml')
@haml.renderFile(lpath, { compiler: 'haml' })
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res, lpath, done))
it 'should compile a string', (done) ->
@haml.compile('%p= "Hello there " + name')
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res({ name: 'my friend' }), path.join(@path, 'pstring.haml'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.haml')
@haml.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res({ friend: 'doge' }), lpath, done))
it 'should not support client compiles', (done) ->
@haml.compileClient("%p= 'Here comes the ' + thing")
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@haml.render("%p= wow()")
.done(should.not.exist, (-> done()))
describe 'marc', ->
before ->
@marc = accord.load('marc')
@path = path.join(__dirname, 'fixtures', 'marc')
it 'should expose name, extensions, output, and compiler', ->
@marc.extensions.should.be.an.instanceOf(Array)
@marc.output.should.be.type('string')
@marc.compiler.should.be.ok
@marc.name.should.be.ok
it 'should render a string', (done) ->
@marc.render(
'I am using __markdown__ with {{label}}!'
data:
label: 'marc'
).catch(
should.not.exist
).done((res) =>
should.match_expected(@marc, res, path.join(@path, 'basic.md'), done)
)
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.md')
@marc.renderFile(lpath, data: {label: 'marc'})
.catch(should.not.exist)
.done((res) => should.match_expected(@marc, res, lpath, done))
it 'should not be able to compile', (done) ->
@marc.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
| 109920 | should = require 'should'
path = require 'path'
accord = require '../'
require('./helpers')(should)
describe 'base functions', ->
it 'supports should work', ->
accord.supports('jade').should.be.ok
accord.supports('markdown').should.be.ok
accord.supports('marked').should.be.ok
accord.supports('blargh').should.not.be.ok
it 'load should work', ->
(-> accord.load('jade')).should.not.throw()
(-> accord.load('blargh')).should.throw()
it 'load should accept a custom path', ->
(-> accord.load('jade', path.join(__dirname, '../node_modules/jade'))).should.not.throw()
it 'all should return all adapters', ->
accord.all().should.be.type('object')
describe 'jade', ->
before ->
@jade = accord.load('jade')
@path = path.join(__dirname, 'fixtures', 'jade')
it 'should expose name, extensions, output, and compiler', ->
@jade.extensions.should.be.an.instanceOf(Array)
@jade.output.should.be.type('string')
@jade.compiler.should.be.ok
@jade.name.should.be.ok
it 'should render a string', (done) ->
@jade.render('p BLAHHHHH\np= foo', { foo: 'such options' })
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, path.join(@path, 'rstring.jade'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.jade')
@jade.renderFile(lpath, { foo: 'such options' })
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, lpath, done))
it 'should compile a string', (done) ->
@jade.compile("p why cant I shot web?\np= foo")
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res({foo: 'such options'}), path.join(@path, 'pstring.jade'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.jade')
@jade.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res({foo: 'such options'}), lpath, done))
it 'should client-compile a string', (done) ->
@jade.compileClient("p imma firin mah lazer!\np= foo", {foo: 'such options'})
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, path.join(@path, 'cstring.jade'), done))
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.jade')
@jade.compileFileClient(lpath, {foo: 'such options'})
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.jade')
@jade.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.jade')
@jade.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@jade.clientHelpers()}#{res}; template({ wow: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@jade, tpl, lpath, done)
it 'should correctly handle errors', (done) ->
@jade.render("!= nonexistantfunction()")
.done(should.not.exist, (-> done()))
describe 'swig', ->
before ->
@swig = accord.load('swig')
@path = path.join(__dirname, 'fixtures', 'swig')
it 'should expose name, extensions, output, and compiler', ->
@swig.extensions.should.be.an.instanceOf(Array)
@swig.output.should.be.type('string')
@swig.compiler.should.be.ok
@swig.name.should.be.ok
it 'should render a string', (done) ->
@swig.render('<h1>{% if foo %}Bar{% endif %}</h1>', { locals: { foo: true } })
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, path.join(@path, 'string.swig'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.swig')
@swig.renderFile(lpath, { locals: { author: "<NAME>" } })
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should compile a string', (done) ->
@swig.compile("<h1>{{ title }}</h1>")
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res({title: 'Hello!'}), path.join(@path, 'pstring.swig'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.swig')
@swig.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res({title: 'Hello!'}), lpath, done))
it 'should client-compile a string', (done) ->
@swig.compileClient("<h1>{% if foo %}Bar{% endif %}</h1>", {foo: true})
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, path.join(@path, 'cstring.swig'), done))
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.swig')
@swig.compileFileClient(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.swig')
@swig.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.swig')
@swig.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "window = {}; #{@swig.clientHelpers()};\n var tpl = (#{res});"
should.match_expected(@swig, tpl_string, lpath, done)
describe 'coffeescript', ->
before ->
@coffee = accord.load('coffee-script')
@path = path.join(__dirname, 'fixtures', 'coffee')
it 'should expose name, extensions, output, and compiler', ->
@coffee.extensions.should.be.an.instanceOf(Array)
@coffee.output.should.be.type('string')
@coffee.compiler.should.be.ok
@coffee.name.should.be.ok
it 'should render a string', (done) ->
@coffee.render('console.log "test"', { bare: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@coffee, res, path.join(@path, 'string.coffee'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.coffee')
@coffee.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@coffee, res, lpath, done))
it 'should not be able to compile', (done) ->
@coffee.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@coffee.render("! ---@#$$@%#$")
.done(should.not.exist, (-> done()))
describe 'stylus', ->
before ->
@stylus = accord.load('stylus')
@path = path.join(__dirname, 'fixtures', 'stylus')
it 'should expose name, extensions, output, and compiler', ->
@stylus.extensions.should.be.an.instanceOf(Array)
@stylus.output.should.be.type('string')
@stylus.compiler.should.be.ok
@stylus.name.should.be.ok
it 'should render a string', (done) ->
@stylus.render('.test\n foo: bar')
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'string.styl'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.styl')
@stylus.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should not be able to compile', (done) ->
@stylus.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should set normal options', (done) ->
opts =
paths: ['pluginz']
foo: 'bar'
lpath = path.join(@path, 'include1.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set defines', (done) ->
opts =
define: { foo: 'bar', baz: 'quux' }
@stylus.render('.test\n test: foo', opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'defines.styl'), done))
it 'should set includes', (done) ->
opts =
include: 'pluginz'
lpath = path.join(@path, 'include1.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set multiple includes', (done) ->
opts =
include: ['pluginz', 'extra_plugin']
lpath = path.join(@path, 'include2.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set imports', (done) ->
opts =
import: 'pluginz/lib'
lpath = path.join(@path, 'import1.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set multiple imports', (done) ->
opts =
import: ['pluginz/lib', 'pluginz/lib2']
lpath = path.join(@path, 'import2.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set plugins', (done) ->
opts =
use: (style) ->
style.define('main-width', 500)
@stylus.render('.test\n foo: main-width', opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'plugins1.styl'), done))
it 'should set multiple plugins', (done) ->
opts =
use: [
((style) -> style.define('main-width', 500)),
((style) -> style.define('main-height', 200)),
]
@stylus.render('.test\n foo: main-width\n bar: main-height', opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'plugins2.styl'), done))
it 'should correctly handle errors', (done) ->
@stylus.render("214m2/3l")
.done(should.not.exist, (-> done()))
describe 'ejs', ->
before ->
@ejs = accord.load('ejs')
@path = path.join(__dirname, 'fixtures', 'ejs')
it 'should expose name, extensions, output, and compiler', ->
@ejs.extensions.should.be.an.instanceOf(Array)
@ejs.output.should.be.type('string')
@ejs.compiler.should.be.ok
@ejs.name.should.be.ok
it 'should render a string', (done) ->
@ejs.render('<p>ejs yah</p><p><%= foo%></p>', { foo: 'wow opts' })
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, path.join(@path, 'rstring.ejs'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.ejs')
@ejs.renderFile(lpath, { foo: 'wow opts' })
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, lpath, done))
it 'should compile a string', (done) ->
@ejs.compile("<p>precompilez</p><p><%= foo %></p>")
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res({foo: 'wow opts'}), path.join(@path, 'pstring.ejs'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.ejs')
@ejs.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res({foo: 'wow opts'}), lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.ejs')
@ejs.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, lpath, done))
it 'should client-compile a string', (done) ->
@ejs.compileClient("Woah look, a <%= thing %>")
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, path.join(@path, 'cstring.ejs'), done))
# ejs writes the filename to the function, which makes this
# not work cross-system as expected
it.skip 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.ejs')
@ejs.compileFileClient(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.ejs')
@ejs.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@ejs.clientHelpers()}; var tpl = #{res}; tpl({ foo: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@ejs, tpl, lpath, done)
it 'should correctly handle errors', (done) ->
@ejs.render("<%= wow() %>")
.done(should.not.exist, (-> done()))
describe 'markdown', ->
before ->
@markdown = accord.load('markdown')
@path = path.join(__dirname, 'fixtures', 'markdown')
it 'should expose name, extensions, output, and compiler', ->
@markdown.extensions.should.be.an.instanceOf(Array)
@markdown.output.should.be.type('string')
@markdown.compiler.should.be.ok
@markdown.name.should.be.ok
it 'should render a string', (done) ->
@markdown.render('hello **world**')
.catch(should.not.exist)
.done((res) => should.match_expected(@markdown, res, path.join(@path, 'string.md'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.md')
@markdown.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@markdown, res, lpath, done))
it 'should render with options', (done) ->
lpath = path.join(@path, 'opts.md')
@markdown.renderFile(lpath, {sanitize: true})
.catch(should.not.exist)
.done((res) => should.match_expected(@markdown, res, lpath, done))
it 'should not be able to compile', (done) ->
@markdown.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
describe 'minify-js', ->
before ->
@minifyjs = accord.load('minify-js')
@path = path.join(__dirname, 'fixtures', 'minify-js')
it 'should expose name, extensions, output, and compiler', ->
@minifyjs.extensions.should.be.an.instanceOf(Array)
@minifyjs.output.should.be.type('string')
@minifyjs.compiler.should.be.ok
@minifyjs.name.should.be.ok
it 'should minify a string', (done) ->
@minifyjs.render('var foo = "foobar";\nconsole.log(foo)')
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyjs, res, path.join(@path, 'string.js'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.js')
@minifyjs.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyjs, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.js')
@minifyjs.renderFile(lpath, { compress: false })
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyjs, res, lpath, done))
it 'should not be able to compile', (done) ->
@minifyjs.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@minifyjs.render("@#$%#I$$N%NI#$%I$PQ")
.done(should.not.exist, (-> done()))
describe 'minify-css', ->
before ->
@minifycss = accord.load('minify-css')
@path = path.join(__dirname, 'fixtures', 'minify-css')
it 'should expose name, extensions, output, and compiler', ->
@minifycss.extensions.should.be.an.instanceOf(Array)
@minifycss.output.should.be.type('string')
@minifycss.compiler.should.be.ok
@minifycss.name.should.be.ok
it 'should minify a string', (done) ->
@minifycss.render('.test {\n foo: bar;\n}')
.catch(should.not.exist)
.done((res) => should.match_expected(@minifycss, res, path.join(@path, 'string.css'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.css')
@minifycss.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@minifycss, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.css')
@minifycss.renderFile(lpath, { keepBreaks: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@minifycss, res, lpath, done))
it 'should not be able to compile', (done) ->
@minifycss.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@minifycss.render("FMWT$SP#TPO%M@#@#M!@@@")
.done(should.not.exist, (-> done()))
describe 'minify-html', ->
before ->
@minifyhtml = accord.load('minify-html')
@path = path.join(__dirname, 'fixtures', 'minify-html')
it 'should expose name, extensions, output, and compiler', ->
@minifyhtml.extensions.should.be.an.instanceOf(Array)
@minifyhtml.output.should.be.type('string')
@minifyhtml.compiler.should.be.ok
@minifyhtml.name.should.be.ok
it 'should minify a string', (done) ->
@minifyhtml.render('<div class="hi" id="">\n <p>hello</p>\n</div>')
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyhtml, res, path.join(@path, 'string.html'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.html')
@minifyhtml.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyhtml, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.html')
@minifyhtml.renderFile(lpath, { collapseWhitespace: false })
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyhtml, res, lpath, done))
it 'should not be able to compile', (done) ->
@minifyhtml.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@minifyhtml.render("<<<{@$@#$")
.done(should.not.exist, (-> done()))
describe 'csso', ->
before ->
@csso = accord.load('csso')
@path = path.join(__dirname, 'fixtures', 'csso')
it 'should expose name, extensions, output, and compiler', ->
@csso.extensions.should.be.an.instanceOf(Array)
@csso.output.should.be.type('string')
@csso.compiler.should.be.ok
@csso.name.should.be.ok
it 'should minify a string', (done) ->
@csso.render(".hello { foo: bar; }\n .hello { color: green }")
.catch(should.not.exist)
.done((res) => should.match_expected(@csso, res, path.join(@path, 'string.css'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.css')
@csso.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@csso, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.css')
@csso.renderFile(lpath, { noRestructure: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@csso, res, lpath, done))
it 'should not be able to compile', (done) ->
@csso.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@csso.render("wow")
.done(should.not.exist, (-> done()))
describe 'mustache', ->
before ->
@mustache = accord.load('mustache')
@path = path.join(__dirname, 'fixtures', 'mustache')
it 'should expose name, extensions, output, and compiler', ->
@mustache.extensions.should.be.an.instanceOf(Array)
@mustache.output.should.be.type('string')
@mustache.compiler.should.be.ok
@mustache.name.should.be.ok
it 'should render a string', (done) ->
@mustache.render("Why hello, {{ name }}!", { name: 'dogeudle' })
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res, path.join(@path, 'string.mustache'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.mustache')
@mustache.renderFile(lpath, { name: 'doge', winner: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res, lpath, done))
it 'should compile a string', (done) ->
@mustache.compile("Wow, such {{ noun }}")
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res.render({noun: 'compile'}), path.join(@path, 'pstring.mustache'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.mustache')
@mustache.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res.render({name: 'foo'}), lpath, done))
it 'client compile should work', (done) ->
lpath = path.join(@path, 'client-complex.mustache')
@mustache.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@mustache.clientHelpers()}; var tpl = #{res} tpl.render({ wow: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@mustache, tpl, lpath, done)
it 'should handle partials', (done) ->
lpath = path.join(@path, 'partial.mustache')
@mustache.renderFile(lpath, { foo: 'bar', partials: { partial: 'foo {{ foo }}' } })
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res, lpath, done))
it 'should correctly handle errors', (done) ->
@mustache.render("{{# !@{!# }}")
.done(should.not.exist, (-> done()))
describe 'dogescript', ->
before ->
@doge = accord.load('dogescript')
@path = path.join(__dirname, 'fixtures', 'dogescript')
it 'should expose name, extensions, output, and compiler', ->
@doge.extensions.should.be.an.instanceOf(Array)
@doge.output.should.be.type('string')
@doge.compiler.should.be.ok
@doge.name.should.be.ok
it 'should render a string', (done) ->
@doge.render("console dose loge with 'wow'", { beautify: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@doge, res, path.join(@path, 'string.djs'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.djs')
@doge.renderFile(lpath, { trueDoge: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@doge, res, lpath, done))
it 'should not be able to compile', (done) ->
@doge.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
# it turns out that it's impossible for dogescript to throw an error
# which, honestly, is how it should be. so no test here.
describe 'handlebars', ->
before ->
@handlebars = accord.load('handlebars')
@path = path.join(__dirname, 'fixtures', 'handlebars')
it 'should expose name, extensions, output, and compiler', ->
@handlebars.extensions.should.be.an.instanceOf(Array)
@handlebars.output.should.be.type('string')
@handlebars.compiler.should.be.ok
@handlebars.name.should.be.ok
it 'should render a string', (done) ->
@handlebars.render('Hello there {{ name }}', { name: '<NAME>' })
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, path.join(@path, 'rstring.hbs'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.hbs')
@handlebars.renderFile(lpath, { compiler: 'handlebars' })
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, lpath, done))
it 'should compile a string', (done) ->
@handlebars.compile('Hello there {{ name }}')
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res({ name: '<NAME>' }), path.join(@path, 'pstring.hbs'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.hbs')
@handlebars.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res({ friend: '<NAME>' }), lpath, done))
it 'should client-compile a string', (done) ->
@handlebars.compileClient("Here comes the {{ thing }}")
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, path.join(@path, 'cstring.hbs'), done))
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.hbs')
@handlebars.compileFileClient(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.hbs')
@handlebars.renderFile(lpath, { partials: { foo: "<p>hello from a partial!</p>" }})
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.hbs')
@handlebars.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@handlebars.clientHelpers()}; var tpl = #{res}; tpl({ wow: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@handlebars, tpl, lpath, done)
it 'should correctly handle errors', (done) ->
@handlebars.render("{{# !@{!# }}")
.done(should.not.exist, (-> done()))
describe 'scss', ->
before ->
@scss = accord.load('scss')
@path = path.join(__dirname, 'fixtures', 'scss')
it 'should expose name, extensions, output, and compiler', ->
@scss.extensions.should.be.an.instanceOf(Array)
@scss.output.should.be.type('string')
@scss.compiler.should.be.ok
@scss.name.should.be.ok
it 'should render a string', (done) ->
@scss.render("$wow: 'red'; foo { bar: $wow; }")
.catch(should.not.exist)
.done((res) => should.match_expected(@scss, res, path.join(@path, 'string.scss'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.scss')
@scss.renderFile(lpath, { trueDoge: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@scss, res, lpath, done))
it 'should include external files', (done) ->
lpath = path.join(@path, 'external.scss')
@scss.renderFile(lpath, { includePaths: [@path] })
.catch(should.not.exist)
.done((res) => should.match_expected(@scss, res, lpath, done))
it 'should not be able to compile', (done) ->
@scss.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@scss.render("!@##%#$#^$")
.done(should.not.exist, (-> done()))
describe 'less', ->
before ->
@less = accord.load('less')
@path = path.join(__dirname, 'fixtures', 'less')
it 'should expose name, extensions, output, and compiler', ->
@less.extensions.should.be.an.instanceOf(Array)
@less.output.should.be.type('string')
@less.compiler.should.be.ok
@less.name.should.be.ok
it 'should render a string', (done) ->
@less.render(".foo { width: 100 + 20 }")
.catch(should.not.exist)
.done((res) => should.match_expected(@less, res, path.join(@path, 'string.less'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.less')
@less.renderFile(lpath, { trueDoge: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@less, res, lpath, done))
it 'should include external files', (done) ->
lpath = path.join(@path, 'external.less')
@less.renderFile(lpath, { paths: [@path] })
.catch(should.not.exist)
.done((res) => should.match_expected(@less, res, lpath, done))
it 'should not be able to compile', (done) ->
@less.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@less.render("!@##%#$#^$")
.done(should.not.exist, (-> done()))
describe 'coco', ->
before ->
@coco = accord.load('coco')
@path = path.join(__dirname, 'fixtures', 'coco')
it 'should expose name, extensions, output, and compiler', ->
@coco.extensions.should.be.an.instanceOf(Array)
@coco.output.should.be.type('string')
@coco.compiler.should.be.ok
@coco.name.should.be.ok
it 'should render a string', (done) ->
@coco.render("function test\n console.log('foo')", { bare: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@coco, res, path.join(@path, 'string.co'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.co')
@coco.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@coco, res, lpath, done))
it 'should not be able to compile', (done) ->
@coco.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@coco.render("!! --- )I%$_(I(YRTO")
.done(should.not.exist, (-> done()))
describe 'livescript', ->
before ->
@livescript = accord.load('LiveScript')
@path = path.join(__dirname, 'fixtures', 'livescript')
it 'should expose name, extensions, output, and compiler', ->
@livescript.extensions.should.be.an.instanceOf(Array)
@livescript.output.should.be.type('string')
@livescript.compiler.should.be.ok
@livescript.name.should.be.ok
it 'should render a string', (done) ->
@livescript.render("test = ~> console.log('foo')", { bare: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@livescript, res, path.join(@path, 'string.ls'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.ls')
@livescript.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@livescript, res, lpath, done))
it 'should not be able to compile', (done) ->
@livescript.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@livescript.render("!! --- )I%$_(I(YRTO")
.done(should.not.exist, (-> done()))
describe 'myth', ->
before ->
@myth = accord.load('myth')
@path = path.join(__dirname, 'fixtures', 'myth')
it 'should expose name, extensions, output, and compiler', ->
@myth.extensions.should.be.an.instanceOf(Array)
@myth.output.should.be.type('string')
@myth.compiler.should.be.ok
@myth.name.should.be.ok
it 'should render a string', (done) ->
@myth.render(".foo { transition: all 1s ease; }")
.catch(should.not.exist)
.done((res) => should.match_expected(@myth, res, path.join(@path, 'string.myth'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.myth')
@myth.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@myth, res, lpath, done))
it 'should not be able to compile', (done) ->
@myth.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@myth.render("!! --- )I%$_(I(YRTO")
.done(should.not.exist, (-> done()))
describe 'haml', ->
before ->
@haml = accord.load('haml')
@path = path.join(__dirname, 'fixtures', 'haml')
it 'should expose name, extensions, output, and compiler', ->
@haml.extensions.should.be.an.instanceOf(Array)
@haml.output.should.be.type('string')
@haml.compiler.should.be.ok
@haml.name.should.be.ok
it 'should render a string', (done) ->
@haml.render('%div.foo= "Whats up " + name', { name: '<NAME>' })
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res, path.join(@path, 'rstring.haml'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.haml')
@haml.renderFile(lpath, { compiler: 'haml' })
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res, lpath, done))
it 'should compile a string', (done) ->
@haml.compile('%p= "Hello there " + name')
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res({ name: '<NAME>' }), path.join(@path, 'pstring.haml'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.haml')
@haml.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res({ friend: 'doge' }), lpath, done))
it 'should not support client compiles', (done) ->
@haml.compileClient("%p= 'Here comes the ' + thing")
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@haml.render("%p= wow()")
.done(should.not.exist, (-> done()))
describe 'marc', ->
before ->
@marc = accord.load('marc')
@path = path.join(__dirname, 'fixtures', 'marc')
it 'should expose name, extensions, output, and compiler', ->
@marc.extensions.should.be.an.instanceOf(Array)
@marc.output.should.be.type('string')
@marc.compiler.should.be.ok
@marc.name.should.be.ok
it 'should render a string', (done) ->
@marc.render(
'I am using __markdown__ with {{label}}!'
data:
label: 'marc'
).catch(
should.not.exist
).done((res) =>
should.match_expected(@marc, res, path.join(@path, 'basic.md'), done)
)
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.md')
@marc.renderFile(lpath, data: {label: 'marc'})
.catch(should.not.exist)
.done((res) => should.match_expected(@marc, res, lpath, done))
it 'should not be able to compile', (done) ->
@marc.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
| true | should = require 'should'
path = require 'path'
accord = require '../'
require('./helpers')(should)
describe 'base functions', ->
it 'supports should work', ->
accord.supports('jade').should.be.ok
accord.supports('markdown').should.be.ok
accord.supports('marked').should.be.ok
accord.supports('blargh').should.not.be.ok
it 'load should work', ->
(-> accord.load('jade')).should.not.throw()
(-> accord.load('blargh')).should.throw()
it 'load should accept a custom path', ->
(-> accord.load('jade', path.join(__dirname, '../node_modules/jade'))).should.not.throw()
it 'all should return all adapters', ->
accord.all().should.be.type('object')
describe 'jade', ->
before ->
@jade = accord.load('jade')
@path = path.join(__dirname, 'fixtures', 'jade')
it 'should expose name, extensions, output, and compiler', ->
@jade.extensions.should.be.an.instanceOf(Array)
@jade.output.should.be.type('string')
@jade.compiler.should.be.ok
@jade.name.should.be.ok
it 'should render a string', (done) ->
@jade.render('p BLAHHHHH\np= foo', { foo: 'such options' })
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, path.join(@path, 'rstring.jade'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.jade')
@jade.renderFile(lpath, { foo: 'such options' })
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, lpath, done))
it 'should compile a string', (done) ->
@jade.compile("p why cant I shot web?\np= foo")
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res({foo: 'such options'}), path.join(@path, 'pstring.jade'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.jade')
@jade.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res({foo: 'such options'}), lpath, done))
it 'should client-compile a string', (done) ->
@jade.compileClient("p imma firin mah lazer!\np= foo", {foo: 'such options'})
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, path.join(@path, 'cstring.jade'), done))
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.jade')
@jade.compileFileClient(lpath, {foo: 'such options'})
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.jade')
@jade.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@jade, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.jade')
@jade.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@jade.clientHelpers()}#{res}; template({ wow: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@jade, tpl, lpath, done)
it 'should correctly handle errors', (done) ->
@jade.render("!= nonexistantfunction()")
.done(should.not.exist, (-> done()))
describe 'swig', ->
before ->
@swig = accord.load('swig')
@path = path.join(__dirname, 'fixtures', 'swig')
it 'should expose name, extensions, output, and compiler', ->
@swig.extensions.should.be.an.instanceOf(Array)
@swig.output.should.be.type('string')
@swig.compiler.should.be.ok
@swig.name.should.be.ok
it 'should render a string', (done) ->
@swig.render('<h1>{% if foo %}Bar{% endif %}</h1>', { locals: { foo: true } })
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, path.join(@path, 'string.swig'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.swig')
@swig.renderFile(lpath, { locals: { author: "PI:NAME:<NAME>END_PI" } })
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should compile a string', (done) ->
@swig.compile("<h1>{{ title }}</h1>")
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res({title: 'Hello!'}), path.join(@path, 'pstring.swig'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.swig')
@swig.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res({title: 'Hello!'}), lpath, done))
it 'should client-compile a string', (done) ->
@swig.compileClient("<h1>{% if foo %}Bar{% endif %}</h1>", {foo: true})
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, path.join(@path, 'cstring.swig'), done))
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.swig')
@swig.compileFileClient(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.swig')
@swig.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.swig')
@swig.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "window = {}; #{@swig.clientHelpers()};\n var tpl = (#{res});"
should.match_expected(@swig, tpl_string, lpath, done)
describe 'coffeescript', ->
before ->
@coffee = accord.load('coffee-script')
@path = path.join(__dirname, 'fixtures', 'coffee')
it 'should expose name, extensions, output, and compiler', ->
@coffee.extensions.should.be.an.instanceOf(Array)
@coffee.output.should.be.type('string')
@coffee.compiler.should.be.ok
@coffee.name.should.be.ok
it 'should render a string', (done) ->
@coffee.render('console.log "test"', { bare: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@coffee, res, path.join(@path, 'string.coffee'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.coffee')
@coffee.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@coffee, res, lpath, done))
it 'should not be able to compile', (done) ->
@coffee.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@coffee.render("! ---@#$$@%#$")
.done(should.not.exist, (-> done()))
describe 'stylus', ->
before ->
@stylus = accord.load('stylus')
@path = path.join(__dirname, 'fixtures', 'stylus')
it 'should expose name, extensions, output, and compiler', ->
@stylus.extensions.should.be.an.instanceOf(Array)
@stylus.output.should.be.type('string')
@stylus.compiler.should.be.ok
@stylus.name.should.be.ok
it 'should render a string', (done) ->
@stylus.render('.test\n foo: bar')
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'string.styl'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.styl')
@stylus.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should not be able to compile', (done) ->
@stylus.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should set normal options', (done) ->
opts =
paths: ['pluginz']
foo: 'bar'
lpath = path.join(@path, 'include1.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set defines', (done) ->
opts =
define: { foo: 'bar', baz: 'quux' }
@stylus.render('.test\n test: foo', opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'defines.styl'), done))
it 'should set includes', (done) ->
opts =
include: 'pluginz'
lpath = path.join(@path, 'include1.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set multiple includes', (done) ->
opts =
include: ['pluginz', 'extra_plugin']
lpath = path.join(@path, 'include2.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set imports', (done) ->
opts =
import: 'pluginz/lib'
lpath = path.join(@path, 'import1.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set multiple imports', (done) ->
opts =
import: ['pluginz/lib', 'pluginz/lib2']
lpath = path.join(@path, 'import2.styl')
@stylus.renderFile(lpath, opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, lpath, done))
it 'should set plugins', (done) ->
opts =
use: (style) ->
style.define('main-width', 500)
@stylus.render('.test\n foo: main-width', opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'plugins1.styl'), done))
it 'should set multiple plugins', (done) ->
opts =
use: [
((style) -> style.define('main-width', 500)),
((style) -> style.define('main-height', 200)),
]
@stylus.render('.test\n foo: main-width\n bar: main-height', opts)
.catch(should.not.exist)
.done((res) => should.match_expected(@stylus, res, path.join(@path, 'plugins2.styl'), done))
it 'should correctly handle errors', (done) ->
@stylus.render("214m2/3l")
.done(should.not.exist, (-> done()))
describe 'ejs', ->
before ->
@ejs = accord.load('ejs')
@path = path.join(__dirname, 'fixtures', 'ejs')
it 'should expose name, extensions, output, and compiler', ->
@ejs.extensions.should.be.an.instanceOf(Array)
@ejs.output.should.be.type('string')
@ejs.compiler.should.be.ok
@ejs.name.should.be.ok
it 'should render a string', (done) ->
@ejs.render('<p>ejs yah</p><p><%= foo%></p>', { foo: 'wow opts' })
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, path.join(@path, 'rstring.ejs'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.ejs')
@ejs.renderFile(lpath, { foo: 'wow opts' })
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, lpath, done))
it 'should compile a string', (done) ->
@ejs.compile("<p>precompilez</p><p><%= foo %></p>")
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res({foo: 'wow opts'}), path.join(@path, 'pstring.ejs'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.ejs')
@ejs.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res({foo: 'wow opts'}), lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.ejs')
@ejs.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, lpath, done))
it 'should client-compile a string', (done) ->
@ejs.compileClient("Woah look, a <%= thing %>")
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, path.join(@path, 'cstring.ejs'), done))
# ejs writes the filename to the function, which makes this
# not work cross-system as expected
it.skip 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.ejs')
@ejs.compileFileClient(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@ejs, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.ejs')
@ejs.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@ejs.clientHelpers()}; var tpl = #{res}; tpl({ foo: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@ejs, tpl, lpath, done)
it 'should correctly handle errors', (done) ->
@ejs.render("<%= wow() %>")
.done(should.not.exist, (-> done()))
describe 'markdown', ->
before ->
@markdown = accord.load('markdown')
@path = path.join(__dirname, 'fixtures', 'markdown')
it 'should expose name, extensions, output, and compiler', ->
@markdown.extensions.should.be.an.instanceOf(Array)
@markdown.output.should.be.type('string')
@markdown.compiler.should.be.ok
@markdown.name.should.be.ok
it 'should render a string', (done) ->
@markdown.render('hello **world**')
.catch(should.not.exist)
.done((res) => should.match_expected(@markdown, res, path.join(@path, 'string.md'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.md')
@markdown.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@markdown, res, lpath, done))
it 'should render with options', (done) ->
lpath = path.join(@path, 'opts.md')
@markdown.renderFile(lpath, {sanitize: true})
.catch(should.not.exist)
.done((res) => should.match_expected(@markdown, res, lpath, done))
it 'should not be able to compile', (done) ->
@markdown.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
describe 'minify-js', ->
before ->
@minifyjs = accord.load('minify-js')
@path = path.join(__dirname, 'fixtures', 'minify-js')
it 'should expose name, extensions, output, and compiler', ->
@minifyjs.extensions.should.be.an.instanceOf(Array)
@minifyjs.output.should.be.type('string')
@minifyjs.compiler.should.be.ok
@minifyjs.name.should.be.ok
it 'should minify a string', (done) ->
@minifyjs.render('var foo = "foobar";\nconsole.log(foo)')
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyjs, res, path.join(@path, 'string.js'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.js')
@minifyjs.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyjs, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.js')
@minifyjs.renderFile(lpath, { compress: false })
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyjs, res, lpath, done))
it 'should not be able to compile', (done) ->
@minifyjs.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@minifyjs.render("@#$%#I$$N%NI#$%I$PQ")
.done(should.not.exist, (-> done()))
describe 'minify-css', ->
before ->
@minifycss = accord.load('minify-css')
@path = path.join(__dirname, 'fixtures', 'minify-css')
it 'should expose name, extensions, output, and compiler', ->
@minifycss.extensions.should.be.an.instanceOf(Array)
@minifycss.output.should.be.type('string')
@minifycss.compiler.should.be.ok
@minifycss.name.should.be.ok
it 'should minify a string', (done) ->
@minifycss.render('.test {\n foo: bar;\n}')
.catch(should.not.exist)
.done((res) => should.match_expected(@minifycss, res, path.join(@path, 'string.css'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.css')
@minifycss.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@minifycss, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.css')
@minifycss.renderFile(lpath, { keepBreaks: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@minifycss, res, lpath, done))
it 'should not be able to compile', (done) ->
@minifycss.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@minifycss.render("FMWT$SP#TPO%M@#@#M!@@@")
.done(should.not.exist, (-> done()))
describe 'minify-html', ->
before ->
@minifyhtml = accord.load('minify-html')
@path = path.join(__dirname, 'fixtures', 'minify-html')
it 'should expose name, extensions, output, and compiler', ->
@minifyhtml.extensions.should.be.an.instanceOf(Array)
@minifyhtml.output.should.be.type('string')
@minifyhtml.compiler.should.be.ok
@minifyhtml.name.should.be.ok
it 'should minify a string', (done) ->
@minifyhtml.render('<div class="hi" id="">\n <p>hello</p>\n</div>')
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyhtml, res, path.join(@path, 'string.html'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.html')
@minifyhtml.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyhtml, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.html')
@minifyhtml.renderFile(lpath, { collapseWhitespace: false })
.catch(should.not.exist)
.done((res) => should.match_expected(@minifyhtml, res, lpath, done))
it 'should not be able to compile', (done) ->
@minifyhtml.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@minifyhtml.render("<<<{@$@#$")
.done(should.not.exist, (-> done()))
describe 'csso', ->
before ->
@csso = accord.load('csso')
@path = path.join(__dirname, 'fixtures', 'csso')
it 'should expose name, extensions, output, and compiler', ->
@csso.extensions.should.be.an.instanceOf(Array)
@csso.output.should.be.type('string')
@csso.compiler.should.be.ok
@csso.name.should.be.ok
it 'should minify a string', (done) ->
@csso.render(".hello { foo: bar; }\n .hello { color: green }")
.catch(should.not.exist)
.done((res) => should.match_expected(@csso, res, path.join(@path, 'string.css'), done))
it 'should minify a file', (done) ->
lpath = path.join(@path, 'basic.css')
@csso.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@csso, res, lpath, done))
it 'should minify with options', (done) ->
lpath = path.join(@path, 'opts.css')
@csso.renderFile(lpath, { noRestructure: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@csso, res, lpath, done))
it 'should not be able to compile', (done) ->
@csso.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@csso.render("wow")
.done(should.not.exist, (-> done()))
describe 'mustache', ->
before ->
@mustache = accord.load('mustache')
@path = path.join(__dirname, 'fixtures', 'mustache')
it 'should expose name, extensions, output, and compiler', ->
@mustache.extensions.should.be.an.instanceOf(Array)
@mustache.output.should.be.type('string')
@mustache.compiler.should.be.ok
@mustache.name.should.be.ok
it 'should render a string', (done) ->
@mustache.render("Why hello, {{ name }}!", { name: 'dogeudle' })
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res, path.join(@path, 'string.mustache'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.mustache')
@mustache.renderFile(lpath, { name: 'doge', winner: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res, lpath, done))
it 'should compile a string', (done) ->
@mustache.compile("Wow, such {{ noun }}")
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res.render({noun: 'compile'}), path.join(@path, 'pstring.mustache'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.mustache')
@mustache.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res.render({name: 'foo'}), lpath, done))
it 'client compile should work', (done) ->
lpath = path.join(@path, 'client-complex.mustache')
@mustache.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@mustache.clientHelpers()}; var tpl = #{res} tpl.render({ wow: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@mustache, tpl, lpath, done)
it 'should handle partials', (done) ->
lpath = path.join(@path, 'partial.mustache')
@mustache.renderFile(lpath, { foo: 'bar', partials: { partial: 'foo {{ foo }}' } })
.catch(should.not.exist)
.done((res) => should.match_expected(@mustache, res, lpath, done))
it 'should correctly handle errors', (done) ->
@mustache.render("{{# !@{!# }}")
.done(should.not.exist, (-> done()))
describe 'dogescript', ->
before ->
@doge = accord.load('dogescript')
@path = path.join(__dirname, 'fixtures', 'dogescript')
it 'should expose name, extensions, output, and compiler', ->
@doge.extensions.should.be.an.instanceOf(Array)
@doge.output.should.be.type('string')
@doge.compiler.should.be.ok
@doge.name.should.be.ok
it 'should render a string', (done) ->
@doge.render("console dose loge with 'wow'", { beautify: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@doge, res, path.join(@path, 'string.djs'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.djs')
@doge.renderFile(lpath, { trueDoge: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@doge, res, lpath, done))
it 'should not be able to compile', (done) ->
@doge.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
# it turns out that it's impossible for dogescript to throw an error
# which, honestly, is how it should be. so no test here.
describe 'handlebars', ->
before ->
@handlebars = accord.load('handlebars')
@path = path.join(__dirname, 'fixtures', 'handlebars')
it 'should expose name, extensions, output, and compiler', ->
@handlebars.extensions.should.be.an.instanceOf(Array)
@handlebars.output.should.be.type('string')
@handlebars.compiler.should.be.ok
@handlebars.name.should.be.ok
it 'should render a string', (done) ->
@handlebars.render('Hello there {{ name }}', { name: 'PI:NAME:<NAME>END_PI' })
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, path.join(@path, 'rstring.hbs'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.hbs')
@handlebars.renderFile(lpath, { compiler: 'handlebars' })
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, lpath, done))
it 'should compile a string', (done) ->
@handlebars.compile('Hello there {{ name }}')
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res({ name: 'PI:NAME:<NAME>END_PI' }), path.join(@path, 'pstring.hbs'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.hbs')
@handlebars.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res({ friend: 'PI:NAME:<NAME>END_PI' }), lpath, done))
it 'should client-compile a string', (done) ->
@handlebars.compileClient("Here comes the {{ thing }}")
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, path.join(@path, 'cstring.hbs'), done))
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.hbs')
@handlebars.compileFileClient(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.hbs')
@handlebars.renderFile(lpath, { partials: { foo: "<p>hello from a partial!</p>" }})
.catch(should.not.exist)
.done((res) => should.match_expected(@handlebars, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.hbs')
@handlebars.compileFileClient(lpath)
.catch(should.not.exist)
.done (res) =>
tpl_string = "#{@handlebars.clientHelpers()}; var tpl = #{res}; tpl({ wow: 'local' })"
tpl = eval.call(global, tpl_string)
should.match_expected(@handlebars, tpl, lpath, done)
it 'should correctly handle errors', (done) ->
@handlebars.render("{{# !@{!# }}")
.done(should.not.exist, (-> done()))
describe 'scss', ->
before ->
@scss = accord.load('scss')
@path = path.join(__dirname, 'fixtures', 'scss')
it 'should expose name, extensions, output, and compiler', ->
@scss.extensions.should.be.an.instanceOf(Array)
@scss.output.should.be.type('string')
@scss.compiler.should.be.ok
@scss.name.should.be.ok
it 'should render a string', (done) ->
@scss.render("$wow: 'red'; foo { bar: $wow; }")
.catch(should.not.exist)
.done((res) => should.match_expected(@scss, res, path.join(@path, 'string.scss'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.scss')
@scss.renderFile(lpath, { trueDoge: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@scss, res, lpath, done))
it 'should include external files', (done) ->
lpath = path.join(@path, 'external.scss')
@scss.renderFile(lpath, { includePaths: [@path] })
.catch(should.not.exist)
.done((res) => should.match_expected(@scss, res, lpath, done))
it 'should not be able to compile', (done) ->
@scss.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@scss.render("!@##%#$#^$")
.done(should.not.exist, (-> done()))
describe 'less', ->
before ->
@less = accord.load('less')
@path = path.join(__dirname, 'fixtures', 'less')
it 'should expose name, extensions, output, and compiler', ->
@less.extensions.should.be.an.instanceOf(Array)
@less.output.should.be.type('string')
@less.compiler.should.be.ok
@less.name.should.be.ok
it 'should render a string', (done) ->
@less.render(".foo { width: 100 + 20 }")
.catch(should.not.exist)
.done((res) => should.match_expected(@less, res, path.join(@path, 'string.less'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.less')
@less.renderFile(lpath, { trueDoge: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@less, res, lpath, done))
it 'should include external files', (done) ->
lpath = path.join(@path, 'external.less')
@less.renderFile(lpath, { paths: [@path] })
.catch(should.not.exist)
.done((res) => should.match_expected(@less, res, lpath, done))
it 'should not be able to compile', (done) ->
@less.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@less.render("!@##%#$#^$")
.done(should.not.exist, (-> done()))
describe 'coco', ->
before ->
@coco = accord.load('coco')
@path = path.join(__dirname, 'fixtures', 'coco')
it 'should expose name, extensions, output, and compiler', ->
@coco.extensions.should.be.an.instanceOf(Array)
@coco.output.should.be.type('string')
@coco.compiler.should.be.ok
@coco.name.should.be.ok
it 'should render a string', (done) ->
@coco.render("function test\n console.log('foo')", { bare: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@coco, res, path.join(@path, 'string.co'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.co')
@coco.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@coco, res, lpath, done))
it 'should not be able to compile', (done) ->
@coco.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@coco.render("!! --- )I%$_(I(YRTO")
.done(should.not.exist, (-> done()))
describe 'livescript', ->
before ->
@livescript = accord.load('LiveScript')
@path = path.join(__dirname, 'fixtures', 'livescript')
it 'should expose name, extensions, output, and compiler', ->
@livescript.extensions.should.be.an.instanceOf(Array)
@livescript.output.should.be.type('string')
@livescript.compiler.should.be.ok
@livescript.name.should.be.ok
it 'should render a string', (done) ->
@livescript.render("test = ~> console.log('foo')", { bare: true })
.catch(should.not.exist)
.done((res) => should.match_expected(@livescript, res, path.join(@path, 'string.ls'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.ls')
@livescript.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@livescript, res, lpath, done))
it 'should not be able to compile', (done) ->
@livescript.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@livescript.render("!! --- )I%$_(I(YRTO")
.done(should.not.exist, (-> done()))
describe 'myth', ->
before ->
@myth = accord.load('myth')
@path = path.join(__dirname, 'fixtures', 'myth')
it 'should expose name, extensions, output, and compiler', ->
@myth.extensions.should.be.an.instanceOf(Array)
@myth.output.should.be.type('string')
@myth.compiler.should.be.ok
@myth.name.should.be.ok
it 'should render a string', (done) ->
@myth.render(".foo { transition: all 1s ease; }")
.catch(should.not.exist)
.done((res) => should.match_expected(@myth, res, path.join(@path, 'string.myth'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.myth')
@myth.renderFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@myth, res, lpath, done))
it 'should not be able to compile', (done) ->
@myth.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@myth.render("!! --- )I%$_(I(YRTO")
.done(should.not.exist, (-> done()))
describe 'haml', ->
before ->
@haml = accord.load('haml')
@path = path.join(__dirname, 'fixtures', 'haml')
it 'should expose name, extensions, output, and compiler', ->
@haml.extensions.should.be.an.instanceOf(Array)
@haml.output.should.be.type('string')
@haml.compiler.should.be.ok
@haml.name.should.be.ok
it 'should render a string', (done) ->
@haml.render('%div.foo= "Whats up " + name', { name: 'PI:NAME:<NAME>END_PI' })
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res, path.join(@path, 'rstring.haml'), done))
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.haml')
@haml.renderFile(lpath, { compiler: 'haml' })
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res, lpath, done))
it 'should compile a string', (done) ->
@haml.compile('%p= "Hello there " + name')
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res({ name: 'PI:NAME:<NAME>END_PI' }), path.join(@path, 'pstring.haml'), done))
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.haml')
@haml.compileFile(lpath)
.catch(should.not.exist)
.done((res) => should.match_expected(@haml, res({ friend: 'doge' }), lpath, done))
it 'should not support client compiles', (done) ->
@haml.compileClient("%p= 'Here comes the ' + thing")
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
it 'should correctly handle errors', (done) ->
@haml.render("%p= wow()")
.done(should.not.exist, (-> done()))
describe 'marc', ->
before ->
@marc = accord.load('marc')
@path = path.join(__dirname, 'fixtures', 'marc')
it 'should expose name, extensions, output, and compiler', ->
@marc.extensions.should.be.an.instanceOf(Array)
@marc.output.should.be.type('string')
@marc.compiler.should.be.ok
@marc.name.should.be.ok
it 'should render a string', (done) ->
@marc.render(
'I am using __markdown__ with {{label}}!'
data:
label: 'marc'
).catch(
should.not.exist
).done((res) =>
should.match_expected(@marc, res, path.join(@path, 'basic.md'), done)
)
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.md')
@marc.renderFile(lpath, data: {label: 'marc'})
.catch(should.not.exist)
.done((res) => should.match_expected(@marc, res, lpath, done))
it 'should not be able to compile', (done) ->
@marc.compile()
.done(((r) -> should.not.exist(r); done()), ((r) -> should.exist(r); done()))
|
[
{
"context": "ooltip\n\n# Inspired by the original jQuery.tipsy by Jason Frame\n# https://github.com/jaz303/tipsy\n\n# Copyright (c",
"end": 71,
"score": 0.9716385006904602,
"start": 60,
"tag": "NAME",
"value": "Jason Frame"
},
{
"context": " jQuery.tipsy by Jason Frame\n# https://github.com/jaz303/tipsy\n\n# Copyright (c) 2014 Miclle\n# Licensed und",
"end": 99,
"score": 0.9997215270996094,
"start": 93,
"tag": "USERNAME",
"value": "jaz303"
},
{
"context": "ps://github.com/jaz303/tipsy\n\n# Copyright (c) 2014 Miclle\n# Licensed under MIT (https://github.com/mic",
"end": 129,
"score": 0.9612869024276733,
"start": 128,
"tag": "NAME",
"value": "M"
},
{
"context": "://github.com/jaz303/tipsy\n\n# Copyright (c) 2014 Miclle\n# Licensed under MIT (https://github.com/miclle/m",
"end": 134,
"score": 0.6082262992858887,
"start": 129,
"tag": "USERNAME",
"value": "iclle"
},
{
"context": "4 Miclle\n# Licensed under MIT (https://github.com/miclle/mice/blob/master/LICENSE)\n\n\n# Generated markup by",
"end": 182,
"score": 0.9993240833282471,
"start": 176,
"tag": "USERNAME",
"value": "miclle"
},
{
"context": ") else @options.placement\n\n autoToken = /\\s?auto?\\s?/i\n autoPlace = autoToken.test(placement)\n ",
"end": 3613,
"score": 0.7844271659851074,
"start": 3603,
"tag": "KEY",
"value": "auto?\\s?/i"
}
] | assets/javascripts/mice/tooltip.coffee | miclle/mice | 7 | # Mice: tooltip
# Inspired by the original jQuery.tipsy by Jason Frame
# https://github.com/jaz303/tipsy
# Copyright (c) 2014 Miclle
# Licensed under MIT (https://github.com/miclle/mice/blob/master/LICENSE)
# Generated markup by the plugin
# <div class="tooltip top" role="tooltip">
# <div class="arrow"></div>
# <div class="inner">Some tooltip text!</div>
# </div>
'use strict'
(($) ->
# TOOLTIP PUBLIC CLASS DEFINITION
# ===============================
class Tooltip
constructor: (element, options) ->
@type
@options
@enabled
@timeout
@hoverState
@$element = null
@init('tooltip', element, options)
init: (type, element, options) ->
@enabled = true
@type = type
@$element = $(element)
@options = @getOptions(options)
@$viewport = @options.viewport and $(@options.viewport.selector or @options.viewport)
for trigger in @options.trigger.split(' ')
if trigger == 'click'
@$element.on('click.' + @type, @options.selector, $.proxy(@toggle, @))
else if trigger != 'manual'
eventIn = if trigger == 'hover' then 'mouseenter' else 'focusin'
eventOut = if trigger == 'hover' then 'mouseleave' else 'focusout'
@$element.on((eventIn) + '.' + @type, @options.selector, $.proxy(@enter, @))
@$element.on((eventOut) + '.' + @type, @options.selector, $.proxy(@leave, @))
if @options.selector
@_options = $.extend({}, @options, { trigger: 'manual', selector: '' })
else
@fixTitle()
return
getDefault: ->
$.fn.tooltip.defaults
getOptions: (options) ->
options = $.extend({}, @getDefault(), @$element.data(), options)
options.delay = show: options.delay, hide: options.delay if options.delay and typeof options.delay == 'number'
options
getDelegateOptions: ->
options = {}
defaults = @getDefaults()
@_options and $.each @_options, (key, value) ->
options[key] = value if defaults[key] != value
options
enter: (obj) ->
self = if obj instanceof @constructor then obj else $(obj.currentTarget).data('mice.' + @type)
if !self
self = new @constructor(obj.currentTarget, @getDelegateOptions())
$(obj.currentTarget).data('mice.' + @type, self)
clearTimeout(@timeout)
self.hoverState = 'in'
return self.show() if !self.options.delay or !self.options.delay.show
self.timeout = setTimeout (-> self.show() if self.hoverState == 'in') , self.options.delay.show
leave: (obj) ->
self = if obj instanceof @constructor then obj else $(obj.currentTarget).data('mice.' + @type)
if !self
self = new @constructor(obj.currentTarget, @getDelegateOptions())
$(obj.currentTarget).data('mice.' + @type, self)
clearTimeout(self.timeout)
self.hoverState = 'out'
return self.hide() if !self.options.delay or !self.options.delay.hide
self.timeout = setTimeout (-> self.hide() if self.hoverState == 'out') , self.options.delay.hide
show: ->
e = $.Event('show.mice.'+@type)
if @getTitle() and @enabled
@$element.trigger e
inDom = $.contains(document.documentElement, @$element[0])
return if e.isDefaultPrevented() or !inDom
$tip = @tip()
@setContent()
$tip.addClass 'fade' if @options.animation
placement = if typeof @options.placement == 'function' then @options.placement.call(@, $tip[0], @$element[0]) else @options.placement
autoToken = /\s?auto?\s?/i
autoPlace = autoToken.test(placement)
placement = placement.replace(autoToken, '') or 'top' if autoPlace
$tip.detach().css({ top: 0, left: 0, display: 'block' }).addClass(placement).data('mice.' + @type, @)
if @options.container then $tip.appendTo(@options.container) else $tip.insertAfter(@$element)
pos = @getPosition()
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
if autoPlace
orgPlacement = placement
$parent = @$element.parent()
parentDim = @getPosition($parent)
placement = if placement == 'bottom' and pos.top + pos.height + actualHeight - parentDim.scroll > parentDim.height then 'top' else
if placement == 'top' and pos.top - parentDim.scroll - actualHeight < 0 then 'bottom' else
if placement == 'right' and pos.right + actualWidth > parentDim.width then 'left' else
if placement == 'left' and pos.left - actualWidth < parentDim.left then 'right' else placement
$tip.removeClass(orgPlacement).addClass(placement)
calculatedOffset = @getCalculatedOffset placement, pos, actualWidth, actualHeight
@applyPlacement calculatedOffset, placement
complete = =>
@$element.trigger('shown.mice.' + @type)
@hoverState = null
if $.support.transition and @$tip.hasClass('fade') then $tip.one('miceTransitionEnd', complete).emulateTransitionEnd(150) else complete()
applyPlacement: (offset, placement) ->
$tip = @tip()
width = $tip[0].offsetWidth
height = $tip[0].offsetHeight
# manually read margins because getBoundingClientRect includes difference
marginTop = parseInt($tip.css('margin-top'), 10)
marginLeft = parseInt($tip.css('margin-left'), 10)
# we must check for NaN for ie 8/9
offset.top = offset.top + if isNaN(marginTop) then 0 else marginTop
offset.left = offset.left + if isNaN(marginLeft) then 0 else marginLeft
# $.fn.offset doesn't round pixel values
# so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({ using: (props) -> $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) }, offset), 0)
$tip.addClass 'in'
# check to see if placing tip in new offset caused the tip to resize itself
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
offset.top = offset.top + height - actualHeight if placement == 'top' and actualHeight != height
delta = @getViewportAdjustedDelta placement, offset, actualWidth, actualHeight
if delta.left then offset.left += delta.left else offset.top += delta.top
arrowDelta = if delta.left then delta.left * 2 - width + actualWidth else delta.top * 2 - height + actualHeight
arrowPosition = if delta.left then 'left' else 'top'
arrowOffsetPosition = if delta.left then 'offsetWidth' else 'offsetHeight'
$tip.offset(offset)
@replaceArrow arrowDelta, $tip[0][arrowOffsetPosition], arrowPosition
replaceArrow: (delta, dimension, position) ->
@arrow().css(position, if delta then (50 * (1 - delta / dimension) + '%') else '')
setContent: ->
@tip().find('.inner')[if @options.html then 'html' else 'text'](@getTitle()).removeClass('fade in top bottom left right')
hide: ->
$tip = @tip()
e = $.Event('hide.mice.' + @type)
complete = =>
$tip.detach() if @hoverState != 'in'
@$element.trigger('hidden.mice.' + @type)
@$element.trigger(e)
return if e.isDefaultPrevented()
$tip.removeClass('in')
if $.support.transition and @$tip.hasClass('fade') then $tip.one('miceTransitionEnd', complete).emulateTransitionEnd(150) else complete()
@hoverState = null
@
fixTitle: ->
@$element.attr('data-original-title', @$element.attr('title') or '').removeAttr('title') if @$element.attr('title') or typeof (@$element.attr('data-original-title')) != 'string'
getPosition: ($element) ->
$element = $element or @$element
el = $element[0]
isBody = el.tagName == 'BODY'
return $.extend({}, (if (typeof el.getBoundingClientRect == 'function') then el.getBoundingClientRect() else null), {
scroll: if isBody then document.documentElement.scrollTop or document.body.scrollTop else $element.scrollTop()
width: if isBody then $(window).width() else $element.outerWidth()
height: if isBody then $(window).height() else $element.outerHeight()
}, if isBody then { top: 0, left: 0 } else $element.offset())
getCalculatedOffset: (placement, pos, actualWidth, actualHeight) ->
switch placement
when 'bottom' then { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 }
when 'top' then { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 }
when 'left' then { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth }
when 'right' then { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
getViewportAdjustedDelta: (placement, pos, actualWidth, actualHeight) ->
delta = { top: 0, left: 0 }
return delta if !@$viewport
viewportPadding = @options.viewport and @options.viewport.padding or 0
viewportDimensions = @getPosition @$viewport
if /right|left/.test placement
topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if topEdgeOffset < viewportDimensions.top #top overflow
delta.top = viewportDimensions.top - topEdgeOffset
else if bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height #bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
else
leftEdgeOffset = pos.left - viewportPadding
rightEdgeOffset = pos.left + viewportPadding + actualWidth
if leftEdgeOffset < viewportDimensions.left #left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
else if rightEdgeOffset > viewportDimensions.width #right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
delta
getTitle: ->
@$element.attr('data-original-title') or (if typeof @options.title == 'function' then @options.title.call(@$element[0]) else @options.title)
tip: ->
@$tip = @$tip or $(@options.template).addClass @options.contextual
arrow: ->
@$arrow = @$arrow or @tip().find('.arrow')
validate: ->
if !@$element[0].parentNode
@hide()
@$element = null
@options = null
enable: ->
@enabled = true
disable: ->
@enabled = false
toggleEnabled: ->
@enabled = !@enabled
toggle: (e) ->
self = @
if e
self = $(e.currentTarget).data('mice.' + @type)
if !self
self = new @constructor(e.currentTarget, @getDelegateOptions())
$(e.currentTarget).data('mice.' + @type, self)
if self.tip().hasClass('in') then self.leave(self) else self.enter(self)
destroy: ->
clearTimeout(@timeout)
@hide().$element.off('.' + @type).removeData('mice.' + @type)
# TOOLTIP PLUGIN DEFINITION
# =========================
$.fn.tooltip = (option) ->
@each ->
$element = $(@)
data = $element.data('mice.tooltip')
options = typeof option == 'object' and option
return if !data and option == 'destroy'
$element.data('mice.tooltip', (data = new Tooltip(@, options))) if !data
data[option]() if typeof option == 'string'
$.fn.tooltip.Constructor = Tooltip
# TOOLTIP PLUGIN DEFAULT OPTIONS
# =========================
$.fn.tooltip.defaults =
animation: true
placement: 'top'
contextual: ''
selector: false
template: '<div class="tooltip" role="tooltip"><div class="arrow"></div><div class="inner"></div></div>'
trigger: 'hover focus'
title: ''
delay: 0
html: false
container: false
viewport:
selector: 'body'
padding: 0
$ -> $("[data-toggle=tooltip]").tooltip()
return
) jQuery | 215547 | # Mice: tooltip
# Inspired by the original jQuery.tipsy by <NAME>
# https://github.com/jaz303/tipsy
# Copyright (c) 2014 <NAME>iclle
# Licensed under MIT (https://github.com/miclle/mice/blob/master/LICENSE)
# Generated markup by the plugin
# <div class="tooltip top" role="tooltip">
# <div class="arrow"></div>
# <div class="inner">Some tooltip text!</div>
# </div>
'use strict'
(($) ->
# TOOLTIP PUBLIC CLASS DEFINITION
# ===============================
class Tooltip
constructor: (element, options) ->
@type
@options
@enabled
@timeout
@hoverState
@$element = null
@init('tooltip', element, options)
init: (type, element, options) ->
@enabled = true
@type = type
@$element = $(element)
@options = @getOptions(options)
@$viewport = @options.viewport and $(@options.viewport.selector or @options.viewport)
for trigger in @options.trigger.split(' ')
if trigger == 'click'
@$element.on('click.' + @type, @options.selector, $.proxy(@toggle, @))
else if trigger != 'manual'
eventIn = if trigger == 'hover' then 'mouseenter' else 'focusin'
eventOut = if trigger == 'hover' then 'mouseleave' else 'focusout'
@$element.on((eventIn) + '.' + @type, @options.selector, $.proxy(@enter, @))
@$element.on((eventOut) + '.' + @type, @options.selector, $.proxy(@leave, @))
if @options.selector
@_options = $.extend({}, @options, { trigger: 'manual', selector: '' })
else
@fixTitle()
return
getDefault: ->
$.fn.tooltip.defaults
getOptions: (options) ->
options = $.extend({}, @getDefault(), @$element.data(), options)
options.delay = show: options.delay, hide: options.delay if options.delay and typeof options.delay == 'number'
options
getDelegateOptions: ->
options = {}
defaults = @getDefaults()
@_options and $.each @_options, (key, value) ->
options[key] = value if defaults[key] != value
options
enter: (obj) ->
self = if obj instanceof @constructor then obj else $(obj.currentTarget).data('mice.' + @type)
if !self
self = new @constructor(obj.currentTarget, @getDelegateOptions())
$(obj.currentTarget).data('mice.' + @type, self)
clearTimeout(@timeout)
self.hoverState = 'in'
return self.show() if !self.options.delay or !self.options.delay.show
self.timeout = setTimeout (-> self.show() if self.hoverState == 'in') , self.options.delay.show
leave: (obj) ->
self = if obj instanceof @constructor then obj else $(obj.currentTarget).data('mice.' + @type)
if !self
self = new @constructor(obj.currentTarget, @getDelegateOptions())
$(obj.currentTarget).data('mice.' + @type, self)
clearTimeout(self.timeout)
self.hoverState = 'out'
return self.hide() if !self.options.delay or !self.options.delay.hide
self.timeout = setTimeout (-> self.hide() if self.hoverState == 'out') , self.options.delay.hide
show: ->
e = $.Event('show.mice.'+@type)
if @getTitle() and @enabled
@$element.trigger e
inDom = $.contains(document.documentElement, @$element[0])
return if e.isDefaultPrevented() or !inDom
$tip = @tip()
@setContent()
$tip.addClass 'fade' if @options.animation
placement = if typeof @options.placement == 'function' then @options.placement.call(@, $tip[0], @$element[0]) else @options.placement
autoToken = /\s?<KEY>
autoPlace = autoToken.test(placement)
placement = placement.replace(autoToken, '') or 'top' if autoPlace
$tip.detach().css({ top: 0, left: 0, display: 'block' }).addClass(placement).data('mice.' + @type, @)
if @options.container then $tip.appendTo(@options.container) else $tip.insertAfter(@$element)
pos = @getPosition()
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
if autoPlace
orgPlacement = placement
$parent = @$element.parent()
parentDim = @getPosition($parent)
placement = if placement == 'bottom' and pos.top + pos.height + actualHeight - parentDim.scroll > parentDim.height then 'top' else
if placement == 'top' and pos.top - parentDim.scroll - actualHeight < 0 then 'bottom' else
if placement == 'right' and pos.right + actualWidth > parentDim.width then 'left' else
if placement == 'left' and pos.left - actualWidth < parentDim.left then 'right' else placement
$tip.removeClass(orgPlacement).addClass(placement)
calculatedOffset = @getCalculatedOffset placement, pos, actualWidth, actualHeight
@applyPlacement calculatedOffset, placement
complete = =>
@$element.trigger('shown.mice.' + @type)
@hoverState = null
if $.support.transition and @$tip.hasClass('fade') then $tip.one('miceTransitionEnd', complete).emulateTransitionEnd(150) else complete()
applyPlacement: (offset, placement) ->
$tip = @tip()
width = $tip[0].offsetWidth
height = $tip[0].offsetHeight
# manually read margins because getBoundingClientRect includes difference
marginTop = parseInt($tip.css('margin-top'), 10)
marginLeft = parseInt($tip.css('margin-left'), 10)
# we must check for NaN for ie 8/9
offset.top = offset.top + if isNaN(marginTop) then 0 else marginTop
offset.left = offset.left + if isNaN(marginLeft) then 0 else marginLeft
# $.fn.offset doesn't round pixel values
# so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({ using: (props) -> $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) }, offset), 0)
$tip.addClass 'in'
# check to see if placing tip in new offset caused the tip to resize itself
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
offset.top = offset.top + height - actualHeight if placement == 'top' and actualHeight != height
delta = @getViewportAdjustedDelta placement, offset, actualWidth, actualHeight
if delta.left then offset.left += delta.left else offset.top += delta.top
arrowDelta = if delta.left then delta.left * 2 - width + actualWidth else delta.top * 2 - height + actualHeight
arrowPosition = if delta.left then 'left' else 'top'
arrowOffsetPosition = if delta.left then 'offsetWidth' else 'offsetHeight'
$tip.offset(offset)
@replaceArrow arrowDelta, $tip[0][arrowOffsetPosition], arrowPosition
replaceArrow: (delta, dimension, position) ->
@arrow().css(position, if delta then (50 * (1 - delta / dimension) + '%') else '')
setContent: ->
@tip().find('.inner')[if @options.html then 'html' else 'text'](@getTitle()).removeClass('fade in top bottom left right')
hide: ->
$tip = @tip()
e = $.Event('hide.mice.' + @type)
complete = =>
$tip.detach() if @hoverState != 'in'
@$element.trigger('hidden.mice.' + @type)
@$element.trigger(e)
return if e.isDefaultPrevented()
$tip.removeClass('in')
if $.support.transition and @$tip.hasClass('fade') then $tip.one('miceTransitionEnd', complete).emulateTransitionEnd(150) else complete()
@hoverState = null
@
fixTitle: ->
@$element.attr('data-original-title', @$element.attr('title') or '').removeAttr('title') if @$element.attr('title') or typeof (@$element.attr('data-original-title')) != 'string'
getPosition: ($element) ->
$element = $element or @$element
el = $element[0]
isBody = el.tagName == 'BODY'
return $.extend({}, (if (typeof el.getBoundingClientRect == 'function') then el.getBoundingClientRect() else null), {
scroll: if isBody then document.documentElement.scrollTop or document.body.scrollTop else $element.scrollTop()
width: if isBody then $(window).width() else $element.outerWidth()
height: if isBody then $(window).height() else $element.outerHeight()
}, if isBody then { top: 0, left: 0 } else $element.offset())
getCalculatedOffset: (placement, pos, actualWidth, actualHeight) ->
switch placement
when 'bottom' then { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 }
when 'top' then { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 }
when 'left' then { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth }
when 'right' then { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
getViewportAdjustedDelta: (placement, pos, actualWidth, actualHeight) ->
delta = { top: 0, left: 0 }
return delta if !@$viewport
viewportPadding = @options.viewport and @options.viewport.padding or 0
viewportDimensions = @getPosition @$viewport
if /right|left/.test placement
topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if topEdgeOffset < viewportDimensions.top #top overflow
delta.top = viewportDimensions.top - topEdgeOffset
else if bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height #bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
else
leftEdgeOffset = pos.left - viewportPadding
rightEdgeOffset = pos.left + viewportPadding + actualWidth
if leftEdgeOffset < viewportDimensions.left #left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
else if rightEdgeOffset > viewportDimensions.width #right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
delta
getTitle: ->
@$element.attr('data-original-title') or (if typeof @options.title == 'function' then @options.title.call(@$element[0]) else @options.title)
tip: ->
@$tip = @$tip or $(@options.template).addClass @options.contextual
arrow: ->
@$arrow = @$arrow or @tip().find('.arrow')
validate: ->
if !@$element[0].parentNode
@hide()
@$element = null
@options = null
enable: ->
@enabled = true
disable: ->
@enabled = false
toggleEnabled: ->
@enabled = !@enabled
toggle: (e) ->
self = @
if e
self = $(e.currentTarget).data('mice.' + @type)
if !self
self = new @constructor(e.currentTarget, @getDelegateOptions())
$(e.currentTarget).data('mice.' + @type, self)
if self.tip().hasClass('in') then self.leave(self) else self.enter(self)
destroy: ->
clearTimeout(@timeout)
@hide().$element.off('.' + @type).removeData('mice.' + @type)
# TOOLTIP PLUGIN DEFINITION
# =========================
$.fn.tooltip = (option) ->
@each ->
$element = $(@)
data = $element.data('mice.tooltip')
options = typeof option == 'object' and option
return if !data and option == 'destroy'
$element.data('mice.tooltip', (data = new Tooltip(@, options))) if !data
data[option]() if typeof option == 'string'
$.fn.tooltip.Constructor = Tooltip
# TOOLTIP PLUGIN DEFAULT OPTIONS
# =========================
$.fn.tooltip.defaults =
animation: true
placement: 'top'
contextual: ''
selector: false
template: '<div class="tooltip" role="tooltip"><div class="arrow"></div><div class="inner"></div></div>'
trigger: 'hover focus'
title: ''
delay: 0
html: false
container: false
viewport:
selector: 'body'
padding: 0
$ -> $("[data-toggle=tooltip]").tooltip()
return
) jQuery | true | # Mice: tooltip
# Inspired by the original jQuery.tipsy by PI:NAME:<NAME>END_PI
# https://github.com/jaz303/tipsy
# Copyright (c) 2014 PI:NAME:<NAME>END_PIiclle
# Licensed under MIT (https://github.com/miclle/mice/blob/master/LICENSE)
# Generated markup by the plugin
# <div class="tooltip top" role="tooltip">
# <div class="arrow"></div>
# <div class="inner">Some tooltip text!</div>
# </div>
'use strict'
(($) ->
# TOOLTIP PUBLIC CLASS DEFINITION
# ===============================
class Tooltip
constructor: (element, options) ->
@type
@options
@enabled
@timeout
@hoverState
@$element = null
@init('tooltip', element, options)
init: (type, element, options) ->
@enabled = true
@type = type
@$element = $(element)
@options = @getOptions(options)
@$viewport = @options.viewport and $(@options.viewport.selector or @options.viewport)
for trigger in @options.trigger.split(' ')
if trigger == 'click'
@$element.on('click.' + @type, @options.selector, $.proxy(@toggle, @))
else if trigger != 'manual'
eventIn = if trigger == 'hover' then 'mouseenter' else 'focusin'
eventOut = if trigger == 'hover' then 'mouseleave' else 'focusout'
@$element.on((eventIn) + '.' + @type, @options.selector, $.proxy(@enter, @))
@$element.on((eventOut) + '.' + @type, @options.selector, $.proxy(@leave, @))
if @options.selector
@_options = $.extend({}, @options, { trigger: 'manual', selector: '' })
else
@fixTitle()
return
getDefault: ->
$.fn.tooltip.defaults
getOptions: (options) ->
options = $.extend({}, @getDefault(), @$element.data(), options)
options.delay = show: options.delay, hide: options.delay if options.delay and typeof options.delay == 'number'
options
getDelegateOptions: ->
options = {}
defaults = @getDefaults()
@_options and $.each @_options, (key, value) ->
options[key] = value if defaults[key] != value
options
enter: (obj) ->
self = if obj instanceof @constructor then obj else $(obj.currentTarget).data('mice.' + @type)
if !self
self = new @constructor(obj.currentTarget, @getDelegateOptions())
$(obj.currentTarget).data('mice.' + @type, self)
clearTimeout(@timeout)
self.hoverState = 'in'
return self.show() if !self.options.delay or !self.options.delay.show
self.timeout = setTimeout (-> self.show() if self.hoverState == 'in') , self.options.delay.show
leave: (obj) ->
self = if obj instanceof @constructor then obj else $(obj.currentTarget).data('mice.' + @type)
if !self
self = new @constructor(obj.currentTarget, @getDelegateOptions())
$(obj.currentTarget).data('mice.' + @type, self)
clearTimeout(self.timeout)
self.hoverState = 'out'
return self.hide() if !self.options.delay or !self.options.delay.hide
self.timeout = setTimeout (-> self.hide() if self.hoverState == 'out') , self.options.delay.hide
show: ->
e = $.Event('show.mice.'+@type)
if @getTitle() and @enabled
@$element.trigger e
inDom = $.contains(document.documentElement, @$element[0])
return if e.isDefaultPrevented() or !inDom
$tip = @tip()
@setContent()
$tip.addClass 'fade' if @options.animation
placement = if typeof @options.placement == 'function' then @options.placement.call(@, $tip[0], @$element[0]) else @options.placement
autoToken = /\s?PI:KEY:<KEY>END_PI
autoPlace = autoToken.test(placement)
placement = placement.replace(autoToken, '') or 'top' if autoPlace
$tip.detach().css({ top: 0, left: 0, display: 'block' }).addClass(placement).data('mice.' + @type, @)
if @options.container then $tip.appendTo(@options.container) else $tip.insertAfter(@$element)
pos = @getPosition()
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
if autoPlace
orgPlacement = placement
$parent = @$element.parent()
parentDim = @getPosition($parent)
placement = if placement == 'bottom' and pos.top + pos.height + actualHeight - parentDim.scroll > parentDim.height then 'top' else
if placement == 'top' and pos.top - parentDim.scroll - actualHeight < 0 then 'bottom' else
if placement == 'right' and pos.right + actualWidth > parentDim.width then 'left' else
if placement == 'left' and pos.left - actualWidth < parentDim.left then 'right' else placement
$tip.removeClass(orgPlacement).addClass(placement)
calculatedOffset = @getCalculatedOffset placement, pos, actualWidth, actualHeight
@applyPlacement calculatedOffset, placement
complete = =>
@$element.trigger('shown.mice.' + @type)
@hoverState = null
if $.support.transition and @$tip.hasClass('fade') then $tip.one('miceTransitionEnd', complete).emulateTransitionEnd(150) else complete()
applyPlacement: (offset, placement) ->
$tip = @tip()
width = $tip[0].offsetWidth
height = $tip[0].offsetHeight
# manually read margins because getBoundingClientRect includes difference
marginTop = parseInt($tip.css('margin-top'), 10)
marginLeft = parseInt($tip.css('margin-left'), 10)
# we must check for NaN for ie 8/9
offset.top = offset.top + if isNaN(marginTop) then 0 else marginTop
offset.left = offset.left + if isNaN(marginLeft) then 0 else marginLeft
# $.fn.offset doesn't round pixel values
# so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({ using: (props) -> $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) }, offset), 0)
$tip.addClass 'in'
# check to see if placing tip in new offset caused the tip to resize itself
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
offset.top = offset.top + height - actualHeight if placement == 'top' and actualHeight != height
delta = @getViewportAdjustedDelta placement, offset, actualWidth, actualHeight
if delta.left then offset.left += delta.left else offset.top += delta.top
arrowDelta = if delta.left then delta.left * 2 - width + actualWidth else delta.top * 2 - height + actualHeight
arrowPosition = if delta.left then 'left' else 'top'
arrowOffsetPosition = if delta.left then 'offsetWidth' else 'offsetHeight'
$tip.offset(offset)
@replaceArrow arrowDelta, $tip[0][arrowOffsetPosition], arrowPosition
replaceArrow: (delta, dimension, position) ->
@arrow().css(position, if delta then (50 * (1 - delta / dimension) + '%') else '')
setContent: ->
@tip().find('.inner')[if @options.html then 'html' else 'text'](@getTitle()).removeClass('fade in top bottom left right')
hide: ->
$tip = @tip()
e = $.Event('hide.mice.' + @type)
complete = =>
$tip.detach() if @hoverState != 'in'
@$element.trigger('hidden.mice.' + @type)
@$element.trigger(e)
return if e.isDefaultPrevented()
$tip.removeClass('in')
if $.support.transition and @$tip.hasClass('fade') then $tip.one('miceTransitionEnd', complete).emulateTransitionEnd(150) else complete()
@hoverState = null
@
fixTitle: ->
@$element.attr('data-original-title', @$element.attr('title') or '').removeAttr('title') if @$element.attr('title') or typeof (@$element.attr('data-original-title')) != 'string'
getPosition: ($element) ->
$element = $element or @$element
el = $element[0]
isBody = el.tagName == 'BODY'
return $.extend({}, (if (typeof el.getBoundingClientRect == 'function') then el.getBoundingClientRect() else null), {
scroll: if isBody then document.documentElement.scrollTop or document.body.scrollTop else $element.scrollTop()
width: if isBody then $(window).width() else $element.outerWidth()
height: if isBody then $(window).height() else $element.outerHeight()
}, if isBody then { top: 0, left: 0 } else $element.offset())
getCalculatedOffset: (placement, pos, actualWidth, actualHeight) ->
switch placement
when 'bottom' then { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 }
when 'top' then { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 }
when 'left' then { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth }
when 'right' then { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
getViewportAdjustedDelta: (placement, pos, actualWidth, actualHeight) ->
delta = { top: 0, left: 0 }
return delta if !@$viewport
viewportPadding = @options.viewport and @options.viewport.padding or 0
viewportDimensions = @getPosition @$viewport
if /right|left/.test placement
topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if topEdgeOffset < viewportDimensions.top #top overflow
delta.top = viewportDimensions.top - topEdgeOffset
else if bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height #bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
else
leftEdgeOffset = pos.left - viewportPadding
rightEdgeOffset = pos.left + viewportPadding + actualWidth
if leftEdgeOffset < viewportDimensions.left #left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
else if rightEdgeOffset > viewportDimensions.width #right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
delta
getTitle: ->
@$element.attr('data-original-title') or (if typeof @options.title == 'function' then @options.title.call(@$element[0]) else @options.title)
tip: ->
@$tip = @$tip or $(@options.template).addClass @options.contextual
arrow: ->
@$arrow = @$arrow or @tip().find('.arrow')
validate: ->
if !@$element[0].parentNode
@hide()
@$element = null
@options = null
enable: ->
@enabled = true
disable: ->
@enabled = false
toggleEnabled: ->
@enabled = !@enabled
toggle: (e) ->
self = @
if e
self = $(e.currentTarget).data('mice.' + @type)
if !self
self = new @constructor(e.currentTarget, @getDelegateOptions())
$(e.currentTarget).data('mice.' + @type, self)
if self.tip().hasClass('in') then self.leave(self) else self.enter(self)
destroy: ->
clearTimeout(@timeout)
@hide().$element.off('.' + @type).removeData('mice.' + @type)
# TOOLTIP PLUGIN DEFINITION
# =========================
$.fn.tooltip = (option) ->
@each ->
$element = $(@)
data = $element.data('mice.tooltip')
options = typeof option == 'object' and option
return if !data and option == 'destroy'
$element.data('mice.tooltip', (data = new Tooltip(@, options))) if !data
data[option]() if typeof option == 'string'
$.fn.tooltip.Constructor = Tooltip
# TOOLTIP PLUGIN DEFAULT OPTIONS
# =========================
$.fn.tooltip.defaults =
animation: true
placement: 'top'
contextual: ''
selector: false
template: '<div class="tooltip" role="tooltip"><div class="arrow"></div><div class="inner"></div></div>'
trigger: 'hover focus'
title: ''
delay: 0
html: false
container: false
viewport:
selector: 'body'
padding: 0
$ -> $("[data-toggle=tooltip]").tooltip()
return
) jQuery |
[
{
"context": "n’t work in Grunt Pelican:\n# # https://github.com/chuwy/grunt-pelican/issues/4\n# pelican:\n# \toptions:\n# \t",
"end": 608,
"score": 0.99932861328125,
"start": 603,
"tag": "USERNAME",
"value": "chuwy"
},
{
"context": "ve on GitHub, so no issue:\n# # https://github.com/sina-mfe\n# converthttps:\n# \tconfig:\n# \t\texpand: true\n# \t\tc",
"end": 1131,
"score": 0.9995391964912415,
"start": 1123,
"tag": "USERNAME",
"value": "sina-mfe"
},
{
"context": " Replace text, using regex\n# # https://github.com/yoniholmes/grunt-text-replace\n# replace:\n# \treplacehtml:\n# \t",
"end": 1578,
"score": 0.9996871948242188,
"start": 1568,
"tag": "USERNAME",
"value": "yoniholmes"
},
{
"context": "=\"$1\"></a>'\n# \t\t# GitCDN\n# \t\t# https://github.com/schme16/gitcdn.xyz\n# \t\t\tfrom: /http:\\/\\/kristinita.netlif",
"end": 3130,
"score": 0.999575138092041,
"start": 3123,
"tag": "USERNAME",
"value": "schme16"
},
{
"context": "sn't work for me, details:\n# # https://github.com/TCotton/grunt-posthtml/issues/3\n# # [INFO] Use grunt-juwa",
"end": 3844,
"score": 0.9995408058166504,
"start": 3837,
"tag": "USERNAME",
"value": "TCotton"
},
{
"context": "html, it fix this problem:\n# # https://github.com/posthtml/grunt-posthtml/issues/3\n# # https://www.npmjs.com",
"end": 3959,
"score": 0.9955555200576782,
"start": 3951,
"tag": "USERNAME",
"value": "posthtml"
},
{
"context": "# # Fix HTML markup errors\n# # https://github.com/gavinballard/grunt-htmltidy\n# # [BUG] I don't use, because bug",
"end": 4560,
"score": 0.9997426271438599,
"start": 4548,
"tag": "USERNAME",
"value": "gavinballard"
},
{
"context": " I don't use, because bug:\n# # https://github.com/gavinballard/grunt-htmltidy/issues/6\n# htmltidy:\n# \toptions:\n#",
"end": 4647,
"score": 0.9997442960739136,
"start": 4635,
"tag": "USERNAME",
"value": "gavinballard"
},
{
"context": "##########\n# # Validate HTML — https://github.com/rgladwell/grunt-html5-validate\n# # [BUG] Plugin doesn't wor",
"end": 5072,
"score": 0.9996759295463562,
"start": 5063,
"tag": "USERNAME",
"value": "rgladwell"
},
{
"context": "[BUG] Plugin doesn't work:\n# # https://github.com/rgladwell/grunt-html5-validate/issues/1\n# html5validate:\n\t#",
"end": 5157,
"score": 0.9996678233146667,
"start": 5148,
"tag": "USERNAME",
"value": "rgladwell"
},
{
"context": "#####\n# # Compress images:\n# # https://github.com/1000ch/grunt-image\n# # [BUG] Doesn't work with multiple ",
"end": 5353,
"score": 0.9995835423469543,
"start": 5347,
"tag": "USERNAME",
"value": "1000ch"
},
{
"context": "work with multiple images:\n# # https://github.com/1000ch/grunt-image/issues/29\n# image:\n# \tstatic:\n# \t\topt",
"end": 5440,
"score": 0.9995770454406738,
"start": 5434,
"tag": "USERNAME",
"value": "1000ch"
},
{
"context": "ok\n# # [BUG] Doesn't work:\n# # https://github.com/bazilio91/grunt-ngrok/issues/7\n# ngrok:\n# \toptions:\n# \t\taut",
"end": 5898,
"score": 0.9996554851531982,
"start": 5889,
"tag": "USERNAME",
"value": "bazilio91"
},
{
"context": "rok/issues/7\n# ngrok:\n# \toptions:\n# \t\tauthToken: '6FAzTiHpA7FhKkLKjUoQi_4TJMoSofsewziHE3XFC5J'\n# \tserver:\n# \t\tproto: 'https'\n\n\n# ##############",
"end": 6000,
"score": 0.7059662342071533,
"start": 5957,
"tag": "KEY",
"value": "6FAzTiHpA7FhKkLKjUoQi_4TJMoSofsewziHE3XFC5J"
},
{
"context": " features works incorrect:\n# # https://github.com/bahmutov/grunt-nice-package/issues/25\n# # https://github.c",
"end": 6267,
"score": 0.9997299909591675,
"start": 6259,
"tag": "USERNAME",
"value": "bahmutov"
},
{
"context": "unt-nice-package/issues/25\n# # https://github.com/bahmutov/grunt-nice-package/issues/26\n# # nicePackage shor",
"end": 6328,
"score": 0.999733567237854,
"start": 6320,
"tag": "USERNAME",
"value": "bahmutov"
},
{
"context": "or multiple commands, see:\n# # https://github.com/shama/grunt-gulp/issues/13\n# module.exports =\n# \tgulpti",
"end": 7243,
"score": 0.9990556240081787,
"start": 7238,
"tag": "USERNAME",
"value": "shama"
},
{
"context": "26718306/5951529\n# # https://pypi.org/project/yolk3k/\n# yolk:\n# \tcommand: 'pipenv run yolk -l -f lice",
"end": 7669,
"score": 0.5072622299194336,
"start": 7668,
"tag": "USERNAME",
"value": "3"
},
{
"context": "perFences now preserve tabs:\n# https://github.com/facelessuser/pymdown-extensions/issues/276\n# #################",
"end": 7816,
"score": 0.9996660351753235,
"start": 7804,
"tag": "USERNAME",
"value": "facelessuser"
},
{
"context": "s run before “eslint fix”:\n# # https://github.com/gespinha/grunt-indentator/issues/1\n# module.exports =\n# \to",
"end": 8141,
"score": 0.99948650598526,
"start": 8133,
"tag": "USERNAME",
"value": "gespinha"
},
{
"context": "erate invalid license files:\n# https://github.com/licenses/lice/issues/50\n# I can't file Grunt package for t",
"end": 8378,
"score": 0.960498034954071,
"start": 8370,
"tag": "USERNAME",
"value": "licenses"
},
{
"context": "doesn't work in AppVeyor:\n# \t# https://github.com/appveyor/ci/issues/2226\n# \tif process.platform == \"win32\"\n",
"end": 8732,
"score": 0.9962283968925476,
"start": 8724,
"tag": "USERNAME",
"value": "appveyor"
},
{
"context": "ce doesn\\'t work in AppVeyor — https://github.com/appveyor/ci/issues/2226\"'\n# \telse\n# \t\tcommand: 'pipenv run",
"end": 8869,
"score": 0.9945938587188721,
"start": 8861,
"tag": "USERNAME",
"value": "appveyor"
},
{
"context": "6\"'\n# \telse\n# \t\tcommand: 'pipenv run lice mit -o \"Sasha Chernykh\" --file output/LICENSE.md'\n\n\n# [DEPRECATED] Doesn",
"end": 8947,
"score": 0.9997761845588684,
"start": 8933,
"tag": "NAME",
"value": "Sasha Chernykh"
},
{
"context": "TML support for Grunt:\n# # https://github.com/posthtml/posthtml\n# # https://www.npmjs.com/package/grunt-",
"end": 10115,
"score": 0.5229086875915527,
"start": 10111,
"tag": "USERNAME",
"value": "html"
},
{
"context": "native “posthtml” version:\n# # https://github.com/TCotton/grunt-posthtml/issues/3\n# module.exports =\n# \topt",
"end": 10279,
"score": 0.9978471398353577,
"start": 10272,
"tag": "USERNAME",
"value": "TCotton"
},
{
"context": "fee-format make files wrong:\n# https://github.com/NotBobTheBuilder/grunt-coffee-format/issues/3\n# ##################",
"end": 11023,
"score": 0.9977853298187256,
"start": 11007,
"tag": "USERNAME",
"value": "NotBobTheBuilder"
},
{
"context": "ly than grunt-minify-html:\n# # https://github.com/anseki/htmlclean/issues/11#issuecomment-389386676\n# modu",
"end": 12052,
"score": 0.9996396899223328,
"start": 12046,
"tag": "USERNAME",
"value": "anseki"
},
{
"context": "386676\n# module.exports =\n# \t# https://github.com/Swaagie/minimize#options-1\n# \t# All set false by default:",
"end": 12146,
"score": 0.9994635581970215,
"start": 12139,
"tag": "USERNAME",
"value": "Swaagie"
},
{
"context": "All set false by default:\n# \t# https://github.com/Swaagie/minimize#options\n# \toptions:\n# \t\t# [INFO] I'm not",
"end": 12228,
"score": 0.9995182156562805,
"start": 12221,
"tag": "USERNAME",
"value": "Swaagie"
},
{
"context": "utes for older browsers:\n# \t\t# https://github.com/Swaagie/minimize#spare\n# \t\tspare: false\n# \t\t# [INFO] W3C ",
"end": 12356,
"score": 0.9994803667068481,
"start": 12349,
"tag": "USERNAME",
"value": "Swaagie"
},
{
"context": "d «eo is not defined» bug:\n# # https://github.com/xpressyoo/Email-Obfuscator/issues/1\n# document.getElementBy",
"end": 12991,
"score": 0.9972021579742432,
"start": 12982,
"tag": "USERNAME",
"value": "xpressyoo"
},
{
"context": "getElementById('obf').innerHTML = \\\n# '<n uers=\"znvygb:FnfunPurealxuRzcerffBsHavirefr@xevfgvavgn.eh?fh",
"end": 13081,
"score": 0.8021124005317688,
"start": 13079,
"tag": "EMAIL",
"value": "vy"
},
{
"context": "ementById('obf').innerHTML = \\\n# '<n uers=\"znvygb:FnfunPurealxuRzcerffBsHavirefr@xevfgvavgn.eh?fhowrpg=R-znvy gb ",
"end": 13097,
"score": 0.9839166402816772,
"start": 13084,
"tag": "EMAIL",
"value": "FnfunPurealxu"
},
{
"context": ").innerHTML = \\\n# '<n uers=\"znvygb:FnfunPurealxuRzcerffBsHavirefr@xevfgvavgn.eh?fhowrpg=R-znvy gb Fnfun Purealxu\" \\\n# gnetrg=\"_oy",
"end": 13128,
"score": 0.9956808090209961,
"start": 13099,
"tag": "EMAIL",
"value": "cerffBsHavirefr@xevfgvavgn.eh"
},
{
"context": "/css-purge/\n# Grunt wrapper:\n# https://github.com/dominikwilkowski/grunt-css-purge\n# Options:\n# https://www.npmjs.co",
"end": 13550,
"score": 0.999492883682251,
"start": 13534,
"tag": "USERNAME",
"value": "dominikwilkowski"
},
{
"context": " and Pipenv doesn't support:\n# https://github.com/btholt/grunt-flake8/issues/1\n# [WARNING] All linting pas",
"end": 14619,
"score": 0.9996358752250671,
"start": 14613,
"tag": "USERNAME",
"value": "btholt"
},
{
"context": "sed, if flake8 no installed:\n# https://github.com/btholt/grunt-flake8/issues/3#issuecomment-473383610\n# ##",
"end": 14725,
"score": 0.999640166759491,
"start": 14719,
"tag": "USERNAME",
"value": "btholt"
},
{
"context": "ogle-fonts-and-font-display/\n# https://github.com/google/fonts/issues/358\n\n# [INFO] “font-display: swap”, ",
"end": 15207,
"score": 0.9624457359313965,
"start": 15201,
"tag": "USERNAME",
"value": "google"
},
{
"context": " CoffeeScript via js2coffee.\n# https://github.com/js2coffee/js2coffee/issues/449#issuecomment-470128539\n# ###",
"end": 15869,
"score": 0.9084599614143372,
"start": 15860,
"tag": "USERNAME",
"value": "js2coffee"
},
{
"context": "# if CoffeeLint warnings:\n# \t# https://github.com/clutchski/coffeelint/blob/master/src/rules/non_empty_constr",
"end": 16089,
"score": 0.9996865391731262,
"start": 16080,
"tag": "USERNAME",
"value": "clutchski"
},
{
"context": "uctor_needs_parens.coffee\n# \t# https://github.com/clutchski/coffeelint/blob/master/src/rules/empty_constructo",
"end": 16198,
"score": 0.9996688961982727,
"start": 16189,
"tag": "USERNAME",
"value": "clutchski"
},
{
"context": "# 4. Bug for grunt-prettier:\n# https://github.com/poalrom/grunt-prettier/issues/20\n# ############\n# # Prett",
"end": 18493,
"score": 0.9996328353881836,
"start": 18486,
"tag": "USERNAME",
"value": "poalrom"
},
{
"context": "e examples:\n# Another users:\n# https://github.com/ChrisWren/grunt-link-checker/issues/28\n# Me:\n# “>> Resource",
"end": 19618,
"score": 0.999752402305603,
"start": 19609,
"tag": "USERNAME",
"value": "ChrisWren"
},
{
"context": "inks via node-simplecrawler:\n# https://github.com/chriswren/grunt-link-checker\n# https://www.npmjs.com/packag",
"end": 19937,
"score": 0.9997017979621887,
"start": 19928,
"tag": "USERNAME",
"value": "chriswren"
},
{
"context": " Node.js and Grunt versions:\n# https://github.com/mradcliffe/grunt-crawl/pull/15\n# ###############\n# # grunt-c",
"end": 20255,
"score": 0.9997135400772095,
"start": 20245,
"tag": "USERNAME",
"value": "mradcliffe"
},
{
"context": "sn’t support internal links:\n# https://github.com/tcort/markdown-link-check\n# Example:\n#\t[✖] ../Special/П",
"end": 20520,
"score": 0.9985995292663574,
"start": 20515,
"tag": "USERNAME",
"value": "tcort"
},
{
"context": "onger maintained since 2018:\n# https://github.com/purifycss/purifycss/issues/213\n# I migrate to PurgeCSS.\n# #",
"end": 21358,
"score": 0.9996182322502136,
"start": 21349,
"tag": "USERNAME",
"value": "purifycss"
},
{
"context": "esn’t work with grunt-newer:\n# https://github.com/purifycss/grunt-purifycss/issues/30\n# ###\n# module.exports ",
"end": 21793,
"score": 0.9995449185371399,
"start": 21784,
"tag": "USERNAME",
"value": "purifycss"
},
{
"context": "t, PurifyCSS doesn’t work:\n# \t\thttps://github.com/purifycss/purifycss/issues/194\n# \t\t###\n# \t\twhitelist: [\n# \t",
"end": 22127,
"score": 0.9996240139007568,
"start": 22118,
"tag": "USERNAME",
"value": "purifycss"
},
{
"context": "ained at March, 2019:\n# \t\t\t\t\t# https://github.com/clutchski/coffeelint/issues\n# \t\t\t\t\t# [INFO] Wildfire classe",
"end": 22399,
"score": 0.9996225833892822,
"start": 22390,
"tag": "USERNAME",
"value": "clutchski"
},
{
"context": "ire class separately:\n# \t\t\t\t\t# https://github.com/FullHuman/grunt-purgecss/issues/9\n# \t\t\t\t\t\".animate-flicker\"",
"end": 22626,
"score": 0.9994683861732483,
"start": 22617,
"tag": "USERNAME",
"value": "FullHuman"
},
{
"context": "n’t work for relative paths:\n# https://github.com/posthtml/grunt-posthtml/issues/4\n# 2. lazysizes plugin req",
"end": 26518,
"score": 0.9993553757667542,
"start": 26510,
"tag": "USERNAME",
"value": "posthtml"
},
{
"context": "unt-juwain-posthtml\n\n# [FIXED] https://github.com/posthtml/grunt-posthtml/issues/4\n# [NOTE] Default version ",
"end": 27042,
"score": 0.9991179704666138,
"start": 27034,
"tag": "USERNAME",
"value": "posthtml"
},
{
"context": "unt-juwain-posthtml version:\n# https://github.com/posthtml/grunt-posthtml/issues/3\n# ###\n# module.exports =\n",
"end": 27232,
"score": 0.9990087151527405,
"start": 27224,
"tag": "USERNAME",
"value": "posthtml"
},
{
"context": "pported loading=\"lazy\":\n# \t\t\t# https://github.com/mfranzke/loading-attribute-polyfill\n# \t\t\t# Polyfill proble",
"end": 27578,
"score": 0.9997183680534363,
"start": 27570,
"tag": "USERNAME",
"value": "mfranzke"
},
{
"context": "# \t\t\t# 1. It not valid:\n# \t\t\t# https://github.com/mfranzke/loading-attribute-polyfill/issues/90\n# \t\t\t# 2. Ad",
"end": 27690,
"score": 0.9997122287750244,
"start": 27682,
"tag": "USERNAME",
"value": "mfranzke"
},
{
"context": "tional syntax required:\n# \t\t\t# https://github.com/mfranzke/loading-attribute-polyfill#simple-image\n\n\n# \t\t\t# ",
"end": 27800,
"score": 0.9997187852859497,
"start": 27792,
"tag": "USERNAME",
"value": "mfranzke"
},
{
"context": "rk with relative paths:\n# \t\t\t# https://github.com/posthtml/posthtml-img-autosize/issues/17#issuecomment-7065",
"end": 28826,
"score": 0.9993196129798889,
"start": 28818,
"tag": "USERNAME",
"value": "posthtml"
},
{
"context": "ey obsolete:\n# # Esmangle:\n# # https://github.com/estools/esmangle\n# # Closure-compiler:\n# # https://github",
"end": 29837,
"score": 0.9986586570739746,
"start": 29830,
"tag": "USERNAME",
"value": "estools"
},
{
"context": "ngle\n# # Closure-compiler:\n# # https://github.com/gmarty/grunt-closure-compiler\n# # [INFO] Benchmark:\n# # ",
"end": 29898,
"score": 0.9985550045967102,
"start": 29892,
"tag": "USERNAME",
"value": "gmarty"
},
{
"context": " problems will not be fixed:\n# https://github.com/google/closure-compiler/issues/3729\n# https://github.com",
"end": 31245,
"score": 0.8505832552909851,
"start": 31239,
"tag": "USERNAME",
"value": "google"
},
{
"context": "closure-compiler/issues/3729\n# https://github.com/google/closure-compiler/issues/3727\n# https://stackoverf",
"end": 31302,
"score": 0.8919877409934998,
"start": 31296,
"tag": "USERNAME",
"value": "google"
},
{
"context": "e they obsolete:\n# Esmangle:\n# https://github.com/estools/esmangle\n# Closure-compiler:\n# https://github.com",
"end": 31699,
"score": 0.9599103927612305,
"start": 31692,
"tag": "USERNAME",
"value": "estools"
},
{
"context": "esmangle\n# Closure-compiler:\n# https://github.com/gmarty/grunt-closure-compiler\n# ###\n# module.exports =\n#",
"end": 31756,
"score": 0.867421567440033,
"start": 31750,
"tag": "USERNAME",
"value": "gmarty"
}
] | grunt/deprecated.coffee | Kristinita/--- | 6 | ######################
## Deprecated tasks ##
######################
# All buggy, obsolete and/or unneedable plugins.
# Save, because possibly I can use them again.
# [FIXME] Re-install grunt-eslint, when I will have a time:
# ################
# # grunt-eslint #
# ################
# module.exports =
# options:
# maxWarnings: 40
# lint:
# files: "<%= templates.paths.js %>"
# ###################
# ## grunt-pelican ##
# ###################
# # Pelican tasks from Grunt
# # https://www.npmjs.com/package/grunt-pelican
# # [WARNING] Pipenv doesn’t work in Grunt Pelican:
# # https://github.com/chuwy/grunt-pelican/issues/4
# pelican:
# options:
# contentDir: 'content'
# outputDir: 'output'
# build:
# configFile: 'pelicanconf.py'
# publish:
# configFile: 'publishconf.py'
##############################
## grunt-http-convert-https ##
##############################
# # Convert http to https
# # https://www.npmjs.com/package/grunt-http-convert-https
# # [BUG] plugin doesn't work, “Warning: Task "converthttps" not found”.
# # Author long time inactive on GitHub, so no issue:
# # https://github.com/sina-mfe
# converthttps:
# config:
# expand: true
# cwd: 'output'
# src: '**/*.html'
# dest: 'output'
# httpsJson:
# "imgur": [
# "http": "i.imgur.com"
# "https": "i.imgur.com"
# ]
########################
## grunt-text-replace ##
########################
# # [DECLINED] grunt-string-replace active maintained
# # https://www.npmjs.com/package/grunt-string-replace
# # Replace text, using regex
# # https://github.com/yoniholmes/grunt-text-replace
# replace:
# replacehtml:
# src: [ 'output/**/*.html' ]
# overwrite: true
# replacements: [
# ## [NOTE] Use (.|\n|\r) for any symbol, not (.|\n)
# ## [DEPRECATED] Cllipboard.js + Tooltipster for Rainbow
# ## http://ru.stackoverflow.com/a/582520/199934
# ## http://stackoverflow.com/a/33758293/5951529
# # {
# # from: /<pre><code class="(.+?)">((.|\n|\r)+?)<\/code><\/pre>/g
# # to: '<pre><code data-language="$1">$2</code><button class="SashaButton SashaTooltip">\
# <img class="SashaNotModify" src="../images/interface_images/clippy.svg" \
# alt="Clipboard button" width="13"></button></pre>'
# # }
# # Clipboard.js + Tooltipster for SuperFences
# # http://ru.stackoverflow.com/a/582520/199934
# # https://stackoverflow.com/a/33758435/5951529
# # <button> and <img> tags must be in one line;
# # no line breaks between them!
# from: /(<pre>)((.|\n|\r)+?)(<\/pre>(\s+?)<\/div>)/g
# to: '$1<button class="SashaButton SashaTooltip"><img class="SashaNotModify" \
# src="//gitcdn.xyz/repo/Kristinita/Kristinita.netlify.com/master/images/interface-images/clippy.svg" \
# alt="Clipboard button" width="13"></button>$2$4'
# # Fancybox and JQueryLazy images,
# from: /<img alt="([^"]+?)" src="(.+?)"( \/)?>/g
# to: '<a class="fancybox" href="$2"><img class="SashaLazy" \
# src="//gitcdn.xyz/repo/Kristinita/Kristinita.netlify.com\
# /master/images/interface-images/transparent-one-pixel.png" \
# data-src="$2" alt="$1"></a>'
# # GitCDN
# # https://github.com/schme16/gitcdn.xyz
# from: /http:\/\/kristinita.netlify.app\/(.+?)\.(js|css|ico|xml)/g
# to: '//gitcdn.xyz/repo/Kristinita/Kristinita.netlify.com/master/$1.$2'
# # Header permalink
# from: /(<p>\s*?<a name="(.+?)" id="(.+?)"><\/a>\s*?<\/p>\s+?<h\d+?>((.|\n|\r)+?))(<\/h\d+?>)/g
# to: '$1 <a class="headerlink" href="#$2" title="Permanent link">¶</a>$6'
# ]
# [DECLINED] Currently, I don’t need posthtml plugins
# ####################
# ## grunt-posthtml ##
# ####################
# # PostHTML wrapper for Grunt:
# # https://www.npmjs.com/package/grunt-posthtml
# # https://www.npmjs.com/package/posthtml
# # [NOTE] Any default PostHTML plugin doesn't work for me, details:
# # https://github.com/TCotton/grunt-posthtml/issues/3
# # [INFO] Use grunt-juwain-posthtml, it fix this problem:
# # https://github.com/posthtml/grunt-posthtml/issues/3
# # https://www.npmjs.com/package/grunt-juwain-posthtml
# posthtml:
# options:
# use: [
# require('posthtml-aria-tabs')()
# require('posthtml-doctype')(doctype : 'HTML 4.01 Frameset')
# require('posthtml-alt-always')()
# ]
# single:
# files: [
# src: '<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/KristinitaLuckyLink.html'
# dest: '<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/KristinitaLuckyLink.html'
# ]
# ####################
# ## grunt-htmltidy ##
# ####################
# # Fix HTML markup errors
# # https://github.com/gavinballard/grunt-htmltidy
# # [BUG] I don't use, because bug:
# # https://github.com/gavinballard/grunt-htmltidy/issues/6
# htmltidy:
# options:
# # indent: no
# # Disable line breaks
# # https://stackoverflow.com/a/7681425/5951529
# wrap: 0
# # 'vertical-space': no
# gingerinas:
# files: [
# expand: true
# cwd: 'output'
# src: '**/*.html'
# dest: 'output'
# ]
##########################
## grunt-html5-validate ##
##########################
# # Validate HTML — https://github.com/rgladwell/grunt-html5-validate
# # [BUG] Plugin doesn't work:
# # https://github.com/rgladwell/grunt-html5-validate/issues/1
# html5validate:
# src: 'output/IT-articles/*.html'
# #################
# ## grunt-image ##
# #################
# # Compress images:
# # https://github.com/1000ch/grunt-image
# # [BUG] Doesn't work with multiple images:
# # https://github.com/1000ch/grunt-image/issues/29
# image:
# static:
# options:
# pngquant: true
# optipng: true
# zopflipng: true
# jpegRecompress: true
# jpegoptim: true
# mozjpeg: true
# gifsicle: true
# svgo: true
# files:
# src: ['output/**/*.jpg']
# #################
# ## grunt-ngrok ##
# #################
# # ngrok implementation for Grunt
# # https://www.npmjs.com/package/grunt-ngrok
# # [BUG] Doesn't work:
# # https://github.com/bazilio91/grunt-ngrok/issues/7
# ngrok:
# options:
# authToken: '6FAzTiHpA7FhKkLKjUoQi_4TJMoSofsewziHE3XFC5J'
# server:
# proto: 'https'
# ########################
# ## grunt-nice-package ##
# ########################
# # package.json validator
# # https://www.npmjs.com/package/grunt-nice-package
# # [BUG] Some features works incorrect:
# # https://github.com/bahmutov/grunt-nice-package/issues/25
# # https://github.com/bahmutov/grunt-nice-package/issues/26
# # nicePackage shortcut:
# # https://www.npmjs.com/package/grunt-nice-package#alternative-default-options
# # "generate-package" generate package.json:
# # https://www.npmjs.com/package/generate-package
# # https://stackoverflow.com/a/49053110/5951529
# nicePackage:
# all:
# options:
# blankLine: false
# ###################
# ## gulp-htmltidy ##
# ###################
# # Validate HTML
# # https://www.npmjs.com/package/gulp-htmltidy
# ##########################
# ## grunt-gulp variables ##
# ##########################
# # https://www.npmjs.com/package/grunt-gulp#examples
# # CoffeeScript to JavaScript online — http://js2.coffee/
# gulp = require('gulp')
# htmltidy = require('gulp-htmltidy')
# # For in-place dest needs «base: "."», see:
# # https://stackoverflow.com/a/44337370/5951529
# # [BUG] Doesn't work for multiple commands, see:
# # https://github.com/shama/grunt-gulp/issues/13
# module.exports =
# gulptidy:
# gulp.src('<%= templates.paths.html %>', base: ".")
# .pipe(htmltidy(
# doctype: 'html5'
# indent: true
# wrap: 0)).pipe gulp.dest('./')
# [DECLINED] pip-licenses more customisable
# ############
# ## yolk3k ##
# ############
# # Generate licenses for all Python packages:
# # https://stackoverflow.com/a/26718306/5951529
# # https://pypi.org/project/yolk3k/
# yolk:
# command: 'pipenv run yolk -l -f license > python.txt'
# [DECLINED] SuperFences now preserve tabs:
# https://github.com/facelessuser/pymdown-extensions/issues/276
# ######################
# ## grunt-indentator ##
# ######################
# # Indent 4 spaces to tab:
# # https://www.npmjs.com/package/grunt-indentator
# # [WARNING]: Replace tabs to spaces only if first indentation — spaces:
# # Needs run before “eslint fix”:
# # https://github.com/gespinha/grunt-indentator/issues/1
# module.exports =
# options:
# type: 'tab'
# size: 1
# debug: true
# files:
# [
# "<%= templates.paths.html %>"
# ]
# [DEPRECATED] Generate invalid license files:
# https://github.com/licenses/lice/issues/50
# I can't file Grunt package for this task;
# license-generator output error in installation process:
# https://pypi.org/project/license-generator/
# ##########
# ## lice ##
# ##########
# # Generate license for project:
# # https://pypi.org/project/lice/
# lice:
# # [BUG] lice doesn't work in AppVeyor:
# # https://github.com/appveyor/ci/issues/2226
# if process.platform == "win32"
# command: 'echo "Sorry, lice doesn\'t work in AppVeyor — https://github.com/appveyor/ci/issues/2226"'
# else
# command: 'pipenv run lice mit -o "Sasha Chernykh" --file output/LICENSE.md'
# [DEPRECATED] Doesn't work for CSS paths
# #########################
# # grunt-path-absolutely #
# #########################
# # https://www.npmjs.com/package/grunt-path-absolutely
# module.exports =
# cssimages:
# options:
# devRoot: "."
# releaseRoot: "https://kristinita.netlify.app"
# resourceFilter: ["*.css"]
# files: [
# expand: true
# cwd: "."
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/css/aside/*.css"]
# dest: "."
# ]
# [DEPRECATED] Doesn't allow to have comments in JSON configuration files:
# #############################
# # grunt-strip-json-comments #
# #############################
# # Delete comments in JSON files
# # https://www.npmjs.com/package/strip-json-comments
# # https://www.npmjs.com/package/grunt-strip-json-comments
# stripJsonComments:
# dist:
# options:
# whitespace: false
# files:
# '.jsbeautifyrc': '.jsbeautifyrc'
# [DEPRECATED] I don't see plugins, that can come in handy
# ####################
# ## grunt-posthtml ##
# ####################
# # PostHTML support for Grunt:
# # https://github.com/posthtml/posthtml
# # https://www.npmjs.com/package/grunt-juwain-posthtml
# # [WARNING] Use “juwain-posthtml”, not native “posthtml” version:
# # https://github.com/TCotton/grunt-posthtml/issues/3
# module.exports =
# options:
# use: [
# #############
# # ARIA Tabs #
# #############
# # Add WAI-ARIA attributes:
# # http://prgssr.ru/development/ispolzovanie-aria-v-html5.html
# # http://jonathantneal.github.io/posthtml-aria-tabs/
# # [WARNING] Disable, because I use “ul/li” for progressive enhancements:
# # http://jonathantneal.github.io/posthtml-aria-tabs/#caveats
# # require('posthtml-aria-tabs')()
# ]
# build:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# src: ['**/*.html']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# ]
# [DEPRECATED][BUG] grunt-coffee-format make files wrong:
# https://github.com/NotBobTheBuilder/grunt-coffee-format/issues/3
# #######################
# # grunt-coffee-format #
# #######################
# # Formatter for CoffeeScript files:
# # https://www.npmjs.com/package/coffee-fmt
# # Grunt adapter:
# # https://www.npmjs.com/package/grunt-coffee-format
# module.exports =
# options:
# # [INFO] Use tabs, not spaces:
# # https://www.npmjs.com/package/grunt-coffee-format#optionstab
# tab: '\t'
# theme:
# files:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/coffee/**/*.coffee"]
# personal:
# files:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/coffee/**/*.coffee"]
# [DEPRECATED] I migrate to HTML-minifier, arguments:
# [LINK] “htmlmin.coffee”
# ############
# # minimize #
# ############
# # Minify HTML:
# # https://www.npmjs.com/package/minimize
# # https://www.npmjs.com/package/grunt-minify-html
# # [NOTE] Use HTML parser, grunt-contrib-htmlmin use regexes.
# # grunt-htmlclean simply than grunt-minify-html:
# # https://github.com/anseki/htmlclean/issues/11#issuecomment-389386676
# module.exports =
# # https://github.com/Swaagie/minimize#options-1
# # All set false by default:
# # https://github.com/Swaagie/minimize#options
# options:
# # [INFO] I'm not support spare attirbutes for older browsers:
# # https://github.com/Swaagie/minimize#spare
# spare: false
# # [INFO] W3C recommends quotes:
# # https://www.w3schools.com/html/html_attributes.asp
# quotes: true
# minimize:
# files: [
# expand: true
# cwd: "."
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/**/*.html"]
# dest: "."
# ]
# [DECLINED] I hate private discussions
# #########
# # ROT13 #
# #########
# # ROT13 algorithm for e-mail obfuscation:
# # https://en.wikipedia.org/wiki/ROT13
# # https://superuser.com/a/235965/572069
# # Generated by:
# # http://rot13.florianbersier.com/
# # [NOTE] In this script fixed «eo is not defined» bug:
# # https://github.com/xpressyoo/Email-Obfuscator/issues/1
# document.getElementById('obf').innerHTML = \
# '<n uers="znvygb:FnfunPurealxuRzcerffBsHavirefr@xevfgvavgn.eh?fhowrpg=R-znvy gb Fnfun Purealxu" \
# gnetrg="_oynax">r-znvy</n>'.replace(/[a-zA-Z]/g, (c) ->
# String.fromCharCode if (if c <= 'Z' then 90 else 122) >= (c = c.charCodeAt(0) + 13) then c else c - 26
# )
# [DEPRECATED] Compress files as cssnano; don't remove duplicates
#############
# css-purge #
#############
# Compress CSS:
# http://rbtech.github.io/css-purge/
# Grunt wrapper:
# https://github.com/dominikwilkowski/grunt-css-purge
# Options:
# https://www.npmjs.com/package/css-purge#config-options
# module.exports =
# task:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/css"
# src: ['!**/**/*.css'
# '**/**/*.min.css']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/css"
# ext: '.min.css'
# ]
# [DEPRECATED] UNCSS build all CSS files to single;
# behavior not similar as PurgeCSS and PurifyCSS
###############
# grunt-uncss #
###############
# module.exports =
# options:
# uncssrc: ".uncssrc"
# sublimetexttarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Sublime-Text/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"
# [DEPRECATED]
# Virtual environment and Pipenv doesn't support:
# https://github.com/btholt/grunt-flake8/issues/1
# [WARNING] All linting passed, if flake8 no installed:
# https://github.com/btholt/grunt-flake8/issues/3#issuecomment-473383610
# ##########
# # flake8 #
# ##########
# module.exports =
# dist:
# src: ["*.py"
# "personal-plugins/**/*.py"]
# [DEPRECATED]
# Google Fonts support “font-display: swap” from May 2019:
# https://www.zachleat.com/web/google-fonts-display/
# ###
# Load Google Fonts
# [NOTE] Script required, because Google Fonts doesn't support “font-display”:
# https://css-tricks.com/google-fonts-and-font-display/
# https://github.com/google/fonts/issues/358
# [INFO] “font-display: swap”, that:
# 1. Default font will show to site visitors before Google font
# 2. Fix “Ensure text remains visible during webfont load” of PageSpeed Insights
# https://web.dev/fast/avoid-invisible-text
# https://developers.google.com/web/updates/2016/02/font-display
# [INFO] If “font-display: swap”, sit visitor see text without any delay:
# https://font-display.glitch.me/
# [LEARN][COFFEESCRIPT] For converting EcmaScript 6 to CoffeeScript:
# 1. Convert EcmaScript 6 to JavaScript. Online converter — https://babeljs.io/en/repl .
# 2. Convert JavaScript to CoffeeScript via js2coffee.
# https://github.com/js2coffee/js2coffee/issues/449#issuecomment-470128539
# ###
# loadFont = (url) ->
# # [LEARN][COFFEESCRIPT] Wrap constructor to parens (parentheses, round brackets),
# # if CoffeeLint warnings:
# # https://github.com/clutchski/coffeelint/blob/master/src/rules/non_empty_constructor_needs_parens.coffee
# # https://github.com/clutchski/coffeelint/blob/master/src/rules/empty_constructor_needs_parens.coffee
# xhr = new (XMLHttpRequest)
# xhr.open 'GET', url, true
# xhr.onreadystatechange = ->
# if xhr.readyState is 4 and xhr.status is 200
# css = xhr.responseText
# css = css.replace(/}/g, 'font-display: swap; }')
# head = document.getElementsByTagName('head')[0]
# style = document.createElement('style')
# style.appendChild document.createTextNode(css)
# head.appendChild style
# return
# xhr.send()
# return
# loadFont 'https://fonts.googleapis.com/css?family=Play:700\
# |El+Messiri|Scada:700i|Fira+Mono|Marck+Script&subset=cyrillic&display=swap'
# [DEPRECATED]
# Linux — it not needed; Linux doesn't lock opened files and folders$
# see “You Can Delete or Modify Open Files”:
# https://www.howtogeek.com/137096/6-ways-the-linux-file-system-is-different-from-the-windows-file-system/
# Windows — it not unlock files or folders as any another program:
# https://superuser.com/q/1485406/572069
###############
# grunt-chmod #
###############
# # Add read and write permissions for all output folders and files:
# # https://www.npmjs.com/package/grunt-chmod
# # About chmod:
# # https://ss64.com/bash/chmod.html
# # [DESCRIPTION]
# # I open any files → I run “publishconf.py”, that delete “output” folder →
# # I can get errors as:
# # ERROR: Unable to delete directory D:\Kristinita\output\stylus; OSError: [WinError 145]
# # The directory is not empty: 'D:\\Kristinita\\output\\stylus\\personal'
# # chmod fix this problem.
# # [WARNING] You need close BrowserSync before publishing,
# # because it can create new permissions.
# module.exports =
# options:
# # [NOTE] 444 and 666 modes works in Windows:
# # https://www.npmjs.com/package/grunt-chmod#warnings
# mode: '666'
# kiratarget:
# # [LEARN][GRUNT] All folders and files recursive, include current:
# # https://gruntjs.com/configuring-tasks#globbing-patterns
# src: "<%= templates.yamlconfig.OUTPUT_PATH %>/**"
# [DECLINED]
# 1. JSBeautifier is more powerful tool
# 2. JSBeautifier has many options; Prettier — minimal set, see options philosophy:
# https://prettier.io/docs/en/option-philosophy.html
# 3. Strange HTML prettifying for Prettier
# 4. Bug for grunt-prettier:
# https://github.com/poalrom/grunt-prettier/issues/20
# ############
# # Prettier #
# ############
# # Prettifier for many formats, include css, javascript:
# # https://prettier.io/
# # Grunt wrapper:
# # https://www.npmjs.com/package/grunt-prettier
# # Options:
# # https://prettier.io/docs/en/options.html
# module.exports =
# cssdebug:
# # [NOTE] “ext: '.min.{css,js}'” will not work;
# # Grunt will generate file “kirafile.min.{css,js}”
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# src: ['**/*.css'
# '!**/*.min.css']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# ]
# jsdebug:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# src: ['**/*.js'
# '!**/*.min.js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# ]
# # htmldebug:
# # files: [
# # expand: true
# # cwd: "."
# # src: "<%= templates.yamlconfig.OUTPUT_PATH %>/Books-Reviews/Как-читать-архитектуру.html"
# # dest: "."
# # ]
# [DEPRECATED]
# [BUG] Checker works incorectly with encoded URLs, see examples:
# Another users:
# https://github.com/ChrisWren/grunt-link-checker/issues/28
# Me:
# “>> Resource not found linked from https://kristinita.netlify.app/opensearch.xml
# to https://kristinita.netlify.app/favicon16%C3%9716.ico”
# ################
# # link-checker #
# ################
# ###
# [PURPOSE] Check links via node-simplecrawler:
# https://github.com/chriswren/grunt-link-checker
# https://www.npmjs.com/package/simplecrawler
# ###
# module.exports =
# development:
# site: "kristinita.netlify.app"
# options:
# checkRedirect: true
# noFragment: false
# [DEPRECATED] grunt-crawl doesn’t support the newest Node.js and Grunt versions:
# https://github.com/mradcliffe/grunt-crawl/pull/15
# ###############
# # grunt-crawl #
# ###############
# ###
# [INFO] Grunt crawler; possibly, check URLs:
# https://www.npmjs.com/package/grunt-crawl
#
# [NOTE] markdown-link-check tool doesn’t support internal links:
# https://github.com/tcort/markdown-link-check
# Example:
# [✖] ../Special/Полная-библиография#Открытость → Status: 400
# ###
# module.exports =
# myapp:
# options:
# baseUrl: "http://localhost:4147/"
# contentDir: "output"
# [FIXME][ISSUE] 2 problems:
# 1. grunt-blank audit failed, but manually with (TreeSize Free) review shows,
# that I haven’t files < 2 bytes
# 2. grunt-blank doesn’t show, which files lower that 2 bytes.
# ###############
# # grunt-blank #
# ###############
# # [PURPOSE] Check files with size lower than “minBytes”:
# # https://www.npmjs.com/package/grunt-blank
# module.exports =
# options:
# minBytes: 2
# task:
# src: [
# "<%= templates.yamlconfig.CONTENT_PATH %>"
# "<%= templates.yamlconfig.THEME_STATIC_DIR %>"
# ]
# [DECLINED] The project no longer maintained since 2018:
# https://github.com/purifycss/purifycss/issues/213
# I migrate to PurgeCSS.
# #####################
# ## grunt-purifycss ##
# #####################
# ###
# [OVERVIEW] Remove unused CSS for kristinita.netlify.app design:
# https://www.npmjs.com/package/purify-css
# https://www.npmjs.com/package/grunt-purifycss
# [NOTE] Needs separate task for each style. Because theme use different styles:
# [BUG] Doesn’t work with grunt-newer:
# https://github.com/purifycss/grunt-purifycss/issues/30
# ###
# module.exports =
# options:
# ###
# [WARNING] PurifyCSS support elements, that include simply methods.
# Example: <div class="SashaClass"></div> in HTML;
# .SashaClass { color: black } in CSS;
# If elements generated by JavaScript, PurifyCSS doesn’t work:
# https://github.com/purifycss/purifycss/issues/194
# ###
# whitelist: [
# # [WARNING] Don't use multiline comments inside list!
# # Coffeelint will show “unexpected newline” error:
# # No issue, because coffeelint not maintained at March, 2019:
# # https://github.com/clutchski/coffeelint/issues
# # [INFO] Wildfire classes
# # [INFO] “div” for parent classes not required.
# # [FIXME] Migrate to PurgeCSS, that not add each Wildfire class separately:
# # https://github.com/FullHuman/grunt-purgecss/issues/9
# ".animate-flicker"
# ".ivu-modal-body"
# ".ivu-btn"
# ".ivu-tabs-tabpane"
# # [NOTE] Adjoining classes required in this case.
# ".wf.wf-theme-dark"
# ".ivu-btn-primary"
# ".wf-separator"
# ".wf-no-content-tip"
# ":not(.v-transfer-dom)"
# ".ivu-menu-submenu-title-icon"
# ".ivu-input-wrapper"
# ".wf-post-btn"
# ".ivu-menu-horizontal"
# ".ivu-menu-light"
# ".ivu-icon-heart-broken"
# ".ivu-icon-heart"
# ".wf-inactive"
# ".ivu-icon-at"
# ".ivu-menu-item-selected"
# ".ivu-menu"
# "svg"
# # [INFO] Tooltipster classes.
# # [NOTE] Use parent classes:
# # For:
# # .tooltipster-punk-aquamarine .tooltipster-box
# # .tooltipster-punk-purple .tooltipster-box
# # “.tooltipster-box” in “whitelist” option will not works
# ".tooltipster-punk-purple .tooltipster-box"
# ".tooltipster-punk-aquamarine .tooltipster-box"
# ]
# indextarget:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/index.html"]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/kristinita.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/kristinita.css"
# sublimetexttarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Erics-Rooms/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Sublime-Text/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"
# gingerinastarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Erics-Rooms/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Gingerinas/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/gingerinas.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/gingerinas.css"
# itarticlestarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Erics-Rooms/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/IT-articles/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/it-articles.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/it-articles.css"
# giologicabluetarget:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/Giologica/Valerywork-Kiravel.html"]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica-blue.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica-blue.css"
# giologicatarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Books-Reviews/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Giologica/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/G-Rights/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Special/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica.css"
# sashablacktarget:
# # Pages and Sasha Black
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Sasha-Black/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Pages/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/sasha-black-description.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/sasha-black-description.css"
# smertsvobodetarget:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/Smert-svobode/*.html"]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/smert-svobode.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/smert-svobode.css"
# [DECLINED]
# 1. posthtml-img-autosize doesn’t work for relative paths:
# https://github.com/posthtml/grunt-posthtml/issues/4
# 2. lazysizes plugin required for my environment,
# I don’t add native lazy loading via posthtml-lazyload
# ####################
# ## grunt-posthtml ##
# ####################
# ###
# [INFO] Framework to transform HTML/XML via JavaScript plugins:
# https://posthtml.org/#/
# https://www.npmjs.com/package/posthtml
# [INFO] Plugins:
# https://www.npmjs.com/package/posthtml#plugins
# [INFO] Grunt wrapper:
# https://www.npmjs.com/package/grunt-juwain-posthtml
# [FIXED] https://github.com/posthtml/grunt-posthtml/issues/4
# [NOTE] Default version — “https://www.npmjs.com/package/grunt-posthtml” —
# doesn’t work for me. I use grunt-juwain-posthtml version:
# https://github.com/posthtml/grunt-posthtml/issues/3
# ###
# module.exports =
# options:
# use: [
# #####################
# # posthtml-lazyload #
# #####################
# # [SOON] Currently, I still use JQuery Lazy for lazy loading images and iframes.
# # We have polyfill for browsers that not supported loading="lazy":
# # https://github.com/mfranzke/loading-attribute-polyfill
# # Polyfill problems:
# # 1. It not valid:
# # https://github.com/mfranzke/loading-attribute-polyfill/issues/90
# # 2. Additional syntax required:
# # https://github.com/mfranzke/loading-attribute-polyfill#simple-image
# # [ACTION] Add “loading="lazy"” to all images and iframes:
# # https://www.npmjs.com/package/posthtml-lazyload
# # [NOTE] I couldn’t find any method for applying lazy loading for
# # all images and frames without adding “loading="lazy"” each time
# # [INFO] “loading="eager"” — load resources immediatly:
# # https://web.dev/browser-level-image-lazy-loading/
# # [INFO] For “picture” tag the “loading” attribute required solely for
# # the fallback “img” element:
# # https://web.dev/browser-level-image-lazy-loading/
# # [NOTE] CSS background images haven’t “loading” attribute:
# # https://web.dev/browser-level-image-lazy-loading/\
# #can-css-background-images-take-advantage-of-the-loading-attribute
# # require('posthtml-lazyload')(loading: 'lazy')
# #########################
# # posthtml-img-autosize #
# #########################
# # [BUG] Plugin doesn’t work with relative paths:
# # https://github.com/posthtml/posthtml-img-autosize/issues/17#issuecomment-706592803
# # [OVERVIEW] Plugin adds “height” and “width” attributes to all images:
# # https://www.npmjs.com/package/posthtml-img-autosize
# # [INFO] It required for 2020:
# # https://www.smashingmagazine.com/2020/03/setting-height-width-images-important-again/
# # require('posthtml-img-autosize')(
# # processEmptySize: true
# # root: "output/Programs"
# # )
# ]
# target:
# files: [
# expand: true
# cwd: "."
# src: "output/Programs/*.html"
# dest: "."
# ]
# [DECLINED] UglifyJS doesn’t support EcmaScript 2015 and above:
# https://www.npmjs.com/package/uglify-js#note
# #############
# # Uglify JS #
# #############
# # JavaScript minifier:
# # http://lisperator.net/uglifyjs/
# # https://www.npmjs.com/package/grunt-contrib-uglify
# # Options:
# # http://lisperator.net/uglifyjs/compress
# # [INFO] I selected Uglify JS, not alternatives, because they obsolete:
# # Esmangle:
# # https://github.com/estools/esmangle
# # Closure-compiler:
# # https://github.com/gmarty/grunt-closure-compiler
# # [INFO] Benchmark:
# # https://evmar.github.io/js-min-bench/
# module.exports =
# options:
# # [LEARN][CSS][JAVASCRIPT] Sourcemaps
# # make debugging simply, if styles and scripts combine and compress:
# # https://blog.teamtreehouse.com/introduction-source-maps
# sourceMap: true
# uglifypersonal:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] “!” symbol — exclude paths:
# # https://stackoverflow.com/a/28277841/5951529
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] Extensions in filepaths:
# # https://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
# ext: '.min.js'
# ]
# uglifytheme:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# ext: '.min.js'
# ]
# [DECLINED] Closure Compiler have best result in the benchmark:
# https://evmar.github.io/js-min-bench/
# [INFO] I don’t exclude that I will use terser if Closure Compiler problems will not be fixed:
# https://github.com/google/closure-compiler/issues/3729
# https://github.com/google/closure-compiler/issues/3727
# https://stackoverflow.com/q/64927683/5951529
# ##########
# # Terser #
# ##########
# ###
# JavaScript minifier:
# http://lisperator.net/uglifyjs/
# https://www.npmjs.com/package/grunt-contrib-uglify
# Options:
# http://lisperator.net/uglifyjs/compress
# [INFO] I selected Uglify JS, not alternatives, because they obsolete:
# Esmangle:
# https://github.com/estools/esmangle
# Closure-compiler:
# https://github.com/gmarty/grunt-closure-compiler
# ###
# module.exports =
# options:
# # [LEARN][CSS][JAVASCRIPT] Sourcemaps
# # make debugging simply, if styles and scripts combine and compress:
# # https://blog.teamtreehouse.com/introduction-source-maps
# sourceMap: true
# terserpersonal:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] “!” symbol — exclude paths:
# # https://stackoverflow.com/a/28277841/5951529
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] Extensions in filepaths:
# # https://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
# ext: '.min.js'
# ]
# tersertheme:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# ext: '.min.js'
# ]
| 127583 | ######################
## Deprecated tasks ##
######################
# All buggy, obsolete and/or unneedable plugins.
# Save, because possibly I can use them again.
# [FIXME] Re-install grunt-eslint, when I will have a time:
# ################
# # grunt-eslint #
# ################
# module.exports =
# options:
# maxWarnings: 40
# lint:
# files: "<%= templates.paths.js %>"
# ###################
# ## grunt-pelican ##
# ###################
# # Pelican tasks from Grunt
# # https://www.npmjs.com/package/grunt-pelican
# # [WARNING] Pipenv doesn’t work in Grunt Pelican:
# # https://github.com/chuwy/grunt-pelican/issues/4
# pelican:
# options:
# contentDir: 'content'
# outputDir: 'output'
# build:
# configFile: 'pelicanconf.py'
# publish:
# configFile: 'publishconf.py'
##############################
## grunt-http-convert-https ##
##############################
# # Convert http to https
# # https://www.npmjs.com/package/grunt-http-convert-https
# # [BUG] plugin doesn't work, “Warning: Task "converthttps" not found”.
# # Author long time inactive on GitHub, so no issue:
# # https://github.com/sina-mfe
# converthttps:
# config:
# expand: true
# cwd: 'output'
# src: '**/*.html'
# dest: 'output'
# httpsJson:
# "imgur": [
# "http": "i.imgur.com"
# "https": "i.imgur.com"
# ]
########################
## grunt-text-replace ##
########################
# # [DECLINED] grunt-string-replace active maintained
# # https://www.npmjs.com/package/grunt-string-replace
# # Replace text, using regex
# # https://github.com/yoniholmes/grunt-text-replace
# replace:
# replacehtml:
# src: [ 'output/**/*.html' ]
# overwrite: true
# replacements: [
# ## [NOTE] Use (.|\n|\r) for any symbol, not (.|\n)
# ## [DEPRECATED] Cllipboard.js + Tooltipster for Rainbow
# ## http://ru.stackoverflow.com/a/582520/199934
# ## http://stackoverflow.com/a/33758293/5951529
# # {
# # from: /<pre><code class="(.+?)">((.|\n|\r)+?)<\/code><\/pre>/g
# # to: '<pre><code data-language="$1">$2</code><button class="SashaButton SashaTooltip">\
# <img class="SashaNotModify" src="../images/interface_images/clippy.svg" \
# alt="Clipboard button" width="13"></button></pre>'
# # }
# # Clipboard.js + Tooltipster for SuperFences
# # http://ru.stackoverflow.com/a/582520/199934
# # https://stackoverflow.com/a/33758435/5951529
# # <button> and <img> tags must be in one line;
# # no line breaks between them!
# from: /(<pre>)((.|\n|\r)+?)(<\/pre>(\s+?)<\/div>)/g
# to: '$1<button class="SashaButton SashaTooltip"><img class="SashaNotModify" \
# src="//gitcdn.xyz/repo/Kristinita/Kristinita.netlify.com/master/images/interface-images/clippy.svg" \
# alt="Clipboard button" width="13"></button>$2$4'
# # Fancybox and JQueryLazy images,
# from: /<img alt="([^"]+?)" src="(.+?)"( \/)?>/g
# to: '<a class="fancybox" href="$2"><img class="SashaLazy" \
# src="//gitcdn.xyz/repo/Kristinita/Kristinita.netlify.com\
# /master/images/interface-images/transparent-one-pixel.png" \
# data-src="$2" alt="$1"></a>'
# # GitCDN
# # https://github.com/schme16/gitcdn.xyz
# from: /http:\/\/kristinita.netlify.app\/(.+?)\.(js|css|ico|xml)/g
# to: '//gitcdn.xyz/repo/Kristinita/Kristinita.netlify.com/master/$1.$2'
# # Header permalink
# from: /(<p>\s*?<a name="(.+?)" id="(.+?)"><\/a>\s*?<\/p>\s+?<h\d+?>((.|\n|\r)+?))(<\/h\d+?>)/g
# to: '$1 <a class="headerlink" href="#$2" title="Permanent link">¶</a>$6'
# ]
# [DECLINED] Currently, I don’t need posthtml plugins
# ####################
# ## grunt-posthtml ##
# ####################
# # PostHTML wrapper for Grunt:
# # https://www.npmjs.com/package/grunt-posthtml
# # https://www.npmjs.com/package/posthtml
# # [NOTE] Any default PostHTML plugin doesn't work for me, details:
# # https://github.com/TCotton/grunt-posthtml/issues/3
# # [INFO] Use grunt-juwain-posthtml, it fix this problem:
# # https://github.com/posthtml/grunt-posthtml/issues/3
# # https://www.npmjs.com/package/grunt-juwain-posthtml
# posthtml:
# options:
# use: [
# require('posthtml-aria-tabs')()
# require('posthtml-doctype')(doctype : 'HTML 4.01 Frameset')
# require('posthtml-alt-always')()
# ]
# single:
# files: [
# src: '<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/KristinitaLuckyLink.html'
# dest: '<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/KristinitaLuckyLink.html'
# ]
# ####################
# ## grunt-htmltidy ##
# ####################
# # Fix HTML markup errors
# # https://github.com/gavinballard/grunt-htmltidy
# # [BUG] I don't use, because bug:
# # https://github.com/gavinballard/grunt-htmltidy/issues/6
# htmltidy:
# options:
# # indent: no
# # Disable line breaks
# # https://stackoverflow.com/a/7681425/5951529
# wrap: 0
# # 'vertical-space': no
# gingerinas:
# files: [
# expand: true
# cwd: 'output'
# src: '**/*.html'
# dest: 'output'
# ]
##########################
## grunt-html5-validate ##
##########################
# # Validate HTML — https://github.com/rgladwell/grunt-html5-validate
# # [BUG] Plugin doesn't work:
# # https://github.com/rgladwell/grunt-html5-validate/issues/1
# html5validate:
# src: 'output/IT-articles/*.html'
# #################
# ## grunt-image ##
# #################
# # Compress images:
# # https://github.com/1000ch/grunt-image
# # [BUG] Doesn't work with multiple images:
# # https://github.com/1000ch/grunt-image/issues/29
# image:
# static:
# options:
# pngquant: true
# optipng: true
# zopflipng: true
# jpegRecompress: true
# jpegoptim: true
# mozjpeg: true
# gifsicle: true
# svgo: true
# files:
# src: ['output/**/*.jpg']
# #################
# ## grunt-ngrok ##
# #################
# # ngrok implementation for Grunt
# # https://www.npmjs.com/package/grunt-ngrok
# # [BUG] Doesn't work:
# # https://github.com/bazilio91/grunt-ngrok/issues/7
# ngrok:
# options:
# authToken: '<KEY>'
# server:
# proto: 'https'
# ########################
# ## grunt-nice-package ##
# ########################
# # package.json validator
# # https://www.npmjs.com/package/grunt-nice-package
# # [BUG] Some features works incorrect:
# # https://github.com/bahmutov/grunt-nice-package/issues/25
# # https://github.com/bahmutov/grunt-nice-package/issues/26
# # nicePackage shortcut:
# # https://www.npmjs.com/package/grunt-nice-package#alternative-default-options
# # "generate-package" generate package.json:
# # https://www.npmjs.com/package/generate-package
# # https://stackoverflow.com/a/49053110/5951529
# nicePackage:
# all:
# options:
# blankLine: false
# ###################
# ## gulp-htmltidy ##
# ###################
# # Validate HTML
# # https://www.npmjs.com/package/gulp-htmltidy
# ##########################
# ## grunt-gulp variables ##
# ##########################
# # https://www.npmjs.com/package/grunt-gulp#examples
# # CoffeeScript to JavaScript online — http://js2.coffee/
# gulp = require('gulp')
# htmltidy = require('gulp-htmltidy')
# # For in-place dest needs «base: "."», see:
# # https://stackoverflow.com/a/44337370/5951529
# # [BUG] Doesn't work for multiple commands, see:
# # https://github.com/shama/grunt-gulp/issues/13
# module.exports =
# gulptidy:
# gulp.src('<%= templates.paths.html %>', base: ".")
# .pipe(htmltidy(
# doctype: 'html5'
# indent: true
# wrap: 0)).pipe gulp.dest('./')
# [DECLINED] pip-licenses more customisable
# ############
# ## yolk3k ##
# ############
# # Generate licenses for all Python packages:
# # https://stackoverflow.com/a/26718306/5951529
# # https://pypi.org/project/yolk3k/
# yolk:
# command: 'pipenv run yolk -l -f license > python.txt'
# [DECLINED] SuperFences now preserve tabs:
# https://github.com/facelessuser/pymdown-extensions/issues/276
# ######################
# ## grunt-indentator ##
# ######################
# # Indent 4 spaces to tab:
# # https://www.npmjs.com/package/grunt-indentator
# # [WARNING]: Replace tabs to spaces only if first indentation — spaces:
# # Needs run before “eslint fix”:
# # https://github.com/gespinha/grunt-indentator/issues/1
# module.exports =
# options:
# type: 'tab'
# size: 1
# debug: true
# files:
# [
# "<%= templates.paths.html %>"
# ]
# [DEPRECATED] Generate invalid license files:
# https://github.com/licenses/lice/issues/50
# I can't file Grunt package for this task;
# license-generator output error in installation process:
# https://pypi.org/project/license-generator/
# ##########
# ## lice ##
# ##########
# # Generate license for project:
# # https://pypi.org/project/lice/
# lice:
# # [BUG] lice doesn't work in AppVeyor:
# # https://github.com/appveyor/ci/issues/2226
# if process.platform == "win32"
# command: 'echo "Sorry, lice doesn\'t work in AppVeyor — https://github.com/appveyor/ci/issues/2226"'
# else
# command: 'pipenv run lice mit -o "<NAME>" --file output/LICENSE.md'
# [DEPRECATED] Doesn't work for CSS paths
# #########################
# # grunt-path-absolutely #
# #########################
# # https://www.npmjs.com/package/grunt-path-absolutely
# module.exports =
# cssimages:
# options:
# devRoot: "."
# releaseRoot: "https://kristinita.netlify.app"
# resourceFilter: ["*.css"]
# files: [
# expand: true
# cwd: "."
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/css/aside/*.css"]
# dest: "."
# ]
# [DEPRECATED] Doesn't allow to have comments in JSON configuration files:
# #############################
# # grunt-strip-json-comments #
# #############################
# # Delete comments in JSON files
# # https://www.npmjs.com/package/strip-json-comments
# # https://www.npmjs.com/package/grunt-strip-json-comments
# stripJsonComments:
# dist:
# options:
# whitespace: false
# files:
# '.jsbeautifyrc': '.jsbeautifyrc'
# [DEPRECATED] I don't see plugins, that can come in handy
# ####################
# ## grunt-posthtml ##
# ####################
# # PostHTML support for Grunt:
# # https://github.com/posthtml/posthtml
# # https://www.npmjs.com/package/grunt-juwain-posthtml
# # [WARNING] Use “juwain-posthtml”, not native “posthtml” version:
# # https://github.com/TCotton/grunt-posthtml/issues/3
# module.exports =
# options:
# use: [
# #############
# # ARIA Tabs #
# #############
# # Add WAI-ARIA attributes:
# # http://prgssr.ru/development/ispolzovanie-aria-v-html5.html
# # http://jonathantneal.github.io/posthtml-aria-tabs/
# # [WARNING] Disable, because I use “ul/li” for progressive enhancements:
# # http://jonathantneal.github.io/posthtml-aria-tabs/#caveats
# # require('posthtml-aria-tabs')()
# ]
# build:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# src: ['**/*.html']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# ]
# [DEPRECATED][BUG] grunt-coffee-format make files wrong:
# https://github.com/NotBobTheBuilder/grunt-coffee-format/issues/3
# #######################
# # grunt-coffee-format #
# #######################
# # Formatter for CoffeeScript files:
# # https://www.npmjs.com/package/coffee-fmt
# # Grunt adapter:
# # https://www.npmjs.com/package/grunt-coffee-format
# module.exports =
# options:
# # [INFO] Use tabs, not spaces:
# # https://www.npmjs.com/package/grunt-coffee-format#optionstab
# tab: '\t'
# theme:
# files:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/coffee/**/*.coffee"]
# personal:
# files:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/coffee/**/*.coffee"]
# [DEPRECATED] I migrate to HTML-minifier, arguments:
# [LINK] “htmlmin.coffee”
# ############
# # minimize #
# ############
# # Minify HTML:
# # https://www.npmjs.com/package/minimize
# # https://www.npmjs.com/package/grunt-minify-html
# # [NOTE] Use HTML parser, grunt-contrib-htmlmin use regexes.
# # grunt-htmlclean simply than grunt-minify-html:
# # https://github.com/anseki/htmlclean/issues/11#issuecomment-389386676
# module.exports =
# # https://github.com/Swaagie/minimize#options-1
# # All set false by default:
# # https://github.com/Swaagie/minimize#options
# options:
# # [INFO] I'm not support spare attirbutes for older browsers:
# # https://github.com/Swaagie/minimize#spare
# spare: false
# # [INFO] W3C recommends quotes:
# # https://www.w3schools.com/html/html_attributes.asp
# quotes: true
# minimize:
# files: [
# expand: true
# cwd: "."
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/**/*.html"]
# dest: "."
# ]
# [DECLINED] I hate private discussions
# #########
# # ROT13 #
# #########
# # ROT13 algorithm for e-mail obfuscation:
# # https://en.wikipedia.org/wiki/ROT13
# # https://superuser.com/a/235965/572069
# # Generated by:
# # http://rot13.florianbersier.com/
# # [NOTE] In this script fixed «eo is not defined» bug:
# # https://github.com/xpressyoo/Email-Obfuscator/issues/1
# document.getElementById('obf').innerHTML = \
# '<n uers="zn<EMAIL>gb:<EMAIL>Rz<EMAIL>?fhowrpg=R-znvy gb Fnfun Purealxu" \
# gnetrg="_oynax">r-znvy</n>'.replace(/[a-zA-Z]/g, (c) ->
# String.fromCharCode if (if c <= 'Z' then 90 else 122) >= (c = c.charCodeAt(0) + 13) then c else c - 26
# )
# [DEPRECATED] Compress files as cssnano; don't remove duplicates
#############
# css-purge #
#############
# Compress CSS:
# http://rbtech.github.io/css-purge/
# Grunt wrapper:
# https://github.com/dominikwilkowski/grunt-css-purge
# Options:
# https://www.npmjs.com/package/css-purge#config-options
# module.exports =
# task:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/css"
# src: ['!**/**/*.css'
# '**/**/*.min.css']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/css"
# ext: '.min.css'
# ]
# [DEPRECATED] UNCSS build all CSS files to single;
# behavior not similar as PurgeCSS and PurifyCSS
###############
# grunt-uncss #
###############
# module.exports =
# options:
# uncssrc: ".uncssrc"
# sublimetexttarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Sublime-Text/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"
# [DEPRECATED]
# Virtual environment and Pipenv doesn't support:
# https://github.com/btholt/grunt-flake8/issues/1
# [WARNING] All linting passed, if flake8 no installed:
# https://github.com/btholt/grunt-flake8/issues/3#issuecomment-473383610
# ##########
# # flake8 #
# ##########
# module.exports =
# dist:
# src: ["*.py"
# "personal-plugins/**/*.py"]
# [DEPRECATED]
# Google Fonts support “font-display: swap” from May 2019:
# https://www.zachleat.com/web/google-fonts-display/
# ###
# Load Google Fonts
# [NOTE] Script required, because Google Fonts doesn't support “font-display”:
# https://css-tricks.com/google-fonts-and-font-display/
# https://github.com/google/fonts/issues/358
# [INFO] “font-display: swap”, that:
# 1. Default font will show to site visitors before Google font
# 2. Fix “Ensure text remains visible during webfont load” of PageSpeed Insights
# https://web.dev/fast/avoid-invisible-text
# https://developers.google.com/web/updates/2016/02/font-display
# [INFO] If “font-display: swap”, sit visitor see text without any delay:
# https://font-display.glitch.me/
# [LEARN][COFFEESCRIPT] For converting EcmaScript 6 to CoffeeScript:
# 1. Convert EcmaScript 6 to JavaScript. Online converter — https://babeljs.io/en/repl .
# 2. Convert JavaScript to CoffeeScript via js2coffee.
# https://github.com/js2coffee/js2coffee/issues/449#issuecomment-470128539
# ###
# loadFont = (url) ->
# # [LEARN][COFFEESCRIPT] Wrap constructor to parens (parentheses, round brackets),
# # if CoffeeLint warnings:
# # https://github.com/clutchski/coffeelint/blob/master/src/rules/non_empty_constructor_needs_parens.coffee
# # https://github.com/clutchski/coffeelint/blob/master/src/rules/empty_constructor_needs_parens.coffee
# xhr = new (XMLHttpRequest)
# xhr.open 'GET', url, true
# xhr.onreadystatechange = ->
# if xhr.readyState is 4 and xhr.status is 200
# css = xhr.responseText
# css = css.replace(/}/g, 'font-display: swap; }')
# head = document.getElementsByTagName('head')[0]
# style = document.createElement('style')
# style.appendChild document.createTextNode(css)
# head.appendChild style
# return
# xhr.send()
# return
# loadFont 'https://fonts.googleapis.com/css?family=Play:700\
# |El+Messiri|Scada:700i|Fira+Mono|Marck+Script&subset=cyrillic&display=swap'
# [DEPRECATED]
# Linux — it not needed; Linux doesn't lock opened files and folders$
# see “You Can Delete or Modify Open Files”:
# https://www.howtogeek.com/137096/6-ways-the-linux-file-system-is-different-from-the-windows-file-system/
# Windows — it not unlock files or folders as any another program:
# https://superuser.com/q/1485406/572069
###############
# grunt-chmod #
###############
# # Add read and write permissions for all output folders and files:
# # https://www.npmjs.com/package/grunt-chmod
# # About chmod:
# # https://ss64.com/bash/chmod.html
# # [DESCRIPTION]
# # I open any files → I run “publishconf.py”, that delete “output” folder →
# # I can get errors as:
# # ERROR: Unable to delete directory D:\Kristinita\output\stylus; OSError: [WinError 145]
# # The directory is not empty: 'D:\\Kristinita\\output\\stylus\\personal'
# # chmod fix this problem.
# # [WARNING] You need close BrowserSync before publishing,
# # because it can create new permissions.
# module.exports =
# options:
# # [NOTE] 444 and 666 modes works in Windows:
# # https://www.npmjs.com/package/grunt-chmod#warnings
# mode: '666'
# kiratarget:
# # [LEARN][GRUNT] All folders and files recursive, include current:
# # https://gruntjs.com/configuring-tasks#globbing-patterns
# src: "<%= templates.yamlconfig.OUTPUT_PATH %>/**"
# [DECLINED]
# 1. JSBeautifier is more powerful tool
# 2. JSBeautifier has many options; Prettier — minimal set, see options philosophy:
# https://prettier.io/docs/en/option-philosophy.html
# 3. Strange HTML prettifying for Prettier
# 4. Bug for grunt-prettier:
# https://github.com/poalrom/grunt-prettier/issues/20
# ############
# # Prettier #
# ############
# # Prettifier for many formats, include css, javascript:
# # https://prettier.io/
# # Grunt wrapper:
# # https://www.npmjs.com/package/grunt-prettier
# # Options:
# # https://prettier.io/docs/en/options.html
# module.exports =
# cssdebug:
# # [NOTE] “ext: '.min.{css,js}'” will not work;
# # Grunt will generate file “kirafile.min.{css,js}”
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# src: ['**/*.css'
# '!**/*.min.css']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# ]
# jsdebug:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# src: ['**/*.js'
# '!**/*.min.js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# ]
# # htmldebug:
# # files: [
# # expand: true
# # cwd: "."
# # src: "<%= templates.yamlconfig.OUTPUT_PATH %>/Books-Reviews/Как-читать-архитектуру.html"
# # dest: "."
# # ]
# [DEPRECATED]
# [BUG] Checker works incorectly with encoded URLs, see examples:
# Another users:
# https://github.com/ChrisWren/grunt-link-checker/issues/28
# Me:
# “>> Resource not found linked from https://kristinita.netlify.app/opensearch.xml
# to https://kristinita.netlify.app/favicon16%C3%9716.ico”
# ################
# # link-checker #
# ################
# ###
# [PURPOSE] Check links via node-simplecrawler:
# https://github.com/chriswren/grunt-link-checker
# https://www.npmjs.com/package/simplecrawler
# ###
# module.exports =
# development:
# site: "kristinita.netlify.app"
# options:
# checkRedirect: true
# noFragment: false
# [DEPRECATED] grunt-crawl doesn’t support the newest Node.js and Grunt versions:
# https://github.com/mradcliffe/grunt-crawl/pull/15
# ###############
# # grunt-crawl #
# ###############
# ###
# [INFO] Grunt crawler; possibly, check URLs:
# https://www.npmjs.com/package/grunt-crawl
#
# [NOTE] markdown-link-check tool doesn’t support internal links:
# https://github.com/tcort/markdown-link-check
# Example:
# [✖] ../Special/Полная-библиография#Открытость → Status: 400
# ###
# module.exports =
# myapp:
# options:
# baseUrl: "http://localhost:4147/"
# contentDir: "output"
# [FIXME][ISSUE] 2 problems:
# 1. grunt-blank audit failed, but manually with (TreeSize Free) review shows,
# that I haven’t files < 2 bytes
# 2. grunt-blank doesn’t show, which files lower that 2 bytes.
# ###############
# # grunt-blank #
# ###############
# # [PURPOSE] Check files with size lower than “minBytes”:
# # https://www.npmjs.com/package/grunt-blank
# module.exports =
# options:
# minBytes: 2
# task:
# src: [
# "<%= templates.yamlconfig.CONTENT_PATH %>"
# "<%= templates.yamlconfig.THEME_STATIC_DIR %>"
# ]
# [DECLINED] The project no longer maintained since 2018:
# https://github.com/purifycss/purifycss/issues/213
# I migrate to PurgeCSS.
# #####################
# ## grunt-purifycss ##
# #####################
# ###
# [OVERVIEW] Remove unused CSS for kristinita.netlify.app design:
# https://www.npmjs.com/package/purify-css
# https://www.npmjs.com/package/grunt-purifycss
# [NOTE] Needs separate task for each style. Because theme use different styles:
# [BUG] Doesn’t work with grunt-newer:
# https://github.com/purifycss/grunt-purifycss/issues/30
# ###
# module.exports =
# options:
# ###
# [WARNING] PurifyCSS support elements, that include simply methods.
# Example: <div class="SashaClass"></div> in HTML;
# .SashaClass { color: black } in CSS;
# If elements generated by JavaScript, PurifyCSS doesn’t work:
# https://github.com/purifycss/purifycss/issues/194
# ###
# whitelist: [
# # [WARNING] Don't use multiline comments inside list!
# # Coffeelint will show “unexpected newline” error:
# # No issue, because coffeelint not maintained at March, 2019:
# # https://github.com/clutchski/coffeelint/issues
# # [INFO] Wildfire classes
# # [INFO] “div” for parent classes not required.
# # [FIXME] Migrate to PurgeCSS, that not add each Wildfire class separately:
# # https://github.com/FullHuman/grunt-purgecss/issues/9
# ".animate-flicker"
# ".ivu-modal-body"
# ".ivu-btn"
# ".ivu-tabs-tabpane"
# # [NOTE] Adjoining classes required in this case.
# ".wf.wf-theme-dark"
# ".ivu-btn-primary"
# ".wf-separator"
# ".wf-no-content-tip"
# ":not(.v-transfer-dom)"
# ".ivu-menu-submenu-title-icon"
# ".ivu-input-wrapper"
# ".wf-post-btn"
# ".ivu-menu-horizontal"
# ".ivu-menu-light"
# ".ivu-icon-heart-broken"
# ".ivu-icon-heart"
# ".wf-inactive"
# ".ivu-icon-at"
# ".ivu-menu-item-selected"
# ".ivu-menu"
# "svg"
# # [INFO] Tooltipster classes.
# # [NOTE] Use parent classes:
# # For:
# # .tooltipster-punk-aquamarine .tooltipster-box
# # .tooltipster-punk-purple .tooltipster-box
# # “.tooltipster-box” in “whitelist” option will not works
# ".tooltipster-punk-purple .tooltipster-box"
# ".tooltipster-punk-aquamarine .tooltipster-box"
# ]
# indextarget:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/index.html"]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/kristinita.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/kristinita.css"
# sublimetexttarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Erics-Rooms/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Sublime-Text/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"
# gingerinastarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Erics-Rooms/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Gingerinas/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/gingerinas.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/gingerinas.css"
# itarticlestarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Erics-Rooms/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/IT-articles/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/it-articles.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/it-articles.css"
# giologicabluetarget:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/Giologica/Valerywork-Kiravel.html"]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica-blue.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica-blue.css"
# giologicatarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Books-Reviews/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Giologica/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/G-Rights/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Special/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica.css"
# sashablacktarget:
# # Pages and Sasha Black
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Sasha-Black/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Pages/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/sasha-black-description.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/sasha-black-description.css"
# smertsvobodetarget:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/Smert-svobode/*.html"]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/smert-svobode.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/smert-svobode.css"
# [DECLINED]
# 1. posthtml-img-autosize doesn’t work for relative paths:
# https://github.com/posthtml/grunt-posthtml/issues/4
# 2. lazysizes plugin required for my environment,
# I don’t add native lazy loading via posthtml-lazyload
# ####################
# ## grunt-posthtml ##
# ####################
# ###
# [INFO] Framework to transform HTML/XML via JavaScript plugins:
# https://posthtml.org/#/
# https://www.npmjs.com/package/posthtml
# [INFO] Plugins:
# https://www.npmjs.com/package/posthtml#plugins
# [INFO] Grunt wrapper:
# https://www.npmjs.com/package/grunt-juwain-posthtml
# [FIXED] https://github.com/posthtml/grunt-posthtml/issues/4
# [NOTE] Default version — “https://www.npmjs.com/package/grunt-posthtml” —
# doesn’t work for me. I use grunt-juwain-posthtml version:
# https://github.com/posthtml/grunt-posthtml/issues/3
# ###
# module.exports =
# options:
# use: [
# #####################
# # posthtml-lazyload #
# #####################
# # [SOON] Currently, I still use JQuery Lazy for lazy loading images and iframes.
# # We have polyfill for browsers that not supported loading="lazy":
# # https://github.com/mfranzke/loading-attribute-polyfill
# # Polyfill problems:
# # 1. It not valid:
# # https://github.com/mfranzke/loading-attribute-polyfill/issues/90
# # 2. Additional syntax required:
# # https://github.com/mfranzke/loading-attribute-polyfill#simple-image
# # [ACTION] Add “loading="lazy"” to all images and iframes:
# # https://www.npmjs.com/package/posthtml-lazyload
# # [NOTE] I couldn’t find any method for applying lazy loading for
# # all images and frames without adding “loading="lazy"” each time
# # [INFO] “loading="eager"” — load resources immediatly:
# # https://web.dev/browser-level-image-lazy-loading/
# # [INFO] For “picture” tag the “loading” attribute required solely for
# # the fallback “img” element:
# # https://web.dev/browser-level-image-lazy-loading/
# # [NOTE] CSS background images haven’t “loading” attribute:
# # https://web.dev/browser-level-image-lazy-loading/\
# #can-css-background-images-take-advantage-of-the-loading-attribute
# # require('posthtml-lazyload')(loading: 'lazy')
# #########################
# # posthtml-img-autosize #
# #########################
# # [BUG] Plugin doesn’t work with relative paths:
# # https://github.com/posthtml/posthtml-img-autosize/issues/17#issuecomment-706592803
# # [OVERVIEW] Plugin adds “height” and “width” attributes to all images:
# # https://www.npmjs.com/package/posthtml-img-autosize
# # [INFO] It required for 2020:
# # https://www.smashingmagazine.com/2020/03/setting-height-width-images-important-again/
# # require('posthtml-img-autosize')(
# # processEmptySize: true
# # root: "output/Programs"
# # )
# ]
# target:
# files: [
# expand: true
# cwd: "."
# src: "output/Programs/*.html"
# dest: "."
# ]
# [DECLINED] UglifyJS doesn’t support EcmaScript 2015 and above:
# https://www.npmjs.com/package/uglify-js#note
# #############
# # Uglify JS #
# #############
# # JavaScript minifier:
# # http://lisperator.net/uglifyjs/
# # https://www.npmjs.com/package/grunt-contrib-uglify
# # Options:
# # http://lisperator.net/uglifyjs/compress
# # [INFO] I selected Uglify JS, not alternatives, because they obsolete:
# # Esmangle:
# # https://github.com/estools/esmangle
# # Closure-compiler:
# # https://github.com/gmarty/grunt-closure-compiler
# # [INFO] Benchmark:
# # https://evmar.github.io/js-min-bench/
# module.exports =
# options:
# # [LEARN][CSS][JAVASCRIPT] Sourcemaps
# # make debugging simply, if styles and scripts combine and compress:
# # https://blog.teamtreehouse.com/introduction-source-maps
# sourceMap: true
# uglifypersonal:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] “!” symbol — exclude paths:
# # https://stackoverflow.com/a/28277841/5951529
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] Extensions in filepaths:
# # https://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
# ext: '.min.js'
# ]
# uglifytheme:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# ext: '.min.js'
# ]
# [DECLINED] Closure Compiler have best result in the benchmark:
# https://evmar.github.io/js-min-bench/
# [INFO] I don’t exclude that I will use terser if Closure Compiler problems will not be fixed:
# https://github.com/google/closure-compiler/issues/3729
# https://github.com/google/closure-compiler/issues/3727
# https://stackoverflow.com/q/64927683/5951529
# ##########
# # Terser #
# ##########
# ###
# JavaScript minifier:
# http://lisperator.net/uglifyjs/
# https://www.npmjs.com/package/grunt-contrib-uglify
# Options:
# http://lisperator.net/uglifyjs/compress
# [INFO] I selected Uglify JS, not alternatives, because they obsolete:
# Esmangle:
# https://github.com/estools/esmangle
# Closure-compiler:
# https://github.com/gmarty/grunt-closure-compiler
# ###
# module.exports =
# options:
# # [LEARN][CSS][JAVASCRIPT] Sourcemaps
# # make debugging simply, if styles and scripts combine and compress:
# # https://blog.teamtreehouse.com/introduction-source-maps
# sourceMap: true
# terserpersonal:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] “!” symbol — exclude paths:
# # https://stackoverflow.com/a/28277841/5951529
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] Extensions in filepaths:
# # https://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
# ext: '.min.js'
# ]
# tersertheme:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# ext: '.min.js'
# ]
| true | ######################
## Deprecated tasks ##
######################
# All buggy, obsolete and/or unneedable plugins.
# Save, because possibly I can use them again.
# [FIXME] Re-install grunt-eslint, when I will have a time:
# ################
# # grunt-eslint #
# ################
# module.exports =
# options:
# maxWarnings: 40
# lint:
# files: "<%= templates.paths.js %>"
# ###################
# ## grunt-pelican ##
# ###################
# # Pelican tasks from Grunt
# # https://www.npmjs.com/package/grunt-pelican
# # [WARNING] Pipenv doesn’t work in Grunt Pelican:
# # https://github.com/chuwy/grunt-pelican/issues/4
# pelican:
# options:
# contentDir: 'content'
# outputDir: 'output'
# build:
# configFile: 'pelicanconf.py'
# publish:
# configFile: 'publishconf.py'
##############################
## grunt-http-convert-https ##
##############################
# # Convert http to https
# # https://www.npmjs.com/package/grunt-http-convert-https
# # [BUG] plugin doesn't work, “Warning: Task "converthttps" not found”.
# # Author long time inactive on GitHub, so no issue:
# # https://github.com/sina-mfe
# converthttps:
# config:
# expand: true
# cwd: 'output'
# src: '**/*.html'
# dest: 'output'
# httpsJson:
# "imgur": [
# "http": "i.imgur.com"
# "https": "i.imgur.com"
# ]
########################
## grunt-text-replace ##
########################
# # [DECLINED] grunt-string-replace active maintained
# # https://www.npmjs.com/package/grunt-string-replace
# # Replace text, using regex
# # https://github.com/yoniholmes/grunt-text-replace
# replace:
# replacehtml:
# src: [ 'output/**/*.html' ]
# overwrite: true
# replacements: [
# ## [NOTE] Use (.|\n|\r) for any symbol, not (.|\n)
# ## [DEPRECATED] Cllipboard.js + Tooltipster for Rainbow
# ## http://ru.stackoverflow.com/a/582520/199934
# ## http://stackoverflow.com/a/33758293/5951529
# # {
# # from: /<pre><code class="(.+?)">((.|\n|\r)+?)<\/code><\/pre>/g
# # to: '<pre><code data-language="$1">$2</code><button class="SashaButton SashaTooltip">\
# <img class="SashaNotModify" src="../images/interface_images/clippy.svg" \
# alt="Clipboard button" width="13"></button></pre>'
# # }
# # Clipboard.js + Tooltipster for SuperFences
# # http://ru.stackoverflow.com/a/582520/199934
# # https://stackoverflow.com/a/33758435/5951529
# # <button> and <img> tags must be in one line;
# # no line breaks between them!
# from: /(<pre>)((.|\n|\r)+?)(<\/pre>(\s+?)<\/div>)/g
# to: '$1<button class="SashaButton SashaTooltip"><img class="SashaNotModify" \
# src="//gitcdn.xyz/repo/Kristinita/Kristinita.netlify.com/master/images/interface-images/clippy.svg" \
# alt="Clipboard button" width="13"></button>$2$4'
# # Fancybox and JQueryLazy images,
# from: /<img alt="([^"]+?)" src="(.+?)"( \/)?>/g
# to: '<a class="fancybox" href="$2"><img class="SashaLazy" \
# src="//gitcdn.xyz/repo/Kristinita/Kristinita.netlify.com\
# /master/images/interface-images/transparent-one-pixel.png" \
# data-src="$2" alt="$1"></a>'
# # GitCDN
# # https://github.com/schme16/gitcdn.xyz
# from: /http:\/\/kristinita.netlify.app\/(.+?)\.(js|css|ico|xml)/g
# to: '//gitcdn.xyz/repo/Kristinita/Kristinita.netlify.com/master/$1.$2'
# # Header permalink
# from: /(<p>\s*?<a name="(.+?)" id="(.+?)"><\/a>\s*?<\/p>\s+?<h\d+?>((.|\n|\r)+?))(<\/h\d+?>)/g
# to: '$1 <a class="headerlink" href="#$2" title="Permanent link">¶</a>$6'
# ]
# [DECLINED] Currently, I don’t need posthtml plugins
# ####################
# ## grunt-posthtml ##
# ####################
# # PostHTML wrapper for Grunt:
# # https://www.npmjs.com/package/grunt-posthtml
# # https://www.npmjs.com/package/posthtml
# # [NOTE] Any default PostHTML plugin doesn't work for me, details:
# # https://github.com/TCotton/grunt-posthtml/issues/3
# # [INFO] Use grunt-juwain-posthtml, it fix this problem:
# # https://github.com/posthtml/grunt-posthtml/issues/3
# # https://www.npmjs.com/package/grunt-juwain-posthtml
# posthtml:
# options:
# use: [
# require('posthtml-aria-tabs')()
# require('posthtml-doctype')(doctype : 'HTML 4.01 Frameset')
# require('posthtml-alt-always')()
# ]
# single:
# files: [
# src: '<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/KristinitaLuckyLink.html'
# dest: '<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/KristinitaLuckyLink.html'
# ]
# ####################
# ## grunt-htmltidy ##
# ####################
# # Fix HTML markup errors
# # https://github.com/gavinballard/grunt-htmltidy
# # [BUG] I don't use, because bug:
# # https://github.com/gavinballard/grunt-htmltidy/issues/6
# htmltidy:
# options:
# # indent: no
# # Disable line breaks
# # https://stackoverflow.com/a/7681425/5951529
# wrap: 0
# # 'vertical-space': no
# gingerinas:
# files: [
# expand: true
# cwd: 'output'
# src: '**/*.html'
# dest: 'output'
# ]
##########################
## grunt-html5-validate ##
##########################
# # Validate HTML — https://github.com/rgladwell/grunt-html5-validate
# # [BUG] Plugin doesn't work:
# # https://github.com/rgladwell/grunt-html5-validate/issues/1
# html5validate:
# src: 'output/IT-articles/*.html'
# #################
# ## grunt-image ##
# #################
# # Compress images:
# # https://github.com/1000ch/grunt-image
# # [BUG] Doesn't work with multiple images:
# # https://github.com/1000ch/grunt-image/issues/29
# image:
# static:
# options:
# pngquant: true
# optipng: true
# zopflipng: true
# jpegRecompress: true
# jpegoptim: true
# mozjpeg: true
# gifsicle: true
# svgo: true
# files:
# src: ['output/**/*.jpg']
# #################
# ## grunt-ngrok ##
# #################
# # ngrok implementation for Grunt
# # https://www.npmjs.com/package/grunt-ngrok
# # [BUG] Doesn't work:
# # https://github.com/bazilio91/grunt-ngrok/issues/7
# ngrok:
# options:
# authToken: 'PI:KEY:<KEY>END_PI'
# server:
# proto: 'https'
# ########################
# ## grunt-nice-package ##
# ########################
# # package.json validator
# # https://www.npmjs.com/package/grunt-nice-package
# # [BUG] Some features works incorrect:
# # https://github.com/bahmutov/grunt-nice-package/issues/25
# # https://github.com/bahmutov/grunt-nice-package/issues/26
# # nicePackage shortcut:
# # https://www.npmjs.com/package/grunt-nice-package#alternative-default-options
# # "generate-package" generate package.json:
# # https://www.npmjs.com/package/generate-package
# # https://stackoverflow.com/a/49053110/5951529
# nicePackage:
# all:
# options:
# blankLine: false
# ###################
# ## gulp-htmltidy ##
# ###################
# # Validate HTML
# # https://www.npmjs.com/package/gulp-htmltidy
# ##########################
# ## grunt-gulp variables ##
# ##########################
# # https://www.npmjs.com/package/grunt-gulp#examples
# # CoffeeScript to JavaScript online — http://js2.coffee/
# gulp = require('gulp')
# htmltidy = require('gulp-htmltidy')
# # For in-place dest needs «base: "."», see:
# # https://stackoverflow.com/a/44337370/5951529
# # [BUG] Doesn't work for multiple commands, see:
# # https://github.com/shama/grunt-gulp/issues/13
# module.exports =
# gulptidy:
# gulp.src('<%= templates.paths.html %>', base: ".")
# .pipe(htmltidy(
# doctype: 'html5'
# indent: true
# wrap: 0)).pipe gulp.dest('./')
# [DECLINED] pip-licenses more customisable
# ############
# ## yolk3k ##
# ############
# # Generate licenses for all Python packages:
# # https://stackoverflow.com/a/26718306/5951529
# # https://pypi.org/project/yolk3k/
# yolk:
# command: 'pipenv run yolk -l -f license > python.txt'
# [DECLINED] SuperFences now preserve tabs:
# https://github.com/facelessuser/pymdown-extensions/issues/276
# ######################
# ## grunt-indentator ##
# ######################
# # Indent 4 spaces to tab:
# # https://www.npmjs.com/package/grunt-indentator
# # [WARNING]: Replace tabs to spaces only if first indentation — spaces:
# # Needs run before “eslint fix”:
# # https://github.com/gespinha/grunt-indentator/issues/1
# module.exports =
# options:
# type: 'tab'
# size: 1
# debug: true
# files:
# [
# "<%= templates.paths.html %>"
# ]
# [DEPRECATED] Generate invalid license files:
# https://github.com/licenses/lice/issues/50
# I can't file Grunt package for this task;
# license-generator output error in installation process:
# https://pypi.org/project/license-generator/
# ##########
# ## lice ##
# ##########
# # Generate license for project:
# # https://pypi.org/project/lice/
# lice:
# # [BUG] lice doesn't work in AppVeyor:
# # https://github.com/appveyor/ci/issues/2226
# if process.platform == "win32"
# command: 'echo "Sorry, lice doesn\'t work in AppVeyor — https://github.com/appveyor/ci/issues/2226"'
# else
# command: 'pipenv run lice mit -o "PI:NAME:<NAME>END_PI" --file output/LICENSE.md'
# [DEPRECATED] Doesn't work for CSS paths
# #########################
# # grunt-path-absolutely #
# #########################
# # https://www.npmjs.com/package/grunt-path-absolutely
# module.exports =
# cssimages:
# options:
# devRoot: "."
# releaseRoot: "https://kristinita.netlify.app"
# resourceFilter: ["*.css"]
# files: [
# expand: true
# cwd: "."
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/css/aside/*.css"]
# dest: "."
# ]
# [DEPRECATED] Doesn't allow to have comments in JSON configuration files:
# #############################
# # grunt-strip-json-comments #
# #############################
# # Delete comments in JSON files
# # https://www.npmjs.com/package/strip-json-comments
# # https://www.npmjs.com/package/grunt-strip-json-comments
# stripJsonComments:
# dist:
# options:
# whitespace: false
# files:
# '.jsbeautifyrc': '.jsbeautifyrc'
# [DEPRECATED] I don't see plugins, that can come in handy
# ####################
# ## grunt-posthtml ##
# ####################
# # PostHTML support for Grunt:
# # https://github.com/posthtml/posthtml
# # https://www.npmjs.com/package/grunt-juwain-posthtml
# # [WARNING] Use “juwain-posthtml”, not native “posthtml” version:
# # https://github.com/TCotton/grunt-posthtml/issues/3
# module.exports =
# options:
# use: [
# #############
# # ARIA Tabs #
# #############
# # Add WAI-ARIA attributes:
# # http://prgssr.ru/development/ispolzovanie-aria-v-html5.html
# # http://jonathantneal.github.io/posthtml-aria-tabs/
# # [WARNING] Disable, because I use “ul/li” for progressive enhancements:
# # http://jonathantneal.github.io/posthtml-aria-tabs/#caveats
# # require('posthtml-aria-tabs')()
# ]
# build:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# src: ['**/*.html']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# ]
# [DEPRECATED][BUG] grunt-coffee-format make files wrong:
# https://github.com/NotBobTheBuilder/grunt-coffee-format/issues/3
# #######################
# # grunt-coffee-format #
# #######################
# # Formatter for CoffeeScript files:
# # https://www.npmjs.com/package/coffee-fmt
# # Grunt adapter:
# # https://www.npmjs.com/package/grunt-coffee-format
# module.exports =
# options:
# # [INFO] Use tabs, not spaces:
# # https://www.npmjs.com/package/grunt-coffee-format#optionstab
# tab: '\t'
# theme:
# files:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/coffee/**/*.coffee"]
# personal:
# files:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/coffee/**/*.coffee"]
# [DEPRECATED] I migrate to HTML-minifier, arguments:
# [LINK] “htmlmin.coffee”
# ############
# # minimize #
# ############
# # Minify HTML:
# # https://www.npmjs.com/package/minimize
# # https://www.npmjs.com/package/grunt-minify-html
# # [NOTE] Use HTML parser, grunt-contrib-htmlmin use regexes.
# # grunt-htmlclean simply than grunt-minify-html:
# # https://github.com/anseki/htmlclean/issues/11#issuecomment-389386676
# module.exports =
# # https://github.com/Swaagie/minimize#options-1
# # All set false by default:
# # https://github.com/Swaagie/minimize#options
# options:
# # [INFO] I'm not support spare attirbutes for older browsers:
# # https://github.com/Swaagie/minimize#spare
# spare: false
# # [INFO] W3C recommends quotes:
# # https://www.w3schools.com/html/html_attributes.asp
# quotes: true
# minimize:
# files: [
# expand: true
# cwd: "."
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/**/*.html"]
# dest: "."
# ]
# [DECLINED] I hate private discussions
# #########
# # ROT13 #
# #########
# # ROT13 algorithm for e-mail obfuscation:
# # https://en.wikipedia.org/wiki/ROT13
# # https://superuser.com/a/235965/572069
# # Generated by:
# # http://rot13.florianbersier.com/
# # [NOTE] In this script fixed «eo is not defined» bug:
# # https://github.com/xpressyoo/Email-Obfuscator/issues/1
# document.getElementById('obf').innerHTML = \
# '<n uers="znPI:EMAIL:<EMAIL>END_PIgb:PI:EMAIL:<EMAIL>END_PIRzPI:EMAIL:<EMAIL>END_PI?fhowrpg=R-znvy gb Fnfun Purealxu" \
# gnetrg="_oynax">r-znvy</n>'.replace(/[a-zA-Z]/g, (c) ->
# String.fromCharCode if (if c <= 'Z' then 90 else 122) >= (c = c.charCodeAt(0) + 13) then c else c - 26
# )
# [DEPRECATED] Compress files as cssnano; don't remove duplicates
#############
# css-purge #
#############
# Compress CSS:
# http://rbtech.github.io/css-purge/
# Grunt wrapper:
# https://github.com/dominikwilkowski/grunt-css-purge
# Options:
# https://www.npmjs.com/package/css-purge#config-options
# module.exports =
# task:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/css"
# src: ['!**/**/*.css'
# '**/**/*.min.css']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/css"
# ext: '.min.css'
# ]
# [DEPRECATED] UNCSS build all CSS files to single;
# behavior not similar as PurgeCSS and PurifyCSS
###############
# grunt-uncss #
###############
# module.exports =
# options:
# uncssrc: ".uncssrc"
# sublimetexttarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Sublime-Text/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"
# [DEPRECATED]
# Virtual environment and Pipenv doesn't support:
# https://github.com/btholt/grunt-flake8/issues/1
# [WARNING] All linting passed, if flake8 no installed:
# https://github.com/btholt/grunt-flake8/issues/3#issuecomment-473383610
# ##########
# # flake8 #
# ##########
# module.exports =
# dist:
# src: ["*.py"
# "personal-plugins/**/*.py"]
# [DEPRECATED]
# Google Fonts support “font-display: swap” from May 2019:
# https://www.zachleat.com/web/google-fonts-display/
# ###
# Load Google Fonts
# [NOTE] Script required, because Google Fonts doesn't support “font-display”:
# https://css-tricks.com/google-fonts-and-font-display/
# https://github.com/google/fonts/issues/358
# [INFO] “font-display: swap”, that:
# 1. Default font will show to site visitors before Google font
# 2. Fix “Ensure text remains visible during webfont load” of PageSpeed Insights
# https://web.dev/fast/avoid-invisible-text
# https://developers.google.com/web/updates/2016/02/font-display
# [INFO] If “font-display: swap”, sit visitor see text without any delay:
# https://font-display.glitch.me/
# [LEARN][COFFEESCRIPT] For converting EcmaScript 6 to CoffeeScript:
# 1. Convert EcmaScript 6 to JavaScript. Online converter — https://babeljs.io/en/repl .
# 2. Convert JavaScript to CoffeeScript via js2coffee.
# https://github.com/js2coffee/js2coffee/issues/449#issuecomment-470128539
# ###
# loadFont = (url) ->
# # [LEARN][COFFEESCRIPT] Wrap constructor to parens (parentheses, round brackets),
# # if CoffeeLint warnings:
# # https://github.com/clutchski/coffeelint/blob/master/src/rules/non_empty_constructor_needs_parens.coffee
# # https://github.com/clutchski/coffeelint/blob/master/src/rules/empty_constructor_needs_parens.coffee
# xhr = new (XMLHttpRequest)
# xhr.open 'GET', url, true
# xhr.onreadystatechange = ->
# if xhr.readyState is 4 and xhr.status is 200
# css = xhr.responseText
# css = css.replace(/}/g, 'font-display: swap; }')
# head = document.getElementsByTagName('head')[0]
# style = document.createElement('style')
# style.appendChild document.createTextNode(css)
# head.appendChild style
# return
# xhr.send()
# return
# loadFont 'https://fonts.googleapis.com/css?family=Play:700\
# |El+Messiri|Scada:700i|Fira+Mono|Marck+Script&subset=cyrillic&display=swap'
# [DEPRECATED]
# Linux — it not needed; Linux doesn't lock opened files and folders$
# see “You Can Delete or Modify Open Files”:
# https://www.howtogeek.com/137096/6-ways-the-linux-file-system-is-different-from-the-windows-file-system/
# Windows — it not unlock files or folders as any another program:
# https://superuser.com/q/1485406/572069
###############
# grunt-chmod #
###############
# # Add read and write permissions for all output folders and files:
# # https://www.npmjs.com/package/grunt-chmod
# # About chmod:
# # https://ss64.com/bash/chmod.html
# # [DESCRIPTION]
# # I open any files → I run “publishconf.py”, that delete “output” folder →
# # I can get errors as:
# # ERROR: Unable to delete directory D:\Kristinita\output\stylus; OSError: [WinError 145]
# # The directory is not empty: 'D:\\Kristinita\\output\\stylus\\personal'
# # chmod fix this problem.
# # [WARNING] You need close BrowserSync before publishing,
# # because it can create new permissions.
# module.exports =
# options:
# # [NOTE] 444 and 666 modes works in Windows:
# # https://www.npmjs.com/package/grunt-chmod#warnings
# mode: '666'
# kiratarget:
# # [LEARN][GRUNT] All folders and files recursive, include current:
# # https://gruntjs.com/configuring-tasks#globbing-patterns
# src: "<%= templates.yamlconfig.OUTPUT_PATH %>/**"
# [DECLINED]
# 1. JSBeautifier is more powerful tool
# 2. JSBeautifier has many options; Prettier — minimal set, see options philosophy:
# https://prettier.io/docs/en/option-philosophy.html
# 3. Strange HTML prettifying for Prettier
# 4. Bug for grunt-prettier:
# https://github.com/poalrom/grunt-prettier/issues/20
# ############
# # Prettier #
# ############
# # Prettifier for many formats, include css, javascript:
# # https://prettier.io/
# # Grunt wrapper:
# # https://www.npmjs.com/package/grunt-prettier
# # Options:
# # https://prettier.io/docs/en/options.html
# module.exports =
# cssdebug:
# # [NOTE] “ext: '.min.{css,js}'” will not work;
# # Grunt will generate file “kirafile.min.{css,js}”
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# src: ['**/*.css'
# '!**/*.min.css']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# ]
# jsdebug:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# src: ['**/*.js'
# '!**/*.min.js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>"
# ]
# # htmldebug:
# # files: [
# # expand: true
# # cwd: "."
# # src: "<%= templates.yamlconfig.OUTPUT_PATH %>/Books-Reviews/Как-читать-архитектуру.html"
# # dest: "."
# # ]
# [DEPRECATED]
# [BUG] Checker works incorectly with encoded URLs, see examples:
# Another users:
# https://github.com/ChrisWren/grunt-link-checker/issues/28
# Me:
# “>> Resource not found linked from https://kristinita.netlify.app/opensearch.xml
# to https://kristinita.netlify.app/favicon16%C3%9716.ico”
# ################
# # link-checker #
# ################
# ###
# [PURPOSE] Check links via node-simplecrawler:
# https://github.com/chriswren/grunt-link-checker
# https://www.npmjs.com/package/simplecrawler
# ###
# module.exports =
# development:
# site: "kristinita.netlify.app"
# options:
# checkRedirect: true
# noFragment: false
# [DEPRECATED] grunt-crawl doesn’t support the newest Node.js and Grunt versions:
# https://github.com/mradcliffe/grunt-crawl/pull/15
# ###############
# # grunt-crawl #
# ###############
# ###
# [INFO] Grunt crawler; possibly, check URLs:
# https://www.npmjs.com/package/grunt-crawl
#
# [NOTE] markdown-link-check tool doesn’t support internal links:
# https://github.com/tcort/markdown-link-check
# Example:
# [✖] ../Special/Полная-библиография#Открытость → Status: 400
# ###
# module.exports =
# myapp:
# options:
# baseUrl: "http://localhost:4147/"
# contentDir: "output"
# [FIXME][ISSUE] 2 problems:
# 1. grunt-blank audit failed, but manually with (TreeSize Free) review shows,
# that I haven’t files < 2 bytes
# 2. grunt-blank doesn’t show, which files lower that 2 bytes.
# ###############
# # grunt-blank #
# ###############
# # [PURPOSE] Check files with size lower than “minBytes”:
# # https://www.npmjs.com/package/grunt-blank
# module.exports =
# options:
# minBytes: 2
# task:
# src: [
# "<%= templates.yamlconfig.CONTENT_PATH %>"
# "<%= templates.yamlconfig.THEME_STATIC_DIR %>"
# ]
# [DECLINED] The project no longer maintained since 2018:
# https://github.com/purifycss/purifycss/issues/213
# I migrate to PurgeCSS.
# #####################
# ## grunt-purifycss ##
# #####################
# ###
# [OVERVIEW] Remove unused CSS for kristinita.netlify.app design:
# https://www.npmjs.com/package/purify-css
# https://www.npmjs.com/package/grunt-purifycss
# [NOTE] Needs separate task for each style. Because theme use different styles:
# [BUG] Doesn’t work with grunt-newer:
# https://github.com/purifycss/grunt-purifycss/issues/30
# ###
# module.exports =
# options:
# ###
# [WARNING] PurifyCSS support elements, that include simply methods.
# Example: <div class="SashaClass"></div> in HTML;
# .SashaClass { color: black } in CSS;
# If elements generated by JavaScript, PurifyCSS doesn’t work:
# https://github.com/purifycss/purifycss/issues/194
# ###
# whitelist: [
# # [WARNING] Don't use multiline comments inside list!
# # Coffeelint will show “unexpected newline” error:
# # No issue, because coffeelint not maintained at March, 2019:
# # https://github.com/clutchski/coffeelint/issues
# # [INFO] Wildfire classes
# # [INFO] “div” for parent classes not required.
# # [FIXME] Migrate to PurgeCSS, that not add each Wildfire class separately:
# # https://github.com/FullHuman/grunt-purgecss/issues/9
# ".animate-flicker"
# ".ivu-modal-body"
# ".ivu-btn"
# ".ivu-tabs-tabpane"
# # [NOTE] Adjoining classes required in this case.
# ".wf.wf-theme-dark"
# ".ivu-btn-primary"
# ".wf-separator"
# ".wf-no-content-tip"
# ":not(.v-transfer-dom)"
# ".ivu-menu-submenu-title-icon"
# ".ivu-input-wrapper"
# ".wf-post-btn"
# ".ivu-menu-horizontal"
# ".ivu-menu-light"
# ".ivu-icon-heart-broken"
# ".ivu-icon-heart"
# ".wf-inactive"
# ".ivu-icon-at"
# ".ivu-menu-item-selected"
# ".ivu-menu"
# "svg"
# # [INFO] Tooltipster classes.
# # [NOTE] Use parent classes:
# # For:
# # .tooltipster-punk-aquamarine .tooltipster-box
# # .tooltipster-punk-purple .tooltipster-box
# # “.tooltipster-box” in “whitelist” option will not works
# ".tooltipster-punk-purple .tooltipster-box"
# ".tooltipster-punk-aquamarine .tooltipster-box"
# ]
# indextarget:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/index.html"]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/kristinita.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/kristinita.css"
# sublimetexttarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Erics-Rooms/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Programs/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Sublime-Text/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/programs.css"
# gingerinastarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Erics-Rooms/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Gingerinas/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/gingerinas.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/gingerinas.css"
# itarticlestarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Erics-Rooms/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/IT-articles/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/it-articles.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/it-articles.css"
# giologicabluetarget:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/Giologica/Valerywork-Kiravel.html"]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica-blue.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica-blue.css"
# giologicatarget:
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Books-Reviews/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Giologica/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/G-Rights/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Special/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/giologica.css"
# sashablacktarget:
# # Pages and Sasha Black
# src: [
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Sasha-Black/*.html"
# "<%= templates.yamlconfig.OUTPUT_PATH %>/Pages/*.html"
# ]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/sasha-black-description.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/sasha-black-description.css"
# smertsvobodetarget:
# src: ["<%= templates.yamlconfig.OUTPUT_PATH %>/Smert-svobode/*.html"]
# css: ["<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/smert-svobode.css"]
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/theme/css/sections/smert-svobode.css"
# [DECLINED]
# 1. posthtml-img-autosize doesn’t work for relative paths:
# https://github.com/posthtml/grunt-posthtml/issues/4
# 2. lazysizes plugin required for my environment,
# I don’t add native lazy loading via posthtml-lazyload
# ####################
# ## grunt-posthtml ##
# ####################
# ###
# [INFO] Framework to transform HTML/XML via JavaScript plugins:
# https://posthtml.org/#/
# https://www.npmjs.com/package/posthtml
# [INFO] Plugins:
# https://www.npmjs.com/package/posthtml#plugins
# [INFO] Grunt wrapper:
# https://www.npmjs.com/package/grunt-juwain-posthtml
# [FIXED] https://github.com/posthtml/grunt-posthtml/issues/4
# [NOTE] Default version — “https://www.npmjs.com/package/grunt-posthtml” —
# doesn’t work for me. I use grunt-juwain-posthtml version:
# https://github.com/posthtml/grunt-posthtml/issues/3
# ###
# module.exports =
# options:
# use: [
# #####################
# # posthtml-lazyload #
# #####################
# # [SOON] Currently, I still use JQuery Lazy for lazy loading images and iframes.
# # We have polyfill for browsers that not supported loading="lazy":
# # https://github.com/mfranzke/loading-attribute-polyfill
# # Polyfill problems:
# # 1. It not valid:
# # https://github.com/mfranzke/loading-attribute-polyfill/issues/90
# # 2. Additional syntax required:
# # https://github.com/mfranzke/loading-attribute-polyfill#simple-image
# # [ACTION] Add “loading="lazy"” to all images and iframes:
# # https://www.npmjs.com/package/posthtml-lazyload
# # [NOTE] I couldn’t find any method for applying lazy loading for
# # all images and frames without adding “loading="lazy"” each time
# # [INFO] “loading="eager"” — load resources immediatly:
# # https://web.dev/browser-level-image-lazy-loading/
# # [INFO] For “picture” tag the “loading” attribute required solely for
# # the fallback “img” element:
# # https://web.dev/browser-level-image-lazy-loading/
# # [NOTE] CSS background images haven’t “loading” attribute:
# # https://web.dev/browser-level-image-lazy-loading/\
# #can-css-background-images-take-advantage-of-the-loading-attribute
# # require('posthtml-lazyload')(loading: 'lazy')
# #########################
# # posthtml-img-autosize #
# #########################
# # [BUG] Plugin doesn’t work with relative paths:
# # https://github.com/posthtml/posthtml-img-autosize/issues/17#issuecomment-706592803
# # [OVERVIEW] Plugin adds “height” and “width” attributes to all images:
# # https://www.npmjs.com/package/posthtml-img-autosize
# # [INFO] It required for 2020:
# # https://www.smashingmagazine.com/2020/03/setting-height-width-images-important-again/
# # require('posthtml-img-autosize')(
# # processEmptySize: true
# # root: "output/Programs"
# # )
# ]
# target:
# files: [
# expand: true
# cwd: "."
# src: "output/Programs/*.html"
# dest: "."
# ]
# [DECLINED] UglifyJS doesn’t support EcmaScript 2015 and above:
# https://www.npmjs.com/package/uglify-js#note
# #############
# # Uglify JS #
# #############
# # JavaScript minifier:
# # http://lisperator.net/uglifyjs/
# # https://www.npmjs.com/package/grunt-contrib-uglify
# # Options:
# # http://lisperator.net/uglifyjs/compress
# # [INFO] I selected Uglify JS, not alternatives, because they obsolete:
# # Esmangle:
# # https://github.com/estools/esmangle
# # Closure-compiler:
# # https://github.com/gmarty/grunt-closure-compiler
# # [INFO] Benchmark:
# # https://evmar.github.io/js-min-bench/
# module.exports =
# options:
# # [LEARN][CSS][JAVASCRIPT] Sourcemaps
# # make debugging simply, if styles and scripts combine and compress:
# # https://blog.teamtreehouse.com/introduction-source-maps
# sourceMap: true
# uglifypersonal:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] “!” symbol — exclude paths:
# # https://stackoverflow.com/a/28277841/5951529
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] Extensions in filepaths:
# # https://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
# ext: '.min.js'
# ]
# uglifytheme:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# ext: '.min.js'
# ]
# [DECLINED] Closure Compiler have best result in the benchmark:
# https://evmar.github.io/js-min-bench/
# [INFO] I don’t exclude that I will use terser if Closure Compiler problems will not be fixed:
# https://github.com/google/closure-compiler/issues/3729
# https://github.com/google/closure-compiler/issues/3727
# https://stackoverflow.com/q/64927683/5951529
# ##########
# # Terser #
# ##########
# ###
# JavaScript minifier:
# http://lisperator.net/uglifyjs/
# https://www.npmjs.com/package/grunt-contrib-uglify
# Options:
# http://lisperator.net/uglifyjs/compress
# [INFO] I selected Uglify JS, not alternatives, because they obsolete:
# Esmangle:
# https://github.com/estools/esmangle
# Closure-compiler:
# https://github.com/gmarty/grunt-closure-compiler
# ###
# module.exports =
# options:
# # [LEARN][CSS][JAVASCRIPT] Sourcemaps
# # make debugging simply, if styles and scripts combine and compress:
# # https://blog.teamtreehouse.com/introduction-source-maps
# sourceMap: true
# terserpersonal:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] “!” symbol — exclude paths:
# # https://stackoverflow.com/a/28277841/5951529
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/js/personal"
# # [LEARN][GRUNT] Extensions in filepaths:
# # https://gruntjs.com/configuring-tasks#building-the-files-object-dynamically
# ext: '.min.js'
# ]
# tersertheme:
# files: [
# expand: true
# cwd: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# src: ['**/*.js'
# '!**/*.min*js']
# dest: "<%= templates.yamlconfig.OUTPUT_PATH %>/<%= templates.yamlconfig.THEME_STATIC_DIR %>/js"
# ext: '.min.js'
# ]
|
[
{
"context": "p://voxe.org/assets/iOS/114ios.png',\n name: \"Voxe\",\n caption: 'Voxe.org',\n description: '",
"end": 578,
"score": 0.9971392154693604,
"start": 574,
"tag": "NAME",
"value": "Voxe"
}
] | app/assets/javascripts/embed/elections/views/application.js.coffee | JulienGuizot/voxe | 5 | class window.ApplicationView extends Backbone.View
events:
"click .facebook": "facebook"
initialize: ->
@model.bind 'change', @setElectionName
@width = $('#app').width()
@height = $('#app').height()
setElectionName: =>
@.$('#header .container').html @model.name()
render: ->
$(@el).html Mustache.to_html($('#application-template').html(), election: @model.toJSON())
@
facebook: ->
obj = {
method: 'feed',
link: 'http://voxe.org',
picture: 'http://voxe.org/assets/iOS/114ios.png',
name: "Voxe",
caption: 'Voxe.org',
description: 'Comparer les candidats avant de voter.'
}
FB.ui obj, (response)->
if response['post_id']
alert 'Envoye!' | 199133 | class window.ApplicationView extends Backbone.View
events:
"click .facebook": "facebook"
initialize: ->
@model.bind 'change', @setElectionName
@width = $('#app').width()
@height = $('#app').height()
setElectionName: =>
@.$('#header .container').html @model.name()
render: ->
$(@el).html Mustache.to_html($('#application-template').html(), election: @model.toJSON())
@
facebook: ->
obj = {
method: 'feed',
link: 'http://voxe.org',
picture: 'http://voxe.org/assets/iOS/114ios.png',
name: "<NAME>",
caption: 'Voxe.org',
description: 'Comparer les candidats avant de voter.'
}
FB.ui obj, (response)->
if response['post_id']
alert 'Envoye!' | true | class window.ApplicationView extends Backbone.View
events:
"click .facebook": "facebook"
initialize: ->
@model.bind 'change', @setElectionName
@width = $('#app').width()
@height = $('#app').height()
setElectionName: =>
@.$('#header .container').html @model.name()
render: ->
$(@el).html Mustache.to_html($('#application-template').html(), election: @model.toJSON())
@
facebook: ->
obj = {
method: 'feed',
link: 'http://voxe.org',
picture: 'http://voxe.org/assets/iOS/114ios.png',
name: "PI:NAME:<NAME>END_PI",
caption: 'Voxe.org',
description: 'Comparer les candidats avant de voter.'
}
FB.ui obj, (response)->
if response['post_id']
alert 'Envoye!' |
[
{
"context": "#\n# Project's main unit\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Autocompleter extends UI.Menu\n include: ",
"end": 64,
"score": 0.9998811483383179,
"start": 47,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | ui/autocompleter/src/autocompleter.coffee | lovely-io/lovely.io-stl | 2 | #
# Project's main unit
#
# Copyright (C) 2012 Nikolay Nemshilov
#
class Autocompleter extends UI.Menu
include: core.Options
extend:
Options: # default options
src: [] # an url to the search query or an Array of
method: 'get' # ajax requests default HTTP method
minLength: 1 # min text length for the autocompleter to start working
threshold: 200 # the user's typing pause length for the autocompleter to watch
highlight: true # autohighlight matching entries
cache: true # cache search results internally
#
# Basic constructor
#
# @param {Element|HTMLElement|String} the input element reference
# @param {Object} extra options
# @return {Autocompleter} this
#
constructor: (input, options)->
options or= {}; opts = {}
for key, value of options
if key of @constructor.Options
opts[key] = value
delete(options[key])
@$super(options).addClass('lui-autocompleter')
@input = Element.resolve(input).on('keyup', (event)=> @listen(event) )
@spinner = new UI.Spinner()
@input.autocompleter = @
for key, value of options = @input.data('autocompleter') || {}
opts[key] or= value
@setOptions(opts)
@on 'pick', (event)->
@input.value(event.link.text())
@emit 'complete', text: event.link.text()
return @
#
# Listens to an input field keyups, waits for it to pause
#
# @param {dom.Event} keyboard event
# @return {Autocompleter} this
#
listen: (event)->
window.clearTimeout @_timeout if @_timeout
if !(event.keyCode in [37,38,39,40,13,27]) && @input._.value.length >= @options.minLength
@_timeout = window.setTimeout =>
if @input._.value.length >= @options.minLength
@suggest()
else
@hide()
, @options.threshold
return @
#
# Starts the autocompletion search
#
# @return {Autocompleter} this
#
suggest: ->
search = '' + @input._.value
if typeof(@options.src) is 'string'
unless @ajax
@ajax = new Ajax(@options.src.replace('{search}', search), method: @options.method)
@ajax.on 'complete', =>
if @ajax.responseJSON
@update(@ajax.responseJSON, search).showAt(@input)
else
@hide()
@ajax = null
@ajax.send()
else # assuming it's an array
@update core.L(@options.src).filter (item)->
item.toLowerCase().substr(0, search.length) is search.toLowerCase()
, search
@showAt(@input)
return @
#
# Updates the element's content
#
# @param {String|Array} content
# @param {String} highlight text
# @return {Autocompleter} self
#
update: (content, highlight)->
if isArray(content) && highlight isnt undefined
highlight = String(highlight).toLowerCase()
content = core.L(content).map (entry)=>
if @options.highlight && highlight && (index = entry.toLowerCase().indexOf(highlight)) isnt -1
entry = entry.substr(0, index) + '<strong>' +
entry.substr(index, index + highlight.length) + '</strong>' +
entry.substr(index + highlight.length)
"<a href='#'>#{entry}</a>"
content = content.join("\n")
@$super(content) | 95692 | #
# Project's main unit
#
# Copyright (C) 2012 <NAME>
#
class Autocompleter extends UI.Menu
include: core.Options
extend:
Options: # default options
src: [] # an url to the search query or an Array of
method: 'get' # ajax requests default HTTP method
minLength: 1 # min text length for the autocompleter to start working
threshold: 200 # the user's typing pause length for the autocompleter to watch
highlight: true # autohighlight matching entries
cache: true # cache search results internally
#
# Basic constructor
#
# @param {Element|HTMLElement|String} the input element reference
# @param {Object} extra options
# @return {Autocompleter} this
#
constructor: (input, options)->
options or= {}; opts = {}
for key, value of options
if key of @constructor.Options
opts[key] = value
delete(options[key])
@$super(options).addClass('lui-autocompleter')
@input = Element.resolve(input).on('keyup', (event)=> @listen(event) )
@spinner = new UI.Spinner()
@input.autocompleter = @
for key, value of options = @input.data('autocompleter') || {}
opts[key] or= value
@setOptions(opts)
@on 'pick', (event)->
@input.value(event.link.text())
@emit 'complete', text: event.link.text()
return @
#
# Listens to an input field keyups, waits for it to pause
#
# @param {dom.Event} keyboard event
# @return {Autocompleter} this
#
listen: (event)->
window.clearTimeout @_timeout if @_timeout
if !(event.keyCode in [37,38,39,40,13,27]) && @input._.value.length >= @options.minLength
@_timeout = window.setTimeout =>
if @input._.value.length >= @options.minLength
@suggest()
else
@hide()
, @options.threshold
return @
#
# Starts the autocompletion search
#
# @return {Autocompleter} this
#
suggest: ->
search = '' + @input._.value
if typeof(@options.src) is 'string'
unless @ajax
@ajax = new Ajax(@options.src.replace('{search}', search), method: @options.method)
@ajax.on 'complete', =>
if @ajax.responseJSON
@update(@ajax.responseJSON, search).showAt(@input)
else
@hide()
@ajax = null
@ajax.send()
else # assuming it's an array
@update core.L(@options.src).filter (item)->
item.toLowerCase().substr(0, search.length) is search.toLowerCase()
, search
@showAt(@input)
return @
#
# Updates the element's content
#
# @param {String|Array} content
# @param {String} highlight text
# @return {Autocompleter} self
#
update: (content, highlight)->
if isArray(content) && highlight isnt undefined
highlight = String(highlight).toLowerCase()
content = core.L(content).map (entry)=>
if @options.highlight && highlight && (index = entry.toLowerCase().indexOf(highlight)) isnt -1
entry = entry.substr(0, index) + '<strong>' +
entry.substr(index, index + highlight.length) + '</strong>' +
entry.substr(index + highlight.length)
"<a href='#'>#{entry}</a>"
content = content.join("\n")
@$super(content) | true | #
# Project's main unit
#
# Copyright (C) 2012 PI:NAME:<NAME>END_PI
#
class Autocompleter extends UI.Menu
include: core.Options
extend:
Options: # default options
src: [] # an url to the search query or an Array of
method: 'get' # ajax requests default HTTP method
minLength: 1 # min text length for the autocompleter to start working
threshold: 200 # the user's typing pause length for the autocompleter to watch
highlight: true # autohighlight matching entries
cache: true # cache search results internally
#
# Basic constructor
#
# @param {Element|HTMLElement|String} the input element reference
# @param {Object} extra options
# @return {Autocompleter} this
#
constructor: (input, options)->
options or= {}; opts = {}
for key, value of options
if key of @constructor.Options
opts[key] = value
delete(options[key])
@$super(options).addClass('lui-autocompleter')
@input = Element.resolve(input).on('keyup', (event)=> @listen(event) )
@spinner = new UI.Spinner()
@input.autocompleter = @
for key, value of options = @input.data('autocompleter') || {}
opts[key] or= value
@setOptions(opts)
@on 'pick', (event)->
@input.value(event.link.text())
@emit 'complete', text: event.link.text()
return @
#
# Listens to an input field keyups, waits for it to pause
#
# @param {dom.Event} keyboard event
# @return {Autocompleter} this
#
listen: (event)->
window.clearTimeout @_timeout if @_timeout
if !(event.keyCode in [37,38,39,40,13,27]) && @input._.value.length >= @options.minLength
@_timeout = window.setTimeout =>
if @input._.value.length >= @options.minLength
@suggest()
else
@hide()
, @options.threshold
return @
#
# Starts the autocompletion search
#
# @return {Autocompleter} this
#
suggest: ->
search = '' + @input._.value
if typeof(@options.src) is 'string'
unless @ajax
@ajax = new Ajax(@options.src.replace('{search}', search), method: @options.method)
@ajax.on 'complete', =>
if @ajax.responseJSON
@update(@ajax.responseJSON, search).showAt(@input)
else
@hide()
@ajax = null
@ajax.send()
else # assuming it's an array
@update core.L(@options.src).filter (item)->
item.toLowerCase().substr(0, search.length) is search.toLowerCase()
, search
@showAt(@input)
return @
#
# Updates the element's content
#
# @param {String|Array} content
# @param {String} highlight text
# @return {Autocompleter} self
#
update: (content, highlight)->
if isArray(content) && highlight isnt undefined
highlight = String(highlight).toLowerCase()
content = core.L(content).map (entry)=>
if @options.highlight && highlight && (index = entry.toLowerCase().indexOf(highlight)) isnt -1
entry = entry.substr(0, index) + '<strong>' +
entry.substr(index, index + highlight.length) + '</strong>' +
entry.substr(index + highlight.length)
"<a href='#'>#{entry}</a>"
content = content.join("\n")
@$super(content) |
[
{
"context": "', ->\n effect = null\n user = {\n name: 'user1'\n iff: -> true\n attackAttrs: -> []\n ",
"end": 3397,
"score": 0.9991282224655151,
"start": 3392,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " targets = [\n {\n hp:50\n name:'user2'\n iff: -> true\n }\n ]\n it 'エフェクト",
"end": 3506,
"score": 0.997965931892395,
"start": 3501,
"tag": "USERNAME",
"value": "user2"
},
{
"context": "er,targets,log)\n log.user.name.should.equal 'user1'\n log.targets[0].name.should.equal 'user2'\n ",
"end": 4035,
"score": 0.9990741610527039,
"start": 4030,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "l 'user1'\n log.targets[0].name.should.equal 'user2'\n log.targets[0].hp.should.equal 10\n ta",
"end": 4082,
"score": 0.9778053164482117,
"start": 4077,
"tag": "USERNAME",
"value": "user2"
},
{
"context": "', ->\n effect = null\n user = {\n name: 'user1'\n patk: 100\n matk: 50\n iff: -> fal",
"end": 4235,
"score": 0.9989714622497559,
"start": 4230,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " targets = [\n {\n hp:50\n name:'user2'\n pdef: 100\n iff: -> true\n }\n ",
"end": 4376,
"score": 0.9971598982810974,
"start": 4371,
"tag": "USERNAME",
"value": "user2"
},
{
"context": " ->\n effect = new rpg.Effect(\n name: '炎の矢'\n scope: {\n type: SCOPE.TYPE.EN",
"end": 4915,
"score": 0.6569886803627014,
"start": 4914,
"tag": "NAME",
"value": "炎"
},
{
"context": "', ->\n effect = null\n user = {\n name: 'user1'\n atk: 100\n matk: 50\n iff: -> fals",
"end": 5383,
"score": 0.9987703561782837,
"start": 5378,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " targets = [\n {\n hp:50\n name:'user2'\n iff: -> true\n states: []\n }\n",
"end": 5523,
"score": 0.9931954741477966,
"start": 5518,
"tag": "USERNAME",
"value": "user2"
},
{
"context": ".equal 'State1'\n log.user.name.should.equal 'user1'\n log.targets[0].name.should.equal 'user2'\n ",
"end": 6102,
"score": 0.9983272552490234,
"start": 6097,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "l 'user1'\n log.targets[0].name.should.equal 'user2'\n log.targets[0].state.name.should.equal 'St",
"end": 6149,
"score": 0.9628928899765015,
"start": 6144,
"tag": "USERNAME",
"value": "user2"
},
{
"context": ".should.equal 0\n log.user.name.should.equal 'user1'\n log.targets[0].name.should.equal 'user2'\n ",
"end": 6820,
"score": 0.9985602498054504,
"start": 6815,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "l 'user1'\n log.targets[0].name.should.equal 'user2'\n log.targets[0].state.name.should.equal 'St",
"end": 6867,
"score": 0.9936263561248779,
"start": 6862,
"tag": "USERNAME",
"value": "user2"
},
{
"context": ",'回復']}\n ]\n )\n user = {\n name: 'user1'\n iff: -> true\n attackAttrs: -> []\n ",
"end": 7187,
"score": 0.9990451335906982,
"start": 7182,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " targets = [\n {\n hp:50\n name:'user2'\n iff: -> true\n }\n ]\n it 'エフェクト",
"end": 7296,
"score": 0.9943599104881287,
"start": 7291,
"tag": "USERNAME",
"value": "user2"
},
{
"context": "', ->\n effect = null\n user = {\n name: 'user1'\n patk: 100\n matk: 50\n iff: -> fal",
"end": 7660,
"score": 0.9993749856948853,
"start": 7655,
"tag": "USERNAME",
"value": "user1"
},
{
"context": "ets = [\n {\n hp:50\n name:'user2'\n pdef: 100\n iff: -> true\n ",
"end": 8393,
"score": 0.9992291927337646,
"start": 8388,
"tag": "USERNAME",
"value": "user2"
},
{
"context": "ets = [\n {\n hp:50\n name:'user2'\n iff: -> true\n states: []\n ",
"end": 9113,
"score": 0.9991650581359863,
"start": 9108,
"tag": "USERNAME",
"value": "user2"
},
{
"context": "l 'user1'\n log.targets[0].name.should.equal 'user2'\n log.targets[0].state.name.should.equal 'St",
"end": 9820,
"score": 0.810616672039032,
"start": 9815,
"tag": "USERNAME",
"value": "user2"
}
] | src/test/common/EffectTest.coffee | fukuyama/tmlib-rpg | 0 | require('chai').should()
require('../../main/common/utils.coffee')
require('../../main/common/constants.coffee')
require('../../main/common/Battler.coffee')
require('../../main/common/Actor.coffee')
require('../../main/common/Effect.coffee')
require('../../main/common/State.coffee')
require('../../test/common/System.coffee')
{
SCOPE
USABLE
} = rpg.constants
# 価値は何か,誰にとっての価値か,実際の機能は何か
describe 'rpg.Effect', ->
rpg.system.temp = rpg.system.temp ? {}
states = {
'State1': new rpg.State({name:'State1'})
}
rpg.system.temp.battle = false
rpg.system.db.state = (key) -> states[key]
describe 'ヘルプテキスト', ->
effect = null
it 'default', ->
effect = new rpg.Effect(url:'test01')
effect.help.should.equal ''
it 'set/get', ->
effect = new rpg.Effect(url:'test01')
effect.help.should.equal ''
effect.help = 'help'
effect.help.should.equal 'help'
effect.help = 'help1'
effect.help.should.equal 'help'
it 'cache', ->
effect = new rpg.Effect(url:'test01')
effect.help.should.equal 'help'
describe 'メッセージテンプレート', ->
effect = null
it 'default', ->
effect = new rpg.Effect(url:'test02')
effect.message.should.equal ''
it 'set/get', ->
effect = new rpg.Effect(url:'test02',message:{ok:[{type:'message',params:['test']}],ng:[]})
effect.message.should.have.property 'ok'
effect.message.ok.should.have.length 1
it 'cache', ->
effect = new rpg.Effect(url:'test02')
effect.message.should.have.property 'ok'
effect.message.ok.should.have.length 1
effect = new rpg.Effect(url:'test03')
effect.message.should.equal ''
describe 'useableフラグ', ->
effect = null
it 'default', ->
effect = new rpg.Effect()
rpg.system.temp.battle = false
effect.usable.should.equal false
it '使用できない', ->
effect = new rpg.Effect(usable:USABLE.NONE)
rpg.system.temp.battle = false
effect.usable.should.equal false, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal false, '戦闘時'
it 'いつでも使用できる', ->
effect = new rpg.Effect(usable:USABLE.ALL)
rpg.system.temp.battle = false
effect.usable.should.equal true, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal true, '戦闘時'
it 'マップのみ(戦闘時以外)使用できる', ->
effect = new rpg.Effect(usable:USABLE.MAP)
rpg.system.temp.battle = false
effect.usable.should.equal true, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal false, '戦闘時'
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
rpg.system.temp.battle = false
effect.usable.should.equal true, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal false, '戦闘時'
it '戦闘時のみ使用できる', ->
effect = new rpg.Effect(usable:USABLE.BATTLE)
rpg.system.temp.battle = false
effect.usable.should.equal false, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal true, '戦闘時'
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
rpg.system.temp.battle = false
effect.usable.should.equal false, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal true, '戦闘時'
describe '回復エフェクト', ->
effect = null
user = {
name: 'user1'
iff: -> true
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
iff: -> true
}
]
it 'エフェクトの作成', ->
effect = new rpg.Effect(
user:
effects:[
]
target:
effects:[
{hp:10,attrs:['魔法','回復']}
]
)
it 'エフェクトの取得', ->
cx = effect.effect(user,targets)
cx.targets[0].hp.should.equal 10
(cx.user isnt null).should.equal true
it 'エフェクトの反映', ->
targets[0].hp.should.equal 50
log = {}
effect.effectApply(user,targets,log)
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].hp.should.equal 10
targets[0].hp.should.equal 60
describe '攻撃コンテキスト', ->
effect = null
user = {
name: 'user1'
patk: 100
matk: 50
iff: -> false
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
pdef: 100
iff: -> true
}
]
it '通常攻撃(物理)', ->
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hpdamage:[['user.patk','/',2],'-',['target.pdef','/',4]],attrs:['物理']}
]
)
atkcx = effect.effect(user,targets)
atkcx.target.hpdamage.should.equal 25
atkcx.target.attrs[0].should.equal '物理'
it '魔法攻撃', ->
effect = new rpg.Effect(
name: '炎の矢'
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hpdamage:['user.matk','*',1.5],attrs:['魔法','炎']}
]
)
atkcx = effect.effect(user,targets)
atkcx.target.hpdamage.should.equal 75
atkcx.target.attrs[0].should.equal '魔法'
atkcx.target.attrs[1].should.equal '炎'
describe 'ステートエフェクト', ->
effect = null
user = {
name: 'user1'
atk: 100
matk: 50
iff: -> false
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
iff: -> true
states: []
}
]
it 'ステート追加', ->
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{state: {type:'add',name:'State1'}}
]
)
target = targets[0]
unless target.addState?
target.addState = (state) ->
target.states.push state
log = {}
effect.effectApply(user,targets,log)
target.states[0].name.should.equal 'State1'
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].state.name.should.equal 'State1'
log.targets[0].state.type.should.equal 'add'
it 'ステート削除する', ->
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{state: {type:'remove',name:'State1'}}
]
)
target = targets[0]
unless target.removeState?
target.removeState = (state) ->
state.name.should.equal 'State1'
target.states.pop()
log = {}
effect.effectApply(user,targets,log)
target.states.length.should.equal 0
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].state.name.should.equal 'State1'
log.targets[0].state.type.should.equal 'remove'
describe '効果なしエフェクト', ->
effect = new rpg.Effect(
user:
effects:[
]
target:
effects:[
{hp:0,attrs:['魔法','回復']}
]
)
user = {
name: 'user1'
iff: -> true
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
iff: -> true
}
]
it 'エフェクトの取得', ->
cx = effect.effect(user,targets)
cx.targets[0].hp.should.equal 0
(cx.user isnt null).should.equal true
it 'エフェクトの反映', ->
log = {}
r = effect.effectApply(user,targets,log)
r.should.equal false
describe 'セーブロード', ->
effect = null
user = {
name: 'user1'
patk: 100
matk: 50
iff: -> false
attackAttrs: -> []
}
it '基本', ->
effect = new rpg.Effect(
url: 'test01_save_load'
help: 'help01'
message:
ok: [{type:'message',params:['TEST01']}]
ng: []
)
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
effect.url.should.equal 'test01_save_load'
effect.help.should.equal 'help01'
effect.message.should.have.property 'ok'
effect.message.ok[0].type.should.equal 'message'
jsontest = rpg.utils.createJsonData(effect)
jsontest.should.equal json
it '通常攻撃(物理)', ->
targets = [
{
hp:50
name:'user2'
pdef: 100
iff: -> true
}
]
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hpdamage:[['user.patk','/',2],'-',['target.pdef','/',4]],attrs:['物理']}
]
)
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
atkcx = effect.effect(user,targets)
atkcx.target.hpdamage.should.equal 25
atkcx.target.attrs[0].should.equal '物理'
jsontest = rpg.utils.createJsonData(effect)
jsontest.should.equal json
it 'ステート追加', ->
targets = [
{
hp:50
name:'user2'
iff: -> true
states: []
}
]
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{state: {type:'add',name:'State1'}}
]
)
target = targets[0]
unless target.addState?
target.addState = (state) ->
target.states.push state
log = {}
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
effect.effectApply(user,targets,log)
target.states[0].name.should.equal 'State1'
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].state.name.should.equal 'State1'
log.targets[0].state.type.should.equal 'add'
| 14506 | require('chai').should()
require('../../main/common/utils.coffee')
require('../../main/common/constants.coffee')
require('../../main/common/Battler.coffee')
require('../../main/common/Actor.coffee')
require('../../main/common/Effect.coffee')
require('../../main/common/State.coffee')
require('../../test/common/System.coffee')
{
SCOPE
USABLE
} = rpg.constants
# 価値は何か,誰にとっての価値か,実際の機能は何か
describe 'rpg.Effect', ->
rpg.system.temp = rpg.system.temp ? {}
states = {
'State1': new rpg.State({name:'State1'})
}
rpg.system.temp.battle = false
rpg.system.db.state = (key) -> states[key]
describe 'ヘルプテキスト', ->
effect = null
it 'default', ->
effect = new rpg.Effect(url:'test01')
effect.help.should.equal ''
it 'set/get', ->
effect = new rpg.Effect(url:'test01')
effect.help.should.equal ''
effect.help = 'help'
effect.help.should.equal 'help'
effect.help = 'help1'
effect.help.should.equal 'help'
it 'cache', ->
effect = new rpg.Effect(url:'test01')
effect.help.should.equal 'help'
describe 'メッセージテンプレート', ->
effect = null
it 'default', ->
effect = new rpg.Effect(url:'test02')
effect.message.should.equal ''
it 'set/get', ->
effect = new rpg.Effect(url:'test02',message:{ok:[{type:'message',params:['test']}],ng:[]})
effect.message.should.have.property 'ok'
effect.message.ok.should.have.length 1
it 'cache', ->
effect = new rpg.Effect(url:'test02')
effect.message.should.have.property 'ok'
effect.message.ok.should.have.length 1
effect = new rpg.Effect(url:'test03')
effect.message.should.equal ''
describe 'useableフラグ', ->
effect = null
it 'default', ->
effect = new rpg.Effect()
rpg.system.temp.battle = false
effect.usable.should.equal false
it '使用できない', ->
effect = new rpg.Effect(usable:USABLE.NONE)
rpg.system.temp.battle = false
effect.usable.should.equal false, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal false, '戦闘時'
it 'いつでも使用できる', ->
effect = new rpg.Effect(usable:USABLE.ALL)
rpg.system.temp.battle = false
effect.usable.should.equal true, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal true, '戦闘時'
it 'マップのみ(戦闘時以外)使用できる', ->
effect = new rpg.Effect(usable:USABLE.MAP)
rpg.system.temp.battle = false
effect.usable.should.equal true, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal false, '戦闘時'
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
rpg.system.temp.battle = false
effect.usable.should.equal true, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal false, '戦闘時'
it '戦闘時のみ使用できる', ->
effect = new rpg.Effect(usable:USABLE.BATTLE)
rpg.system.temp.battle = false
effect.usable.should.equal false, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal true, '戦闘時'
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
rpg.system.temp.battle = false
effect.usable.should.equal false, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal true, '戦闘時'
describe '回復エフェクト', ->
effect = null
user = {
name: 'user1'
iff: -> true
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
iff: -> true
}
]
it 'エフェクトの作成', ->
effect = new rpg.Effect(
user:
effects:[
]
target:
effects:[
{hp:10,attrs:['魔法','回復']}
]
)
it 'エフェクトの取得', ->
cx = effect.effect(user,targets)
cx.targets[0].hp.should.equal 10
(cx.user isnt null).should.equal true
it 'エフェクトの反映', ->
targets[0].hp.should.equal 50
log = {}
effect.effectApply(user,targets,log)
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].hp.should.equal 10
targets[0].hp.should.equal 60
describe '攻撃コンテキスト', ->
effect = null
user = {
name: 'user1'
patk: 100
matk: 50
iff: -> false
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
pdef: 100
iff: -> true
}
]
it '通常攻撃(物理)', ->
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hpdamage:[['user.patk','/',2],'-',['target.pdef','/',4]],attrs:['物理']}
]
)
atkcx = effect.effect(user,targets)
atkcx.target.hpdamage.should.equal 25
atkcx.target.attrs[0].should.equal '物理'
it '魔法攻撃', ->
effect = new rpg.Effect(
name: '<NAME>の矢'
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hpdamage:['user.matk','*',1.5],attrs:['魔法','炎']}
]
)
atkcx = effect.effect(user,targets)
atkcx.target.hpdamage.should.equal 75
atkcx.target.attrs[0].should.equal '魔法'
atkcx.target.attrs[1].should.equal '炎'
describe 'ステートエフェクト', ->
effect = null
user = {
name: 'user1'
atk: 100
matk: 50
iff: -> false
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
iff: -> true
states: []
}
]
it 'ステート追加', ->
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{state: {type:'add',name:'State1'}}
]
)
target = targets[0]
unless target.addState?
target.addState = (state) ->
target.states.push state
log = {}
effect.effectApply(user,targets,log)
target.states[0].name.should.equal 'State1'
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].state.name.should.equal 'State1'
log.targets[0].state.type.should.equal 'add'
it 'ステート削除する', ->
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{state: {type:'remove',name:'State1'}}
]
)
target = targets[0]
unless target.removeState?
target.removeState = (state) ->
state.name.should.equal 'State1'
target.states.pop()
log = {}
effect.effectApply(user,targets,log)
target.states.length.should.equal 0
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].state.name.should.equal 'State1'
log.targets[0].state.type.should.equal 'remove'
describe '効果なしエフェクト', ->
effect = new rpg.Effect(
user:
effects:[
]
target:
effects:[
{hp:0,attrs:['魔法','回復']}
]
)
user = {
name: 'user1'
iff: -> true
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
iff: -> true
}
]
it 'エフェクトの取得', ->
cx = effect.effect(user,targets)
cx.targets[0].hp.should.equal 0
(cx.user isnt null).should.equal true
it 'エフェクトの反映', ->
log = {}
r = effect.effectApply(user,targets,log)
r.should.equal false
describe 'セーブロード', ->
effect = null
user = {
name: 'user1'
patk: 100
matk: 50
iff: -> false
attackAttrs: -> []
}
it '基本', ->
effect = new rpg.Effect(
url: 'test01_save_load'
help: 'help01'
message:
ok: [{type:'message',params:['TEST01']}]
ng: []
)
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
effect.url.should.equal 'test01_save_load'
effect.help.should.equal 'help01'
effect.message.should.have.property 'ok'
effect.message.ok[0].type.should.equal 'message'
jsontest = rpg.utils.createJsonData(effect)
jsontest.should.equal json
it '通常攻撃(物理)', ->
targets = [
{
hp:50
name:'user2'
pdef: 100
iff: -> true
}
]
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hpdamage:[['user.patk','/',2],'-',['target.pdef','/',4]],attrs:['物理']}
]
)
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
atkcx = effect.effect(user,targets)
atkcx.target.hpdamage.should.equal 25
atkcx.target.attrs[0].should.equal '物理'
jsontest = rpg.utils.createJsonData(effect)
jsontest.should.equal json
it 'ステート追加', ->
targets = [
{
hp:50
name:'user2'
iff: -> true
states: []
}
]
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{state: {type:'add',name:'State1'}}
]
)
target = targets[0]
unless target.addState?
target.addState = (state) ->
target.states.push state
log = {}
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
effect.effectApply(user,targets,log)
target.states[0].name.should.equal 'State1'
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].state.name.should.equal 'State1'
log.targets[0].state.type.should.equal 'add'
| true | require('chai').should()
require('../../main/common/utils.coffee')
require('../../main/common/constants.coffee')
require('../../main/common/Battler.coffee')
require('../../main/common/Actor.coffee')
require('../../main/common/Effect.coffee')
require('../../main/common/State.coffee')
require('../../test/common/System.coffee')
{
SCOPE
USABLE
} = rpg.constants
# 価値は何か,誰にとっての価値か,実際の機能は何か
describe 'rpg.Effect', ->
rpg.system.temp = rpg.system.temp ? {}
states = {
'State1': new rpg.State({name:'State1'})
}
rpg.system.temp.battle = false
rpg.system.db.state = (key) -> states[key]
describe 'ヘルプテキスト', ->
effect = null
it 'default', ->
effect = new rpg.Effect(url:'test01')
effect.help.should.equal ''
it 'set/get', ->
effect = new rpg.Effect(url:'test01')
effect.help.should.equal ''
effect.help = 'help'
effect.help.should.equal 'help'
effect.help = 'help1'
effect.help.should.equal 'help'
it 'cache', ->
effect = new rpg.Effect(url:'test01')
effect.help.should.equal 'help'
describe 'メッセージテンプレート', ->
effect = null
it 'default', ->
effect = new rpg.Effect(url:'test02')
effect.message.should.equal ''
it 'set/get', ->
effect = new rpg.Effect(url:'test02',message:{ok:[{type:'message',params:['test']}],ng:[]})
effect.message.should.have.property 'ok'
effect.message.ok.should.have.length 1
it 'cache', ->
effect = new rpg.Effect(url:'test02')
effect.message.should.have.property 'ok'
effect.message.ok.should.have.length 1
effect = new rpg.Effect(url:'test03')
effect.message.should.equal ''
describe 'useableフラグ', ->
effect = null
it 'default', ->
effect = new rpg.Effect()
rpg.system.temp.battle = false
effect.usable.should.equal false
it '使用できない', ->
effect = new rpg.Effect(usable:USABLE.NONE)
rpg.system.temp.battle = false
effect.usable.should.equal false, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal false, '戦闘時'
it 'いつでも使用できる', ->
effect = new rpg.Effect(usable:USABLE.ALL)
rpg.system.temp.battle = false
effect.usable.should.equal true, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal true, '戦闘時'
it 'マップのみ(戦闘時以外)使用できる', ->
effect = new rpg.Effect(usable:USABLE.MAP)
rpg.system.temp.battle = false
effect.usable.should.equal true, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal false, '戦闘時'
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
rpg.system.temp.battle = false
effect.usable.should.equal true, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal false, '戦闘時'
it '戦闘時のみ使用できる', ->
effect = new rpg.Effect(usable:USABLE.BATTLE)
rpg.system.temp.battle = false
effect.usable.should.equal false, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal true, '戦闘時'
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
rpg.system.temp.battle = false
effect.usable.should.equal false, 'マップ上'
rpg.system.temp.battle = true
effect.usable.should.equal true, '戦闘時'
describe '回復エフェクト', ->
effect = null
user = {
name: 'user1'
iff: -> true
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
iff: -> true
}
]
it 'エフェクトの作成', ->
effect = new rpg.Effect(
user:
effects:[
]
target:
effects:[
{hp:10,attrs:['魔法','回復']}
]
)
it 'エフェクトの取得', ->
cx = effect.effect(user,targets)
cx.targets[0].hp.should.equal 10
(cx.user isnt null).should.equal true
it 'エフェクトの反映', ->
targets[0].hp.should.equal 50
log = {}
effect.effectApply(user,targets,log)
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].hp.should.equal 10
targets[0].hp.should.equal 60
describe '攻撃コンテキスト', ->
effect = null
user = {
name: 'user1'
patk: 100
matk: 50
iff: -> false
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
pdef: 100
iff: -> true
}
]
it '通常攻撃(物理)', ->
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hpdamage:[['user.patk','/',2],'-',['target.pdef','/',4]],attrs:['物理']}
]
)
atkcx = effect.effect(user,targets)
atkcx.target.hpdamage.should.equal 25
atkcx.target.attrs[0].should.equal '物理'
it '魔法攻撃', ->
effect = new rpg.Effect(
name: 'PI:NAME:<NAME>END_PIの矢'
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hpdamage:['user.matk','*',1.5],attrs:['魔法','炎']}
]
)
atkcx = effect.effect(user,targets)
atkcx.target.hpdamage.should.equal 75
atkcx.target.attrs[0].should.equal '魔法'
atkcx.target.attrs[1].should.equal '炎'
describe 'ステートエフェクト', ->
effect = null
user = {
name: 'user1'
atk: 100
matk: 50
iff: -> false
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
iff: -> true
states: []
}
]
it 'ステート追加', ->
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{state: {type:'add',name:'State1'}}
]
)
target = targets[0]
unless target.addState?
target.addState = (state) ->
target.states.push state
log = {}
effect.effectApply(user,targets,log)
target.states[0].name.should.equal 'State1'
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].state.name.should.equal 'State1'
log.targets[0].state.type.should.equal 'add'
it 'ステート削除する', ->
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{state: {type:'remove',name:'State1'}}
]
)
target = targets[0]
unless target.removeState?
target.removeState = (state) ->
state.name.should.equal 'State1'
target.states.pop()
log = {}
effect.effectApply(user,targets,log)
target.states.length.should.equal 0
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].state.name.should.equal 'State1'
log.targets[0].state.type.should.equal 'remove'
describe '効果なしエフェクト', ->
effect = new rpg.Effect(
user:
effects:[
]
target:
effects:[
{hp:0,attrs:['魔法','回復']}
]
)
user = {
name: 'user1'
iff: -> true
attackAttrs: -> []
}
targets = [
{
hp:50
name:'user2'
iff: -> true
}
]
it 'エフェクトの取得', ->
cx = effect.effect(user,targets)
cx.targets[0].hp.should.equal 0
(cx.user isnt null).should.equal true
it 'エフェクトの反映', ->
log = {}
r = effect.effectApply(user,targets,log)
r.should.equal false
describe 'セーブロード', ->
effect = null
user = {
name: 'user1'
patk: 100
matk: 50
iff: -> false
attackAttrs: -> []
}
it '基本', ->
effect = new rpg.Effect(
url: 'test01_save_load'
help: 'help01'
message:
ok: [{type:'message',params:['TEST01']}]
ng: []
)
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
effect.url.should.equal 'test01_save_load'
effect.help.should.equal 'help01'
effect.message.should.have.property 'ok'
effect.message.ok[0].type.should.equal 'message'
jsontest = rpg.utils.createJsonData(effect)
jsontest.should.equal json
it '通常攻撃(物理)', ->
targets = [
{
hp:50
name:'user2'
pdef: 100
iff: -> true
}
]
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{hpdamage:[['user.patk','/',2],'-',['target.pdef','/',4]],attrs:['物理']}
]
)
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
atkcx = effect.effect(user,targets)
atkcx.target.hpdamage.should.equal 25
atkcx.target.attrs[0].should.equal '物理'
jsontest = rpg.utils.createJsonData(effect)
jsontest.should.equal json
it 'ステート追加', ->
targets = [
{
hp:50
name:'user2'
iff: -> true
states: []
}
]
effect = new rpg.Effect(
scope: {
type: SCOPE.TYPE.ENEMY
range: SCOPE.RANGE.ONE
}
target:
effects:[
{state: {type:'add',name:'State1'}}
]
)
target = targets[0]
unless target.addState?
target.addState = (state) ->
target.states.push state
log = {}
json = rpg.utils.createJsonData(effect)
effect = rpg.utils.createRpgObject(json)
effect.effectApply(user,targets,log)
target.states[0].name.should.equal 'State1'
log.user.name.should.equal 'user1'
log.targets[0].name.should.equal 'user2'
log.targets[0].state.name.should.equal 'State1'
log.targets[0].state.type.should.equal 'add'
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9993293881416321,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": " \"error\", socketErrorListener\n \n # TODO(isaacs): Need a way to reset a stream to fresh state\n ",
"end": 8491,
"score": 0.9847866296768188,
"start": 8485,
"tag": "USERNAME",
"value": "isaacs"
}
] | lib/_http_client.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
ClientRequest = (options, cb) ->
self = this
OutgoingMessage.call self
if util.isString(options)
options = url.parse(options)
else
options = util._extend({}, options)
agent = options.agent
defaultAgent = options._defaultAgent or Agent.globalAgent
if agent is false
agent = new defaultAgent.constructor()
else agent = defaultAgent if util.isNullOrUndefined(agent) and not options.createConnection
self.agent = agent
protocol = options.protocol or defaultAgent.protocol
expectedProtocol = defaultAgent.protocol
expectedProtocol = self.agent.protocol if self.agent and self.agent.protocol
if options.path and RegExp(" ").test(options.path)
# The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
# with an additional rule for ignoring percentage-escaped characters
# but that's a) hard to capture in a regular expression that performs
# well, and b) possibly too restrictive for real-world usage. That's
# why it only scans for spaces because those are guaranteed to create
# an invalid request.
throw new TypeError("Request path contains unescaped characters.")
else throw new Error("Protocol \"" + protocol + "\" not supported. " + "Expected \"" + expectedProtocol + "\".") if protocol isnt expectedProtocol
defaultPort = options.defaultPort or self.agent and self.agent.defaultPort
port = options.port = options.port or defaultPort or 80
host = options.host = options.hostname or options.host or "localhost"
setHost = true if util.isUndefined(options.setHost)
self.socketPath = options.socketPath
method = self.method = (options.method or "GET").toUpperCase()
self.path = options.path or "/"
self.once "response", cb if cb
unless util.isArray(options.headers)
if options.headers
keys = Object.keys(options.headers)
i = 0
l = keys.length
while i < l
key = keys[i]
self.setHeader key, options.headers[key]
i++
if host and not @getHeader("host") and setHost
hostHeader = host
hostHeader += ":" + port if port and +port isnt defaultPort
@setHeader "Host", hostHeader
#basic auth
@setHeader "Authorization", "Basic " + new Buffer(options.auth).toString("base64") if options.auth and not @getHeader("Authorization")
if method is "GET" or method is "HEAD" or method is "DELETE" or method is "OPTIONS" or method is "CONNECT"
self.useChunkedEncodingByDefault = false
else
self.useChunkedEncodingByDefault = true
if util.isArray(options.headers)
self._storeHeader self.method + " " + self.path + " HTTP/1.1\r\n", options.headers
else self._storeHeader self.method + " " + self.path + " HTTP/1.1\r\n", self._renderHeaders() if self.getHeader("expect")
if self.socketPath
self._last = true
self.shouldKeepAlive = false
conn = self.agent.createConnection(path: self.socketPath)
self.onSocket conn
else if self.agent
# If there is an agent we should default to Connection:keep-alive,
# but only if the Agent will actually reuse the connection!
# If it's not a keepAlive agent, and the maxSockets==Infinity, then
# there's never a case where this socket will actually be reused
if not self.agent.keepAlive and not Number.isFinite(self.agent.maxSockets)
self._last = true
self.shouldKeepAlive = false
else
self._last = false
self.shouldKeepAlive = true
self.agent.addRequest self, options
else
# No agent, default to Connection:close.
self._last = true
self.shouldKeepAlive = false
if options.createConnection
conn = options.createConnection(options)
else
debug "CLIENT use net.createConnection", options
conn = net.createConnection(options)
self.onSocket conn
self._deferToConnect null, null, ->
self._flush()
self = null
return
return
# Mark as aborting so we can avoid sending queued request data
# This is used as a truthy flag elsewhere. The use of Date.now is for
# debugging purposes only.
# If we're aborting, we don't care about any more response data.
# In the event that we don't have a socket, we will pop out of
# the request queue through handling in onSocket.
# in-progress
createHangUpError = ->
error = new Error("socket hang up")
error.code = "ECONNRESET"
error
socketCloseListener = ->
socket = this
req = socket._httpMessage
debug "HTTP socket close"
# Pull through final chunk, if anything is buffered.
# the ondata function will handle it properly, and this
# is a no-op if no final chunk remains.
socket.read()
# NOTE: Its important to get parser here, because it could be freed by
# the `socketOnData`.
parser = socket.parser
req.emit "close"
if req.res and req.res.readable
# Socket closed before we emitted 'end' below.
req.res.emit "aborted"
res = req.res
res.on "end", ->
res.emit "close"
return
res.push null
else if not req.res and not req.socket._hadError
# This socket error fired before we started to
# receive a response. The error needs to
# fire on the request.
req.emit "error", createHangUpError()
req.socket._hadError = true
# Too bad. That output wasn't getting written.
# This is pretty terrible that it doesn't raise an error.
# Fixed better in v0.10
req.output.length = 0 if req.output
req.outputEncodings.length = 0 if req.outputEncodings
if parser
parser.finish()
freeParser parser, req, socket
return
socketErrorListener = (err) ->
socket = this
parser = socket.parser
req = socket._httpMessage
debug "SOCKET ERROR:", err.message, err.stack
if req
req.emit "error", err
# For Safety. Some additional errors might fire later on
# and we need to make sure we don't double-fire the error event.
req.socket._hadError = true
if parser
parser.finish()
freeParser parser, req, socket
socket.destroy()
return
socketOnEnd = ->
socket = this
req = @_httpMessage
parser = @parser
if not req.res and not req.socket._hadError
# If we don't have a response then we know that the socket
# ended prematurely and we need to emit an error on the request.
req.emit "error", createHangUpError()
req.socket._hadError = true
if parser
parser.finish()
freeParser parser, req, socket
socket.destroy()
return
socketOnData = (d) ->
socket = this
req = @_httpMessage
parser = @parser
assert parser and parser.socket is socket
ret = parser.execute(d)
if ret instanceof Error
debug "parse error"
freeParser parser, req, socket
socket.destroy()
req.emit "error", ret
req.socket._hadError = true
else if parser.incoming and parser.incoming.upgrade
# Upgrade or CONNECT
bytesParsed = ret
res = parser.incoming
req.res = res
socket.removeListener "data", socketOnData
socket.removeListener "end", socketOnEnd
parser.finish()
bodyHead = d.slice(bytesParsed, d.length)
eventName = (if req.method is "CONNECT" then "connect" else "upgrade")
if EventEmitter.listenerCount(req, eventName) > 0
req.upgradeOrConnect = true
# detach the socket
socket.emit "agentRemove"
socket.removeListener "close", socketCloseListener
socket.removeListener "error", socketErrorListener
# TODO(isaacs): Need a way to reset a stream to fresh state
# IE, not flowing, and not explicitly paused.
socket._readableState.flowing = null
req.emit eventName, res, socket, bodyHead
req.emit "close"
else
# Got Upgrade header or CONNECT method, but have no handler.
socket.destroy()
freeParser parser, req, socket
# When the status code is 100 (Continue), the server will
# send a final response after this client sends a request
# body. So, we must not free the parser.
else if parser.incoming and parser.incoming.complete and parser.incoming.statusCode isnt 100
socket.removeListener "data", socketOnData
socket.removeListener "end", socketOnEnd
freeParser parser, req, socket
return
# client
parserOnIncomingClient = (res, shouldKeepAlive) ->
socket = @socket
req = socket._httpMessage
# propogate "domain" setting...
if req.domain and not res.domain
debug "setting \"res.domain\""
res.domain = req.domain
debug "AGENT incoming response!"
if req.res
# We already have a response object, this means the server
# sent a double response.
socket.destroy()
return
req.res = res
# Responses to CONNECT request is handled as Upgrade.
if req.method is "CONNECT"
res.upgrade = true
return true # skip body
# Responses to HEAD requests are crazy.
# HEAD responses aren't allowed to have an entity-body
# but *can* have a content-length which actually corresponds
# to the content-length of the entity-body had the request
# been a GET.
isHeadResponse = req.method is "HEAD"
debug "AGENT isHeadResponse", isHeadResponse
if res.statusCode is 100
# restart the parser, as this is a continue message.
delete req.res # Clear res so that we don't hit double-responses.
req.emit "continue"
return true
# Server MUST respond with Connection:keep-alive for us to enable it.
# If we've been upgraded (via WebSockets) we also shouldn't try to
# keep the connection open.
req.shouldKeepAlive = false if req.shouldKeepAlive and not shouldKeepAlive and not req.upgradeOrConnect
DTRACE_HTTP_CLIENT_RESPONSE socket, req
COUNTER_HTTP_CLIENT_RESPONSE()
req.res = res
res.req = req
# add our listener first, so that we guarantee socket cleanup
res.on "end", responseOnEnd
handled = req.emit("response", res)
# If the user did not listen for the 'response' event, then they
# can't possibly read the data, so we ._dump() it into the void
# so that the socket doesn't hang there in a paused state.
res._dump() unless handled
isHeadResponse
# client
responseOnEnd = ->
res = this
req = res.req
socket = req.socket
unless req.shouldKeepAlive
if socket.writable
debug "AGENT socket.destroySoon()"
socket.destroySoon()
assert not socket.writable
else
debug "AGENT socket keep-alive"
if req.timeoutCb
socket.setTimeout 0, req.timeoutCb
req.timeoutCb = null
socket.removeListener "close", socketCloseListener
socket.removeListener "error", socketErrorListener
# Mark this socket as available, AFTER user-added end
# handlers have a chance to run.
process.nextTick ->
socket.emit "free"
return
return
tickOnSocket = (req, socket) ->
parser = parsers.alloc()
req.socket = socket
req.connection = socket
parser.reinitialize HTTPParser.RESPONSE
parser.socket = socket
parser.incoming = null
req.parser = parser
socket.parser = parser
socket._httpMessage = req
# Setup "drain" propogation.
httpSocketSetup socket
# Propagate headers limit from request object to parser
if util.isNumber(req.maxHeadersCount)
parser.maxHeaderPairs = req.maxHeadersCount << 1
else
# Set default value because parser may be reused from FreeList
parser.maxHeaderPairs = 2000
parser.onIncoming = parserOnIncomingClient
socket.on "error", socketErrorListener
socket.on "data", socketOnData
socket.on "end", socketOnEnd
socket.on "close", socketCloseListener
req.emit "socket", socket
return
"use strict"
util = require("util")
net = require("net")
url = require("url")
EventEmitter = require("events").EventEmitter
HTTPParser = process.binding("http_parser").HTTPParser
assert = require("assert").ok
common = require("_http_common")
httpSocketSetup = common.httpSocketSetup
parsers = common.parsers
freeParser = common.freeParser
debug = common.debug
OutgoingMessage = require("_http_outgoing").OutgoingMessage
Agent = require("_http_agent")
util.inherits ClientRequest, OutgoingMessage
exports.ClientRequest = ClientRequest
ClientRequest::aborted = `undefined`
ClientRequest::_finish = ->
DTRACE_HTTP_CLIENT_REQUEST this, @connection
COUNTER_HTTP_CLIENT_REQUEST()
OutgoingMessage::_finish.call this
return
ClientRequest::_implicitHeader = ->
@_storeHeader @method + " " + @path + " HTTP/1.1\r\n", @_renderHeaders()
return
ClientRequest::abort = ->
@aborted = Date.now()
if @res
@res._dump()
else
@once "response", (res) ->
res._dump()
return
@socket.destroy() if @socket
return
ClientRequest::onSocket = (socket) ->
req = this
process.nextTick ->
if req.aborted
# If we were aborted while waiting for a socket, skip the whole thing.
socket.emit "free"
else
tickOnSocket req, socket
return
return
ClientRequest::_deferToConnect = (method, arguments_, cb) ->
# This function is for calls that need to happen once the socket is
# connected and writable. It's an important promisy thing for all the socket
# calls that happen either now (when a socket is assigned) or
# in the future (when a socket gets assigned out of the pool and is
# eventually writable).
self = this
onSocket = ->
if self.socket.writable
self.socket[method].apply self.socket, arguments_ if method
cb() if cb
else
self.socket.once "connect", ->
self.socket[method].apply self.socket, arguments_ if method
cb() if cb
return
return
unless self.socket
self.once "socket", onSocket
else
onSocket()
return
ClientRequest::setTimeout = (msecs, callback) ->
emitTimeout = ->
self.emit "timeout"
return
@once "timeout", callback if callback
self = this
if @socket and @socket.writable
@socket.setTimeout 0, @timeoutCb if @timeoutCb
@timeoutCb = emitTimeout
@socket.setTimeout msecs, emitTimeout
return
# Set timeoutCb so that it'll get cleaned up on request end
@timeoutCb = emitTimeout
if @socket
sock = @socket
@socket.once "connect", ->
sock.setTimeout msecs, emitTimeout
return
return
@once "socket", (sock) ->
sock.setTimeout msecs, emitTimeout
return
return
ClientRequest::setNoDelay = ->
@_deferToConnect "setNoDelay", arguments
return
ClientRequest::setSocketKeepAlive = ->
@_deferToConnect "setKeepAlive", arguments
return
ClientRequest::clearTimeout = (cb) ->
@setTimeout 0, cb
return
| 50531 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
ClientRequest = (options, cb) ->
self = this
OutgoingMessage.call self
if util.isString(options)
options = url.parse(options)
else
options = util._extend({}, options)
agent = options.agent
defaultAgent = options._defaultAgent or Agent.globalAgent
if agent is false
agent = new defaultAgent.constructor()
else agent = defaultAgent if util.isNullOrUndefined(agent) and not options.createConnection
self.agent = agent
protocol = options.protocol or defaultAgent.protocol
expectedProtocol = defaultAgent.protocol
expectedProtocol = self.agent.protocol if self.agent and self.agent.protocol
if options.path and RegExp(" ").test(options.path)
# The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
# with an additional rule for ignoring percentage-escaped characters
# but that's a) hard to capture in a regular expression that performs
# well, and b) possibly too restrictive for real-world usage. That's
# why it only scans for spaces because those are guaranteed to create
# an invalid request.
throw new TypeError("Request path contains unescaped characters.")
else throw new Error("Protocol \"" + protocol + "\" not supported. " + "Expected \"" + expectedProtocol + "\".") if protocol isnt expectedProtocol
defaultPort = options.defaultPort or self.agent and self.agent.defaultPort
port = options.port = options.port or defaultPort or 80
host = options.host = options.hostname or options.host or "localhost"
setHost = true if util.isUndefined(options.setHost)
self.socketPath = options.socketPath
method = self.method = (options.method or "GET").toUpperCase()
self.path = options.path or "/"
self.once "response", cb if cb
unless util.isArray(options.headers)
if options.headers
keys = Object.keys(options.headers)
i = 0
l = keys.length
while i < l
key = keys[i]
self.setHeader key, options.headers[key]
i++
if host and not @getHeader("host") and setHost
hostHeader = host
hostHeader += ":" + port if port and +port isnt defaultPort
@setHeader "Host", hostHeader
#basic auth
@setHeader "Authorization", "Basic " + new Buffer(options.auth).toString("base64") if options.auth and not @getHeader("Authorization")
if method is "GET" or method is "HEAD" or method is "DELETE" or method is "OPTIONS" or method is "CONNECT"
self.useChunkedEncodingByDefault = false
else
self.useChunkedEncodingByDefault = true
if util.isArray(options.headers)
self._storeHeader self.method + " " + self.path + " HTTP/1.1\r\n", options.headers
else self._storeHeader self.method + " " + self.path + " HTTP/1.1\r\n", self._renderHeaders() if self.getHeader("expect")
if self.socketPath
self._last = true
self.shouldKeepAlive = false
conn = self.agent.createConnection(path: self.socketPath)
self.onSocket conn
else if self.agent
# If there is an agent we should default to Connection:keep-alive,
# but only if the Agent will actually reuse the connection!
# If it's not a keepAlive agent, and the maxSockets==Infinity, then
# there's never a case where this socket will actually be reused
if not self.agent.keepAlive and not Number.isFinite(self.agent.maxSockets)
self._last = true
self.shouldKeepAlive = false
else
self._last = false
self.shouldKeepAlive = true
self.agent.addRequest self, options
else
# No agent, default to Connection:close.
self._last = true
self.shouldKeepAlive = false
if options.createConnection
conn = options.createConnection(options)
else
debug "CLIENT use net.createConnection", options
conn = net.createConnection(options)
self.onSocket conn
self._deferToConnect null, null, ->
self._flush()
self = null
return
return
# Mark as aborting so we can avoid sending queued request data
# This is used as a truthy flag elsewhere. The use of Date.now is for
# debugging purposes only.
# If we're aborting, we don't care about any more response data.
# In the event that we don't have a socket, we will pop out of
# the request queue through handling in onSocket.
# in-progress
createHangUpError = ->
error = new Error("socket hang up")
error.code = "ECONNRESET"
error
socketCloseListener = ->
socket = this
req = socket._httpMessage
debug "HTTP socket close"
# Pull through final chunk, if anything is buffered.
# the ondata function will handle it properly, and this
# is a no-op if no final chunk remains.
socket.read()
# NOTE: Its important to get parser here, because it could be freed by
# the `socketOnData`.
parser = socket.parser
req.emit "close"
if req.res and req.res.readable
# Socket closed before we emitted 'end' below.
req.res.emit "aborted"
res = req.res
res.on "end", ->
res.emit "close"
return
res.push null
else if not req.res and not req.socket._hadError
# This socket error fired before we started to
# receive a response. The error needs to
# fire on the request.
req.emit "error", createHangUpError()
req.socket._hadError = true
# Too bad. That output wasn't getting written.
# This is pretty terrible that it doesn't raise an error.
# Fixed better in v0.10
req.output.length = 0 if req.output
req.outputEncodings.length = 0 if req.outputEncodings
if parser
parser.finish()
freeParser parser, req, socket
return
socketErrorListener = (err) ->
socket = this
parser = socket.parser
req = socket._httpMessage
debug "SOCKET ERROR:", err.message, err.stack
if req
req.emit "error", err
# For Safety. Some additional errors might fire later on
# and we need to make sure we don't double-fire the error event.
req.socket._hadError = true
if parser
parser.finish()
freeParser parser, req, socket
socket.destroy()
return
socketOnEnd = ->
socket = this
req = @_httpMessage
parser = @parser
if not req.res and not req.socket._hadError
# If we don't have a response then we know that the socket
# ended prematurely and we need to emit an error on the request.
req.emit "error", createHangUpError()
req.socket._hadError = true
if parser
parser.finish()
freeParser parser, req, socket
socket.destroy()
return
socketOnData = (d) ->
socket = this
req = @_httpMessage
parser = @parser
assert parser and parser.socket is socket
ret = parser.execute(d)
if ret instanceof Error
debug "parse error"
freeParser parser, req, socket
socket.destroy()
req.emit "error", ret
req.socket._hadError = true
else if parser.incoming and parser.incoming.upgrade
# Upgrade or CONNECT
bytesParsed = ret
res = parser.incoming
req.res = res
socket.removeListener "data", socketOnData
socket.removeListener "end", socketOnEnd
parser.finish()
bodyHead = d.slice(bytesParsed, d.length)
eventName = (if req.method is "CONNECT" then "connect" else "upgrade")
if EventEmitter.listenerCount(req, eventName) > 0
req.upgradeOrConnect = true
# detach the socket
socket.emit "agentRemove"
socket.removeListener "close", socketCloseListener
socket.removeListener "error", socketErrorListener
# TODO(isaacs): Need a way to reset a stream to fresh state
# IE, not flowing, and not explicitly paused.
socket._readableState.flowing = null
req.emit eventName, res, socket, bodyHead
req.emit "close"
else
# Got Upgrade header or CONNECT method, but have no handler.
socket.destroy()
freeParser parser, req, socket
# When the status code is 100 (Continue), the server will
# send a final response after this client sends a request
# body. So, we must not free the parser.
else if parser.incoming and parser.incoming.complete and parser.incoming.statusCode isnt 100
socket.removeListener "data", socketOnData
socket.removeListener "end", socketOnEnd
freeParser parser, req, socket
return
# client
parserOnIncomingClient = (res, shouldKeepAlive) ->
socket = @socket
req = socket._httpMessage
# propogate "domain" setting...
if req.domain and not res.domain
debug "setting \"res.domain\""
res.domain = req.domain
debug "AGENT incoming response!"
if req.res
# We already have a response object, this means the server
# sent a double response.
socket.destroy()
return
req.res = res
# Responses to CONNECT request is handled as Upgrade.
if req.method is "CONNECT"
res.upgrade = true
return true # skip body
# Responses to HEAD requests are crazy.
# HEAD responses aren't allowed to have an entity-body
# but *can* have a content-length which actually corresponds
# to the content-length of the entity-body had the request
# been a GET.
isHeadResponse = req.method is "HEAD"
debug "AGENT isHeadResponse", isHeadResponse
if res.statusCode is 100
# restart the parser, as this is a continue message.
delete req.res # Clear res so that we don't hit double-responses.
req.emit "continue"
return true
# Server MUST respond with Connection:keep-alive for us to enable it.
# If we've been upgraded (via WebSockets) we also shouldn't try to
# keep the connection open.
req.shouldKeepAlive = false if req.shouldKeepAlive and not shouldKeepAlive and not req.upgradeOrConnect
DTRACE_HTTP_CLIENT_RESPONSE socket, req
COUNTER_HTTP_CLIENT_RESPONSE()
req.res = res
res.req = req
# add our listener first, so that we guarantee socket cleanup
res.on "end", responseOnEnd
handled = req.emit("response", res)
# If the user did not listen for the 'response' event, then they
# can't possibly read the data, so we ._dump() it into the void
# so that the socket doesn't hang there in a paused state.
res._dump() unless handled
isHeadResponse
# client
responseOnEnd = ->
res = this
req = res.req
socket = req.socket
unless req.shouldKeepAlive
if socket.writable
debug "AGENT socket.destroySoon()"
socket.destroySoon()
assert not socket.writable
else
debug "AGENT socket keep-alive"
if req.timeoutCb
socket.setTimeout 0, req.timeoutCb
req.timeoutCb = null
socket.removeListener "close", socketCloseListener
socket.removeListener "error", socketErrorListener
# Mark this socket as available, AFTER user-added end
# handlers have a chance to run.
process.nextTick ->
socket.emit "free"
return
return
tickOnSocket = (req, socket) ->
parser = parsers.alloc()
req.socket = socket
req.connection = socket
parser.reinitialize HTTPParser.RESPONSE
parser.socket = socket
parser.incoming = null
req.parser = parser
socket.parser = parser
socket._httpMessage = req
# Setup "drain" propogation.
httpSocketSetup socket
# Propagate headers limit from request object to parser
if util.isNumber(req.maxHeadersCount)
parser.maxHeaderPairs = req.maxHeadersCount << 1
else
# Set default value because parser may be reused from FreeList
parser.maxHeaderPairs = 2000
parser.onIncoming = parserOnIncomingClient
socket.on "error", socketErrorListener
socket.on "data", socketOnData
socket.on "end", socketOnEnd
socket.on "close", socketCloseListener
req.emit "socket", socket
return
"use strict"
util = require("util")
net = require("net")
url = require("url")
EventEmitter = require("events").EventEmitter
HTTPParser = process.binding("http_parser").HTTPParser
assert = require("assert").ok
common = require("_http_common")
httpSocketSetup = common.httpSocketSetup
parsers = common.parsers
freeParser = common.freeParser
debug = common.debug
OutgoingMessage = require("_http_outgoing").OutgoingMessage
Agent = require("_http_agent")
util.inherits ClientRequest, OutgoingMessage
exports.ClientRequest = ClientRequest
ClientRequest::aborted = `undefined`
ClientRequest::_finish = ->
DTRACE_HTTP_CLIENT_REQUEST this, @connection
COUNTER_HTTP_CLIENT_REQUEST()
OutgoingMessage::_finish.call this
return
ClientRequest::_implicitHeader = ->
@_storeHeader @method + " " + @path + " HTTP/1.1\r\n", @_renderHeaders()
return
ClientRequest::abort = ->
@aborted = Date.now()
if @res
@res._dump()
else
@once "response", (res) ->
res._dump()
return
@socket.destroy() if @socket
return
ClientRequest::onSocket = (socket) ->
req = this
process.nextTick ->
if req.aborted
# If we were aborted while waiting for a socket, skip the whole thing.
socket.emit "free"
else
tickOnSocket req, socket
return
return
ClientRequest::_deferToConnect = (method, arguments_, cb) ->
# This function is for calls that need to happen once the socket is
# connected and writable. It's an important promisy thing for all the socket
# calls that happen either now (when a socket is assigned) or
# in the future (when a socket gets assigned out of the pool and is
# eventually writable).
self = this
onSocket = ->
if self.socket.writable
self.socket[method].apply self.socket, arguments_ if method
cb() if cb
else
self.socket.once "connect", ->
self.socket[method].apply self.socket, arguments_ if method
cb() if cb
return
return
unless self.socket
self.once "socket", onSocket
else
onSocket()
return
ClientRequest::setTimeout = (msecs, callback) ->
emitTimeout = ->
self.emit "timeout"
return
@once "timeout", callback if callback
self = this
if @socket and @socket.writable
@socket.setTimeout 0, @timeoutCb if @timeoutCb
@timeoutCb = emitTimeout
@socket.setTimeout msecs, emitTimeout
return
# Set timeoutCb so that it'll get cleaned up on request end
@timeoutCb = emitTimeout
if @socket
sock = @socket
@socket.once "connect", ->
sock.setTimeout msecs, emitTimeout
return
return
@once "socket", (sock) ->
sock.setTimeout msecs, emitTimeout
return
return
ClientRequest::setNoDelay = ->
@_deferToConnect "setNoDelay", arguments
return
ClientRequest::setSocketKeepAlive = ->
@_deferToConnect "setKeepAlive", arguments
return
ClientRequest::clearTimeout = (cb) ->
@setTimeout 0, cb
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
ClientRequest = (options, cb) ->
self = this
OutgoingMessage.call self
if util.isString(options)
options = url.parse(options)
else
options = util._extend({}, options)
agent = options.agent
defaultAgent = options._defaultAgent or Agent.globalAgent
if agent is false
agent = new defaultAgent.constructor()
else agent = defaultAgent if util.isNullOrUndefined(agent) and not options.createConnection
self.agent = agent
protocol = options.protocol or defaultAgent.protocol
expectedProtocol = defaultAgent.protocol
expectedProtocol = self.agent.protocol if self.agent and self.agent.protocol
if options.path and RegExp(" ").test(options.path)
# The actual regex is more like /[^A-Za-z0-9\-._~!$&'()*+,;=/:@]/
# with an additional rule for ignoring percentage-escaped characters
# but that's a) hard to capture in a regular expression that performs
# well, and b) possibly too restrictive for real-world usage. That's
# why it only scans for spaces because those are guaranteed to create
# an invalid request.
throw new TypeError("Request path contains unescaped characters.")
else throw new Error("Protocol \"" + protocol + "\" not supported. " + "Expected \"" + expectedProtocol + "\".") if protocol isnt expectedProtocol
defaultPort = options.defaultPort or self.agent and self.agent.defaultPort
port = options.port = options.port or defaultPort or 80
host = options.host = options.hostname or options.host or "localhost"
setHost = true if util.isUndefined(options.setHost)
self.socketPath = options.socketPath
method = self.method = (options.method or "GET").toUpperCase()
self.path = options.path or "/"
self.once "response", cb if cb
unless util.isArray(options.headers)
if options.headers
keys = Object.keys(options.headers)
i = 0
l = keys.length
while i < l
key = keys[i]
self.setHeader key, options.headers[key]
i++
if host and not @getHeader("host") and setHost
hostHeader = host
hostHeader += ":" + port if port and +port isnt defaultPort
@setHeader "Host", hostHeader
#basic auth
@setHeader "Authorization", "Basic " + new Buffer(options.auth).toString("base64") if options.auth and not @getHeader("Authorization")
if method is "GET" or method is "HEAD" or method is "DELETE" or method is "OPTIONS" or method is "CONNECT"
self.useChunkedEncodingByDefault = false
else
self.useChunkedEncodingByDefault = true
if util.isArray(options.headers)
self._storeHeader self.method + " " + self.path + " HTTP/1.1\r\n", options.headers
else self._storeHeader self.method + " " + self.path + " HTTP/1.1\r\n", self._renderHeaders() if self.getHeader("expect")
if self.socketPath
self._last = true
self.shouldKeepAlive = false
conn = self.agent.createConnection(path: self.socketPath)
self.onSocket conn
else if self.agent
# If there is an agent we should default to Connection:keep-alive,
# but only if the Agent will actually reuse the connection!
# If it's not a keepAlive agent, and the maxSockets==Infinity, then
# there's never a case where this socket will actually be reused
if not self.agent.keepAlive and not Number.isFinite(self.agent.maxSockets)
self._last = true
self.shouldKeepAlive = false
else
self._last = false
self.shouldKeepAlive = true
self.agent.addRequest self, options
else
# No agent, default to Connection:close.
self._last = true
self.shouldKeepAlive = false
if options.createConnection
conn = options.createConnection(options)
else
debug "CLIENT use net.createConnection", options
conn = net.createConnection(options)
self.onSocket conn
self._deferToConnect null, null, ->
self._flush()
self = null
return
return
# Mark as aborting so we can avoid sending queued request data
# This is used as a truthy flag elsewhere. The use of Date.now is for
# debugging purposes only.
# If we're aborting, we don't care about any more response data.
# In the event that we don't have a socket, we will pop out of
# the request queue through handling in onSocket.
# in-progress
createHangUpError = ->
error = new Error("socket hang up")
error.code = "ECONNRESET"
error
socketCloseListener = ->
socket = this
req = socket._httpMessage
debug "HTTP socket close"
# Pull through final chunk, if anything is buffered.
# the ondata function will handle it properly, and this
# is a no-op if no final chunk remains.
socket.read()
# NOTE: Its important to get parser here, because it could be freed by
# the `socketOnData`.
parser = socket.parser
req.emit "close"
if req.res and req.res.readable
# Socket closed before we emitted 'end' below.
req.res.emit "aborted"
res = req.res
res.on "end", ->
res.emit "close"
return
res.push null
else if not req.res and not req.socket._hadError
# This socket error fired before we started to
# receive a response. The error needs to
# fire on the request.
req.emit "error", createHangUpError()
req.socket._hadError = true
# Too bad. That output wasn't getting written.
# This is pretty terrible that it doesn't raise an error.
# Fixed better in v0.10
req.output.length = 0 if req.output
req.outputEncodings.length = 0 if req.outputEncodings
if parser
parser.finish()
freeParser parser, req, socket
return
socketErrorListener = (err) ->
socket = this
parser = socket.parser
req = socket._httpMessage
debug "SOCKET ERROR:", err.message, err.stack
if req
req.emit "error", err
# For Safety. Some additional errors might fire later on
# and we need to make sure we don't double-fire the error event.
req.socket._hadError = true
if parser
parser.finish()
freeParser parser, req, socket
socket.destroy()
return
socketOnEnd = ->
socket = this
req = @_httpMessage
parser = @parser
if not req.res and not req.socket._hadError
# If we don't have a response then we know that the socket
# ended prematurely and we need to emit an error on the request.
req.emit "error", createHangUpError()
req.socket._hadError = true
if parser
parser.finish()
freeParser parser, req, socket
socket.destroy()
return
socketOnData = (d) ->
socket = this
req = @_httpMessage
parser = @parser
assert parser and parser.socket is socket
ret = parser.execute(d)
if ret instanceof Error
debug "parse error"
freeParser parser, req, socket
socket.destroy()
req.emit "error", ret
req.socket._hadError = true
else if parser.incoming and parser.incoming.upgrade
# Upgrade or CONNECT
bytesParsed = ret
res = parser.incoming
req.res = res
socket.removeListener "data", socketOnData
socket.removeListener "end", socketOnEnd
parser.finish()
bodyHead = d.slice(bytesParsed, d.length)
eventName = (if req.method is "CONNECT" then "connect" else "upgrade")
if EventEmitter.listenerCount(req, eventName) > 0
req.upgradeOrConnect = true
# detach the socket
socket.emit "agentRemove"
socket.removeListener "close", socketCloseListener
socket.removeListener "error", socketErrorListener
# TODO(isaacs): Need a way to reset a stream to fresh state
# IE, not flowing, and not explicitly paused.
socket._readableState.flowing = null
req.emit eventName, res, socket, bodyHead
req.emit "close"
else
# Got Upgrade header or CONNECT method, but have no handler.
socket.destroy()
freeParser parser, req, socket
# When the status code is 100 (Continue), the server will
# send a final response after this client sends a request
# body. So, we must not free the parser.
else if parser.incoming and parser.incoming.complete and parser.incoming.statusCode isnt 100
socket.removeListener "data", socketOnData
socket.removeListener "end", socketOnEnd
freeParser parser, req, socket
return
# client
parserOnIncomingClient = (res, shouldKeepAlive) ->
socket = @socket
req = socket._httpMessage
# propogate "domain" setting...
if req.domain and not res.domain
debug "setting \"res.domain\""
res.domain = req.domain
debug "AGENT incoming response!"
if req.res
# We already have a response object, this means the server
# sent a double response.
socket.destroy()
return
req.res = res
# Responses to CONNECT request is handled as Upgrade.
if req.method is "CONNECT"
res.upgrade = true
return true # skip body
# Responses to HEAD requests are crazy.
# HEAD responses aren't allowed to have an entity-body
# but *can* have a content-length which actually corresponds
# to the content-length of the entity-body had the request
# been a GET.
isHeadResponse = req.method is "HEAD"
debug "AGENT isHeadResponse", isHeadResponse
if res.statusCode is 100
# restart the parser, as this is a continue message.
delete req.res # Clear res so that we don't hit double-responses.
req.emit "continue"
return true
# Server MUST respond with Connection:keep-alive for us to enable it.
# If we've been upgraded (via WebSockets) we also shouldn't try to
# keep the connection open.
req.shouldKeepAlive = false if req.shouldKeepAlive and not shouldKeepAlive and not req.upgradeOrConnect
DTRACE_HTTP_CLIENT_RESPONSE socket, req
COUNTER_HTTP_CLIENT_RESPONSE()
req.res = res
res.req = req
# add our listener first, so that we guarantee socket cleanup
res.on "end", responseOnEnd
handled = req.emit("response", res)
# If the user did not listen for the 'response' event, then they
# can't possibly read the data, so we ._dump() it into the void
# so that the socket doesn't hang there in a paused state.
res._dump() unless handled
isHeadResponse
# client
responseOnEnd = ->
res = this
req = res.req
socket = req.socket
unless req.shouldKeepAlive
if socket.writable
debug "AGENT socket.destroySoon()"
socket.destroySoon()
assert not socket.writable
else
debug "AGENT socket keep-alive"
if req.timeoutCb
socket.setTimeout 0, req.timeoutCb
req.timeoutCb = null
socket.removeListener "close", socketCloseListener
socket.removeListener "error", socketErrorListener
# Mark this socket as available, AFTER user-added end
# handlers have a chance to run.
process.nextTick ->
socket.emit "free"
return
return
tickOnSocket = (req, socket) ->
parser = parsers.alloc()
req.socket = socket
req.connection = socket
parser.reinitialize HTTPParser.RESPONSE
parser.socket = socket
parser.incoming = null
req.parser = parser
socket.parser = parser
socket._httpMessage = req
# Setup "drain" propogation.
httpSocketSetup socket
# Propagate headers limit from request object to parser
if util.isNumber(req.maxHeadersCount)
parser.maxHeaderPairs = req.maxHeadersCount << 1
else
# Set default value because parser may be reused from FreeList
parser.maxHeaderPairs = 2000
parser.onIncoming = parserOnIncomingClient
socket.on "error", socketErrorListener
socket.on "data", socketOnData
socket.on "end", socketOnEnd
socket.on "close", socketCloseListener
req.emit "socket", socket
return
"use strict"
util = require("util")
net = require("net")
url = require("url")
EventEmitter = require("events").EventEmitter
HTTPParser = process.binding("http_parser").HTTPParser
assert = require("assert").ok
common = require("_http_common")
httpSocketSetup = common.httpSocketSetup
parsers = common.parsers
freeParser = common.freeParser
debug = common.debug
OutgoingMessage = require("_http_outgoing").OutgoingMessage
Agent = require("_http_agent")
util.inherits ClientRequest, OutgoingMessage
exports.ClientRequest = ClientRequest
ClientRequest::aborted = `undefined`
ClientRequest::_finish = ->
DTRACE_HTTP_CLIENT_REQUEST this, @connection
COUNTER_HTTP_CLIENT_REQUEST()
OutgoingMessage::_finish.call this
return
ClientRequest::_implicitHeader = ->
@_storeHeader @method + " " + @path + " HTTP/1.1\r\n", @_renderHeaders()
return
ClientRequest::abort = ->
@aborted = Date.now()
if @res
@res._dump()
else
@once "response", (res) ->
res._dump()
return
@socket.destroy() if @socket
return
ClientRequest::onSocket = (socket) ->
req = this
process.nextTick ->
if req.aborted
# If we were aborted while waiting for a socket, skip the whole thing.
socket.emit "free"
else
tickOnSocket req, socket
return
return
ClientRequest::_deferToConnect = (method, arguments_, cb) ->
# This function is for calls that need to happen once the socket is
# connected and writable. It's an important promisy thing for all the socket
# calls that happen either now (when a socket is assigned) or
# in the future (when a socket gets assigned out of the pool and is
# eventually writable).
self = this
onSocket = ->
if self.socket.writable
self.socket[method].apply self.socket, arguments_ if method
cb() if cb
else
self.socket.once "connect", ->
self.socket[method].apply self.socket, arguments_ if method
cb() if cb
return
return
unless self.socket
self.once "socket", onSocket
else
onSocket()
return
ClientRequest::setTimeout = (msecs, callback) ->
emitTimeout = ->
self.emit "timeout"
return
@once "timeout", callback if callback
self = this
if @socket and @socket.writable
@socket.setTimeout 0, @timeoutCb if @timeoutCb
@timeoutCb = emitTimeout
@socket.setTimeout msecs, emitTimeout
return
# Set timeoutCb so that it'll get cleaned up on request end
@timeoutCb = emitTimeout
if @socket
sock = @socket
@socket.once "connect", ->
sock.setTimeout msecs, emitTimeout
return
return
@once "socket", (sock) ->
sock.setTimeout msecs, emitTimeout
return
return
ClientRequest::setNoDelay = ->
@_deferToConnect "setNoDelay", arguments
return
ClientRequest::setSocketKeepAlive = ->
@_deferToConnect "setKeepAlive", arguments
return
ClientRequest::clearTimeout = (cb) ->
@setTimeout 0, cb
return
|
[
{
"context": " inviting me!\"\n .setDescription \"\"\"\n Hi! I'm Kko-hi, a Discord bot coded purely on CoffeeScript!",
"end": 463,
"score": 0.6821931004524231,
"start": 462,
"tag": "NAME",
"value": "K"
},
{
"context": "nviting me!\"\n .setDescription \"\"\"\n Hi! I'm Kko-hi, a Discord bot coded purely on CoffeeScript!\n ",
"end": 468,
"score": 0.5624669194221497,
"start": 463,
"tag": "USERNAME",
"value": "ko-hi"
}
] | events/guildCreate.coffee | Fizuku/Kko-hi-Public | 4 | Discord = require 'discord.js'
module.exports =
event: "guildCreate"
emitter: "on"
run: (guild, bot) ->
channelID;
channels = guild.channels;
for c in channels
channelType = c[1].type;
if channelType is "text" then channelID = c[0];
channel = bot.channels.cache.get guild.systemChannelID or channelID
welcome = new Discord.MessageEmbed()
.setTitle "Thanks for inviting me!"
.setDescription """
Hi! I'm Kko-hi, a Discord bot coded purely on CoffeeScript!
See my commands list using the `help` command.
Mention me to discover my prefix! Default is `kko-`
You may find the starter source code by the link below.
Thanks! ♥ - Fizx
"""
.setColor "#db9a7b"
channel.send welcome | 82707 | Discord = require 'discord.js'
module.exports =
event: "guildCreate"
emitter: "on"
run: (guild, bot) ->
channelID;
channels = guild.channels;
for c in channels
channelType = c[1].type;
if channelType is "text" then channelID = c[0];
channel = bot.channels.cache.get guild.systemChannelID or channelID
welcome = new Discord.MessageEmbed()
.setTitle "Thanks for inviting me!"
.setDescription """
Hi! I'm <NAME>ko-hi, a Discord bot coded purely on CoffeeScript!
See my commands list using the `help` command.
Mention me to discover my prefix! Default is `kko-`
You may find the starter source code by the link below.
Thanks! ♥ - Fizx
"""
.setColor "#db9a7b"
channel.send welcome | true | Discord = require 'discord.js'
module.exports =
event: "guildCreate"
emitter: "on"
run: (guild, bot) ->
channelID;
channels = guild.channels;
for c in channels
channelType = c[1].type;
if channelType is "text" then channelID = c[0];
channel = bot.channels.cache.get guild.systemChannelID or channelID
welcome = new Discord.MessageEmbed()
.setTitle "Thanks for inviting me!"
.setDescription """
Hi! I'm PI:NAME:<NAME>END_PIko-hi, a Discord bot coded purely on CoffeeScript!
See my commands list using the `help` command.
Mention me to discover my prefix! Default is `kko-`
You may find the starter source code by the link below.
Thanks! ♥ - Fizx
"""
.setColor "#db9a7b"
channel.send welcome |
[
{
"context": " illustrate how easy it is to write one.\n Author: Mikolaj Pawlikowski (mikolaj@pawlikowski.pl)\n\n###\n\nstate = JSON.parse",
"end": 106,
"score": 0.9998726844787598,
"start": 87,
"tag": "NAME",
"value": "Mikolaj Pawlikowski"
},
{
"context": "t is to write one.\n Author: Mikolaj Pawlikowski (mikolaj@pawlikowski.pl)\n\n###\n\nstate = JSON.parse process.argv.slice(2)\n\n",
"end": 130,
"score": 0.9999319911003113,
"start": 108,
"tag": "EMAIL",
"value": "mikolaj@pawlikowski.pl"
}
] | bot.coffee | wioota/battleships-bot | 1 | ###
Random bot: an example bot to illustrate how easy it is to write one.
Author: Mikolaj Pawlikowski (mikolaj@pawlikowski.pl)
###
state = JSON.parse process.argv.slice(2)
rand = (n) ->
Math.floor(Math.random()*100000 + new Date().getTime()) % (n+1)
randomMove = ->
"#{rand(7)}#{rand(7)}"
if state.cmd is 'init'
diff = 0
config = {}
for i in [2..5]
config[i] =
point: "#{rand(7-i)}#{diff}"
orientation: "horizontal"
diff = diff + 1 + rand(1)
console.log JSON.stringify config
else
move = randomMove()
while (move in state.hit) or (move in state.missed)
move = randomMove()
console.log JSON.stringify
move: move
| 7624 | ###
Random bot: an example bot to illustrate how easy it is to write one.
Author: <NAME> (<EMAIL>)
###
state = JSON.parse process.argv.slice(2)
rand = (n) ->
Math.floor(Math.random()*100000 + new Date().getTime()) % (n+1)
randomMove = ->
"#{rand(7)}#{rand(7)}"
if state.cmd is 'init'
diff = 0
config = {}
for i in [2..5]
config[i] =
point: "#{rand(7-i)}#{diff}"
orientation: "horizontal"
diff = diff + 1 + rand(1)
console.log JSON.stringify config
else
move = randomMove()
while (move in state.hit) or (move in state.missed)
move = randomMove()
console.log JSON.stringify
move: move
| true | ###
Random bot: an example bot to illustrate how easy it is to write one.
Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
###
state = JSON.parse process.argv.slice(2)
rand = (n) ->
Math.floor(Math.random()*100000 + new Date().getTime()) % (n+1)
randomMove = ->
"#{rand(7)}#{rand(7)}"
if state.cmd is 'init'
diff = 0
config = {}
for i in [2..5]
config[i] =
point: "#{rand(7-i)}#{diff}"
orientation: "horizontal"
diff = diff + 1 + rand(1)
console.log JSON.stringify config
else
move = randomMove()
while (move in state.hit) or (move in state.missed)
move = randomMove()
console.log JSON.stringify
move: move
|
[
{
"context": ", ->\n dd ->\n span \"姓名:\"\n span \"黄鑫\"\n dd ->\n span \"性别:\"\n span \"男\"\n",
"end": 2536,
"score": 0.9996986985206604,
"start": 2534,
"tag": "NAME",
"value": "黄鑫"
},
{
"context": "\nPersonal Repository: <a href=\"https://github.com/dreampuf/\">https://github.com/dreampuf/</a>\n\nPersonal Slid",
"end": 2864,
"score": 0.999679684638977,
"start": 2856,
"tag": "USERNAME",
"value": "dreampuf"
},
{
"context": "\"https://github.com/dreampuf/\">https://github.com/dreampuf/</a>\n\nPersonal Slides: <a href=\"http://www.slide",
"end": 2894,
"score": 0.9996849298477173,
"start": 2886,
"tag": "USERNAME",
"value": "dreampuf"
},
{
"context": "sonal Slides: <a href=\"http://www.slideshare.net/dreampuf/\">http://www.slideshare.net/dreampuf/</a>\n\n研究方向: ",
"end": 2962,
"score": 0.943837583065033,
"start": 2954,
"tag": "USERNAME",
"value": "dreampuf"
},
{
"context": "ideshare.net/dreampuf/\">http://www.slideshare.net/dreampuf/</a>\n\n研究方向: <br />并行处理,喜欢使用(但不仅有)multiprocess进行多进",
"end": 2999,
"score": 0.9419981241226196,
"start": 2991,
"tag": "USERNAME",
"value": "dreampuf"
},
{
"context": "document.getElementById \"mailme\"\n my_mail = \"soddyque\" + \"@\" + \"gmail.com\"\n mailme.innerText = my_",
"end": 6299,
"score": 0.9994699954986572,
"start": 6291,
"tag": "USERNAME",
"value": "soddyque"
}
] | views/about.coffee | dreampuf/banajs | 3 | doctype 5
html ->
head ->
meta charset:"utf-8"
title "About Huangxin"
script src:"/js/raphael.js"
style -> """
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
body {
font-family: 'PT Sans', sans-serif;
min-height: 600px;
background: rgb(215, 215, 215);
background: -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 500, from(rgb(240, 240, 240)), to(rgb(190, 190, 190)));
background: -webkit-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: -moz-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: -o-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
-webkit-font-smoothing: antialiased;
}
b, strong { font-weight: bold }
i, em { font-style: italic}
a {
color: inherit;
text-decoration: none;
padding: 0 0.1em;
background: rgba(255,255,255,0.5);
text-shadow: -1px -1px 2px rgba(100,100,100,0.9);
border-radius: 0.2em;
-webkit-transition: 0.5s;
-moz-transition: 0.5s;
-ms-transition: 0.5s;
-o-transition: 0.5s;
transition: 0.5s;
}
a:hover {
background: rgba(255,255,255,1);
text-shadow: -1px -1px 2px rgba(100,100,100,0.5);
}
body { padding: 15px; }
#skillradar { float:right; }
#baseinfo { width: 200px; padding-top: 50px; padding-left: 10px;}
#baseinfo dd { padding-top: 3px;}
.personal_experience { margin-top: 10px; }
"""
body ->
div id:"skillradar"
div id:"baseinfo", ->
dd ->
span "姓名:"
span "黄鑫"
dd ->
span "性别:"
span "男"
dd ->
span "年龄:"
span "24"
dd ->
span "专业:"
span "软件工程"
dd ->
span "Email:"
a id:"mailme", "Are you spam?"
pre class: "personal_experience", """
Personal Repository: <a href="https://github.com/dreampuf/">https://github.com/dreampuf/</a>
Personal Slides: <a href="http://www.slideshare.net/dreampuf/">http://www.slideshare.net/dreampuf/</a>
研究方向: <br />并行处理,喜欢使用(但不仅有)multiprocess进行多进程并行开发,知道锁的好处与麻烦点,不能抑制对加速比的追求。<br />数据挖掘,对于数据充满饥渴,爬虫,格式化,存储,检索,挖掘,应用。
2012.05~2012.09: 作为Scrum Master在团队中解决各项问题,已经进行了8个Sprint。
2012.08: 参加北大可视化学习班,进行为期一周的数据可视化学习。
2012.05: 负责果壳长微博生成优化。
2012.03~2012.04: UBB格式内容渲染为适合微博转发的组件。
2012.01~2012.02: 负责果壳网问答相关优化,@功能数据端开发。问答提问相似检索实现randing部分。
2011.11~2011.12: 负责果壳网问答开发项目.
2011.3~2011.10: 负责果壳网Python中间层实现.主要负责缓存系统维护.
2011.1~2011.2 : 负责果壳网v2前台个人主页模块.架构同上.
2010.12 : 果壳网v2后台CMS. Python + Django + Twisted + Postgresql + Memcaache + Ngnix
2010.12 :果壳时间 青年谱系 测试系统(Python + Django +Postgresql + Memcache + Ngnix),随后的果壳网承接IBM宣传项目Watson机器人大赛答题测试,也是于此相同的架构.
2010.6~2010.7 微软之星大赛全国三等奖网站.(C# / Asp.net MVC 2 + Microsoft Unity 2 + EntityFrameWork) : 作为组长负责整体系统架构,以及代码编写。
2009.11~2010.4 eWindow网站制作(Java / Structs2 + Hibernate) : 实践Java开发环境,项目包括三个小组,我负责前台组的页面脚本(JavaScript / Ext )编写。
2009.11 参加湖南省冬季技能大赛,获得软件应用二等奖. 同时期参加ACM个人斩获2题,不敌题牛被淘汰.
"""
coffeescript ->
class Radar
constructor: (@el, ds)->
@dslen = 0
@ds = []
max = 0
for k, v of ds
@dslen++
@ds.push [k, v]
max = v if max < v
@dmax = max
draw:()->
@draw_bg()
draw_bg: ()->
el = @el
ds = @ds
dslen = @dslen
dmax = @dmax
width = height = 320
paper = Raphael el, width+80, height
cx = width/2 + 40
cy = height/2
r = width*0.45
times = 7 #if r > 200 then 10 else 6
for i in [1..times]
c = paper.circle cx, cy, r*i/times
c.attr stroke:"#EEE"
grah_path_end = undefined
grah_path = []
radian_rate = 2 * Math.PI / 360
for i in [0...dslen]
angle = (360*i/dslen - 90) % 360
rd = angle*radian_rate
ty = r * (Math.sin rd)
tx = r * (Math.cos rd)
l = paper.path "M#{cx},#{cy}l#{tx},#{ty}"
l.attr stroke: "#FEF"
[k, v] = ds[i]
ew = 14
dx = if tx>0 then 1 else -1
dy = if ty>0 then 1 else -1
dr = v/dmax
text = paper.text cx+tx, cy+ty, k
#dd = Math.sqrt(Math.pow(text.attr("width"), 2) + Math.pow(text.attr("height"), 2))
text.attr
"font-size": 14
"font-weight": 2
#"x": cx+tx+dd*dx
#"y": cy+ty+dd*dy
if i == 0
grah_path.push "M#{cx+tx*dr},#{cy+ty*dr}"
grah_path.push "L#{cx+tx*dr},#{cy+ty*dr}z"
else
grah_path.splice -1, 0, "L#{cx+tx*dr},#{cy+ty*dr}"
grah = paper.path grah_path.join ""
grah.attr
fill: "#F0F"
"fill-opacity": .5
stroke: "#F0F"
"stroke-width": 0
"stroke-opacity": .5
0
#
rg = new Radar document.getElementById("skillradar"),
"Csharp": 45
"JavaScript": 80
"Python": 99
"Algorithm": 50
"Concurrent": 50
"Mining": 20
"Visualization": 10
rg.draw()
mailme = document.getElementById "mailme"
my_mail = "soddyque" + "@" + "gmail.com"
mailme.innerText = my_mail
mailme.href = "mailto:" + my_mail
`var _gaq = _gaq || [];_gaq.push(['_setAccount', 'UA-5293693-3']);_gaq.push(['_setDomainName', 'huangx.in']);_gaq.push(['_trackPageview']);(function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();`
null
| 142955 | doctype 5
html ->
head ->
meta charset:"utf-8"
title "About Huangxin"
script src:"/js/raphael.js"
style -> """
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
body {
font-family: 'PT Sans', sans-serif;
min-height: 600px;
background: rgb(215, 215, 215);
background: -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 500, from(rgb(240, 240, 240)), to(rgb(190, 190, 190)));
background: -webkit-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: -moz-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: -o-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
-webkit-font-smoothing: antialiased;
}
b, strong { font-weight: bold }
i, em { font-style: italic}
a {
color: inherit;
text-decoration: none;
padding: 0 0.1em;
background: rgba(255,255,255,0.5);
text-shadow: -1px -1px 2px rgba(100,100,100,0.9);
border-radius: 0.2em;
-webkit-transition: 0.5s;
-moz-transition: 0.5s;
-ms-transition: 0.5s;
-o-transition: 0.5s;
transition: 0.5s;
}
a:hover {
background: rgba(255,255,255,1);
text-shadow: -1px -1px 2px rgba(100,100,100,0.5);
}
body { padding: 15px; }
#skillradar { float:right; }
#baseinfo { width: 200px; padding-top: 50px; padding-left: 10px;}
#baseinfo dd { padding-top: 3px;}
.personal_experience { margin-top: 10px; }
"""
body ->
div id:"skillradar"
div id:"baseinfo", ->
dd ->
span "姓名:"
span "<NAME>"
dd ->
span "性别:"
span "男"
dd ->
span "年龄:"
span "24"
dd ->
span "专业:"
span "软件工程"
dd ->
span "Email:"
a id:"mailme", "Are you spam?"
pre class: "personal_experience", """
Personal Repository: <a href="https://github.com/dreampuf/">https://github.com/dreampuf/</a>
Personal Slides: <a href="http://www.slideshare.net/dreampuf/">http://www.slideshare.net/dreampuf/</a>
研究方向: <br />并行处理,喜欢使用(但不仅有)multiprocess进行多进程并行开发,知道锁的好处与麻烦点,不能抑制对加速比的追求。<br />数据挖掘,对于数据充满饥渴,爬虫,格式化,存储,检索,挖掘,应用。
2012.05~2012.09: 作为Scrum Master在团队中解决各项问题,已经进行了8个Sprint。
2012.08: 参加北大可视化学习班,进行为期一周的数据可视化学习。
2012.05: 负责果壳长微博生成优化。
2012.03~2012.04: UBB格式内容渲染为适合微博转发的组件。
2012.01~2012.02: 负责果壳网问答相关优化,@功能数据端开发。问答提问相似检索实现randing部分。
2011.11~2011.12: 负责果壳网问答开发项目.
2011.3~2011.10: 负责果壳网Python中间层实现.主要负责缓存系统维护.
2011.1~2011.2 : 负责果壳网v2前台个人主页模块.架构同上.
2010.12 : 果壳网v2后台CMS. Python + Django + Twisted + Postgresql + Memcaache + Ngnix
2010.12 :果壳时间 青年谱系 测试系统(Python + Django +Postgresql + Memcache + Ngnix),随后的果壳网承接IBM宣传项目Watson机器人大赛答题测试,也是于此相同的架构.
2010.6~2010.7 微软之星大赛全国三等奖网站.(C# / Asp.net MVC 2 + Microsoft Unity 2 + EntityFrameWork) : 作为组长负责整体系统架构,以及代码编写。
2009.11~2010.4 eWindow网站制作(Java / Structs2 + Hibernate) : 实践Java开发环境,项目包括三个小组,我负责前台组的页面脚本(JavaScript / Ext )编写。
2009.11 参加湖南省冬季技能大赛,获得软件应用二等奖. 同时期参加ACM个人斩获2题,不敌题牛被淘汰.
"""
coffeescript ->
class Radar
constructor: (@el, ds)->
@dslen = 0
@ds = []
max = 0
for k, v of ds
@dslen++
@ds.push [k, v]
max = v if max < v
@dmax = max
draw:()->
@draw_bg()
draw_bg: ()->
el = @el
ds = @ds
dslen = @dslen
dmax = @dmax
width = height = 320
paper = Raphael el, width+80, height
cx = width/2 + 40
cy = height/2
r = width*0.45
times = 7 #if r > 200 then 10 else 6
for i in [1..times]
c = paper.circle cx, cy, r*i/times
c.attr stroke:"#EEE"
grah_path_end = undefined
grah_path = []
radian_rate = 2 * Math.PI / 360
for i in [0...dslen]
angle = (360*i/dslen - 90) % 360
rd = angle*radian_rate
ty = r * (Math.sin rd)
tx = r * (Math.cos rd)
l = paper.path "M#{cx},#{cy}l#{tx},#{ty}"
l.attr stroke: "#FEF"
[k, v] = ds[i]
ew = 14
dx = if tx>0 then 1 else -1
dy = if ty>0 then 1 else -1
dr = v/dmax
text = paper.text cx+tx, cy+ty, k
#dd = Math.sqrt(Math.pow(text.attr("width"), 2) + Math.pow(text.attr("height"), 2))
text.attr
"font-size": 14
"font-weight": 2
#"x": cx+tx+dd*dx
#"y": cy+ty+dd*dy
if i == 0
grah_path.push "M#{cx+tx*dr},#{cy+ty*dr}"
grah_path.push "L#{cx+tx*dr},#{cy+ty*dr}z"
else
grah_path.splice -1, 0, "L#{cx+tx*dr},#{cy+ty*dr}"
grah = paper.path grah_path.join ""
grah.attr
fill: "#F0F"
"fill-opacity": .5
stroke: "#F0F"
"stroke-width": 0
"stroke-opacity": .5
0
#
rg = new Radar document.getElementById("skillradar"),
"Csharp": 45
"JavaScript": 80
"Python": 99
"Algorithm": 50
"Concurrent": 50
"Mining": 20
"Visualization": 10
rg.draw()
mailme = document.getElementById "mailme"
my_mail = "soddyque" + "@" + "gmail.com"
mailme.innerText = my_mail
mailme.href = "mailto:" + my_mail
`var _gaq = _gaq || [];_gaq.push(['_setAccount', 'UA-5293693-3']);_gaq.push(['_setDomainName', 'huangx.in']);_gaq.push(['_trackPageview']);(function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();`
null
| true | doctype 5
html ->
head ->
meta charset:"utf-8"
title "About Huangxin"
script src:"/js/raphael.js"
style -> """
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
body {
font-family: 'PT Sans', sans-serif;
min-height: 600px;
background: rgb(215, 215, 215);
background: -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 500, from(rgb(240, 240, 240)), to(rgb(190, 190, 190)));
background: -webkit-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: -moz-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: -o-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
-webkit-font-smoothing: antialiased;
}
b, strong { font-weight: bold }
i, em { font-style: italic}
a {
color: inherit;
text-decoration: none;
padding: 0 0.1em;
background: rgba(255,255,255,0.5);
text-shadow: -1px -1px 2px rgba(100,100,100,0.9);
border-radius: 0.2em;
-webkit-transition: 0.5s;
-moz-transition: 0.5s;
-ms-transition: 0.5s;
-o-transition: 0.5s;
transition: 0.5s;
}
a:hover {
background: rgba(255,255,255,1);
text-shadow: -1px -1px 2px rgba(100,100,100,0.5);
}
body { padding: 15px; }
#skillradar { float:right; }
#baseinfo { width: 200px; padding-top: 50px; padding-left: 10px;}
#baseinfo dd { padding-top: 3px;}
.personal_experience { margin-top: 10px; }
"""
body ->
div id:"skillradar"
div id:"baseinfo", ->
dd ->
span "姓名:"
span "PI:NAME:<NAME>END_PI"
dd ->
span "性别:"
span "男"
dd ->
span "年龄:"
span "24"
dd ->
span "专业:"
span "软件工程"
dd ->
span "Email:"
a id:"mailme", "Are you spam?"
pre class: "personal_experience", """
Personal Repository: <a href="https://github.com/dreampuf/">https://github.com/dreampuf/</a>
Personal Slides: <a href="http://www.slideshare.net/dreampuf/">http://www.slideshare.net/dreampuf/</a>
研究方向: <br />并行处理,喜欢使用(但不仅有)multiprocess进行多进程并行开发,知道锁的好处与麻烦点,不能抑制对加速比的追求。<br />数据挖掘,对于数据充满饥渴,爬虫,格式化,存储,检索,挖掘,应用。
2012.05~2012.09: 作为Scrum Master在团队中解决各项问题,已经进行了8个Sprint。
2012.08: 参加北大可视化学习班,进行为期一周的数据可视化学习。
2012.05: 负责果壳长微博生成优化。
2012.03~2012.04: UBB格式内容渲染为适合微博转发的组件。
2012.01~2012.02: 负责果壳网问答相关优化,@功能数据端开发。问答提问相似检索实现randing部分。
2011.11~2011.12: 负责果壳网问答开发项目.
2011.3~2011.10: 负责果壳网Python中间层实现.主要负责缓存系统维护.
2011.1~2011.2 : 负责果壳网v2前台个人主页模块.架构同上.
2010.12 : 果壳网v2后台CMS. Python + Django + Twisted + Postgresql + Memcaache + Ngnix
2010.12 :果壳时间 青年谱系 测试系统(Python + Django +Postgresql + Memcache + Ngnix),随后的果壳网承接IBM宣传项目Watson机器人大赛答题测试,也是于此相同的架构.
2010.6~2010.7 微软之星大赛全国三等奖网站.(C# / Asp.net MVC 2 + Microsoft Unity 2 + EntityFrameWork) : 作为组长负责整体系统架构,以及代码编写。
2009.11~2010.4 eWindow网站制作(Java / Structs2 + Hibernate) : 实践Java开发环境,项目包括三个小组,我负责前台组的页面脚本(JavaScript / Ext )编写。
2009.11 参加湖南省冬季技能大赛,获得软件应用二等奖. 同时期参加ACM个人斩获2题,不敌题牛被淘汰.
"""
coffeescript ->
class Radar
constructor: (@el, ds)->
@dslen = 0
@ds = []
max = 0
for k, v of ds
@dslen++
@ds.push [k, v]
max = v if max < v
@dmax = max
draw:()->
@draw_bg()
draw_bg: ()->
el = @el
ds = @ds
dslen = @dslen
dmax = @dmax
width = height = 320
paper = Raphael el, width+80, height
cx = width/2 + 40
cy = height/2
r = width*0.45
times = 7 #if r > 200 then 10 else 6
for i in [1..times]
c = paper.circle cx, cy, r*i/times
c.attr stroke:"#EEE"
grah_path_end = undefined
grah_path = []
radian_rate = 2 * Math.PI / 360
for i in [0...dslen]
angle = (360*i/dslen - 90) % 360
rd = angle*radian_rate
ty = r * (Math.sin rd)
tx = r * (Math.cos rd)
l = paper.path "M#{cx},#{cy}l#{tx},#{ty}"
l.attr stroke: "#FEF"
[k, v] = ds[i]
ew = 14
dx = if tx>0 then 1 else -1
dy = if ty>0 then 1 else -1
dr = v/dmax
text = paper.text cx+tx, cy+ty, k
#dd = Math.sqrt(Math.pow(text.attr("width"), 2) + Math.pow(text.attr("height"), 2))
text.attr
"font-size": 14
"font-weight": 2
#"x": cx+tx+dd*dx
#"y": cy+ty+dd*dy
if i == 0
grah_path.push "M#{cx+tx*dr},#{cy+ty*dr}"
grah_path.push "L#{cx+tx*dr},#{cy+ty*dr}z"
else
grah_path.splice -1, 0, "L#{cx+tx*dr},#{cy+ty*dr}"
grah = paper.path grah_path.join ""
grah.attr
fill: "#F0F"
"fill-opacity": .5
stroke: "#F0F"
"stroke-width": 0
"stroke-opacity": .5
0
#
rg = new Radar document.getElementById("skillradar"),
"Csharp": 45
"JavaScript": 80
"Python": 99
"Algorithm": 50
"Concurrent": 50
"Mining": 20
"Visualization": 10
rg.draw()
mailme = document.getElementById "mailme"
my_mail = "soddyque" + "@" + "gmail.com"
mailme.innerText = my_mail
mailme.href = "mailto:" + my_mail
`var _gaq = _gaq || [];_gaq.push(['_setAccount', 'UA-5293693-3']);_gaq.push(['_setDomainName', 'huangx.in']);_gaq.push(['_trackPageview']);(function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();`
null
|
[
{
"context": "\n user = robot.brain.userForId('1', name: 'jasmine', room: '#jasmine')\n adapter = robot.adapt",
"end": 935,
"score": 0.5987827777862549,
"start": 928,
"tag": "NAME",
"value": "jasmine"
}
] | spec/pubsub_spec.coffee | hubot-scripts/hubot-pubsub | 24 | path = require 'path'
Robot = require 'hubot/src/robot'
messages = require 'hubot/src/message'
describe 'pubsub', ->
robot = null
adapter = null
user = null
say = (msg) ->
adapter.receive new messages.TextMessage(user, msg)
expectHubotToSay = (msg, done) ->
adapter.on 'send', (envelope, strings) ->
(expect strings[0]).toMatch msg
done()
captureHubotOutput = (captured, done) ->
adapter.on 'send', (envelope, strings) ->
unless strings[0] in captured
captured.push strings[0]
done()
beforeEach ->
ready = false
runs ->
robot = new Robot(null, 'mock-adapter', false, 'Hubot')
robot.adapter.on 'connected', ->
process.env.HUBOT_AUTH_ADMIN = '1'
robot.loadFile (path.resolve path.join 'node_modules/hubot/src/scripts'), 'auth.coffee'
(require '../src/pubsub')(robot)
user = robot.brain.userForId('1', name: 'jasmine', room: '#jasmine')
adapter = robot.adapter
ready = true
robot.run()
waitsFor -> ready
afterEach ->
robot.shutdown()
it 'lists current room subscriptions when none are present', (done) ->
expectHubotToSay 'Total subscriptions for #jasmine: 0', done
say 'hubot subscriptions'
it 'lists current room subscriptions', (done) ->
robot.brain.data.subscriptions =
'foo.bar': [ '#jasmine', '#other' ]
'baz': [ '#foo', '#jasmine' ]
count = 0
captured = []
doneLatch = ->
count += 1
if count == 3
(expect 'foo.bar -> #jasmine' in captured).toBeTruthy()
(expect 'baz -> #jasmine' in captured).toBeTruthy()
(expect 'Total subscriptions for #jasmine: 2' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
captureHubotOutput captured, doneLatch
captureHubotOutput captured, doneLatch
say 'hubot subscriptions'
it 'lists all subscriptions', (done) ->
expectHubotToSay 'Total subscriptions: 0', done
say 'hubot all subscriptions'
it 'subscribes a room', (done) ->
expectHubotToSay 'Subscribed #jasmine to foo.bar events', ->
(expect robot.brain.data.subscriptions['foo.bar']).toEqual [ '#jasmine' ]
done()
say 'hubot subscribe foo.bar'
it 'cannot unsubscribe a room which was not subscribed', (done) ->
expectHubotToSay '#jasmine was not subscribed to foo.bar events', done
say 'hubot unsubscribe foo.bar'
it 'unsubscribes a room', (done) ->
robot.brain.data.subscriptions = 'foo.bar': [ '#jasmine' ]
expectHubotToSay 'Unsubscribed #jasmine from foo.bar events', ->
(expect robot.brain.data.subscriptions['foo.bar']).toEqual [ ]
done()
say 'hubot unsubscribe foo.bar'
it 'allows subscribing all unsubscribed events for debugging', (done) ->
robot.brain.data.subscriptions = 'unsubscribed.event': [ '#jasmine' ]
count = 0
captured = []
doneLatch = ->
count += 1
if count == 2
(expect 'unsubscribed.event: unrouted: no one should receive it' in captured).toBeTruthy()
(expect 'Notified 0 rooms about unrouted' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
say 'hubot publish unrouted no one should receive it'
it 'allows subscribing to namespaces', (done) ->
robot.brain.data.subscriptions = 'errors.critical': [ '#jasmine' ]
count = 0
captured = []
doneLatch = ->
(expect 'errors.critical.subsystem: blew up!' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
say 'hubot publish errors.critical.subsystem blew up!'
it 'handles pubsub:publish event', (done) ->
robot.brain.data.subscriptions = 'alien.event': [ '#jasmine' ]
count = 0
captured = []
doneLatch = ->
(expect 'alien.event: hi from other script' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
robot.emit 'pubsub:publish', 'alien.event', 'hi from other script'
| 151371 | path = require 'path'
Robot = require 'hubot/src/robot'
messages = require 'hubot/src/message'
describe 'pubsub', ->
robot = null
adapter = null
user = null
say = (msg) ->
adapter.receive new messages.TextMessage(user, msg)
expectHubotToSay = (msg, done) ->
adapter.on 'send', (envelope, strings) ->
(expect strings[0]).toMatch msg
done()
captureHubotOutput = (captured, done) ->
adapter.on 'send', (envelope, strings) ->
unless strings[0] in captured
captured.push strings[0]
done()
beforeEach ->
ready = false
runs ->
robot = new Robot(null, 'mock-adapter', false, 'Hubot')
robot.adapter.on 'connected', ->
process.env.HUBOT_AUTH_ADMIN = '1'
robot.loadFile (path.resolve path.join 'node_modules/hubot/src/scripts'), 'auth.coffee'
(require '../src/pubsub')(robot)
user = robot.brain.userForId('1', name: '<NAME>', room: '#jasmine')
adapter = robot.adapter
ready = true
robot.run()
waitsFor -> ready
afterEach ->
robot.shutdown()
it 'lists current room subscriptions when none are present', (done) ->
expectHubotToSay 'Total subscriptions for #jasmine: 0', done
say 'hubot subscriptions'
it 'lists current room subscriptions', (done) ->
robot.brain.data.subscriptions =
'foo.bar': [ '#jasmine', '#other' ]
'baz': [ '#foo', '#jasmine' ]
count = 0
captured = []
doneLatch = ->
count += 1
if count == 3
(expect 'foo.bar -> #jasmine' in captured).toBeTruthy()
(expect 'baz -> #jasmine' in captured).toBeTruthy()
(expect 'Total subscriptions for #jasmine: 2' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
captureHubotOutput captured, doneLatch
captureHubotOutput captured, doneLatch
say 'hubot subscriptions'
it 'lists all subscriptions', (done) ->
expectHubotToSay 'Total subscriptions: 0', done
say 'hubot all subscriptions'
it 'subscribes a room', (done) ->
expectHubotToSay 'Subscribed #jasmine to foo.bar events', ->
(expect robot.brain.data.subscriptions['foo.bar']).toEqual [ '#jasmine' ]
done()
say 'hubot subscribe foo.bar'
it 'cannot unsubscribe a room which was not subscribed', (done) ->
expectHubotToSay '#jasmine was not subscribed to foo.bar events', done
say 'hubot unsubscribe foo.bar'
it 'unsubscribes a room', (done) ->
robot.brain.data.subscriptions = 'foo.bar': [ '#jasmine' ]
expectHubotToSay 'Unsubscribed #jasmine from foo.bar events', ->
(expect robot.brain.data.subscriptions['foo.bar']).toEqual [ ]
done()
say 'hubot unsubscribe foo.bar'
it 'allows subscribing all unsubscribed events for debugging', (done) ->
robot.brain.data.subscriptions = 'unsubscribed.event': [ '#jasmine' ]
count = 0
captured = []
doneLatch = ->
count += 1
if count == 2
(expect 'unsubscribed.event: unrouted: no one should receive it' in captured).toBeTruthy()
(expect 'Notified 0 rooms about unrouted' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
say 'hubot publish unrouted no one should receive it'
it 'allows subscribing to namespaces', (done) ->
robot.brain.data.subscriptions = 'errors.critical': [ '#jasmine' ]
count = 0
captured = []
doneLatch = ->
(expect 'errors.critical.subsystem: blew up!' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
say 'hubot publish errors.critical.subsystem blew up!'
it 'handles pubsub:publish event', (done) ->
robot.brain.data.subscriptions = 'alien.event': [ '#jasmine' ]
count = 0
captured = []
doneLatch = ->
(expect 'alien.event: hi from other script' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
robot.emit 'pubsub:publish', 'alien.event', 'hi from other script'
| true | path = require 'path'
Robot = require 'hubot/src/robot'
messages = require 'hubot/src/message'
describe 'pubsub', ->
robot = null
adapter = null
user = null
say = (msg) ->
adapter.receive new messages.TextMessage(user, msg)
expectHubotToSay = (msg, done) ->
adapter.on 'send', (envelope, strings) ->
(expect strings[0]).toMatch msg
done()
captureHubotOutput = (captured, done) ->
adapter.on 'send', (envelope, strings) ->
unless strings[0] in captured
captured.push strings[0]
done()
beforeEach ->
ready = false
runs ->
robot = new Robot(null, 'mock-adapter', false, 'Hubot')
robot.adapter.on 'connected', ->
process.env.HUBOT_AUTH_ADMIN = '1'
robot.loadFile (path.resolve path.join 'node_modules/hubot/src/scripts'), 'auth.coffee'
(require '../src/pubsub')(robot)
user = robot.brain.userForId('1', name: 'PI:NAME:<NAME>END_PI', room: '#jasmine')
adapter = robot.adapter
ready = true
robot.run()
waitsFor -> ready
afterEach ->
robot.shutdown()
it 'lists current room subscriptions when none are present', (done) ->
expectHubotToSay 'Total subscriptions for #jasmine: 0', done
say 'hubot subscriptions'
it 'lists current room subscriptions', (done) ->
robot.brain.data.subscriptions =
'foo.bar': [ '#jasmine', '#other' ]
'baz': [ '#foo', '#jasmine' ]
count = 0
captured = []
doneLatch = ->
count += 1
if count == 3
(expect 'foo.bar -> #jasmine' in captured).toBeTruthy()
(expect 'baz -> #jasmine' in captured).toBeTruthy()
(expect 'Total subscriptions for #jasmine: 2' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
captureHubotOutput captured, doneLatch
captureHubotOutput captured, doneLatch
say 'hubot subscriptions'
it 'lists all subscriptions', (done) ->
expectHubotToSay 'Total subscriptions: 0', done
say 'hubot all subscriptions'
it 'subscribes a room', (done) ->
expectHubotToSay 'Subscribed #jasmine to foo.bar events', ->
(expect robot.brain.data.subscriptions['foo.bar']).toEqual [ '#jasmine' ]
done()
say 'hubot subscribe foo.bar'
it 'cannot unsubscribe a room which was not subscribed', (done) ->
expectHubotToSay '#jasmine was not subscribed to foo.bar events', done
say 'hubot unsubscribe foo.bar'
it 'unsubscribes a room', (done) ->
robot.brain.data.subscriptions = 'foo.bar': [ '#jasmine' ]
expectHubotToSay 'Unsubscribed #jasmine from foo.bar events', ->
(expect robot.brain.data.subscriptions['foo.bar']).toEqual [ ]
done()
say 'hubot unsubscribe foo.bar'
it 'allows subscribing all unsubscribed events for debugging', (done) ->
robot.brain.data.subscriptions = 'unsubscribed.event': [ '#jasmine' ]
count = 0
captured = []
doneLatch = ->
count += 1
if count == 2
(expect 'unsubscribed.event: unrouted: no one should receive it' in captured).toBeTruthy()
(expect 'Notified 0 rooms about unrouted' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
say 'hubot publish unrouted no one should receive it'
it 'allows subscribing to namespaces', (done) ->
robot.brain.data.subscriptions = 'errors.critical': [ '#jasmine' ]
count = 0
captured = []
doneLatch = ->
(expect 'errors.critical.subsystem: blew up!' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
say 'hubot publish errors.critical.subsystem blew up!'
it 'handles pubsub:publish event', (done) ->
robot.brain.data.subscriptions = 'alien.event': [ '#jasmine' ]
count = 0
captured = []
doneLatch = ->
(expect 'alien.event: hi from other script' in captured).toBeTruthy()
done()
captureHubotOutput captured, doneLatch
robot.emit 'pubsub:publish', 'alien.event', 'hi from other script'
|
[
{
"context": "late:'hi ${user}!'\n data:\n user: 'Mikey'\n expect(result).to.be.equal 'hi Mikey!'\n ",
"end": 2731,
"score": 0.8979530334472656,
"start": 2726,
"tag": "USERNAME",
"value": "Mikey"
},
{
"context": "late:'hi ${user}!'\n data:\n user: 'Mikey'\n engine: 'Test1'\n expect(result).to.",
"end": 3081,
"score": 0.9195554852485657,
"start": 3076,
"tag": "USERNAME",
"value": "Mikey"
},
{
"context": "late:'hi ${user}!'\n data:\n user: 'Mikey'\n engine:\n name: 'Test1'\n ",
"end": 3450,
"score": 0.8858286142349243,
"start": 3445,
"tag": "USERNAME",
"value": "Mikey"
},
{
"context": "late:'hi ${user}!'\n data:\n user: 'Mikey'\n opt1: '1'\n expect(TestTemplateEngin",
"end": 3754,
"score": 0.8804266452789307,
"start": 3749,
"tag": "USERNAME",
"value": "Mikey"
},
{
"context": "late:'hi ${user}!'\n data:\n user: 'Mikey'\n , (err, result)->\n unless err\n ",
"end": 4004,
"score": 0.9311284422874451,
"start": 3999,
"tag": "USERNAME",
"value": "Mikey"
},
{
"context": "late:'hi ${user}!'\n data:\n user: 'Mikey'\n engine: 'Test1'\n , (err, result)->\n",
"end": 4420,
"score": 0.8554824590682983,
"start": 4415,
"tag": "USERNAME",
"value": "Mikey"
},
{
"context": "late:'hi ${user}!'\n data:\n user: 'Mikey'\n engine:\n name: 'Test1'\n ",
"end": 4852,
"score": 0.5533738136291504,
"start": 4850,
"tag": "NAME",
"value": "Mi"
},
{
"context": "te:'hi ${user}!'\n data:\n user: 'Mikey'\n engine:\n name: 'Test1'\n ",
"end": 4855,
"score": 0.8209682703018188,
"start": 4852,
"tag": "USERNAME",
"value": "key"
},
{
"context": " ${user}!'\n data:\n user: 'Mikey'\n opt1: '1'\n expect(TestTe",
"end": 5223,
"score": 0.5687510371208191,
"start": 5221,
"tag": "NAME",
"value": "Mi"
},
{
"context": "{user}!'\n data:\n user: 'Mikey'\n opt1: '1'\n expect(TestTempl",
"end": 5226,
"score": 0.8693882822990417,
"start": 5223,
"tag": "USERNAME",
"value": "key"
}
] | test/index-test.coffee | snowyu/task-registry-template-engine.js | 0 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
should = chai.should()
expect = chai.expect
assert = chai.assert
chai.use(sinonChai)
setImmediate = setImmediate || process.nextTick
Task = require 'task-registry'
TemplateEngine = require '../src'
register = TemplateEngine.register
aliases = TemplateEngine.aliases
templateEngine = Task 'TemplateEngine'
class TestTemplateEngine
register TestTemplateEngine
aliases TestTemplateEngine, 'test'
constructor: -> return super
_executeSync: sinon.spy (aOptions)->
result = aOptions.template
result = result.toString() if result
if result
for k, v of aOptions.data
result = result.replace '${'+k+'}', v
result
class Test1TemplateEngine
register Test1TemplateEngine
aliases Test1TemplateEngine, 'test1'
constructor: -> return super
_executeSync: sinon.spy (aOptions)->
result = aOptions.template
result = result.toString() if result
if result
for k, v of aOptions.data
result = result.replace '${'+k+'}', v
result
describe 'TemplateEngine', ->
beforeEach ->
TestTemplateEngine::_executeSync.reset()
Test1TemplateEngine::_executeSync.reset()
it 'should get the test template engine via constructor', ->
result = TemplateEngine 'Test'
expect(result).to.be.instanceOf TestTemplateEngine
result = TemplateEngine 'Test1'
expect(result).to.be.instanceOf Test1TemplateEngine
it 'should get the test template engine', ->
result = templateEngine.get 'Test'
expect(result).to.be.instanceOf TestTemplateEngine
result = templateEngine.get 'test'
expect(result).to.be.instanceOf TestTemplateEngine
result = templateEngine.get 'Test1'
expect(result).to.be.instanceOf Test1TemplateEngine
result = templateEngine.get 'test1'
expect(result).to.be.instanceOf Test1TemplateEngine
describe 'toString', ->
it 'should toString templateEngines', ->
expect(templateEngine.toString()).to.be.equal '[TemplateEngines]'
it 'should toString templateEngine', ->
result = templateEngine.get 'Test'
expect(result.toString()).to.be.equal 'Test'
describe 'inspect', ->
it 'should inspect templateEngines', ->
expect(templateEngine.inspect()).to.be.equal '<TemplateEngines "Test","Test1">'
it 'should inspect templateEngine', ->
result = templateEngine.get 'Test'
expect(result.inspect()).to.be.equal '<TemplateEngine "Test">'
describe 'executeSync', ->
it 'should render a template', ->
result = templateEngine.executeSync
template:'hi ${user}!'
data:
user: 'Mikey'
expect(result).to.be.equal 'hi Mikey!'
expect(TestTemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.not.called
it 'should render a template via specified engine name', ->
result = templateEngine.executeSync
template:'hi ${user}!'
data:
user: 'Mikey'
engine: 'Test1'
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(TestTemplateEngine::_executeSync).to.be.not.called
it 'should render a template via specified engine', ->
result = templateEngine.executeSync
template:'hi ${user}!'
data:
user: 'Mikey'
engine:
name: 'Test1'
opt1: '1'
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.calledWith
template:'hi ${user}!'
data:
user: 'Mikey'
opt1: '1'
expect(TestTemplateEngine::_executeSync).to.be.not.called
describe 'execute', ->
it 'should render a template', (done)->
templateEngine.execute
template:'hi ${user}!'
data:
user: 'Mikey'
, (err, result)->
unless err
expect(result).to.be.equal 'hi Mikey!'
expect(TestTemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.not.called
done(err)
it 'should render a template via specified engine name', (done)->
templateEngine.execute
template:'hi ${user}!'
data:
user: 'Mikey'
engine: 'Test1'
, (err, result)->
unless err
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(TestTemplateEngine::_executeSync).to.be.not.called
done(err)
it 'should render a template via specified engine', (done)->
templateEngine.execute
template:'hi ${user}!'
data:
user: 'Mikey'
engine:
name: 'Test1'
opt1: '1'
, (err, result)->
unless err
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.calledWith
template:'hi ${user}!'
data:
user: 'Mikey'
opt1: '1'
expect(TestTemplateEngine::_executeSync).to.be.not.called
done(err)
| 99598 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
should = chai.should()
expect = chai.expect
assert = chai.assert
chai.use(sinonChai)
setImmediate = setImmediate || process.nextTick
Task = require 'task-registry'
TemplateEngine = require '../src'
register = TemplateEngine.register
aliases = TemplateEngine.aliases
templateEngine = Task 'TemplateEngine'
class TestTemplateEngine
register TestTemplateEngine
aliases TestTemplateEngine, 'test'
constructor: -> return super
_executeSync: sinon.spy (aOptions)->
result = aOptions.template
result = result.toString() if result
if result
for k, v of aOptions.data
result = result.replace '${'+k+'}', v
result
class Test1TemplateEngine
register Test1TemplateEngine
aliases Test1TemplateEngine, 'test1'
constructor: -> return super
_executeSync: sinon.spy (aOptions)->
result = aOptions.template
result = result.toString() if result
if result
for k, v of aOptions.data
result = result.replace '${'+k+'}', v
result
describe 'TemplateEngine', ->
beforeEach ->
TestTemplateEngine::_executeSync.reset()
Test1TemplateEngine::_executeSync.reset()
it 'should get the test template engine via constructor', ->
result = TemplateEngine 'Test'
expect(result).to.be.instanceOf TestTemplateEngine
result = TemplateEngine 'Test1'
expect(result).to.be.instanceOf Test1TemplateEngine
it 'should get the test template engine', ->
result = templateEngine.get 'Test'
expect(result).to.be.instanceOf TestTemplateEngine
result = templateEngine.get 'test'
expect(result).to.be.instanceOf TestTemplateEngine
result = templateEngine.get 'Test1'
expect(result).to.be.instanceOf Test1TemplateEngine
result = templateEngine.get 'test1'
expect(result).to.be.instanceOf Test1TemplateEngine
describe 'toString', ->
it 'should toString templateEngines', ->
expect(templateEngine.toString()).to.be.equal '[TemplateEngines]'
it 'should toString templateEngine', ->
result = templateEngine.get 'Test'
expect(result.toString()).to.be.equal 'Test'
describe 'inspect', ->
it 'should inspect templateEngines', ->
expect(templateEngine.inspect()).to.be.equal '<TemplateEngines "Test","Test1">'
it 'should inspect templateEngine', ->
result = templateEngine.get 'Test'
expect(result.inspect()).to.be.equal '<TemplateEngine "Test">'
describe 'executeSync', ->
it 'should render a template', ->
result = templateEngine.executeSync
template:'hi ${user}!'
data:
user: 'Mikey'
expect(result).to.be.equal 'hi Mikey!'
expect(TestTemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.not.called
it 'should render a template via specified engine name', ->
result = templateEngine.executeSync
template:'hi ${user}!'
data:
user: 'Mikey'
engine: 'Test1'
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(TestTemplateEngine::_executeSync).to.be.not.called
it 'should render a template via specified engine', ->
result = templateEngine.executeSync
template:'hi ${user}!'
data:
user: 'Mikey'
engine:
name: 'Test1'
opt1: '1'
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.calledWith
template:'hi ${user}!'
data:
user: 'Mikey'
opt1: '1'
expect(TestTemplateEngine::_executeSync).to.be.not.called
describe 'execute', ->
it 'should render a template', (done)->
templateEngine.execute
template:'hi ${user}!'
data:
user: 'Mikey'
, (err, result)->
unless err
expect(result).to.be.equal 'hi Mikey!'
expect(TestTemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.not.called
done(err)
it 'should render a template via specified engine name', (done)->
templateEngine.execute
template:'hi ${user}!'
data:
user: 'Mikey'
engine: 'Test1'
, (err, result)->
unless err
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(TestTemplateEngine::_executeSync).to.be.not.called
done(err)
it 'should render a template via specified engine', (done)->
templateEngine.execute
template:'hi ${user}!'
data:
user: '<NAME>key'
engine:
name: 'Test1'
opt1: '1'
, (err, result)->
unless err
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.calledWith
template:'hi ${user}!'
data:
user: '<NAME>key'
opt1: '1'
expect(TestTemplateEngine::_executeSync).to.be.not.called
done(err)
| true | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
should = chai.should()
expect = chai.expect
assert = chai.assert
chai.use(sinonChai)
setImmediate = setImmediate || process.nextTick
Task = require 'task-registry'
TemplateEngine = require '../src'
register = TemplateEngine.register
aliases = TemplateEngine.aliases
templateEngine = Task 'TemplateEngine'
class TestTemplateEngine
register TestTemplateEngine
aliases TestTemplateEngine, 'test'
constructor: -> return super
_executeSync: sinon.spy (aOptions)->
result = aOptions.template
result = result.toString() if result
if result
for k, v of aOptions.data
result = result.replace '${'+k+'}', v
result
class Test1TemplateEngine
register Test1TemplateEngine
aliases Test1TemplateEngine, 'test1'
constructor: -> return super
_executeSync: sinon.spy (aOptions)->
result = aOptions.template
result = result.toString() if result
if result
for k, v of aOptions.data
result = result.replace '${'+k+'}', v
result
describe 'TemplateEngine', ->
beforeEach ->
TestTemplateEngine::_executeSync.reset()
Test1TemplateEngine::_executeSync.reset()
it 'should get the test template engine via constructor', ->
result = TemplateEngine 'Test'
expect(result).to.be.instanceOf TestTemplateEngine
result = TemplateEngine 'Test1'
expect(result).to.be.instanceOf Test1TemplateEngine
it 'should get the test template engine', ->
result = templateEngine.get 'Test'
expect(result).to.be.instanceOf TestTemplateEngine
result = templateEngine.get 'test'
expect(result).to.be.instanceOf TestTemplateEngine
result = templateEngine.get 'Test1'
expect(result).to.be.instanceOf Test1TemplateEngine
result = templateEngine.get 'test1'
expect(result).to.be.instanceOf Test1TemplateEngine
describe 'toString', ->
it 'should toString templateEngines', ->
expect(templateEngine.toString()).to.be.equal '[TemplateEngines]'
it 'should toString templateEngine', ->
result = templateEngine.get 'Test'
expect(result.toString()).to.be.equal 'Test'
describe 'inspect', ->
it 'should inspect templateEngines', ->
expect(templateEngine.inspect()).to.be.equal '<TemplateEngines "Test","Test1">'
it 'should inspect templateEngine', ->
result = templateEngine.get 'Test'
expect(result.inspect()).to.be.equal '<TemplateEngine "Test">'
describe 'executeSync', ->
it 'should render a template', ->
result = templateEngine.executeSync
template:'hi ${user}!'
data:
user: 'Mikey'
expect(result).to.be.equal 'hi Mikey!'
expect(TestTemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.not.called
it 'should render a template via specified engine name', ->
result = templateEngine.executeSync
template:'hi ${user}!'
data:
user: 'Mikey'
engine: 'Test1'
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(TestTemplateEngine::_executeSync).to.be.not.called
it 'should render a template via specified engine', ->
result = templateEngine.executeSync
template:'hi ${user}!'
data:
user: 'Mikey'
engine:
name: 'Test1'
opt1: '1'
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.calledWith
template:'hi ${user}!'
data:
user: 'Mikey'
opt1: '1'
expect(TestTemplateEngine::_executeSync).to.be.not.called
describe 'execute', ->
it 'should render a template', (done)->
templateEngine.execute
template:'hi ${user}!'
data:
user: 'Mikey'
, (err, result)->
unless err
expect(result).to.be.equal 'hi Mikey!'
expect(TestTemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.not.called
done(err)
it 'should render a template via specified engine name', (done)->
templateEngine.execute
template:'hi ${user}!'
data:
user: 'Mikey'
engine: 'Test1'
, (err, result)->
unless err
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(TestTemplateEngine::_executeSync).to.be.not.called
done(err)
it 'should render a template via specified engine', (done)->
templateEngine.execute
template:'hi ${user}!'
data:
user: 'PI:NAME:<NAME>END_PIkey'
engine:
name: 'Test1'
opt1: '1'
, (err, result)->
unless err
expect(result).to.be.equal 'hi Mikey!'
expect(Test1TemplateEngine::_executeSync).to.be.calledOnce
expect(Test1TemplateEngine::_executeSync).to.be.calledWith
template:'hi ${user}!'
data:
user: 'PI:NAME:<NAME>END_PIkey'
opt1: '1'
expect(TestTemplateEngine::_executeSync).to.be.not.called
done(err)
|
[
{
"context": "###\ngrunt-ember-script\n\nCopyright (c) 2013 Gordon L. Hempton, contributors\nLicensed under the MIT license.\n###",
"end": 60,
"score": 0.9998518228530884,
"start": 43,
"tag": "NAME",
"value": "Gordon L. Hempton"
}
] | node_modules/grunt-ember-script/test/em_test.coffee | rtablada/ember-walkthrough | 7 | ###
grunt-ember-script
Copyright (c) 2013 Gordon L. Hempton, contributors
Licensed under the MIT license.
###
grunt = require 'grunt'
fs = require 'fs'
read = (file)->
content = grunt.file.read file
if process.platform is 'win32' then content.replace /\r\n/g, '\n' else content
exports.em =
compile: (test)->
test.expect 3
actual = read 'tmp/helloworld.js.em'
expected = read 'test/expected/helloworld.js.em'
test.equal expected, actual, 'should concat all em files'
actual = read 'tmp/helloworld.js'
expected = read 'test/expected/helloworld.js'
test.equal expected, actual, 'should compile emberscript to javascript'
actual = read 'tmp/helloworld.jsmap.json'
expected = read 'test/expected/helloworld.jsmap.json'
test.equal expected, actual, 'should create source map'
test.done()
| 169977 | ###
grunt-ember-script
Copyright (c) 2013 <NAME>, contributors
Licensed under the MIT license.
###
grunt = require 'grunt'
fs = require 'fs'
read = (file)->
content = grunt.file.read file
if process.platform is 'win32' then content.replace /\r\n/g, '\n' else content
exports.em =
compile: (test)->
test.expect 3
actual = read 'tmp/helloworld.js.em'
expected = read 'test/expected/helloworld.js.em'
test.equal expected, actual, 'should concat all em files'
actual = read 'tmp/helloworld.js'
expected = read 'test/expected/helloworld.js'
test.equal expected, actual, 'should compile emberscript to javascript'
actual = read 'tmp/helloworld.jsmap.json'
expected = read 'test/expected/helloworld.jsmap.json'
test.equal expected, actual, 'should create source map'
test.done()
| true | ###
grunt-ember-script
Copyright (c) 2013 PI:NAME:<NAME>END_PI, contributors
Licensed under the MIT license.
###
grunt = require 'grunt'
fs = require 'fs'
read = (file)->
content = grunt.file.read file
if process.platform is 'win32' then content.replace /\r\n/g, '\n' else content
exports.em =
compile: (test)->
test.expect 3
actual = read 'tmp/helloworld.js.em'
expected = read 'test/expected/helloworld.js.em'
test.equal expected, actual, 'should concat all em files'
actual = read 'tmp/helloworld.js'
expected = read 'test/expected/helloworld.js'
test.equal expected, actual, 'should compile emberscript to javascript'
actual = read 'tmp/helloworld.jsmap.json'
expected = read 'test/expected/helloworld.jsmap.json'
test.equal expected, actual, 'should create source map'
test.done()
|
[
{
"context": "llowing text is an excerpt from Finnegan's Wake by James Joyce\"\n done()\n\n it 'can also be chaine",
"end": 1548,
"score": 0.9996936321258545,
"start": 1537,
"tag": "NAME",
"value": "James Joyce"
},
{
"context": "llowing text is an excerpt from Finnegan's Wake by James Joyce\"\n done()\n\n describe 'that matches n",
"end": 1757,
"score": 0.9996860027313232,
"start": 1746,
"tag": "NAME",
"value": "James Joyce"
}
] | node_modules/webdriver-sizzle/test/webdriver_sizzle.test.coffee | goodguytt01/gateway-front | 5 | assert = require 'assert'
path = require 'path'
webdriver = require 'selenium-webdriver'
webdriverSizzle = require '..'
{WebElement} = webdriver
{Deferred} = webdriver.promise
url = (page) ->
"file://#{path.join __dirname, page}"
# hack to work around then not working below,
# hijack mocha's uncaughtException handler.
assertUncaught = (regex, done) ->
listeners = process.listeners 'uncaughtException'
process.removeAllListeners 'uncaughtException'
process.once 'uncaughtException', (err) ->
listeners.forEach (listener) -> process.on 'uncaughtException', listener
assert regex.test err.message, "#{err.message} doesn't match #{regex}"
done()
describe 'webdriver-sizzle', ->
$ = null
driver = null
before ->
chromeCapabilities = webdriver.Capabilities.chrome()
chromeCapabilities.set('chromeOptions', {args: ['--headless']})
driver = new webdriver.Builder()
.forBrowser('chrome')
.withCapabilities(chromeCapabilities)
.build()
@timeout 0 # this may take a while in CI
describe 'once driving a webdriver Builder', ->
before (done) ->
$ = webdriverSizzle(driver)
driver.get(url 'finnegan.html').then -> done()
describe 'calling with a CSS selector', ->
it 'returns the first matching webdriver element', (done) ->
$('.test-el').then (el) ->
assert (el instanceof WebElement), 'is a WebElement'
el.getText().then (text) ->
assert.equal text, "The following text is an excerpt from Finnegan's Wake by James Joyce"
done()
it 'can also be chained', (done) ->
$('.test-el').getText().then (text) ->
assert.equal text, "The following text is an excerpt from Finnegan's Wake by James Joyce"
done()
describe 'that matches no elements', ->
it 'rejects with an error that includes the selector', (done) ->
$('.does-not-match')
.catch (expectedErr) ->
assert /does-not-match/.test(expectedErr?.message)
done()
# TODO? -- this doesn't work, b/c of the way it's implemented
# in selenium-webdriver. doesn't seem that critical to work around.
it.skip 'rejection is also passed down chain', (done) ->
$('.does-not-match').getText()
.then (expectedErr) ->
assert /does-not-match/.test(expectedErr?.message)
done()
# (alternative to above)
it 'chained methods causes error to be thrown', (done) ->
$('.does-not-match').getText()
assertUncaught /does-not-match/, done
describe 'all', ->
it 'returns all matching elements', (done) ->
$.all('p').then (elements) ->
assert.equal elements.length, 2
done()
, (err) ->
done err
it 'returns empty array when no matching elements', (done) ->
$.all('section').then (elements) ->
assert.equal elements.length, 0
done()
, (err) ->
done err
| 153927 | assert = require 'assert'
path = require 'path'
webdriver = require 'selenium-webdriver'
webdriverSizzle = require '..'
{WebElement} = webdriver
{Deferred} = webdriver.promise
url = (page) ->
"file://#{path.join __dirname, page}"
# hack to work around then not working below,
# hijack mocha's uncaughtException handler.
assertUncaught = (regex, done) ->
listeners = process.listeners 'uncaughtException'
process.removeAllListeners 'uncaughtException'
process.once 'uncaughtException', (err) ->
listeners.forEach (listener) -> process.on 'uncaughtException', listener
assert regex.test err.message, "#{err.message} doesn't match #{regex}"
done()
describe 'webdriver-sizzle', ->
$ = null
driver = null
before ->
chromeCapabilities = webdriver.Capabilities.chrome()
chromeCapabilities.set('chromeOptions', {args: ['--headless']})
driver = new webdriver.Builder()
.forBrowser('chrome')
.withCapabilities(chromeCapabilities)
.build()
@timeout 0 # this may take a while in CI
describe 'once driving a webdriver Builder', ->
before (done) ->
$ = webdriverSizzle(driver)
driver.get(url 'finnegan.html').then -> done()
describe 'calling with a CSS selector', ->
it 'returns the first matching webdriver element', (done) ->
$('.test-el').then (el) ->
assert (el instanceof WebElement), 'is a WebElement'
el.getText().then (text) ->
assert.equal text, "The following text is an excerpt from Finnegan's Wake by <NAME>"
done()
it 'can also be chained', (done) ->
$('.test-el').getText().then (text) ->
assert.equal text, "The following text is an excerpt from Finnegan's Wake by <NAME>"
done()
describe 'that matches no elements', ->
it 'rejects with an error that includes the selector', (done) ->
$('.does-not-match')
.catch (expectedErr) ->
assert /does-not-match/.test(expectedErr?.message)
done()
# TODO? -- this doesn't work, b/c of the way it's implemented
# in selenium-webdriver. doesn't seem that critical to work around.
it.skip 'rejection is also passed down chain', (done) ->
$('.does-not-match').getText()
.then (expectedErr) ->
assert /does-not-match/.test(expectedErr?.message)
done()
# (alternative to above)
it 'chained methods causes error to be thrown', (done) ->
$('.does-not-match').getText()
assertUncaught /does-not-match/, done
describe 'all', ->
it 'returns all matching elements', (done) ->
$.all('p').then (elements) ->
assert.equal elements.length, 2
done()
, (err) ->
done err
it 'returns empty array when no matching elements', (done) ->
$.all('section').then (elements) ->
assert.equal elements.length, 0
done()
, (err) ->
done err
| true | assert = require 'assert'
path = require 'path'
webdriver = require 'selenium-webdriver'
webdriverSizzle = require '..'
{WebElement} = webdriver
{Deferred} = webdriver.promise
url = (page) ->
"file://#{path.join __dirname, page}"
# hack to work around then not working below,
# hijack mocha's uncaughtException handler.
assertUncaught = (regex, done) ->
listeners = process.listeners 'uncaughtException'
process.removeAllListeners 'uncaughtException'
process.once 'uncaughtException', (err) ->
listeners.forEach (listener) -> process.on 'uncaughtException', listener
assert regex.test err.message, "#{err.message} doesn't match #{regex}"
done()
describe 'webdriver-sizzle', ->
$ = null
driver = null
before ->
chromeCapabilities = webdriver.Capabilities.chrome()
chromeCapabilities.set('chromeOptions', {args: ['--headless']})
driver = new webdriver.Builder()
.forBrowser('chrome')
.withCapabilities(chromeCapabilities)
.build()
@timeout 0 # this may take a while in CI
describe 'once driving a webdriver Builder', ->
before (done) ->
$ = webdriverSizzle(driver)
driver.get(url 'finnegan.html').then -> done()
describe 'calling with a CSS selector', ->
it 'returns the first matching webdriver element', (done) ->
$('.test-el').then (el) ->
assert (el instanceof WebElement), 'is a WebElement'
el.getText().then (text) ->
assert.equal text, "The following text is an excerpt from Finnegan's Wake by PI:NAME:<NAME>END_PI"
done()
it 'can also be chained', (done) ->
$('.test-el').getText().then (text) ->
assert.equal text, "The following text is an excerpt from Finnegan's Wake by PI:NAME:<NAME>END_PI"
done()
describe 'that matches no elements', ->
it 'rejects with an error that includes the selector', (done) ->
$('.does-not-match')
.catch (expectedErr) ->
assert /does-not-match/.test(expectedErr?.message)
done()
# TODO? -- this doesn't work, b/c of the way it's implemented
# in selenium-webdriver. doesn't seem that critical to work around.
it.skip 'rejection is also passed down chain', (done) ->
$('.does-not-match').getText()
.then (expectedErr) ->
assert /does-not-match/.test(expectedErr?.message)
done()
# (alternative to above)
it 'chained methods causes error to be thrown', (done) ->
$('.does-not-match').getText()
assertUncaught /does-not-match/, done
describe 'all', ->
it 'returns all matching elements', (done) ->
$.all('p').then (elements) ->
assert.equal elements.length, 2
done()
, (err) ->
done err
it 'returns empty array when no matching elements', (done) ->
$.all('section').then (elements) ->
assert.equal elements.length, 0
done()
, (err) ->
done err
|
[
{
"context": "\n return if error\n\n me.set({\n password: attrs.password1\n name: attrs.name\n email: @trialRequest",
"end": 13385,
"score": 0.9985983371734619,
"start": 13370,
"tag": "PASSWORD",
"value": "attrs.password1"
},
{
"context": "Anonymous = {\n type: 'object'\n required: [\n 'fullName', 'email', 'role', 'numStudents', 'numStudentsTot",
"end": 16275,
"score": 0.7154537439346313,
"start": 16267,
"tag": "NAME",
"value": "fullName"
},
{
"context": "Schema = {\n type: 'object'\n required: ['name', 'password1', 'password2']\n properties:\n name: { type: '",
"end": 17107,
"score": 0.8557948470115662,
"start": 17099,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "type: 'object'\n required: ['name', 'password1', 'password2']\n properties:\n name: { type: 'string' }\n ",
"end": 17121,
"score": 0.897406280040741,
"start": 17112,
"tag": "PASSWORD",
"value": "password2"
}
] | app/views/teachers/RequestQuoteView.coffee | mjaqueFL/codecombat | 0 | require('app/styles/teachers/teacher-trial-requests.sass')
RootView = require 'views/core/RootView'
forms = require 'core/forms'
TrialRequest = require 'models/TrialRequest'
TrialRequests = require 'collections/TrialRequests'
AuthModal = require 'views/core/AuthModal'
errors = require 'core/errors'
ConfirmModal = require 'views/core/ConfirmModal'
User = require 'models/User'
algolia = require 'core/services/algolia'
State = require 'models/State'
parseFullName = require('parse-full-name').parseFullName
countryList = require('country-list')()
UsaStates = require('usa-states').UsaStates
SIGNUP_REDIRECT = '/teachers'
DISTRICT_NCES_KEYS = ['district', 'district_id', 'district_schools', 'district_students', 'phone']
SCHOOL_NCES_KEYS = DISTRICT_NCES_KEYS.concat(['id', 'name', 'students'])
module.exports = class RequestQuoteView extends RootView
id: 'request-quote-view'
template: require 'app/templates/teachers/request-quote-view'
logoutRedirectURL: null
events:
'change #request-form': 'onChangeRequestForm'
'submit #request-form': 'onSubmitRequestForm'
'change input[name="city"]': 'invalidateNCES'
'change input[name="state"]': 'invalidateNCES'
'change select[name="state"]': 'invalidateNCES'
'change input[name="district"]': 'invalidateNCES'
'change select[name="country"]': 'onChangeCountry'
'click #email-exists-login-link': 'onClickEmailExistsLoginLink'
'submit #signup-form': 'onSubmitSignupForm'
'click #logout-link': -> me.logout()
'click #gplus-signup-btn': 'onClickGPlusSignupButton'
'click #facebook-signup-btn': 'onClickFacebookSignupButton'
'change input[name="email"]': 'onChangeEmail'
'change input[name="name"]': 'onChangeName'
'click #submit-request-btn': 'onClickRequestButton'
getTitle: -> $.i18n.t('new_home.request_quote')
initialize: ->
@trialRequest = new TrialRequest()
@trialRequests = new TrialRequests()
@trialRequests.fetchOwn()
@supermodel.trackCollection(@trialRequests)
@formChanged = false
window.tracker?.trackEvent 'Teachers Request Demo Loaded', category: 'Teachers'
@state = new State {
suggestedNameText: '...'
checkEmailState: 'standby' # 'checking', 'exists', 'available'
checkEmailValue: null
checkEmailPromise: null
checkNameState: 'standby' # same
checkNameValue: null
checkNamePromise: null
authModalInitialValues: {}
showUsaStateDropdown: true
stateValue: null
}
@countries = countryList.getNames()
@usaStates = new UsaStates().states
@usaStatesAbbreviations = new UsaStates().arrayOf('abbreviations')
@listenTo @state, 'change:checkEmailState', -> @renderSelectors('.email-check')
@listenTo @state, 'change:checkNameState', -> @renderSelectors('.name-check')
@listenTo @state, 'change:error', -> @renderSelectors('.error-area')
@listenTo @state, 'change:showUsaStateDropdown', -> @renderSelectors('.state')
@listenTo @state, 'change:stateValue', -> @renderSelectors('.state')
onLeaveMessage: ->
if @formChanged
return 'Your request has not been submitted! If you continue, your changes will be lost.'
onLoaded: ->
if @trialRequests.size()
@trialRequest = @trialRequests.first()
@state.set({
authModalInitialValues: {
email: @trialRequest?.get('properties')?.email
}
})
super()
invalidateNCES: ->
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val ''
onChangeCountry: (e) ->
@invalidateNCES()
stateElem = @$('select[name="state"]')
if @$('[name="state"]').prop('nodeName') == 'INPUT'
stateElem = @$('input[name="state"]')
stateVal = stateElem.val()
@state.set({stateValue: stateVal})
if e.target.value == 'United States'
@state.set({showUsaStateDropdown: true})
if !@usaStatesAbbreviations.includes(stateVal)
@state.set({stateValue: ''})
else
@state.set({showUsaStateDropdown: false})
afterRender: ->
super()
# apply existing trial request on form
properties = @trialRequest.get('properties')
if properties
forms.objectToForm(@$('#request-form'), properties)
$("#organization-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'name',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='school'> #{hr.name.value} </div>" +
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="district"]').val suggestion.district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeRequestForm()
$("#district-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'district',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="organization"]').val '' # TODO: does not persist on tabbing: back to school, back to district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in DISTRICT_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeRequestForm()
onChangeRequestForm: ->
unless @formChanged
window.tracker?.trackEvent 'Teachers Request Demo Form Started', category: 'Teachers'
@formChanged = true
onClickRequestButton: (e) ->
eventAction = $(e.target).data('event-action')
if eventAction
window.tracker?.trackEvent(eventAction, category: 'Teachers')
onSubmitRequestForm: (e) ->
e.preventDefault()
form = @$('#request-form')
attrs = forms.formToObject(form)
trialRequestAttrs = _.cloneDeep(attrs)
# Don't save n/a district entries, but do validate required district client-side
trialRequestAttrs = _.omit(trialRequestAttrs, 'district') if trialRequestAttrs.district?.replace(/\s/ig, '').match(/n\/a/ig)
forms.clearFormAlerts(form)
requestFormSchema = if me.isAnonymous() then requestFormSchemaAnonymous else requestFormSchemaLoggedIn
result = tv4.validateMultiple(trialRequestAttrs, requestFormSchemaAnonymous)
error = false
if not result.valid
forms.applyErrorsToForm(form, result.errors)
error = true
if not error and not forms.validateEmail(trialRequestAttrs.email)
forms.setErrorToProperty(form, 'email', 'invalid email')
error = true
unless attrs.district
forms.setErrorToProperty(form, 'district', $.i18n.t('common.required_field'))
error = true
trialRequestAttrs['siteOrigin'] = 'demo request'
try
parsedName = parseFullName(trialRequestAttrs['fullName'], 'all', -1, true)
if parsedName.first and parsedName.last
trialRequestAttrs['firstName'] = parsedName.first
trialRequestAttrs['lastName'] = parsedName.last
catch e
# TODO handle_error_ozaria
if not trialRequestAttrs['firstName'] or not trialRequestAttrs['lastName']
error = true
forms.clearFormAlerts($('#full-name'))
forms.setErrorToProperty(form, 'fullName', $.i18n.t('teachers_quote.full_name_required'))
if error
forms.scrollToFirstError()
return
@trialRequest = new TrialRequest({
type: 'course'
properties: trialRequestAttrs
})
if me.get('role') is 'student' and not me.isAnonymous()
modal = new ConfirmModal({
title: ''
body: "<p>#{$.i18n.t('teachers_quote.conversion_warning')}</p><p>#{$.i18n.t('teachers_quote.learn_more_modal')}</p>"
confirm: $.i18n.t('common.continue')
decline: $.i18n.t('common.cancel')
})
@openModalView(modal)
modal.once('confirm', (->
modal.hide()
@saveTrialRequest()
), @)
else
@saveTrialRequest()
saveTrialRequest: ->
@trialRequest.notyErrors = false
@$('#submit-request-btn').text('Sending').attr('disabled', true)
@trialRequest.save()
@trialRequest.on 'sync', @onTrialRequestSubmit, @
@trialRequest.on 'error', @onTrialRequestError, @
onTrialRequestError: (model, jqxhr) ->
@$('#submit-request-btn').text('Submit').attr('disabled', false)
if jqxhr.status is 409
userExists = $.i18n.t('teachers_quote.email_exists')
logIn = $.i18n.t('login.log_in')
@$('#email-form-group')
.addClass('has-error')
.append($("<div class='help-block error-help-block'>#{userExists} <a id='email-exists-login-link'>#{logIn}</a>"))
forms.scrollToFirstError()
else
errors.showNotyNetworkError(arguments...)
onClickEmailExistsLoginLink: ->
@openModalView(new AuthModal({ initialValues: @state.get('authModalInitialValues') }))
onTrialRequestSubmit: ->
window.tracker?.trackEvent 'Teachers Request Demo Form Submitted', category: 'Teachers'
@formChanged = false
trialRequestProperties = @trialRequest.get('properties')
me.setRole trialRequestProperties.role.toLowerCase(), true
defaultName = [trialRequestProperties.firstName, trialRequestProperties.lastName].join(' ')
@$('input[name="name"]').val(defaultName)
@$('#request-form, #form-submit-success').toggleClass('hide')
@scrollToTop(0)
$('#flying-focus').css({top: 0, left: 0}) # Hack copied from Router.coffee#187. Ideally we'd swap out the view and have view-swapping logic handle this
onClickGPlusSignupButton: ->
btn = @$('#gplus-signup-btn')
btn.attr('disabled', true)
application.gplusHandler.loadAPI({
context: @
success: ->
btn.attr('disabled', false)
application.gplusHandler.connect({
context: @
success: ->
btn.find('.sign-in-blurb').text($.i18n.t('signup.creating'))
btn.attr('disabled', true)
application.gplusHandler.loadPerson({
context: @
success: (gplusAttrs) ->
me.set(gplusAttrs)
me.save(null, {
url: "/db/user?gplusID=#{gplusAttrs.gplusID}&gplusAccessToken=#{application.gplusHandler.token()}"
type: 'PUT'
success: ->
window.tracker?.trackEvent 'Teachers Request Demo Create Account Google', category: 'Teachers'
application.router.navigate(SIGNUP_REDIRECT)
window.location.reload()
error: errors.showNotyNetworkError
})
})
})
})
onClickFacebookSignupButton: ->
btn = @$('#facebook-signup-btn')
btn.attr('disabled', true)
application.facebookHandler.loadAPI({
context: @
success: ->
btn.attr('disabled', false)
application.facebookHandler.connect({
context: @
success: ->
btn.find('.sign-in-blurb').text($.i18n.t('signup.creating'))
btn.attr('disabled', true)
application.facebookHandler.loadPerson({
context: @
success: (facebookAttrs) ->
me.set(facebookAttrs)
me.save(null, {
url: "/db/user?facebookID=#{facebookAttrs.facebookID}&facebookAccessToken=#{application.facebookHandler.token()}"
type: 'PUT'
success: ->
window.tracker?.trackEvent 'Teachers Request Demo Create Account Facebook', category: 'Teachers'
application.router.navigate(SIGNUP_REDIRECT)
window.location.reload()
error: errors.showNotyNetworkError
})
})
})
})
onSubmitSignupForm: (e) ->
e.preventDefault()
form = @$('#signup-form')
attrs = forms.formToObject(form)
forms.clearFormAlerts(form)
result = tv4.validateMultiple(attrs, signupFormSchema)
error = false
if not result.valid
forms.applyErrorsToForm(form, result.errors)
error = true
if attrs.password1 isnt attrs.password2
forms.setErrorToProperty(form, 'password1', 'Passwords do not match')
error = true
return if error
me.set({
password: attrs.password1
name: attrs.name
email: @trialRequest.get('properties').email
})
if me.inEU()
emails = _.assign({}, me.get('emails'))
emails.generalNews ?= {}
emails.generalNews.enabled = false
me.set('emails', emails)
me.set('unsubscribedFromMarketingEmails', true)
me.save(null, {
success: ->
window.tracker?.trackEvent 'Teachers Request Demo Create Account', category: 'Teachers'
application.router.navigate(SIGNUP_REDIRECT)
window.location.reload()
error: errors.showNotyNetworkError
})
updateAuthModalInitialValues: (values) ->
@state.set {
authModalInitialValues: _.merge @state.get('authModalInitialValues'), values
}, { silent: true }
onChangeName: (e) ->
@updateAuthModalInitialValues { name: @$(e.currentTarget).val() }
@checkName()
checkName: ->
name = @$('input[name="name"]').val()
if name is @state.get('checkNameValue')
return @state.get('checkNamePromise')
if not name
@state.set({
checkNameState: 'standby'
checkNameValue: name
checkNamePromise: null
})
return Promise.resolve()
@state.set({
checkNameState: 'checking'
checkNameValue: name
checkNamePromise: (User.checkNameConflicts(name)
.then ({ suggestedName, conflicts }) =>
return unless name is @$('input[name="name"]').val()
if conflicts
suggestedNameText = $.i18n.t('signup.name_taken').replace('{{suggestedName}}', suggestedName)
@state.set({ checkNameState: 'exists', suggestedNameText })
else
@state.set { checkNameState: 'available' }
.catch (error) =>
@state.set('checkNameState', 'standby')
throw error
)
})
return @state.get('checkNamePromise')
onChangeEmail: (e) ->
@updateAuthModalInitialValues { email: @$(e.currentTarget).val() }
@checkEmail()
checkEmail: ->
email = @$('[name="email"]').val()
if not _.isEmpty(email) and email is @state.get('checkEmailValue')
return @state.get('checkEmailPromise')
if not (email and forms.validateEmail(email))
@state.set({
checkEmailState: 'standby'
checkEmailValue: email
checkEmailPromise: null
})
return Promise.resolve()
@state.set({
checkEmailState: 'checking'
checkEmailValue: email
checkEmailPromise: (User.checkEmailExists(email)
.then ({exists}) =>
return unless email is @$('[name="email"]').val()
if exists
@state.set('checkEmailState', 'exists')
else
@state.set('checkEmailState', 'available')
.catch (e) =>
@state.set('checkEmailState', 'standby')
throw e
)
})
return @state.get('checkEmailPromise')
requestFormSchemaAnonymous = {
type: 'object'
required: [
'fullName', 'email', 'role', 'numStudents', 'numStudentsTotal', 'city', 'state',
'country', 'organization', 'phoneNumber'
]
properties:
fullName: { type: 'string' }
email: { type: 'string', format: 'email' }
phoneNumber: { type: 'string' }
role: { type: 'string' }
organization: { type: 'string' }
district: { type: 'string' }
city: { type: 'string' }
state: { type: 'string' }
country: { type: 'string' }
numStudents: { type: 'string' }
numStudentsTotal: { type: 'string' }
}
for key in SCHOOL_NCES_KEYS
requestFormSchemaAnonymous['nces_' + key] = type: 'string'
# same form, but add username input
requestFormSchemaLoggedIn = _.cloneDeep(requestFormSchemaAnonymous)
requestFormSchemaLoggedIn.required.push('name')
signupFormSchema = {
type: 'object'
required: ['name', 'password1', 'password2']
properties:
name: { type: 'string' }
password1: { type: 'string' }
password2: { type: 'string' }
}
| 28392 | require('app/styles/teachers/teacher-trial-requests.sass')
RootView = require 'views/core/RootView'
forms = require 'core/forms'
TrialRequest = require 'models/TrialRequest'
TrialRequests = require 'collections/TrialRequests'
AuthModal = require 'views/core/AuthModal'
errors = require 'core/errors'
ConfirmModal = require 'views/core/ConfirmModal'
User = require 'models/User'
algolia = require 'core/services/algolia'
State = require 'models/State'
parseFullName = require('parse-full-name').parseFullName
countryList = require('country-list')()
UsaStates = require('usa-states').UsaStates
SIGNUP_REDIRECT = '/teachers'
DISTRICT_NCES_KEYS = ['district', 'district_id', 'district_schools', 'district_students', 'phone']
SCHOOL_NCES_KEYS = DISTRICT_NCES_KEYS.concat(['id', 'name', 'students'])
module.exports = class RequestQuoteView extends RootView
id: 'request-quote-view'
template: require 'app/templates/teachers/request-quote-view'
logoutRedirectURL: null
events:
'change #request-form': 'onChangeRequestForm'
'submit #request-form': 'onSubmitRequestForm'
'change input[name="city"]': 'invalidateNCES'
'change input[name="state"]': 'invalidateNCES'
'change select[name="state"]': 'invalidateNCES'
'change input[name="district"]': 'invalidateNCES'
'change select[name="country"]': 'onChangeCountry'
'click #email-exists-login-link': 'onClickEmailExistsLoginLink'
'submit #signup-form': 'onSubmitSignupForm'
'click #logout-link': -> me.logout()
'click #gplus-signup-btn': 'onClickGPlusSignupButton'
'click #facebook-signup-btn': 'onClickFacebookSignupButton'
'change input[name="email"]': 'onChangeEmail'
'change input[name="name"]': 'onChangeName'
'click #submit-request-btn': 'onClickRequestButton'
getTitle: -> $.i18n.t('new_home.request_quote')
initialize: ->
@trialRequest = new TrialRequest()
@trialRequests = new TrialRequests()
@trialRequests.fetchOwn()
@supermodel.trackCollection(@trialRequests)
@formChanged = false
window.tracker?.trackEvent 'Teachers Request Demo Loaded', category: 'Teachers'
@state = new State {
suggestedNameText: '...'
checkEmailState: 'standby' # 'checking', 'exists', 'available'
checkEmailValue: null
checkEmailPromise: null
checkNameState: 'standby' # same
checkNameValue: null
checkNamePromise: null
authModalInitialValues: {}
showUsaStateDropdown: true
stateValue: null
}
@countries = countryList.getNames()
@usaStates = new UsaStates().states
@usaStatesAbbreviations = new UsaStates().arrayOf('abbreviations')
@listenTo @state, 'change:checkEmailState', -> @renderSelectors('.email-check')
@listenTo @state, 'change:checkNameState', -> @renderSelectors('.name-check')
@listenTo @state, 'change:error', -> @renderSelectors('.error-area')
@listenTo @state, 'change:showUsaStateDropdown', -> @renderSelectors('.state')
@listenTo @state, 'change:stateValue', -> @renderSelectors('.state')
onLeaveMessage: ->
if @formChanged
return 'Your request has not been submitted! If you continue, your changes will be lost.'
onLoaded: ->
if @trialRequests.size()
@trialRequest = @trialRequests.first()
@state.set({
authModalInitialValues: {
email: @trialRequest?.get('properties')?.email
}
})
super()
invalidateNCES: ->
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val ''
onChangeCountry: (e) ->
@invalidateNCES()
stateElem = @$('select[name="state"]')
if @$('[name="state"]').prop('nodeName') == 'INPUT'
stateElem = @$('input[name="state"]')
stateVal = stateElem.val()
@state.set({stateValue: stateVal})
if e.target.value == 'United States'
@state.set({showUsaStateDropdown: true})
if !@usaStatesAbbreviations.includes(stateVal)
@state.set({stateValue: ''})
else
@state.set({showUsaStateDropdown: false})
afterRender: ->
super()
# apply existing trial request on form
properties = @trialRequest.get('properties')
if properties
forms.objectToForm(@$('#request-form'), properties)
$("#organization-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'name',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='school'> #{hr.name.value} </div>" +
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="district"]').val suggestion.district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeRequestForm()
$("#district-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'district',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="organization"]').val '' # TODO: does not persist on tabbing: back to school, back to district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in DISTRICT_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeRequestForm()
onChangeRequestForm: ->
unless @formChanged
window.tracker?.trackEvent 'Teachers Request Demo Form Started', category: 'Teachers'
@formChanged = true
onClickRequestButton: (e) ->
eventAction = $(e.target).data('event-action')
if eventAction
window.tracker?.trackEvent(eventAction, category: 'Teachers')
onSubmitRequestForm: (e) ->
e.preventDefault()
form = @$('#request-form')
attrs = forms.formToObject(form)
trialRequestAttrs = _.cloneDeep(attrs)
# Don't save n/a district entries, but do validate required district client-side
trialRequestAttrs = _.omit(trialRequestAttrs, 'district') if trialRequestAttrs.district?.replace(/\s/ig, '').match(/n\/a/ig)
forms.clearFormAlerts(form)
requestFormSchema = if me.isAnonymous() then requestFormSchemaAnonymous else requestFormSchemaLoggedIn
result = tv4.validateMultiple(trialRequestAttrs, requestFormSchemaAnonymous)
error = false
if not result.valid
forms.applyErrorsToForm(form, result.errors)
error = true
if not error and not forms.validateEmail(trialRequestAttrs.email)
forms.setErrorToProperty(form, 'email', 'invalid email')
error = true
unless attrs.district
forms.setErrorToProperty(form, 'district', $.i18n.t('common.required_field'))
error = true
trialRequestAttrs['siteOrigin'] = 'demo request'
try
parsedName = parseFullName(trialRequestAttrs['fullName'], 'all', -1, true)
if parsedName.first and parsedName.last
trialRequestAttrs['firstName'] = parsedName.first
trialRequestAttrs['lastName'] = parsedName.last
catch e
# TODO handle_error_ozaria
if not trialRequestAttrs['firstName'] or not trialRequestAttrs['lastName']
error = true
forms.clearFormAlerts($('#full-name'))
forms.setErrorToProperty(form, 'fullName', $.i18n.t('teachers_quote.full_name_required'))
if error
forms.scrollToFirstError()
return
@trialRequest = new TrialRequest({
type: 'course'
properties: trialRequestAttrs
})
if me.get('role') is 'student' and not me.isAnonymous()
modal = new ConfirmModal({
title: ''
body: "<p>#{$.i18n.t('teachers_quote.conversion_warning')}</p><p>#{$.i18n.t('teachers_quote.learn_more_modal')}</p>"
confirm: $.i18n.t('common.continue')
decline: $.i18n.t('common.cancel')
})
@openModalView(modal)
modal.once('confirm', (->
modal.hide()
@saveTrialRequest()
), @)
else
@saveTrialRequest()
saveTrialRequest: ->
@trialRequest.notyErrors = false
@$('#submit-request-btn').text('Sending').attr('disabled', true)
@trialRequest.save()
@trialRequest.on 'sync', @onTrialRequestSubmit, @
@trialRequest.on 'error', @onTrialRequestError, @
onTrialRequestError: (model, jqxhr) ->
@$('#submit-request-btn').text('Submit').attr('disabled', false)
if jqxhr.status is 409
userExists = $.i18n.t('teachers_quote.email_exists')
logIn = $.i18n.t('login.log_in')
@$('#email-form-group')
.addClass('has-error')
.append($("<div class='help-block error-help-block'>#{userExists} <a id='email-exists-login-link'>#{logIn}</a>"))
forms.scrollToFirstError()
else
errors.showNotyNetworkError(arguments...)
onClickEmailExistsLoginLink: ->
@openModalView(new AuthModal({ initialValues: @state.get('authModalInitialValues') }))
onTrialRequestSubmit: ->
window.tracker?.trackEvent 'Teachers Request Demo Form Submitted', category: 'Teachers'
@formChanged = false
trialRequestProperties = @trialRequest.get('properties')
me.setRole trialRequestProperties.role.toLowerCase(), true
defaultName = [trialRequestProperties.firstName, trialRequestProperties.lastName].join(' ')
@$('input[name="name"]').val(defaultName)
@$('#request-form, #form-submit-success').toggleClass('hide')
@scrollToTop(0)
$('#flying-focus').css({top: 0, left: 0}) # Hack copied from Router.coffee#187. Ideally we'd swap out the view and have view-swapping logic handle this
onClickGPlusSignupButton: ->
btn = @$('#gplus-signup-btn')
btn.attr('disabled', true)
application.gplusHandler.loadAPI({
context: @
success: ->
btn.attr('disabled', false)
application.gplusHandler.connect({
context: @
success: ->
btn.find('.sign-in-blurb').text($.i18n.t('signup.creating'))
btn.attr('disabled', true)
application.gplusHandler.loadPerson({
context: @
success: (gplusAttrs) ->
me.set(gplusAttrs)
me.save(null, {
url: "/db/user?gplusID=#{gplusAttrs.gplusID}&gplusAccessToken=#{application.gplusHandler.token()}"
type: 'PUT'
success: ->
window.tracker?.trackEvent 'Teachers Request Demo Create Account Google', category: 'Teachers'
application.router.navigate(SIGNUP_REDIRECT)
window.location.reload()
error: errors.showNotyNetworkError
})
})
})
})
onClickFacebookSignupButton: ->
btn = @$('#facebook-signup-btn')
btn.attr('disabled', true)
application.facebookHandler.loadAPI({
context: @
success: ->
btn.attr('disabled', false)
application.facebookHandler.connect({
context: @
success: ->
btn.find('.sign-in-blurb').text($.i18n.t('signup.creating'))
btn.attr('disabled', true)
application.facebookHandler.loadPerson({
context: @
success: (facebookAttrs) ->
me.set(facebookAttrs)
me.save(null, {
url: "/db/user?facebookID=#{facebookAttrs.facebookID}&facebookAccessToken=#{application.facebookHandler.token()}"
type: 'PUT'
success: ->
window.tracker?.trackEvent 'Teachers Request Demo Create Account Facebook', category: 'Teachers'
application.router.navigate(SIGNUP_REDIRECT)
window.location.reload()
error: errors.showNotyNetworkError
})
})
})
})
onSubmitSignupForm: (e) ->
e.preventDefault()
form = @$('#signup-form')
attrs = forms.formToObject(form)
forms.clearFormAlerts(form)
result = tv4.validateMultiple(attrs, signupFormSchema)
error = false
if not result.valid
forms.applyErrorsToForm(form, result.errors)
error = true
if attrs.password1 isnt attrs.password2
forms.setErrorToProperty(form, 'password1', 'Passwords do not match')
error = true
return if error
me.set({
password: <PASSWORD>
name: attrs.name
email: @trialRequest.get('properties').email
})
if me.inEU()
emails = _.assign({}, me.get('emails'))
emails.generalNews ?= {}
emails.generalNews.enabled = false
me.set('emails', emails)
me.set('unsubscribedFromMarketingEmails', true)
me.save(null, {
success: ->
window.tracker?.trackEvent 'Teachers Request Demo Create Account', category: 'Teachers'
application.router.navigate(SIGNUP_REDIRECT)
window.location.reload()
error: errors.showNotyNetworkError
})
updateAuthModalInitialValues: (values) ->
@state.set {
authModalInitialValues: _.merge @state.get('authModalInitialValues'), values
}, { silent: true }
onChangeName: (e) ->
@updateAuthModalInitialValues { name: @$(e.currentTarget).val() }
@checkName()
checkName: ->
name = @$('input[name="name"]').val()
if name is @state.get('checkNameValue')
return @state.get('checkNamePromise')
if not name
@state.set({
checkNameState: 'standby'
checkNameValue: name
checkNamePromise: null
})
return Promise.resolve()
@state.set({
checkNameState: 'checking'
checkNameValue: name
checkNamePromise: (User.checkNameConflicts(name)
.then ({ suggestedName, conflicts }) =>
return unless name is @$('input[name="name"]').val()
if conflicts
suggestedNameText = $.i18n.t('signup.name_taken').replace('{{suggestedName}}', suggestedName)
@state.set({ checkNameState: 'exists', suggestedNameText })
else
@state.set { checkNameState: 'available' }
.catch (error) =>
@state.set('checkNameState', 'standby')
throw error
)
})
return @state.get('checkNamePromise')
onChangeEmail: (e) ->
@updateAuthModalInitialValues { email: @$(e.currentTarget).val() }
@checkEmail()
checkEmail: ->
email = @$('[name="email"]').val()
if not _.isEmpty(email) and email is @state.get('checkEmailValue')
return @state.get('checkEmailPromise')
if not (email and forms.validateEmail(email))
@state.set({
checkEmailState: 'standby'
checkEmailValue: email
checkEmailPromise: null
})
return Promise.resolve()
@state.set({
checkEmailState: 'checking'
checkEmailValue: email
checkEmailPromise: (User.checkEmailExists(email)
.then ({exists}) =>
return unless email is @$('[name="email"]').val()
if exists
@state.set('checkEmailState', 'exists')
else
@state.set('checkEmailState', 'available')
.catch (e) =>
@state.set('checkEmailState', 'standby')
throw e
)
})
return @state.get('checkEmailPromise')
requestFormSchemaAnonymous = {
type: 'object'
required: [
'<NAME>', 'email', 'role', 'numStudents', 'numStudentsTotal', 'city', 'state',
'country', 'organization', 'phoneNumber'
]
properties:
fullName: { type: 'string' }
email: { type: 'string', format: 'email' }
phoneNumber: { type: 'string' }
role: { type: 'string' }
organization: { type: 'string' }
district: { type: 'string' }
city: { type: 'string' }
state: { type: 'string' }
country: { type: 'string' }
numStudents: { type: 'string' }
numStudentsTotal: { type: 'string' }
}
for key in SCHOOL_NCES_KEYS
requestFormSchemaAnonymous['nces_' + key] = type: 'string'
# same form, but add username input
requestFormSchemaLoggedIn = _.cloneDeep(requestFormSchemaAnonymous)
requestFormSchemaLoggedIn.required.push('name')
signupFormSchema = {
type: 'object'
required: ['name', '<PASSWORD>1', '<PASSWORD>']
properties:
name: { type: 'string' }
password1: { type: 'string' }
password2: { type: 'string' }
}
| true | require('app/styles/teachers/teacher-trial-requests.sass')
RootView = require 'views/core/RootView'
forms = require 'core/forms'
TrialRequest = require 'models/TrialRequest'
TrialRequests = require 'collections/TrialRequests'
AuthModal = require 'views/core/AuthModal'
errors = require 'core/errors'
ConfirmModal = require 'views/core/ConfirmModal'
User = require 'models/User'
algolia = require 'core/services/algolia'
State = require 'models/State'
parseFullName = require('parse-full-name').parseFullName
countryList = require('country-list')()
UsaStates = require('usa-states').UsaStates
SIGNUP_REDIRECT = '/teachers'
DISTRICT_NCES_KEYS = ['district', 'district_id', 'district_schools', 'district_students', 'phone']
SCHOOL_NCES_KEYS = DISTRICT_NCES_KEYS.concat(['id', 'name', 'students'])
module.exports = class RequestQuoteView extends RootView
id: 'request-quote-view'
template: require 'app/templates/teachers/request-quote-view'
logoutRedirectURL: null
events:
'change #request-form': 'onChangeRequestForm'
'submit #request-form': 'onSubmitRequestForm'
'change input[name="city"]': 'invalidateNCES'
'change input[name="state"]': 'invalidateNCES'
'change select[name="state"]': 'invalidateNCES'
'change input[name="district"]': 'invalidateNCES'
'change select[name="country"]': 'onChangeCountry'
'click #email-exists-login-link': 'onClickEmailExistsLoginLink'
'submit #signup-form': 'onSubmitSignupForm'
'click #logout-link': -> me.logout()
'click #gplus-signup-btn': 'onClickGPlusSignupButton'
'click #facebook-signup-btn': 'onClickFacebookSignupButton'
'change input[name="email"]': 'onChangeEmail'
'change input[name="name"]': 'onChangeName'
'click #submit-request-btn': 'onClickRequestButton'
getTitle: -> $.i18n.t('new_home.request_quote')
initialize: ->
@trialRequest = new TrialRequest()
@trialRequests = new TrialRequests()
@trialRequests.fetchOwn()
@supermodel.trackCollection(@trialRequests)
@formChanged = false
window.tracker?.trackEvent 'Teachers Request Demo Loaded', category: 'Teachers'
@state = new State {
suggestedNameText: '...'
checkEmailState: 'standby' # 'checking', 'exists', 'available'
checkEmailValue: null
checkEmailPromise: null
checkNameState: 'standby' # same
checkNameValue: null
checkNamePromise: null
authModalInitialValues: {}
showUsaStateDropdown: true
stateValue: null
}
@countries = countryList.getNames()
@usaStates = new UsaStates().states
@usaStatesAbbreviations = new UsaStates().arrayOf('abbreviations')
@listenTo @state, 'change:checkEmailState', -> @renderSelectors('.email-check')
@listenTo @state, 'change:checkNameState', -> @renderSelectors('.name-check')
@listenTo @state, 'change:error', -> @renderSelectors('.error-area')
@listenTo @state, 'change:showUsaStateDropdown', -> @renderSelectors('.state')
@listenTo @state, 'change:stateValue', -> @renderSelectors('.state')
onLeaveMessage: ->
if @formChanged
return 'Your request has not been submitted! If you continue, your changes will be lost.'
onLoaded: ->
if @trialRequests.size()
@trialRequest = @trialRequests.first()
@state.set({
authModalInitialValues: {
email: @trialRequest?.get('properties')?.email
}
})
super()
invalidateNCES: ->
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val ''
onChangeCountry: (e) ->
@invalidateNCES()
stateElem = @$('select[name="state"]')
if @$('[name="state"]').prop('nodeName') == 'INPUT'
stateElem = @$('input[name="state"]')
stateVal = stateElem.val()
@state.set({stateValue: stateVal})
if e.target.value == 'United States'
@state.set({showUsaStateDropdown: true})
if !@usaStatesAbbreviations.includes(stateVal)
@state.set({stateValue: ''})
else
@state.set({showUsaStateDropdown: false})
afterRender: ->
super()
# apply existing trial request on form
properties = @trialRequest.get('properties')
if properties
forms.objectToForm(@$('#request-form'), properties)
$("#organization-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'name',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='school'> #{hr.name.value} </div>" +
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="district"]').val suggestion.district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in SCHOOL_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeRequestForm()
$("#district-control").algolia_autocomplete({hint: false}, [
source: (query, callback) ->
algolia.schoolsIndex.search(query, { hitsPerPage: 5, aroundLatLngViaIP: false }).then (answer) ->
callback answer.hits
, ->
callback []
displayKey: 'district',
templates:
suggestion: (suggestion) ->
hr = suggestion._highlightResult
"<div class='district'>#{hr.district.value}, " +
"<span>#{hr.city?.value}, #{hr.state.value}</span></div>"
]).on 'autocomplete:selected', (event, suggestion, dataset) =>
@$('input[name="organization"]').val '' # TODO: does not persist on tabbing: back to school, back to district
@$('input[name="city"]').val suggestion.city
@$('input[name="state"]').val suggestion.state
@$('select[name="state"]').val suggestion.state
@$('select[name="country"]').val 'United States'
@state.set({showUsaStateDropdown: true})
@state.set({stateValue: suggestion.state})
for key in DISTRICT_NCES_KEYS
@$('input[name="nces_' + key + '"]').val suggestion[key]
@onChangeRequestForm()
onChangeRequestForm: ->
unless @formChanged
window.tracker?.trackEvent 'Teachers Request Demo Form Started', category: 'Teachers'
@formChanged = true
onClickRequestButton: (e) ->
eventAction = $(e.target).data('event-action')
if eventAction
window.tracker?.trackEvent(eventAction, category: 'Teachers')
onSubmitRequestForm: (e) ->
e.preventDefault()
form = @$('#request-form')
attrs = forms.formToObject(form)
trialRequestAttrs = _.cloneDeep(attrs)
# Don't save n/a district entries, but do validate required district client-side
trialRequestAttrs = _.omit(trialRequestAttrs, 'district') if trialRequestAttrs.district?.replace(/\s/ig, '').match(/n\/a/ig)
forms.clearFormAlerts(form)
requestFormSchema = if me.isAnonymous() then requestFormSchemaAnonymous else requestFormSchemaLoggedIn
result = tv4.validateMultiple(trialRequestAttrs, requestFormSchemaAnonymous)
error = false
if not result.valid
forms.applyErrorsToForm(form, result.errors)
error = true
if not error and not forms.validateEmail(trialRequestAttrs.email)
forms.setErrorToProperty(form, 'email', 'invalid email')
error = true
unless attrs.district
forms.setErrorToProperty(form, 'district', $.i18n.t('common.required_field'))
error = true
trialRequestAttrs['siteOrigin'] = 'demo request'
try
parsedName = parseFullName(trialRequestAttrs['fullName'], 'all', -1, true)
if parsedName.first and parsedName.last
trialRequestAttrs['firstName'] = parsedName.first
trialRequestAttrs['lastName'] = parsedName.last
catch e
# TODO handle_error_ozaria
if not trialRequestAttrs['firstName'] or not trialRequestAttrs['lastName']
error = true
forms.clearFormAlerts($('#full-name'))
forms.setErrorToProperty(form, 'fullName', $.i18n.t('teachers_quote.full_name_required'))
if error
forms.scrollToFirstError()
return
@trialRequest = new TrialRequest({
type: 'course'
properties: trialRequestAttrs
})
if me.get('role') is 'student' and not me.isAnonymous()
modal = new ConfirmModal({
title: ''
body: "<p>#{$.i18n.t('teachers_quote.conversion_warning')}</p><p>#{$.i18n.t('teachers_quote.learn_more_modal')}</p>"
confirm: $.i18n.t('common.continue')
decline: $.i18n.t('common.cancel')
})
@openModalView(modal)
modal.once('confirm', (->
modal.hide()
@saveTrialRequest()
), @)
else
@saveTrialRequest()
saveTrialRequest: ->
@trialRequest.notyErrors = false
@$('#submit-request-btn').text('Sending').attr('disabled', true)
@trialRequest.save()
@trialRequest.on 'sync', @onTrialRequestSubmit, @
@trialRequest.on 'error', @onTrialRequestError, @
onTrialRequestError: (model, jqxhr) ->
@$('#submit-request-btn').text('Submit').attr('disabled', false)
if jqxhr.status is 409
userExists = $.i18n.t('teachers_quote.email_exists')
logIn = $.i18n.t('login.log_in')
@$('#email-form-group')
.addClass('has-error')
.append($("<div class='help-block error-help-block'>#{userExists} <a id='email-exists-login-link'>#{logIn}</a>"))
forms.scrollToFirstError()
else
errors.showNotyNetworkError(arguments...)
onClickEmailExistsLoginLink: ->
@openModalView(new AuthModal({ initialValues: @state.get('authModalInitialValues') }))
onTrialRequestSubmit: ->
window.tracker?.trackEvent 'Teachers Request Demo Form Submitted', category: 'Teachers'
@formChanged = false
trialRequestProperties = @trialRequest.get('properties')
me.setRole trialRequestProperties.role.toLowerCase(), true
defaultName = [trialRequestProperties.firstName, trialRequestProperties.lastName].join(' ')
@$('input[name="name"]').val(defaultName)
@$('#request-form, #form-submit-success').toggleClass('hide')
@scrollToTop(0)
$('#flying-focus').css({top: 0, left: 0}) # Hack copied from Router.coffee#187. Ideally we'd swap out the view and have view-swapping logic handle this
onClickGPlusSignupButton: ->
btn = @$('#gplus-signup-btn')
btn.attr('disabled', true)
application.gplusHandler.loadAPI({
context: @
success: ->
btn.attr('disabled', false)
application.gplusHandler.connect({
context: @
success: ->
btn.find('.sign-in-blurb').text($.i18n.t('signup.creating'))
btn.attr('disabled', true)
application.gplusHandler.loadPerson({
context: @
success: (gplusAttrs) ->
me.set(gplusAttrs)
me.save(null, {
url: "/db/user?gplusID=#{gplusAttrs.gplusID}&gplusAccessToken=#{application.gplusHandler.token()}"
type: 'PUT'
success: ->
window.tracker?.trackEvent 'Teachers Request Demo Create Account Google', category: 'Teachers'
application.router.navigate(SIGNUP_REDIRECT)
window.location.reload()
error: errors.showNotyNetworkError
})
})
})
})
onClickFacebookSignupButton: ->
btn = @$('#facebook-signup-btn')
btn.attr('disabled', true)
application.facebookHandler.loadAPI({
context: @
success: ->
btn.attr('disabled', false)
application.facebookHandler.connect({
context: @
success: ->
btn.find('.sign-in-blurb').text($.i18n.t('signup.creating'))
btn.attr('disabled', true)
application.facebookHandler.loadPerson({
context: @
success: (facebookAttrs) ->
me.set(facebookAttrs)
me.save(null, {
url: "/db/user?facebookID=#{facebookAttrs.facebookID}&facebookAccessToken=#{application.facebookHandler.token()}"
type: 'PUT'
success: ->
window.tracker?.trackEvent 'Teachers Request Demo Create Account Facebook', category: 'Teachers'
application.router.navigate(SIGNUP_REDIRECT)
window.location.reload()
error: errors.showNotyNetworkError
})
})
})
})
onSubmitSignupForm: (e) ->
e.preventDefault()
form = @$('#signup-form')
attrs = forms.formToObject(form)
forms.clearFormAlerts(form)
result = tv4.validateMultiple(attrs, signupFormSchema)
error = false
if not result.valid
forms.applyErrorsToForm(form, result.errors)
error = true
if attrs.password1 isnt attrs.password2
forms.setErrorToProperty(form, 'password1', 'Passwords do not match')
error = true
return if error
me.set({
password: PI:PASSWORD:<PASSWORD>END_PI
name: attrs.name
email: @trialRequest.get('properties').email
})
if me.inEU()
emails = _.assign({}, me.get('emails'))
emails.generalNews ?= {}
emails.generalNews.enabled = false
me.set('emails', emails)
me.set('unsubscribedFromMarketingEmails', true)
me.save(null, {
success: ->
window.tracker?.trackEvent 'Teachers Request Demo Create Account', category: 'Teachers'
application.router.navigate(SIGNUP_REDIRECT)
window.location.reload()
error: errors.showNotyNetworkError
})
updateAuthModalInitialValues: (values) ->
@state.set {
authModalInitialValues: _.merge @state.get('authModalInitialValues'), values
}, { silent: true }
onChangeName: (e) ->
@updateAuthModalInitialValues { name: @$(e.currentTarget).val() }
@checkName()
checkName: ->
name = @$('input[name="name"]').val()
if name is @state.get('checkNameValue')
return @state.get('checkNamePromise')
if not name
@state.set({
checkNameState: 'standby'
checkNameValue: name
checkNamePromise: null
})
return Promise.resolve()
@state.set({
checkNameState: 'checking'
checkNameValue: name
checkNamePromise: (User.checkNameConflicts(name)
.then ({ suggestedName, conflicts }) =>
return unless name is @$('input[name="name"]').val()
if conflicts
suggestedNameText = $.i18n.t('signup.name_taken').replace('{{suggestedName}}', suggestedName)
@state.set({ checkNameState: 'exists', suggestedNameText })
else
@state.set { checkNameState: 'available' }
.catch (error) =>
@state.set('checkNameState', 'standby')
throw error
)
})
return @state.get('checkNamePromise')
onChangeEmail: (e) ->
@updateAuthModalInitialValues { email: @$(e.currentTarget).val() }
@checkEmail()
checkEmail: ->
email = @$('[name="email"]').val()
if not _.isEmpty(email) and email is @state.get('checkEmailValue')
return @state.get('checkEmailPromise')
if not (email and forms.validateEmail(email))
@state.set({
checkEmailState: 'standby'
checkEmailValue: email
checkEmailPromise: null
})
return Promise.resolve()
@state.set({
checkEmailState: 'checking'
checkEmailValue: email
checkEmailPromise: (User.checkEmailExists(email)
.then ({exists}) =>
return unless email is @$('[name="email"]').val()
if exists
@state.set('checkEmailState', 'exists')
else
@state.set('checkEmailState', 'available')
.catch (e) =>
@state.set('checkEmailState', 'standby')
throw e
)
})
return @state.get('checkEmailPromise')
requestFormSchemaAnonymous = {
type: 'object'
required: [
'PI:NAME:<NAME>END_PI', 'email', 'role', 'numStudents', 'numStudentsTotal', 'city', 'state',
'country', 'organization', 'phoneNumber'
]
properties:
fullName: { type: 'string' }
email: { type: 'string', format: 'email' }
phoneNumber: { type: 'string' }
role: { type: 'string' }
organization: { type: 'string' }
district: { type: 'string' }
city: { type: 'string' }
state: { type: 'string' }
country: { type: 'string' }
numStudents: { type: 'string' }
numStudentsTotal: { type: 'string' }
}
for key in SCHOOL_NCES_KEYS
requestFormSchemaAnonymous['nces_' + key] = type: 'string'
# same form, but add username input
requestFormSchemaLoggedIn = _.cloneDeep(requestFormSchemaAnonymous)
requestFormSchemaLoggedIn.required.push('name')
signupFormSchema = {
type: 'object'
required: ['name', 'PI:PASSWORD:<PASSWORD>END_PI1', 'PI:PASSWORD:<PASSWORD>END_PI']
properties:
name: { type: 'string' }
password1: { type: 'string' }
password2: { type: 'string' }
}
|
[
{
"context": "#\n# Ethan Mick\n# 2015\n#\n\nmodule.exports =\n Client: require './c",
"end": 14,
"score": 0.9998003840446472,
"start": 4,
"tag": "NAME",
"value": "Ethan Mick"
}
] | lib/index.coffee | ethanmick/future-client | 0 | #
# Ethan Mick
# 2015
#
module.exports =
Client: require './client'
Task: require './task'
| 134763 | #
# <NAME>
# 2015
#
module.exports =
Client: require './client'
Task: require './task'
| true | #
# PI:NAME:<NAME>END_PI
# 2015
#
module.exports =
Client: require './client'
Task: require './task'
|
[
{
"context": "evelopers\n 'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - client-email-1@example.com\n 'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - client-e",
"end": 525,
"score": 0.9973485469818115,
"start": 499,
"tag": "EMAIL",
"value": "client-email-1@example.com"
},
{
"context": "ample.com\n 'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - client-email-2@exmaple.com\n 'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - client-e",
"end": 593,
"score": 0.9534974694252014,
"start": 567,
"tag": "EMAIL",
"value": "client-email-2@exmaple.com"
},
{
"context": "maple.com\n 'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - client-email-3@exmaple.com\n ]\n\n###\n# Default paths\n###\nTODAY = new Date();\n",
"end": 661,
"score": 0.8700477480888367,
"start": 635,
"tag": "EMAIL",
"value": "client-email-3@exmaple.com"
}
] | include/example-gulpfile.coffee | reatlat/wp-theme-builder-with-docker | 0 | app = {}
app.name = theme.name # Application name
app.desc = theme.desc # This is my application
app.url = "localhost" # Homepage link
app.devName = theme.author # Developer name (Company name)
app.devURL = theme.authorUrl # Developer URL (Company URL)
###
# TinyPNG API Keys
###
tinypng = {}
tinypng.key = 0 # choose API from array
tinypng.api = [
# Get your own API key from TinyPNG
# @link https://tinypng.com/developers
'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - client-email-1@example.com
'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - client-email-2@exmaple.com
'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - client-email-3@exmaple.com
]
###
# Default paths
###
TODAY = new Date();
DD = TODAY.getDate();
if 10 > DD
DD = '0' + DD
MM = TODAY.getMonth()+1;
if 10 > MM
MM = '0' + MM
YYYY = TODAY.getFullYear();
THEME_NAME = 'wp_'+ theme.slug + '_' + YYYY + '-' + MM + '-' + DD + '_build-' + Date.now()
path = {}
path.temp = './temp'
path.source = './source'
path.build = './build'
path.release = './release'
path.dev = './dev' # /wp-content/themes
csso_options = {restructure: false, sourceMap: true, debug: true}
THEME_PATH = path.dev
###
# General requires
###
gulp = require('gulp')
runSequence = require('run-sequence')
Notification = require('node-notifier')
$ = require('gulp-load-plugins')(
pattern: [
'gulp-*'
'gulp.*'
]
replaceString: /\bgulp[\-.]/)
gulp.task 'default', [ 'test' ]
###
# Initial project
###
gulp.task 'init', (callback) ->
runSequence [
'init_favicons'
'init_php'
'init_js'
'init_styles'
'init_screenshot'
'init_lang'
'init_others'
],
'init_styles_normalize', callback
gulp.task 'init_favicons', ->
gulp.src("./include/logo.png")
.pipe($.favicons({
appName: app.name
appDescription: app.desc
developerName: app.devName
developerURL: app.devURL
background: "#020307"
path: "favicons/"
url: app.url
display: "standalone"
orientation: "portrait"
start_url: "/?homescreen=1"
version: 1.0
logging: false
online: false
html: "favicons.html"
pipeHTML: true
replace: true
}))
.on('error', errorHandler('Favicons generator'))
.pipe(gulp.dest(path.source+'/favicons'));
gulp.task 'init_php', ->
gulp.src('./include/_s/**/*.php')
.pipe($.replace('\'_s\'', '\''+theme.slug+'\''))
.pipe($.replace('_s_', theme.slug_s+'_'))
.pipe($.replace(' _s', ' '+theme.name_s))
.pipe($.replace('_s-', theme.slug+'-'))
.pipe gulp.dest(path.source+'/php/')
gulp.task 'init_js', ->
gulp.src('./include/_s/js/**/*.js')
.pipe($.replace('\'_s\'', '\''+theme.slug+'\''))
.pipe($.replace('_s_', theme.slug_s+'_'))
.pipe($.replace(' _s', ' '+theme.name_s))
.pipe($.replace('_s-', theme.slug+'-'))
.pipe gulp.dest(path.source+'/scripts/')
gulp.task 'init_styles', ->
gulp.src('./include/_s/sass/**/*.scss')
.pipe($.replace('\'_s\'', '\''+theme.slug+'\''))
.pipe($.replace('_s_', theme.slug_s+'_'))
.pipe($.replace(' _s', ' '+theme.name_s))
.pipe($.replace('_s-', theme.slug+'-'))
.pipe gulp.dest(path.source+'/styles/')
gulp.task 'init_styles_normalize', ->
gulp.src('./include/normalize/**/*.scss')
.pipe gulp.dest(path.source+'/styles/')
gulp.task 'init_screenshot', ->
gulp.src('./include/screenshot.{png,xcf}')
.pipe gulp.dest(path.source)
gulp.task 'init_lang', ->
gulp.src('./include/_s/languages/_s.pot')
.pipe($.replace('_s', theme.name_s))
.pipe($.rename(theme.slug+'.pot'))
.pipe gulp.dest(path.source+'/others/languages/')
gulp.task 'init_others', ->
gulp.src(['./include/_s/languages*/readme.txt', './include/_s/layouts*/*', './include/_s/LICENSE', './include/_s/README.md', './include/_s/.jscsrc', './include/_s/.jshintignore', './include/_s/.travis.yml', './include/_s/CONTRIBUTING.md', './include/_s/codesniffer.ruleset.xml', './include/_s/rtl.css', './include/_s/readme.txt'])
.pipe gulp.dest(path.source+'/others/')
###
# Regular tasks
###
gulp.task 'dev', (callback) ->
THEME_PATH = path.dev+'/'+theme.slug
runSequence [
'clean_temp_folder'
'clean_theme_folder'
], [
'copy_screenshot'
'copy_favicons'
'copy_fonts'
'copy_images'
'copy_others'
'copy_php'
'styles'
'scripts'
], 'watch', callback
gulp.task 'build', (callback) ->
THEME_PATH = path.build+'/'+theme.slug
csso_options = ''
runSequence [
'clean_temp_folder'
'clean_theme_folder'
], [
'copy_screenshot'
'copy_favicons'
'copy_fonts'
'copy_images'
'copy_others'
'copy_php'
], [
'images_optimize'
'styles'
'scripts'
], 'zip', callback
###
# Tasks
###
gulp.task 'styles', (callback) ->
runSequence [
'clean_temp_css_folder'
'styles_scss'
],
'styles_merge'
callback
gulp.task 'styles_scss', ->
gulp.src(path.source+'/styles/style.scss')
.pipe($.sass(errLogToConsole: true).on('error', errorHandler('SASS')))
.pipe($.autoprefixer('last 2 version'))
.pipe($.stripCssComments(preserve: false))
.pipe($.csso(csso_options))
.pipe gulp.dest('./temp/css/')
gulp.task 'styles_merge', ->
gulp.src([
path.source+'/style.css'
'./temp/css/style.css'
])
.pipe($.concat('style.css')).pipe gulp.dest(THEME_PATH + '/')
gulp.task 'test', ->
Notification.notify
title: '!!! Test task for example !!!'
message: 'All done!\nPlease check result!'
icon: __dirname+'/include/reatlat.png'
gulp.task 'done', ->
Notification.notify
title: 'Congrats!'
message: 'All done!\nPlease check result!'
icon: __dirname+'/include/reatlat.png'
gulp.task 'watch', ->
# Watch all files - *.coffee, *.js and *.scss
console.log ''
console.log ' May the Force be with you'
console.log ''
gulp.watch path.source+'/favicons/**/*', [ 'copy_favicons' ]
gulp.watch path.source+'/fonts/**/*', [ 'copy_fonts' ]
gulp.watch path.source+'/scripts/**/*.{coffee,js}', [ 'scripts' ]
gulp.watch path.source+'/styles/**/*.scss', [ 'styles' ]
gulp.watch path.source+'/style.css', [ 'styles' ]
gulp.watch path.source+'/php/**/*.php', [ 'copy_php' ]
gulp.task 'clean_temp_folder', ->
gulp.src(path.temp, read: false)
.pipe $.clean()
gulp.task 'clean_temp_css_folder', ->
gulp.src(path.temp+'/css', read: false)
.pipe $.clean()
gulp.task 'clean_theme_folder', ->
gulp.src(THEME_PATH+'/*', read: false)
.pipe $.clean(force: true)
gulp.task 'scripts', (callback) ->
runSequence [
'coffeeScripts'
'javaScripts'
], callback
gulp.task 'coffeeScripts', ->
gulp.src(path.source+'/scripts/!(_)*.coffee')
.pipe($.include(extension: '.coffee').on('error', errorHandler('Include *.coffee')))
.pipe($.coffee(bare: true).on('error', errorHandler('CoffeeScript')))
.pipe($.uglify({}))
.pipe gulp.dest(THEME_PATH+'/js/')
gulp.task 'javaScripts', ->
gulp.src(path.source+'/scripts/*.js')
.pipe($.include(extension: '.js').on('error', errorHandler('Include *.js')))
.pipe($.uglify({}))
.pipe gulp.dest(THEME_PATH+'/js/')
gulp.task 'javaScripts_vendor', ->
gulp.src(path.source+'/scripts/vendor/**/*.js')
.pipe($.changed(THEME_PATH+'/js/vendor/'))
.pipe gulp.dest(THEME_PATH+'/js/vendor/')
gulp.task 'copy_screenshot', ->
gulp.src(path.source+'/screenshot.png')
.pipe($.changed(THEME_PATH))
.pipe gulp.dest(THEME_PATH)
gulp.task 'copy_favicons', ->
gulp.src(path.source+'/favicons/**/*')
.pipe($.changed(THEME_PATH+'/favicons/'))
.pipe gulp.dest(THEME_PATH+'/favicons/')
gulp.task 'copy_fonts', ->
gulp.src(path.source+'/fonts/**/*')
.pipe($.changed(THEME_PATH+'/fonts/'))
.pipe gulp.dest(THEME_PATH+'/fonts/')
gulp.task 'copy_images', ->
gulp.src(path.source+'/images/**/*.{jpg,JPG,png,PNG,gif,GIF,svg,SVG}')
.pipe($.changed(THEME_PATH+'/images/'))
.pipe gulp.dest(THEME_PATH+'/images/')
gulp.task 'images_optimize', ->
gulp.src(THEME_PATH+'/images/**/*.{jpg,JPG,png,PNG}')
.pipe($.tinypngCompress({
key: tinypng.api[tinypng.key] # TinyPNG API key
sigFile: THEME_PATH+'/images/.tinypng-sigs'
summarize: true
log: true
}))
.pipe(gulp.dest(THEME_PATH+'/images/'))
gulp.task 'copy_others', ->
gulp.src(THEME_PATH+'/others/**/*')
.pipe(gulp.dest(THEME_PATH))
gulp.task 'copy_php', ->
gulp.src(path.source+'/php/**/*.php')
.pipe($.changed(THEME_PATH+'/'))
.pipe gulp.dest(THEME_PATH+'/')
gulp.task 'zip', ->
gulp.src(THEME_PATH+'*/**')
.pipe($.archiver(THEME_NAME+'.zip').on('error', errorHandler('ZIP Compression')))
.pipe($.notify(
title: 'WP Theme builder'
message: 'Theme already archived to zip file'
icon: __dirname+'/include/reatlat.png'))
.pipe gulp.dest(path.release)
###
# Helpers
###
errorHandler = (title) ->
(error) ->
$.util.log $.util.colors.yellow(error.message)
Notification.notify
title: title
message: error.message
icon: __dirname+'/include/reatlat.png'
@emit 'end'
| 82670 | app = {}
app.name = theme.name # Application name
app.desc = theme.desc # This is my application
app.url = "localhost" # Homepage link
app.devName = theme.author # Developer name (Company name)
app.devURL = theme.authorUrl # Developer URL (Company URL)
###
# TinyPNG API Keys
###
tinypng = {}
tinypng.key = 0 # choose API from array
tinypng.api = [
# Get your own API key from TinyPNG
# @link https://tinypng.com/developers
'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - <EMAIL>
'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - <EMAIL>
'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - <EMAIL>
]
###
# Default paths
###
TODAY = new Date();
DD = TODAY.getDate();
if 10 > DD
DD = '0' + DD
MM = TODAY.getMonth()+1;
if 10 > MM
MM = '0' + MM
YYYY = TODAY.getFullYear();
THEME_NAME = 'wp_'+ theme.slug + '_' + YYYY + '-' + MM + '-' + DD + '_build-' + Date.now()
path = {}
path.temp = './temp'
path.source = './source'
path.build = './build'
path.release = './release'
path.dev = './dev' # /wp-content/themes
csso_options = {restructure: false, sourceMap: true, debug: true}
THEME_PATH = path.dev
###
# General requires
###
gulp = require('gulp')
runSequence = require('run-sequence')
Notification = require('node-notifier')
$ = require('gulp-load-plugins')(
pattern: [
'gulp-*'
'gulp.*'
]
replaceString: /\bgulp[\-.]/)
gulp.task 'default', [ 'test' ]
###
# Initial project
###
gulp.task 'init', (callback) ->
runSequence [
'init_favicons'
'init_php'
'init_js'
'init_styles'
'init_screenshot'
'init_lang'
'init_others'
],
'init_styles_normalize', callback
gulp.task 'init_favicons', ->
gulp.src("./include/logo.png")
.pipe($.favicons({
appName: app.name
appDescription: app.desc
developerName: app.devName
developerURL: app.devURL
background: "#020307"
path: "favicons/"
url: app.url
display: "standalone"
orientation: "portrait"
start_url: "/?homescreen=1"
version: 1.0
logging: false
online: false
html: "favicons.html"
pipeHTML: true
replace: true
}))
.on('error', errorHandler('Favicons generator'))
.pipe(gulp.dest(path.source+'/favicons'));
gulp.task 'init_php', ->
gulp.src('./include/_s/**/*.php')
.pipe($.replace('\'_s\'', '\''+theme.slug+'\''))
.pipe($.replace('_s_', theme.slug_s+'_'))
.pipe($.replace(' _s', ' '+theme.name_s))
.pipe($.replace('_s-', theme.slug+'-'))
.pipe gulp.dest(path.source+'/php/')
gulp.task 'init_js', ->
gulp.src('./include/_s/js/**/*.js')
.pipe($.replace('\'_s\'', '\''+theme.slug+'\''))
.pipe($.replace('_s_', theme.slug_s+'_'))
.pipe($.replace(' _s', ' '+theme.name_s))
.pipe($.replace('_s-', theme.slug+'-'))
.pipe gulp.dest(path.source+'/scripts/')
gulp.task 'init_styles', ->
gulp.src('./include/_s/sass/**/*.scss')
.pipe($.replace('\'_s\'', '\''+theme.slug+'\''))
.pipe($.replace('_s_', theme.slug_s+'_'))
.pipe($.replace(' _s', ' '+theme.name_s))
.pipe($.replace('_s-', theme.slug+'-'))
.pipe gulp.dest(path.source+'/styles/')
gulp.task 'init_styles_normalize', ->
gulp.src('./include/normalize/**/*.scss')
.pipe gulp.dest(path.source+'/styles/')
gulp.task 'init_screenshot', ->
gulp.src('./include/screenshot.{png,xcf}')
.pipe gulp.dest(path.source)
gulp.task 'init_lang', ->
gulp.src('./include/_s/languages/_s.pot')
.pipe($.replace('_s', theme.name_s))
.pipe($.rename(theme.slug+'.pot'))
.pipe gulp.dest(path.source+'/others/languages/')
gulp.task 'init_others', ->
gulp.src(['./include/_s/languages*/readme.txt', './include/_s/layouts*/*', './include/_s/LICENSE', './include/_s/README.md', './include/_s/.jscsrc', './include/_s/.jshintignore', './include/_s/.travis.yml', './include/_s/CONTRIBUTING.md', './include/_s/codesniffer.ruleset.xml', './include/_s/rtl.css', './include/_s/readme.txt'])
.pipe gulp.dest(path.source+'/others/')
###
# Regular tasks
###
gulp.task 'dev', (callback) ->
THEME_PATH = path.dev+'/'+theme.slug
runSequence [
'clean_temp_folder'
'clean_theme_folder'
], [
'copy_screenshot'
'copy_favicons'
'copy_fonts'
'copy_images'
'copy_others'
'copy_php'
'styles'
'scripts'
], 'watch', callback
gulp.task 'build', (callback) ->
THEME_PATH = path.build+'/'+theme.slug
csso_options = ''
runSequence [
'clean_temp_folder'
'clean_theme_folder'
], [
'copy_screenshot'
'copy_favicons'
'copy_fonts'
'copy_images'
'copy_others'
'copy_php'
], [
'images_optimize'
'styles'
'scripts'
], 'zip', callback
###
# Tasks
###
gulp.task 'styles', (callback) ->
runSequence [
'clean_temp_css_folder'
'styles_scss'
],
'styles_merge'
callback
gulp.task 'styles_scss', ->
gulp.src(path.source+'/styles/style.scss')
.pipe($.sass(errLogToConsole: true).on('error', errorHandler('SASS')))
.pipe($.autoprefixer('last 2 version'))
.pipe($.stripCssComments(preserve: false))
.pipe($.csso(csso_options))
.pipe gulp.dest('./temp/css/')
gulp.task 'styles_merge', ->
gulp.src([
path.source+'/style.css'
'./temp/css/style.css'
])
.pipe($.concat('style.css')).pipe gulp.dest(THEME_PATH + '/')
gulp.task 'test', ->
Notification.notify
title: '!!! Test task for example !!!'
message: 'All done!\nPlease check result!'
icon: __dirname+'/include/reatlat.png'
gulp.task 'done', ->
Notification.notify
title: 'Congrats!'
message: 'All done!\nPlease check result!'
icon: __dirname+'/include/reatlat.png'
gulp.task 'watch', ->
# Watch all files - *.coffee, *.js and *.scss
console.log ''
console.log ' May the Force be with you'
console.log ''
gulp.watch path.source+'/favicons/**/*', [ 'copy_favicons' ]
gulp.watch path.source+'/fonts/**/*', [ 'copy_fonts' ]
gulp.watch path.source+'/scripts/**/*.{coffee,js}', [ 'scripts' ]
gulp.watch path.source+'/styles/**/*.scss', [ 'styles' ]
gulp.watch path.source+'/style.css', [ 'styles' ]
gulp.watch path.source+'/php/**/*.php', [ 'copy_php' ]
gulp.task 'clean_temp_folder', ->
gulp.src(path.temp, read: false)
.pipe $.clean()
gulp.task 'clean_temp_css_folder', ->
gulp.src(path.temp+'/css', read: false)
.pipe $.clean()
gulp.task 'clean_theme_folder', ->
gulp.src(THEME_PATH+'/*', read: false)
.pipe $.clean(force: true)
gulp.task 'scripts', (callback) ->
runSequence [
'coffeeScripts'
'javaScripts'
], callback
gulp.task 'coffeeScripts', ->
gulp.src(path.source+'/scripts/!(_)*.coffee')
.pipe($.include(extension: '.coffee').on('error', errorHandler('Include *.coffee')))
.pipe($.coffee(bare: true).on('error', errorHandler('CoffeeScript')))
.pipe($.uglify({}))
.pipe gulp.dest(THEME_PATH+'/js/')
gulp.task 'javaScripts', ->
gulp.src(path.source+'/scripts/*.js')
.pipe($.include(extension: '.js').on('error', errorHandler('Include *.js')))
.pipe($.uglify({}))
.pipe gulp.dest(THEME_PATH+'/js/')
gulp.task 'javaScripts_vendor', ->
gulp.src(path.source+'/scripts/vendor/**/*.js')
.pipe($.changed(THEME_PATH+'/js/vendor/'))
.pipe gulp.dest(THEME_PATH+'/js/vendor/')
gulp.task 'copy_screenshot', ->
gulp.src(path.source+'/screenshot.png')
.pipe($.changed(THEME_PATH))
.pipe gulp.dest(THEME_PATH)
gulp.task 'copy_favicons', ->
gulp.src(path.source+'/favicons/**/*')
.pipe($.changed(THEME_PATH+'/favicons/'))
.pipe gulp.dest(THEME_PATH+'/favicons/')
gulp.task 'copy_fonts', ->
gulp.src(path.source+'/fonts/**/*')
.pipe($.changed(THEME_PATH+'/fonts/'))
.pipe gulp.dest(THEME_PATH+'/fonts/')
gulp.task 'copy_images', ->
gulp.src(path.source+'/images/**/*.{jpg,JPG,png,PNG,gif,GIF,svg,SVG}')
.pipe($.changed(THEME_PATH+'/images/'))
.pipe gulp.dest(THEME_PATH+'/images/')
gulp.task 'images_optimize', ->
gulp.src(THEME_PATH+'/images/**/*.{jpg,JPG,png,PNG}')
.pipe($.tinypngCompress({
key: tinypng.api[tinypng.key] # TinyPNG API key
sigFile: THEME_PATH+'/images/.tinypng-sigs'
summarize: true
log: true
}))
.pipe(gulp.dest(THEME_PATH+'/images/'))
gulp.task 'copy_others', ->
gulp.src(THEME_PATH+'/others/**/*')
.pipe(gulp.dest(THEME_PATH))
gulp.task 'copy_php', ->
gulp.src(path.source+'/php/**/*.php')
.pipe($.changed(THEME_PATH+'/'))
.pipe gulp.dest(THEME_PATH+'/')
gulp.task 'zip', ->
gulp.src(THEME_PATH+'*/**')
.pipe($.archiver(THEME_NAME+'.zip').on('error', errorHandler('ZIP Compression')))
.pipe($.notify(
title: 'WP Theme builder'
message: 'Theme already archived to zip file'
icon: __dirname+'/include/reatlat.png'))
.pipe gulp.dest(path.release)
###
# Helpers
###
errorHandler = (title) ->
(error) ->
$.util.log $.util.colors.yellow(error.message)
Notification.notify
title: title
message: error.message
icon: __dirname+'/include/reatlat.png'
@emit 'end'
| true | app = {}
app.name = theme.name # Application name
app.desc = theme.desc # This is my application
app.url = "localhost" # Homepage link
app.devName = theme.author # Developer name (Company name)
app.devURL = theme.authorUrl # Developer URL (Company URL)
###
# TinyPNG API Keys
###
tinypng = {}
tinypng.key = 0 # choose API from array
tinypng.api = [
# Get your own API key from TinyPNG
# @link https://tinypng.com/developers
'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - PI:EMAIL:<EMAIL>END_PI
'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - PI:EMAIL:<EMAIL>END_PI
'GET_YOUR_OWN_API_KEY_FOR_TINYPNG' # - PI:EMAIL:<EMAIL>END_PI
]
###
# Default paths
###
TODAY = new Date();
DD = TODAY.getDate();
if 10 > DD
DD = '0' + DD
MM = TODAY.getMonth()+1;
if 10 > MM
MM = '0' + MM
YYYY = TODAY.getFullYear();
THEME_NAME = 'wp_'+ theme.slug + '_' + YYYY + '-' + MM + '-' + DD + '_build-' + Date.now()
path = {}
path.temp = './temp'
path.source = './source'
path.build = './build'
path.release = './release'
path.dev = './dev' # /wp-content/themes
csso_options = {restructure: false, sourceMap: true, debug: true}
THEME_PATH = path.dev
###
# General requires
###
gulp = require('gulp')
runSequence = require('run-sequence')
Notification = require('node-notifier')
$ = require('gulp-load-plugins')(
pattern: [
'gulp-*'
'gulp.*'
]
replaceString: /\bgulp[\-.]/)
gulp.task 'default', [ 'test' ]
###
# Initial project
###
gulp.task 'init', (callback) ->
runSequence [
'init_favicons'
'init_php'
'init_js'
'init_styles'
'init_screenshot'
'init_lang'
'init_others'
],
'init_styles_normalize', callback
gulp.task 'init_favicons', ->
gulp.src("./include/logo.png")
.pipe($.favicons({
appName: app.name
appDescription: app.desc
developerName: app.devName
developerURL: app.devURL
background: "#020307"
path: "favicons/"
url: app.url
display: "standalone"
orientation: "portrait"
start_url: "/?homescreen=1"
version: 1.0
logging: false
online: false
html: "favicons.html"
pipeHTML: true
replace: true
}))
.on('error', errorHandler('Favicons generator'))
.pipe(gulp.dest(path.source+'/favicons'));
gulp.task 'init_php', ->
gulp.src('./include/_s/**/*.php')
.pipe($.replace('\'_s\'', '\''+theme.slug+'\''))
.pipe($.replace('_s_', theme.slug_s+'_'))
.pipe($.replace(' _s', ' '+theme.name_s))
.pipe($.replace('_s-', theme.slug+'-'))
.pipe gulp.dest(path.source+'/php/')
gulp.task 'init_js', ->
gulp.src('./include/_s/js/**/*.js')
.pipe($.replace('\'_s\'', '\''+theme.slug+'\''))
.pipe($.replace('_s_', theme.slug_s+'_'))
.pipe($.replace(' _s', ' '+theme.name_s))
.pipe($.replace('_s-', theme.slug+'-'))
.pipe gulp.dest(path.source+'/scripts/')
gulp.task 'init_styles', ->
gulp.src('./include/_s/sass/**/*.scss')
.pipe($.replace('\'_s\'', '\''+theme.slug+'\''))
.pipe($.replace('_s_', theme.slug_s+'_'))
.pipe($.replace(' _s', ' '+theme.name_s))
.pipe($.replace('_s-', theme.slug+'-'))
.pipe gulp.dest(path.source+'/styles/')
gulp.task 'init_styles_normalize', ->
gulp.src('./include/normalize/**/*.scss')
.pipe gulp.dest(path.source+'/styles/')
gulp.task 'init_screenshot', ->
gulp.src('./include/screenshot.{png,xcf}')
.pipe gulp.dest(path.source)
gulp.task 'init_lang', ->
gulp.src('./include/_s/languages/_s.pot')
.pipe($.replace('_s', theme.name_s))
.pipe($.rename(theme.slug+'.pot'))
.pipe gulp.dest(path.source+'/others/languages/')
gulp.task 'init_others', ->
gulp.src(['./include/_s/languages*/readme.txt', './include/_s/layouts*/*', './include/_s/LICENSE', './include/_s/README.md', './include/_s/.jscsrc', './include/_s/.jshintignore', './include/_s/.travis.yml', './include/_s/CONTRIBUTING.md', './include/_s/codesniffer.ruleset.xml', './include/_s/rtl.css', './include/_s/readme.txt'])
.pipe gulp.dest(path.source+'/others/')
###
# Regular tasks
###
gulp.task 'dev', (callback) ->
THEME_PATH = path.dev+'/'+theme.slug
runSequence [
'clean_temp_folder'
'clean_theme_folder'
], [
'copy_screenshot'
'copy_favicons'
'copy_fonts'
'copy_images'
'copy_others'
'copy_php'
'styles'
'scripts'
], 'watch', callback
gulp.task 'build', (callback) ->
THEME_PATH = path.build+'/'+theme.slug
csso_options = ''
runSequence [
'clean_temp_folder'
'clean_theme_folder'
], [
'copy_screenshot'
'copy_favicons'
'copy_fonts'
'copy_images'
'copy_others'
'copy_php'
], [
'images_optimize'
'styles'
'scripts'
], 'zip', callback
###
# Tasks
###
gulp.task 'styles', (callback) ->
runSequence [
'clean_temp_css_folder'
'styles_scss'
],
'styles_merge'
callback
gulp.task 'styles_scss', ->
gulp.src(path.source+'/styles/style.scss')
.pipe($.sass(errLogToConsole: true).on('error', errorHandler('SASS')))
.pipe($.autoprefixer('last 2 version'))
.pipe($.stripCssComments(preserve: false))
.pipe($.csso(csso_options))
.pipe gulp.dest('./temp/css/')
gulp.task 'styles_merge', ->
gulp.src([
path.source+'/style.css'
'./temp/css/style.css'
])
.pipe($.concat('style.css')).pipe gulp.dest(THEME_PATH + '/')
gulp.task 'test', ->
Notification.notify
title: '!!! Test task for example !!!'
message: 'All done!\nPlease check result!'
icon: __dirname+'/include/reatlat.png'
gulp.task 'done', ->
Notification.notify
title: 'Congrats!'
message: 'All done!\nPlease check result!'
icon: __dirname+'/include/reatlat.png'
gulp.task 'watch', ->
# Watch all files - *.coffee, *.js and *.scss
console.log ''
console.log ' May the Force be with you'
console.log ''
gulp.watch path.source+'/favicons/**/*', [ 'copy_favicons' ]
gulp.watch path.source+'/fonts/**/*', [ 'copy_fonts' ]
gulp.watch path.source+'/scripts/**/*.{coffee,js}', [ 'scripts' ]
gulp.watch path.source+'/styles/**/*.scss', [ 'styles' ]
gulp.watch path.source+'/style.css', [ 'styles' ]
gulp.watch path.source+'/php/**/*.php', [ 'copy_php' ]
gulp.task 'clean_temp_folder', ->
gulp.src(path.temp, read: false)
.pipe $.clean()
gulp.task 'clean_temp_css_folder', ->
gulp.src(path.temp+'/css', read: false)
.pipe $.clean()
gulp.task 'clean_theme_folder', ->
gulp.src(THEME_PATH+'/*', read: false)
.pipe $.clean(force: true)
gulp.task 'scripts', (callback) ->
runSequence [
'coffeeScripts'
'javaScripts'
], callback
gulp.task 'coffeeScripts', ->
gulp.src(path.source+'/scripts/!(_)*.coffee')
.pipe($.include(extension: '.coffee').on('error', errorHandler('Include *.coffee')))
.pipe($.coffee(bare: true).on('error', errorHandler('CoffeeScript')))
.pipe($.uglify({}))
.pipe gulp.dest(THEME_PATH+'/js/')
gulp.task 'javaScripts', ->
gulp.src(path.source+'/scripts/*.js')
.pipe($.include(extension: '.js').on('error', errorHandler('Include *.js')))
.pipe($.uglify({}))
.pipe gulp.dest(THEME_PATH+'/js/')
gulp.task 'javaScripts_vendor', ->
gulp.src(path.source+'/scripts/vendor/**/*.js')
.pipe($.changed(THEME_PATH+'/js/vendor/'))
.pipe gulp.dest(THEME_PATH+'/js/vendor/')
gulp.task 'copy_screenshot', ->
gulp.src(path.source+'/screenshot.png')
.pipe($.changed(THEME_PATH))
.pipe gulp.dest(THEME_PATH)
gulp.task 'copy_favicons', ->
gulp.src(path.source+'/favicons/**/*')
.pipe($.changed(THEME_PATH+'/favicons/'))
.pipe gulp.dest(THEME_PATH+'/favicons/')
gulp.task 'copy_fonts', ->
gulp.src(path.source+'/fonts/**/*')
.pipe($.changed(THEME_PATH+'/fonts/'))
.pipe gulp.dest(THEME_PATH+'/fonts/')
gulp.task 'copy_images', ->
gulp.src(path.source+'/images/**/*.{jpg,JPG,png,PNG,gif,GIF,svg,SVG}')
.pipe($.changed(THEME_PATH+'/images/'))
.pipe gulp.dest(THEME_PATH+'/images/')
gulp.task 'images_optimize', ->
gulp.src(THEME_PATH+'/images/**/*.{jpg,JPG,png,PNG}')
.pipe($.tinypngCompress({
key: tinypng.api[tinypng.key] # TinyPNG API key
sigFile: THEME_PATH+'/images/.tinypng-sigs'
summarize: true
log: true
}))
.pipe(gulp.dest(THEME_PATH+'/images/'))
gulp.task 'copy_others', ->
gulp.src(THEME_PATH+'/others/**/*')
.pipe(gulp.dest(THEME_PATH))
gulp.task 'copy_php', ->
gulp.src(path.source+'/php/**/*.php')
.pipe($.changed(THEME_PATH+'/'))
.pipe gulp.dest(THEME_PATH+'/')
gulp.task 'zip', ->
gulp.src(THEME_PATH+'*/**')
.pipe($.archiver(THEME_NAME+'.zip').on('error', errorHandler('ZIP Compression')))
.pipe($.notify(
title: 'WP Theme builder'
message: 'Theme already archived to zip file'
icon: __dirname+'/include/reatlat.png'))
.pipe gulp.dest(path.release)
###
# Helpers
###
errorHandler = (title) ->
(error) ->
$.util.log $.util.colors.yellow(error.message)
Notification.notify
title: title
message: error.message
icon: __dirname+'/include/reatlat.png'
@emit 'end'
|
[
{
"context": "is “ride” is mostly a movie in a theater. It stars Ellen DeGeneres, Bill Nye, and Jamie Lee Curtis and debuted in 19",
"end": 1777,
"score": 0.9998108148574829,
"start": 1762,
"tag": "NAME",
"value": "Ellen DeGeneres"
},
{
"context": "ly a movie in a theater. It stars Ellen DeGeneres, Bill Nye, and Jamie Lee Curtis and debuted in 1996. That w",
"end": 1787,
"score": 0.9998598098754883,
"start": 1779,
"tag": "NAME",
"value": "Bill Nye"
},
{
"context": "a theater. It stars Ellen DeGeneres, Bill Nye, and Jamie Lee Curtis and debuted in 1996. That was before Ellen was ou",
"end": 1809,
"score": 0.9998863339424133,
"start": 1793,
"tag": "NAME",
"value": "Jamie Lee Curtis"
},
{
"context": "ie Lee Curtis and debuted in 1996. That was before Ellen was out.\"\n url: \"http://bestrestaurant.gawker.",
"end": 1852,
"score": 0.9975399374961853,
"start": 1847,
"tag": "NAME",
"value": "Ellen"
},
{
"context": " World Is: The Circle of Life\"\n text: \"<strong>Rich:</strong> Simba seemed like he was going to appro",
"end": 3421,
"score": 0.9242467880249023,
"start": 3417,
"tag": "NAME",
"value": "Rich"
},
{
"context": " Circle of Life\"\n text: \"<strong>Rich:</strong> Simba seemed like he was going to approach the topic of",
"end": 3437,
"score": 0.992470383644104,
"start": 3432,
"tag": "NAME",
"value": "Simba"
},
{
"context": "adline: \"The Best Ride in the World Is: Captain EO Starring Michael Jackson\"\n text: \"<strong>Rich:</",
"end": 4167,
"score": 0.7055298089981079,
"start": 4165,
"tag": "NAME",
"value": "St"
},
{
"context": "The Best Ride in the World Is: Captain EO Starring Michael Jackson\"\n text: \"<strong>Rich:</strong> I gasped along",
"end": 4189,
"score": 0.9908325672149658,
"start": 4174,
"tag": "NAME",
"value": "Michael Jackson"
},
{
"context": "n EO Starring Michael Jackson\"\n text: \"<strong>Rich:</strong> I gasped along with all of the toddlers",
"end": 4214,
"score": 0.9026218056678772,
"start": 4210,
"tag": "NAME",
"value": "Rich"
},
{
"context": "ttle French girl, raised in an all girls school by Miss Clavelle. But what happened next was truly the most bizarr",
"end": 5794,
"score": 0.9180753827095032,
"start": 5781,
"tag": "NAME",
"value": "Miss Clavelle"
},
{
"context": "rmany's Biergarten Restaurant\"\n text: \"<strong>Rich:</strong> I thought the Bavarian cheesecake was e",
"end": 7541,
"score": 0.6407455205917358,
"start": 7537,
"tag": "NAME",
"value": "Rich"
},
{
"context": "ecake was excellent. “It’s just like my mother’s!” Bella gushed. This felt overly on the nose, but I was s",
"end": 7636,
"score": 0.9953773021697998,
"start": 7631,
"tag": "NAME",
"value": "Bella"
}
] | src/javascript/data.coffee | adampash/epcot_map | 0 | module.exports =
Norway:
headline: "The Best Restaurant in the World Is: Norway's Kringla Bakeri Og Kafe"
text: "<strong>Rich:</strong> “Is it too much?” you asked. Before I could answer, a female patron in line behind us piped up: “You’re at Disney. It’s not too much.”"
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-norway-1699415308"
coords:
x: 150
y: 94
Mexico:
headline: "The Best Restaurant in the World Is: Mexico's San Angel Inn Restaurante"
text: "<strong>Caity:</strong> I got a Wild Passionfruit Margarita and that’s how it made me feel! I give the Wild Passionfruit Margarita one hundred out of one hundred stars."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-mexicos-san-angel-1699425811"
coords:
x: 139
y: 123
Test:
headline: "The Best Ride in the World Is: Test Track® Presented by Chevrolet®"
text: "<strong>Rich:</strong> That was exciting! Would a giant truck end our lives right there and then in Epcot? Perhaps!"
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-test-track-presented-by-1699557476"
coords:
x: 50
y: 145
Mission:
headline: "The Best Ride in the World Is: Mission: SPACE"
text: "<strong>Rich:</strong> Mission: SPACE is a vomit factory. Worst of all, you are told at the beginning that if you start to feel sick you should not close your eyes."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-mission-space-1699556680"
coords:
x: 30
y: 174
Ellen:
headline: "The Best Ride in the World Is: Ellen's Energy Adventure"
text: "<strong>Rich:</strong> This “ride” is mostly a movie in a theater. It stars Ellen DeGeneres, Bill Nye, and Jamie Lee Curtis and debuted in 1996. That was before Ellen was out."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-ellens-energy-adventure-1699566900"
coords:
x: 30
y: 219
Spaceship:
headline: "The Best Ride in the World Is: Spaceship Earth"
text: "<strong>Caity:</strong> I could not believe how lifelike the features and movements of the animatronic figures were. I would say they are about 85% of the way to being indistinguishable from humans."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-spaceship-earth-1699556002"
coords:
x: 122
y: 244
Seas:
headline: "The Best Ride in the World Is: The Seas with Nemo & Friends®"
text: "<strong>Rich:</strong> The Finding Nemo ride is a cheap-looking knock-off of something you’d find in the Magic Kingdom, and keeping dolphins captive is despicable. But you know what? The manatees and their story of survival via freeloading had me captivated."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-the-seas-with-nemo-fri-1699558430"
coords:
x: 162
y: 330
Living:
headline: "The Best Ride in the World Is: Living With the Land"
text: "<strong>Caity:</strong> I was so worried I was going to get kicked out of the park that I made a point to gesticulate wildly for the rest of the ride."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-living-with-the-land-1699539150"
coords:
x: 247
y: 282
Circle:
headline: "The Best Ride in the World Is: The Circle of Life"
text: "<strong>Rich:</strong> Simba seemed like he was going to approach the topic of why dams are bad, which is something I’ve been meaning to get around to learning myself."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-the-circle-of-life-1699554892"
coords:
x: 241
y: 308
Soarin:
headline: "The Best Ride in the World Is: Soarin'®"
text: "<strong>Caity:</strong> Idiotically, the ride only simulates hang gliding over various parts of California, even though there is a whole world over which to hang glide."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-soarin-1699562403"
coords:
x: 277
y: 296
Captain:
headline: "The Best Ride in the World Is: Captain EO Starring Michael Jackson"
text: "<strong>Rich:</strong> I gasped along with all of the toddlers who delighted at the reveal.<br><strong>Caity:</strong> My hands flew to my mouth in shock. I could not believe it."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-captain-eo-starring-mich-1699555451"
coords:
x: 297
y: 268
Journey:
headline: "The Best Ride in the World Is: Journey Into Imagination with Figment"
text: "<strong>Rich:</strong> I can’t eat at a kitchen table upside down!"
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-journey-into-imagination-1699560979"
coords:
x: 266
y: 238
Canada:
headline: "The Best Restaurant in the World Is: Canada's Le Cellier"
text: "<strong>Caity:</strong> I think the Canadians are just not equipped, emotionally or militarily, to accommodate furious Americans."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-le-cellier-1699426233"
coords:
x: 313
y: 215
UK:
headline: "The Best Restaurant in the World Is: The UK's Rose & Crown Pub & Dining Room"
text: "<strong>Caity:</strong> G L U T E N - F R E E F A M I L Y."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-the-uks-rose-cro-1699494369"
coords:
x: 397
y: 181
France:
headline: "The Best Restaurant in the World Is: France's Les Chefs de France"
text: "<strong>Caity:</strong> You feel that we have been overly harsh on our waitress, a queer little French girl, raised in an all girls school by Miss Clavelle. But what happened next was truly the most bizarre and uncomfortable waiter interaction of my life."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-frances-les-chefs-1699499193"
coords:
x: 480
y: 147
Innoventions:
headline: "The Best Ride in the World Is: Innoventions"
text: "<strong>Caity:</strong> The Sum of All Thrills was terrifying to behold and fun to experience. The best kept secret in Epcot, and possibly the entire world."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-innoventions-1699566319"
coords:
x: 161
y: 201
Drinking:
headline: "Shot, Sake, Margarita, Slush: The Best Drinking Around the World"
text: "<strong>Rich:</strong> Inside China's giant store, I was tempted by Chinese ghost stories, giant fans to take with me to the club, and an incense burner with a dragon gazing into a crystal ball."
url: "http://bestrestaurant.gawker.com/shot-sake-margarita-slush-the-best-drinking-around-1699537518"
coords:
x: 218
y: 156
Illuminations:
headline: "The Best Spectacle in the World Is: IllumiNations: Reflections of Earth"
text: "<strong>Caity:</strong> You have to line up obscenely early for the nightly fireworks show, not because you actually have to, but because Epcot expends so much effort making you believe you have to, that it creates a ripple panic effect through the park, and you end up actually having to."
url: "http://bestrestaurant.gawker.com/the-best-spectacle-in-the-world-is-illuminations-refl-1699567497"
coords:
x: 296
y: 111
Germany:
headline: "The Best Restaurant in the World Is: Germany's Biergarten Restaurant"
text: "<strong>Rich:</strong> I thought the Bavarian cheesecake was excellent. “It’s just like my mother’s!” Bella gushed. This felt overly on the nose, but I was so in love with her and the sister that she calls cheesecake that I felt no need to call bullshit."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-germanys-biergarte-1699495170#_ga=1.160226557.1794012354.1428955654"
coords:
x: 259
y: 25
Italy:
headline: "The Best Restaurant in the World Is: Italy's Via Napoli"
text: "<strong>Rich:</strong> Via Napoli was wall-to-wall beautiful men holding pizzas. This was like Italy in reverse: the guys are all hot and none of them make passes at you."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-italys-via-napoli-1699429900"
coords:
x: 326
y: 12
Adventure:
headline: "The Best Restaurant in the World Is: America's Unnamed Funnel Cake Kiosk"
text: "<strong>Rich:</strong> The funnel cake came with what a giant might call a “pat” of ice cream. In actuality, it was bigger than a slice of bread, that pat of ice cream."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-americas-unnamed-f-1699509155#_ga=1.159382394.1794012354.1428955654"
coords:
x: 388
y: 36
China:
headline: "The Best Restaurant in the World Is: China's Joy of Tea"
text: "<strong>Caity:</strong> I was ready to die at that pavilion, fighting for my Lucky Combo."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-chinas-joy-of-tea-1699428916"
coords:
x: 183
y: 56
Japan:
headline: "The Best Restaurant in the World Is: Japan's Teppan Edo"
text: "<strong>Caity:</strong> “I made you origami,” she said. She did not make the French Canadians origami, perhaps because they had spilled Diet Coke."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-japans-teppan-edo-1699498320"
coords:
x: 447
y: 60
Morocco:
headline: "The Best Restaurant in the World Is: Morocco's Restaurant Marrakesh"
text: "<strong>Rich:</strong> I really liked that your meal explored beef in two of its three states: water and solid. If they could engineer a beef air, Restaurant Marrakesh would."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-moroccos-restauran-1699489246"
coords:
x: 465
y: 98
| 82090 | module.exports =
Norway:
headline: "The Best Restaurant in the World Is: Norway's Kringla Bakeri Og Kafe"
text: "<strong>Rich:</strong> “Is it too much?” you asked. Before I could answer, a female patron in line behind us piped up: “You’re at Disney. It’s not too much.”"
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-norway-1699415308"
coords:
x: 150
y: 94
Mexico:
headline: "The Best Restaurant in the World Is: Mexico's San Angel Inn Restaurante"
text: "<strong>Caity:</strong> I got a Wild Passionfruit Margarita and that’s how it made me feel! I give the Wild Passionfruit Margarita one hundred out of one hundred stars."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-mexicos-san-angel-1699425811"
coords:
x: 139
y: 123
Test:
headline: "The Best Ride in the World Is: Test Track® Presented by Chevrolet®"
text: "<strong>Rich:</strong> That was exciting! Would a giant truck end our lives right there and then in Epcot? Perhaps!"
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-test-track-presented-by-1699557476"
coords:
x: 50
y: 145
Mission:
headline: "The Best Ride in the World Is: Mission: SPACE"
text: "<strong>Rich:</strong> Mission: SPACE is a vomit factory. Worst of all, you are told at the beginning that if you start to feel sick you should not close your eyes."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-mission-space-1699556680"
coords:
x: 30
y: 174
Ellen:
headline: "The Best Ride in the World Is: Ellen's Energy Adventure"
text: "<strong>Rich:</strong> This “ride” is mostly a movie in a theater. It stars <NAME>, <NAME>, and <NAME> and debuted in 1996. That was before <NAME> was out."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-ellens-energy-adventure-1699566900"
coords:
x: 30
y: 219
Spaceship:
headline: "The Best Ride in the World Is: Spaceship Earth"
text: "<strong>Caity:</strong> I could not believe how lifelike the features and movements of the animatronic figures were. I would say they are about 85% of the way to being indistinguishable from humans."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-spaceship-earth-1699556002"
coords:
x: 122
y: 244
Seas:
headline: "The Best Ride in the World Is: The Seas with Nemo & Friends®"
text: "<strong>Rich:</strong> The Finding Nemo ride is a cheap-looking knock-off of something you’d find in the Magic Kingdom, and keeping dolphins captive is despicable. But you know what? The manatees and their story of survival via freeloading had me captivated."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-the-seas-with-nemo-fri-1699558430"
coords:
x: 162
y: 330
Living:
headline: "The Best Ride in the World Is: Living With the Land"
text: "<strong>Caity:</strong> I was so worried I was going to get kicked out of the park that I made a point to gesticulate wildly for the rest of the ride."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-living-with-the-land-1699539150"
coords:
x: 247
y: 282
Circle:
headline: "The Best Ride in the World Is: The Circle of Life"
text: "<strong><NAME>:</strong> <NAME> seemed like he was going to approach the topic of why dams are bad, which is something I’ve been meaning to get around to learning myself."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-the-circle-of-life-1699554892"
coords:
x: 241
y: 308
Soarin:
headline: "The Best Ride in the World Is: Soarin'®"
text: "<strong>Caity:</strong> Idiotically, the ride only simulates hang gliding over various parts of California, even though there is a whole world over which to hang glide."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-soarin-1699562403"
coords:
x: 277
y: 296
Captain:
headline: "The Best Ride in the World Is: Captain EO <NAME>arring <NAME>"
text: "<strong><NAME>:</strong> I gasped along with all of the toddlers who delighted at the reveal.<br><strong>Caity:</strong> My hands flew to my mouth in shock. I could not believe it."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-captain-eo-starring-mich-1699555451"
coords:
x: 297
y: 268
Journey:
headline: "The Best Ride in the World Is: Journey Into Imagination with Figment"
text: "<strong>Rich:</strong> I can’t eat at a kitchen table upside down!"
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-journey-into-imagination-1699560979"
coords:
x: 266
y: 238
Canada:
headline: "The Best Restaurant in the World Is: Canada's Le Cellier"
text: "<strong>Caity:</strong> I think the Canadians are just not equipped, emotionally or militarily, to accommodate furious Americans."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-le-cellier-1699426233"
coords:
x: 313
y: 215
UK:
headline: "The Best Restaurant in the World Is: The UK's Rose & Crown Pub & Dining Room"
text: "<strong>Caity:</strong> G L U T E N - F R E E F A M I L Y."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-the-uks-rose-cro-1699494369"
coords:
x: 397
y: 181
France:
headline: "The Best Restaurant in the World Is: France's Les Chefs de France"
text: "<strong>Caity:</strong> You feel that we have been overly harsh on our waitress, a queer little French girl, raised in an all girls school by <NAME>. But what happened next was truly the most bizarre and uncomfortable waiter interaction of my life."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-frances-les-chefs-1699499193"
coords:
x: 480
y: 147
Innoventions:
headline: "The Best Ride in the World Is: Innoventions"
text: "<strong>Caity:</strong> The Sum of All Thrills was terrifying to behold and fun to experience. The best kept secret in Epcot, and possibly the entire world."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-innoventions-1699566319"
coords:
x: 161
y: 201
Drinking:
headline: "Shot, Sake, Margarita, Slush: The Best Drinking Around the World"
text: "<strong>Rich:</strong> Inside China's giant store, I was tempted by Chinese ghost stories, giant fans to take with me to the club, and an incense burner with a dragon gazing into a crystal ball."
url: "http://bestrestaurant.gawker.com/shot-sake-margarita-slush-the-best-drinking-around-1699537518"
coords:
x: 218
y: 156
Illuminations:
headline: "The Best Spectacle in the World Is: IllumiNations: Reflections of Earth"
text: "<strong>Caity:</strong> You have to line up obscenely early for the nightly fireworks show, not because you actually have to, but because Epcot expends so much effort making you believe you have to, that it creates a ripple panic effect through the park, and you end up actually having to."
url: "http://bestrestaurant.gawker.com/the-best-spectacle-in-the-world-is-illuminations-refl-1699567497"
coords:
x: 296
y: 111
Germany:
headline: "The Best Restaurant in the World Is: Germany's Biergarten Restaurant"
text: "<strong><NAME>:</strong> I thought the Bavarian cheesecake was excellent. “It’s just like my mother’s!” <NAME> gushed. This felt overly on the nose, but I was so in love with her and the sister that she calls cheesecake that I felt no need to call bullshit."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-germanys-biergarte-1699495170#_ga=1.160226557.1794012354.1428955654"
coords:
x: 259
y: 25
Italy:
headline: "The Best Restaurant in the World Is: Italy's Via Napoli"
text: "<strong>Rich:</strong> Via Napoli was wall-to-wall beautiful men holding pizzas. This was like Italy in reverse: the guys are all hot and none of them make passes at you."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-italys-via-napoli-1699429900"
coords:
x: 326
y: 12
Adventure:
headline: "The Best Restaurant in the World Is: America's Unnamed Funnel Cake Kiosk"
text: "<strong>Rich:</strong> The funnel cake came with what a giant might call a “pat” of ice cream. In actuality, it was bigger than a slice of bread, that pat of ice cream."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-americas-unnamed-f-1699509155#_ga=1.159382394.1794012354.1428955654"
coords:
x: 388
y: 36
China:
headline: "The Best Restaurant in the World Is: China's Joy of Tea"
text: "<strong>Caity:</strong> I was ready to die at that pavilion, fighting for my Lucky Combo."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-chinas-joy-of-tea-1699428916"
coords:
x: 183
y: 56
Japan:
headline: "The Best Restaurant in the World Is: Japan's Teppan Edo"
text: "<strong>Caity:</strong> “I made you origami,” she said. She did not make the French Canadians origami, perhaps because they had spilled Diet Coke."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-japans-teppan-edo-1699498320"
coords:
x: 447
y: 60
Morocco:
headline: "The Best Restaurant in the World Is: Morocco's Restaurant Marrakesh"
text: "<strong>Rich:</strong> I really liked that your meal explored beef in two of its three states: water and solid. If they could engineer a beef air, Restaurant Marrakesh would."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-moroccos-restauran-1699489246"
coords:
x: 465
y: 98
| true | module.exports =
Norway:
headline: "The Best Restaurant in the World Is: Norway's Kringla Bakeri Og Kafe"
text: "<strong>Rich:</strong> “Is it too much?” you asked. Before I could answer, a female patron in line behind us piped up: “You’re at Disney. It’s not too much.”"
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-norway-1699415308"
coords:
x: 150
y: 94
Mexico:
headline: "The Best Restaurant in the World Is: Mexico's San Angel Inn Restaurante"
text: "<strong>Caity:</strong> I got a Wild Passionfruit Margarita and that’s how it made me feel! I give the Wild Passionfruit Margarita one hundred out of one hundred stars."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-mexicos-san-angel-1699425811"
coords:
x: 139
y: 123
Test:
headline: "The Best Ride in the World Is: Test Track® Presented by Chevrolet®"
text: "<strong>Rich:</strong> That was exciting! Would a giant truck end our lives right there and then in Epcot? Perhaps!"
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-test-track-presented-by-1699557476"
coords:
x: 50
y: 145
Mission:
headline: "The Best Ride in the World Is: Mission: SPACE"
text: "<strong>Rich:</strong> Mission: SPACE is a vomit factory. Worst of all, you are told at the beginning that if you start to feel sick you should not close your eyes."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-mission-space-1699556680"
coords:
x: 30
y: 174
Ellen:
headline: "The Best Ride in the World Is: Ellen's Energy Adventure"
text: "<strong>Rich:</strong> This “ride” is mostly a movie in a theater. It stars PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI and debuted in 1996. That was before PI:NAME:<NAME>END_PI was out."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-ellens-energy-adventure-1699566900"
coords:
x: 30
y: 219
Spaceship:
headline: "The Best Ride in the World Is: Spaceship Earth"
text: "<strong>Caity:</strong> I could not believe how lifelike the features and movements of the animatronic figures were. I would say they are about 85% of the way to being indistinguishable from humans."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-spaceship-earth-1699556002"
coords:
x: 122
y: 244
Seas:
headline: "The Best Ride in the World Is: The Seas with Nemo & Friends®"
text: "<strong>Rich:</strong> The Finding Nemo ride is a cheap-looking knock-off of something you’d find in the Magic Kingdom, and keeping dolphins captive is despicable. But you know what? The manatees and their story of survival via freeloading had me captivated."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-the-seas-with-nemo-fri-1699558430"
coords:
x: 162
y: 330
Living:
headline: "The Best Ride in the World Is: Living With the Land"
text: "<strong>Caity:</strong> I was so worried I was going to get kicked out of the park that I made a point to gesticulate wildly for the rest of the ride."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-living-with-the-land-1699539150"
coords:
x: 247
y: 282
Circle:
headline: "The Best Ride in the World Is: The Circle of Life"
text: "<strong>PI:NAME:<NAME>END_PI:</strong> PI:NAME:<NAME>END_PI seemed like he was going to approach the topic of why dams are bad, which is something I’ve been meaning to get around to learning myself."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-the-circle-of-life-1699554892"
coords:
x: 241
y: 308
Soarin:
headline: "The Best Ride in the World Is: Soarin'®"
text: "<strong>Caity:</strong> Idiotically, the ride only simulates hang gliding over various parts of California, even though there is a whole world over which to hang glide."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-soarin-1699562403"
coords:
x: 277
y: 296
Captain:
headline: "The Best Ride in the World Is: Captain EO PI:NAME:<NAME>END_PIarring PI:NAME:<NAME>END_PI"
text: "<strong>PI:NAME:<NAME>END_PI:</strong> I gasped along with all of the toddlers who delighted at the reveal.<br><strong>Caity:</strong> My hands flew to my mouth in shock. I could not believe it."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-captain-eo-starring-mich-1699555451"
coords:
x: 297
y: 268
Journey:
headline: "The Best Ride in the World Is: Journey Into Imagination with Figment"
text: "<strong>Rich:</strong> I can’t eat at a kitchen table upside down!"
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-journey-into-imagination-1699560979"
coords:
x: 266
y: 238
Canada:
headline: "The Best Restaurant in the World Is: Canada's Le Cellier"
text: "<strong>Caity:</strong> I think the Canadians are just not equipped, emotionally or militarily, to accommodate furious Americans."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-le-cellier-1699426233"
coords:
x: 313
y: 215
UK:
headline: "The Best Restaurant in the World Is: The UK's Rose & Crown Pub & Dining Room"
text: "<strong>Caity:</strong> G L U T E N - F R E E F A M I L Y."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-the-uks-rose-cro-1699494369"
coords:
x: 397
y: 181
France:
headline: "The Best Restaurant in the World Is: France's Les Chefs de France"
text: "<strong>Caity:</strong> You feel that we have been overly harsh on our waitress, a queer little French girl, raised in an all girls school by PI:NAME:<NAME>END_PI. But what happened next was truly the most bizarre and uncomfortable waiter interaction of my life."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-frances-les-chefs-1699499193"
coords:
x: 480
y: 147
Innoventions:
headline: "The Best Ride in the World Is: Innoventions"
text: "<strong>Caity:</strong> The Sum of All Thrills was terrifying to behold and fun to experience. The best kept secret in Epcot, and possibly the entire world."
url: "http://bestrestaurant.gawker.com/the-best-ride-in-the-world-is-innoventions-1699566319"
coords:
x: 161
y: 201
Drinking:
headline: "Shot, Sake, Margarita, Slush: The Best Drinking Around the World"
text: "<strong>Rich:</strong> Inside China's giant store, I was tempted by Chinese ghost stories, giant fans to take with me to the club, and an incense burner with a dragon gazing into a crystal ball."
url: "http://bestrestaurant.gawker.com/shot-sake-margarita-slush-the-best-drinking-around-1699537518"
coords:
x: 218
y: 156
Illuminations:
headline: "The Best Spectacle in the World Is: IllumiNations: Reflections of Earth"
text: "<strong>Caity:</strong> You have to line up obscenely early for the nightly fireworks show, not because you actually have to, but because Epcot expends so much effort making you believe you have to, that it creates a ripple panic effect through the park, and you end up actually having to."
url: "http://bestrestaurant.gawker.com/the-best-spectacle-in-the-world-is-illuminations-refl-1699567497"
coords:
x: 296
y: 111
Germany:
headline: "The Best Restaurant in the World Is: Germany's Biergarten Restaurant"
text: "<strong>PI:NAME:<NAME>END_PI:</strong> I thought the Bavarian cheesecake was excellent. “It’s just like my mother’s!” PI:NAME:<NAME>END_PI gushed. This felt overly on the nose, but I was so in love with her and the sister that she calls cheesecake that I felt no need to call bullshit."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-germanys-biergarte-1699495170#_ga=1.160226557.1794012354.1428955654"
coords:
x: 259
y: 25
Italy:
headline: "The Best Restaurant in the World Is: Italy's Via Napoli"
text: "<strong>Rich:</strong> Via Napoli was wall-to-wall beautiful men holding pizzas. This was like Italy in reverse: the guys are all hot and none of them make passes at you."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-italys-via-napoli-1699429900"
coords:
x: 326
y: 12
Adventure:
headline: "The Best Restaurant in the World Is: America's Unnamed Funnel Cake Kiosk"
text: "<strong>Rich:</strong> The funnel cake came with what a giant might call a “pat” of ice cream. In actuality, it was bigger than a slice of bread, that pat of ice cream."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-americas-unnamed-f-1699509155#_ga=1.159382394.1794012354.1428955654"
coords:
x: 388
y: 36
China:
headline: "The Best Restaurant in the World Is: China's Joy of Tea"
text: "<strong>Caity:</strong> I was ready to die at that pavilion, fighting for my Lucky Combo."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-chinas-joy-of-tea-1699428916"
coords:
x: 183
y: 56
Japan:
headline: "The Best Restaurant in the World Is: Japan's Teppan Edo"
text: "<strong>Caity:</strong> “I made you origami,” she said. She did not make the French Canadians origami, perhaps because they had spilled Diet Coke."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-japans-teppan-edo-1699498320"
coords:
x: 447
y: 60
Morocco:
headline: "The Best Restaurant in the World Is: Morocco's Restaurant Marrakesh"
text: "<strong>Rich:</strong> I really liked that your meal explored beef in two of its three states: water and solid. If they could engineer a beef air, Restaurant Marrakesh would."
url: "http://bestrestaurant.gawker.com/the-best-restaurant-in-the-world-is-moroccos-restauran-1699489246"
coords:
x: 465
y: 98
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9654585123062134,
"start": 16,
"tag": "NAME",
"value": "Konode"
}
] | src/persist/cache.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# This module provides a simple key-value store suitable as a cache.
# Keys must be strings. Values can be anything except undefined or null.
Moment = require 'moment'
class Cache
# timeToLive: number of milliseconds until an entry expires
constructor: (@timeToLive) ->
@_data = {}
# Accesses the cache entry with the specified key.
#
# key: must be a string
# returns: null or the cache entry value
get: (key) ->
entry = @_data[key]
unless entry?
return null
now = Moment()
# If entry is expired
if entry.expiresAt.isBefore(now)
delete @_data[key]
return null
return entry.value
# Add/replace an entry. If an entry already exists under this key, it is
# replaced and the expiry time is reset.
#
# key: must be a string
# value: anything except null or undefined
set: (key, value) ->
unless value?
throw new Error "cannot add value to cache: #{value}"
@_data[key] = {
expiresAt: Moment().add(@timeToLive, 'ms')
value
}
return
# Update an entry without affecting the expiry time.
# updateFn is provided with the current value of the entry under this key,
# and should return a new value. If no entry exists under this key,
# updateFn is not called and no changes are made.
#
# key: must be a string
# updateFn(oldValue) -> newValue: a function that converts the old value to a new value
# returns: true if entry was updated, false if no entry was found for key
update: (key, updateFn) ->
oldValue = @get(key)
if oldValue?
newValue = updateFn(oldValue)
@_data[key].value = newValue
return true
return false
# Remove the entry with the specified key (if one exists).
#
# key: must be a string
remove: (key) ->
delete @_data[key]
return
module.exports = Cache
| 220948 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# This module provides a simple key-value store suitable as a cache.
# Keys must be strings. Values can be anything except undefined or null.
Moment = require 'moment'
class Cache
# timeToLive: number of milliseconds until an entry expires
constructor: (@timeToLive) ->
@_data = {}
# Accesses the cache entry with the specified key.
#
# key: must be a string
# returns: null or the cache entry value
get: (key) ->
entry = @_data[key]
unless entry?
return null
now = Moment()
# If entry is expired
if entry.expiresAt.isBefore(now)
delete @_data[key]
return null
return entry.value
# Add/replace an entry. If an entry already exists under this key, it is
# replaced and the expiry time is reset.
#
# key: must be a string
# value: anything except null or undefined
set: (key, value) ->
unless value?
throw new Error "cannot add value to cache: #{value}"
@_data[key] = {
expiresAt: Moment().add(@timeToLive, 'ms')
value
}
return
# Update an entry without affecting the expiry time.
# updateFn is provided with the current value of the entry under this key,
# and should return a new value. If no entry exists under this key,
# updateFn is not called and no changes are made.
#
# key: must be a string
# updateFn(oldValue) -> newValue: a function that converts the old value to a new value
# returns: true if entry was updated, false if no entry was found for key
update: (key, updateFn) ->
oldValue = @get(key)
if oldValue?
newValue = updateFn(oldValue)
@_data[key].value = newValue
return true
return false
# Remove the entry with the specified key (if one exists).
#
# key: must be a string
remove: (key) ->
delete @_data[key]
return
module.exports = Cache
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# This module provides a simple key-value store suitable as a cache.
# Keys must be strings. Values can be anything except undefined or null.
Moment = require 'moment'
class Cache
# timeToLive: number of milliseconds until an entry expires
constructor: (@timeToLive) ->
@_data = {}
# Accesses the cache entry with the specified key.
#
# key: must be a string
# returns: null or the cache entry value
get: (key) ->
entry = @_data[key]
unless entry?
return null
now = Moment()
# If entry is expired
if entry.expiresAt.isBefore(now)
delete @_data[key]
return null
return entry.value
# Add/replace an entry. If an entry already exists under this key, it is
# replaced and the expiry time is reset.
#
# key: must be a string
# value: anything except null or undefined
set: (key, value) ->
unless value?
throw new Error "cannot add value to cache: #{value}"
@_data[key] = {
expiresAt: Moment().add(@timeToLive, 'ms')
value
}
return
# Update an entry without affecting the expiry time.
# updateFn is provided with the current value of the entry under this key,
# and should return a new value. If no entry exists under this key,
# updateFn is not called and no changes are made.
#
# key: must be a string
# updateFn(oldValue) -> newValue: a function that converts the old value to a new value
# returns: true if entry was updated, false if no entry was found for key
update: (key, updateFn) ->
oldValue = @get(key)
if oldValue?
newValue = updateFn(oldValue)
@_data[key].value = newValue
return true
return false
# Remove the entry with the specified key (if one exists).
#
# key: must be a string
remove: (key) ->
delete @_data[key]
return
module.exports = Cache
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9988306164741516,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/pummel/test-crypto-dh.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
try
crypto = require("crypto")
catch e
console.log "Not compiled with OPENSSL support."
process.exit()
assert.throws ->
crypto.getDiffieHellman "unknown-group"
return
assert.throws ->
crypto.getDiffieHellman("modp1").setPrivateKey ""
return
assert.throws ->
crypto.getDiffieHellman("modp1").setPublicKey ""
return
hashes =
modp1: "b4b330a6ffeacfbd861e7fe2135b4431"
modp2: "7c3c5cad8b9f378d88f1dd64a4b6413a"
modp5: "b1d2acc22c542e08669a5c5ae812694d"
modp14: "8d041538cecc1a7d915ba4b718f8ad20"
modp15: "dc3b93def24e078c4fbf92d5e14ba69b"
modp16: "a273487f46f699461f613b3878d9dfd9"
modp17: "dc76e09935310348c492de9bd82014d0"
modp18: "db08973bfd2371758a69db180871c993"
for name of hashes
group = crypto.getDiffieHellman(name)
private_key = group.getPrime("hex")
hash1 = hashes[name]
hash2 = crypto.createHash("md5").update(private_key.toUpperCase()).digest("hex")
assert.equal hash1, hash2
assert.equal group.getGenerator("hex"), "02"
for name of hashes
group1 = crypto.getDiffieHellman(name)
group2 = crypto.getDiffieHellman(name)
group1.generateKeys()
group2.generateKeys()
key1 = group1.computeSecret(group2.getPublicKey())
key2 = group2.computeSecret(group1.getPublicKey())
assert.deepEqual key1, key2
| 36738 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
try
crypto = require("crypto")
catch e
console.log "Not compiled with OPENSSL support."
process.exit()
assert.throws ->
crypto.getDiffieHellman "unknown-group"
return
assert.throws ->
crypto.getDiffieHellman("modp1").setPrivateKey ""
return
assert.throws ->
crypto.getDiffieHellman("modp1").setPublicKey ""
return
hashes =
modp1: "b4b330a6ffeacfbd861e7fe2135b4431"
modp2: "7c3c5cad8b9f378d88f1dd64a4b6413a"
modp5: "b1d2acc22c542e08669a5c5ae812694d"
modp14: "8d041538cecc1a7d915ba4b718f8ad20"
modp15: "dc3b93def24e078c4fbf92d5e14ba69b"
modp16: "a273487f46f699461f613b3878d9dfd9"
modp17: "dc76e09935310348c492de9bd82014d0"
modp18: "db08973bfd2371758a69db180871c993"
for name of hashes
group = crypto.getDiffieHellman(name)
private_key = group.getPrime("hex")
hash1 = hashes[name]
hash2 = crypto.createHash("md5").update(private_key.toUpperCase()).digest("hex")
assert.equal hash1, hash2
assert.equal group.getGenerator("hex"), "02"
for name of hashes
group1 = crypto.getDiffieHellman(name)
group2 = crypto.getDiffieHellman(name)
group1.generateKeys()
group2.generateKeys()
key1 = group1.computeSecret(group2.getPublicKey())
key2 = group2.computeSecret(group1.getPublicKey())
assert.deepEqual key1, key2
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
try
crypto = require("crypto")
catch e
console.log "Not compiled with OPENSSL support."
process.exit()
assert.throws ->
crypto.getDiffieHellman "unknown-group"
return
assert.throws ->
crypto.getDiffieHellman("modp1").setPrivateKey ""
return
assert.throws ->
crypto.getDiffieHellman("modp1").setPublicKey ""
return
hashes =
modp1: "b4b330a6ffeacfbd861e7fe2135b4431"
modp2: "7c3c5cad8b9f378d88f1dd64a4b6413a"
modp5: "b1d2acc22c542e08669a5c5ae812694d"
modp14: "8d041538cecc1a7d915ba4b718f8ad20"
modp15: "dc3b93def24e078c4fbf92d5e14ba69b"
modp16: "a273487f46f699461f613b3878d9dfd9"
modp17: "dc76e09935310348c492de9bd82014d0"
modp18: "db08973bfd2371758a69db180871c993"
for name of hashes
group = crypto.getDiffieHellman(name)
private_key = group.getPrime("hex")
hash1 = hashes[name]
hash2 = crypto.createHash("md5").update(private_key.toUpperCase()).digest("hex")
assert.equal hash1, hash2
assert.equal group.getGenerator("hex"), "02"
for name of hashes
group1 = crypto.getDiffieHellman(name)
group2 = crypto.getDiffieHellman(name)
group1.generateKeys()
group2.generateKeys()
key1 = group1.computeSecret(group2.getPublicKey())
key2 = group2.computeSecret(group1.getPublicKey())
assert.deepEqual key1, key2
|
[
{
"context": "h ->\n\t\t\t@req.session =\n\t\t\t\tuser: _id: @user_id = \"user-id-123\"\n\t\t\t\tdestroy:->\n\t\t\t@req.params = project_id: @pro",
"end": 1971,
"score": 0.5925742387771606,
"start": 1960,
"tag": "USERNAME",
"value": "user-id-123"
},
{
"context": "\n\t\t\t@owner =\n\t\t\t\t_id: ObjectId()\n\t\t\t\tfirst_name: \"Lenny\"\n\t\t\t\tlast_name: \"Lion\"\n\t\t\t\temail: \"test@sharelate",
"end": 2494,
"score": 0.9997121095657349,
"start": 2489,
"tag": "NAME",
"value": "Lenny"
},
{
"context": "bjectId()\n\t\t\t\tfirst_name: \"Lenny\"\n\t\t\t\tlast_name: \"Lion\"\n\t\t\t\temail: \"test@sharelatex.com\"\n\t\t\t\thashed_pass",
"end": 2516,
"score": 0.9996218681335449,
"start": 2512,
"tag": "NAME",
"value": "Lion"
},
{
"context": "t_name: \"Lenny\"\n\t\t\t\tlast_name: \"Lion\"\n\t\t\t\temail: \"test@sharelatex.com\"\n\t\t\t\thashed_password: \"password\" # should not be ",
"end": 2549,
"score": 0.9999316334724426,
"start": 2530,
"tag": "EMAIL",
"value": "test@sharelatex.com"
},
{
"context": "mail: \"test@sharelatex.com\"\n\t\t\t\thashed_password: \"password\" # should not be included\n\n\t\tdescribe \"formatting",
"end": 2581,
"score": 0.9995160102844238,
"start": 2573,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "aborator =\n\t\t\t\t\t_id: ObjectId()\n\t\t\t\t\tfirst_name: \"Douglas\"\n\t\t\t\t\tlast_name: \"Adams\"\n\t\t\t\t\temail: \"doug@sharel",
"end": 3303,
"score": 0.9997053742408752,
"start": 3296,
"tag": "NAME",
"value": "Douglas"
},
{
"context": "tId()\n\t\t\t\t\tfirst_name: \"Douglas\"\n\t\t\t\t\tlast_name: \"Adams\"\n\t\t\t\t\temail: \"doug@sharelatex.com\"\n\t\t\t\t\thashed_pa",
"end": 3327,
"score": 0.9996625185012817,
"start": 3322,
"tag": "NAME",
"value": "Adams"
},
{
"context": "e: \"Douglas\"\n\t\t\t\t\tlast_name: \"Adams\"\n\t\t\t\t\temail: \"doug@sharelatex.com\"\n\t\t\t\t\thashed_password: \"password\" # should not be",
"end": 3361,
"score": 0.9999346733093262,
"start": 3342,
"tag": "EMAIL",
"value": "doug@sharelatex.com"
},
{
"context": "ail: \"doug@sharelatex.com\"\n\t\t\t\t\thashed_password: \"password\" # should not be included\n\t\t\t\t\t\n\t\t\t\t@project =\n\t\t",
"end": 3394,
"score": 0.9995187520980835,
"start": 3386,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "aborator =\n\t\t\t\t\t_id: ObjectId()\n\t\t\t\t\tfirst_name: \"Douglas\"\n\t\t\t\t\tlast_name: \"Adams\"\n\t\t\t\t\temail: \"doug@sharel",
"end": 4119,
"score": 0.9997135996818542,
"start": 4112,
"tag": "NAME",
"value": "Douglas"
},
{
"context": "tId()\n\t\t\t\t\tfirst_name: \"Douglas\"\n\t\t\t\t\tlast_name: \"Adams\"\n\t\t\t\t\temail: \"doug@sharelatex.com\"\n\t\t\t\t\thashed_pa",
"end": 4143,
"score": 0.9996352791786194,
"start": 4138,
"tag": "NAME",
"value": "Adams"
},
{
"context": "e: \"Douglas\"\n\t\t\t\t\tlast_name: \"Adams\"\n\t\t\t\t\temail: \"doug@sharelatex.com\"\n\t\t\t\t\thashed_password: \"password\" # should not be",
"end": 4177,
"score": 0.9999333024024963,
"start": 4158,
"tag": "EMAIL",
"value": "doug@sharelatex.com"
},
{
"context": "ail: \"doug@sharelatex.com\"\n\t\t\t\t\thashed_password: \"password\" # should not be included\n\t\t\t\t\t\n\t\t\t\t@project =\n\t\t",
"end": 4210,
"score": 0.9993746876716614,
"start": 4202,
"tag": "PASSWORD",
"value": "password"
}
] | test/UnitTests/coffee/Collaborators/CollaboratorsControllerTests.coffee | ukasiu/web-sharelatex | 0 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/Collaborators/CollaboratorsController.js"
SandboxedModule = require('sandboxed-module')
events = require "events"
MockRequest = require "../helpers/MockRequest"
MockResponse = require "../helpers/MockResponse"
ObjectId = require("mongojs").ObjectId
describe "CollaboratorsController", ->
beforeEach ->
@CollaboratorsHandler =
removeUserFromProject:sinon.stub()
@CollaboratorsController = SandboxedModule.require modulePath, requires:
"../Project/ProjectGetter": @ProjectGetter = {}
"./CollaboratorsHandler": @CollaboratorsHandler
@res = new MockResponse()
@req = new MockRequest()
@callback = sinon.stub()
describe "getCollaborators", ->
beforeEach ->
@project =
_id: @project_id = "project-id-123"
@collaborators = ["array of collaborators"]
@req.params = Project_id: @project_id
@ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, @project)
@ProjectGetter.populateProjectWithUsers = sinon.stub().callsArgWith(1, null, @project)
@CollaboratorsController._formatCollaborators = sinon.stub().callsArgWith(1, null, @collaborators)
@CollaboratorsController.getCollaborators(@req, @res)
it "should get the project", ->
@ProjectGetter.getProject
.calledWith(@project_id, { owner_ref: true, collaberator_refs: true, readOnly_refs: true })
.should.equal true
it "should populate the users in the project", ->
@ProjectGetter.populateProjectWithUsers
.calledWith(@project)
.should.equal true
it "should format the collaborators", ->
@CollaboratorsController._formatCollaborators
.calledWith(@project)
.should.equal true
it "should return the formatted collaborators", ->
@res.body.should.equal JSON.stringify(@collaborators)
describe "removeSelfFromProject", ->
beforeEach ->
@req.session =
user: _id: @user_id = "user-id-123"
destroy:->
@req.params = project_id: @project_id
@CollaboratorsHandler.removeUserFromProject = sinon.stub().callsArg(2)
@CollaboratorsController.removeSelfFromProject(@req, @res)
it "should remove the logged in user from the project", ->
@CollaboratorsHandler.removeUserFromProject.calledWith(@project_id, @user_id)
it "should return a success code", ->
@res.statusCode.should.equal 204
describe "_formatCollaborators", ->
beforeEach ->
@owner =
_id: ObjectId()
first_name: "Lenny"
last_name: "Lion"
email: "test@sharelatex.com"
hashed_password: "password" # should not be included
describe "formatting the owner", ->
beforeEach ->
@project =
owner_ref: @owner
collaberator_refs: []
@CollaboratorsController._formatCollaborators(@project, @callback)
it "should return the owner with read, write and admin permissions", ->
@formattedOwner = @callback.args[0][1][0]
expect(@formattedOwner).to.deep.equal {
id: @owner._id.toString()
first_name: @owner.first_name
last_name: @owner.last_name
email: @owner.email
permissions: ["read", "write", "admin"]
owner: true
}
describe "formatting a collaborator with write access", ->
beforeEach ->
@collaborator =
_id: ObjectId()
first_name: "Douglas"
last_name: "Adams"
email: "doug@sharelatex.com"
hashed_password: "password" # should not be included
@project =
owner_ref: @owner
collaberator_refs: [ @collaborator ]
@CollaboratorsController._formatCollaborators(@project, @callback)
it "should return the collaborator with read and write permissions", ->
@formattedCollaborator = @callback.args[0][1][1]
expect(@formattedCollaborator).to.deep.equal {
id: @collaborator._id.toString()
first_name: @collaborator.first_name
last_name: @collaborator.last_name
email: @collaborator.email
permissions: ["read", "write"]
owner: false
}
describe "formatting a collaborator with read only access", ->
beforeEach ->
@collaborator =
_id: ObjectId()
first_name: "Douglas"
last_name: "Adams"
email: "doug@sharelatex.com"
hashed_password: "password" # should not be included
@project =
owner_ref: @owner
collaberator_refs: []
readOnly_refs: [ @collaborator ]
@CollaboratorsController._formatCollaborators(@project, @callback)
it "should return the collaborator with read permissions", ->
@formattedCollaborator = @callback.args[0][1][1]
expect(@formattedCollaborator).to.deep.equal {
id: @collaborator._id.toString()
first_name: @collaborator.first_name
last_name: @collaborator.last_name
email: @collaborator.email
permissions: ["read"]
owner: false
}
| 206932 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/Collaborators/CollaboratorsController.js"
SandboxedModule = require('sandboxed-module')
events = require "events"
MockRequest = require "../helpers/MockRequest"
MockResponse = require "../helpers/MockResponse"
ObjectId = require("mongojs").ObjectId
describe "CollaboratorsController", ->
beforeEach ->
@CollaboratorsHandler =
removeUserFromProject:sinon.stub()
@CollaboratorsController = SandboxedModule.require modulePath, requires:
"../Project/ProjectGetter": @ProjectGetter = {}
"./CollaboratorsHandler": @CollaboratorsHandler
@res = new MockResponse()
@req = new MockRequest()
@callback = sinon.stub()
describe "getCollaborators", ->
beforeEach ->
@project =
_id: @project_id = "project-id-123"
@collaborators = ["array of collaborators"]
@req.params = Project_id: @project_id
@ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, @project)
@ProjectGetter.populateProjectWithUsers = sinon.stub().callsArgWith(1, null, @project)
@CollaboratorsController._formatCollaborators = sinon.stub().callsArgWith(1, null, @collaborators)
@CollaboratorsController.getCollaborators(@req, @res)
it "should get the project", ->
@ProjectGetter.getProject
.calledWith(@project_id, { owner_ref: true, collaberator_refs: true, readOnly_refs: true })
.should.equal true
it "should populate the users in the project", ->
@ProjectGetter.populateProjectWithUsers
.calledWith(@project)
.should.equal true
it "should format the collaborators", ->
@CollaboratorsController._formatCollaborators
.calledWith(@project)
.should.equal true
it "should return the formatted collaborators", ->
@res.body.should.equal JSON.stringify(@collaborators)
describe "removeSelfFromProject", ->
beforeEach ->
@req.session =
user: _id: @user_id = "user-id-123"
destroy:->
@req.params = project_id: @project_id
@CollaboratorsHandler.removeUserFromProject = sinon.stub().callsArg(2)
@CollaboratorsController.removeSelfFromProject(@req, @res)
it "should remove the logged in user from the project", ->
@CollaboratorsHandler.removeUserFromProject.calledWith(@project_id, @user_id)
it "should return a success code", ->
@res.statusCode.should.equal 204
describe "_formatCollaborators", ->
beforeEach ->
@owner =
_id: ObjectId()
first_name: "<NAME>"
last_name: "<NAME>"
email: "<EMAIL>"
hashed_password: "<PASSWORD>" # should not be included
describe "formatting the owner", ->
beforeEach ->
@project =
owner_ref: @owner
collaberator_refs: []
@CollaboratorsController._formatCollaborators(@project, @callback)
it "should return the owner with read, write and admin permissions", ->
@formattedOwner = @callback.args[0][1][0]
expect(@formattedOwner).to.deep.equal {
id: @owner._id.toString()
first_name: @owner.first_name
last_name: @owner.last_name
email: @owner.email
permissions: ["read", "write", "admin"]
owner: true
}
describe "formatting a collaborator with write access", ->
beforeEach ->
@collaborator =
_id: ObjectId()
first_name: "<NAME>"
last_name: "<NAME>"
email: "<EMAIL>"
hashed_password: "<PASSWORD>" # should not be included
@project =
owner_ref: @owner
collaberator_refs: [ @collaborator ]
@CollaboratorsController._formatCollaborators(@project, @callback)
it "should return the collaborator with read and write permissions", ->
@formattedCollaborator = @callback.args[0][1][1]
expect(@formattedCollaborator).to.deep.equal {
id: @collaborator._id.toString()
first_name: @collaborator.first_name
last_name: @collaborator.last_name
email: @collaborator.email
permissions: ["read", "write"]
owner: false
}
describe "formatting a collaborator with read only access", ->
beforeEach ->
@collaborator =
_id: ObjectId()
first_name: "<NAME>"
last_name: "<NAME>"
email: "<EMAIL>"
hashed_password: "<PASSWORD>" # should not be included
@project =
owner_ref: @owner
collaberator_refs: []
readOnly_refs: [ @collaborator ]
@CollaboratorsController._formatCollaborators(@project, @callback)
it "should return the collaborator with read permissions", ->
@formattedCollaborator = @callback.args[0][1][1]
expect(@formattedCollaborator).to.deep.equal {
id: @collaborator._id.toString()
first_name: @collaborator.first_name
last_name: @collaborator.last_name
email: @collaborator.email
permissions: ["read"]
owner: false
}
| true | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/Collaborators/CollaboratorsController.js"
SandboxedModule = require('sandboxed-module')
events = require "events"
MockRequest = require "../helpers/MockRequest"
MockResponse = require "../helpers/MockResponse"
ObjectId = require("mongojs").ObjectId
describe "CollaboratorsController", ->
beforeEach ->
@CollaboratorsHandler =
removeUserFromProject:sinon.stub()
@CollaboratorsController = SandboxedModule.require modulePath, requires:
"../Project/ProjectGetter": @ProjectGetter = {}
"./CollaboratorsHandler": @CollaboratorsHandler
@res = new MockResponse()
@req = new MockRequest()
@callback = sinon.stub()
describe "getCollaborators", ->
beforeEach ->
@project =
_id: @project_id = "project-id-123"
@collaborators = ["array of collaborators"]
@req.params = Project_id: @project_id
@ProjectGetter.getProject = sinon.stub().callsArgWith(2, null, @project)
@ProjectGetter.populateProjectWithUsers = sinon.stub().callsArgWith(1, null, @project)
@CollaboratorsController._formatCollaborators = sinon.stub().callsArgWith(1, null, @collaborators)
@CollaboratorsController.getCollaborators(@req, @res)
it "should get the project", ->
@ProjectGetter.getProject
.calledWith(@project_id, { owner_ref: true, collaberator_refs: true, readOnly_refs: true })
.should.equal true
it "should populate the users in the project", ->
@ProjectGetter.populateProjectWithUsers
.calledWith(@project)
.should.equal true
it "should format the collaborators", ->
@CollaboratorsController._formatCollaborators
.calledWith(@project)
.should.equal true
it "should return the formatted collaborators", ->
@res.body.should.equal JSON.stringify(@collaborators)
describe "removeSelfFromProject", ->
beforeEach ->
@req.session =
user: _id: @user_id = "user-id-123"
destroy:->
@req.params = project_id: @project_id
@CollaboratorsHandler.removeUserFromProject = sinon.stub().callsArg(2)
@CollaboratorsController.removeSelfFromProject(@req, @res)
it "should remove the logged in user from the project", ->
@CollaboratorsHandler.removeUserFromProject.calledWith(@project_id, @user_id)
it "should return a success code", ->
@res.statusCode.should.equal 204
describe "_formatCollaborators", ->
beforeEach ->
@owner =
_id: ObjectId()
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
hashed_password: "PI:PASSWORD:<PASSWORD>END_PI" # should not be included
describe "formatting the owner", ->
beforeEach ->
@project =
owner_ref: @owner
collaberator_refs: []
@CollaboratorsController._formatCollaborators(@project, @callback)
it "should return the owner with read, write and admin permissions", ->
@formattedOwner = @callback.args[0][1][0]
expect(@formattedOwner).to.deep.equal {
id: @owner._id.toString()
first_name: @owner.first_name
last_name: @owner.last_name
email: @owner.email
permissions: ["read", "write", "admin"]
owner: true
}
describe "formatting a collaborator with write access", ->
beforeEach ->
@collaborator =
_id: ObjectId()
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
hashed_password: "PI:PASSWORD:<PASSWORD>END_PI" # should not be included
@project =
owner_ref: @owner
collaberator_refs: [ @collaborator ]
@CollaboratorsController._formatCollaborators(@project, @callback)
it "should return the collaborator with read and write permissions", ->
@formattedCollaborator = @callback.args[0][1][1]
expect(@formattedCollaborator).to.deep.equal {
id: @collaborator._id.toString()
first_name: @collaborator.first_name
last_name: @collaborator.last_name
email: @collaborator.email
permissions: ["read", "write"]
owner: false
}
describe "formatting a collaborator with read only access", ->
beforeEach ->
@collaborator =
_id: ObjectId()
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
hashed_password: "PI:PASSWORD:<PASSWORD>END_PI" # should not be included
@project =
owner_ref: @owner
collaberator_refs: []
readOnly_refs: [ @collaborator ]
@CollaboratorsController._formatCollaborators(@project, @callback)
it "should return the collaborator with read permissions", ->
@formattedCollaborator = @callback.args[0][1][1]
expect(@formattedCollaborator).to.deep.equal {
id: @collaborator._id.toString()
first_name: @collaborator.first_name
last_name: @collaborator.last_name
email: @collaborator.email
permissions: ["read"]
owner: false
}
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991805553436279,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-repl-reset-event.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# create a dummy stream that does nothing
testReset = (cb) ->
r = repl.start(
input: dummy
output: dummy
useGlobal: false
)
r.context.foo = 42
r.on "reset", (context) ->
assert !!context, "REPL did not emit a context with reset event"
assert.equal context, r.context, "REPL emitted incorrect context"
assert.equal context.foo, `undefined`, "REPL emitted the previous context, and is not using global as context"
context.foo = 42
cb()
return
r.resetContext()
return
testResetGlobal = (cb) ->
r = repl.start(
input: dummy
output: dummy
useGlobal: true
)
r.context.foo = 42
r.on "reset", (context) ->
assert.equal context.foo, 42, "\"foo\" property is missing from REPL using global as context"
cb()
return
r.resetContext()
return
common = require("../common")
common.globalCheck = false
assert = require("assert")
repl = require("repl")
Stream = require("stream")
dummy = new Stream()
dummy.write = dummy.pause = dummy.resume = ->
dummy.readable = dummy.writable = true
timeout = setTimeout(->
assert.fail "Timeout, REPL did not emit reset events"
return
, 5000)
testReset ->
testResetGlobal ->
clearTimeout timeout
return
return
| 137481 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# create a dummy stream that does nothing
testReset = (cb) ->
r = repl.start(
input: dummy
output: dummy
useGlobal: false
)
r.context.foo = 42
r.on "reset", (context) ->
assert !!context, "REPL did not emit a context with reset event"
assert.equal context, r.context, "REPL emitted incorrect context"
assert.equal context.foo, `undefined`, "REPL emitted the previous context, and is not using global as context"
context.foo = 42
cb()
return
r.resetContext()
return
testResetGlobal = (cb) ->
r = repl.start(
input: dummy
output: dummy
useGlobal: true
)
r.context.foo = 42
r.on "reset", (context) ->
assert.equal context.foo, 42, "\"foo\" property is missing from REPL using global as context"
cb()
return
r.resetContext()
return
common = require("../common")
common.globalCheck = false
assert = require("assert")
repl = require("repl")
Stream = require("stream")
dummy = new Stream()
dummy.write = dummy.pause = dummy.resume = ->
dummy.readable = dummy.writable = true
timeout = setTimeout(->
assert.fail "Timeout, REPL did not emit reset events"
return
, 5000)
testReset ->
testResetGlobal ->
clearTimeout timeout
return
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# create a dummy stream that does nothing
testReset = (cb) ->
r = repl.start(
input: dummy
output: dummy
useGlobal: false
)
r.context.foo = 42
r.on "reset", (context) ->
assert !!context, "REPL did not emit a context with reset event"
assert.equal context, r.context, "REPL emitted incorrect context"
assert.equal context.foo, `undefined`, "REPL emitted the previous context, and is not using global as context"
context.foo = 42
cb()
return
r.resetContext()
return
testResetGlobal = (cb) ->
r = repl.start(
input: dummy
output: dummy
useGlobal: true
)
r.context.foo = 42
r.on "reset", (context) ->
assert.equal context.foo, 42, "\"foo\" property is missing from REPL using global as context"
cb()
return
r.resetContext()
return
common = require("../common")
common.globalCheck = false
assert = require("assert")
repl = require("repl")
Stream = require("stream")
dummy = new Stream()
dummy.write = dummy.pause = dummy.resume = ->
dummy.readable = dummy.writable = true
timeout = setTimeout(->
assert.fail "Timeout, REPL did not emit reset events"
return
, 5000)
testReset ->
testResetGlobal ->
clearTimeout timeout
return
return
|
[
{
"context": "###\n\n Faviconr\n\n Andrey Popp (c) 2013\n\n###\n\nurl = require 'url'\nexpres",
"end": 30,
"score": 0.9998693466186523,
"start": 19,
"tag": "NAME",
"value": "Andrey Popp"
}
] | index.coffee | andreypopp/faviconr | 1 | ###
Faviconr
Andrey Popp (c) 2013
###
url = require 'url'
express = require 'express'
hyperquest = require 'hyperquest'
sax = require 'sax'
checkRel = (v) ->
v == 'icon' or
v == 'shortcut' or
v == 'shortcut icon' or
v == 'icon shortcut'
parseFavicon = (cb) ->
parser = sax.createStream(false)
seen = false
parser.on 'error', (err) ->
cb(err)
parser.on 'opentag', (node) ->
if node.name == 'LINK' and checkRel node.attributes.REL
seen = true
cb(null, node.attributes.HREF)
parser.on 'end', (node) ->
cb(null) unless seen
parser
resolveURL = (uri, cb) ->
hyperquest.get {uri}, (err, response) ->
return cb(err) if err
if /3\d\d/.exec response.statusCode
resolveURL(response.headers.location, cb)
else if /2\d\d/.exec response.statusCode
cb(null, uri)
else
cb(null)
resolveFavicon = (uri, cb) ->
{host, protocol} = url.parse(uri)
resolveURL "#{protocol}//#{host}/favicon.ico", (err, icon) ->
if icon
cb(null, icon)
else
hyperquest(uri: uri, method: 'GET').pipe parseFavicon (err, icon) ->
if err
cb(err)
else if not icon
cb(null)
else
icon = url.resolve(uri, icon)
cb(null, icon)
memoized = (func) ->
cache = {}
(args..., cb) ->
return cb(null, cache[args]) if cache[args]?
func args..., (err, result) ->
cache[args] = result unless err
cb(err, result)
send = (type, req, res, icon) ->
switch type
when 'image' then hyperquest.get(icon).pipe(res)
when 'json' then res.send {icon}
else res.send icon
module.exports = ->
resolveFaviconMemoized = memoized resolveFavicon
app = express()
app.get '/', (req, res) ->
return res.send 400, 'provide URL as url param' unless req.query.url?
resolveFaviconMemoized req.query.url, (err, icon) ->
if err or not icon
res.send 404
else
send (req.query.as or req.accepts('text, image, json')), req, res, icon
app
module.exports.makeApp = module.exports
module.exports.resolveFavicon = resolveFavicon
module.exports.parseFavicon = parseFavicon
| 113349 | ###
Faviconr
<NAME> (c) 2013
###
url = require 'url'
express = require 'express'
hyperquest = require 'hyperquest'
sax = require 'sax'
checkRel = (v) ->
v == 'icon' or
v == 'shortcut' or
v == 'shortcut icon' or
v == 'icon shortcut'
parseFavicon = (cb) ->
parser = sax.createStream(false)
seen = false
parser.on 'error', (err) ->
cb(err)
parser.on 'opentag', (node) ->
if node.name == 'LINK' and checkRel node.attributes.REL
seen = true
cb(null, node.attributes.HREF)
parser.on 'end', (node) ->
cb(null) unless seen
parser
resolveURL = (uri, cb) ->
hyperquest.get {uri}, (err, response) ->
return cb(err) if err
if /3\d\d/.exec response.statusCode
resolveURL(response.headers.location, cb)
else if /2\d\d/.exec response.statusCode
cb(null, uri)
else
cb(null)
resolveFavicon = (uri, cb) ->
{host, protocol} = url.parse(uri)
resolveURL "#{protocol}//#{host}/favicon.ico", (err, icon) ->
if icon
cb(null, icon)
else
hyperquest(uri: uri, method: 'GET').pipe parseFavicon (err, icon) ->
if err
cb(err)
else if not icon
cb(null)
else
icon = url.resolve(uri, icon)
cb(null, icon)
memoized = (func) ->
cache = {}
(args..., cb) ->
return cb(null, cache[args]) if cache[args]?
func args..., (err, result) ->
cache[args] = result unless err
cb(err, result)
send = (type, req, res, icon) ->
switch type
when 'image' then hyperquest.get(icon).pipe(res)
when 'json' then res.send {icon}
else res.send icon
module.exports = ->
resolveFaviconMemoized = memoized resolveFavicon
app = express()
app.get '/', (req, res) ->
return res.send 400, 'provide URL as url param' unless req.query.url?
resolveFaviconMemoized req.query.url, (err, icon) ->
if err or not icon
res.send 404
else
send (req.query.as or req.accepts('text, image, json')), req, res, icon
app
module.exports.makeApp = module.exports
module.exports.resolveFavicon = resolveFavicon
module.exports.parseFavicon = parseFavicon
| true | ###
Faviconr
PI:NAME:<NAME>END_PI (c) 2013
###
url = require 'url'
express = require 'express'
hyperquest = require 'hyperquest'
sax = require 'sax'
checkRel = (v) ->
v == 'icon' or
v == 'shortcut' or
v == 'shortcut icon' or
v == 'icon shortcut'
parseFavicon = (cb) ->
parser = sax.createStream(false)
seen = false
parser.on 'error', (err) ->
cb(err)
parser.on 'opentag', (node) ->
if node.name == 'LINK' and checkRel node.attributes.REL
seen = true
cb(null, node.attributes.HREF)
parser.on 'end', (node) ->
cb(null) unless seen
parser
resolveURL = (uri, cb) ->
hyperquest.get {uri}, (err, response) ->
return cb(err) if err
if /3\d\d/.exec response.statusCode
resolveURL(response.headers.location, cb)
else if /2\d\d/.exec response.statusCode
cb(null, uri)
else
cb(null)
resolveFavicon = (uri, cb) ->
{host, protocol} = url.parse(uri)
resolveURL "#{protocol}//#{host}/favicon.ico", (err, icon) ->
if icon
cb(null, icon)
else
hyperquest(uri: uri, method: 'GET').pipe parseFavicon (err, icon) ->
if err
cb(err)
else if not icon
cb(null)
else
icon = url.resolve(uri, icon)
cb(null, icon)
memoized = (func) ->
cache = {}
(args..., cb) ->
return cb(null, cache[args]) if cache[args]?
func args..., (err, result) ->
cache[args] = result unless err
cb(err, result)
send = (type, req, res, icon) ->
switch type
when 'image' then hyperquest.get(icon).pipe(res)
when 'json' then res.send {icon}
else res.send icon
module.exports = ->
resolveFaviconMemoized = memoized resolveFavicon
app = express()
app.get '/', (req, res) ->
return res.send 400, 'provide URL as url param' unless req.query.url?
resolveFaviconMemoized req.query.url, (err, icon) ->
if err or not icon
res.send 404
else
send (req.query.as or req.accepts('text, image, json')), req, res, icon
app
module.exports.makeApp = module.exports
module.exports.resolveFavicon = resolveFavicon
module.exports.parseFavicon = parseFavicon
|
[
{
"context": "pp/behaviours/hello'\n\n $(\"body\").append \"<p>Hello Anais</p>\"\n\n bye.bye 'Simon'",
"end": 219,
"score": 0.9887545704841614,
"start": 214,
"tag": "NAME",
"value": "Anais"
},
{
"context": "$(\"body\").append \"<p>Hello Anais</p>\"\n\n bye.bye 'Simon'",
"end": 242,
"score": 0.9996938705444336,
"start": 237,
"tag": "NAME",
"value": "Simon"
}
] | examples/hello-world-coffee/behaviours/index.coffee | hanging-gardens/hanging_gardens.js | 0 | $ = require "jquery"
console = require "browser/console"
bye = require "app/behaviours/bye"
$ ()=>
console.log 'hello %o', hello: "hello"
require 'app/behaviours/hello'
$("body").append "<p>Hello Anais</p>"
bye.bye 'Simon' | 118668 | $ = require "jquery"
console = require "browser/console"
bye = require "app/behaviours/bye"
$ ()=>
console.log 'hello %o', hello: "hello"
require 'app/behaviours/hello'
$("body").append "<p>Hello <NAME></p>"
bye.bye '<NAME>' | true | $ = require "jquery"
console = require "browser/console"
bye = require "app/behaviours/bye"
$ ()=>
console.log 'hello %o', hello: "hello"
require 'app/behaviours/hello'
$("body").append "<p>Hello PI:NAME:<NAME>END_PI</p>"
bye.bye 'PI:NAME:<NAME>END_PI' |
[
{
"context": "###\nFretboard Tests\nCopyright Mohit Cheppudira 2013 <mohit@muthanna.com>\n###\n\nclass Vex.Flow.Tes",
"end": 46,
"score": 0.9998812675476074,
"start": 30,
"tag": "NAME",
"value": "Mohit Cheppudira"
},
{
"context": "\nFretboard Tests\nCopyright Mohit Cheppudira 2013 <mohit@muthanna.com>\n###\n\nclass Vex.Flow.Test\n sel = \"#notespace_tes",
"end": 71,
"score": 0.9999260902404785,
"start": 53,
"tag": "EMAIL",
"value": "mohit@muthanna.com"
}
] | src/fretboard_test.coffee | MSD200X/fretboard | 43 | ###
Fretboard Tests
Copyright Mohit Cheppudira 2013 <mohit@muthanna.com>
###
class Vex.Flow.Test
sel = "#notespace_testoutput"
id = 0
genID = ->
id++
createTestCanvas = (canvas_sel_name, div_sel_name, test_name) ->
test_div = $('<div></div>').addClass("testcanvas").
attr("id", div_sel_name)
test_div.append($('<div></div>').text(test_name))
test_div.append($('<canvas></canvas>').
attr("id", canvas_sel_name).
text(test_name))
$(sel).append(test_div)
@resizeCanvas: (sel, width, height) ->
$("#" + sel).width(width)
$("#" + sel).attr("width", width)
$("#" + sel).attr("height", height)
@runTest: (name, func, params) ->
test(name, ->
test_canvas_sel = "canvas_" + genID()
test_div_sel = "div_" + genID()
test_canvas = createTestCanvas(test_canvas_sel, test_div_sel, name)
func({
canvas_sel: test_canvas_sel,
div_sel: test_div_sel,
params: params
}, Vex.Flow.Renderer.getCanvasContext)
)
class Vex.Flow.Test.Fretboard
runTest = Vex.Flow.Test.runTest
@Start: ->
module "Vex Fretboard"
runTest("Basic Test", @basic)
runTest("Lightup Test", @lightFret)
runTest("Lightup with Text", @lightFretText)
test("Parse Options", @parseOptions)
test("Parse Lights", @parseLights)
runTest("FretboardDiv Width", @divTestWidth)
runTest("FretboardDiv Height", @divTestHeight)
runTest("FretboardDiv Frets", @divTestFrets)
runTest("FretboardDiv Strings", @divTestStrings)
runTest("FretboardDiv Seven String", @divTest7String)
runTest("FretboardDiv Lights", @divLights)
runTest("FretboardDiv Light Colors", @divLightColors)
runTest("FretboardDiv Note Syntax", @divLightsWithNotes)
runTest("FretboardDiv Start Fret", @divStartFret)
runTest("FretboardDiv Start Fret 10", @divStartFret10)
runTest("FretboardDiv Start Fret Text", @divStartFretText)
# Private methods
parse = (data) ->
fb = new Vex.Flow.FretboardDiv(null)
fb.parse data
catchError = (data, error_type="FretboardError") ->
error =
code: "NoError"
message: "Expected exception not caught"
try
parse data
catch e
error = e
equal(error.code, error_type, error.message)
@basic: (options) ->
ps = new paper.PaperScope()
Vex.Flow.Test.resizeCanvas(options.canvas_sel, 650, 120)
ps.setup(options.canvas_sel)
fretboard = new Vex.Flow.Fretboard(ps)
fretboard.draw()
ok true, "all pass"
@lightFret: (options) ->
ps = new paper.PaperScope()
Vex.Flow.Test.resizeCanvas(options.canvas_sel, 600, 120)
ps.setup(options.canvas_sel)
fretboard = new Vex.Flow.Fretboard(ps)
fretboard.draw()
fretboard.lightUp({fret: 5, string: 5, color: "red"})
fretboard.lightUp({fret: 6, string: 5, color: "#666", fillColor: "white"})
fretboard.lightUp({fret: 6, string: 6, color: "#666"})
fretboard.lightUp({fret: 7, string: 5, color: "blue"})
fretboard.lightUp({fret: 0, string: 2, color: "#666", fillColor: "white"})
ok true, "all pass"
@lightFretText: (options) ->
ps = new paper.PaperScope()
Vex.Flow.Test.resizeCanvas(options.canvas_sel, 600, 150)
ps.setup(options.canvas_sel)
fretboard = new Vex.Flow.Fretboard(ps, {end_fret: 17})
fretboard.draw()
fretboard.lightText({fret: 9, string: 5, text: "F#"})
fretboard.lightText({fret: 9, string: 4, text: "B", color: "#2a2", fillColor: "#efe"})
fretboard.lightText({fret: 3, string: 6, text: "2", color: "black", fillColor: "white"})
fretboard.lightText({fret: 2, string: 5, text: "1"})
fretboard.lightText({fret: 3, string: 2, text: "3"})
fretboard.lightText({fret: 3, string: 1, text: "4"})
fretboard.lightText({fret: 12, string: 4, text: ""})
fretboard.lightText({fret: 0, string: 4, text: "D"})
ok true, "all pass"
@parseOptions: (options) ->
catchError "option blah=boo"
equal true, parse "option tuning=standard"
equal true, parse "option strings=4"
equal true, parse "option frets=17"
ok true, "all pass"
@parseLights: (options) ->
equal true, parse "show fret=ha string=boo color=#555"
catchError "show key=ha string=boo color=#555"
@divTestWidth: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option width=500")
ok true, "all pass"
@divTestHeight: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option height=100")
ok true, "all pass"
@divTestFrets: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option frets=10\noption width=700")
ok true, "all pass"
@divTestStrings: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option strings=4")
ok true, "all pass"
@divTest7String: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option strings=7")
ok true, "all pass"
@divLights: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"show frets=3,5,7 strings=6,5 color=red\n" +
"show fret=3 string=1 text=G")
ok true, "all pass"
@divLightsWithNotes: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"show notes=3/6,5/5 color=red\n" +
"show fret=3 string=1 text=G")
ok true, "all pass"
@divLightColors: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"show frets=3,5,7 strings=6,5 color=red\n" +
"show fret=4 string=1 text=G#\n" +
"show fret=5 string=1 text=A color=#666 fill-color=white\n" +
"show fret=6 string=1 text=Bb fill-color=#afa color=black\n" +
"show frets=4,5,7 strings=4,3 color=blue fill-color=white\n")
ok true, "all pass"
@divStartFret: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"option start=5\n" +
"option frets=10\n" +
"option width=400\n" +
"show frets=5,7,9 strings=6,5 color=red\n" +
"show fret=7 string=1 text=G")
ok true, "all pass"
@divStartFretText: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"option start=5\n" +
"option frets=10\n" +
"option width=400\n" +
"option start-text=5th Fret\n" +
"show frets=5,7,9 strings=6,5 color=red\n" +
"show fret=7 string=1 text=G")
ok true, "all pass"
@divStartFret10: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"option start=10\n" +
"option frets=16\n" +
"option width=400\n" +
"show frets=10,12,15 strings=6,5 color=red\n" +
"show fret=12 string=1 text=X")
ok true, "all pass"
| 26616 | ###
Fretboard Tests
Copyright <NAME> 2013 <<EMAIL>>
###
class Vex.Flow.Test
sel = "#notespace_testoutput"
id = 0
genID = ->
id++
createTestCanvas = (canvas_sel_name, div_sel_name, test_name) ->
test_div = $('<div></div>').addClass("testcanvas").
attr("id", div_sel_name)
test_div.append($('<div></div>').text(test_name))
test_div.append($('<canvas></canvas>').
attr("id", canvas_sel_name).
text(test_name))
$(sel).append(test_div)
@resizeCanvas: (sel, width, height) ->
$("#" + sel).width(width)
$("#" + sel).attr("width", width)
$("#" + sel).attr("height", height)
@runTest: (name, func, params) ->
test(name, ->
test_canvas_sel = "canvas_" + genID()
test_div_sel = "div_" + genID()
test_canvas = createTestCanvas(test_canvas_sel, test_div_sel, name)
func({
canvas_sel: test_canvas_sel,
div_sel: test_div_sel,
params: params
}, Vex.Flow.Renderer.getCanvasContext)
)
class Vex.Flow.Test.Fretboard
runTest = Vex.Flow.Test.runTest
@Start: ->
module "Vex Fretboard"
runTest("Basic Test", @basic)
runTest("Lightup Test", @lightFret)
runTest("Lightup with Text", @lightFretText)
test("Parse Options", @parseOptions)
test("Parse Lights", @parseLights)
runTest("FretboardDiv Width", @divTestWidth)
runTest("FretboardDiv Height", @divTestHeight)
runTest("FretboardDiv Frets", @divTestFrets)
runTest("FretboardDiv Strings", @divTestStrings)
runTest("FretboardDiv Seven String", @divTest7String)
runTest("FretboardDiv Lights", @divLights)
runTest("FretboardDiv Light Colors", @divLightColors)
runTest("FretboardDiv Note Syntax", @divLightsWithNotes)
runTest("FretboardDiv Start Fret", @divStartFret)
runTest("FretboardDiv Start Fret 10", @divStartFret10)
runTest("FretboardDiv Start Fret Text", @divStartFretText)
# Private methods
parse = (data) ->
fb = new Vex.Flow.FretboardDiv(null)
fb.parse data
catchError = (data, error_type="FretboardError") ->
error =
code: "NoError"
message: "Expected exception not caught"
try
parse data
catch e
error = e
equal(error.code, error_type, error.message)
@basic: (options) ->
ps = new paper.PaperScope()
Vex.Flow.Test.resizeCanvas(options.canvas_sel, 650, 120)
ps.setup(options.canvas_sel)
fretboard = new Vex.Flow.Fretboard(ps)
fretboard.draw()
ok true, "all pass"
@lightFret: (options) ->
ps = new paper.PaperScope()
Vex.Flow.Test.resizeCanvas(options.canvas_sel, 600, 120)
ps.setup(options.canvas_sel)
fretboard = new Vex.Flow.Fretboard(ps)
fretboard.draw()
fretboard.lightUp({fret: 5, string: 5, color: "red"})
fretboard.lightUp({fret: 6, string: 5, color: "#666", fillColor: "white"})
fretboard.lightUp({fret: 6, string: 6, color: "#666"})
fretboard.lightUp({fret: 7, string: 5, color: "blue"})
fretboard.lightUp({fret: 0, string: 2, color: "#666", fillColor: "white"})
ok true, "all pass"
@lightFretText: (options) ->
ps = new paper.PaperScope()
Vex.Flow.Test.resizeCanvas(options.canvas_sel, 600, 150)
ps.setup(options.canvas_sel)
fretboard = new Vex.Flow.Fretboard(ps, {end_fret: 17})
fretboard.draw()
fretboard.lightText({fret: 9, string: 5, text: "F#"})
fretboard.lightText({fret: 9, string: 4, text: "B", color: "#2a2", fillColor: "#efe"})
fretboard.lightText({fret: 3, string: 6, text: "2", color: "black", fillColor: "white"})
fretboard.lightText({fret: 2, string: 5, text: "1"})
fretboard.lightText({fret: 3, string: 2, text: "3"})
fretboard.lightText({fret: 3, string: 1, text: "4"})
fretboard.lightText({fret: 12, string: 4, text: ""})
fretboard.lightText({fret: 0, string: 4, text: "D"})
ok true, "all pass"
@parseOptions: (options) ->
catchError "option blah=boo"
equal true, parse "option tuning=standard"
equal true, parse "option strings=4"
equal true, parse "option frets=17"
ok true, "all pass"
@parseLights: (options) ->
equal true, parse "show fret=ha string=boo color=#555"
catchError "show key=ha string=boo color=#555"
@divTestWidth: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option width=500")
ok true, "all pass"
@divTestHeight: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option height=100")
ok true, "all pass"
@divTestFrets: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option frets=10\noption width=700")
ok true, "all pass"
@divTestStrings: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option strings=4")
ok true, "all pass"
@divTest7String: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option strings=7")
ok true, "all pass"
@divLights: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"show frets=3,5,7 strings=6,5 color=red\n" +
"show fret=3 string=1 text=G")
ok true, "all pass"
@divLightsWithNotes: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"show notes=3/6,5/5 color=red\n" +
"show fret=3 string=1 text=G")
ok true, "all pass"
@divLightColors: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"show frets=3,5,7 strings=6,5 color=red\n" +
"show fret=4 string=1 text=G#\n" +
"show fret=5 string=1 text=A color=#666 fill-color=white\n" +
"show fret=6 string=1 text=Bb fill-color=#afa color=black\n" +
"show frets=4,5,7 strings=4,3 color=blue fill-color=white\n")
ok true, "all pass"
@divStartFret: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"option start=5\n" +
"option frets=10\n" +
"option width=400\n" +
"show frets=5,7,9 strings=6,5 color=red\n" +
"show fret=7 string=1 text=G")
ok true, "all pass"
@divStartFretText: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"option start=5\n" +
"option frets=10\n" +
"option width=400\n" +
"option start-text=5th Fret\n" +
"show frets=5,7,9 strings=6,5 color=red\n" +
"show fret=7 string=1 text=G")
ok true, "all pass"
@divStartFret10: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"option start=10\n" +
"option frets=16\n" +
"option width=400\n" +
"show frets=10,12,15 strings=6,5 color=red\n" +
"show fret=12 string=1 text=X")
ok true, "all pass"
| true | ###
Fretboard Tests
Copyright PI:NAME:<NAME>END_PI 2013 <PI:EMAIL:<EMAIL>END_PI>
###
class Vex.Flow.Test
sel = "#notespace_testoutput"
id = 0
genID = ->
id++
createTestCanvas = (canvas_sel_name, div_sel_name, test_name) ->
test_div = $('<div></div>').addClass("testcanvas").
attr("id", div_sel_name)
test_div.append($('<div></div>').text(test_name))
test_div.append($('<canvas></canvas>').
attr("id", canvas_sel_name).
text(test_name))
$(sel).append(test_div)
@resizeCanvas: (sel, width, height) ->
$("#" + sel).width(width)
$("#" + sel).attr("width", width)
$("#" + sel).attr("height", height)
@runTest: (name, func, params) ->
test(name, ->
test_canvas_sel = "canvas_" + genID()
test_div_sel = "div_" + genID()
test_canvas = createTestCanvas(test_canvas_sel, test_div_sel, name)
func({
canvas_sel: test_canvas_sel,
div_sel: test_div_sel,
params: params
}, Vex.Flow.Renderer.getCanvasContext)
)
class Vex.Flow.Test.Fretboard
runTest = Vex.Flow.Test.runTest
@Start: ->
module "Vex Fretboard"
runTest("Basic Test", @basic)
runTest("Lightup Test", @lightFret)
runTest("Lightup with Text", @lightFretText)
test("Parse Options", @parseOptions)
test("Parse Lights", @parseLights)
runTest("FretboardDiv Width", @divTestWidth)
runTest("FretboardDiv Height", @divTestHeight)
runTest("FretboardDiv Frets", @divTestFrets)
runTest("FretboardDiv Strings", @divTestStrings)
runTest("FretboardDiv Seven String", @divTest7String)
runTest("FretboardDiv Lights", @divLights)
runTest("FretboardDiv Light Colors", @divLightColors)
runTest("FretboardDiv Note Syntax", @divLightsWithNotes)
runTest("FretboardDiv Start Fret", @divStartFret)
runTest("FretboardDiv Start Fret 10", @divStartFret10)
runTest("FretboardDiv Start Fret Text", @divStartFretText)
# Private methods
parse = (data) ->
fb = new Vex.Flow.FretboardDiv(null)
fb.parse data
catchError = (data, error_type="FretboardError") ->
error =
code: "NoError"
message: "Expected exception not caught"
try
parse data
catch e
error = e
equal(error.code, error_type, error.message)
@basic: (options) ->
ps = new paper.PaperScope()
Vex.Flow.Test.resizeCanvas(options.canvas_sel, 650, 120)
ps.setup(options.canvas_sel)
fretboard = new Vex.Flow.Fretboard(ps)
fretboard.draw()
ok true, "all pass"
@lightFret: (options) ->
ps = new paper.PaperScope()
Vex.Flow.Test.resizeCanvas(options.canvas_sel, 600, 120)
ps.setup(options.canvas_sel)
fretboard = new Vex.Flow.Fretboard(ps)
fretboard.draw()
fretboard.lightUp({fret: 5, string: 5, color: "red"})
fretboard.lightUp({fret: 6, string: 5, color: "#666", fillColor: "white"})
fretboard.lightUp({fret: 6, string: 6, color: "#666"})
fretboard.lightUp({fret: 7, string: 5, color: "blue"})
fretboard.lightUp({fret: 0, string: 2, color: "#666", fillColor: "white"})
ok true, "all pass"
@lightFretText: (options) ->
ps = new paper.PaperScope()
Vex.Flow.Test.resizeCanvas(options.canvas_sel, 600, 150)
ps.setup(options.canvas_sel)
fretboard = new Vex.Flow.Fretboard(ps, {end_fret: 17})
fretboard.draw()
fretboard.lightText({fret: 9, string: 5, text: "F#"})
fretboard.lightText({fret: 9, string: 4, text: "B", color: "#2a2", fillColor: "#efe"})
fretboard.lightText({fret: 3, string: 6, text: "2", color: "black", fillColor: "white"})
fretboard.lightText({fret: 2, string: 5, text: "1"})
fretboard.lightText({fret: 3, string: 2, text: "3"})
fretboard.lightText({fret: 3, string: 1, text: "4"})
fretboard.lightText({fret: 12, string: 4, text: ""})
fretboard.lightText({fret: 0, string: 4, text: "D"})
ok true, "all pass"
@parseOptions: (options) ->
catchError "option blah=boo"
equal true, parse "option tuning=standard"
equal true, parse "option strings=4"
equal true, parse "option frets=17"
ok true, "all pass"
@parseLights: (options) ->
equal true, parse "show fret=ha string=boo color=#555"
catchError "show key=ha string=boo color=#555"
@divTestWidth: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option width=500")
ok true, "all pass"
@divTestHeight: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option height=100")
ok true, "all pass"
@divTestFrets: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option frets=10\noption width=700")
ok true, "all pass"
@divTestStrings: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option strings=4")
ok true, "all pass"
@divTest7String: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build("option strings=7")
ok true, "all pass"
@divLights: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"show frets=3,5,7 strings=6,5 color=red\n" +
"show fret=3 string=1 text=G")
ok true, "all pass"
@divLightsWithNotes: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"show notes=3/6,5/5 color=red\n" +
"show fret=3 string=1 text=G")
ok true, "all pass"
@divLightColors: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"show frets=3,5,7 strings=6,5 color=red\n" +
"show fret=4 string=1 text=G#\n" +
"show fret=5 string=1 text=A color=#666 fill-color=white\n" +
"show fret=6 string=1 text=Bb fill-color=#afa color=black\n" +
"show frets=4,5,7 strings=4,3 color=blue fill-color=white\n")
ok true, "all pass"
@divStartFret: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"option start=5\n" +
"option frets=10\n" +
"option width=400\n" +
"show frets=5,7,9 strings=6,5 color=red\n" +
"show fret=7 string=1 text=G")
ok true, "all pass"
@divStartFretText: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"option start=5\n" +
"option frets=10\n" +
"option width=400\n" +
"option start-text=5th Fret\n" +
"show frets=5,7,9 strings=6,5 color=red\n" +
"show fret=7 string=1 text=G")
ok true, "all pass"
@divStartFret10: (options) ->
div = new Vex.Flow.FretboardDiv("#"+options.canvas_sel)
div.build(
"option start=10\n" +
"option frets=16\n" +
"option width=400\n" +
"show frets=10,12,15 strings=6,5 color=red\n" +
"show fret=12 string=1 text=X")
ok true, "all pass"
|
[
{
"context": "# Vex Fretboard\n#\n# Uses PaperJS.\n# Copyright Mohit Muthanna Cheppudira 2013\n\nclass Vex.Flow.Fretboard\n @DEBUG = false\n ",
"end": 71,
"score": 0.9998824000358582,
"start": 46,
"tag": "NAME",
"value": "Mohit Muthanna Cheppudira"
}
] | src/fretboard.coffee | MSD200X/fretboard | 43 | # Vex Fretboard
#
# Uses PaperJS.
# Copyright Mohit Muthanna Cheppudira 2013
class Vex.Flow.Fretboard
@DEBUG = false
L = (args...) -> console?.log("(Vex.Flow.Fretboard)", args...) if Vex.Flow.Fretboard.DEBUG
constructor: (@paper, options) ->
L "constructor: options=", options
@options =
strings: 6
start_fret: 1
end_fret: 22
tuning: "standard"
color: "black"
marker_color: "#aaa"
x: 10
y: 20
width: @paper.view.size.width - 20
height: @paper.view.size.height - 40
marker_radius: 4
font_face: "Arial"
font_size: 12
font_color: "black"
nut_color: "#aaa"
start_fret_text: null
_.extend(@options, options)
@reset()
error = (msg) -> new Vex.RERR("FretboardError", msg)
reset: ->
L "reset()"
throw error("Too few strings: " + @options.strings) if @options.strings < 2
throw error("Too few frets: " + @options.end_fret) if (@options.end_fret - @options.start_fret) < 3
@x = @options.x
@y = @options.y
@width = @options.width
@nut_width = 10
@start_fret = parseInt(@options.start_fret, 10)
@end_fret = parseInt(@options.end_fret, 10)
@total_frets = @end_fret - @start_fret
if @end_fret <= @start_fret
throw error("Start fret number must be lower than end fret number: #{@start_fret} >= #{@end_fret}")
@start_fret_text = if @options.start_fret_text? then @options.start_fret_text else @start_fret
@height = @options.height - (if @start_fret == 0 then 0 else 10)
@string_spacing = @height / (@options.strings - 1)
@fret_spacing = (@width - @nut_width) / (@total_frets - 1)
@light_radius = (@string_spacing / 2) - 1
@calculateFretPositions()
calculateFretPositions: ->
L "calculateFretPositions: width=#{@width}"
width = @width - @nut_width
@bridge_to_fret = [width]
@fretXs = [0]
k = 1.05946
for num in [1..@total_frets]
@bridge_to_fret[num] = width / Math.pow(k, num)
@fretXs[num] = width - @bridge_to_fret[num]
# We don't need the entire scale (nut to bridge), so transform
# the X positions.
transform = (x) => (x / @fretXs[@total_frets]) * width
@fretXs = (transform(x) for x in @fretXs)
hasFret: (num) -> num in [(@start_fret - 1)..@end_fret]
hasString: (num) -> num in [1..@options.strings]
getFretX: (num) ->
@fretXs[num - (@start_fret - 1)] + (if @start_fret > 1 then 3 else @nut_width)
getStringY: (num) -> @y + ((num - 1) * @string_spacing)
getFretCenter: (fret, string) ->
start_fret = @options.start_fret
end_fret = @options.end_fret
throw error("Invalid fret: #{fret}") unless @hasFret(fret)
throw error("Invalid string: #{string}") unless @hasString(string)
x = 0
if fret is 0
x = @getFretX(0) + (@nut_width / 2)
else
x = (@getFretX(fret) + @getFretX(fret - 1)) / 2
y = @getStringY(string)
return new @paper.Point(x, y)
drawNut: ->
L "drawNut()"
path = new @paper.Path.RoundRectangle(@x, @y - 5, @nut_width, @height + 10)
path.strokeColor = @options.nut_color
path.fillColor = @options.nut_color
showStartFret: ->
L "showStartFret()"
center = @getFretCenter(@start_fret, 1)
L "Center: ", center
@renderText(new @paper.Point(center.x, @y + @height + 20), @start_fret_text)
drawString: (num) ->
path = new @paper.Path()
path.strokeColor = @options.color
y = @getStringY(num)
start = new @paper.Point(@x, y)
path.moveTo(start)
path.lineTo(start.add([@width, 0]))
drawFret: (num) ->
path = new @paper.Path()
path.strokeColor = @options.color
x = @getFretX(num)
start = new @paper.Point(x, @y)
path.moveTo(start)
path.lineTo(start.add([0, @height]))
drawDot: (x, y, color='red', radius=2) ->
path = new @paper.Path.Circle(new @paper.Point(x, y), radius)
path.strokeColor = color
path.fillColor = color
drawMarkers: ->
L "drawMarkers"
middle_dot = 3
top_dot = 4
bottom_dot = 2
if parseInt(@options.strings, 10) == 4
middle_dot = 2
top_dot = 3
bottom_dot = 1
drawCircle = (start) =>
path = new @paper.Path.Circle(start, @options.marker_radius)
path.strokeColor = @options.marker_color
path.fillColor = @options.marker_color
y_displacement = @string_spacing / 2
for position in [3, 5, 7, 9, 15, 17, 19, 21]
if @hasFret(position)
start = @getFretCenter(position, middle_dot).add([0, y_displacement])
drawCircle(start)
for position in [12, 24]
if @hasFret(position)
start = @getFretCenter(position, bottom_dot).add([0, y_displacement])
drawCircle(start)
start = @getFretCenter(position, top_dot).add([0, y_displacement])
drawCircle(start)
renderText: (point, value, color=@options.font_color, size=@options.font_size) ->
text = new @paper.PointText(point)
text.justification = "center"
text.characterStyle =
font: @options.font_face
fontSize: size
fillColor: color
text.content = value
drawFretNumbers: ->
for position, value of {5: "V", 12: "XII", 19: "XIX"}
fret = parseInt(position, 10)
if @hasFret(fret)
point = @getFretCenter(fret, 6)
point.y = @getStringY(@options.strings + 1)
@renderText(point, value)
lightText: (options) ->
opts =
color: "white"
fillColor: "#666"
_.extend(opts, options)
L "lightUp: ", opts
point = @getFretCenter(opts.fret, opts.string)
path = new @paper.Path.Circle(point, @light_radius)
path.strokeColor = opts.color
path.fillColor = opts.fillColor
y_displacement = @string_spacing / 5
point.y += y_displacement
@renderText(point, opts.text, opts.color) if opts.text?
@paper.view.draw()
lightUp: (options) ->
options.color ?= '#666'
options.fillColor ?= options.color
L "lightUp: ", options
point = @getFretCenter(options.fret, options.string)
path = new @paper.Path.Circle(point, @light_radius - 2)
path.strokeColor = options.color
path.fillColor = options.fillColor
@paper.view.draw()
draw: ->
L "draw()"
for num in [1..@options.strings]
@drawString num
for num in [@start_fret..@end_fret]
@drawFret num
if @start_fret == 1
@drawNut()
else
@showStartFret()
@drawMarkers()
@paper.view.draw()
class Vex.Flow.FretboardDiv
@DEBUG = false
L = (args...) -> console?.log("(Vex.Flow.FretboardDiv)", args...) if Vex.Flow.FretboardDiv.DEBUG
error = (msg) -> new Vex.RERR("FretboardError", msg)
constructor: (@sel, @id) ->
@options =
"width": 700
"height": 150
"strings": 6
"frets": 17
"start": 1
"start-text": null
"tuning": "standard"
throw error("Invalid selector: " + @sel) if @sel? and $(@sel).length == 0
@id ?= $(@sel).attr('id')
@lights = []
setOption: (key, value) ->
if key in _.keys(@options)
L "Option: #{key}=#{value}"
@options[key] = value
else
throw error("Invalid option: " + key)
genFretboardOptions = (options) ->
fboptions = {}
for k, v of options
switch k
when "width", "height"
continue
when "strings"
fboptions.strings = v
when "frets"
fboptions.end_fret = v
when "tuning"
fboptions.tuning = v
when "start"
fboptions.start_fret = v
when "start-text"
fboptions.start_fret_text = v
else
throw error("Invalid option: " + k)
return fboptions
show: (line) ->
options = line.split(/\s+/)
params = {}
valid_options = ["fret", "frets", "string", "strings",
"text", "color", "note", "notes", "fill-color"]
for option in options
match = option.match(/^(\S+)\s*=\s*(\S+)/)
throw error("Invalid 'show' option: " + match[1]) unless match[1] in valid_options
params[match[1]] = match[2] if match?
L "Show: ", params
@lights.push params
parse: (data) ->
L "Parsing: " + data
lines = data.split(/\n/)
for line in lines
line.trim()
match = line.match(/^\s*option\s+(\S+)\s*=\s*(\S+)/)
@setOption(match[1], match[2]) if match?
match = line.match(/^\s*show\s+(.+)/)
@show(match[1]) if match?
return true
extractNumbers = (str) ->
L "ExtractNumbers: ", str
str.trim()
str.split(/\s*,\s*/)
extractNotes = (str) ->
L "ExtractNotes: ", str
str.trim()
notes = str.split(/\s*,\s*/)
extracted_notes = []
for note in notes
parts = note.match(/(\d+)\/(\d+)/)
if parts?
extracted_notes.push(
fret: parseInt(parts[1], 10)
string: parseInt(parts[2], 10))
else
throw error("Invalid note: " + note)
return extracted_notes
extractFrets = (light) ->
frets = extractNumbers(light.fret) if light.fret?
frets = extractNumbers(light.frets) if light.frets?
strings = extractNumbers(light.string) if light.string?
strings = extractNumbers(light.strings) if light.strings?
notes = extractNotes(light.note) if light.note?
notes = extractNotes(light.notes) if light.notes?
throw error("No frets or strings specified on line") if (not (frets? and strings?)) and (not notes?)
lights = []
if frets? and strings?
for fret in frets
for string in strings
lights.push({fret: parseInt(fret, 10), string: parseInt(string, 10)})
if notes?
for note in notes
lights.push(note)
return lights
lightsCameraAction: ->
L @lights
for light in @lights
params = extractFrets(light)
for param in params
param.color = light.color if light.color?
param.fillColor = light["fill-color"] if light["fill-color"]?
L "Lighting up: ", param
if light.text?
param.text = light.text
@fretboard.lightText(param)
else
@fretboard.lightUp(param)
build: (code=null) ->
L "Creating canvas id=#{@id} #{@options.width}x#{@options.height}"
code ?= $(@sel).text()
@parse(code)
canvas = $("<canvas id=#{@id}>").
attr("width", @options.width).
attr("height", @options.height).
attr("id", @id).
width(@options.width)
$(@sel).replaceWith(canvas)
ps = new paper.PaperScope()
ps.setup(document.getElementById(@id))
@fretboard = new Vex.Flow.Fretboard(ps, genFretboardOptions(@options))
@fretboard.draw()
@lightsCameraAction()
| 180435 | # Vex Fretboard
#
# Uses PaperJS.
# Copyright <NAME> 2013
class Vex.Flow.Fretboard
@DEBUG = false
L = (args...) -> console?.log("(Vex.Flow.Fretboard)", args...) if Vex.Flow.Fretboard.DEBUG
constructor: (@paper, options) ->
L "constructor: options=", options
@options =
strings: 6
start_fret: 1
end_fret: 22
tuning: "standard"
color: "black"
marker_color: "#aaa"
x: 10
y: 20
width: @paper.view.size.width - 20
height: @paper.view.size.height - 40
marker_radius: 4
font_face: "Arial"
font_size: 12
font_color: "black"
nut_color: "#aaa"
start_fret_text: null
_.extend(@options, options)
@reset()
error = (msg) -> new Vex.RERR("FretboardError", msg)
reset: ->
L "reset()"
throw error("Too few strings: " + @options.strings) if @options.strings < 2
throw error("Too few frets: " + @options.end_fret) if (@options.end_fret - @options.start_fret) < 3
@x = @options.x
@y = @options.y
@width = @options.width
@nut_width = 10
@start_fret = parseInt(@options.start_fret, 10)
@end_fret = parseInt(@options.end_fret, 10)
@total_frets = @end_fret - @start_fret
if @end_fret <= @start_fret
throw error("Start fret number must be lower than end fret number: #{@start_fret} >= #{@end_fret}")
@start_fret_text = if @options.start_fret_text? then @options.start_fret_text else @start_fret
@height = @options.height - (if @start_fret == 0 then 0 else 10)
@string_spacing = @height / (@options.strings - 1)
@fret_spacing = (@width - @nut_width) / (@total_frets - 1)
@light_radius = (@string_spacing / 2) - 1
@calculateFretPositions()
calculateFretPositions: ->
L "calculateFretPositions: width=#{@width}"
width = @width - @nut_width
@bridge_to_fret = [width]
@fretXs = [0]
k = 1.05946
for num in [1..@total_frets]
@bridge_to_fret[num] = width / Math.pow(k, num)
@fretXs[num] = width - @bridge_to_fret[num]
# We don't need the entire scale (nut to bridge), so transform
# the X positions.
transform = (x) => (x / @fretXs[@total_frets]) * width
@fretXs = (transform(x) for x in @fretXs)
hasFret: (num) -> num in [(@start_fret - 1)..@end_fret]
hasString: (num) -> num in [1..@options.strings]
getFretX: (num) ->
@fretXs[num - (@start_fret - 1)] + (if @start_fret > 1 then 3 else @nut_width)
getStringY: (num) -> @y + ((num - 1) * @string_spacing)
getFretCenter: (fret, string) ->
start_fret = @options.start_fret
end_fret = @options.end_fret
throw error("Invalid fret: #{fret}") unless @hasFret(fret)
throw error("Invalid string: #{string}") unless @hasString(string)
x = 0
if fret is 0
x = @getFretX(0) + (@nut_width / 2)
else
x = (@getFretX(fret) + @getFretX(fret - 1)) / 2
y = @getStringY(string)
return new @paper.Point(x, y)
drawNut: ->
L "drawNut()"
path = new @paper.Path.RoundRectangle(@x, @y - 5, @nut_width, @height + 10)
path.strokeColor = @options.nut_color
path.fillColor = @options.nut_color
showStartFret: ->
L "showStartFret()"
center = @getFretCenter(@start_fret, 1)
L "Center: ", center
@renderText(new @paper.Point(center.x, @y + @height + 20), @start_fret_text)
drawString: (num) ->
path = new @paper.Path()
path.strokeColor = @options.color
y = @getStringY(num)
start = new @paper.Point(@x, y)
path.moveTo(start)
path.lineTo(start.add([@width, 0]))
drawFret: (num) ->
path = new @paper.Path()
path.strokeColor = @options.color
x = @getFretX(num)
start = new @paper.Point(x, @y)
path.moveTo(start)
path.lineTo(start.add([0, @height]))
drawDot: (x, y, color='red', radius=2) ->
path = new @paper.Path.Circle(new @paper.Point(x, y), radius)
path.strokeColor = color
path.fillColor = color
drawMarkers: ->
L "drawMarkers"
middle_dot = 3
top_dot = 4
bottom_dot = 2
if parseInt(@options.strings, 10) == 4
middle_dot = 2
top_dot = 3
bottom_dot = 1
drawCircle = (start) =>
path = new @paper.Path.Circle(start, @options.marker_radius)
path.strokeColor = @options.marker_color
path.fillColor = @options.marker_color
y_displacement = @string_spacing / 2
for position in [3, 5, 7, 9, 15, 17, 19, 21]
if @hasFret(position)
start = @getFretCenter(position, middle_dot).add([0, y_displacement])
drawCircle(start)
for position in [12, 24]
if @hasFret(position)
start = @getFretCenter(position, bottom_dot).add([0, y_displacement])
drawCircle(start)
start = @getFretCenter(position, top_dot).add([0, y_displacement])
drawCircle(start)
renderText: (point, value, color=@options.font_color, size=@options.font_size) ->
text = new @paper.PointText(point)
text.justification = "center"
text.characterStyle =
font: @options.font_face
fontSize: size
fillColor: color
text.content = value
drawFretNumbers: ->
for position, value of {5: "V", 12: "XII", 19: "XIX"}
fret = parseInt(position, 10)
if @hasFret(fret)
point = @getFretCenter(fret, 6)
point.y = @getStringY(@options.strings + 1)
@renderText(point, value)
lightText: (options) ->
opts =
color: "white"
fillColor: "#666"
_.extend(opts, options)
L "lightUp: ", opts
point = @getFretCenter(opts.fret, opts.string)
path = new @paper.Path.Circle(point, @light_radius)
path.strokeColor = opts.color
path.fillColor = opts.fillColor
y_displacement = @string_spacing / 5
point.y += y_displacement
@renderText(point, opts.text, opts.color) if opts.text?
@paper.view.draw()
lightUp: (options) ->
options.color ?= '#666'
options.fillColor ?= options.color
L "lightUp: ", options
point = @getFretCenter(options.fret, options.string)
path = new @paper.Path.Circle(point, @light_radius - 2)
path.strokeColor = options.color
path.fillColor = options.fillColor
@paper.view.draw()
draw: ->
L "draw()"
for num in [1..@options.strings]
@drawString num
for num in [@start_fret..@end_fret]
@drawFret num
if @start_fret == 1
@drawNut()
else
@showStartFret()
@drawMarkers()
@paper.view.draw()
class Vex.Flow.FretboardDiv
@DEBUG = false
L = (args...) -> console?.log("(Vex.Flow.FretboardDiv)", args...) if Vex.Flow.FretboardDiv.DEBUG
error = (msg) -> new Vex.RERR("FretboardError", msg)
constructor: (@sel, @id) ->
@options =
"width": 700
"height": 150
"strings": 6
"frets": 17
"start": 1
"start-text": null
"tuning": "standard"
throw error("Invalid selector: " + @sel) if @sel? and $(@sel).length == 0
@id ?= $(@sel).attr('id')
@lights = []
setOption: (key, value) ->
if key in _.keys(@options)
L "Option: #{key}=#{value}"
@options[key] = value
else
throw error("Invalid option: " + key)
genFretboardOptions = (options) ->
fboptions = {}
for k, v of options
switch k
when "width", "height"
continue
when "strings"
fboptions.strings = v
when "frets"
fboptions.end_fret = v
when "tuning"
fboptions.tuning = v
when "start"
fboptions.start_fret = v
when "start-text"
fboptions.start_fret_text = v
else
throw error("Invalid option: " + k)
return fboptions
show: (line) ->
options = line.split(/\s+/)
params = {}
valid_options = ["fret", "frets", "string", "strings",
"text", "color", "note", "notes", "fill-color"]
for option in options
match = option.match(/^(\S+)\s*=\s*(\S+)/)
throw error("Invalid 'show' option: " + match[1]) unless match[1] in valid_options
params[match[1]] = match[2] if match?
L "Show: ", params
@lights.push params
parse: (data) ->
L "Parsing: " + data
lines = data.split(/\n/)
for line in lines
line.trim()
match = line.match(/^\s*option\s+(\S+)\s*=\s*(\S+)/)
@setOption(match[1], match[2]) if match?
match = line.match(/^\s*show\s+(.+)/)
@show(match[1]) if match?
return true
extractNumbers = (str) ->
L "ExtractNumbers: ", str
str.trim()
str.split(/\s*,\s*/)
extractNotes = (str) ->
L "ExtractNotes: ", str
str.trim()
notes = str.split(/\s*,\s*/)
extracted_notes = []
for note in notes
parts = note.match(/(\d+)\/(\d+)/)
if parts?
extracted_notes.push(
fret: parseInt(parts[1], 10)
string: parseInt(parts[2], 10))
else
throw error("Invalid note: " + note)
return extracted_notes
extractFrets = (light) ->
frets = extractNumbers(light.fret) if light.fret?
frets = extractNumbers(light.frets) if light.frets?
strings = extractNumbers(light.string) if light.string?
strings = extractNumbers(light.strings) if light.strings?
notes = extractNotes(light.note) if light.note?
notes = extractNotes(light.notes) if light.notes?
throw error("No frets or strings specified on line") if (not (frets? and strings?)) and (not notes?)
lights = []
if frets? and strings?
for fret in frets
for string in strings
lights.push({fret: parseInt(fret, 10), string: parseInt(string, 10)})
if notes?
for note in notes
lights.push(note)
return lights
lightsCameraAction: ->
L @lights
for light in @lights
params = extractFrets(light)
for param in params
param.color = light.color if light.color?
param.fillColor = light["fill-color"] if light["fill-color"]?
L "Lighting up: ", param
if light.text?
param.text = light.text
@fretboard.lightText(param)
else
@fretboard.lightUp(param)
build: (code=null) ->
L "Creating canvas id=#{@id} #{@options.width}x#{@options.height}"
code ?= $(@sel).text()
@parse(code)
canvas = $("<canvas id=#{@id}>").
attr("width", @options.width).
attr("height", @options.height).
attr("id", @id).
width(@options.width)
$(@sel).replaceWith(canvas)
ps = new paper.PaperScope()
ps.setup(document.getElementById(@id))
@fretboard = new Vex.Flow.Fretboard(ps, genFretboardOptions(@options))
@fretboard.draw()
@lightsCameraAction()
| true | # Vex Fretboard
#
# Uses PaperJS.
# Copyright PI:NAME:<NAME>END_PI 2013
class Vex.Flow.Fretboard
@DEBUG = false
L = (args...) -> console?.log("(Vex.Flow.Fretboard)", args...) if Vex.Flow.Fretboard.DEBUG
constructor: (@paper, options) ->
L "constructor: options=", options
@options =
strings: 6
start_fret: 1
end_fret: 22
tuning: "standard"
color: "black"
marker_color: "#aaa"
x: 10
y: 20
width: @paper.view.size.width - 20
height: @paper.view.size.height - 40
marker_radius: 4
font_face: "Arial"
font_size: 12
font_color: "black"
nut_color: "#aaa"
start_fret_text: null
_.extend(@options, options)
@reset()
error = (msg) -> new Vex.RERR("FretboardError", msg)
reset: ->
L "reset()"
throw error("Too few strings: " + @options.strings) if @options.strings < 2
throw error("Too few frets: " + @options.end_fret) if (@options.end_fret - @options.start_fret) < 3
@x = @options.x
@y = @options.y
@width = @options.width
@nut_width = 10
@start_fret = parseInt(@options.start_fret, 10)
@end_fret = parseInt(@options.end_fret, 10)
@total_frets = @end_fret - @start_fret
if @end_fret <= @start_fret
throw error("Start fret number must be lower than end fret number: #{@start_fret} >= #{@end_fret}")
@start_fret_text = if @options.start_fret_text? then @options.start_fret_text else @start_fret
@height = @options.height - (if @start_fret == 0 then 0 else 10)
@string_spacing = @height / (@options.strings - 1)
@fret_spacing = (@width - @nut_width) / (@total_frets - 1)
@light_radius = (@string_spacing / 2) - 1
@calculateFretPositions()
calculateFretPositions: ->
L "calculateFretPositions: width=#{@width}"
width = @width - @nut_width
@bridge_to_fret = [width]
@fretXs = [0]
k = 1.05946
for num in [1..@total_frets]
@bridge_to_fret[num] = width / Math.pow(k, num)
@fretXs[num] = width - @bridge_to_fret[num]
# We don't need the entire scale (nut to bridge), so transform
# the X positions.
transform = (x) => (x / @fretXs[@total_frets]) * width
@fretXs = (transform(x) for x in @fretXs)
hasFret: (num) -> num in [(@start_fret - 1)..@end_fret]
hasString: (num) -> num in [1..@options.strings]
getFretX: (num) ->
@fretXs[num - (@start_fret - 1)] + (if @start_fret > 1 then 3 else @nut_width)
getStringY: (num) -> @y + ((num - 1) * @string_spacing)
getFretCenter: (fret, string) ->
start_fret = @options.start_fret
end_fret = @options.end_fret
throw error("Invalid fret: #{fret}") unless @hasFret(fret)
throw error("Invalid string: #{string}") unless @hasString(string)
x = 0
if fret is 0
x = @getFretX(0) + (@nut_width / 2)
else
x = (@getFretX(fret) + @getFretX(fret - 1)) / 2
y = @getStringY(string)
return new @paper.Point(x, y)
drawNut: ->
L "drawNut()"
path = new @paper.Path.RoundRectangle(@x, @y - 5, @nut_width, @height + 10)
path.strokeColor = @options.nut_color
path.fillColor = @options.nut_color
showStartFret: ->
L "showStartFret()"
center = @getFretCenter(@start_fret, 1)
L "Center: ", center
@renderText(new @paper.Point(center.x, @y + @height + 20), @start_fret_text)
drawString: (num) ->
path = new @paper.Path()
path.strokeColor = @options.color
y = @getStringY(num)
start = new @paper.Point(@x, y)
path.moveTo(start)
path.lineTo(start.add([@width, 0]))
drawFret: (num) ->
path = new @paper.Path()
path.strokeColor = @options.color
x = @getFretX(num)
start = new @paper.Point(x, @y)
path.moveTo(start)
path.lineTo(start.add([0, @height]))
drawDot: (x, y, color='red', radius=2) ->
path = new @paper.Path.Circle(new @paper.Point(x, y), radius)
path.strokeColor = color
path.fillColor = color
drawMarkers: ->
L "drawMarkers"
middle_dot = 3
top_dot = 4
bottom_dot = 2
if parseInt(@options.strings, 10) == 4
middle_dot = 2
top_dot = 3
bottom_dot = 1
drawCircle = (start) =>
path = new @paper.Path.Circle(start, @options.marker_radius)
path.strokeColor = @options.marker_color
path.fillColor = @options.marker_color
y_displacement = @string_spacing / 2
for position in [3, 5, 7, 9, 15, 17, 19, 21]
if @hasFret(position)
start = @getFretCenter(position, middle_dot).add([0, y_displacement])
drawCircle(start)
for position in [12, 24]
if @hasFret(position)
start = @getFretCenter(position, bottom_dot).add([0, y_displacement])
drawCircle(start)
start = @getFretCenter(position, top_dot).add([0, y_displacement])
drawCircle(start)
renderText: (point, value, color=@options.font_color, size=@options.font_size) ->
text = new @paper.PointText(point)
text.justification = "center"
text.characterStyle =
font: @options.font_face
fontSize: size
fillColor: color
text.content = value
drawFretNumbers: ->
for position, value of {5: "V", 12: "XII", 19: "XIX"}
fret = parseInt(position, 10)
if @hasFret(fret)
point = @getFretCenter(fret, 6)
point.y = @getStringY(@options.strings + 1)
@renderText(point, value)
lightText: (options) ->
opts =
color: "white"
fillColor: "#666"
_.extend(opts, options)
L "lightUp: ", opts
point = @getFretCenter(opts.fret, opts.string)
path = new @paper.Path.Circle(point, @light_radius)
path.strokeColor = opts.color
path.fillColor = opts.fillColor
y_displacement = @string_spacing / 5
point.y += y_displacement
@renderText(point, opts.text, opts.color) if opts.text?
@paper.view.draw()
lightUp: (options) ->
options.color ?= '#666'
options.fillColor ?= options.color
L "lightUp: ", options
point = @getFretCenter(options.fret, options.string)
path = new @paper.Path.Circle(point, @light_radius - 2)
path.strokeColor = options.color
path.fillColor = options.fillColor
@paper.view.draw()
draw: ->
L "draw()"
for num in [1..@options.strings]
@drawString num
for num in [@start_fret..@end_fret]
@drawFret num
if @start_fret == 1
@drawNut()
else
@showStartFret()
@drawMarkers()
@paper.view.draw()
class Vex.Flow.FretboardDiv
@DEBUG = false
L = (args...) -> console?.log("(Vex.Flow.FretboardDiv)", args...) if Vex.Flow.FretboardDiv.DEBUG
error = (msg) -> new Vex.RERR("FretboardError", msg)
constructor: (@sel, @id) ->
@options =
"width": 700
"height": 150
"strings": 6
"frets": 17
"start": 1
"start-text": null
"tuning": "standard"
throw error("Invalid selector: " + @sel) if @sel? and $(@sel).length == 0
@id ?= $(@sel).attr('id')
@lights = []
setOption: (key, value) ->
if key in _.keys(@options)
L "Option: #{key}=#{value}"
@options[key] = value
else
throw error("Invalid option: " + key)
genFretboardOptions = (options) ->
fboptions = {}
for k, v of options
switch k
when "width", "height"
continue
when "strings"
fboptions.strings = v
when "frets"
fboptions.end_fret = v
when "tuning"
fboptions.tuning = v
when "start"
fboptions.start_fret = v
when "start-text"
fboptions.start_fret_text = v
else
throw error("Invalid option: " + k)
return fboptions
show: (line) ->
options = line.split(/\s+/)
params = {}
valid_options = ["fret", "frets", "string", "strings",
"text", "color", "note", "notes", "fill-color"]
for option in options
match = option.match(/^(\S+)\s*=\s*(\S+)/)
throw error("Invalid 'show' option: " + match[1]) unless match[1] in valid_options
params[match[1]] = match[2] if match?
L "Show: ", params
@lights.push params
parse: (data) ->
L "Parsing: " + data
lines = data.split(/\n/)
for line in lines
line.trim()
match = line.match(/^\s*option\s+(\S+)\s*=\s*(\S+)/)
@setOption(match[1], match[2]) if match?
match = line.match(/^\s*show\s+(.+)/)
@show(match[1]) if match?
return true
extractNumbers = (str) ->
L "ExtractNumbers: ", str
str.trim()
str.split(/\s*,\s*/)
extractNotes = (str) ->
L "ExtractNotes: ", str
str.trim()
notes = str.split(/\s*,\s*/)
extracted_notes = []
for note in notes
parts = note.match(/(\d+)\/(\d+)/)
if parts?
extracted_notes.push(
fret: parseInt(parts[1], 10)
string: parseInt(parts[2], 10))
else
throw error("Invalid note: " + note)
return extracted_notes
extractFrets = (light) ->
frets = extractNumbers(light.fret) if light.fret?
frets = extractNumbers(light.frets) if light.frets?
strings = extractNumbers(light.string) if light.string?
strings = extractNumbers(light.strings) if light.strings?
notes = extractNotes(light.note) if light.note?
notes = extractNotes(light.notes) if light.notes?
throw error("No frets or strings specified on line") if (not (frets? and strings?)) and (not notes?)
lights = []
if frets? and strings?
for fret in frets
for string in strings
lights.push({fret: parseInt(fret, 10), string: parseInt(string, 10)})
if notes?
for note in notes
lights.push(note)
return lights
lightsCameraAction: ->
L @lights
for light in @lights
params = extractFrets(light)
for param in params
param.color = light.color if light.color?
param.fillColor = light["fill-color"] if light["fill-color"]?
L "Lighting up: ", param
if light.text?
param.text = light.text
@fretboard.lightText(param)
else
@fretboard.lightUp(param)
build: (code=null) ->
L "Creating canvas id=#{@id} #{@options.width}x#{@options.height}"
code ?= $(@sel).text()
@parse(code)
canvas = $("<canvas id=#{@id}>").
attr("width", @options.width).
attr("height", @options.height).
attr("id", @id).
width(@options.width)
$(@sel).replaceWith(canvas)
ps = new paper.PaperScope()
ps.setup(document.getElementById(@id))
@fretboard = new Vex.Flow.Fretboard(ps, genFretboardOptions(@options))
@fretboard.draw()
@lightsCameraAction()
|
[
{
"context": "ry email protector plug-in\n#\n# https://github.com/pgib/jquery.email-protector/\n#\n# This plugin will allo",
"end": 60,
"score": 0.9996788501739502,
"start": 56,
"tag": "USERNAME",
"value": "pgib"
},
{
"context": "ster bots. Instead of having:\n#\n# <a href=\"mailto:foo@bar.com\">foo@bar.com</a>\n#\n# You would simply have:\n#\n# <",
"end": 246,
"score": 0.9999211430549622,
"start": 235,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "stead of having:\n#\n# <a href=\"mailto:foo@bar.com\">foo@bar.com</a>\n#\n# You would simply have:\n#\n# <a data-email-",
"end": 259,
"score": 0.9999181032180786,
"start": 248,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "\\\"foo|bar.com\\\"></a> will become <a href=\\\"mailto:foo@bar.com\\\"></a>.\"\n\n",
"end": 1688,
"score": 0.9998849034309387,
"start": 1677,
"tag": "EMAIL",
"value": "foo@bar.com"
}
] | src/jquery.email-protector.coffee | pgib/jquery.email-protector | 0 | # jQuery email protector plug-in
#
# https://github.com/pgib/jquery.email-protector/
#
# This plugin will allow you to keep your mailto: links away from the
# prying eyes of email harvester bots. Instead of having:
#
# <a href="mailto:foo@bar.com">foo@bar.com</a>
#
# You would simply have:
#
# <a data-email-protector="foo|bar.com"></a>
#
# If you want to use alternate text for the link, do it like this:
#
# <a data-email-protector="foo|bar.com" data-email-protector-preserve-text="true">email me!</a>
#
# To activate it, you could do:
#
# <script type="text/javascript">
# $("a[data-email-protector]").emailProtector()
# </script>
#
# If you always want to preserve the text inside the link, you can pass in an option:
#
# <script type="text/javascript">
# $("a[data-email-protector]").emailProtector({ 'preserve-text': true })
# </script>
#
$ = jQuery
$.fn.extend
emailProtector: (options) ->
settings =
'preserve-text': false
settings = $.extend settings, options
return @each ->
el = $(@)
parts = el.attr('data-email-protector').split('|')
preserveText = if el.attr('data-email-protector-preserve-text') then el.attr('data-email-protector-preserve-text') != 'false' else settings['preserve-text']
if parts.length == 2
if queryMatch = parts[1].match(/(\?.+)/)
query = queryMatch[1]
parts[1] = parts[1].substring(0, parts[1].indexOf('?'))
el.text "#{parts[0]}@#{parts[1]}" unless preserveText
el.attr 'href', "mailto:#{parts[0]}@#{parts[1]}#{query ? ''}"
else
el.text "Invalid format. eg. <a data-email-protector=\"foo|bar.com\"></a> will become <a href=\"mailto:foo@bar.com\"></a>."
| 54581 | # jQuery email protector plug-in
#
# https://github.com/pgib/jquery.email-protector/
#
# This plugin will allow you to keep your mailto: links away from the
# prying eyes of email harvester bots. Instead of having:
#
# <a href="mailto:<EMAIL>"><EMAIL></a>
#
# You would simply have:
#
# <a data-email-protector="foo|bar.com"></a>
#
# If you want to use alternate text for the link, do it like this:
#
# <a data-email-protector="foo|bar.com" data-email-protector-preserve-text="true">email me!</a>
#
# To activate it, you could do:
#
# <script type="text/javascript">
# $("a[data-email-protector]").emailProtector()
# </script>
#
# If you always want to preserve the text inside the link, you can pass in an option:
#
# <script type="text/javascript">
# $("a[data-email-protector]").emailProtector({ 'preserve-text': true })
# </script>
#
$ = jQuery
$.fn.extend
emailProtector: (options) ->
settings =
'preserve-text': false
settings = $.extend settings, options
return @each ->
el = $(@)
parts = el.attr('data-email-protector').split('|')
preserveText = if el.attr('data-email-protector-preserve-text') then el.attr('data-email-protector-preserve-text') != 'false' else settings['preserve-text']
if parts.length == 2
if queryMatch = parts[1].match(/(\?.+)/)
query = queryMatch[1]
parts[1] = parts[1].substring(0, parts[1].indexOf('?'))
el.text "#{parts[0]}@#{parts[1]}" unless preserveText
el.attr 'href', "mailto:#{parts[0]}@#{parts[1]}#{query ? ''}"
else
el.text "Invalid format. eg. <a data-email-protector=\"foo|bar.com\"></a> will become <a href=\"mailto:<EMAIL>\"></a>."
| true | # jQuery email protector plug-in
#
# https://github.com/pgib/jquery.email-protector/
#
# This plugin will allow you to keep your mailto: links away from the
# prying eyes of email harvester bots. Instead of having:
#
# <a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>
#
# You would simply have:
#
# <a data-email-protector="foo|bar.com"></a>
#
# If you want to use alternate text for the link, do it like this:
#
# <a data-email-protector="foo|bar.com" data-email-protector-preserve-text="true">email me!</a>
#
# To activate it, you could do:
#
# <script type="text/javascript">
# $("a[data-email-protector]").emailProtector()
# </script>
#
# If you always want to preserve the text inside the link, you can pass in an option:
#
# <script type="text/javascript">
# $("a[data-email-protector]").emailProtector({ 'preserve-text': true })
# </script>
#
$ = jQuery
$.fn.extend
emailProtector: (options) ->
settings =
'preserve-text': false
settings = $.extend settings, options
return @each ->
el = $(@)
parts = el.attr('data-email-protector').split('|')
preserveText = if el.attr('data-email-protector-preserve-text') then el.attr('data-email-protector-preserve-text') != 'false' else settings['preserve-text']
if parts.length == 2
if queryMatch = parts[1].match(/(\?.+)/)
query = queryMatch[1]
parts[1] = parts[1].substring(0, parts[1].indexOf('?'))
el.text "#{parts[0]}@#{parts[1]}" unless preserveText
el.attr 'href', "mailto:#{parts[0]}@#{parts[1]}#{query ? ''}"
else
el.text "Invalid format. eg. <a data-email-protector=\"foo|bar.com\"></a> will become <a href=\"mailto:PI:EMAIL:<EMAIL>END_PI\"></a>."
|
[
{
"context": "ww.googleapis.com/youtube/v3/search'\n apiKey: 'AIzaSyCof4lR7pAYUvem4KdZ7xke7XvI_FqI0gY'\n playerOptions:\n #videoId: 'XkemFr6gmZo'",
"end": 413,
"score": 0.9997755885124207,
"start": 374,
"tag": "KEY",
"value": "AIzaSyCof4lR7pAYUvem4KdZ7xke7XvI_FqI0gY"
}
] | app/assets/javascripts/classes/defaults.js.coffee | morion4000/molamp | 1 | class Molamp.Defaults
SPIN_OPTIONS:
lines: 12 # The number of lines to draw
length: 4 # The length of each line
width: 3 # The line thickness
radius: 5 # The radius of the inner circle
LASTFM_OPTIONS:
apiKey: ''
apiSecret: ''
YOUTUBE_OPTIONS:
domElement: 'ytplayer'
apiUrl: 'https://www.googleapis.com/youtube/v3/search'
apiKey: 'AIzaSyCof4lR7pAYUvem4KdZ7xke7XvI_FqI0gY'
playerOptions:
#videoId: 'XkemFr6gmZo'
width: 250
height: 340
playerVars:
rel: 0
enablejsapi: 1
theme: 'light'
color: 'red'
controls: 0
iv_load_policy: 3
modestbranding: 1
origin: 'http://www.molamp.net'
| 20832 | class Molamp.Defaults
SPIN_OPTIONS:
lines: 12 # The number of lines to draw
length: 4 # The length of each line
width: 3 # The line thickness
radius: 5 # The radius of the inner circle
LASTFM_OPTIONS:
apiKey: ''
apiSecret: ''
YOUTUBE_OPTIONS:
domElement: 'ytplayer'
apiUrl: 'https://www.googleapis.com/youtube/v3/search'
apiKey: '<KEY>'
playerOptions:
#videoId: 'XkemFr6gmZo'
width: 250
height: 340
playerVars:
rel: 0
enablejsapi: 1
theme: 'light'
color: 'red'
controls: 0
iv_load_policy: 3
modestbranding: 1
origin: 'http://www.molamp.net'
| true | class Molamp.Defaults
SPIN_OPTIONS:
lines: 12 # The number of lines to draw
length: 4 # The length of each line
width: 3 # The line thickness
radius: 5 # The radius of the inner circle
LASTFM_OPTIONS:
apiKey: ''
apiSecret: ''
YOUTUBE_OPTIONS:
domElement: 'ytplayer'
apiUrl: 'https://www.googleapis.com/youtube/v3/search'
apiKey: 'PI:KEY:<KEY>END_PI'
playerOptions:
#videoId: 'XkemFr6gmZo'
width: 250
height: 340
playerVars:
rel: 0
enablejsapi: 1
theme: 'light'
color: 'red'
controls: 0
iv_load_policy: 3
modestbranding: 1
origin: 'http://www.molamp.net'
|
[
{
"context": " method: 'GET'\n data:{email:email, password: password, mooc_provider:mooc_provider}\n error: (jqXHR, ",
"end": 5700,
"score": 0.9993245601654053,
"start": 5692,
"tag": "PASSWORD",
"value": "password"
}
] | app/assets/javascripts/user_settings.coffee | jprberlin/mammooc | 6 |
ready = ->
$('#load-account-settings-button').on 'click', (event) -> loadAccountSettings(event)
$('#load-mooc-provider-settings-button').on 'click', (event) -> loadMoocProviderSettings(event)
$('#load-privacy-settings-button').on 'click', (event) -> loadPrivacySettings(event)
$('#load-newsletter-settings-button').on 'click', (event) -> loadNewsletterSettings(event)
$('#add_new_email_field').on 'click', (event) -> addNewEmailField(event)
$('.remove_added_email_field').on 'click', (event) -> removeAddedEmailField(event)
$('.remove_email').on 'click', (event) -> markEmailAsDeleted(event)
$('button.setting-add-button').on 'click', (event) -> addSetting(event)
$('button.setting-remove-button').on 'click', (event) -> removeSetting(event)
return
$(document).ready(ready)
addNewEmailField = (event) ->
event.preventDefault()
table = document.getElementById('table_for_user_emails')
index = table.rows.length - 1
new_row = table.insertRow(index)
cell_address = new_row.insertCell(0)
cell_primary = new_row.insertCell(1)
cell_remove = new_row.insertCell(2)
html_for_address_field = "<input class='form-control' autofocus='autofocus' type='email' name='user[user_email][address_#{index}]' id='user_user_email_address_#{index}'>"
cell_address.innerHTML = html_for_address_field
html_for_primary_field = "<input type='radio' name='user[user_email][is_primary]' value='new_email_index_#{index}' id='user_user_email_is_primary_#{index}'>"
cell_primary.innerHTML = html_for_primary_field
html_for_remove_field = "<div class='text-right'><button class='btn btn-xs btn-default remove_added_email_field' id='remove_button_#{index}'><span class='glyphicon glyphicon-remove'></span></button></div>"
cell_remove.innerHTML = html_for_remove_field
$("#remove_button_#{index}").closest('.remove_added_email_field').on 'click', (event) -> removeAddedEmailField(event)
$('#user_index').val(index)
removeAddedEmailField = (event) ->
event.preventDefault()
button = $(event.target)
row_id = button.closest("tr")[0].rowIndex
table = document.getElementById('table_for_user_emails')
if $("#user_user_email_is_primary_#{row_id}")[0].checked
alert(I18n.t('users.settings.change_emails.alert_can_not_delete_primary'))
else
table.deleteRow(row_id)
markEmailAsDeleted = (event) ->
event.preventDefault()
button = $(event.target)
email_id = button.data('email_id')
if $("#user_user_email_is_primary_#{email_id}")[0].checked
alert(I18n.t('users.settings.change_emails.alert_can_not_delete_primary'))
else
url = "/user_emails/#{email_id}/mark_as_deleted.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_mark_as_deleted')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
console.log('deleted')
button.closest("tr").hide()
loadAccountSettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/account_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_account_subsite'}, '', 'settings?subsite=account');
event.preventDefault()
loadMoocProviderSettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/mooc_provider_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_mooc_provider_subsite'}, '', 'settings?subsite=mooc_provider');
event.preventDefault()
loadPrivacySettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/privacy_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_privacy_subsite'}, '', 'settings?subsite=privacy');
event.preventDefault()
loadNewsletterSettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/newsletter_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
console.log(textStatus)
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_newsletter_subsite'}, '', 'settings?subsite=newsletter');
event.preventDefault()
synchronizeNaiveUserMoocProviderConnection = (event) ->
button = $(event.target)
user_id = button.data('user_id')
mooc_provider = button.data('mooc_provider')
email = $("#input-email-#{mooc_provider}").val()
password = $("#input-password-#{mooc_provider}").val()
url = "/users/#{user_id}/set_mooc_provider_connection.json"
$.ajax
url: url
method: 'GET'
data:{email:email, password: password, mooc_provider:mooc_provider}
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
if data.status == true
$("div.settings-container").html(data.partial)
else
$("#div-error-#{mooc_provider}").text("Error!")
event.preventDefault()
revokeNaiveUserMoocProviderConnection = (event) ->
button = $(event.target)
user_id = button.data('user_id')
mooc_provider = button.data('mooc_provider')
url = "/users/#{user_id}/revoke_mooc_provider_connection.json"
$.ajax
url: url
method: 'GET'
data:{mooc_provider:mooc_provider}
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
if data.status == true
$("div.settings-container").html(data.partial)
else
$("#div-error-#{mooc_provider}").text("Error!")
event.preventDefault()
addSetting = (event) ->
button = if (event.target.nodeName == 'SPAN') then $(event.target.parentElement) else $(event.target)
list_id = button.data('list-id')
list = $("##{list_id}")
user_id = button.data('user-id')
ok_button = $('<button></button>')
.addClass('btn btn-default new-item-ok')
.append($('<span></span>').addClass('glyphicon glyphicon-ok'))
ok_button.on 'click', (event) ->
event.preventDefault()
name = $("#new-#{list.data('key')}-name").val()
id = $("#new-#{list.data('key')}-id").val()
if name != '' && id != ''
ids = getExistingIDs(list.data('setting'), list.data('key'))
ids.push id
$.ajax
type: 'POST'
url: "/users/#{user_id}/set_setting"
data:
setting: list.data('setting')
key: list.data('key')
value: ids
dataType: 'json'
success: (data, textStatus, jqXHR) ->
new_item = $('<li></li>').addClass('list-group-item').data('id', id)
.append(name)
.append($('<button></button>').addClass('btn btn-xs btn-default pull-right')
.data('user-id', user_id)
.on('click', removeSetting)
.append($('<span></span>').addClass('glyphicon glyphicon-remove')))
form_item.remove()
list.prepend(new_item)
error: (jqXHR, textStatus, errorThrown) ->
alert(I18n.t('global.ajax_failed'))
else
subject = list.data('key').slice(0, -1)
alert(I18n.t('flash.error.settings.input_empty', subject: I18n.t("flash.error.settings.#{subject}")))
cancel_button = $('<button></button>')
.addClass('btn btn-default new-item-cancel')
.append($('<span></span>').addClass('glyphicon glyphicon-remove'))
cancel_button.on 'click', (event) ->
event.preventDefault()
form_item.remove()
id_input = $('<input></input>').attr('type', 'hidden').attr('id', "new-#{list.data('key')}-id")
name_input = $('<input></input>').attr('type', 'text').addClass('form-control').attr('id', "new-#{list.data('key')}-name")
input_source_url = switch list.data('key')
when 'groups' then '/groups.json'
when 'users' then "/users/#{user_id}/connected_users_autocomplete.json"
name_input.autocomplete
minLength: 0
delay: 100
autoFocus: true
source: (request, response) ->
$.ajax
url: input_source_url
dataType: 'json'
data:
q: request.term
error: (jqXHR, textStatus, errorThrown) ->
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
results = []
existing_ids = getExistingIDs(list.data('setting'), list.data('key'))
for item in data
label = switch list.data('key')
when 'groups' then item.name
when 'users' then "#{item.full_name}"
results.push({label: label, value: item.id}) if existing_ids.indexOf(item.id) < 0
response(results)
select: (event, ui) ->
id_input.val(ui.item.value)
name_input.val(ui.item.label)
return false
search: (event, ui) ->
id_input.val('')
form_item = $('<li></li>').addClass('list-group-item').append(
$('<form></form>').addClass('form-inline')
.append($('<div></div>').addClass('form-group')
.append(name_input)
.append(id_input))
.append(ok_button)
.append(cancel_button))
list.prepend(form_item)
name_input.autocomplete('search')
name_input.focus()
removeSetting = (event) ->
button = if (event.target.nodeName == 'SPAN') then $(event.target.parentElement) else $(event.target)
list = button.closest('ul')
user_id = button.data('user-id')
ids = getExistingIDs(list.data('setting'), list.data('key'))
remove_id = button.parent().data('id')
remove_index = ids.indexOf(remove_id)
ids.splice(remove_index, 1) if remove_index >= 0
$.ajax
type: 'POST'
url: "/users/#{user_id}/set_setting"
data:
setting: list.data('setting')
key: list.data('key')
value: ids
dataType: 'json'
success: (data, textStatus, jqXHR) ->
button.parent().remove()
error: (jqXHR, textStatus, errorThrown) ->
alert(I18n.t('global.ajax_failed'))
getExistingIDs = (setting, key) ->
existing_ids = []
ul_id = "#{setting.replace(/_/g, '-')}-#{key}-list"
lis = $("##{ul_id}").children()
$.each lis, (_, li) ->
existing_ids.push $(li).data('id') if $(li).data('id')
return existing_ids
@bindMoocProviderConnectionClickEvents = () ->
$('button[id="sync-naive-user-mooc_provider-connection-button"]').on 'click', (event) ->
synchronizeNaiveUserMoocProviderConnection(event)
$('button[id="revoke-naive-user-mooc_provider-connection-button"]').on 'click', (event) ->
revokeNaiveUserMoocProviderConnection(event)
$('#add_new_email_field').on 'click', (event) -> addNewEmailField(event)
$('.remove_added_email_field').on 'click', (event) -> removeAddedEmailField(event)
$('.remove_email').on 'click', (event) -> markEmailAsDeleted(event)
$('button.setting-add-button').on 'click', (event) -> addSetting(event)
$('button.setting-remove-button').on 'click', (event) -> removeSetting(event)
| 143894 |
ready = ->
$('#load-account-settings-button').on 'click', (event) -> loadAccountSettings(event)
$('#load-mooc-provider-settings-button').on 'click', (event) -> loadMoocProviderSettings(event)
$('#load-privacy-settings-button').on 'click', (event) -> loadPrivacySettings(event)
$('#load-newsletter-settings-button').on 'click', (event) -> loadNewsletterSettings(event)
$('#add_new_email_field').on 'click', (event) -> addNewEmailField(event)
$('.remove_added_email_field').on 'click', (event) -> removeAddedEmailField(event)
$('.remove_email').on 'click', (event) -> markEmailAsDeleted(event)
$('button.setting-add-button').on 'click', (event) -> addSetting(event)
$('button.setting-remove-button').on 'click', (event) -> removeSetting(event)
return
$(document).ready(ready)
addNewEmailField = (event) ->
event.preventDefault()
table = document.getElementById('table_for_user_emails')
index = table.rows.length - 1
new_row = table.insertRow(index)
cell_address = new_row.insertCell(0)
cell_primary = new_row.insertCell(1)
cell_remove = new_row.insertCell(2)
html_for_address_field = "<input class='form-control' autofocus='autofocus' type='email' name='user[user_email][address_#{index}]' id='user_user_email_address_#{index}'>"
cell_address.innerHTML = html_for_address_field
html_for_primary_field = "<input type='radio' name='user[user_email][is_primary]' value='new_email_index_#{index}' id='user_user_email_is_primary_#{index}'>"
cell_primary.innerHTML = html_for_primary_field
html_for_remove_field = "<div class='text-right'><button class='btn btn-xs btn-default remove_added_email_field' id='remove_button_#{index}'><span class='glyphicon glyphicon-remove'></span></button></div>"
cell_remove.innerHTML = html_for_remove_field
$("#remove_button_#{index}").closest('.remove_added_email_field').on 'click', (event) -> removeAddedEmailField(event)
$('#user_index').val(index)
removeAddedEmailField = (event) ->
event.preventDefault()
button = $(event.target)
row_id = button.closest("tr")[0].rowIndex
table = document.getElementById('table_for_user_emails')
if $("#user_user_email_is_primary_#{row_id}")[0].checked
alert(I18n.t('users.settings.change_emails.alert_can_not_delete_primary'))
else
table.deleteRow(row_id)
markEmailAsDeleted = (event) ->
event.preventDefault()
button = $(event.target)
email_id = button.data('email_id')
if $("#user_user_email_is_primary_#{email_id}")[0].checked
alert(I18n.t('users.settings.change_emails.alert_can_not_delete_primary'))
else
url = "/user_emails/#{email_id}/mark_as_deleted.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_mark_as_deleted')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
console.log('deleted')
button.closest("tr").hide()
loadAccountSettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/account_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_account_subsite'}, '', 'settings?subsite=account');
event.preventDefault()
loadMoocProviderSettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/mooc_provider_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_mooc_provider_subsite'}, '', 'settings?subsite=mooc_provider');
event.preventDefault()
loadPrivacySettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/privacy_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_privacy_subsite'}, '', 'settings?subsite=privacy');
event.preventDefault()
loadNewsletterSettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/newsletter_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
console.log(textStatus)
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_newsletter_subsite'}, '', 'settings?subsite=newsletter');
event.preventDefault()
synchronizeNaiveUserMoocProviderConnection = (event) ->
button = $(event.target)
user_id = button.data('user_id')
mooc_provider = button.data('mooc_provider')
email = $("#input-email-#{mooc_provider}").val()
password = $("#input-password-#{mooc_provider}").val()
url = "/users/#{user_id}/set_mooc_provider_connection.json"
$.ajax
url: url
method: 'GET'
data:{email:email, password: <PASSWORD>, mooc_provider:mooc_provider}
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
if data.status == true
$("div.settings-container").html(data.partial)
else
$("#div-error-#{mooc_provider}").text("Error!")
event.preventDefault()
revokeNaiveUserMoocProviderConnection = (event) ->
button = $(event.target)
user_id = button.data('user_id')
mooc_provider = button.data('mooc_provider')
url = "/users/#{user_id}/revoke_mooc_provider_connection.json"
$.ajax
url: url
method: 'GET'
data:{mooc_provider:mooc_provider}
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
if data.status == true
$("div.settings-container").html(data.partial)
else
$("#div-error-#{mooc_provider}").text("Error!")
event.preventDefault()
addSetting = (event) ->
button = if (event.target.nodeName == 'SPAN') then $(event.target.parentElement) else $(event.target)
list_id = button.data('list-id')
list = $("##{list_id}")
user_id = button.data('user-id')
ok_button = $('<button></button>')
.addClass('btn btn-default new-item-ok')
.append($('<span></span>').addClass('glyphicon glyphicon-ok'))
ok_button.on 'click', (event) ->
event.preventDefault()
name = $("#new-#{list.data('key')}-name").val()
id = $("#new-#{list.data('key')}-id").val()
if name != '' && id != ''
ids = getExistingIDs(list.data('setting'), list.data('key'))
ids.push id
$.ajax
type: 'POST'
url: "/users/#{user_id}/set_setting"
data:
setting: list.data('setting')
key: list.data('key')
value: ids
dataType: 'json'
success: (data, textStatus, jqXHR) ->
new_item = $('<li></li>').addClass('list-group-item').data('id', id)
.append(name)
.append($('<button></button>').addClass('btn btn-xs btn-default pull-right')
.data('user-id', user_id)
.on('click', removeSetting)
.append($('<span></span>').addClass('glyphicon glyphicon-remove')))
form_item.remove()
list.prepend(new_item)
error: (jqXHR, textStatus, errorThrown) ->
alert(I18n.t('global.ajax_failed'))
else
subject = list.data('key').slice(0, -1)
alert(I18n.t('flash.error.settings.input_empty', subject: I18n.t("flash.error.settings.#{subject}")))
cancel_button = $('<button></button>')
.addClass('btn btn-default new-item-cancel')
.append($('<span></span>').addClass('glyphicon glyphicon-remove'))
cancel_button.on 'click', (event) ->
event.preventDefault()
form_item.remove()
id_input = $('<input></input>').attr('type', 'hidden').attr('id', "new-#{list.data('key')}-id")
name_input = $('<input></input>').attr('type', 'text').addClass('form-control').attr('id', "new-#{list.data('key')}-name")
input_source_url = switch list.data('key')
when 'groups' then '/groups.json'
when 'users' then "/users/#{user_id}/connected_users_autocomplete.json"
name_input.autocomplete
minLength: 0
delay: 100
autoFocus: true
source: (request, response) ->
$.ajax
url: input_source_url
dataType: 'json'
data:
q: request.term
error: (jqXHR, textStatus, errorThrown) ->
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
results = []
existing_ids = getExistingIDs(list.data('setting'), list.data('key'))
for item in data
label = switch list.data('key')
when 'groups' then item.name
when 'users' then "#{item.full_name}"
results.push({label: label, value: item.id}) if existing_ids.indexOf(item.id) < 0
response(results)
select: (event, ui) ->
id_input.val(ui.item.value)
name_input.val(ui.item.label)
return false
search: (event, ui) ->
id_input.val('')
form_item = $('<li></li>').addClass('list-group-item').append(
$('<form></form>').addClass('form-inline')
.append($('<div></div>').addClass('form-group')
.append(name_input)
.append(id_input))
.append(ok_button)
.append(cancel_button))
list.prepend(form_item)
name_input.autocomplete('search')
name_input.focus()
removeSetting = (event) ->
button = if (event.target.nodeName == 'SPAN') then $(event.target.parentElement) else $(event.target)
list = button.closest('ul')
user_id = button.data('user-id')
ids = getExistingIDs(list.data('setting'), list.data('key'))
remove_id = button.parent().data('id')
remove_index = ids.indexOf(remove_id)
ids.splice(remove_index, 1) if remove_index >= 0
$.ajax
type: 'POST'
url: "/users/#{user_id}/set_setting"
data:
setting: list.data('setting')
key: list.data('key')
value: ids
dataType: 'json'
success: (data, textStatus, jqXHR) ->
button.parent().remove()
error: (jqXHR, textStatus, errorThrown) ->
alert(I18n.t('global.ajax_failed'))
getExistingIDs = (setting, key) ->
existing_ids = []
ul_id = "#{setting.replace(/_/g, '-')}-#{key}-list"
lis = $("##{ul_id}").children()
$.each lis, (_, li) ->
existing_ids.push $(li).data('id') if $(li).data('id')
return existing_ids
@bindMoocProviderConnectionClickEvents = () ->
$('button[id="sync-naive-user-mooc_provider-connection-button"]').on 'click', (event) ->
synchronizeNaiveUserMoocProviderConnection(event)
$('button[id="revoke-naive-user-mooc_provider-connection-button"]').on 'click', (event) ->
revokeNaiveUserMoocProviderConnection(event)
$('#add_new_email_field').on 'click', (event) -> addNewEmailField(event)
$('.remove_added_email_field').on 'click', (event) -> removeAddedEmailField(event)
$('.remove_email').on 'click', (event) -> markEmailAsDeleted(event)
$('button.setting-add-button').on 'click', (event) -> addSetting(event)
$('button.setting-remove-button').on 'click', (event) -> removeSetting(event)
| true |
ready = ->
$('#load-account-settings-button').on 'click', (event) -> loadAccountSettings(event)
$('#load-mooc-provider-settings-button').on 'click', (event) -> loadMoocProviderSettings(event)
$('#load-privacy-settings-button').on 'click', (event) -> loadPrivacySettings(event)
$('#load-newsletter-settings-button').on 'click', (event) -> loadNewsletterSettings(event)
$('#add_new_email_field').on 'click', (event) -> addNewEmailField(event)
$('.remove_added_email_field').on 'click', (event) -> removeAddedEmailField(event)
$('.remove_email').on 'click', (event) -> markEmailAsDeleted(event)
$('button.setting-add-button').on 'click', (event) -> addSetting(event)
$('button.setting-remove-button').on 'click', (event) -> removeSetting(event)
return
$(document).ready(ready)
addNewEmailField = (event) ->
event.preventDefault()
table = document.getElementById('table_for_user_emails')
index = table.rows.length - 1
new_row = table.insertRow(index)
cell_address = new_row.insertCell(0)
cell_primary = new_row.insertCell(1)
cell_remove = new_row.insertCell(2)
html_for_address_field = "<input class='form-control' autofocus='autofocus' type='email' name='user[user_email][address_#{index}]' id='user_user_email_address_#{index}'>"
cell_address.innerHTML = html_for_address_field
html_for_primary_field = "<input type='radio' name='user[user_email][is_primary]' value='new_email_index_#{index}' id='user_user_email_is_primary_#{index}'>"
cell_primary.innerHTML = html_for_primary_field
html_for_remove_field = "<div class='text-right'><button class='btn btn-xs btn-default remove_added_email_field' id='remove_button_#{index}'><span class='glyphicon glyphicon-remove'></span></button></div>"
cell_remove.innerHTML = html_for_remove_field
$("#remove_button_#{index}").closest('.remove_added_email_field').on 'click', (event) -> removeAddedEmailField(event)
$('#user_index').val(index)
removeAddedEmailField = (event) ->
event.preventDefault()
button = $(event.target)
row_id = button.closest("tr")[0].rowIndex
table = document.getElementById('table_for_user_emails')
if $("#user_user_email_is_primary_#{row_id}")[0].checked
alert(I18n.t('users.settings.change_emails.alert_can_not_delete_primary'))
else
table.deleteRow(row_id)
markEmailAsDeleted = (event) ->
event.preventDefault()
button = $(event.target)
email_id = button.data('email_id')
if $("#user_user_email_is_primary_#{email_id}")[0].checked
alert(I18n.t('users.settings.change_emails.alert_can_not_delete_primary'))
else
url = "/user_emails/#{email_id}/mark_as_deleted.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_mark_as_deleted')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
console.log('deleted')
button.closest("tr").hide()
loadAccountSettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/account_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_account_subsite'}, '', 'settings?subsite=account');
event.preventDefault()
loadMoocProviderSettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/mooc_provider_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_mooc_provider_subsite'}, '', 'settings?subsite=mooc_provider');
event.preventDefault()
loadPrivacySettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/privacy_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_privacy_subsite'}, '', 'settings?subsite=privacy');
event.preventDefault()
loadNewsletterSettings = (event) ->
button = $(event.target)
user_id = button.data('user_id')
url = "/users/#{user_id}/newsletter_settings.json"
$.ajax
url: url
method: 'GET'
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
console.log(textStatus)
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
$("div.settings-container").html(data.partial)
bindMoocProviderConnectionClickEvents()
window.history.pushState({id: 'set_newsletter_subsite'}, '', 'settings?subsite=newsletter');
event.preventDefault()
synchronizeNaiveUserMoocProviderConnection = (event) ->
button = $(event.target)
user_id = button.data('user_id')
mooc_provider = button.data('mooc_provider')
email = $("#input-email-#{mooc_provider}").val()
password = $("#input-password-#{mooc_provider}").val()
url = "/users/#{user_id}/set_mooc_provider_connection.json"
$.ajax
url: url
method: 'GET'
data:{email:email, password: PI:PASSWORD:<PASSWORD>END_PI, mooc_provider:mooc_provider}
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
if data.status == true
$("div.settings-container").html(data.partial)
else
$("#div-error-#{mooc_provider}").text("Error!")
event.preventDefault()
revokeNaiveUserMoocProviderConnection = (event) ->
button = $(event.target)
user_id = button.data('user_id')
mooc_provider = button.data('mooc_provider')
url = "/users/#{user_id}/revoke_mooc_provider_connection.json"
$.ajax
url: url
method: 'GET'
data:{mooc_provider:mooc_provider}
error: (jqXHR, textStatus, errorThrown) ->
console.log('error_synchronize')
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
if data.status == true
$("div.settings-container").html(data.partial)
else
$("#div-error-#{mooc_provider}").text("Error!")
event.preventDefault()
addSetting = (event) ->
button = if (event.target.nodeName == 'SPAN') then $(event.target.parentElement) else $(event.target)
list_id = button.data('list-id')
list = $("##{list_id}")
user_id = button.data('user-id')
ok_button = $('<button></button>')
.addClass('btn btn-default new-item-ok')
.append($('<span></span>').addClass('glyphicon glyphicon-ok'))
ok_button.on 'click', (event) ->
event.preventDefault()
name = $("#new-#{list.data('key')}-name").val()
id = $("#new-#{list.data('key')}-id").val()
if name != '' && id != ''
ids = getExistingIDs(list.data('setting'), list.data('key'))
ids.push id
$.ajax
type: 'POST'
url: "/users/#{user_id}/set_setting"
data:
setting: list.data('setting')
key: list.data('key')
value: ids
dataType: 'json'
success: (data, textStatus, jqXHR) ->
new_item = $('<li></li>').addClass('list-group-item').data('id', id)
.append(name)
.append($('<button></button>').addClass('btn btn-xs btn-default pull-right')
.data('user-id', user_id)
.on('click', removeSetting)
.append($('<span></span>').addClass('glyphicon glyphicon-remove')))
form_item.remove()
list.prepend(new_item)
error: (jqXHR, textStatus, errorThrown) ->
alert(I18n.t('global.ajax_failed'))
else
subject = list.data('key').slice(0, -1)
alert(I18n.t('flash.error.settings.input_empty', subject: I18n.t("flash.error.settings.#{subject}")))
cancel_button = $('<button></button>')
.addClass('btn btn-default new-item-cancel')
.append($('<span></span>').addClass('glyphicon glyphicon-remove'))
cancel_button.on 'click', (event) ->
event.preventDefault()
form_item.remove()
id_input = $('<input></input>').attr('type', 'hidden').attr('id', "new-#{list.data('key')}-id")
name_input = $('<input></input>').attr('type', 'text').addClass('form-control').attr('id', "new-#{list.data('key')}-name")
input_source_url = switch list.data('key')
when 'groups' then '/groups.json'
when 'users' then "/users/#{user_id}/connected_users_autocomplete.json"
name_input.autocomplete
minLength: 0
delay: 100
autoFocus: true
source: (request, response) ->
$.ajax
url: input_source_url
dataType: 'json'
data:
q: request.term
error: (jqXHR, textStatus, errorThrown) ->
alert(I18n.t('global.ajax_failed'))
success: (data, textStatus, jqXHR) ->
results = []
existing_ids = getExistingIDs(list.data('setting'), list.data('key'))
for item in data
label = switch list.data('key')
when 'groups' then item.name
when 'users' then "#{item.full_name}"
results.push({label: label, value: item.id}) if existing_ids.indexOf(item.id) < 0
response(results)
select: (event, ui) ->
id_input.val(ui.item.value)
name_input.val(ui.item.label)
return false
search: (event, ui) ->
id_input.val('')
form_item = $('<li></li>').addClass('list-group-item').append(
$('<form></form>').addClass('form-inline')
.append($('<div></div>').addClass('form-group')
.append(name_input)
.append(id_input))
.append(ok_button)
.append(cancel_button))
list.prepend(form_item)
name_input.autocomplete('search')
name_input.focus()
removeSetting = (event) ->
button = if (event.target.nodeName == 'SPAN') then $(event.target.parentElement) else $(event.target)
list = button.closest('ul')
user_id = button.data('user-id')
ids = getExistingIDs(list.data('setting'), list.data('key'))
remove_id = button.parent().data('id')
remove_index = ids.indexOf(remove_id)
ids.splice(remove_index, 1) if remove_index >= 0
$.ajax
type: 'POST'
url: "/users/#{user_id}/set_setting"
data:
setting: list.data('setting')
key: list.data('key')
value: ids
dataType: 'json'
success: (data, textStatus, jqXHR) ->
button.parent().remove()
error: (jqXHR, textStatus, errorThrown) ->
alert(I18n.t('global.ajax_failed'))
getExistingIDs = (setting, key) ->
existing_ids = []
ul_id = "#{setting.replace(/_/g, '-')}-#{key}-list"
lis = $("##{ul_id}").children()
$.each lis, (_, li) ->
existing_ids.push $(li).data('id') if $(li).data('id')
return existing_ids
@bindMoocProviderConnectionClickEvents = () ->
$('button[id="sync-naive-user-mooc_provider-connection-button"]').on 'click', (event) ->
synchronizeNaiveUserMoocProviderConnection(event)
$('button[id="revoke-naive-user-mooc_provider-connection-button"]').on 'click', (event) ->
revokeNaiveUserMoocProviderConnection(event)
$('#add_new_email_field').on 'click', (event) -> addNewEmailField(event)
$('.remove_added_email_field').on 'click', (event) -> removeAddedEmailField(event)
$('.remove_email').on 'click', (event) -> markEmailAsDeleted(event)
$('button.setting-add-button').on 'click', (event) -> addSetting(event)
$('button.setting-remove-button').on 'click', (event) -> removeSetting(event)
|
[
{
"context": "ame.toLowerCase()\n primaryKey = \"#{lowerModelName}Id\"\n\n # collection level\n # GET lists all items in",
"end": 400,
"score": 0.6683080196380615,
"start": 398,
"tag": "KEY",
"value": "Id"
},
{
"context": "delName = actualModel.modelName\n secondaryKey = \"#{fieldName}#{nestedModelName}Id\"\n\n # GET returns",
"end": 1967,
"score": 0.6762990355491638,
"start": 1964,
"tag": "KEY",
"value": "\"#{"
},
{
"context": "ualModel.modelName\n secondaryKey = \"#{fieldName}#{nestedModelName}Id\"\n\n # GET returns the popul",
"end": 1976,
"score": 0.7871529459953308,
"start": 1976,
"tag": "KEY",
"value": ""
},
{
"context": "\n secondaryKey = \"#{fieldName}#{nestedModelName}Id\"\n\n # GET returns the populated field\n route",
"end": 1997,
"score": 0.8301292061805725,
"start": 1995,
"tag": "KEY",
"value": "Id"
}
] | lib/util/getRoutesFromModel.coffee | wearefractal/crudify | 8 | getPopulatesFromModel = require "./getPopulatesFromModel"
getStaticsFromModel = require "./getStaticsFromModel"
getInstanceMethodsFromModel = require "./getInstanceMethodsFromModel"
reserved = ['authorize']
module.exports = (model) ->
routes = []
collectionName = model.collection.name
modelName = model.modelName
lowerModelName = modelName.toLowerCase()
primaryKey = "#{lowerModelName}Id"
# collection level
# GET lists all items in the collection
# POST creates a new item in the collection
routes.push
meta:
type: "collection"
models: [model]
methods: ["post","get"]
path: "/#{collectionName}"
# static methods
statics = getStaticsFromModel model
for name, fn of statics when !(name in reserved)
routes.push
meta:
type: "collection-static-method"
models: [model]
handlerName: name
handler: fn
methods: ["post","get"]
path: "/#{collectionName}/#{name}"
# specific item
# GET returns the object from the collection
# PUT replaces the object in the collection
# PATCH modifies the object in the collection
# DELETe removes the object from the collection
routes.push
meta:
type: "single"
models: [model]
primaryKey: primaryKey
methods: ["get","put","patch","delete"]
path: "/#{collectionName}/:#{primaryKey}"
# instance methods
instMethods = getInstanceMethodsFromModel model
for name, fn of instMethods when !(name in reserved)
routes.push
meta:
type: "single-instance-method"
models: [model]
handlerName: name
handler: fn
primaryKey: primaryKey
methods: ["post","get"]
path: "/#{collectionName}/:#{primaryKey}/#{name}"
# sub-items
toPopulate = getPopulatesFromModel model
for path in toPopulate
fieldName = path.name
actualModel = model.db.model path.modelName
nestedModelName = actualModel.modelName
secondaryKey = "#{fieldName}#{nestedModelName}Id"
# GET returns the populated field
routes.push
meta:
type: "single-with-populate"
models: [model, actualModel]
field: fieldName
primaryKey: primaryKey
methods: ["get"]
path: "/#{collectionName}/:#{primaryKey}/#{fieldName}"
if path.plural
# POST adds a new DBRef to the list
routes.push
meta:
type: "single-with-populate-many"
models: [model, actualModel]
field: fieldName
primaryKey: primaryKey
methods: ["post"]
path: "/#{collectionName}/:#{primaryKey}/#{fieldName}"
# DELETE will delete the DBRef from the list
###
routes.push
meta:
type: "single-with-populate-many"
models: [model, actualModel]
field: fieldName
primaryKey: primaryKey
secondaryKey: secondaryKey
methods: ["delete"]
path: "/#{collectionName}/:#{primaryKey}/#{fieldName}/:#{secondaryKey}"
###
return routes | 126240 | getPopulatesFromModel = require "./getPopulatesFromModel"
getStaticsFromModel = require "./getStaticsFromModel"
getInstanceMethodsFromModel = require "./getInstanceMethodsFromModel"
reserved = ['authorize']
module.exports = (model) ->
routes = []
collectionName = model.collection.name
modelName = model.modelName
lowerModelName = modelName.toLowerCase()
primaryKey = "#{lowerModelName}<KEY>"
# collection level
# GET lists all items in the collection
# POST creates a new item in the collection
routes.push
meta:
type: "collection"
models: [model]
methods: ["post","get"]
path: "/#{collectionName}"
# static methods
statics = getStaticsFromModel model
for name, fn of statics when !(name in reserved)
routes.push
meta:
type: "collection-static-method"
models: [model]
handlerName: name
handler: fn
methods: ["post","get"]
path: "/#{collectionName}/#{name}"
# specific item
# GET returns the object from the collection
# PUT replaces the object in the collection
# PATCH modifies the object in the collection
# DELETe removes the object from the collection
routes.push
meta:
type: "single"
models: [model]
primaryKey: primaryKey
methods: ["get","put","patch","delete"]
path: "/#{collectionName}/:#{primaryKey}"
# instance methods
instMethods = getInstanceMethodsFromModel model
for name, fn of instMethods when !(name in reserved)
routes.push
meta:
type: "single-instance-method"
models: [model]
handlerName: name
handler: fn
primaryKey: primaryKey
methods: ["post","get"]
path: "/#{collectionName}/:#{primaryKey}/#{name}"
# sub-items
toPopulate = getPopulatesFromModel model
for path in toPopulate
fieldName = path.name
actualModel = model.db.model path.modelName
nestedModelName = actualModel.modelName
secondaryKey = <KEY>fieldName<KEY>}#{nestedModelName}<KEY>"
# GET returns the populated field
routes.push
meta:
type: "single-with-populate"
models: [model, actualModel]
field: fieldName
primaryKey: primaryKey
methods: ["get"]
path: "/#{collectionName}/:#{primaryKey}/#{fieldName}"
if path.plural
# POST adds a new DBRef to the list
routes.push
meta:
type: "single-with-populate-many"
models: [model, actualModel]
field: fieldName
primaryKey: primaryKey
methods: ["post"]
path: "/#{collectionName}/:#{primaryKey}/#{fieldName}"
# DELETE will delete the DBRef from the list
###
routes.push
meta:
type: "single-with-populate-many"
models: [model, actualModel]
field: fieldName
primaryKey: primaryKey
secondaryKey: secondaryKey
methods: ["delete"]
path: "/#{collectionName}/:#{primaryKey}/#{fieldName}/:#{secondaryKey}"
###
return routes | true | getPopulatesFromModel = require "./getPopulatesFromModel"
getStaticsFromModel = require "./getStaticsFromModel"
getInstanceMethodsFromModel = require "./getInstanceMethodsFromModel"
reserved = ['authorize']
module.exports = (model) ->
routes = []
collectionName = model.collection.name
modelName = model.modelName
lowerModelName = modelName.toLowerCase()
primaryKey = "#{lowerModelName}PI:KEY:<KEY>END_PI"
# collection level
# GET lists all items in the collection
# POST creates a new item in the collection
routes.push
meta:
type: "collection"
models: [model]
methods: ["post","get"]
path: "/#{collectionName}"
# static methods
statics = getStaticsFromModel model
for name, fn of statics when !(name in reserved)
routes.push
meta:
type: "collection-static-method"
models: [model]
handlerName: name
handler: fn
methods: ["post","get"]
path: "/#{collectionName}/#{name}"
# specific item
# GET returns the object from the collection
# PUT replaces the object in the collection
# PATCH modifies the object in the collection
# DELETe removes the object from the collection
routes.push
meta:
type: "single"
models: [model]
primaryKey: primaryKey
methods: ["get","put","patch","delete"]
path: "/#{collectionName}/:#{primaryKey}"
# instance methods
instMethods = getInstanceMethodsFromModel model
for name, fn of instMethods when !(name in reserved)
routes.push
meta:
type: "single-instance-method"
models: [model]
handlerName: name
handler: fn
primaryKey: primaryKey
methods: ["post","get"]
path: "/#{collectionName}/:#{primaryKey}/#{name}"
# sub-items
toPopulate = getPopulatesFromModel model
for path in toPopulate
fieldName = path.name
actualModel = model.db.model path.modelName
nestedModelName = actualModel.modelName
secondaryKey = PI:KEY:<KEY>END_PIfieldNamePI:KEY:<KEY>END_PI}#{nestedModelName}PI:KEY:<KEY>END_PI"
# GET returns the populated field
routes.push
meta:
type: "single-with-populate"
models: [model, actualModel]
field: fieldName
primaryKey: primaryKey
methods: ["get"]
path: "/#{collectionName}/:#{primaryKey}/#{fieldName}"
if path.plural
# POST adds a new DBRef to the list
routes.push
meta:
type: "single-with-populate-many"
models: [model, actualModel]
field: fieldName
primaryKey: primaryKey
methods: ["post"]
path: "/#{collectionName}/:#{primaryKey}/#{fieldName}"
# DELETE will delete the DBRef from the list
###
routes.push
meta:
type: "single-with-populate-many"
models: [model, actualModel]
field: fieldName
primaryKey: primaryKey
secondaryKey: secondaryKey
methods: ["delete"]
path: "/#{collectionName}/:#{primaryKey}/#{fieldName}/:#{secondaryKey}"
###
return routes |
[
{
"context": "or 25 invitees on a vote. Contact <a href=\"mailto:support@swarm.fund\">support@swarm.fund</a> if you require more than ",
"end": 3284,
"score": 0.9999209642410278,
"start": 3266,
"tag": "EMAIL",
"value": "support@swarm.fund"
},
{
"context": "vote. Contact <a href=\"mailto:support@swarm.fund\">support@swarm.fund</a> if you require more than this.'\n\t\t\t\tscope.for",
"end": 3304,
"score": 0.9999189376831055,
"start": 3286,
"tag": "EMAIL",
"value": "support@swarm.fund"
},
{
"context": "true\n\t\t\t\t\t\t\temail: email\n\t\t\t\t\t\t\ttemporaryPassword: encodedPassphrase\n\t\t\t\t\t\t}\n\t\t\t\t\t\tUser.create email, passphrase, user",
"end": 3994,
"score": 0.9979572892189026,
"start": 3977,
"tag": "PASSWORD",
"value": "encodedPassphrase"
},
{
"context": "cation {login: userData.email, password: userData.passphrase}, 'votingwalletinvite'\n\t\t\t\t\t\t\tscope.tmpInviteesCo",
"end": 4303,
"score": 0.7609992027282715,
"start": 4293,
"tag": "PASSWORD",
"value": "passphrase"
}
] | js/directives/sidebar/da-sidebar-voting-admin.coffee | SwarmCorp/razzledazzle | 0 | window.app.directive 'daSidebarVotingAdmin', ($q, $sce, $timeout, Voting, User, Wallet, Counterparty) ->
restrict: 'A'
templateUrl: 'partials/app/blocks/sidebar-voting-admin.html'
replace: true
link: (scope) ->
scope.voting = ''
scope.newVoting = null || window.daDebug?.createNewVotingMode
scope.loading = false
scope.votingOptions = [{name: 'option1', value: ''}, {name: 'option2', value: ''}]
scope.today = new Date()
scope.votingOptionsView = true
scope.votingInviteesView = false
scope.expectingPayment = false
scope.paymentReceived = false
scope.votingCreated = false
scope.$watch (-> User.info), (newValue) ->
scope.userInfo = User.info if newValue.loaded
scope.parseEmails = (emails) ->
list = emails?.split('\n') || ''
emailPattern = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i
recipientsTmpArr = []
# let's check if any line has mails delimited by comma
for str, i in list
do (i, str) ->
arr = str.split ','
if arr.length > 1
recipientsTmpArr = recipientsTmpArr.concat arr.filter (val) -> emailPattern.test val.trim()
else
recipientsTmpArr.push str.trim() if emailPattern.test str.trim()
recipients = []
for recipient in recipientsTmpArr
recipient = recipient.trim()
if recipients.indexOf(recipient) < 0
recipients.push recipient
scope.inviteesCount = recipients.length
return recipients
toCamelCase = (string) ->
date = new Date
timestamp = Date.parse(date)/1000
string = string.replace(/[^a-zA-Z ]/g, '')
string = string.replace(RegExp(' ', 'g'), '_')
string = string+timestamp
checkInvitees = ->
defer = $q.defer()
invitees = scope.parseEmails(scope.form.addVoting.votingInvitees.$viewValue)
scope.voting.votingInvitees = invitees.join()
if invitees.length < 2
scope.form.addVoting.votingInvitees.$setValidity 'incorrect', false
scope.form.addVoting.votingInvitees.customError = true
scope.form.addVoting.votingInvitees.errorMessage = 'At least two invitees required.'
scope.formSubmitted = false
defer.reject()
else if invitees.length > 25
scope.form.addVoting.votingInvitees.$setValidity 'incorrect', false
scope.form.addVoting.votingInvitees.customError = true
scope.form.addVoting.votingInvitees.errorMessage = 'The public version of Swarm vote only allows for 25 invitees on a vote. Contact <a href="mailto:support@swarm.fund">support@swarm.fund</a> if you require more than this.'
scope.formSubmitted = false
defer.reject()
else
defer.resolve invitees
return defer.promise
createInvitees = (votingId) ->
scope.tmpInviteesObj = {}
scope.tmpInvitees = []
defer = $q.defer()
scope.tmpInviteesCount = 0
User.getAllUsers().then ()->
checkInvitees().then (invitees)->
scope.tmpInvitees = invitees
angular.forEach invitees, (invitee) ->
email = invitee.trim().toLowerCase()
passphrase = User.generatePassphrase(6)
encodedPassphrase = User.encodePassword passphrase
userData = {
votingWallet: true
email: email
temporaryPassword: encodedPassphrase
}
User.create email, passphrase, userData
.then (userData) ->
uid = userData.uid
scope.tmpInviteesObj[uid] = {
email: userData.email
signed: false
voted: false
}
User.emailNotification {login: userData.email, password: userData.passphrase}, 'votingwalletinvite'
scope.tmpInviteesCount = scope.tmpInviteesCount+1
Voting.inviteUser uid, votingId
.then null, (reason) ->
if reason.code == 'EMAIL_TAKEN'
email = reason.userData.email.toLowerCase()
User.emailNotification {login: email, voting: votingId}, 'invite-existing-user-to-vote'
User.allUsers.forEach (data, id)->
if data.email == email
if !data.wallet
userData = {votingWallet: true}
User.update userData, id
else
Voting.signUser id, votingId
scope.tmpInviteesObj[id] = {
email: data.email
signed: true
voted: false
}
scope.tmpInviteesCount = scope.tmpInviteesCount+1
Voting.inviteUser id, votingId
return false
scope.$watch (-> scope.tmpInviteesCount), (newValue)->
if newValue == scope.tmpInvitees.length
defer.resolve scope.tmpInviteesObj
return defer.promise
Voting.getVotings(true)
.then (votings) ->
scope.votings = votings
scope.loading = false
.then null, ()->
scope.votings = null
scope.loading = false
scope.switchOptionsAndUsersView = ->
scope.votingOptionsView = !scope.votingOptionsView
scope.votingInviteesView = !scope.votingInviteesView
scope.selectVoting = (voting) ->
inviteesLength = 0
for id, invitee of voting.invitees
inviteesLength++ if invitee
asset = voting.asset
votingOptions = voting.options
for option of votingOptions
Voting.getVotesCount option, asset, true
.then (data) ->
if data.balance
percent = data.balance / inviteesLength * 100
votingOptions[data.address].votesCount = Math.round(percent*100)/100
else
votingOptions[data.address].votesCount = 0
scope.title = voting.title
scope.voting = voting
scope.backToVotes = ->
scope.voting = null
scope.title = null
scope.addNewVoting = ->
scope.newVoting = true
scope.cancelAddingVoting = ->
scope.newVoting = false
scope.createVoting = ->
form = scope.form.addVoting
scope.formSubmitted = true
options = ->
optionsObj = {}
for index, option of scope.votingOptions
optionWallet = Wallet.new().public
optionsObj[optionWallet] = {
address: optionWallet
bio: option.value
}
return optionsObj
if form.$valid
votingId = toCamelCase form.votingName.$viewValue
scope.votingWallet = Wallet.new()
checkInvitees().then (invitees)->
votingData = {
paid: false
description: form.votingDescription.$viewValue
multiple: form.votingMultiple?.$viewValue || 1
end_date: moment.utc(form.votingEndDate.$viewValue).format()
id: votingId
invitees: invitees
options: options()
owner: User.info.id
start_date: moment.utc(form.votingStartDate.$viewValue).format()
title: form.votingName.$viewValue
wallet: scope.votingWallet
}
assetAmount = invitees.length
Voting.create votingData
.then () ->
Voting.inviteUser User.info.id, votingId
scope.expectingPayment = true
multipleFee = form.votingMultiple?.$viewValue || 1
scope.payForUsers = ((scope.inviteesCount*300000)*multipleFee)+100000
scope.paymentValue = scope.payForUsers + 100000
Voting.getPayment(scope.votingWallet.public, scope.paymentValue)
.then ()->
scope.paymentReceived = true
scope.expectingPayment = false
scope.loading = true
counterparty = new Counterparty(scope.votingWallet.private)
assetName = counterparty.generateFreeAssetName()
counterparty.issueAsset(assetAmount*multipleFee, assetName)
.then ()->
createInvitees(votingId)
.then (invitees)->
Voting.create {
paid: true
id: votingId
asset: assetName
invitees: invitees
}
.then ()->
Voting.getVotings()
.then (votings) ->
scope.votings = votings
scope.voting = null
scope.loading = false
scope.newVoting = false
scope.formSubmitted = false
scope.removeOption = (optionIndex) ->
if optionIndex > 1
votingOptions = scope.votingOptions
votingOptions.splice(optionIndex, 1)
scope.votingOptions = votingOptions
scope.addOption = ->
votingOptions = scope.votingOptions
votingOptions.push {name: 'option'+(votingOptions.length+1), value: ''}
scope.votingOptions = votingOptions
scope.hasError = (field) ->
form = scope.form.addVoting
if (field?.$touched && field?.$invalid) || ( scope.formSubmitted && field?.$invalid)
if !field?.customError
form.votingName?.errorMessage = if form.votingName.$invalid then 'Title is required.' else null
form.votingDescription?.errorMessage = if form.votingDescription.$invalid then 'Description is required.' else null
form.votingInvitees?.errorMessage = if form.votingInvitees.$invalid then 'Invitees are required.' else null
form.votingStartDate?.errorMessage = if form.votingStartDate.$invalid then 'Start date is required.' else null
form.votingEndDate?.errorMessage = if form.votingEndDate.$invalid then 'End date is required.' else null
if field.$name.indexOf('option') > -1
field.errorMessage = if field.$invalid then 'Option is required.' else null
return true
scope.resetInvitesValidity = ->
scope.form.addVoting.votingInvitees.$setValidity 'incorrect', true
scope.form.addVoting.votingInvitees.customError = false | 75011 | window.app.directive 'daSidebarVotingAdmin', ($q, $sce, $timeout, Voting, User, Wallet, Counterparty) ->
restrict: 'A'
templateUrl: 'partials/app/blocks/sidebar-voting-admin.html'
replace: true
link: (scope) ->
scope.voting = ''
scope.newVoting = null || window.daDebug?.createNewVotingMode
scope.loading = false
scope.votingOptions = [{name: 'option1', value: ''}, {name: 'option2', value: ''}]
scope.today = new Date()
scope.votingOptionsView = true
scope.votingInviteesView = false
scope.expectingPayment = false
scope.paymentReceived = false
scope.votingCreated = false
scope.$watch (-> User.info), (newValue) ->
scope.userInfo = User.info if newValue.loaded
scope.parseEmails = (emails) ->
list = emails?.split('\n') || ''
emailPattern = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i
recipientsTmpArr = []
# let's check if any line has mails delimited by comma
for str, i in list
do (i, str) ->
arr = str.split ','
if arr.length > 1
recipientsTmpArr = recipientsTmpArr.concat arr.filter (val) -> emailPattern.test val.trim()
else
recipientsTmpArr.push str.trim() if emailPattern.test str.trim()
recipients = []
for recipient in recipientsTmpArr
recipient = recipient.trim()
if recipients.indexOf(recipient) < 0
recipients.push recipient
scope.inviteesCount = recipients.length
return recipients
toCamelCase = (string) ->
date = new Date
timestamp = Date.parse(date)/1000
string = string.replace(/[^a-zA-Z ]/g, '')
string = string.replace(RegExp(' ', 'g'), '_')
string = string+timestamp
checkInvitees = ->
defer = $q.defer()
invitees = scope.parseEmails(scope.form.addVoting.votingInvitees.$viewValue)
scope.voting.votingInvitees = invitees.join()
if invitees.length < 2
scope.form.addVoting.votingInvitees.$setValidity 'incorrect', false
scope.form.addVoting.votingInvitees.customError = true
scope.form.addVoting.votingInvitees.errorMessage = 'At least two invitees required.'
scope.formSubmitted = false
defer.reject()
else if invitees.length > 25
scope.form.addVoting.votingInvitees.$setValidity 'incorrect', false
scope.form.addVoting.votingInvitees.customError = true
scope.form.addVoting.votingInvitees.errorMessage = 'The public version of Swarm vote only allows for 25 invitees on a vote. Contact <a href="mailto:<EMAIL>"><EMAIL></a> if you require more than this.'
scope.formSubmitted = false
defer.reject()
else
defer.resolve invitees
return defer.promise
createInvitees = (votingId) ->
scope.tmpInviteesObj = {}
scope.tmpInvitees = []
defer = $q.defer()
scope.tmpInviteesCount = 0
User.getAllUsers().then ()->
checkInvitees().then (invitees)->
scope.tmpInvitees = invitees
angular.forEach invitees, (invitee) ->
email = invitee.trim().toLowerCase()
passphrase = User.generatePassphrase(6)
encodedPassphrase = User.encodePassword passphrase
userData = {
votingWallet: true
email: email
temporaryPassword: <PASSWORD>
}
User.create email, passphrase, userData
.then (userData) ->
uid = userData.uid
scope.tmpInviteesObj[uid] = {
email: userData.email
signed: false
voted: false
}
User.emailNotification {login: userData.email, password: userData.<PASSWORD>}, 'votingwalletinvite'
scope.tmpInviteesCount = scope.tmpInviteesCount+1
Voting.inviteUser uid, votingId
.then null, (reason) ->
if reason.code == 'EMAIL_TAKEN'
email = reason.userData.email.toLowerCase()
User.emailNotification {login: email, voting: votingId}, 'invite-existing-user-to-vote'
User.allUsers.forEach (data, id)->
if data.email == email
if !data.wallet
userData = {votingWallet: true}
User.update userData, id
else
Voting.signUser id, votingId
scope.tmpInviteesObj[id] = {
email: data.email
signed: true
voted: false
}
scope.tmpInviteesCount = scope.tmpInviteesCount+1
Voting.inviteUser id, votingId
return false
scope.$watch (-> scope.tmpInviteesCount), (newValue)->
if newValue == scope.tmpInvitees.length
defer.resolve scope.tmpInviteesObj
return defer.promise
Voting.getVotings(true)
.then (votings) ->
scope.votings = votings
scope.loading = false
.then null, ()->
scope.votings = null
scope.loading = false
scope.switchOptionsAndUsersView = ->
scope.votingOptionsView = !scope.votingOptionsView
scope.votingInviteesView = !scope.votingInviteesView
scope.selectVoting = (voting) ->
inviteesLength = 0
for id, invitee of voting.invitees
inviteesLength++ if invitee
asset = voting.asset
votingOptions = voting.options
for option of votingOptions
Voting.getVotesCount option, asset, true
.then (data) ->
if data.balance
percent = data.balance / inviteesLength * 100
votingOptions[data.address].votesCount = Math.round(percent*100)/100
else
votingOptions[data.address].votesCount = 0
scope.title = voting.title
scope.voting = voting
scope.backToVotes = ->
scope.voting = null
scope.title = null
scope.addNewVoting = ->
scope.newVoting = true
scope.cancelAddingVoting = ->
scope.newVoting = false
scope.createVoting = ->
form = scope.form.addVoting
scope.formSubmitted = true
options = ->
optionsObj = {}
for index, option of scope.votingOptions
optionWallet = Wallet.new().public
optionsObj[optionWallet] = {
address: optionWallet
bio: option.value
}
return optionsObj
if form.$valid
votingId = toCamelCase form.votingName.$viewValue
scope.votingWallet = Wallet.new()
checkInvitees().then (invitees)->
votingData = {
paid: false
description: form.votingDescription.$viewValue
multiple: form.votingMultiple?.$viewValue || 1
end_date: moment.utc(form.votingEndDate.$viewValue).format()
id: votingId
invitees: invitees
options: options()
owner: User.info.id
start_date: moment.utc(form.votingStartDate.$viewValue).format()
title: form.votingName.$viewValue
wallet: scope.votingWallet
}
assetAmount = invitees.length
Voting.create votingData
.then () ->
Voting.inviteUser User.info.id, votingId
scope.expectingPayment = true
multipleFee = form.votingMultiple?.$viewValue || 1
scope.payForUsers = ((scope.inviteesCount*300000)*multipleFee)+100000
scope.paymentValue = scope.payForUsers + 100000
Voting.getPayment(scope.votingWallet.public, scope.paymentValue)
.then ()->
scope.paymentReceived = true
scope.expectingPayment = false
scope.loading = true
counterparty = new Counterparty(scope.votingWallet.private)
assetName = counterparty.generateFreeAssetName()
counterparty.issueAsset(assetAmount*multipleFee, assetName)
.then ()->
createInvitees(votingId)
.then (invitees)->
Voting.create {
paid: true
id: votingId
asset: assetName
invitees: invitees
}
.then ()->
Voting.getVotings()
.then (votings) ->
scope.votings = votings
scope.voting = null
scope.loading = false
scope.newVoting = false
scope.formSubmitted = false
scope.removeOption = (optionIndex) ->
if optionIndex > 1
votingOptions = scope.votingOptions
votingOptions.splice(optionIndex, 1)
scope.votingOptions = votingOptions
scope.addOption = ->
votingOptions = scope.votingOptions
votingOptions.push {name: 'option'+(votingOptions.length+1), value: ''}
scope.votingOptions = votingOptions
scope.hasError = (field) ->
form = scope.form.addVoting
if (field?.$touched && field?.$invalid) || ( scope.formSubmitted && field?.$invalid)
if !field?.customError
form.votingName?.errorMessage = if form.votingName.$invalid then 'Title is required.' else null
form.votingDescription?.errorMessage = if form.votingDescription.$invalid then 'Description is required.' else null
form.votingInvitees?.errorMessage = if form.votingInvitees.$invalid then 'Invitees are required.' else null
form.votingStartDate?.errorMessage = if form.votingStartDate.$invalid then 'Start date is required.' else null
form.votingEndDate?.errorMessage = if form.votingEndDate.$invalid then 'End date is required.' else null
if field.$name.indexOf('option') > -1
field.errorMessage = if field.$invalid then 'Option is required.' else null
return true
scope.resetInvitesValidity = ->
scope.form.addVoting.votingInvitees.$setValidity 'incorrect', true
scope.form.addVoting.votingInvitees.customError = false | true | window.app.directive 'daSidebarVotingAdmin', ($q, $sce, $timeout, Voting, User, Wallet, Counterparty) ->
restrict: 'A'
templateUrl: 'partials/app/blocks/sidebar-voting-admin.html'
replace: true
link: (scope) ->
scope.voting = ''
scope.newVoting = null || window.daDebug?.createNewVotingMode
scope.loading = false
scope.votingOptions = [{name: 'option1', value: ''}, {name: 'option2', value: ''}]
scope.today = new Date()
scope.votingOptionsView = true
scope.votingInviteesView = false
scope.expectingPayment = false
scope.paymentReceived = false
scope.votingCreated = false
scope.$watch (-> User.info), (newValue) ->
scope.userInfo = User.info if newValue.loaded
scope.parseEmails = (emails) ->
list = emails?.split('\n') || ''
emailPattern = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i
recipientsTmpArr = []
# let's check if any line has mails delimited by comma
for str, i in list
do (i, str) ->
arr = str.split ','
if arr.length > 1
recipientsTmpArr = recipientsTmpArr.concat arr.filter (val) -> emailPattern.test val.trim()
else
recipientsTmpArr.push str.trim() if emailPattern.test str.trim()
recipients = []
for recipient in recipientsTmpArr
recipient = recipient.trim()
if recipients.indexOf(recipient) < 0
recipients.push recipient
scope.inviteesCount = recipients.length
return recipients
toCamelCase = (string) ->
date = new Date
timestamp = Date.parse(date)/1000
string = string.replace(/[^a-zA-Z ]/g, '')
string = string.replace(RegExp(' ', 'g'), '_')
string = string+timestamp
checkInvitees = ->
defer = $q.defer()
invitees = scope.parseEmails(scope.form.addVoting.votingInvitees.$viewValue)
scope.voting.votingInvitees = invitees.join()
if invitees.length < 2
scope.form.addVoting.votingInvitees.$setValidity 'incorrect', false
scope.form.addVoting.votingInvitees.customError = true
scope.form.addVoting.votingInvitees.errorMessage = 'At least two invitees required.'
scope.formSubmitted = false
defer.reject()
else if invitees.length > 25
scope.form.addVoting.votingInvitees.$setValidity 'incorrect', false
scope.form.addVoting.votingInvitees.customError = true
scope.form.addVoting.votingInvitees.errorMessage = 'The public version of Swarm vote only allows for 25 invitees on a vote. Contact <a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a> if you require more than this.'
scope.formSubmitted = false
defer.reject()
else
defer.resolve invitees
return defer.promise
createInvitees = (votingId) ->
scope.tmpInviteesObj = {}
scope.tmpInvitees = []
defer = $q.defer()
scope.tmpInviteesCount = 0
User.getAllUsers().then ()->
checkInvitees().then (invitees)->
scope.tmpInvitees = invitees
angular.forEach invitees, (invitee) ->
email = invitee.trim().toLowerCase()
passphrase = User.generatePassphrase(6)
encodedPassphrase = User.encodePassword passphrase
userData = {
votingWallet: true
email: email
temporaryPassword: PI:PASSWORD:<PASSWORD>END_PI
}
User.create email, passphrase, userData
.then (userData) ->
uid = userData.uid
scope.tmpInviteesObj[uid] = {
email: userData.email
signed: false
voted: false
}
User.emailNotification {login: userData.email, password: userData.PI:PASSWORD:<PASSWORD>END_PI}, 'votingwalletinvite'
scope.tmpInviteesCount = scope.tmpInviteesCount+1
Voting.inviteUser uid, votingId
.then null, (reason) ->
if reason.code == 'EMAIL_TAKEN'
email = reason.userData.email.toLowerCase()
User.emailNotification {login: email, voting: votingId}, 'invite-existing-user-to-vote'
User.allUsers.forEach (data, id)->
if data.email == email
if !data.wallet
userData = {votingWallet: true}
User.update userData, id
else
Voting.signUser id, votingId
scope.tmpInviteesObj[id] = {
email: data.email
signed: true
voted: false
}
scope.tmpInviteesCount = scope.tmpInviteesCount+1
Voting.inviteUser id, votingId
return false
scope.$watch (-> scope.tmpInviteesCount), (newValue)->
if newValue == scope.tmpInvitees.length
defer.resolve scope.tmpInviteesObj
return defer.promise
Voting.getVotings(true)
.then (votings) ->
scope.votings = votings
scope.loading = false
.then null, ()->
scope.votings = null
scope.loading = false
scope.switchOptionsAndUsersView = ->
scope.votingOptionsView = !scope.votingOptionsView
scope.votingInviteesView = !scope.votingInviteesView
scope.selectVoting = (voting) ->
inviteesLength = 0
for id, invitee of voting.invitees
inviteesLength++ if invitee
asset = voting.asset
votingOptions = voting.options
for option of votingOptions
Voting.getVotesCount option, asset, true
.then (data) ->
if data.balance
percent = data.balance / inviteesLength * 100
votingOptions[data.address].votesCount = Math.round(percent*100)/100
else
votingOptions[data.address].votesCount = 0
scope.title = voting.title
scope.voting = voting
scope.backToVotes = ->
scope.voting = null
scope.title = null
scope.addNewVoting = ->
scope.newVoting = true
scope.cancelAddingVoting = ->
scope.newVoting = false
scope.createVoting = ->
form = scope.form.addVoting
scope.formSubmitted = true
options = ->
optionsObj = {}
for index, option of scope.votingOptions
optionWallet = Wallet.new().public
optionsObj[optionWallet] = {
address: optionWallet
bio: option.value
}
return optionsObj
if form.$valid
votingId = toCamelCase form.votingName.$viewValue
scope.votingWallet = Wallet.new()
checkInvitees().then (invitees)->
votingData = {
paid: false
description: form.votingDescription.$viewValue
multiple: form.votingMultiple?.$viewValue || 1
end_date: moment.utc(form.votingEndDate.$viewValue).format()
id: votingId
invitees: invitees
options: options()
owner: User.info.id
start_date: moment.utc(form.votingStartDate.$viewValue).format()
title: form.votingName.$viewValue
wallet: scope.votingWallet
}
assetAmount = invitees.length
Voting.create votingData
.then () ->
Voting.inviteUser User.info.id, votingId
scope.expectingPayment = true
multipleFee = form.votingMultiple?.$viewValue || 1
scope.payForUsers = ((scope.inviteesCount*300000)*multipleFee)+100000
scope.paymentValue = scope.payForUsers + 100000
Voting.getPayment(scope.votingWallet.public, scope.paymentValue)
.then ()->
scope.paymentReceived = true
scope.expectingPayment = false
scope.loading = true
counterparty = new Counterparty(scope.votingWallet.private)
assetName = counterparty.generateFreeAssetName()
counterparty.issueAsset(assetAmount*multipleFee, assetName)
.then ()->
createInvitees(votingId)
.then (invitees)->
Voting.create {
paid: true
id: votingId
asset: assetName
invitees: invitees
}
.then ()->
Voting.getVotings()
.then (votings) ->
scope.votings = votings
scope.voting = null
scope.loading = false
scope.newVoting = false
scope.formSubmitted = false
scope.removeOption = (optionIndex) ->
if optionIndex > 1
votingOptions = scope.votingOptions
votingOptions.splice(optionIndex, 1)
scope.votingOptions = votingOptions
scope.addOption = ->
votingOptions = scope.votingOptions
votingOptions.push {name: 'option'+(votingOptions.length+1), value: ''}
scope.votingOptions = votingOptions
scope.hasError = (field) ->
form = scope.form.addVoting
if (field?.$touched && field?.$invalid) || ( scope.formSubmitted && field?.$invalid)
if !field?.customError
form.votingName?.errorMessage = if form.votingName.$invalid then 'Title is required.' else null
form.votingDescription?.errorMessage = if form.votingDescription.$invalid then 'Description is required.' else null
form.votingInvitees?.errorMessage = if form.votingInvitees.$invalid then 'Invitees are required.' else null
form.votingStartDate?.errorMessage = if form.votingStartDate.$invalid then 'Start date is required.' else null
form.votingEndDate?.errorMessage = if form.votingEndDate.$invalid then 'End date is required.' else null
if field.$name.indexOf('option') > -1
field.errorMessage = if field.$invalid then 'Option is required.' else null
return true
scope.resetInvitesValidity = ->
scope.form.addVoting.votingInvitees.$setValidity 'incorrect', true
scope.form.addVoting.votingInvitees.customError = false |
[
{
"context": "loader from archive.routeviews.org\n#\n# Author:\n# Shintaro Kojima <goodies@codeout.net>\n\nHttpClient = require('scop",
"end": 100,
"score": 0.9998614192008972,
"start": 85,
"tag": "NAME",
"value": "Shintaro Kojima"
},
{
"context": "e.routeviews.org\n#\n# Author:\n# Shintaro Kojima <goodies@codeout.net>\n\nHttpClient = require('scoped-http-client')\nPars",
"end": 121,
"score": 0.9999282956123352,
"start": 102,
"tag": "EMAIL",
"value": "goodies@codeout.net"
}
] | src/index.coffee | codeout/node-mrt | 0 | # Description
# MRT archive downloader from archive.routeviews.org
#
# Author:
# Shintaro Kojima <goodies@codeout.net>
HttpClient = require('scoped-http-client')
Parser = require('cheerio')
Tmp = require('tmp')
class MRT
constructor: (@server) ->
@cache = {}
month: ->
date = new Date()
date.getUTCFullYear().toString() + '.' + ('0' + (date.getUTCMonth()+1)).slice(-2)
indexUrl: (month) ->
"http://archive.routeviews.org/route-views.#{@server}/bgpdata/#{@month()}/RIBS/"
lastFileUrl: (errorHandler, callback) ->
url = @indexUrl()
HttpClient.create(url).get() (err, res, body) ->
if err
errorHandler err
return
if res.statusCode != 200
errorHandler "Bad HTTP response: #{res.statusCode}"
return
$ = Parser.load(body)
callback url + $('a').last().attr('href')
get: (messageHandler, callback) ->
timeout = process.env.MRT_CACHE_TIMEOUT || 86400000 # 1 day
if @cache.date && new Date() - @cache['date'] < timeout
callback @cache.path
return
messageHandler "Fresh MRT is not found"
@lastFileUrl messageHandler, (url) =>
messageHandler "Downloading #{url} ... please wait"
HttpClient.create(url, encoding: 'binary').get() (err, res, body) =>
if err
messageHandler err
return
if res.statusCode != 200
messageHandler "Bad HTTP response: #{res.statusCode}"
return
@write body, url, messageHandler, (path) =>
@cache.date = new Date()
@cache.path = path
messageHandler "Saved as #{path}"
callback path
write: (content, url, errorHandler, callback) ->
path = require('path')
ext = path.extname(url)
Tmp.file postfix: ext, (err, path, fd, cleanupCallback) ->
if err
errorHandler err
return
fs = require('fs')
fs.writeFile path, content, 'binary', (err) ->
if err
errorHandler err
return
callback path
module.exports = MRT
| 126897 | # Description
# MRT archive downloader from archive.routeviews.org
#
# Author:
# <NAME> <<EMAIL>>
HttpClient = require('scoped-http-client')
Parser = require('cheerio')
Tmp = require('tmp')
class MRT
constructor: (@server) ->
@cache = {}
month: ->
date = new Date()
date.getUTCFullYear().toString() + '.' + ('0' + (date.getUTCMonth()+1)).slice(-2)
indexUrl: (month) ->
"http://archive.routeviews.org/route-views.#{@server}/bgpdata/#{@month()}/RIBS/"
lastFileUrl: (errorHandler, callback) ->
url = @indexUrl()
HttpClient.create(url).get() (err, res, body) ->
if err
errorHandler err
return
if res.statusCode != 200
errorHandler "Bad HTTP response: #{res.statusCode}"
return
$ = Parser.load(body)
callback url + $('a').last().attr('href')
get: (messageHandler, callback) ->
timeout = process.env.MRT_CACHE_TIMEOUT || 86400000 # 1 day
if @cache.date && new Date() - @cache['date'] < timeout
callback @cache.path
return
messageHandler "Fresh MRT is not found"
@lastFileUrl messageHandler, (url) =>
messageHandler "Downloading #{url} ... please wait"
HttpClient.create(url, encoding: 'binary').get() (err, res, body) =>
if err
messageHandler err
return
if res.statusCode != 200
messageHandler "Bad HTTP response: #{res.statusCode}"
return
@write body, url, messageHandler, (path) =>
@cache.date = new Date()
@cache.path = path
messageHandler "Saved as #{path}"
callback path
write: (content, url, errorHandler, callback) ->
path = require('path')
ext = path.extname(url)
Tmp.file postfix: ext, (err, path, fd, cleanupCallback) ->
if err
errorHandler err
return
fs = require('fs')
fs.writeFile path, content, 'binary', (err) ->
if err
errorHandler err
return
callback path
module.exports = MRT
| true | # Description
# MRT archive downloader from archive.routeviews.org
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
HttpClient = require('scoped-http-client')
Parser = require('cheerio')
Tmp = require('tmp')
class MRT
constructor: (@server) ->
@cache = {}
month: ->
date = new Date()
date.getUTCFullYear().toString() + '.' + ('0' + (date.getUTCMonth()+1)).slice(-2)
indexUrl: (month) ->
"http://archive.routeviews.org/route-views.#{@server}/bgpdata/#{@month()}/RIBS/"
lastFileUrl: (errorHandler, callback) ->
url = @indexUrl()
HttpClient.create(url).get() (err, res, body) ->
if err
errorHandler err
return
if res.statusCode != 200
errorHandler "Bad HTTP response: #{res.statusCode}"
return
$ = Parser.load(body)
callback url + $('a').last().attr('href')
get: (messageHandler, callback) ->
timeout = process.env.MRT_CACHE_TIMEOUT || 86400000 # 1 day
if @cache.date && new Date() - @cache['date'] < timeout
callback @cache.path
return
messageHandler "Fresh MRT is not found"
@lastFileUrl messageHandler, (url) =>
messageHandler "Downloading #{url} ... please wait"
HttpClient.create(url, encoding: 'binary').get() (err, res, body) =>
if err
messageHandler err
return
if res.statusCode != 200
messageHandler "Bad HTTP response: #{res.statusCode}"
return
@write body, url, messageHandler, (path) =>
@cache.date = new Date()
@cache.path = path
messageHandler "Saved as #{path}"
callback path
write: (content, url, errorHandler, callback) ->
path = require('path')
ext = path.extname(url)
Tmp.file postfix: ext, (err, path, fd, cleanupCallback) ->
if err
errorHandler err
return
fs = require('fs')
fs.writeFile path, content, 'binary', (err) ->
if err
errorHandler err
return
callback path
module.exports = MRT
|
[
{
"context": "= 42\n\n fakeRecipe =\n id: recipeId\n name: \"Baked Potatoes\"\n instructions: \"Pierce potato with fork, nuke",
"end": 215,
"score": 0.9200836420059204,
"start": 201,
"tag": "NAME",
"value": "Baked Potatoes"
}
] | spec/javascripts/controllers/RecipeController_spec.coffee | yumikohey/receta | 0 | describe "RecipeController", ->
scope = null
ctrl = null
routeParams = null
httpBackend = null
flash = null
recipeId = 42
fakeRecipe =
id: recipeId
name: "Baked Potatoes"
instructions: "Pierce potato with fork, nuke for 20 minutes"
setupController =(recipeExists=true)->
inject(($location, $routeParams, $rootScope, $httpBackend, $controller, _flash_)->
scope = $rootScope.$new()
location = $location
httpBackend = $httpBackend
routeParams = $routeParams
routeParams.recipeId = recipeId
flash = _flash_
request = new RegExp("\/recipes/#{recipeId}")
results = if recipeExists
[200,fakeRecipe]
else
[404]
httpBackend.expectGET(request).respond(results[0],results[1])
ctrl = $controller('RecipeController',
$scope: scope)
)
beforeEach(module("receta"))
afterEach ->
httpBackend.verifyNoOutstandingExpectation()
httpBackend.verifyNoOutstandingRequest()
describe 'controller initialization', ->
describe 'recipe is found', ->
beforeEach(setupController())
it 'loads the given recipe', ->
httpBackend.flush()
expect(scope.recipe).toEqualData(fakeRecipe)
describe 'recipe is not found', ->
beforeEach(setupController(false))
it 'loads the given recipe', ->
httpBackend.flush()
expect(scope.recipe).toBe(null)
expect(flash.error).toBe("There is no recipe with ID #{recipeId}") | 118508 | describe "RecipeController", ->
scope = null
ctrl = null
routeParams = null
httpBackend = null
flash = null
recipeId = 42
fakeRecipe =
id: recipeId
name: "<NAME>"
instructions: "Pierce potato with fork, nuke for 20 minutes"
setupController =(recipeExists=true)->
inject(($location, $routeParams, $rootScope, $httpBackend, $controller, _flash_)->
scope = $rootScope.$new()
location = $location
httpBackend = $httpBackend
routeParams = $routeParams
routeParams.recipeId = recipeId
flash = _flash_
request = new RegExp("\/recipes/#{recipeId}")
results = if recipeExists
[200,fakeRecipe]
else
[404]
httpBackend.expectGET(request).respond(results[0],results[1])
ctrl = $controller('RecipeController',
$scope: scope)
)
beforeEach(module("receta"))
afterEach ->
httpBackend.verifyNoOutstandingExpectation()
httpBackend.verifyNoOutstandingRequest()
describe 'controller initialization', ->
describe 'recipe is found', ->
beforeEach(setupController())
it 'loads the given recipe', ->
httpBackend.flush()
expect(scope.recipe).toEqualData(fakeRecipe)
describe 'recipe is not found', ->
beforeEach(setupController(false))
it 'loads the given recipe', ->
httpBackend.flush()
expect(scope.recipe).toBe(null)
expect(flash.error).toBe("There is no recipe with ID #{recipeId}") | true | describe "RecipeController", ->
scope = null
ctrl = null
routeParams = null
httpBackend = null
flash = null
recipeId = 42
fakeRecipe =
id: recipeId
name: "PI:NAME:<NAME>END_PI"
instructions: "Pierce potato with fork, nuke for 20 minutes"
setupController =(recipeExists=true)->
inject(($location, $routeParams, $rootScope, $httpBackend, $controller, _flash_)->
scope = $rootScope.$new()
location = $location
httpBackend = $httpBackend
routeParams = $routeParams
routeParams.recipeId = recipeId
flash = _flash_
request = new RegExp("\/recipes/#{recipeId}")
results = if recipeExists
[200,fakeRecipe]
else
[404]
httpBackend.expectGET(request).respond(results[0],results[1])
ctrl = $controller('RecipeController',
$scope: scope)
)
beforeEach(module("receta"))
afterEach ->
httpBackend.verifyNoOutstandingExpectation()
httpBackend.verifyNoOutstandingRequest()
describe 'controller initialization', ->
describe 'recipe is found', ->
beforeEach(setupController())
it 'loads the given recipe', ->
httpBackend.flush()
expect(scope.recipe).toEqualData(fakeRecipe)
describe 'recipe is not found', ->
beforeEach(setupController(false))
it 'loads the given recipe', ->
httpBackend.flush()
expect(scope.recipe).toBe(null)
expect(flash.error).toBe("There is no recipe with ID #{recipeId}") |
[
{
"context": "nfo.title\n tags : 'Cnode'\n consumer_key:process.env.pocket\n access_token:''\n }\n users = []\n as",
"end": 1535,
"score": 0.963706910610199,
"start": 1517,
"tag": "KEY",
"value": "process.env.pocket"
}
] | servers/saveArticle.coffee | youqingkui/cnode2pocket | 0 | request = require('request')
async = require('async')
Article = require('../models/article')
User = require('../models/user')
saveErr = require('../servers/saveErr')
class ArticleSave
constructor:() ->
@baseUrl = 'https://cnodejs.org/api/v1/topics?tab=good&page='
@urlArr = []
getPage:(page, cb) ->
self = @
url = self.baseUrl + page
console.log url
async.auto
getInfo:(callback) ->
request.get url, (err, res, body) ->
return saveErr url, 1, {err:err,body:body} if err
try
data = JSON.parse(body)
catch
return saveErr url, 3, {err:body}
callback(null, data)
pieceUrl:['getInfo', (callback, result) ->
data = result.getInfo
if data.data.length
data.data.forEach (item) ->
tmp =
url:'https://cnodejs.org/topic/' + item.id
title:item.title
created:Date.now()
Article.findOne {url:tmp.url}, (err, row) ->
return saveErr tmp.url, 2, {err:err} if err
if not row
newArt = new Article(tmp)
newArt.save (err2, row2) ->
return saveErr "", 2, {err:err2} if err2
self.pushUser(tmp)
self.getPage(page + 1, cb)
else
console.log "page =>", page, data
]
pushUser:(info) ->
self = @
form = {
url:info.url
title : info.title
tags : 'Cnode'
consumer_key:process.env.pocket
access_token:''
}
users = []
async.auto
findUser:(cb) ->
User.find {subscribe:true}, (err, rows) ->
return saveErr "", 2, {err:err} if err
users = rows
cb()
pushInfo:['findUser', (cb) ->
if users.length
async.eachLimit users, 10, (item, callback) ->
form.access_token = item.token
op =
form:form
url:'https://getpocket.com/v3/add'
request.post op, (err, res, body) ->
return saveErr op.url, 1, {err:err,body:body} if err
console.log body
callback()
,() ->
console.log "### push user subscribe #{form.url} all do ###"
]
module.exports = ArticleSave
| 11975 | request = require('request')
async = require('async')
Article = require('../models/article')
User = require('../models/user')
saveErr = require('../servers/saveErr')
class ArticleSave
constructor:() ->
@baseUrl = 'https://cnodejs.org/api/v1/topics?tab=good&page='
@urlArr = []
getPage:(page, cb) ->
self = @
url = self.baseUrl + page
console.log url
async.auto
getInfo:(callback) ->
request.get url, (err, res, body) ->
return saveErr url, 1, {err:err,body:body} if err
try
data = JSON.parse(body)
catch
return saveErr url, 3, {err:body}
callback(null, data)
pieceUrl:['getInfo', (callback, result) ->
data = result.getInfo
if data.data.length
data.data.forEach (item) ->
tmp =
url:'https://cnodejs.org/topic/' + item.id
title:item.title
created:Date.now()
Article.findOne {url:tmp.url}, (err, row) ->
return saveErr tmp.url, 2, {err:err} if err
if not row
newArt = new Article(tmp)
newArt.save (err2, row2) ->
return saveErr "", 2, {err:err2} if err2
self.pushUser(tmp)
self.getPage(page + 1, cb)
else
console.log "page =>", page, data
]
pushUser:(info) ->
self = @
form = {
url:info.url
title : info.title
tags : 'Cnode'
consumer_key:<KEY>
access_token:''
}
users = []
async.auto
findUser:(cb) ->
User.find {subscribe:true}, (err, rows) ->
return saveErr "", 2, {err:err} if err
users = rows
cb()
pushInfo:['findUser', (cb) ->
if users.length
async.eachLimit users, 10, (item, callback) ->
form.access_token = item.token
op =
form:form
url:'https://getpocket.com/v3/add'
request.post op, (err, res, body) ->
return saveErr op.url, 1, {err:err,body:body} if err
console.log body
callback()
,() ->
console.log "### push user subscribe #{form.url} all do ###"
]
module.exports = ArticleSave
| true | request = require('request')
async = require('async')
Article = require('../models/article')
User = require('../models/user')
saveErr = require('../servers/saveErr')
class ArticleSave
constructor:() ->
@baseUrl = 'https://cnodejs.org/api/v1/topics?tab=good&page='
@urlArr = []
getPage:(page, cb) ->
self = @
url = self.baseUrl + page
console.log url
async.auto
getInfo:(callback) ->
request.get url, (err, res, body) ->
return saveErr url, 1, {err:err,body:body} if err
try
data = JSON.parse(body)
catch
return saveErr url, 3, {err:body}
callback(null, data)
pieceUrl:['getInfo', (callback, result) ->
data = result.getInfo
if data.data.length
data.data.forEach (item) ->
tmp =
url:'https://cnodejs.org/topic/' + item.id
title:item.title
created:Date.now()
Article.findOne {url:tmp.url}, (err, row) ->
return saveErr tmp.url, 2, {err:err} if err
if not row
newArt = new Article(tmp)
newArt.save (err2, row2) ->
return saveErr "", 2, {err:err2} if err2
self.pushUser(tmp)
self.getPage(page + 1, cb)
else
console.log "page =>", page, data
]
pushUser:(info) ->
self = @
form = {
url:info.url
title : info.title
tags : 'Cnode'
consumer_key:PI:KEY:<KEY>END_PI
access_token:''
}
users = []
async.auto
findUser:(cb) ->
User.find {subscribe:true}, (err, rows) ->
return saveErr "", 2, {err:err} if err
users = rows
cb()
pushInfo:['findUser', (cb) ->
if users.length
async.eachLimit users, 10, (item, callback) ->
form.access_token = item.token
op =
form:form
url:'https://getpocket.com/v3/add'
request.post op, (err, res, body) ->
return saveErr op.url, 1, {err:err,body:body} if err
console.log body
callback()
,() ->
console.log "### push user subscribe #{form.url} all do ###"
]
module.exports = ArticleSave
|
[
{
"context": "s'\n folder: 'utils'\n ,\n name: 'Lier'\n folder: 'app'\n ]\n\n @provider =",
"end": 430,
"score": 0.9810205698013306,
"start": 426,
"tag": "NAME",
"value": "Lier"
}
] | lib/extjs4-autocomplete.coffee | Sighter/extjs4-autocomplete | 0 | module.exports =
provider: null
activate: ->
console.log "activating extjs4-autocomplete"
console.log 'got path', atom.project.getDirectories()
deactivate: ->
@provider = null
provide: ->
unless @provider?
console.log "providing extjs4-autocomplete"
Extjs4Provider = require('./classpath-provider')
mapping = [
name: 'Utils'
folder: 'utils'
,
name: 'Lier'
folder: 'app'
]
@provider = new Extjs4Provider(mapping)
return @provider
| 149889 | module.exports =
provider: null
activate: ->
console.log "activating extjs4-autocomplete"
console.log 'got path', atom.project.getDirectories()
deactivate: ->
@provider = null
provide: ->
unless @provider?
console.log "providing extjs4-autocomplete"
Extjs4Provider = require('./classpath-provider')
mapping = [
name: 'Utils'
folder: 'utils'
,
name: '<NAME>'
folder: 'app'
]
@provider = new Extjs4Provider(mapping)
return @provider
| true | module.exports =
provider: null
activate: ->
console.log "activating extjs4-autocomplete"
console.log 'got path', atom.project.getDirectories()
deactivate: ->
@provider = null
provide: ->
unless @provider?
console.log "providing extjs4-autocomplete"
Extjs4Provider = require('./classpath-provider')
mapping = [
name: 'Utils'
folder: 'utils'
,
name: 'PI:NAME:<NAME>END_PI'
folder: 'app'
]
@provider = new Extjs4Provider(mapping)
return @provider
|
[
{
"context": "###\nGulp task bower\n@create 2014-10-07\n@author KoutarouYabe <idolm@ster.pw>\n###\n\nmodule.exports = (gulp, plug",
"end": 59,
"score": 0.9998926520347595,
"start": 47,
"tag": "NAME",
"value": "KoutarouYabe"
},
{
"context": "sk bower\n@create 2014-10-07\n@author KoutarouYabe <idolm@ster.pw>\n###\n\nmodule.exports = (gulp, plugins, path)->\n ",
"end": 74,
"score": 0.9999317526817322,
"start": 61,
"tag": "EMAIL",
"value": "idolm@ster.pw"
}
] | tasks/config/dependencies.coffee | ky0615/atc_tram | 0 | ###
Gulp task bower
@create 2014-10-07
@author KoutarouYabe <idolm@ster.pw>
###
module.exports = (gulp, plugins, path)->
filter = plugins.filter
jsFilter = filter ["**/*.js", "**/*.js.map"]
cssFilter = filter "**/*.css"
fontFilter = filter ["**/*.ttf", "**/*.svg", "**/*.eot", "**/*.woff", "**/*.woff2"]
gulp.task "dependencies", ->
dependenciesFiles = require("../pipeline").dependenciesFilesToInject
plugins.util.log "---dependencies including file---"
for bf in dependenciesFiles
plugins.util.log path.basename bf
plugins.util.log "--------------------------"
gulp.src dependenciesFiles
.pipe jsFilter
.pipe gulp.dest plugins.config.destPath + "js/lib"
.pipe jsFilter.restore()
.pipe cssFilter
.pipe gulp.dest plugins.config.destPath + "css/lib"
.pipe cssFilter.restore()
.pipe fontFilter
.pipe gulp.dest plugins.config.destPath + "css/fonts"
| 142300 | ###
Gulp task bower
@create 2014-10-07
@author <NAME> <<EMAIL>>
###
module.exports = (gulp, plugins, path)->
filter = plugins.filter
jsFilter = filter ["**/*.js", "**/*.js.map"]
cssFilter = filter "**/*.css"
fontFilter = filter ["**/*.ttf", "**/*.svg", "**/*.eot", "**/*.woff", "**/*.woff2"]
gulp.task "dependencies", ->
dependenciesFiles = require("../pipeline").dependenciesFilesToInject
plugins.util.log "---dependencies including file---"
for bf in dependenciesFiles
plugins.util.log path.basename bf
plugins.util.log "--------------------------"
gulp.src dependenciesFiles
.pipe jsFilter
.pipe gulp.dest plugins.config.destPath + "js/lib"
.pipe jsFilter.restore()
.pipe cssFilter
.pipe gulp.dest plugins.config.destPath + "css/lib"
.pipe cssFilter.restore()
.pipe fontFilter
.pipe gulp.dest plugins.config.destPath + "css/fonts"
| true | ###
Gulp task bower
@create 2014-10-07
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
module.exports = (gulp, plugins, path)->
filter = plugins.filter
jsFilter = filter ["**/*.js", "**/*.js.map"]
cssFilter = filter "**/*.css"
fontFilter = filter ["**/*.ttf", "**/*.svg", "**/*.eot", "**/*.woff", "**/*.woff2"]
gulp.task "dependencies", ->
dependenciesFiles = require("../pipeline").dependenciesFilesToInject
plugins.util.log "---dependencies including file---"
for bf in dependenciesFiles
plugins.util.log path.basename bf
plugins.util.log "--------------------------"
gulp.src dependenciesFiles
.pipe jsFilter
.pipe gulp.dest plugins.config.destPath + "js/lib"
.pipe jsFilter.restore()
.pipe cssFilter
.pipe gulp.dest plugins.config.destPath + "css/lib"
.pipe cssFilter.restore()
.pipe fontFilter
.pipe gulp.dest plugins.config.destPath + "css/fonts"
|
[
{
"context": "'speaks by', @name\ndan = man.new()\ndan.give_name 'Dan'\ndan.introduce()\ndan.speak()\n\nconsole.log '-- sup",
"end": 348,
"score": 0.9938783049583435,
"start": 345,
"tag": "NAME",
"value": "Dan"
}
] | test.coffee | tiye/proto-scope | 1 |
proto = require './proto.coffee'
console.log '-- inherent --'
human = proto.as
init: -> @name = 'human race'
give_name: (@name) ->
introduce: -> console.log "this is #{@name}"
tom = human.new()
tom.introduce()
console.log '-- sub class --'
man = human.as
speak: ->
console.log 'speaks by', @name
dan = man.new()
dan.give_name 'Dan'
dan.introduce()
dan.speak()
console.log '-- super --'
a = proto.as
init: ->
console.log 'this is a'
b = a.as
init: ->
console.log 'this is b'
@super()
c = b.new
init: ->
console.log 'this is c'
@super() | 13179 |
proto = require './proto.coffee'
console.log '-- inherent --'
human = proto.as
init: -> @name = 'human race'
give_name: (@name) ->
introduce: -> console.log "this is #{@name}"
tom = human.new()
tom.introduce()
console.log '-- sub class --'
man = human.as
speak: ->
console.log 'speaks by', @name
dan = man.new()
dan.give_name '<NAME>'
dan.introduce()
dan.speak()
console.log '-- super --'
a = proto.as
init: ->
console.log 'this is a'
b = a.as
init: ->
console.log 'this is b'
@super()
c = b.new
init: ->
console.log 'this is c'
@super() | true |
proto = require './proto.coffee'
console.log '-- inherent --'
human = proto.as
init: -> @name = 'human race'
give_name: (@name) ->
introduce: -> console.log "this is #{@name}"
tom = human.new()
tom.introduce()
console.log '-- sub class --'
man = human.as
speak: ->
console.log 'speaks by', @name
dan = man.new()
dan.give_name 'PI:NAME:<NAME>END_PI'
dan.introduce()
dan.speak()
console.log '-- super --'
a = proto.as
init: ->
console.log 'this is a'
b = a.as
init: ->
console.log 'this is b'
@super()
c = b.new
init: ->
console.log 'this is c'
@super() |
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9990425109863281,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": "Nov 6 09:52:22 2029 GMT\\\",\" + \"\\\"fingerprint\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n if re",
"end": 2614,
"score": 0.942126452922821,
"start": 2588,
"tag": "IP_ADDRESS",
"value": "2A:7A:C2:DD:E5:F9:CC:53:72"
},
{
"context": " + \"\\\"fingerprint\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n if req.i",
"end": 2617,
"score": 0.80707186460495,
"start": 2616,
"tag": "IP_ADDRESS",
"value": "5"
},
{
"context": "\"\\\"fingerprint\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n if req.id i",
"end": 2620,
"score": 0.7112470865249634,
"start": 2619,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": "fingerprint\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n if req.id is 0",
"end": 2623,
"score": 0.5226801037788391,
"start": 2622,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": "t\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n if req.id is 0\n assert.equal \"GET\", req.",
"end": 2652,
"score": 0.996577799320221,
"start": 2632,
"tag": "IP_ADDRESS",
"value": "5A:71:38:52:EC:8A:DF"
},
{
"context": "Nov 6 09:52:22 2029 GMT\\\",\" + \"\\\"fingerprint\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n c.w",
"end": 4067,
"score": 0.9569572806358337,
"start": 4041,
"tag": "IP_ADDRESS",
"value": "2A:7A:C2:DD:E5:F9:CC:53:72"
},
{
"context": " + \"\\\"fingerprint\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n c.writ",
"end": 4070,
"score": 0.8697559237480164,
"start": 4069,
"tag": "IP_ADDRESS",
"value": "5"
},
{
"context": "\"\\\"fingerprint\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n c.write \"",
"end": 4073,
"score": 0.7818194627761841,
"start": 4072,
"tag": "IP_ADDRESS",
"value": "9"
},
{
"context": "fingerprint\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n c.write \"GET",
"end": 4076,
"score": 0.7363075017929077,
"start": 4075,
"tag": "IP_ADDRESS",
"value": "A"
},
{
"context": "gerprint\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n c.write \"GET /h",
"end": 4079,
"score": 0.7540459632873535,
"start": 4078,
"tag": "IP_ADDRESS",
"value": "2"
},
{
"context": "t\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:\" + \"5A:71:38:52:EC:8A:DF\\\"}\"\n c.write \"GET /hello?hello=world&foo=b==ar",
"end": 4105,
"score": 0.9703991413116455,
"start": 4085,
"tag": "IP_ADDRESS",
"value": "5A:71:38:52:EC:8A:DF"
}
] | test/disabled/test-http-tls.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
http = require("http")
url = require("url")
qs = require("querystring")
fs = require("fs")
have_openssl = undefined
try
crypto = require("crypto")
dummy_server = http.createServer(->
)
dummy_server.setSecure()
have_openssl = true
catch e
have_openssl = false
console.log "Not compiled with OPENSSL support."
process.exit()
request_number = 0
requests_sent = 0
server_response = ""
client_got_eof = false
caPem = fs.readFileSync(common.fixturesDir + "/test_ca.pem", "ascii")
certPem = fs.readFileSync(common.fixturesDir + "/test_cert.pem", "ascii")
keyPem = fs.readFileSync(common.fixturesDir + "/test_key.pem", "ascii")
try
credentials = crypto.createCredentials(
key: keyPem
cert: certPem
ca: caPem
)
catch e
console.log "Not compiled with OPENSSL support."
process.exit()
https_server = http.createServer((req, res) ->
res.id = request_number
req.id = request_number++
verified = res.connection.verifyPeer()
peerDN = JSON.stringify(req.connection.getPeerCertificate())
assert.equal verified, true
assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}"
if req.id is 0
assert.equal "GET", req.method
assert.equal "/hello", url.parse(req.url).pathname
assert.equal "world", qs.parse(url.parse(req.url).query).hello
assert.equal "b==ar", qs.parse(url.parse(req.url).query).foo
if req.id is 1
assert.equal "POST", req.method
assert.equal "/quit", url.parse(req.url).pathname
assert.equal "foo", req.headers["x-x"] if req.id is 2
if req.id is 3
assert.equal "bar", req.headers["x-x"]
@close()
#console.log('server closed');
setTimeout (->
res.writeHead 200,
"Content-Type": "text/plain"
res.write url.parse(req.url).pathname
res.end()
return
), 1
return
)
https_server.setSecure credentials
https_server.listen common.PORT
https_server.on "listening", ->
c = net.createConnection(common.PORT)
c.setEncoding "utf8"
c.on "connect", ->
c.setSecure credentials
return
c.on "secure", ->
verified = c.verifyPeer()
peerDN = JSON.stringify(c.getPeerCertificate())
assert.equal verified, true
assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}"
c.write "GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n"
requests_sent += 1
return
c.on "data", (chunk) ->
server_response += chunk
if requests_sent is 1
c.write "POST /quit HTTP/1.1\r\n\r\n"
requests_sent += 1
if requests_sent is 2
c.write "GET / HTTP/1.1\r\nX-X: foo\r\n\r\n" + "GET / HTTP/1.1\r\nX-X: bar\r\n\r\n"
c.end()
assert.equal c.readyState, "readOnly"
requests_sent += 2
return
c.on "end", ->
client_got_eof = true
return
c.on "close", ->
assert.equal c.readyState, "closed"
return
return
process.on "exit", ->
assert.equal 4, request_number
assert.equal 4, requests_sent
hello = new RegExp("/hello")
assert.equal true, hello.exec(server_response)?
quit = new RegExp("/quit")
assert.equal true, quit.exec(server_response)?
assert.equal true, client_got_eof
return
| 218894 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
http = require("http")
url = require("url")
qs = require("querystring")
fs = require("fs")
have_openssl = undefined
try
crypto = require("crypto")
dummy_server = http.createServer(->
)
dummy_server.setSecure()
have_openssl = true
catch e
have_openssl = false
console.log "Not compiled with OPENSSL support."
process.exit()
request_number = 0
requests_sent = 0
server_response = ""
client_got_eof = false
caPem = fs.readFileSync(common.fixturesDir + "/test_ca.pem", "ascii")
certPem = fs.readFileSync(common.fixturesDir + "/test_cert.pem", "ascii")
keyPem = fs.readFileSync(common.fixturesDir + "/test_key.pem", "ascii")
try
credentials = crypto.createCredentials(
key: keyPem
cert: certPem
ca: caPem
)
catch e
console.log "Not compiled with OPENSSL support."
process.exit()
https_server = http.createServer((req, res) ->
res.id = request_number
req.id = request_number++
verified = res.connection.verifyPeer()
peerDN = JSON.stringify(req.connection.getPeerCertificate())
assert.equal verified, true
assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}"
if req.id is 0
assert.equal "GET", req.method
assert.equal "/hello", url.parse(req.url).pathname
assert.equal "world", qs.parse(url.parse(req.url).query).hello
assert.equal "b==ar", qs.parse(url.parse(req.url).query).foo
if req.id is 1
assert.equal "POST", req.method
assert.equal "/quit", url.parse(req.url).pathname
assert.equal "foo", req.headers["x-x"] if req.id is 2
if req.id is 3
assert.equal "bar", req.headers["x-x"]
@close()
#console.log('server closed');
setTimeout (->
res.writeHead 200,
"Content-Type": "text/plain"
res.write url.parse(req.url).pathname
res.end()
return
), 1
return
)
https_server.setSecure credentials
https_server.listen common.PORT
https_server.on "listening", ->
c = net.createConnection(common.PORT)
c.setEncoding "utf8"
c.on "connect", ->
c.setSecure credentials
return
c.on "secure", ->
verified = c.verifyPeer()
peerDN = JSON.stringify(c.getPeerCertificate())
assert.equal verified, true
assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}"
c.write "GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n"
requests_sent += 1
return
c.on "data", (chunk) ->
server_response += chunk
if requests_sent is 1
c.write "POST /quit HTTP/1.1\r\n\r\n"
requests_sent += 1
if requests_sent is 2
c.write "GET / HTTP/1.1\r\nX-X: foo\r\n\r\n" + "GET / HTTP/1.1\r\nX-X: bar\r\n\r\n"
c.end()
assert.equal c.readyState, "readOnly"
requests_sent += 2
return
c.on "end", ->
client_got_eof = true
return
c.on "close", ->
assert.equal c.readyState, "closed"
return
return
process.on "exit", ->
assert.equal 4, request_number
assert.equal 4, requests_sent
hello = new RegExp("/hello")
assert.equal true, hello.exec(server_response)?
quit = new RegExp("/quit")
assert.equal true, quit.exec(server_response)?
assert.equal true, client_got_eof
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
net = require("net")
http = require("http")
url = require("url")
qs = require("querystring")
fs = require("fs")
have_openssl = undefined
try
crypto = require("crypto")
dummy_server = http.createServer(->
)
dummy_server.setSecure()
have_openssl = true
catch e
have_openssl = false
console.log "Not compiled with OPENSSL support."
process.exit()
request_number = 0
requests_sent = 0
server_response = ""
client_got_eof = false
caPem = fs.readFileSync(common.fixturesDir + "/test_ca.pem", "ascii")
certPem = fs.readFileSync(common.fixturesDir + "/test_cert.pem", "ascii")
keyPem = fs.readFileSync(common.fixturesDir + "/test_key.pem", "ascii")
try
credentials = crypto.createCredentials(
key: keyPem
cert: certPem
ca: caPem
)
catch e
console.log "Not compiled with OPENSSL support."
process.exit()
https_server = http.createServer((req, res) ->
res.id = request_number
req.id = request_number++
verified = res.connection.verifyPeer()
peerDN = JSON.stringify(req.connection.getPeerCertificate())
assert.equal verified, true
assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}"
if req.id is 0
assert.equal "GET", req.method
assert.equal "/hello", url.parse(req.url).pathname
assert.equal "world", qs.parse(url.parse(req.url).query).hello
assert.equal "b==ar", qs.parse(url.parse(req.url).query).foo
if req.id is 1
assert.equal "POST", req.method
assert.equal "/quit", url.parse(req.url).pathname
assert.equal "foo", req.headers["x-x"] if req.id is 2
if req.id is 3
assert.equal "bar", req.headers["x-x"]
@close()
#console.log('server closed');
setTimeout (->
res.writeHead 200,
"Content-Type": "text/plain"
res.write url.parse(req.url).pathname
res.end()
return
), 1
return
)
https_server.setSecure credentials
https_server.listen common.PORT
https_server.on "listening", ->
c = net.createConnection(common.PORT)
c.setEncoding "utf8"
c.on "connect", ->
c.setSecure credentials
return
c.on "secure", ->
verified = c.verifyPeer()
peerDN = JSON.stringify(c.getPeerCertificate())
assert.equal verified, true
assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}"
c.write "GET /hello?hello=world&foo=b==ar HTTP/1.1\r\n\r\n"
requests_sent += 1
return
c.on "data", (chunk) ->
server_response += chunk
if requests_sent is 1
c.write "POST /quit HTTP/1.1\r\n\r\n"
requests_sent += 1
if requests_sent is 2
c.write "GET / HTTP/1.1\r\nX-X: foo\r\n\r\n" + "GET / HTTP/1.1\r\nX-X: bar\r\n\r\n"
c.end()
assert.equal c.readyState, "readOnly"
requests_sent += 2
return
c.on "end", ->
client_got_eof = true
return
c.on "close", ->
assert.equal c.readyState, "closed"
return
return
process.on "exit", ->
assert.equal 4, request_number
assert.equal 4, requests_sent
hello = new RegExp("/hello")
assert.equal true, hello.exec(server_response)?
quit = new RegExp("/quit")
assert.equal true, quit.exec(server_response)?
assert.equal true, client_got_eof
return
|
[
{
"context": "\r\n ],\r\n xkey: 'x'\r\n ykeys: ['y', 'z', 'a']\r\n labels: ['Y', 'Z', 'A']\r\n\r\n ",
"end": 4021,
"score": 0.9517794251441956,
"start": 4020,
"tag": "KEY",
"value": "y"
},
{
"context": " ],\r\n xkey: 'x'\r\n ykeys: ['y', 'z', 'a']\r\n labels: ['Y', 'Z', 'A']\r\n\r\n ",
"end": 4026,
"score": 0.9905243515968323,
"start": 4025,
"tag": "KEY",
"value": "z"
},
{
"context": "],\r\n xkey: 'x'\r\n ykeys: ['y', 'z', 'a']\r\n labels: ['Y', 'Z', 'A']\r\n\r\n it 's",
"end": 4031,
"score": 0.9910485148429871,
"start": 4030,
"tag": "KEY",
"value": "a"
}
] | src/main/webapp/resources/contents/lib/morris.js/spec/lib/bar/bar_spec.coffee | noor52/qa_board_repo | 0 | describe 'Morris.Bar', ->
describe 'when using vertical grid', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
barColors: ['#0b62a4', '#7a92a3']
gridLineColor: '#aaa'
gridStrokeWidth: 0.5
gridTextColor: '#888'
gridTextSize: 12
verticalGridCondition: (index) -> index % 2
verticalGridColor: '#888888'
verticalGridOpacity: '0.2'
describe 'svg structure', ->
it 'should contain extra rectangles for vertical grid', ->
$('#graph').css('height', '250px').css('width', '800px')
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect").size().should.equal 6
describe 'svg attributes', ->
it 'should have to bars with verticalGrid.color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[fill='#{defaults.verticalGridColor}']").size().should.equal 2
it 'should have to bars with verticalGrid.color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[fill-opacity='#{defaults.verticalGridOpacity}']").size().should.equal 2
describe 'svg structure', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
it 'should contain a rect for each bar', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect").size().should.equal 4
it 'should contain 5 grid lines', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("path").size().should.equal 5
it 'should contain 7 text elements', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("text").size().should.equal 7
describe 'svg attributes', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
barColors: ['#0b62a4', '#7a92a3']
gridLineColor: '#aaa'
gridStrokeWidth: 0.5
gridTextColor: '#888'
gridTextSize: 12
it 'should have a bar with the first default color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[fill='#0b62a4']").size().should.equal 2
it 'should have a bar with no stroke', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[stroke='none']").size().should.equal 4
it 'should have text with configured fill color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("text[fill='#888888']").size().should.equal 7
it 'should have text with configured font size', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("text[font-size='12px']").size().should.equal 7
describe 'when setting bar radius', ->
describe 'svg structure', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
barRadius: [5, 5, 0, 0]
it 'should contain a path for each bar', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("path").size().should.equal 9
it 'should use rects if radius is too big', ->
delete defaults.barStyle
chart = Morris.Bar $.extend {}, defaults,
barRadius: [300, 300, 0, 0]
$('#graph').find("rect").size().should.equal 4
describe 'barSize option', ->
describe 'svg attributes', ->
defaults =
element: 'graph'
barSize: 20
data: [
{x: '2011 Q1', y: 3, z: 2, a: 3}
{x: '2011 Q2', y: 2, z: null, a: 1}
{x: '2011 Q3', y: 0, z: 2, a: 4}
{x: '2011 Q4', y: 2, z: 4, a: 3}
],
xkey: 'x'
ykeys: ['y', 'z', 'a']
labels: ['Y', 'Z', 'A']
it 'should calc the width if too narrow for barSize', ->
$('#graph').width('200px')
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect").filter((i) ->
parseFloat($(@).attr('width'), 10) < 10
).size().should.equal 11
it 'should set width to @options.barSize if possible', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[width='#{defaults.barSize}']").size().should.equal 11
| 207001 | describe 'Morris.Bar', ->
describe 'when using vertical grid', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
barColors: ['#0b62a4', '#7a92a3']
gridLineColor: '#aaa'
gridStrokeWidth: 0.5
gridTextColor: '#888'
gridTextSize: 12
verticalGridCondition: (index) -> index % 2
verticalGridColor: '#888888'
verticalGridOpacity: '0.2'
describe 'svg structure', ->
it 'should contain extra rectangles for vertical grid', ->
$('#graph').css('height', '250px').css('width', '800px')
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect").size().should.equal 6
describe 'svg attributes', ->
it 'should have to bars with verticalGrid.color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[fill='#{defaults.verticalGridColor}']").size().should.equal 2
it 'should have to bars with verticalGrid.color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[fill-opacity='#{defaults.verticalGridOpacity}']").size().should.equal 2
describe 'svg structure', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
it 'should contain a rect for each bar', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect").size().should.equal 4
it 'should contain 5 grid lines', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("path").size().should.equal 5
it 'should contain 7 text elements', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("text").size().should.equal 7
describe 'svg attributes', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
barColors: ['#0b62a4', '#7a92a3']
gridLineColor: '#aaa'
gridStrokeWidth: 0.5
gridTextColor: '#888'
gridTextSize: 12
it 'should have a bar with the first default color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[fill='#0b62a4']").size().should.equal 2
it 'should have a bar with no stroke', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[stroke='none']").size().should.equal 4
it 'should have text with configured fill color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("text[fill='#888888']").size().should.equal 7
it 'should have text with configured font size', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("text[font-size='12px']").size().should.equal 7
describe 'when setting bar radius', ->
describe 'svg structure', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
barRadius: [5, 5, 0, 0]
it 'should contain a path for each bar', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("path").size().should.equal 9
it 'should use rects if radius is too big', ->
delete defaults.barStyle
chart = Morris.Bar $.extend {}, defaults,
barRadius: [300, 300, 0, 0]
$('#graph').find("rect").size().should.equal 4
describe 'barSize option', ->
describe 'svg attributes', ->
defaults =
element: 'graph'
barSize: 20
data: [
{x: '2011 Q1', y: 3, z: 2, a: 3}
{x: '2011 Q2', y: 2, z: null, a: 1}
{x: '2011 Q3', y: 0, z: 2, a: 4}
{x: '2011 Q4', y: 2, z: 4, a: 3}
],
xkey: 'x'
ykeys: ['<KEY>', '<KEY>', '<KEY>']
labels: ['Y', 'Z', 'A']
it 'should calc the width if too narrow for barSize', ->
$('#graph').width('200px')
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect").filter((i) ->
parseFloat($(@).attr('width'), 10) < 10
).size().should.equal 11
it 'should set width to @options.barSize if possible', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[width='#{defaults.barSize}']").size().should.equal 11
| true | describe 'Morris.Bar', ->
describe 'when using vertical grid', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
barColors: ['#0b62a4', '#7a92a3']
gridLineColor: '#aaa'
gridStrokeWidth: 0.5
gridTextColor: '#888'
gridTextSize: 12
verticalGridCondition: (index) -> index % 2
verticalGridColor: '#888888'
verticalGridOpacity: '0.2'
describe 'svg structure', ->
it 'should contain extra rectangles for vertical grid', ->
$('#graph').css('height', '250px').css('width', '800px')
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect").size().should.equal 6
describe 'svg attributes', ->
it 'should have to bars with verticalGrid.color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[fill='#{defaults.verticalGridColor}']").size().should.equal 2
it 'should have to bars with verticalGrid.color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[fill-opacity='#{defaults.verticalGridOpacity}']").size().should.equal 2
describe 'svg structure', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
it 'should contain a rect for each bar', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect").size().should.equal 4
it 'should contain 5 grid lines', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("path").size().should.equal 5
it 'should contain 7 text elements', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("text").size().should.equal 7
describe 'svg attributes', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
barColors: ['#0b62a4', '#7a92a3']
gridLineColor: '#aaa'
gridStrokeWidth: 0.5
gridTextColor: '#888'
gridTextSize: 12
it 'should have a bar with the first default color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[fill='#0b62a4']").size().should.equal 2
it 'should have a bar with no stroke', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[stroke='none']").size().should.equal 4
it 'should have text with configured fill color', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("text[fill='#888888']").size().should.equal 7
it 'should have text with configured font size', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("text[font-size='12px']").size().should.equal 7
describe 'when setting bar radius', ->
describe 'svg structure', ->
defaults =
element: 'graph'
data: [{x: 'foo', y: 2, z: 3}, {x: 'bar', y: 4, z: 6}]
xkey: 'x'
ykeys: ['y', 'z']
labels: ['Y', 'Z']
barRadius: [5, 5, 0, 0]
it 'should contain a path for each bar', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("path").size().should.equal 9
it 'should use rects if radius is too big', ->
delete defaults.barStyle
chart = Morris.Bar $.extend {}, defaults,
barRadius: [300, 300, 0, 0]
$('#graph').find("rect").size().should.equal 4
describe 'barSize option', ->
describe 'svg attributes', ->
defaults =
element: 'graph'
barSize: 20
data: [
{x: '2011 Q1', y: 3, z: 2, a: 3}
{x: '2011 Q2', y: 2, z: null, a: 1}
{x: '2011 Q3', y: 0, z: 2, a: 4}
{x: '2011 Q4', y: 2, z: 4, a: 3}
],
xkey: 'x'
ykeys: ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI']
labels: ['Y', 'Z', 'A']
it 'should calc the width if too narrow for barSize', ->
$('#graph').width('200px')
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect").filter((i) ->
parseFloat($(@).attr('width'), 10) < 10
).size().should.equal 11
it 'should set width to @options.barSize if possible', ->
chart = Morris.Bar $.extend {}, defaults
$('#graph').find("rect[width='#{defaults.barSize}']").size().should.equal 11
|
[
{
"context": "muestra nuestro código de conducta\n#\n# Author:\n# Francho\n\nhttps = require 'https'\n\nmodule.exports = (ro",
"end": 198,
"score": 0.637177586555481,
"start": 194,
"tag": "NAME",
"value": "Fran"
},
{
"context": "ra nuestro código de conducta\n#\n# Author:\n# Francho\n\nhttps = require 'https'\n\nmodule.exports = (robot",
"end": 201,
"score": 0.6644324660301208,
"start": 198,
"tag": "USERNAME",
"value": "cho"
},
{
"context": " rulesUrl = 'https://raw.githubusercontent.com/francho/zithub-slackin/master/code-of-conduct.md'\n htt",
"end": 357,
"score": 0.9991645812988281,
"start": 350,
"tag": "USERNAME",
"value": "francho"
}
] | scripts/zithub-code-of-conduct.coffee | francho/agilico | 1 | # Description:
# Show zithub code of conduct
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot nuestro código - muestra nuestro código de conducta
#
# Author:
# Francho
https = require 'https'
module.exports = (robot) ->
robot.respond /nuestro c.digo/i, (msg) ->
rulesUrl = 'https://raw.githubusercontent.com/francho/zithub-slackin/master/code-of-conduct.md'
https.get rulesUrl, (res) ->
data = ''
res.on 'data', (chunk) ->
data += chunk.toString()
res.on 'end', () ->
msg.reply data
| 115467 | # Description:
# Show zithub code of conduct
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot nuestro código - muestra nuestro código de conducta
#
# Author:
# <NAME>cho
https = require 'https'
module.exports = (robot) ->
robot.respond /nuestro c.digo/i, (msg) ->
rulesUrl = 'https://raw.githubusercontent.com/francho/zithub-slackin/master/code-of-conduct.md'
https.get rulesUrl, (res) ->
data = ''
res.on 'data', (chunk) ->
data += chunk.toString()
res.on 'end', () ->
msg.reply data
| true | # Description:
# Show zithub code of conduct
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot nuestro código - muestra nuestro código de conducta
#
# Author:
# PI:NAME:<NAME>END_PIcho
https = require 'https'
module.exports = (robot) ->
robot.respond /nuestro c.digo/i, (msg) ->
rulesUrl = 'https://raw.githubusercontent.com/francho/zithub-slackin/master/code-of-conduct.md'
https.get rulesUrl, (res) ->
data = ''
res.on 'data', (chunk) ->
data += chunk.toString()
res.on 'end', () ->
msg.reply data
|
[
{
"context": "###\n\t(c) 2016 Julian Gonggrijp\n###\n\n'use strict'\n\nmodule.exports = (grunt) ->\n\t\n",
"end": 30,
"score": 0.9998762011528015,
"start": 14,
"tag": "NAME",
"value": "Julian Gonggrijp"
}
] | Gruntfile.coffee | NBOCampbellToets/CampbellSoup | 0 | ###
(c) 2016 Julian Gonggrijp
###
'use strict'
module.exports = (grunt) ->
if grunt.option 'production'
require('load-grunt-tasks') grunt, scope: 'dependencies'
else
jasmineTemplate = require 'grunt-template-jasmine-requirejs'
require('load-grunt-tasks') grunt
stripRegExp = (path, ext) -> new RegExp "^#{path}/|\\.#{ext}$", 'g'
fs = require 'fs'
grunt.initConfig
pypackage: 'campbellsoup'
source: 'client'
script: 'script'
style: 'style'
template: 'template'
templateSrc: '<%= source %>/<%= template %>'
functional: 'functional-tests'
stage: '.tmp'
dist: 'dist'
clean:
develop: ['<%= stage %>/index.html']
dist: ['<%= dist %>/index.html']
all: [
'<%= stage %>'
'<%= dist %>'
'.<%= functional %>'
'.*cache'
'**/__pycache__'
'**/*.{pyc,pyo}'
]
handlebars:
options:
amd: true
processName: (path) ->
src = grunt.config('templateSrc')
pattern = stripRegExp src, 'mustache'
path.replace pattern, ''
compilerOptions:
knownHelpers: {}
knownHelpersOnly: true
compat: true
compile:
src: [
'<%= source %>/<%= template %>/**/*.mustache'
'!<%= source %>/<%= template %>/index.mustache'
]
dest: '<%= stage %>/<%= script %>/templates.js'
coffee:
options:
bare: true
compile:
expand: true
cwd: '<%= source %>/<%= script %>'
src: ['**/*.coffee']
dest: '<%= stage %>/<%= script %>/'
ext: '.js'
functional:
expand: true
cwd: '<%= functional %>'
src: ['**/*.coffee']
dest: '.<%= functional %>/'
ext: '.js'
'compile-handlebars':
develop:
src: '<%= source %>/<%= template %>/index.mustache'
dest: '<%= stage %>/index.html'
partials: '<%= stage %>/<%= script %>/*.js'
templateData:
production: false
dist:
src: '<%= source %>/<%= template %>/index.mustache'
dest: '<%= dist %>/index.html'
partials: '<%= stage %>/<%= script %>/*.js'
templateData:
production: true
sass:
compile:
options:
includePaths: [
'node_modules'
]
sourceComments: true
expand: true
cwd: '<%= source %>/<%= style %>'
src: ['*.sass', '*.scss']
dest: '<%= stage %>/<%= style %>'
ext: '.css.pre'
postcss:
compile:
options:
processors: [
(require 'autoprefixer') {
browsers: [
'Android 2.3'
'Android >= 4'
'Chrome >= 20'
'Firefox >= 24'
'Explorer >= 8'
'iOS >= 6'
'Opera >= 12'
'Safari >= 6'
]
}
]
expand: true
cwd: '<%= stage %>/<%= style %>'
src: ['*.css.pre']
dest: '<%= stage %>/<%= style %>'
ext: '.css'
symlink:
compile:
expand: true
src: [
'bower_components'
]
dest: '<%= stage %>'
shell:
backend:
command: (filename) ->
filename ?= 'config.py'
"$VIRTUAL_ENV/bin/python manage.py -c ../#{filename} runserver -rd"
pytest:
files: [{
src: ['campbellsoup/**/*_test.py']
}]
command: ->
files = (o.src for o in grunt.config 'shell.pytest.files')
src = [].concat.apply([], files)
paths = (grunt.file.expand src).join ' '
"py.test #{paths}"
jasmine:
test:
options:
specs: '<%= stage %>/<%= script %>/**/*_test.js'
helpers: [
'bower_components/jquery/dist/jquery.js'
'bower_components/jasmine-jquery/lib/jasmine-jquery.js'
]
# host: 'http://localhost:8000/'
template: jasmineTemplate
templateOptions:
requireConfigFile: '<%= stage %>/<%= script %>/developConfig.js'
requireConfig:
baseUrl: '<%= script %>'
outfile: '<%= stage %>/_SpecRunner.html'
display: 'short'
summary: true
casperjs:
options:
silent: true
functional:
src: ['.<%= functional %>/**/*.js']
watch:
handlebars:
files: '<%= handlebars.compile.src %>'
tasks: 'handlebars:compile'
scripts:
files: '<%= coffee.compile.src %>'
options:
cwd:
files: '<%= coffee.compile.cwd %>'
tasks: ['newer:coffee:compile', 'jasmine:test']
sass:
files: '<%= sass.compile.src %>'
options:
cwd:
files: '<%= sass.compile.cwd %>'
tasks: ['sass:compile', 'postcss:compile']
html:
files: [
'<%= grunt.config("compile-handlebars.develop.src") %>'
'<%= stage %>/<%= script %>/developConfig.js'
]
tasks: ['clean:develop', 'compile-handlebars:develop']
python:
files: '<%= pypackage %>/**/*.py'
tasks: 'newer:shell:pytest'
functional:
files: '<%= coffee.functional.src %>'
options:
cwd:
files: '<%= coffee.functional.cwd %>'
tasks: ['newer:coffee:functional', 'newer:casperjs:functional']
config:
files: 'Gruntfile.coffee'
livereload:
files: [
'<%= script %>/**/*.js'
'<%= style %>/*.css'
'*.html'
'!_SpecRunner.html'
]
options:
cwd:
files: '<%= stage %>'
livereload: true
requirejs:
dist:
options:
baseUrl: '<%= stage %>/<%= script %>'
mainConfigFile: '<%= stage %>/<%= script %>/developConfig.js'
wrapShim: true
paths:
jquery: 'empty:'
backbone: 'empty:'
underscore: 'empty:'
'handlebars.runtime': 'empty:'
include: ['main.js']
out: '<%= dist %>/campbellsoup.js'
cssmin:
dist:
src: ['<%= stage %>/<%= style %>/*.css']
dest: '<%= dist %>/campbellsoup.css'
concurrent:
preserver:
tasks: ['shell:pytest', 'compile']
develop:
tasks: [
['concurrent:preserver', 'server']
['watch']
]
options:
logConcurrentOutput: true
newer:
options:
override: (info, include) ->
if info.task == 'shell' and info.target == 'pytest'
source = info.path.replace /_test\.py$/, '.py'
fs.stat source, (error, stats) ->
if stats.mtime.getTime() > info.time.getTime()
include yes
else
include no
else
include no
grunt.registerTask 'compile-base', [
'handlebars:compile'
'newer:coffee:compile'
'sass:compile'
'postcss:compile'
'symlink:compile'
]
grunt.registerTask 'compile', [
'compile-base'
'clean:develop'
'compile-handlebars:develop'
]
grunt.registerTask 'dist', [
'compile-base'
'clean:dist'
'compile-handlebars:dist'
'requirejs:dist'
'cssmin:dist'
]
grunt.registerTask 'server', ['shell:backend']
grunt.registerTask 'default', ['concurrent:develop']
| 35122 | ###
(c) 2016 <NAME>
###
'use strict'
module.exports = (grunt) ->
if grunt.option 'production'
require('load-grunt-tasks') grunt, scope: 'dependencies'
else
jasmineTemplate = require 'grunt-template-jasmine-requirejs'
require('load-grunt-tasks') grunt
stripRegExp = (path, ext) -> new RegExp "^#{path}/|\\.#{ext}$", 'g'
fs = require 'fs'
grunt.initConfig
pypackage: 'campbellsoup'
source: 'client'
script: 'script'
style: 'style'
template: 'template'
templateSrc: '<%= source %>/<%= template %>'
functional: 'functional-tests'
stage: '.tmp'
dist: 'dist'
clean:
develop: ['<%= stage %>/index.html']
dist: ['<%= dist %>/index.html']
all: [
'<%= stage %>'
'<%= dist %>'
'.<%= functional %>'
'.*cache'
'**/__pycache__'
'**/*.{pyc,pyo}'
]
handlebars:
options:
amd: true
processName: (path) ->
src = grunt.config('templateSrc')
pattern = stripRegExp src, 'mustache'
path.replace pattern, ''
compilerOptions:
knownHelpers: {}
knownHelpersOnly: true
compat: true
compile:
src: [
'<%= source %>/<%= template %>/**/*.mustache'
'!<%= source %>/<%= template %>/index.mustache'
]
dest: '<%= stage %>/<%= script %>/templates.js'
coffee:
options:
bare: true
compile:
expand: true
cwd: '<%= source %>/<%= script %>'
src: ['**/*.coffee']
dest: '<%= stage %>/<%= script %>/'
ext: '.js'
functional:
expand: true
cwd: '<%= functional %>'
src: ['**/*.coffee']
dest: '.<%= functional %>/'
ext: '.js'
'compile-handlebars':
develop:
src: '<%= source %>/<%= template %>/index.mustache'
dest: '<%= stage %>/index.html'
partials: '<%= stage %>/<%= script %>/*.js'
templateData:
production: false
dist:
src: '<%= source %>/<%= template %>/index.mustache'
dest: '<%= dist %>/index.html'
partials: '<%= stage %>/<%= script %>/*.js'
templateData:
production: true
sass:
compile:
options:
includePaths: [
'node_modules'
]
sourceComments: true
expand: true
cwd: '<%= source %>/<%= style %>'
src: ['*.sass', '*.scss']
dest: '<%= stage %>/<%= style %>'
ext: '.css.pre'
postcss:
compile:
options:
processors: [
(require 'autoprefixer') {
browsers: [
'Android 2.3'
'Android >= 4'
'Chrome >= 20'
'Firefox >= 24'
'Explorer >= 8'
'iOS >= 6'
'Opera >= 12'
'Safari >= 6'
]
}
]
expand: true
cwd: '<%= stage %>/<%= style %>'
src: ['*.css.pre']
dest: '<%= stage %>/<%= style %>'
ext: '.css'
symlink:
compile:
expand: true
src: [
'bower_components'
]
dest: '<%= stage %>'
shell:
backend:
command: (filename) ->
filename ?= 'config.py'
"$VIRTUAL_ENV/bin/python manage.py -c ../#{filename} runserver -rd"
pytest:
files: [{
src: ['campbellsoup/**/*_test.py']
}]
command: ->
files = (o.src for o in grunt.config 'shell.pytest.files')
src = [].concat.apply([], files)
paths = (grunt.file.expand src).join ' '
"py.test #{paths}"
jasmine:
test:
options:
specs: '<%= stage %>/<%= script %>/**/*_test.js'
helpers: [
'bower_components/jquery/dist/jquery.js'
'bower_components/jasmine-jquery/lib/jasmine-jquery.js'
]
# host: 'http://localhost:8000/'
template: jasmineTemplate
templateOptions:
requireConfigFile: '<%= stage %>/<%= script %>/developConfig.js'
requireConfig:
baseUrl: '<%= script %>'
outfile: '<%= stage %>/_SpecRunner.html'
display: 'short'
summary: true
casperjs:
options:
silent: true
functional:
src: ['.<%= functional %>/**/*.js']
watch:
handlebars:
files: '<%= handlebars.compile.src %>'
tasks: 'handlebars:compile'
scripts:
files: '<%= coffee.compile.src %>'
options:
cwd:
files: '<%= coffee.compile.cwd %>'
tasks: ['newer:coffee:compile', 'jasmine:test']
sass:
files: '<%= sass.compile.src %>'
options:
cwd:
files: '<%= sass.compile.cwd %>'
tasks: ['sass:compile', 'postcss:compile']
html:
files: [
'<%= grunt.config("compile-handlebars.develop.src") %>'
'<%= stage %>/<%= script %>/developConfig.js'
]
tasks: ['clean:develop', 'compile-handlebars:develop']
python:
files: '<%= pypackage %>/**/*.py'
tasks: 'newer:shell:pytest'
functional:
files: '<%= coffee.functional.src %>'
options:
cwd:
files: '<%= coffee.functional.cwd %>'
tasks: ['newer:coffee:functional', 'newer:casperjs:functional']
config:
files: 'Gruntfile.coffee'
livereload:
files: [
'<%= script %>/**/*.js'
'<%= style %>/*.css'
'*.html'
'!_SpecRunner.html'
]
options:
cwd:
files: '<%= stage %>'
livereload: true
requirejs:
dist:
options:
baseUrl: '<%= stage %>/<%= script %>'
mainConfigFile: '<%= stage %>/<%= script %>/developConfig.js'
wrapShim: true
paths:
jquery: 'empty:'
backbone: 'empty:'
underscore: 'empty:'
'handlebars.runtime': 'empty:'
include: ['main.js']
out: '<%= dist %>/campbellsoup.js'
cssmin:
dist:
src: ['<%= stage %>/<%= style %>/*.css']
dest: '<%= dist %>/campbellsoup.css'
concurrent:
preserver:
tasks: ['shell:pytest', 'compile']
develop:
tasks: [
['concurrent:preserver', 'server']
['watch']
]
options:
logConcurrentOutput: true
newer:
options:
override: (info, include) ->
if info.task == 'shell' and info.target == 'pytest'
source = info.path.replace /_test\.py$/, '.py'
fs.stat source, (error, stats) ->
if stats.mtime.getTime() > info.time.getTime()
include yes
else
include no
else
include no
grunt.registerTask 'compile-base', [
'handlebars:compile'
'newer:coffee:compile'
'sass:compile'
'postcss:compile'
'symlink:compile'
]
grunt.registerTask 'compile', [
'compile-base'
'clean:develop'
'compile-handlebars:develop'
]
grunt.registerTask 'dist', [
'compile-base'
'clean:dist'
'compile-handlebars:dist'
'requirejs:dist'
'cssmin:dist'
]
grunt.registerTask 'server', ['shell:backend']
grunt.registerTask 'default', ['concurrent:develop']
| true | ###
(c) 2016 PI:NAME:<NAME>END_PI
###
'use strict'
module.exports = (grunt) ->
if grunt.option 'production'
require('load-grunt-tasks') grunt, scope: 'dependencies'
else
jasmineTemplate = require 'grunt-template-jasmine-requirejs'
require('load-grunt-tasks') grunt
stripRegExp = (path, ext) -> new RegExp "^#{path}/|\\.#{ext}$", 'g'
fs = require 'fs'
grunt.initConfig
pypackage: 'campbellsoup'
source: 'client'
script: 'script'
style: 'style'
template: 'template'
templateSrc: '<%= source %>/<%= template %>'
functional: 'functional-tests'
stage: '.tmp'
dist: 'dist'
clean:
develop: ['<%= stage %>/index.html']
dist: ['<%= dist %>/index.html']
all: [
'<%= stage %>'
'<%= dist %>'
'.<%= functional %>'
'.*cache'
'**/__pycache__'
'**/*.{pyc,pyo}'
]
handlebars:
options:
amd: true
processName: (path) ->
src = grunt.config('templateSrc')
pattern = stripRegExp src, 'mustache'
path.replace pattern, ''
compilerOptions:
knownHelpers: {}
knownHelpersOnly: true
compat: true
compile:
src: [
'<%= source %>/<%= template %>/**/*.mustache'
'!<%= source %>/<%= template %>/index.mustache'
]
dest: '<%= stage %>/<%= script %>/templates.js'
coffee:
options:
bare: true
compile:
expand: true
cwd: '<%= source %>/<%= script %>'
src: ['**/*.coffee']
dest: '<%= stage %>/<%= script %>/'
ext: '.js'
functional:
expand: true
cwd: '<%= functional %>'
src: ['**/*.coffee']
dest: '.<%= functional %>/'
ext: '.js'
'compile-handlebars':
develop:
src: '<%= source %>/<%= template %>/index.mustache'
dest: '<%= stage %>/index.html'
partials: '<%= stage %>/<%= script %>/*.js'
templateData:
production: false
dist:
src: '<%= source %>/<%= template %>/index.mustache'
dest: '<%= dist %>/index.html'
partials: '<%= stage %>/<%= script %>/*.js'
templateData:
production: true
sass:
compile:
options:
includePaths: [
'node_modules'
]
sourceComments: true
expand: true
cwd: '<%= source %>/<%= style %>'
src: ['*.sass', '*.scss']
dest: '<%= stage %>/<%= style %>'
ext: '.css.pre'
postcss:
compile:
options:
processors: [
(require 'autoprefixer') {
browsers: [
'Android 2.3'
'Android >= 4'
'Chrome >= 20'
'Firefox >= 24'
'Explorer >= 8'
'iOS >= 6'
'Opera >= 12'
'Safari >= 6'
]
}
]
expand: true
cwd: '<%= stage %>/<%= style %>'
src: ['*.css.pre']
dest: '<%= stage %>/<%= style %>'
ext: '.css'
symlink:
compile:
expand: true
src: [
'bower_components'
]
dest: '<%= stage %>'
shell:
backend:
command: (filename) ->
filename ?= 'config.py'
"$VIRTUAL_ENV/bin/python manage.py -c ../#{filename} runserver -rd"
pytest:
files: [{
src: ['campbellsoup/**/*_test.py']
}]
command: ->
files = (o.src for o in grunt.config 'shell.pytest.files')
src = [].concat.apply([], files)
paths = (grunt.file.expand src).join ' '
"py.test #{paths}"
jasmine:
test:
options:
specs: '<%= stage %>/<%= script %>/**/*_test.js'
helpers: [
'bower_components/jquery/dist/jquery.js'
'bower_components/jasmine-jquery/lib/jasmine-jquery.js'
]
# host: 'http://localhost:8000/'
template: jasmineTemplate
templateOptions:
requireConfigFile: '<%= stage %>/<%= script %>/developConfig.js'
requireConfig:
baseUrl: '<%= script %>'
outfile: '<%= stage %>/_SpecRunner.html'
display: 'short'
summary: true
casperjs:
options:
silent: true
functional:
src: ['.<%= functional %>/**/*.js']
watch:
handlebars:
files: '<%= handlebars.compile.src %>'
tasks: 'handlebars:compile'
scripts:
files: '<%= coffee.compile.src %>'
options:
cwd:
files: '<%= coffee.compile.cwd %>'
tasks: ['newer:coffee:compile', 'jasmine:test']
sass:
files: '<%= sass.compile.src %>'
options:
cwd:
files: '<%= sass.compile.cwd %>'
tasks: ['sass:compile', 'postcss:compile']
html:
files: [
'<%= grunt.config("compile-handlebars.develop.src") %>'
'<%= stage %>/<%= script %>/developConfig.js'
]
tasks: ['clean:develop', 'compile-handlebars:develop']
python:
files: '<%= pypackage %>/**/*.py'
tasks: 'newer:shell:pytest'
functional:
files: '<%= coffee.functional.src %>'
options:
cwd:
files: '<%= coffee.functional.cwd %>'
tasks: ['newer:coffee:functional', 'newer:casperjs:functional']
config:
files: 'Gruntfile.coffee'
livereload:
files: [
'<%= script %>/**/*.js'
'<%= style %>/*.css'
'*.html'
'!_SpecRunner.html'
]
options:
cwd:
files: '<%= stage %>'
livereload: true
requirejs:
dist:
options:
baseUrl: '<%= stage %>/<%= script %>'
mainConfigFile: '<%= stage %>/<%= script %>/developConfig.js'
wrapShim: true
paths:
jquery: 'empty:'
backbone: 'empty:'
underscore: 'empty:'
'handlebars.runtime': 'empty:'
include: ['main.js']
out: '<%= dist %>/campbellsoup.js'
cssmin:
dist:
src: ['<%= stage %>/<%= style %>/*.css']
dest: '<%= dist %>/campbellsoup.css'
concurrent:
preserver:
tasks: ['shell:pytest', 'compile']
develop:
tasks: [
['concurrent:preserver', 'server']
['watch']
]
options:
logConcurrentOutput: true
newer:
options:
override: (info, include) ->
if info.task == 'shell' and info.target == 'pytest'
source = info.path.replace /_test\.py$/, '.py'
fs.stat source, (error, stats) ->
if stats.mtime.getTime() > info.time.getTime()
include yes
else
include no
else
include no
grunt.registerTask 'compile-base', [
'handlebars:compile'
'newer:coffee:compile'
'sass:compile'
'postcss:compile'
'symlink:compile'
]
grunt.registerTask 'compile', [
'compile-base'
'clean:develop'
'compile-handlebars:develop'
]
grunt.registerTask 'dist', [
'compile-base'
'clean:dist'
'compile-handlebars:dist'
'requirejs:dist'
'cssmin:dist'
]
grunt.registerTask 'server', ['shell:backend']
grunt.registerTask 'default', ['concurrent:develop']
|
[
{
"context": "03/\", =>\n @browser.document.innerHTML = \"Wolf\"\n @browser.window.addEventListener \"hash",
"end": 8481,
"score": 0.6539329290390015,
"start": 8477,
"tag": "NAME",
"value": "Wolf"
},
{
"context": ">\n @browser.window.document.innerHTML = \"Wolf\"\n @browser.reload()\n @browser.o",
"end": 10217,
"score": 0.9711356163024902,
"start": 10213,
"tag": "NAME",
"value": "Wolf"
}
] | test/history_test.coffee | krasimir/zombie | 1 | { assert, brains, Browser } = require("./helpers")
JSDOM = require("jsdom")
URL = require("url")
describe "History", ->
file_url = "file://#{__dirname}/data/index.html"
before (done)->
brains.get "/history/boo/", (req, res)->
response = if req.query.redirected then "Redirected" else "Eeek!"
res.send "<html><title>#{response}</title></html>"
brains.get "/history/boo", (req, res)->
res.redirect URL.format(pathname: "/history/boo/", query: req.query)
brains.get "/history/redirect", (req, res)->
res.redirect "/history/boo?redirected=true"
brains.get "/history/redirect_back", (req, res)->
res.redirect req.headers["referer"]
brains.get "/history/referer", (req, res)->
res.send "<html><title>#{req.headers["referer"]}</title></html>"
brains.ready done
describe "URL without path", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003", done
it "should resolve URL", ->
assert.equal @browser.location.href, "http://localhost:3003/"
it "should load page", ->
assert.equal @browser.text("title"), "Tap, Tap"
describe "new window", ->
before ->
@window = new Browser().window
it "should start out with one location", ->
assert.equal @window.history.length, 1
assert.equal @window.location.href, "about:blank"
describe "go forward", ->
before ->
@window.history.forward()
it "should have no effect", ->
assert.equal @window.history.length, 1
assert.equal @window.location.href, "about:blank"
describe "go backwards", ->
before ->
@window.history.back()
it "should have no effect", ->
assert.equal @window.history.length, 1
assert.equal @window.location.href, "about:blank"
describe "history", ->
describe "pushState", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
browser.history.pushState { is: "start" }, null, "/start"
browser.history.pushState { is: "end" }, null, "/end"
@window = browser.window
done()
it "should add state to history", ->
assert.equal @window.history.length, 3
it "should change location URL", ->
assert.equal @window.location.href, "http://localhost:3003/end"
describe "go backwards", ->
before (done)->
@window.document.magic = 123
@window.addEventListener "popstate", (@event)=>
done()
@window.history.back()
it "should fire popstate event", ->
assert @event instanceof JSDOM.dom.level3.events.Event
it "should include state", ->
assert.equal @event.state.is, "start"
it "should not reload page from same host", ->
# Get access to the *current* document
document = @event.target.window.browser.document
assert.equal document.magic, 123
describe "go forwards", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
browser.history.pushState { is: "start" }, null, "/start"
browser.history.pushState { is: "end" }, null, "/end"
browser.back()
browser.window.addEventListener "popstate", (@event)=>
done()
browser.history.forward()
it "should fire popstate event", ->
assert @event instanceof JSDOM.dom.level3.events.Event
it "should include state", ->
assert.equal @event.state.is, "end"
describe "replaceState", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
browser.history.pushState { is: "start" }, null, "/start"
browser.history.replaceState { is: "end" }, null, "/end"
@window = browser.window
done()
it "should not add state to history", ->
assert.equal @window.history.length, 2
it "should change location URL", ->
assert.equal @window.location.href, "http://localhost:3003/end"
describe "go backwards", ->
before (done)->
@window.addEventListener "popstate", (evt)=>
@window.popstate = true
@window.history.back()
done()
it "should change location URL", ->
assert.equal @window.location.href, "http://localhost:3003/"
it "should not fire popstate event", ->
assert.equal @window.popstate, undefined
describe "redirect", ->
browser = new Browser()
before (done)->
browser.visit "http://localhost:3003/history/redirect", done
it "should redirect to final destination", ->
assert.equal browser.location, "http://localhost:3003/history/boo/?redirected=true"
it "should pass query parameter", ->
assert.equal browser.text("title"), "Redirected"
it "should not add location in history", ->
assert.equal browser.history.length, 1
it "should indicate last request followed a redirect", ->
assert browser.redirected
describe "redirect back", ->
browser = new Browser()
before (done)->
browser.visit "http://localhost:3003/history/boo", ->
browser.visit "http://localhost:3003/history/redirect_back", ->
done()
it "should redirect to the previous path", ->
assert.equal browser.location.href, "http://localhost:3003/history/boo/"
it "should pass query parameter", ->
assert /Eeek!/.test(browser.text("title"))
it "should not add location in history", ->
assert.equal browser.history.length, 2
it "should indicate last request followed a redirect", ->
assert browser.redirected
describe "location", ->
describe "open page", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", done
it "should add page to history", ->
assert.equal @browser.history.length, 1
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/"
it "should load document", ->
assert /Tap, Tap/.test(@browser.html())
it "should set window location", ->
assert.equal @browser.window.location.href, "http://localhost:3003/"
it "should set document location", ->
assert.equal @browser.document.location.href, "http://localhost:3003/"
describe "open from file system", ->
before (done)->
@browser = new Browser()
@browser.visit file_url, done
it "should add page to history", ->
assert.equal @browser.history.length, 1
it "should change location URL", ->
assert.equal @browser.location.href, file_url
it "should load document", ->
assert ~@browser.html("title").indexOf("Insanely fast, headless full-stack testing using Node.js")
it "should set window location", ->
assert.equal @browser.window.location.href, file_url
it "should set document location", ->
assert.equal @browser.document.location.href, file_url
describe "change pathname", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.pathname = "/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "change relative href", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.href = "/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "change hash", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.document.innerHTML = "Wolf"
@browser.window.addEventListener "hashchange", ->
done()
@browser.window.location.hash = "boo"
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/#boo"
it "should not reload document", ->
assert /Wolf/.test(@browser.document.innerHTML)
describe "assign", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.assign "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "replace", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.replace "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should not add page to history", ->
assert.equal @browser.history.length, 1
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "reload", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.document.innerHTML = "Wolf"
@browser.reload()
@browser.on "loaded", ->
done()
it "should not add page to history", ->
assert.equal @browser.history.length, 1
it "should not change location URL", ->
assert.equal @browser.location, "http://localhost:3003/"
it "should reload document", ->
assert /Tap, Tap/.test(@browser.html())
describe "components", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
@location = browser.location
done()
it "should include protocol", ->
assert.equal @location.protocol, "http:"
it "should include hostname", ->
assert.equal @location.hostname, "localhost"
it "should include port", ->
assert.equal @location.port, 3003
it "should include hostname and port", ->
assert.equal @location.host, "localhost:3003"
it "should include pathname", ->
assert.equal @location.pathname, "/"
it "should include search", ->
assert.equal @location.search, ""
it "should include hash", ->
assert.equal @location.hash, ""
describe "set window.location", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location = "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "set document.location", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.document.location = "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "referer not set", ->
describe "first page", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/history/referer", done
it "should be empty", ->
assert.equal @browser.text("title"), "undefined"
describe "second page", ->
before (done)->
@browser.visit "http://localhost:3003/history/referer", done
it "should point to first page", ->
assert.equal @browser.text("title"), "http://localhost:3003/history/referer"
describe "referer set", ->
describe "first page", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/history/referer", referer: "http://braindepot", done
it "should be empty", ->
assert.equal @browser.text("title"), "http://braindepot"
describe "second page", ->
before (done)->
@browser.visit "http://localhost:3003/history/referer", done
it "should point to first page", ->
assert.equal @browser.text("title"), "http://localhost:3003/history/referer"
describe "URL with hash", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003#with-hash", done
it "should load page", ->
assert.equal @browser.text("title"), "Tap, Tap"
it "should set location to hash", ->
assert.equal @browser.location.hash, "#with-hash"
| 90762 | { assert, brains, Browser } = require("./helpers")
JSDOM = require("jsdom")
URL = require("url")
describe "History", ->
file_url = "file://#{__dirname}/data/index.html"
before (done)->
brains.get "/history/boo/", (req, res)->
response = if req.query.redirected then "Redirected" else "Eeek!"
res.send "<html><title>#{response}</title></html>"
brains.get "/history/boo", (req, res)->
res.redirect URL.format(pathname: "/history/boo/", query: req.query)
brains.get "/history/redirect", (req, res)->
res.redirect "/history/boo?redirected=true"
brains.get "/history/redirect_back", (req, res)->
res.redirect req.headers["referer"]
brains.get "/history/referer", (req, res)->
res.send "<html><title>#{req.headers["referer"]}</title></html>"
brains.ready done
describe "URL without path", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003", done
it "should resolve URL", ->
assert.equal @browser.location.href, "http://localhost:3003/"
it "should load page", ->
assert.equal @browser.text("title"), "Tap, Tap"
describe "new window", ->
before ->
@window = new Browser().window
it "should start out with one location", ->
assert.equal @window.history.length, 1
assert.equal @window.location.href, "about:blank"
describe "go forward", ->
before ->
@window.history.forward()
it "should have no effect", ->
assert.equal @window.history.length, 1
assert.equal @window.location.href, "about:blank"
describe "go backwards", ->
before ->
@window.history.back()
it "should have no effect", ->
assert.equal @window.history.length, 1
assert.equal @window.location.href, "about:blank"
describe "history", ->
describe "pushState", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
browser.history.pushState { is: "start" }, null, "/start"
browser.history.pushState { is: "end" }, null, "/end"
@window = browser.window
done()
it "should add state to history", ->
assert.equal @window.history.length, 3
it "should change location URL", ->
assert.equal @window.location.href, "http://localhost:3003/end"
describe "go backwards", ->
before (done)->
@window.document.magic = 123
@window.addEventListener "popstate", (@event)=>
done()
@window.history.back()
it "should fire popstate event", ->
assert @event instanceof JSDOM.dom.level3.events.Event
it "should include state", ->
assert.equal @event.state.is, "start"
it "should not reload page from same host", ->
# Get access to the *current* document
document = @event.target.window.browser.document
assert.equal document.magic, 123
describe "go forwards", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
browser.history.pushState { is: "start" }, null, "/start"
browser.history.pushState { is: "end" }, null, "/end"
browser.back()
browser.window.addEventListener "popstate", (@event)=>
done()
browser.history.forward()
it "should fire popstate event", ->
assert @event instanceof JSDOM.dom.level3.events.Event
it "should include state", ->
assert.equal @event.state.is, "end"
describe "replaceState", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
browser.history.pushState { is: "start" }, null, "/start"
browser.history.replaceState { is: "end" }, null, "/end"
@window = browser.window
done()
it "should not add state to history", ->
assert.equal @window.history.length, 2
it "should change location URL", ->
assert.equal @window.location.href, "http://localhost:3003/end"
describe "go backwards", ->
before (done)->
@window.addEventListener "popstate", (evt)=>
@window.popstate = true
@window.history.back()
done()
it "should change location URL", ->
assert.equal @window.location.href, "http://localhost:3003/"
it "should not fire popstate event", ->
assert.equal @window.popstate, undefined
describe "redirect", ->
browser = new Browser()
before (done)->
browser.visit "http://localhost:3003/history/redirect", done
it "should redirect to final destination", ->
assert.equal browser.location, "http://localhost:3003/history/boo/?redirected=true"
it "should pass query parameter", ->
assert.equal browser.text("title"), "Redirected"
it "should not add location in history", ->
assert.equal browser.history.length, 1
it "should indicate last request followed a redirect", ->
assert browser.redirected
describe "redirect back", ->
browser = new Browser()
before (done)->
browser.visit "http://localhost:3003/history/boo", ->
browser.visit "http://localhost:3003/history/redirect_back", ->
done()
it "should redirect to the previous path", ->
assert.equal browser.location.href, "http://localhost:3003/history/boo/"
it "should pass query parameter", ->
assert /Eeek!/.test(browser.text("title"))
it "should not add location in history", ->
assert.equal browser.history.length, 2
it "should indicate last request followed a redirect", ->
assert browser.redirected
describe "location", ->
describe "open page", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", done
it "should add page to history", ->
assert.equal @browser.history.length, 1
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/"
it "should load document", ->
assert /Tap, Tap/.test(@browser.html())
it "should set window location", ->
assert.equal @browser.window.location.href, "http://localhost:3003/"
it "should set document location", ->
assert.equal @browser.document.location.href, "http://localhost:3003/"
describe "open from file system", ->
before (done)->
@browser = new Browser()
@browser.visit file_url, done
it "should add page to history", ->
assert.equal @browser.history.length, 1
it "should change location URL", ->
assert.equal @browser.location.href, file_url
it "should load document", ->
assert ~@browser.html("title").indexOf("Insanely fast, headless full-stack testing using Node.js")
it "should set window location", ->
assert.equal @browser.window.location.href, file_url
it "should set document location", ->
assert.equal @browser.document.location.href, file_url
describe "change pathname", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.pathname = "/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "change relative href", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.href = "/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "change hash", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.document.innerHTML = "<NAME>"
@browser.window.addEventListener "hashchange", ->
done()
@browser.window.location.hash = "boo"
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/#boo"
it "should not reload document", ->
assert /Wolf/.test(@browser.document.innerHTML)
describe "assign", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.assign "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "replace", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.replace "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should not add page to history", ->
assert.equal @browser.history.length, 1
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "reload", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.document.innerHTML = "<NAME>"
@browser.reload()
@browser.on "loaded", ->
done()
it "should not add page to history", ->
assert.equal @browser.history.length, 1
it "should not change location URL", ->
assert.equal @browser.location, "http://localhost:3003/"
it "should reload document", ->
assert /Tap, Tap/.test(@browser.html())
describe "components", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
@location = browser.location
done()
it "should include protocol", ->
assert.equal @location.protocol, "http:"
it "should include hostname", ->
assert.equal @location.hostname, "localhost"
it "should include port", ->
assert.equal @location.port, 3003
it "should include hostname and port", ->
assert.equal @location.host, "localhost:3003"
it "should include pathname", ->
assert.equal @location.pathname, "/"
it "should include search", ->
assert.equal @location.search, ""
it "should include hash", ->
assert.equal @location.hash, ""
describe "set window.location", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location = "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "set document.location", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.document.location = "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "referer not set", ->
describe "first page", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/history/referer", done
it "should be empty", ->
assert.equal @browser.text("title"), "undefined"
describe "second page", ->
before (done)->
@browser.visit "http://localhost:3003/history/referer", done
it "should point to first page", ->
assert.equal @browser.text("title"), "http://localhost:3003/history/referer"
describe "referer set", ->
describe "first page", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/history/referer", referer: "http://braindepot", done
it "should be empty", ->
assert.equal @browser.text("title"), "http://braindepot"
describe "second page", ->
before (done)->
@browser.visit "http://localhost:3003/history/referer", done
it "should point to first page", ->
assert.equal @browser.text("title"), "http://localhost:3003/history/referer"
describe "URL with hash", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003#with-hash", done
it "should load page", ->
assert.equal @browser.text("title"), "Tap, Tap"
it "should set location to hash", ->
assert.equal @browser.location.hash, "#with-hash"
| true | { assert, brains, Browser } = require("./helpers")
JSDOM = require("jsdom")
URL = require("url")
describe "History", ->
file_url = "file://#{__dirname}/data/index.html"
before (done)->
brains.get "/history/boo/", (req, res)->
response = if req.query.redirected then "Redirected" else "Eeek!"
res.send "<html><title>#{response}</title></html>"
brains.get "/history/boo", (req, res)->
res.redirect URL.format(pathname: "/history/boo/", query: req.query)
brains.get "/history/redirect", (req, res)->
res.redirect "/history/boo?redirected=true"
brains.get "/history/redirect_back", (req, res)->
res.redirect req.headers["referer"]
brains.get "/history/referer", (req, res)->
res.send "<html><title>#{req.headers["referer"]}</title></html>"
brains.ready done
describe "URL without path", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003", done
it "should resolve URL", ->
assert.equal @browser.location.href, "http://localhost:3003/"
it "should load page", ->
assert.equal @browser.text("title"), "Tap, Tap"
describe "new window", ->
before ->
@window = new Browser().window
it "should start out with one location", ->
assert.equal @window.history.length, 1
assert.equal @window.location.href, "about:blank"
describe "go forward", ->
before ->
@window.history.forward()
it "should have no effect", ->
assert.equal @window.history.length, 1
assert.equal @window.location.href, "about:blank"
describe "go backwards", ->
before ->
@window.history.back()
it "should have no effect", ->
assert.equal @window.history.length, 1
assert.equal @window.location.href, "about:blank"
describe "history", ->
describe "pushState", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
browser.history.pushState { is: "start" }, null, "/start"
browser.history.pushState { is: "end" }, null, "/end"
@window = browser.window
done()
it "should add state to history", ->
assert.equal @window.history.length, 3
it "should change location URL", ->
assert.equal @window.location.href, "http://localhost:3003/end"
describe "go backwards", ->
before (done)->
@window.document.magic = 123
@window.addEventListener "popstate", (@event)=>
done()
@window.history.back()
it "should fire popstate event", ->
assert @event instanceof JSDOM.dom.level3.events.Event
it "should include state", ->
assert.equal @event.state.is, "start"
it "should not reload page from same host", ->
# Get access to the *current* document
document = @event.target.window.browser.document
assert.equal document.magic, 123
describe "go forwards", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
browser.history.pushState { is: "start" }, null, "/start"
browser.history.pushState { is: "end" }, null, "/end"
browser.back()
browser.window.addEventListener "popstate", (@event)=>
done()
browser.history.forward()
it "should fire popstate event", ->
assert @event instanceof JSDOM.dom.level3.events.Event
it "should include state", ->
assert.equal @event.state.is, "end"
describe "replaceState", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
browser.history.pushState { is: "start" }, null, "/start"
browser.history.replaceState { is: "end" }, null, "/end"
@window = browser.window
done()
it "should not add state to history", ->
assert.equal @window.history.length, 2
it "should change location URL", ->
assert.equal @window.location.href, "http://localhost:3003/end"
describe "go backwards", ->
before (done)->
@window.addEventListener "popstate", (evt)=>
@window.popstate = true
@window.history.back()
done()
it "should change location URL", ->
assert.equal @window.location.href, "http://localhost:3003/"
it "should not fire popstate event", ->
assert.equal @window.popstate, undefined
describe "redirect", ->
browser = new Browser()
before (done)->
browser.visit "http://localhost:3003/history/redirect", done
it "should redirect to final destination", ->
assert.equal browser.location, "http://localhost:3003/history/boo/?redirected=true"
it "should pass query parameter", ->
assert.equal browser.text("title"), "Redirected"
it "should not add location in history", ->
assert.equal browser.history.length, 1
it "should indicate last request followed a redirect", ->
assert browser.redirected
describe "redirect back", ->
browser = new Browser()
before (done)->
browser.visit "http://localhost:3003/history/boo", ->
browser.visit "http://localhost:3003/history/redirect_back", ->
done()
it "should redirect to the previous path", ->
assert.equal browser.location.href, "http://localhost:3003/history/boo/"
it "should pass query parameter", ->
assert /Eeek!/.test(browser.text("title"))
it "should not add location in history", ->
assert.equal browser.history.length, 2
it "should indicate last request followed a redirect", ->
assert browser.redirected
describe "location", ->
describe "open page", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", done
it "should add page to history", ->
assert.equal @browser.history.length, 1
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/"
it "should load document", ->
assert /Tap, Tap/.test(@browser.html())
it "should set window location", ->
assert.equal @browser.window.location.href, "http://localhost:3003/"
it "should set document location", ->
assert.equal @browser.document.location.href, "http://localhost:3003/"
describe "open from file system", ->
before (done)->
@browser = new Browser()
@browser.visit file_url, done
it "should add page to history", ->
assert.equal @browser.history.length, 1
it "should change location URL", ->
assert.equal @browser.location.href, file_url
it "should load document", ->
assert ~@browser.html("title").indexOf("Insanely fast, headless full-stack testing using Node.js")
it "should set window location", ->
assert.equal @browser.window.location.href, file_url
it "should set document location", ->
assert.equal @browser.document.location.href, file_url
describe "change pathname", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.pathname = "/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "change relative href", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.href = "/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "change hash", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.document.innerHTML = "PI:NAME:<NAME>END_PI"
@browser.window.addEventListener "hashchange", ->
done()
@browser.window.location.hash = "boo"
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/#boo"
it "should not reload document", ->
assert /Wolf/.test(@browser.document.innerHTML)
describe "assign", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.assign "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "replace", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location.replace "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should not add page to history", ->
assert.equal @browser.history.length, 1
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "reload", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.document.innerHTML = "PI:NAME:<NAME>END_PI"
@browser.reload()
@browser.on "loaded", ->
done()
it "should not add page to history", ->
assert.equal @browser.history.length, 1
it "should not change location URL", ->
assert.equal @browser.location, "http://localhost:3003/"
it "should reload document", ->
assert /Tap, Tap/.test(@browser.html())
describe "components", ->
before (done)->
browser = new Browser()
browser.visit "http://localhost:3003/", =>
@location = browser.location
done()
it "should include protocol", ->
assert.equal @location.protocol, "http:"
it "should include hostname", ->
assert.equal @location.hostname, "localhost"
it "should include port", ->
assert.equal @location.port, 3003
it "should include hostname and port", ->
assert.equal @location.host, "localhost:3003"
it "should include pathname", ->
assert.equal @location.pathname, "/"
it "should include search", ->
assert.equal @location.search, ""
it "should include hash", ->
assert.equal @location.hash, ""
describe "set window.location", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.location = "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "set document.location", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/", =>
@browser.window.document.location = "http://localhost:3003/history/boo"
@browser.on "loaded", ->
done()
it "should add page to history", ->
assert.equal @browser.history.length, 2
it "should change location URL", ->
assert.equal @browser.location, "http://localhost:3003/history/boo/"
it "should load document", ->
assert /Eeek!/.test(@browser.html())
describe "referer not set", ->
describe "first page", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/history/referer", done
it "should be empty", ->
assert.equal @browser.text("title"), "undefined"
describe "second page", ->
before (done)->
@browser.visit "http://localhost:3003/history/referer", done
it "should point to first page", ->
assert.equal @browser.text("title"), "http://localhost:3003/history/referer"
describe "referer set", ->
describe "first page", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003/history/referer", referer: "http://braindepot", done
it "should be empty", ->
assert.equal @browser.text("title"), "http://braindepot"
describe "second page", ->
before (done)->
@browser.visit "http://localhost:3003/history/referer", done
it "should point to first page", ->
assert.equal @browser.text("title"), "http://localhost:3003/history/referer"
describe "URL with hash", ->
before (done)->
@browser = new Browser()
@browser.visit "http://localhost:3003#with-hash", done
it "should load page", ->
assert.equal @browser.text("title"), "Tap, Tap"
it "should set location to hash", ->
assert.equal @browser.location.hash, "#with-hash"
|
[
{
"context": " (request, response, next) =>\n {email,password,firstName,lastName} = request.body\n return response.stat",
"end": 412,
"score": 0.5220289826393127,
"start": 403,
"tag": "NAME",
"value": "firstName"
},
{
"context": "\n\n request.email = email\n request.password = password\n request.deviceQuery = query\n request.first",
"end": 767,
"score": 0.9989916682243347,
"start": 759,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "equest.deviceQuery = query\n request.firstName = firstName\n request.lastName = lastName\n\n next()\n\n cr",
"end": 833,
"score": 0.8238706588745117,
"start": 824,
"tag": "NAME",
"value": "firstName"
},
{
"context": "t, response) =>\n {deviceQuery, email, password, firstName, lastName} = request\n debug 'device query', de",
"end": 956,
"score": 0.8378489017486572,
"start": 947,
"tag": "NAME",
"value": "firstName"
},
{
"context": " profile:\n image: ''\n firstName: firstName\n lastName: lastName\n user_id: email",
"end": 1214,
"score": 0.9657711386680603,
"start": 1205,
"tag": "NAME",
"value": "firstName"
},
{
"context": " firstName: firstName\n lastName: lastName\n user_id: email\n secret: password\n ,",
"end": 1243,
"score": 0.8220816850662231,
"start": 1235,
"tag": "NAME",
"value": "lastName"
}
] | app/controllers/device-controller.coffee | iotrentil/rentil-authenticator-email-password | 0 | debug = require('debug')('meshblu-authenticator-email-password:device-controller')
_ = require 'lodash'
validator = require 'validator'
url = require 'url'
request = require 'request'
class DeviceController
constructor: ({@meshbluHttp, @deviceModel, @forwarderUrl}) ->
throw new Error('forwarderUrl is required') unless @forwarderUrl?
prepare: (request, response, next) =>
{email,password,firstName,lastName} = request.body
return response.status(422).send 'Password required' if _.isEmpty(password)
return response.status(422).send 'Invalid email' unless validator.isEmail(email)
query = {}
email = email.toLowerCase()
query[@deviceModel.authenticatorUuid + '.id'] = email
request.email = email
request.password = password
request.deviceQuery = query
request.firstName = firstName
request.lastName = lastName
next()
create: (request, response) =>
{deviceQuery, email, password, firstName, lastName} = request
debug 'device query', deviceQuery
@deviceModel.create
query: deviceQuery
data:
type: 'account:user'
id: email
lastLogin: ''
profile:
image: ''
firstName: firstName
lastName: lastName
user_id: email
secret: password
, @reply(request.body.callbackUrl, response)
update: (request, response) =>
{deviceQuery, email, password} = request
{uuid} = request.body
debug 'device query', deviceQuery
return response.status(422).send 'Uuid required' if _.isEmpty(uuid)
@deviceModel.addAuth
query: deviceQuery
uuid: uuid
user_id: email
secret: password
, @reply(request.body.callbackUrl, response)
reply: (callbackUrl, response) =>
(error, device) =>
if error?
debug 'got an error', error.message
if error.message == 'device already exists'
return response.status(401).json error: "Unable to create user"
if error.message == @ERROR_DEVICE_NOT_FOUND
return response.status(401).json error: "Unable to find user"
return response.status(500).json error: error.message
@meshbluHttp.generateAndStoreToken device.uuid, (error, device) =>
options =
method: 'POST'
url: "#{@forwarderUrl}/devices"
headers:
'cache-control': 'no-cache'
meshblu_auth_uuid: device.uuid
meshblu_auth_token: device.token
'content-type': 'application/json'
body:
forwarderConfig:
disabled: false
type: 'account:user'
json: true
debug 'Request to create forwarder:account :' + JSON.stringify options
request options, (error, resp, body) =>
return response.status(500).json error: error.message if error?
return response.status(201).send(device: device) unless callbackUrl?
uriParams = url.parse callbackUrl, true
delete uriParams.search
uriParams.query ?= {}
uriParams.query.uuid = device.uuid
uriParams.query.token = device.token
uri = decodeURIComponent url.format(uriParams)
response.status(201).location(uri).send(device: device, callbackUrl: uri)
module.exports = DeviceController
| 220513 | debug = require('debug')('meshblu-authenticator-email-password:device-controller')
_ = require 'lodash'
validator = require 'validator'
url = require 'url'
request = require 'request'
class DeviceController
constructor: ({@meshbluHttp, @deviceModel, @forwarderUrl}) ->
throw new Error('forwarderUrl is required') unless @forwarderUrl?
prepare: (request, response, next) =>
{email,password,<NAME>,lastName} = request.body
return response.status(422).send 'Password required' if _.isEmpty(password)
return response.status(422).send 'Invalid email' unless validator.isEmail(email)
query = {}
email = email.toLowerCase()
query[@deviceModel.authenticatorUuid + '.id'] = email
request.email = email
request.password = <PASSWORD>
request.deviceQuery = query
request.firstName = <NAME>
request.lastName = lastName
next()
create: (request, response) =>
{deviceQuery, email, password, <NAME>, lastName} = request
debug 'device query', deviceQuery
@deviceModel.create
query: deviceQuery
data:
type: 'account:user'
id: email
lastLogin: ''
profile:
image: ''
firstName: <NAME>
lastName: <NAME>
user_id: email
secret: password
, @reply(request.body.callbackUrl, response)
update: (request, response) =>
{deviceQuery, email, password} = request
{uuid} = request.body
debug 'device query', deviceQuery
return response.status(422).send 'Uuid required' if _.isEmpty(uuid)
@deviceModel.addAuth
query: deviceQuery
uuid: uuid
user_id: email
secret: password
, @reply(request.body.callbackUrl, response)
reply: (callbackUrl, response) =>
(error, device) =>
if error?
debug 'got an error', error.message
if error.message == 'device already exists'
return response.status(401).json error: "Unable to create user"
if error.message == @ERROR_DEVICE_NOT_FOUND
return response.status(401).json error: "Unable to find user"
return response.status(500).json error: error.message
@meshbluHttp.generateAndStoreToken device.uuid, (error, device) =>
options =
method: 'POST'
url: "#{@forwarderUrl}/devices"
headers:
'cache-control': 'no-cache'
meshblu_auth_uuid: device.uuid
meshblu_auth_token: device.token
'content-type': 'application/json'
body:
forwarderConfig:
disabled: false
type: 'account:user'
json: true
debug 'Request to create forwarder:account :' + JSON.stringify options
request options, (error, resp, body) =>
return response.status(500).json error: error.message if error?
return response.status(201).send(device: device) unless callbackUrl?
uriParams = url.parse callbackUrl, true
delete uriParams.search
uriParams.query ?= {}
uriParams.query.uuid = device.uuid
uriParams.query.token = device.token
uri = decodeURIComponent url.format(uriParams)
response.status(201).location(uri).send(device: device, callbackUrl: uri)
module.exports = DeviceController
| true | debug = require('debug')('meshblu-authenticator-email-password:device-controller')
_ = require 'lodash'
validator = require 'validator'
url = require 'url'
request = require 'request'
class DeviceController
constructor: ({@meshbluHttp, @deviceModel, @forwarderUrl}) ->
throw new Error('forwarderUrl is required') unless @forwarderUrl?
prepare: (request, response, next) =>
{email,password,PI:NAME:<NAME>END_PI,lastName} = request.body
return response.status(422).send 'Password required' if _.isEmpty(password)
return response.status(422).send 'Invalid email' unless validator.isEmail(email)
query = {}
email = email.toLowerCase()
query[@deviceModel.authenticatorUuid + '.id'] = email
request.email = email
request.password = PI:PASSWORD:<PASSWORD>END_PI
request.deviceQuery = query
request.firstName = PI:NAME:<NAME>END_PI
request.lastName = lastName
next()
create: (request, response) =>
{deviceQuery, email, password, PI:NAME:<NAME>END_PI, lastName} = request
debug 'device query', deviceQuery
@deviceModel.create
query: deviceQuery
data:
type: 'account:user'
id: email
lastLogin: ''
profile:
image: ''
firstName: PI:NAME:<NAME>END_PI
lastName: PI:NAME:<NAME>END_PI
user_id: email
secret: password
, @reply(request.body.callbackUrl, response)
update: (request, response) =>
{deviceQuery, email, password} = request
{uuid} = request.body
debug 'device query', deviceQuery
return response.status(422).send 'Uuid required' if _.isEmpty(uuid)
@deviceModel.addAuth
query: deviceQuery
uuid: uuid
user_id: email
secret: password
, @reply(request.body.callbackUrl, response)
reply: (callbackUrl, response) =>
(error, device) =>
if error?
debug 'got an error', error.message
if error.message == 'device already exists'
return response.status(401).json error: "Unable to create user"
if error.message == @ERROR_DEVICE_NOT_FOUND
return response.status(401).json error: "Unable to find user"
return response.status(500).json error: error.message
@meshbluHttp.generateAndStoreToken device.uuid, (error, device) =>
options =
method: 'POST'
url: "#{@forwarderUrl}/devices"
headers:
'cache-control': 'no-cache'
meshblu_auth_uuid: device.uuid
meshblu_auth_token: device.token
'content-type': 'application/json'
body:
forwarderConfig:
disabled: false
type: 'account:user'
json: true
debug 'Request to create forwarder:account :' + JSON.stringify options
request options, (error, resp, body) =>
return response.status(500).json error: error.message if error?
return response.status(201).send(device: device) unless callbackUrl?
uriParams = url.parse callbackUrl, true
delete uriParams.search
uriParams.query ?= {}
uriParams.query.uuid = device.uuid
uriParams.query.token = device.token
uri = decodeURIComponent url.format(uriParams)
response.status(201).location(uri).send(device: device, callbackUrl: uri)
module.exports = DeviceController
|
[
{
"context": "# MIT License:\n#\n# Copyright (c) 2010-2012, Joe Walnes\n#\n# Permission is hereby granted, free of charge,",
"end": 54,
"score": 0.9998564720153809,
"start": 44,
"tag": "NAME",
"value": "Joe Walnes"
},
{
"context": "/joewalnes/reconnecting-websocket/\nContributors:\n- Joe Walnes\n- Didier Colens\n- Wout Mertens\n###\nclass Reconnec",
"end": 1723,
"score": 0.9998742938041687,
"start": 1713,
"tag": "NAME",
"value": "Joe Walnes"
},
{
"context": "connecting-websocket/\nContributors:\n- Joe Walnes\n- Didier Colens\n- Wout Mertens\n###\nclass ReconnectingWebSocket\n ",
"end": 1739,
"score": 0.9998691082000732,
"start": 1726,
"tag": "NAME",
"value": "Didier Colens"
},
{
"context": "cket/\nContributors:\n- Joe Walnes\n- Didier Colens\n- Wout Mertens\n###\nclass ReconnectingWebSocket\n constructor: (u",
"end": 1754,
"score": 0.9998645782470703,
"start": 1742,
"tag": "NAME",
"value": "Wout Mertens"
}
] | node_modules/share/src/client/reconnecting_websocket.coffee | abraarsyed/workshare | 2 | # MIT License:
#
# Copyright (c) 2010-2012, Joe Walnes
#
# 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.
###
This behaves like a WebSocket in every way, except if it fails to connect,
or it gets disconnected, it will repeatedly poll until it succesfully connects
again.
It is API compatible, so when you have:
ws = new WebSocket('ws://....');
you can replace with:
ws = new ReconnectingWebSocket('ws://....');
The event stream will typically look like:
onopen
onmessage
onmessage
onclose // lost connection
onopen // sometime later...
onmessage
onmessage
etc...
It is API compatible with the standard WebSocket API.
Inspired from: https://github.com/joewalnes/reconnecting-websocket/
Contributors:
- Joe Walnes
- Didier Colens
- Wout Mertens
###
class ReconnectingWebSocket
constructor: (url, protocols, Socket) ->
if protocols? and typeof protocols is 'function'
Socket = protocols
protocols = undefined
else if typeof Socket isnt 'function'
Socket = WebSocket
# These can be altered by calling code.
@debug = @debugAll
@reconnectInterval = 1000
@timeoutInterval = 2000
@forcedClose = false
@url = url
@protocols = protocols
@readyState = Socket.CONNECTING
@URL = url # Public API
timedOut = false
connect = (reconnectAttempt) =>
@ws = new Socket(@url)
console.debug "ReconnectingWebSocket", "attempt-connect", @url if @debug
timeout = setTimeout(=>
console.debug "ReconnectingWebSocket", "connection-timeout", @url if @debug
timedOut = true
@ws.close()
timedOut = false
, @timeoutInterval)
@ws.onopen = (event) =>
clearTimeout timeout
console.debug "ReconnectingWebSocket", "onopen", @url if @debug
@readyState = Socket.OPEN
reconnectAttempt = false
@onopen event
@ws.onclose = (event) =>
clearTimeout timeout
@ws = null
if @forcedClose
@readyState = Socket.CLOSED
@onclose event
else
@readyState = Socket.CONNECTING
@onconnecting event
if not reconnectAttempt and not timedOut
console.debug "ReconnectingWebSocket", "onclose", @url if @debug
@onclose event
setTimeout (-> connect true ), @reconnectInterval
@ws.onmessage = (event) =>
console.debug "ReconnectingWebSocket", "onmessage", @url, event.data if @debug
@onmessage event
@ws.onerror = (event) =>
console.debug "ReconnectingWebSocket", "onerror", @url, event if @debug
@onerror event
connect @url
onopen: (event) ->
onclose: (event) ->
onconnecting: (event) ->
onmessage: (event) ->
onerror: (event) ->
send: (data) ->
if @ws
console.debug "ReconnectingWebSocket", "send", @url, data if @debug
@ws.send data
else
throw "INVALID_STATE_ERR : Pausing to reconnect websocket"
close: ->
if @ws
@forcedClose = true
@ws.close()
###
Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true.
###
debugAll: false
###
Additional public API method to refresh the connection if still open (close, re-open).
For example, if the app suspects bad data / missed heart beats, it can try to refresh.
###
refresh: ->
@ws.close() if @ws
| 192982 | # MIT License:
#
# Copyright (c) 2010-2012, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
###
This behaves like a WebSocket in every way, except if it fails to connect,
or it gets disconnected, it will repeatedly poll until it succesfully connects
again.
It is API compatible, so when you have:
ws = new WebSocket('ws://....');
you can replace with:
ws = new ReconnectingWebSocket('ws://....');
The event stream will typically look like:
onopen
onmessage
onmessage
onclose // lost connection
onopen // sometime later...
onmessage
onmessage
etc...
It is API compatible with the standard WebSocket API.
Inspired from: https://github.com/joewalnes/reconnecting-websocket/
Contributors:
- <NAME>
- <NAME>
- <NAME>
###
class ReconnectingWebSocket
constructor: (url, protocols, Socket) ->
if protocols? and typeof protocols is 'function'
Socket = protocols
protocols = undefined
else if typeof Socket isnt 'function'
Socket = WebSocket
# These can be altered by calling code.
@debug = @debugAll
@reconnectInterval = 1000
@timeoutInterval = 2000
@forcedClose = false
@url = url
@protocols = protocols
@readyState = Socket.CONNECTING
@URL = url # Public API
timedOut = false
connect = (reconnectAttempt) =>
@ws = new Socket(@url)
console.debug "ReconnectingWebSocket", "attempt-connect", @url if @debug
timeout = setTimeout(=>
console.debug "ReconnectingWebSocket", "connection-timeout", @url if @debug
timedOut = true
@ws.close()
timedOut = false
, @timeoutInterval)
@ws.onopen = (event) =>
clearTimeout timeout
console.debug "ReconnectingWebSocket", "onopen", @url if @debug
@readyState = Socket.OPEN
reconnectAttempt = false
@onopen event
@ws.onclose = (event) =>
clearTimeout timeout
@ws = null
if @forcedClose
@readyState = Socket.CLOSED
@onclose event
else
@readyState = Socket.CONNECTING
@onconnecting event
if not reconnectAttempt and not timedOut
console.debug "ReconnectingWebSocket", "onclose", @url if @debug
@onclose event
setTimeout (-> connect true ), @reconnectInterval
@ws.onmessage = (event) =>
console.debug "ReconnectingWebSocket", "onmessage", @url, event.data if @debug
@onmessage event
@ws.onerror = (event) =>
console.debug "ReconnectingWebSocket", "onerror", @url, event if @debug
@onerror event
connect @url
onopen: (event) ->
onclose: (event) ->
onconnecting: (event) ->
onmessage: (event) ->
onerror: (event) ->
send: (data) ->
if @ws
console.debug "ReconnectingWebSocket", "send", @url, data if @debug
@ws.send data
else
throw "INVALID_STATE_ERR : Pausing to reconnect websocket"
close: ->
if @ws
@forcedClose = true
@ws.close()
###
Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true.
###
debugAll: false
###
Additional public API method to refresh the connection if still open (close, re-open).
For example, if the app suspects bad data / missed heart beats, it can try to refresh.
###
refresh: ->
@ws.close() if @ws
| true | # MIT License:
#
# Copyright (c) 2010-2012, PI:NAME:<NAME>END_PI
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
###
This behaves like a WebSocket in every way, except if it fails to connect,
or it gets disconnected, it will repeatedly poll until it succesfully connects
again.
It is API compatible, so when you have:
ws = new WebSocket('ws://....');
you can replace with:
ws = new ReconnectingWebSocket('ws://....');
The event stream will typically look like:
onopen
onmessage
onmessage
onclose // lost connection
onopen // sometime later...
onmessage
onmessage
etc...
It is API compatible with the standard WebSocket API.
Inspired from: https://github.com/joewalnes/reconnecting-websocket/
Contributors:
- PI:NAME:<NAME>END_PI
- PI:NAME:<NAME>END_PI
- PI:NAME:<NAME>END_PI
###
class ReconnectingWebSocket
constructor: (url, protocols, Socket) ->
if protocols? and typeof protocols is 'function'
Socket = protocols
protocols = undefined
else if typeof Socket isnt 'function'
Socket = WebSocket
# These can be altered by calling code.
@debug = @debugAll
@reconnectInterval = 1000
@timeoutInterval = 2000
@forcedClose = false
@url = url
@protocols = protocols
@readyState = Socket.CONNECTING
@URL = url # Public API
timedOut = false
connect = (reconnectAttempt) =>
@ws = new Socket(@url)
console.debug "ReconnectingWebSocket", "attempt-connect", @url if @debug
timeout = setTimeout(=>
console.debug "ReconnectingWebSocket", "connection-timeout", @url if @debug
timedOut = true
@ws.close()
timedOut = false
, @timeoutInterval)
@ws.onopen = (event) =>
clearTimeout timeout
console.debug "ReconnectingWebSocket", "onopen", @url if @debug
@readyState = Socket.OPEN
reconnectAttempt = false
@onopen event
@ws.onclose = (event) =>
clearTimeout timeout
@ws = null
if @forcedClose
@readyState = Socket.CLOSED
@onclose event
else
@readyState = Socket.CONNECTING
@onconnecting event
if not reconnectAttempt and not timedOut
console.debug "ReconnectingWebSocket", "onclose", @url if @debug
@onclose event
setTimeout (-> connect true ), @reconnectInterval
@ws.onmessage = (event) =>
console.debug "ReconnectingWebSocket", "onmessage", @url, event.data if @debug
@onmessage event
@ws.onerror = (event) =>
console.debug "ReconnectingWebSocket", "onerror", @url, event if @debug
@onerror event
connect @url
onopen: (event) ->
onclose: (event) ->
onconnecting: (event) ->
onmessage: (event) ->
onerror: (event) ->
send: (data) ->
if @ws
console.debug "ReconnectingWebSocket", "send", @url, data if @debug
@ws.send data
else
throw "INVALID_STATE_ERR : Pausing to reconnect websocket"
close: ->
if @ws
@forcedClose = true
@ws.close()
###
Setting this to true is the equivalent of setting all instances of ReconnectingWebSocket.debug to true.
###
debugAll: false
###
Additional public API method to refresh the connection if still open (close, re-open).
For example, if the app suspects bad data / missed heart beats, it can try to refresh.
###
refresh: ->
@ws.close() if @ws
|
[
{
"context": "s\" : {\n \"def\" : [ {\n \"name\" : \"Patient\",\n \"context\" : \"Patient\",\n ",
"end": 2876,
"score": 0.9986213445663452,
"start": 2869,
"tag": "NAME",
"value": "Patient"
},
{
"context": " }\n }, {\n \"name\" : \"Age\",\n \"context\" : \"Patient\",\n ",
"end": 3250,
"score": 0.9959523677825928,
"start": 3247,
"tag": "NAME",
"value": "Age"
},
{
"context": " \"source\" : {\n \"name\" : \"Patient\",\n \"type\" : \"ExpressionRef\"\n ",
"end": 3613,
"score": 0.6842243075370789,
"start": 3606,
"tag": "NAME",
"value": "Patient"
},
{
"context": " }\n }, {\n \"name\" : \"InDemographic\",\n \"context\" : \"Patient\",\n ",
"end": 3968,
"score": 0.839896023273468,
"start": 3955,
"tag": "NAME",
"value": "InDemographic"
},
{
"context": "\"source\" : {\n \"name\" : \"Patient\",\n \"type\" : \"Expression",
"end": 4514,
"score": 0.8997697234153748,
"start": 4507,
"tag": "NAME",
"value": "Patient"
},
{
"context": "\"source\" : {\n \"name\" : \"Patient\",\n \"type\" : \"Expression",
"end": 5442,
"score": 0.9305360913276672,
"start": 5435,
"tag": "NAME",
"value": "Patient"
},
{
"context": " }\n }, {\n \"name\" : \"AgeSum\",\n \"context\" : \"Population\",\n ",
"end": 6057,
"score": 0.7802680730819702,
"start": 6051,
"tag": "NAME",
"value": "AgeSum"
},
{
"context": " }\n }, {\n \"name\" : \"DEMO\",\n \"context\" : \"Population\",\n ",
"end": 6372,
"score": 0.9468306303024292,
"start": 6368,
"tag": "NAME",
"value": "DEMO"
}
] | Src/coffeescript/cql-execution/test/elm/executor/data.coffee | MeasureAuthoringTool/clinical_quality_language | 2 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### Age
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define Age:
AgeInYearsAt(start of MeasurementPeriod)
define InDemographic:
AgeInYearsAt(start of MeasurementPeriod) >= 2 and AgeInYearsAt(start of MeasurementPeriod) < 18
context Population
define AgeSum: Sum(Age)
define DEMO: Count(InDemographic w where w is true )
define AgeSumRef : AgeSum
###
module.exports['Age'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "Age",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}
}, {
"name" : "InDemographic",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "GreaterOrEqual",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}, {
"type" : "Less",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "Patient",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "18",
"type" : "Literal"
} ]
} ]
}
}, {
"name" : "AgeSum",
"context" : "Population",
"accessLevel" : "Public",
"expression" : {
"type" : "Sum",
"source" : {
"name" : "Age",
"type" : "ExpressionRef"
}
}
}, {
"name" : "DEMO",
"context" : "Population",
"accessLevel" : "Public",
"expression" : {
"type" : "Count",
"source" : {
"type" : "Query",
"source" : [ {
"alias" : "w",
"expression" : {
"name" : "InDemographic",
"type" : "ExpressionRef"
}
} ],
"relationship" : [ ],
"where" : {
"type" : "IsTrue",
"operand" : {
"name" : "w",
"type" : "AliasRef"
}
}
}
}
}, {
"name" : "AgeSumRef",
"context" : "Population",
"accessLevel" : "Public",
"expression" : {
"name" : "AgeSum",
"type" : "ExpressionRef"
}
} ]
}
}
}
| 73589 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### Age
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define Age:
AgeInYearsAt(start of MeasurementPeriod)
define InDemographic:
AgeInYearsAt(start of MeasurementPeriod) >= 2 and AgeInYearsAt(start of MeasurementPeriod) < 18
context Population
define AgeSum: Sum(Age)
define DEMO: Count(InDemographic w where w is true )
define AgeSumRef : AgeSum
###
module.exports['Age'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "<NAME>",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}
}, {
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "GreaterOrEqual",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "<NAME>",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}, {
"type" : "Less",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "<NAME>",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "18",
"type" : "Literal"
} ]
} ]
}
}, {
"name" : "<NAME>",
"context" : "Population",
"accessLevel" : "Public",
"expression" : {
"type" : "Sum",
"source" : {
"name" : "Age",
"type" : "ExpressionRef"
}
}
}, {
"name" : "<NAME>",
"context" : "Population",
"accessLevel" : "Public",
"expression" : {
"type" : "Count",
"source" : {
"type" : "Query",
"source" : [ {
"alias" : "w",
"expression" : {
"name" : "InDemographic",
"type" : "ExpressionRef"
}
} ],
"relationship" : [ ],
"where" : {
"type" : "IsTrue",
"operand" : {
"name" : "w",
"type" : "AliasRef"
}
}
}
}
}, {
"name" : "AgeSumRef",
"context" : "Population",
"accessLevel" : "Public",
"expression" : {
"name" : "AgeSum",
"type" : "ExpressionRef"
}
} ]
}
}
}
| true | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.coffee to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### Age
library TestSnippet version '1'
using QUICK
parameter MeasurementPeriod default Interval[DateTime(2013, 1, 1), DateTime(2014, 1, 1))
context Patient
define Age:
AgeInYearsAt(start of MeasurementPeriod)
define InDemographic:
AgeInYearsAt(start of MeasurementPeriod) >= 2 and AgeInYearsAt(start of MeasurementPeriod) < 18
context Population
define AgeSum: Sum(Age)
define DEMO: Count(InDemographic w where w is true )
define AgeSumRef : AgeSum
###
module.exports['Age'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"name" : "MeasurementPeriod",
"accessLevel" : "Public",
"default" : {
"lowClosed" : true,
"highClosed" : false,
"type" : "Interval",
"low" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2014",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"expression" : {
"type" : "And",
"operand" : [ {
"type" : "GreaterOrEqual",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
} ]
}, {
"type" : "Less",
"operand" : [ {
"precision" : "Year",
"type" : "CalculateAgeAt",
"operand" : [ {
"path" : "birthDate",
"type" : "Property",
"source" : {
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ExpressionRef"
}
}, {
"type" : "Start",
"operand" : {
"name" : "MeasurementPeriod",
"type" : "ParameterRef"
}
} ]
}, {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "18",
"type" : "Literal"
} ]
} ]
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Population",
"accessLevel" : "Public",
"expression" : {
"type" : "Sum",
"source" : {
"name" : "Age",
"type" : "ExpressionRef"
}
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Population",
"accessLevel" : "Public",
"expression" : {
"type" : "Count",
"source" : {
"type" : "Query",
"source" : [ {
"alias" : "w",
"expression" : {
"name" : "InDemographic",
"type" : "ExpressionRef"
}
} ],
"relationship" : [ ],
"where" : {
"type" : "IsTrue",
"operand" : {
"name" : "w",
"type" : "AliasRef"
}
}
}
}
}, {
"name" : "AgeSumRef",
"context" : "Population",
"accessLevel" : "Public",
"expression" : {
"name" : "AgeSum",
"type" : "ExpressionRef"
}
} ]
}
}
}
|
[
{
"context": " # * Date Format 1.2.3\n # * (c) 2007-2009 Steven Levithan <stevenlevithan.com>\n # * MIT license\n #",
"end": 650,
"score": 0.9999071955680847,
"start": 635,
"tag": "NAME",
"value": "Steven Levithan"
},
{
"context": "t 1.2.3\n # * (c) 2007-2009 Steven Levithan <stevenlevithan.com>\n # * MIT license\n # *\n # * Inc",
"end": 670,
"score": 0.998742938041687,
"start": 652,
"tag": "EMAIL",
"value": "stevenlevithan.com"
},
{
"context": "nse\n # *\n # * Includes enhancements by Scott Trenda <scott.trenda.net>\n # * and Kris Kowal <cix",
"end": 754,
"score": 0.9997739791870117,
"start": 742,
"tag": "NAME",
"value": "Scott Trenda"
},
{
"context": " by Scott Trenda <scott.trenda.net>\n # * and Kris Kowal <cixar.com/~kris.kowal/>\n # *\n # * Ac",
"end": 799,
"score": 0.9999033212661743,
"start": 789,
"tag": "NAME",
"value": "Kris Kowal"
}
] | www/js/helper.coffee | ierror/29C3 | 2 | class Helper
@i18nDateFormats
constructor: ->
@i18nDateFormats = @_i18nDateFormats()
_i18nDateFormats: ->
dayNames: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
monthNames: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
formatDate: (date, mask, utc) ->
# Build coffeescript version form Date Format 1.2.3
#
# * Date Format 1.2.3
# * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
# * MIT license
# *
# * Includes enhancements by Scott Trenda <scott.trenda.net>
# * and Kris Kowal <cixar.com/~kris.kowal/>
# *
# * Accepts a date, a mask, or a date and a mask.
# * Returns a formatted version of the given date.
# * The date defaults to the current date/time.
# * The mask defaults to dateFormat.masks.default.
#
self = @
inner = {}
# Some common format strings
inner.masks =
default: "ddd mmm dd yyyy HH:MM:ss"
shortDate: "m/d/yy"
mediumDate: "mmm d, yyyy"
longDate: "mmmm d, yyyy"
fullDate: "dddd, mmmm d, yyyy"
shortTime: "h:MM TT"
mediumTime: "h:MM:ss TT"
longTime: "h:MM:ss TT Z"
isoDate: "yyyy-mm-dd"
isoTime: "HH:MM:ss"
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss"
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
inner._dateFormat = ->
token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g
timezoneClip = /[^-+\dA-Z]/g
pad = (val, len) ->
val = String(val)
len = len or 2
val = "0" + val while val.length < len
val
# Passing date through Date applies Date.parse, if necessary
date = (if date then new Date(date) else new Date)
throw SyntaxError("invalid date") if isNaN(date)
mask = String(inner.masks[mask] or mask or inner.masks["default"])
# Allow setting the utc argument via the mask
if mask.slice(0, 4) is "UTC:"
mask = mask.slice(4)
utc = true
_ = (if utc then "getUTC" else "get")
d = date[_ + "Date"]()
D = date[_ + "Day"]()
m = date[_ + "Month"]()
y = date[_ + "FullYear"]()
H = date[_ + "Hours"]()
M = date[_ + "Minutes"]()
s = date[_ + "Seconds"]()
L = date[_ + "Milliseconds"]()
o = (if utc then 0 else date.getTimezoneOffset())
flags =
d: d
dd: pad(d)
ddd: self.i18nDateFormats.dayNames[D]
dddd: self.i18nDateFormats.dayNames[D + 7]
m: m + 1
mm: pad(m + 1)
mmm: self.i18nDateFormats.monthNames[m]
mmmm: self.i18nDateFormats.monthNames[m + 12]
yy: String(y).slice(2)
yyyy: y
h: H % 12 or 12
hh: pad(H % 12 or 12)
H: H
HH: pad(H)
M: M
MM: pad(M)
s: s
ss: pad(s)
l: pad(L, 3)
L: pad((if L > 99 then Math.round(L / 10) else L))
t: (if H < 12 then "a" else "p")
tt: (if H < 12 then "am" else "pm")
T: (if H < 12 then "A" else "P")
TT: (if H < 12 then "AM" else "PM")
Z: (if utc then "UTC" else (String(date).match(timezone) or [""]).pop().replace(timezoneClip, ""))
o: ((if o > 0 then "-" else "+")) + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
S: ["th", "st", "nd", "rd"][(if d % 10 > 3 then 0 else (d % 100 - d % 10 isnt 10) * d % 10)]
mask.replace token, ($0) ->
(if $0 of flags then flags[$0] else $0.slice(1, $0.length - 1))
inner._dateFormat(date, mask, utc)
getObjKeys: (obj, keys) ->
keys = new Array()
for i of obj
keys.push i if obj.hasOwnProperty(i)
keys
clone: (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
getURLVarsFromString: (url) ->
vars = {}
for hash in url.slice(url.indexOf('?') + 1).split('&')
hash = hash.split('=')
vars[hash[0]] = hash[1]
vars
pad: (num, size) ->
s = num + ''
s = '0' + s while s.length < size
s
helper = new Helper() | 152971 | class Helper
@i18nDateFormats
constructor: ->
@i18nDateFormats = @_i18nDateFormats()
_i18nDateFormats: ->
dayNames: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
monthNames: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
formatDate: (date, mask, utc) ->
# Build coffeescript version form Date Format 1.2.3
#
# * Date Format 1.2.3
# * (c) 2007-2009 <NAME> <<EMAIL>>
# * MIT license
# *
# * Includes enhancements by <NAME> <scott.trenda.net>
# * and <NAME> <cixar.com/~kris.kowal/>
# *
# * Accepts a date, a mask, or a date and a mask.
# * Returns a formatted version of the given date.
# * The date defaults to the current date/time.
# * The mask defaults to dateFormat.masks.default.
#
self = @
inner = {}
# Some common format strings
inner.masks =
default: "ddd mmm dd yyyy HH:MM:ss"
shortDate: "m/d/yy"
mediumDate: "mmm d, yyyy"
longDate: "mmmm d, yyyy"
fullDate: "dddd, mmmm d, yyyy"
shortTime: "h:MM TT"
mediumTime: "h:MM:ss TT"
longTime: "h:MM:ss TT Z"
isoDate: "yyyy-mm-dd"
isoTime: "HH:MM:ss"
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss"
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
inner._dateFormat = ->
token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g
timezoneClip = /[^-+\dA-Z]/g
pad = (val, len) ->
val = String(val)
len = len or 2
val = "0" + val while val.length < len
val
# Passing date through Date applies Date.parse, if necessary
date = (if date then new Date(date) else new Date)
throw SyntaxError("invalid date") if isNaN(date)
mask = String(inner.masks[mask] or mask or inner.masks["default"])
# Allow setting the utc argument via the mask
if mask.slice(0, 4) is "UTC:"
mask = mask.slice(4)
utc = true
_ = (if utc then "getUTC" else "get")
d = date[_ + "Date"]()
D = date[_ + "Day"]()
m = date[_ + "Month"]()
y = date[_ + "FullYear"]()
H = date[_ + "Hours"]()
M = date[_ + "Minutes"]()
s = date[_ + "Seconds"]()
L = date[_ + "Milliseconds"]()
o = (if utc then 0 else date.getTimezoneOffset())
flags =
d: d
dd: pad(d)
ddd: self.i18nDateFormats.dayNames[D]
dddd: self.i18nDateFormats.dayNames[D + 7]
m: m + 1
mm: pad(m + 1)
mmm: self.i18nDateFormats.monthNames[m]
mmmm: self.i18nDateFormats.monthNames[m + 12]
yy: String(y).slice(2)
yyyy: y
h: H % 12 or 12
hh: pad(H % 12 or 12)
H: H
HH: pad(H)
M: M
MM: pad(M)
s: s
ss: pad(s)
l: pad(L, 3)
L: pad((if L > 99 then Math.round(L / 10) else L))
t: (if H < 12 then "a" else "p")
tt: (if H < 12 then "am" else "pm")
T: (if H < 12 then "A" else "P")
TT: (if H < 12 then "AM" else "PM")
Z: (if utc then "UTC" else (String(date).match(timezone) or [""]).pop().replace(timezoneClip, ""))
o: ((if o > 0 then "-" else "+")) + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
S: ["th", "st", "nd", "rd"][(if d % 10 > 3 then 0 else (d % 100 - d % 10 isnt 10) * d % 10)]
mask.replace token, ($0) ->
(if $0 of flags then flags[$0] else $0.slice(1, $0.length - 1))
inner._dateFormat(date, mask, utc)
getObjKeys: (obj, keys) ->
keys = new Array()
for i of obj
keys.push i if obj.hasOwnProperty(i)
keys
clone: (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
getURLVarsFromString: (url) ->
vars = {}
for hash in url.slice(url.indexOf('?') + 1).split('&')
hash = hash.split('=')
vars[hash[0]] = hash[1]
vars
pad: (num, size) ->
s = num + ''
s = '0' + s while s.length < size
s
helper = new Helper() | true | class Helper
@i18nDateFormats
constructor: ->
@i18nDateFormats = @_i18nDateFormats()
_i18nDateFormats: ->
dayNames: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
monthNames: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
formatDate: (date, mask, utc) ->
# Build coffeescript version form Date Format 1.2.3
#
# * Date Format 1.2.3
# * (c) 2007-2009 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# * MIT license
# *
# * Includes enhancements by PI:NAME:<NAME>END_PI <scott.trenda.net>
# * and PI:NAME:<NAME>END_PI <cixar.com/~kris.kowal/>
# *
# * Accepts a date, a mask, or a date and a mask.
# * Returns a formatted version of the given date.
# * The date defaults to the current date/time.
# * The mask defaults to dateFormat.masks.default.
#
self = @
inner = {}
# Some common format strings
inner.masks =
default: "ddd mmm dd yyyy HH:MM:ss"
shortDate: "m/d/yy"
mediumDate: "mmm d, yyyy"
longDate: "mmmm d, yyyy"
fullDate: "dddd, mmmm d, yyyy"
shortTime: "h:MM TT"
mediumTime: "h:MM:ss TT"
longTime: "h:MM:ss TT Z"
isoDate: "yyyy-mm-dd"
isoTime: "HH:MM:ss"
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss"
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
inner._dateFormat = ->
token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g
timezoneClip = /[^-+\dA-Z]/g
pad = (val, len) ->
val = String(val)
len = len or 2
val = "0" + val while val.length < len
val
# Passing date through Date applies Date.parse, if necessary
date = (if date then new Date(date) else new Date)
throw SyntaxError("invalid date") if isNaN(date)
mask = String(inner.masks[mask] or mask or inner.masks["default"])
# Allow setting the utc argument via the mask
if mask.slice(0, 4) is "UTC:"
mask = mask.slice(4)
utc = true
_ = (if utc then "getUTC" else "get")
d = date[_ + "Date"]()
D = date[_ + "Day"]()
m = date[_ + "Month"]()
y = date[_ + "FullYear"]()
H = date[_ + "Hours"]()
M = date[_ + "Minutes"]()
s = date[_ + "Seconds"]()
L = date[_ + "Milliseconds"]()
o = (if utc then 0 else date.getTimezoneOffset())
flags =
d: d
dd: pad(d)
ddd: self.i18nDateFormats.dayNames[D]
dddd: self.i18nDateFormats.dayNames[D + 7]
m: m + 1
mm: pad(m + 1)
mmm: self.i18nDateFormats.monthNames[m]
mmmm: self.i18nDateFormats.monthNames[m + 12]
yy: String(y).slice(2)
yyyy: y
h: H % 12 or 12
hh: pad(H % 12 or 12)
H: H
HH: pad(H)
M: M
MM: pad(M)
s: s
ss: pad(s)
l: pad(L, 3)
L: pad((if L > 99 then Math.round(L / 10) else L))
t: (if H < 12 then "a" else "p")
tt: (if H < 12 then "am" else "pm")
T: (if H < 12 then "A" else "P")
TT: (if H < 12 then "AM" else "PM")
Z: (if utc then "UTC" else (String(date).match(timezone) or [""]).pop().replace(timezoneClip, ""))
o: ((if o > 0 then "-" else "+")) + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
S: ["th", "st", "nd", "rd"][(if d % 10 > 3 then 0 else (d % 100 - d % 10 isnt 10) * d % 10)]
mask.replace token, ($0) ->
(if $0 of flags then flags[$0] else $0.slice(1, $0.length - 1))
inner._dateFormat(date, mask, utc)
getObjKeys: (obj, keys) ->
keys = new Array()
for i of obj
keys.push i if obj.hasOwnProperty(i)
keys
clone: (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
getURLVarsFromString: (url) ->
vars = {}
for hash in url.slice(url.indexOf('?') + 1).split('&')
hash = hash.split('=')
vars[hash[0]] = hash[1]
vars
pad: (num, size) ->
s = num + ''
s = '0' + s while s.length < size
s
helper = new Helper() |
[
{
"context": "= new Director(\"push\", router)\n\n\t###\n\t###\n\t\n\tname: director.name\n\n\t###\n\t###\n\t\n\tdirector: director\n\n\t###\n\t###\n",
"end": 146,
"score": 0.9040957093238831,
"start": 138,
"tag": "NAME",
"value": "director"
}
] | src/push/plugin.coffee | crcn-archive/beanpoll.js | 1 | Director = require "./director"
module.exports = (router) ->
###
###
director = new Director("push", router)
###
###
name: director.name
###
###
director: director
###
###
newListener: (listener) ->
router.request('new/listener').tag('private',true).query(listener).push();
###
###
router:
push: (path, query, headers) -> @request(path, query, headers).push null
###
###
request:
push: (data) ->
# no error handler? add a blank func
# if not @error()
# @error ->
writer = @dispatch director.name
# if data exists, then we're done.
writer.end data if !!arguments.length
writer
| 12841 | Director = require "./director"
module.exports = (router) ->
###
###
director = new Director("push", router)
###
###
name: <NAME>.name
###
###
director: director
###
###
newListener: (listener) ->
router.request('new/listener').tag('private',true).query(listener).push();
###
###
router:
push: (path, query, headers) -> @request(path, query, headers).push null
###
###
request:
push: (data) ->
# no error handler? add a blank func
# if not @error()
# @error ->
writer = @dispatch director.name
# if data exists, then we're done.
writer.end data if !!arguments.length
writer
| true | Director = require "./director"
module.exports = (router) ->
###
###
director = new Director("push", router)
###
###
name: PI:NAME:<NAME>END_PI.name
###
###
director: director
###
###
newListener: (listener) ->
router.request('new/listener').tag('private',true).query(listener).push();
###
###
router:
push: (path, query, headers) -> @request(path, query, headers).push null
###
###
request:
push: (data) ->
# no error handler? add a blank func
# if not @error()
# @error ->
writer = @dispatch director.name
# if data exists, then we're done.
writer.end data if !!arguments.length
writer
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.