Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Make db accessible from spec | {Emitter} = require 'atom'
_ = require 'underscore-plus'
DB = require './db'
Project = require './project'
module.exports =
class Projects
constructor: () ->
@emitter = new Emitter
@db = new DB()
@db.onUpdate () =>
@emitter.emit 'projects-updated'
onUpdate: (callback) ->
@emitter.on 'projec... | {Emitter} = require 'atom'
_ = require 'underscore-plus'
DB = require './db'
Project = require './project'
module.exports =
class Projects
db: null
constructor: () ->
@emitter = new Emitter
@db = new DB()
@db.onUpdate () =>
@emitter.emit 'projects-updated'
onUpdate: (callback) ->
@emit... |
Use new global export for underscore.string | isActive = (type, inverse = false) ->
name = 'is'
name = name + 'Not' if inverse
name = name + 'Active' + _.capitalize type
(view) ->
unless view instanceof Spacebars.kw
throw new Error "#{name} options must be key value pair such " +
"as {{#{name} regex='route/path'}}. You passed: " +
... | isActive = (type, inverse = false) ->
name = 'is'
name = name + 'Not' if inverse
name = name + 'Active' + s.capitalize type
(view) ->
unless view instanceof Spacebars.kw
throw new Error "#{name} options must be key value pair such " +
"as {{#{name} regex='route/path'}}. You passed: " +
... |
Add spec for out ports | chai = require 'chai' unless chai
if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1
outport = require '../src/lib/OutPort'
socket = require '../src/lib/InternalSocket'
else
outport = require 'noflo/src/lib/OutPort.js'
socket = require 'noflo/src/lib/InternalSoc... | |
Remove inlined files from app directory | path = require 'path'
CSON = require 'season'
fs = require 'fs-plus'
module.exports = (grunt) ->
{spawn} = require('./task-helpers')(grunt)
grunt.registerTask 'compile-packages-slug', 'Add bundled package metadata information to to the main package.json file', ->
appDir = grunt.config.get('atom.appDir')
... | path = require 'path'
CSON = require 'season'
fs = require 'fs-plus'
module.exports = (grunt) ->
{spawn, rm} = require('./task-helpers')(grunt)
grunt.registerTask 'compile-packages-slug', 'Add bundled package metadata information to to the main package.json file', ->
appDir = grunt.config.get('atom.appDir')
... |
Clarify that CSON requires unique keys | # Your keymap
#
# Atom keymaps work similarly to style sheets. Just as style sheets use
# selectors to apply styles to elements, Atom keymaps use selectors to associate
# keystrokes with events in specific contexts.
#
# You can create a new keybinding in this file by typing "key" and then hitting
# tab.
#
# Here's an e... | # Your keymap
#
# Atom keymaps work similarly to style sheets. Just as style sheets use
# selectors to apply styles to elements, Atom keymaps use selectors to associate
# keystrokes with events in specific contexts. (Unlike style sheets however,
# each selector can only be declared once.)
#
# You can create a new keybi... |
Put stuff in else and cleaned up navigateTo | # WARNING: be very careful when changing this stuff, there are many edge cases!
# Add a default clickhandler so we can use hrefs
defaultClickHandler = (e) ->
if Backbone.History.started # Capitalization in Backbone.[H]istory is intentional
$link = $(e.target).closest("a")
url = $link.attr("href")
target... | # WARNING: be very careful when changing this stuff, there are many edge cases!
# Add a default clickhandler so we can use hrefs
defaultClickHandler = (e) ->
if Backbone.History.started # Capitalization in Backbone.[H]istory is intentional
$link = $(e.target).closest("a")
url = $link.attr("href")
if e.m... |
Add missing test for Unreleased Ban. | require '../../helpers'
{BattleServer} = require('../../../server/server')
gen = require('../../../server/generations')
{User} = require('../../../server/user')
{Conditions} = require '../../../shared/conditions'
{Factory} = require '../../factory'
should = require('should')
describe 'Validations: Unreleased Ban', ->... | |
Use Vex for delete confirmation dialogs | $ ->
$(document).on "page:change", ->
$('a[data-method="delete"]').on "click", (e) ->
$link = $(this)
vex.dialog.open
message: "Are you sure you want to delete this item?"
buttons: [
$.extend({}, vex.dialog.buttons.NO,
className: "secondary"
text: "Ca... | |
Add migration to remove non-null constraints |
exports.up = (knex, Promise) ->
knex.raw('ALTER TABLE teams ALTER COLUMN name DROP NOT NULL')
.then ->
knex.raw('ALTER TABLE teams ALTER COLUMN generation DROP NOT NULL')
exports.down = (knex, Promise) ->
knex.raw('ALTER TABLE teams ALTER COLUMN name SET NOT NULL')
.then ->
knex.raw('ALTER TA... | |
Add create build directories spec. | fs = require 'fs'
path = require 'path'
helpers = require '../src/helpers'
describe 'create build directories', ->
beforeEach -> helpers.createBuildDirectories 'output'
afterEach -> removeDirectory 'output'
it 'should create directory structure for build path', ->
expect(path.existsSync 'output/web/js').to... | |
Add method to execute migration | Meteor.methods
migrate: (version) ->
user = Meteor.user()
if not user? or user.admin isnt true
return
this.ublock()
Migrations.migrateTo version
return version
getMigrationVersion: ->
return Migrations.getVersion() | |
Add numbers for special stored procedures.. | modules.exports =
Sp_Cursor: 1
Sp_CursorOpen: 2
Sp_CursorPrepare: 3
Sp_CursorExecute: 4
Sp_CursorPrepExec: 5
Sp_CursorUnprepare: 6
Sp_CursorFetch: 7
Sp_CursorOption: 8
Sp_CursorClose: 9
Sp_ExecuteSql: 10
Sp_Prepare: 11
Sp_Execute: 12
Sp_PrepExec: 13
Sp_PrepExecRpc: 14
Sp_Unprepare: 15
| |
Add tests to test prettify-response method | {assert} = require 'chai'
sinon = require 'sinon'
loggerStub = require '../../src/logger'
prettifyResponse = require '../../src/prettify-response'
describe 'prettifyResponse(response)', () ->
describe 'with a real object without any circular references', () ->
it 'should print JSON.stringified application/json ... | |
Add UDP netowork messages to Hubot | # Send messages to channels via hubot
#
# $ echo "#channel|hello everyone" | nc -u -w1 bot_hostname bot_port
# $ echo "nickname|hello mister" | nc -u -w1 bot_hostname bot_port
dgram = require "dgram"
server = dgram.createSocket "udp4"
module.exports = (robot) ->
server.on 'message', (message, rinfo) ->
msg = mes... | |
Add script to evaluate Ruby script | # Evaluate one line of Ruby script.
#
# ruby|rb <script> - Evaluate one line of Ruby script
module.exports = (robot) ->
robot.respond /(ruby|rb)\s+(.*)/i, (msg)->
script = msg.match[2]
msg.http("http://tryruby.org/levels/1/challenges/0")
.query("cmd": script)
.headers("Content-Length": "0")
... | |
Fix scroll position on transition | ETahi.ApplicationController = Ember.Controller.extend
delayedSave: false
currentUser: ( ->
@getCurrentUser()
).property()
isLoggedIn: ( ->
!Ember.isBlank(@get('currentUser.id'))
).property('currentUser.id')
isAdmin: Ember.computed.alias 'currentUser.siteAdmin'
canViewAdminLinks: false
# this ... | ETahi.ApplicationController = Ember.Controller.extend
delayedSave: false
currentUser: ( ->
@getCurrentUser()
).property()
isLoggedIn: ( ->
!Ember.isBlank(@get('currentUser.id'))
).property('currentUser.id')
isAdmin: Ember.computed.alias 'currentUser.siteAdmin'
canViewAdminLinks: false
# this ... |
Add integration test for channels (create, update, delete) | _ = require 'underscore'
SphereClient = require '../../lib/client'
Config = require('../../config').config
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
newChannel = ->
key: uniqueId 'c'
updateChannel = (version) ->
version: version
actions: [
{action: 'changeName', name: {en: 'A ... | |
Add missing javascript for acts as list. | $ ->
$('[data-acts-as-list-item]').each ->
$(@).draggable({
scope: $(@).attr('data-acts-as-list-item-scope'),
revert: true
})
$ ->
$('[data-acts-as-list-item]').each ->
redirect_target = $(@).attr('data-acts-as-list-item-on-drop-target')
authenticity_token = $( 'meta[name="csrf-token"]'... | |
Use splat instead of apply | _ = require 'underscore'
BufferedProcess = require 'buffered-process'
$ = require 'jquery'
module.exports =
class LoadPathsTask
constructor: (@callback) ->
start: ->
rootPath = project.getPath()
ignoredNames = config.get('fuzzyFinder.ignoredNames') ? []
ignoredNames = ignoredNames.concat(config.get('c... | _ = require 'underscore'
BufferedProcess = require 'buffered-process'
$ = require 'jquery'
module.exports =
class LoadPathsTask
constructor: (@callback) ->
start: ->
rootPath = project.getPath()
ignoredNames = config.get('fuzzyFinder.ignoredNames') ? []
ignoredNames = ignoredNames.concat(config.get('c... |
Support moving up/down in tree view with k/j keys | 'body':
'meta-\\': 'tree-view:toggle'
'meta-|': 'tree-view:reveal-active-file'
'.tree-view':
'right': 'tree-view:expand-directory'
'ctrl-]': 'tree-view:expand-directory'
'left': 'tree-view:collapse-directory'
'ctrl-[': 'tree-view:collapse-directory'
'enter': 'tree-view:open-selected-entry'
'm': 'tree-v... | 'body':
'meta-\\': 'tree-view:toggle'
'meta-|': 'tree-view:reveal-active-file'
'.tree-view':
'right': 'tree-view:expand-directory'
'ctrl-]': 'tree-view:expand-directory'
'left': 'tree-view:collapse-directory'
'ctrl-[': 'tree-view:collapse-directory'
'enter': 'tree-view:open-selected-entry'
'm': 'tree-v... |
Add spec for ArchiveEditor self-destruction | {Document} = require 'atom'
ArchiveEditor = require '../lib/archive-editor'
describe "ArchiveEditor", ->
it "destroys itself upon creation if no file exists at the given path", ->
doc = Document.create()
doc.set('archiveEditor', new ArchiveEditor(path: "bogus"))
expect(doc.has('imageEditor')).toBe false
| |
Add component to rotate buffers | noflo = require 'noflo'
sharp = require 'sharp'
Canvas = require('noflo-canvas').canvas
# @runtime noflo-nodejs
# @name Rotate
exports.getComponent = ->
c = new noflo.Component
c.icon = 'expand'
c.description = 'Rotate a given image buffer to a new angle'
c.inPorts.add 'buffer',
datatype: 'object'
d... | |
Add a MainArea component skeleton | ###* @jsx React.DOM ###
window.MainArea = React.createClass
sideBarButtons: ->
`<button id="hide-criteria-button" className="btn btn-mini" title="Hide search criteria">
<i className="icon-double-angle-left"> Hide</i>
</button>
<button id="show-criteria-button" className="btn btn-mini" style={{displ... | |
Implement API for flat galleries on year, month and day levels | options = require '../tools/optionsroute'
moment = require 'moment'
_ = require 'lodash'
getTimespanImages = (db, res, start, end) ->
db.all 'SELECT * FROM tFile WHERE timestamp >= ? AND timestamp < ? ORDER BY timestamp ASC',
start.valueOf(), end.valueOf(), (err, rows) ->
if err?
... | |
Add some specs for ValidatableInput | #= require magic_word
describe 'ValidatableInput', ->
beforeEach ->
@input = $('<input name="foo[bar]"/>')
@form = validate: ->
@defaultTimeout = 500
@v = new MagicWord.ValidatableInput @input, @form
describe "#constructor", ->
it 'sets the default timeout to 500ms', ->
... | |
Remove unused StorageFolder::store method (moved state to IndexedDB) | path = require "path"
fs = require "fs-plus"
module.exports =
class StorageFolder
constructor: (containingPath) ->
@path = path.join(containingPath, "storage") if containingPath?
storeSync: (name, object) ->
return unless @path?
fs.writeFileSync(@pathForKey(name), JSON.stringify(object), 'utf8')
s... | path = require "path"
fs = require "fs-plus"
module.exports =
class StorageFolder
constructor: (containingPath) ->
@path = path.join(containingPath, "storage") if containingPath?
storeSync: (name, object) ->
return unless @path?
fs.writeFileSync(@pathForKey(name), JSON.stringify(object), 'utf8')
l... |
Test directive: display properly & basic behavior & communicate with controller | describe 'Unit test: superman directive', ->
beforeEach ->
module 'angularjsGettingStartedApp'
$rootScope = $compile = $httpBackend = {}
beforeEach ->
inject ['$compile','$rootScope', ($c,$r) ->
$rootScope = $r
$compile = $c
]
it 'should display right', ->
elem = $compile('<superman>... | |
Add a bundle of snippet-templates | ".source.apl":
Function:
prefix: "fn"
body: "∇${2:R ←} ${3:X} ${1:NAME} ${4:Y}\n\t$0\n∇"
Operator:
prefix: "op"
body: "∇${2:R ←} ${3:X} (${4:LOP} ${1:NAME} ${5:ROP}) ${6:Y}\n\t$0\n∇"
Assignment:
prefix: "a"
body: "${1:⎕ }← ${2:VALUE}"
# GNU APL extensions
"GNU Heredoc: Plain":
prefix:... | |
Implement 'gulp' and 'gulp build' | coffee = require 'gulp-coffee'
gulp = require 'gulp'
gutil = require 'gulp-util'
rimraf = require 'rimraf'
handleError = (err) ->
gutil.log err
@emit 'end'
gulp.task 'clean', (done) ->
rimraf './lib', done
gulp.task 'build', ['clean'], ->
gulp.src './lib-src/**/*.coffee'
.pipe coffee(bare: true).on 'erro... | |
Use a Jake instead of shell script | desc 'Deploy to production'
task 'deploy', ->
console.log '-----> Deploying...' ;
cmds = [
//'git ci -m "lol"',
//'git push',
'cd ../prod',
'pwd'
]
jake.exec cmds, { printStdOut: true }, () ->
console.log 'OK'
complete
task 'default', ->
jake.Task[... | |
Update scrollbars after toggle sidebar | $(document).on("click", '.toggle-nav-collapse', (e) ->
e.preventDefault()
collapsed = 'page-sidebar-collapsed'
expanded = 'page-sidebar-expanded'
$('.page-with-sidebar').toggleClass("#{collapsed} #{expanded}")
$('header').toggleClass("header-collapsed header-expanded")
$('.sidebar-wrapper').toggleClass("si... | $(document).on("click", '.toggle-nav-collapse', (e) ->
e.preventDefault()
collapsed = 'page-sidebar-collapsed'
expanded = 'page-sidebar-expanded'
$('.page-with-sidebar').toggleClass("#{collapsed} #{expanded}")
$('header').toggleClass("header-collapsed header-expanded")
$('.sidebar-wrapper').toggleClass("si... |
Update on the correct checkbox. | $ ->
$(":checkbox").change ->
id = $(this).val()
checked = $(this).is(":checked")
url = $(this).data("url")
$.ajax
type: "PUT"
url: url
dataType: "json"
data:
id: id
developers_can_push: checked
success: ->
new Flash("Branch updated.", "notice")
... | $ ->
$(":checkbox").change ->
name = $(this).attr("name")
if name == "developers_can_push"
id = $(this).val()
checked = $(this).is(":checked")
url = $(this).data("url")
$.ajax
type: "PUT"
url: url
dataType: "json"
data:
id: id
develop... |
Add keymaps file so that autocompletion is properly triggered. | ".autocomplete-plus input.hidden-input":
"tab": "autocomplete-plus:confirm"
"down": "autocomplete-plus:select-next"
"ctrl-n": "autocomplete-plus:select-next"
"up": "autocomplete-plus:select-previous"
"ctrl-p": "autocomplete-plus:select-previous"
"escape": "autocomplete-plus:cancel"
".editor":
"ctrl-shift... | |
Add constructor tests for SpeficationDirectory. | describe "SpecificationDirectory",
{
"given a directory manifest with no files or sub-directories": ->
@manifest =
name: "example"
files: []
directories: []
"when a SpecificationDirectory is created with the manifest": ->
@directory = new Witness.SpecificationDirectory @manifest
then:
di... | |
Rename Editor export to EditorView | {Document, Point, Range} = require 'telepath'
module.exports =
_: require 'underscore-plus'
BufferedNodeProcess: require '../src/buffered-node-process'
BufferedProcess: require '../src/buffered-process'
Directory: require '../src/directory'
Document: Document
File: require '../src/file'
fs: require 'fs-p... | {Document, Point, Range} = require 'telepath'
module.exports =
_: require 'underscore-plus'
BufferedNodeProcess: require '../src/buffered-node-process'
BufferedProcess: require '../src/buffered-process'
Directory: require '../src/directory'
Document: Document
File: require '../src/file'
fs: require 'fs-p... |
Make the models into event-emitters |
{EventEmitter} = require 'events'
_ = require 'lodash'
# using DS events imply one more query for each update
# instead we monkeypatch cozydb
module.exports.wrapModel = (Model) ->
Model.ee = new EventEmitter()
Model.on = -> Model.ee.on.apply Model.ee, arguments
_oldCreate = Model.create
Model.creat... | |
Add initial Save Progress module | # *************************************
#
# Save Progress
# -> Save input text in Local Storage
#
# *************************************
#
# options.elements - the element containing text to save
# options.dataAttribute - the data attribute of the Local Storage key
#
# *************************************
@Spell... | |
Add spec to ModerationApp component | define [
'react'
'jsx/assignments/ModerationApp'
'jsx/assignments/actions/ModerationActions'
], (React, ModerationApp, Actions) ->
TestUtils = React.addons.TestUtils
module 'ModerationApp',
setup: ->
@store =
subscribe: sinon.spy()
dispatch: sinon.spy()
getState: -> {
... | |
Allow artist CV to include non displayable shows | module.exports =
"""
query artist($artist_id: String!, $shows: Boolean!, $articles: Boolean!) {
artist(id: $artist_id) {
... on Artist @include(if: $shows) {
group_shows: shows(at_a_fair: false, solo_show:false, sort: start_at_desc, is_reference: true, size: 99) {
... relatedShow
... | module.exports =
"""
query artist($artist_id: String!, $shows: Boolean!, $articles: Boolean!) {
artist(id: $artist_id) {
... on Artist @include(if: $shows) {
group_shows: shows(at_a_fair: false, solo_show:false, sort: start_at_desc, is_reference: true, visible_to_public: false, size: 99) {
... |
Create test for canvas 2 buffer component | noflo = require 'noflo'
unless noflo.isBrowser()
chai = require 'chai' unless chai
CanvasToBuffer = require '../components/CanvasToBuffer.coffee'
else
CanvasToBuffer = require 'noflo-image/components/CanvasToBuffer.js'
describe 'CanvasToBuffer component', ->
c = null
ins = null
out = null
error = null
... | |
Add failing tests for error reporting | describe 'compilation error "undefined function"', ->
it 'occurs if a function in the spec does not exist in the context', ->
a.throws (-> ss a: b: $bar: 5),
"""
Error: The function "$bar" is not defined.
{
"a": {
"b": {
"$bar": 5
^^^
}
}
}"""
it 'correctly highlights position ... | |
Add more info to new. Closes gh-619. | 'use strict'
initSkeleton = require 'init-skeleton'
sysPath = require 'path'
watch = require './watch'
logger = require 'loggy'
create = (skeleton, path = '.') ->
unless skeleton
logger.error '''
You must specify skeleton (boilerplate) from which brunch will initialize
new application.
You can specify di... | 'use strict'
initSkeleton = require 'init-skeleton'
sysPath = require 'path'
watch = require './watch'
logger = require 'loggy'
create = (skeleton, path = '.') ->
unless skeleton
logger.error '''
You must specify skeleton (boilerplate) from which brunch will initialize new app:
brunch new --skeleton <path-... |
Speed up friendlyDatetime component in react files | define [
'react'
'timezone'
'underscore'
'jquery'
'jquery.instructure_date_and_time'
], (React, tz, _, $) ->
FriendlyDatetime = React.createClass
propTypes:
datetime: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.instanceOf(Date)
])
render: ->
... | define [
'react'
'timezone'
'underscore'
'jquery'
'jquery.instructure_date_and_time'
], (React, tz, _, $) ->
slowRender = ->
datetime = @props.datetime
return React.DOM.time() unless datetime?
datetime = tz.parse(datetime) unless _.isDate datetime
fudged = $.fudgeDateForProfileTimezone(dat... |
Add component to SWT detector | noflo = require 'noflo'
temporary = require 'temporary'
fs = require 'fs'
path = require 'path'
exec = require('child_process').exec
# @runtime noflo-nodejs
# @name SWTDetect
compute = (canvas, callback) ->
# Get canvas
ctx = canvas.getContext '2d'
imageData = ctx.getImageData 0, 0, canvas.width, canvas.height
... | |
Add initial traffic signs to CSON | {
information_pedestrian_crossing:
category: 'other'
name: 'pedestrian crossing'
elements: [
{ type: 'tri-bg', value: 'white' }
{ type: 'tri-o', value: 'red' }
{ type: 'pedestrian', value: 'black' }
]
mandatory_keep_right:
category: 'mandatory'
name: 'keep right'
eleme... | |
Implement helper method for XML escaping | escapeXMLCharacter = (c) ->
'&' + { '&': 'amp', '<': 'lt', '>': 'gt', "'": 'apos', '"': 'quot'}[c] + ';'
escapeXML = (s) ->
s.replace(/([&<>'"])/g, escapeXMLCharacter)
module.exports.escapeXML = escapeXML | |
Use `show me issues for <user/repo>` to list open issues (Github) | # Show open issues from a Github repository.
#
# You need to set the following variables:
# HUBOT_GITHUB_TOKEN = <oauth token>
# HUBOT_GITHUB_USER = <user name>
#
# HUBOT_GITHUB_USER is optional, but if you set it, you can ask `show me issues
# for hubot` instead of `show me issues for github/hubot`.
#
# show me is... | |
Add custom html view tests | should = require 'should'
KDCustomHTMLView = require '../../lib/core/customhtmlview'
describe 'KDCustomHTMLView', ->
it 'exists', ->
KDCustomHTMLView.should.exist
describe 'constructor', ->
it 'should instantiate without error', ->
router = new KDCustomHTMLView
router.should.exist
| |
Hide adjustments in cart by default, show by click | $(document).ready ->
$('#cart_adjustments').hide()
$('th.cart-adjustment-header').html('<a href="#">Order Adjustments...</a>')
$('th.cart-adjustment-header a').click ->
$('#cart_adjustments').toggle()
$('th.cart-adjustment-header a').html('Order Adjustments')
false | |
Fix calling showItemInFolder in renderer | module.exports = process.atomBinding 'shell'
if process.platform is 'win32' and process.type is 'renderer'
module.exports.showItemInFolder = require('remote').process.atomBinding('shell').showItemInFolder
| module.exports = process.atomBinding 'shell'
if process.platform is 'win32' and process.type is 'renderer'
module.exports.showItemInFolder = (item) ->
require('remote').require('shell').showItemInFolder item
|
Allow sending messages to non-whitelisted devices by default | util = require "./util"
bcrypt = require "bcrypt"
_ = require "lodash"
checkLists = (fromDevice, toDevice, whitelist, blacklist, openByDefault) ->
return false if !fromDevice or !toDevice
return true if toDevice.uuid == fromDevice.uuid
return true if toDevice.owner == fromDevice.uuid
return _.contains(whit... | util = require "./util"
bcrypt = require "bcrypt"
_ = require "lodash"
checkLists = (fromDevice, toDevice, whitelist, blacklist, openByDefault) ->
return false if !fromDevice or !toDevice
return true if toDevice.uuid == fromDevice.uuid
return true if toDevice.owner == fromDevice.uuid
return _.contains(whit... |
Decrease the callback priority of highlight words | ###
# Hilights is a named function that will process Highlights
# @param {Object} message - The message object
###
class HighlightWordsClient
constructor: (message) ->
msg = message
if not _.isString message
if _.trim message.html
msg = message.html
else
return message
to_hi... | ###
# Hilights is a named function that will process Highlights
# @param {Object} message - The message object
###
class HighlightWordsClient
constructor: (message) ->
msg = message
if not _.isString message
if _.trim message.html
msg = message.html
else
return message
to_hi... |
Add unit tests for presigned URLs | helpers = require('../helpers')
AWS = helpers.AWS
describe 'AWS.Signers.Presign', ->
it 'presigns requests', ->
spyOn(AWS.util.date, 'getDate').andReturn(new Date(0))
resultUrl = 'https://monitoring.mock-region.amazonaws.com/?' +
'Action=ListMetrics&Version=2010-08-01&' +
'X-Amz-Algorithm=AWS4-HM... | |
Add specs for grammar overrides | GrammarRegistry = require '../lib/grammar-registry'
describe "GrammarRegistry", ->
describe "grammar overrides", ->
it "stores the override scope name for a path", ->
registry = new GrammarRegistry()
expect(registry.grammarOverrideForPath('foo.js.txt')).toBeUndefined()
expect(registry.grammarO... | |
Add -> tests for common utils. | debug = require('debug')('spec:common-utils')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
{CommonUtils} = require '../lib'
{ExtendedLogger} = require 'sphere-node-utils'
package_json = require '../package.json'
sampleObjectCollection = [
action: 'addPlainEnumValue'
attributeName: 'sample-enum-attr... | |
Set default metadata and pagination hashes. | #= require_self
#= require_tree .
DotLedger.module 'Collections', ->
class @Base extends Backbone.Collection
parse: (response, options)->
@_fetch_options_data = options.data || {}
@pagination = JSON.parse options.xhr.getResponseHeader('X-Pagination')
@metadata = JSON.parse options.xhr.getRespon... | #= require_self
#= require_tree .
DotLedger.module 'Collections', ->
class @Base extends Backbone.Collection
pagination: {}
metadata: {}
parse: (response, options)->
@_fetch_options_data = options.data || {}
@pagination = JSON.parse options.xhr.getResponseHeader('X-Pagination')
@metad... |
Add tests that changelog loads | j.describe "changelog", ->
j.it "should have correct twitter", ->
@expect(CI.outer.changelog.twitter("pbiggar")).toEqual "https://twitter.com/pbiggar"
@expect(CI.outer.changelog.twitter("notarealuser")).toThrow
| |
Add `Processor` for creating DZIs | DeepZoomImage = require 'deepzoomtools'
path = require 'path'
# Defaults
DEFAULT_TILE_SIZE = 254
DEFAULT_TILE_OVERLAP = 1
DEFAULT_FORMAT = 'jpg'
# Public API
module.exports = class Processor
constructor: (@path) ->
process: (source, _) ->
destination = path.join @path, path.basename source
DeepZoomImage... | |
Include fuzzy search lib from old repo | define ["underscore"], (_) ->
class FuzzySearch
WEIGHT_SEPARATOR_REGEX = /(\_|\-|\.)/gi
match: (search, text) ->
chars = _splitChars search
# Escape non alphanumerical chars
for char, i in chars
if /\W/.test char
chars[i] = "\\#{char}"
new RegExp(chars.join(".*"), ... | |
Fix file inputs not displaying selected file name | # Overwrites text with filename for BS4 custom-file fields in
# app/views/forms/[horizontal|vertical]/_file_field.html.haml
# when files are selected.
$(document)
.on("change", ".custom-file-input", ->
fileNameStart = $(this).val().lastIndexOf("\\")
fileName = $(this).val().substr(fileNameStart + 1);
text... | |
Add some helper methods for classes | kopi.module("kopi.utils.klass")
.require("kopi.exceptions")
.require("kopi.utils")
.define (exports, exceptions, utils) ->
extend = (klass, mixin) ->
for name, method of mixin
klass[name] = method
klass
include = (klass, mixin) ->
for name, method of mixin.prototype
kla... | |
Throw error when starting terminated process | _ = require 'underscore'
child_process = require 'child_process'
EventEmitter = require 'event-emitter'
module.exports =
class Task
callback: null
constructor: (taskPath) ->
bootstrap = """
require('coffee-script');
require('coffee-cache').setCacheDir('/tmp/atom-coffee-cache');
require('task... | _ = require 'underscore'
child_process = require 'child_process'
EventEmitter = require 'event-emitter'
module.exports =
class Task
callback: null
constructor: (taskPath) ->
bootstrap = """
require('coffee-script');
require('coffee-cache').setCacheDir('/tmp/atom-coffee-cache');
require('task... |
Implement refactored zoom component using Modalize | modalize = require '../modalize/index.coffee'
module.exports = (src) ->
(img = new Image).src = src
$img = $("<img src='#{src}'>")
modal = modalize render: -> $el: $img
modal.load (done) ->
$img.on 'load', ->
modal.view.dimensions.width = img.width
done()
| |
Improve logging when Cozy instance goes down | async = require 'async'
Account = require '../models/account'
CozyInstance = require '../models/cozy_instance'
fixtures = require 'cozy-fixtures'
module.exports.main = (req, res, next) ->
async.parallel [
(cb) -> CozyInstance.getLocale cb
(cb) -> Account.getAll cb
], (err, results) ->
... | async = require 'async'
Account = require '../models/account'
CozyInstance = require '../models/cozy_instance'
fixtures = require 'cozy-fixtures'
module.exports.main = (req, res, next) ->
async.parallel [
(cb) -> CozyInstance.getLocale cb
(cb) -> Account.getAll cb
], (err, results) ->
... |
Add token to request when available | $ = require 'jquery'
{$$} = require 'space-pen'
module.exports =
class Gists
@activate: -> new Gists
constructor: ->
rootView.command 'gist:create', '.editor', => @createGist()
createGist: ->
editor = rootView.getActiveView()
return unless editor?
gist = { public: false, files: {} }
gist.f... | $ = require 'jquery'
{$$} = require 'space-pen'
module.exports =
class Gists
@activate: -> new Gists
constructor: ->
rootView.command 'gist:create', '.editor', => @createGist()
createGist: ->
editor = rootView.getActiveView()
return unless editor?
gist = { public: false, files: {} }
gist.fi... |
Test two step help component/mixin | {Testing, expect, sinon, _, React} = require 'test/helpers'
TwoStepHelpMixin = require 'components/exercise/two-step-help-mixin'
Networking = require 'model/networking'
TestComponent = React.createClass
mixins: [TwoStepHelpMixin]
render: ->
return @renderTwoStepHelp() if @hasTwoStepHelp()
<span>No Help D... | |
Create team table to display lifetime team standings for a league | {div, table, thead, tbody, tr, th, td} = React.DOM
table_headers = [
"Team"
"Win %"
"Wins"
"Losses"
"Ties"
]
@TeamTable = React.createClass
propTypes:
teams: React.PropTypes.array
render: ->
div className: "league--table-container",
table className: "league--table",
thead className: "league--table-... | |
Add an experimental resource-bound auto-saving input | React = require 'react'
ChangeListener = require './change-listener'
handleInputChange = require '../lib/handle-input-change'
module.exports = React.createClass
displayName: 'ResourceInput'
getDefaultProps: ->
type: ''
resource: null
attribute: ''
autoSaveDelay: 5000
getInitialState: ->
edi... | |
Add env and it's related test. | # Tests configuration.
#
# Author: Andy Zhao(andy@nodeswork.com)
config = require 'coffiew/config'
describe 'Config', ->
describe 'env', ->
it 'should run in nodes', ->
config.env.isNode.should.be.true
| |
Package server API file w/header | # ______ ______ ______ __ __ ______ __ ______
# /\__ _\ /\ == \ /\ __ \ /\ "-.\ \ /\___ \ /\ \ /\__ _\
# \/_/\ \/ \ \ __< \ \ __ \ \ \ \-. \ \/_/ /__ \ \ \ \/_/\ \/
# \ \_\ \ \_\ \_\ \ \_\ \_\ \ \_\\"\_\ /\_____\ \ \_\ \ \_\
# \/_/ \/_/ /_/ \/_/... | |
Add menu item to toggle | 'menu': [
{
'label': 'Packages'
'submenu': [
'label': 'Keybinding Resolver'
'submenu': [
{ 'label': 'Toggle', 'command': 'key-binding-resolver:toggle' }
]
]
}
]
| |
Fix viewing repo after viewing all repos on safari | `import TravisRoute from 'travis/routes/basic'`
Route = TravisRoute.extend
renderTemplate: ->
@render 'repo'
@render 'build', into: 'repo'
setupController: ->
@_super.apply this, arguments
@controllerFor('repo').activate('index')
@controllerFor('repos').activate(@get('reposTabName'))
@cu... | `import TravisRoute from 'travis/routes/basic'`
Route = TravisRoute.extend
renderTemplate: ->
@render 'repo'
@render 'build', into: 'repo'
setupController: ->
@_super.apply this, arguments
@controllerFor('repo').activate('index')
@controllerFor('repos').activate(@get('reposTabName'))
@cu... |
Create method to load locale from private | Meteor.methods
loadLocale: (locale) ->
console.log "[method] loadLocale: #{locale}".green
try
return Assets.getText "moment-locales/#{locale.toLowerCase()}.js"
catch e
console.log e
| |
Add attempt at keep alive. | # Description:
# Utility commands surrounding Hubot uptime.
#
# Commands:
# hubot stay alive - Try keep hubot alive
stayingalive = false
module.exports = (robot) ->
robot.respond /(stay alive$/i, (msg) ->
if stayingalive
msg.send 'Already staying alive.'
else
startKeepAlive msg, (text) ->
... | |
Use shift in the example rather than explaining the difference | # Your keymap
#
# Atom keymaps work similarly to stylesheets. Just as stylesheets use selectors
# to apply styles to elements, Atom keymaps use selectors to associate
# keystrokes with events in specific contexts.
#
# You can create a new keybinding in this file by typing "key" and then hitting
# tab.
#
# Here's an exa... | # Your keymap
#
# Atom keymaps work similarly to stylesheets. Just as stylesheets use selectors
# to apply styles to elements, Atom keymaps use selectors to associate
# keystrokes with events in specific contexts.
#
# You can create a new keybinding in this file by typing "key" and then hitting
# tab.
#
# Here's an exa... |
Update the upvote arrows on ajax submit | $(document).ready ->
$(".vote-form").on 'ajax:success', (event, xhr, status) ->
if xhr.vote_type_id == 1
$(this).find('.upvote').addClass('vote-active')
else if xhr.vote_type_id == 2
$(this).find('.downvote').addClass('vote-active')
$(".vote-form").on 'ajax:error', (event, xhr, status) ->
#... | |
Add a spec about ignoredMessageTypes config | describe 'Linter Config', ->
linter = null
beforeEach ->
waitsForPromise ->
atom.packages.activatePackage('linter').then ->
linter = atom.packages.getActivePackage('linter').mainModule.instance
getLinter = ->
return {grammarScopes: ['*'], lintOnFly: false, modifiesBuffer: false, scope: 'pro... | |
Add script translate addresses in crash report into symbols. | #!/usr/bin/env coffee
# Usage:
# Copy the crash log into pasteboard and then run
# pbpaste | ./script/translate-crash-log-addresses.coffee
atos = (addresses, callback) ->
path = require 'path'
exec = require('child_process').exec
exec 'atos -o vendor/brightray/vendor/download/libchromiumcontent/Release/libchrom... | |
Copy over Coffee Cache from Atom | crypto = require 'crypto'
path = require 'path'
CoffeeScript = require 'coffee-script'
CSON = require 'season'
fs = require 'fs-plus'
cacheDir = path.join(fs.absolute('~/.atom'), 'compile-cache')
coffeeCacheDir = path.join(cacheDir, 'coffee')
CSON.setCacheDir(path.join(cacheDir, 'cson'))
getCachePath = (coffee) ->
... | |
Fix syntax error in on() method. | jQuery ->
$('.locales a:first').tab('show')
$('.accordion-body').on('hidden', ->
$(@).prev().find('i').first().removeClass().addClass('icon-chevron-right')
)
$('.accordion-body').on('shown', ->
$(@).prev().find('i').first().removeClass().addClass('icon-chevron-down'))
$('body').o... | jQuery ->
$('.locales a:first').tab('show')
$('.accordion-body').on('hidden', ->
$(@).prev().find('i').first().removeClass().addClass('icon-chevron-right')
)
$('.accordion-body').on('shown', ->
$(@).prev().find('i').first().removeClass().addClass('icon-chevron-down'))
$('.toggle-... |
Patch issue with dependency tracking in Chrome |
# Patch for this issue https://github.com/meteor/meteor/issues/4793
# Found here: https://github.com/meteor/meteor/issues/4793#issuecomment-129930335
#
# Fixes issue with dependencies invalidating on change in Chrome producing this error:
# TypeError: Cannot read property 'invalidate' of undefined
#
# Meteor core te... | |
Build GItHub API tags URL | ###
GitHub API
###
exports.api = ->
"#{PACKAGE.homepage
.replace /// // ///, '$&api.'
.replace /// \w/ ///, '$&repos/'
}/tags?per_page=8"
| |
Add projects definitions for atom | [
{
title: "Spyns"
group: "Development"
paths: [
"~/Development/spyns"
]
}
{
title: "CSI-702: Homework02 Instructor Attempt"
group: "Mason Fall 2017"
paths: [
"~/Documents/work/teaching/2017_Spring_Semester/CSI-702_High_Performance_Computing/assignments/homework02-instructo... | |
Allow user to be passed in | Backbone = require 'backbone'
Form = require '../../form/index.coffee'
CurrentUser = require '../../../models/current_user.coffee'
module.exports = class ContactView extends Backbone.View
className: 'scontact'
template: (->)
events:
'click button': 'submit'
initialize: ->
@user = CurrentUser.orNull(... | Backbone = require 'backbone'
Form = require '../../form/index.coffee'
CurrentUser = require '../../../models/current_user.coffee'
module.exports = class ContactView extends Backbone.View
className: 'scontact'
template: (->)
events:
'click button': 'submit'
initialize: (options = {}) ->
@user = opti... |
Add script to look up postgres sql statements | # Description:
# Strip help information from the Postgres web documentation.
# Example: hubot pgsql 9.0 select
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot pgsql <version> <sql>
#
# Author:
# mwongatemma
module.exports = (robot) ->
robot.respond /pgsql\s+(\d.\d)?\s+(.+)$/i, (m... | |
Clean up Webhook parse method | Collection = require './collection'
class Webhooks extends Collection
model: require '../models/Webhook'
url: "#{ env.SINGULARITY_BASE }/#{ constants.apiBase }/webhooks"
parse: (webhooks) =>
_.each webhooks, (webhook, i) =>
webhooks[i] = url: webhook
webhooks
comparator... | Collection = require './collection'
class Webhooks extends Collection
model: require '../models/Webhook'
url: "#{ env.SINGULARITY_BASE }/#{ constants.apiBase }/webhooks"
parse: (webhooks) => _.map webhooks, (webhook) -> url: webhook
comparator: 'url'
module.exports = Webhooks |
Test question component's model logic. | module 'Unit: components/question'
test 'its model will come from its tasks questions by ident', ->
q1 = Ember.Object.create(ident: "foo")
q2 = Ember.Object.create(ident: "bar")
task = Ember.Object.create(questions: [q1, q2])
component = ETahi.QuestionComponent.create(task: task, ident: "bar")
equal componen... | |
Add a test for the comparison function c255lbigintcmp | fs = require "fs"
env = do -> this
env.eval(fs.readFileSync("../curve255.js").toString())
stdout = process.stdout
stderr = process.stderr
write = (x) -> stdout.write x
echo = (x) -> write x + "\n"
fromHex = env.c255lhexdecode
toHex = env.c255lhexencode
hex2ibh = (x) ->
x = new Array(64 + 1 - x.length).... | |
Use simple JS menu to choose login portal. (missed one file in commit) | class LoginMenu
constructor: (@trigger=$('.login_portal_widget_toggle')) ->
@trigger = $('.login_portal_widget_toggle')
@menu = $('.login_portals_widget')
@register_handlers()
position_menu: () ->
o = @trigger.offset()
parent = @trigger.parent().parent()
po = parent.offset()
margin =... | |
Add requestId as a top-level attribute of an active task | Tasks = require './Tasks'
Task = require '../models/Task'
class TasksActive extends Tasks
model: Task
url: "#{ env.SINGULARITY_BASE }/#{ constants.apiBase }/tasks/active"
parse: (tasks) ->
_.each tasks, (task, i) =>
task.JSONString = utils.stringJSON task
task.id = task.t... | Tasks = require './Tasks'
Task = require '../models/Task'
class TasksActive extends Tasks
model: Task
url: "#{ env.SINGULARITY_BASE }/#{ constants.apiBase }/tasks/active"
parse: (tasks) ->
_.each tasks, (task, i) =>
task.JSONString = utils.stringJSON task
task.id = task.t... |
Add tests for the Letterclick app initializer. | #= require test_helper
suite 'Letterclick', ->
test 'exists in the global namespace', ->
expect(Letterclick.Models).to.be.an 'object'
test 'has namespaces', ->
expect(Letterclick.Models).to.be.an 'object'
expect(Letterclick.Collections).to.be.an 'object'
expect(Letterclick.Views).to.be.an 'object'... | |
Add missing spec for TypeError. | {TypeError} = require('../../src/finitio/errors')
should = require('should')
_ = require('underscore')
describe "TypeError", ->
error = new TypeError({
context: "{{x: Posint}}"
typeName: "Hobbies"
error: ["Invalid ${typeName}", [ "Relation" ]]
children: [
{
location: 1
context:... | |
Add current version of infinite-scroll script | angular.module('infinite-scroll', []).directive 'infiniteScroll', [->
link: (scope, elem, attrs) ->
$window = angular.element(window)
$document = angular.element(document)
# infinite-scroll-distance specifies how close to the bottom of the page
# the window is allowed to be before we trigger a new ... | |
Add service skeleton for handling session state on client | angular.module('kassa').service('SessionService',[
'$http'
'$q'
($http, $q)->
currentUser = null
setAuthenticated = (promise)-> promise.then (resp)-> currentUser = resp.data
checkStatus = -> setAuthenticated $http.get('/users/me')
signIn = (email, password)-> setAuthenticated $http.post('/se... | |
Use uniq to filter out dupes | _ = require 'underscore'
Backbone = require 'backbone'
module.exports = class Params extends Backbone.Model
urlWhitelist:[
'page'
'medium'
'color',
'price_range',
'width',
'height',
'gene_id',
'sort',
'major_periods',
'partner_cities'
]
defaults:
size: 50
page: 1
... | _ = require 'underscore'
Backbone = require 'backbone'
module.exports = class Params extends Backbone.Model
urlWhitelist:[
'page'
'medium'
'color',
'price_range',
'width',
'height',
'gene_id',
'sort',
'major_periods',
'partner_cities'
]
defaults:
size: 50
page: 1
... |
Add spec to validate invalid executable error message | #!/usr/bin/env coffee
#
# This spec file validates:
# * The atom-linter method used by linter-mypy.
# * Make sure that over time the behavior is as expected.
#
# If it fails:
# * Validate everywhere in the code where the problematic method is used and validate that linter-mypy still works.
{CompositeDisposable} ... | |
Update mobile logic to use new buy flow if lab feature enabled | Backbone = require 'backbone'
{ acquireArtwork } = require('../../../../components/acquire/view.coffee')
module.exports = class MetaDataView extends Backbone.View
events:
'click #artwork-page-edition-sets input[type=radio]': 'addEditionToOrder'
'click .js-purchase': 'buy'
initialize: ->
@editionSetId... | Backbone = require 'backbone'
CurrentUser = require '../../../../models/current_user.coffee'
{ createOrder } = require '../../../../../lib/components/create_order'
{ acquireArtwork } = require('../../../../components/acquire/view.coffee')
module.exports = class MetaDataView extends Backbone.View
events:
'click ... |
Add test coverage for kickoff class | chai = require('chai')
sinon = require("sinon")
sinonChai = require("sinon-chai")
chai.should()
chai.use(sinonChai)
Pioneer = require("../../lib/pioneer.js")
describe "Pioneer Kickoff File", ->
describe "isVersionRequested()", ->
it "should return true when --version is pas... | |
Move main_form function definitions out of nesting | if window.location.pathname.match(/\/apply$/)
$ ->
changeSection = ->
hash = window.location.hash
sectionId = hash.substring 1
$('.section').each ()->
section = $ @
if section.attr('id') is sectionId
section.toggleClass 'hide', false
else
section.togg... | changeSection = ->
hash = window.location.hash
sectionId = hash.substring 1
$('.section').each ()->
section = $ @
if section.attr('id') is sectionId
section.toggleClass 'hide', false
else
section.toggleClass 'hide', true
$('.wizard-nav a').each ()->
link = $ @
parent = link.paren... |
Add porojects, will need customizing | [
{
title: "Lloyd Flanagan Word Count"
group: "Atom"
paths: [
"/home/aflanagan/Devel/atom/lloyd-flanagan-word-count"
]
devMode: true
}
{
title: "Atom Configuration"
group: "Atom"
paths: [
"/home/aflanagan/Devel/atom/atom_configuration"
]
}
{
title: "Atom Utl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.