text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add new property to factory | import { Factory, faker } from 'ember-cli-mirage';
const REF_TIME = new Date();
export default Factory.extend({
name: '',
autoRevert: () => Math.random() > 0.5,
promoted: () => Math.random() > 0.5,
requireProgressBy: () => faker.date.past(0.5 / 365, REF_TIME),
desiredTotal: faker.random.number({ min: 1, max: 10 }),
desiredCanaries() {
return faker.random.number(Math.floor(this.desiredTotal / 2));
},
// PlacedCanaries is an array of allocation IDs. Since the IDs aren't currently
// used for associating allocations, any random value will do for now.
placedCanaries() {
return Array(faker.random.number(this.desiredCanaries))
.fill(null)
.map(() => faker.random.uuid());
},
placedAllocs() {
return faker.random.number(this.desiredTotal);
},
healthyAllocs() {
return faker.random.number(this.placedAllocs);
},
unhealthyAllocs() {
return this.placedAllocs - this.healthyAllocs;
},
});
| import { Factory, faker } from 'ember-cli-mirage';
export default Factory.extend({
name: '',
autoRevert: () => Math.random() > 0.5,
promoted: () => Math.random() > 0.5,
desiredTotal: faker.random.number({ min: 1, max: 10 }),
desiredCanaries() {
return faker.random.number(Math.floor(this.desiredTotal / 2));
},
// PlacedCanaries is an array of allocation IDs. Since the IDs aren't currently
// used for associating allocations, any random value will do for now.
placedCanaries() {
return Array(faker.random.number(this.desiredCanaries))
.fill(null)
.map(() => faker.random.uuid());
},
placedAllocs() {
return faker.random.number(this.desiredTotal);
},
healthyAllocs() {
return faker.random.number(this.placedAllocs);
},
unhealthyAllocs() {
return this.placedAllocs - this.healthyAllocs;
},
});
|
Remove exception in migration
Some users moved their data folder despite the code not permitting it yet.
This migration will fail for those users, but they will still be able to run
the app. | import sqlite3
from config import DATA_FOLDER
def migrate(database_path):
print "migrating to db version 2"
conn = sqlite3.connect(database_path)
conn.text_factory = str
cursor = conn.cursor()
# read hashmap from db
cursor.execute('''SELECT * FROM hashmap''')
mappings = cursor.fetchall()
for mapping in mappings:
if DATA_FOLDER in mapping[1]:
path = mapping[1][len(DATA_FOLDER):]
cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath)
VALUES (?,?)''', (mapping[0], path))
# update version
cursor.execute('''PRAGMA user_version = 2''')
conn.commit()
conn.close()
| import sqlite3
from config import DATA_FOLDER
def migrate(database_path):
print "migrating to db version 2"
conn = sqlite3.connect(database_path)
conn.text_factory = str
cursor = conn.cursor()
# read hashmap from db
cursor.execute('''SELECT * FROM hashmap''')
mappings = cursor.fetchall()
for mapping in mappings:
if DATA_FOLDER not in mapping[1]:
raise Exception("To complete migration 2 please run openbazaard at least once using the original "
"data folder location before moving it to a different location.")
path = mapping[1][len(DATA_FOLDER):]
cursor.execute('''INSERT OR REPLACE INTO hashmap(hash, filepath)
VALUES (?,?)''', (mapping[0], path))
# update version
cursor.execute('''PRAGMA user_version = 2''')
conn.commit()
conn.close()
|
Fix rate itunes not being hidden on production build (to be enabled later) | import Ember from 'ember';
import config from '../config/environment';
export default Ember.Controller.extend({
cordova: Ember.inject.service(),
subscriptions: Ember.inject.controller(),
config,
initSubscriptions: Ember.on('init', function() {
if (this.session.get("isLoggedIn")) {
this.send('setSubscriptions');
}
}),
supportGCLink: Ember.computed('session.language', function(){
return this.get('session.language') === 'zh-tw' ? "https://www.goodcity.hk/get_involved_zh.html" : "https://www.goodcity.hk/get_involved.html";
}),
appVersion: Ember.computed(function(){
return config.cordova.enabled ? config.APP.VERSION : null;
}),
actions: {
logMeOut() {
this.session.clear(); // this should be first since it updates isLoggedIn status
this.get('subscriptions').send('unwire');
this.get('subscriptions').send('unloadNotifications');
this.store.unloadAll();
var _this = this;
config.APP.PRELOAD_TYPES.forEach(function(type) {
_this.store.findAll(type);
});
this.transitionToRoute('login');
},
logMeIn() {
this.send('setSubscriptions');
},
setSubscriptions() {
this.get('subscriptions').send('wire');
}
}
});
| import Ember from 'ember';
import config from '../config/environment';
export default Ember.Controller.extend({
cordova: Ember.inject.service(),
subscriptions: Ember.inject.controller(),
initSubscriptions: Ember.on('init', function() {
if (this.session.get("isLoggedIn")) {
this.send('setSubscriptions');
}
}),
supportGCLink: Ember.computed('session.language', function(){
return this.get('session.language') === 'zh-tw' ? "https://www.goodcity.hk/get_involved_zh.html" : "https://www.goodcity.hk/get_involved.html";
}),
appVersion: Ember.computed(function(){
return config.cordova.enabled ? config.APP.VERSION : null;
}),
actions: {
logMeOut() {
this.session.clear(); // this should be first since it updates isLoggedIn status
this.get('subscriptions').send('unwire');
this.get('subscriptions').send('unloadNotifications');
this.store.unloadAll();
var _this = this;
config.APP.PRELOAD_TYPES.forEach(function(type) {
_this.store.findAll(type);
});
this.transitionToRoute('login');
},
logMeIn() {
this.send('setSubscriptions');
},
setSubscriptions() {
this.get('subscriptions').send('wire');
}
}
});
|
Make sure the verbosity stuff actually works | from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables
from daisyproducer.dictionary.models import Word
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = ''
help = 'Write Liblouis tables from the confirmed words in the dictionary'
def handle(self, *args, **options):
# write new global white lists
verbosity = int(options['verbosity'])
if verbosity >= 2:
self.stderr.write('Writing new global white lists...\n')
writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated'))
# update local tables
if verbosity >= 2:
self.stderr.write('Updating local tables...\n')
writeLocalTables(Document.objects.all())
| from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables
from daisyproducer.dictionary.models import Word
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = ''
help = 'Write Liblouis tables from the confirmed words in the dictionary'
def handle(self, *args, **options):
# write new global white lists
if options['verbosity'] >= 2:
self.stderr.write('Writing new global white lists...\n')
writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated'))
# update local tables
if options['verbosity'] >= 2:
self.stderr.write('Updating local tables...\n')
writeLocalTables(Document.objects.all())
|
Add a tripped message to the suspenders, but disable for now | from bluesky.suspenders import (SuspendFloor, SuspendBoolHigh, SuspendBoolLow)
from bluesky.global_state import get_gs
gs = get_gs()
RE = gs.RE
# Here are some conditions that will cause scans to pause automatically:
# - when the beam current goes below a certain threshold
susp_current = SuspendFloor(beamline_status.beam_current,
suspend_thresh=100.0,
resume_thresh=105.0,
tripped_message='beam current too low',
)
# - when the shutter is closed
susp_shutter = SuspendBoolLow(beamline_status.shutter_status,
tripped_message='shutter not open',
)
# - if the beamline isn't enabled
susp_enabled = SuspendBoolLow(beamline_status.beamline_enabled,
tripped_message='beamline is not enabled',
)
# Install all suspenders:
# RE.install_suspender(susp_current)
# RE.install_suspender(susp_shutter)
# RE.install_suspender(susp_enabled)
| from bluesky.suspenders import (SuspendFloor, SuspendBoolHigh, SuspendBoolLow)
from bluesky.global_state import get_gs
gs = get_gs()
RE = gs.RE
# Here are some conditions that will cause scans to pause automatically:
# - when the beam current goes below a certain threshold
susp_current = SuspendFloor(beamline_status.beam_current,
suspend_thresh=100.0,
resume_thresh=105.0,
# message='beam current too low',
)
# RE.install_suspender(susp_current)
# - when the shutter is closed
susp_shutter = SuspendBoolLow(beamline_status.shutter_status,
# message='shutter not open',
)
# RE.install_suspender(susp_shutter)
# - if the beamline isn't enabled
susp_enabled = SuspendBoolLow(beamline_status.beamline_enabled,
# message='beamline is not enabled',
)
# RE.install_suspender(susp_enabled)
|
Make windows bigger in this test so the captions can be read.
Index: tests/window/WINDOW_CAPTION.py
===================================================================
--- tests/window/WINDOW_CAPTION.py (revision 777)
+++ tests/window/WINDOW_CAPTION.py (working copy)
@@ -19,8 +19,8 @@
class WINDOW_CAPTION(unittest.TestCase):
def test_caption(self):
- w1 = window.Window(200, 200)
- w2 = window.Window(200, 200)
+ w1 = window.Window(400, 200, resizable=True)
+ w2 = window.Window(400, 200, resizable=True)
count = 1
w1.set_caption('Window caption %d' % count)
w2.set_caption(u'\u00bfHabla espa\u00f1ol?') | #!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import time
import unittest
from pyglet import window
class WINDOW_CAPTION(unittest.TestCase):
def test_caption(self):
w1 = window.Window(400, 200, resizable=True)
w2 = window.Window(400, 200, resizable=True)
count = 1
w1.set_caption('Window caption %d' % count)
w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
last_time = time.time()
while not (w1.has_exit or w2.has_exit):
if time.time() - last_time > 1:
count += 1
w1.set_caption('Window caption %d' % count)
last_time = time.time()
w1.dispatch_events()
w2.dispatch_events()
w1.close()
w2.close()
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import time
import unittest
from pyglet import window
class WINDOW_CAPTION(unittest.TestCase):
def test_caption(self):
w1 = window.Window(200, 200)
w2 = window.Window(200, 200)
count = 1
w1.set_caption('Window caption %d' % count)
w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
last_time = time.time()
while not (w1.has_exit or w2.has_exit):
if time.time() - last_time > 1:
count += 1
w1.set_caption('Window caption %d' % count)
last_time = time.time()
w1.dispatch_events()
w2.dispatch_events()
w1.close()
w2.close()
if __name__ == '__main__':
unittest.main()
|
Add new colors to the palette | const colors = {
main: '#023365',
background: '#EEF1F4',
positive: '#009933',
warm: '#990033',
facebook: '#3b5998',
transparent: 'rgba(0,0,0,0)',
silver: '#F7F7F7',
steel: '#CCCCCC',
error: 'rgba(200, 0, 0, 0.8)',
ricePaper: 'rgba(255,255,255, 0.75)',
frost: '#D8D8D8',
cloud: 'rgba(200,200,200, 0.35)',
windowTint: 'rgba(0, 0, 0, 0.2)',
panther: '#161616',
charcoal: '#595959',
coal: '#2d2d2d',
bloodOrange: '#fb5f26',
snow: 'white',
ember: 'rgba(164, 0, 48, 0.5)',
fire: '#e73536',
};
export default colors;
| const colors = {
main: '#023365',
background: '#EEF1F4',
clear: 'rgba(0,0,0,0)',
facebook: '#3b5998',
transparent: 'rgba(0,0,0,0)',
silver: '#F7F7F7',
steel: '#CCCCCC',
error: 'rgba(200, 0, 0, 0.8)',
ricePaper: 'rgba(255,255,255, 0.75)',
frost: '#D8D8D8',
cloud: 'rgba(200,200,200, 0.35)',
windowTint: 'rgba(0, 0, 0, 0.2)',
panther: '#161616',
charcoal: '#595959',
coal: '#2d2d2d',
bloodOrange: '#fb5f26',
snow: 'white',
ember: 'rgba(164, 0, 48, 0.5)',
fire: '#e73536',
drawer: 'rgba(30, 30, 29, 0.95)'
};
export default colors;
|
Optimize with micromatch.matcher when possible | 'use strict';
var micromatch = require('micromatch');
var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) {
if (!Array.isArray(criteria)) { criteria = [criteria]; }
if (arguments.length === 1) {
return criteria.length === 1 ?
micromatch.matcher(criteria[0]) : anymatch.bind(null, criteria);
}
var string = Array.isArray(value) ? value[0] : value;
if (!startIndex) { startIndex = 0; }
var matchIndex = -1;
function testCriteria (criterion, index) {
var result;
switch (toString.call(criterion)) {
case '[object String]':
result = string === criterion || micromatch.isMatch(string, criterion);
break;
case '[object RegExp]':
result = criterion.test(string);
break;
case '[object Function]':
result = criterion.apply(null, Array.isArray(value) ? value : [value]);
break;
default:
result = false;
}
if (result) { matchIndex = index + startIndex; }
return result;
}
var matched = criteria.slice(startIndex, endIndex).some(testCriteria);
return returnIndex === true ? matchIndex : matched;
};
module.exports = anymatch;
| 'use strict';
var micromatch = require('micromatch');
var anymatch = function(criteria, value, returnIndex, startIndex, endIndex) {
if (!Array.isArray(criteria)) { criteria = [criteria]; }
if (arguments.length === 1) { return anymatch.bind(null, criteria); }
var string = Array.isArray(value) ? value[0] : value;
if (!startIndex) { startIndex = 0; }
var matchIndex = -1;
function testCriteria (criterion, index) {
var result;
switch (toString.call(criterion)) {
case '[object String]':
result = string === criterion || micromatch.isMatch(string, criterion);
break;
case '[object RegExp]':
result = criterion.test(string);
break;
case '[object Function]':
result = criterion.apply(null, Array.isArray(value) ? value : [value]);
break;
default:
result = false;
}
if (result) { matchIndex = index + startIndex; }
return result;
}
var matched = criteria.slice(startIndex, endIndex).some(testCriteria);
return returnIndex === true ? matchIndex : matched;
};
module.exports = anymatch;
|
Fix problem running glance --version
__version__ should point to a string and not VersionInfo
Fixes LP# 1164760
Change-Id: I27d366af5ed89d0931ef46eb1507e6ba0eec0b6e | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# 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.
#NOTE(bcwaldon): this try/except block is needed to run setup.py due to
# its need to import local code before installing required dependencies
try:
import glanceclient.client
Client = glanceclient.client.Client
except ImportError:
import warnings
warnings.warn("Could not import glanceclient.client", ImportWarning)
from glanceclient.openstack.common import version as common_version
#__version__ = common_version.VersionInfo('python-glanceclient')
version_info = common_version.VersionInfo('python-glanceclient')
try:
__version__ = version_info.version_string()
except AttributeError:
__version__ = None
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# 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.
#NOTE(bcwaldon): this try/except block is needed to run setup.py due to
# its need to import local code before installing required dependencies
try:
import glanceclient.client
Client = glanceclient.client.Client
except ImportError:
import warnings
warnings.warn("Could not import glanceclient.client", ImportWarning)
from glanceclient.openstack.common import version as common_version
__version__ = common_version.VersionInfo('python-glanceclient')
|
Use verbose name for FormSubmissionsPanel heading | from __future__ import absolute_import, unicode_literals
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from wagtail.wagtailadmin.edit_handlers import EditHandler
class BaseFormSubmissionsPanel(EditHandler):
template = "wagtailforms/edit_handlers/form_responses_panel.html"
def render(self):
from .models import FormSubmission
submissions = FormSubmission.objects.filter(page=self.instance)
if not submissions:
return ''
return mark_safe(render_to_string(self.template, {
'self': self,
'submissions': submissions
}))
class FormSubmissionsPanel(object):
def __init__(self, heading=None):
self.heading = heading
def bind_to_model(self, model):
heading = _('{} submissions').format(model.get_verbose_name())
return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), {
'model': model,
'heading': self.heading or heading,
})
| from __future__ import absolute_import, unicode_literals
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from wagtail.wagtailadmin.edit_handlers import EditHandler
class BaseFormSubmissionsPanel(EditHandler):
template = "wagtailforms/edit_handlers/form_responses_panel.html"
def render(self):
from .models import FormSubmission
submissions = FormSubmission.objects.filter(page=self.instance)
if not submissions:
return ''
return mark_safe(render_to_string(self.template, {
'self': self,
'submissions': submissions
}))
class FormSubmissionsPanel(object):
def __init__(self, heading=None):
self.heading = heading
def bind_to_model(self, model):
heading = _('{} submissions').format(model._meta.model_name)
return type(str('_FormResponsesPanel'), (BaseFormSubmissionsPanel,), {
'model': model,
'heading': self.heading or heading,
})
|
Add a test to check that authentication using the token directly works | from rocketchat_API.rocketchat import RocketChat
def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
def test_login_token(logged_rocket):
user_id = logged_rocket.headers["X-User-Id"]
auth_token = logged_rocket.headers["X-Auth-Token"]
another_rocket = RocketChat(user_id=user_id, auth_token=auth_token)
logged_user = another_rocket.me().json()
assert logged_user.get("_id") == user_id
| def test_info(logged_rocket):
info = logged_rocket.info().json()
assert "info" in info
assert info.get("success")
def test_statistics(logged_rocket):
statistics = logged_rocket.statistics().json()
assert statistics.get("success")
def test_statistics_list(logged_rocket):
statistics_list = logged_rocket.statistics_list().json()
assert statistics_list.get("success")
def test_directory(logged_rocket):
directory = logged_rocket.directory(
query={"text": "rocket", "type": "users"}
).json()
assert directory.get("success")
def test_spotlight(logged_rocket):
spotlight = logged_rocket.spotlight(query="user1").json()
assert spotlight.get("success")
assert spotlight.get("users") is not None, "No users list found"
assert spotlight.get("rooms") is not None, "No rooms list found"
|
Fix adapter endpoint (pantheon changed their urls…) | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
wordpressHost: 'http://dev-ember-wordpress.pantheonsite.io'
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
wordpressHost: 'http://dev-ember-wordpress.pantheon.io'
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
Return the SQL we've just tried to run | """
APIs exposed by pubsubpull.
"""
from __future__ import absolute_import
from async.api import schedule
from django.db import connection
from pubsubpull import _join_with_project_path
def add_trigger_function():
"""Used for older versions of Postres, or test runs where there are no
migrations.
"""
cursor = connection.cursor()
sql = file(_join_with_project_path("trigger-function.sql")).read()
cursor.execute(sql)
def change_detect(model):
"""Enable change detection on the requested model.
"""
cursor = connection.cursor()
sql = file(_join_with_project_path("trigger-attach.sql")).read()
sql = sql.format(db_table=model._meta.db_table)
cursor.execute(sql)
return sql
def pull(model, callback, **kwargs):
"""Start a job pulling data from one service to this one.
"""
schedule('pubsubpull.async.pull_monitor',
args=[model, callback], kwargs=kwargs)
| """
APIs exposed by pubsubpull.
"""
from __future__ import absolute_import
from async.api import schedule
from django.db import connection
from pubsubpull import _join_with_project_path
def add_trigger_function():
"""Used for older versions of Postres, or test runs where there are no
migrations.
"""
cursor = connection.cursor()
sql = file(_join_with_project_path("trigger-function.sql")).read()
cursor.execute(sql)
def change_detect(model):
"""Enable change detection on the requested model.
"""
cursor = connection.cursor()
sql = file(_join_with_project_path("trigger-attach.sql")).read()
sql = sql.format(db_table=model._meta.db_table)
cursor.execute(sql)
def pull(model, callback, **kwargs):
"""Start a job pulling data from one service to this one.
"""
schedule('pubsubpull.async.pull_monitor',
args=[model, callback], kwargs=kwargs)
|
Update HTTP 406 view to display exception message
The exception message will contain the list of content types that are accepted/supported by the back-end.
This commit also fixes a typo. | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Non-acceptable request</title>
<style>
/* Create a small Belgian flag at the top of the page. */
html:before {
content: '';
display: block;
height: 3px;
background-image: linear-gradient(
to right,
#000, #000 33%,
#ffe936 33%, #ffe936 66%,
#ff0f21 66%, #ff0f21
);
box-shadow: 0 1px 5px rgba(0,0,0,.15);
}
body {
margin: 2em;
background-color: #fff;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #333;
}
</style>
</head>
<body>
<p>The resource you are looking for cannot be provided in any of the formats you accept.</p>
<p>{{ $exception->getMessage() }}</p>
</body>
</html>
| <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Non-acceptable request</title>
<style>
/* Create a small Belgian flag at the top of the page. */
html:before {
content: '';
display: block;
height: 3px;
background-image: linear-gradient(
to right,
#000, #000 33%,
#ffe936 33%, #ffe936 66%,
#ff0f21 66%, #ff0f21
);
box-shadow: 0 1px 5px rgba(0,0,0,.15);
}
body {
margin: 2em;
background-color: #fff;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #333;
}
</style>
</head>
<body>
<p>The resource you are looking cannot be provided in any of the formats you accept.</p>
</body>
</html>
|
Add Laws and Policies to country sections routes | import { createElement } from 'react';
import GHGCountryEmissions from 'components/country/country-ghg';
import NDCSDGLinkages from 'components/country/country-ndc-sdg-linkages';
import ClimateVulnerability from 'components/country/country-climate-vulnerability';
import CountryNdcOverview from 'components/country/country-ndc-overview';
import LawsAndPolicies from 'components/country/laws-and-policies';
export default [
{
hash: 'ghg-emissions',
label: 'GHG Emissions',
anchor: true,
component: GHGCountryEmissions
},
{
hash: 'climate-vulnerability',
label: 'Climate Vulnerability and Readiness',
anchor: true,
component: ClimateVulnerability
},
{
hash: 'ndc-content-overview',
label: 'NDC Content Overview',
anchor: true,
component: () => createElement(CountryNdcOverview, { actions: true })
},
{
hash: 'ndc-sdg-linkages',
label: 'NDC-SDG Linkages',
anchor: true,
component: NDCSDGLinkages
},
{
hash: 'laws-and-policies',
label: 'Laws and Policies',
anchor: true,
component: LawsAndPolicies
}
];
| import { createElement } from 'react';
import GHGCountryEmissions from 'components/country/country-ghg';
import NDCSDGLinkages from 'components/country/country-ndc-sdg-linkages';
import ClimateVulnerability from 'components/country/country-climate-vulnerability';
import CountryNdcOverview from 'components/country/country-ndc-overview';
export default [
{
hash: 'ghg-emissions',
label: 'GHG Emissions',
anchor: true,
component: GHGCountryEmissions
},
{
hash: 'climate-vulnerability',
label: 'Climate Vulnerability and Readiness',
anchor: true,
component: ClimateVulnerability
},
{
hash: 'ndc-content-overview',
label: 'NDC Content Overview',
anchor: true,
component: () => createElement(CountryNdcOverview, { actions: true })
},
{
hash: 'ndc-sdg-linkages',
label: 'NDC-SDG Linkages',
anchor: true,
component: NDCSDGLinkages
}
];
|
Use external window for tumlr share | ((window, document) => {
const encode = window.encodeURIComponent;
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
const url = ((t=$("link[rel=canonical]")) && t.href)
|| ((t=$('meta[property="og:url"],meta[property="twitter:url"]')) && t.content)
|| location.href;
const title = document.title;
const q = {
url: encode(url),
caption: encode(`<a href="${url}">${title}</a>`),
};
// extract imgage
// twitter
const query = "#permalink-overlay [data-element-context='platform_photo_card'] img";
const imgs = Array.from($$(query))
.map(i => i.src + ":orig");
if (imgs.length !== 0) {
q.posttype = "photo";
q.content = imgs.map(encode).join(",");
}
const tumblr = 'https://www.tumblr.com/widgets/share/tool?'
+Object.entries(q).map(e => e.join("=")).join("&");
const height = screen && screen.height || 600;
window.open(tumblr, null, `height=${height},width=540`);
})(window, document);
| ((window, document) => {
const encode = window.encodeURIComponent;
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
const url = ((t=$("link[rel=canonical]")) && t.href)
|| ((t=$('meta[property="og:url"],meta[property="twitter:url"]')) && t.content)
|| location.href;
const title = document.title;
const q = {
url: encode(url),
caption: encode(`<a href="${url}">${title}</a>`),
};
// extract imgage
// twitter
const query = "#permalink-overlay [data-element-context='platform_photo_card'] img";
const imgs = Array.from($$(query))
.map(i => i.src + ":orig");
if (imgs.length !== 0) {
q.posttype = "photo";
q.content = imgs.map(encode).join(",");
}
window.open('https://www.tumblr.com/widgets/share/tool?'+Object.entries(q).map(e => e.join("=")).join("&"),
'_blank');
})(window, document);
|
Fix example test--map iteration not ordered | package entrevista_test
import (
"fmt"
"github.com/hoop33/entrevista"
)
func Example() {
interview := entrevista.NewInterview()
interview.ReadAnswer = func(question *entrevista.Question) (string, error) {
return question.Key, nil
}
interview.Questions = []entrevista.Question{
{
Key: "name",
Text: "Enter your name",
Required: true,
},
{
Key: "email",
Text: "Enter your email address",
DefaultAnswer: "john.doe@example.com",
},
}
answers, err := interview.Run()
if err == nil {
fmt.Print(answers["name"], ",", answers["email"])
} else {
fmt.Print(err.Error())
}
// Output: Enter your name: Enter your email address (john.doe@example.com): name,email
}
| package entrevista_test
import (
"fmt"
"github.com/hoop33/entrevista"
)
func Example() {
interview := entrevista.NewInterview()
interview.ReadAnswer = func(question *entrevista.Question) (string, error) {
return question.Key, nil
}
interview.Questions = []entrevista.Question{
{
Key: "name",
Text: "Enter your name",
Required: true,
},
{
Key: "email",
Text: "Enter your email address",
DefaultAnswer: "john.doe@example.com",
},
}
answers, err := interview.Run()
if err == nil {
for key, answer := range answers {
fmt.Print(key, ":", answer, ";")
}
} else {
fmt.Print(err.Error())
}
// Output: Enter your name: Enter your email address (john.doe@example.com): name:name;email:email;
}
|
[Tests] Move Bolt\Mapping to Bolt\Storage\Mapping namespace | <?php
namespace Bolt\Tests\Mapping;
use Bolt\Storage\Mapping\MetadataDriver;
use Bolt\Tests\BoltUnitTest;
/**
* Class to test src/Mapping/MetadataDriver.
*
* @author Ross Riley <riley.ross@gmail.com>
*/
class MetadataDriverTest extends BoltUnitTest
{
public function testConstruct()
{
$app = $this->getApp();
$map = new MetadataDriver($app['schema'], $app['config']->get('contenttypes'), $app['config']->get('taxonomy'), $app['storage.typemap']);
$this->assertSame($app['schema'], \PHPUnit_Framework_Assert::readAttribute($map, 'schemaManager'));
}
public function testInitialize()
{
$app = $this->getApp();
$map = new MetadataDriver($app['schema'], $app['config']->get('contenttypes'), $app['config']->get('taxonomy'), $app['storage.typemap']);
$map->initialize();
$metadata = $map->loadMetadataForClass('Bolt\Storage\Entity\Users');
$this->assertNotNull($metadata);
$this->assertEquals('bolt_users', $metadata->getTableName());
$field = $metadata->getFieldMapping('id');
$this->assertEquals('id', $field['fieldname']);
}
}
| <?php
namespace Bolt\Tests\Mapping;
use Bolt\Mapping\MetadataDriver;
use Bolt\Tests\BoltUnitTest;
/**
* Class to test src/Mapping/MetadataDriver.
*
* @author Ross Riley <riley.ross@gmail.com>
*/
class MetadataDriverTest extends BoltUnitTest
{
public function testConstruct()
{
$app = $this->getApp();
$map = new MetadataDriver($app['schema'], $app['config']->get('contenttypes'), $app['config']->get('taxonomy'), $app['storage.typemap']);
$this->assertSame($app['schema'], \PHPUnit_Framework_Assert::readAttribute($map, 'schemaManager'));
}
public function testInitialize()
{
$app = $this->getApp();
$map = new MetadataDriver($app['schema'], $app['config']->get('contenttypes'), $app['config']->get('taxonomy'), $app['storage.typemap']);
$map->initialize();
$metadata = $map->loadMetadataForClass('Bolt\Storage\Entity\Users');
$this->assertNotNull($metadata);
$this->assertEquals('bolt_users', $metadata->getTableName());
$field = $metadata->getFieldMapping('id');
$this->assertEquals('id', $field['fieldname']);
}
}
|
Misc: Update plugin version to 0.27 | <?php
/*
* Plugin Name: Hyyan WooCommerce Polylang Integration
* Plugin URI: https://github.com/hyyan/woo-poly-integration/
* Description: Integrates Woocommerce with Polylang
* Author: Hyyan Abo Fakher
* Author URI: https://github.com/hyyan
* Text Domain: woo-poly-integration
* Domain Path: /languages
* GitHub Plugin URI: hyyan/woo-poly-integration
* License: MIT License
* Version: 0.27
*/
/**
* This file is part of the hyyan/woo-poly-integration plugin.
* (c) Hyyan Abo Fakher <tiribthea4hyyan@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (!defined('ABSPATH')) {
exit('restricted access');
}
define('Hyyan_WPI_DIR', __FILE__);
define('Hyyan_WPI_URL', plugin_dir_url(__FILE__));
require_once ABSPATH . 'wp-admin/includes/plugin.php';
require_once __DIR__ . '/vendor/class.settings-api.php';
require_once __DIR__ . '/src/Hyyan/WPI/Autoloader.php';
/* register the autoloader */
new Hyyan\WPI\Autoloader(__DIR__ . '/src/');
/* bootstrap the plugin */
new Hyyan\WPI\Plugin();
| <?php
/*
* Plugin Name: Hyyan WooCommerce Polylang Integration
* Plugin URI: https://github.com/hyyan/woo-poly-integration/
* Description: Integrates Woocommerce with Polylang
* Author: Hyyan Abo Fakher
* Author URI: https://github.com/hyyan
* Text Domain: woo-poly-integration
* Domain Path: /languages
* GitHub Plugin URI: hyyan/woo-poly-integration
* License: MIT License
* Version: 0.26.2 (Not Released)
*/
/**
* This file is part of the hyyan/woo-poly-integration plugin.
* (c) Hyyan Abo Fakher <tiribthea4hyyan@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (!defined('ABSPATH')) {
exit('restricted access');
}
define('Hyyan_WPI_DIR', __FILE__);
define('Hyyan_WPI_URL', plugin_dir_url(__FILE__));
require_once ABSPATH . 'wp-admin/includes/plugin.php';
require_once __DIR__ . '/vendor/class.settings-api.php';
require_once __DIR__ . '/src/Hyyan/WPI/Autoloader.php';
/* register the autoloader */
new Hyyan\WPI\Autoloader(__DIR__ . '/src/');
/* bootstrap the plugin */
new Hyyan\WPI\Plugin();
|
Update self-test for new text for meteor remove-platform | var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
var files = require('../files.js');
selftest.define("add cordova platforms", function () {
var s = new Sandbox();
var run;
// Starting a run
s.createApp("myapp", "package-tests");
s.cd("myapp");
s.set("METEOR_TEST_TMP", files.mkdtemp());
run = s.run("run", "android");
run.matchErr("Platform is not added");
run.match("meteor add-platform android");
run.expectExit(1);
// XXX: This prints the Android EULA.
// We should move this to a once-per-machine agreement.
/*
run = s.run("add-platform", "android");
run.matchErr("Platform is not installed");
run.expectExit(2);
*/
run = s.run("install-sdk", "android");
run.extraTime = 90; // Big downloads
run.expectExit(0);
run = s.run("add-platform", "android");
run.match("Do you agree");
run.write("Y\n");
run.extraTime = 90; // Huge download
run.match("added");
run = s.run("remove-platform", "foo");
run.match("foo: platform is not");
run = s.run("remove-platform", "android");
run.match("removed");
run = s.run("run", "android");
run.matchErr("Platform is not added");
run.match("meteor add-platform android");
run.expectExit(1);
});
| var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
var files = require('../files.js');
selftest.define("add cordova platforms", function () {
var s = new Sandbox();
var run;
// Starting a run
s.createApp("myapp", "package-tests");
s.cd("myapp");
s.set("METEOR_TEST_TMP", files.mkdtemp());
run = s.run("run", "android");
run.matchErr("Platform is not added");
run.match("meteor add-platform android");
run.expectExit(1);
// XXX: This prints the Android EULA.
// We should move this to a once-per-machine agreement.
/*
run = s.run("add-platform", "android");
run.matchErr("Platform is not installed");
run.expectExit(2);
*/
run = s.run("install-sdk", "android");
run.extraTime = 90; // Big downloads
run.expectExit(0);
run = s.run("add-platform", "android");
run.match("Do you agree");
run.write("Y\n");
run.extraTime = 90; // Huge download
run.match("added");
run = s.run("remove-platform", "foo");
run.match("foo is not");
run = s.run("remove-platform", "android");
run.match("removed");
run = s.run("run", "android");
run.matchErr("Platform is not added");
run.match("meteor add-platform android");
run.expectExit(1);
});
|
Throw exception on Elasticsearch update error
This isn't ideal because we use the bulk update API, so some of the
bulk items can succeed, while other fail. In an ideal situation, we
would requeue only the items that failed, and allow the bulk process
to continue. We aren't quite there yet, so this is a good stopgap.
We are ready to survey these exceptions via Sentry. | <?php
namespace App;
use ScoutEngines\Elasticsearch\ElasticsearchEngine as BaseEngine;
class ElasticsearchEngine extends BaseEngine
{
/**
* Update the given model in the index.
*
* @param Collection $models
* @return void
*/
public function update($models)
{
$params['body'] = [];
$models->each(function($model) use (&$params)
{
$params['body'][] = [
'update' => $this->getIdIndexType($model)
];
$params['body'][] = [
'doc' => $model->toSearchableArray(),
'doc_as_upsert' => true
];
});
$result = $this->elastic->bulk($params);
// TODO: Requeue only the models that failed?
if (isset($result['errors']) && $result['errors'] === true)
{
throw new \Exception(json_encode($result));
}
}
}
| <?php
namespace App;
use ScoutEngines\Elasticsearch\ElasticsearchEngine as BaseEngine;
class ElasticsearchEngine extends BaseEngine
{
/**
* Update the given model in the index.
*
* @param Collection $models
* @return void
*/
public function update($models)
{
$params['body'] = [];
$models->each(function($model) use (&$params)
{
$params['body'][] = [
'update' => $this->getIdIndexType($model)
];
$params['body'][] = [
'doc' => $model->toSearchableArray(),
'doc_as_upsert' => true
];
});
// dd( $params );
$result = $this->elastic->bulk($params);
// Unfortunately, we aren't quite ready to handle these exceptions.
// if (isset($result['errors']) === true && $result['errors'] === true)
// {
// throw new \Exception(json_encode($result));
// }
}
}
|
Make reference input use new Sanity client syntax | import client from 'client:@sanity/base/client'
import {ReferenceInput} from 'role:@sanity/form-builder'
import {unprefixType} from '../utils/unprefixType'
function fetchSingle(id) {
return client.data.getDocument(id).then(doc => unprefixType(doc))
}
export default ReferenceInput.createBrowser({
fetch(field) {
const toFieldTypes = field.to.map(toField => toField.type)
const dataset = client.config().dataset
const params = toFieldTypes.reduce((acc, toFieldType, i) => {
acc[`toFieldType${i}`] = `${dataset}.${toFieldType}`
return acc
}, {})
const eqls = Object.keys(params).map(key => (
`.$type == %${key}`
)).join(' || ')
return client.data.fetch(`*[${eqls}]`, params)
.then(response => response.map(unprefixType))
},
materializeReferences(referenceIds) {
return Promise.all(referenceIds.map(fetchSingle))
}
})
| import {ReferenceInput} from 'role:@sanity/form-builder'
import client from 'client:@sanity/base/client'
import {unprefixType} from '../utils/unprefixType'
function fetchSingle(id) {
return client.fetch('*[.$id == %id]', {id}).then(response => unprefixType(response.result[0]))
}
export default ReferenceInput.createBrowser({
fetch(field) {
const toFieldTypes = field.to.map(toField => toField.type)
const params = toFieldTypes.reduce((acc, toFieldType, i) => {
acc[`toFieldType${i}`] = `beerfiesta.${toFieldType}`
return acc
}, {})
const eqls = Object.keys(params).map(key => (
`.$type == %${key}`
)).join(' || ')
return client.fetch(`*[${eqls}]`, params)
.then(response => response.result.map(unprefixType))
},
materializeReferences(referenceIds) {
return Promise.all(referenceIds.map(fetchSingle))
}
})
|
Create spot along with user | const bcrypt = require('bcrypt');
const GitHub = require('github-api');
const crypto = require('crypto');
const { Spot, User } = require('../models');
const { email } = require('../utils');
const GITHUB_API_TOKEN = process.env.GITHUB_TOKEN;
const GITHUB_GIST_ID = process.env.GITHUB_GIST_ID;
// Authenticate using a GitHub Token
const ghClient = new GitHub({
token: GITHUB_API_TOKEN
});
const userGist = ghClient.getGist(GITHUB_GIST_ID);
userGist.read((err, gist) => {
if (err) {
console.error(err);
return;
}
JSON.parse(gist['files']['users.json']['content']).forEach((user) => { // eslint-disable-line dot-notation
const current_date = (new Date()).valueOf().toString();
const random = Math.random().toString();
const password = crypto.createHmac('sha1', current_date).update(random).digest('hex');
user.password = bcrypt.hashSync(password, bcrypt.genSaltSync(1)); // eslint-disable-line no-sync
return Spot.create(user.spotId)
.then(() => User.create(user.name, user.nameNumber, user.instrument, user.part, user.role, user.spotId, user.email, user.password))
.then(() => {
email.sendUserCreateEmail(user.email, user.nameNumber, password);
return;
})
.catch((err) => {
console.error(err);
console.log(user);
});
});
});
| const bcrypt = require('bcrypt');
const GitHub = require('github-api');
const crypto = require('crypto');
const { User } = require('../models');
const { email } = require('../utils');
const GITHUB_API_TOKEN = process.env.GITHUB_TOKEN;
const GITHUB_GIST_ID = process.env.GITHUB_GIST_ID;
// Authenticate using a GitHub Token
const ghClient = new GitHub({
token: GITHUB_API_TOKEN
});
const userGist = ghClient.getGist(GITHUB_GIST_ID);
userGist.read((err, gist) => {
if (err) {
console.error(err);
return;
}
JSON.parse(gist['files']['users.json']['content']).forEach((user) => { // eslint-disable-line dot-notation
const current_date = (new Date()).valueOf().toString();
const random = Math.random().toString();
const password = crypto.createHmac('sha1', current_date).update(random).digest('hex');
user.password = bcrypt.hashSync(password, bcrypt.genSaltSync(1)); // eslint-disable-line no-sync
return User.create(user.name, user.nameNumber, user.instrument, user.part, user.role, user.spotId, user.email, user.password)
.then(() => {
email.sendUserCreateEmail(user.email, user.nameNumber, password);
return;
})
.catch(console.error);
});
});
|
Remove dependency on KnowledgeGraph object. | <?php
namespace actsmart\actsmart\Interpreters\KnowledgeGraph\DGraph;
use actsmart\actsmart\Interpreters\KnowledgeGraph\KnowledgeGraphInterpreter;
use actsmart\actsmart\Interpreters\KnowledgeGraph\KnowledgeGraphObject;
use actsmart\actsmart\Interpreters\NLP\NLPAnalysis;
use actsmart\actsmart\Utils\ComponentInterface;
use actsmart\actsmart\Utils\ComponentTrait;
use actsmart\actsmart\Utils\DGraph\DGraphClient;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
abstract class DGraphInterpreter implements KnowledgeGraphInterpreter, ComponentInterface, LoggerAwareInterface
{
use ComponentTrait, LoggerAwareTrait;
protected $dGraphClient;
public function __construct(DGraphClient $dGraphclient) {
$this->dGraphClient = $dGraphclient;
}
public abstract function analyse(NLPAnalysis $analysis);
} | <?php
namespace actsmart\actsmart\Interpreters\KnowledgeGraph\DGraph;
use actsmart\actsmart\Interpreters\KnowledgeGraph\KnowledgeGraphInterpreter;
use actsmart\actsmart\Interpreters\KnowledgeGraph\KnowledgeGraphObject;
use actsmart\actsmart\Interpreters\NLP\NLPAnalysis;
use actsmart\actsmart\Utils\ComponentInterface;
use actsmart\actsmart\Utils\ComponentTrait;
use actsmart\actsmart\Utils\DGraph\DGraphClient;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
abstract class DGraphInterpreter implements KnowledgeGraphInterpreter, ComponentInterface, LoggerAwareInterface
{
use ComponentTrait, LoggerAwareTrait;
protected $dGraphClient;
public function __construct(DGraphClient $dGraphclient) {
$this->dGraphClient = $dGraphclient;
}
public abstract function analyse(NLPAnalysis $analysis) : KnowledgeGraphObject;
} |
Fix new line on while and for statements. | <?php
namespace Vinkla\Base62;
class Base62
{
/**
* The base string.
*
* @var string
*/
protected $base;
/**
* @param $base
*/
function __construct($base)
{
$this->base = $base;
}
/**
* Decode a string to a integer.
*
* @param string $value
* @param int $b
* @return int
*/
public function decode($value, $b = 62)
{
$limit = strlen($value);
$result = strpos($this->base, $value[0]);
for ($i = 1; $i < $limit; $i++) {
$result = $b * $result + strpos($this->base, $value[$i]);
}
return $result;
}
/**
* Encode an integer to a string.
*
* @param int $value
* @param int $b
* @return string
*/
public function encode($value, $b = 62)
{
$r = (int) $value % $b;
$result = $this->base[$r];
$q = floor((int) $value / $b);
while ($q) {
$r = $q % $b;
$q = floor($q / $b);
$result = $this->base[$r] . $result;
}
return $result;
}
}
| <?php
namespace Vinkla\Base62;
class Base62
{
/**
* The base string.
*
* @var string
*/
protected $base;
/**
* @param $base
*/
function __construct($base)
{
$this->base = $base;
}
/**
* Decode a string to a integer.
*
* @param string $value
* @param int $b
* @return int
*/
public function decode($value, $b = 62)
{
$limit = strlen($value);
$result = strpos($this->base, $value[0]);
for ($i = 1; $i < $limit; $i++)
{
$result = $b * $result + strpos($this->base, $value[$i]);
}
return $result;
}
/**
* Encode an integer to a string.
*
* @param int $value
* @param int $b
* @return string
*/
public function encode($value, $b = 62)
{
$r = (int) $value % $b;
$result = $this->base[$r];
$q = floor((int) $value / $b);
while ($q)
{
$r = $q % $b;
$q = floor($q / $b);
$result = $this->base[$r] . $result;
}
return $result;
}
}
|
Fix Duplicate Tab shortcut typo | (function () {
'use strict';
// Awesome Browser Shortcuts
chrome.commands.onCommand.addListener(function (command) {
var tabQuery = {active: true, currentWindow: true};
if (command === 'toggle-pin') {
// Get current tab in the active window
chrome.tabs.query(tabQuery, function(tabs) {
var currentTab = tabs[0];
chrome.tabs.update(currentTab.id, {'pinned': !currentTab.pinned});
});
}
else if (command === 'move-tab-left') {
chrome.tabs.query(tabQuery, function (tabs) {
var currentTab = tabs[0];
chrome.tabs.move(currentTab.id, {'index': currentTab.index - 1});
});
}
else if (command === 'move-tab-right') {
chrome.tabs.query(tabQuery, function (tabs) {
var currentTab = tabs[0];
// TODO: Move tab to first if current index is the last one
// Chrome moves non-existent index to the last
chrome.tabs.move(currentTab.id, {'index': currentTab.index + 1});
});
}
else if (command === 'duplicate-tab') {
chrome.tabs.query(tabQuery, function (tabs) {
var currentTab = tabs[0];
chrome.tabs.duplicate(currentTab.id);
});
}
});
})(); | (function () {
'use strict';
// Awesome Browser Shortcuts
chrome.commands.onCommand.addListener(function (command) {
var tabQuery = {active: true, currentWindow: true};
if (command === 'toggle-pin') {
// Get current tab in the active window
chrome.tabs.query(tabQuery, function(tabs) {
var currentTab = tabs[0];
chrome.tabs.update(currentTab.id, {'pinned': !currentTab.pinned});
});
}
else if (command === 'move-tab-left') {
chrome.tabs.query(tabQuery, function (tabs) {
var currentTab = tabs[0];
chrome.tabs.move(currentTab.id, {'index': currentTab.index - 1});
});
}
else if (command === 'move-tab-right') {
chrome.tabs.query(tabQuery, function (tabs) {
var currentTab = tabs[0];
// TODO: Move tab to first if current index is the last one
// Chrome moves non-existent index to the last
chrome.tabs.move(currentTab.id, {'index': currentTab.index + 1});
});
}
else if (command === 'duplicate=tab') {
chrome.tabs.query(tabQuery, function (tabs) {
var currentTab = tabs[0];
chrome.tabs.duplicate(currentTab.id);
})
}
});
})(); |
Add change directory context manager | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import argparse
import os
import subprocess as sp
from contextlib import contextmanager
import tempfile
try:
import urllib.request as urllib2
except ImportError:
import urllib2
MINICONDA_URL = 'https://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh'
@contextmanager
def change_directory(path):
old_cwd = os.getcwd()
try:
os.chdir(path)
yield
finally:
os.chdir(old_cwd)
def main(args):
pass
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--directory',
required=False,
default=os.getcwd())
main(parser.parse_args())
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import argparse
import os
import subprocess as sp
from contextlib import contextmanager
import tempfile
try:
import urllib.request as urllib2
except ImportError:
import urllib2
MINICONDA_URL = 'https://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh'
def main(args):
pass
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--directory',
required=False,
default=os.getcwd())
main(parser.parse_args())
|
Remove 'go' from suported runtimes | 'use strict'
// native runtime support for AWS
// https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html
// .NET CORE
const supportedDotnetcore = [
// deprecated
// 'dotnetcore1.0',
// 'dotnetcore2.0',
// supported
// 'dotnetcore2.1'
]
// GO
const supportedGo = [
// 'go1.x'
]
// JAVA
const supportedJava = [
// 'java8'
]
// NODE.JS
const supportedNodejs = [
// deprecated, but still working
'nodejs4.3',
'nodejs6.10',
// supported
'nodejs8.10',
'nodejs10.x',
]
// PROVIDED
const supportedProvided = ['provided']
// PYTHON
const supportedPython = ['python2.7', 'python3.6', 'python3.7']
// RUBY
const supportedRuby = ['ruby2.5']
exports.supportedDotnetcore = supportedDotnetcore
exports.supportedGo = supportedGo
exports.supportedJava = supportedJava
exports.supportedNodejs = supportedNodejs
exports.supportedProvided = supportedProvided
exports.supportedPython = supportedPython
exports.supportedRuby = supportedRuby
// deprecated runtimes
// https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html
exports.supportedRuntimes = new Set([
...supportedDotnetcore,
...supportedGo,
...supportedJava,
...supportedNodejs,
...supportedProvided,
...supportedPython,
...supportedRuby,
])
| 'use strict'
// native runtime support for AWS
// https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html
// .NET CORE
const supportedDotnetcore = [
// deprecated
// 'dotnetcore1.0',
// 'dotnetcore2.0',
// supported
// 'dotnetcore2.1'
]
// GO
const supportedGo = ['go1.x']
// JAVA
const supportedJava = [
// 'java8'
]
// NODE.JS
const supportedNodejs = [
// deprecated, but still working
'nodejs4.3',
'nodejs6.10',
// supported
'nodejs8.10',
'nodejs10.x',
]
// PROVIDED
const supportedProvided = ['provided']
// PYTHON
const supportedPython = ['python2.7', 'python3.6', 'python3.7']
// RUBY
const supportedRuby = ['ruby2.5']
exports.supportedDotnetcore = supportedDotnetcore
exports.supportedGo = supportedGo
exports.supportedJava = supportedJava
exports.supportedNodejs = supportedNodejs
exports.supportedProvided = supportedProvided
exports.supportedPython = supportedPython
exports.supportedRuby = supportedRuby
// deprecated runtimes
// https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html
exports.supportedRuntimes = new Set([
...supportedDotnetcore,
...supportedGo,
...supportedJava,
...supportedNodejs,
...supportedProvided,
...supportedPython,
...supportedRuby,
])
|
Fix parameter name mismatch with interface | <?php
/**
*
* This file is part of Aura for PHP.
*
* @license http://opensource.org/licenses/mit-license.php MIT
*
*/
namespace Aura\SqlQuery\Common;
use Aura\SqlQuery\AbstractDmlQuery;
/**
*
* An object for DELETE queries.
*
* @package Aura.SqlQuery
*
*/
class Delete extends AbstractDmlQuery implements DeleteInterface
{
use WhereTrait;
/**
*
* The table to delete from.
*
* @var string
*
*/
protected $from;
/**
*
* Sets the table to delete from.
*
* @param string $from The table to delete from.
*
* @return $this
*
*/
public function from($from)
{
$this->from = $this->quoter->quoteName($from);
return $this;
}
/**
*
* Builds this query object into a string.
*
* @return string
*
*/
protected function build()
{
return 'DELETE'
. $this->builder->buildFlags($this->flags)
. $this->builder->buildFrom($this->from)
. $this->builder->buildWhere($this->where)
. $this->builder->buildOrderBy($this->order_by);
}
}
| <?php
/**
*
* This file is part of Aura for PHP.
*
* @license http://opensource.org/licenses/mit-license.php MIT
*
*/
namespace Aura\SqlQuery\Common;
use Aura\SqlQuery\AbstractDmlQuery;
/**
*
* An object for DELETE queries.
*
* @package Aura.SqlQuery
*
*/
class Delete extends AbstractDmlQuery implements DeleteInterface
{
use WhereTrait;
/**
*
* The table to delete from.
*
* @var string
*
*/
protected $from;
/**
*
* Sets the table to delete from.
*
* @param string $table The table to delete from.
*
* @return $this
*
*/
public function from($table)
{
$this->from = $this->quoter->quoteName($table);
return $this;
}
/**
*
* Builds this query object into a string.
*
* @return string
*
*/
protected function build()
{
return 'DELETE'
. $this->builder->buildFlags($this->flags)
. $this->builder->buildFrom($this->from)
. $this->builder->buildWhere($this->where)
. $this->builder->buildOrderBy($this->order_by);
}
}
|
Fix national caseload screen, ensure ID isn't used in query | const knex = require('../../../knex').web
const orgUnitFinder = require('../helpers/org-unit-finder')
const ORGANISATION_UNIT = require('../../constants/organisation-unit')
module.exports = function (id, type) {
var orgUnit = orgUnitFinder('name', type)
var table = orgUnit.caseloadView
var selectList = [
'link_id AS linkId',
'grade_code AS grade',
'total_cases AS totalCases',
'location AS caseType',
'untiered',
'd2',
'd1',
'c2',
'c1',
'b2',
'b1',
'a'
]
var requiresWorkloadOwnerName = (type === ORGANISATION_UNIT.TEAM.name)
var whereString = ''
if (requiresWorkloadOwnerName) {
selectList.push('CONCAT(forename, \' \', surname) AS name')
} else {
selectList.push('name')
}
var displayAllRecords = (type === ORGANISATION_UNIT.NATIONAL.name)
if (!displayAllRecords) {
if (id !== undefined && (!isNaN(parseInt(id, 10)))) {
whereString += ' WHERE id = ' + id
}
}
var noExpandHint = ' WITH (NOEXPAND)'
return knex.schema.raw('SELECT ' + selectList.join(', ') +
' FROM ' + table +
noExpandHint +
whereString)
}
| const knex = require('../../../knex').web
const orgUnitFinder = require('../helpers/org-unit-finder')
const ORGANISATION_UNIT = require('../../constants/organisation-unit')
module.exports = function (id, type) {
var orgUnit = orgUnitFinder('name', type)
var table = orgUnit.caseloadView
var selectList = [
'link_id AS linkId',
'grade_code AS grade',
'total_cases AS totalCases',
'location AS caseType',
'untiered',
'd2',
'd1',
'c2',
'c1',
'b2',
'b1',
'a'
]
var requiresWorkloadOwnerName = (type === ORGANISATION_UNIT.TEAM.name)
if (requiresWorkloadOwnerName) {
selectList.push('CONCAT(forename, \' \', surname) AS name')
} else {
selectList.push('name')
}
var whereString = ''
if (id !== undefined && (!isNaN(parseInt(id, 10)))) {
whereString += ' WHERE id = ' + id
}
var noExpandHint = ' WITH (NOEXPAND)'
return knex.schema.raw('SELECT ' + selectList.join(', ') +
' FROM ' + table +
noExpandHint +
whereString)
}
|
Use "owner" in place of "manager" for bar roles | from flask_sqlalchemy import SQLAlchemy
from flask_alembic import Alembic
db = SQLAlchemy()
alembic = Alembic()
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
# you will have to import them first before calling init_db()
import models
import barstock
from authorization import user_datastore
db.create_all()
user_datastore.find_or_create_role(name='admin', description='An admin user may modify the parameters of the app backend')
user_datastore.find_or_create_role(name='bartender', description='This user is a bartender at at least one bar')
user_datastore.find_or_create_role(name='owner', description='This user can do limited management at one bar')
user_datastore.find_or_create_role(name='customer', description='Customer may register to make it easier to order drinks')
db.session.commit()
# now handle alembic revisions
alembic.revision('Convert columns to support unicode')
alembic.upgrade()
| from flask_sqlalchemy import SQLAlchemy
from flask_alembic import Alembic
db = SQLAlchemy()
alembic = Alembic()
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata. Otherwise
# you will have to import them first before calling init_db()
import models
import barstock
from authorization import user_datastore
db.create_all()
user_datastore.find_or_create_role(name='admin', description='An admin user may modify the parameters of the app backend')
user_datastore.find_or_create_role(name='bartender', description='This user is a bartender at at least one bar')
user_datastore.find_or_create_role(name='manager', description='This user can do limited management at one bar')
user_datastore.find_or_create_role(name='customer', description='Customer may register to make it easier to order drinks')
db.session.commit()
# now handle alembic revisions
alembic.revision('Convert columns to support unicode')
alembic.upgrade()
|
Make builds platform specific and add zipping | 'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell')
var sass = require('gulp-sass');
var electron = require('electron-connect').server.create();
var package_info = require('./package.json')
gulp.task('serve', function () {
// Compile the sass
gulp.start('sass');
// Start browser process
electron.start();
// Restart browser process
gulp.watch('main.js', electron.restart);
// Reload renderer process
gulp.watch(['index.js', 'index.html', 'index.scss'], function(){
gulp.start('sass');
electron.reload()
});
});
gulp.task('build-all', shell.task([
'electron-packager . --overwrite --platform=all --arch=all --prune=true --out=release_builds'
]));
gulp.task('build-mac', shell.task([
'electron-packager . --overwrite --platform=darwin --icon=assets/icons/mac/icon.icns --arch=x64 --prune=true --out=release_builds'
]));
gulp.task('zip', shell.task([
`zip -FSr release_builds/opsdroid-desktop-darwin-x64/opsdroid-desktop-${package_info.version}-macos-x64.zip release_builds/opsdroid-desktop-darwin-x64/opsdroid-desktop.app`
]));
gulp.task('sass', function () {
return gulp.src('./*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./'));
});
| 'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell')
var sass = require('gulp-sass');
var electron = require('electron-connect').server.create();
gulp.task('serve', function () {
// Compile the sass
gulp.start('sass');
// Start browser process
electron.start();
// Restart browser process
gulp.watch('main.js', electron.restart);
// Reload renderer process
gulp.watch(['index.js', 'index.html', 'index.scss'], function(){
gulp.start('sass');
electron.reload()
});
});
gulp.task('build', shell.task([
'electron-packager . --overwrite --platform=darwin --icon=assets/icons/mac/icon.icns --arch=x64 --prune=true --out=release_builds'
]))
gulp.task('sass', function () {
return gulp.src('./*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./'));
});
|
Convert top-level-comment to a docstring. | #!/usr/bin/python
#
# Copyright 2014 Google Inc.
#
# 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.
"""Demonstration of catching an exception and verifying its fields."""
import unittest
class MyException(Exception):
def __init__(self, message):
self.message = message
def RaiseException(message):
raise MyException(message)
class ExceptionTest(unittest.TestCase):
def verifyComplexException(self, exception_class, message, callable, *args):
with self.assertRaises(exception_class) as cm:
callable(*args)
exception = cm.exception
self.assertEqual(exception.message, message)
def testRaises(self):
self.verifyComplexException(MyException, 'asdf', RaiseException, 'asdf')
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/python
#
# Copyright 2014 Google Inc.
#
# 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.
#
################################################################################
#
# Demonstration of catching an exception and verifying its fields.
#
################################################################################
import unittest
class MyException(Exception):
def __init__(self, message):
self.message = message
def RaiseException(message):
raise MyException(message)
class ExceptionTest(unittest.TestCase):
def verifyComplexException(self, exception_class, message, callable, *args):
with self.assertRaises(exception_class) as cm:
callable(*args)
exception = cm.exception
self.assertEqual(exception.message, message)
def testRaises(self):
self.verifyComplexException(MyException, 'asdf', RaiseException, 'asdf')
if __name__ == '__main__':
unittest.main()
|
FIX: Update tests after major broker refactor. | import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(['ch1', 'ch2'], start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
| import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from ..sources import channelarchiver as ca
from ..sources import switch
from ..broker.simple_broker import POPULAR_CHANNELS
class TestBroker(unittest.TestCase):
def setUp(self):
switch(channelarchiver=False, metadatastore=False, filestore=False)
start, end = '2015-01-01 00:00:00', '2015-01-01 00:01:00'
simulated_ca_data = generate_ca_data(POPULAR_CHANNELS, start, end)
ca.insert_data(simulated_ca_data)
def tearDown(self):
switch(channelarchiver=True, metadatastore=True, filestore=True)
def generate_ca_data(channels, start_time, end_time):
timestamps = pd.date_range(start_time, end_time, freq='T').to_series()
timestamps = list(timestamps.dt.to_pydatetime()) # list of datetime objects
values = list(np.arange(len(timestamps)))
return {channel: (timestamps, values) for channel in channels}
|
Add missing font file in build
Signed-off-by: Rohan Jain <f3a935f2cb7c3d75d1446a19169b923809d6e623@gmail.com> | /* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Add options here
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import('bower_components/bootstrap/dist/js/bootstrap.js');
app.import('bower_components/bootstrap/dist/css/bootstrap.css');
app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', {
destDir: 'fonts'
});
app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2', {
destDir: 'fonts'
});
app.import('vendor/forge.min.js');
return app.toTree();
};
| /* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Add options here
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import('bower_components/bootstrap/dist/js/bootstrap.js');
app.import('bower_components/bootstrap/dist/css/bootstrap.css');
app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', {
destDir: 'fonts'
});
app.import('vendor/forge.min.js');
return app.toTree();
};
|
Add to doc string: time complexity | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def insertion_sort(a_list):
"""Insertion Sort algortihm.
Time complexity: O(n^2).
"""
for index in range(1, len(a_list)):
current_value = a_list[index]
position = index
while position > 0 and a_list[position - 1] > current_value:
a_list[position] = a_list[position - 1]
position -= 1
a_list[position] = current_value
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: \n{}'.format(a_list))
print('By insertion sort: ')
insertion_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def insertion_sort(a_list):
"""Insertion Sort algortihm."""
for index in range(1, len(a_list)):
current_value = a_list[index]
position = index
while position > 0 and a_list[position - 1] > current_value:
a_list[position] = a_list[position - 1]
position -= 1
a_list[position] = current_value
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: \n{}'.format(a_list))
print('By insertion sort: ')
insertion_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
Update to https from http | $(document).ready(function() {
var title = [],
desc = [],
link = [],
val = $('#search-box'),
url = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=';
$('#search-box').focus();
$('.search-button').click(function() {
$('.wiki-container').empty();
$.getJSON(url + val.val() + '&callback=?').success(function(data) {
for (i = 0; i < data[1].length; i++) {
title = data[1][i];
if (data[2][i] === '') {
desc = "No description"
} else {
desc = data[2][i];
}
link = data[3][i];
$('.wiki-container').append('<div class="results"><a href="' + link + '" target="_blank"><h3><br>' + title + '</h3></a><p>' + desc + '</p></div>');
}
});
});
$('#search-box').click(function() {
$(this).val('');
});
//enables the "enter" key to perform search
$('#search-box').keydown(function(e) {
if (e.which === 13) {
$('.search-button').click();
$('#search-box').blur();
}
});
}); | $(document).ready(function() {
var title = [],
desc = [],
link = [],
val = $('#search-box'),
url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=';
$('#search-box').focus();
$('.search-button').click(function() {
$('.wiki-container').empty();
$.getJSON(url + val.val() + '&callback=?').success(function(data) {
for (i = 0; i < data[1].length; i++) {
title = data[1][i];
if (data[2][i] === '') {
desc = "No description"
} else {
desc = data[2][i];
}
link = data[3][i];
$('.wiki-container').append('<div class="results"><a href="' + link + '" target="_blank"><h3><br>' + title + '</h3></a><p>' + desc + '</p></div>');
}
});
});
$('#search-box').click(function() {
$(this).val('');
});
//enables the "enter" key to perform search
$('#search-box').keydown(function(e) {
if (e.which === 13) {
$('.search-button').click();
$('#search-box').blur();
}
});
}); |
Swap out hard tabs for spaces | """
Launch the Python script on the command line after
setuptools is bootstrapped via import.
"""
# Note that setuptools gets imported implicitly by the
# invocation of this script using python -m setuptools.launch
import tokenize
import sys
def run():
"""
Run the script in sys.argv[1] as if it had
been invoked naturally.
"""
__builtins__
script_name = sys.argv[1]
namespace = dict(
__file__ = script_name,
__name__ = '__main__',
__doc__ = None,
)
sys.argv[:] = sys.argv[1:]
open_ = getattr(tokenize, 'open', open)
script = open_(script_name).read()
norm_script = script.replace('\\r\\n', '\\n')
code = compile(norm_script, script_name, 'exec')
exec(code, namespace)
if __name__ == '__main__':
run()
| """
Launch the Python script on the command line after
setuptools is bootstrapped via import.
"""
# Note that setuptools gets imported implicitly by the
# invocation of this script using python -m setuptools.launch
import tokenize
import sys
def run():
"""
Run the script in sys.argv[1] as if it had
been invoked naturally.
"""
__builtins__
script_name = sys.argv[1]
namespace = dict(
__file__ = script_name,
__name__ = '__main__',
__doc__ = None,
)
sys.argv[:] = sys.argv[1:]
open_ = getattr(tokenize, 'open', open)
script = open_(script_name).read()
norm_script = script.replace('\\r\\n', '\\n')
code = compile(norm_script, script_name, 'exec')
exec(code, namespace)
if __name__ == '__main__':
run()
|
Add some javadoc. Add @SafeVarags annotation. Change for loops to for each. | package uk.ac.ebi.quickgo.index.annotation.coterms;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author Tony Wardell
* Date: 05/10/2016
* Time: 16:41
* Created with IntelliJ IDEA.
*/
public class CoTermsAggregatorMocker {
/**
* Mocks the {@code CoTermsAggregator#getGeneProductCounts} to product a count of gene products annotated by a
* single GO Term.
* @param count the number that the count for Gene Product will be set to.
* @param termsLists a list of GO Term identifiers used to seed a map of term::count used in testing
* @return a map of term::count used in testing
*/
@SafeVarargs
static Map<String, AtomicLong> makeGpCountForTerm(int count, List<String>... termsLists ){
Map<String, AtomicLong> termGpCount = new HashMap<>();
for (List<String> terms : termsLists) {
for (String s : terms) {
termGpCount.put(s, new AtomicLong(count));
}
}
return termGpCount;
}
}
| package uk.ac.ebi.quickgo.index.annotation.coterms;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author Tony Wardell
* Date: 05/10/2016
* Time: 16:41
* Created with IntelliJ IDEA.
*/
public class CoTermsAggregatorMocker {
/**
* Mocks the {@code CoTermsAggregator#getGeneProductCounts} to product a count of gene products annotated by a
* single GO Term.
* @param count
* @param termsLists
* @return
*/
static Map<String, AtomicLong> makeGpCountForTerm(int count, List<String>... termsLists ){
Map<String, AtomicLong> termGpCount = new HashMap<>();
for (int i = 0; i < termsLists.length; i++) {
List<String> terms = termsLists[i];
for (int j = 0; j < terms.size(); j++) {
String s = terms.get(j);
termGpCount.put(s, new AtomicLong(count));
}
}
return termGpCount;
}
}
|
Fix bug when inserting user.
Scheme of table: User has changed. | #!/usr/bin/python
from MySQLdb import Error
from util import connect_db, dump_response_and_exit
import cgi
import hashlib
import json
import re
import sys
print "Content-type:applicaion/json\r\n\r\n"
form = cgi.FieldStorage()
username = form.getvalue('username')
password = form.getvalue('password')
if username is None or password is None:
dump_response_and_exit(False, 'Missing field: username or password.')
if re.match(r"^[a-zA-Z0-9_.-]+$", username) is None:
dump_response_and_exit(False, 'Invalid username.')
if re.match(r'[A-Za-z0-9@#$%^&+=_.-]{6,}', password) is None:
dump_response_and_exit(False, 'Invalid password.')
try:
con = connect_db()
with con:
cur = con.cursor()
cur.execute("INSERT INTO User(username, password) values (%s, %s)",
(username, hashlib.sha1(password).digest()))
con.commit()
dump_response_and_exit(True, 'Done.')
except Error, e:
if con:
con.rollback()
dump_response_and_exit(False, e[1])
finally:
con.close()
| #!/usr/bin/python
from MySQLdb import Error
from util import connect_db, dump_response_and_exit
import cgi
import hashlib
import json
import re
import sys
print "Content-type:applicaion/json\r\n\r\n"
form = cgi.FieldStorage()
username = form.getvalue('username')
password = form.getvalue('password')
if username is None or password is None:
dump_response_and_exit(False, 'Missing field: username or password.')
if re.match(r"^[a-zA-Z0-9_.-]+$", username) is None:
dump_response_and_exit(False, 'Invalid username.')
if re.match(r'[A-Za-z0-9@#$%^&+=_.-]{6,}', password) is None:
dump_response_and_exit(False, 'Invalid password.')
try:
con = connect_db()
with con:
cur = con.cursor()
cur.execute("INSERT INTO User values (%s, %s)",
(username, hashlib.sha1(password).digest()))
con.commit()
dump_response_and_exit(True, 'Done.')
except Error, e:
if con:
con.rollback()
dump_response_and_exit(False, e[1])
finally:
con.close()
|
fix: Use relative resolve path for webpack | 'use strict'
const path = require('path')
const { DefinePlugin, ContextReplacementPlugin } = require('webpack')
const SRC_DIR = path.resolve(__dirname, '../src')
// See https://github.com/date-fns/date-fns/blob/master/docs/webpack.md
const supportedLocales = ['en', 'fr', 'es']
const regexpLocales = new RegExp(`/(${supportedLocales.join('|')})`)
module.exports = {
resolve: {
modules: [SRC_DIR, 'node_modules'],
alias: {
config: path.resolve(SRC_DIR, './config'),
'redux-cozy-client': path.resolve(SRC_DIR, './lib/redux-cozy-client'),
'cozy-ui/react': 'cozy-ui/transpiled/react'
}
},
plugins: [
new DefinePlugin({
__PIWIK_SITEID__: 8,
__PIWIK_DIMENSION_ID_APP__: 1,
__PIWIK_TRACKER_URL__: JSON.stringify('https://piwik.cozycloud.cc')
}),
new ContextReplacementPlugin(/moment[\/\\]locale$/, regexpLocales),
new ContextReplacementPlugin(/date-fns[\/\\]locale$/, regexpLocales),
new ContextReplacementPlugin(/src[\/\\]locales/, regexpLocales)
]
}
| 'use strict'
const path = require('path')
const { DefinePlugin, ContextReplacementPlugin } = require('webpack')
const SRC_DIR = path.resolve(__dirname, '../src')
// See https://github.com/date-fns/date-fns/blob/master/docs/webpack.md
const supportedLocales = ['en', 'fr', 'es']
const regexpLocales = new RegExp(`/(${supportedLocales.join('|')})`)
module.exports = {
resolve: {
alias: {
config: path.resolve(SRC_DIR, './config'),
'redux-cozy-client': path.resolve(SRC_DIR, './lib/redux-cozy-client'),
'cozy-ui/react': 'cozy-ui/transpiled/react'
}
},
plugins: [
new DefinePlugin({
__PIWIK_SITEID__: 8,
__PIWIK_DIMENSION_ID_APP__: 1,
__PIWIK_TRACKER_URL__: JSON.stringify('https://piwik.cozycloud.cc')
}),
new ContextReplacementPlugin(/moment[\/\\]locale$/, regexpLocales),
new ContextReplacementPlugin(/date-fns[\/\\]locale$/, regexpLocales),
new ContextReplacementPlugin(/src[\/\\]locales/, regexpLocales),
]
}
|
Hide data when "reset zoom" button is pressed. | /// </// <reference path="data_functions.js" />
function getAnalysisNavtab() {
return document.getElementsByClassName("nav")[0].getElementsByTagName("li")[0];
}
var svgObserver = new MutationObserver(function (mutations) {
//console.log({ svg: mutations });
var button = null;
for (var i = 0; i < mutations[0].addedNodes.length; i++) {
var element = mutations[0].addedNodes[i];
var classAtt = element.attributes["class"];
if (classAtt && classAtt.value === "highcharts-button") {
button = element;
break;
}
}
if (button === null)
return;
button.addEventListener("click", function (e) {
hideData();
});
});
var navtabObserver = new MutationObserver(function (mutations) {
console.log({ tab: mutations });
});
function initObservers(svg, navtab) {
var svgObserverConfig = { childList: true };
var navtabObserverConfig = {
attributes: true,
attributeOldValue: true,
attributeFilter: ["class"]
}
svgObserver.observe(svg, svgObserverConfig);
navtabObserver.observe(navtab || getAnalysisNavtab(), navtabObserverConfig);
}
function disconnectObservers() {
svgObserver.disconnect();
navtabObserver.disconnect();
} | /// </// <reference path="data_functions.js" />
// function getSvg(){
// return document.getElementsByClassName("highcharts-container")[0].firstChild;
// }
function getAnalysisNavtab() {
return document.getElementsByClassName("nav")[0].getElementsByTagName("li")[0];
}
var svgObserver = new MutationObserver(function (mutations) {
console.log({ svg: mutations });
});
var navtabObserver = new MutationObserver(function (mutations) {
console.log({ tab: mutations });
});
function initObservers(svg, navtab) {
var svgObserverConfig = { childList: true };
var navtabObserverConfig = {
attributes: true,
attributeOldValue: true,
attributeFilter: ["class"]
}
svgObserver.observe(svg, svgObserverConfig);
navtabObserver.observe(navtab || getAnalysisNavtab(), navtabObserverConfig);
}
function disconnectObservers() {
svgObserver.disconnect();
navtabObserver.disconnect();
} |
Add "forDOM" var when rendering for DOM | var getDefaultHistory = require('./history/getHistory');
/**
* Bootstraps the app by getting the initial state.
*/
function attach(Router, element, opts) {
if (!opts) opts = {};
var router = new Router({defaultVars: {forDOM: true}});
var history = opts.history || getDefaultHistory();
var render = function() {
Router.engine.renderInto(router, element);
};
var onInitialReady = function() {
render();
router
.on('viewChange', render)
.on('stateChange', render);
// Now that the view has been bootstrapped (i.e. is in its inital state), it
// can be updated.
update();
history.on('change', function() {
update();
});
};
var previousURL;
var update = function(isInitial) {
var url = history.currentURL();
if (url === previousURL) return;
previousURL = url;
// TODO: How should we handle an error here? Throw it? Log it?
var res = router.dispatch(url);
if (isInitial) {
res.once('initialReady', onInitialReady);
}
};
// Start the process.
update(true);
return router;
}
module.exports = attach;
| var getDefaultHistory = require('./history/getHistory');
/**
* Bootstraps the app by getting the initial state.
*/
function attach(Router, element, opts) {
if (!opts) opts = {};
var router = new Router();
var history = opts.history || getDefaultHistory();
var render = function() {
Router.engine.renderInto(router, element);
};
var onInitialReady = function() {
render();
router
.on('viewChange', render)
.on('stateChange', render);
// Now that the view has been bootstrapped (i.e. is in its inital state), it
// can be updated.
update();
history.on('change', function() {
update();
});
};
var previousURL;
var update = function(isInitial) {
var url = history.currentURL();
if (url === previousURL) return;
previousURL = url;
// TODO: How should we handle an error here? Throw it? Log it?
var res = router.dispatch(url);
if (isInitial) {
res.once('initialReady', onInitialReady);
}
};
// Start the process.
update(true);
return router;
}
module.exports = attach;
|
Change root component to actual React component. | import Notify from './notification';
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
class App extends Component { // eslint-disable-line react/prefer-stateless-function
render() {
const { children, loading: { isLoading, wip } } = this.props;
return (
<div className="app">
<ul id="spinner" className={isLoading ? 'is-loading' : ''}>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
{children}
<ul id="loading_list">
{Object.keys(wip).map((loadingKey, ndx) => {
return (<li key={ndx}>{loadingKey}</li>);
})}
</ul>
<Notify />
</div>
);
}
}
App.displayName = 'App';
App.propTypes = {
children: PropTypes.node,
loading: PropTypes.object,
};
function select(state) {
return {
loading: state.loading,
};
}
export default connect(select)(App);
| import Notify from './notification';
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
function App(props) {
const isLoading = props.loading.isLoading;
return (
<div className="app">
<ul id="spinner" className={isLoading ? 'is-loading' : ''}>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
{props.children}
<ul id="loading_list">
{Object.keys(props.loading.wip).map((loadingKey, ndx) => {
return (<li key={ndx}>{loadingKey}</li>);
})}
</ul>
<Notify />
</div>
);
}
App.displayName = 'App';
App.propTypes = {
children: PropTypes.node,
loading: PropTypes.object,
};
function select(state) {
return {
loading: state.loading,
};
}
export default connect(select)(App);
|
Fix formatting for v7 rename service broker command. | package v7
import (
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/flag"
"code.cloudfoundry.org/cli/command/translatableerror"
)
type RenameServiceBrokerCommand struct {
RequiredArgs flag.RenameServiceBrokerArgs `positional-args:"yes"`
usage interface{} `usage:"CF_NAME rename-service-broker SERVICE_BROKER NEW_SERVICE_BROKER"`
relatedCommands interface{} `related_commands:"service-brokers, update-service-broker"`
}
func (RenameServiceBrokerCommand) Setup(config command.Config, ui command.UI) error {
return nil
}
func (RenameServiceBrokerCommand) Execute(args []string) error {
return translatableerror.UnrefactoredCommandError{}
}
| package v7
import (
"code.cloudfoundry.org/cli/command"
"code.cloudfoundry.org/cli/command/flag"
"code.cloudfoundry.org/cli/command/translatableerror"
)
type RenameServiceBrokerCommand struct {
RequiredArgs flag.RenameServiceBrokerArgs `positional-args:"yes"`
usage interface{} `usage:"CF_NAME rename-service-broker SERVICE_BROKER NEW_SERVICE_BROKER"`
relatedCommands interface{} `related_commands:"service-brokers, update-service-broker"`
}
func (RenameServiceBrokerCommand) Setup(config command.Config, ui command.UI) error {
return nil
}
func (RenameServiceBrokerCommand) Execute(args []string) error {
return translatableerror.UnrefactoredCommandError{}
}
|
Fix eslint strict mode option | 'use strict'
const { env, platform } = process
module.exports = {
extends: [
'eslint:recommended',
'eslint-config-airbnb-base',
'plugin:prettier/recommended',
],
env: {
es6: true,
jest: true,
node: true,
},
parserOptions: {
sourceType: 'script',
},
rules: {
// TODO FIXME turn off temporary, to make eslint pass
'class-methods-use-this': 'off',
'consistent-return': 'off',
'no-console': 'off',
'no-multi-assign': 'off',
'no-param-reassign': 'off',
'no-restricted-syntax': 'off',
'no-shadow': 'off',
'no-underscore-dangle': 'off',
'no-use-before-define': 'off',
radix: 'off',
// workaround for git + eslint line ending issue on Travis for Windows OS:
// https://travis-ci.community/t/files-in-checkout-have-eol-changed-from-lf-to-crlf/349/2
...(env.TRAVIS &&
platform === 'win32' && {
['linebreak-style']: 'off',
}),
},
}
| 'use strict'
const { env, platform } = process
module.exports = {
extends: [
'eslint:recommended',
'eslint-config-airbnb-base',
'plugin:prettier/recommended',
],
env: {
es6: true,
jest: true,
node: true,
},
rules: {
// TODO FIXME turn off temporary, to make eslint pass
'class-methods-use-this': 'off',
'consistent-return': 'off',
'no-console': 'off',
'no-multi-assign': 'off',
'no-param-reassign': 'off',
'no-restricted-syntax': 'off',
'no-shadow': 'off',
'no-underscore-dangle': 'off',
'no-use-before-define': 'off',
radix: 'off',
strict: 'off',
// workaround for git + eslint line ending issue on Travis for Windows OS:
// https://travis-ci.community/t/files-in-checkout-have-eol-changed-from-lf-to-crlf/349/2
...(env.TRAVIS &&
platform === 'win32' && {
['linebreak-style']: 'off',
}),
},
}
|
Fix test to use message | 'use strict';
var expect = require('expect.js')
, proxyquire = require('proxyquire')
;
describe('SockJS', function() {
describe('Constructor', function () {
describe('WebSocket specification step #2', function () {
it('should throw SecurityError for an insecure url from a secure page', function () {
var main = proxyquire('../../lib/main', { './location': {
protocol: 'https'
}});
var sjs = proxyquire('../../lib/entry', { './main': main });
expect(function () {
sjs('http://localhost');
}).to.throwException(function (e) {
expect(e).to.be.a(Error);
expect(e.message).to.contain('SecurityError');
});
});
});
});
});
| 'use strict';
var expect = require('expect.js')
, proxyquire = require('proxyquire')
;
describe('SockJS', function() {
describe('Constructor', function () {
describe('WebSocket specification step #2', function () {
it('should throw SecurityError for an insecure url from a secure page', function () {
var main = proxyquire('../../lib/main', { './location': {
protocol: 'https'
}});
var sjs = proxyquire('../../lib/entry', { './main': main });
expect(function () {
sjs('http://localhost');
}).to.throwException(function (e) {
expect(e).to.be.a(Error);
expect(e).to.contain('SecurityError');
});
});
});
});
});
|
Add demo app version code to launch URL. | // Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// 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.
package com.google.androidbrowserhelper.demos.playbilling;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import com.google.androidbrowserhelper.trusted.LauncherActivity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void launch(View view) {
Intent intent = new Intent(this, LauncherActivity.class);
intent.setData(
Uri.parse("https://beer.conn.dev?client_version=" + BuildConfig.VERSION_CODE));
startActivity(intent);
}
}
| // Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// 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.
package com.google.androidbrowserhelper.demos.playbilling;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.google.androidbrowserhelper.trusted.LauncherActivity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void launch(View view) {
Intent intent = new Intent(this, LauncherActivity.class);
startActivity(intent);
}
}
|
Revert "tolerate missing edge data"
This reverts commit 93f1f6b24b7e8e61dbbfebe500048db752bc9fed. | from romanesco.format import dict_to_vtkarrays, dict_to_vtkrow
import vtk
vtk_builder = vtk.vtkMutableDirectedGraph()
node_fields = input["node_fields"]
edge_fields = input["edge_fields"]
dict_to_vtkarrays(input["node_data"], node_fields, vtk_builder.GetVertexData())
if "children" in input and len(input["children"]) > 0:
dict_to_vtkarrays(input["children"][0]["edge_data"], edge_fields,
vtk_builder.GetEdgeData())
def process_node(vtknode, node):
if "children" in node:
for n in node["children"]:
vtkchild = vtk_builder.AddVertex()
vtkparentedge = vtk_builder.AddGraphEdge(vtknode, vtkchild).GetId()
dict_to_vtkrow(n["node_data"], vtk_builder.GetVertexData())
dict_to_vtkrow(n["edge_data"], vtk_builder.GetEdgeData())
process_node(vtkchild, n)
vtk_builder.AddVertex()
dict_to_vtkrow(input["node_data"], vtk_builder.GetVertexData())
process_node(0, input)
output = vtk.vtkTree()
output.ShallowCopy(vtk_builder)
| from romanesco.format import dict_to_vtkarrays, dict_to_vtkrow
import vtk
vtk_builder = vtk.vtkMutableDirectedGraph()
node_fields = input["node_fields"]
edge_fields = input["edge_fields"]
dict_to_vtkarrays(input["node_data"], node_fields, vtk_builder.GetVertexData())
if "children" in input and len(input["children"]) > 0:
dict_to_vtkarrays(input["children"][0]["edge_data"], edge_fields,
vtk_builder.GetEdgeData())
def process_node(vtknode, node):
if "children" in node:
for n in node["children"]:
vtkchild = vtk_builder.AddVertex()
vtkparentedge = vtk_builder.AddGraphEdge(vtknode, vtkchild).GetId()
dict_to_vtkrow(n["node_data"], vtk_builder.GetVertexData())
if "edge_data" in n:
dict_to_vtkrow(n["edge_data"], vtk_builder.GetEdgeData())
process_node(vtkchild, n)
vtk_builder.AddVertex()
dict_to_vtkrow(input["node_data"], vtk_builder.GetVertexData())
process_node(0, input)
output = vtk.vtkTree()
output.ShallowCopy(vtk_builder)
|
Return a 404, not a 500 on a verb mismatch
Fixes #1101 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import json
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseRedirect, Http404
def route(**kwargs):
@csrf_exempt
def routed(request, *args2, **kwargs2):
method = request.method
if method not in kwargs:
raise Http404()
else:
req_method = kwargs[method]
return req_method(request, *args2, **kwargs2)
return routed
def json_from_request(request):
body = request.body
if body:
return json.loads(body)
else:
return None
def merge_view_contexts(viewfns):
def wrapped(*args, **kwargs):
context = {}
for viewfn in viewfns:
context.update(viewfn(*args, **kwargs))
return context
return wrapped
| from django.views.decorators.csrf import csrf_exempt
import json
def route(**kwargs):
@csrf_exempt
def routed(request, *args2, **kwargs2):
method = request.method
req_method = kwargs[method]
return req_method(request, *args2, **kwargs2)
return routed
def json_from_request(request):
body = request.body
if body:
return json.loads(body)
else:
return None
def merge_view_contexts(viewfns):
def wrapped(*args, **kwargs):
context = {}
for viewfn in viewfns:
context.update(viewfn(*args, **kwargs))
return context
return wrapped
|
Trim isn't available in IE8
* Use jQuery’s trim instead | (function () {
"use strict"
var root = this,
$ = root.jQuery;
if (typeof root.GOVUK === 'undefined') {
root.GOVUK = {};
}
root.GOVUK.Tagging = {
ready: function(options) {
$('.js-tag-list').select2({
tags: options['autocompleteWith'],
tokenSeparators: [','],
initSelection: function (input, setTags) {
setTags(
$(input.val().split(",")).map(function () {
return {
id: $.trim(this),
text: $.trim(this)
};
})
)
}
})
}
};
}).call(this);
| (function () {
"use strict"
var root = this,
$ = root.jQuery;
if (typeof root.GOVUK === 'undefined') {
root.GOVUK = {};
}
root.GOVUK.Tagging = {
ready: function(options) {
$('.js-tag-list').select2({
tags: options['autocompleteWith'],
tokenSeparators: [','],
initSelection: function (input, setTags) {
setTags(
$(input.val().split(",")).map(function () {
return {
id: this.trim(),
text: this.trim()
};
})
)
}
})
}
};
}).call(this);
|
Fix improper namespace causing test to ignore App\Actions\LaravelUi and make no assertions against it. | <?php
namespace App\Actions;
use App\Shell\Shell;
class ConfigureFrontendFramework
{
use LamboAction;
private $shell;
private $laravelUi;
public function __construct(Shell $shell, LaravelUi $laravelUi)
{
$this->shell = $shell;
$this->laravelUi = $laravelUi;
}
public function __invoke()
{
if (! config('lambo.store.frontend')) {
return;
}
$this->laravelUi->install();
$this->logStep('Configuring frontend scaffolding');
$process = $this->shell->execInProject('php artisan ui ' . config('lambo.store.frontend'));
$this->abortIf(! $process->isSuccessful(), "Installation of UI scaffolding did not complete successfully.", $process);
$this->info('UI scaffolding has been set to ' . config('lambo.store.frontend'));
}
}
| <?php
namespace App\Actions;
use App\LaravelUi;
use App\Shell\Shell;
class ConfigureFrontendFramework
{
use LamboAction;
private $shell;
private $laravelUi;
public function __construct(Shell $shell, LaravelUi $laravelUi)
{
$this->shell = $shell;
$this->laravelUi = $laravelUi;
}
public function __invoke()
{
if (! config('lambo.store.frontend')) {
return;
}
$this->laravelUi->install();
$this->logStep('Configuring frontend scaffolding');
$process = $this->shell->execInProject('php artisan ui ' . config('lambo.store.frontend'));
$this->abortIf(! $process->isSuccessful(), "Installation of UI scaffolding did not complete successfully.", $process);
$this->info('UI scaffolding has been set to ' . config('lambo.store.frontend'));
}
}
|
Increase watch speed by adding spawn:false | module.exports = function (grunt) {
'use strict';
grunt.initConfig({
jshint: {
files: [
'Gruntfile.js',
'generators/**/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
watch: {
options: {
spawn: false
},
scripts: {
files: [
'generators/**/*.js',
'Gruntfile.js'
],
tasks: ['jshint']
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('test', ['jshint']);
grunt.registerTask('default', ['watch']);
};
| module.exports = function (grunt) {
'use strict';
grunt.initConfig({
jshint: {
files: [
'Gruntfile.js',
'generators/**/*.js'
],
options: {
jshintrc: '.jshintrc'
}
},
watch: {
scripts: {
files: [
'generators/**/*.js',
'Gruntfile.js'
],
tasks: ['jshint']
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('test', ['jshint']);
grunt.registerTask('default', ['watch']);
};
|
Check for errors parsing the CSV as we go.
When rows bleed into each other, we can get keys that are None in the records.
Now we get a user error in this case. | # -*- coding: utf-8 -*-
#
# records.py
# csvdiff
#
import csv
from . import error
class InvalidKeyError(Exception):
pass
def load(file_or_stream):
istream = (open(file_or_stream)
if not hasattr(file_or_stream, 'read')
else file_or_stream)
return _safe_iterator(csv.DictReader(istream))
def _safe_iterator(reader):
for lineno, r in enumerate(reader, 2):
if any(k is None for k in r):
error.abort('CSV parse error on line {}'.format(lineno))
yield r
def index(record_seq, index_columns):
try:
return {
tuple(r[i] for i in index_columns): r
for r in record_seq
}
except KeyError as k:
raise InvalidKeyError('invalid column name {k} as key'.format(k=k))
def save(record_seq, fieldnames, ostream):
writer = csv.DictWriter(ostream, fieldnames)
writer.writeheader()
for r in record_seq:
writer.writerow(r)
def sort(recs):
return sorted(recs, key=_record_key)
def _record_key(r):
return sorted(r.items())
| # -*- coding: utf-8 -*-
#
# records.py
# csvdiff
#
import csv
class InvalidKeyError(Exception):
pass
def load(file_or_stream):
istream = (open(file_or_stream)
if not hasattr(file_or_stream, 'read')
else file_or_stream)
return csv.DictReader(istream)
def index(record_seq, index_columns):
try:
return {
tuple(r[i] for i in index_columns): r
for r in record_seq
}
except KeyError as k:
raise InvalidKeyError('invalid column name {k} as key'.format(k=k))
def save(record_seq, fieldnames, ostream):
writer = csv.DictWriter(ostream, fieldnames)
writer.writeheader()
for r in record_seq:
writer.writerow(r)
def sort(recs):
return sorted(recs, key=_record_key)
def _record_key(r):
return sorted(r.items())
|
Remove download URL since Github doesn't get his act together. Damnit
git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f
committer: leidel <48255722c72bb2e7f7bec0fff5f60dc7fb5357fb@12edf5ea-513a-0410-8a8c-37067077e60f> | from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://code.google.com/p/django-robots/',
packages=['robots'],
package_dir={'dbtemplates': 'dbtemplates'},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
| from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://code.google.com/p/django-robots/',
download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4',
packages=['robots'],
package_dir={'dbtemplates': 'dbtemplates'},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
Load grunt-* dependencies with matchdep | module.exports = function(grunt) {
require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks);
grunt.registerTask('default', ['browserify']);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify: {
main: {
src: 'lib/vjs-hls.js',
dest: 'debug/vjs-hls.js',
options: {
transform: ['babelify'],
browserifyOptions: {
debug: true
},
watch: true,
keepAlive: true
}
}
}
});
}
| module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browserify');
grunt.registerTask('default', ['browserify']);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify: {
main: {
src: 'lib/vjs-hls.js',
dest: 'debug/vjs-hls.js',
options: {
transform: ['babelify'],
browserifyOptions: {
debug: true
},
watch: true,
keepAlive: true
}
}
}
});
}
|
Make item_properties value of length 1024. | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsProperties extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create(Folio::table('item_properties'),
function (Blueprint $table) {
$table->increments('id');
$table->integer('item_id')->nullable();
$table->timestamps();
$table->string('name')->nullable();
$table->string('value', 1024)->nullable();
$table->string('label')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop(Folio::table('item_properties'));
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsProperties extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create(Folio::table('item_properties'),
function (Blueprint $table) {
$table->increments('id');
$table->integer('item_id')->nullable();
$table->timestamps();
$table->string('name')->nullable();
$table->string('value')->nullable();
$table->string('label')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop(Folio::table('item_properties'));
}
}
|
Remove useless 'arrangedContent'. The controller it itself sorted | //= require test_helper
describe("App.ContactsController", function() {
var controller,
store;
beforeEach(function() {
store = lookupStore();
Ember.run(function() {
store.loadMany(App.Contact, [
{id: 1, first_name: 'Aaron', last_name: 'Zeebob'},
{id: 2, first_name: 'Aaaron', last_name: 'Zeebob'},
{id: 3, first_name: 'Zeus', last_name: 'Aaardvaaark'},
]);
controller = App.ContactsController.create();
controller.set('content', store.findMany(App.Contact, [1, 2, 3]));
});
});
it("sorts by [lastName, firstName]", function() {
assert.equal(controller.get('length'), 3);
assert.equal(controller.objectAt(0).get('id'), '3');
assert.equal(controller.objectAt(1).get('id'), '2');
assert.equal(controller.objectAt(2).get('id'), '1');
});
});
| //= require test_helper
describe("App.ContactsController", function() {
var controller,
store;
beforeEach(function() {
store = lookupStore();
Ember.run(function() {
store.loadMany(App.Contact, [
{id: 1, first_name: 'Aaron', last_name: 'Zeebob'},
{id: 2, first_name: 'Aaaron', last_name: 'Zeebob'},
{id: 3, first_name: 'Zeus', last_name: 'Aaardvaaark'},
]);
controller = App.ContactsController.create();
controller.set('content', store.findMany(App.Contact, [1, 2, 3]));
});
});
it("sorts by [lastName, firstName]", function() {
assert.equal(controller.get('arrangedContent.length'), 3);
assert.equal(controller.get('arrangedContent').objectAt(0).get('id'), '3');
assert.equal(controller.get('arrangedContent').objectAt(1).get('id'), '2');
assert.equal(controller.get('arrangedContent').objectAt(2).get('id'), '1');
});
});
|
Print out syntax tree on parse failure, to make it easier to debug where the failure happened. | package main
import (
"flag"
"io/ioutil"
"log"
"os"
"fmt"
)
func main() {
var version bool
flag.BoolVar(&version, "v", false, "version string")
flag.Parse()
if version {
fmt.Println("Header: perly.c,v 1.0 87/12/18 15:53:31 root Exp\nPatch level: 0")
os.Exit(0)
}
var sourcetext string
if len(os.Args) < 2 {
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal(err)
}
sourcetext = string(buf)
} else {
buf, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Printf("Perl script \"%v\" doesn't seem to exist.\n", os.Args[1])
log.Fatal(err)
}
sourcetext = string(buf)
}
gparser := &Gunie{Buffer: sourcetext}
gparser.Init()
err := gparser.Parse()
if err != nil {
gparser.PrintSyntaxTree()
log.Fatal(err)
}
gparser.PrintSyntaxTree()
}
| package main
import (
"flag"
"io/ioutil"
"log"
"os"
"fmt"
)
func main() {
var version bool
flag.BoolVar(&version, "v", false, "version string")
flag.Parse()
if version {
fmt.Println("Header: perly.c,v 1.0 87/12/18 15:53:31 root Exp\nPatch level: 0")
os.Exit(0)
}
var sourcetext string
if len(os.Args) < 2 {
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal(err)
}
sourcetext = string(buf)
} else {
buf, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Printf("Perl script \"%v\" doesn't seem to exist.\n", os.Args[1])
log.Fatal(err)
}
sourcetext = string(buf)
}
gparser := &Gunie{Buffer: sourcetext}
gparser.Init()
err := gparser.Parse()
if err != nil {
log.Fatal(err)
}
gparser.PrintSyntaxTree()
}
|
Add missing entity action mapping for horse inventory open for 1.6-1.7 | package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_6_7;
import io.netty.buffer.ByteBuf;
import protocolsupport.protocol.packet.middle.serverbound.play.MiddleEntityAction;
import protocolsupport.utils.CollectionsUtils.ArrayMap;
public class EntityAction extends MiddleEntityAction {
private static final ArrayMap<Action> actionById = new ArrayMap<>(
new ArrayMap.Entry<>(1, Action.START_SNEAK), new ArrayMap.Entry<>(2, Action.STOP_SNEAK),
new ArrayMap.Entry<>(3, Action.LEAVE_BED),
new ArrayMap.Entry<>(4, Action.START_SPRINT), new ArrayMap.Entry<>(5, Action.STOP_SPRINT),
new ArrayMap.Entry<>(6, Action.STOP_JUMP),
new ArrayMap.Entry<>(7, Action.OPEN_HORSE_INV)
);
@Override
public void readFromClientData(ByteBuf clientdata) {
entityId = clientdata.readInt();
action = actionById.get(clientdata.readByte());
jumpBoost = clientdata.readInt();
}
}
| package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_6_7;
import io.netty.buffer.ByteBuf;
import protocolsupport.protocol.packet.middle.serverbound.play.MiddleEntityAction;
import protocolsupport.utils.CollectionsUtils.ArrayMap;
public class EntityAction extends MiddleEntityAction {
private static final ArrayMap<Action> actionById = new ArrayMap<>(
new ArrayMap.Entry<>(1, Action.START_SNEAK), new ArrayMap.Entry<>(2, Action.STOP_SNEAK),
new ArrayMap.Entry<>(3, Action.LEAVE_BED),
new ArrayMap.Entry<>(4, Action.START_SPRINT), new ArrayMap.Entry<>(5, Action.STOP_SPRINT),
new ArrayMap.Entry<>(6, Action.STOP_JUMP) //this won't work now anyway, but still map it
);
@Override
public void readFromClientData(ByteBuf clientdata) {
entityId = clientdata.readInt();
action = actionById.get(clientdata.readByte());
jumpBoost = clientdata.readInt();
}
}
|
Fix theme asset pathing in "no allocation" |
import logging
from django.conf import settings
from django.shortcuts import render, redirect, render_to_response
from django.template import RequestContext
logger = logging.getLogger(__name__)
def allocations(request):
"""
View that is shown if a community member has XSEDE/Globus access,
but is missing allocation-sources (no way to charge activity).
"""
# populate with values `site_metadata` in the future
template_params = {}
template_params['THEME_URL'] = "/assets/theme"
template_params['ORG_NAME'] = settings.ORG_NAME
if hasattr(settings, "BASE_URL"):
template_params['BASE_URL'] = settings.BASE_URL
response = render_to_response(
'allocations.html',
template_params,
context_instance=RequestContext(request)
)
return response
|
import logging
from django.conf import settings
from django.shortcuts import render, redirect, render_to_response
from django.template import RequestContext
logger = logging.getLogger(__name__)
def allocations(request):
"""
View that is shown if a community member has XSEDE/Globus access,
but is missing allocation-sources (no way to charge activity).
"""
# populate with values `site_metadata` in the future
template_params = {}
template_params['THEME_URL'] = "/themes/%s" % settings.THEME_NAME
template_params['ORG_NAME'] = settings.ORG_NAME
if hasattr(settings, "BASE_URL"):
template_params['BASE_URL'] = settings.BASE_URL
response = render_to_response(
'allocations.html',
template_params,
context_instance=RequestContext(request)
)
return response
|
Fix for calling a static method | <?php
namespace vsc\application\controllers;
use vsc\presentation\requests\HttpRequestA;
use vsc\presentation\views\ExceptionView;
use vsc\presentation\views\ViewA;
class ContentTypeController extends FrontControllerA {
public static function isValidContentType($sContentType) {}
public function getAvailableContentTypes() {}
public function getController() {}
/**
* @returns ViewA
*/
public function getDefaultView() {
}
/**
* @param HttpRequestA $oRequest
* @param null $oProcessor
* @return \vsc\presentation\responses\HttpResponseA
*/
public function getResponse(HttpRequestA $oRequest, $oProcessor = null) {
}
/**
* @param HttpRequestA $oRequest
* @param null $oProcessor
* @return \vsc\presentation\responses\HttpResponse|\vsc\presentation\responses\HttpResponseA
*/
public function getErrorResponse(HttpRequestA $oRequest, $oProcessor = null) {
}
/**
* @returns ViewA
* @throws ExceptionView
*/
public function getView() {
}
}
| <?php
namespace vsc\application\controllers;
use vsc\presentation\requests\HttpRequestA;
use vsc\presentation\views\ExceptionView;
use vsc\presentation\views\ViewA;
class ContentTypeController extends FrontControllerA {
public function isValidContentType($sContentType) {}
public function getAvailableContentTypes() {}
public function getController() {}
/**
* @returns ViewA
*/
public function getDefaultView() {
}
/**
* @param HttpRequestA $oRequest
* @param null $oProcessor
* @return \vsc\presentation\responses\HttpResponseA
*/
public function getResponse(HttpRequestA $oRequest, $oProcessor = null) {
}
/**
* @param HttpRequestA $oRequest
* @param null $oProcessor
* @return \vsc\presentation\responses\HttpResponse|\vsc\presentation\responses\HttpResponseA
*/
public function getErrorResponse(HttpRequestA $oRequest, $oProcessor = null) {
}
/**
* @returns ViewA
* @throws ExceptionView
*/
public function getView() {
}
}
|
Return the error result of MkdirAll to be handled by the caller. | package datalayer
import (
"os"
"path/filepath"
"regexp"
)
const MAX_VOLUME_NAME_LENGTH int = 40
// ClusterHQ data layer, naive vfs (directory-based) implementation
func ValidVolumeName(volumeName string) bool {
var validVolumeRegex = regexp.MustCompile(`^[a-zA-Z]+[a-zA-Z0-9-]*$`)
return validVolumeRegex.MatchString(volumeName) && len(volumeName) <= MAX_VOLUME_NAME_LENGTH
}
func VolumeExists(basePath string, volumeName string) bool {
volumePath := filepath.FromSlash(basePath + "/" + volumeName)
_, err := os.Stat(volumePath)
return err == nil
}
func CreateVolume(basePath string, volumeName string) error {
volumePath := filepath.FromSlash(basePath + "/" + volumeName)
// TODO Factor this into a data layer object.
return os.MkdirAll(volumePath, 0777) // XXX SEC
}
func CreateVariant(basePath, volumeName, variantName string) error {
// XXX Variants are meant to be tagged commits???
variantPath := filepath.FromSlash(basePath + "/" + volumeName + "/branches/master")
return os.MkdirAll(variantPath, 0777) // XXX SEC
}
| package datalayer
import (
"os"
"path/filepath"
"regexp"
)
const MAX_VOLUME_NAME_LENGTH int = 40
// ClusterHQ data layer, naive vfs (directory-based) implementation
func ValidVolumeName(volumeName string) bool {
var validVolumeRegex = regexp.MustCompile(`^[a-zA-Z]+[a-zA-Z0-9-]*$`)
return validVolumeRegex.MatchString(volumeName) && len(volumeName) <= MAX_VOLUME_NAME_LENGTH
}
func VolumeExists(basePath string, volumeName string) bool {
volumePath := filepath.FromSlash(basePath + "/" + volumeName)
_, err := os.Stat(volumePath)
return err == nil
}
func CreateVolume(basePath string, volumeName string) error {
volumePath := filepath.FromSlash(basePath + "/" + volumeName)
// TODO Factor this into a data layer object.
os.MkdirAll(volumePath, 0777) // XXX SEC
return nil
}
func CreateVariant(basePath, volumeName, variantName string) error {
// XXX Variants are meant to be tagged commits???
variantPath := filepath.FromSlash(basePath + "/" + volumeName + "/branches/master")
os.MkdirAll(variantPath, 0777) // XXX SEC
return nil
}
|
Revert system names to normal | from django.db import models
from cyder.base.mixins import ObjectUrlMixin
from cyder.base.models import BaseModel
from cyder.base.helpers import get_display
from cyder.cydhcp.keyvalue.models import KeyValue
class System(BaseModel, ObjectUrlMixin):
name = models.CharField(max_length=255, unique=False)
search_fields = ('name',)
display_fields = ('name',)
def __str__(self):
return get_display(self)
class Meta:
db_table = 'system'
def details(self):
"""For tables."""
data = super(System, self).details()
data['data'] = [
('Name', 'name', self),
]
return data
@staticmethod
def eg_metadata():
"""EditableGrid metadata."""
return {'metadata': [
{'name': 'name', 'datatype': 'string', 'editable': True},
]}
class SystemKeyValue(KeyValue):
system = models.ForeignKey(System, null=False)
class Meta:
db_table = 'system_key_value'
unique_together = ('key', 'value', 'system')
| from django.db import models
from cyder.base.mixins import ObjectUrlMixin
from cyder.base.models import BaseModel
from cyder.cydhcp.keyvalue.models import KeyValue
class System(BaseModel, ObjectUrlMixin):
name = models.CharField(max_length=255, unique=False)
search_fields = ('name',)
display_fields = ('name', 'pk')
def __str__(self):
return "{0} : {1}".format(*(str(getattr(self, f))
for f in self.display_fields))
class Meta:
db_table = 'system'
def details(self):
"""For tables."""
data = super(System, self).details()
data['data'] = [
('Name', 'name', self),
]
return data
@staticmethod
def eg_metadata():
"""EditableGrid metadata."""
return {'metadata': [
{'name': 'name', 'datatype': 'string', 'editable': True},
]}
class SystemKeyValue(KeyValue):
system = models.ForeignKey(System, null=False)
class Meta:
db_table = 'system_key_value'
unique_together = ('key', 'value', 'system')
|
Set correct noDevMode in composer | <?php
namespace Fiddler\Composer;
use Fiddler\Build;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
use Composer\Script\Event;
use Composer\EventDispatcher\EventSubscriberInterface;
class Plugin implements PluginInterface, EventSubscriberInterface
{
/**
* @var \Fiddler\Build
*/
private $build;
public function __construct(Build $build = null)
{
$this->build = $build;
}
public function activate(Composer $composer, IOInterface $io)
{
$this->build = $this->build ?: new Build($io);
}
public static function getSubscribedEvents()
{
return [
'post-autoload-dump' => 'generateMonorepoAutoloads',
];
}
/**
* Delegate autoload dump to all the fiddler monorepo subdirectories.
*/
public function generateMonorepoAutoloads(Event $event)
{
$flags = $event->getFlags();
$optimize = isset($flags['optimize']) ? $flags['optimize'] : false;
$this->build->build(getcwd(), $optimize, !$event->isDevMode());
}
}
| <?php
namespace Fiddler\Composer;
use Fiddler\Build;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
use Composer\Script\Event;
use Composer\EventDispatcher\EventSubscriberInterface;
class Plugin implements PluginInterface, EventSubscriberInterface
{
/**
* @var \Fiddler\Build
*/
private $build;
public function __construct(Build $build = null)
{
$this->build = $build;
}
public function activate(Composer $composer, IOInterface $io)
{
$this->build = $this->build ?: new Build($io);
}
public static function getSubscribedEvents()
{
return [
'post-autoload-dump' => 'generateMonorepoAutoloads',
];
}
/**
* Delegate autoload dump to all the fiddler monorepo subdirectories.
*/
public function generateMonorepoAutoloads(Event $event)
{
$flags = $event->getFlags();
$optimize = isset($flags['optimize']) ? $flags['optimize'] : false;
$this->build->build(getcwd(), $optimize, $event->isDevMode());
}
}
|
Add case of multiple indexes | package main
import (
"reflect"
"testing"
)
var parseIndexesListTests = []struct {
list string
indexes []int
}{
// Only one index
{
list: "10",
indexes: []int{10},
},
{
list: "120",
indexes: []int{120},
},
// Multiple indexes
{
list: "10,120",
indexes: []int{10, 120},
},
{
list: "10,120,50",
indexes: []int{10, 120, 50},
},
{
list: "3,2,1,0",
indexes: []int{3, 2, 1, 0},
},
}
func TestParseIndexesList(t *testing.T) {
for _, test := range parseIndexesListTests {
expect := test.indexes
actual, err := parseIndexesList(test.list)
if err != nil {
t.Errorf("parseIndexesList(%q) returns %q, want nil",
test.list, err)
}
if !reflect.DeepEqual(actual, expect) {
t.Error("parseIndexesList(%q) = %v, want %v",
test.list, actual, expect)
}
}
}
| package main
import (
"reflect"
"testing"
)
var parseIndexesListTests = []struct {
list string
indexes []int
}{
// Only one index
{
list: "10",
indexes: []int{10},
},
{
list: "120",
indexes: []int{120},
},
}
func TestParseIndexesList(t *testing.T) {
for _, test := range parseIndexesListTests {
expect := test.indexes
actual, err := parseIndexesList(test.list)
if err != nil {
t.Errorf("parseIndexesList(%q) returns %q, want nil",
test.list, err)
}
if !reflect.DeepEqual(actual, expect) {
t.Error("parseIndexesList(%q) = %v, want %v",
test.list, actual, expect)
}
}
}
|
Add get String from resource | package com.naijab.nextzytimeline.utility;
import android.content.Context;
import android.support.annotation.NonNull;
import com.naijab.nextzytimeline.R;
public class StringUtility {
@NonNull
public static String getSaveSuccess(Context context) {
return context.getResources().getString(R.string.save_success);
}
@NonNull
public static String getSaveError(Context context) {
return context.getResources().getString(R.string.save_error);
}
@NonNull
public static String getDeleteSuccess(Context context){
return context.getResources().getString(R.string.delete_success);
}
@NonNull
public static String getDeleteError(Context context){
return context.getResources().getString(R.string.delete_error);
}
}
| package com.naijab.nextzytimeline.utility;
import android.content.Context;
import android.support.annotation.NonNull;
import com.naijab.nextzytimeline.R;
public class StringUtility {
@NonNull
public static String getHomeString(Context context) {
return context.getResources().getString(R.string.tab_home);
}
@NonNull
public static String getAboutString(Context context) {
return context.getResources().getString(R.string.tab_about);
}
@NonNull
public static String getContactString(Context context) {
return context.getResources().getString(R.string.tab_contact);
}
@NonNull
public static String getSaveSuccess(Context context) {
return context.getResources().getString(R.string.save_success);
}
@NonNull
public static String getDeleteSuccess(Context context){
return context.getResources().getString(R.string.delete_success);
}
}
|
Remove test print and use better practice to get path of gen.py | """
CLI Entry point for respawn
"""
from docopt import docopt
from schema import Schema, Use, Or
from subprocess import check_call, CalledProcessError
from pkg_resources import require
import respawn
import os
def generate():
"""Generate CloudFormation Template from YAML Specifications
Usage:
respawn <yaml>
respawn --help
respawn --version
Options:
--help
This usage information
--version
Package version
"""
version = require("respawn")[0].version
args = docopt(generate.__doc__, version=version)
scheme = Schema({
'<yaml>': Use(str),
'--help': Or(True, False),
'--version': Or(True, False),
})
args = scheme.validate(args)
# The pyplates library takes a python script that specifies options
# that is not in scope. As a result, the file cannot be imported, so
# the path of the library is used and gen.py is appended
gen_location = os.path.join(os.path.dirname(respawn.__file__), "gen.py")
try:
check_call(["cfn_py_generate", gen_location, "-o", args['<yaml>']])
return 0
except CalledProcessError:
return 1
| """
CLI Entry point for respawn
"""
from docopt import docopt
from schema import Schema, Use, Or
from subprocess import check_call, CalledProcessError
from pkg_resources import require
import respawn
def generate():
"""Generate CloudFormation Template from YAML Specifications
Usage:
respawn <yaml>
respawn --help
respawn --version
Options:
--help
This usage information
--version
Package version
"""
version = require("respawn")[0].version
args = docopt(generate.__doc__, version=version)
scheme = Schema({
'<yaml>': Use(str),
'--help': Or(True, False),
'--version': Or(True, False),
})
args = scheme.validate(args)
gen_location = "/".join(respawn.__file__.split("/")[:-1]) + "/gen.py"
print gen_location
try:
check_call(["cfn_py_generate", gen_location, "-o", args['<yaml>']])
return 0
except CalledProcessError, e:
return 1
|
Set identifier to undefined when setting geo in area filter reducer | import {
FILTER_BY_AREA_TYPE,
FILTER_BY_AREA_IDENTIFIER,
FILTER_BY_AREA_CUSTOM,
} from '../constants/action_types';
const defaultState = {
area: 'Citywide',
identifier: undefined,
latLons: []
};
export default (state = defaultState, action) => {
switch (action.type) {
case FILTER_BY_AREA_TYPE:
return {
...state,
geo: action.geo,
identifier: undefined,
};
case FILTER_BY_AREA_IDENTIFIER:
return {
...state,
identifier: action.identifier,
};
case FILTER_BY_AREA_CUSTOM:
return {
...state,
latLons: action.latLons
};
default:
return state;
}
};
| import {
FILTER_BY_AREA_TYPE,
FILTER_BY_AREA_IDENTIFIER,
FILTER_BY_AREA_CUSTOM,
} from '../constants/action_types';
const defaultState = {
area: 'Citywide',
identifier: undefined,
latLons: []
};
export default (state = defaultState, action) => {
switch (action.type) {
case FILTER_BY_AREA_TYPE:
return {
...state,
geo: action.geo,
};
case FILTER_BY_AREA_IDENTIFIER:
return {
...state,
identifier: action.identifier,
};
case FILTER_BY_AREA_CUSTOM:
return {
...state,
latLons: action.latLons
};
default:
return state;
}
};
|
Install npm packages for client/server before building | var gulp = require('gulp');
var tslint = require('gulp-tslint');
var shell = require('gulp-shell')
var serverFiles = {
src: 'server/src/**/*.ts'
};
var clientFiles = {
src: 'client/src/**/*.ts'
}
gulp.task('compileClient', shell.task([
'cd client && npm install && tsc -p .'
]));
gulp.task('compileServer', shell.task([
'cd server && npm install && tsc -p .'
]));
gulp.task('tslint', function () {
return gulp.src([serverFiles.src, clientFiles.src])
.pipe(tslint({
formatter: "verbose"
}))
.pipe(tslint.report())
});
gulp.task('default', ['compileServer', 'compileClient', 'tslint']);
| var gulp = require('gulp');
var tslint = require('gulp-tslint');
var shell = require('gulp-shell')
var serverFiles = {
src: 'server/src/**/*.ts'
};
var clientFiles = {
src: 'client/src/**/*.ts'
}
gulp.task('compileClient', shell.task([
'cd client && tsc -p .'
]));
gulp.task('compileServer', shell.task([
'cd server && tsc -p .'
]));
gulp.task('tslint', function () {
return gulp.src([serverFiles.src, clientFiles.src])
.pipe(tslint({
formatter: "verbose"
}))
.pipe(tslint.report())
});
gulp.task('default', ['compileServer', 'compileClient', 'tslint']);
|
Fix inverted logic on the logging expired details check | <?php
class SV_IntegratedReports_XenForo_Model_Warning extends XFCP_SV_IntegratedReports_XenForo_Model_Warning
{
public function processExpiredWarnings()
{
SV_IntegratedReports_Model_WarningLog::$UseSystemUsernameForComments = true;
$options = XenForo_Application::getOptions();
if (!$options->sv_ir_log_to_report_natural_warning_expire)
{
SV_IntegratedReports_Model_WarningLog::$SupressLoggingWarningToReport = true;
}
try
{
parent::processExpiredWarnings();
}
finally
{
SV_IntegratedReports_Model_WarningLog::$UseSystemUsernameForComments = false;
SV_IntegratedReports_Model_WarningLog::$SupressLoggingWarningToReport = false;
}
}
} | <?php
class SV_IntegratedReports_XenForo_Model_Warning extends XFCP_SV_IntegratedReports_XenForo_Model_Warning
{
public function processExpiredWarnings()
{
SV_IntegratedReports_Model_WarningLog::$UseSystemUsernameForComments = true;
$options = XenForo_Application::getOptions();
if ($options->sv_ir_log_to_report_natural_warning_expire)
{
SV_IntegratedReports_Model_WarningLog::$SupressLoggingWarningToReport = true;
}
try
{
parent::processExpiredWarnings();
}
finally
{
SV_IntegratedReports_Model_WarningLog::$UseSystemUsernameForComments = false;
SV_IntegratedReports_Model_WarningLog::$SupressLoggingWarningToReport = false;
}
}
} |
Address review comment: Better function name. | """
Cross-process log tracing: HTTP client.
"""
from __future__ import unicode_literals
import sys
import requests
from eliot import Logger, to_file, start_action
to_file(sys.stdout)
logger = Logger()
def remote_divide(x, y):
with start_action(logger, "http_request", x=x, y=y) as action:
task_id = action.serialize_task_id()
response = requests.get(
"http://localhost:5000/?x={}&y={}".format(x, y),
headers={"x-eliot-task-id": task_id})
response.raise_for_status() # ensure this is a successful response
result = float(response.text)
action.add_success_fields(result=result)
return result
if __name__ == '__main__':
with start_action(logger, "main"):
remote_divide(int(sys.argv[1]), int(sys.argv[2]))
| """
Cross-process log tracing: HTTP client.
"""
from __future__ import unicode_literals
import sys
import requests
from eliot import Logger, to_file, start_action
to_file(sys.stdout)
logger = Logger()
def request(x, y):
with start_action(logger, "http_request", x=x, y=y) as action:
task_id = action.serialize_task_id()
response = requests.get(
"http://localhost:5000/?x={}&y={}".format(x, y),
headers={"x-eliot-task-id": task_id})
response.raise_for_status() # ensure this is a successful response
result = float(response.text)
action.add_success_fields(result=result)
return result
if __name__ == '__main__':
with start_action(logger, "main"):
request(int(sys.argv[1]), int(sys.argv[2]))
|
Fix args.file and remove stat from argparse | #!/usr/bin/env python
# encoding: utf-8
import sys
import re
import argparse
import fileinput
from argparse import RawDescriptionHelpFormatter
from patterns import pre_patterns
def prepare(infile, outfile=sys.stdout):
"""
Apply pre_patterns from patterns to infile
:infile: input file
"""
try:
for line in infile:
result = line
for pattern in pre_patterns:
result = re.sub(pattern[0], pattern[1], result, re.VERBOSE)
outfile.write(result)
except (KeyboardInterrupt):
pass
except:
raise
def main():
parser = argparse.ArgumentParser(description=\
"""
Parse file[s]\n\n
examlpe: cat error_log | tail -n 1000 | ./direlog.py
""", formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('file', nargs='*', default=[],
help='file[s] to do some work')
args = parser.parse_args()
input_stream = fileinput.input(args.file)
prepare(input_stream)
pass
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# encoding: utf-8
import sys
import re
import argparse
import fileinput
from argparse import RawDescriptionHelpFormatter
from patterns import pre_patterns
def prepare(infile, outfile=sys.stdout):
"""
Apply pre_patterns from patterns to infile
:infile: input file
"""
try:
for line in infile:
result = line
for pattern in pre_patterns:
result = re.sub(pattern[0], pattern[1], result, re.VERBOSE)
outfile.write(result)
except (KeyboardInterrupt):
pass
except:
raise
def main():
parser = argparse.ArgumentParser(description=\
"""
Parse file[s]\n\n
examlpe: cat error_log | tail -n 1000 | ./direlog.py
""", formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('file', nargs='*', default=[],
help='file[s] to do some work')
parser.add_argument('-s', '--stat', action='store_const', const=True,
help='get statistics')
args = parser.parse_args()
input_stream = fileinput.input(args.stat)
prepare(input_stream)
pass
if __name__ == '__main__':
main()
|
Add method to get all saved timetables | package com.mick88.dittimetable;
import java.util.List;
import android.content.Context;
import android.util.Log;
import com.michaldabski.msqlite.MSQLiteOpenHelper;
import com.mick88.dittimetable.timetable.Timetable;
public class DatabaseHelper extends MSQLiteOpenHelper
{
private static final String name = "timetables.db";
private static final int version = 1;
private static final String TAG = "SQLite";
public DatabaseHelper(Context context) {
super(context, name, null, version, new Class<?>[]{
Timetable.class,
});
}
public Timetable getTimetable(String course, int year, String weeks)
{
List<Timetable> timetables = select(Timetable.class, "course=? AND year=? and weekRange=?",
new String[]{course, String.valueOf(year), weeks},
null, "1");
if (timetables.isEmpty()) return null;
Log.d(TAG, "Timetable loaded: "+timetables.get(0).describe());
return timetables.get(0);
}
public void saveTimetable(Timetable timetable)
{
replace(timetable);
Log.d(TAG, "Timetable saved: "+timetable.describe());
}
/**
* returns all timetables saved in database
* @return
*/
public List<Timetable> getSavedTimetables()
{
return selectAll(Timetable.class);
}
}
| package com.mick88.dittimetable;
import java.util.List;
import android.content.Context;
import android.util.Log;
import com.michaldabski.msqlite.MSQLiteOpenHelper;
import com.mick88.dittimetable.timetable.Timetable;
public class DatabaseHelper extends MSQLiteOpenHelper
{
private static final String name = "timetables.db";
private static final int version = 1;
private static final String TAG = "SQLite";
public DatabaseHelper(Context context) {
super(context, name, null, version, new Class<?>[]{
Timetable.class,
});
}
public Timetable getTimetable(String course, int year, String weeks)
{
List<Timetable> timetables = select(Timetable.class, "course=? AND year=? and weekRange=?",
new String[]{course, String.valueOf(year), weeks},
null, "1");
if (timetables.isEmpty()) return null;
Log.d(TAG, "Timetable loaded: "+timetables.get(0).describe());
return timetables.get(0);
}
public void saveTimetable(Timetable timetable)
{
replace(timetable);
Log.d(TAG, "Timetable saved: "+timetable.describe());
}
}
|
Change self-reported version from 0.1.0 to 0.4.1 | # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at:
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the
# License.
# Python 2/3 compatibility
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__author__ = 'Amazon.com, Inc.'
__version__ = '0.4.1'
__all__ = [
'core',
'exceptions',
'reader',
'reader_binary',
'reader_managed',
'simple_types',
'simpleion',
'symbols',
'util',
'writer',
'writer_binary',
'writer_binary_raw',
'writer_binary_raw_fields',
'writer_buffer',
'writer_text',
]
| # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at:
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the
# License.
# Python 2/3 compatibility
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__author__ = 'Amazon.com, Inc.'
__version__ = '0.1.0'
__all__ = [
'core',
'exceptions',
'reader',
'reader_binary',
'reader_managed',
'simple_types',
'simpleion',
'symbols',
'util',
'writer',
'writer_binary',
'writer_binary_raw',
'writer_binary_raw_fields',
'writer_buffer',
'writer_text',
]
|
Fix capitalization of views imported | "use strict";
const Promise = require('bluebird');
const Task = require('../Task');
const path = require('path');
const ProjectType = require('../../ProjectType');
const fs = require('fs');
class ViewImportTask extends Task {
constructor(buildManager, taskRunner) {
super(buildManager, taskRunner);
this.availableTo = [ProjectType.FRONTEND];
}
action() {
var _ = require('lodash');
var views = require('../../RequireViews')({
dirname: path.join(process.cwd(), this._buildManager.options.views),
filter: /(.+)\.tsx$/,
map: function (name) {
return name[0].toUpperCase() + name.slice(1);
}
});
const exportFolder = path.join(process.cwd(), this._buildManager.options.views, 'export.js');
process.env.EXPORT_VIEWS_PATH = exportFolder;
fs.writeFileSync(exportFolder, 'module.exports = ' + JSON.stringify(views).replace(/"/gmi, ''));
return Promise.resolve();
}
}
module.exports = ViewImportTask; | "use strict";
const Promise = require('bluebird');
const Task = require('../Task');
const path = require('path');
const ProjectType = require('../../ProjectType');
const fs = require('fs');
class ViewImportTask extends Task {
constructor(buildManager, taskRunner) {
super(buildManager, taskRunner);
this.availableTo = [ProjectType.FRONTEND];
}
action() {
var _ = require('lodash');
var views = require('../../RequireViews')({
dirname: path.join(process.cwd(), this._buildManager.options.views),
filter: /(.+)\.tsx$/,
map: function (name) {
return _.capitalize(name);
}
});
const exportFolder = path.join(process.cwd(), this._buildManager.options.views, 'export.js');
process.env.EXPORT_VIEWS_PATH = exportFolder;
fs.writeFileSync(exportFolder, 'module.exports = ' + JSON.stringify(views).replace(/"/gmi, ''));
return Promise.resolve();
}
}
module.exports = ViewImportTask; |
Check stdout with --debug for actual ddl | """"Test adapter specific config options."""
from test.integration.base import DBTIntegrationTest, use_profile
import textwrap
import yaml
class TestBigqueryAdapterSpecific(DBTIntegrationTest):
@property
def schema(self):
return "bigquery_test_022"
@property
def models(self):
return "adapter-specific-models"
@property
def profile_config(self):
return self.bigquery_profile()
@property
def project_config(self):
return yaml.safe_load(textwrap.dedent('''\
config-version: 2
models:
test:
materialized: table
expiring_table:
time_to_expiration: 4
'''))
@use_profile('bigquery')
def test_bigquery_time_to_expiration(self):
_, stdout = self.run_dbt_and_capture(['run', '--debug'])
self.assertIn(
'expiration_timestamp: TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL '
'4 hour)', stdout)
| """"Test adapter specific config options."""
from test.integration.base import DBTIntegrationTest, use_profile
import textwrap
import yaml
class TestBigqueryAdapterSpecific(DBTIntegrationTest):
@property
def schema(self):
return "bigquery_test_022"
@property
def models(self):
return "adapter-specific-models"
@property
def profile_config(self):
return self.bigquery_profile()
@property
def project_config(self):
return yaml.safe_load(textwrap.dedent('''\
config-version: 2
models:
test:
materialized: table
expiring_table:
time_to_expiration: 4
'''))
@use_profile('bigquery')
def test_bigquery_time_to_expiration(self):
results = self.run_dbt()
self.assertIn(
'expiration_timestamp: TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL '
'4 hour)', results[0].node.injected_sql)
|
Upgrade openfisca core to v4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='OpenFisca-Senegal',
version='0.0.0',
author='OpenFisca Team',
author_email='contact@openfisca.fr',
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description=u'Senegalese tax and benefit system for OpenFisca',
keywords='benefit microsimulation senegal social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
url='https://github.com/openfisca/openfisca-senegal',
data_files=[
('share/openfisca/openfisca-senegal',
['CHANGELOG.md', 'LICENSE', 'README.md']),
],
extras_require={
'test': ['nose'],
},
install_requires=[
'OpenFisca-Core >= 4.1.4b1, < 5.0',
'notebook',
],
packages=find_packages(exclude=['openfisca_senegal.tests*']),
test_suite='nose.collector',
)
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='OpenFisca-Senegal',
version='0.0.0',
author='OpenFisca Team',
author_email='contact@openfisca.fr',
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description=u'Senegalese tax and benefit system for OpenFisca',
keywords='benefit microsimulation senegal social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
url='https://github.com/openfisca/openfisca-senegal',
data_files=[
('share/openfisca/openfisca-senegal',
['CHANGELOG.md', 'LICENSE', 'README.md']),
],
extras_require={
'test': ['nose'],
},
install_requires=[
'OpenFisca-Core >= 3.0.0, < 4.0',
'notebook',
],
packages=find_packages(exclude=['openfisca_senegal.tests*']),
test_suite='nose.collector',
)
|
Use much better function name | import classNames from 'classnames';
import React from 'react';
import FormGroupHeadingContent from './FormGroupHeadingContent';
function injectAsteriskNode(children) {
const asteriskNode = (
<FormGroupHeadingContent className="text-danger" key="asterisk">
*
</FormGroupHeadingContent>
);
const nextChildren = React.Children.toArray(children);
nextChildren.splice(1, 0, asteriskNode);
return nextChildren;
}
function FormGroupHeading({className, children, required}) {
const classes = classNames('form-group-heading', className);
return (
<div className={classes}>
{required ? injectAsteriskNode(children) : children}
</div>
);
}
FormGroupHeading.defaultProps = {
required: false
};
FormGroupHeading.propTypes = {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object,
React.PropTypes.string
]),
required: React.PropTypes.bool
};
module.exports = FormGroupHeading;
| import classNames from 'classnames';
import React from 'react';
import FormGroupHeadingContent from './FormGroupHeadingContent';
function getModifiedChildren(children) {
const asteriskNode = (
<FormGroupHeadingContent className="text-danger" key="asterisk">
*
</FormGroupHeadingContent>
);
const nextChildren = React.Children.toArray(children);
nextChildren.splice(1, 0, asteriskNode);
return nextChildren;
}
function FormGroupHeading({className, children, required}) {
const classes = classNames('form-group-heading', className);
return (
<div className={classes}>
{required ? getModifiedChildren(children) : children}
</div>
);
}
FormGroupHeading.defaultProps = {
required: false
};
FormGroupHeading.propTypes = {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object,
React.PropTypes.string
]),
required: React.PropTypes.bool
};
module.exports = FormGroupHeading;
|
Add client keys to config | module.exports = {
// API Port
port: 3000,
// Log file (check for errors here)
log: 'app.log',
// Database to save users and other data to
mongo: {
uri: 'mongodb://localhost:27017/test'
},
// Redis is used for caching
redis: {
host: '127.0.0.1',
port: 6379
},
// SendGrid account info for sending emails
// This is the account info you use to log into the SendGrid website
sendgrid: {
username: 'username',
password: 'password',
from: 'me@example.com',
fromname: 'First Last'
},
// Users to be added to the db upon starting the app. Useful for adding an initial admin
users: [{
email: 'user@example.com',
password: 'password123',
role: 'attendee|staff|admin'
}],
// A list of enabled client IDs
// Clients must use one of these IDs to get a token for a user
clients: [
'abcdefg123456',
'hijklmn789012'
]
};
| module.exports = {
// API Port
port: 3000,
// Log file (check for errors here)
log: 'app.log',
// Database to save users and other data to
mongo: {
uri: 'mongodb://localhost:27017/test'
},
// Redis is used for caching
redis: {
host: '127.0.0.1',
port: 6379
},
// SendGrid account info for sending emails
// This is the account info you use to log into the SendGrid website
sendgrid: {
username: 'username',
password: 'password',
from: 'me@example.com',
fromname: 'First Last'
},
// Users to be added to the db upon starting the app. Useful for adding an initial admin
users: [{
email: 'user@example.com',
password: 'password123',
role: 'attendee|staff|admin'
}]
};
|
Bump version number for future release. | from setuptools import setup, find_packages
setup (
name = 'hypnotoad',
version = '0.1.2',
author = 'Jon Bringhurst',
author_email = 'jonb@lanl.gov',
url = 'https://www.git.lanl.gov/rm/hypnotoad',
license = 'LICENSE.txt',
scripts = ['hypnotoad/bin/hypnotoad'],
long_description = open('README.txt').read(),
description = 'A utility that aids in transporting directory ' +
'information from one or more data sources to various ' +
'applications on a cluster using a standard interface. ' +
'Not Zoidberg.',
packages = find_packages(),
)
# EOF
| from setuptools import setup, find_packages
setup (
name = 'hypnotoad',
version = '0.1.1',
author = 'Jon Bringhurst',
author_email = 'jonb@lanl.gov',
url = 'https://www.git.lanl.gov/rm/hypnotoad',
license = 'LICENSE.txt',
scripts = ['hypnotoad/bin/hypnotoad'],
long_description = open('README.txt').read(),
description = 'A utility that aids in transporting directory ' +
'information from one or more data sources to various ' +
'applications on a cluster using a standard interface. ' +
'Not Zoidberg.',
packages = find_packages(),
)
# EOF
|
Fix logic for determining whether users can add tags to a discussion | <?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Tags\Access;
use Flarum\Tags\Tag;
use Flarum\User\Access\AbstractPolicy;
use Flarum\User\User;
class TagPolicy extends AbstractPolicy
{
/**
* @param User $actor
* @param Tag $tag
* @return bool|null
*/
public function startDiscussion(User $actor, Tag $tag)
{
if ($tag->is_restricted) {
return $actor->hasPermission('tag'.$tag->id.'.startDiscussion') ? $this->allow() : $this->deny();
}
}
/**
* @param User $actor
* @param Tag $tag
* @return bool|null
*/
public function addToDiscussion(User $actor, Tag $tag)
{
return $actor->can('startDiscussion', $tag);
}
}
| <?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Tags\Access;
use Flarum\Tags\Tag;
use Flarum\User\Access\AbstractPolicy;
use Flarum\User\User;
class TagPolicy extends AbstractPolicy
{
/**
* @param User $actor
* @param Tag $tag
* @return bool|null
*/
public function startDiscussion(User $actor, Tag $tag)
{
if ($tag->is_restricted) {
return $actor->hasPermission('tag'.$tag->id.'.startDiscussion') ? $this->allow() : $this->deny();
}
}
/**
* @param User $actor
* @param Tag $tag
* @return bool|null
*/
public function addToDiscussion(User $actor, Tag $tag)
{
return $this->startDiscussion($actor, $tag);
}
}
|
Write error if no matching gifs are found | # -*- coding: utf-8 -*-
#
# Insert a random giphy URL based on a search
#
# Usage: /giphy search
#
# History:
#
# Version 1.0.2: Write text if no matches are found
# Version 1.0.1: Auto post gif URL along with query string
# Version 1.0.0: initial release
#
import requests
import weechat
URL = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=%s"
def giphy(data, buf, args):
search = args.replace(" ", "+")
response = requests.get(URL % search)
data = response.json()
try:
image_url = data["data"]["image_url"]
except TypeError:
image_url = "No matches found"
weechat.command(buf, " /giphy %s -- %s" % (search, image_url))
return weechat.WEECHAT_RC_OK
def main():
if not weechat.register("giphy", "Keith Smiley", "1.0.0", "MIT",
"Insert a random giphy URL", "", ""):
return weechat.WEECHAT_RC_ERROR
weechat.hook_command("giphy", "Insert a random giphy URL", "",
"", "", "giphy", "")
if __name__ == "__main__":
main()
| # -*- coding: utf-8 -*-
#
# Insert a random giphy URL based on a search
#
# Usage: /giphy search
#
# History:
#
# Version 1.0.1: Auto post gif URL along with query string
# Version 1.0.0: initial release
#
import requests
import weechat
URL = "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=%s"
def giphy(data, buf, args):
search = args.replace(" ", "+")
response = requests.get(URL % search)
data = response.json()
image_url = data["data"]["image_url"]
weechat.command(buf, " /giphy %s -- %s" % (search, image_url))
return weechat.WEECHAT_RC_OK
def main():
if not weechat.register("giphy", "Keith Smiley", "1.0.0", "MIT",
"Insert a random giphy URL", "", ""):
return weechat.WEECHAT_RC_ERROR
weechat.hook_command("giphy", "Insert a random giphy URL", "",
"", "", "giphy", "")
if __name__ == "__main__":
main()
|
Remove test moved to plugin. | #!/usr/bin/python -S
"""
xrender_test.py: Tests for xrender.py
"""
import unittest
import xrender # module under test
CSV = """\
name,age
<carol>,10
<dave>,20
"""
class FunctionsTest(unittest.TestCase):
def testGuessFileType(self):
self.assertEqual('png', xrender.GuessFileType('Rplot001.png'))
self.assertEqual('ansi', xrender.GuessFileType('typescript'))
def testCleanFilename(self):
print xrender.CleanFilename('foo-bar_baz')
print xrender.CleanFilename('foo bar')
print xrender.CleanFilename('foo bar <>&')
print xrender.CleanFilename('foo bar \\ @ ')
class ResourcesTest(unittest.TestCase):
def testResources(self):
res = xrender.Resources()
p = res.GetPluginBin('ansi')
print p
p = res.GetPluginBin('unknown')
print p
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/python -S
"""
xrender_test.py: Tests for xrender.py
"""
import unittest
import xrender # module under test
CSV = """\
name,age
<carol>,10
<dave>,20
"""
class FunctionsTest(unittest.TestCase):
def testRenderCsv(self):
html, orig = xrender.RenderCsv('dir/foo.csv', 'foo.csv', CSV)
print html
def testGuessFileType(self):
self.assertEqual('png', xrender.GuessFileType('Rplot001.png'))
self.assertEqual('ansi', xrender.GuessFileType('typescript'))
def testCleanFilename(self):
print xrender.CleanFilename('foo-bar_baz')
print xrender.CleanFilename('foo bar')
print xrender.CleanFilename('foo bar <>&')
print xrender.CleanFilename('foo bar \\ @ ')
class ResourcesTest(unittest.TestCase):
def testResources(self):
res = xrender.Resources()
p = res.GetPluginBin('ansi')
print p
p = res.GetPluginBin('unknown')
print p
if __name__ == '__main__':
unittest.main()
|
Fix JS task to be async. Should fix travis. | 'use strict';
var gulp = require('gulp');
var config = require('./_config.js');
var paths = config.paths;
var $ = config.plugins;
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var istanbul = require('browserify-istanbul');
gulp.task('clean', function () {
return gulp.src(paths.tmp, { read: false })
.pipe($.rimraf());
});
gulp.task('build', ['index.html', 'js', 'css']);
gulp.task('index.html', function () {
return gulp.src(paths.app + '/index.jade')
.pipe($.jade({
pretty: true
}))
.pipe(gulp.dest(paths.tmp));
});
gulp.task('jade', function () {
return gulp.src(paths.app + '/*.html')
.pipe(gulp.dest(paths.tmp));
});
gulp.task('js', function () {
var bundleStream = browserify(paths.app + '/js/main.js')
.transform(istanbul)
.bundle();
return bundleStream
.pipe(source(paths.app + '/js/main.js'))
.pipe($.rename('main.js'))
.pipe(gulp.dest(paths.tmp + '/js/'));
});
gulp.task('css', function () {
// FIXME
return gulp.src('mama');
});
| 'use strict';
var gulp = require('gulp');
var config = require('./_config.js');
var paths = config.paths;
var $ = config.plugins;
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var istanbul = require('browserify-istanbul');
gulp.task('clean', function () {
return gulp.src(paths.tmp, { read: false })
.pipe($.rimraf());
});
gulp.task('build', ['index.html', 'js', 'css']);
gulp.task('index.html', function () {
return gulp.src(paths.app + '/index.jade')
.pipe($.jade({
pretty: true
}))
.pipe(gulp.dest(paths.tmp));
});
gulp.task('jade', function () {
return gulp.src(paths.app + '/*.html')
.pipe(gulp.dest(paths.tmp));
});
gulp.task('js', function () {
var bundleStream = browserify(paths.app + '/js/main.js')
.transform(istanbul)
.bundle();
bundleStream
.pipe(source(paths.app + '/js/main.js'))
.pipe($.rename('main.js'))
.pipe(gulp.dest(paths.tmp + '/js/'));
});
gulp.task('css', function () {
// FIXME
return gulp.src('mama');
});
|
Fix camera offset when in the play state | package game
import (
"math"
"time"
"github.com/Bredgren/geo"
)
type playerCameraTarget struct {
g *Game
p *player
offset geo.Vec
pos geo.Vec
}
func newPlayerCameraTarget(g *Game, p *player, screenHeight int) *playerCameraTarget {
return &playerCameraTarget{
g: g,
p: p,
offset: geo.VecXY(0, -float64(screenHeight)*0.4),
pos: p.Pos(),
}
}
func (ct *playerCameraTarget) update(dt time.Duration) {
switch ct.g.state {
case mainMenuState:
ct.pos.Y = ct.offset.Y
case playState:
offset := ct.offset
offset.Y = -math.Max(0, ct.p.Pos().Y-offset.Y)
ct.pos = ct.p.Pos().Plus(offset)
}
}
func (ct *playerCameraTarget) Pos() geo.Vec {
return ct.pos
}
| package game
import (
"time"
"github.com/Bredgren/geo"
)
type playerCameraTarget struct {
g *Game
p *player
offset geo.Vec
pos geo.Vec
}
func newPlayerCameraTarget(g *Game, p *player, screenHeight int) *playerCameraTarget {
return &playerCameraTarget{
g: g,
p: p,
offset: geo.VecXY(0, -float64(screenHeight)*0.4),
pos: p.Pos(),
}
}
func (ct *playerCameraTarget) update(dt time.Duration) {
switch ct.g.state {
case mainMenuState:
ct.pos.Y = ct.offset.Y
case playState:
ct.pos = ct.p.Pos().Plus(ct.offset)
}
}
func (ct *playerCameraTarget) Pos() geo.Vec {
return ct.pos
}
|
Add token parameter to upload method | import apiClient from 'api-client';
import logger from 'logger';
import picker from 'picker';
export default (apikey, security, moduleOverrides = {}) => {
if (typeof apikey !== 'string') {
throw new Error('No apikey specified');
}
if (security && !(security.policy && security.signature)) {
throw new Error('signature and policy are both required for security');
}
const client = moduleOverrides.apiClient || apiClient.init(apikey, security);
logger(`Initiated with apikey ${apikey}`);
return {
getSecurity() {
return client.getSecurity();
},
setSecurity(sec) {
return client.setSecurity(sec);
},
pick(options) {
return picker(client, options);
},
storeURL(url, options) {
return client.storeURL(url, options);
},
transform(url, options) {
return client.transform(url, options);
},
upload(file, uploadOptions, storeOptions, token) {
return client.upload(file, uploadOptions, storeOptions, token);
},
retrieve(handle, options) {
return client.retrieve(handle, options);
},
remove(handle) {
return client.remove(handle);
},
metadata(handle, options) {
return client.metadata(handle, options);
},
};
};
| import apiClient from 'api-client';
import logger from 'logger';
import picker from 'picker';
export default (apikey, security, moduleOverrides = {}) => {
if (typeof apikey !== 'string') {
throw new Error('No apikey specified');
}
if (security && !(security.policy && security.signature)) {
throw new Error('signature and policy are both required for security');
}
const client = moduleOverrides.apiClient || apiClient.init(apikey, security);
logger(`Initiated with apikey ${apikey}`);
return {
getSecurity() {
return client.getSecurity();
},
setSecurity(sec) {
return client.setSecurity(sec);
},
pick(options) {
return picker(client, options);
},
storeURL(url, options) {
return client.storeURL(url, options);
},
transform(url, options) {
return client.transform(url, options);
},
upload(file, uploadOptions, storeOptions) {
return client.upload(file, uploadOptions, storeOptions);
},
retrieve(handle, options) {
return client.retrieve(handle, options);
},
remove(handle) {
return client.remove(handle);
},
metadata(handle, options) {
return client.metadata(handle, options);
},
};
};
|
Support new PHPStorm Meta Generator | <?php
namespace DelayedJobs\Generator\Task;
use Cake\Core\App;
use DelayedJobs\DelayedJob\Job;
use DelayedJobs\WorkerFinder;
use IdeHelper\Generator\Directive\Override;
use IdeHelper\Generator\Task\TaskInterface;
/**
* Class WorkerTask
*/
class WorkerTask implements TaskInterface
{
const CLASS_JOB = Job::class;
/**
* @return array
*/
public function collect()
{
$map = [];
$workers = $this->collectWorkers();
$map = [];
foreach ($workers as $worker) {
$map[$worker] = '\\' . static::CLASS_JOB . '::class';
}
$directive = new Override('\\' . static::CLASS_JOB . '::enqueue(0)', $map);
$result[$directive->key()] = $directive;
return $result;
}
/**
* @return string[]
*/
protected function collectWorkers()
{
$result = [];
$workerFinder = new WorkerFinder();
$workers = $workerFinder->allAppAndPluginWorkers();
sort($workers);
return $workers;
}
}
| <?php
namespace DelayedJobs\Generator\Task;
use Cake\Core\App;
use DelayedJobs\DelayedJob\Job;
use DelayedJobs\WorkerFinder;
use IdeHelper\Generator\Task\TaskInterface;
/**
* Class WorkerTask
*/
class WorkerTask implements TaskInterface
{
const CLASS_JOB = Job::class;
/**
* @return array
*/
public function collect()
{
$map = [];
$workers = $this->collectWorkers();
$map = [];
foreach ($workers as $worker) {
$map[$worker] = '\\' . static::CLASS_JOB . '::class';
}
$result['\\' . static::CLASS_JOB . '::enqueue(0)'] = $map;
return $result;
}
/**
* @return string[]
*/
protected function collectWorkers()
{
$result = [];
$workerFinder = new WorkerFinder();
$workers = $workerFinder->allAppAndPluginWorkers();
sort($workers);
return $workers;
}
}
|
Use better syntax for unpacking tuples | #!/usr/bin/python3
import sys, os
import nltk
if len(sys.argv) < 2:
print("Please supply a filename.")
sys.exit(1)
filename = sys.argv[1]
with open(filename, 'r') as f:
data = f.read()
# Break the input down into sentences, then into words, and position tag
# those words.
raw_sentences = nltk.sent_tokenize(data)
sentences = [nltk.pos_tag(nltk.word_tokenize(sentence)) \
for sentence in raw_sentences]
# Define a grammar, and identify the noun phrases in the sentences.
# TODO: Look into using exclusive grammars to discard prepositional
# phrases, and such.
chunk_parser = nltk.RegexpParser("""
NP: {<PRP|NN|NNP|CD>+}
NPR: {((<DT|PRP\$>)?<JJ>*(<NP|CC>)+)}
""")
trees = [chunk_parser.parse(sentence) for sentence in sentences]
for index, tree in enumerate(trees):
print("===\nSentence: %s\nNoun phrases:" %
raw_sentences[index].replace('\n', ' '))
for subtree in tree.subtrees(filter = lambda t: t.label() == 'NPR'):
print(" %s" % subtree)
print("Key elements:")
for subtree in tree.subtrees(filter = lambda t: t.label() == 'NP'):
print(" %s" % ' '.join(word for (word, tag) in subtree.leaves()))
| #!/usr/bin/python3
import sys, os
import nltk
if len(sys.argv) < 2:
print("Please supply a filename.")
sys.exit(1)
filename = sys.argv[1]
with open(filename, 'r') as f:
data = f.read()
# Break the input down into sentences, then into words, and position tag
# those words.
raw_sentences = nltk.sent_tokenize(data)
sentences = [nltk.pos_tag(nltk.word_tokenize(sentence)) \
for sentence in raw_sentences]
# Define a grammar, and identify the noun phrases in the sentences.
# TODO: Look into using exclusive grammars to discard prepositional
# phrases, and such.
chunk_parser = nltk.RegexpParser("""
NP: {<PRP|NN|NNP|CD>+}
NPR: {((<DT|PRP\$>)?<JJ>*(<NP|CC>)+)}
""")
trees = [chunk_parser.parse(sentence) for sentence in sentences]
for index, tree in enumerate(trees):
print("===\nSentence: %s\nNoun phrases:" %
raw_sentences[index].replace('\n', ' '))
for subtree in tree.subtrees(filter = lambda t: t.label() == 'NPR'):
print(" %s" % subtree)
print("Key elements:")
for subtree in tree.subtrees(filter = lambda t: t.label() == 'NP'):
print(" %s" % ' '.join(wordtag[0] for wordtag in subtree.leaves()))
|
Add six as dependency to fix import issue | from distutils.core import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup(
name='pymp4parse',
version='0.3.0',
packages=[''],
url='https://github.com/use-sparingly/pymp4parse',
license='The MIT License',
author='Alastair Mccormack',
author_email='alastair at alu.media',
description='MP4 / ISO base media file format (ISO/IEC 14496-12 - MPEG-4 Part 12) file parser',
requires=['bitstring', 'six'],
install_requires=['bitstring', 'six'],
long_description=long_description,
data_files=[('', ['README.md'])]
)
| from distutils.core import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup(
name='pymp4parse',
version='0.3.0',
packages=[''],
url='https://github.com/use-sparingly/pymp4parse',
license='The MIT License',
author='Alastair Mccormack',
author_email='alastair at alu.media',
description='MP4 / ISO base media file format (ISO/IEC 14496-12 - MPEG-4 Part 12) file parser',
requires=['bitstring'],
install_requires=['bitstring'],
long_description=long_description,
data_files=[('', ['README.md'])]
)
|
Fix link to xj component documentation | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.camel.component.xj;
import org.apache.camel.component.xslt.XsltComponent;
import org.apache.camel.component.xslt.XsltEndpoint;
import org.apache.camel.spi.annotations.Component;
/**
* The <a href="https://camel.apache.org/components/latest/xj-component.html">XJ Component</a> is for performing xml to json and back transformations of messages
*/
@Component("xj")
public class XJComponent extends XsltComponent {
public XJComponent() {
}
protected XsltEndpoint createXsltEndpoint(String uri) {
return new XJEndpoint(uri, this);
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.camel.component.xj;
import org.apache.camel.component.xslt.XsltComponent;
import org.apache.camel.component.xslt.XsltEndpoint;
import org.apache.camel.spi.annotations.Component;
/**
* The <a href="http://camel.apache.org/xj.html">XJ Component</a> is for performing xml to json and back transformations of messages
*/
@Component("xj")
public class XJComponent extends XsltComponent {
public XJComponent() {
}
protected XsltEndpoint createXsltEndpoint(String uri) {
return new XJEndpoint(uri, this);
}
}
|
Remove unpublished posts from latest posts list sidebar | <?php
namespace App\Providers;
use App\Post;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* @return void
*/
public function boot()
{
// Using Closure based composers...
View::composer('_partials._aside_recent_articles', function ($view) {
return $view->with('latestPosts', Post::published()->latest()->take(5)->get());
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
} | <?php
namespace App\Providers;
use App\Post;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* @return void
*/
public function boot()
{
// Using Closure based composers...
View::composer('_partials._aside_recent_articles', function ($view) {
return $view->with('latestPosts', Post::latest()->take(5)->get());
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
} |
Add quick comment to explain test_runner.py | # Monary - Copyright 2011-2013 David J. C. Beach
# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.
"""
Note: This runs all of the tests. Maybe
this will be removed eventually?
"""
import os
from os import listdir
from os.path import isfile, join
from inspect import getmembers, isfunction
def main():
abspath = os.path.abspath(__file__)
test_path = list(os.path.split(abspath))[:-1]
test_path = join(*test_path)
test_files = [ f.partition('.')[0] for f in listdir(test_path)
if isfile(join(test_path,f)) and f.endswith('.py')]
test_files = filter(lambda f: f.startswith('test'), test_files)
for f in test_files:
print 'Running tests from', f
exec('import ' + f + ' as test')
methods = [ m[0] for m in getmembers(test, isfunction) ]
if 'setup' in methods:
test.setup()
for m in filter(lambda m: m.startswith('test'), methods):
getattr(test, m)()
if 'teardown' in methods:
test.teardown()
if __name__ == '__main__':
main()
| # Monary - Copyright 2011-2013 David J. C. Beach
# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.
import os
from os import listdir
from os.path import isfile, join
from inspect import getmembers, isfunction
def main():
abspath = os.path.abspath(__file__)
test_path = list(os.path.split(abspath))[:-1]
test_path = join(*test_path)
test_files = [ f.partition('.')[0] for f in listdir(test_path)
if isfile(join(test_path,f)) and f.endswith('.py')]
test_files = filter(lambda f: f.startswith('test'), test_files)
for f in test_files:
print 'Running tests from', f
exec('import ' + f + ' as test')
methods = [ m[0] for m in getmembers(test, isfunction) ]
if 'setup' in methods:
test.setup()
for m in filter(lambda m: m.startswith('test'), methods):
getattr(test, m)()
if 'teardown' in methods:
test.teardown()
if __name__ == '__main__':
main()
|
Reword test for add string and find string | var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have a root', function() {
expect(trie.root).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
it('should add string without errors', function() {
expect(trie.add('test')).to.be.undefined;
});
it('should find an added string', function() {
trie.add('test');
expect(trie.find('test')).to.be.true;
});
it('should trim leading/trailing spaces when adding a string', function() {
trie.add(' test ');
expect(trie.find('test')).to.be.true;
});
});
| var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have a root', function() {
expect(trie.root).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
it('should add string to trie', function() {
expect(trie.add('test')).to.be.undefined;
});
it('should correctly find an added string', function() {
trie.add('test');
expect(trie.find('test')).to.be.true;
});
it('should trim leading/trailing spaces when adding a string', function() {
trie.add(' test ');
expect(trie.find('test')).to.be.true;
});
});
|
Fix mixed indents. replaced tabs with spaces | import sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument('--db2Name', help='tab-separated database lookup: full name file for reference (eg nr or swissprot)')
parser.add_argument('-b','--blast', help='blast input file')
args = parser.parse_args()
blastOrder = []
blastD = {}
with open(args.blast, 'r') as f:
for line in f:
line = line.rstrip().split('\t')
#import pdb; pdb.set_trace()
blastOrder.append(line[1])
blastD[line[1]] = line
f.close()
#potentially huge file --> don't want this in memory
with open(args.db2Name, 'r') as f:
for line in f:
line = line.rstrip().split('\t')
hitInfo = blastD.get(line[0], None)
if hitInfo is not None:
hitInfo.extend(line[1:])
f.close()
outExtendedTab = open(args.blast, 'w')
for hit in blastOrder:
outExtendedTab.write('\t'.join(map(str,blastD[hit])) + '\n')
| import sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument('--db2Name', help='tab-separated database lookup: full name file for reference (eg nr or swissprot)')
parser.add_argument('-b','--blast', help='blast input file')
args = parser.parse_args()
blastOrder = []
blastD = {}
with open(args.blast, 'r') as f:
for line in f:
line = line.rstrip().split('\t')
#import pdb; pdb.set_trace()
blastOrder.append(line[1])
blastD[line[1]] = line
f.close()
#potentially huge file --> don't want this in memory
with open(args.db2Name, 'r') as f:
for line in f:
line = line.rstrip().split('\t')
hitInfo = blastD.get(line[0], None)
if hitInfo is not None:
hitInfo.extend(line[1:])
f.close()
outExtendedTab = open(args.blast, 'w')
for hit in blastOrder:
outExtendedTab.write('\t'.join(map(str,blastD[hit])) + '\n')
|
Store the command help information in the ExcInfo field | package commands
import (
"github.com/centurylinkcloud/clc-go-cli/base"
)
type CommandBase struct {
Input interface{}
Output interface{}
ExcInfo CommandExcInfo
}
type CommandExcInfo struct {
Verb string
Url string
Resource string
Command string
Help string
}
func (c *CommandBase) Execute(cn base.Connection) error {
return cn.ExecuteRequest(c.ExcInfo.Verb, c.ExcInfo.Url, c.Input, c.Output)
}
func (c *CommandBase) Resource() string {
return c.ExcInfo.Resource
}
func (c *CommandBase) Command() string {
return c.ExcInfo.Command
}
func (c *CommandBase) ShowHelp() string {
return c.ExcInfo.Help
}
func (c *CommandBase) InputModel() interface{} {
return c.Input
}
func (c *CommandBase) OutputModel() interface{} {
return c.Output
}
| package commands
import (
"github.com/centurylinkcloud/clc-go-cli/base"
)
type CommandBase struct {
Input interface{}
Output interface{}
ExcInfo CommandExcInfo
}
type CommandExcInfo struct {
Verb string
Url string
Resource string
Command string
}
func (c *CommandBase) Execute(cn base.Connection) error {
return cn.ExecuteRequest(c.ExcInfo.Verb, c.ExcInfo.Url, c.Input, c.Output)
}
func (c *CommandBase) Resource() string {
return c.ExcInfo.Resource
}
func (c *CommandBase) Command() string {
return c.ExcInfo.Command
}
func (c *CommandBase) ShowHelp() string {
return ""
}
func (c *CommandBase) InputModel() interface{} {
return c.Input
}
func (c *CommandBase) OutputModel() interface{} {
return c.Output
}
|
Make sure to not route `/log(in|out)` to index.html | const express = require('express');
const session = require('express-session');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const logger = require('./logging');
const auth = require('./auth');
const db = require('./models/postgresql');
// Initialize express
const app = express();
// Set up session store using database connection
const store = new SequelizeStore({ db: db.sequelize });
// Set up session store
app.use(session({
secret: 'super secret',
store,
resave: true,
saveUninitialized: true,
}));
store.sync();
if (process.env.PRODUCTION) {
// Register dist path for static files in prod
const staticDir = './dist';
logger.info(`Serving staticfiles from ${staticDir}`);
app.use('/assets/', express.static(staticDir));
app.get(/^(?!\/log(in|out))/, (req, res) =>
res.sendFile('index.html', { root: staticDir }));
}
module.exports = async () => auth(app);
| const express = require('express');
const session = require('express-session');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const logger = require('./logging');
const auth = require('./auth');
const db = require('./models/postgresql');
// Initialize express
const app = express();
// Set up session store using database connection
const store = new SequelizeStore({ db: db.sequelize });
// Set up session store
app.use(session({
secret: 'super secret',
store,
resave: true,
saveUninitialized: true,
}));
store.sync();
if (process.env.PRODUCTION) {
// Register dist path for static files in prod
const staticDir = './dist';
logger.info(`Serving staticfiles from ${staticDir}`);
app.use('/assets/', express.static(staticDir));
app.get('*', (req, res) =>
res.sendFile('index.html', { root: staticDir }));
}
module.exports = async () => auth(app);
|
Fix documentFormatter to handle failed promise | import documentFormatter from 'src/logic/documentPackager/documentFormatter';
import base64OfSimplePdf from './reference/base64OfSimplePdf';
describe('DocumentFormatter', () => {
it('should returns the same data for \'html viewMode\'', () => {
const viewMode = 'html';
const inputData = '<div>This is a HTML content</div>';
const outputData = documentFormatter.format(inputData, viewMode);
expect(outputData).to.equal('<div>This is a HTML content</div>');
});
it('should returns a pdfBlob for \'pages viewMode\'', (done) => {
const expectedOutput = base64OfSimplePdf;
const inputData = '<div>This is a HTML content</div>';
const thatPromise = documentFormatter.getPdfBlob(inputData);
thatPromise.then((outputData) => {
// pdfJS does not give deterministic outputData
// around 5 characters will always be different in the output
// therefore, an approximation method to use content length for
// testing is used.
expect(outputData.length).to.equal(expectedOutput.length);
done();
}).catch((error) => {
done(error);
});
});
});
| import documentFormatter from 'src/logic/documentPackager/documentFormatter';
import base64OfSimplePdf from './reference/base64OfSimplePdf';
describe('DocumentFormatter', () => {
it('should returns the same data for \'html viewMode\'', () => {
const viewMode = 'html';
const inputData = '<div>This is a HTML content</div>';
const outputData = documentFormatter.format(inputData, viewMode);
expect(outputData).to.equal('<div>This is a HTML content</div>');
});
it('should returns a pdfBlob for \'pages viewMode\'', () => {
const expectedOutput = base64OfSimplePdf;
const inputData = '<div>This is a HTML content</div>';
const thatPromise = documentFormatter.getPdfBlob(inputData);
thatPromise.then((outputData) => {
// pdfJS does not give deterministic outputData
// around 5 characters will always be different in the output
// therefore, an approximation method to use content length for
// testing is used.
expect(outputData.length).to.equal(expectedOutput.length);
});
});
});
|
Return new post on save | import * as Builder from 'src/server/modules/build';
import * as Queries from 'src/server/modules/queries';
export const publish = async (req, res, next) => {
const post = await Queries.post(req.params.id);
post.lastPublished = Date.now();
post.publishedMarkdown = post.markdown;
const newPost = await post.save()
.catch(err => next(err));
await Queries.publishedPosts()
.then(Builder.rebuild)
.catch(err => next(err));
res.json(newPost);
}
export const unpublish = async (req, res, next) => {
const post = await Queries.post(req.params.id);
post.lastPublished = null;
post.publishedMarkdown = '';
post.save()
.then(Queries.publishedPosts)
.then(Builder.rebuild)
.then(() => res.send('OK'))
.catch(err => next(err));
}
| import * as Builder from 'src/server/modules/build';
import * as Queries from 'src/server/modules/queries';
export const publish = async (req, res, next) => {
const post = await Queries.post(req.params.id);
post.lastPublished = Date.now();
post.publishedMarkdown = post.markdown;
post.save()
.then(Queries.publishedPosts)
.then(Builder.rebuild)
.then(() => res.send('OK'))
.catch(err => next(err));
}
export const unpublish = async (req, res, next) => {
const post = await Queries.post(req.params.id);
post.lastPublished = null;
post.publishedMarkdown = '';
post.save()
.then(Queries.publishedPosts)
.then(Builder.rebuild)
.then(() => res.send('OK'))
.catch(err => next(err));
}
|
:bug: Fix middleware check for admin commands | const chalk = require('chalk')
const logger = require('winston')
const { Permitter } = require('../core')
module.exports = {
priority: 100,
process: container => {
const { msg, isPrivate, isCommand, cache, commander, trigger, settings, admins } = container
if (!isCommand) return Promise.resolve()
const cmd = commander.get(trigger).cmd
if (!admins.includes(msg.author.id) || !(cmd.options.modOnly || cmd.options.adminOnly)) {
const isAllowed = Permitter.verifyMessage(cmd.permissionNode, msg, settings.permissions)
if (!isAllowed) return Promise.resolve()
}
logger.info(`${chalk.bold.magenta(
!isPrivate
? msg.guild.name
: '(in PMs)'
)} > ${chalk.bold.green(msg.author.username)}: ` +
`${chalk.bold.blue(msg.cleanContent.replace(/\n/g, ' '))}`)
cache.client.multi()
.hincrby('usage', commander.get(trigger).cmd.labels[0], 1)
.hincrby('usage', 'ALL', 1)
.exec()
return Promise.resolve(container)
}
}
| const chalk = require('chalk')
const logger = require('winston')
const { Permitter } = require('../core')
module.exports = {
priority: 100,
process: container => {
const { msg, isPrivate, isCommand, cache, commander, trigger, settings, admins } = container
if (!isCommand) return Promise.resolve()
const cmd = commander.get(trigger).cmd
if (!admins.includes(msg.author.id) || !cmd.options.modOnly) {
const isAllowed = Permitter.verifyMessage(cmd.permissionNode, msg, settings.permissions)
if (!isAllowed) return Promise.resolve()
}
logger.info(`${chalk.bold.magenta(
!isPrivate
? msg.guild.name
: '(in PMs)'
)} > ${chalk.bold.green(msg.author.username)}: ` +
`${chalk.bold.blue(msg.cleanContent.replace(/\n/g, ' '))}`)
cache.client.multi()
.hincrby('usage', commander.get(trigger).cmd.labels[0], 1)
.hincrby('usage', 'ALL', 1)
.exec()
return Promise.resolve(container)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.