text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Change units on graph y-axis
import graphs import star def main(): """ Plots graph of black body emission wavelengths against amplitudes, then UBVR magnitudes of a star. """ graph = graphs.FunctionsGraph(x_label="wavelength / m", y_label="amplitude / W * sr^-1 * m^-3") # Temperatures of black bodies (K) mapped to style of lines on graph. temps_to_styles_map = {3000.0: "g-", 4000.0: "b-", 5000.0: "r-"} for temp, style in temps_to_styles_map.items(): planck_function = graphs.PlottedPlanckFunction(temp) graph.add_plotted_function(planck_function, style=style, label=str(int(temp)) + "K") graph.plot(x_range=(0.1e-6, 6e-6), point_spacing=0.02e-6) # TODO: input required parameters st = star.Star(1, 10, 4000) print st.get_ubvr_magnitudes() if __name__ == "__main__": main()
import graphs import star def main(): """ Plots graph of black body emission wavelengths against amplitudes, then UBVR magnitudes of a star. """ graph = graphs.FunctionsGraph(x_label="wavelength / m", y_label="amplitude") # Temperatures of black bodies (K) mapped to style of lines on graph. temps_to_styles_map = {3000.0: "g-", 4000.0: "b-", 5000.0: "r-"} for temp, style in temps_to_styles_map.items(): planck_function = graphs.PlottedPlanckFunction(temp) graph.add_plotted_function(planck_function, style=style, label=str(int(temp)) + "K") graph.plot(x_range=(0.1e-6, 6e-6), point_spacing=0.02e-6) # TODO: input required parameters st = star.Star(1, 10, 4000) print st.get_ubvr_magnitudes() if __name__ == "__main__": main()
Use backported commonpath instead of built in os.path.commonpath The built in one is only available for Python 3.5
import glob import shutil import os if os.name == "nt": from .ntcommonpath import commonpath else: from .posixcommonpath import commonpath def move_glob(src,dst): """Moves files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): shutil.move(obj,dst) def copy_glob(src,dst): """Copies files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): if os.path.isdir(obj): start_part=commonpath([src,obj]) end_part=os.path.relpath(obj,start_part) shutil.copytree(obj,os.path.join(dst,end_part)) else: shutil.copy2(obj,dst)
import glob import shutil import os def move_glob(src,dst): """Moves files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): shutil.move(obj,dst) def copy_glob(src,dst): """Copies files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): if os.path.isdir(obj): start_part=os.path.commonpath([src,obj]) end_part=os.path.relpath(obj,start_part) shutil.copytree(obj,os.path.join(dst,end_part)) else: shutil.copy2(obj,dst)
Add missing phpdoc @throws tag
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / Include / Class */ namespace PH7; use PH7\Framework\Http\Http; abstract class Cron extends Framework\Cron\Run\Cron { public function __construct() { parent::__construct(); // Check delay $this->isAlreadyExec(); } /** * Check if the cron has already been executed. * * @return void If cron has already been executed, the script stops with exit() function and an explanatory message. * * @throws Framework\Http\Exception */ public function isAlreadyExec() { if (!$this->checkDelay()) { Http::setHeadersByCode(403); exit(t('This cron has already been executed.')); } } }
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / Include / Class */ namespace PH7; use PH7\Framework\Http\Http; abstract class Cron extends Framework\Cron\Run\Cron { public function __construct() { parent::__construct(); // Check delay $this->isAlreadyExec(); } /** * Check if the cron has already been executed. * * @return void If cron has already been executed, the script stops with exit() function and an explanatory message. */ public function isAlreadyExec() { if (!$this->checkDelay()) { Http::setHeadersByCode(403); exit(t('This cron has already been executed.')); } } }
Remove R.isNaN leftover in documentation The examples for `R.none` are still using `R.isNaN` which was removed in #1112. I’ve replace the examples with actual use-cases from the tests.
var _complement = require('./internal/_complement'); var _curry2 = require('./internal/_curry2'); var _dispatchable = require('./internal/_dispatchable'); var _xany = require('./internal/_xany'); var any = require('./any'); /** * Returns `true` if no elements of the list match the predicate, `false` * otherwise. * * Dispatches to the `any` method of the second argument, if present. * * @func * @memberOf R * @since v0.12.0 * @category List * @sig (a -> Boolean) -> [a] -> Boolean * @param {Function} fn The predicate function. * @param {Array} list The array to consider. * @return {Boolean} `true` if the predicate is not satisfied by every element, `false` otherwise. * @see R.all, R.any * @example * * var isEven = n => n % 2 === 0; * * R.none(isEven, [1, 3, 5, 7, 9, 11]), //=> true * R.none(isEven, [1, 3, 5, 7, 8, 11]), //=> false */ module.exports = _curry2(_complement(_dispatchable('any', _xany, any)));
var _complement = require('./internal/_complement'); var _curry2 = require('./internal/_curry2'); var _dispatchable = require('./internal/_dispatchable'); var _xany = require('./internal/_xany'); var any = require('./any'); /** * Returns `true` if no elements of the list match the predicate, `false` * otherwise. * * Dispatches to the `any` method of the second argument, if present. * * @func * @memberOf R * @since v0.12.0 * @category List * @sig (a -> Boolean) -> [a] -> Boolean * @param {Function} fn The predicate function. * @param {Array} list The array to consider. * @return {Boolean} `true` if the predicate is not satisfied by every element, `false` otherwise. * @see R.all, R.any * @example * * R.none(R.isNaN, [1, 2, 3]); //=> true * R.none(R.isNaN, [1, 2, 3, NaN]); //=> false */ module.exports = _curry2(_complement(_dispatchable('any', _xany, any)));
Make it possible to disable enrollment and goal record analytics.
from django.conf import settings from django_lean.experiments.models import GoalRecord from django_lean.experiments.signals import goal_recorded, user_enrolled from django_lean.lean_analytics import get_all_analytics def analytics_goalrecord(sender, goal_record, experiment_user, *args, **kwargs): if getattr(settings, 'LEAN_ANALYTICS_FOR_EXPERIMENTS', False): for analytics in get_all_analytics(): analytics.record(goal_record=goal_record, experiment_user=experiment_user) goal_recorded.connect(analytics_goalrecord, sender=GoalRecord) def analytics_enrolled(sender, experiment, experiment_user, group_id, *args, **kwargs): if getattr(settings, 'LEAN_ANALYTICS_FOR_EXPERIMENTS', False): for analytics in get_all_analytics(): analytics.enroll(experiment=experiment, experiment_user=experiment_user, group_id=group_id) user_enrolled.connect(analytics_enrolled)
from django_lean.experiments.models import GoalRecord from django_lean.experiments.signals import goal_recorded, user_enrolled from django_lean.lean_analytics import get_all_analytics def analytics_goalrecord(sender, goal_record, experiment_user, *args, **kwargs): for analytics in get_all_analytics(): analytics.record(goal_record=goal_record, experiment_user=experiment_user) goal_recorded.connect(analytics_goalrecord, sender=GoalRecord) def analytics_enrolled(sender, experiment, experiment_user, group_id, *args, **kwargs): for analytics in get_all_analytics(): analytics.enroll(experiment=experiment, experiment_user=experiment_user, group_id=group_id) user_enrolled.connect(analytics_enrolled)
Change Canvas api to use queued get
import _ from 'lodash'; import Api from './api'; function proxyUrl(url){ return `api/canvas?url=${encodeURIComponent(url)}`; } function getNextUrl(link){ if(link){ const url = _.find(link.split(','), (l) => { return _.trim(l.split(";")[1]) == 'rel="next"'; }) if(url){ return url.split(';')[0].replace(/[\<\>\s]/g, ""); } } } export default class CanvasApi{ static get(url, key, cb, payload){ function getNext(response){ if(cb) { cb(response.body || JSON.parse(response.text)); } if(response.header){ var nextUrl = getNextUrl(response.headers['link']); if(nextUrl){ CanvasApi.get(nextUrl, key, cb, payload); } } } Api.queuedGet(key, proxyUrl(url), payload, getNext); } static post(url, body, key){ return Api.post(key, proxyUrl(url), body); } static put(url, body, key){ return Api.put(key, proxyUrl(url), body); } }
import _ from 'lodash'; import Api from './api'; function proxyUrl(url){ return `api/canvas?url=${encodeURIComponent(url)}`; } function get_next_url(link){ if(link){ const url = _.find(link.split(','), (l) => { return _.trim(l.split(";")[1]) == 'rel="next"'; }) if(url){ return url.split(';')[0].replace(/[\<\>\s]/g, ""); } } } export default class CanvasApi{ static get(url, key, cb){ Api.get(key, proxyUrl(url)).then( (response) => { if(cb) { cb(response.body || JSON.parse(response.text)); } if(response.header){ var next_url = get_next_url(response.headers['link']); if(next_url){ this.get(next_url, key, cb); } else { return; } } }, (error) => { console.log(error); }); } static post(url, body, key){ return Api.post(key, proxyUrl(url), body); } static put(url, body, key){ return Api.put(key, proxyUrl(url), body); } }
Move the sidebar logic to its own context
function initSidebar () { var sidebarOpen = false; var menuText = ["Menu", "Close"]; var menuElement = document.querySelector(".menu-link"); var sidebarElement = document.querySelector(".sidebar"); var mainElement = document.querySelector("main"); var headerElement = document.querySelector("header"); var rAF; mainElement.addEventListener( "click", toggleSidebar, true ); menuElement.addEventListener( "click", toggleSidebar, false ); window.addEventListener( "hashchange", toggleSidebar, false ); function toggleSidebar ( event ) { // Don't toggle when there's nothing to hide. if (event.type === "hashchange" && !sidebarOpen) return; if (event.currentTarget === mainElement && !sidebarOpen) return; sidebarOpen = (!sidebarOpen); cancelAnimationFrame(rAF); rAF = requestAnimationFrame(function () { sidebarElement.classList.toggle( "sidebar-open" ); headerElement.classList.toggle( "hidden" ); menuElement.textContent = menuText[(sidebarOpen ? 1 : 0)]; }); } } initSidebar();
var sidebarOpen = false; var menuText = ["Menu", "Close"]; var menuElement = document.querySelector(".menu-link"); var sidebarElement = document.querySelector(".sidebar"); var mainElement = document.querySelector("main"); var headerElement = document.querySelector("header"); var rAF; mainElement.addEventListener( "click", toggleSidebar, true ); menuElement.addEventListener( "click", toggleSidebar, false ); window.addEventListener( "hashchange", toggleSidebar, false ); function toggleSidebar ( event ) { // Don't toggle when there's nothing to hide. if (event.type === "hashchange" && !sidebarOpen) return; if (event.currentTarget === mainElement && !sidebarOpen) return; sidebarOpen = (!sidebarOpen); cancelAnimationFrame(rAF); rAF = requestAnimationFrame(function () { sidebarElement.classList.toggle( "sidebar-open" ); headerElement.classList.toggle( "hidden" ); menuElement.textContent = menuText[(sidebarOpen ? 1 : 0)]; }); }
Fix a bunch of issues with the stub helper thingo
/* * node-http-cache. * Copyright © 2012 Chris Corbyn. * * See LICENSE file for details. */ /* Convenience stuff for testing */ module.exports = { httpCache: require('../lib/http-cache'), http: require('http'), sinon: require('sinon'), memo: require('memo-is'), /** Create a full stub object based on the given prototype */ stub: function(obj, target){ var self = this; var proto = (typeof obj == 'function') ? obj.prototype : obj; target = target || { __proto__: proto, constructor: proto.constructor }; Object.getOwnPropertyNames(proto).filter(function(p){ return typeof proto[p] == 'function' && typeof {}[p] == 'undefined'; }).forEach(function(p) { target[p] = self.sinon.stub() }); return proto.__proto__ ? this.stub(proto.__proto__, target) : target; }, createRequest: function createRequest(options){ var req = new this.http.IncomingMessage(); options = options || {}; req.method = options.method || 'GET'; req.url = options.url || '/'; req.headers = options.headers || {}; req.httpVersion = options.httpVersion || '1.1'; return req; }, createResponse: function createResponse(req){ return new this.http.ServerResponse(req); } };
/* * node-http-cache. * Copyright © 2012 Chris Corbyn. * * See LICENSE file for details. */ /* Convenience stuff for testing */ module.exports = { httpCache: require('../lib/http-cache'), http: require('http'), sinon: require('sinon'), memo: require('memo-is'), /** Create a full stub object based on the given prototype */ stub: function(obj, target) { var self = this; var cls = (typeof obj == 'function') ? obj.prototype : obj; target = target || {}; Object.getOwnPropertyNames(cls).filter(function(p){ return typeof cls[p] == 'function'; }).forEach(function(p) { target[p] = self.sinon.stub() }); return cls.__proto__ ? this.stub(cls.__proto__, target) : target; }, createRequest: function createRequest(options){ var req = new this.http.IncomingMessage(); options = options || {}; req.method = options.method || 'GET'; req.url = options.url || '/'; req.headers = options.headers || {}; req.httpVersion = options.httpVersion || '1.1'; return req; }, createResponse: function createResponse(req){ return new this.http.ServerResponse(req); } };
Add dots reporting to karma
// karma.conf.js module.exports = function(config) { config.set({ basePath : '../', frameworks: ['jasmine'], files : [ 'public/bower_components/jquery/dist/jquery.js', 'public/bower_components/angular/angular.js', 'public/bower_components/angular-cookies/angular-cookies.js', 'public/bower_components/angular-route/angular-route.js', 'public/bower_components/angular-mocks/angular-mocks.js', 'public/bower_components/angular-socket.io-mock/angular-socket.io-mock.js', 'public/bower_components/toastr/toastr.min.js', 'public/js/**/*.js', 'test/unit/**/*.js' ], reporters: ['junit', 'coverage', 'dots'], coverageReporter: { type: 'html', dir: 'build/coverage/' }, preprocessors: { 'public/js/**/*.js': ['coverage'] }, junitReporter: { outputFile: 'build/unit/test-results.xml' }, port: 8876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], captureTimeout: 60000, singleRun: true }); };
// karma.conf.js module.exports = function(config) { config.set({ basePath : '../', frameworks: ['jasmine'], files : [ 'public/bower_components/jquery/dist/jquery.js', 'public/bower_components/angular/angular.js', 'public/bower_components/angular-cookies/angular-cookies.js', 'public/bower_components/angular-route/angular-route.js', 'public/bower_components/angular-mocks/angular-mocks.js', 'public/bower_components/angular-socket.io-mock/angular-socket.io-mock.js', 'public/bower_components/toastr/toastr.min.js', 'public/js/**/*.js', 'test/unit/**/*.js' ], reporters: ['junit', 'coverage'], coverageReporter: { type: 'html', dir: 'build/coverage/' }, preprocessors: { 'public/js/**/*.js': ['coverage'] }, junitReporter: { outputFile: 'build/unit/test-results.xml' }, port: 8876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], captureTimeout: 60000, singleRun: true }); };
Remove the created_at date from the list view
<div id="list" ng-controller="ListCtrl"> <div class="unpacked"> <ul class="packing-list"> <li ng-repeat="item in items | filter:{packed:false}"> <form class="form-inline"> <input type="checkbox" class="check" ng-model="item.packed"> <input ng-model='item.name'> </form> </li> </ul> </div> <div class="packed"> <h3>Already Packed</h3> <ul class="packing-list"> <li ng-repeat="item in items | filter:{packed:true}"> <form class="form-inline"> <input type="checkbox" class="check" ng-model="item.packed"> <input ng-model='item.name'> </form> </li> </ul> </div> </div>
<div id="list" ng-controller="ListCtrl"> <div class="unpacked"> <ul class="packing-list"> <li ng-repeat="item in items | filter:{packed:false}"> <form class="form-inline"> <input type="checkbox" class="check" ng-model="item.packed"> <input ng-model='item.name'> (added {{item.created_at|date}}) </form> </li> </ul> </div> <div class="packed"> <h3>Already Packed</h3> <ul class="packing-list"> <li ng-repeat="item in items | filter:{packed:true}"> <form class="form-inline"> <input type="checkbox" class="check" ng-model="item.packed"> <input ng-model='item.name'> (added {{item.created_at|date}}) </form> </li> </ul> </div> </div>
Set CHECK_LINKS to False for default
HOST = "irc.twitch.tv" PORT = 6667 PASS = "oauth:##############################" # Your bot's oauth (https://twitchapps.com/tmi/) IDENTITY = "my_bot" # Your bot's username. Lowercase!! WHITELIST = ["some_authourized_account", "another one"] # People who may execute commands. Lower!! CHANNEL = "channel" # The channel to join. Lowercase!! JOIN_MESSAGE = "Hi, I'm a bot that just joined this channel." # Message from the bot when it joins a channel. WOT_KEY = "" # Api key of WOT to check sites (mywot.com) CHECK_LINKS = False # Should the bot check links via WOT?
HOST = "irc.twitch.tv" PORT = 6667 PASS = "oauth:##############################" # Your bot's oauth (https://twitchapps.com/tmi/) IDENTITY = "my_bot" # Your bot's username. Lowercase!! WHITELIST = ["some_authourized_account", "another one"] # People who may execute commands. Lower!! CHANNEL = "channel" # The channel to join. Lowercase!! JOIN_MESSAGE = "Hi, I'm a bot that just joined this channel." # Message from the bot when it joins a channel. WOT_KEY = "" # Api key of WOT to check sites (mywot.com) CHECK_LINKS = True # Should the bot check links via WOT?
Test bad call/better error msg
from __future__ import (absolute_import, division, print_function) import subprocess import tempfile import pytest import ruamel.yaml as yaml from yaml2ncml import build def test_call(): output = subprocess.check_output(['yaml2ncml', 'roms_0.yaml']) with open('base_roms_test.ncml') as f: expected = f.read() assert output.decode() == expected def test_save_file(): outfile = tempfile.mktemp(suffix='.ncml') subprocess.call(['yaml2ncml', 'roms_0.yaml', '--output={}'.format(outfile)]) with open('base_roms_test.ncml') as f: expected = f.read() with open(outfile) as f: output = f.read() assert output == expected @pytest.fixture def load_ymal(fname='roms_1.yaml'): with open(fname, 'r') as stream: yml = yaml.load(stream, Loader=yaml.RoundTripLoader) return yml def test_bad_yaml(): with pytest.raises(ValueError): yml = load_ymal(fname='roms_1.yaml') build(yml)
from __future__ import (absolute_import, division, print_function) import subprocess import tempfile def test_call(): output = subprocess.check_output(['yaml2ncml', 'roms_0.yaml']) with open('base_roms_test.ncml') as f: expected = f.read() assert output.decode() == expected def test_save_file(): outfile = tempfile.mktemp(suffix='.ncml') subprocess.call(['yaml2ncml', 'roms_0.yaml', '--output={}'.format(outfile)]) with open('base_roms_test.ncml') as f: expected = f.read() with open(outfile) as f: output = f.read() assert output == expected
Remove comment and move piece of code into own method for better understanding/readability
<?php /** * @title Google Map Class * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Geo / Map */ namespace PH7\Framework\Geo\Map; defined('PH7') or exit('Restricted access'); use PH7\Framework\Mvc\Model\DbConfig; class Map extends Api { public function __construct() { parent::__construct(); $this->initializeGoogleMaps(); } private function initializeGoogleMaps() { $this->setEnableWindowZoom(true); $this->setMapType(DbConfig::getSetting('mapType')); $this->setLang(PH7_LANG_CODE); } }
<?php /** * @title Google Map Class * * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Geo / Map */ namespace PH7\Framework\Geo\Map; defined('PH7') or exit('Restricted access'); use PH7\Framework\Mvc\Model\DbConfig; class Map extends Api { public function __construct() { parent::__construct(); /***** Initialization of Google Map *****/ $this->setEnableWindowZoom(true); $this->setMapType(DbConfig::getSetting('mapType')); $this->setLang(PH7_LANG_CODE); } }
Fix minor bug in test_get_root_discovers_v1 Invoke json method to get response body instead of referring it. Change-Id: I5af060b75b14f2b9322099d8a658c070b056cee2
# -*- coding: utf-8 -*- # # Copyright 2013 - Red Hat, 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. import requests import testtools class VersionDiscoveryTestCase(testtools.TestCase): def test_get_root_discovers_v1(self): r = requests.get('http://127.0.0.1:9777') self.assertEqual(r.status_code, 200) body = r.json() self.assertEqual(len(body), 1) v1 = body[0] self.assertEqual(v1['id'], 'v1.0') self.assertEqual(v1['status'], 'CURRENT') self.assertEqual(v1['link']['target_name'], 'v1') self.assertEqual(v1['link']['href'], 'http://127.0.0.1:9777/v1')
# -*- coding: utf-8 -*- # # Copyright 2013 - Red Hat, 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. import requests import testtools class VersionDiscoveryTestCase(testtools.TestCase): def test_get_root_discovers_v1(self): r = requests.get('http://127.0.0.1:9777') self.assertEqual(r.status_code, 200) body = r.json self.assertEqual(len(body), 1) v1 = body[0] self.assertEqual(v1['id'], 'v1.0') self.assertEqual(v1['status'], 'CURRENT') self.assertEqual(v1['link']['target_name'], 'v1') self.assertEqual(v1['link']['href'], 'http://127.0.0.1:9777/v1')
Add trove classifiers for all supported Python versions
from distutils.core import setup from setuptools import find_packages VERSION = __import__("import_export").__version__ CLASSIFIERS = [ 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Framework :: Django :: 1.10', 'Framework :: Django :: 1.11', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development', ] install_requires = [ 'diff-match-patch', 'django>=1.5', 'tablib', ] setup( name="django-import-export", description="Django application and library for importing and exporting" "data with included admin integration.", version=VERSION, author="Informatika Mihelac", author_email="bmihelac@mihelac.org", license='BSD License', platforms=['OS Independent'], url="https://github.com/django-import-export/django-import-export", packages=find_packages(exclude=["tests"]), include_package_data=True, install_requires=install_requires, classifiers=CLASSIFIERS, )
from distutils.core import setup from setuptools import find_packages VERSION = __import__("import_export").__version__ CLASSIFIERS = [ 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Framework :: Django :: 1.10', 'Framework :: Django :: 1.11', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: Software Development', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ] install_requires = [ 'diff-match-patch', 'django>=1.5', 'tablib', ] setup( name="django-import-export", description="Django application and library for importing and exporting" "data with included admin integration.", version=VERSION, author="Informatika Mihelac", author_email="bmihelac@mihelac.org", license='BSD License', platforms=['OS Independent'], url="https://github.com/django-import-export/django-import-export", packages=find_packages(exclude=["tests"]), include_package_data=True, install_requires=install_requires, classifiers=CLASSIFIERS, )
[WB-8591] Fix issue where sagemaker run ids break run queues
import json import os import socket from . import files as sm_files def parse_sm_secrets(): """We read our api_key from secrets.env in SageMaker""" env_dict = dict() # Set secret variables if os.path.exists(sm_files.SM_SECRETS): for line in open(sm_files.SM_SECRETS, "r"): key, val = line.strip().split("=", 1) env_dict[key] = val return env_dict def parse_sm_resources(): run_dict = dict() env_dict = dict() run_id = os.getenv("TRAINING_JOB_NAME") if run_id and os.getenv("WANDB_RUN_ID") is None: run_dict["run_id"] = "-".join( [run_id, os.getenv("CURRENT_HOST", socket.gethostname())] ) conf = json.load(open(sm_files.SM_RESOURCE_CONFIG)) if len(conf["hosts"]) > 1: run_dict["run_group"] = os.getenv("TRAINING_JOB_NAME") env_dict = parse_sm_secrets() return run_dict, env_dict
import json import os import socket from . import files as sm_files def parse_sm_secrets(): """We read our api_key from secrets.env in SageMaker""" env_dict = dict() # Set secret variables if os.path.exists(sm_files.SM_SECRETS): for line in open(sm_files.SM_SECRETS, "r"): key, val = line.strip().split("=", 1) env_dict[key] = val return env_dict def parse_sm_resources(): run_dict = dict() env_dict = dict() run_id = os.getenv("TRAINING_JOB_NAME") if run_id: run_dict["run_id"] = "-".join( [run_id, os.getenv("CURRENT_HOST", socket.gethostname())] ) conf = json.load(open(sm_files.SM_RESOURCE_CONFIG)) if len(conf["hosts"]) > 1: run_dict["run_group"] = os.getenv("TRAINING_JOB_NAME") env_dict = parse_sm_secrets() return run_dict, env_dict
Mark output of tweet filter as safe by default
from datetime import datetime from twitter_text import TwitterText from flask import Markup def relative_time(timestamp): delta = (datetime.now() - datetime.fromtimestamp(timestamp)) delta_s = delta.days * 86400 + delta.seconds if delta_s < 60: return "less than a minute ago" elif delta_s < 120: return "about a minute ago" elif delta_s < (60 * 60): return str(delta_s / 60) + " minutes ago" elif delta_s < (120 * 60): return "about an hour ago" elif delta_s < (24 * 60 * 60): return "about " + str(delta_s / 3600) + " hours ago" elif delta_s < (48 * 60 * 60): return "1 day ago" else: return str(delta_s / 86400) + " days ago" def tweet(text): return Markup(TwitterText(text).autolink.auto_link())
from datetime import datetime from twitter_text import TwitterText def relative_time(timestamp): delta = (datetime.now() - datetime.fromtimestamp(timestamp)) delta_s = delta.days * 86400 + delta.seconds if delta_s < 60: return "less than a minute ago" elif delta_s < 120: return "about a minute ago" elif delta_s < (60 * 60): return str(delta_s / 60) + " minutes ago" elif delta_s < (120 * 60): return "about an hour ago" elif delta_s < (24 * 60 * 60): return "about " + str(delta_s / 3600) + " hours ago" elif delta_s < (48 * 60 * 60): return "1 day ago" else: return str(delta_s / 86400) + " days ago" def tweet(text): return TwitterText(text).autolink.auto_link()
Sort file list before writing to project file Now using the built-in Python `list.sort` method to sort files. This should ensure consistent behavior on all systems and prevent unnecessary merge conflicts.
#!/usr/bin/python3 import os import re import subprocess dir_path = os.path.dirname(os.path.realpath(__file__)) filename = 'chatterino.pro' data = "" with open(filename, 'r') as project: data = project.read() sources_list = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'").splitlines() sources_list.sort(key=str.lower) sources = "\n".join(sources_list) sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE) sources += "\n" data = re.sub(r'^SOURCES(.|\r|\n)*?^$', 'SOURCES += \\\n' + sources, data, flags=re.MULTILINE) headers_list = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'").splitlines() headers_list.sort(key=str.lower) headers = "\n".join(headers_list) headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE) headers += "\n" data = re.sub(r'^HEADERS(.|\r|\n)*?^$', 'HEADERS += \\\n' + headers, data, flags=re.MULTILINE) with open(filename, 'w') as project: project.write(data)
#!/usr/bin/python3 import os import re import subprocess dir_path = os.path.dirname(os.path.realpath(__file__)) filename = 'chatterino.pro' data = "" with open(filename, 'r') as project: data = project.read() sources = subprocess.getoutput("find ./src -type f -regex '.*\.cpp' | sed 's_\./_ _g'") sources = re.sub(r'$', r' \\\\', sources, flags=re.MULTILINE) sources += "\n" data = re.sub(r'^SOURCES(.|\r|\n)*?^$', 'SOURCES += \\\n' + sources, data, flags=re.MULTILINE) headers = subprocess.getoutput("find ./src -type f -regex '.*\.hpp' | sed 's_\./_ _g'") headers = re.sub(r'$', r' \\\\', headers, flags=re.MULTILINE) headers += "\n" data = re.sub(r'^HEADERS(.|\r|\n)*?^$', 'HEADERS += \\\n' + headers, data, flags=re.MULTILINE) with open(filename, 'w') as project: project.write(data)
Fix signup confirm action test
<?php namespace SimplyTestable\WebClientBundle\Tests\Controller\View\User\SignUp\Confirm\IndexAction; use SimplyTestable\WebClientBundle\Tests\Controller\Base\ActionTest as BaseActionTest; class ActionTest extends BaseActionTest { protected function getHttpFixtureItems() { return array( "HTTP/1.0 200 OK" ); } protected function getExpectedResponseStatusCode() { return 200; } protected function getRequestQueryData() { return array( 'email' => 'user@example.com' ); } protected function getActionMethodArguments() { return array( 'email' => 'user@example.com' ); } protected function getRequestAttributes() { return array( 'email' => 'user@example.com' ); } }
<?php namespace SimplyTestable\WebClientBundle\Tests\Controller\View\User\SignUp\Confirm\IndexAction; use SimplyTestable\WebClientBundle\Tests\Controller\Base\ActionTest as BaseActionTest; class ActionTest extends BaseActionTest { protected function getHttpFixtureItems() { return array( "HTTP/1.0 200 OK" ); } protected function getExpectedResponseStatusCode() { return 200; } protected function getRequestQueryData() { return array( 'email' => 'user@example.com' ); } protected function getActionMethodArguments() { return array( 'email' => 'user@example.com' ); } }
Align test with new base class
package com.grayben.riskExtractor.htmlScorer.scorers.elementScorers; import com.grayben.riskExtractor.htmlScorer.scorers.Scorer; import com.grayben.riskExtractor.htmlScorer.scorers.ScorerTest; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; /** * Created by beng on 28/11/2015. */ @RunWith(MockitoJUnitRunner.class) public class SegmentationElementScorerTest extends ScorerTest<Element> { SegmentationElementScorer elementScorerSUT; @Mock Scorer<Tag> tagScorerMock; @Mock Element elementMock; @Before public void setUp() throws Exception { elementScorerSUT = new SegmentationElementScorer(tagScorerMock); super.setUp(elementScorerSUT); } @After public void tearDown() throws Exception { elementScorerSUT = null; } }
package com.grayben.riskExtractor.htmlScorer.scorers.elementScorers; import com.grayben.riskExtractor.htmlScorer.scorers.Scorer; import com.grayben.riskExtractor.htmlScorer.scorers.ScorerTest; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; /** * Created by beng on 28/11/2015. */ @RunWith(MockitoJUnitRunner.class) public class SegmentationElementScorerTest implements ScorerTest { SegmentationElementScorer elementScorerSUT; @Mock Scorer<Tag> tagScorerMock; @Mock Element elementMock; @Rule ExpectedException thrown = ExpectedException.none(); @Before public void setUp() throws Exception { elementScorerSUT = new SegmentationElementScorer(tagScorerMock); } @After public void tearDown() throws Exception { elementScorerSUT = null; } }
Use base because everyone can use the template view git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@750 0d517254-b314-0410-acde-c619094fa49f
package edu.northwestern.bioinformatics.studycalendar.web.template; import edu.northwestern.bioinformatics.studycalendar.web.ReturnSingleObjectController; import edu.northwestern.bioinformatics.studycalendar.domain.Arm; import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.AccessControl; import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.StudyCalendarProtectionGroup; /** * @author Rhett Sutphin */ @AccessControl(protectionGroups = StudyCalendarProtectionGroup.BASE) public class SelectArmController extends ReturnSingleObjectController<Arm> { public SelectArmController() { setParameterName("arm"); setViewName("template/ajax/selectArm"); } @Override protected Object wrapObject(Arm loaded) { return new ArmTemplate(loaded); } }
package edu.northwestern.bioinformatics.studycalendar.web.template; import edu.northwestern.bioinformatics.studycalendar.web.ReturnSingleObjectController; import edu.northwestern.bioinformatics.studycalendar.domain.Arm; import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.AccessControl; import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.StudyCalendarProtectionGroup; /** * @author Rhett Sutphin */ @AccessControl(protectionGroups = StudyCalendarProtectionGroup.STUDY_COORDINATOR) public class SelectArmController extends ReturnSingleObjectController<Arm> { public SelectArmController() { setParameterName("arm"); setViewName("template/ajax/selectArm"); } @Override protected Object wrapObject(Arm loaded) { return new ArmTemplate(loaded); } }
Make sure function has constructor
'use strict'; /* * Lots of things get wrapped in output(...args) * This function basically just makes sure the right stuffs * gets output */ module.exports = function output(obj, ...args) { if (!obj) { // return empty string for undefined objects return ''; } else if (Array.isArray(obj)) { // recurse into arrays return obj.map((obj) => output(obj, ...args)).join('') || ''; } else if (obj.prototype && obj.prototype.constructor && obj.prototype.render) { // should be a Component instance, create a new instance and return the // result of render const instance = new obj(Object.assign({}, args[0], { children: args.slice(1) })); return instance.render(instance.props, instance.state) || ''; } else if (typeof obj === 'function') { // a dumb / stateless component... simply call it return obj(Object.assign({}, args[0], { children: args.slice(1) })); } return obj; };
'use strict'; /* * Lots of things get wrapped in output(...args) * This function basically just makes sure the right stuffs * gets output */ module.exports = function output(obj, ...args) { if (!obj) { // return empty string for undefined objects return ''; } else if (Array.isArray(obj)) { // recurse into arrays return obj.map((obj) => output(obj, ...args)).join('') || ''; } else if (obj.prototype && obj.prototype.render) { // should be a Component instance, create a new instance and return the // result of render const instance = new obj(Object.assign({}, args[0], { children: args.slice(1) })); return instance.render(instance.props, instance.state) || ''; } else if (typeof obj === 'function') { // a dumb / stateless component... simply call it return obj(Object.assign({}, args[0], { children: args.slice(1) })); } return obj; };
Improve component test when fails to take snapshot
import { describeComponent, it } from 'ember-mocha'; import { beforeEach, afterEach } from 'mocha'; import { expect } from 'chai'; import hbs from 'htmlbars-inline-precompile'; import page from './page'; describeComponent('ember-webcam', 'Integration: EmberWebcamComponent', { integration: true }, () => { beforeEach(function () { page.setContext(this); }); afterEach(() => { page.removeContext(); }); it('renders', () => { page.render(hbs`{{ember-webcam}}`); expect(page.viewer.isVisible).to.be.true; }); it('takes a snapshot', done => { let isDone = false; page.context.setProperties({ didError(error) { // Should fail because camera is not available in test environment. expect(error.name).to.equal('WebcamError'); if (!isDone) { done(); isDone = true; } } }); page.render(hbs` {{#ember-webcam didError=(action didError) as |camera|}} <button {{action camera.snap}}> Take Snapshot! </button> {{/ember-webcam}} `); page.button.click(); }); });
import { describeComponent, it } from 'ember-mocha'; import { beforeEach, afterEach } from 'mocha'; import { expect } from 'chai'; import hbs from 'htmlbars-inline-precompile'; import page from './page'; describeComponent('ember-webcam', 'Integration: EmberWebcamComponent', { integration: true }, () => { beforeEach(function () { page.setContext(this); }); afterEach(() => { page.removeContext(); }); it('renders', () => { page.render(hbs`{{ember-webcam}}`); expect(page.viewer.isVisible).to.be.true; }); it('takes a snapshot', done => { let isDone = false; page.context.setProperties({ didError(errorMessage) { expect(errorMessage).to.be.ok; if (!isDone) { done(); isDone = true; } } }); page.render(hbs` {{#ember-webcam didError=(action didError) as |camera|}} <button {{action camera.snap}}> Take Snapshot! </button> {{/ember-webcam}} `); page.button.click(); }); });
Add test for valid json supplied in 'start' request Signed-off-by: Bryan Boreham <de652539b24efdf404b95def4635bf3dbfd846aa@gmail.com>
package client import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "testing" "golang.org/x/net/context" ) func TestContainerStartError(t *testing.T) { client := &Client{ transport: newMockClient(nil, errorMock(http.StatusInternalServerError, "Server error")), } err := client.ContainerStart(context.Background(), "nothing") if err == nil || err.Error() != "Error response from daemon: Server error" { t.Fatalf("expected a Server Error, got %v", err) } } func TestContainerStart(t *testing.T) { client := &Client{ transport: newMockClient(nil, func(req *http.Request) (*http.Response, error) { // we're not expecting any payload, but if one is supplied, check it is valid. if req.Header.Get("Content-Type") == "application/json" { var startConfig interface{} if err := json.NewDecoder(req.Body).Decode(&startConfig); err != nil { return nil, fmt.Errorf("Unable to parse json: %s", err) } } return &http.Response{ StatusCode: http.StatusOK, Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), }, nil }), } err := client.ContainerStart(context.Background(), "container_id") if err != nil { t.Fatal(err) } }
package client import ( "bytes" "io/ioutil" "net/http" "testing" "golang.org/x/net/context" ) func TestContainerStartError(t *testing.T) { client := &Client{ transport: newMockClient(nil, errorMock(http.StatusInternalServerError, "Server error")), } err := client.ContainerStart(context.Background(), "nothing") if err == nil || err.Error() != "Error response from daemon: Server error" { t.Fatalf("expected a Server Error, got %v", err) } } func TestContainerStart(t *testing.T) { client := &Client{ transport: newMockClient(nil, func(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: http.StatusOK, Body: ioutil.NopCloser(bytes.NewReader([]byte(""))), }, nil }), } err := client.ContainerStart(context.Background(), "container_id") if err != nil { t.Fatal(err) } }
Make sure events are consistently ordered
<?php class Denkmal_Paging_Event_Date extends Denkmal_Paging_Event_Abstract { /** * @param DateTime $date * @param bool|null $showAll */ public function __construct(DateTime $date, $showAll = null) { $date = clone $date; $date->setTime(Denkmal_Site::getDayOffset(), 0, 0); $startStamp = $date->getTimestamp(); $date->add(new DateInterval('P1D')); $endStamp = $date->getTimestamp(); $where = '`from` >= ' . $startStamp . ' AND `from` < ' . $endStamp; if (!$showAll) { $where .= ' AND `enabled` = 1 AND `hidden` = 0'; } $join = 'LEFT JOIN `denkmal_model_venue` AS `v` ON `e`.`venue` = `v`.`id`'; $source = new CM_PagingSource_Sql('e.id', 'denkmal_model_event` AS `e', $where, '`starred` DESC, `v`.`name`, `e`.`id`', $join); parent::__construct($source); } }
<?php class Denkmal_Paging_Event_Date extends Denkmal_Paging_Event_Abstract { /** * @param DateTime $date * @param bool|null $showAll */ public function __construct(DateTime $date, $showAll = null) { $date = clone $date; $date->setTime(Denkmal_Site::getDayOffset(), 0, 0); $startStamp = $date->getTimestamp(); $date->add(new DateInterval('P1D')); $endStamp = $date->getTimestamp(); $where = '`from` >= ' . $startStamp . ' AND `from` < ' . $endStamp; if (!$showAll) { $where .= ' AND `enabled` = 1 AND `hidden` = 0'; } $join = 'LEFT JOIN `denkmal_model_venue` AS `v` ON `e`.`venue` = `v`.`id`'; $source = new CM_PagingSource_Sql('e.id', 'denkmal_model_event` AS `e', $where, '`starred` DESC, `name`', $join); parent::__construct($source); } }
Print progress from the indexing script
#!/usr/bin/env python3 import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) import glob, json import numpy as np import task_usage def main(data_path, index_path, report_each=10000): print('Looking for data in "{}"...'.format(data_path)) paths = sorted(glob.glob('{}/**/*.sqlite3'.format(data_path))) print('Processing {} databases...'.format(len(paths))) index = [] count = 0 for path in paths: data = task_usage.count_job_task_samples(path) for i in range(data.shape[0]): index.append({ 'path': path, 'job': int(data[i, 0]), 'task': int(data[i, 1]), 'length': int(data[i, 2]), }) count += 1 if count % report_each == 0: print('Processed: {}'.format(count)) print('Saving into "{}"...'.format(index_path)) with open(index_path, 'w') as file: json.dump({'index': index}, file, indent=4) if __name__ == '__main__': assert(len(sys.argv) == 3) main(sys.argv[1], sys.argv[2])
#!/usr/bin/env python3 import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib')) import glob, json import numpy as np import task_usage def main(data_path, index_path): count = 0 index = [] for path in sorted(glob.glob('{}/**/*.sqlite3'.format(data_path))): data = task_usage.count_job_task_samples(path) for i in range(data.shape[0]): index.append({ 'path': path, 'job': int(data[i, 0]), 'task': int(data[i, 1]), 'count': int(data[i, 2]), }) count += 1 if count % 10000 == 0: print('Processed: {}'.format(count)) with open(index_path, 'w') as file: json.dump({'index': index}, file, indent=4) if __name__ == '__main__': assert(len(sys.argv) == 3) main(sys.argv[1], sys.argv[2])
Clarify how to perform future migrations
import packageJson from '../package.json'; import compareVersions from 'semver-compare'; import { SETTINGS_KEYS } from './settings'; export function migrateDataToVersion(database, settings) { // Get the current version we are upgrading from let fromVersion = settings.get(SETTINGS_KEYS.APP_VERSION); // If no is version saved, it is from an early version, which can be represented as 0.0.0 if (!fromVersion || fromVersion.length === 0) fromVersion = '0.0.0'; // Get the new version we are upgrading to const toVersion = packageJson.version; // If the version has not changed, we are not upgrading, so don't do anything if (fromVersion === toVersion) return; // Do any required version update data migrations for (const migration of dataMigrations) { if (compareVersions(fromVersion, migration.version) < 0) migration.migrate(database, settings); } // Record the new app version settings.set(SETTINGS_KEYS.APP_VERSION, toVersion); } // All data migration functions should be kept in this array, in sequential order. Each migration // needs a 'version' key, denoting the version that migration will migrate to, and a 'migrate' key, // which is a function taking the database and the settings and performs the migration const dataMigrations = [ { version: '1.0.30', migrate: (database, settings) => { // 1.0.30 added the setting 'SYNC_IS_INITIALISED', where it previously relied on 'SYNC_URL' const syncURL = settings.get(SETTINGS_KEYS.SYNC_URL); if (syncURL && syncURL.length > 0) settings.set(SETTINGS_KEYS.SYNC_IS_INITIALISED, 'true'); }, }, ];
import packageJson from '../package.json'; import compareVersions from 'semver-compare'; import { SETTINGS_KEYS } from './settings'; export function migrateDataToVersion(database, settings) { let fromVersion = settings.get(SETTINGS_KEYS.APP_VERSION); if (!fromVersion || fromVersion.length === 0) fromVersion = '0.0.0'; const toVersion = packageJson.version; if (fromVersion === toVersion) return; // Don't do anything if the version has not changed if (compareVersions(fromVersion, '1.0.30') < 0) { // 1.0.30 added the setting 'SYNC_IS_INITIALISED', where it previously relied on the 'SYNC_URL' const syncURL = settings.get(SETTINGS_KEYS.SYNC_URL); if (syncURL && syncURL.length > 0) settings.set(SETTINGS_KEYS.SYNC_IS_INITIALISED, 'true'); } settings.set(SETTINGS_KEYS.APP_VERSION, toVersion); }
Add rejectUnauthorized = false property in https-request
'use strict'; var https = require('https'); /** * Checks SSL Expiry date * @param {string} host * @param {string} method * @param {number} port * @return {object} */ module.exports = (host, method, port) => { if (!host) throw new Error("Invalid host"); const options = { host: host, method: method || 'HEAD', port: port || 443, rejectUnauthorized: false }; let numericPort = (!isNaN(parseFloat(options.port)) && isFinite(options.port)); if (numericPort === false) throw new Error("Invalid port"); let daysBetween = (from, to) => Math.round(Math.abs((+from) - (+to))/8.64e7); if (options.host === null || options.port === null) throw new Error("Invalid host or port"); try { return new Promise(function(resolve, reject) { const req = https.request(options, res => { let { valid_from, valid_to } = res.connection.getPeerCertificate(); resolve({ valid_from: valid_from, valid_to: valid_to, days_remaining: daysBetween(new Date(), new Date(valid_to)) }); }); req.on('error', (e) => { reject(e) }); req.end(); }).catch(console.error); } catch (e) { throw new Error(e) } };
'use strict'; var https = require('https'); /** * Checks SSL Expiry date * @param {string} host * @param {string} method * @param {number} port * @return {object} */ module.exports = (host, method, port) => { if (!host) throw new Error("Invalid host"); const options = { host: host, method: method || 'HEAD', port: port || 443 }; let numericPort = (!isNaN(parseFloat(options.port)) && isFinite(options.port)); if (numericPort === false) throw new Error("Invalid port"); let daysBetween = (from, to) => Math.round(Math.abs((+from) - (+to))/8.64e7); if (options.host === null || options.port === null) throw new Error("Invalid host or port"); try { return new Promise(function(resolve, reject) { const req = https.request(options, res => { let { valid_from, valid_to } = res.connection.getPeerCertificate(); resolve({ valid_from: valid_from, valid_to: valid_to, days_remaining: daysBetween(new Date(), new Date(valid_to)) }); }); req.on('error', (e) => { reject(e) }); req.end(); }).catch(console.error); } catch (e) { throw new Error(e) } };
Delete a trailing beginning of another test case
package maker import ( "strings" "testing" ) func check(value, pattern string, t *testing.T) { if value != pattern { t.Fatalf("Value %s did not match expected pattern %s", value, pattern) } } func TestLines(t *testing.T) { docs := []string{`// TestMethod is great`} code := `func TestMethod() string {return "I am great"}` method := Method{Code: code, Docs: docs} lines := method.Lines() check(lines[0], "// TestMethod is great", t) check(lines[1], "func TestMethod() string {return \"I am great\"}", t) } func TestParseStruct(t *testing.T) { src := []byte(`package main import ( "fmt" ) // Person ... type Person struct { name string } // Name ... func (p *Person) Name() string { return p.name }`) methods, imports := ParseStruct(src, "Person", true) check(methods[0].Code, "Name() string", t) imp := imports[0] trimmedImp := strings.TrimSpace(imp) expected := "\"fmt\"" check(trimmedImp, expected, t) }
package maker import ( "strings" "testing" ) func check(value, pattern string, t *testing.T) { if value != pattern { t.Fatalf("Value %s did not match expected pattern %s", value, pattern) } } func TestLines(t *testing.T) { docs := []string{`// TestMethod is great`} code := `func TestMethod() string {return "I am great"}` method := Method{Code: code, Docs: docs} lines := method.Lines() check(lines[0], "// TestMethod is great", t) check(lines[1], "func TestMethod() string {return \"I am great\"}", t) } func TestParseStruct(t *testing.T) { src := []byte(`package main import ( "fmt" ) // Person ... type Person struct { name string } // Name ... func (p *Person) Name() string { return p.name }`) methods, imports := ParseStruct(src, "Person", true) check(methods[0].Code, "Name() string", t) imp := imports[0] trimmedImp := strings.TrimSpace(imp) expected := "\"fmt\"" check(trimmedImp, expected, t) } func Test
Use ignorePattern to not gzip index.json This option wasn't originally available which is why filePattern needed to be overridden.
/* eslint-env node */ module.exports = function(deployTarget) { const API_VERSION = 'v1.12'; var ENV = { build: {}, exclude: ['.DS_Store', '*-test.js'], 'revision-data': { type: 'git-commit', } }; ENV.s3 = { acl: 'public-read', region: 'us-west-2', bucket: 'ilios-frontend-assets' }; ENV['s3-index'] = { region: 'us-west-2', filePattern: 'index.json', bucket: 'frontend-json-config', }; ENV.gzip = { //dont gzip the json index file ignorePattern: '**/index.json' }; if (deployTarget === 'staging') { ENV.build.environment = 'production'; ENV['s3-index'].prefix = 'stage-' + API_VERSION; } if (deployTarget === 'production') { ENV.build.environment = 'production'; ENV['s3-index'].prefix = 'prod-' + API_VERSION; } // Note: if you need to build some configuration asynchronously, you can return // a promise that resolves with the ENV object instead of returning the // ENV object synchronously. return ENV; };
/* eslint-env node */ module.exports = function(deployTarget) { const API_VERSION = 'v1.12'; var ENV = { build: {}, exclude: ['.DS_Store', '*-test.js'], 'revision-data': { type: 'git-commit', } }; ENV.s3 = { acl: 'public-read', region: 'us-west-2', bucket: 'ilios-frontend-assets' }; ENV['s3-index'] = { region: 'us-west-2', filePattern: 'index.json', bucket: 'frontend-json-config', }; ENV.gzip = { //dont gzip JSON files filePattern: '**/*.{js,css,ico,map,xml,txt,svg,eot,ttf,woff,woff2}' }; if (deployTarget === 'staging') { ENV.build.environment = 'production'; ENV['s3-index'].prefix = 'stage-' + API_VERSION; } if (deployTarget === 'production') { ENV.build.environment = 'production'; ENV['s3-index'].prefix = 'prod-' + API_VERSION; } // Note: if you need to build some configuration asynchronously, you can return // a promise that resolves with the ENV object instead of returning the // ENV object synchronously. return ENV; };
Document that not all slots a scheduling strategy returns are necessarily executed.
package com.collective.celos; import java.util.List; /** * A scheduling strategy determines the order in which slots of a workflow are executed. * * Scheduling strategies are configured on a per-workflow basis. * * On each scheduler cycle, a workflow's scheduling strategy is asked * which workflow instances (slots) should be executed. * * As input for making this decision, the scheduling strategy receives * all slot states of the given workflow within the sliding window. * * There's no guarantee that all slots returned by a strategy will be executed. */ public interface SchedulingStrategy { /** * Returns the slots that this strategy wishes to execute. * * Only slots in READY state should be returned. Others will be ignored. * * @param states The states of all slots within sliding window for this workflow, with oldest ones first. * @return List of slots this strategy wishes to execute - the first in the list will be executed first. */ public List<SlotID> getSchedulingCandidates(List<SlotState> states); }
package com.collective.celos; import java.util.List; /** * A scheduling strategy determines the order in which slots of a workflow are executed. * * Scheduling strategies are configured on a per-workflow basis. * * On each scheduler cycle, a workflow's scheduling strategy is asked * which workflow instances (slots) should be executed. * * As input for making this decision, the scheduling strategy receives * all slot states of the given workflow within the sliding window. */ public interface SchedulingStrategy { /** * Returns the slots that this strategy wishes to execute. * * Only slots in READY state should be returned. Others will be ignored. * * @param states The states of all slots within sliding window for this workflow, with oldest ones first. * @return List of slots this strategy wishes to execute - the first in the list will be executed first. */ public List<SlotID> getSchedulingCandidates(List<SlotState> states); }
Add day 12 part two solution in python
#!/usr/local/bin/python3 import json import pathlib input_file = pathlib.Path(__file__).parent.parent.joinpath('day12_input.txt') def sum_data(d): total = 0 if isinstance(d, dict): d = d.values() if 'red' in d: return 0 for item in d: if isinstance(item, int): total += item elif isinstance(item, (list, dict)): total += sum_data(item) else: continue # Some other type we’re not interested in return total def sum_json(raw_json): parsed = json.loads(raw_json) return sum_data(parsed) def test_simple(): assert sum_json('[1,2,3]') == 6 assert sum_json('{"a":2,"b":4}') == 6 def test_nested(): assert sum_json('[[[3]]]') == 3 assert sum_json('{"a":{"b":4},"c":-1}') == 3 def test_mixed(): assert sum_json('{"a":[-1,1]}') == 0 assert sum_json('[-1,{"a":1}]') == 0 def test_empty(): assert sum_json('[]') == 0 assert sum_json('{}') == 0 if __name__ == '__main__': with open(input_file) as json_file: json_data = json_file.read() print(sum_json(json_data))
#!/usr/local/bin/python3 import json import pathlib input_file = pathlib.Path(__file__).parent.parent.joinpath('day12_input.txt') def sum_data(d): total = 0 if isinstance(d, dict): d = d.values() for item in d: if isinstance(item, int): total += item elif isinstance(item, (list, dict)): total += sum_data(item) else: continue # Some other type we’re not interested in return total def sum_json(raw_json): parsed = json.loads(raw_json) return sum_data(parsed) def test_simple(): assert sum_json('[1,2,3]') == 6 assert sum_json('{"a":2,"b":4}') == 6 def test_nested(): assert sum_json('[[[3]]]') == 3 assert sum_json('{"a":{"b":4},"c":-1}') == 3 def test_mixed(): assert sum_json('{"a":[-1,1]}') == 0 assert sum_json('[-1,{"a":1}]') == 0 def test_empty(): assert sum_json('[]') == 0 assert sum_json('{}') == 0 if __name__ == '__main__': with open(input_file) as json_file: json_data = json_file.read() print(sum_json(json_data))
Use select_related to help with category foreign keys
from django.views.generic import ListView, DateDetailView from django.shortcuts import get_object_or_404 from django.utils import timezone from django.conf import settings from .models import Category, Post class PostListView(ListView): paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) def get_queryset(self): return Post.objects.select_related().filter( published=True, date__lte=timezone.now()) class PostListCategoryView(ListView): paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) template_name_suffix = '_list_category' def get_queryset(self): self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return Post.objects.select_related().filter( published=True, date__lte=timezone.now(), category=self.category) def get_context_data(self, **kwargs): context = super(PostListCategoryView, self).get_context_data(**kwargs) context['category'] = self.category return context class PostDetailView(DateDetailView): queryset = Post.objects.filter(published=True) month_format = '%m' date_field = 'date'
from django.views.generic import ListView, DateDetailView from django.shortcuts import get_object_or_404 from django.utils import timezone from django.conf import settings from .models import Category, Post class PostListView(ListView): paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) def get_queryset(self): return Post.objects.filter(published=True, date__lte=timezone.now()) class PostListCategoryView(ListView): paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) template_name_suffix = '_list_category' def get_queryset(self): self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return Post.objects.filter(published=True, date__lte=timezone.now(), category=self.category) def get_context_data(self, **kwargs): context = super(PostListCategoryView, self).get_context_data(**kwargs) context['category'] = self.category return context class PostDetailView(DateDetailView): queryset = Post.objects.filter(published=True) month_format = '%m' date_field = 'date'
Hide exceptions if elasticsearch is not running. This needs some fixing and cleaning up by someone smarter than myself.
<?php namespace FOQ\ElasticaBundle; use Elastica_Client; use FOQ\ElasticaBundle\Logger\ElasticaLogger; /** * @author Gordon Franke <info@nevalon.de> */ class Client extends Elastica_Client { protected $logger; public function setLogger(ElasticaLogger $logger) { $this->logger = $logger; } public function request($path, $method, $data = array()) { $start = microtime(true); //this is ghetto, but i couldnt figure out another way of making our site continue to behave normally even if ES was not running. //Any improvements on this welcome. Perhaps another parameter that allows you to control if you want to ignore exceptions about ES not running try { $response = parent::request($path, $method, $data); } catch(\Exception $e) { //again, ghetto, but couldnt figure out how to return a default empty Elastica_Response return new \Elastica_Response('{"took":0,"timed_out":false,"hits":{"total":0,"max_score":0,"hits":[]}}'); } if (null !== $this->logger) { $time = microtime(true) - $start; $this->logger->logQuery($path, $method, $data, $time); } return $response; } }
<?php namespace FOQ\ElasticaBundle; use Elastica_Client; use FOQ\ElasticaBundle\Logger\ElasticaLogger; /** * @author Gordon Franke <info@nevalon.de> */ class Client extends Elastica_Client { protected $logger; public function setLogger(ElasticaLogger $logger) { $this->logger = $logger; } public function request($path, $method, $data = array()) { $start = microtime(true); $response = parent::request($path, $method, $data); if (null !== $this->logger) { $time = microtime(true) - $start; $this->logger->logQuery($path, $method, $data, $time); } return $response; } }
Append timestamp to existing message string - This fixes a race condition that could cause the timestamp to become separated from the rest of the message if there were a lot of calls to a log method roughly at the same time.
var isPatched = false; var slice = Array.prototype.slice; if (isPatched) return; function addColor(string) { var colorName = getColorName(string); var colors = { green: ['\x1B[32m', '\x1B[39m'], red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'], yellow: ['\x1B[33m', '\x1B[39m'] } return colors[colorName][0] + string + colors[colorName][1]; } function getColorName(methodName) { switch (methodName) { case 'ERROR': return 'red'; case 'WARN': return 'yellow'; default: return 'green'; } } ['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) { var baseConsoleMethod = console[method]; var messageType = method.toUpperCase(); var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout'; if (process[output].isTTY) messageType = addColor(messageType); console[method] = function() { var date = (new Date()).toISOString(); var args = slice.call(arguments); var dateMessage = '[' + date + '] ' + messageType + ' '; args[0] = typeof args[0] === 'string' ? dateMessage + args[0] : dateMessage; return baseConsoleMethod.apply(console, args); } }); isPatched = true;
var isPatched = false; var slice = Array.prototype.slice; if (isPatched) return; function addColor(string) { var colorName = getColorName(string); var colors = { green: ['\x1B[32m', '\x1B[39m'], red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'], yellow: ['\x1B[33m', '\x1B[39m'] } return colors[colorName][0] + string + colors[colorName][1]; } function getColorName(methodName) { switch (methodName) { case 'ERROR': return 'red'; case 'WARN': return 'yellow'; default: return 'green'; } } ['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) { var baseConsoleMethod = console[method]; var messageType = method.toUpperCase(); var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout'; console[method] = function() { var date = (new Date()).toISOString(); var args = slice.call(arguments); if (process[output].isTTY) messageType = addColor(messageType); process[output].write('[' + date + '] ' + messageType + ' '); return baseConsoleMethod.apply(console, args); } }); isPatched = true;
Add missing key to retryPlugin apis
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014 Groupon, Inc * Copyright 2014 The Billing Project, LLC * * The Billing Project 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.killbill.billing.retry.plugin.api; import org.joda.time.DateTime; public interface RetryPluginApi { /** * * @return true if retry logic should be aborted */ public boolean isRetryAborted(final String externalKey); /** * * @return the next date where retry should occur; null if there is no more retry */ public DateTime getNextRetryDate(final String externalKey); }
/* * Copyright 2010-2013 Ning, Inc. * Copyright 2014 Groupon, Inc * Copyright 2014 The Billing Project, LLC * * The Billing Project 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.killbill.billing.retry.plugin.api; import org.joda.time.DateTime; public interface RetryPluginApi { /** * * @return true if retry logic should be aborted */ public boolean isRetryAborted(); /** * * @return the next date where retry should occur; null if there is no more retry */ public DateTime getNextRetryDate(); }
Fix identity scales, override map & train methods
from __future__ import absolute_import, division, print_function from ..utils import identity, alias from .scale import scale_discrete, scale_continuous class MapTrainMixin(object): """ Override map and train methods """ def map(self, x): return x def train(self, x): # do nothing if no guide, # otherwise train so we know what breaks to use if self.guide is None: return return super(MapTrainMixin, self).train(x) class scale_color_identity(MapTrainMixin, scale_discrete): aesthetics = ['color'] palette = staticmethod(identity) guide = None class scale_fill_identity(scale_color_identity): aesthetics = ['fill'] class scale_shape_identity(MapTrainMixin, scale_discrete): aesthetics = ['shape'] palette = staticmethod(identity) guide = None class scale_linetype_identity(MapTrainMixin, scale_discrete): aesthetics = ['linetype'] palette = staticmethod(identity) guide = None class scale_alpha_identity(MapTrainMixin, scale_continuous): aesthetics = ['alpha'] palette = staticmethod(identity) guide = None class scale_size_identity(MapTrainMixin, scale_continuous): aesthetics = ['size'] palette = staticmethod(identity) guide = None # American to British spelling alias('scale_colour_identity', scale_color_identity)
from __future__ import absolute_import, division, print_function from ..utils import identity, alias from .scale import scale_discrete, scale_continuous class scale_color_identity(scale_discrete): aesthetics = ['color'] palette = staticmethod(identity) class scale_fill_identity(scale_color_identity): aesthetics = ['fill'] class scale_shape_identity(scale_discrete): aesthetics = ['shape'] palette = staticmethod(identity) class scale_linetype_identity(scale_discrete): aesthetics = ['linetype'] palette = staticmethod(identity) class scale_alpha_identity(scale_continuous): aesthetics = ['alpha'] palette = staticmethod(identity) class scale_size_identity(scale_continuous): aesthetics = ['size'] palette = staticmethod(identity) # American to British spelling alias('scale_colour_identity', scale_color_identity)
Fix pagination links on the RPC page navigation.
// RPC reply serializer, that should heppen in the end, // because we pass errors in serialized form too // 'use strict'; //////////////////////////////////////////////////////////////////////////////// module.exports = function (N) { N.wire.after('responder:rpc', { priority: 90 }, function rpc_serialize(env) { // Set Content-Type and charset (override existing) env.headers['Content-Type'] = 'application/json; charset=UTF-8'; // Status is always ok - errors are embedded into payload env.status = N.io.OK; // Expose API path of the executed server method, e.g. 'forum.index' env.response.data.head.apiPath = env.method; // HEAD requested - no need for real rendering if ('HEAD' === env.origin.req.method) { env.body = null; return; } // Replace body with serialized payload env.body = JSON.stringify({ version: N.runtime.version, error: env.err, response: env.err ? null : env.response }); }); };
// RPC reply serializer, that should heppen in the end, // because we pass errors in serialized form too // 'use strict'; //////////////////////////////////////////////////////////////////////////////// module.exports = function (N) { N.wire.after('responder:rpc', { priority: 90 }, function rpc_serialize(env) { // // Set Content-Type and charset (override existing) // env.headers['Content-Type'] = 'application/json; charset=UTF-8'; // // Status is always ok - errors are embedded into payload // env.status = N.io.OK; // // HEAD requested - no need for real rendering // if ('HEAD' === env.origin.req.method) { env.body = null; return; } // // Replace body with serialized payload // env.body = JSON.stringify({ version: N.runtime.version, error: env.err, response: env.err ? null : env.response }); }); };
Add convenience test for running against a filesystem codebase. git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@417 c7a0535c-eda6-11de-83d8-6d5adf01d787
/* * Mutability Detector * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Further licensing information for this project can be found in * license/LICENSE.txt */ package org.mutabilitydetector.cli; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import org.junit.Ignore; import org.junit.Test; import com.google.classpath.ClassPathFactory; public class NullPointerExceptionAnalysingRtJar { private final PrintStream errorStream = new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException { // suppress output in tests } }); @Ignore @Test public void checkNullPointerExceptionIsNotThrown() { String rtJarPath = System.getProperty("java.home") + "/lib/rt.jar"; BatchAnalysisOptions options = new CommandLineOptions(errorStream, "-cp", rtJarPath); new RunMutabilityDetector(new ClassPathFactory().createFromPath(rtJarPath), options).run(); } @Ignore @Test public void checkNullPointerExceptionIsNotThrownOnAbritaryCodebase() { String rtJarPath = "..."; BatchAnalysisOptions options = new CommandLineOptions(errorStream, "-cp", rtJarPath); new RunMutabilityDetector(new ClassPathFactory().createFromPath(rtJarPath), options).run(); } }
/* * Mutability Detector * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * Further licensing information for this project can be found in * license/LICENSE.txt */ package org.mutabilitydetector.cli; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import org.junit.Ignore; import org.junit.Test; import com.google.classpath.ClassPathFactory; public class NullPointerExceptionAnalysingRtJar { private final PrintStream errorStream = new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException { // suppress output in tests } }); @Ignore @Test public void checkNullPointerExceptionIsNotThrown() { String rtJarPath = System.getProperty("java.home") + "/lib/rt.jar"; BatchAnalysisOptions options = new CommandLineOptions(errorStream, "-cp", rtJarPath); new RunMutabilityDetector(new ClassPathFactory().createFromPath(rtJarPath), options).run(); } }
Fix hello world phrase in russian
function hello(language) { var hellos = { 'Chinese': '你好世界', 'Dutch': 'Hello wereld', 'English': 'Hello world', 'French': 'Bonjour monde', 'German': 'Hallo Welt', 'Greek': 'γειά σου κόσμος', 'Italian': 'Ciao mondo', 'Japanese': 'こんにちは世界', 'Korean': '안녕하세요 세계', 'Portuguese': 'Olá mundo', 'Russian': 'Здравствуй мир', 'Spanish': 'Hola mundo', 'Latin': 'Salve munde', 'Piglatin': 'Ellohay orldway' }; return hellos[language]; }
function hello(language) { var hellos = { 'Chinese': '你好世界', 'Dutch': 'Hello wereld', 'English': 'Hello world', 'French': 'Bonjour monde', 'German': 'Hallo Welt', 'Greek': 'γειά σου κόσμος', 'Italian': 'Ciao mondo', 'Japanese': 'こんにちは世界', 'Korean': '안녕하세요 세계', 'Portuguese': 'Olá mundo', 'Russian': 'Здравствулте мир', 'Spanish': 'Hola mundo', 'Latin': 'Salve munde', 'Piglatin': 'Ellohay orldway' }; return hellos[language]; }
Change the instructor value to be the same as other impls
package org.tsugi; /** * This is a class to provide access to the data for the logged-in user * * This data comes from the LTI launch from the LMS. * If this is an anonymous launch the User will be null. */ public interface User { public final int LEARNER_ROLE = 0; public final int INSTRUCTOR_ROLE = 1; public final int TENANT_ADMIN_ROLE = 1000; public final int ROOT_ADMIN_ROLE = 10000; /** * Get the launch associated with this object */ public Launch getLaunch(); /** * The integer primary key for this user in this instance of Tsugi. */ public Long getId(); /** * The user's email */ public String getEmail(); /** * The user's display name */ public String getDisplayname(); /** * Is the user a Mentor? (TBD) */ public boolean isMentor(); /** * Is the user an instructor? */ public boolean isInstructor(); /** * Is the user a Tenant Administrator? */ public boolean isTenantAdmin(); /** * Is the user a Tsugi-wide Administrator? */ public boolean isRootAdmin(); }
package org.tsugi; /** * This is a class to provide access to the data for the logged-in user * * This data comes from the LTI launch from the LMS. * If this is an anonymous launch the User will be null. */ public interface User { public final int LEARNER_ROLE = 0; public final int INSTRUCTOR_ROLE = 1000; public final int TENANT_ADMIN_ROLE = 5000; public final int ROOT_ADMIN_ROLE = 10000; /** * Get the launch associated with this object */ public Launch getLaunch(); /** * The integer primary key for this user in this instance of Tsugi. */ public Long getId(); /** * The user's email */ public String getEmail(); /** * The user's display name */ public String getDisplayname(); /** * Is the user a Mentor? (TBD) */ public boolean isMentor(); /** * Is the user an instructor? */ public boolean isInstructor(); /** * Is the user a Tenant Administrator? */ public boolean isTenantAdmin(); /** * Is the user a Tsugi-wide Administrator? */ public boolean isRootAdmin(); }
Fix path to commit.sh script It should be relative to __dirname, not to cwd()
var exec = require('child_process').exec; var temp = require('temp'); var fs = fs = require('fs'); var log = require('./logger'); exports.head = function (path, callback) { exec('git --git-dir=' + path + ".git log -1 --pretty=format:'%H%n%an <%ae>%n%ad%n%s%n'", function(error, stdout, stderr) { var str = stdout.split('\n'); var commit = { commit: str[0], author: str[1], date: str[2], message: str[3], }; callback(commit); }); }; exports.commit = function (path, author, message, callback) { temp.open('bombastic', function(err, info) { if (err) { log.error("Can't create temporaty file " + info.path); callback(); } log.debug('Write commit message into temporary file ' + info.path); fs.write(info.fd, message); fs.close(info.fd, function(err) { var command = [__dirname + '/scripts/commit.sh ', path, ' "', author.name, ' <', author.email, '> " "', info.path, '"'].join(''); exec(command, function(error, stdout, stderr) { log.debug(stdout); callback(); }); }); }); }
var exec = require('child_process').exec; var temp = require('temp'); var fs = fs = require('fs'); var log = require('./logger'); exports.head = function (path, callback) { exec('git --git-dir=' + path + ".git log -1 --pretty=format:'%H%n%an <%ae>%n%ad%n%s%n'", function(error, stdout, stderr) { var str = stdout.split('\n'); var commit = { commit: str[0], author: str[1], date: str[2], message: str[3], }; callback(commit); }); }; exports.commit = function (path, author, message, callback) { temp.open('bombastic', function(err, info) { if (err) { log.error("Can't create temporaty file " + info.path); callback(); } log.debug('Write commit message into temporary file ' + info.path); fs.write(info.fd, message); fs.close(info.fd, function(err) { var command = ['./scripts/commit.sh ', path, ' "', author.name, ' <', author.email, '> " "', info.path, '"'].join(''); exec(command, function(error, stdout, stderr) { log.debug(stdout); callback(); }); }); }); }
Revert "Vimeo connector to generate gzip file." This reverts commit 28a5383fb8e781812f79c7f838776f86df517782.
<?php namespace php_active_record; /* connector for Vimeo estimated execution time: 20 minutes */ $timestart = microtime(1); include_once(dirname(__FILE__) . "/../../config/environment.php"); require_library('connectors/VimeoAPI'); $resource_id = 214; $taxa = VimeoAPI::get_all_taxa(); $xml = \SchemaDocument::get_taxon_xml($taxa); $resource_path = CONTENT_RESOURCE_LOCAL_PATH . $resource_id . ".xml"; $OUT = fopen($resource_path, "w"); fwrite($OUT, $xml); fclose($OUT); Functions::set_resource_status_to_force_harvest($resource_id); $elapsed_time_sec = microtime(1) - $timestart; echo "\n"; echo "elapsed time = $elapsed_time_sec seconds \n"; echo "elapsed time = " . $elapsed_time_sec/60 . " minutes \n"; echo "\n\n Done processing."; ?>
<?php namespace php_active_record; /* connector for Vimeo estimated execution time: 20 minutes */ $timestart = microtime(1); include_once(dirname(__FILE__) . "/../../config/environment.php"); require_library('connectors/VimeoAPI'); $resource_id = 214; $taxa = VimeoAPI::get_all_taxa(); $xml = \SchemaDocument::get_taxon_xml($taxa); $resource_path = CONTENT_RESOURCE_LOCAL_PATH . $resource_id . ".xml"; $OUT = fopen($resource_path, "w"); fwrite($OUT, $xml); fclose($OUT); if(filesize(CONTENT_RESOURCE_LOCAL_PATH . $resource_id . ".xml") > 1000) { Functions::set_resource_status_to_force_harvest($resource_id); $command_line = "gzip -c " . CONTENT_RESOURCE_LOCAL_PATH . $resource_id . ".xml >" . CONTENT_RESOURCE_LOCAL_PATH . $resource_id . ".xml.gz"; $output = shell_exec($command_line); } $elapsed_time_sec = microtime(1) - $timestart; echo "\n"; echo "elapsed time = $elapsed_time_sec seconds \n"; echo "elapsed time = " . $elapsed_time_sec/60 . " minutes \n"; echo "\n\n Done processing."; ?>
fix: Remove redis test for build platform travis
const chai = require('chai'); const expect = chai.expect; const sinon = require('sinon'); const proxyquire = require('proxyquire'); const confStub = { redis: {} }; describe('IsTokenRevoked', function () { it('should return false if the token is not revoked', function (done) { const SessionService = require('./session-service'); const email = "foo@bar.com"; const tokenId = "validToken"; SessionService.isTokenRevoked(email, tokenId, (err, bool) => { expect(err).to.be.null; expect(bool).to.be.false; done(); }); }); // it('should return false if the token is revoked in Redis', function (done) { // const SessionService = proxyquire('./session-service', {'../config/dev.js': confStub}); // // const email = "foo@bar.com"; // const tokenId = "validToken"; // SessionService.isTokenRevoked(email, tokenId, (err, bool) => { // expect(err).to.be.null; // expect(bool).to.be.false; // done(); // }); // }); });
const chai = require('chai'); const expect = chai.expect; const sinon = require('sinon'); const proxyquire = require('proxyquire'); const confStub = { redis: {} }; describe('IsTokenRevoked', function () { it('should return false if the token is not revoked', function (done) { const SessionService = require('./session-service'); const email = "foo@bar.com"; const tokenId = "validToken"; SessionService.isTokenRevoked(email, tokenId, (err, bool) => { expect(err).to.be.null; expect(bool).to.be.false; done(); }); }); it('should return false if the token is revoked in Redis', function (done) { const SessionService = proxyquire('./session-service', {'../config/dev.js': confStub}); const email = "foo@bar.com"; const tokenId = "validToken"; SessionService.isTokenRevoked(email, tokenId, (err, bool) => { expect(err).to.be.null; expect(bool).to.be.false; done(); }); }); });
Fix varriable name of json
(function ($) { $(window).load(function(){ window.hologram(document.getElementsByClassName('hologram-area')[0], { uploadUrl: Drupal.settings.Hologram.uploadUrl, onComplete: function(result){ var response = result['response']; var json = JSON.stringify(result['files']); $('input[name="field_image[und][0][value][image_json]"').val(json); }, config: { uploader: '/hologram/upload' }, }); var store = window.hologram.store; store.subscribe(function(){ var files = store.getState().files; var json = JSON.stringify(files); $('input[name="field_image[und][0][value][field][image_json]"').val(json); }); }); })(jQuery);
(function ($) { $(window).load(function(){ window.hologram(document.getElementsByClassName('hologram-area')[0], { uploadUrl: Drupal.settings.Hologram.uploadUrl, onComplete: function(result){ var response = result['response']; console.log(result['response'].text); var json = JSON.stringify(result['files']); $('input[name="field_image[und][0][value][image_json]"').val(json); }, config: { uploader: '/hologram/upload' }, }); var store = window.hologram.store; store.subscribe(function(){ var files = store.getState().files; var val = JSON.stringify(files); $('input[name="field_image[und][0][value][field][image_json]"').val(json); }); }); })(jQuery);
Use a single shared 'begin' function in postgres adapter
var pg = require('pg') , Transaction = require('any-db').Transaction , pgNative = null try { pgNative = pg.native } catch (__e) {} exports.forceJS = false exports.createConnection = function (opts, callback) { var backend = chooseBackend() , conn = new backend.Client(opts) conn.begin = begin if (callback) { conn.connect(function (err) { if (err) callback(err) else callback(null, conn) }) } else { conn.connect() } return conn } // Create a Query object that conforms to the Any-DB interface exports.createQuery = function (stmt, params, callback) { var backend = chooseBackend() return new backend.Query(stmt, params, callback) } function chooseBackend () { return (exports.forceJS || !pgNative) ? pg : pgNative } var Transaction = require('any-db').Transaction var begin = Transaction.createBeginMethod(exports.createQuery)
var pg = require('pg') , Transaction = require('any-db').Transaction , pgNative = null try { pgNative = pg.native } catch (__e) {} exports.forceJS = false exports.createConnection = function (opts, callback) { var backend = chooseBackend() , conn = new backend.Client(opts) conn.begin = Transaction.createBeginMethod(exports.createQuery) if (callback) { conn.connect(function (err) { if (err) callback(err) else callback(null, conn) }) } else { conn.connect() } return conn } // Create a Query object that conforms to the Any-DB interface exports.createQuery = function (stmt, params, callback) { var backend = chooseBackend() return new backend.Query(stmt, params, callback) } function chooseBackend () { return (exports.forceJS || !pgNative) ? pg : pgNative }
Refactor a new method for context definition i.e. mapping between templates and data structures
package ie.ucd.clops.documentation; import java.io.OutputStream; import java.io.PrintStream; import java.io.Writer; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; /** * <BON> * class_chart DOCUMENT_GENERATION * explanation * "Generation of documentation from the descriptions of options" * command * "Generate Documentation" * end * </BON> */ public class DocumentGeneration { public static final String HTML_TEMPLATE_NAME = "html.vm"; public void generate(OutputStream targetFile) { try { Velocity.init(); VelocityContext context = createContext(); Template template = Velocity.getTemplate(DocumentGeneration.HTML_TEMPLATE_NAME); Writer writer = new java.io.OutputStreamWriter(targetFile); template.merge(context, writer); writer.flush(); writer.close(); } catch (Exception e) { // @TODO log this e.printStackTrace(); } } /** * Define the context for document generation * * @return */ protected VelocityContext createContext() { VelocityContext context = new VelocityContext(); context.put("option", new OptionDescription()); return context; } }
package ie.ucd.clops.documentation; import java.io.Writer; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; /** * <BON> * class_chart DOCUMENT_GENERATION * explanation "Generation of documentation from the descriptions of options" * end * </BON> */ public class DocumentGeneration { public void generate() { try { Velocity.init(); VelocityContext context = new VelocityContext(); context.put("option", new OptionDescription()); Template template = Velocity.getTemplate("html.vm"); Writer writer = new java.io.OutputStreamWriter(System.out); template.merge(context, writer); writer.flush(); writer.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Improve assertion messages in test utility
const { expect } = require('chai') const OError = require('../..') exports.expectError = function OErrorExpectError(e, expected) { expect( e.name, "error should set the name property to the error's name" ).to.equal(expected.name) expect( e instanceof expected.klass, 'error should be an instance of the error type' ).to.be.true expect( e instanceof Error, 'error should be an instance of the built-in Error type' ).to.be.true expect( require('util').types.isNativeError(e), 'error should be recognised by util.types.isNativeError' ).to.be.true expect(e.stack, 'error should have a stack trace').to.be.truthy expect( e.toString(), 'toString should return the default error message formatting' ).to.equal(expected.message) expect( e.stack.split('\n')[0], 'stack should start with the default error message formatting' ).to.match(new RegExp(`^${expected.name}:`)) expect( e.stack.split('\n')[1], 'first stack frame should be the function where the error was thrown' ).to.match(expected.firstFrameRx) } exports.expectFullStackWithoutStackFramesToEqual = function (error, expected) { const fullStack = OError.getFullStack(error) const fullStackWithoutFrames = fullStack .split('\n') .filter((line) => !/^\s+at\s/.test(line)) expect( fullStackWithoutFrames, 'full stack without frames should equal' ).to.deep.equal(expected) }
const { expect } = require('chai') const OError = require('../..') exports.expectError = function OErrorExpectError(e, expected) { // should set the name to the error's name expect(e.name).to.equal(expected.name) // should be an instance of the error type expect(e instanceof expected.klass).to.be.true // should be an instance of the built-in Error type expect(e instanceof Error).to.be.true // should be recognised by util.isError expect(require('util').types.isNativeError(e)).to.be.true // should have a stack trace expect(e.stack).to.be.truthy // toString should return the default error message formatting expect(e.toString()).to.equal(expected.message) // stack should start with the default error message formatting expect(e.stack.split('\n')[0]).to.match(new RegExp(`^${expected.name}:`)) // first stack frame should be the function where the error was thrown expect(e.stack.split('\n')[1]).to.match(expected.firstFrameRx) } exports.expectFullStackWithoutStackFramesToEqual = function (error, expected) { // But the stack contains all of the errors and tags. const fullStack = OError.getFullStack(error) const fullStackWithoutFrames = fullStack .split('\n') .filter((line) => !/^\s+at\s/.test(line)) expect(fullStackWithoutFrames).to.deep.equal(expected) }
Disable click binding in page.js Right now, page.js should only be setting the dashboard based on the URL, not handling any actual routing, since most of the pages are being loaded from Django.
'use strict'; var page = require('page'); module.exports = { template: require('./template.html'), replace: true, data: function () { return { dashboard: 'management-dashboard' }; }, created: function () { var show = function (ctx) { console.debug('dashboard::show', ctx.params.dashboard); this.dashboard = ctx.params.dashboard || 'management-dashboard'; }.bind(this); page('/datapoints/:dashboard', show); page({ click: false }); }, components: { 'management-dashboard': require('../../dashboard/management'), 'nco-dashboard' : require('../../dashboard/nco'), 'chart-bar' : require('../../component/chart/bar'), 'chart-bullet' : require('../../component/chart/bullet'), 'chart-map' : require('../../component/chart/map'), 'chart-pie' : require('../../component/chart/pie'), 'chart-stacked-area' : require('../../component/chart/stacked-area'), 'chart-line' : require('../../component/chart/line'), 'chart-year-over-year': require('../../component/chart/year-over-year'), 'vue-dropdown' : require('../../component/dropdown') }, partials: { 'loading-overlay': require('../../component/chart/partials/loading-overlay.html') } };
'use strict'; var page = require('page'); module.exports = { template: require('./template.html'), replace: true, data: function () { return { dashboard: 'management-dashboard' }; }, created: function () { var show = function (ctx) { console.debug('dashboard::show', ctx.params.dashboard); this.dashboard = ctx.params.dashboard || 'management-dashboard'; }.bind(this); page('/datapoints/:dashboard', show); page(); }, components: { 'management-dashboard': require('../../dashboard/management'), 'nco-dashboard' : require('../../dashboard/nco'), 'chart-bar' : require('../../component/chart/bar'), 'chart-bullet' : require('../../component/chart/bullet'), 'chart-map' : require('../../component/chart/map'), 'chart-pie' : require('../../component/chart/pie'), 'chart-stacked-area' : require('../../component/chart/stacked-area'), 'chart-line' : require('../../component/chart/line'), 'chart-year-over-year': require('../../component/chart/year-over-year'), 'vue-dropdown' : require('../../component/dropdown') }, partials: { 'loading-overlay': require('../../component/chart/partials/loading-overlay.html') } };
Improve selector performance, remove comment
module.exports = { get zero() { return browser.element('button=0'); }, get one() { return browser.element('button=1'); }, get two() { return browser.element('button=2'); }, get three() { return browser.element('button=3'); }, get four() { return browser.element('button=4'); }, get five() { return browser.element('button=5'); }, get six() { return browser.element('button=6'); }, get seven() { return browser.element('button=7'); }, get eight() { return browser.element('button=8'); }, get nine() { return browser.element('button=9'); }, get period() { return browser.element('button=.'); }, get dividedBy() { return browser.element('button=÷'); }, get times() { return browser.element('button=×'); }, get minus() { return browser.element('button=-'); }, get plus() { return browser.element('button=+'); }, get equals() { return browser.element('button=='); }, get responsePaneText() { return browser.getText('#response-pane'); }, };
module.exports = { // get zero () { return browser.element('button*=0)'); }, get zero() { return browser.element('button*=0'); }, get one() { return browser.element('button*=1'); }, get two() { return browser.element('button*=2'); }, get three() { return browser.element('button*=3'); }, get four() { return browser.element('button*=4'); }, get five() { return browser.element('button*=5'); }, get six() { return browser.element('button*=6'); }, get seven() { return browser.element('button*=7'); }, get eight() { return browser.element('button*=8'); }, get nine() { return browser.element('button*=9'); }, get period() { return browser.element('button*=.'); }, get dividedBy() { return browser.element('button*=÷'); }, get times() { return browser.element('button*=×'); }, get minus() { return browser.element('button*=-'); }, get plus() { return browser.element('button*=+'); }, get equals() { return browser.element('button*=='); }, get responsePaneText() { return browser.getText('#response-pane'); }, };
Use S2 port for US sensor
import lejos.nxt.*; public class Group7Robot { public static void main(String[] args) { // MOTORS NXTRegulatedMotor leftMotor = Motor.A; NXTRegulatedMotor rightMotor = Motor.C; NXTRegulatedMotor clawMotor = Motor.B; // SENSORS FilteredLightSensor lightSensor = new FilteredLightSensor(SensorPort.S1); FilteredUltrasonicSensor ultrasonicSensor = new FilteredUltrasonicSensor(SensorPort.S2); // HELPER THREADS Odometer odometer = new Odometer(leftMotor, rightMotor, lightSensor); Navigation navigation = new Navigation(leftMotor, rightMotor, odometer); // CONTROLLERS LocalizationController localization = new LocalizationController(navigation, null, ultrasonicSensor); // LOGIC odometer.start(); navigation.start(); Button.waitForAnyPress(); // logic for presentation vid // TODO: use claw correctly // TODO: do quick callibration so navig works (Odometer WHEEL_RADIUS and WHEEL_DISTANCE) clawMotor.rotate(180); navigation.forward(60); navigation.waitUntilDone(); clawMotor.rotate(-180); navigation.forward(-60); navigation.waitUntilDone(); } }
import lejos.nxt.*; public class Group7Robot { public static void main(String[] args) { // MOTORS NXTRegulatedMotor leftMotor = Motor.A; NXTRegulatedMotor rightMotor = Motor.C; NXTRegulatedMotor clawMotor = Motor.B; // SENSORS FilteredLightSensor lightSensor = new FilteredLightSensor(SensorPort.S1); FilteredUltrasonicSensor ultrasonicSensor = new FilteredUltrasonicSensor(SensorPort.S1); // HELPER THREADS Odometer odometer = new Odometer(leftMotor, rightMotor, lightSensor); Navigation navigation = new Navigation(leftMotor, rightMotor, odometer); // CONTROLLERS LocalizationController localization = new LocalizationController(navigation, null, ultrasonicSensor); // LOGIC odometer.start(); navigation.start(); Button.waitForAnyPress(); // logic for presentation vid // TODO: use claw correctly // TODO: do quick callibration so navig works (Odometer WHEEL_RADIUS and WHEEL_DISTANCE) clawMotor.rotate(180); navigation.forward(60); navigation.waitUntilDone(); clawMotor.rotate(-180); navigation.forward(-60); navigation.waitUntilDone(); } }
Create instance of TwitterApi in constructor
<?php namespace Twitter; use TwitterOAuth\TwitterOAuth as TwitterApi; class LatestTweets { /** * * @var TwitterApi */ private $api; /** * * @param array $apiConfig */ public function __construct(array $apiConfig) { $this->api = new TwitterApi($apiConfig); } public function getLatestTweet($username) { $tweets = $this->getTweets($username, 1); return isset($tweets[0]) ? $tweets[0] : null; } public function getTweets($username, $howMany) { $tweets = $this->api->get('statuses/user_timeline', array( 'screen_name' => $username, 'exclude_replies' => 'true', 'include_rts' => 'false', 'count' => $howMany )); array_walk($tweets, function(&$tweet) { $tweet = new Tweet( (array) $tweet); }); return $tweets; } }
<?php namespace Twitter; use TwitterOAuth\TwitterOAuth as TwitterApi; class LatestTweets { /** * * @var TwitterApi */ private $api; /** * * @param string $apiKey * @param string $apiSecret */ public function __construct(TwitterApi $api) { $this->api = $api; } public function getLatestTweet($username) { $tweets = $this->getTweets($username, 1); return isset($tweets[0]) ? $tweets[0] : null; } public function getTweets($username, $howMany) { $tweets = $this->api->get('statuses/user_timeline', array( 'screen_name' => $username, 'exclude_replies' => 'true', 'include_rts' => 'false', 'count' => $howMany )); array_walk($tweets, function(&$tweet) { $tweet = new Tweet( (array) $tweet); }); return $tweets; } }
Revert "make test output a litte more intuitive" This reverts commit e09fa453b1bb72f08053d13cc3050012a20ba724.
from django.utils.unittest.case import TestCase from casexml.apps.case.tests import check_xml_line_by_line from corehq.apps.app_manager.models import Application from corehq.apps.app_manager.tests.util import TestFileMixin # snippet from http://stackoverflow.com/questions/321795/comparing-xml-in-a-unit-test-in-python/7060342#7060342 from doctest import Example from lxml.doctestcompare import LXMLOutputChecker class XmlTest(TestCase): def assertXmlEqual(self, want, got): checker = LXMLOutputChecker() if not checker.check_output(want, got, 0): message = checker.output_difference(Example("", want), got, 0) raise AssertionError(message) # end snippet class SuiteTest(XmlTest, TestFileMixin): file_path = ('data', 'suite') def setUp(self): self.app = Application.wrap(self.get_json('app')) def test_normal_suite(self): self.assertXmlEqual(self.get_xml('normal-suite'), self.app.create_suite())
from django.utils.unittest.case import TestCase from corehq.apps.app_manager.models import Application from corehq.apps.app_manager.tests.util import TestFileMixin # snippet from http://stackoverflow.com/questions/321795/comparing-xml-in-a-unit-test-in-python/7060342#7060342 from doctest import Example from lxml.doctestcompare import LXMLOutputChecker class XmlTest(TestCase): def assertXmlEqual(self, want, got): checker = LXMLOutputChecker() if not checker.check_output(want, got, 0): message = checker.output_difference(Example("", want), got, 0) raise AssertionError(message) # end snippet class SuiteTest(XmlTest, TestFileMixin): file_path = ('data', 'suite') def setUp(self): self.app = Application.wrap(self.get_json('app')) def test_normal_suite(self): self.assertXmlEqual(self.app.create_suite(), self.get_xml('normal-suite'))
Tweak a method name in tests
<?php namespace Phive\TaskQueue\Tests; use Phive\TaskQueue\SimpleSerializer; class SimpleSerializerTest extends \PHPUnit_Framework_TestCase { /** * @var SimpleSerializer */ protected $serializer; protected function setUp() { $this->serializer = new SimpleSerializer(); } /** * @dataProvider provideDataToSerialize */ public function testSerialization($raw) { $serialized = $this->serializer->serialize($raw); $this->assertInternalType('string', $serialized); $this->assertEquals($raw, $this->serializer->deserialize($serialized)); } public function provideDataToSerialize() { return [ [null], [false], [0], ['foo bar'], [new \stdClass()], [[null, false, 0, 'foo bar', new \stdClass(), []]], ]; } }
<?php namespace Phive\TaskQueue\Tests; use Phive\TaskQueue\SimpleSerializer; class SimpleSerializerTest extends \PHPUnit_Framework_TestCase { /** * @var SimpleSerializer */ protected $serializer; protected function setUp() { $this->serializer = new SimpleSerializer(); } /** * @dataProvider providerDataToSerialize */ public function testSerialization($raw) { $serialized = $this->serializer->serialize($raw); $this->assertInternalType('string', $serialized); $this->assertEquals($raw, $this->serializer->deserialize($serialized)); } public function providerDataToSerialize() { return [ [null], [false], [0], ['foo bar'], [new \stdClass()], [[null, false, 0, 'foo bar', new \stdClass(), []]], ]; } }
Improve WSGI file for apache deployment/database configuration management
""" WSGI config for cellcounter project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import site from distutils.sysconfig import get_python_lib #ensure the venv is being loaded correctly site.addsitedir(get_python_lib()) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cellcounter.settings") #import the DATABASE_URL from an Apache environment variable #this allows per-vhost database configuration to be passed in import django.core.handlers.wsgi _application = django.core.handlers.wsgi.WSGIHandler() def application(environ, start_response): os.environ['DATABASE_URL'] = environ['DATABASE_URL'] return _application(environ, start_response) # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
""" WSGI config for cellcounter project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cellcounter.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Add NO-OP for pong messages (to handle unsolicited pongs) git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1425646 13f79535-47bb-0310-9956-ffa450edef68
/* * 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 websocket.echo; import java.nio.ByteBuffer; import javax.websocket.PongMessage; import javax.websocket.WebSocketMessage; import javax.websocket.server.WebSocketEndpoint; @WebSocketEndpoint("/websocket/echoAnnotation") public class EchoAnnotation { @WebSocketMessage public String echoTextMessage(String msg) { return msg; } @WebSocketMessage public ByteBuffer echoBinaryMessage(ByteBuffer bb) { return bb; } /** * Process a received pong. This is a NO-OP. * * @param pm Ignored. */ @WebSocketMessage public void echoPongMessage(PongMessage pm) { // NO-OP } }
/* * 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 websocket.echo; import java.nio.ByteBuffer; import javax.websocket.WebSocketMessage; import javax.websocket.server.WebSocketEndpoint; @WebSocketEndpoint("/websocket/echoAnnotation") public class EchoAnnotation { @WebSocketMessage public String echoTextMessage(String msg) { return msg; } @WebSocketMessage public ByteBuffer echoBinaryMessage(ByteBuffer bb) { return bb; } }
Increment number for bug release
<?php // Can be used by plugins/themes to check if Terminus is running or not define( 'Terminus', true ); define( 'TERMINUS_VERSION', '0.3.1-beta' ); date_default_timezone_set('UTC'); include TERMINUS_ROOT . '/php/utils.php'; include TERMINUS_ROOT . '/php/login.php'; include TERMINUS_ROOT . '/php/FileCache.php'; include TERMINUS_ROOT . '/php/dispatcher.php'; include TERMINUS_ROOT . '/php/class-terminus.php'; include TERMINUS_ROOT . '/php/class-terminus-command.php'; \Terminus\Utils\load_dependencies(); # Set a custom exception handler set_exception_handler('\Terminus\Utils\handle_exception'); if (isset($_SERVER['TERMINUS_HOST']) && $_SERVER['TERMINUS_HOST'] != '') { define( 'TERMINUS_HOST', $_SERVER['TERMINUS_HOST'] ); \cli\line(\cli\Colors::colorize('%YNote: using custom target "'. $_SERVER['TERMINUS_HOST'] .'"%n')); } else { define( 'TERMINUS_HOST', 'dashboard.getpantheon.com' ); } define( 'TERMINUS_PORT', '443' ); Terminus::get_runner()->run();
<?php // Can be used by plugins/themes to check if Terminus is running or not define( 'Terminus', true ); define( 'TERMINUS_VERSION', '0.3.0-beta' ); date_default_timezone_set('UTC'); include TERMINUS_ROOT . '/php/utils.php'; include TERMINUS_ROOT . '/php/login.php'; include TERMINUS_ROOT . '/php/FileCache.php'; include TERMINUS_ROOT . '/php/dispatcher.php'; include TERMINUS_ROOT . '/php/class-terminus.php'; include TERMINUS_ROOT . '/php/class-terminus-command.php'; \Terminus\Utils\load_dependencies(); # Set a custom exception handler set_exception_handler('\Terminus\Utils\handle_exception'); if (isset($_SERVER['TERMINUS_HOST']) && $_SERVER['TERMINUS_HOST'] != '') { define( 'TERMINUS_HOST', $_SERVER['TERMINUS_HOST'] ); \cli\line(\cli\Colors::colorize('%YNote: using custom target "'. $_SERVER['TERMINUS_HOST'] .'"%n')); } else { define( 'TERMINUS_HOST', 'dashboard.getpantheon.com' ); } define( 'TERMINUS_PORT', '443' ); Terminus::get_runner()->run();
Declare queues when broker is instantiated
""" sentry.queue.client ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from kombu import BrokerConnection from kombu.common import maybe_declare from kombu.pools import producers from sentry.conf import settings from sentry.queue.queues import task_queues, task_exchange class Broker(object): def __init__(self, config): self.connection = BrokerConnection(**config) with producers[self.connection].acquire(block=False) as producer: for queue in task_queues: maybe_declare(queue, producer.channel) def delay(self, func, *args, **kwargs): payload = { "func": func, "args": args, "kwargs": kwargs, } with producers[self.connection].acquire(block=False) as producer: producer.publish(payload, exchange=task_exchange, serializer="pickle", compression="bzip2", queue='default', routing_key='default', ) broker = Broker(settings.QUEUE)
""" sentry.queue.client ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from kombu import BrokerConnection from kombu.common import maybe_declare from kombu.pools import producers from sentry.conf import settings from sentry.queue.queues import task_queues, task_exchange class Broker(object): def __init__(self, config): self.connection = BrokerConnection(**config) def delay(self, func, *args, **kwargs): payload = { "func": func, "args": args, "kwargs": kwargs, } with producers[self.connection].acquire(block=False) as producer: for queue in task_queues: maybe_declare(queue, producer.channel) producer.publish(payload, exchange=task_exchange, serializer="pickle", compression="bzip2", queue='default', routing_key='default', ) broker = Broker(settings.QUEUE)
Use expanduser instead of env
# coding=utf-8 import re import os import sys # Regex for matching URLs # See https://mathiasbynens.be/demo/url-regex url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)") ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE) INPUT_FILE = os.path.join(os.path.expanduser('~'), '.cache', 'ulp', 'links') def escape_ansi(text): return ansi_escape_regex.sub("", text) def parse_stdin(): lines = [line.strip() for line in sys.stdin] print(os.linesep.join(lines).strip(), file=sys.stderr) return parse_input(os.linesep.join(lines)) def parse_input(text): matches = url_regex.findall(escape_ansi(text.strip())) return [result[0] for result in matches] def read_inputfile(): with open(INPUT_FILE) as f: return [l.strip() for l in f.readlines()] def main(): #If we are not being piped, exit if sys.stdin.isatty(): sys.exit(1) result = parse_stdin() for url in result: print(url) if __name__ == '__main__': main()
# coding=utf-8 import re import os import sys # Regex for matching URLs # See https://mathiasbynens.be/demo/url-regex url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)") ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE) INPUT_FILE = os.path.join(os.getenv('HOME'), '.cache', 'ulp', 'links') def escape_ansi(text): return ansi_escape_regex.sub("", text) def parse_stdin(): lines = [line.strip() for line in sys.stdin] print(os.linesep.join(lines).strip(), file=sys.stderr) return parse_input(os.linesep.join(lines)) def parse_input(text): matches = url_regex.findall(escape_ansi(text.strip())) return [result[0] for result in matches] def read_inputfile(): with open(INPUT_FILE) as f: return [l.strip() for l in f.readlines()] def main(): #If we are not being piped, exit if sys.stdin.isatty(): sys.exit(1) result = parse_stdin() for url in result: print(url) if __name__ == '__main__': main()
Fix small mistake; options is a argument, not a member.
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals # Import the fastest implementation of # pickle package. This should be removed # when python3 come the unique supported # python version try: import cPickle as pickle except ImportError: import pickle from django.core.exceptions import ImproperlyConfigured try: from django.utils.encoding import force_bytes from django.utils.encoding import force_text except ImportError: from django.utils.encoding import smart_bytes as force_bytes from django.utils.encoding import force_unicode as force_text from .base import BaseSerializer class PickleSerializer(BaseSerializer): def __init__(self, options): self._pickle_version = -1 self.setup_pickle_version(options) def setup_pickle_version(self, options): if "PICKLE_VERSION" in options: try: self._pickle_version = int(options["PICKLE_VERSION"]) except (ValueError, TypeError): raise ImproperlyConfigured("PICKLE_VERSION value must be an integer") def dumps(self, value): return pickle.dumps(value, self._pickle_version) def loads(self, value): return pickle.loads(force_bytes(value))
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals # Import the fastest implementation of # pickle package. This should be removed # when python3 come the unique supported # python version try: import cPickle as pickle except ImportError: import pickle from django.core.exceptions import ImproperlyConfigured try: from django.utils.encoding import force_bytes from django.utils.encoding import force_text except ImportError: from django.utils.encoding import smart_bytes as force_bytes from django.utils.encoding import force_unicode as force_text from .base import BaseSerializer class PickleSerializer(BaseSerializer): def __init__(self, options): self._pickle_version = -1 self.setup_pickle_version(options) def setup_pickle_version(self, options): if "PICKLE_VERSION" in options: try: self._pickle_version = int(self._options["PICKLE_VERSION"]) except (ValueError, TypeError): raise ImproperlyConfigured("PICKLE_VERSION value must be an integer") def dumps(self, value): return pickle.dumps(value, self._pickle_version) def loads(self, value): return pickle.loads(force_bytes(value))
Clean up the account security context
package io.paradoxical.cassieq.discoverable.auth; import io.dropwizard.auth.Authorizer; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.SecurityContext; import java.security.Principal; public class AccountSecurityContext<P extends Principal> implements SecurityContext { private final P principal; private final Authorizer<P> authorizer; private final SecurityContext previousContext; public AccountSecurityContext( final P principal, final Authorizer<P> authorizer, final SecurityContext previousContext) { this.principal = principal; this.authorizer = authorizer; this.previousContext = previousContext; } @Override public Principal getUserPrincipal() { return principal; } @Override public boolean isUserInRole(String role) { return authorizer.authorize(principal, role); } @Override public boolean isSecure() { return previousContext.isSecure(); } @Override public String getAuthenticationScheme() { return "Signed"; } }
package io.paradoxical.cassieq.discoverable.auth; import io.dropwizard.auth.Authorizer; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.SecurityContext; import java.security.Principal; public class AccountSecurityContext<P extends Principal> implements SecurityContext { private final P principal; private final Authorizer<P> authorizer; private final ContainerRequestContext requestContext; public AccountSecurityContext( final P principal, Authorizer<P> authorizer, ContainerRequestContext requestContext) { this.principal = principal; this.authorizer = authorizer; this.requestContext = requestContext; } @Override public Principal getUserPrincipal() { return principal; } @Override public boolean isUserInRole(String role) { return authorizer.authorize(principal, role); } @Override public boolean isSecure() { return true; } @Override public String getAuthenticationScheme() { return "Signed"; } }
Fix the doc for bootstrap 3
@extends('layout') @section('title')Documentation @stop @section('content') <header> <h1>{{ Config::get('docs.title', 'Documentation') }}</h1> </header> <div class="row"> <div class="col-md-3"> {{ $index }} </div> <div class="col-md-9"> {{ $chapter }} <nav> @if($prev) <a href="{{ $prev['URI'] }}" title="Previous: {{ $prev['title'] }}">← {{ $prev['title'] }}</a> | @endif @if($next) <a href="{{ $next['URI'] }}" title="Next: {{ $next['title'] }}">{{ $next['title'] }} →</a> @endif </nav> </div> </div> <div class="clearfix"></div> @stop
@extends('layout') @section('title')Documentation @stop @section('content') <div class="wrapper"> <header> <h1>{{ Config::get('docs.title', 'Documentation') }}</h1> </header> <div class="row"> <div class="span3"> {{ $index }} </div> <div class="span9"> {{ $chapter }} <nav> @if($prev) <a href="{{ $prev['URI'] }}" title="Previous: {{ $prev['title'] }}">← {{ $prev['title'] }}</a> | @endif @if($next) <a href="{{ $next['URI'] }}" title="Next: {{ $next['title'] }}">{{ $next['title'] }} →</a> @endif </nav> </div> </div> <div class="clearfix"></div> </div> @stop
Sort the months in archive_templatetag
"""Templatetags for djangopress.""" from datetime import date from collections import defaultdict from django import template from djangopress.models import Post, Category register = template.Library() @register.inclusion_tag('djangopress/tags/archive_list.html') def archive_list(): """List post by date""" posts = Post.objects.all() years_dictionary = defaultdict(set) for post in posts: year = post.creation_date.year month = post.creation_date.month years_dictionary[year].add(month) years = {} for year, months in years_dictionary.items(): year = str(year) years[year] = [] for month in months: years[year].append(date(int(year), month, 1)) for year in years: years[year].sort(reverse=True) return {'years': years} @register.inclusion_tag('djangopress/tags/category_list.html') def category_list(): """List the categories in the blog.""" categories = Category.objects.all() return {'categories': categories}
"""Templatetags for djangopress.""" from datetime import date from collections import defaultdict from django import template from djangopress.models import Post, Category register = template.Library() @register.inclusion_tag('djangopress/tags/archive_list.html') def archive_list(): """List post by date""" posts = Post.objects.all() years_dictionary = defaultdict(set) for post in posts: year = post.creation_date.year month = post.creation_date.month years_dictionary[year].add(month) years = {} for year, months in years_dictionary.items(): year = str(year) years[year] = [] for month in months: years[year].append(date(int(year), month, 1)) return {'years': years} @register.inclusion_tag('djangopress/tags/category_list.html') def category_list(): """List the categories in the blog.""" categories = Category.objects.all() return {'categories': categories}
Make sure v1alpha1.Condition satisfy webhook.GenericCRD ⚙ This makes Condition consistent with the rest of the CRDs defined by tektoncd/pipeline. Signed-off-by: Vincent Demeester <b98c0fd48a8945096c766de790fe70420dd2f223@redhat.com>
/* Copyright 2019 The Tekton Authors 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 v1alpha1_test import ( "testing" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "knative.dev/pkg/webhook" ) func TestTypes(t *testing.T) { // Assert that types satisfy webhook interface. var _ webhook.GenericCRD = (*v1alpha1.ClusterTask)(nil) var _ webhook.GenericCRD = (*v1alpha1.TaskRun)(nil) var _ webhook.GenericCRD = (*v1alpha1.PipelineResource)(nil) var _ webhook.GenericCRD = (*v1alpha1.Task)(nil) var _ webhook.GenericCRD = (*v1alpha1.TaskRun)(nil) var _ webhook.GenericCRD = (*v1alpha1.Condition)(nil) }
/* Copyright 2019 The Tekton Authors 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 v1alpha1_test import ( "testing" "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1" "knative.dev/pkg/webhook" ) func TestTypes(t *testing.T) { // Assert that types satisfy webhook interface. var _ webhook.GenericCRD = (*v1alpha1.ClusterTask)(nil) var _ webhook.GenericCRD = (*v1alpha1.TaskRun)(nil) var _ webhook.GenericCRD = (*v1alpha1.PipelineResource)(nil) var _ webhook.GenericCRD = (*v1alpha1.Task)(nil) var _ webhook.GenericCRD = (*v1alpha1.TaskRun)(nil) }
Add stack trace to api errors
<?php declare(strict_types=1); /*. require_module 'standard'; require_module 'json'; .*/ namespace App\Handler; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; final class ApiError extends \Slim\Handlers\Error { public function __invoke(Request $request, Response $response, \Exception $exception) { $statusCode = 500; if (is_int($exception->getCode()) && $exception->getCode() !== 0 && $exception->getCode() < 599) { $statusCode = $exception->getCode(); } $className = new \ReflectionClass(get_class($exception)); $data = [ 'message' => $exception->getMessage(), 'status' => $className->getShortName(), 'code' => $statusCode, 'type' => 'error', 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => $exception->getTraceAsString(), ]; $body = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); error_log($body); return $response->withStatus($statusCode)->withHeader('Content-type', 'application/problem+json')->write($body); } /* End ApiError Class */ }
<?php declare(strict_types=1); /*. require_module 'standard'; require_module 'json'; .*/ namespace App\Handler; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; final class ApiError extends \Slim\Handlers\Error { public function __invoke(Request $request, Response $response, \Exception $exception) { $statusCode = 500; if (is_int($exception->getCode()) && $exception->getCode() !== 0 && $exception->getCode() < 599) { $statusCode = $exception->getCode(); } $className = new \ReflectionClass(get_class($exception)); $data = [ 'message' => $exception->getMessage(), 'status' => $className->getShortName(), 'code' => $statusCode, 'type' => 'error', 'file' => $exception->getFile(), 'line' => $exception->getLine() ]; $body = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); error_log($body); return $response->withStatus($statusCode)->withHeader('Content-type', 'application/problem+json')->write($body); } /* End ApiError Class */ }
Put back changes in observer after unsuccessful commit.
/** * Topic observer pattern base class */ export class TopicObserver { constructor() { this.observers = { __all__: [] }; } observe(fn, topic) { // default is all topic = topic || '__all__'; // create topic if needed if (!this.observers.hasOwnProperty(topic)) this.observers[topic] = []; this.observers[topic].push(fn); } remove(fn, topic) { // default is all topic = topic || '__all__'; this.observers[topic] = this.observers[topic].filter((subscriber) => subscriber !== fn); } broadcast(data, topic) { // default is all topic = topic || '__all__'; // is that a particular topic? if (topic !== '__all__') this.observers[topic].forEach((subscriber) => subscriber(data)); // broadcast for all this.observers['__all__'].forEach((subscriber) => subscriber(data)); } }
/** * Topic observer pattern base class */ export class TopicObserver { constructor() { this.observers = { __all__: [] }; } observe(fn, topic) { // default is all topic = topic || '__all__'; // create topic if needed if (!this.observers.hasOwnProperty(topic)) this.observers[topic] = []; this.observers[topic].push(fn); } remove(fn, topic) { // default is all topic = topic || '__all__'; this.observers = this.observers[topic].filter((subscriber) => subscriber !== fn); } broadcast(data, topic) { // default is all topic = topic || '__all__'; // is that a particular topic? if (topic !== '__all__') this.observers[topic].forEach((subscriber) => subscriber(data)); // broadcast for all this.observers['__all__'].forEach((subscriber) => subscriber(data)); } }
Add test for aligning too long strings
var buster = require("buster"); var assert = buster.assert; var a = require("../../lib/buster-terminal").align; buster.testCase("Terminal string align test", { "max width": { "should get width of array of strings": function () { assert.equals(a.maxWidth(["a", "b", "hey", "there"]), 5); }, "should get width of array of strings and numbers": function () { assert.equals(a.maxWidth(["a", 666782, 2, "there"]), 6); }, "should count width of undefined as 0": function () { assert.equals(a.maxWidth([null, undefined, false, ""]), 5); } }, "alignment": { "should left align text": function () { assert.equals(a.alignLeft("Hey there", 13), "Hey there "); }, "should right align text": function () { assert.equals(a.alignRight("Hey there", 13), " Hey there"); }, "should not pad too long text": function () { assert.equals(a.alignRight("Hey there", 4), "Hey there"); } } });
var buster = require("buster"); var assert = buster.assert; var a = require("../../lib/buster-terminal").align; buster.testCase("Terminal string align test", { "max width": { "should get width of array of strings": function () { assert.equals(a.maxWidth(["a", "b", "hey", "there"]), 5); }, "should get width of array of strings and numbers": function () { assert.equals(a.maxWidth(["a", 666782, 2, "there"]), 6); }, "should count width of undefined as 0": function () { assert.equals(a.maxWidth([null, undefined, false, ""]), 5); } }, "alignment": { "should left align text": function () { assert.equals(a.alignLeft("Hey there", 13), "Hey there "); }, "should right align text": function () { assert.equals(a.alignRight("Hey there", 13), " Hey there"); } } });
Update exception syntax to be py3 compat
import os import subprocess try: VERSION = __import__('pkg_resources') \ .get_distribution('changes').version except Exception: VERSION = 'unknown' def _get_git_revision(path): try: r = subprocess.check_output('git rev-parse HEAD', cwd=path, shell=True) except Exception: return None return r.strip() def get_revision(): """ :returns: Revision number of this branch/checkout, if available. None if no revision number can be determined. """ package_dir = os.path.dirname(__file__) checkout_dir = os.path.normpath(os.path.join(package_dir, os.pardir)) path = os.path.join(checkout_dir, '.git') if os.path.exists(path): return _get_git_revision(path) return None def get_version(): base = VERSION if __build__: base = '%s (%s)' % (base, __build__) return base __build__ = get_revision() __docformat__ = 'restructuredtext en'
import os import subprocess try: VERSION = __import__('pkg_resources') \ .get_distribution('changes').version except Exception, e: VERSION = 'unknown' def _get_git_revision(path): try: r = subprocess.check_output('git rev-parse HEAD', cwd=path, shell=True) except Exception: return None return r.strip() def get_revision(): """ :returns: Revision number of this branch/checkout, if available. None if no revision number can be determined. """ package_dir = os.path.dirname(__file__) checkout_dir = os.path.normpath(os.path.join(package_dir, os.pardir)) path = os.path.join(checkout_dir, '.git') if os.path.exists(path): return _get_git_revision(path) return None def get_version(): base = VERSION if __build__: base = '%s (%s)' % (base, __build__) return base __build__ = get_revision() __docformat__ = 'restructuredtext en'
[TASK] Add missing method to the PairRepository
<?php namespace DreadLabs\VantomasWebsite\SecretSanta\Pair; use DreadLabs\VantomasWebsite\SecretSanta\Donee\DoneeInterface; use DreadLabs\VantomasWebsite\SecretSanta\Donor\DonorInterface; interface RepositoryInterface { /** * Finds a pair for the given donor * * @param DonorInterface $donor * @return PairInterface */ public function findPairFor(DonorInterface $donor); /** * Determines if the given donor/donee pair is mutual * * @param DonorInterface $donor * @param DoneeInterface $donee * @return bool */ public function isPairMutually(DonorInterface $donor, DoneeInterface $donee); /** * Flags if the incoming donor / donee pair is already existing * * @param DonorInterface $donor * @param DoneeInterface $donee * @return bool */ public function isPairExisting(DonorInterface $donor, DoneeInterface $donee); /** * @param PairInterface $pair * @return void */ public function add(PairInterface $pair); }
<?php namespace DreadLabs\VantomasWebsite\SecretSanta\Pair; use DreadLabs\VantomasWebsite\SecretSanta\Donee\DoneeInterface; use DreadLabs\VantomasWebsite\SecretSanta\Donor\DonorInterface; interface RepositoryInterface { /** * Finds a pair for the given donor * * @param DonorInterface $donor * @return PairInterface */ public function findPairFor(DonorInterface $donor); /** * Determines if the given donor/donee pair is mutual * * @param DonorInterface $donor * @param DoneeInterface $donee * @return bool */ public function isPairMutually(DonorInterface $donor, DoneeInterface $donee); /** * @param PairInterface $pair * @return void */ public function add(PairInterface $pair); }
Stop the event chain when we have handled the event.
goog.provide('ol.control.Navigation'); goog.require('ol.control.Control'); /** * @constructor * @extends {ol.control.Control} * @param {boolean|undefined} opt_autoActivate */ ol.control.Navigation = function(opt_autoActivate) { goog.base(this, opt_autoActivate); /** * Activate this control when it is added to a map. Default is true. * * @type {boolean} autoActivate */ this.autoActivate_ = goog.isDef(opt_autoActivate) ? opt_autoActivate : true; }; goog.inherits(ol.control.Navigation, ol.control.Control); /** @inheritDoc */ ol.control.Navigation.prototype.activate = function() { var active = goog.base(this, 'activate'); if (active) { this.getMap().getEvents().register("drag", this.moveMap, this); } return active; }; /** @inheritDoc */ ol.control.Navigation.prototype.deactivate = function() { var inactive = goog.base(this, 'deactivate'); if (inactive) { this.getMap().getEvents().unregister("drag", this.moveMap, this); } return inactive; }; /** * @param {ol.event.DragEvent} evt */ ol.control.Navigation.prototype.moveMap = function(evt) { this.getMap().moveByPx(evt.dx, evt.dy); return false; }; ol.control.addControl('navigation', ol.control.Navigation);
goog.provide('ol.control.Navigation'); goog.require('ol.control.Control'); /** * @constructor * @extends {ol.control.Control} * @param {boolean|undefined} opt_autoActivate */ ol.control.Navigation = function(opt_autoActivate) { goog.base(this, opt_autoActivate); /** * Activate this control when it is added to a map. Default is true. * * @type {boolean} autoActivate */ this.autoActivate_ = goog.isDef(opt_autoActivate) ? opt_autoActivate : true; }; goog.inherits(ol.control.Navigation, ol.control.Control); /** @inheritDoc */ ol.control.Navigation.prototype.activate = function() { var active = goog.base(this, 'activate'); if (active) { this.getMap().getEvents().register("drag", this.moveMap, this); } return active; }; /** @inheritDoc */ ol.control.Navigation.prototype.deactivate = function() { var inactive = goog.base(this, 'deactivate'); if (inactive) { this.getMap().getEvents().unregister("drag", this.moveMap, this); } return inactive; }; /** * @param {ol.event.DragEvent} evt */ ol.control.Navigation.prototype.moveMap = function(evt) { this.getMap().moveByPx(evt.dx, evt.dy); }; ol.control.addControl('navigation', ol.control.Navigation);
Fix browser history app launch
'use strict' const AppBase = require(global.upath.joinSafe(__dirname, 'AppBase')) const defaultWrapper = { name: '', text: '', exec: 'browserHistory', icon: 'link.png', type: '_internal_' } class BrowserHistory extends AppBase { constructor(options) { super(defaultWrapper, options) // super.setup() } exec( ex, query ) { // Unwrap object, link is on subtext let q = ex.text let reg = /((http|ftp|https)\:\/\/)(www\.)?|(www\.)([^\.]*)/i if( !reg.test( q ) ){ // Lack starting www.... q = 'http://' + q; } global.app.utils.spawn( 'xdg-open', [q] ) } match(query) { // Never match, searched apart return null } } module.exports = BrowserHistory
'use strict' const AppBase = require(global.upath.joinSafe(__dirname, 'AppBase')) const defaultWrapper = { name: '', text: '', exec: 'browserHistory', icon: 'link.png', type: '_internal_' } class BrowserHistory extends AppBase { constructor(options) { super(defaultWrapper, options) // super.setup() } exec( ex, query ) { // Unwrap object, link is on subtext let q = exec.text let reg = /((http|ftp|https)\:\/\/)(www\.)?|(www\.)([^\.]*)/i if( !reg.test( q ) ){ // Lack starting www.... q = 'http://' + q; } global.app.utils.spawn( 'xdg-open', [q] ) } match(query) { // Never match, searched apart return null } } module.exports = BrowserHistory
Return JSON in the autocomplete view
import json import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = [{ "name": unicodedata.normalize('NFKD', t.name), "county_name": t.county_name, "lon": t.point.coords[0], "lat": t.point.coords[1], } for t in towns] if not content: content = [{'name': _('No results. Search is limited to city names.')}] return HttpResponse(json.dumps(content), content_type='application/json')
import unicodedata from django.http import HttpResponse from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from .models import Town def autocomplete(request): if not 'q' in request.GET or len(request.GET['q']) < 3: response = HttpResponse() response.status_code = 204 return response query = slugify(request.GET['q']).replace('-', ' ').upper() if query.startswith('ST '): query = 'SAINT ' + query[3:] towns = Town.objects.filter( tokenized__startswith=query ).order_by('tokenized', 'postal_code')[:15] content = u'\n'.join([u'{name} <em>{county_name}</em>|{lon} {lat}'.format( name=unicodedata.normalize('NFKD', t.name), county_name=t.county_name, lon=t.point.coords[0], lat=t.point.coords[1], ) for t in towns]) if not content: content = _('No results. Search is limited to city names.') return HttpResponse(content)
Fix required file in ArrayController.
// ========================================================================== // Project: SproutCore Metal // Copyright: ©2011 Strobe Inc. and contributors. // License: Licensed under MIT license (see license.js) // ========================================================================== require('sproutcore-runtime/system/array_proxy'); /** @class SC.ArrayController provides a way for you to publish an array of objects for SC.CollectionView or other controllers to work with. To work with an ArrayController, set the content property to the array you want the controller to manage. Then work directly with the controller object as if it were the array itself. For example, imagine you wanted to display a list of items fetched via an XHR request. Create an SC.ArrayController and set its `content` property: MyApp.listController = SC.ArrayController.create(); $.get('people.json', function(data) { MyApp.listController.set('content', data); }); Then, create a view that binds to your new controller: {{collection contentBinding="MyApp.listController"}} {{content.firstName}} {{content.lastName}} {{/collection}} The advantage of using an array controller is that you only have to set up your view bindings once; to change what's displayed, simply swap out the `content` property on the controller. @extends SC.ArrayProxy */ SC.ArrayController = SC.ArrayProxy.extend();
// ========================================================================== // Project: SproutCore Metal // Copyright: ©2011 Strobe Inc. and contributors. // License: Licensed under MIT license (see license.js) // ========================================================================== /** @class SC.ArrayController provides a way for you to publish an array of objects for SC.CollectionView or other controllers to work with. To work with an ArrayController, set the content property to the array you want the controller to manage. Then work directly with the controller object as if it were the array itself. For example, imagine you wanted to display a list of items fetched via an XHR request. Create an SC.ArrayController and set its `content` property: MyApp.listController = SC.ArrayController.create(); $.get('people.json', function(data) { MyApp.listController.set('content', data); }); Then, create a view that binds to your new controller: {{collection contentBinding="MyApp.listController"}} {{content.firstName}} {{content.lastName}} {{/collection}} The advantage of using an array controller is that you only have to set up your view bindings once; to change what's displayed, simply swap out the `content` property on the controller. @extends SC.ArrayProxy */ SC.ArrayController = SC.ArrayProxy.extend();
Update GA tracking code to match subdomain
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Become a member - Cowork Niagara</title> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans"> <link rel="stylesheet" href="assets/vendor/normalize.css"> <link rel="stylesheet" href="assets/main.css"> </head> <body> <header> <div> <a href="http://coworkniagara.com"> <img src="assets/logo-horizontal.svg" height="60"> </a> </div> </header> <?= $body_content; ?> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-51684825-2', 'auto'); ga('send', 'pageview'); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Become a member - Cowork Niagara</title> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans"> <link rel="stylesheet" href="assets/vendor/normalize.css"> <link rel="stylesheet" href="assets/main.css"> </head> <body> <header> <div> <a href="http://coworkniagara.com"> <img src="assets/logo-horizontal.svg" height="60"> </a> </div> </header> <?= $body_content; ?> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-51684825-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
Exclude Fast test for Python 2
import unittest try: import spotpy except ImportError: import sys sys.path.append(".") import spotpy from spotpy.examples.spot_setup_hymod_python import spot_setup # Test only untder Python 3 as Python >2.7.10 results in a strange fft error if sys.version_info >= (3, 5): class TestFast(unittest.TestCase): def setUp(self): self.spot_setup = spot_setup() self.rep = 200 # REP must be a multiply of amount of parameters which are in 7 if using hymod self.timeout = 10 # Given in Seconds def test_fast(self): sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram", sim_timeout=self.timeout) results = [] sampler.sample(self.rep) results = sampler.getdata() self.assertEqual(203,len(results)) if __name__ == '__main__': unittest.main()
import unittest try: import spotpy except ImportError: import sys sys.path.append(".") import spotpy from spotpy.examples.spot_setup_hymod_python import spot_setup class TestFast(unittest.TestCase): def setUp(self): self.spot_setup = spot_setup() self.rep = 200 # REP must be a multiply of amount of parameters which are in 7 if using hymod self.timeout = 10 # Given in Seconds def test_fast(self): sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram", sim_timeout=self.timeout) results = [] sampler.sample(self.rep) results = sampler.getdata() self.assertEqual(203,len(results)) if __name__ == '__main__': unittest.main()
Convert GpuBenchmarkingExtension to a gin::Wrappable class v8 extensions are slowing down context creation and we're trying to get rid of them. BUG=334679 R=ernstm@chromium.org,nduca@chromium.org Review URL: https://codereview.chromium.org/647433003 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#300957}
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import benchmark from telemetry.unittest import tab_test_case class InspectorMemoryTest(tab_test_case.TabTestCase): @benchmark.Enabled('has tabs') @benchmark.Disabled # http://crbug.com/422244 def testGetDOMStats(self): # Due to an issue with CrOS, we create a new tab here rather than # using the existing tab to get a consistent starting page on all platforms. self._tab = self._browser.tabs.New() self.Navigate('dom_counter_sample.html') # Document_count > 1 indicates that WebCore::Document loaded in Chrome # is leaking! The baseline should exactly match the numbers on: # unittest_data/dom_counter_sample.html # Please contact kouhei@, hajimehoshi@ when rebaselining. counts = self._tab.dom_stats self.assertEqual(counts['document_count'], 1, 'Document leak is detected! '+ 'The previous document is likely retained unexpectedly.') self.assertEqual(counts['node_count'], 14, 'Node leak is detected!') self.assertEqual(counts['event_listener_count'], 2, 'EventListener leak is detected!')
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import benchmark from telemetry.unittest import tab_test_case class InspectorMemoryTest(tab_test_case.TabTestCase): @benchmark.Enabled('has tabs') def testGetDOMStats(self): # Due to an issue with CrOS, we create a new tab here rather than # using the existing tab to get a consistent starting page on all platforms. self._tab = self._browser.tabs.New() self.Navigate('dom_counter_sample.html') # Document_count > 1 indicates that WebCore::Document loaded in Chrome # is leaking! The baseline should exactly match the numbers on: # unittest_data/dom_counter_sample.html # Please contact kouhei@, hajimehoshi@ when rebaselining. counts = self._tab.dom_stats self.assertEqual(counts['document_count'], 1, 'Document leak is detected! '+ 'The previous document is likely retained unexpectedly.') self.assertEqual(counts['node_count'], 14, 'Node leak is detected!') self.assertEqual(counts['event_listener_count'], 2, 'EventListener leak is detected!')
Set defaut interval to 20 minutes New Heroku instances now rotate every 30 minutes instead of every hour
"use strict"; var request = require('request'); module.exports = function herokuSelfPing(url, options) { if(!options) { options = {}; } options.interval = options.interval || 20 * 1000 * 60; options.logger = options.logger || console.log; options.verbose = options.verbose || false; var isHeroku = require("is-heroku"); if(!url) { options.verbose && options.logger("heroku-self-ping: no url provided. Exiting."); return false; } if(!isHeroku) { options.verbose && options.logger("heroku-self-ping: heroku not detected. Exiting."); return false; } options.verbose && options.logger("heroku-self-ping: Setting up hearbeat to " + url + " every " + options.interval + "ms."); return setInterval(function() { options.logger("heroku-self-ping: Sending hearbeat to " + url); request(url, function () {}); }, options.interval); };
"use strict"; var request = require('request'); module.exports = function herokuSelfPing(url, options) { if(!options) { options = {}; } options.interval = options.interval || 45 * 1000 * 60; options.logger = options.logger || console.log; options.verbose = options.verbose || false; var isHeroku = require("is-heroku"); if(!url) { options.verbose && options.logger("heroku-self-ping: no url provided. Exiting."); return false; } if(!isHeroku) { options.verbose && options.logger("heroku-self-ping: heroku not detected. Exiting."); return false; } options.verbose && options.logger("heroku-self-ping: Setting up hearbeat to " + url + " every " + options.interval + "ms."); return setInterval(function() { options.logger("heroku-self-ping: Sending hearbeat to " + url); request(url, function () {}); }, options.interval); };
Fix output of permissions import script
#!/usr/bin/env python """Import permissions, roles, and their relations from a TOML file. :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ import click from byceps.services.authorization import impex_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.argument('data_file', type=click.File()) def execute(data_file): permission_count, role_count = impex_service.import_from_file(data_file) click.secho( f'Imported {permission_count} permissions and {role_count} roles.', fg='green', ) if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute()
#!/usr/bin/env python """Import permissions, roles, and their relations from a TOML file. :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ import click from byceps.services.authorization import impex_service from byceps.util.system import get_config_filename_from_env_or_exit from _util import app_context @click.command() @click.argument('data_file', type=click.File()) def execute(data_file): permission_count, role_count = impex_service.import_from_file(data_file) click.secho( 'Imported {permission_count} permissions and {role_count} roles.', fg='green', ) if __name__ == '__main__': config_filename = get_config_filename_from_env_or_exit() with app_context(config_filename): execute()
Change default port for influxdb to 8186
<?php namespace Vorbind\InfluxAnalytics; use InfluxDB\Client; use InfluxDB\Database; /** * Analytics * * Use this section to define what this class is doing, the PHPDocumentator will use this * to automatically generate an API documentation using this information. * * @author sasa.rajkovic */ class Connection { private $db; private $client; private $host; private $port; public function __construct($host = 'localhost', $port = '8186') { $this->host = $host; $this->port = $port; } public function getDatabase($name) { if (!isset($name)) { throw InvalidArgumentException::invalidType('"db name" driver option', $name, 'string'); } if (null == $this->client) { $this->client = new \InfluxDB\Client($this->host, $this->port); } if (!isset($this->dbs[$name])) { $this->dbs[$name] = $this->client->selectDB($name); } return $this->dbs[$name]; } }
<?php namespace Vorbind\InfluxAnalytics; use InfluxDB\Client; use InfluxDB\Database; /** * Analytics * * Use this section to define what this class is doing, the PHPDocumentator will use this * to automatically generate an API documentation using this information. * * @author sasa.rajkovic */ class Connection { private $db; private $client; private $host; private $port; public function __construct($host = 'localhost', $port = '8186') { $this->host = $host; $this->port = $port; } public function getDatabase($name) { if (!isset($name)) { throw InvalidArgumentException::invalidType('"db name" driver option', $name, 'string'); } if (null == $this->client) { $this->client = new \InfluxDB\Client($this->host, $this->port); } if (!isset($this->dbs[$name])) { $this->dbs[$name] = $this->client->selectDB($name); } return $this->dbs[$name]; } }
Change the name of the verify/no-verify param
# -*- coding: utf-8 -*- """ """ from __future__ import print_function, division import ssl import warnings import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager from requests.packages.urllib3.exceptions import InsecureRequestWarning def get_transport(verify=True, use_tlsv1=True): transport = requests.Session() if not verify: warnings.filterwarnings("ignore", category=InsecureRequestWarning) transport.verify = False if use_tlsv1: transport.mount('https://', SSLTLSV1Adapter()) return transport class SSLTLSV1Adapter(HTTPAdapter): """"Transport adapter that allows us to use TLSv1 which is required for interacting with the A10 load balancer. """ def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs): self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1, **pool_kwargs)
# -*- coding: utf-8 -*- """ """ from __future__ import print_function, division import ssl import warnings import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager from requests.packages.urllib3.exceptions import InsecureRequestWarning def get_transport(disable_verify=False, use_tlsv1=True): transport = requests.Session() if disable_verify: warnings.filterwarnings("ignore", category=InsecureRequestWarning) transport.verify = False if use_tlsv1: transport.mount('https://', SSLTLSV1Adapter()) return transport class SSLTLSV1Adapter(HTTPAdapter): """"Transport adapter that allows us to use TLSv1 which is required for interacting with the A10 load balancer. """ def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs): self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1, **pool_kwargs)
Disable debug info for release.
angular.module('proxtop', ['ngMaterial', 'ngSanitize', 'ui.router', 'angular-progress-arc', 'pascalprecht.translate', 'debounce']) .config(['$stateProvider', '$urlRouterProvider', '$translateProvider', '$mdIconProvider', '$logProvider', '$compileProvider', function($stateProvider, $urlRouterProvider, $translateProvider, $mdIconProvider, $logProvider, $compileProvider) { $urlRouterProvider.otherwise('/'); $translateProvider.useStaticFilesLoader({ prefix: 'locale/locale-', suffix: '.json' }); $translateProvider.preferredLanguage('de'); $translateProvider.useSanitizeValueStrategy('escape'); $mdIconProvider.defaultIconSet('../bower_components/font-awesome/fonts/fontawesome-webfont.svg'); $logProvider.debugEnabled(false); $compileProvider.debugInfoEnabled(false); }]);
angular.module('proxtop', ['ngMaterial', 'ngSanitize', 'ui.router', 'angular-progress-arc', 'pascalprecht.translate', 'debounce']) .config(['$stateProvider', '$urlRouterProvider', '$translateProvider', '$mdIconProvider', '$logProvider', function($stateProvider, $urlRouterProvider, $translateProvider, $mdIconProvider, $logProvider) { $urlRouterProvider.otherwise('/'); $translateProvider.useStaticFilesLoader({ prefix: 'locale/locale-', suffix: '.json' }); $translateProvider.preferredLanguage('de'); $translateProvider.useSanitizeValueStrategy('escape'); $mdIconProvider.defaultIconSet('../bower_components/font-awesome/fonts/fontawesome-webfont.svg'); $logProvider.debugEnabled(false); }]);
Add version updater and server health messages
/* * Copyright 2018 ThoughtWorks, 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. */ const $ = require('jquery'); const m = require('mithril'); const ArtifactStoresWidget = require('views/artifact_stores/artifact_stores_widget'); const VersionUpdater = require('models/shared/version_updater'); require('helpers/server_health_messages_helper'); require('foundation-sites'); $(() => { $(document).foundation(); new VersionUpdater().update(); m.mount($("#artifact-stores").get(0), ArtifactStoresWidget); });
/* * Copyright 2018 ThoughtWorks, 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. */ const $ = require('jquery'); const m = require('mithril'); const ArtifactStoresWidget = require('views/artifact_stores/artifact_stores_widget'); require('foundation-sites'); $(() => { $(document).foundation(); m.mount($("#artifact-stores").get(0), ArtifactStoresWidget); });
Remove redundant keyword argument from create_test_args
import os import yaml def read_file(path): with open(path) as f: return f.read() PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa") PVT_KEY = read_file(PVT_KEY_FILE) PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub")) OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "other_rsa.pub")) DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key") def create_test_args(non_standard_arguments): with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f: default_arguments = yaml.safe_load(f) default_arguments.update(non_standard_arguments) return default_arguments
import os import yaml def read_file(path): with open(path) as f: return f.read() PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa") PVT_KEY = read_file(PVT_KEY_FILE) PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub")) OTHER_PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "other_rsa.pub")) DUMMY_PUBLIC_KEY = os.path.join(os.path.dirname(__file__), "public.key") def create_test_args(non_standard_arguments, permitted_defaults=None): with open(os.path.join(os.path.dirname(__file__), 'test_graph_parameters.yml')) as f: default_arguments = yaml.safe_load(f) default_arguments.update(non_standard_arguments) if permitted_defaults is not None: default_arguments = { key: val for key, val in default_arguments.items() if key in non_standard_arguments or key in permitted_defaults } return default_arguments
Add getCountry method that gets country of apple music track
import { formatOpenURL, parse, } from 'spotify-uri'; export const getCountry = (urlString) => { const regex = /\/geo\.itunes\.apple\.com\/([a-zA-Z]+)\//; const results = urlString.match(regex); if (results.length >= 2) { return results[1]; } return 'us'; }; export const getOwnerUrl = (track) => { if (!track || !track.owner_id) { return null; } const ownerId = track.owner_id; switch (track.provider) { case 'YouTube': return `https://www.youtube.com/channel/${ownerId}`; case 'SoundCloud': return null; // Not support default: return null; } }; export const getUrl = (track) => { if (!track || !track.identifier) { return track.url; } const id = track.identifier; switch (track.provider) { case 'YouTube': return `https://www.youtube.com/watch/?v=${id}`; case 'SoundCloud': return `https://soundcloud.com/tracks/${id}`; case 'Spotify': return formatOpenURL(parse(track.url)); case 'AppleMusic': { const country = getCountry(track.url); return `http://tools.applemusic.com/embed/v1/song/${id}?country=${country}`; } default: return track.url; } };
import { formatOpenURL, parse, } from 'spotify-uri'; import { getCountryParam } from './Playlist'; export const getOwnerUrl = (track) => { if (!track || !track.owner_id) { return null; } const ownerId = track.owner_id; switch (track.provider) { case 'YouTube': return `https://www.youtube.com/channel/${ownerId}`; case 'SoundCloud': return null; // Not support default: return null; } }; export const getUrl = (track) => { if (!track || !track.identifier) { return track.url; } const id = track.identifier; switch (track.provider) { case 'YouTube': return `https://www.youtube.com/watch/?v=${id}`; case 'SoundCloud': return `https://soundcloud.com/tracks/${id}`; case 'Spotify': return formatOpenURL(parse(track.url)); case 'AppleMusic': { const country = getCountryParam(track.url); return `http://tools.applemusic.com/embed/v1/song/${id}?country=${country}`; } default: return track.url; } };
Replace HN newlines similar to t_t
var hn = require('hacker-news-api'); var ent = require('ent'); var qs = require('querystring'); var S = require('string'); var hnRegex = /^https?:\/\/news\.ycombinator\.com\/(.*)/; module.exports.url = function(url, reply) { var m; if((m = hnRegex.exec(url))) { if(m[1].indexOf('?') == -1) { return; //Don't handle naked links yet, only stories } var qsToParse = m[1].split('?'); var query = qs.parse(qsToParse[qsToParse.length - 1]); var id = parseInt(query.id, 10); if(typeof id !== 'number' || isNaN(id)) return; hn.item(id, function(err, res) { if(err) return reply("Unable to get HN store info"); if(res.type == 'story') { return reply("HackerNews - " + res.title + " - Posted by: " + res.author); //Todo, created-at info } else if(res.type == 'comment') { var toSay = res.author + " wrote: " + ent.decode(res.text); toSay = S(toSay).stripTags().replaceAll('\n',' | ').s; if(toSay.length < 500) return reply(toSay); } }); } };
var hn = require('hacker-news-api'); var ent = require('ent'); var qs = require('querystring'); var S = require('string'); var hnRegex = /^https?:\/\/news\.ycombinator\.com\/(.*)/; module.exports.url = function(url, reply) { var m; if((m = hnRegex.exec(url))) { if(m[1].indexOf('?') == -1) { return; //Don't handle naked links yet, only stories } var qsToParse = m[1].split('?'); var query = qs.parse(qsToParse[qsToParse.length - 1]); var id = parseInt(query.id, 10); if(typeof id !== 'number' || isNaN(id)) return; hn.item(id, function(err, res) { if(err) return reply("Unable to get HN store info"); if(res.type == 'story') { return reply("HackerNews - " + res.title + " - Posted by: " + res.author); //Todo, created-at info } else if(res.type == 'comment') { var toSay = res.author + " wrote: " + ent.decode(res.text); toSay = S(toSay).stripTags().s; if(toSay.length < 500) return reply(toSay); } }); } };
Use compatible(for Python2.6) format string.
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import Column, String from .db import Base, Session __all__ = ['Schema'] class Schema(Base): __tablename__ = 'schemas' # TODO: allow Only UUID? or user defined ID too? id = Column(String, primary_key=True) # TODO: JSON uniqueness is needed body = Column(String) # ID is generated in Python context(=in application) def __init__(self, id=None, body=None): self.id = id self.body = body def __repr__(self): return "<{0}: '{1}'>".format(self.__class__.__name__, self.body) # TODO: Use contextmanager. Ref. http://docs.sqlalchemy.org/en/rel_1_0/orm/session_basics.html def save(self): s = Session() s.add(self) try: # TODO: logger s.commit() except: s.rollback() # TODO: Error message raise RuntimeError('') finally: # TODO: logger s.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import Column, String from .db import Base, Session __all__ = ['Schema'] class Schema(Base): __tablename__ = 'schemas' # TODO: allow Only UUID? or user defined ID too? id = Column(String, primary_key=True) # TODO: JSON uniqueness is needed body = Column(String) # ID is generated in Python context(=in application) def __init__(self, id=None, body=None): self.id = id self.body = body def __repr__(self): return '<{!s}: {!r}>'.format(self.__class__.__name__, self.body) # TODO: Use contextmanager. Ref. http://docs.sqlalchemy.org/en/rel_1_0/orm/session_basics.html def save(self): s = Session() s.add(self) try: # TODO: logger s.commit() except: s.rollback() # TODO: Error message raise RuntimeError('') finally: # TODO: logger s.close()
Make sure data is an exact equal to undefined to treat it as nonexistent
'use strict'; class Keyv { constructor(opts) { this.opts = opts || {}; this.opts.store = this.opts.store || new Map(); } get(key) { const store = this.opts.store; return Promise.resolve(store.get(key)).then(data => { if (data === undefined) { return undefined; } if (!store.ttlSupport && Date.now() > data.expires) { this.delete(key); return undefined; } return store.ttlSupport ? data : data.value; }); } set(key, value, ttl) { ttl = ttl || this.opts.ttl; const store = this.opts.store; let set; if (store.ttlSupport) { set = store.set(key, value, ttl); } else { const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : undefined; const data = { value, expires }; set = store.set(key, data); } return Promise.resolve(set).then(() => value); } delete(key) { const store = this.opts.store; return Promise.resolve(store.delete(key)); } } module.exports = Keyv;
'use strict'; class Keyv { constructor(opts) { this.opts = opts || {}; this.opts.store = this.opts.store || new Map(); } get(key) { const store = this.opts.store; return Promise.resolve(store.get(key)).then(data => { if (!data) { return undefined; } if (!store.ttlSupport && Date.now() > data.expires) { this.delete(key); return undefined; } return store.ttlSupport ? data : data.value; }); } set(key, value, ttl) { ttl = ttl || this.opts.ttl; const store = this.opts.store; let set; if (store.ttlSupport) { set = store.set(key, value, ttl); } else { const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : undefined; const data = { value, expires }; set = store.set(key, data); } return Promise.resolve(set).then(() => value); } delete(key) { const store = this.opts.store; return Promise.resolve(store.delete(key)); } } module.exports = Keyv;
Change version and license for 0.2 git-svn-id: 150a648d6f30c8fc6b9d405c0558dface314bbdd@617 b426a367-1105-0410-b9ff-cdf4ab011145
from setuptools import setup setup(name = 'OWSLib', version = '0.2.0', description = 'OGC Web Service utility library', license = 'BSD', keywords = 'gis ogc ows wfs wms capabilities metadata', author = 'Sean Gillies', author_email = 'sgillies@frii.com', maintainer = 'Sean Gillies', maintainer_email = 'sgillies@frii.com', url = 'http://trac.gispython.org/projects/PCL/wiki/OwsLib', packages = ['owslib'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: GIS', ], )
from setuptools import setup setup(name = 'OWSLib', version = '0.1.0', description = 'OGC Web Service utility library', license = 'GPL', keywords = 'gis ogc ows wfs wms capabilities metadata', author = 'Sean Gillies', author_email = 'sgillies@frii.com', maintainer = 'Sean Gillies', maintainer_email = 'sgillies@frii.com', url = 'http://trac.gispython.org/projects/PCL/wiki/OwsLib', packages = ['owslib'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: GIS', ], )
Convert license detail to pytest
import pytest import functools from api.base.settings.defaults import API_BASE from osf.models.licenses import NodeLicense @pytest.mark.django_db class TestLicenseDetail: @pytest.fixture() def license(self): return NodeLicense.find()[0] @pytest.fixture() def url_license(self, license): return '/{}licenses/{}/'.format(API_BASE, license._id) @pytest.fixture() def res_license(self, app, url_license): return app.get(url_license) @pytest.fixture() def data_license(self, res_license): return res_license.json['data'] def test_license_detail(self, license, res_license, data_license): #test_license_detail_success(self, res_license): assert res_license.status_code == 200 assert res_license.content_type == 'application/vnd.api+json' #test_license_top_level(self, license, data_license): assert data_license['type'] == 'licenses' assert data_license['id'] == license._id #test_license_name(self, data_license, license): assert data_license['attributes']['name'] == license.name #test_license_text(self, data_license, license): assert data_license['attributes']['text'] == license.text
from nose.tools import * # flake8: noqa import functools from tests.base import ApiTestCase from osf.models.licenses import NodeLicense from api.base.settings.defaults import API_BASE class TestLicenseDetail(ApiTestCase): def setUp(self): super(TestLicenseDetail, self).setUp() self.license = NodeLicense.find()[0] self.url = '/{}licenses/{}/'.format(API_BASE, self.license._id) self.res = self.app.get(self.url) self.data = self.res.json['data'] def test_license_detail_success(self): assert_equal(self.res.status_code, 200) assert_equal(self.res.content_type, 'application/vnd.api+json') def test_license_top_level(self): assert_equal(self.data['type'], 'licenses') assert_equal(self.data['id'], self.license._id) def test_license_name(self): assert_equal(self.data['attributes']['name'], self.license.name) def test_license_text(self): assert_equal(self.data['attributes']['text'], self.license.text)
Delete non present ignore files from gulp parsing
// gulp var gulp = require('gulp'); // plugins var jshint = require('gulp-jshint'); var jscs = require('gulp-jscs'); var argv = require('yargs').argv; var gulpIgnore = require('gulp-ignore'); var filesJSToScan = (argv.js ? argv.js : 'src/**/*.js'); var filesJSToIgnore = [ ]; gulp.task('jscs', function () { return gulp.src(filesJSToScan) .pipe(gulpIgnore.exclude(filesJSToIgnore)) .pipe(jscs()); }); gulp.task('jshint', function () { gulp.src(filesJSToScan) .pipe(gulpIgnore.exclude(filesJSToIgnore)) .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('default', ['jshint', 'jscs'] );
// gulp var gulp = require('gulp'); // plugins var jshint = require('gulp-jshint'); var jscs = require('gulp-jscs'); var argv = require('yargs').argv; var gulpIgnore = require('gulp-ignore'); var filesJSToScan = (argv.js ? argv.js : 'src/**/*.js'); var filesJSToIgnore = [ '**/*jquery*', '**/*min*', '**/wowslider*', '**/wowSlider/engine1/script.js', '**/js/bootstrap.js', '**/js/wowSliderForm.js' ]; gulp.task('jscs', function () { return gulp.src(filesJSToScan) .pipe(gulpIgnore.exclude(filesJSToIgnore)) .pipe(jscs()); }); gulp.task('jshint', function () { gulp.src(filesJSToScan) .pipe(gulpIgnore.exclude(filesJSToIgnore)) .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('default', ['jshint', 'jscs'] );
Add long description (from README).
from setuptools import setup import jasinja, sys requires = ['Jinja2'] if sys.version_info < (2, 6): requires += ['simplejson'] setup( name='jasinja', version=jasinja.__version__, url='http://bitbucket.org/djc/jasinja', license='BSD', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='A JavaScript code generator for Jinja templates', long_description=open('README.txt').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=['jasinja', 'jasinja.tests'], package_data={ 'jasinja': ['*.js'] }, install_requires=requires, test_suite='jasinja.tests.run.suite', test_requires=['python-spidermonkey'], entry_points={ 'console_scripts': ['jasinja-compile = jasinja.compile:main'], }, )
from setuptools import setup import jasinja, sys requires = ['Jinja2'] if sys.version_info < (2, 6): requires += ['simplejson'] setup( name='jasinja', version=jasinja.__version__, url='http://bitbucket.org/djc/jasinja', license='BSD', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='A JavaScript code generator for Jinja templates', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], packages=['jasinja', 'jasinja.tests'], package_data={ 'jasinja': ['*.js'] }, install_requires=requires, test_suite='jasinja.tests.run.suite', test_requires=['python-spidermonkey'], entry_points={ 'console_scripts': ['jasinja-compile = jasinja.compile:main'], }, )
TDP-982: Fix support for preflight HTTP requests * Fix missing allowed header "accept" when doing preflight HTTP requests.
package org.talend.dataprep.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class CORSConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { // Add CORS header for all path in application registry.addMapping("/**") // .allowedOrigins("*") // .allowedMethods("POST", "GET", "OPTIONS", "DELETE", "PUT") // .maxAge(3600) // .allowedHeaders("x-requested-with", "Content-Type", "accept") .allowCredentials(true); } }; } }
package org.talend.dataprep.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class CORSConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { // Add CORS header for all path in application registry.addMapping("/**") // .allowedOrigins("*") // .allowedMethods("POST", "GET", "OPTIONS", "DELETE", "PUT") // .maxAge(3600) // .allowedHeaders("x-requested-with", "Content-Type") .allowCredentials(true); } }; } }
Use equal width grid to so that, in the future, we can use four column retro formats without changing the code
import React, { Component } from "react" import UserList from "./user_list" import CategoryColumn from "./category_column" import IdeaSubmissionForm from "./idea_submission_form" class Room extends Component { constructor(props) { super(props) this.state = { ideas: [] } this.handleIdeaSubmission = this.handleIdeaSubmission.bind(this) this._setupRoomChannelEventHandlers() } _setupRoomChannelEventHandlers() { this.props.roomChannel.on("new_idea_received", newIdea => { this.setState({ ideas: [...this.state.ideas, newIdea] }) }) } handleIdeaSubmission(idea) { this.props.roomChannel.push("new_idea", { body: idea }) } render() { return ( <section className="room"> <div className="ui equal width padded grid category-columns-wrapper"> <CategoryColumn category="happy" ideas={ this.state.ideas }/> <CategoryColumn category="sad" ideas={ [] }/> <CategoryColumn category="confused" ideas={ [] }/> </div> <UserList users={ this.props.users } /> <IdeaSubmissionForm onIdeaSubmission={ this.handleIdeaSubmission }/> </section> ) } } Room.propTypes = { roomChannel: React.PropTypes.object.isRequired, users: React.PropTypes.array.isRequired, } export default Room
import React, { Component } from "react" import UserList from "./user_list" import CategoryColumn from "./category_column" import IdeaSubmissionForm from "./idea_submission_form" class Room extends Component { constructor(props) { super(props) this.state = { ideas: [] } this.handleIdeaSubmission = this.handleIdeaSubmission.bind(this) this._setupRoomChannelEventHandlers() } _setupRoomChannelEventHandlers() { this.props.roomChannel.on("new_idea_received", newIdea => { this.setState({ ideas: [...this.state.ideas, newIdea] }) }) } handleIdeaSubmission(idea) { this.props.roomChannel.push("new_idea", { body: idea }) } render() { return ( <section className="room"> <div className="ui three column padded grid category-columns-wrapper"> <CategoryColumn category="happy" ideas={ this.state.ideas }/> <CategoryColumn category="sad" ideas={ [] }/> <CategoryColumn category="confused" ideas={ [] }/> </div> <UserList users={ this.props.users } /> <IdeaSubmissionForm onIdeaSubmission={ this.handleIdeaSubmission }/> </section> ) } } Room.propTypes = { roomChannel: React.PropTypes.object.isRequired, users: React.PropTypes.array.isRequired, } export default Room
Allow periods in statsd names
package com.furnaghan.home.component.metrics.statsd; import com.furnaghan.home.component.Component; import com.furnaghan.home.component.metrics.MetricsType; import com.timgroup.statsd.NonBlockingStatsDClient; import com.timgroup.statsd.StatsDClient; public class StatsDMetricsComponent extends Component<MetricsType.Listener> implements MetricsType { private static String sanitize(final String name) { return name.replaceAll("[^a-zA-Z0-9\\s\\.]", "").replaceAll("\\s", "_"); } private final StatsDClient statsd; public StatsDMetricsComponent(final StatsDMetricsConfiguration configuration) { statsd = new NonBlockingStatsDClient(configuration.getPrefix(), configuration.getAddress().getHostText(), configuration.getAddress().getPortOrDefault(StatsDMetricsConfiguration.DEFAULT_PORT)); } @Override public void send(final String name, final double value) { statsd.gauge(sanitize(name), value); } }
package com.furnaghan.home.component.metrics.statsd; import com.furnaghan.home.component.Component; import com.furnaghan.home.component.metrics.MetricsType; import com.timgroup.statsd.NonBlockingStatsDClient; import com.timgroup.statsd.StatsDClient; public class StatsDMetricsComponent extends Component<MetricsType.Listener> implements MetricsType { private static String sanitize(final String name) { return name.replaceAll("[^a-zA-Z0-9\\s]", "").replaceAll("\\s", "_"); } private final StatsDClient statsd; public StatsDMetricsComponent(final StatsDMetricsConfiguration configuration) { statsd = new NonBlockingStatsDClient(configuration.getPrefix(), configuration.getAddress().getHostText(), configuration.getAddress().getPortOrDefault(StatsDMetricsConfiguration.DEFAULT_PORT)); } @Override public void send(final String name, final double value) { statsd.gauge(sanitize(name), value); } }
Fix the phone Column type
from datetime import datetime from sqlalchemy import Column, DateTime, Integer, Text, Boolean, Date from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker DBSession = scoped_session(sessionmaker()) Base = declarative_base() class Application(Base): __tablename__ = 'applications' id = Column(Integer, primary_key=True) realname = Column(Text) username = Column(Text, unique=True) country = Column(Text) state = Column(Text) hardware = Column(Text) shield = Column(Text) date = Column(DateTime, default=datetime.now) text = Column(Text) approved = Column(Boolean, default=False) address = Column(Text) phone = Column(Text) def __repr__(self): return "<Application %s %s>" % (self.username, self.hardware)
from datetime import datetime from sqlalchemy import Column, DateTime, Integer, Text, Boolean, Date from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker DBSession = scoped_session(sessionmaker()) Base = declarative_base() class Application(Base): __tablename__ = 'applications' id = Column(Integer, primary_key=True) realname = Column(Text) username = Column(Text, unique=True) country = Column(Text) state = Column(Text) hardware = Column(Text) shield = Column(Text) date = Column(DateTime, default=datetime.now) text = Column(Text) approved = Column(Boolean, default=False) address = Column(Text) phone = Column(Date) def __repr__(self): return "<Application %s %s>" % (self.username, self.hardware)
Fix logout route not working in admin
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | This file is where you may define all of the routes that are handled | by your application. Just tell Laravel the URIs it should respond | to using a Closure or controller method. Build something great! | */ // Search Engine Robot Routes Route::get('/confession/{id}', function ($id) { $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null; $botTypes = 'bot|crawl|slurp|spider|facebookexternalhit'; $isCrawler = ! empty($userAgent) ? preg_match("/{$botTypes}/", $userAgent) > 0 : false; if ($isCrawler) { return App::make('NUSWhispers\Http\Controllers\RobotsController')->getConfession($id); } else { return File::get(public_path() . '/app.html'); } }); // Auth Routes Auth::routes(['register' => false]); Route::get('logout', 'Auth\LoginController@logout'); // Mobile submit page Route::get('/mobile_submit', function () { return File::get(public_path() . '/mobile_submit.html'); }); // Reroute everything else to angular Route::get('/{getEverything?}/{all?}', function () { return File::get(public_path() . '/app.html'); });
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | This file is where you may define all of the routes that are handled | by your application. Just tell Laravel the URIs it should respond | to using a Closure or controller method. Build something great! | */ // Search Engine Robot Routes Route::get('/confession/{id}', function ($id) { $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null; $botTypes = 'bot|crawl|slurp|spider|facebookexternalhit'; $isCrawler = ! empty($userAgent) ? preg_match("/{$botTypes}/", $userAgent) > 0 : false; if ($isCrawler) { return App::make('NUSWhispers\Http\Controllers\RobotsController')->getConfession($id); } else { return File::get(public_path() . '/app.html'); } }); // Auth Routes Auth::routes(['register' => false]); // Mobile submit page Route::get('/mobile_submit', function () { return File::get(public_path() . '/mobile_submit.html'); }); // Reroute everything else to angular Route::get('/{getEverything?}/{all?}', function () { return File::get(public_path() . '/app.html'); });
Allow multiple files to be loaded via eject
export async function genArrayBufferFromFileReference(fileReference) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function(e) { resolve(e.target.result); }; reader.onerror = function(e) { reject(e); }; reader.readAsArrayBuffer(fileReference); }); } export async function genArrayBufferFromUrl(url) { return new Promise((resolve, reject) => { const oReq = new XMLHttpRequest(); oReq.open("GET", url, true); oReq.responseType = "arraybuffer"; oReq.onload = () => { const arrayBuffer = oReq.response; // Note: not oReq.responseText resolve(arrayBuffer); }; oReq.onerror = reject; oReq.send(null); }); } export async function promptForFileReferences() { return new Promise(resolve => { // Does this represent a memory leak somehow? // Can this fail? Do we ever reject? const fileInput = document.createElement("input"); fileInput.type = "file"; fileInput.multiple = true; // Not entirely sure why this is needed, since the input // was just created, but somehow this helps prevent change // events from getting swallowed. // https://stackoverflow.com/a/12102992/1263117 fileInput.value = null; fileInput.addEventListener("change", e => { resolve(e.target.files); }); fileInput.click(); }); }
export async function genArrayBufferFromFileReference(fileReference) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function(e) { resolve(e.target.result); }; reader.onerror = function(e) { reject(e); }; reader.readAsArrayBuffer(fileReference); }); } export async function genArrayBufferFromUrl(url) { return new Promise((resolve, reject) => { const oReq = new XMLHttpRequest(); oReq.open("GET", url, true); oReq.responseType = "arraybuffer"; oReq.onload = () => { const arrayBuffer = oReq.response; // Note: not oReq.responseText resolve(arrayBuffer); }; oReq.onerror = reject; oReq.send(null); }); } export async function promptForFileReferences() { return new Promise(resolve => { // Does this represent a memory leak somehow? // Can this fail? Do we ever reject? const fileInput = document.createElement("input"); fileInput.type = "file"; // Not entirely sure why this is needed, since the input // was just created, but somehow this helps prevent change // events from getting swallowed. // https://stackoverflow.com/a/12102992/1263117 fileInput.value = null; fileInput.addEventListener("change", e => { resolve(e.target.files); }); fileInput.click(); }); }
Fix merge problem with map
function initHomeMap (coords){ $("h1.logozone").after("<div id='zoneHomeMap'><div id='homeMap'></div><div id='mask'></div></div>"); var imgmarker='../img/marker.png'; var objectMarker = coords.map(function(coord) { return { latitude: coord.lat, longitude: coord.lon, icon: imgmarker}; }); $("#homeMap").goMap({ navigationControl: false, mapTypeControl: false, scrollwheel: false, disableDoubleClickZoom: true, zoom: 12, maptype: 'ROADMAP', markers: objectMarker }); $.goMap.setMap({latitude:'46.836944988044465', longitude:'-71.28376007080078'}); } $(document).on('homemap:ready', function(e, coords) { // Idempotence if($("#zoneHomeMap").length !== 0) return; $(window).on('resize.homemap', function() { if($("#zoneHomeMap").length == 0 && $(window).width() > 960) { initHomeMap(coords); } }) $(window).trigger('resize.homemap'); $(document).on('page:change', function() { $(window).off('.homemap'); }); });
function initHomeMap (coords){ $("h1.logozone").after("<div id='zoneHomeMap'><div id='homeMap'></div><div id='mask'></div></div>"); var imgmarker='../img/marker.png'; var objectMarker = coords.map(function(coord) { return { latitude: coord.lat, longitude: coord.lon, icon: imgmarker}; }); $("#homeMap").goMap({ navigationControl: false, mapTypeControl: false, scrollwheel: false, disableDoubleClickZoom: true, zoom: 12, maptype: 'ROADMAP', markers: objectMarker }); $.goMap.setMap({latitude:'46.836944988044465', longitude:'-71.28376007080078'}); } $(document).on('homemap:ready', function(e, coords) { // Idempotence if($("#zoneHomeMap").length !== 0) return; $(window).on('resize.homemap', function() { if($("#zoneHomeMap").length == 0 && $(window).width() > 960) { initHomeMap(coords); } }) $(window).trigger('resize.homemap'); $(document).on('page:change', function() { $(window.off('.homemap')); }); });
Delete unused var and func
import alt from '../alt'; import SignupActions from '../actions/SignupActions'; class SignupStore { constructor() { this.bindActions(SignupActions); this.username = ''; this.password = ''; this.signupValidationState = ''; } onSignupSuccess(successMessage) { this.signupValidationState = 'has-success'; } onAddLabelFail(errorMessage) { this.signupValidationState = 'has-error'; } onUpdateUsername(event) { this.username = event.target.value; this.signupValidationState = ''; } onUpdatePassword(event) { this.password = event.target.value; this.signupValidationState = ''; } onInvalidLabel() { this.signupValidationState = 'has-error'; } } export default alt.createStore(SignupStore);
import alt from '../alt'; import SignupActions from '../actions/SignupActions'; class SignupStore { constructor() { this.bindActions(SignupActions); this.username = ''; this.password = ''; this.signupValidationState = ''; } onSignupSuccess(successMessage) { this.signupValidationState = 'has-success'; } onAddLabelFail(errorMessage) { this.signupValidationState = 'has-error'; } onUpdateName(event) { this.name = event.target.value; this.signupValidationState = ''; } onUpdateEmail(event) { this.email = event.target.value; this.signupValidationState = ''; } onUpdateUsername(event) { this.username = event.target.value; this.signupValidationState = ''; } onUpdatePassword(event) { this.password = event.target.value; this.signupValidationState = ''; } onInvalidLabel() { this.signupValidationState = 'has-error'; } } export default alt.createStore(SignupStore);
Use upper case when testing for HTTP request type
document.addEventListener('click', function(event) { var form, input, method, element; element = event.target; if (matches.call(element, 'a[data-method]')) { if (matches.call(element, 'a[data-remote]')) { return true; } method = element.getAttribute('data-method').toUpperCase(); if (method == 'GET') { return true; } form = document.createElement('form'); form.method = 'POST'; form.action = element.getAttribute('href'); form.style.display = 'none'; if (method != 'POST') { input = document.createElement('input'); input.setAttribute('type', 'hidden'); input.setAttribute('name', '_method'); input.setAttribute('value', method); form.appendChild(input); } document.body.appendChild(form); form.submit(); event.preventDefault(); } }, false);
document.addEventListener('click', function(event) { var form, input, method, element; element = event.target; if (matches.call(element, 'a[data-method]')) { if (matches.call(element, 'a[data-remote]')) { return true; } method = element.getAttribute('data-method').toLowerCase(); if (method == 'get') { return true; } form = document.createElement('form'); form.method = 'POST'; form.action = element.getAttribute('href'); form.style.display = 'none'; if (method != 'post') { input = document.createElement('input'); input.setAttribute('type', 'hidden'); input.setAttribute('name', '_method'); input.setAttribute('value', method); form.appendChild(input); } document.body.appendChild(form); form.submit(); event.preventDefault(); } }, false);