text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Change openness users icon by unlock icon
import React from 'react' import PieChart from '../../Charts/PieChart/PieChart' import BarChart from '../../Charts/BarChart/BarChart' import Percent from '../../Statistics/Percent/Percent' const StatisticsSection = ({metrics}) => { return ( <div className="ui equal width center aligned stackable grid"> <div className="eight wide column"> <Percent metrics={metrics} label="openness" icon="unlock alternate icon" description="Percentage of open source data." /> </div> <div className="eight wide column"> <Percent metrics={metrics} label="download" icon="download" description="Percentage of successfully downloaded data." /> </div> <div className="eight wide column"> <PieChart data={metrics.partitions.recordType} /> </div> <div className="eight wide column"> <BarChart data={metrics.partitions.dataType} /> </div> </div> ) } export default StatisticsSection
import React from 'react' import PieChart from '../../Charts/PieChart/PieChart' import BarChart from '../../Charts/BarChart/BarChart' import Percent from '../../Statistics/Percent/Percent' const StatisticsSection = ({metrics}) => { return ( <div className="ui equal width center aligned stackable grid"> <div className="eight wide column"> <Percent metrics={metrics} label="openness" icon="users" description="Percentage of open source data." /> </div> <div className="eight wide column"> <Percent metrics={metrics} label="download" icon="download" description="Percentage of successfully downloaded data." /> </div> <div className="eight wide column"> <PieChart data={metrics.partitions.recordType} /> </div> <div className="eight wide column"> <BarChart data={metrics.partitions.dataType} /> </div> </div> ) } export default StatisticsSection
Increase chan buffer size in snake observer
package observers import ( "github.com/sirupsen/logrus" "github.com/ivan1993spb/snake-server/objects/corpse" "github.com/ivan1993spb/snake-server/objects/snake" "github.com/ivan1993spb/snake-server/world" ) const chanSnakeObserverEventsBuffer = 64 type SnakeObserver struct{} func (SnakeObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) { go func() { for event := range w.Events(stop, chanSnakeObserverEventsBuffer) { if event.Type == world.EventTypeObjectDelete { if s, ok := event.Payload.(*snake.Snake); ok { if c, err := corpse.NewCorpse(w, s.GetLocation()); err != nil { logger.WithError(err).Error("cannot create corpse") } else { c.Run(stop) } } } } }() }
package observers import ( "github.com/sirupsen/logrus" "github.com/ivan1993spb/snake-server/objects/corpse" "github.com/ivan1993spb/snake-server/objects/snake" "github.com/ivan1993spb/snake-server/world" ) const chanSnakeObserverEventsBuffer = 32 type SnakeObserver struct{} func (SnakeObserver) Observe(stop <-chan struct{}, w *world.World, logger logrus.FieldLogger) { go func() { for event := range w.Events(stop, chanSnakeObserverEventsBuffer) { if event.Type == world.EventTypeObjectDelete { if s, ok := event.Payload.(*snake.Snake); ok { if c, err := corpse.NewCorpse(w, s.GetLocation()); err != nil { logger.WithError(err).Error("cannot create corpse") } else { c.Run(stop) } } } } }() }
Add matter, generate and help commands to switch
#!/usr/bin/env node 'use strict'; var pkg = require('../package.json'); var docopt = require('docopt').docopt; var updateNotifier = require('update-notifier'); updateNotifier({ pkg }).notify(); var doc = ` usage: collider [--version] [--help] <command> [<args>...] options: -h, --help Show help information. --version Show program version. commands: run Run the current project. new Create a new project in the current directory. matter Manage Matter libraries in the current project. generate Generate skeleton Matter within the current project. help Show help information. See 'collider help <command>' for more information on a specific command. `; var args = docopt(doc, { version: `Collider CLI ${pkg.version}`, options_first: true, }); var cmd = args['<command>']; var argv = [cmd].concat(args['<args>']); switch(cmd) { case 'run': require('../lib/commands/run')(argv); break; case 'new': require('../lib/commands/new')(argv); break; case 'matter': require('../lib/commands/matter')(argv); break; case 'generate': require('../lib/commands/generate')(argv); break; case 'help': require('../lib/commands/help')(argv); break; default: console.error(`"${cmd}" is not a collider command. See 'collider --help'.`) }
#!/usr/bin/env node 'use strict'; var pkg = require('../package.json'); var docopt = require('docopt').docopt; var updateNotifier = require('update-notifier'); updateNotifier({ pkg }).notify(); var doc = ` usage: collider [--version] [--help] <command> [<args>...] options: -h, --help Show help information. --version Show program version. commands: run Run the current project. new Create a new project in the current directory. matter Manage Matter libraries in the current project. generate Generate skeleton Matter within the current project. help Show help information. See 'collider help <command>' for more information on a specific command. `; var args = docopt(doc, { version: `Collider CLI ${pkg.version}`, options_first: true, }); var cmd = args['<command>']; var argv = [cmd].concat(args['<args>']); switch(cmd) { case 'run': require('../lib/commands/run')(argv); break; case 'new': require('../lib/commands/new')(argv); break; default: console.error(`"${cmd}" is not a collider command. See 'collider --help'.`) }
Remove vaccine from redux store persistance blacklist
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import Bugsnag from '@bugsnag/react-native'; import AsyncStorage from '@react-native-community/async-storage'; import { persistStore, persistReducer } from 'redux-persist'; import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { navigationMiddleware } from './navigation'; import reducers from './reducers'; const persistConfig = { keyPrefix: '', key: 'root', storage: AsyncStorage, blacklist: [ 'pages', 'user', 'prescription', 'patient', 'finalise', 'form', 'prescriber', 'wizard', 'payment', 'insurance', 'dashboard', 'dispensary', 'modules', 'supplierCredit', 'fridge', 'breach', 'rowDetail', 'permission', 'cashTransaction', 'entities', ], }; const persistedReducer = persistReducer(persistConfig, reducers); const bugsnagMiddleware = () => next => action => { const { type = 'No action type!' } = action; Bugsnag.leaveBreadcrumb(type); next(action); }; const store = createStore( persistedReducer, {}, applyMiddleware(thunk, navigationMiddleware, bugsnagMiddleware) ); const persistedStore = persistStore(store); export { store, persistedStore };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import Bugsnag from '@bugsnag/react-native'; import AsyncStorage from '@react-native-community/async-storage'; import { persistStore, persistReducer } from 'redux-persist'; import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { navigationMiddleware } from './navigation'; import reducers from './reducers'; const persistConfig = { keyPrefix: '', key: 'root', storage: AsyncStorage, blacklist: [ 'pages', 'user', 'prescription', 'patient', 'finalise', 'form', 'prescriber', 'wizard', 'payment', 'insurance', 'dashboard', 'dispensary', 'modules', 'supplierCredit', 'fridge', 'breach', 'rowDetail', 'permission', 'cashTransaction', 'vaccine', 'entities', ], }; const persistedReducer = persistReducer(persistConfig, reducers); const bugsnagMiddleware = () => next => action => { const { type = 'No action type!' } = action; Bugsnag.leaveBreadcrumb(type); next(action); }; const store = createStore( persistedReducer, {}, applyMiddleware(thunk, navigationMiddleware, bugsnagMiddleware) ); const persistedStore = persistStore(store); export { store, persistedStore };
Increase some intervals to further reduce stress on the jobtracker. git-svn-id: 4d48d1092ee340c9ada5711cdbe4355b138bc22b@383623 13f79535-47bb-0310-9956-ffa450edef68
/** * Copyright 2005 The Apache Software Foundation * * 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 org.apache.hadoop.mapred; /******************************* * Some handy constants * * @author Mike Cafarella *******************************/ interface MRConstants { // // Timeouts, constants // public static final long HEARTBEAT_INTERVAL = 10 * 1000; public static final long TASKTRACKER_EXPIRY_INTERVAL = 10 * 60 * 1000; // // Result codes // public static int SUCCESS = 0; public static int FILE_NOT_FOUND = -1; }
/** * Copyright 2005 The Apache Software Foundation * * 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 org.apache.hadoop.mapred; /******************************* * Some handy constants * * @author Mike Cafarella *******************************/ interface MRConstants { // // Timeouts, constants // public static final long HEARTBEAT_INTERVAL = 3 * 1000; public static final long TASKTRACKER_EXPIRY_INTERVAL = 60 * 1000; // // Result codes // public static int SUCCESS = 0; public static int FILE_NOT_FOUND = -1; }
Test we have access to envvar when we have no file
# coding: utf-8 import os import pytest from mock import patch from decouple import AutoConfig def test_autoconfig_env(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'ENV' == config('KEY') def test_autoconfig_ini(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'ini', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'INI' == config('KEY') def test_autoconfig_none(): os.environ['KeyFallback'] = 'On' config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'none') with patch('os.path.exists', return_value=False): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback'] def test_autoconfig_exception(): os.environ['KeyFallback'] = 'On' config = AutoConfig() with patch('os.path.exists', side_effect=Exception('PermissionDenied')): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback']
# coding: utf-8 import os import pytest from mock import patch from decouple import AutoConfig def test_autoconfig_env(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'ENV' == config('KEY') def test_autoconfig_ini(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'ini', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'INI' == config('KEY') def test_autoconfig_none(): os.environ['KeyFallback'] = 'On' config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'none') with patch('os.path.exists', return_value=False): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback']
Add js tasks to fabric update
# -*- coding: utf-8 -*- u""" .. module:: fabfile Be aware, that becaus fabric doesn't support py3k You need to execute this particular script using Python 2. """ import contextlib from fabric.api import cd from fabric.api import env from fabric.api import prefix from fabric.api import run env.user = 'root' env.hosts = ['wysadzulice.pl'] env.forward_agent = True def update(): u"""Function defining all steps required to properly update application.""" with contextlib.nested( cd('/var/www/wysadzulice_pl'), prefix('workon wysadzulice_pl') ): run('git pull') run('git checkout master') run('python manage.py migrate --traceback') run('npm cache clear') run('rm -rf ./node_modules') run('npm install') run('gulp build') run('service apache2 restart')
# -*- coding: utf-8 -*- u""" .. module:: fabfile Be aware, that becaus fabric doesn't support py3k You need to execute this particular script using Python 2. """ import contextlib from fabric.api import cd from fabric.api import env from fabric.api import prefix from fabric.api import run env.user = 'root' env.hosts = ['wysadzulice.pl'] env.forward_agent = True def update(): u"""Function defining all steps required to properly update application.""" with contextlib.nested( cd('/var/www/wysadzulice_pl'), prefix('workon wysadzulice_pl') ): run('git pull') run('git checkout master') run('python manage.py migrate --traceback') run('service apache2 restart')
Update zopfli binary URL to the latest commit https://github.com/google/zopfli/commit/64c6f362fefd56dccbf31906fdb3e31f6a6faf80
'use strict'; const BinBuild = require('bin-build'); const log = require('logalot'); const bin = require('.'); bin.run(['--help'], err => { if (err) { log.warn(err.message); log.warn('zopflipng pre-build test failed'); log.info('compiling from source'); let makeBin = 'make'; let makeArgs = ''; if (process.platform === 'freebsd') { makeBin = 'gmake'; makeArgs = 'CC=cc CXX=c++'; } const builder = new BinBuild() .src('https://github.com/google/zopfli/archive/64c6f362fefd56dccbf31906fdb3e31f6a6faf80.zip') .cmd(`mkdir -p ${bin.dest()}`) .cmd(`${makeBin} zopflipng ${makeArgs} && mv ./zopflipng ${bin.path()}`); return builder.run(err => { if (err) { log.error(err.stack); return; } log.success('zopflipng built successfully'); }); } log.success('zopflipng pre-build test passed successfully'); });
'use strict'; const BinBuild = require('bin-build'); const log = require('logalot'); const bin = require('.'); bin.run(['--help'], err => { if (err) { log.warn(err.message); log.warn('zopflipng pre-build test failed'); log.info('compiling from source'); let makeBin = 'make'; let makeArgs = ''; if (process.platform === 'freebsd') { makeBin = 'gmake'; makeArgs = 'CC=cc CXX=c++'; } const builder = new BinBuild() .src('https://github.com/google/zopfli/archive/6818a0859063b946094fb6f94732836404a0d89a.zip') .cmd(`mkdir -p ${bin.dest()}`) .cmd(`${makeBin} zopflipng ${makeArgs} && mv ./zopflipng ${bin.path()}`); return builder.run(err => { if (err) { log.error(err.stack); return; } log.success('zopflipng built successfully'); }); } log.success('zopflipng pre-build test passed successfully'); });
Add onerror retry for flag loader
import {generateQuizOptions} from '../data/quiz'; export const SELECT_COUNTRY = 'SELECT_COUNTRY'; export const SET_QUIZ = 'SET_QUIZ'; export const setQuiz = (quiz) => ({ type: SET_QUIZ, payload: quiz }); export const loadImg = (src) => { return new Promise((resolve, reject) => { const img = new Image(); img.onload = () => resolve(); img.onerror = () => reject(src); img.src = src; }); } export const fetchFlag = (country) => { return loadImg(country.flag) .catch(src => loadImg(src)) }; export const wait = (time) => { return new Promise(resolve => setTimeout(() => resolve(), time)); }; export const loadQuiz = () => { return (dispatch) => { const quiz = generateQuizOptions(); const flagsPromises = quiz.options.map(fetchFlag); return Promise.all(flagsPromises.concat(wait(2500))) .then(flags => dispatch(setQuiz(quiz))); } } export const selectCountry = (country = null) => ({ type: SELECT_COUNTRY, payload: country, }); export const answerQuiz = (country) => { return (dispatch) => { dispatch(selectCountry(country)); dispatch(loadQuiz()) } }
import {generateQuizOptions} from '../data/quiz'; export const SELECT_COUNTRY = 'SELECT_COUNTRY'; export const SET_QUIZ = 'SET_QUIZ'; export const setQuiz = (quiz) => ({ type: SET_QUIZ, payload: quiz }); export const fetchFlag = (country) => { return new Promise(resolve => { const flag = new Image(); flag.onload = () => resolve(); flag.src = country.flag }); }; export const wait = (time) => { return new Promise(resolve => setTimeout(() => resolve(), time)); }; export const loadQuiz = () => { return (dispatch) => { const quiz = generateQuizOptions(); const flagsPromises = quiz.options.map(fetchFlag); return Promise.all(flagsPromises.concat(wait(2500))) .then(flags => dispatch(setQuiz(quiz))); } } export const selectCountry = (country = null) => ({ type: SELECT_COUNTRY, payload: country, }); export const answerQuiz = (country) => { return (dispatch) => { dispatch(selectCountry(country)); dispatch(loadQuiz()) } }
Add tweet and like interval
// This module is the server of my site. // Require external dependecies. var http = require('http'); var filed = require('filed'); var path = require('path'); var readFile = require('fs').readFile; var publish = require('./publish'); var bake = require('blake').bake; // Start the site. module.exports = function (config) { var isInvalid = !config || !config.port || !config.input || !config.output; if (isInvalid) { throw new Error('Invalid configuration'); } // Create and start the server. http.createServer(function (req, resp) { var file = path.resolve(config.output + req.url); var ext = file.split('.')[1]; var isPublish = req.url === config.hook; if (isPublish) { return publish(config, req, resp, function (err) { console.log(err || 'Published on %s', new Date()); }); } if (req.url != '/' && !ext) { file += '.html'; } else if (!ext) { file += '/'; } req.pipe(filed(file)).pipe(resp); }).listen(config.port, config.ip); // Retrieve latest tweet and instapaper likes. var tweet = path.resolve(config.input, 'data', 'tweet.json'); var likes = path.resolve(config.input, 'data', 'likes.json'); setInterval(function () { bake(config.input, config.output, tweet, likes, function (err) { console.log('Published tweet and likes on %s', new Date()); }); }, 3600000); };
// This module is the server of my site. // Require external dependecies. var http = require('http'); var filed = require('filed'); var path = require('path'); var readFile = require('fs').readFile; var publish = require('./publish'); // Start the site. module.exports = function (config) { var isInvalid = !config || !config.port || !config.input || !config.output; if (isInvalid) { throw new Error('Invalid configuration'); } // Create and start the server. http.createServer(function (req, resp) { var file = path.resolve(config.output + req.url); var ext = file.split('.')[1]; var isPublish = req.url === config.hook; if (isPublish) { return publish(config, req, resp, function (err) { console.log(err || 'Published on %s', new Date()); }); } if (req.url != '/' && !ext) { file += '.html'; } else if (!ext) { file += '/'; } req.pipe(filed(file)).pipe(resp); }).listen(config.port, config.ip); };
Add more private pages to access denied list
/*****************************************************************************/ /* Client and Server Routes */ /*****************************************************************************/ Router.configure({ layoutTemplate: 'MasterLayout', loadingTemplate: 'Loading', notFoundTemplate: 'NotFound' }); Router.route('/', { name: 'marketing' }); Router.route('/pages', { name: 'pages.index' }); Router.route('/pages/new', { name: 'pages.new' }); Router.route('/pages/:_id', { name: 'pages.show' }); Router.route('/settings', { name: 'settings.index' }); Router.route('/users/:_id', { name: 'users.show' }); Router.route('/users/:_id/edit', { name:'users.edit' }); var requireLogin = function () { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('AccessDenied'); } } else { this.next(); } }; Router.onBeforeAction('dataNotFound'); Router.onBeforeAction(requireLogin, { only: [ 'pages.index', 'pages.new', 'settings.index', 'users.show', 'users.edit' ] });
/*****************************************************************************/ /* Client and Server Routes */ /*****************************************************************************/ Router.configure({ layoutTemplate: 'MasterLayout', loadingTemplate: 'Loading', notFoundTemplate: 'NotFound' }); Router.route('/', { name: 'marketing' }); Router.route('/pages', { name: 'pages.index' }); Router.route('/pages/new', { name: 'pages.new' }); Router.route('/pages/:_id', { name: 'pages.show' }); Router.route('/settings', { name: 'settings.index' }); Router.route('/users/:_id', { name: 'users.show' }); Router.route('/users/:_id/edit', { name:'users.edit' }); var requireLogin = function () { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('AccessDenied'); } } else { this.next(); } }; Router.onBeforeAction('dataNotFound'); Router.onBeforeAction(requireLogin, { only: 'pages.index' });
Rename misleading parameter name: UnicodeDictReader should have the same interface as csv.DictReader
# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, fp, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(fp, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding)
# work around python2's csv.py's difficulty with utf8 # partly cribbed from http://stackoverflow.com/questions/5478659/python-module-like-csv-dictreader-with-full-utf8-support import csv class EmptyCSVError(Exception): pass class UnicodeDictReader(object): def __init__(self, file_or_str, encoding='utf8', **kwargs): self.encoding = encoding self.reader = csv.DictReader(file_or_str, **kwargs) if not self.reader.fieldnames: raise EmptyCSVError("No fieldnames in CSV reader: empty file?") self.keymap = dict((k, k.decode(encoding)) for k in self.reader.fieldnames) def __iter__(self): return (self._decode_row(row) for row in self.reader) def _decode_row(self, row): return dict( (self.keymap[k], self._decode_str(v)) for k, v in row.iteritems() ) def _decode_str(self, s): if s is None: return None return s.decode(self.encoding)
Revert some stuff due to an issue where artisan would eager load all providers, causing an issue here. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Foundation\Providers; use Illuminate\Support\ServiceProvider; class ExtensionServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var boolean */ protected $defer = true; /** * Available orchestra extensions * * @var array */ protected $extensions = []; /** * Register the service provider * * @return void */ public function register() { // } /** * Bootstrap the application events. * * @return void */ public function boot() { $finder = $this->app['orchestra.extension.finder']; foreach ($this->extensions as $name => $path) { if (is_numeric($name)) { $finder->addPath($path); } else { $finder->registerExtension($name, $path); } } } /** * Get the events that trigger this service provider to register. * * @return array */ public function when() { return ['orchestra.extension: detecting']; } }
<?php namespace Orchestra\Foundation\Providers; use Illuminate\Support\ServiceProvider; class ExtensionServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var boolean */ protected $defer = true; /** * Available orchestra extensions * * @var array */ protected $extensions = []; /** * Register the service provider * * @return void */ public function register() { $extension = $this->app['orchestra.extension']; foreach ($this->extensions as $name => $path) { if (is_numeric($name)) { $extension->finder()->addPath($path); } else { $extension->register($name, $path); } } } /** * Get the events that trigger this service provider to register. * * @return array */ public function when() { return ['orchestra.extension: detecting']; } }
Fix this janky script and autoformat.
$(document).ready(function() { $('a.menu').click(function() { $('.site-header nav').slideToggle(100); return false; }); $(window).resize(function() { var w = $(window).width(); var menu = $('.site-header nav'); if (w > 680 && menu.is(':hidden')) { menu.removeAttr('style'); } }); $('article.post iframe').wrap('<div class="video-container" />'); }); $(document).ready(function() { var vpH = $(window).height(); var vH = vpH - 350; $('.overlay').css("height", vH); $('.featured-image').css("height", vH); }); $(function() { $('<img>').attr('src', function() { var imgUrl = $('div.featured-image').css('background-image'); if (!imgUrl) { return; } imgUrl = imgUrl.substring(4, imgUrl.length - 1).replace(/\"/g, ''); return imgUrl; }).load(function() { $('img.loading').fadeOut(500); $('div.overlay').fadeTo("slow", 0.6); }); }); $(function() { $('.post-list li').each(function(i) { var t = $(this); setTimeout(function() { t.addClass('slider'); }, (i + 1) * 330); }); });
$(document).ready(function() { $('a.menu').click(function() { $('.site-header nav').slideToggle(100); return false; }); $(window).resize(function(){ var w = $(window).width(); var menu = $('.site-header nav'); if(w > 680 && menu.is(':hidden')) { menu.removeAttr('style'); } }); $('article.post iframe').wrap('<div class="video-container" />'); }); $(document).ready(function() { var vpH = $(window).height(); var vH = vpH - 350; $('.overlay').css("height", vH); $('.featured-image').css("height", vH); }); $(function(){ $('<img>').attr('src',function(){ var imgUrl = $('div.featured-image').css('background-image'); if (!imgUrl) { return; } imgUrl = imgUrl.substring(4, imgUrl.length-1); return imgUrl; }).load(function(){ $('img.loading').fadeOut(500); $('div.overlay').fadeTo("slow", 0.6); }); }); $(function(){ $('.post-list li').each(function(i){ var t = $(this); setTimeout(function(){ t.addClass('slider'); }, (i+1) * 330); }); });
Install the treepriors package along with everything else. Feels very wrong that these need to be manually declared one-by-one, but oh well.
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup from beastling import __version__ as version requires = [ 'six', 'newick>=0.6.0', 'appdirs', 'clldutils~=2.0', 'pycldf', ] setup( name='beastling', version=version, description='Command line tool to help mortal linguists use BEAST', author='Luke Maurits', author_email='luke@maurits.id.au', license="BSD (3 clause)", classifiers=[ 'Programming Language :: Python', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'License :: OSI Approved :: BSD License', ], packages=['beastling','beastling.clocks','beastling.fileio','beastling.models','beastling.treepriors'], install_requires=requires, tests_require=['mock==1.0.0', 'nose'], entry_points={ 'console_scripts': ['beastling=beastling.cli:main'], }, package_data={'beastling': ['data/*']}, )
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup from beastling import __version__ as version requires = [ 'six', 'newick>=0.6.0', 'appdirs', 'clldutils~=2.0', 'pycldf', ] setup( name='beastling', version=version, description='Command line tool to help mortal linguists use BEAST', author='Luke Maurits', author_email='luke@maurits.id.au', license="BSD (3 clause)", classifiers=[ 'Programming Language :: Python', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'License :: OSI Approved :: BSD License', ], packages=['beastling','beastling.clocks','beastling.fileio','beastling.models'], install_requires=requires, tests_require=['mock==1.0.0', 'nose'], entry_points={ 'console_scripts': ['beastling=beastling.cli:main'], }, package_data={'beastling': ['data/*']}, )
Add id of node generating the supervisor event
#!/usr/bin/env python import json import sys from utils import serf_event def write_stdout(s): sys.stdout.write(s) sys.stdout.flush() def write_stderr(s): sys.stderr.write(s) sys.stderr.flush() def main(): while True: write_stdout('READY\n') # transition from ACKNOWLEDGED to READY line = sys.stdin.readline() # read header line from stdin headers = dict(x.split(':') for x in line.split()) data = sys.stdin.read(int(headers['len'])) # read the event payload data_dict = dict(x.split(':') for x in data.split()) data_dict['eventname'] = headers['eventname'] data_dict['node'] = serf('info')['agent']['name'] serf_event('supervisor', json.dumps(data_dict)) write_stdout('RESULT 2\nOK') # transition from READY to ACKNOWLEDGED if __name__ == '__main__': main()
#!/usr/bin/env python import json import sys from utils import serf_event def write_stdout(s): sys.stdout.write(s) sys.stdout.flush() def write_stderr(s): sys.stderr.write(s) sys.stderr.flush() def main(): while True: write_stdout('READY\n') # transition from ACKNOWLEDGED to READY line = sys.stdin.readline() # read header line from stdin headers = dict(x.split(':') for x in line.split()) data = sys.stdin.read(int(headers['len'])) # read the event payload data_dict = dict(x.split(':') for x in data.split()) data_dict['eventname'] = headers['eventname'] serf_event('myevent', json.dumps(data_dict)) write_stdout('RESULT 2\nOK') # transition from READY to ACKNOWLEDGED if __name__ == '__main__': main()
Fix problem with highlighting tokens after whitespace
CodeMirror.defineMode("roy", function(config, parserConfig) { return { token: function(stream, state) { var token, sliced = stream.string.slice(stream.pos); try { token = roy.lexer.tokenise(sliced)[0]; if(!token[1].length) { stream.next(); return; } stream.pos += sliced.match(/\s*/)[0].length + token[1].length; } catch(e) { stream.next(); return; } switch(token[0]) { case 'LET': case 'IF': case 'THEN': case 'ELSE': case 'DATA': case 'TYPE': case 'MATCH': case 'CASE': case 'DO': case 'RETURN': case 'MACRO': case 'WITH': case 'WHERE': return 'keyword'; case 'BOOLEAN': return 'builtin'; } return token[0].toLowerCase(); } }; });
CodeMirror.defineMode("roy", function(config, parserConfig) { return { token: function(stream, state) { var token; try { token = roy.lexer.tokenise(stream.string.slice(stream.pos))[0]; if(!token[1].length) { stream.next(); return; } stream.pos += token[1].length; } catch(e) { stream.next(); return; } switch(token[0]) { case 'LET': case 'IF': case 'THEN': case 'ELSE': case 'DATA': case 'TYPE': case 'MATCH': case 'CASE': case 'DO': case 'RETURN': case 'MACRO': case 'WITH': case 'WHERE': return 'keyword'; case 'BOOLEAN': return 'builtin'; } return token[0].toLowerCase(); } }; });
Add description to ethnicity model
# -*- coding: utf-8 -*- # ############################################################################# # # Tech-Receptives Solutions Pvt. Ltd. # Copyright (C) 2004-TODAY Tech-Receptives(<http://www.techreceptives.com>) # Special Credit and Thanks to Thymbra Latinoamericana S.A. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ############################################################################# from openerp import models, fields class MedicalPatientEthnicity(models.Model): _name = 'medical.patient.ethnicity' _description = 'Medical Patient Ethnicity' notes = fields.Char() code = fields.Char(required=True, ) name = fields.Char(required=True, translate=True) _sql_constraints = [ ('name_uniq', 'UNIQUE(name)', 'Ethnicity name must be unique!'), ('code_uniq', 'UNIQUE(code)', 'Ethnicity code must be unique!'), ]
# -*- coding: utf-8 -*- # ############################################################################# # # Tech-Receptives Solutions Pvt. Ltd. # Copyright (C) 2004-TODAY Tech-Receptives(<http://www.techreceptives.com>) # Special Credit and Thanks to Thymbra Latinoamericana S.A. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # ############################################################################# from openerp import models, fields class MedicalPatientEthnicity(models.Model): _name = 'medical.patient.ethnicity' notes = fields.Char() code = fields.Char(required=True, ) name = fields.Char(required=True, translate=True) _sql_constraints = [ ('name_uniq', 'UNIQUE(name)', 'Ethnicity name must be unique!'), ('code_uniq', 'UNIQUE(code)', 'Ethnicity code must be unique!'), ]
Fix spelling of HTTP referer header
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const models = require('../models/index') const insecurity = require('../lib/insecurity') const utils = require('../lib/utils') const cache = require('../data/datacache') const challenges = cache.challenges module.exports = function updateUserProfile () { return (req, res, next) => { const loggedInUser = insecurity.authenticatedUsers.get(req.cookies.token) if (loggedInUser) { models.User.findByPk(loggedInUser.data.id).then(user => { utils.solveIf(challenges.csrfChallenge, () => { return ((req.headers.origin && req.headers.origin.includes('://htmledit.squarefree.com')) || (req.headers.referer && req.headers.referer.includes('://htmledit.squarefree.com'))) && req.body.username !== user.username }) return user.update({ username: req.body.username }) }).catch(error => { next(error) }) } else { next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress)) } res.location(process.env.BASE_PATH + '/profile') res.redirect(process.env.BASE_PATH + '/profile') } }
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const models = require('../models/index') const insecurity = require('../lib/insecurity') const utils = require('../lib/utils') const cache = require('../data/datacache') const challenges = cache.challenges module.exports = function updateUserProfile () { return (req, res, next) => { const loggedInUser = insecurity.authenticatedUsers.get(req.cookies.token) if (loggedInUser) { models.User.findByPk(loggedInUser.data.id).then(user => { utils.solveIf(challenges.csrfChallenge, () => { return ((req.headers.origin && req.headers.origin.includes('://htmledit.squarefree.com')) || (req.headers.referrer && req.headers.referrer.includes('://htmledit.squarefree.com'))) && req.body.username !== user.username }) return user.update({ username: req.body.username }) }).catch(error => { next(error) }) } else { next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress)) } res.location(process.env.BASE_PATH + '/profile') res.redirect(process.env.BASE_PATH + '/profile') } }
Use a more randomly made number for the system
package com.skelril.aurora.util; import java.util.Random; /** * @author Turtle9598 */ public class ChanceUtil { private static Random r = new Random(1374633257); public static int getRandom(int highestValue) { return highestValue < 0 ? (r.nextInt(highestValue * -1) + 1) * -1 : r.nextInt(highestValue) + 1; } public static int getRangedRandom(int lowestValue, int highestValue) { if (lowestValue == highestValue) return lowestValue; return lowestValue + getRandom(highestValue - lowestValue) - 1; } public static double getRandom(double highestValue) { if (highestValue < 0) { return (r.nextDouble() * (highestValue * -1) + 1) * -1; } return (r.nextDouble() * highestValue) + 1; } public static double getRangedRandom(double lowestValue, double highestValue) { if (lowestValue == highestValue) return lowestValue; return lowestValue + getRandom(highestValue - lowestValue) - 1; } public static boolean getChance(int outOf) { return getChance(1, outOf); } public static boolean getChance(int chance, int outOf) { return getRandom(outOf) <= chance; } }
package com.skelril.aurora.util; import java.util.Random; /** * @author Turtle9598 */ public class ChanceUtil { private static Random r = new Random(8888); public static int getRandom(int highestValue) { return highestValue < 0 ? (r.nextInt(highestValue * -1) + 1) * -1 : r.nextInt(highestValue) + 1; } public static int getRangedRandom(int lowestValue, int highestValue) { if (lowestValue == highestValue) return lowestValue; return lowestValue + getRandom(highestValue - lowestValue) - 1; } public static double getRandom(double highestValue) { if (highestValue < 0) { return (r.nextDouble() * (highestValue * -1) + 1) * -1; } return (r.nextDouble() * highestValue) + 1; } public static double getRangedRandom(double lowestValue, double highestValue) { if (lowestValue == highestValue) return lowestValue; return lowestValue + getRandom(highestValue - lowestValue) - 1; } public static boolean getChance(int outOf) { return getChance(1, outOf); } public static boolean getChance(int chance, int outOf) { return getRandom(outOf) <= chance; } }
Update problem 67 to be legible
# Project Euler Problem 67 def import_triangle(): with open('problem67.txt') as f: # Split each line by spaces and convert to integers return [list(map(int, line.split(' '))) for line in f] # The max of this row is the maximum sum up to its parent items plus the value # in this row. But note that the first and last items in this row only have one # parent each, so it can make the code a little funky to write. def get_max(last_maxes, cur): current_maxes = [cur[0] + last_maxes[0]] for idx, lm in enumerate(last_maxes): # Our left child was the right child of a previous element; get max max_for_left_child = cur[idx] + lm current_maxes[idx] = max(current_maxes[idx], max_for_left_child) # Right child hasn't been seen yet, just append it current_maxes.append(lm + cur[idx + 1]) return current_maxes def solve(): triangle = import_triangle() max_for_last_row = triangle[0] for current_row in triangle[1:]: max_for_last_row = get_max(max_for_last_row, current_row) print('Answer: {}'.format(max(max_for_last_row))) if __name__ == '__main__': solve()
# Project Euler Problem 67 # Created on: 2012-06-18 # Created by: William McDonald def importTri(): t = [] f = open("problem67.txt") for line in f: t.append(map(int, line.split(" "))) return t def getMax(lm, cur): l = len(cur) - 1 maxL = [lm[0] + cur[0]] i = 1 while True: if i == l: maxL.append(lm[i - 1] + cur[i]) break maxL.append(max((lm[i - 1]), lm[i]) + cur[i]) i += 1 return maxL def getAns(): t = importTri() lmax = t[0] for i in range(1, len(t)): lmax = getMax(lmax, t[i]) print(max(x for x in lmax)) getAns()
Add parse error test for bad URL case
package kitsu import ( "net/url" "testing" ) func TestNewClient(t *testing.T) { c := NewClient(nil) if got, want := c.BaseURL.String(), defaultBaseURL; got != want { t.Errorf("NewClient BaseURL is %v, want %v", got, want) } } func TestClient_NewRequest(t *testing.T) { c := NewClient(nil) inURL, outURL := "/foo", defaultBaseURL+"foo" req, _ := c.NewRequest("GET", inURL, nil) // Test that the client's base URL is added to the endpoint. if got, want := req.URL.String(), outURL; got != want { t.Errorf("NewRequest(%q) URL is %q, want %q", inURL, got, want) } } func TestClient_NewRequest_badURL(t *testing.T) { c := NewClient(nil) inURL := ":" _, err := c.NewRequest("GET", inURL, nil) if err == nil { t.Errorf("NewRequest(%q) should return parse err", inURL) } if err, ok := err.(*url.Error); !ok || err.Op != "parse" { t.Errorf("Expected URL parse error, got %+v", err) } }
package kitsu import "testing" func TestNewClient(t *testing.T) { c := NewClient(nil) if got, want := c.BaseURL.String(), defaultBaseURL; got != want { t.Errorf("NewClient BaseURL is %v, want %v", got, want) } } func TestNewRequest(t *testing.T) { c := NewClient(nil) inURL, outURL := "/foo", defaultBaseURL+"foo" req, _ := c.NewRequest("GET", inURL, nil) // Test that the base URL is added to the endpoint. if got, want := req.URL.String(), outURL; got != want { t.Errorf("NewRequest(%q) URL is %q, want %q", inURL, got, want) } } func TestClient_NewRequest_badEndpoint(t *testing.T) { c := NewClient(nil) inURL := "%foo" _, err := c.NewRequest("GET", inURL, nil) if err == nil { t.Errorf("NewRequest(%q) should return parse err", inURL) } }
Add support for brotli content encoding and alias for none
from setuptools import setup setup( name='icapservice', version='0.2.0', description='ICAP service library for Python', author='Giles Brown', author_email='giles_brown@hotmail.com', url='https://github.com/gilesbrown/icapservice', license='MIT', packages=['icapservice'], zip_safe=False, install_requires=['six', 'brotlipy'], include_package_data=True, package_data={'': ['LICENSE']}, classifiers=( 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', #'Programming Language :: Python :: 3', #'Programming Language :: Python :: 3.4', #'Programming Language :: Python :: 3.5', ), )
from setuptools import setup setup( name='icapservice', version='0.1.1', description='ICAP service library for Python', author='Giles Brown', author_email='giles_brown@hotmail.com', url='https://github.com/gilesbrown/icapservice', license='MIT', packages=['icapservice'], zip_safe=False, install_requires=['six', 'brotlipy'], include_package_data=True, package_data={'': ['LICENSE']}, classifiers=( 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', #'Programming Language :: Python :: 3', #'Programming Language :: Python :: 3.4', #'Programming Language :: Python :: 3.5', ), )
Fix testing if element exists.
$(function() { var cookieName = '_wheelmap_splash_seen'; var setCookie = function() { $.cookie(cookieName, true, { expires: 1000 }); }; if(!$.cookie(cookieName)) { var width = 600; // splash width // calculate left edge so it is centered var left = (0.5 - (width / 2)/($(window).width())) * 100 + '%'; if ($('#splash').length > 0 ){ $.blockUI({ message: $("#splash"), css: { top: '25%', left: left, width: width + 'px' } }); } var clickHandler = function() { $.unblockUI(); setCookie(); return false; }; $("#splash .unblock-splash").click(clickHandler); $('.blockOverlay').css('cursor', 'auto').click(clickHandler); $('a.whatis').click(function() { setCookie(); return true; }); } });
$(function() { var cookieName = '_wheelmap_splash_seen'; var setCookie = function() { $.cookie(cookieName, true, { expires: 1000 }); }; if(!$.cookie(cookieName)) { var width = 600; // splash width // calculate left edge so it is centered var left = (0.5 - (width / 2)/($(window).width())) * 100 + '%'; if (!$('#splash').is(':empty')){ $.blockUI({ message: $("#splash"), css: { top: '25%', left: left, width: width + 'px' } }); } var clickHandler = function() { $.unblockUI(); setCookie(); return false; }; $("#splash .unblock-splash").click(clickHandler); $('.blockOverlay').css('cursor', 'auto').click(clickHandler); $('a.whatis').click(function() { setCookie(); return true; }); } });
Check query string for access_token before checking in headers
module.exports = function (req) { function getParam(paramName) { if (req.query && typeof req.query[paramName] !== 'undefined') return req.query[paramName]; else if (req.body && typeof req.body[paramName] !== 'undefined') return req.body[paramName]; else return null; }; function getAccessToken() { if (getParam('access_token')) return getParam('access_token') if (!req || !req.headers || !req.headers.authorization) return null; var authHeader = req.headers.authorization, startIndex = authHeader.toLowerCase().indexOf('bearer '); if (startIndex === -1) return null; var bearer = authHeader.substring(startIndex + 7), spaceIndex = bearer.indexOf(' '); if (spaceIndex > 0) bearer = bearer.substring(0, spaceIndex); return bearer; }; return req ? { responseType: getParam('response_type'), clientId: getParam('client_id'), clientSecret: getParam('client_secret'), code: getParam('code'), grantType: getParam('grant_type'), state: getParam('state'), password: getParam('password'), scope: getParam('scope') ? getParam('scope').split(',') : null, redirectUri: getParam('redirect_uri'), accessToken: getAccessToken(), userName: getParam('username') } : null; };
module.exports = function (req) { function getParam(paramName) { if (req.query && typeof req.query[paramName] !== 'undefined') return req.query[paramName]; else if (req.body && typeof req.body[paramName] !== 'undefined') return req.body[paramName]; else return null; }; function getAccessToken() { if (!req || !req.headers || !req.headers.authorization) return null; var authHeader = req.headers.authorization, startIndex = authHeader.toLowerCase().indexOf('bearer '); if (startIndex === -1) return null; var bearer = authHeader.substring(startIndex + 7), spaceIndex = bearer.indexOf(' '); if (spaceIndex > 0) bearer = bearer.substring(0, spaceIndex); return bearer; }; return req ? { responseType: getParam('response_type'), clientId: getParam('client_id'), clientSecret: getParam('client_secret'), code: getParam('code'), grantType: getParam('grant_type'), state: getParam('state'), password: getParam('password'), scope: getParam('scope') ? getParam('scope').split(',') : null, redirectUri: getParam('redirect_uri'), accessToken: getAccessToken(), userName: getParam('username') } : null; };
Add load communication in /jobs
<?php /** Copyright (C) 2010-2016 by the FusionInventory Development Team Copyright (C) 2016 Teclib' This file is part of Armadito Plugin for GLPI. Armadito Plugin for GLPI is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Armadito Plugin for GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>. **/ include_once ("../../../../inc/includes.php"); if (isset($_GET['agent_id'])) { // GET /jobs include_once("../../front/communication.php"); $communication = new PluginArmaditoCommunication(); $communication->init(); session_destroy(); } else{ http_response_code(400); header("Content-Type: application/json"); echo '{ "plugin_response" : { "version": "'.PLUGIN_ARMADITO_VERSION.'", "error": "Invalid request sent to plugin index." }}'; } ?>
<?php /** Copyright (C) 2010-2016 by the FusionInventory Development Team Copyright (C) 2016 Teclib' This file is part of Armadito Plugin for GLPI. Armadito Plugin for GLPI is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Armadito Plugin for GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>. **/ include_once ("../../../../inc/includes.php"); if (isset($_GET['agent_id'])) { // GET /jobs include_once("../../front/communication.php"); session_destroy(); } else{ http_response_code(400); header("Content-Type: application/json"); echo '{ "plugin_response" : { "version": "'.PLUGIN_ARMADITO_VERSION.'", "error": "Invalid request sent to plugin index." }}'; } ?>
Add raw option (even if ignored by esprima 1.1.x)
/** * power-assert - Empower your assertions * * https://github.com/twada/power-assert * * Copyright (c) 2013-2014 Takuto Wada * Licensed under the MIT license. * https://raw.github.com/twada/power-assert/master/MIT-LICENSE.txt */ var espower = require('espower'), esprima = require('esprima'), escodegen = require('escodegen'), argv = require('optimist').argv, fs = require('fs'), options = {}, file = argv._[0], path = fs.realpathSync(file), source = fs.readFileSync(file, 'utf-8'), tree = esprima.parse(source, {tolerant: true, loc: true, tokens: true, raw: true, source: path}); if (argv.powerAssertVariableName) { options['powerAssertVariableName'] = argv.powerAssertVariableName; } options['path'] = path; options['source'] = source; tree = espower(tree, options); console.log(escodegen.generate(tree));
/** * power-assert - Empower your assertions * * https://github.com/twada/power-assert * * Copyright (c) 2013-2014 Takuto Wada * Licensed under the MIT license. * https://raw.github.com/twada/power-assert/master/MIT-LICENSE.txt */ var espower = require('espower'), esprima = require('esprima'), escodegen = require('escodegen'), argv = require('optimist').argv, fs = require('fs'), options = {}, file = argv._[0], path = fs.realpathSync(file), source = fs.readFileSync(file, 'utf-8'), tree = esprima.parse(source, {tolerant: true, loc: true, range: true, tokens: true}); if (argv.powerAssertVariableName) { options['powerAssertVariableName'] = argv.powerAssertVariableName; } options['path'] = path; options['source'] = source; tree = espower(tree, options); console.log(escodegen.generate(tree));
Update delayJob test to use TimeKeeper
'use strict'; require('../helpers'); const assert = require('assert'); const Ironium = require('../..'); const ms = require('ms'); const TimeKeeper = require('timekeeper'); describe('Queue with delay', function() { const captureQueue = Ironium.queue('capture'); // Capture processed jobs here. const processed = []; before(function() { captureQueue.eachJob(function(job) { processed.push(job); return Promise.resolve(); }); }); before(function() { return captureQueue.delayJob('delayed', '2m'); }); before(Ironium.runOnce); it('should not process immediately', function() { assert.equal(processed.length, 0); }); describe('after 1 minute', function() { before(function() { TimeKeeper.travel(Date.now() + ms('1m')); }); before(Ironium.runOnce); it('should not process job', function() { assert.equal(processed.length, 0); }); }); describe('after 2 minutes', function() { before(function() { TimeKeeper.travel(Date.now() + ms('2m')); }); before(Ironium.runOnce); it('should process job', function() { assert.equal(processed.length, 1); assert.equal(processed[0], 'delayed'); }); }); });
'use strict'; require('../helpers'); const assert = require('assert'); const Ironium = require('../..'); describe('Queue with delay', function() { const captureQueue = Ironium.queue('capture'); // Capture processed jobs here. const processed = []; before(function() { captureQueue.eachJob(function(job) { processed.push(job); return Promise.resolve(); }); }); before(function() { return captureQueue.delayJob('delayed', '2s'); }); before(Ironium.runOnce); it('should not process immediately', function() { assert.equal(processed.length, 0); }); describe('after short delay', function() { before(function(done) { setTimeout(done, 1500); }); before(Ironium.runOnce); it('should not process job', function() { assert.equal(processed.length, 0); }); }); describe('after sufficient delay', function() { before(function(done) { setTimeout(done, 1000); }); before(Ironium.runOnce); it('should process job', function() { assert.equal(processed.length, 1); assert.equal(processed[0], 'delayed'); }); }); });
Enable markdown for PyPI README
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests']) raise SystemExit(errno) with open('README.md') as readme: long_description = readme.read() setup( name='parserutils', description='A collection of performant parsing utilities', long_description=long_description, long_description_content_type='text/markdown', keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml', version='1.1.2', packages=[ 'parserutils', 'parserutils.tests' ], install_requires=[ 'defusedxml>=0.4.1', 'python-dateutil>=2.4.2', 'six>=1.9.0' ], url='https://github.com/consbio/parserutils', license='BSD', cmdclass={'test': RunTests} )
import subprocess import sys from setuptools import Command, setup class RunTests(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests']) raise SystemExit(errno) with open('README.md') as readme: long_description = readme.read() setup( name='parserutils', description='A collection of performant parsing utilities', long_description=long_description, keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml', version='1.1.1', packages=[ 'parserutils', 'parserutils.tests' ], install_requires=[ 'defusedxml>=0.4.1', 'python-dateutil>=2.4.2', 'six>=1.9.0' ], url='https://github.com/consbio/parserutils', license='BSD', cmdclass={'test': RunTests} )
Add object method instead of the property
const Reporter = require('./src/Reporter'); const PostReporter = require('./src/PostReport'); const Verification = require('./src/Verification'); const Joi = require('joi'); module.exports = [ { method: 'GET', path: '/report/', handler: Reporter, config: { validate: { query: { hipchat: Joi.string().required(), site: Joi.string().uri().required(), } } } }, { method: 'POST', path: '/report/', handler: PostReporter, config: { validate: { payload: Joi.object().keys({ item: Joi.object().required(), }), } } }, { method: 'GET', path: '/verification/{hipchat}/', handler: Verification, config: { validate: { query: { id: Joi.required(), } } } } ]
const Reporter = require('./src/Reporter'); const PostReporter = require('./src/PostReport'); const Verification = require('./src/Verification'); const Joi = require('joi'); module.exports = [ { method: 'GET', path: '/report/', handler: Reporter, config: { validate: { query: { hipchat: Joi.string().required(), site: Joi.string().uri().required(), } } } }, { method: 'POST', path: '/report/', handler: PostReporter, config: { validate: { payload: Joi.object().keys({ item: Joi.object.required(), }), } } }, { method: 'GET', path: '/verification/{hipchat}/', handler: Verification, config: { validate: { query: { id: Joi.required(), } } } } ]
Migrate link tests to pytest
from unittest.mock import MagicMock from buffpy.models.link import Link def test_links_shares(): """ Test link"s shares retrieving from constructor. """ mocked_api = MagicMock() mocked_api.get.return_value = {"shares": 123} link = Link(api=mocked_api, url="www.google.com") assert link["shares"] == 123 assert link["url"] == "www.google.com" mocked_api.get.assert_called_once_with(url="links/shares.json?url=www.google.com") def test_links_get_shares(): """ Test link"s shares retrieving method. """ mocked_api = MagicMock() mocked_api.get.return_value = {"shares": 123} link = Link(api=mocked_api, url="www.google.com") assert link["shares"] == 123 assert link["url"] == "www.google.com" assert link.get_shares() == 123 mocked_api.get.assert_any_call(url="links/shares.json?url=www.google.com") assert mocked_api.get.call_count == 2
from nose.tools import eq_ from mock import MagicMock from buffpy.models.link import Link def test_links_shares(): ''' Test link's shares retrieving from constructor ''' mocked_api = MagicMock() mocked_api.get.return_value = {'shares': 123} link = Link(api=mocked_api, url='www.google.com') eq_(link, {'shares': 123, 'url': 'www.google.com', 'api': mocked_api}) mocked_api.get.assert_called_once_with(url='links/shares.json?url=www.google.com') def test_links_get_shares(): ''' Test link's shares retrieving method ''' mocked_api = MagicMock() mocked_api.get.return_value = {'shares': 123} link = Link(api=mocked_api, url='www.google.com') eq_(link, {'shares': 123, 'url': 'www.google.com', 'api': mocked_api}) eq_(link.get_shares(), 123) mocked_api.get.assert_any_call(url='links/shares.json?url=www.google.com') eq_(mocked_api.get.call_count, 2)
refactor(settings): Remove extra withTheme hoc on styled components.
/* @flow */ import React from 'react' import styled from 'styled-components' import Label from 'components/Label' import Input from 'components/Input' import editable from 'hoc/editable' type Props = { name: string, onChange: Function } const Editable = editable( styled.div` position: relative; line-height: 3.6rem; background: transparent; border: none; border-radius: 0; padding-left: 0; border-bottom: 1px solid ${props => props.theme.borderColor}; color: ${props => props.theme.color}; margin: 0 0 1.2rem; width: 100%; &:hover { cursor: pointer; } ` ) const NameInput = Input.extend` background: transparent; border: none; border-bottom: 1px solid ${props => props.theme.borderColor}; color: ${props => props.theme.color}; margin: 0 0 1.2rem; width: 100%; padding: 0; ` const Name = (props: Props) => { return ( <div> <Label>Display Name:</Label> <Editable isHovering={true} value={props.name} input={NameInput} onChange={props.onChange} /> </div> ) } export default Name
/* @flow */ import React from 'react' import styled, { withTheme } from 'styled-components' import Label from 'components/Label' import Input from 'components/Input' import editable from 'hoc/editable' type Props = { name: string, onChange: Function } const Editable = editable( withTheme(styled.div` position: relative; line-height: 3.6rem; background: transparent; border: none; border-radius: 0; padding-left: 0; border-bottom: 1px solid ${props => props.theme.borderColor}; color: ${props => props.theme.color}; margin: 0 0 1.2rem; width: 100%; &:hover { cursor: pointer; } `) ) const NameInput = withTheme(Input.extend` background: transparent; border: none; border-bottom: 1px solid ${props => props.theme.borderColor}; color: ${props => props.theme.color}; margin: 0 0 1.2rem; width: 100%; padding: 0; `) const Name = (props: Props) => { return ( <div> <Label>Display Name:</Label> <Editable isHovering={true} value={props.name} input={NameInput} onChange={props.onChange} /> </div> ) } export default Name
migrations: Disable atomic for delivery_email migration. I'm not sure theoretically why this should be required only for some installations, but these articles all suggest the root problem is doing these two migrations together atomically (creating the field and setting a value for it), so the right answer is to declare the migration as not atomic: https://stackoverflow.com/questions/12838111/django-db-migrations-cannot-alter-table-because-it-has-pending-trigger-events https://confluence.atlassian.com/confkb/upgrade-failed-with-the-error-message-error-cannot-alter-table-content-because-it-has-pending-trigger-events-747606853.html
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-07-05 17:57 from __future__ import unicode_literals from django.db import migrations, models from django.apps import apps from django.db.models import F from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def copy_email_field(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: UserProfile = apps.get_model('zerver', 'UserProfile') UserProfile.objects.all().update(delivery_email=F('email')) class Migration(migrations.Migration): atomic = False dependencies = [ ('zerver', '0173_support_seat_based_plans'), ] operations = [ migrations.AddField( model_name='userprofile', name='delivery_email', field=models.EmailField(db_index=True, default='', max_length=254), preserve_default=False, ), migrations.RunPython(copy_email_field, reverse_code=migrations.RunPython.noop), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-07-05 17:57 from __future__ import unicode_literals from django.db import migrations, models from django.apps import apps from django.db.models import F from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def copy_email_field(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: UserProfile = apps.get_model('zerver', 'UserProfile') UserProfile.objects.all().update(delivery_email=F('email')) class Migration(migrations.Migration): dependencies = [ ('zerver', '0173_support_seat_based_plans'), ] operations = [ migrations.AddField( model_name='userprofile', name='delivery_email', field=models.EmailField(db_index=True, default='', max_length=254), preserve_default=False, ), migrations.RunPython(copy_email_field, reverse_code=migrations.RunPython.noop), ]
Put language modal in alphabetical order LMS-2302
""" Models for the dark-launching languages """ from django.db import models from config_models.models import ConfigurationModel class DarkLangConfig(ConfigurationModel): """ Configuration for the dark_lang django app """ released_languages = models.TextField( blank=True, help_text="A comma-separated list of language codes to release to the public." ) @property def released_languages_list(self): """ ``released_languages`` as a list of language codes. Example: ['it', 'de-at', 'es', 'pt-br'] """ if not self.released_languages.strip(): # pylint: disable=no-member return [] languages = [lang.strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member # Put in alphabetical order languages.sort() return languages
""" Models for the dark-launching languages """ from django.db import models from config_models.models import ConfigurationModel class DarkLangConfig(ConfigurationModel): """ Configuration for the dark_lang django app """ released_languages = models.TextField( blank=True, help_text="A comma-separated list of language codes to release to the public." ) @property def released_languages_list(self): """ ``released_languages`` as a list of language codes. Example: ['it', 'de-at', 'es', 'pt-br'] """ if not self.released_languages.strip(): # pylint: disable=no-member return [] return [lang.strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member
fix(checkbox): Change default value for indeterminate
import {CheckableComponentViewModel} from './mdc-knockout-base'; import template from './templates/checkbox.html'; export default class CheckboxViewModel extends CheckableComponentViewModel { initialize () { const checked = this.bindings.checked; const instance = this.instance(); instance.indeterminate = ko.unwrap(this.indeterminate); if (ko.isSubscribable(this.indeterminate)) { this.track = this.indeterminate.subscribe( value => { if (value) instance.indeterminate = true } ); if (ko.isSubscribable(checked)) { this.track = checked.subscribe(value => { this.indeterminate(false); if (instance.indeterminate) { instance.indeterminate = false; } }); } } } defaultParams () { return { indeterminate: false } } static get TEMPLATE () { return template(); } }
import {CheckableComponentViewModel} from './mdc-knockout-base'; import template from './templates/checkbox.html'; export default class CheckboxViewModel extends CheckableComponentViewModel { initialize () { const checked = this.bindings.checked; const instance = this.instance(); instance.indeterminate = ko.unwrap(this.indeterminate); if (ko.isSubscribable(this.indeterminate)) { this.track = this.indeterminate.subscribe( value => { if (value) instance.indeterminate = true } ); if (ko.isSubscribable(checked)) { this.track = checked.subscribe(value => { this.indeterminate(false); if (instance.indeterminate) { instance.indeterminate = false; } }); } } } defaultParams () { return { indeterminate: true } } static get TEMPLATE () { return template(); } }
Increase Core and Maximum ThreadPool Size
package sg.ncl; import nz.net.ultraq.thymeleaf.LayoutDialect; import org.springframework.boot.autoconfigure.web.ErrorAttributes; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.validation.constraints.NotNull; /** * @author by Te Ye * @updated by James, 27-Dec-2017 * * References: * [1] https://www.mkyong.com/spring/spring-and-java-thread-example/ */ @Configuration("sg.ncl.AppConfig") public class AppConfig { @Bean public AppErrorController appErrorController(@NotNull ErrorAttributes errorAttributes) { return new AppErrorController(errorAttributes); } // thymleaf-layout-dialect // for fragments @Bean public LayoutDialect layoutDialect() { return new LayoutDialect(); } @Bean public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); pool.setCorePoolSize(10); pool.setMaxPoolSize(100); pool.setWaitForTasksToCompleteOnShutdown(true); return pool; } }
package sg.ncl; import nz.net.ultraq.thymeleaf.LayoutDialect; import org.springframework.boot.autoconfigure.web.ErrorAttributes; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.validation.constraints.NotNull; /** * @author by Te Ye * @updated by James, 27-Dec-2017 * * References: * [1] https://www.mkyong.com/spring/spring-and-java-thread-example/ */ @Configuration("sg.ncl.AppConfig") public class AppConfig { @Bean public AppErrorController appErrorController(@NotNull ErrorAttributes errorAttributes) { return new AppErrorController(errorAttributes); } // thymleaf-layout-dialect // for fragments @Bean public LayoutDialect layoutDialect() { return new LayoutDialect(); } @Bean public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); pool.setCorePoolSize(5); pool.setMaxPoolSize(10); pool.setWaitForTasksToCompleteOnShutdown(true); return pool; } }
Update capabilities to fix fetch detection in chrome Spec now uses ReadableStream rather than ReadableByteStream. In chrome ReadableByteStream is no longer available on window so the existing check in capabilities for fetch was failing. The fix is to check both.
exports.fetch = isFunction(window.fetch) && (isFunction(window.ReadableStream) || isFunction(window.ReadableByteStream)) exports.blobConstructor = false try { new Blob([new ArrayBuffer(1)]) exports.blobConstructor = true } catch (e) {} var xhr = new window.XMLHttpRequest() xhr.open('GET', '/') function checkTypeSupport (type) { try { xhr.responseType = type return xhr.responseType === type } catch (e) {} return false } var haveArrayBuffer = isFunction(window.ArrayBuffer) var haveSlice = haveArrayBuffer && isFunction(window.ArrayBuffer.prototype.slice) exports.arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer') exports.msstream = haveSlice && checkTypeSupport('ms-stream') exports.mozchunkedarraybuffer = haveArrayBuffer && checkTypeSupport('moz-chunked-arraybuffer') exports.overrideMimeType = isFunction(xhr.overrideMimeType) exports.vbArray = isFunction(window.VBArray) function isFunction (value) { return typeof value === 'function' } xhr = null // Help gc
exports.fetch = isFunction(window.fetch) && isFunction(window.ReadableByteStream) exports.blobConstructor = false try { new Blob([new ArrayBuffer(1)]) exports.blobConstructor = true } catch (e) {} var xhr = new window.XMLHttpRequest() xhr.open('GET', '/') function checkTypeSupport (type) { try { xhr.responseType = type return xhr.responseType === type } catch (e) {} return false } var haveArrayBuffer = isFunction(window.ArrayBuffer) var haveSlice = haveArrayBuffer && isFunction(window.ArrayBuffer.prototype.slice) exports.arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer') exports.msstream = haveSlice && checkTypeSupport('ms-stream') exports.mozchunkedarraybuffer = haveArrayBuffer && checkTypeSupport('moz-chunked-arraybuffer') exports.overrideMimeType = isFunction(xhr.overrideMimeType) exports.vbArray = isFunction(window.VBArray) function isFunction (value) { return typeof value === 'function' } xhr = null // Help gc
Use an atomic update operation
// TODO: should the baseScore be stored, and updated at vote time? // This interface should change and become more OO, this'll do for now var Scoring = { // re-run the scoring algorithm on a single object updateObject: function(object) { // just count the number of votes for now var baseScore = object.votes; // now multiply by 'age' exponentiated // FIXME: timezones <-- set by server or is getTime() ok? var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000); object.score = baseScore * Math.pow(ageInHours + 2, -0.1375); }, // rerun all the scoring updateScores: function() { Posts.find().forEach(function(post) { Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); }); } } Meteor.methods({ voteForPost: function(post){ var userId = this.userId(); if(!userId) return false; // atomically update the post's votes var query = {_id: post._id, voters: {$ne: userId}}; var update = {$push: {voters: userId}, $inc: {votes: 1}}; Posts.update(query, update); // now update the post's score post = Posts.findOne(post._id); Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); return true; } });
// TODO: should the baseScore be stored, and updated at vote time? // This interface should change and become more OO, this'll do for now var Scoring = { // re-run the scoring algorithm on a single object updateObject: function(object) { // just count the number of votes for now var baseScore = MyVotes.find({votedFor: object._id}).count(); // now multiply by 'age' exponentiated // FIXME: timezones <-- set by server or is getTime() ok? var ageInHours = (new Date().getTime() - object.submitted) / (60 * 60 * 1000); object.score = baseScore * Math.pow(ageInHours + 2, -0.1375); }, // rerun all the scoring updateScores: function() { Posts.find().forEach(function(post) { Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); }); } } Meteor.methods({ voteForPost: function(post){ var user = this.userId(); if(!user) return false; var myvote = MyVotes.findOne({votedFor: post._id, user: user}); if(myvote) return false; MyVotes.insert({votedFor: post._id, user: user, vote: 1}); Scoring.updateObject(post); Posts.update(post._id, {$set: {score: post.score}}); return true; } });
Set comp info boxes opened as default
'use strict'; angular.module('konehuone.competitionInfos') .controller('CompetitionInfosCtrl', function ($scope, lodash, apiService) { var _ = lodash; // # Variables $scope.uiClosed = { jj1: false, jj2: false, rc: false }; $scope.compData = {}; $scope.igImages = []; // # Functions $scope.init = function() { apiService.getCompetitionData().then( function success(compData) { _.extend($scope.compData, compData); } ); apiService.getLatestIgImages().then( function success(igImages) { $scope.igImages = igImages; } ); }; });
'use strict'; angular.module('konehuone.competitionInfos') .controller('CompetitionInfosCtrl', function ($scope, lodash, apiService) { var _ = lodash; // # Variables $scope.uiClosed = { jj1: true, jj2: true, rc: true }; $scope.compData = {}; $scope.igImages = []; // # Functions $scope.init = function() { apiService.getCompetitionData().then( function success(compData) { _.extend($scope.compData, compData); } ); apiService.getLatestIgImages().then( function success(igImages) { $scope.igImages = igImages; } ); }; });
Fix bug where admin panel was redirected to semesterpage app
"""kokekunster URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from semesterpage.views import semester, user_request urlpatterns = [ url(r'^$', include('semesterpage.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')), ]
"""kokekunster URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin from semesterpage.views import semester, user_request urlpatterns = [ url(r'^$', include('semesterpage.urls')), url(r'^(?P<program_code>\w{3,6})/', include('semesterpage.urls')), url(r'^admin/', include(admin.site.urls)), ]
Revert "Don't start crash reporter on Windows." This reverts commit 684f15ab89eae5088688955721876271798d9b38.
window.onload = function() { var path = require('path'); var ipc = require('ipc'); try { // Skip "?loadSettings=". var loadSettings = JSON.parse(decodeURIComponent(location.search.substr(14))); // Start the crash reporter before anything else. require('crash-reporter').start({ productName: 'Atom', companyName: 'GitHub', // By explicitly passing the app version here, we could save the call // of "require('remote').require('app').getVersion()". extra: {_version: loadSettings.appVersion} }); require('vm-compatibility-layer'); require('coffee-script').register(); require(path.resolve(__dirname, '..', 'src', 'coffee-cache')).register(); require(loadSettings.bootstrapScript); ipc.sendChannel('window-command', 'window:loaded') } catch (error) { var currentWindow = require('remote').getCurrentWindow(); currentWindow.setSize(800, 600); currentWindow.center(); currentWindow.show(); currentWindow.openDevTools(); console.error(error.stack || error); } }
window.onload = function() { var path = require('path'); var ipc = require('ipc'); try { // Skip "?loadSettings=". var loadSettings = JSON.parse(decodeURIComponent(location.search.substr(14))); // Start the crash reporter before anything else. if (process.platform != 'win32') require('crash-reporter').start({ productName: 'Atom', companyName: 'GitHub', // By explicitly passing the app version here, we could save the call // of "require('remote').require('app').getVersion()". extra: {_version: loadSettings.appVersion} }); require('vm-compatibility-layer'); require('coffee-script').register(); require(path.resolve(__dirname, '..', 'src', 'coffee-cache')).register(); require(loadSettings.bootstrapScript); ipc.sendChannel('window-command', 'window:loaded') } catch (error) { var currentWindow = require('remote').getCurrentWindow(); currentWindow.setSize(800, 600); currentWindow.center(); currentWindow.show(); currentWindow.openDevTools(); console.error(error.stack || error); } }
Save output language after conversion.
/* Extracts the code elements and returns array of source-code and code elements */ export default function convertSourceCode(el, converter) { let miniSource = el.find('code[language=mini]') let nativeSource = el.find('code:not([language=mini])') let output = el.find('code[specific-use=output]') let miniSourceText let result = [] if (miniSource) { miniSourceText = miniSource.textContent } else if (nativeSource) { // We make up mini source string if not present miniSourceText = nativeSource.attr('language')+'()' } else { converter.error({ msg: 'Either code[lanuage=mini] or code:not([language=mini]) must be provided', el: el }) } result.push( el.createElement('source-code').attr('language', 'mini').append( miniSourceText ) ) if (nativeSource) { result.push( el.createElement('source-code').attr('language', nativeSource.attr('language')).append( nativeSource.textContent ) ) } result.push( el.createElement('output').attr('language', output.attr('language')).append( output.textContent ) ) return result }
/* Extracts the code elements and returns array of source-code and code elements */ export default function convertSourceCode(el, converter) { let miniSource = el.find('code[language=mini]') let nativeSource = el.find('code:not([language=mini])') let output = el.find('code[specific-use=output]') let miniSourceText let result = [] if (miniSource) { miniSourceText = miniSource.textContent } else if (nativeSource) { // We make up mini source string if not present miniSourceText = nativeSource.attr('language')+'()' } else { converter.error({ msg: 'Either code[lanuage=mini] or code:not([language=mini]) must be provided', el: el }) } result.push( el.createElement('source-code').attr('language', 'mini').append( miniSourceText ) ) if (nativeSource) { result.push( el.createElement('source-code').attr('language', nativeSource.attr('language')).append( nativeSource.textContent ) ) } result.push( el.createElement('output').append(output.textContent) ) return result }
Handle case where rule shows before severity Thank you @suprMax !
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Brewer # Copyright (c) 2015 Jack Brewer # # License: MIT """Exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" npm_name = 'stylint' syntax = ('stylus', 'vue') selectors = {'vue': 'source.stylus.embedded.html'} cmd = 'stylint @ *' executable = 'stylint' version_requirement = '>= 1.5.0' regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable ^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Brewer # Copyright (c) 2015 Jack Brewer # # License: MIT """Exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" npm_name = 'stylint' syntax = ('stylus', 'vue') selectors = {'vue': 'source.stylus.embedded.html'} cmd = 'stylint @ *' executable = 'stylint' version_requirement = '>= 1.5.0' regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable ^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
Fix a wrong line problem This problem will cause compilation error when after license header formatting, which is caused by the package line removed.
/** * Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy) * * 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 org.commonjava.indy.bind.jaxrs; import javax.enterprise.context.ApplicationScoped; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @ApplicationScoped public class SlashTolerationFilter implements Filter { @Override public void init( final FilterConfig filterConfig ) throws ServletException { } @Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException { final HttpServletRequest hsr = (HttpServletRequest) servletRequest; String newURI = hsr.getRequestURI().replaceAll( "/+", "/" ); servletRequest.getRequestDispatcher(newURI).forward(servletRequest, servletResponse); } @Override public void destroy() { } }
/** * Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy) * * 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 javax.enterprise.context.ApplicationScoped; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @ApplicationScoped public class SlashTolerationFilter implements Filter { @Override public void init( final FilterConfig filterConfig ) throws ServletException { } @Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException { final HttpServletRequest hsr = (HttpServletRequest) servletRequest; String newURI = hsr.getRequestURI().replaceAll( "/+", "/" ); servletRequest.getRequestDispatcher(newURI).forward(servletRequest, servletResponse); } @Override public void destroy() { } }
Remove temporary test for ResultDetailCtrl
/** * 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. */ 'use strict'; describe('Controller: ResultdetailCtrl', function () { // load the controller's module beforeEach(module('ocwUiApp')); var ResultdetailCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); ResultdetailCtrl = $controller('ResultdetailCtrl', { $scope: scope }); })); });
/** * 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. */ 'use strict'; describe('Controller: ResultdetailCtrl', function () { // load the controller's module beforeEach(module('ocwUiApp')); var ResultdetailCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); ResultdetailCtrl = $controller('ResultdetailCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
Remove self references from setup/teardown
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_get_user_config -------------------- Tests formerly known from a unittest residing in test_config.py named """ import os import shutil import pytest @pytest.fixture(scope='function') def back_up_rc(request): """ Back up an existing cookiecutter rc and restore it after the test. If ~/.cookiecutterrc is pre-existing, move it to a temp location """ user_config_path = os.path.expanduser('~/.cookiecutterrc') user_config_path_backup = os.path.expanduser( '~/.cookiecutterrc.backup' ) if os.path.exists(user_config_path): shutil.copy(user_config_path, user_config_path_backup) os.remove(user_config_path) def restore_rc(): """ If it existed, restore ~/.cookiecutterrc """ if os.path.exists(user_config_path_backup): shutil.copy(user_config_path_backup, user_config_path) os.remove(user_config_path_backup) request.addfinalizer(restore_rc)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_get_user_config -------------------- Tests formerly known from a unittest residing in test_config.py named """ import pytest @pytest.fixture(scope='function') def back_up_rc(request): """ Back up an existing cookiecutter rc and restore it after the test. If ~/.cookiecutterrc is pre-existing, move it to a temp location """ self.user_config_path = os.path.expanduser('~/.cookiecutterrc') self.user_config_path_backup = os.path.expanduser( '~/.cookiecutterrc.backup' ) if os.path.exists(self.user_config_path): shutil.copy(self.user_config_path, self.user_config_path_backup) os.remove(self.user_config_path) def restore_rc(): """ If it existed, restore ~/.cookiecutterrc """ if os.path.exists(self.user_config_path_backup): shutil.copy(self.user_config_path_backup, self.user_config_path) os.remove(self.user_config_path_backup) request.addfinalizer(restore_rc)
Set up the production environment of heap analytics instead of development
window.heap = window.heap || [], heap.load = function(t, e) { window.heap.appid = t, window.heap.config = e; var a = document.createElement("script"); a.type = "text/javascript", a.async = !0, a.src = ("https:" === document.location.protocol ? "https:" : "http:") + "//cdn.heapanalytics.com/js/heap.js"; var n = document.getElementsByTagName("script")[0]; n.parentNode.insertBefore(a, n); for (var o = function(t) { return function() { heap.push([t].concat(Array.prototype.slice.call(arguments, 0))) } }, p = ["clearEventProperties", "identify", "setEventProperties", "track", "unsetEventProperty"], c = 0; c < p.length; c++) heap[p[c]] = o(p[c]) }; heap.load("3770493230");
window.heap = window.heap || [], heap.load = function(t, e) { window.heap.appid = t, window.heap.config = e; var a = document.createElement("script"); a.type = "text/javascript", a.async = !0, a.src = ("https:" === document.location.protocol ? "https:" : "http:") + "//cdn.heapanalytics.com/js/heap.js"; var n = document.getElementsByTagName("script")[0]; n.parentNode.insertBefore(a, n); for (var o = function(t) { return function() { heap.push([t].concat(Array.prototype.slice.call(arguments, 0))) } }, p = ["clearEventProperties", "identify", "setEventProperties", "track", "unsetEventProperty"], c = 0; c < p.length; c++) heap[p[c]] = o(p[c]) }; heap.load("123010716");
Make tag classes functions non-anonymous
iD.svg.TagClasses = function() { var keys = iD.util.trueObj([ 'highway', 'railway', 'motorway', 'amenity', 'natural', 'landuse', 'building', 'oneway', 'bridge' ]), tagClassRe = /^tag-/; return function tagClassesSelection(selection) { selection.each(function tagClassesEach(d, i) { var classes, value = this.className; if (value.baseVal !== undefined) value = value.baseVal; classes = value.trim().split(/\s+/).filter(function(name) { return name.length && !tagClassRe.test(name); }); var tags = d.tags; for (var k in tags) { if (!keys[k]) continue; classes.push('tag-' + k); classes.push('tag-' + k + '-' + tags[k]); } return this.className = classes.join(' '); }); }; };
iD.svg.TagClasses = function() { var keys = iD.util.trueObj([ 'highway', 'railway', 'motorway', 'amenity', 'natural', 'landuse', 'building', 'oneway', 'bridge' ]), tagClassRe = /^tag-/; return function(selection) { selection.each(function(d, i) { var classes, value = this.className; if (value.baseVal !== undefined) value = value.baseVal; classes = value.trim().split(/\s+/).filter(function(name) { return name.length && !tagClassRe.test(name); }); var tags = d.tags; for (var k in tags) { if (!keys[k]) continue; classes.push('tag-' + k); classes.push('tag-' + k + '-' + tags[k]); } return d3.select(this).attr('class', classes.join(' ')); }); }; };
Improve thread safety around adding and removing IDataListener's Previously deadlock was possible if a listener was running in the same thread as a call attempting to add or remove listeners. As might be commonly the case for the UI thread. Also replaced the listeners List with a Set to prevent duplicate listeners being added. Using a set backed by a ConcurrentHashMap should allow all operation to complete safely without requiring external synchronized, this allows the methods in the class to be simplified. Signed-off-by: James Mudd <50b9fff9a292b5df2aef2220dca201538f796e13@diamond.ac.uk>
/*- * Copyright 2015, 2016 Diamond Light Source Ltd. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.january.dataset; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Class used by DynamicDataset to delegate */ public class DataListenerDelegate { private Set<IDataListener> listeners; public DataListenerDelegate() { listeners = Collections.newSetFromMap(new ConcurrentHashMap<IDataListener, Boolean>()); } public void addDataListener(IDataListener l) { listeners.add(l); } public void removeDataListener(IDataListener l) { listeners.remove(l); } public void fire(DataEvent evt) { for (IDataListener listener : listeners) { listener.dataChangePerformed(evt); } } public boolean hasDataListeners() { return listeners.size() > 0; } public void clear() { listeners.clear(); } }
/*- * Copyright 2015, 2016 Diamond Light Source Ltd. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.january.dataset; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Class used by DynamicDataset to delegate */ public class DataListenerDelegate { private List<IDataListener> listeners; public DataListenerDelegate() { listeners = Collections.synchronizedList(new ArrayList<IDataListener>()); } public void addDataListener(IDataListener l) { synchronized (listeners) { if (!listeners.contains(l)) { listeners.add(l); } } } public void removeDataListener(IDataListener l) { listeners.remove(l); } public void fire(DataEvent evt) { synchronized (listeners) { for (Iterator<IDataListener> iterator = listeners.iterator(); iterator.hasNext();) { iterator.next().dataChangePerformed(evt); } } } public boolean hasDataListeners() { return listeners.size() > 0; } public void clear() { listeners.clear(); } }
Update the comment for VcapPassword
package common import ( bosherr "github.com/cloudfoundry/bosh-utils/errors" ) type AgentOptions struct { // e.g. "https://user:password@127.0.0.1:4321/agent" Mbus string // e.g. ["0.us.pool.ntp.org"]. Ok to be empty NTP []string Blobstore BlobstoreOptions //The SHA-512 encrypted vcap password VcapPassword string } type RegistryOptions struct { Host string Port int Username string Password string } type BlobstoreOptions struct { Provider string `json:"provider"` Options map[string]interface{} `json:"options"` } func (o AgentOptions) Validate() error { if o.Mbus == "" { return bosherr.Error("Must provide non-empty Mbus") } err := o.Blobstore.Validate() if err != nil { return bosherr.WrapError(err, "Validating Blobstore configuration") } return nil } func (o BlobstoreOptions) Validate() error { if o.Provider == "" { return bosherr.Error("Must provide non-empty provider") } return nil }
package common import ( bosherr "github.com/cloudfoundry/bosh-utils/errors" ) type AgentOptions struct { // e.g. "https://user:password@127.0.0.1:4321/agent" Mbus string // e.g. ["0.us.pool.ntp.org"]. Ok to be empty NTP []string Blobstore BlobstoreOptions //vcap password VcapPassword string } type RegistryOptions struct { Host string Port int Username string Password string } type BlobstoreOptions struct { Provider string `json:"provider"` Options map[string]interface{} `json:"options"` } func (o AgentOptions) Validate() error { if o.Mbus == "" { return bosherr.Error("Must provide non-empty Mbus") } err := o.Blobstore.Validate() if err != nil { return bosherr.WrapError(err, "Validating Blobstore configuration") } return nil } func (o BlobstoreOptions) Validate() error { if o.Provider == "" { return bosherr.Error("Must provide non-empty provider") } return nil }
Compress Discord event connectors into single function
""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.base import _BaseEvent from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news EVENT_TYPES_TO_HANDLERS = { BoardTopicCreated: board.announce_board_topic_created, BoardPostingCreated: board.announce_board_posting_created, NewsItemPublished: news.announce_news_item_published, } @board_signals.topic_created.connect @board_signals.posting_created.connect @news_signals.item_published.connect def _on_event(sender, *, event: Optional[_BaseEvent] = None) -> None: event_type = type(event) handler = EVENT_TYPES_TO_HANDLERS.get(event_type) if handler is None: return None enqueue(handler, event)
""" byceps.announce.discord.connections ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Announce events on Discord. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from typing import Optional from ...events.board import BoardPostingCreated, BoardTopicCreated from ...events.news import NewsItemPublished from ...signals import board as board_signals from ...signals import news as news_signals from ...util.jobqueue import enqueue from . import board, news # board @board_signals.topic_created.connect def _on_board_topic_created( sender, *, event: Optional[BoardTopicCreated] = None ) -> None: enqueue(board.announce_board_topic_created, event) @board_signals.posting_created.connect def _on_board_posting_created( sender, *, event: Optional[BoardPostingCreated] = None ) -> None: enqueue(board.announce_board_posting_created, event) # news @news_signals.item_published.connect def _on_news_item_published( sender, *, event: Optional[NewsItemPublished] = None ) -> None: enqueue(news.announce_news_item_published, event)
Fix app constructor not being exported
var express = require('express'); var serveStatic = require('serve-static'); var bodyParser = require('body-parser'); var session = require('express-session'); var RedisStore = require('connect-redis')(session); function appCtor(cfg, pool) { var app = express(); app.set('trust proxy', true); app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); app.use(serveStatic(__dirname + '/static')); app.use(session({ store: new RedisStore({ host: cfg.redis.hostname, port: cfg.redis.port}), secret: cfg.env.SECRET_KEY_BASE, resave: false, saveUninitialized: false })); app.use(function (req, res, next) { if (!req.session) { return next(new Error("couldn't find sessions")); } else return next(); }); app.use(bodyParser.urlencoded({ extended: false })); app.get('/', function(req, res) { return res.render('index'); }); app.get('/m', function(req, res) { return res.render('messaging'); }); return app; } module.exports = appCtor;
var express = require('express'); var serveStatic = require('serve-static'); var bodyParser = require('body-parser'); var session = require('express-session'); var RedisStore = require('connect-redis')(session); function appCtor(cfg, pool) { var app = express(); app.set('trust proxy', true); app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); app.use(serveStatic(__dirname + '/static')); app.use(session({ store: new RedisStore({ host: cfg.redis.hostname, port: cfg.redis.port}), secret: cfg.env.SECRET_KEY_BASE, resave: false, saveUninitialized: false })); app.use(function (req, res, next) { if (!req.session) { return next(new Error("couldn't find sessions")); } else return next(); }); app.use(bodyParser.urlencoded({ extended: false })); app.get('/', function(req, res) { return res.render('index'); }); app.get('/m', function(req, res) { return res.render('messaging'); }); return app; }
Add empty check to earliestMatchingOrder query. This was throwing an error when the subscription was brand-new and had no orders yet
<?php class Infusionsoft_RecurringOrder extends Infusionsoft_Generated_RecurringOrder{ var $customFieldFormId = -10; public function __construct($id = null, $app = null){ parent::__construct($id, $app); } //Find the Id first order charged for this subscription public static function getFirstOrderId ($recurringOrderId) { //load recurringOrder $recurringOrder = new Infusionsoft_RecurringOrder($recurringOrderId); //If there was an originating shopping cart or order form order, that is the first order if ($recurringOrder->OriginatingOrderId != 0) { return $recurringOrder->OriginatingOrderId; } else { //find all Orders with a matching JobRecurringId and put them in this array, sorted by date. $matchingOrders = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_Job(), array('JobRecurringId' => $recurringOrderId),'DateCreated'); if (!empty($matchingOrders)){ $earliestMatchingOrder = array_shift($matchingOrders); return $earliestMatchingOrder->Id; } else { return false; } } } }
<?php class Infusionsoft_RecurringOrder extends Infusionsoft_Generated_RecurringOrder{ var $customFieldFormId = -10; public function __construct($id = null, $app = null){ parent::__construct($id, $app); } //Find the Id first order charged for this subscription public static function getFirstOrderId ($recurringOrderId) { //load recurringOrder $recurringOrder = new Infusionsoft_RecurringOrder($recurringOrderId); //If there was an originating shopping cart or order form order, that is the first order if ($recurringOrder->OriginatingOrderId != 0) { return $recurringOrder->OriginatingOrderId; } else { //find all Orders with a matching JobRecurringId and put them in this array, sorted by date. $matchingOrders = Infusionsoft_DataService::queryWithOrderBy(new Infusionsoft_Job(), array('JobRecurringId' => $recurringOrderId),'DateCreated'); $earliestMatchingOrder = array_shift($matchingOrders); return $earliestMatchingOrder->Id; } } }
[TEXT-113] Add an interpolator string lookup. No long needs to subclass StrLookup.
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.commons.text.lookup; /** * A default lookup for others to extend in this package. * <p> * Unfortunately, the type {@link org.apache.commons.text.StrLookup} was defined as class and not an interface, which is * why this package introduces the interface {@link StringLookup}. * </p> * * @since 1.3 */ public abstract class AbstractStringLookup implements StringLookup { protected static final String EMPTY = ""; protected boolean isEmpty(final String value) { return value == null ? true : value.isEmpty(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.commons.text.lookup; import org.apache.commons.text.StrLookup; /** * A default lookup for others to extend in this package. * <p> * Unfortunately, the type {@link org.apache.commons.text.StrLookup} was defined as class and not an interface, which is * why this package introduces the interface {@link StringLookup}. In time, some deprecation strategy should be created. * </p> * * @since 1.3 */ public abstract class AbstractStringLookup extends StrLookup<String> { protected static final String EMPTY = ""; protected boolean isEmpty(final String value) { return value == null ? true : value.isEmpty(); } }
Replace enum34 with enum-compat to allow use with Py3.6+
#!/usr/bin/env python from setuptools import setup from Registry import _version_ setup(name='python-registry', version=_version_, description='Read access to Windows Registry files.', author='Willi Ballenthin', author_email='willi.ballenthin@gmail.com', url='http://www.williballenthin.com/registry/', license='Apache License (2.0)', packages=['Registry'], classifiers = ["Programming Language :: Python", "Programming Language :: Python :: 3", "Operating System :: OS Independent", "License :: OSI Approved :: Apache Software License"], install_requires=['enum-compat','unicodecsv'] )
#!/usr/bin/env python from setuptools import setup from Registry import _version_ setup(name='python-registry', version=_version_, description='Read access to Windows Registry files.', author='Willi Ballenthin', author_email='willi.ballenthin@gmail.com', url='http://www.williballenthin.com/registry/', license='Apache License (2.0)', packages=['Registry'], classifiers = ["Programming Language :: Python", "Programming Language :: Python :: 3", "Operating System :: OS Independent", "License :: OSI Approved :: Apache Software License"], install_requires=['enum34','unicodecsv'] )
Implement 'Delete' action for polls sample app
from django.shortcuts import render from django.core.urlresolvers import reverse_lazy from singleurlcrud.views import CRUDView from .models import * # Create your views here. class AuthorCRUDView(CRUDView): model = Author list_display = ('name',) class QuestionCRUDView(CRUDView): model = Question list_display = ('question_text', 'pub_date', 'author') related_field_crud_urls = { 'author': reverse_lazy("polls:authors") } def get_actions(self): self.related_field_crud_urls = { 'author': reverse_lazy('polls:authors') +"?o=add", } return [ ('Delete', self.delete_multiple_items) ] def delete_multiple_items(self, request, items): Question.objects.filter(pk__in=items).delete() class VoteItemAction(object): title = 'Vote' key = 'vote1' css = 'glyphicon glyphicon-envelope' def doAction(self, item): import logging logging.getLogger('general').info("VoteItemAction invoked!") pass def get_item_actions(self): return [self.VoteItemAction()]
from django.shortcuts import render from django.core.urlresolvers import reverse_lazy from singleurlcrud.views import CRUDView from .models import * # Create your views here. class AuthorCRUDView(CRUDView): model = Author list_display = ('name',) class QuestionCRUDView(CRUDView): model = Question list_display = ('question_text', 'pub_date', 'author') related_field_crud_urls = { 'author': reverse_lazy("polls:authors") } def get_actions(self): self.related_field_crud_urls = { 'author': reverse_lazy('polls:authors') +"?o=add", } return [ ('Delete', self.delete_multiple_items) ] def delete_multiple_items(self, request, items): pass class VoteItemAction(object): title = 'Vote' key = 'vote1' css = 'glyphicon glyphicon-envelope' def doAction(self, item): import logging logging.getLogger('general').info("VoteItemAction invoked!") pass def get_item_actions(self): return [self.VoteItemAction()]
Update procedure to restart controller on quarantined condition. There was a behavior change in Karaf [0] because of which restarting the container now requires the system property karaf.restart to be set to true in addition to karaf.restart.jvm property. Update controller restart logic on quarantined condition for the same. [0] https://issues.apache.org/jira/browse/KARAF-5179 Change-Id: I7b93eb87f53870efea70f2c9a9b82eeca783aa0b Signed-off-by: Ajay Lele <0c60352b9c35f386562c10f2260731d7efbca4a6@gmail.com>
/* * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.cluster.akka.osgi.impl; import akka.actor.Props; import org.opendaylight.controller.cluster.common.actor.QuarantinedMonitorActor; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class QuarantinedMonitorActorPropsFactory { private static final Logger LOG = LoggerFactory.getLogger(QuarantinedMonitorActorPropsFactory.class); private QuarantinedMonitorActorPropsFactory() { } public static Props createProps(final BundleContext bundleContext) { return QuarantinedMonitorActor.props(() -> { // restart the entire karaf container LOG.warn("Restarting karaf container"); System.setProperty("karaf.restart.jvm", "true"); System.setProperty("karaf.restart", "true"); bundleContext.getBundle(0).stop(); }); } }
/* * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.cluster.akka.osgi.impl; import akka.actor.Props; import org.opendaylight.controller.cluster.common.actor.QuarantinedMonitorActor; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class QuarantinedMonitorActorPropsFactory { private static final Logger LOG = LoggerFactory.getLogger(QuarantinedMonitorActorPropsFactory.class); private QuarantinedMonitorActorPropsFactory() { } public static Props createProps(final BundleContext bundleContext) { return QuarantinedMonitorActor.props(() -> { // restart the entire karaf container LOG.warn("Restarting karaf container"); System.setProperty("karaf.restart.jvm", "true"); bundleContext.getBundle(0).stop(); }); } }
Remove music button for now
import { createDownloadMP3Button } from './youtubeinmp3'; let playerIframe; export default function startMixerBoxMainScript() { console.log('MixerBox+ loaded.'); playerIframe = document.getElementById('MB-player-iframe'); if (!playerIframe) { return; } playerIframe.setAttribute('allowfullscreen', ''); setInterval(detectPlaylistItems, 350); } function detectPlaylistItems() { const result = document.querySelectorAll('.playlist-item-container:not(.mbplus-annotated)'); if (result.length === 0) { return; } result.forEach((playlist) => { const songRows = playlist.querySelectorAll('.song-row'); songRows.forEach((row) => { const imgEl = row.querySelector('.thumbnailContainer > img'); const videoId = imgEl.src.match(/.+:\/\/i\.ytimg\.com\/vi\/(.+)\/hqdefault\.jpg/i)[1]; // const titleEl = row.querySelector('.title'); // const mp3Button = createDownloadMP3Button(videoId); // titleEl.appendChild(mp3Button); }); playlist.classList.add('mbplus-annotated'); }); }
import { createDownloadMP3Button } from './youtubeinmp3'; let playerIframe; export default function startMixerBoxMainScript() { console.log('MixerBox+ loaded.'); playerIframe = document.getElementById('MB-player-iframe'); if (!playerIframe) { return; } playerIframe.setAttribute('allowfullscreen', ''); setInterval(detectPlaylistItems, 350); } function detectPlaylistItems() { const result = document.querySelectorAll('.playlist-item-container:not(.mbplus-annotated)'); if (result.length === 0) { return; } result.forEach((playlist) => { const songRows = playlist.querySelectorAll('.song-row'); songRows.forEach((row) => { const imgEl = row.querySelector('.thumbnailContainer > img'); const videoId = imgEl.src.match(/.+:\/\/i\.ytimg\.com\/vi\/(.+)\/hqdefault\.jpg/i)[1]; const titleEl = row.querySelector('.title'); const mp3Button = createDownloadMP3Button(videoId); titleEl.appendChild(mp3Button); }); playlist.classList.add('mbplus-annotated'); }); }
Fix for sending XML before async call returns
"use strict"; var BlogController = require('./controllers/blog'); var BloggerController = require('./controllers/blogger'); var RSS = require('rss'); exports.serveRoutes = function(router) { router.get('/main', function(req, res) { var mainFeed = new RSS({ title: "CS Blogs Main Feed", description: "All of the blog posts from bloggers on CSBlogs.com", feed_url: "http://feeds.csblogs.com/main", site_url: "http://csblogs.com", }); BlogController.getAllBlogs({}, function(blogs, error) { blogs.forEach(function(blog) { mainFeed.item({ title: blog.title, description: blog.summary, url: blog.link, guid: blog.link, author: "CS Blogs User", date: blog.pubDate }); }); res.header('Content-Type','application/rss+xml'); res.send(mainFeed.xml({indent: true})); }); }); };
"use strict"; var BlogController = require('./controllers/blog'); var BloggerController = require('./controllers/blogger'); var RSS = require('rss'); exports.serveRoutes = function(router) { router.get('/main', function(req, res) { var mainFeed = new RSS({ title: "CS Blogs Main Feed", description: "All of the blog posts from bloggers on CSBlogs.com", feed_url: "http://feeds.csblogs.com/main", site_url: "http://csblogs.com", }); BlogController.getAllBlogs({}, function(blogs, error) { blogs.forEach(function(blog) { mainFeed.item({ title: blog.title, description: blog.summary, url: blog.link, guid: blog.link, author: "CS Blogs User", date: blog.pubDate }); }); }); res.header('Content-Type','application/rss+xml'); res.send(mainFeed.xml({indent: true})); }); };
[NCL-3741] Remove user token from logs
import asyncio import logging from jose import jwt, JWTError from repour.config import config logger = logging.getLogger(__name__) @asyncio.coroutine def verify_token(token): c = yield from config.get_configuration() logger.info('Got token!') OPTIONS = { 'verify_signature': True, 'verify_aud': False, 'verify_iat': True, 'verify_exp': True, 'verify_nbf': True, 'verify_iss': True, 'verify_sub': False, 'verify_jti': True, 'verify_at_hash': True, 'leeway': 0, } try: token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS, issuer=c['auth']['oauth2_jwt']['token_issuer']) logger.info('Got valid token!') return True except JWTError as e: logger.info('Got invalid token: ' + str(e)) return False
import asyncio import logging from jose import jwt, JWTError from repour.config import config logger = logging.getLogger(__name__) @asyncio.coroutine def verify_token(token): c = yield from config.get_configuration() logger.info('Got token: ' + str(token)) OPTIONS = { 'verify_signature': True, 'verify_aud': False, 'verify_iat': True, 'verify_exp': True, 'verify_nbf': True, 'verify_iss': True, 'verify_sub': False, 'verify_jti': True, 'verify_at_hash': True, 'leeway': 0, } try: token = jwt.decode(token, c['auth']['oauth2_jwt']['public_key'], algorithms=['RS256'], options=OPTIONS, issuer=c['auth']['oauth2_jwt']['token_issuer']) logger.info('Got valid token: ' + str(token)) return True except JWTError as e: logger.info('Got invalid token: ' + str(e)) return False
Use ms timestamp on log messages The previous string was just outputting the date, which is sort of useless. We could look into a better formatted string but for now the ms version is actually helpful since I can better debug timing issues.
import winston from 'winston'; import Configuration from './Configuration'; import rerouteConsoleLog from './rerouteConsoleLog'; function initializeLogging(pathToLogFile) { // The `importjs` here is mostly a dummy file because config relies on a // `pathToCurrentFile`. Normally, this is the javascript file you are // editing. const level = new Configuration('importjs').get('logLevel'); winston.configure({ level, transports: [ new winston.transports.File({ filename: pathToLogFile, json: false, timestamp() { return Date.now(); }, formatter({ timestamp, level, message }) { const parts = [timestamp(), level.toUpperCase()]; if (initializeLogging.parentPid) { // This gets set when run as a daemon parts.push(`PID:${initializeLogging.parentPid}`); } parts.push(message); return parts.join(' '); }, }), ], }); rerouteConsoleLog(); } export default initializeLogging;
import winston from 'winston'; import Configuration from './Configuration'; import rerouteConsoleLog from './rerouteConsoleLog'; function initializeLogging(pathToLogFile) { // The `importjs` here is mostly a dummy file because config relies on a // `pathToCurrentFile`. Normally, this is the javascript file you are // editing. const level = new Configuration('importjs').get('logLevel'); winston.configure({ level, transports: [ new winston.transports.File({ filename: pathToLogFile, json: false, timestamp() { return new Date().toDateString(); }, formatter({ timestamp, level, message }) { const parts = [timestamp(), level.toUpperCase()]; if (initializeLogging.parentPid) { // This gets set when run as a daemon parts.push(`PID:${initializeLogging.parentPid}`); } parts.push(message); return parts.join(' '); }, }), ], }); rerouteConsoleLog(); } export default initializeLogging;
Change serialization date format again
/* * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) * * 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 org.traccar.api; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import java.text.SimpleDateFormat; @Provider public class ObjectMapperProvider implements ContextResolver<ObjectMapper> { private ObjectMapper mapper = new ObjectMapper(); public ObjectMapperProvider() { mapper.setConfig(mapper.getSerializationConfig().without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)); } @Override public ObjectMapper getContext(Class<?> type) { return mapper; } }
/* * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com) * * 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 org.traccar.api; import com.fasterxml.jackson.databind.ObjectMapper; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import java.text.SimpleDateFormat; @Provider public class ObjectMapperProvider implements ContextResolver<ObjectMapper> { private ObjectMapper mapper = new ObjectMapper(); public ObjectMapperProvider() { mapper.setConfig(mapper.getSerializationConfig().with( new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"))); } @Override public ObjectMapper getContext(Class<?> type) { return mapper; } }
Change New Todo to Modal.
import NavigationBar from 'react-native-navbar'; import React, { Component, PropTypes } from 'react'; import { View, ScrollView, Modal, } from 'react-native'; import {default as AddTodo} from '../components/add-todo'; class NewTodo extends Component { constructor(props) { super(props); this.cancel = this.backToList.bind(this); this.done = this.backToList.bind(this); } backToList() { this.props.navigator.pop(); } render() { const {theme} = this.props; const {styles, variables} = theme; return ( <Modal animationType={'slide'} > <View style={styles.container}> <NavigationBar title={{ title: 'New Task', tintColor: variables.colorTint }} leftButton={{ title: 'Cancel', handler: this.cancel, tintColor: variables.colorNavbarText }} style={styles.navbar} /> <ScrollView horizontal={false}> <AddTodo onFinish={this.done} theme={theme} /> </ScrollView> </View> </Modal> ); } } NewTodo.propTypes = { theme: PropTypes.object }; export default NewTodo;
import NavigationBar from 'react-native-navbar'; import React, { Component, PropTypes } from 'react'; import { View, ScrollView, } from 'react-native'; import {default as AddTodo} from '../components/add-todo'; class NewTodo extends Component { constructor(props) { super(props); this.cancel = this.backToList.bind(this); this.done = this.backToList.bind(this); } backToList() { this.props.navigator.pop(); } render() { const {theme} = this.props; const {styles, variables} = theme; return ( <View style={styles.container}> <NavigationBar title={{ title: 'New Task', tintColor: variables.colorTint }} leftButton={{ title: 'Cancel', handler: this.cancel, tintColor: variables.colorNavbarText }} style={styles.navbar} /> <ScrollView horizontal={false}> <AddTodo onFinish={this.done} theme={theme} /> </ScrollView> </View> ); } } NewTodo.propTypes = { theme: PropTypes.object }; export default NewTodo;
Put a blank line before section headings, courtesy spiv.
"""Formatters for creating documents. A formatter is an object which accepts an output stream (usually a file or standard output) and then provides a structured way for writing to that stream. All formatters should provide 'title', 'section', 'subsection' and 'paragraph' methods which write to the stream. """ class WikiFormatter(object): """Moin formatter.""" def __init__(self, stream): self.stream = stream def writeln(self, line): self.stream.write('%s\n' % (line,)) def title(self, name): self.writeln('= %s =\n' % (name,)) def section(self, name): self.writeln('') self.writeln('== %s ==\n' % (name,)) def subsection(self, name): self.writeln('=== %s ===\n' % (name,)) def paragraph(self, text): self.writeln('%s\n' % (text.strip(),))
"""Formatters for creating documents. A formatter is an object which accepts an output stream (usually a file or standard output) and then provides a structured way for writing to that stream. All formatters should provide 'title', 'section', 'subsection' and 'paragraph' methods which write to the stream. """ class WikiFormatter(object): """Moin formatter.""" def __init__(self, stream): self.stream = stream def writeln(self, line): self.stream.write('%s\n' % (line,)) def title(self, name): self.writeln('= %s =\n' % (name,)) def section(self, name): self.writeln('== %s ==\n' % (name,)) def subsection(self, name): self.writeln('=== %s ===\n' % (name,)) def paragraph(self, text): self.writeln('%s\n' % (text.strip(),))
[SMALLFIX] Use static import for standard test utilities pr-link: Alluxio/alluxio#8981 change-id: cid-e8e2596b0f3cb68489b88cbf42646844098151dc
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runners.model.Statement; import java.io.ByteArrayOutputStream; import java.io.PrintStream; /** * Unit tests for {@link SystemErrRule}. */ public class SystemErrRuleTest { private static final ByteArrayOutputStream OUTPUT = new ByteArrayOutputStream(); private static final PrintStream ORIGINAL_SYSTEM_ERR = System.err; private Statement mStatement = new Statement() { @Override public void evaluate() throws Throwable { System.err.println("2048"); assertEquals("2048\n", OUTPUT.toString()); OUTPUT.reset(); System.err.println("1234"); assertEquals("1234\n", OUTPUT.toString()); } }; @Test public void testSystemErrRule() throws Throwable { new SystemErrRule(OUTPUT).apply(mStatement, null).evaluate(); assertEquals(System.err, ORIGINAL_SYSTEM_ERR); } }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio; import org.junit.Assert; import org.junit.Test; import org.junit.runners.model.Statement; import java.io.ByteArrayOutputStream; import java.io.PrintStream; /** * Unit tests for {@link SystemErrRule}. */ public class SystemErrRuleTest { private static final ByteArrayOutputStream OUTPUT = new ByteArrayOutputStream(); private static final PrintStream ORIGINAL_SYSTEM_ERR = System.err; private Statement mStatement = new Statement() { @Override public void evaluate() throws Throwable { System.err.println("2048"); Assert.assertEquals("2048\n", OUTPUT.toString()); OUTPUT.reset(); System.err.println("1234"); Assert.assertEquals("1234\n", OUTPUT.toString()); } }; @Test public void testSystemErrRule() throws Throwable { new SystemErrRule(OUTPUT).apply(mStatement, null).evaluate(); Assert.assertEquals(System.err, ORIGINAL_SYSTEM_ERR); } }
Fix issue where add account would not appear
/* * Copyright (C) 2012 Brian Muramatsu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmura.android.reddit.app; import android.os.Bundle; import android.preference.PreferenceFragment; import com.btmura.android.reddit.R; public class DebugFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); addPreferencesFromResource(R.xml.debug_preferences); } }
/* * Copyright (C) 2012 Brian Muramatsu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmura.android.reddit.app; import com.btmura.android.reddit.R; import android.os.Bundle; import android.preference.PreferenceFragment; import android.view.Menu; public class DebugFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); addPreferencesFromResource(R.xml.debug_preferences); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); // TODO: Figure out how to move this somehow to SettingsActivity. menu.findItem(R.id.menu_add_account).setVisible(false); } }
Set Development Status to Beta
from setuptools import setup import os def read(*names): values = dict() for name in names: filename = name + '.rst' if os.path.isfile(filename): fd = open(filename) value = fd.read() fd.close() else: value = '' values[name] = value return values long_description = """ %(README)s News ==== %(CHANGES)s """ % read('README', 'CHANGES') setup(name='noattr', version='0.0.1', description='Python text operations module', long_description=long_description, classifiers=[ "Intended Audience :: Developers", "Development Status :: 4 - Beta", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", ], keywords='attribute, AttrDict', url='https://github.com/elapouya/noattr', author='Eric Lapouyade', author_email='elapouya@gmail.com', license='LGPL 2.1', packages=['noattr'], install_requires = [], eager_resources = [], zip_safe=False)
from setuptools import setup import os def read(*names): values = dict() for name in names: filename = name + '.rst' if os.path.isfile(filename): fd = open(filename) value = fd.read() fd.close() else: value = '' values[name] = value return values long_description = """ %(README)s News ==== %(CHANGES)s """ % read('README', 'CHANGES') setup(name='noattr', version='0.0.1', description='Python text operations module', long_description=long_description, classifiers=[ "Intended Audience :: Developers", "Development Status :: 2 - Pre-Alpha", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", ], keywords='attribute, AttrDict', url='https://github.com/elapouya/noattr', author='Eric Lapouyade', author_email='elapouya@gmail.com', license='LGPL 2.1', packages=['noattr'], install_requires = [], eager_resources = [], zip_safe=False)
tests/initializer-addon: Use alternative blueprint test helpers
'use strict'; var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers'); var setupTestHooks = blueprintHelpers.setupTestHooks; var emberNew = blueprintHelpers.emberNew; var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy; var chai = require('ember-cli-blueprint-test-helpers/chai'); var expect = chai.expect; describe('Acceptance: ember generate and destroy initializer-addon', function() { setupTestHooks(this); it('initializer-addon foo', function() { var args = ['initializer-addon', 'foo']; return emberNew({ target: 'addon' }) .then(() => emberGenerateDestroy(args, _file => { expect(_file('app/initializers/foo.js')) .to.contain("export { default, initialize } from 'my-addon/initializers/foo';"); })); }); });
'use strict'; var setupTestHooks = require('ember-cli-blueprint-test-helpers/lib/helpers/setup'); var BlueprintHelpers = require('ember-cli-blueprint-test-helpers/lib/helpers/blueprint-helper'); var generateAndDestroy = BlueprintHelpers.generateAndDestroy; describe('Acceptance: ember generate and destroy initializer-addon', function() { setupTestHooks(this); it('initializer-addon foo', function() { // pass any additional command line options in the arguments array return generateAndDestroy(['initializer-addon', 'foo'], { // define files to assert, and their contents target: 'addon', files: [ { file: 'app/initializers/foo.js', contains: "export { default, initialize } from 'my-addon/initializers/foo';" } ] }); }); });
Add support for alternate URLs for input logging (aka ec2)
/* * config.js: Configuration information for your Loggly account. * This information is only used for require('loggly')./\.+/ methods * * (C) 2010 Nodejitsu Inc. * MIT LICENSE * */ // // function createConfig (defaults) // Creates a new instance of the configuration // object based on default values // exports.createConfig = function (defaults) { return new Config(defaults); }; // // Config (defaults) // Constructor for the Config object // var Config = exports.Config = function (defaults) { if (!defaults.subdomain) { throw new Error('Subdomain is required to create an instance of Config'); } this.subdomain = defaults.subdomain; this.json = defaults.json || null; this.auth = defaults.auth || null; this.inputUrl = defaults.inputUrl || 'https://logs.loggly.com/inputs/'; }; Config.prototype = { get subdomain () { return this._subdomain; }, set subdomain (value) { this._subdomain = value; }, get logglyUrl () { return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api'; }, get inputUrl () { return this._inputUrl; }, set inputUrl (value) { this._inputUrl = value; } };
/* * config.js: Configuration information for your Loggly account. * This information is only used for require('loggly')./\.+/ methods * * (C) 2010 Nodejitsu Inc. * MIT LICENSE * */ // // function createConfig (defaults) // Creates a new instance of the configuration // object based on default values // exports.createConfig = function (defaults) { return new Config(defaults); }; // // Config (defaults) // Constructor for the Config object // var Config = exports.Config = function (defaults) { if (!defaults.subdomain) { throw new Error('Subdomain is required to create an instance of Config'); } this.subdomain = defaults.subdomain; this.json = defaults.json || null; this.auth = defaults.auth || null; }; Config.prototype = { get subdomain () { return this._subdomain; }, set subdomain (value) { this._subdomain = value; }, get logglyUrl () { return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api'; }, get inputUrl () { return 'https://logs.loggly.com/inputs/'; } };
Define 'city' at top decorator
from functools import wraps from django.http import HttpResponseNotFound from django.shortcuts import redirect from core.utils import get_event_page def organiser_only(function): """ Decorator for views that checks that the user is logged in and that they are a team member for a particular page. Returns 404 otherwise. """ @wraps(function) def decorator(request, *args, **kwargs): city = kwargs.get('city') if not city: raise ValueError( '"City" slug must be present to user this decorator.') if not request.user.is_authenticated(): return redirect('core:event', city) page = get_event_page(city, request.user.is_authenticated(), False) if page and (request.user in page.event.team.all() or request.user.is_superuser): return function(request, *args, **kwargs) return HttpResponseNotFound() return decorator
from functools import wraps from django.http import HttpResponseNotFound from django.shortcuts import redirect from core.utils import get_event_page def organiser_only(function): """ Decorator for views that checks that the user is logged in and that they are a team member for a particular page. Returns 404 otherwise. """ @wraps(function) def decorator(request, *args, **kwargs): if not kwargs.get('city'): raise ValueError( '"City" slug must be present to user this decorator.') if not request.user.is_authenticated(): return redirect('core:event', kwargs.get('city')) city = kwargs.get('city') page = get_event_page(city, request.user.is_authenticated(), False) if page and (request.user in page.event.team.all() or request.user.is_superuser): return function(request, *args, **kwargs) return HttpResponseNotFound() return decorator
Increase daemon shutdown timeout to 20s for slow Travis CI Windows runs
import time import pytest def test_version(client): expected_keys = {"Repo", "Commit", "Version"} resp_version = client.version() assert set(resp_version.keys()).issuperset(expected_keys) def test_id(client): expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"} resp_id = client.id() assert set(resp_id.keys()).issuperset(expected_keys) ################# # Shutdown test # ################# @pytest.mark.last def test_daemon_stop(daemon, client): # The value for the `daemon` “fixture” is injected using a pytest plugin # with access to the created daemon subprocess object defined directly # in the `test/run-test.py` file if not daemon: pytest.skip("Not started using `test/run-test.py`") def daemon_is_running(): return daemon.poll() is None # Daemon should still be running at this point assert daemon_is_running() # Send stop request client.stop() # Wait for daemon process to disappear # #XXX: 10s is apparently not enough for slow Travis CI on Windows. for _ in range(20000): if not daemon_is_running(): break time.sleep(0.001) # Daemon should not be running anymore assert not daemon_is_running()
import time import pytest def test_version(client): expected_keys = {"Repo", "Commit", "Version"} resp_version = client.version() assert set(resp_version.keys()).issuperset(expected_keys) def test_id(client): expected_keys = {"PublicKey", "ProtocolVersion", "ID", "AgentVersion", "Addresses"} resp_id = client.id() assert set(resp_id.keys()).issuperset(expected_keys) ################# # Shutdown test # ################# @pytest.mark.last def test_daemon_stop(daemon, client): # The value for the `daemon` “fixture” is injected using a pytest plugin # with access to the created daemon subprocess object defined directly # in the `test/run-test.py` file if not daemon: pytest.skip("Not started using `test/run-test.py`") def daemon_is_running(): return daemon.poll() is None # Daemon should still be running at this point assert daemon_is_running() # Send stop request client.stop() # Wait for daemon process to disappear for _ in range(10000): if not daemon_is_running(): break time.sleep(0.001) # Daemon should not be running anymore assert not daemon_is_running()
Upgrade Django for security vulnerability
from setuptools import setup setup( name='tablo', description='A PostGIS table to feature service app for Django', keywords='feature service, map server, postgis, django', version='1.3.0', packages=['tablo', 'tablo.migrations', 'tablo.interfaces', 'tablo.interfaces.arcgis'], install_requires=[ 'Django>=1.11.28,<2.0', 'sqlparse>=0.1.18', 'pyproj', 'six', 'pandas==0.24.*', 'django-tastypie==0.14.*', 'psycopg2', 'Pillow>=2.9.0', 'django-storages>=1.5.2', 'boto3>=1.4.4', 'sqlalchemy==1.3.*', 'geoalchemy2==0.6.*' ], test_suite='tablo.tests.runtests.runtests', tests_require=['django-nose', 'rednose'], url='http://github.com/consbio/tablo', license='BSD', )
from setuptools import setup setup( name='tablo', description='A PostGIS table to feature service app for Django', keywords='feature service, map server, postgis, django', version='1.3.0', packages=['tablo', 'tablo.migrations', 'tablo.interfaces', 'tablo.interfaces.arcgis'], install_requires=[ 'Django>=1.11.19,<2.0', 'sqlparse>=0.1.18', 'pyproj', 'six', 'pandas==0.24.*', 'django-tastypie==0.14.*', 'psycopg2', 'Pillow>=2.9.0', 'django-storages>=1.5.2', 'boto3>=1.4.4', 'sqlalchemy==1.3.*', 'geoalchemy2==0.6.*' ], test_suite='tablo.tests.runtests.runtests', tests_require=['django-nose', 'rednose'], url='http://github.com/consbio/tablo', license='BSD', )
Make accompanying changes to DB when cancelling Gift Aid declaration.
import React from 'react' export default class GiftAidButton extends React.Component { constructor (props) { super (props) this.state = { confirmation: false } } cancel () { this.props.update_member_user( { gift_aid_cancelled: true , date_gift_aid_cancelled: new Date().toISOString() , gift_aid_signed: false , date_gift_aid_signed: null } ) } attempt_cancel () { this.setState({ confirmation: true }) } reset () { this.setState({ confirmation: false }) } which_cancel () { return this.state.confirmation ? this.cancel.bind(this) : this.attempt_cancel.bind(this) } which_text () { return this.state.confirmation ? 'Confirm' : 'Cancel Gift Aid' } render () { return ( <div> <p><b>Would you like to revoke your Gift Aid declaration?</b></p> <button onClick={this.which_cancel()} className={this.state.confirmation ? 'red' : ''}> {this.which_text()} </button> {this.state.confirmation && <button onClick={this.reset.bind(this)} className='green' >Keep Gift Aid</button>} </div> ) } }
import React from 'react' export default class GiftAidButton extends React.Component { constructor (props) { super (props) this.state = { confirmation: false } } cancel () { this.props.update_member_user({ gift_aid_signed: false, gift_aid_cancelled: true }) } attempt_cancel () { this.setState({ confirmation: true }) } reset () { this.setState({ confirmation: false }) } which_cancel () { return this.state.confirmation ? this.cancel.bind(this) : this.attempt_cancel.bind(this) } which_text () { return this.state.confirmation ? 'Confirm' : 'Cancel Gift Aid' } render () { return ( <div> <p><b>Would you like to cancel your Gift Aid?</b></p> <button onClick={this.which_cancel()} className={this.state.confirmation ? 'red' : ''}> {this.which_text()} </button> {this.state.confirmation && <button onClick={this.reset.bind(this)} className='green' >Keep Gift Aid</button>} </div> ) } }
Add backwards compatibility with pip v9
#!/usr/bin/env python import json import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: from pip._internal.download import PipSession except ImportError: from pip.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in parse_requirements(sys.argv[1], session=PipSession()) if req.req != None] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
#!/usr/bin/env python import json import sys from pip._internal.req import parse_requirements from pip._internal.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in parse_requirements(sys.argv[1], session=PipSession()) if req.req != None] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
Add picture field in user schema for loading from google profile data
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('email')->nullable(); $table->string('password')->nullable(); $table->string('displayName')->nullable(); $table->string('facebook')->nullable(); $table->string('foursquare')->nullable(); $table->string('instagram')->nullable(); $table->string('github')->nullable(); $table->string('google')->nullable(); $table->string('linkedin')->nullable(); $table->string('twitter')->nullable(); $table->string('picture')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('email')->nullable(); $table->string('password')->nullable(); $table->string('displayName')->nullable(); $table->string('facebook')->nullable(); $table->string('foursquare')->nullable(); $table->string('instagram')->nullable(); $table->string('github')->nullable(); $table->string('google')->nullable(); $table->string('linkedin')->nullable(); $table->string('twitter')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Disable updating serviceInfo when retrieving daily data.
#!/usr/bin/env python import json, os, requests from awsauth import S3Auth key = os.environ.get('UWOPENDATA_APIKEY') ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY_ID') SECRET_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') def getData(service): payload = {'key': key, 'service': service} r = requests.get('http://api.uwaterloo.ca/public/v1/', params=payload) return r foodMenu = getData('FoodMenu').text requests.put('http://s3.amazonaws.com/uwfoodmenu/foodMenu.txt', data=foodMenu, auth=S3Auth(ACCESS_KEY, SECRET_KEY)) # serviceInfo = getData('FoodServices').text # requests.put('http://s3.amazonaws.com/uwfoodmenu/serviceInfo.txt', data=serviceInfo, auth=S3Auth(ACCESS_KEY, SECRET_KEY))
#!/usr/bin/env python import json, os, requests from awsauth import S3Auth key = os.environ.get('UWOPENDATA_APIKEY') ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY_ID') SECRET_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') def getData(service): payload = {'key': key, 'service': service} r = requests.get('http://api.uwaterloo.ca/public/v1/', params=payload) return r foodMenu = getData('FoodMenu').text requests.put('http://s3.amazonaws.com/uwfoodmenu/foodMenu.txt', data=foodMenu, auth=S3Auth(ACCESS_KEY, SECRET_KEY)) serviceInfo = getData('FoodServices').text requests.put('http://s3.amazonaws.com/uwfoodmenu/serviceInfo.txt', data=serviceInfo, auth=S3Auth(ACCESS_KEY, SECRET_KEY))
Move path strings into a config object
#!/usr/bin/env node 'use strict'; var program = require('commander') , gulp = require('gulp') , chalk = require('chalk') , exec = require('exec') , pjson = require('./package.json') var strings = { create: 'Creating new project', install: 'Installing dependencies', complete: 'Done!' } var paths = { basefiles: __dirname + '/assets/**/*', dotfiles: __dirname + '/assets/.*' } function notify(message) { if (!program.quiet) console.log(chalk.green(message)) } function installDependencies(name) { notify(strings.install) exec('cd ' + name + ' && npm install', function () { notify(strings.complete) }) } function newProject(name) { notify(strings.create, name) gulp.src([paths.basefiles, paths.dotfiles]) .pipe(gulp.dest(process.cwd() + '/' + name)) .on('end', installDependencies.bind(this, name)) } program .version(pjson.version) .option('-q, --quiet', 'Hide logging information') program .command('new <name>') .description('scaffold out a new app in the current directory') .action(newProject) program.parse(process.argv);
#!/usr/bin/env node 'use strict'; var program = require('commander') , gulp = require('gulp') , chalk = require('chalk') , exec = require('exec') , pjson = require('./package.json') var strings = { create: 'Creating new project', install: 'Installing dependencies', complete: 'Done!' } function notify(message) { if (!program.quiet) console.log(chalk.green(message)) } function installDependencies(name) { notify(strings.install) exec('cd ' + name + ' && npm install', function () { notify(strings.complete) }) } function newProject(name) { notify(strings.create, name) gulp.src([__dirname + '/assets/**/*', __dirname + '/assets/.*']) .pipe(gulp.dest(process.cwd() + '/' + name)) .on('end', installDependencies.bind(this, name)) } program .version(pjson.version) .option('-q, --quiet', 'Hide logging information') program .command('new <name>') .description('scaffold out a new app in the current directory') .action(newProject) program.parse(process.argv);
Add wait of 1 second waiting for further events
package main import ( "fmt" "github.com/sdegutis/go.fsevents" "log" "os" "os/exec" "time" ) func main() { if len(os.Args) < 3 { fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY|FILE COMMAND [ARGS…]") os.Exit(1) } ch := fsevents.WatchPaths([]string{os.Args[1]}) var cmd *exec.Cmd go func() { for _ = range ch { WAIT: // Wait 1 second in case multiple events occur in quick succession for { select { case <-ch: case <-time.After(1 * time.Second): break WAIT } } log.Println("Changes detected, restarting") cmd.Process.Signal(os.Interrupt) } }() for { cmd = exec.Command(os.Args[2]) cmd.Args = os.Args[2:] cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr err := cmd.Run() if err != nil { if _, ok := err.(*exec.ExitError); !ok { log.Fatal(err) } } } }
package main import ( "fmt" "github.com/sdegutis/go.fsevents" "log" "os" "os/exec" ) func main() { if len(os.Args) < 3 { fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY|FILE COMMAND [ARGS…]") os.Exit(1) } ch := fsevents.WatchPaths([]string{os.Args[1]}) var cmd *exec.Cmd go func() { for _ = range ch { log.Println("Changes detected, restarting") cmd.Process.Signal(os.Interrupt) } }() for { cmd = exec.Command(os.Args[2]) cmd.Args = os.Args[2:] cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr err := cmd.Run() if err != nil { if _, ok := err.(*exec.ExitError); !ok { log.Fatal(err) } } } }
Add timeout to preview rendering
// function that reloads the DOM for // MathJax (http://www.mathjax.org/docs/1.1/typeset.html) function reloadDOM() { MathJax.Hub.Queue(["Typeset", MathJax.Hub]); } var timeout; function updateAnnotationPreview(){ var updatedAnnotation = document.getElementById("new_annotation_content").value; var previewParagraph = document.getElementById("annotation_preview"); var title = document.getElementById("annotation_preview_title"); var firstIndex = updatedAnnotation.indexOf("$$"); var secondIndex = updatedAnnotation.indexOf("$$", firstIndex + 1); if(firstIndex != -1 && secondIndex != -1 && firstIndex != secondIndex){ title.show(); previewParagraph.show(); previewParagraph.innerHTML = updatedAnnotation; if(timeout){ clearTimeout(timeout) timeout = null } // typeset the preview timeout = setTimeout(function() { MathJax.Hub.Queue(["Typeset", MathJax.Hub, previewParagraph]); clearTimeout(timeout) }, 3000); }else{ title.hide(); previewParagraph.hide() } }
// function that reloads the DOM for // MathJax (http://www.mathjax.org/docs/1.1/typeset.html) function reloadDOM() { MathJax.Hub.Queue(["Typeset", MathJax.Hub]); } function updateAnnotationPreview(){ var updatedAnnotation = document.getElementById("new_annotation_content").value; var previewParagraph = document.getElementById("annotation_preview"); var title = document.getElementById("annotation_preview_title"); var firstIndex = updatedAnnotation.indexOf("$$"); var secondIndex = updatedAnnotation.indexOf("$$", firstIndex + 1); if(firstIndex != -1 && secondIndex != -1 && firstIndex != secondIndex){ title.show(); previewParagraph.show(); previewParagraph.innerHTML = updatedAnnotation; // typeset the preview MathJax.Hub.Queue(["Typeset", MathJax.Hub, previewParagraph]); }else{ title.hide(); previewParagraph.hide() } }
Change the runserver command to run a server at a host ip of 127.0.0.1 to easily change the xternal visibility of the application later
import os from app import create_app, db from app.models import User, Category from flask_script import Manager, Server from flask_migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) manager.add_command('runserver', Server(host='127.0.0.1')) #pylint: disable-msg=E1101 @manager.command def adduser(email, username, admin=False): """ Register a new user""" from getpass import getpass password = getpass() password2 = getpass(prompt='Confirm: ') if password != password2: import sys sys.exit("Error: Passwords do not match!") db.create_all() category = Category.get_by_name('Almenn frétt') if category is None: category = Category(name='Almenn frétt', name_en='General News', active=True) db.session.add(category) user = User(email=email, username=username, password=password, is_admin=admin) db.session.add(user) db.session.commit() print('User {0} was registered successfully!'.format(username)) if __name__ == '__main__': manager.run()
import os from app import create_app, db from app.models import User, Category from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) #pylint: disable-msg=E1101 @manager.command def adduser(email, username, admin=False): """ Register a new user""" from getpass import getpass password = getpass() password2 = getpass(prompt='Confirm: ') if password != password2: import sys sys.exit("Error: Passwords do not match!") db.create_all() category = Category.get_by_name('Almenn frétt') if category is None: category = Category(name='Almenn frétt', name_en='General News', active=True) db.session.add(category) user = User(email=email, username=username, password=password, is_admin=admin) db.session.add(user) db.session.commit() print('User {0} was registered successfully!'.format(username)) if __name__ == '__main__': manager.run()
Move algorithm types to static strings on top
package login; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class PasswordHelper { private static String hashAlgorithm = "MD5"; private static String stringEncodingFormat = "UTF-8"; public static String generatePasswordHash(String password) { //Create instances of digest and password char array MessageDigest passDigest; byte[] passArray; try { //Create instance of MessageDigest we can use to passDigest = MessageDigest.getInstance(hashAlgorithm); //Convert password to byte array passArray = password.getBytes(stringEncodingFormat); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } //Use digest to get an array of chars as a hash and return it as a string byte[] hashArray = passDigest.digest(passArray); return new String(hashArray); } }
package login; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class PasswordHelper { public static String generatePasswordHash(String password) { //Create instances of digest and password char array MessageDigest passDigest; byte[] passArray; try { //Create instance of MessageDigest we can use to passDigest = MessageDigest.getInstance("MD5"); //Convert password to byte array passArray = password.getBytes("UTF-8"); } catch (NoSuchAlgorithmException e) { //Hardcoded algorithm type, this exception shouldn't be called e.printStackTrace(); return ""; } catch (UnsupportedEncodingException e) { //Hardcoded encoding type, this exception shouldn't be called e.printStackTrace(); return ""; } //Use digest to get an array of chars as a hash and return it as a string byte[] hashArray = passDigest.digest(passArray); return new String(hashArray); } }
Add a test that a non-GET method is rejected
# -*- encoding: utf-8 -*- import uuid import pytest import archive_report_ingest_status as report_ingest_status def test_get_returns_status(dynamodb_resource, table_name): guid = str(uuid.uuid4()) table = dynamodb_resource.Table(table_name) table.put_item(Item={'id': guid}) event = { 'request_method': 'GET', 'id': guid } response = report_ingest_status.main( event=event, dynamodb_resource=dynamodb_resource ) assert response['id'] == guid def test_get_includes_other_dynamodb_metadata(dynamodb_resource, table_name): guid = str(uuid.uuid4()) item = {'id': guid, 'fooKey': 'barValue'} table = dynamodb_resource.Table(table_name) table.put_item(Item=item) event = { 'request_method': 'GET', 'id': guid } response = report_ingest_status.main( event=event, dynamodb_resource=dynamodb_resource ) assert response == item def test_fails_if_called_with_post_event(): event = { 'request_method': 'POST' } with pytest.raises(AssertionError, match='Expected request_method=GET'): report_ingest_status.main(event=event)
# -*- encoding: utf-8 -*- import uuid import archive_report_ingest_status as report_ingest_status def test_get_returns_status(dynamodb_resource, table_name): guid = str(uuid.uuid4()) table = dynamodb_resource.Table(table_name) table.put_item(Item={'id': guid}) event = { 'request_method': 'GET', 'id': guid } response = report_ingest_status.main( event=event, dynamodb_resource=dynamodb_resource ) assert response['id'] == guid def test_get_includes_other_dynamodb_metadata(dynamodb_resource, table_name): guid = str(uuid.uuid4()) item = {'id': guid, 'fooKey': 'barValue'} table = dynamodb_resource.Table(table_name) table.put_item(Item=item) event = { 'request_method': 'GET', 'id': guid } response = report_ingest_status.main( event=event, dynamodb_resource=dynamodb_resource ) assert response == item
Set underscored to true so that authorId becomes author_id and is consistent with other column names
import Sequelize from 'sequelize'; import database from '../'; import User from './user'; const blogPostDatabaseDefinition = database.define('blog_post', { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true, field: 'id', allowNull: false }, title: { type: Sequelize.STRING, field: 'title', allowNull: false }, link: { type: Sequelize.STRING, field: 'link', allowNull: false }, description: { type: Sequelize.TEXT, field: 'description', allowNull: false }, dateUpdated: { type: Sequelize.DATE, field: 'date_updated', allowNull: false }, datePublished: { type: Sequelize.DATE, field: 'date_published', allowNull: false } }, { underscored: true }); blogPostDatabaseDefinition.belongsTo(User, { as: 'author' }); export default blogPostDatabaseDefinition;
import Sequelize from 'sequelize'; import database from '../'; import User from './user'; const blogPostDatabaseDefinition = database.define('blog_post', { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true, field: 'id', allowNull: false }, title: { type: Sequelize.STRING, field: 'title', allowNull: false }, link: { type: Sequelize.STRING, field: 'link', allowNull: false }, description: { type: Sequelize.TEXT, field: 'description', allowNull: false }, dateUpdated: { type: Sequelize.DATE, field: 'date_updated', allowNull: false }, datePublished: { type: Sequelize.DATE, field: 'date_published', allowNull: false } }); blogPostDatabaseDefinition.belongsTo(User, { as: 'author' }); export default blogPostDatabaseDefinition;
[fix] Replace Unicode space (U+00A0) with ASCII space
/* * config.js: Configuration information for your Loggly account. * This information is only used for require('loggly')./\.+/ methods * * (C) 2010 Nodejitsu Inc. * MIT LICENSE * */ // // function createConfig (defaults) // Creates a new instance of the configuration // object based on default values // exports.createConfig = function (defaults) { return new Config(defaults); }; // // Config (defaults) // Constructor for the Config object // var Config = exports.Config = function (defaults) { if (!defaults.subdomain) { throw new Error('Subdomain is required to create an instance of Config'); } this.subdomain = defaults.subdomain; this.json = defaults.json || null; this.auth = defaults.auth || null; }; Config.prototype = { get subdomain () { return this._subdomain; }, set subdomain (value) { this._subdomain = value; }, get logglyUrl () { return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api'; }, get inputUrl () { return 'https://logs.loggly.com/inputs/'; } };
/* * config.js: Configuration information for your Loggly account. * This information is only used for require('loggly')./\.+/ methods * * (C) 2010 Nodejitsu Inc. * MIT LICENSE * */ // // function createConfig (defaults) // Creates a new instance of the configuration // object based on default values // exports.createConfig = function (defaults) { return new Config(defaults); }; // // Config (defaults) // Constructor for the Config object // var Config = exports.Config = function (defaults) { if (!defaults.subdomain) { throw new Error('Subdomain is required to create an instance of Config'); } this.subdomain = defaults.subdomain; this.json = defaults.json || null; this.auth = defaults.auth || null; }; Config.prototype = { get subdomain () { return this._subdomain; }, set subdomain (value) { this._subdomain = value; }, get logglyUrl () { return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api'; }, get inputUrl () { return 'https://logs.loggly.com/inputs/'; } };
Test access token csv download Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
from takeyourmeds.utils.test import SuperuserTestCase class SmokeTest(SuperuserTestCase): def test_index(self): self.assertGET(200, 'groups:admin:index', login=True) def test_view(self): self.assertGET( 200, 'groups:admin:view', self.user.profile.group_id, login=True, ) def test_access_tokens_csv(self): self.assertGET( 200, 'groups:admin:access-tokens-csv', self.user.profile.group_id, login=True, ) def test_create_access_tokens(self): group = self.user.profile.group self.assertEqual(group.access_tokens.count(), 0) self.assertPOST( 302, {'num_tokens': 10}, 'groups:admin:create-access-tokens', group.pk, login=True, ) self.assertEqual(group.access_tokens.count(), 10)
from takeyourmeds.utils.test import SuperuserTestCase class SmokeTest(SuperuserTestCase): def test_index(self): self.assertGET(200, 'groups:admin:index', login=True) def test_view(self): self.assertGET( 200, 'groups:admin:view', self.user.profile.group_id, login=True, ) def test_create_access_tokens(self): group = self.user.profile.group self.assertEqual(group.access_tokens.count(), 0) self.assertPOST( 302, {'num_tokens': 10}, 'groups:admin:create-access-tokens', group.pk, login=True, ) self.assertEqual(group.access_tokens.count(), 10)
Fix query to WHERE In from WHERE
<?php namespace app\controllers; use app\models\FlightFilterForm; use app\models\OutdoorLogs; use app\models\forge\Brand; use yii\helpers\VarDumper; class FlightController extends \yii\web\Controller { public function actionIndex() { $model = new FlightFilterForm(); // profile $profile = \Yii::$app->user->identity->profile; // get brands for respective company $brands = Brand::find()->where(['company_id'=>$profile->type_id])->all(); if ($model->load(\Yii::$app->request->post())) { if ($model->validate()) { $logs = OutdoorLogs::find() ->where(['in','brand_id',$model->brand]) ->andWhere(['between','date_time',$model->start_date,$model->end_date]); return $this->render('result',[ 'logs'=>$logs ]); } } return $this->render('index', [ 'model' => $model, 'brands'=>$brands ]); } }
<?php namespace app\controllers; use app\models\FlightFilterForm; use app\models\OutdoorLogs; use app\models\forge\Brand; use yii\helpers\VarDumper; class FlightController extends \yii\web\Controller { public function actionIndex() { $model = new FlightFilterForm(); // profile $profile = \Yii::$app->user->identity->profile; // get brands for respective company $brands = Brand::find()->where(['company_id'=>$profile->type_id])->all(); if ($model->load(\Yii::$app->request->post())) { if ($model->validate()) { $logs = OutdoorLogs::find() ->where(['brand_id'=>$model->brand]) ->andWhere(['between','date_time',$model->start_date,$model->end_date]); return $this->render('result',[ 'logs'=>$logs ]); } } return $this->render('index', [ 'model' => $model, 'brands'=>$brands ]); } }
Set a flag when config is loaded on a browser
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. window.process = {}; window.process._RJS_baseUrl = function(n) { return ".."; }; window.process._RJS_rootDir = function(n) { if (n == 0) return "."; }; window.process._RJS_isBrowser = true; require.config({ /* http://requirejs.org/docs/api.html#config-waitSeconds */ waitSeconds: 1 });
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. window.process = {}; window.process._RJS_baseUrl = function(n) { return ".."; }; window.process._RJS_rootDir = function(n) { if (n == 0) return "."; }; require.config({ /* http://requirejs.org/docs/api.html#config-waitSeconds */ waitSeconds: 1 });
Fix a bug in the mesh optimizer.
# -*- coding: utf-8 -*- import re import uuid from abc import ABCMeta, abstractmethod import numpy as np class BaseReader(object): __metaclass__ = ABCMeta @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def _optimize(self, mesh): # Sort interior interfaces for f in filter(lambda f: re.match(r'^con_p\d+$', f), mesh): mesh[f] = mesh[f][:,np.argsort(mesh[f][0])] def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Perform some simple optimizations on the mesh self._optimize(mesh) # Add metadata mesh['mesh_uuid'] = str(uuid.uuid4()) return mesh
# -*- coding: utf-8 -*- import re import uuid import itertools as it from abc import ABCMeta, abstractmethod import numpy as np class BaseReader(object): __metaclass__ = ABCMeta @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def _optimize(self, mesh): # Sort interior interfaces for f in it.ifilter(lambda f: re.match('con_p\d+', f), mesh): mesh[f] = mesh[f][:,np.argsort(mesh[f][0])] def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Perform some simple optimizations on the mesh self._optimize(mesh) # Add metadata mesh['mesh_uuid'] = str(uuid.uuid4()) return mesh
Add dot also to env prefix
package com.coding4people.mosquitoreport.api.factories; import java.util.Optional; import javax.inject.Inject; import org.glassfish.hk2.api.Factory; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride; import com.coding4people.mosquitoreport.api.Env; public class DynamoDBMapperFactory implements Factory<DynamoDBMapper> { DynamoDBMapper mapper; @Inject public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) { mapper = new DynamoDBMapper(client, new DynamoDBMapperConfig.Builder() .withTableNameOverride(TableNameOverride.withTableNamePrefix(Optional .ofNullable(env.get("MOSQUITO_REPORT_DYNAMODB_TABLE_PREFIX")).orElse("localhost") + ".")) .build()); } @Override public void dispose(DynamoDBMapper mapper) { } @Override public DynamoDBMapper provide() { return mapper; } }
package com.coding4people.mosquitoreport.api.factories; import java.util.Optional; import javax.inject.Inject; import org.glassfish.hk2.api.Factory; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride; import com.coding4people.mosquitoreport.api.Env; public class DynamoDBMapperFactory implements Factory<DynamoDBMapper> { DynamoDBMapper mapper; @Inject public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) { mapper = new DynamoDBMapper(client, new DynamoDBMapperConfig.Builder() .withTableNameOverride(TableNameOverride.withTableNamePrefix(Optional .ofNullable(env.get("MOSQUITO_REPORT_DYNAMODB_TABLE_PREFIX")).orElse("localhost."))) .build()); } @Override public void dispose(DynamoDBMapper mapper) { } @Override public DynamoDBMapper provide() { return mapper; } }
Include threadName in DEBUG format
import sys import logging DEBUG_FORMAT = ("[%(asctime)s] %(levelname)s %(threadName)s " "%(name)s:%(lineno)d(%(funcName)s): %(message)s") INFO_FORMAT = ("[%(asctime)s] %(message)s") COLOR_FORMAT = ("[%(asctime)s] \033[%(color)sm%(message)s\033[39m") ISO_8601 = "%Y-%m-%dT%H:%M:%S" class ColorFormatter(logging.Formatter): """ Handles colorizing formatted log messages if color provided. """ def format(self, record): if 'color' not in record.__dict__: record.__dict__['color'] = 37 msg = super(ColorFormatter, self).format(record) return msg def setup_logging(verbosity): log_level = logging.INFO log_format = INFO_FORMAT if sys.stdout.isatty(): log_format = COLOR_FORMAT if verbosity > 0: log_level = logging.DEBUG log_format = DEBUG_FORMAT if verbosity < 2: logging.getLogger("botocore").setLevel(logging.CRITICAL) hdlr = logging.StreamHandler() hdlr.setFormatter(ColorFormatter(log_format, ISO_8601)) logging.root.addHandler(hdlr) logging.root.setLevel(log_level)
import sys import logging DEBUG_FORMAT = ("[%(asctime)s] %(levelname)s %(name)s:%(lineno)d" "(%(funcName)s): %(message)s") INFO_FORMAT = ("[%(asctime)s] %(message)s") COLOR_FORMAT = ("[%(asctime)s] \033[%(color)sm%(message)s\033[39m") ISO_8601 = "%Y-%m-%dT%H:%M:%S" class ColorFormatter(logging.Formatter): """ Handles colorizing formatted log messages if color provided. """ def format(self, record): if 'color' not in record.__dict__: record.__dict__['color'] = 37 msg = super(ColorFormatter, self).format(record) return msg def setup_logging(verbosity): log_level = logging.INFO log_format = INFO_FORMAT if sys.stdout.isatty(): log_format = COLOR_FORMAT if verbosity > 0: log_level = logging.DEBUG log_format = DEBUG_FORMAT if verbosity < 2: logging.getLogger("botocore").setLevel(logging.CRITICAL) hdlr = logging.StreamHandler() hdlr.setFormatter(ColorFormatter(log_format, ISO_8601)) logging.root.addHandler(hdlr) logging.root.setLevel(log_level)
Print stack traces from failed `meteor {node,npm}` commands.
// Note that this file is required before we install our Babel hooks in // ../tool-env/install-babel.js, so we can't use ES2015+ syntax here. var win32Extensions = { node: ".exe", npm: ".cmd" }; // The dev_bundle/bin command has to come immediately after the meteor // command, as in `meteor npm` or `meteor node`, because we don't want to // require("./main.js") for these commands. var devBundleBinCommand = process.argv[2]; var args = process.argv.slice(3); function getChildProcess() { if (! win32Extensions.hasOwnProperty(devBundleBinCommand)) { return Promise.resolve(null); } var helpers = require("./dev-bundle-bin-helpers.js"); if (process.platform === "win32") { devBundleBinCommand += win32Extensions[devBundleBinCommand]; } return Promise.all([ helpers.getCommandPath(devBundleBinCommand), helpers.getEnv() ]).then(function (cmdAndEnv) { var cmd = cmdAndEnv[0]; var env = cmdAndEnv[1]; var child = require("child_process").spawn(cmd, args, { stdio: "inherit", env: env }); require("./flush-buffers-on-exit-in-windows.js"); child.on("error", function (error) { console.log(error.stack || error); }); child.on("exit", function (exitCode) { process.exit(exitCode); }); return child; }); } module.exports = getChildProcess();
// Note that this file is required before we install our Babel hooks in // ../tool-env/install-babel.js, so we can't use ES2015+ syntax here. var win32Extensions = { node: ".exe", npm: ".cmd" }; // The dev_bundle/bin command has to come immediately after the meteor // command, as in `meteor npm` or `meteor node`, because we don't want to // require("./main.js") for these commands. var devBundleBinCommand = process.argv[2]; var args = process.argv.slice(3); function getChildProcess() { if (! win32Extensions.hasOwnProperty(devBundleBinCommand)) { return Promise.resolve(null); } var helpers = require("./dev-bundle-bin-helpers.js"); if (process.platform === "win32") { devBundleBinCommand += win32Extensions[devBundleBinCommand]; } return Promise.all([ helpers.getCommandPath(devBundleBinCommand), helpers.getEnv() ]).then(function (cmdAndEnv) { var cmd = cmdAndEnv[0]; var env = cmdAndEnv[1]; var child = require("child_process").spawn(cmd, args, { stdio: "inherit", env: env }); require("./flush-buffers-on-exit-in-windows.js"); child.on("exit", function (exitCode) { process.exit(exitCode); }); return child; }); } module.exports = getChildProcess();
Fix to CHT station name
from data_importers.management.commands import BaseHalaroseCsvImporter class Command(BaseHalaroseCsvImporter): council_id = "CHT" addresses_name = ( "2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv" ) stations_name = ( "2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv" ) elections = ["2022-05-05"] def address_record_to_dict(self, record): if record.housepostcode in [ "GL50 2RF", "GL52 6RN", "GL52 2ES", "GL53 7AJ", "GL50 3RB", "GL53 0HL", "GL50 2DZ", ]: return None return super().address_record_to_dict(record) def station_record_to_dict(self, record): if record.pollingstationnumber == "191": record = record._replace(pollingstationaddress_1="") return super().station_record_to_dict(record)
from data_importers.management.commands import BaseHalaroseCsvImporter class Command(BaseHalaroseCsvImporter): council_id = "CHT" addresses_name = ( "2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv" ) stations_name = ( "2022-05-05/2022-02-25T12:48:35.558843/polling_station_export-2022-02-25.csv" ) elections = ["2022-05-05"] def address_record_to_dict(self, record): if record.housepostcode in [ "GL50 2RF", "GL52 6RN", "GL52 2ES", "GL53 7AJ", "GL50 3RB", "GL53 0HL", "GL50 2DZ", ]: return None return super().address_record_to_dict(record)
Make port dynamic for Heroku
var express = require('express'), cons = require('consolidate'), app = express(), mustacheRender = require("./lib/mustacheRender").mustacheRender, port = (process.env.PORT || 3000); // Application settings app.engine('html', cons.mustache); app.set('view engine', 'html'); app.set('views', __dirname + '/views'); // Middleware to serve static assets app.use('/public', express.static(__dirname + '/public')); app.use('/public', express.static(__dirname + '/govuk/public')); // middleware to wrap mustache views in govuk template app.use(mustacheRender); // var commonHead = '<link href="/public/stylesheets/application.css" rel="stylesheet" type="text/css" />'; // routes app.get('/', function (req, res) { var head = commonHead; res.render('index', {'pageTitle': 'index', 'head' : head }); }); app.get('/sample', function (req, res) { var head = commonHead; res.render('sample', {'pageTitle': 'sample', 'head' : head }); }); // start the app app.listen(port); console.log(''); console.log('Listening on port ' + port); console.log('');
var express = require('express'), cons = require('consolidate'), app = express(), mustacheRender = require("./lib/mustacheRender").mustacheRender; // Application settings app.engine('html', cons.mustache); app.set('view engine', 'html'); app.set('views', __dirname + '/views'); // Middleware to serve static assets app.use('/public', express.static(__dirname + '/public')); app.use('/public', express.static(__dirname + '/govuk/public')); // middleware to wrap mustache views in govuk template app.use(mustacheRender); // var commonHead = '<link href="/public/stylesheets/application.css" rel="stylesheet" type="text/css" />'; // routes app.get('/', function (req, res) { var head = commonHead; res.render('index', {'pageTitle': 'index', 'head' : head }); }); app.get('/sample', function (req, res) { var head = commonHead; res.render('sample', {'pageTitle': 'sample', 'head' : head }); }); // start the app app.listen(3000); console.log(''); console.log('Listening on port 3000'); console.log('');
Allow partial maches in span names
'use strict'; define( [ 'flight/lib/component' ], function (defineComponent) { return defineComponent(spanName); function spanName() { this.updateSpans = function(ev, data) { var html = "<option value='all'>all</option>" + $.map(data.spans, function(span) { return "<option value='"+span+"'>"+span+"</option>"; }).join(""); this.$node.html(html); this.trigger('chosen:updated'); }; this.after('initialize', function() { this.$node.chosen( { search_contains: true }); this.on(document, 'dataSpanNames', this.updateSpans); }); } } );
'use strict'; define( [ 'flight/lib/component' ], function (defineComponent) { return defineComponent(spanName); function spanName() { this.updateSpans = function(ev, data) { var html = "<option value='all'>all</option>" + $.map(data.spans, function(span) { return "<option value='"+span+"'>"+span+"</option>"; }).join(""); this.$node.html(html); this.trigger('chosen:updated'); }; this.after('initialize', function() { this.$node.chosen(); this.on(document, 'dataSpanNames', this.updateSpans); }); } } );
Check for errors from SetKeepAlive and SetKeepAlivePeriod in TCPKeepAliveListener Accept method
// Copyright (c) 2017, Janoš Guljaš <janos@resenje.org> // All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package web import ( "net" "time" ) // TCPKeepAliveListener sets TCP keep alive period. type TCPKeepAliveListener struct { *net.TCPListener } // NewTCPKeepAliveListener creates TCPKeepAliveListener // from net.TCPListener. func NewTCPKeepAliveListener(listener *net.TCPListener) TCPKeepAliveListener { return TCPKeepAliveListener{TCPListener: listener} } // Accept accepts TCP connection and sets TCP keep alive period func (ln TCPKeepAliveListener) Accept() (c net.Conn, err error) { tc, err := ln.AcceptTCP() if err != nil { return } if err := tc.SetKeepAlive(true); err != nil { return nil, err } if err := tc.SetKeepAlivePeriod(3 * time.Minute); err != nil { return nil, err } return tc, nil }
// Copyright (c) 2017, Janoš Guljaš <janos@resenje.org> // All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package web import ( "net" "time" ) // TCPKeepAliveListener sets TCP keep alive period. type TCPKeepAliveListener struct { *net.TCPListener } // NewTCPKeepAliveListener creates TCPKeepAliveListener // from net.TCPListener. func NewTCPKeepAliveListener(listener *net.TCPListener) TCPKeepAliveListener { return TCPKeepAliveListener{TCPListener: listener} } // Accept accepts TCP connection and sets TCP keep alive period func (ln TCPKeepAliveListener) Accept() (c net.Conn, err error) { tc, err := ln.AcceptTCP() if err != nil { return } tc.SetKeepAlive(true) tc.SetKeepAlivePeriod(3 * time.Minute) return tc, nil }
Add forgotten dependency on mock
from setuptools import setup, find_packages from annotator import __version__, __license__, __author__ setup( name = 'annotator', version = __version__, packages = find_packages(), install_requires = [ 'Flask==0.8', 'Flask-WTF==0.5.2', 'Flask-SQLAlchemy==0.15', 'SQLAlchemy==0.7.4', 'pyes==0.16.0', 'nose==1.0.0', 'mock==0.7.4', 'iso8601==0.1.4' ], # metadata for upload to PyPI author = __author__, author_email = 'annotator@okfn.org', description = 'Inline web annotation application and middleware using javascript and WSGI', long_description = """Inline javascript-based web annotation library. \ Package includeds a database-backed annotation store \ with RESTFul (WSGI-powered) web-interface.""", license = __license__, keywords = 'annotation web javascript', url = 'http://okfnlabs.org/annotator/', download_url = 'https://github.com/okfn/annotator-store', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python' ], )
from setuptools import setup, find_packages from annotator import __version__, __license__, __author__ setup( name = 'annotator', version = __version__, packages = find_packages(), install_requires = [ 'Flask==0.8', 'Flask-WTF==0.5.2', 'Flask-SQLAlchemy==0.15', 'SQLAlchemy==0.7.4', 'pyes==0.16.0', 'nose==1.0.0', 'iso8601==0.1.4' ], # metadata for upload to PyPI author = __author__, author_email = 'annotator@okfn.org', description = 'Inline web annotation application and middleware using javascript and WSGI', long_description = """Inline javascript-based web annotation library. \ Package includeds a database-backed annotation store \ with RESTFul (WSGI-powered) web-interface.""", license = __license__, keywords = 'annotation web javascript', url = 'http://okfnlabs.org/annotator/', download_url = 'https://github.com/okfn/annotator-store', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python' ], )
Webpack: Add library target to run it in browser
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: {algorithms: './src/index.js', 'algorithms.min': './src/index.js'}, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js', library: 'alds' }, module: { rules: [{ test: [/\.es6$/, /\.js$/], exclude: /(node_modules|bower_components)/, use: {loader: 'babel-loader', options: {presets: 'es2015'}} }] }, plugins: [new webpack.optimize.UglifyJsPlugin( {include: /\.min\.js$/, minimize: true})], devServer: { contentBase: path.resolve(__dirname, 'dist'), compress: true, port: 9000 } };
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { algorithms: './src/index.js', 'algorithms.min': './src/index.js' }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js' }, module: { rules: [{ test: [/\.es6$/, /\.js$/], exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: 'es2015' } } }] }, plugins: [new webpack.optimize.UglifyJsPlugin( { include: /\.min\.js$/, minimize: true })], devServer: { contentBase: path.resolve(__dirname, 'dist'), compress: true, port: 9000 } };
Change paths to hash-based for "development" env
/* jshint node: true */ module.exports = function(environment) { var ENV = { environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // LOG_MODULE_RESOLVER is needed for pre-1.6.0 ENV.LOG_MODULE_RESOLVER = true; ENV.APP.LOG_RESOLVER = false; ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_MODULE_RESOLVER = false; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.locationType = 'hash'; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // LOG_MODULE_RESOLVER is needed for pre-1.6.0 ENV.LOG_MODULE_RESOLVER = true; ENV.APP.LOG_RESOLVER = false; ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_MODULE_RESOLVER = false; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = false; } if (environment === 'production') { } return ENV; };
Change detection to ignore borders
;(function(window, document){ document.addEventListener('touchmove', function(e) { isScrollElement(e.target) || e.preventDefault(); }, false); document.addEventListener('touchstart', function(e){ var elem = isScrollElement(e.target); var startTopScroll = 0; if(elem) { startTopScroll = elem.scrollTop; if(startTopScroll <= 0) { elem.scrollTop = 1; } if(startTopScroll + elem.clientHeight >= elem.scrollHeight) { elem.scrollTop = elem.scrollHeight - elem.clientHeight - 1; } } }, false); function isScrollElement(element) { while(element) { if ( (window.getComputedStyle(element).overflow === 'scroll' || window.getComputedStyle(element)["overflow-y"] === 'scroll' || window.getComputedStyle(element)["overflow-x"] === 'scroll') && element.scrollHeight > window.innerHeight ) { return element; } element = element.parentElement; } return false; } })(window, document);
;(function(window, document){ document.addEventListener('touchmove', function(e) { isScrollElement(e.target) || e.preventDefault(); }, false); document.addEventListener('touchstart', function(e){ var elem = isScrollElement(e.target); if(elem) { var startTopScroll = elem.scrollTop; if(startTopScroll <= 0) { elem.scrollTop = 1; } if(startTopScroll + elem.offsetHeight >= elem.scrollHeight) { elem.scrollTop = elem.scrollHeight - elem.offsetHeight - 1; } } }, false); function isScrollElement(element) { while(element) { if ( (window.getComputedStyle(element).overflow === 'scroll' || window.getComputedStyle(element)["overflow-y"] === 'scroll' || window.getComputedStyle(element)["overflow-x"] === 'scroll') && element.scrollHeight > window.innerHeight ) { return element; } element = element.parentElement; } return false; } })(window, document);
Move class list logic to it's own function
CenterScout.controller('HomeController', ['$scope', 'gradeData', 'assignmentData', function($scope, gradeData, assignmentData) { $scope.grades = [{ name: 'Loading...', class: '', date: '', percent: '', fraction: ''}]; $scope.assignments = [{ done: false, name: 'Loading...', class: '', date: ''}]; // TODO: Find a better way of doing this hack $scope.courses = ['M', 'CAD']; // TODO: Find a way to use the PowerSchool names for only the classes in lfhs.or $scope.selectedCourse = '...'; $scope.setSelectedCourse = function() { $scope.selectedCourse = this.course; }; var updateClassList = function(grades) { grades.forEach(function(grade) { if($scope.courses.indexOf(grade.class) === -1) $scope.courses.push(grade.class); }); $scope.selectedCourse = $scope.courses[0]; }; gradeData().then(function(grades) { $scope.grades = grades; updateClassList(grades); }, handleError); assignmentData().then(function(assignments) { $scope.assignments = assignments; }, handleError); }]); CenterScout.controller('ClassController', ['$scope', function($scope) { }]); CenterScout.controller('AboutController', ['$scope', function($scope) { }]); CenterScout.controller('ErrorController', ['$scope', function($scope) { }]);
CenterScout.controller('HomeController', ['$scope', 'gradeData', 'assignmentData', function($scope, gradeData, assignmentData) { $scope.grades = [{ name: 'Loading...', class: '', date: '', percent: '', fraction: ''}]; $scope.assignments = [{ done: false, name: 'Loading...', class: '', date: ''}]; // TODO: Find a better way of doing this hack $scope.courses = ['M', 'CAD']; // TODO: Find a way to use the PowerSchool names for only the classes in lfhs.or $scope.selectedCourse = '...'; $scope.setSelectedCourse = function() { $scope.selectedCourse = this.course; }; gradeData().then(function(grades) { $scope.grades = grades; grades.forEach(function(grade) { if($scope.courses.indexOf(grade.class) === -1) $scope.courses.push(grade.class); }); $scope.selectedCourse = $scope.courses[0]; }, handleError); assignmentData().then(function(assignments) { $scope.assignments = assignments; }, handleError); }]); CenterScout.controller('ClassController', ['$scope', function($scope) { }]); CenterScout.controller('AboutController', ['$scope', function($scope) { }]); CenterScout.controller('ErrorController', ['$scope', function($scope) { }]);