text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix some PHP Strict standards errors in tests.
<?php use Mockery as m; abstract class AcTestCase extends Orchestra\Testbench\TestCase { protected $app; protected $router; public function tearDown() { parent::tearDown(); m::close(); } protected function mock($className) { $mock = m::mock($className); App::bind($className, function ($app, $parameters = []) use ($mock) { if (is_array($parameters) && is_array($attributes = array_get($parameters, 0, [])) && respond_to($mock, "fill")) { $mock = $this->fillMock($mock, $attributes); } return $mock; }); return $mock; } protected function fillMock($mock, $attributes = []) { $instance = $mock->makePartial(); foreach ($attributes as $key => $value) { $instance->$key = $value; } return $instance; } protected function getPackageProviders($app) { return [ 'Collective\Html\HtmlServiceProvider', 'Efficiently\AuthorityController\AuthorityControllerServiceProvider', ]; } protected function getPackageAliases($app) { return [ 'Form' => 'Collective\Html\FormFacade', 'Html' => 'Collective\Html\HtmlFacade', 'Authority' => 'Efficiently\AuthorityController\Facades\Authority', 'Params' => 'Efficiently\AuthorityController\Facades\Params', ]; } }
<?php use Mockery as m; abstract class AcTestCase extends Orchestra\Testbench\TestCase { protected $app; protected $router; public function tearDown() { parent::tearDown(); m::close(); } protected function mock($className) { $mock = m::mock($className); App::bind($className, function ($app, $parameters = []) use ($mock) { if (is_array($parameters) && is_array($attributes = array_get($parameters, 0, [])) && respond_to($mock, "fill")) { $mock = $this->fillMock($mock, $attributes); } return $mock; }); return $mock; } protected function fillMock($mock, $attributes = []) { $instance = $mock->makePartial(); foreach ($attributes as $key => $value) { $instance->$key = $value; } return $instance; } protected function getPackageProviders() { return [ 'Collective\Html\HtmlServiceProvider', 'Efficiently\AuthorityController\AuthorityControllerServiceProvider', ]; } protected function getPackageAliases() { return [ 'Form' => 'Collective\Html\FormFacade', 'Html' => 'Collective\Html\HtmlFacade', 'Authority' => 'Efficiently\AuthorityController\Facades\Authority', 'Params' => 'Efficiently\AuthorityController\Facades\Params', ]; } }
Fix for MRV failing to enter enable mode
"""MRV Communications Driver (OptiSwitch).""" from __future__ import unicode_literals import time import re from netmiko.cisco_base_connection import CiscoSSHConnection class MrvOptiswitchSSH(CiscoSSHConnection): """MRV Communications Driver (OptiSwitch).""" def session_preparation(self): """Prepare the session after the connection has been established.""" self._test_channel_read(pattern=r'[>#]') self.set_base_prompt() self.enable() self.disable_paging(command="no cli-paging") # Clear the read buffer time.sleep(.3 * self.global_delay_factor) self.set_base_prompt() self.clear_buffer() def enable(self, cmd='enable', pattern=r'#', re_flags=re.IGNORECASE): """Enable mode on MRV uses no password.""" output = "" if not self.check_enable_mode(): self.write_channel(self.normalize_cmd(cmd)) output += self.read_until_prompt_or_pattern(pattern=pattern, re_flags=re_flags) if not self.check_enable_mode(): msg = "Failed to enter enable mode. Please ensure you pass " \ "the 'secret' argument to ConnectHandler." raise ValueError(msg) return output def save_config(self, cmd='save config flash', confirm=False): """Saves configuration.""" return super(MrvOptiswitchSSH, self).save_config(cmd=cmd, confirm=confirm)
"""MRV Communications Driver (OptiSwitch).""" from __future__ import unicode_literals import time import re from netmiko.cisco_base_connection import CiscoSSHConnection class MrvOptiswitchSSH(CiscoSSHConnection): """MRV Communications Driver (OptiSwitch).""" def session_preparation(self): """Prepare the session after the connection has been established.""" self._test_channel_read(pattern=r'[>#]') self.enable() self.set_base_prompt() self.disable_paging(command="no cli-paging") # Clear the read buffer time.sleep(.3 * self.global_delay_factor) self.clear_buffer() def enable(self, cmd='enable', pattern=r'#', re_flags=re.IGNORECASE): """Enable mode on MRV uses no password.""" output = "" if not self.check_enable_mode(): self.write_channel(self.normalize_cmd(cmd)) output += self.read_until_prompt_or_pattern(pattern=pattern, re_flags=re_flags) if not self.check_enable_mode(): msg = "Failed to enter enable mode. Please ensure you pass " \ "the 'secret' argument to ConnectHandler." raise ValueError(msg) return output def save_config(self, cmd='save config flash', confirm=False): """Saves configuration.""" return super(MrvOptiswitchSSH, self).save_config(cmd=cmd, confirm=confirm)
Remove slash from chapters partial path The slash must be added to ovPlayerDirectory variable, not directly to the path of the partial
(function(app){ "use strict" /** * Creates a new HTML element ov-index to create an openVeo player * index, with a list of presentation slides. * It requires ovPlayerDirectory global variable to be defined and have * a value corresponding to the path of the openVeo Player * root directory. * * e.g. * <ov-index></ov-index> */ app.directive("ovChapters", ovChapters); ovChapters.$inject = ["ovChaptersLink"]; function ovChapters(ovChaptersLink){ return { require : "^ovPlayer", restrict : "E", templateUrl : ovPlayerDirectory + "templates/chapters.html", scope : true, link : ovChaptersLink } } app.factory("ovChaptersLink", function(){ return function(scope, element, attrs, playerCtrl){ scope.chapters = scope.data.chapter; scope.open = function(chapter){ if(!chapter.isOpen) angular.forEach(scope.chapters, function (value, key) { value.isOpen = false; }); chapter.isOpen = !chapter.isOpen; } /** * Seeks media to the given timecode. * @param Number timecode The timecode to seek to */ scope.goToTimecode = function(time){ if(time <= 1) playerCtrl.player.setTime(time * scope.duration); }; }; }); })(angular.module("ov.player"));
(function(app){ "use strict" /** * Creates a new HTML element ov-index to create an openVeo player * index, with a list of presentation slides. * It requires ovPlayerDirectory global variable to be defined and have * a value corresponding to the path of the openVeo Player * root directory. * * e.g. * <ov-index></ov-index> */ app.directive("ovChapters", ovChapters); ovChapters.$inject = ["ovChaptersLink"]; function ovChapters(ovChaptersLink){ return { require : "^ovPlayer", restrict : "E", templateUrl : ovPlayerDirectory + "/templates/chapters.html", scope : true, link : ovChaptersLink } } app.factory("ovChaptersLink", function(){ return function(scope, element, attrs, playerCtrl){ scope.chapters = scope.data.chapter; scope.open = function(chapter){ if(!chapter.isOpen) angular.forEach(scope.chapters, function (value, key) { value.isOpen = false; }); chapter.isOpen = !chapter.isOpen; } /** * Seeks media to the given timecode. * @param Number timecode The timecode to seek to */ scope.goToTimecode = function(time){ if(time <= 1) playerCtrl.player.setTime(time * scope.duration); }; }; }); })(angular.module("ov.player"));
Update Trove classifier to include Python 3.7
from setuptools import setup setup( name='snappass', version='1.3.0', description="It's like SnapChat... for Passwords.", long_description=(open('README.rst').read() + '\n\n' + open('AUTHORS.rst').read()), url='http://github.com/Pinterest/snappass/', install_requires=['Flask', 'redis', 'cryptography'], license='MIT', author='Dave Dash', author_email='[email protected]', packages=['snappass'], entry_points={ 'console_scripts': [ 'snappass = snappass.main:main', ], }, include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Software Development :: Libraries :: Python Modules', ], zip_safe=False, )
from setuptools import setup setup( name='snappass', version='1.3.0', description="It's like SnapChat... for Passwords.", long_description=(open('README.rst').read() + '\n\n' + open('AUTHORS.rst').read()), url='http://github.com/Pinterest/snappass/', install_requires=['Flask', 'redis', 'cryptography'], license='MIT', author='Dave Dash', author_email='[email protected]', packages=['snappass'], entry_points={ 'console_scripts': [ 'snappass = snappass.main:main', ], }, include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Python Modules', ], zip_safe=False, )
Hide the affiliate modal in the e2e theme download tests.
/* Tests for themes generation */ describe('Themes', function () { var async = function(arr, delay, done) { var j = 0; var runner = function() { setTimeout(function() { if(j === arr.length) { return done(); } console.log('async ', arr.length - j); arr[j](); j++; runner(); }, delay) } runner(); }; var downloadPicture = function(elem) { return function() { elem.getAttribute('href') .then(function(href) { console.log('Downloading ', href); }); elem .click() .then(element(by.css('#js-download-button')).click) .then(element(by.css('#drop-downloads a[ng-click*="DownloadPicture()"]')).click) } }; it('should open the page', function () { browser.get('#/'); expect(true).toBe(true); }); it('should download a picture of each theme', function (done) { var downloads = []; // hide the affiliate modal browser.executeScript('window.localStorage.setItem("bizcardmaker-affiliate-modal", "true");'); element.all(by.css('.themes-row a')) .each(function(elem) { downloads.push(downloadPicture(elem)); }) .then(function() { async(downloads, 1500, function() { expect(true).toBe(true); done(); }); }) }); })
/* Tests for themes generation */ describe('Themes', function () { var async = function(arr, delay, done) { var j = 0; var runner = function() { setTimeout(function() { if(j === arr.length) { return done(); } console.log('async ', arr.length - j); arr[j](); j++; runner(); }, delay) } runner(); }; var downloadPicture = function(elem) { return function() { elem.getAttribute('href') .then(function(href) { console.log('Downloading ', href); }); elem .click() .then(element(by.css('#js-download-button')).click) .then(element(by.css('#drop-downloads a[ng-click*="DownloadPicture()"]')).click) } }; it('should open the page', function () { browser.get('#/'); expect(true).toBe(true); }); it('should download a picture of each theme', function (done) { var downloads = []; element.all(by.css('.themes-row a')) .each(function(elem) { downloads.push(downloadPicture(elem)); }) .then(function() { async(downloads, 1500, function() { expect(true).toBe(true); done(); }); }) }); })
Add a few spaces for easier copy-paste
""" A script to scrape all the function exports from the PASS_FTN.FOR By Ian Bell, NIST, January 2018 """ import os from generate_header import generate_interface_file, generate_function_dict if __name__=='__main__': generate_interface_file('R:/FORTRAN/PASS_FTN.FOR','REFPROP.PYF',verbose=False,python_exe='python') funcs = generate_function_dict('REFPROP.PYF') for func in sorted(funcs): print(' X(' + func + ') \\') for func in sorted(funcs): string_lengths = [] types = [] for arg in funcs[func]['argument_list']: if len(arg) == 3: name, _type, size = arg else: name, _type = arg size = 0 if _type == 'double *' and size == 0: types.append('DOUBLE_REF') elif _type == 'double *' and size != 0: types.append('double *') elif _type == 'int *' and size == 0: types.append('INT_REF') elif _type == 'int *' and size != 0: types.append('int *') elif _type == 'char *': types.append('char *') string_lengths.append('RP_SIZE_T') else: print(types) raise ValueError() print(' '*4+'#define '+func+'_ARGS '+','.join(types+string_lengths))
""" A script to scrape all the function exports from the PASS_FTN.FOR By Ian Bell, NIST, January 2018 """ import os from generate_header import generate_interface_file, generate_function_dict if __name__=='__main__': generate_interface_file('R:/FORTRAN/PASS_FTN.FOR','REFPROP.PYF',verbose=False,python_exe='python') funcs = generate_function_dict('REFPROP.PYF') for func in sorted(funcs): print(' X(' + func + ') \\') for func in sorted(funcs): string_lengths = [] types = [] for arg in funcs[func]['argument_list']: if len(arg) == 3: name, _type, size = arg else: name, _type = arg size = 0 if _type == 'double *' and size == 0: types.append('DOUBLE_REF') elif _type == 'double *' and size != 0: types.append('double *') elif _type == 'int *' and size == 0: types.append('INT_REF') elif _type == 'int *' and size != 0: types.append('int *') elif _type == 'char *': types.append('char *') string_lengths.append('RP_SIZE_T') else: print(types) raise ValueError() print('#define '+func+'_ARGS '+','.join(types+string_lengths))
Replace config() helper for Lumen
<?php namespace Neves\Events; use Illuminate\Support\ServiceProvider; use Illuminate\Contracts\Events\Dispatcher as EventDispatcher; class EventServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom( __DIR__.'/../../config/transactional-events.php', 'transactional-events' ); if (! $this->app['config']->get('transactional-events.enable')) { return; } $connectionResolver = $this->app->make('db'); $eventDispatcher = $this->app->make(EventDispatcher::class); $this->app->extend('events', function () use ($connectionResolver, $eventDispatcher) { $dispatcher = new TransactionalDispatcher($connectionResolver, $eventDispatcher); $dispatcher->setTransactionalEvents($this->app['config']->get('transactional-events.transactional')); $dispatcher->setExcludedEvents($this->app['config']->get('transactional-events.excluded')); return $dispatcher; }); } /** * Bootstrap the application events. * * @return void */ public function boot() { $configPath = app()->basePath() . '/config'; $this->publishes([ __DIR__.'/../../config/transactional-events.php' => $configPath.'/transactional-events.php', ]); } }
<?php namespace Neves\Events; use Illuminate\Support\ServiceProvider; use Illuminate\Contracts\Events\Dispatcher as EventDispatcher; class EventServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom( __DIR__.'/../../config/transactional-events.php', 'transactional-events' ); if (! $this->app['config']->get('transactional-events.enable')) { return; } $connectionResolver = $this->app->make('db'); $eventDispatcher = $this->app->make(EventDispatcher::class); $this->app->extend('events', function () use ($connectionResolver, $eventDispatcher) { $dispatcher = new TransactionalDispatcher($connectionResolver, $eventDispatcher); $dispatcher->setTransactionalEvents($this->app['config']->get('transactional-events.transactional')); $dispatcher->setExcludedEvents($this->app['config']->get('transactional-events.excluded')); return $dispatcher; }); } /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../../config/transactional-events.php' => config_path('transactional-events.php'), ]); } }
Remove dubugger; statement from auth controller.
(function() { 'use strict'; angular.module('pub.security.authentication', []) .factory('authentication', [ '$q', '$http', 'securityContext', function($q, $http, securityContext) { var authentication = { requestSecurityContext: function() { if (securityContext.authenticated) { return $q.when(securityContext); } else { var deferred = $q.defer(); $http.get('/users/current', null).success(function(user) { deferred.resolve(securityContext.setAuthentication(user)); }) return deferred.promise; } }, login: function(user, success, error) { $http.post('/login', user, null) .success(function(user) { success(user); securityContext.setAuthentication(user); }) .error(error); }, logout: function(success, error) { securityContext.reset(); $http.get('/logout').success(success).error(error); } } return authentication; } ]); }());
(function() { 'use strict'; angular.module('pub.security.authentication', []) .factory('authentication', [ '$q', '$http', 'securityContext', function($q, $http, securityContext) { var authentication = { requestSecurityContext: function() { debugger; if (securityContext.authenticated) { return $q.when(securityContext); } else { var deferred = $q.defer(); $http.get('/users/current', null).success(function(user) { deferred.resolve(securityContext.setAuthentication(user)); }) return deferred.promise; } }, login: function(user, success, error) { $http.post('/login', user, null) .success(function(user) { success(user); securityContext.setAuthentication(user); }) .error(error); }, logout: function(success, error) { securityContext.reset(); $http.get('/logout').success(success).error(error); } } return authentication; } ]); }());
Fix metadata template import on OS X
import importlib import pkgutil import sys from collections import OrderedDict from inselect.lib.metadata import MetadataTemplate from inselect.lib.utils import debug_print from inselect.lib.templates import dwc, price if True: _library = {} for template in [p.template for p in (dwc, price)]: _library[template.name] = template _library = OrderedDict(sorted(_library.iteritems())) def library(): return _library else: # More flexible solution that breaks with frozen build on OS X using # PyInstaller _library = None def library(): """Returns a list of MetadataTemplate instances """ global _library if not _library: _library = _load_library() return _library def _load_library(): # Import everything inselect.lib.templates that has a 'template' name # that is an instance of MetadataTemplate. # Returns an instance of OrderedDict with items sorted by key. templates = importlib.import_module('inselect.lib.templates') library = {} for loader, name, is_pkg in pkgutil.iter_modules(templates.__path__): try: pkg = importlib.import_module('{0}.{1}'.format(templates.__name__, name)) except ImportError,e: debug_print(u'Error importing [{0}]: [{1}]'.format(name, e)) else: template = getattr(pkg, 'template', None) if isinstance(template, MetadataTemplate): debug_print('Loaded MetadataTemplate from [{0}]'.format(name)) # TODO Raise if duplicated name library[template.name] = template else: msg = u'Not an instance of MetadataTemplate [{0}]' debug_print(msg.format(name)) return OrderedDict(sorted(library.iteritems()))
import importlib import pkgutil import sys from collections import OrderedDict from inselect.lib.metadata import MetadataTemplate from inselect.lib.utils import debug_print _library = None def library(): """Returns a list of MetadataTemplate instances """ global _library if not _library: _library = _load_library() return _library def _load_library(): # Import everything inselect.lib.templates that has a 'template' name # that is an instance of MetadataTemplate. # Returns an instance of OrderedDict with items sorted by key. try: templates = importlib.import_module('.lib.templates', 'inselect') except ImportError,e: debug_print(e) else: library = {} for loader, name, is_pkg in pkgutil.iter_modules(templates.__path__): try: pkg = importlib.import_module('{0}.{1}'.format(templates.__name__, name)) except ImportError,e: debug_print(u'Error importing [{0}]: [{1}]'.format(name, e)) else: template = getattr(pkg, 'template', None) if isinstance(template, MetadataTemplate): debug_print('Loaded MetadataTemplate from [{0}]'.format(name)) # TODO Raise if duplicated name library[template.name] = template else: msg = u'Not an instance of MetadataTemplate [{0}]' debug_print(msg.format(name)) return OrderedDict(sorted(library.iteritems()))
Enable table controls for WYSIWYG editor
tinyMCE.init({ theme:"advanced", mode:"none", plugins: "contextmenu,paste,spellchecker,style,table", theme_advanced_styles : "Heading 1=mce_header1;Heading 2=mce_header2;Heading 3=mce_header3", theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left", theme_advanced_resizing: true, theme_advanced_resize_horizontal: true, paste_auto_cleanup_on_paste: true, theme_advanced_statusbar_location : "bottom", theme_advanced_buttons1: "formatselect,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,indent,outdent,separator,bullist,numlist,forecolor,backcolor,separator,link,unlink,image,undo,redo,separator,code,cleanup,removeformat", theme_advanced_buttons2: "tablecontrols", theme_advanced_buttons3: "", editor_selector: "tinymce", content_css: "/stylesheets/editor.css", convert_newlines_to_brs: false, // cleanup_serializer: 'xml', // encoding: 'xml', entity_encoding: 'raw', debug: true });
tinyMCE.init({ theme:"advanced", mode:"none", plugins: "contextmenu,paste,spellchecker,style", theme_advanced_styles : "Heading 1=mce_header1;Heading 2=mce_header2;Heading 3=mce_header3", theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left", theme_advanced_resizing: true, theme_advanced_resize_horizontal: true, paste_auto_cleanup_on_paste: true, theme_advanced_statusbar_location : "bottom", theme_advanced_buttons1: "formatselect,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,indent,outdent,separator,bullist,numlist,forecolor,backcolor,separator,link,unlink,image,undo,redo,separator,code,cleanup,removeformat", theme_advanced_buttons2: "", theme_advanced_buttons3: "", editor_selector: "tinymce", content_css: "/stylesheets/editor.css", convert_newlines_to_brs: false, // cleanup_serializer: 'xml', // encoding: 'xml', entity_encoding: 'raw', debug: true });
[change] Remove first year from footer
import { format } from 'date-fns'; import React from 'react' import { Navigation } from './blocks/Navigation' import styles from './Main.css' const socialLinks = [ { to: 'https://stackoverflow.com/story/usehotkey', title: 'StackOverflow' }, // { // to: 'https://yadi.sk/d/QzyQ04br3HXrmU', // title: 'CV' // }, { to: 'https://www.linkedin.com/in/igor-golopolosov-98382012a/', title: 'LinkedIn' }, { to: 'https://github.com/usehotkey', title: 'GitHub' }, // { // to: 'https://soundcloud.com/hotkeymusic', // title: 'SoundCloud' // }, ] export const Footer = () => { return ( <footer className={styles.footer}> <div className={styles.socialNav}> <Navigation links={socialLinks} external /> </div> <small> {`Igor Golopolosov, ${format(new Date(), 'YYYY')} ♥️`} <b>[email protected]</b> </small> </footer> ) }
import { format } from 'date-fns'; import React from 'react' import { Navigation } from './blocks/Navigation' import styles from './Main.css' const socialLinks = [ { to: 'https://stackoverflow.com/story/usehotkey', title: 'StackOverflow' }, // { // to: 'https://yadi.sk/d/QzyQ04br3HXrmU', // title: 'CV' // }, { to: 'https://www.linkedin.com/in/igor-golopolosov-98382012a/', title: 'LinkedIn' }, { to: 'https://github.com/usehotkey', title: 'GitHub' }, // { // to: 'https://soundcloud.com/hotkeymusic', // title: 'SoundCloud' // }, ] export const Footer = () => { return ( <footer className={styles.footer}> <div className={styles.socialNav}> <Navigation links={socialLinks} external /> </div> <div> <small> {`Igor Golopolosov, 2016-${format(new Date(), 'YYYY')} ♥️`} <b>[email protected]</b> </small> </div> </footer> ) }
Hide ITS messages for now unless `showITS` url param Until we get sensible messages from ITS, their demo ones are not helpful. Thy can be seen using `?showITS=true` in the url.
import Immutable from 'seamless-immutable'; import { actionTypes } from '../actions'; import urlParams from '../utilities/url-params'; const initialState = Immutable({ show: false, message: null, explanation: null, leftButton: null, rightButton: null }); const defaultRightButton = { label: "~BUTTON.OK", action: "dismissModalDialog" }; export default function modalDialog(state = initialState, action) { switch (action.type) { case actionTypes.MODAL_DIALOG_SHOWN: return state.merge({ show: true, message: action.message, explanation: action.explanation, rightButton: action.rightButton || defaultRightButton, leftButton: action.leftButton, showAward: action.showAward, top: action.top }); case actionTypes.GUIDE_MESSAGE_RECEIVED: if (action.data && urlParams.showITS === "true") { return state.merge({ show: true, message: "Message from ITS", explanation: action.data.message.asString(), rightButton: defaultRightButton }); } else return state; case actionTypes.MODAL_DIALOG_DISMISSED: return initialState; // actions which don't close the dialog, i.e. that can occur // while a dialog is being shown case actionTypes.BASKET_SELECTION_CHANGED: case actionTypes.DRAKE_SELECTION_CHANGED: return state; // Assume for now that all other actions also close dialog default: return initialState; } }
import Immutable from 'seamless-immutable'; import { actionTypes } from '../actions'; const initialState = Immutable({ show: false, message: null, explanation: null, leftButton: null, rightButton: null }); const defaultRightButton = { label: "~BUTTON.OK", action: "dismissModalDialog" }; export default function modalDialog(state = initialState, action) { switch (action.type) { case actionTypes.MODAL_DIALOG_SHOWN: return state.merge({ show: true, message: action.message, explanation: action.explanation, rightButton: action.rightButton || defaultRightButton, leftButton: action.leftButton, showAward: action.showAward, top: action.top }); case actionTypes.GUIDE_MESSAGE_RECEIVED: if (action.data) { return state.merge({ show: true, message: "Message from ITS", explanation: action.data.message.asString(), rightButton: defaultRightButton }); } else return state; case actionTypes.MODAL_DIALOG_DISMISSED: return initialState; // actions which don't close the dialog, i.e. that can occur // while a dialog is being shown case actionTypes.BASKET_SELECTION_CHANGED: case actionTypes.DRAKE_SELECTION_CHANGED: return state; // Assume for now that all other actions also close dialog default: return initialState; } }
Fix problem with finding sample name from fastqc_screen output
import sys import os header = ['Sample', 'Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped'] print '\t'.join(header) for fi in sys.argv[1:]: sample = os.path.basename(fi).split('.')[0] if sample[-7:] == '_screen': sample = sample[:-7] with open(fi) as screen_results: results = {} for line in screen_results: fields = line.strip().split() if len(fields) and fields[0][0] != '#' and fields[0] != 'Library': if fields[0] == '%Hit_no_libraries:': results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads']) continue results[fields[0] + '_single'] = int(fields[4]) results[fields[0] + '_multiple'] = int(fields[6]) results['no_reads'] = int(fields[1]) if not len(results): data = ['0'] * 5 else: try: data = [results['Mouse_single'], results['Mouse_multiple'], results['Human_single'] + results['Human_multiple']] except: sys.exit('Malformed file: {0}'.format(fi)) data.append(results['no_reads'] - sum(data) - results['unmapped']) data.append(results['unmapped']) data = map(lambda i:str(i / float(sum(data))),data) data = [sample] + data print '\t'.join(data)
import sys import os header = ['Mouse_single', 'Mouse_multiple', 'Human', 'Other', 'Unmapped'] print '\t'.join(header) for fi in sys.argv[1:]: sample = os.path.basename(fi).split('.')[0] with open(fi) as screen_results: results = {} for line in screen_results: fields = line.strip().split() if len(fields) and fields[0][0] != '#' and fields[0] != 'Library': if fields[0] == '%Hit_no_libraries:': results['unmapped'] = int(float(fields[1]) / 100.0 * results['no_reads']) continue results[fields[0] + '_single'] = int(fields[4]) results[fields[0] + '_multiple'] = int(fields[6]) results['no_reads'] = int(fields[1]) if not len(results): data = ['0'] * 5 else: try: data = [results['Mouse_single'], results['Mouse_multiple'], results['Human_single'] + results['Human_multiple']] except: sys.exit('Malformed file: {0}'.format(fi)) data.append(results['no_reads'] - sum(data) - results['unmapped']) data.append(results['unmapped']) data = map(lambda i:str(i / float(sum(data))),data) data = [sample] + data print '\t'.join(data)
Clear form on form request.
import * as types from './constants'; export function form(config) { const initialState = { id: '', isActive: false, lastUpdated: 0, form: {}, url: '', error: '', }; return (state = initialState, action) => { // Only proceed for this form. if (action.name !== config.name) { return state; } switch (action.type) { case types.FORM_CLEAR_ERROR: return { ...state, error: '', }; case types.FORM_REQUEST: return { ...state, isActive: true, id: action.id, form: {}, url: action.url, error: '', }; case types.FORM_SUCCESS: return { ...state, isActive: false, id: action.form._id, form: action.form, url: action.url || state.url, error: '', }; case types.FORM_FAILURE: return { ...state, isActive: false, isInvalid: true, error: action.error, }; case types.FORM_SAVE: return { ...state, isActive: true, }; case types.FORM_RESET: return initialState; default: return state; } }; }
import * as types from './constants'; export function form(config) { const initialState = { id: '', isActive: false, lastUpdated: 0, form: {}, url: '', error: '', }; return (state = initialState, action) => { // Only proceed for this form. if (action.name !== config.name) { return state; } switch (action.type) { case types.FORM_CLEAR_ERROR: return { ...state, error: '', }; case types.FORM_REQUEST: return { ...state, isActive: true, id: action.id, url: action.url, error: '', }; case types.FORM_SUCCESS: return { ...state, id: action.form._id, form: action.form, isActive: false, url: action.url || state.url, error: '', }; case types.FORM_FAILURE: return { ...state, isActive: false, isInvalid: true, error: action.error, }; case types.FORM_SAVE: return { ...state, isActive: true, }; case types.FORM_RESET: return initialState; default: return state; } }; }
Fix tests for php < 5.4
<?php class XdgTest extends PHPUnit_Framework_TestCase { /** * @return \ShopwareCli\Services\PathProvider\DirectoryGateway\Xdg */ public function getXdg() { return new \ShopwareCli\Services\PathProvider\DirectoryGateway\Xdg(); } public function testXdgPutCache() { putenv('XDG_DATA_HOME=tmp/'); putenv('XDG_CONFIG_HOME=tmp/'); putenv('XDG_CACHE_HOME=tmp/'); $this->assertEquals('tmp/', $this->getXdg()->getHomeCacheDir()); } public function testXdgPutData() { putenv('XDG_DATA_HOME=tmp/'); $this->assertEquals('tmp/', $this->getXdg()->getHomeDataDir()); } public function testXdgPutConfig() { putenv('XDG_CONFIG_HOME=tmp/'); $this->assertEquals('tmp/', $this->getXdg()->getHomeConfigDir()); } public function testXdgDataDirsShouldIncludeHomeDataDir() { putenv('XDG_DATA_HOME=tmp/'); putenv('XDG_CONFIG_HOME=tmp/'); $expectedDirs = array( 'tmp/', '/usr/local/share', '/usr/share', ); $this->assertEquals($expectedDirs, $this->getXdg()->getDataDirs()); } public function testXdgConfigDirsShouldIncludeHomeConfigDir() { putenv('XDG_CONFIG_HOME=tmp/'); $expectedDirs = array( 'tmp/', '/etc/xdg', ); $this->assertEquals($expectedDirs, $this->getXdg()->getConfigDirs()); } }
<?php class XdgTest extends PHPUnit_Framework_TestCase { /** * @return \ShopwareCli\Services\PathProvider\DirectoryGateway\Xdg */ public function getXdg() { return new \ShopwareCli\Services\PathProvider\DirectoryGateway\Xdg(); } public function testXdgPutCache() { putenv('XDG_DATA_HOME=tmp/'); putenv('XDG_CONFIG_HOME=tmp/'); putenv('XDG_CACHE_HOME=tmp/'); $this->assertEquals('tmp/', $this->getXdg()->getHomeCacheDir()); } public function testXdgPutData() { putenv('XDG_DATA_HOME=tmp/'); $this->assertEquals('tmp/', $this->getXdg()->getHomeDataDir()); } public function testXdgPutConfig() { putenv('XDG_CONFIG_HOME=tmp/'); $this->assertEquals('tmp/', $this->getXdg()->getHomeConfigDir()); } public function testXdgDataDirsShouldIncludeHomeDataDir() { putenv('XDG_DATA_HOME=tmp/'); putenv('XDG_CONFIG_HOME=tmp/'); $this->assertEquals('tmp/', $this->getXdg()->getDataDirs()[0]); } public function testXdgConfigDirsShouldIncludeHomeConfigDir() { putenv('XDG_CONFIG_HOME=tmp/'); $this->assertEquals('tmp/', $this->getXdg()->getConfigDirs()[0]); } }
Fix test to accommodate change of error message.
from django.test import TestCase from main.api.serializers import DatasetSerializer from main.tests.api import helpers class TestDatsetSerializer(helpers.BaseUserTestCase): def test_name_uniqueness(self): """ Test that the serializer report an error if the dataset name is not unique within a project """ # create a dataset dataset = self._create_dataset_from_rows([ ['What', 'Comment'], ['what', 'comments'] ]) dataset.name = 'Test' dataset.save() # Trye serializer with a dataset with the same name data = { 'name': dataset.name, 'project': dataset.project.pk, 'data_package': dataset.data_package, 'type': 'generic' } ser = DatasetSerializer(data=data) self.assertFalse(ser.is_valid(())) # the errors should be of the form # {'non_field_errors': ['The fields project, name must make a unique set.']} errors = ser.errors self.assertEquals(['non_field_errors'], list(errors.keys())) self.assertEquals(1, len(errors.get('non_field_errors'))) self.assertIn('A dataset with this name already exists in the project.', errors.get('non_field_errors')[0])
from django.test import TestCase from main.api.serializers import DatasetSerializer from main.tests.api import helpers class TestDatsetSerializer(helpers.BaseUserTestCase): def test_name_uniqueness(self): """ Test that the serializer report an error if the dataset name is not unique within a project """ # create a dataset dataset = self._create_dataset_from_rows([ ['What', 'Comment'], ['what', 'comments'] ]) dataset.name = 'Test' dataset.save() # Trye serializer with a dataset with the same name data = { 'name': dataset.name, 'project': dataset.project.pk, 'data_package': dataset.data_package, 'type': 'generic' } ser = DatasetSerializer(data=data) self.assertFalse(ser.is_valid(())) # the errors should be of the form # {'non_field_errors': ['The fields project, name must make a unique set.']} errors = ser.errors self.assertEquals(['non_field_errors'], list(errors.keys())) self.assertEquals(1, len(errors.get('non_field_errors'))) self.assertIn('project, name must make a unique set', errors.get('non_field_errors')[0])
ci: Fix failing tests on appveyor
import ci_addons import os import pytest import subprocess from . import captured_lines def test_home(): expected_home = os.path.abspath(os.path.dirname(__file__) + '/..') assert ci_addons.home() == expected_home @pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py']) def test_path(addon): expected_path = os.path.join(ci_addons.home(), addon) if not addon.endswith('.py'): expected_path += '.py' assert ci_addons.path(addon) == expected_path def test_list(capsys): ci_addons.list_addons() output_lines, _ = captured_lines(capsys) assert 'anyci' + os.path.sep + 'noop.py' in output_lines @pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py']) def test_execute(addon, capfd): ci_addons.execute(addon, ['foo', 'bar']) output_lines, _ = captured_lines(capfd) assert os.path.join(ci_addons.home(), 'anyci/noop.py foo bar') in output_lines def test_cli(): root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) environment = dict(os.environ) environment['PYTHONPATH'] = root subprocess.check_call( "python -m ci_addons", shell=True, env=environment, stderr=subprocess.STDOUT, cwd=str(root) )
import ci_addons import os import pytest import subprocess from . import captured_lines def test_home(): expected_home = os.path.abspath(os.path.dirname(__file__) + '/..') assert ci_addons.home() == expected_home @pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py']) def test_path(addon): expected_path = ci_addons.home() + '/' + addon if not addon.endswith('.py'): expected_path += '.py' assert ci_addons.path(addon) == expected_path def test_list(capsys): ci_addons.list_addons() output_lines, _ = captured_lines(capsys) assert 'anyci/noop.py' in output_lines @pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py']) def test_execute(addon, capfd): ci_addons.execute(addon, ['foo', 'bar']) output_lines, _ = captured_lines(capfd) assert ci_addons.home() + '/anyci/noop.py foo bar' in output_lines def test_cli(): root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) environment = dict(os.environ) environment['PYTHONPATH'] = root subprocess.check_call( "python -m ci_addons", shell=True, env=environment, stderr=subprocess.STDOUT, cwd=str(root) )
Allow leading space in lazy continuation lines.
<?php namespace FluxBB\CommonMark\Parser\Block; use FluxBB\CommonMark\Common\Text; use FluxBB\CommonMark\Node\Blockquote; use FluxBB\CommonMark\Node\Container; use FluxBB\CommonMark\Parser\AbstractBlockParser; class BlockquoteParser extends AbstractBlockParser { /** * Parse the given content. * * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser * in the chain. * * @param Text $content * @param Container $target * @return void */ public function parseBlock(Text $content, Container $target) { $content->handle( '/ ^ [ ]{0,3} # up to 3 leading spaces \> # block quote marker [ ]? # an optional space [^\n]* # until end of line (?: # lazy continuation \n [ ]{0,3} [^\-*=\ ].* )* $ /mx', function (Text $content) use ($target) { // Remove block quote marker plus surrounding whitespace on each line $content->replace('/^[ ]{0,3}\>[ ]?/m', ''); $blockquote = new Blockquote(); $target->acceptBlockquote($blockquote); $this->first->parseBlock($content, $blockquote); }, function (Text $part) use ($target) { $this->next->parseBlock($part, $target); } ); } }
<?php namespace FluxBB\CommonMark\Parser\Block; use FluxBB\CommonMark\Common\Text; use FluxBB\CommonMark\Node\Blockquote; use FluxBB\CommonMark\Node\Container; use FluxBB\CommonMark\Parser\AbstractBlockParser; class BlockquoteParser extends AbstractBlockParser { /** * Parse the given content. * * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser * in the chain. * * @param Text $content * @param Container $target * @return void */ public function parseBlock(Text $content, Container $target) { $content->handle( '/ ^ [ ]{0,3} # up to 3 leading spaces \> # block quote marker [ ]? # an optional space [^\n]* # until end of line (?: # lazy continuation \n [^\-*=\ ].* )* $ /mx', function (Text $content) use ($target) { // Remove block quote marker plus surrounding whitespace on each line $content->replace('/^[ ]{0,3}\>[ ]?/m', ''); $blockquote = new Blockquote(); $target->acceptBlockquote($blockquote); $this->first->parseBlock($content, $blockquote); }, function (Text $part) use ($target) { $this->next->parseBlock($part, $target); } ); } }
Remove stray reference to underscore.string
#!/usr/bin/env node 'use strict'; // description: git status across all repositories var async = require('async'); var chalk = require('chalk'); var gift = require('gift'); var path = require('path'); var _ = require('lodash'); var storage = require('../lib/storage.js'); var utilities = require('../lib/utilities.js'); utilities.programDefaultsParse('git-status'); storage.setup(function () { var projects = storage.allWithDirectory(); async.eachSeries(projects, function (project, cbEach) { var repo = gift(utilities.expand(project.directory)); repo.status(function (err, repoStatus) { if (repoStatus.clean) { return cbEach(); } _.each(repoStatus.files, function (status, file) { var letter; var colorFn; if (!status.tracked) { letter = '??'; colorFn = chalk.red; } else if (status.type) { if (status.staged) { letter = _.padRight(status.type, 2); colorFn = chalk.yellow; } else { letter = _.padLeft(status.type, 2); if (status.type === 'M') { colorFn = chalk.green; } else if (status.type === 'D') { colorFn = chalk.red; } } } console.log(letter, utilities.colorizePath(path.join(project.directory, file), colorFn)); }); cbEach(err); }); }); });
#!/usr/bin/env node 'use strict'; // description: git status across all repositories var async = require('async'); var chalk = require('chalk'); var gift = require('gift'); var path = require('path'); var _ = require('lodash'); _.str = require('underscore.string'); var storage = require('../lib/storage.js'); var utilities = require('../lib/utilities.js'); utilities.programDefaultsParse('git-status'); storage.setup(function () { var projects = storage.allWithDirectory(); async.eachSeries(projects, function (project, cbEach) { var repo = gift(utilities.expand(project.directory)); repo.status(function (err, repoStatus) { if (repoStatus.clean) { return cbEach(); } _.each(repoStatus.files, function (status, file) { var letter; var colorFn; if (!status.tracked) { letter = '??'; colorFn = chalk.red; } else if (status.type) { if (status.staged) { letter = _.padRight(status.type, 2); colorFn = chalk.yellow; } else { letter = _.padLeft(status.type, 2); if (status.type === 'M') { colorFn = chalk.green; } else if (status.type === 'D') { colorFn = chalk.red; } } } console.log(letter, utilities.colorizePath(path.join(project.directory, file), colorFn)); }); cbEach(err); }); }); });
Fix test descovery to correctly add test dir to path and import modules rather then files
"""Greencard implementation.""" from functools import wraps TESTS = [] def greencard(func): """ A decorator for providing a unittesting function/method with every card in a librarian card library database when it is called. """ @wraps(func) def wrapped(*args, **kwargs): """Transparent wrapper.""" return func(*args, **kwargs) TESTS.append(wrapped) return wrapped def descovery(testdir): """Descover and load greencard tests.""" from os.path import splitext, basename, join, exists if not exists(testdir): return None import sys from glob import glob import importlib sys.path.append(testdir) for testpath in glob(join(testdir, "*.py")): name, _ = splitext(basename(testpath)) importlib.import_module(name) def main(clargs=None): """Command line entry point.""" from argparse import ArgumentParser from librarian.library import Library import sys parser = ArgumentParser( description="A test runner for each card in a librarian library.") parser.add_argument("library", help="Library database") parser.add_argument("-t", "--tests", default="./tests/", help="Test directory") args = parser.parse_args(clargs) descovery(args.tests) library = Library(args.library) failures = 0 for card in library.retrieve_all(): for test in TESTS: try: test(card) except AssertionError: print("{0} failed {1}".format(card, test.__name__)) failures += 1 sys.exit(failures)
"""Greencard implementation.""" from functools import wraps TESTS = [] def greencard(func): """ A decorator for providing a unittesting function/method with every card in a librarian card library database when it is called. """ @wraps(func) def wrapped(*args, **kwargs): """Transparent wrapper.""" return func(*args, **kwargs) TESTS.append(wrapped) return wrapped def descovery(testdir): """Descover and load greencard tests.""" import os from glob import glob import importlib for testpath in glob(os.path.join(testdir, "*.py")): importlib.import_module(testpath) def main(clargs=None): """Command line entry point.""" from argparse import ArgumentParser from librarian.library import Library import sys parser = ArgumentParser( description="A test runner for each card in a librarian library.") parser.add_argument("library", help="Library database") parser.add_argument("-t", "--tests", default="./tests/", help="Test directory") args = parser.parse_args(clargs) descovery(args.tests) library = Library(args.library) failures = 0 for card in library.retrieve_all(): for test in TESTS: try: test(card) except AssertionError: print("{0} failed {1}".format(card, test.__name__)) failures += 1 sys.exit(failures)
Add function for reading file as array buffer
(function () { var ns = $.namespace('pskl.utils'); var stopPropagation = function (e) { e.stopPropagation(); }; ns.FileUtils = { readFile : function (file, callback) { var reader = new FileReader(); reader.onload = function (event) { callback(event.target.result); }; reader.readAsDataURL(file); }, readFileAsArrayBuffer : function (file, callback) { var reader = new FileReader(); reader.addEventListener("loadend", function() { callback(reader.result); }); reader.readAsArrayBuffer(file); }, readImageFile : function (file, callback) { ns.FileUtils.readFile(file, function (content) { var image = new Image(); image.onload = callback.bind(null, image); image.src = content; }); }, downloadAsFile : function (content, filename) { var saveAs = window.saveAs || (navigator.msSaveBlob && navigator.msSaveBlob.bind(navigator)); if (saveAs) { saveAs(content, filename); } else { var downloadLink = document.createElement('a'); content = window.URL.createObjectURL(new Blob([content])); downloadLink.setAttribute('href', content); downloadLink.setAttribute('download', filename); document.body.appendChild(downloadLink); downloadLink.addEventListener('click', stopPropagation); downloadLink.click(); downloadLink.removeEventListener('click', stopPropagation); document.body.removeChild(downloadLink); } } }; })();
(function () { var ns = $.namespace('pskl.utils'); var stopPropagation = function (e) { e.stopPropagation(); }; ns.FileUtils = { readFile : function (file, callback) { var reader = new FileReader(); reader.onload = function (event) { callback(event.target.result); }; reader.readAsDataURL(file); }, readImageFile : function (file, callback) { ns.FileUtils.readFile(file, function (content) { var image = new Image(); image.onload = callback.bind(null, image); image.src = content; }); }, downloadAsFile : function (content, filename) { var saveAs = window.saveAs || (navigator.msSaveBlob && navigator.msSaveBlob.bind(navigator)); if (saveAs) { saveAs(content, filename); } else { var downloadLink = document.createElement('a'); content = window.URL.createObjectURL(content); downloadLink.setAttribute('href', content); downloadLink.setAttribute('download', filename); document.body.appendChild(downloadLink); downloadLink.addEventListener('click', stopPropagation); downloadLink.click(); downloadLink.removeEventListener('click', stopPropagation); document.body.removeChild(downloadLink); } } }; })();
Add About page to Webpack Dev server.
const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/app.js', output: { path: __dirname + '/dist', filename: 'bundle.js' }, devtool: 'inline-source-map', devServer: { contentBase: '.' }, module: { rules: [ { test: /\.s(a|c)ss$/, use: [{ loader: "style-loader" // creates style nodes from JS strings }, { loader: "css-loader" // translates CSS into CommonJS }, { loader: "sass-loader" // compiles Sass to CSS }], }, { test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/, // Limiting the size of the woff fonts breaks font-awesome ONLY for the extract text plugin // loader: "url?limit=10000" use: "url-loader" }, { test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/, use: 'file-loader' } ] } } if (process.env.NODE_ENV !== 'production') { module.exports.plugins = (module.exports.plugins || []).concat([ new HtmlWebpackPlugin({ template: './src/index.html' }), new HtmlWebpackPlugin({ filename: 'about.html', template: './src/about.html' }) ]) }
const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/js/app.js', output: { path: __dirname + '/dist', filename: 'bundle.js' }, devtool: 'inline-source-map', devServer: { contentBase: '.' }, module: { rules: [ { test: /\.s(a|c)ss$/, use: [{ loader: "style-loader" // creates style nodes from JS strings }, { loader: "css-loader" // translates CSS into CommonJS }, { loader: "sass-loader" // compiles Sass to CSS }], }, { test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/, // Limiting the size of the woff fonts breaks font-awesome ONLY for the extract text plugin // loader: "url?limit=10000" use: "url-loader" }, { test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/, use: 'file-loader' } ] } } if (process.env.NODE_ENV !== 'production') { module.exports.plugins = (module.exports.plugins || []).concat([ new HtmlWebpackPlugin({ template: './src/index.html' }) ]) }
Modify AnalogInput initialization, add exception handling.
""" This module provides classes for interfacing with analog plugins. """ import json from myDevices.plugins.manager import PluginManager from myDevices.utils.logger import info, debug class AnalogInput(): """Reads data from an analog input.""" def __init__(self, adc): """Initializes the analog input. Arguments: adc: Analog-to-digital converter plugin ID in the format 'plugin_name:section', e.g. 'cayenne-mcp3xxx:MCP' """ self.adc_name = adc self.adc = None self.read_args = {} self.pluginManager = PluginManager() self.set_adc() def set_adc(self): """Sets the ADC plugin.""" if not self.adc: self.adc = self.pluginManager.get_plugin_by_id(self.adc_name) self.read_args = json.loads(self.adc['read_args']) def read_value(self, channel, data_type=None): """Read the data value on the specified channel.""" self.set_adc() try: value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args) except ValueError as e: debug(e) value = None return value def read_float(self, channel): """Read the float value on the specified channel.""" return self.read_value(channel, 'float') def read_volt(self, channel): """Read the voltage on the specified channel.""" return self.read_value(channel, 'volt')
""" This module provides classes for interfacing with analog plugins. """ import json from myDevices.plugins.manager import PluginManager from myDevices.utils.logger import info class AnalogInput(): """Reads data from an analog input.""" def __init__(self, adc_name): """Initializes the analog input. Arguments: adc_name: Name of analog-to-digital converter plugin in the format 'plugin_name:section' """ self.adc_name = adc_name self.adc = None self.read_args = {} self.pluginManager = PluginManager() self.set_adc() def set_adc(self): """Sets the ADC plugin.""" if not self.adc: self.adc = self.pluginManager.get_plugin_by_id(self.adc_name) self.read_args = json.loads(self.adc['read_args']) def read_value(self, channel, data_type=None): """Read the data value on the specified channel.""" self.set_adc() value = getattr(self.adc['instance'], self.adc['read'])(channel, data_type=data_type, **self.read_args) return value def read_float(self, channel): """Read the float value on the specified channel.""" return self.read_value(channel, 'float') def read_volt(self, channel): """Read the voltage on the specified channel.""" return self.read_value(channel, 'volt')
Mark compatibility with Python 3.6
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='pyaavso', version=__import__('pyaavso').__version__, description='A Python library for working with AAVSO data.', long_description=read('README.rst'), author='Zbigniew Siciarz', author_email='[email protected]', url='http://github.com/zsiciarz/pyaavso', download_url='http://pypi.python.org/pypi/pyaavso', license='MIT', packages=find_packages(exclude=['tests']), include_package_data=True, install_requires=['lxml>=2.0', 'requests>=1.0'], tests_require=['pytest'], platforms='any', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Utilities' ], )
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='pyaavso', version=__import__('pyaavso').__version__, description='A Python library for working with AAVSO data.', long_description=read('README.rst'), author='Zbigniew Siciarz', author_email='[email protected]', url='http://github.com/zsiciarz/pyaavso', download_url='http://pypi.python.org/pypi/pyaavso', license='MIT', packages=find_packages(exclude=['tests']), include_package_data=True, install_requires=['lxml>=2.0', 'requests>=1.0'], tests_require=['pytest'], platforms='any', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Utilities' ], )
Add Camera and Light class. Refact.
package com.gmail.jiangyang5157.cardboard.scene.projection; import android.util.ArrayMap; import android.util.Log; /** * @author Yang * @since 4/12/2016. */ public class IcosphereBuilder { private volatile static IcosphereBuilder uniqueInstance; private ArrayMap<Integer, IcosphereVertex> icosphereVertices; public static IcosphereBuilder getInstance() { if (uniqueInstance == null) { synchronized (IcosphereBuilder.class) { if (uniqueInstance == null) { uniqueInstance = new IcosphereBuilder(); } } } return uniqueInstance; } private IcosphereBuilder() { icosphereVertices = new ArrayMap<>(); } protected IcosphereVertex build(int recursionLevel) { final int MAX_RECURSION_LEVEL = IcosphereVertex.VERTEX_COUNTS.length - 1; if (recursionLevel > MAX_RECURSION_LEVEL) { throw new RuntimeException("Unable to build a Icosphere with recursion level greater than " + MAX_RECURSION_LEVEL); } Integer vertexCount = IcosphereVertex.VERTEX_COUNTS[recursionLevel]; IcosphereVertex ret = icosphereVertices.get(vertexCount); if (ret == null) { ret = new IcosphereVertex(recursionLevel); icosphereVertices.put(vertexCount, ret); Log.d("####", "IcosphereBuilder: created IcosephereVertex object with vertexCount=" + vertexCount); } return ret; } }
package com.gmail.jiangyang5157.cardboard.scene.projection; import android.util.ArrayMap; import android.util.Log; /** * @author Yang * @since 4/12/2016. */ public class IcosphereBuilder { private volatile static IcosphereBuilder uniqueInstance = null; private ArrayMap<Integer, IcosphereVertex> icosphereVertices = new ArrayMap<>(); public static IcosphereBuilder getInstance() { if (uniqueInstance == null) { synchronized (IcosphereBuilder.class) { if (uniqueInstance == null) { uniqueInstance = new IcosphereBuilder(); } } } return uniqueInstance; } private IcosphereBuilder() { } protected IcosphereVertex build(int recursionLevel) { final int MAX_RECURSION_LEVEL = IcosphereVertex.VERTEX_COUNTS.length - 1; if (recursionLevel > MAX_RECURSION_LEVEL) { throw new RuntimeException("Unable to build a Icosphere with recursion level greater than " + MAX_RECURSION_LEVEL); } Integer vertexCount = IcosphereVertex.VERTEX_COUNTS[recursionLevel]; IcosphereVertex ret = icosphereVertices.get(vertexCount); if (ret == null) { ret = new IcosphereVertex(recursionLevel); icosphereVertices.put(vertexCount, ret); Log.d("####", "IcosphereBuilder: created IcosephereVertex object with vertexCount=" + vertexCount); } return ret; } }
Update header user font weight
'use strict'; import React, { Component } from 'react'; import ReactCSS from 'reactcss'; import colors from '../../styles/variables/colors'; import { spacing } from '../../styles/variables/utils'; import { User, Button, Icon } from '../common/index'; class Header extends Component { classes() { return { 'default': { header: { background: colors.bgDark, display: 'flex', justifyContent: 'space-between', padding: `${spacing.m + spacing.statusBarHeight }px ${spacing.m}px ${spacing.m}px`, }, user: { color: '#fff', flex: '1', fontWeight: '500', }, actions: { display: 'flex', alignItems: 'center', }, Decrypt: { background: colors.primary, color: colors.bgDark, }, }, }; } render() { return ( <div is="header"> <div is="user"> <User name="Cali-Connection" /> </div> <div is="actions"> <Icon name="more" color="#F4C97A"/> <Button is="Decrypt"><Icon name="unlock" /> Decrypt</Button> </div> </div> ); } } export default ReactCSS(Header);
'use strict'; import React, { Component } from 'react'; import ReactCSS from 'reactcss'; import colors from '../../styles/variables/colors'; import { spacing } from '../../styles/variables/utils'; import { User, Button, Icon } from '../common/index'; class Header extends Component { classes() { return { 'default': { header: { background: colors.bgDark, display: 'flex', justifyContent: 'space-between', padding: `${spacing.m + spacing.statusBarHeight }px ${spacing.m}px ${spacing.m}px`, }, user: { color: '#fff', flex: '1', }, actions: { display: 'flex', alignItems: 'center', }, Decrypt: { background: colors.primary, color: colors.bgDark, }, }, }; } render() { return ( <div is="header"> <div is="user"> <User name="Cali-Connection" /> </div> <div is="actions"> <Icon name="more" color="#F4C97A"/> <Button is="Decrypt"><Icon name="unlock" /> Decrypt</Button> </div> </div> ); } } export default ReactCSS(Header);
Extend import statement to support Python 3
# For reasons that I don't fully understand, # unless I include __file__ in here, the packaged version # of this module will just be a .egg file, not a .egg folder. # And if it's just a .egg file, it won't include the necessary # dependencies from MANIFEST.in. # Found the __file__ clue by inspecting the `python setup.py install` # command in the dash_html_components package which printed out: # `dash_html_components.__init__: module references __file__` # TODO - Understand this better from .version import __version__ __file__ # Dash renderer's dependencies get loaded in a special order by the server: # React bundles first, the renderer bundle at the very end. _js_dist_dependencies = [ { 'external_url': [ 'https://unpkg.com/[email protected]/dist/react.min.js', 'https://unpkg.com/[email protected]/dist/react-dom.min.js' ], 'relative_package_path': [ '[email protected]', '[email protected]' ], 'namespace': 'dash_renderer' } ] _js_dist = [ { 'relative_package_path': 'bundle.js', "external_url": ( 'https://unpkg.com/dash-renderer@{}' '/dash_renderer/bundle.js' ).format(__version__), 'namespace': 'dash_renderer' } ]
# For reasons that I don't fully understand, # unless I include __file__ in here, the packaged version # of this module will just be a .egg file, not a .egg folder. # And if it's just a .egg file, it won't include the necessary # dependencies from MANIFEST.in. # Found the __file__ clue by inspecting the `python setup.py install` # command in the dash_html_components package which printed out: # `dash_html_components.__init__: module references __file__` # TODO - Understand this better from version import __version__ __file__ # Dash renderer's dependencies get loaded in a special order by the server: # React bundles first, the renderer bundle at the very end. _js_dist_dependencies = [ { 'external_url': [ 'https://unpkg.com/[email protected]/dist/react.min.js', 'https://unpkg.com/[email protected]/dist/react-dom.min.js' ], 'relative_package_path': [ '[email protected]', '[email protected]' ], 'namespace': 'dash_renderer' } ] _js_dist = [ { 'relative_package_path': 'bundle.js', "external_url": ( 'https://unpkg.com/dash-renderer@{}' '/dash_renderer/bundle.js' ).format(__version__), 'namespace': 'dash_renderer' } ]
Rollback spawn api change. Guess it isn't there yet.
var log = require("../utils/log") module.exports = function exec (cmd, args, env, pipe, cb) { if (!cb) cb = pipe, pipe = false if (!cb) cb = env, env = process.env log(cmd+" "+args.map(JSON.stringify).join(" "), "exec") var stdio = process.binding("stdio") , fds = [ stdio.stdinFD || 0 , stdio.stdoutFD || 1 , stdio.stderrFD || 2 ] , cp = require("child_process").spawn( cmd , args , env , pipe ? null : fds ) , stdout = "" , stderr = "" cp.stdout && cp.stdout.on("data", function (chunk) { if (chunk) stdout += chunk }) cp.stderr && cp.stderr.on("data", function (chunk) { if (chunk) stderr += chunk }) cp.on("exit", function (code) { if (code) cb(new Error("`"+cmd+"` failed with "+code)) else cb(null, code, stdout, stderr) }) return cp }
var log = require("../utils/log") module.exports = function exec (cmd, args, env, pipe, cb) { if (!cb) cb = pipe, pipe = false if (!cb) cb = env, env = process.env log(cmd+" "+args.map(JSON.stringify).join(" "), "exec") var stdio = process.binding("stdio") , fds = [ stdio.stdinFD || 0 , stdio.stdoutFD || 1 , stdio.stderrFD || 2 ] , cp = require("child_process").spawn( cmd , args , { env : env , customFDs : pipe ? null : fds } ) , stdout = "" , stderr = "" cp.stdout && cp.stdout.on("data", function (chunk) { if (chunk) stdout += chunk }) cp.stderr && cp.stderr.on("data", function (chunk) { if (chunk) stderr += chunk }) cp.on("exit", function (code) { if (code) cb(new Error("`"+cmd+"` failed with "+code)) else cb(null, code, stdout, stderr) }) return cp }
Fix auth service tokens url
chipsterWeb.factory('AuthenticationService', ['localStorageService', '$http', 'ConfigService', function (localStorageService, $http, ConfigService) { var service = {}; // Do the authentication here based on userid and password service.login = function (username, password) { // clear any old tokens service.setAuthToken(null); return this.requestToken('POST', username, password).then(function (response) { // login successful service.setAuthToken(response.data.tokenKey); }); }; service.logout = function () { localStorageService.clearAll(); }; service.getTokenHeader = function () { service.updateTokenHeader(); return this.tokenHeader; }; service.requestToken = function (method, username, password) { var string = username + ":" + password; var encodedString = btoa(string); //Convert it to base64 encoded string var url = URI(ConfigService.getAuthUrl()).path('tokens'); return promise = $http({ url: url, method: method, withCredentials: true, headers: {'Authorization': 'Basic ' + encodedString} }); }; service.getToken = function () { return localStorageService.get('auth-token'); }; service.setAuthToken = function (val) { localStorageService.set('auth-token', val); service.updateTokenHeader(); }; service.updateTokenHeader = function () { // return always the same instance so that we can update it later if (!service.tokenHeader) { service.tokenHeader = {}; } this.tokenHeader['Authorization'] = 'Basic ' + btoa('token' + ':' + service.getToken()) }; return service; }]);
chipsterWeb.factory('AuthenticationService', ['localStorageService', '$http', 'ConfigService', function (localStorageService, $http, ConfigService) { var service = {}; // Do the authentication here based on userid and password service.login = function (username, password) { // clear any old tokens service.setAuthToken(null); return this.requestToken('POST', username, password).then(function (response) { // login successful service.setAuthToken(response.data.tokenKey); }); }; service.logout = function () { localStorageService.clearAll(); }; service.getTokenHeader = function () { service.updateTokenHeader(); return this.tokenHeader; }; service.requestToken = function (method, username, password) { var string = username + ":" + password; var encodedString = btoa(string); //Convert it to base64 encoded string return promise = $http({ url: ConfigService.getAuthUrl() + 'tokens', method: method, withCredentials: true, headers: {'Authorization': 'Basic ' + encodedString} }); }; service.getToken = function () { return localStorageService.get('auth-token'); }; service.setAuthToken = function (val) { localStorageService.set('auth-token', val); service.updateTokenHeader(); }; service.updateTokenHeader = function () { // return always the same instance so that we can update it later if (!service.tokenHeader) { service.tokenHeader = {}; } this.tokenHeader['Authorization'] = 'Basic ' + btoa('token' + ':' + service.getToken()) }; return service; }]);
Add a 'project' namespace for custom translations of each project Add a generic namespace where the projects can store custom translations that don't override the preset namespaces of the core Issue edina/fieldtrip-cobweb-project#1
'use strict'; define(function(require) { var i18next = require('ext/i18next'); var i18nextJquery = require('ext/jquery-i18next'); var i18nextXHRbackend = require('ext/i18next-xhr-backend'); i18next .use(i18nextXHRbackend) .init({ debug: false, lng: 'en', preload: ['en', 'es', 'gr'], lngs: ['en', 'es', 'gr'], fallbackLng: 'en', ns: [ 'index', 'map', 'footer', 'project', 'saved-records', 'common' ], defaultNS: 'index', fallbackNS: 'common', backend: { loadPath: 'locales/{{lng}}/{{ns}}.json' } }, function(err, t) { var userLng = localStorage.getItem('user-language'); i18nextJquery.init(i18next, $, { tName: 't', i18nName: 'i18n', handleName: 'localize', selectorAttr: 'data-i18n', targetAttr: 'data-i18n-target', optionsAttr: 'data-i18n-options', useOptionsAttr: false, parseDefaultValueFromContent: true }); $(document).on('pagecreate', function(event, ui) { $(event.target).localize(); }); i18next.changeLanguage(userLng); $(document).localize(); }); });
'use strict'; define(function(require) { var i18next = require('ext/i18next'); var i18nextJquery = require('ext/jquery-i18next'); var i18nextXHRbackend = require('ext/i18next-xhr-backend'); i18next .use(i18nextXHRbackend) .init({ debug: false, lng: 'en', preload: ['en', 'es', 'gr'], lngs: ['en', 'es', 'gr'], fallbackLng: 'en', ns: [ 'index', 'map', 'footer', 'saved-records', 'common' ], defaultNS: 'index', fallbackNS: 'common', backend: { loadPath: 'locales/{{lng}}/{{ns}}.json' } }, function(err, t) { var userLng = localStorage.getItem('user-language'); i18nextJquery.init(i18next, $, { tName: 't', i18nName: 'i18n', handleName: 'localize', selectorAttr: 'data-i18n', targetAttr: 'data-i18n-target', optionsAttr: 'data-i18n-options', useOptionsAttr: false, parseDefaultValueFromContent: true }); $(document).on('pagecreate', function(event, ui) { $(event.target).localize(); }); i18next.changeLanguage(userLng); $(document).localize(); }); });
Add debug.html to build script
var historyApiFallback = require("connect-history-api-fallback"); var dest = "./build"; var src = './src'; module.exports = { browserSync: { server: { // Serve up our build folder baseDir: dest, middleware: [historyApiFallback()] } }, js: { src: src + '/js/app.js' }, templates: { src: src + '/templates/**/*.html' }, css: { src: src + "/js/vendor/highlight.js/styles/docco.css", dest: dest }, sass: { src: src + "/sass/**/*.scss", dest: dest, settings: { outputStyle: "compressed", indentedSyntax: false, // Disable .sass syntax! imagePath: 'img' // Used by the image-url helper } }, images: { src: src + "/img/**", dest: dest + "/img" }, markup: { src: src + "/{index.html,debug.html,favicon.ico,/platform/**,/resources/**}", dest: dest }, browserify: { bundleConfigs: [{ entries: src + '/js/app.js', dest: dest, outputName: 'worker_ui.js', extensions: [], transform: ["ractivate"] }] }, production: { cssSrc: dest + '/*.css', jsSrc: dest + '/*.js', dest: dest } };
var historyApiFallback = require("connect-history-api-fallback"); var dest = "./build"; var src = './src'; module.exports = { browserSync: { server: { // Serve up our build folder baseDir: dest, middleware: [historyApiFallback()] } }, js: { src: src + '/js/app.js' }, templates: { src: src + '/templates/**/*.html' }, css: { src: src + "/js/vendor/highlight.js/styles/docco.css", dest: dest }, sass: { src: src + "/sass/**/*.scss", dest: dest, settings: { outputStyle: "compressed", indentedSyntax: false, // Disable .sass syntax! imagePath: 'img' // Used by the image-url helper } }, images: { src: src + "/img/**", dest: dest + "/img" }, markup: { src: src + "/{index.html,favicon.ico,/platform/**,/resources/**}", dest: dest }, browserify: { bundleConfigs: [{ entries: src + '/js/app.js', dest: dest, outputName: 'worker_ui.js', extensions: [], transform: ["ractivate"] }] }, production: { cssSrc: dest + '/*.css', jsSrc: dest + '/*.js', dest: dest } };
Move crispy helper to '.form' property
from __future__ import absolute_import from copy import deepcopy from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from django_filters import filterset from .filters import BooleanFilter, IsoDateTimeFilter from .. import compat, utils FILTER_FOR_DBFIELD_DEFAULTS = deepcopy(filterset.FILTER_FOR_DBFIELD_DEFAULTS) FILTER_FOR_DBFIELD_DEFAULTS.update({ models.DateTimeField: {'filter_class': IsoDateTimeFilter}, models.BooleanField: {'filter_class': BooleanFilter}, }) class FilterSet(filterset.FilterSet): FILTER_DEFAULTS = FILTER_FOR_DBFIELD_DEFAULTS @property def form(self): form = super(FilterSet, self).form if compat.is_crispy(): from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit layout_components = list(form.fields.keys()) + [ Submit('', _('Submit'), css_class='btn-default'), ] helper = FormHelper() helper.form_method = 'GET' helper.template_pack = 'bootstrap3' helper.layout = Layout(*layout_components) form.helper = helper return form @property def qs(self): from rest_framework.exceptions import ValidationError try: return super(FilterSet, self).qs except forms.ValidationError as e: raise ValidationError(utils.raw_validation(e))
from __future__ import absolute_import from copy import deepcopy from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from django_filters import filterset from .filters import BooleanFilter, IsoDateTimeFilter from .. import compat, utils FILTER_FOR_DBFIELD_DEFAULTS = deepcopy(filterset.FILTER_FOR_DBFIELD_DEFAULTS) FILTER_FOR_DBFIELD_DEFAULTS.update({ models.DateTimeField: {'filter_class': IsoDateTimeFilter}, models.BooleanField: {'filter_class': BooleanFilter}, }) class FilterSet(filterset.FilterSet): FILTER_DEFAULTS = FILTER_FOR_DBFIELD_DEFAULTS def __init__(self, *args, **kwargs): super(FilterSet, self).__init__(*args, **kwargs) if compat.is_crispy(): from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit layout_components = list(self.form.fields.keys()) + [ Submit('', _('Submit'), css_class='btn-default'), ] helper = FormHelper() helper.form_method = 'GET' helper.template_pack = 'bootstrap3' helper.layout = Layout(*layout_components) self.form.helper = helper @property def qs(self): from rest_framework.exceptions import ValidationError try: return super(FilterSet, self).qs except forms.ValidationError as e: raise ValidationError(utils.raw_validation(e))
Deploy Travis CI build 715 to GitHub
#!/usr/bin/env python """Setup script for PythonTemplateDemo.""" import setuptools from demo import __project__, __version__ try: README = open("README.rst").read() CHANGELOG = open("CHANGELOG.rst").read() except IOError: LONG_DESCRIPTION = "Coming soon..." else: LONG_DESCRIPTION = README + '\n' + CHANGELOG setuptools.setup( name=__project__, version=__version__, description="A sample project templated from jacebrowning/template-python.", url='https://github.com/jacebrowning/template-python-demo', author='Jace Browning', author_email='[email protected]', packages=setuptools.find_packages(), entry_points={'console_scripts': []}, long_description=LONG_DESCRIPTION, license='MIT', classifiers=[ # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 1 - Planning', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=open("requirements.txt").readlines(), )
#!/usr/bin/env python """Setup script for PythonTemplateDemo.""" import setuptools from demo import __project__, __version__ try: README = open("README.rst").read() CHANGELOG = open("CHANGELOG.rst").read() except IOError: DESCRIPTION = "<placeholder>" else: DESCRIPTION = README + '\n' + CHANGELOG setuptools.setup( name=__project__, version=__version__, description="A sample project templated from jacebrowning/template-python.", url='https://github.com/jacebrowning/template-python-demo', author='Jace Browning', author_email='[email protected]', packages=setuptools.find_packages(), entry_points={'console_scripts': []}, long_description=(DESCRIPTION), license='MIT', classifiers=[ # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 1 - Planning', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=open("requirements.txt").readlines(), )
MaliciousRequestsMiddleware: Use exception rather than Bad Request view
import re from django.conf import settings from django.core.exceptions import MiddlewareNotUsed, SuspiciousOperation class MaliciousRequestsMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. if settings.MALICIOUS_URL_PATTERNS is not None: patterns = settings.MALICIOUS_URL_PATTERNS.split(',') self.malicious_url_patterns = list(map(lambda pattern: re.compile(pattern, re.IGNORECASE), patterns)) else: raise MiddlewareNotUsed @staticmethod def log_filter_action(path, log_msg): prefix = f'[MaliciousRequestsMiddleware] Filtering malicious url "{path}": ' print(f'{prefix}: {log_msg}') def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. path = request.get_full_path() for pattern in self.malicious_url_patterns: if pattern.search(path) is not None: self.log_filter_action(path, f'Matched pattern "{pattern.pattern}"') # TODO: Fix exception that triggers after this raise SuspiciousOperation("Malicious url detected") response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response
import re from django.conf import settings from django.core.exceptions import MiddlewareNotUsed from django.http import HttpResponseBadRequest class MaliciousRequestsMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. if settings.MALICIOUS_URL_PATTERNS is not None: patterns = settings.MALICIOUS_URL_PATTERNS.split(',') self.malicious_url_patterns = list(map(lambda pattern: re.compile(pattern, re.IGNORECASE), patterns)) else: raise MiddlewareNotUsed @staticmethod def log_filter_action(path, log_msg): prefix = f'[MaliciousRequestsMiddleware] Filtering malicious url "{path}": ' print(f'{prefix}: {log_msg}') def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. path = request.get_full_path() for pattern in self.malicious_url_patterns: if pattern.search(path) is not None: self.log_filter_action(path, f'Matched pattern "{pattern.pattern}"') # TODO: Fix exception that triggers after this return HttpResponseBadRequest response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response
Use equal heights in feature segment rows
import Ui from "./Ui"; export default class FeatureContainer { static displayFeatures(features) { let categoryMap = FeatureContainer._createCategoryMap(features); categoryMap.forEach((features, key) => { let container = $("<div class='ui segment'>"); $("<h3>").text(key).appendTo(container); let list = $("<div class='ui list'>").appendTo(container); for (let feature of features) { let checkbox = FeatureContainer._createFeatureCheckbox(feature); $("<div class='item'>").append(checkbox).appendTo(list); } let column = $("<div class='ui stretched column'>").append(container); Ui.featureContainer.append(column); }); } static _createCategoryMap(features) { let map = new Map(); for (let feature of features) { if (!map.has(feature.category)) { map.set(feature.category, []); } let categoryFeatures = map.get(feature.category); categoryFeatures.push(feature); } map.forEach(values => values.sort((a, b)=> a.name.localeCompare(b.name))); return map; } static _createFeatureCheckbox(feature) { let id = feature.token + "-feature"; let container = $("<div>").data(feature).addClass("ui checkbox"); $("<input type='checkbox' id='" + id + "'>").appendTo(container); $("<label>").attr("for", id).text(feature.name).appendTo(container); return container; } }
import Ui from "./Ui"; export default class FeatureContainer { static displayFeatures(features) { let categoryMap = FeatureContainer._createCategoryMap(features); categoryMap.forEach((features, key) => { let container = $("<div class='ui segment'>"); $("<h3>").text(key).appendTo(container); let list = $("<div class='ui list'>").appendTo(container); for (let feature of features) { let checkbox = FeatureContainer._createFeatureCheckbox(feature); $("<div class='item'>").append(checkbox).appendTo(list); } let column = $("<div class='ui column'>").append(container); Ui.featureContainer.append(column); }); } static _createCategoryMap(features) { let map = new Map(); for (let feature of features) { if (!map.has(feature.category)) { map.set(feature.category, []); } let categoryFeatures = map.get(feature.category); categoryFeatures.push(feature); } map.forEach(values => values.sort((a, b)=> a.name.localeCompare(b.name))); return map; } static _createFeatureCheckbox(feature) { let id = feature.token + "-feature"; let container = $("<div>").data(feature).addClass("ui checkbox"); $("<input type='checkbox' id='" + id + "'>").appendTo(container); $("<label>").attr("for", id).text(feature.name).appendTo(container); return container; } }
Fix tests for symfony 2.7
<?php namespace Fsv\TypographyBundle\Tests\Form\Extension; use Fsv\TypographyBundle\Form\Extension\TextareaTypeExtension; use Fsv\TypographyBundle\Typograph\MdashTypograph; use Symfony\Component\Form\PreloadedExtension; use Symfony\Component\Form\Test\TypeTestCase; class TextareaTypeExtensionTest extends TypeTestCase { public function testSubmitWithTypography() { $form = $this->factory->create('textarea', null, array( 'typography' => true )); $form->submit('Типограф - это здорово!'); $this->assertEquals('Типограф&nbsp;&mdash; это здорово!', $form->getData()); } public function testSubmitWithoutTypography() { $form = $this->factory->create('textarea'); $form->submit('Типограф - это здорово!'); $this->assertEquals('Типограф - это здорово!', $form->getData()); } protected function getExtensions() { return array( new PreloadedExtension( array(), array( 'textarea' => array( new TextareaTypeExtension(new MdashTypograph(array('Text.paragraphs' => 'off'))) ) ) ) ); } }
<?php namespace Fsv\TypographyBundle\Tests\Form\Extension; use Fsv\TypographyBundle\Form\Extension\TextareaTypeExtension; use Fsv\TypographyBundle\Typograph\MdashTypograph; use Symfony\Component\Form\PreloadedExtension; use Symfony\Component\Form\Test\TypeTestCase; class TextareaTypeExtensionTest extends TypeTestCase { public function testSubmitWithTypography() { $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\TextareaType', null, array( 'typography' => true )); $form->submit('Типограф - это здорово!'); $this->assertEquals('Типограф&nbsp;&mdash; это здорово!', $form->getData()); } public function testSubmitWithoutTypography() { $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\TextareaType', null); $form->submit('Типограф - это здорово!'); $this->assertEquals('Типограф - это здорово!', $form->getData()); } protected function getExtensions() { return array( new PreloadedExtension( array(), array( 'Symfony\Component\Form\Extension\Core\Type\TextareaType' => array( new TextareaTypeExtension(new MdashTypograph(array('Text.paragraphs' => 'off'))) ) ) ) ); } }
Update dependencies due to botocore critical changes after 0.64.0
#!/usr/bin/env python """ distutils/setuptools install script. """ import os import sys import kotocore try: from setuptools import setup setup except ImportError: from distutils.core import setup packages = [ 'kotocore', 'kotocore.utils', ] requires = [ 'botocore==0.63.0', 'six>=1.4.0', 'jmespath==0.4.1', 'python-dateutil>=2.1', 'bcdoc==0.12.2', ] setup( name='kotocore', version=kotocore.get_version(), description='Utility for botocore.', long_description=open('README.rst').read(), author='Henry Huang', author_email='[email protected]', url='https://github.com/henrysher/kotocore', scripts=[], packages=packages, package_data={ 'kotocore': [ 'data/aws/resources/*.json', ] }, include_package_data=True, install_requires=requires, license=open("LICENSE").read(), classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], )
#!/usr/bin/env python """ distutils/setuptools install script. """ import os import sys import kotocore try: from setuptools import setup setup except ImportError: from distutils.core import setup packages = [ 'kotocore', 'kotocore.utils', ] requires = [ 'botocore>=0.24.0', 'six>=1.4.0', 'jmespath>=0.1.0', 'python-dateutil>=2.1', ] setup( name='kotocore', version=kotocore.get_version(), description='Utility for botocore.', long_description=open('README.rst').read(), author='Henry Huang', author_email='[email protected]', url='https://github.com/henrysher/kotocore', scripts=[], packages=packages, package_data={ 'kotocore': [ 'data/aws/resources/*.json', ] }, include_package_data=True, install_requires=requires, license=open("LICENSE").read(), classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], )
Add comment explaining details of the dynamic baseUri.
<?php /* * Modified: prepend directory path of current file, because of this file own different ENV under between Apache and command line. * NOTE: please remove this comment. */ defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..')); defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app'); return new \Phalcon\Config([ 'database' => [ 'adapter' => 'Mysql', 'host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'test', 'charset' => 'utf8', ], 'application' => [ 'appDir' => APP_PATH . '/', 'controllersDir' => APP_PATH . '/controllers/', 'modelsDir' => APP_PATH . '/models/', 'migrationsDir' => APP_PATH . '/migrations/', 'viewsDir' => APP_PATH . '/views/', 'pluginsDir' => APP_PATH . '/plugins/', 'libraryDir' => APP_PATH . '/library/', 'cacheDir' => BASE_PATH . '/cache/', // This allows the baseUri to be understand project paths that are not in the root directory // of the webpspace. This will break if the public/index.php entry point is moved or // possibly if the web server rewrite rules are changed. This can also be set to a static path. 'baseUri' => preg_replace('/public([\/\\\\])index.php$/', '', $_SERVER["PHP_SELF"]), ] ]);
<?php /* * Modified: prepend directory path of current file, because of this file own different ENV under between Apache and command line. * NOTE: please remove this comment. */ defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..')); defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app'); return new \Phalcon\Config([ 'database' => [ 'adapter' => 'Mysql', 'host' => 'localhost', 'username' => 'root', 'password' => '', 'dbname' => 'test', 'charset' => 'utf8', ], 'application' => [ 'appDir' => APP_PATH . '/', 'controllersDir' => APP_PATH . '/controllers/', 'modelsDir' => APP_PATH . '/models/', 'migrationsDir' => APP_PATH . '/migrations/', 'viewsDir' => APP_PATH . '/views/', 'pluginsDir' => APP_PATH . '/plugins/', 'libraryDir' => APP_PATH . '/library/', 'cacheDir' => BASE_PATH . '/cache/', 'baseUri' => preg_replace('/public([\/\\\\])index.php$/', '', $_SERVER["PHP_SELF"]), ] ]);
Update check on cluster id
import analytics from django.db import InterfaceError, OperationalError, ProgrammingError from tracker.service import TrackerService class PublishTrackerService(TrackerService): def __init__(self, key=''): self.cluster_id = None self.analytics = analytics self.analytics.write_key = key def get_cluster_id(self): if self.cluster_id: return self.cluster_id from clusters.models import Cluster try: cluster_uuid = Cluster.load().uuid.hex self.cluster_id = cluster_uuid except (Cluster.DoesNotExist, InterfaceError, ProgrammingError, OperationalError): pass return self.cluster_id def record_event(self, event): cluster_id = self.get_cluster_id() if not cluster_id: return if event.event_type == 'cluster.created': self.analytics.identify( cluster_id, event.serialize(dumps=False), ) self.analytics.track( cluster_id, event.event_type, event.serialize(dumps=False), ) def setup(self): super(PublishTrackerService, self).setup() self.cluster_id = self.get_cluster_id()
import analytics from django.db import InterfaceError, OperationalError, ProgrammingError from tracker.service import TrackerService class PublishTrackerService(TrackerService): def __init__(self, key=''): self.cluster_id = None self.analytics = analytics self.analytics.write_key = key def get_cluster_id(self): if self.cluster_id: return self.cluster_id from clusters.models import Cluster try: cluster_uuid = Cluster.load().uuid.hex self.cluster_id = cluster_uuid except (Cluster.DoesNotExist, InterfaceError, ProgrammingError, OperationalError): pass return self.cluster_id def record_event(self, event): if not self.cluster_id: return if event.event_type == 'cluster.created': self.analytics.identify( self.get_cluster_id(), event.serialize(dumps=False), ) self.analytics.track( self.get_cluster_id(), event.event_type, event.serialize(dumps=False), ) def setup(self): super(PublishTrackerService, self).setup() self.cluster_id = self.get_cluster_id()
Add Endashcatredirect as a new item in list of category redirect templates Bug: T183987 Change-Id: I72b6ded1ccab48d5d905f4edd4ce6b9485703563
# -*- coding: utf-8 -*- """Family module for Wikimedia Commons.""" # # (C) Pywikibot team, 2005-2018 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' from pywikibot import family # The Wikimedia Commons family class Family(family.WikimediaFamily): """Family class for Wikimedia Commons.""" name = 'commons' def __init__(self): """Constructor.""" super(Family, self).__init__() self.langs = { 'commons': 'commons.wikimedia.org', 'beta': 'commons.wikimedia.beta.wmflabs.org' } self.interwiki_forward = 'wikipedia' # Templates that indicate a category redirect # Redirects to these templates are automatically included self.category_redirect_templates = { '_default': ( u'Category redirect', u'Synonym taxon category redirect', u'Invalid taxon category redirect', u'Monotypic taxon category redirect', 'Endashcatredirect', ), } # Subpages for documentation. self.doc_subpages = { '_default': ((u'/doc', ), ['commons']), }
# -*- coding: utf-8 -*- """Family module for Wikimedia Commons.""" # # (C) Pywikibot team, 2005-2017 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' from pywikibot import family # The Wikimedia Commons family class Family(family.WikimediaFamily): """Family class for Wikimedia Commons.""" name = 'commons' def __init__(self): """Constructor.""" super(Family, self).__init__() self.langs = { 'commons': 'commons.wikimedia.org', 'beta': 'commons.wikimedia.beta.wmflabs.org' } self.interwiki_forward = 'wikipedia' # Templates that indicate a category redirect # Redirects to these templates are automatically included self.category_redirect_templates = { '_default': ( u'Category redirect', u'Synonym taxon category redirect', u'Invalid taxon category redirect', u'Monotypic taxon category redirect', ), } # Subpages for documentation. self.doc_subpages = { '_default': ((u'/doc', ), ['commons']), }
Fix lambda service in dev environment when lambda function does not have any events.
// This file gets all lambda functions from the Serverless // config and exports the handlers and endpoint info. import path from 'path' import YAML from 'yamljs' import { has } from 'lodash' const getServerlessConfig = function () { return YAML.load(path.join(__dirname, '..', 'serverless.yml')) } export const getLambdasFromServerlessConfig = function (serverlessConfig) { const lambdaFunctions = [] if (serverlessConfig['functions']) { const lambdas = serverlessConfig['functions'] for (const key in lambdas) { let lambda = lambdas[key] // Only set up functions triggered by HTTP GET and POST events. if (lambda.events) { lambda.events.forEach((event) => { let isHttpEvent = ( has(event, 'http.path') && (event.http.method === 'get' || event.http.method === 'post')) if (isHttpEvent) { let handlerModulePath = './' + key + '/' + key lambdaFunctions.push({ name: key, path: event.http.path, httpMethod: event.http.method, handler: require(handlerModulePath).handler }) } }) } }; } return lambdaFunctions } // Get our lambda functions from the Serverless config. // Return objects that include the handler function for // each endpoint. const getLambdas = function () { const serverlessConfig = getServerlessConfig() return getLambdasFromServerlessConfig(serverlessConfig) } export default getLambdas
// This file gets all lambda functions from the Serverless // config and exports the handlers and endpoint info. import path from 'path' import YAML from 'yamljs' import { has } from 'lodash' const getServerlessConfig = function () { return YAML.load(path.join(__dirname, '..', 'serverless.yml')) } export const getLambdasFromServerlessConfig = function (serverlessConfig) { const lambdaFunctions = [] if (serverlessConfig['functions']) { const lambdas = serverlessConfig['functions'] for (const key in lambdas) { let lambda = lambdas[key] // Only set up functions triggered by HTTP GET and POST events. lambda.events.forEach((event) => { let isHttpEvent = ( has(event, 'http.path') && (event.http.method === 'get' || event.http.method === 'post')) if (isHttpEvent) { let handlerModulePath = './' + key + '/' + key lambdaFunctions.push({ name: key, path: event.http.path, httpMethod: event.http.method, handler: require(handlerModulePath).handler }) } }) }; } return lambdaFunctions } // Get our lambda functions from the Serverless config. // Return objects that include the handler function for // each endpoint. const getLambdas = function () { const serverlessConfig = getServerlessConfig() return getLambdasFromServerlessConfig(serverlessConfig) } export default getLambdas
Use variadic args in main method
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; import app.config.BeanConfig; import app.config.PropertyPlaceholderConfig; import app.config.WebSecurityConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import java.util.Arrays; @SpringBootApplication @PropertySource(value = { "file:properties/global.properties", "file:properties/local.properties" }, ignoreResourceNotFound = true) @Import({ WebSecurityConfig.class, BeanConfig.class, PropertyPlaceholderConfig.class }) @EnableDiscoveryClient public class SpringBootTemplateApplication { public static void main(final String ...args) { final ApplicationContext ctx = SpringApplication.run(SpringBootTemplateApplication.class, args); final String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.stream(beanNames) .sorted() .forEach(System.out::println); } }
/* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mpalourdio.springboottemplate; import app.config.BeanConfig; import app.config.PropertyPlaceholderConfig; import app.config.WebSecurityConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import java.util.Arrays; @SpringBootApplication @PropertySource(value = { "file:properties/global.properties", "file:properties/local.properties" }, ignoreResourceNotFound = true) @Import({ WebSecurityConfig.class, BeanConfig.class, PropertyPlaceholderConfig.class }) @EnableDiscoveryClient public class SpringBootTemplateApplication { public static void main(final String[] args) { final ApplicationContext ctx = SpringApplication.run(SpringBootTemplateApplication.class, args); final String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.stream(beanNames) .sorted() .forEach(System.out::println); } }
Add Python 3 classifiers so users know this supports Python 3.
import os from setuptools import setup def get_version(): """ Get the version from version module without importing more than necessary. """ version_module_path = os.path.join(os.path.dirname(__file__), "eliot", "_version.py") # The version module contains a variable called __version__ with open(version_module_path) as version_module: exec(version_module.read()) return locals()["__version__"] def read(path): """ Read the contents of a file. """ with open(path) as f: return f.read() setup( classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], name='eliot', version=get_version(), description="Logging as Storytelling", install_requires=["six"], keywords="logging", license="APL2", packages=["eliot", "eliot.tests"], url="https://github.com/HybridLogic/eliot/", maintainer='Itamar Turner-Trauring', maintainer_email='[email protected]', long_description=read('README.rst'), )
import os from setuptools import setup def get_version(): """ Get the version from version module without importing more than necessary. """ version_module_path = os.path.join(os.path.dirname(__file__), "eliot", "_version.py") # The version module contains a variable called __version__ with open(version_module_path) as version_module: exec(version_module.read()) return locals()["__version__"] def read(path): """ Read the contents of a file. """ with open(path) as f: return f.read() setup( classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], name='eliot', version=get_version(), description="Logging as Storytelling", install_requires=["six"], keywords="logging", license="APL2", packages=["eliot", "eliot.tests"], url="https://github.com/HybridLogic/eliot/", maintainer='Itamar Turner-Trauring', maintainer_email='[email protected]', long_description=read('README.rst'), )
Switch to None based on feedback from @niran
from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView from django.views.generic.list import MultipleObjectMixin from django.utils.translation import ugettext as _ from .models import Well class SimpleWellView(TemplateView): allow_empty = False well_title = None def __init__(self, *args, **kwargs): super(SimpleWellView, self).__init__(*args, **kwargs) if not self.well_title: raise ImproperlyConfigured( _(u"Expects a `well_title` to be provided")) def get_well(self): try: return Well.objects.get_current(title=self.well_title) except Well.DoesNotExist: if self.allow_empty: return None raise def get_context_data(self, **kwargs): context = super(SimpleWellView, self).get_context_data(**kwargs) context["well"] = self.get_well() return context class QuerySetBackedWellView(SimpleWellView, MultipleObjectMixin): def get_queryset(self): well = self.get_well() return (well.items if well is not None else super(QuerySetBackedWellView, self).get_queryset()) def get_well(self): well = super(QuerySetBackedWellView, self).get_well() if well: well.merge_with(super(QuerySetBackedWellView, self).get_queryset()) return well
from django.core.exceptions import ImproperlyConfigured from django.views.generic import TemplateView from django.views.generic.list import MultipleObjectMixin from django.utils.translation import ugettext as _ from .models import Well class SimpleWellView(TemplateView): allow_empty = False well_title = None def __init__(self, *args, **kwargs): super(SimpleWellView, self).__init__(*args, **kwargs) if not self.well_title: raise ImproperlyConfigured( _(u"Expects a `well_title` to be provided")) def get_well(self): try: return Well.objects.get_current(title=self.well_title) except Well.DoesNotExist: if self.allow_empty: return False raise def get_context_data(self, **kwargs): context = super(SimpleWellView, self).get_context_data(**kwargs) context["well"] = self.get_well() return context class QuerySetBackedWellView(SimpleWellView, MultipleObjectMixin): def get_queryset(self): well = self.get_well() return (well.items if well is not False else super(QuerySetBackedWellView, self).get_queryset()) def get_well(self): well = super(QuerySetBackedWellView, self).get_well() if well: well.merge_with(super(QuerySetBackedWellView, self).get_queryset()) return well
Restructure fields in post seed data
import moment from 'moment'; import { Posts } from '../../api/collections'; const seedPosts = () => { const post = Posts.findOne(); if (!post) { for (let i = 0; i < 50; i++) { Posts.insert({ userId: 'QBgyG7MsqswQmvm7J', username: 'evancorl', avatar: '/images/avatar.jpg', createdAt: moment().utc().toDate(), type: 'Video', title: 'This is a sample title', message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' + 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' + 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.', media: { source: 'YouTube', thumbnail: '/images/feeds.jpg', url: 'https://www.meteor.com/', }, likeCount: 14, commentCount: 3, }); Posts.insert({ userId: 'QBgyG7MsqswQmvm7J', username: 'evancorl', avatar: '/images/avatar.jpg', createdAt: moment().utc().toDate(), type: 'Photo', message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' + 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' + 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.', media: { thumbnail: '/images/feeds-2.jpg', url: 'https://www.meteor.com/', }, likeCount: 14, commentCount: 3, }); } } }; export default seedPosts;
import moment from 'moment'; import { Posts } from '../../api/collections'; const seedPosts = () => { const post = Posts.findOne(); if (!post) { for (let i = 0; i < 50; i++) { Posts.insert({ userId: 'QBgyG7MsqswQmvm7J', username: 'evancorl', createdAt: moment().utc().toDate(), message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' + 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' + 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.', media: { type: 'Video', source: 'YouTube', thumbnail: '/images/feeds.jpg', url: 'https://www.meteor.com/', }, likeCount: 14, commentCount: 3, }); Posts.insert({ userId: 'QBgyG7MsqswQmvm7J', username: 'evancorl', createdAt: moment().utc().toDate(), message: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod ' + 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, ' + 'quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.', media: { type: 'Photo', thumbnail: '/images/feeds-2.jpg', url: 'https://www.meteor.com/', }, likeCount: 14, commentCount: 3, }); } } }; export default seedPosts;
Fix weight CSV export test
# This file is part of wger Workout Manager. # # wger Workout Manager 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. # # wger Workout Manager 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 General Public License for more details. # # You should have received a copy of the GNU Affero General Public License import logging from django.core.urlresolvers import reverse from wger.manager.tests.testcase import WorkoutManagerTestCase logger = logging.getLogger('wger.custom') class WeightCsvExportTestCase(WorkoutManagerTestCase): ''' Test case for the CSV export for weight entries ''' def export_csv(self): ''' Helper function to test the CSV export ''' response = self.client.get(reverse('wger.weight.views.export_csv')) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'text/csv') self.assertEqual(response['Content-Disposition'], 'attachment; filename=Weightdata.csv') self.assertEqual(len(response.content), 132) def test_export_csv_loged_in(self): ''' Test the CSV export for weight entries by a logged in user ''' self.user_login('test') self.export_csv()
# This file is part of wger Workout Manager. # # wger Workout Manager 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. # # wger Workout Manager 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 General Public License for more details. # # You should have received a copy of the GNU Affero General Public License import logging from django.core.urlresolvers import reverse from wger.manager.tests.testcase import WorkoutManagerTestCase logger = logging.getLogger('wger.custom') class WeightCsvExportTestCase(WorkoutManagerTestCase): ''' Test case for the CSV export for weight entries ''' def export_csv(self): ''' Helper function to test the CSV export ''' response = self.client.get(reverse('wger.weight.views.export_csv')) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'text/csv') self.assertEqual(response['Content-Disposition'], 'attachment; filename=weightdata-test.csv') self.assertEqual(len(response.content), 132) def test_export_csv_loged_in(self): ''' Test the CSV export for weight entries by a logged in user ''' self.user_login('test') self.export_csv()
KAA-823: Fix topic list hash calculation algorithm.
package org.kaaproject.kaa.client.notification; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import org.kaaproject.kaa.common.endpoint.gen.Topic; public class TopicListHashCalculator { public static final Integer NULL_LIST_HASH = 0; public static final Integer EMPTRY_LIST_HASH = 1; public static Integer calculateTopicListHash(List<Topic> topics) { if (topics == null) return NULL_LIST_HASH; int result = EMPTRY_LIST_HASH; if (!topics.isEmpty()) { List<Topic> newTopics = new LinkedList<>(topics); Collections.sort(newTopics, new Comparator<Topic>() { @Override public int compare(Topic o1, Topic o2) { return o1.getId() < o2.getId() ? -1 : (o1.getId() > o2.getId() ) ? 1 : 0; } }); for (Topic topic : newTopics) { long topicId = topic.getId(); int elementHash = (int)(topicId ^ (topicId >>> 32)); result = 31 * result + elementHash; } } return result; } }
package org.kaaproject.kaa.client.notification; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import org.kaaproject.kaa.common.endpoint.gen.Topic; public class TopicListHashCalculator { public static final Integer NULL_LIST_HASH = 0; public static final Integer EMPTRY_LIST_HASH = 1; public static Integer calculateTopicListHash(List<Topic> topics) { if (topics == null) return NULL_LIST_HASH; int result = EMPTRY_LIST_HASH; if (!topics.isEmpty()) { List<Topic> newTopics = new LinkedList<>(topics); Collections.sort(newTopics, new Comparator<Topic>() { @Override public int compare(Topic o1, Topic o2) { return o1.getId() < o2.getId() ? -1 : (o1.getId() < o2.getId() ) ? 1 : 0; } }); for (Topic topic : newTopics) { long topicId = topic.getId(); int elementHash = (int)(topicId ^ (topicId >>> 32)); result = 31 * result + elementHash; } } return result; } }
Remove dependency for ReviewedVersionTracker in migrations The base widgy migrations had references to ReviewedVersionTracker, which is not part of the base widgy install. This commit changes the dependency to VersionTracker instead, which is part of the base widgy install.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import widgy.db.fields import django.db.models.deletion import widgy.contrib.widgy_mezzanine.models class Migration(migrations.Migration): dependencies = [ ('pages', '__first__'), ('widgy', '0001_initial'), ] operations = [ migrations.CreateModel( name='WidgyPage', fields=[ ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='pages.Page')), ('root_node', widgy.db.fields.VersionedWidgyField(on_delete=django.db.models.deletion.SET_NULL, verbose_name='widgy content', to='widgy.VersionTracker', null=True)), ], options={ 'ordering': ('_order',), 'verbose_name': 'widgy page', 'verbose_name_plural': 'widgy pages', }, bases=(widgy.contrib.widgy_mezzanine.models.WidgyPageMixin, 'pages.page'), ), migrations.CreateModel( name='UndeletePage', fields=[ ], options={ 'ordering': ('_order',), 'verbose_name': 'restore deleted page', 'proxy': True, }, bases=('widgy_mezzanine.widgypage',), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import widgy.db.fields import django.db.models.deletion import widgy.contrib.widgy_mezzanine.models class Migration(migrations.Migration): dependencies = [ ('pages', '__first__'), ('review_queue', '0001_initial'), ] operations = [ migrations.CreateModel( name='WidgyPage', fields=[ ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='pages.Page')), ('root_node', widgy.db.fields.VersionedWidgyField(on_delete=django.db.models.deletion.SET_NULL, verbose_name='widgy content', to='review_queue.ReviewedVersionTracker', null=True)), ], options={ 'ordering': ('_order',), 'verbose_name': 'widgy page', 'verbose_name_plural': 'widgy pages', }, bases=(widgy.contrib.widgy_mezzanine.models.WidgyPageMixin, 'pages.page'), ), migrations.CreateModel( name='UndeletePage', fields=[ ], options={ 'ordering': ('_order',), 'verbose_name': 'restore deleted page', 'proxy': True, }, bases=('widgy_mezzanine.widgypage',), ), ]
Add off as a noop function to touch editor. Closes #3107
var createTouchEditor = function createTouchEditor() { var noop = function () {}, TouchEditor; TouchEditor = function (el, options) { /*jshint unused:false*/ this.textarea = el; this.win = { document : this.textarea }; this.ready = true; this.wrapping = document.createElement('div'); var textareaParent = this.textarea.parentNode; this.wrapping.appendChild(this.textarea); textareaParent.appendChild(this.wrapping); this.textarea.style.opacity = 1; }; TouchEditor.prototype = { setOption: function (type, handler) { if (type === 'onChange') { $(this.textarea).change(handler); } }, eachLine: function () { return []; }, getValue: function () { return this.textarea.value; }, setValue: function (code) { this.textarea.value = code; }, focus: noop, getCursor: function () { return { line: 0, ch: 0 }; }, setCursor: noop, currentLine: function () { return 0; }, cursorPosition: function () { return { character: 0 }; }, addMarkdown: noop, nthLine: noop, refresh: noop, selectLines: noop, on: noop, off: noop }; return TouchEditor; }; export default createTouchEditor;
var createTouchEditor = function createTouchEditor() { var noop = function () {}, TouchEditor; TouchEditor = function (el, options) { /*jshint unused:false*/ this.textarea = el; this.win = { document : this.textarea }; this.ready = true; this.wrapping = document.createElement('div'); var textareaParent = this.textarea.parentNode; this.wrapping.appendChild(this.textarea); textareaParent.appendChild(this.wrapping); this.textarea.style.opacity = 1; }; TouchEditor.prototype = { setOption: function (type, handler) { if (type === 'onChange') { $(this.textarea).change(handler); } }, eachLine: function () { return []; }, getValue: function () { return this.textarea.value; }, setValue: function (code) { this.textarea.value = code; }, focus: noop, getCursor: function () { return { line: 0, ch: 0 }; }, setCursor: noop, currentLine: function () { return 0; }, cursorPosition: function () { return { character: 0 }; }, addMarkdown: noop, nthLine: noop, refresh: noop, selectLines: noop, on: noop }; return TouchEditor; }; export default createTouchEditor;
Consolidate exit logic for initial value conversion.
import {plugin} from 'postcss'; import has from 'has'; import browserslist from 'browserslist'; import {isSupported} from 'caniuse-api'; import fromInitial from '../data/fromInitial.json'; import toInitial from '../data/toInitial.json'; const initial = 'initial'; export default plugin('postcss-reduce-initial', () => { return (css, result) => { const {opts} = result; const browsers = browserslist(null, { stats: opts && opts.stats, path: opts && opts.from, env: opts && opts.env, }); const initialSupport = isSupported('css-initial-value', browsers); css.walkDecls(decl => { const {prop} = decl; if ( initialSupport && has(toInitial, prop) && decl.value === toInitial[prop] ) { decl.value = initial; return; } if (decl.value !== initial || !fromInitial[prop]) { return; } decl.value = fromInitial[prop]; }); }; });
import {plugin} from 'postcss'; import has from 'has'; import browserslist from 'browserslist'; import {isSupported} from 'caniuse-api'; import fromInitial from '../data/fromInitial.json'; import toInitial from '../data/toInitial.json'; const initial = 'initial'; export default plugin('postcss-reduce-initial', () => { return (css, result) => { const {opts} = result; const browsers = browserslist(null, { stats: opts && opts.stats, path: opts && opts.from, env: opts && opts.env, }); const initialSupport = isSupported('css-initial-value', browsers); css.walkDecls(decl => { const {prop} = decl; if ( initialSupport && has(toInitial, prop) && decl.value === toInitial[prop] ) { decl.value = initial; return; } if (decl.value !== initial) { return; } if (fromInitial[prop]) { decl.value = fromInitial[decl.prop]; } }); }; });
Refactor to use a single local
import { select, local } from "d3-selection"; var componentLocal = local(), noop = function (){}; export default function (tagName, className){ var render = noop, create, destroy, selector = className ? "." + className : tagName; function component(selection, props){ var update = selection.selectAll(selector) .data(Array.isArray(props) ? props : [props]), exit = update.exit(), enter = update.enter().append(tagName).attr("class", className), all = enter.merge(update); if(create){ enter.each(function (){ componentLocal.set(this, { state: {}, render: noop }); create(function (state){ var local = componentLocal.get(this); Object.assign(local.state, state); local.render(); }.bind(this)); }); all.each(function (props){ var local = componentLocal.get(this); local.render = function (){ select(this).call(render, props, local.state); }.bind(this); local.render(); }); if(destroy){ exit.each(function (){ var local = componentLocal.get(this); local.render = noop; destroy(local.state); }); } } else { all.each(function (props){ select(this).call(render, props); }); } exit.remove(); } component.render = function(_) { return (render = _, component); }; component.create = function(_) { return (create = _, component); }; component.destroy = function(_) { return (destroy = _, component); }; return component; };
import { select, local } from "d3-selection"; var stateLocal = local(), renderLocal = local(), noop = function (){}; export default function (tagName, className){ var render = noop, create, destroy, selector = className ? "." + className : tagName; function component(selection, props){ var update = selection.selectAll(selector) .data(Array.isArray(props) ? props : [props]), exit = update.exit(), enter = update.enter().append(tagName).attr("class", className), all = enter.merge(update); if(create){ enter.each(function (){ renderLocal.set(this, noop); stateLocal.set(this, {}); create(function (state){ Object.assign(stateLocal.get(this), state); renderLocal.get(this)(); }.bind(this)); }); all.each(function (props){ renderLocal.set(this, function (){ select(this).call(render, props, stateLocal.get(this)); }.bind(this)); renderLocal.get(this)(); }); if(destroy){ exit.each(function (){ renderLocal.set(this, noop); destroy(stateLocal.get(this)); }); } } else { all.each(function (props){ select(this).call(render, props); }); } exit.remove(); } component.render = function(_) { return (render = _, component); }; component.create = function(_) { return (create = _, component); }; component.destroy = function(_) { return (destroy = _, component); }; return component; };
Use KDatabaseTableAbstract::getBehavior() to create behaviors using the behavior name instead of the full identifier. Component specific behaviors can now also be loaded using behavior names instead of identifier strings.
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Categories * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Categories Database Table Class * * @author John Bell <http://nooku.assembla.com/profile/johnbell> * @category Nooku * @package Nooku_Server * @subpackage Categories */ class ComCategoriesDatabaseTableCategories extends KDatabaseTableDefault { public function _initialize(KConfig $config) { $config->identity_column = 'id'; $config->append(array( 'name' => 'categories', 'behaviors' => array('lockable', 'orderable', 'sluggable', 'cascadable'), 'column_map' => array( 'enabled' => 'published', 'locked_on' => 'checked_out_time', 'locked_by' => 'checked_out', 'slug' => 'alias' ), )); parent::_initialize($config); } }
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Categories * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Categories Database Table Class * * @author John Bell <http://nooku.assembla.com/profile/johnbell> * @category Nooku * @package Nooku_Server * @subpackage Categories */ class ComCategoriesDatabaseTableCategories extends KDatabaseTableDefault { public function _initialize(KConfig $config) { $config->identity_column = 'id'; $config->append(array( 'name' => 'categories', 'behaviors' => array('lockable', 'com.categories.database.behavior.orderable', 'sluggable', 'com.categories.database.behavior.cascadable'), 'column_map' => array( 'enabled' => 'published', 'locked_on' => 'checked_out_time', 'locked_by' => 'checked_out', 'slug' => 'alias' ), )); parent::_initialize($config); } }
Remove __webpack_public_path__ for a "gotcha"
import { camelCase } from "lodash"; (async () => { // For minority of browers, bring in heavier polyfills. if (!Object.assign || !Array.from || !window.location.origin) { await import("../polyfills"); } // Iterable list of widget scripts const containers = [...document.querySelectorAll("[data-my-widget]")]; for (const container of containers) { const options = [...container.attributes] .filter(({ name }) => /^data-/.test(name)) .reduce((acc, attribute) => { const { name, value } = attribute; const prop = camelCase(name.replace(/^data-(.+$)/, "$1")); return { ...acc, [prop]: value }; }, {}); const { myWidget, ...props } = options; // Attempt to import widget init script, or throw exception const render = await (async () => { try { const imported = await import(`./${myWidget}.js`); // `import`ed code-split modules contain all exports return imported.default; } catch (e) { // Friendly error message for invalid widget names if (e.message.match("Cannot find module")) { throw new Error(`Unknown data-my-widget: ${myWidget}`); } else { throw e; } } })(); render(props, container); } })();
// Lazy-loaded modules are assumed on the hosting domain, // so we override the constant at runtime. // __webpack_public_path__ = process.env.NODE_ENV === "production" // ? "https://example.com" // : "http://localhost:3000"; import { camelCase } from "lodash"; (async () => { // For minority of browers, bring in heavier polyfills. if (!Object.assign || !Array.from || !window.location.origin) { await import("../polyfills"); } // Iterable list of widget scripts const containers = [...document.querySelectorAll("[data-my-widget]")]; for (const container of containers) { const options = [...container.attributes] .filter(({ name }) => /^data-/.test(name)) .reduce((acc, attribute) => { const { name, value } = attribute; const prop = camelCase(name.replace(/^data-(.+$)/, "$1")); return { ...acc, [prop]: value }; }, {}); const { myWidget, ...props } = options; // Attempt to import widget init script, or throw exception const render = await (async () => { try { const imported = await import(`./${myWidget}.js`); // `import`ed code-split modules contain all exports return imported.default; } catch (e) { // Friendly error message for invalid widget names if (e.message.match("Cannot find module")) { throw new Error(`Unknown data-my-widget: ${myWidget}`); } else { throw e; } } })(); render(props, container); } })();
Allow passing and inheriting a constructor method, stored as _constructor
'use strict'; var common = require('./common'); var create = function (params) { /* extends -- (optional) list of object prototypes to inherit from implements -- (optional) list of interfaces this prototype implements (besides those that are inherited) create({ extends: [SuperObjectPrototype_1, SuperObjectPrototype_2], implements: [IMyObjectInterface, IListableItem] }) */ var extendThese = params.extends, implementsInterfaces = params.implements || [], constructor = params.constructor; if (params.extends) { delete params.extends; }; if (params.implements) { delete params.implements }; if (params.constructor) { // Rename the constructor param so it can be added with the // other params params._constructor = params.constructor; delete params.constructor; }; var outp = function (data) { // Run the constructor this._constructor && this._constructor(data); // Then add passed params/data for (var key in data) { this[key] = data[key]; }; }; outp.prototype._implements = [] // If extends other do first so they get overridden by those passed as params // Inehrited prototypes with lower index have precedence common.extendPrototypeWithThese(outp, extendThese); // The rest of the params are added as methods, overriding previous common.addMembers(outp, params); // Add the interfaces so they can be checked // TODO: Filer so we remove duplicates from existing list (order makes difference) outp.prototype._implements = implementsInterfaces.concat(outp.prototype._implements); return outp; } module.exports.create = create;
'use strict'; var common = require('./common'); var create = function (params) { /* extends -- (optional) list of object prototypes to inherit from implements -- (optional) list of interfaces this prototype implements (besides those that are inherited) create({ extends: [SuperObjectPrototype_1, SuperObjectPrototype_2], implements: [IMyObjectInterface, IListableItem] }) */ var extendThese = params.extends, implementsInterfaces = params.implements || []; if (params.extends) { delete params.extends; } if (params.implements) { delete params.implements } var outp = function (data) { for (var key in data) { this[key] = data[key]; }; }; outp.prototype._implements = [] // If extends other do first so they get overridden by those passed as params // Inehrited prototypes with lower index have precedence common.extendPrototypeWithThese(outp, extendThese) // The rest of the params are added as methods, overriding previous common.addMembers(outp, params); // Add the interfaces so they can be checked // TODO: Filer so we remove duplicates from existing list (order makes difference) outp.prototype._implements = implementsInterfaces.concat(outp.prototype._implements); return outp; } module.exports.create = create;
Add : entry tidy to keep relevant info.
class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(self.tidyLog(line)) return entries def tidyLog(self, entry): """ Tidies up a single log entry to separate usefull infos. """ # TODO : replace this with some regex magic again logLine = {} logLine["date"] = entry[0:10] logLine["time"] = entry[11:19] logLine["service"] = entry[entry.find("[") + 1: entry.find("]")] logLIne["ip"] = entry[entry.find("Ban") + 4: len(entry) - 1] return logLine def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass
class Parser(object): """ Parser class definition. Takes care of parsing the fail2ban log, either in "all" mode or "realtime". """ def __init__(self, config, mode=None): """ Inits the object by registering the configuration object """ self.config = config if mode is None: self.mode = config.parse_default self.log = open(config.log_file) def isLog(line): """ Checks if a log entry is a fail2ban log entry """ # TODO : Change this to some regex magic ? if "fail2ban" in line and "Ban" in line: return True else: return False def parseAll(self): """ Parses all the previous entries in the fail2ban log without realtime support. """ entries = [] while True: line = self.log.readline() if self.isLog(line): entries.append(line) return entries def parseRT(self): """ Parses the log file in realtime : only the upcoming log bans will be """ # TODO : maybe use a separate thread for rt parsing ? pass
[SD-1422] Check that the session is the right one
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import bcrypt from apps.auth.service import AuthService from superdesk import get_resource_service from superdesk.errors import CredentialsAuthError from flask import g, current_app as app class DbAuthService(AuthService): def authenticate(self, credentials): user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username')) if not user: raise CredentialsAuthError(credentials) password = credentials.get('password').encode('UTF-8') hashed = user.get('password').encode('UTF-8') if not (password and hashed): raise CredentialsAuthError(credentials) try: rehashed = bcrypt.hashpw(password, hashed) if hashed != rehashed: raise CredentialsAuthError(credentials) except ValueError: raise CredentialsAuthError(credentials) return user def on_deleted(self, doc): ''' :param doc: A deleted auth doc AKA a session :return: ''' # notify that the session has ended app.on_session_end(doc['user'], doc['_id']) def is_authorized(self, **kwargs): if kwargs.get("user_id") is None: return False auth = self.find_one(_id=kwargs.get("user_id"), req=None) return str(g.auth['_id']) == str(auth.get("_id"))
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import bcrypt from apps.auth.service import AuthService from superdesk import get_resource_service from superdesk.errors import CredentialsAuthError from flask import current_app as app class DbAuthService(AuthService): def authenticate(self, credentials): user = get_resource_service('auth_users').find_one(req=None, username=credentials.get('username')) if not user: raise CredentialsAuthError(credentials) password = credentials.get('password').encode('UTF-8') hashed = user.get('password').encode('UTF-8') if not (password and hashed): raise CredentialsAuthError(credentials) try: rehashed = bcrypt.hashpw(password, hashed) if hashed != rehashed: raise CredentialsAuthError(credentials) except ValueError: raise CredentialsAuthError(credentials) return user def on_deleted(self, doc): ''' :param doc: A deleted auth doc AKA a session :return: ''' # notify that the session has ended app.on_session_end(doc['user'], doc['_id'])
Remove unnecessary use of Promise.resolve
'use strict'; const Path = require('path'); const Glob = require('glob'); async function getFiles(paths, ignored) { const opts = { nodir: true, dot: false, }; if (!Array.isArray(paths)) paths = [paths]; if (ignored) opts.ignore = ignored; return paths.reduce((acc, pattern) => { const joinPaths = Array.prototype.concat.bind([], acc); const paths = Glob.sync(pattern, opts); return joinPaths(paths); }, []); } async function load(files, fn) { if (!files) return []; if (!Array.isArray(files)) files = [files]; return files.reduce((acc, file) => { const models = {}; const filepath = Path.isAbsolute(file) ? file : Path.join(process.cwd(), file); const Model = fn(filepath); models[Model.name] = Model; return Object.assign({}, acc, models); }, {}); } async function applyRelations(models) { if (!models || typeof models !== 'object') throw new Error(`Can't apply relationships on invalid models object`); Object.keys(models).forEach(name => { if (models[name].hasOwnProperty('associate')) { models[name].associate(models); } }); return models; } module.exports = { getFiles, load, applyRelations, };
'use strict'; const Path = require('path'); const Glob = require('glob'); async function getFiles(paths, ignored) { const opts = { nodir: true, dot: false, }; if (!Array.isArray(paths)) paths = [paths]; if (ignored) opts.ignore = ignored; return paths.reduce((acc, pattern) => { const joinPaths = Array.prototype.concat.bind([], acc); const paths = Glob.sync(pattern, opts); return joinPaths(paths); }, []); } async function load(files, fn) { if (!files) return Promise.resolve([]); if (!Array.isArray(files)) files = [files]; return files.reduce((acc, file) => { const models = {}; const filepath = Path.isAbsolute(file) ? file : Path.join(process.cwd(), file); const Model = fn(filepath); models[Model.name] = Model; return Object.assign({}, acc, models); }, {}); } async function applyRelations(models) { if (!models || typeof models !== 'object') throw new Error(`Can't apply relationships on invalid models object`); Object.keys(models).forEach(name => { if (models[name].hasOwnProperty('associate')) { models[name].associate(models); } }); return models; } module.exports = { getFiles, load, applyRelations, };
Stop validation error notification stack closes #3383 - Calls closePassive() if a new validation error is thrown to display only the latest validation error
/* jshint unused: false */ import ajax from 'ghost/utils/ajax'; import ValidationEngine from 'ghost/mixins/validation-engine'; var ForgottenController = Ember.Controller.extend(ValidationEngine, { email: '', submitting: false, // ValidationEngine settings validationType: 'forgotten', actions: { submit: function () { var self = this, data = self.getProperties('email'); this.toggleProperty('submitting'); this.validate({ format: false }).then(function () { ajax({ url: self.get('ghostPaths.url').api('authentication', 'passwordreset'), type: 'POST', data: { passwordreset: [{ email: data.email }] } }).then(function (resp) { self.toggleProperty('submitting'); self.notifications.showSuccess('Please check your email for instructions.'); self.transitionToRoute('signin'); }).catch(function (resp) { self.toggleProperty('submitting'); self.notifications.closePassive(); self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.'); }); }).catch(function (errors) { self.toggleProperty('submitting'); self.notifications.closePassive(); self.notifications.showErrors(errors); }); } } }); export default ForgottenController;
/* jshint unused: false */ import ajax from 'ghost/utils/ajax'; import ValidationEngine from 'ghost/mixins/validation-engine'; var ForgottenController = Ember.Controller.extend(ValidationEngine, { email: '', submitting: false, // ValidationEngine settings validationType: 'forgotten', actions: { submit: function () { var self = this, data = self.getProperties('email'); this.toggleProperty('submitting'); this.validate({ format: false }).then(function () { ajax({ url: self.get('ghostPaths.url').api('authentication', 'passwordreset'), type: 'POST', data: { passwordreset: [{ email: data.email }] } }).then(function (resp) { self.toggleProperty('submitting'); self.notifications.showSuccess('Please check your email for instructions.'); self.transitionToRoute('signin'); }).catch(function (resp) { self.toggleProperty('submitting'); self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.'); }); }).catch(function (errors) { self.toggleProperty('submitting'); self.notifications.showErrors(errors); }); } } }); export default ForgottenController;
Disable tests the launch programs with 'watch'
import os import time import subprocess from sniffer.api import select_runnable, file_validator, runnable try: from pync import Notifier except ImportError: notify = None else: notify = Notifier.notify watch_paths = ['mine/', 'tests/'] show_coverage = True @select_runnable('python_tests') @file_validator def py_files(filename): return all((filename.endswith('.py'), not os.path.basename(filename).startswith('.'))) @runnable def python_tests(*args): group = int(time.time()) # unique per run for count, (command, title) in enumerate(( (('make', 'test-unit'), "Unit Tests"), (('make', 'test-int'), "Integration Tests"), (('make', 'test-all'), "Combined Tests"), (('make', 'check'), "Static Analysis"), (('make', 'doc'), None), ), start=1): print("") print("$ %s" % ' '.join(command)) os.environ['TEST_IDE'] = '1' failure = subprocess.call(command, env=os.environ) if failure: if notify and title: mark = "❌" * count notify(mark + " [FAIL] " + mark, title=title, group=group) return False else: if notify and title: mark = "✅" * count notify(mark + " [PASS] " + mark, title=title, group=group) global show_coverage if show_coverage: subprocess.call(['make', 'read-coverage']) show_coverage = False return True
import os import time import subprocess from sniffer.api import select_runnable, file_validator, runnable try: from pync import Notifier except ImportError: notify = None else: notify = Notifier.notify watch_paths = ['mine/', 'tests/'] show_coverage = True @select_runnable('python_tests') @file_validator def py_files(filename): return all((filename.endswith('.py'), not os.path.basename(filename).startswith('.'))) @runnable def python_tests(*args): group = int(time.time()) # unique per run for count, (command, title) in enumerate(( (('make', 'test-unit'), "Unit Tests"), (('make', 'test-int'), "Integration Tests"), (('make', 'test-all'), "Combined Tests"), (('make', 'check'), "Static Analysis"), (('make', 'doc'), None), ), start=1): print("") print("$ %s" % ' '.join(command)) failure = subprocess.call(command) if failure: if notify and title: mark = "❌" * count notify(mark + " [FAIL] " + mark, title=title, group=group) return False else: if notify and title: mark = "✅" * count notify(mark + " [PASS] " + mark, title=title, group=group) global show_coverage if show_coverage: subprocess.call(['make', 'read-coverage']) show_coverage = False return True
Add key to iterated objects
var React = require('react'); var classNames = require('classnames'); var _ = require('underscore'); var ListItem = require('./ListItem'); var ListItemGroup = require('./ListItemGroup'); var List = React.createClass({ displayName: 'List', propTypes: { className: React.PropTypes.string, items: React.PropTypes.array.isRequired, tag: React.PropTypes.string }, getDefaultProps: function() { return { className: '' } }, getListItems: function(list, childIndex) { var that = this; var childIndex = childIndex || 0; var items = list.map(function(item, parentIndex) { var key = parentIndex + '.' + childIndex; childIndex++; if (item.items) { return ( <ListItemGroup key={key} tag={item.tag} attributes={item.attributes}> {that.getListItems(item.items, childIndex)} </ListItemGroup> ); } else { return ( <ListItem key={key} tag={item.tag} attributes={item.attributes}> {item.value} </ListItem> ); } }); return items; }, render: function() { var Tag = this.props.tag || 'div'; var defaultClasses = [ 'list', 'list-unstyled' ]; var passedClasses = this.props.className.split(' '); var classes = classNames(_.union(defaultClasses, passedClasses)); return ( <Tag {...this.props} className={classes}> {this.getListItems(this.props.items)} </Tag> ); } }); module.exports = List;
var React = require('react'); var classNames = require('classnames'); var ListItem = require('./ListItem'); var ListItemGroup = require('./ListItemGroup'); var List = React.createClass({ displayName: 'List', getDefaultProps: function() { return { className: '' } }, getListItems: function(list) { var that = this; var items = list.map(function(item) { if (item.items) { return ( <ListItemGroup tag={item.tag} attributes={item.attributes}> {that.getListItems(item.items)} </ListItemGroup> ); } else { return ( <ListItem tag={item.tag} attributes={item.attributes}> {item.value} </ListItem> ); } }); return items; }, render: function() { var Tag = this.props.tag || 'div'; var defaultClasses = [ 'list', 'list-unstyled' ]; var passedClasses = this.props.className.split(' '); var classes = classNames(_.union(defaultClasses, passedClasses)); return ( <Tag {...this.props} className={classes}> {this.getListItems(this.props.items)} </Tag> ); } }); module.exports = List;
Change to navbar-default instead of inverse to allow easier style overrides.
<nav class="navbar navbar-toggleable-md navbar-default fixed-top"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">{{ $brand or config('app.name', 'Laravel Application') }}</a> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> @if (isset($menu)) @foreach ($menu as $link) @if (array_key_exists('links', $link)) <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{ $link['title'] }} <span class="caret"></span></a> <ul class="dropdown-menu"> @foreach ($link['links'] as $sublink) <li><a href="{{ $sublink['url'] }}">{{ $sublink['title'] }}</a></li> @endforeach </ul> </li> @else <li><a href="{{ $link['url'] }}">{{ $link['title'] }}</a></li> @endif @endforeach @endif @yield('navigation') @yield('secondary_navigation') @if (\Auth::check()) <li><a>{{ \Auth::user()->name }}</a></li> @endif @yield('navigation') </ul> </div> </nav>
<nav class="navbar navbar-toggleable-md navbar-inverse fixed-top bg-inverse"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">{{ $brand or config('app.name', 'Laravel Application') }}</a> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> @if (isset($menu)) @foreach ($menu as $link) @if (array_key_exists('links', $link)) <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{ $link['title'] }} <span class="caret"></span></a> <ul class="dropdown-menu"> @foreach ($link['links'] as $sublink) <li><a href="{{ $sublink['url'] }}">{{ $sublink['title'] }}</a></li> @endforeach </ul> </li> @else <li><a href="{{ $link['url'] }}">{{ $link['title'] }}</a></li> @endif @endforeach @endif @yield('navigation') @yield('secondary_navigation') @if (\Auth::check()) <li><a>{{ \Auth::user()->name }}</a></li> @endif @yield('navigation') </ul> </div> </nav>
Add formatting for date value.
(function () { 'use strict'; define(function () { return [ { key: 'Title', labelText: 'Title' }, { key: 'Author', labelText: 'Author', displayValue: function (value) { return '<ul class="list-unstyled"><li>' + value.replace(';', '</li><li>') + '</li></ul>'; } }, { key: 'Publisher', labelText: 'Publisher' }, { key: 'DateOfPublication', labelText: 'Date of Publication', displayValue: function (value) { var date = new Date(Date.parse(value)); return '<span title="' + date.toDateString() + '" data-microtime="' + date.getTime() + '">' + date.toLocaleDateString() + '</span>'; } }, { key: 'PublicationType', labelText: 'Type' }, { key: 'Subjects', labelText: 'Subjects', displayValue: function (value) { return '<ul class="list-unstyled"><li>' + value.replace(';', '</li><li>') + '</li></ul>'; } } ]; }); }());
(function () { 'use strict'; define(function () { return [ { key: 'Title', labelText: 'Title' }, { key: 'Author', labelText: 'Author', displayValue: function (value) { return '<ul class="list-unstyled"><li>' + value.replace(';', '</li><li>') + '</li></ul>'; } }, { key: 'Publisher', labelText: 'Publisher' }, { key: 'DateOfPublication', labelText: 'Date of Publication' }, { key: 'PublicationType', labelText: 'Type' }, { key: 'Subjects', labelText: 'Subjects', displayValue: function (value) { return '<ul class="list-unstyled"><li>' + value.replace(';', '</li><li>') + '</li></ul>'; } } ]; }); }());
Allow to override strategy getter
from functools import wraps from django.conf import settings from django.core.urlresolvers import reverse from social.utils import setting_name, module_member from social.strategies.utils import get_strategy BACKENDS = settings.AUTHENTICATION_BACKENDS STRATEGY = getattr(settings, setting_name('STRATEGY'), 'social.strategies.django_strategy.DjangoStrategy') STORAGE = getattr(settings, setting_name('STORAGE'), 'social.apps.django_app.default.models.DjangoStorage') Strategy = module_member(STRATEGY) Storage = module_member(STORAGE) def load_strategy(*args, **kwargs): return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs) def strategy(redirect_uri=None, load_strategy=load_strategy): def decorator(func): @wraps(func) def wrapper(request, backend, *args, **kwargs): uri = redirect_uri if uri and not uri.startswith('/'): uri = reverse(redirect_uri, args=(backend,)) request.strategy = load_strategy(request=request, backend=backend, redirect_uri=uri, *args, **kwargs) return func(request, backend, *args, **kwargs) return wrapper return decorator def setting(name, default=None): try: return getattr(settings, setting_name(name)) except AttributeError: return getattr(settings, name, default) class BackendWrapper(object): def get_user(self, user_id): return Strategy(storage=Storage).get_user(user_id)
from functools import wraps from django.conf import settings from django.core.urlresolvers import reverse from social.utils import setting_name, module_member from social.strategies.utils import get_strategy BACKENDS = settings.AUTHENTICATION_BACKENDS STRATEGY = getattr(settings, setting_name('STRATEGY'), 'social.strategies.django_strategy.DjangoStrategy') STORAGE = getattr(settings, setting_name('STORAGE'), 'social.apps.django_app.default.models.DjangoStorage') Strategy = module_member(STRATEGY) Storage = module_member(STORAGE) def load_strategy(*args, **kwargs): return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs) def strategy(redirect_uri=None): def decorator(func): @wraps(func) def wrapper(request, backend, *args, **kwargs): uri = redirect_uri if uri and not uri.startswith('/'): uri = reverse(redirect_uri, args=(backend,)) request.strategy = load_strategy(request=request, backend=backend, redirect_uri=uri, *args, **kwargs) return func(request, backend, *args, **kwargs) return wrapper return decorator def setting(name, default=None): try: return getattr(settings, setting_name(name)) except AttributeError: return getattr(settings, name, default) class BackendWrapper(object): def get_user(self, user_id): return Strategy(storage=Storage).get_user(user_id)
Fix KeyError when getting fedmsg message info.
#!/bin/env python # -*- coding: utf8 -*- import fedmsg.consumers import fedmsg.encoding import fedimg.uploader class KojiConsumer(fedmsg.consumers.FedmsgConsumer): # To our knowledge, all *image* builds appear under this # exact topic, along with scratch builds. topic = 'org.fedoraproject.prod.buildsys.task.state.change' config_key = 'kojiconsumer' def __init__(self, *args, **kwargs): super(KojiConsumer, self).__init__(*args, **kwargs) def consume(self, msg): """Here we put what we'd like to do when we receive the message.""" builds = list() # These will be the Koji build IDs to upload, if any. msg_info = msg["body"]["msg"]["info"] # If the build method is "image", we check to see if the child # task's method is "createImage". if msg_info["method"] == "image": if isinstance(msg_info["children"], list): for child in msg_info["children"]: if child["method"] == "createImage": # We only care about the image if the build # completed successfully (with state code 2). if child["state"] == 2: builds.append(child["id"]) if len(builds) > 0: fedimg.uploader.upload(builds)
#!/bin/env python # -*- coding: utf8 -*- import fedmsg.consumers import fedmsg.encoding import fedimg.uploader class KojiConsumer(fedmsg.consumers.FedmsgConsumer): # To our knowledge, all *image* builds appear under this # exact topic, along with scratch builds. topic = 'org.fedoraproject.prod.buildsys.task.state.change' config_key = 'kojiconsumer' def __init__(self, *args, **kwargs): super(KojiConsumer, self).__init__(*args, **kwargs) def consume(self, msg): """Here we put what we'd like to do when we receive the message.""" builds = list() # These will be the Koji build IDs to upload, if any. msg_info = msg["msg"]["info"] # If the build method is "image", we check to see if the child # task's method is "createImage". if msg_info["method"] == "image": if isinstance(msg_info["children"], list): for child in msg_info["children"]: if child["method"] == "createImage": # We only care about the image if the build # completed successfully (with state code 2). if child["state"] == 2: builds.append(child["id"]) if len(builds) > 0: fedimg.uploader.upload(builds)
Use enum both in titles and datas.
import React from 'react'; import CSSModules from 'react-css-modules'; import styles from './styles.css'; import BidForm from '../BidForm'; class BidTable extends React.Component { constructor(props) { super(props); this.displayName = 'BidTable'; } render() { const tableElements = ['displayName', 'money', 'clamor', 'time']; const tableTitles = { displayName: 'Display Name', money: 'Money', clamor: 'Clamor', time: 'Time', }; const mockData = { displayName: 'Elaine', money: 500, clamor: 'My goods!!!', time: '01:11', }; return ( <table className="table table-hover" styleName="bid-table"> <thead> <tr className="warning"> { tableElements.map((element, index) => { return ( <td key={index}>{tableTitles[element]}</td> ); }) } </tr> </thead> <tbody> <tr> { tableElements.map((element, index) => { return (<td key={index}>{mockData[element]}</td>); }) } </tr> <BidForm /> </tbody> </table> ); } } export default CSSModules(BidTable, styles);
import React from 'react'; import CSSModules from 'react-css-modules'; import styles from './styles.css'; import BidForm from '../BidForm'; class BidTable extends React.Component { constructor(props) { super(props); this.displayName = 'BidTable'; } render() { const tableTitle = ['Display Name', 'Money', 'Clamor', 'Time']; const test = { displayName: 'Elaine', money: 500, clamor: 'My goods!!!', Time: '01:11', }; return ( <table className="table table-hover" styleName="bid-table"> <thead> <tr className="warning">{ tableTitle.map((title, index) => { return ( <td key={index}>{title}</td> ); }) } </tr> </thead> <tbody> <tr> <td>{test.displayName}</td> <td>{test.money}</td> <td>{test.clamor}</td> <td>{test.Time}</td> </tr> <BidForm /> </tbody> </table> ); } } export default CSSModules(BidTable, styles);
Update now creates tmp git ignored dir
<?php namespace SKE\Composer; class Script { public static function install() { $dirs = array( 'resources/cache', 'resources/log', 'tmp', ); foreach($dirs as $dir) { if (!file_exists($dir)) mkdir($dir, 0755, true); else chmod($dir, 0755); } $console = 'console'; $code = <<<HEREDOC #!/usr/bin/env php <?php require_once __DIR__.'/vendor/autoload.php'; \$app = new Silex\Application(); \$app['environment'] = 'dev'; require __DIR__.'/src/app.php'; \$app->boot(); \$console = require __DIR__.'/src/console.php'; \$console->run(); HEREDOC; if (!file_exists($console)){ $fileinfo = new \SplFileInfo($console); $f = $fileinfo->openFile('w'); $f->fwrite($code); $fileinfo = null; $f= null; } if (file_exists($console)){ chmod($console, 0500); } } }
<?php namespace SKE\Composer; class Script { public static function install() { $dirs = array( 'resources/cache', 'resources/log', ); foreach($dirs as $dir) { if (!file_exists($dir)) mkdir($dir, 0755, true); else chmod($dir, 0755); } $console = 'console'; $code = <<<HEREDOC #!/usr/bin/env php <?php require_once __DIR__.'/vendor/autoload.php'; \$app = new Silex\Application(); \$app['environment'] = 'dev'; require __DIR__.'/src/app.php'; \$app->boot(); \$console = require __DIR__.'/src/console.php'; \$console->run(); HEREDOC; if (!file_exists($console)){ $fileinfo = new \SplFileInfo($console); $f = $fileinfo->openFile('w'); $f->fwrite($code); $fileinfo = null; $f= null; } if (file_exists($console)){ chmod($console, 0500); } } }
Fix return user ProfileID not accessToken
const profileService = require("../../../Db/Service/profileService"); const errors = require("../Mojang/Errors"); module.exports.joinserver = (req, res, next) => { let accessToken = req.body.accessToken, selectedProfile = req.body.selectedProfile, serverId = req.body.serverId, server = "Unknown" || req.params["server"]; profileService.getProfileByProfileId(selectedProfile, profile => { if (!profile || profile.accessToken !== accessToken) return errors.makeError(res, errors.ForbiddenOperationExceptionUserAccount); req.db.redis.set(serverId, selectedProfile, (err, msg) => { profileService.loginServer(profile, "${player} joined " + server + " Server", req.headers['x-forwarded-for'] || req.ip, () => { res.status(204).send() }) }) }) }; module.exports.hasjoinserver = (req, res, next) => { req.db.redis.get(req.query.serverId, (err, reply) => { if (err || !reply) { return res.status(204).send() } profileService.getProfileByProfileId(reply, profile => { if (profile.UserName !== req.query.username ) { return res.status(204).send() } if (!profile) { return res.status(204).send() } res.send({ id: profile.ProfileID, name: profile.UserName }) }) }); };
const profileService = require("../../../Db/Service/profileService"); const errors = require("../Mojang/Errors"); module.exports.joinserver = (req, res, next) => { let accessToken = req.body.accessToken, selectedProfile = req.body.selectedProfile, serverId = req.body.serverId, server = "Unknown" || req.params["server"]; profileService.getProfileByProfileId(selectedProfile, profile => { if (!profile || profile.accessToken !== accessToken) return errors.makeError(res, errors.ForbiddenOperationExceptionUserAccount); req.db.redis.set(serverId, selectedProfile, (err, msg) => { profileService.loginServer(profile, "${player} joined " + server + " Server", req.headers['x-forwarded-for'] || req.ip, () => { res.status(204).send() }) }) }) }; module.exports.hasjoinserver = (req, res, next) => { req.db.redis.get(req.query.serverId, (err, reply) => { if (err || !reply) { return res.status(204).send() } profileService.getProfileByProfileId(reply, profile => { if (profile.UserName !== req.query.username ) { return res.status(204).send() } if (!profile) { return res.status(204).send() } res.send({ id: profile.accessToken, name: profile.UserName }) }) }); };
Remove f-string to allow python 3.4 support
from setuptools import setup from setuptools.command.install import install import os import sys VERSION = '0.1.3' class VerifyVersionCommand(install): """Custom command to verify that the git tag matches our version""" description = 'Verify that the git tag matches our version' def run(self): tag = os.getenv('CIRCLE_TAG') if tag != VERSION: info = "Git tag: {0} != phial version: {1}".format(tag, VERSION) sys.exit(info) setup( name='phial-slack', version=VERSION, url='https://github.com/sedders123/phial/', license='MIT', author='James Seden Smith', author_email='[email protected]', description='A Slack bot framework', long_description=open('README.rst').read(), packages=['phial'], include_package_data=True, zip_safe=False, platforms='any', python_requires='>=3.6', keywords=['Slack', 'bot', 'Slackbot'], install_requires=[ 'slackclient==1.0.6', 'Werkzeug==0.12.2', ], classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Python Modules' ], cmdclass={ 'verify': VerifyVersionCommand, } )
from setuptools import setup from setuptools.command.install import install import os import sys VERSION = '0.1.3' class VerifyVersionCommand(install): """Custom command to verify that the git tag matches our version""" description = 'Verify that the git tag matches our version' def run(self): tag = os.getenv('CIRCLE_TAG') if tag != VERSION: info = f"Git tag: {tag} does not match phial version: {VERSION}" sys.exit(info) setup( name='phial-slack', version=VERSION, url='https://github.com/sedders123/phial/', license='MIT', author='James Seden Smith', author_email='[email protected]', description='A Slack bot framework', long_description=open('README.rst').read(), packages=['phial'], include_package_data=True, zip_safe=False, platforms='any', python_requires='>=3.6', keywords=['Slack', 'bot', 'Slackbot'], install_requires=[ 'slackclient==1.0.6', 'Werkzeug==0.12.2', ], classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Python Modules' ], cmdclass={ 'verify': VerifyVersionCommand, } )
Fix browser hanging because of fast typing in editor.
define( ["backbone", "backbone.marionette", "communicator", "medium.editor", "jquery", "erfgeoviewer.common", "tpl!template/detail.html"], function( Backbone, Marionette, Communicator, MediumEditor, $, App, Template ) { return Marionette.ItemView.extend( { template: Template, layout: null, dom: {}, events: { "click .change-style": function(e) { e.preventDefault(); } }, initialize: function( o ) { this.model = o.model; Communicator.mediator.on( "map:tile-layer-clicked", this.hideFlyout, this); }, onShow: function() { var editables = $(".editable", this.$el).get(); var self = this; var timeout; if (this.editor) this.editor.destroy(); if (App.mode == "mapmaker") { this.editor = new MediumEditor(editables, { buttons: ['bold', 'italic', 'underline', 'anchor'], disableReturn: true }); this.editor.subscribe('editableInput', function (event, editable) { clearTimeout(timeout); timeout = setTimeout(function() { var field = $(editable).attr('id').substr(5); self.model.set(field, $(editable).html()); }, 1000); }); } } } ); } );
define( ["backbone", "backbone.marionette", "communicator", "medium.editor", "jquery", "erfgeoviewer.common", "tpl!template/detail.html"], function( Backbone, Marionette, Communicator, MediumEditor, $, App, Template ) { return Marionette.ItemView.extend( { template: Template, layout: null, dom: {}, events: { "click .change-style": function(e) { e.preventDefault(); } }, initialize: function( o ) { this.model = o.model; Communicator.mediator.on( "map:tile-layer-clicked", this.hideFlyout, this); }, onShow: function() { var editables = $(".editable", this.$el).get(); var self = this; if (this.editor) this.editor.destroy(); if (App.mode == "mapmaker") { this.editor = new MediumEditor(editables, { buttons: ['bold', 'italic', 'underline', 'anchor'], disableReturn: true }); this.editor.subscribe('editableInput', function (event, editable) { var field = $(editable).attr('id').substr(5); self.model.set(field, $(editable).html()); }); } } } ); } );
Use InlineDAOControllerView as the default view for DAO properties.
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.dao', name: 'DAOProperty', extends: 'Property', documentation: 'Property for storing a reference to a DAO.', requires: [ 'foam.dao.ProxyDAO' ], properties: [ { name: 'view', value: {class: 'foam.comics.InlineDAOControllerView'}, } ], methods: [ function installInProto(proto) { this.SUPER(proto); var name = this.name; var prop = this; Object.defineProperty(proto, name + '$proxy', { get: function daoProxyGetter() { var proxy = prop.ProxyDAO.create({delegate: this[name]}); this[name + '$proxy'] = proxy; this.sub('propertyChange', name, function(_, __, ___, s) { proxy.delegate = s.get(); }); return proxy; }, configurable: true }); } ] });
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.dao', name: 'DAOProperty', extends: 'Property', documentation: 'Property for storing a reference to a DAO.', requires: [ 'foam.dao.ProxyDAO' ], properties: [ [ 'view', 'foam.u2.DAOList' ] ], methods: [ function installInProto(proto) { this.SUPER(proto); var name = this.name; var prop = this; Object.defineProperty(proto, name + '$proxy', { get: function daoProxyGetter() { var proxy = prop.ProxyDAO.create({delegate: this[name]}); this[name + '$proxy'] = proxy; this.sub('propertyChange', name, function(_, __, ___, s) { proxy.delegate = s.get(); }); return proxy; }, configurable: true }); } ] });
Update related variables when using search
'use strict'; angular.module('sgApp') .directive('sgSection', ['$rootScope', '$window', '$timeout', function($rootScope, $window, $timeout) { return { replace: true, restrict: 'A', templateUrl: 'views/partials/section.html', link: function(scope, element, attrs) { function updateCurrentReference() { var topOffset = element[0].offsetTop, bottomOffset = element[0].offsetTop + element[0].offsetHeight, buffer = 100; if (this.pageYOffset > topOffset - buffer && this.pageYOffset < bottomOffset - buffer) { if ($rootScope.currentReference.section.reference !== scope.section.reference) { $rootScope.currentReference.section = scope.section; if (!scope.$$phase) { $rootScope.$apply(); } } } } // Init markup visibility based on global setting scope.section.showMarkup = scope.markupSection.isVisible; // By default do not show CSS markup scope.section.showCSS = false; // Listen to scroll events and update currentReference if this section is currently focused angular.element($window).bind('scroll', function() { updateCurrentReference(); }); scope.$watch('search.$', function(newVal, oldVal) { // Search is not processed completely yet // We want to run updateCurrentReference after digest is complete $timeout(function() { updateCurrentReference(); }); }); // Section location will change still after initialzation // We want to run updateCurrentReference after digest is complete $timeout(function() { updateCurrentReference(); }); } }; }]);
'use strict'; angular.module('sgApp') .directive('sgSection', ['$rootScope', '$window', '$timeout', function($rootScope, $window, $timeout) { return { replace: true, restrict: 'A', templateUrl: 'views/partials/section.html', link: function(scope, element, attrs) { function updateCurrentReference() { var topOffset = element[0].offsetTop, bottomOffset = element[0].offsetTop + element[0].offsetHeight, buffer = 100; if (this.pageYOffset > topOffset - buffer && this.pageYOffset < bottomOffset - buffer) { if ($rootScope.currentReference.section.reference !== scope.section.reference) { $rootScope.currentReference.section = scope.section; if (!scope.$$phase) { $rootScope.$apply(); } } } } // Init markup visibility based on global setting scope.section.showMarkup = scope.markupSection.isVisible; // By default do not show CSS markup scope.section.showCSS = false; // Listen to scroll events and update currentReference if this section is currently focused angular.element($window).bind('scroll', function() { updateCurrentReference(); }); // Section location will change still after intiialzation // We want to run updateCurrentReference after digest is complete $timeout(function() { updateCurrentReference(); }); } }; }]);
Add Chats reference to User model
'use strict'; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ profile: { email: String, fname: String, lname: String, username: String, birthdate: {type: Date, default: new Date().toISOString()}, picture: String }, infos: { favorites: { position: String, place: String, }, availability: { monday: { available: Boolean, from: String, to: String }, tuesday: { available: Boolean, from: String, to: String }, wednesday: { available: Boolean, from: String, to: String }, thursday: { available: Boolean, from: String, to: String }, friday: { available: Boolean, from: String, to: String }, saturday: { available: Boolean, from: String, to: String }, sunday: { available: Boolean, from: String, to: String } } }, statistics: { games: Number, goals: Number, wins: Number }, friends: [Schema.Types.ObjectId], teams: [Schema.Types.ObjectId], games: [Schema.Types.ObjectId], chats: [Schema.Types.ObjectId], settings: { notificationsLevel: Number, maxDistance: Number }, createdAt: {type: Date, default: new Date().toISOString()}, private: {type: Boolean, default: false} }); module.exports = mongoose.model('User', UserSchema);
'use strict'; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ profile: { email: String, fname: String, lname: String, username: String, birthdate: {type: Date, default: new Date().toISOString()}, picture: String }, infos: { favorites: { position: String, place: String, }, availability: { monday: { available: Boolean, from: String, to: String }, tuesday: { available: Boolean, from: String, to: String }, wednesday: { available: Boolean, from: String, to: String }, thursday: { available: Boolean, from: String, to: String }, friday: { available: Boolean, from: String, to: String }, saturday: { available: Boolean, from: String, to: String }, sunday: { available: Boolean, from: String, to: String } } }, statistics: { games: Number, goals: Number, wins: Number }, friends: [Schema.Types.ObjectId], teams: [Schema.Types.ObjectId], games: [Schema.Types.ObjectId], settings: { notificationsLevel: Number, maxDistance: Number }, createdAt: {type: Date, default: new Date().toISOString()}, private: {type: Boolean, default: false} }); module.exports = mongoose.model('User', UserSchema);
Fix builder method name for MetricsCollector
package io.rtr.conduit.amqp.impl; import com.rabbitmq.client.MetricsCollector; import io.rtr.conduit.amqp.AMQPConsumerCallback; public class AMQPSyncConsumerBuilder extends AMQPConsumerBuilder<AMQPTransport , AMQPListenProperties , AMQPSyncConsumerBuilder> { private AMQPConsumerCallback callback; private MetricsCollector metricsCollector; public static AMQPSyncConsumerBuilder builder() { return new AMQPSyncConsumerBuilder(); } private AMQPSyncConsumerBuilder() { super.prefetchCount(1); } public AMQPSyncConsumerBuilder callback(AMQPConsumerCallback callback) { this.callback = callback; return this; } public AMQPSyncConsumerBuilder metricsCollector(MetricsCollector metricsCollector) { this.metricsCollector = metricsCollector; return this; } @Override protected AMQPTransport buildTransport() { return new AMQPTransport(isSsl(), getHost(), getPort(), metricsCollector); } @Override protected AMQPListenProperties buildListenProperties() { return new AMQPListenProperties(callback, getExchange(), getQueue(), getRetryThreshold(), getPrefetchCount(), isPoisonQueueEnabled(), shouldPurgeOnConnect(), isDynamicQueueCreation(), getPoisonPrefix(), getDynamicQueueRoutingKey(), isAutoCreateAndBind(), getExchangeType(), getRoutingKey()); } @Override protected AMQPListenContext buildListenContext(AMQPTransport transport , AMQPConnectionProperties connectionProperties , AMQPListenProperties listenProperties) { return new AMQPListenContext(transport, connectionProperties, listenProperties); } }
package io.rtr.conduit.amqp.impl; import com.rabbitmq.client.MetricsCollector; import io.rtr.conduit.amqp.AMQPConsumerCallback; public class AMQPSyncConsumerBuilder extends AMQPConsumerBuilder<AMQPTransport , AMQPListenProperties , AMQPSyncConsumerBuilder> { private AMQPConsumerCallback callback; private MetricsCollector metricsCollector; public static AMQPSyncConsumerBuilder builder() { return new AMQPSyncConsumerBuilder(); } private AMQPSyncConsumerBuilder() { super.prefetchCount(1); } public AMQPSyncConsumerBuilder callback(AMQPConsumerCallback callback) { this.callback = callback; return this; } public AMQPSyncConsumerBuilder callback(MetricsCollector metricsCollector) { this.metricsCollector = metricsCollector; return this; } @Override protected AMQPTransport buildTransport() { return new AMQPTransport(isSsl(), getHost(), getPort(), metricsCollector); } @Override protected AMQPListenProperties buildListenProperties() { return new AMQPListenProperties(callback, getExchange(), getQueue(), getRetryThreshold(), getPrefetchCount(), isPoisonQueueEnabled(), shouldPurgeOnConnect(), isDynamicQueueCreation(), getPoisonPrefix(), getDynamicQueueRoutingKey(), isAutoCreateAndBind(), getExchangeType(), getRoutingKey()); } @Override protected AMQPListenContext buildListenContext(AMQPTransport transport , AMQPConnectionProperties connectionProperties , AMQPListenProperties listenProperties) { return new AMQPListenContext(transport, connectionProperties, listenProperties); } }
Move default value assignments before kwargs
from larvae.base import LarvaeBase class Person(LarvaeBase): """ Details for a Person in Popolo format. """ _schema_name = "person" __slots__ = ('name', '_id', 'gender', 'birth_date', 'death_date', 'image', 'summary', 'biography', 'links', 'other_names', 'extras', 'contact_details', 'openstates_id', 'chamber', 'district') _other_name_slots = ('name', 'start_date', 'end_date', 'note') def __init__(self, name, **kwargs): super(Person, self).__init__() self.name = name self.links = [] self.other_names = [] self.extras = {} for k, v in kwargs.items(): setattr(self, k, v) def add_name(self, name, **kwargs): other_name = {'name': name} for k, v in kwargs.items(): if k not in self._other_name_slots: raise AttributeError('{0} not a valid kwarg for add_name' .format(k)) other_name[k] = v self.other_names.append(other_name) def add_link(self, url, note): self.links.append({"note": note, "url": url}) def __unicode__(self): return self.name __str__ = __unicode__
from larvae.base import LarvaeBase class Person(LarvaeBase): """ Details for a Person in Popolo format. """ _schema_name = "person" __slots__ = ('name', '_id', 'gender', 'birth_date', 'death_date', 'image', 'summary', 'biography', 'links', 'other_names', 'extras', 'contact_details', 'openstates_id', 'chamber', 'district') _other_name_slots = ('name', 'start_date', 'end_date', 'note') def __init__(self, name, **kwargs): super(Person, self).__init__() self.name = name for k, v in kwargs.items(): setattr(self, k, v) self.links = [] self.other_names = [] self.extras = {} def add_name(self, name, **kwargs): other_name = {'name': name} for k, v in kwargs.items(): if k not in self._other_name_slots: raise AttributeError('{0} not a valid kwarg for add_name' .format(k)) other_name[k] = v self.other_names.append(other_name) def add_link(self, url, note): self.links.append({"note": note, "url": url}) def __unicode__(self): return self.name __str__ = __unicode__
Increment version for deployment. Update trove classifier.
from setuptools import setup import sys install_requires = ['six'] if sys.version_info[0] == 2 and sys.version_info[1] == 6: install_requires.extend(['ordereddict', 'argparse']) setup( name='pyfaidx', provides='pyfaidx', version='0.3.1', author='Matthew Shirley', author_email='[email protected]', url='http://mattshirley.com', description='pyfaidx: efficient pythonic random ' 'access to fasta subsequences', long_description=open('README.rst').read(), license='MIT', packages=['pyfaidx'], install_requires=install_requires, entry_points={'console_scripts': ['faidx = pyfaidx.cli:main', 'bedmask = pyfaidx.bedmask:main']}, classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: MIT License", "Environment :: Console", "Intended Audience :: Science/Research", "Natural Language :: English", "Operating System :: Unix", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Scientific/Engineering :: Bio-Informatics" ] )
from setuptools import setup import sys install_requires = ['six'] if sys.version_info[0] == 2 and sys.version_info[1] == 6: install_requires.extend(['ordereddict', 'argparse']) setup( name='pyfaidx', provides='pyfaidx', version='0.3.0', author='Matthew Shirley', author_email='[email protected]', url='http://mattshirley.com', description='pyfaidx: efficient pythonic random ' 'access to fasta subsequences', long_description=open('README.rst').read(), license='MIT', packages=['pyfaidx'], install_requires=install_requires, entry_points={'console_scripts': ['faidx = pyfaidx.cli:main', 'bedmask = pyfaidx.bedmask:main']}, classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Environment :: Console", "Intended Audience :: Science/Research", "Natural Language :: English", "Operating System :: Unix", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Scientific/Engineering :: Bio-Informatics" ] )
Trim trailing whitespace with BasicFormatter
import abc import re class Formatter: @abc.abstractmethod def format(self, query): ''' Should return a human-readable version of the query string ''' pass class BasicFormatter(Formatter): ''' Provides a basic default formatting for query strings This formatter provides only indentation levels and newlines at open braces. ''' def __init__(self): self.indent_str = " " def format(self, query): if not isinstance(query, str): query = query.serialize() #TODO handle braces inside literals correctly formatted_query = "" indent_level = 0 for letter in query: # newline and reindent on open brace if letter == "{": indent_level += 1 formatted_query += "{\n" + self.indent_str*indent_level # newline and reindent on close brace elif letter == "}": indent_level -= 1 formatted_query += "\n" + self.indent_str*indent_level + "}" # reindent after any newline elif len(formatted_query) and formatted_query[-1] == '\n': formatted_query += self.indent_str*indent_level + letter # otherwise just add the letter else: formatted_query += letter # trim whitespace formatted_query = re.sub(r'(.)\s+\n', '\g<1>\n', formatted_query, flags=re.MULTILINE) # remove duplicate newlines formatted_query = re.sub(r'(\n+)', '\n', formatted_query, flags=re.MULTILINE) return formatted_query
import abc import re class Formatter: @abc.abstractmethod def format(self, query): ''' Should return a human-readable version of the query string ''' pass class BasicFormatter(Formatter): ''' Provides a basic default formatting for query strings This formatter provides only indentation levels and newlines at open braces. ''' def __init__(self): self.indent_str = " " def format(self, query): #TODO handle braces inside literals correctly formatted_query = "" indent_level = 0 for letter in query: # newline and reindent on open brace if letter == "{": indent_level += 1 formatted_query += "{\n" + self.indent_str*indent_level # newline and reindent on close brace elif letter == "}": indent_level -= 1 formatted_query += "\n" + self.indent_str*indent_level + "}" # reindent after any newline elif len(formatted_query) and formatted_query[-1] == '\n': formatted_query += self.indent_str*indent_level + letter # otherwise just add the letter else: formatted_query += letter # remove duplicate newlines formatted_query = re.sub(r'(\n+)', '\n', formatted_query, flags=re.MULTILINE) return formatted_query
Use tick instead of timer. Signed-off-by: crynobone <[email protected]>
<?php namespace Laravie\Promise; use React\EventLoop\Factory; class AsyncPromises extends Actionable { /** * Create a new collection. * * @return $this */ public static function create($loop = null) { return new static($loop); } /** * Construct async promises. * * @param object|null $loop */ public function __construct($loop = null) { if (is_null($loop)) { $loop = Factory::create(); } $this->loop = $loop; } /** * All promises. * * @return \React\Promise\PromiseInterface|mixed */ public function all() { return $this->resolvePromises(function (array $promises) { return \React\Promise\all($promises); }); } /** * Map promises. * * @param callable $callback * * @return \React\Promise\PromiseInterface|mixed */ public function map(callable $callback) { return $this->resolvePromises(function (array $promises) use ($callback) { return \React\Promise\map($promises, $callback); }); } /** * Merge promises to actions. * * @return array */ protected function resolvePromises(callable $callback) { $promises = []; foreach ($this->promises as $data) { $this->loop->nextTick(function () use ($data, &$promises) { $promises[] = $this->buildPromise($data); }); } $this->loop->run(); return $callback($promises); } }
<?php namespace Laravie\Promise; use React\EventLoop\Factory; class AsyncPromises extends Actionable { /** * Create a new collection. * * @return $this */ public static function create($loop = null) { return new static($loop); } /** * Construct async promises. * * @param object|null $loop */ public function __construct($loop = null) { if (is_null($loop)) { $loop = Factory::create(); } $this->loop = $loop; } /** * All promises. * * @return \React\Promise\PromiseInterface|mixed */ public function all() { return $this->resolvePromises(function (array $promises) { return \React\Promise\all($promises); }); } /** * Map promises. * * @param callable $callback * * @return \React\Promise\PromiseInterface|mixed */ public function map(callable $callback) { return $this->resolvePromises(function (array $promises) use ($callback) { return \React\Promise\map($promises, $callback); }); } /** * Merge promises to actions. * * @return array */ protected function resolvePromises(callable $callback) { $promises = []; foreach ($this->promises as $data) { $this->loop->addTimer(0.1, function () use ($data, &$promises) { $promises[] = $this->buildPromise($data); }); } $this->loop->run(); return $callback($promises); } }
Enable database transactions for these tests
<?php use Mockery as m; use Illuminate\Foundation\Testing\DatabaseTransactions; class RepositoryTest extends TestCase { use DatabaseTransactions; public function setUp() { parent::setUp(); $this->mock = m::mock('App\Models\TestEntity')->makePartial(); $this->app->instance('App\Models\TestEntity', $this->mock); $this->repository = $this->app->make('App\Repositories\TestRepository'); } /** * Test TestEntity Repository. */ public function testAll() { $this->mock->shouldReceive('get') ->once() ->with(m::type('array')) ->andReturn([]); $result = $this->repository->all(); $this->assertTrue(is_array($result)); } public function testCreate() { $this->mock->shouldReceive('create') ->once() ->with(m::type('array')) ->andReturn($this->mock); $result = $this->repository->create(['foo' => 'bar']); $this->assertTrue(is_object($result)); } public function testFind() { $this->mock->shouldReceive('findOrFail') ->once() ->andReturn($this->mock); $result = $this->repository->find('foobar'); $this->assertTrue(is_object($result)); } public function testFailingFind() { $this->app->instance('App\Models\TestEntity', null); $repository = new App\Repositories\TestRepository($this->app); $this->setExpectedException('Illuminate\Database\Eloquent\ModelNotFoundException'); $result = $repository->find(null); } }
<?php use Mockery as m; class RepositoryTest extends TestCase { public function setUp() { parent::setUp(); $this->mock = m::mock('App\Models\TestEntity')->makePartial(); $this->app->instance('App\Models\TestEntity', $this->mock); $this->repository = $this->app->make('App\Repositories\TestRepository'); } /** * Test TestEntity Repository. */ public function testAll() { $this->mock->shouldReceive('get') ->once() ->with(m::type('array')) ->andReturn([]); $result = $this->repository->all(); $this->assertTrue(is_array($result)); } public function testCreate() { $this->mock->shouldReceive('create') ->once() ->with(m::type('array')) ->andReturn($this->mock); $result = $this->repository->create(['foo' => 'bar']); $this->assertTrue(is_object($result)); } public function testFind() { $this->mock->shouldReceive('findOrFail') ->once() ->andReturn($this->mock); $result = $this->repository->find('foobar'); $this->assertTrue(is_object($result)); } public function testFailingFind() { $this->app->instance('App\Models\TestEntity', null); $repository = new App\Repositories\TestRepository($this->app); $this->setExpectedException('Illuminate\Database\Eloquent\ModelNotFoundException'); $result = $repository->find(null); } }
Fix default folder for scripts
const path = require('path'), ProjectType = require('./ProjectType'); module.exports = projectType => { projectType = projectType || ProjectType.FRONTEND; return { "projectType": projectType, "port": 5000, "liveReloadPort": 35729, "bundleFilename": "main", "distribution": "dist", "targets": "targets", "babel": { "presets": [ path.resolve(__dirname, "../node_modules/babel-preset-es2015"), path.resolve(__dirname, "../node_modules/babel-preset-stage-1") ], "plugins": [ path.resolve(__dirname, "../node_modules/babel-plugin-syntax-async-generators") ] }, "typescript": false, "styles": "styles", "test": "test/**/*", "images": "images", "views": "views", "assets": "assets", "autoprefixerRules": ["last 2 versions", "> 1%"], "scripts": projectType === ProjectType.FRONTEND ? "scripts/*" : "lib/*", "manifest": null, "revisionExclude": [], "onPreBuild": [], "onPostBuild": [], "onRebundle": [] }; };
const path = require('path'), ProjectType = require('./ProjectType'); module.exports = projectType => { projectType = projectType || ProjectType.FRONTEND; return { "projectType": projectType, "port": 5000, "liveReloadPort": 35729, "bundleFilename": "main", "distribution": "dist", "targets": "targets", "babel": { "presets": [ path.resolve(__dirname, "../node_modules/babel-preset-es2015"), path.resolve(__dirname, "../node_modules/babel-preset-stage-1") ], "plugins": [ path.resolve(__dirname, "../node_modules/babel-plugin-syntax-async-generators") ] }, "typescript": false, "styles": "styles", "test": "test/**/*", "images": "images", "views": "views", "assets": "assets", "autoprefixerRules": ["last 2 versions", "> 1%"], "scripts": projectType === ProjectType.FRONTEND ? "lib/*" : "scripts/*", "manifest": null, "revisionExclude": [], "onPreBuild": [], "onPostBuild": [], "onRebundle": [] }; };
Fix django-hvad version in requirements
import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() import multilingual_survey # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-multilingual-survey', version=multilingual_survey.__version__, packages=find_packages(), include_package_data=True, license='BSD License', # example license description='A simple Django app to conduct Web-based multilingual surveys.', long_description=README, url='https://github.com/diadzine/django-multilingual-survey', author='Aymeric Bringard', author_email='[email protected]', install_requires=[ 'Django', 'django-hvad<=1.0.0', ], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() import multilingual_survey # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-multilingual-survey', version=multilingual_survey.__version__, packages=find_packages(), include_package_data=True, license='BSD License', # example license description='A simple Django app to conduct Web-based multilingual surveys.', long_description=README, url='https://github.com/diadzine/django-multilingual-survey', author='Aymeric Bringard', author_email='[email protected]', install_requires=[ 'Django<1.8', 'django-hvad', ], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
Use keys filter in nestedMenuCollection We are accessing `all[label]` here twice - trying to solve this with a variable set through ng-init doesn't work, as ng-init will also resolve after this tag has been processed (at least that's what I think). If we want to access this variable from inside the tag - to use it in other attributes - it won't be set in time and we have to deal with undefined values.
"use strict"; angular.module('arethusa.relation').directive('nestedMenuCollection', function() { return { restrict: 'A', replace: 'true', scope: { current: '=', all: '=', property: '=', ancestors: '=', emptyVal: '@', labelAs: "=", change: "&" }, link: function(scope, element, attrs) { scope.emptyLabel = ""; scope.emptyObj = {}; scope.$watch('current[property]', function(newVal, oldVal) { if (newVal !== oldVal) { scope.change(); } }); scope.labelView = function(labelObj) { if (scope.labelAs) { return labelObj[scope.labelAs]; } else { return labelObj.short; } }; }, template: '\ <ul>\ <li ng-if="emptyVal"\ nested-menu\ property="property"\ rel-obj="current"\ ancestors="ancestors"\ label="emptyLabel"\ label-obj="emptyObj">\ </li>\ <li\ ng-repeat="label in all | keys"\ nested-menu\ property="property"\ rel-obj="current"\ ancestors="ancestors"\ label="labelView(all[label])"\ label-as="labelAs"\ label-obj="all[label]">\ </li>\ </ul>\ ' }; });
"use strict"; angular.module('arethusa.relation').directive('nestedMenuCollection', function() { return { restrict: 'A', replace: 'true', scope: { current: '=', all: '=', property: '=', ancestors: '=', emptyVal: '@', labelAs: "=", change: "&" }, link: function(scope, element, attrs) { scope.emptyLabel = ""; scope.emptyObj = {}; scope.$watch('current[property]', function(newVal, oldVal) { if (newVal !== oldVal) { scope.change(); } }); scope.labelView = function(labelObj) { if (scope.labelAs) { return labelObj[scope.labelAs]; } else { return labelObj.short; } }; }, template: '\ <ul>\ <li ng-if="emptyVal"\ nested-menu\ property="property"\ rel-obj="current"\ ancestors="ancestors"\ label="emptyLabel"\ label-obj="emptyObj">\ </li>\ <li\ ng-repeat="(label, labelObj) in all"\ nested-menu\ property="property"\ rel-obj="current"\ ancestors="ancestors"\ label="labelView(labelObj)"\ label-as="labelAs"\ label-obj="labelObj">\ </li>\ </ul>\ ' }; });
Remove modern-msyslog that breaks travis build
'use strict'; var fs = require('fs'), morgan = require('morgan'), bunyan = require('bunyan'), stream = require('stream').PassThrough, bunyanMiddleware = require('express-bunyan-logger'), log, loggers = { access: function (config) { var conf = { format: (config && config.format) || 'combined', opts: { stream: new stream() } }; conf.opts.stream.pipe(process.stdout); if (config && config.file) { conf.opts.stream.pipe(fs.createWriteStream(config.file, { flags: 'a' })); } return morgan(conf.format, conf.opts); }, error: function (config) { var opts = { name: config && config.name || 'myApp', streams: [ { level: 'error', stream: process.stderr } ] }; if (config && config.file) { opts.streams.push({ 'level': 'error', 'path': config.file }); } return bunyanMiddleware.errorLogger(opts); } }; module.exports = function (config) { if (!(log instanceof bunyan)) { log = bunyan.createLogger(config); log.register = function register (logType, opts) { return loggers[logType](opts); }; log.create = function create (config) { return bunyan.createLogger(config); }; } return log; };
'use strict'; var fs = require('fs'), morgan = require('morgan'), bunyan = require('bunyan'), stream = require('stream').PassThrough, bunyanMiddleware = require('express-bunyan-logger'), msyslog = require('modern-syslog'), log, loggers = { access: function (config) { var msyslogStrm = new msyslog.Stream('LOG_INFO', 'LOG_LOCAL1'), conf = { format: (config && config.format) || 'combined', opts: { stream: new stream() } }; conf.opts.stream.pipe(process.stdout); if (config && config.file) { conf.opts.stream.pipe(fs.createWriteStream(config.file, { flags: 'a' })); } conf.opts.stream.pipe(msyslogStrm); return morgan(conf.format, conf.opts); }, error: function (config) { var opts = { name: config && config.name || 'myApp', streams: [ { level: 'error', stream: process.stderr } ] }; if (config && config.file) { opts.streams.push({ 'level': 'error', 'path': config.file }); } return bunyanMiddleware.errorLogger(opts); } }; module.exports = function (config) { if (!(log instanceof bunyan)) { log = bunyan.createLogger(config); log.register = function register (logType, opts) { return loggers[logType](opts); }; log.create = function create (config) { return bunyan.createLogger(config); }; } return log; };
Send master password when pressing enter
// Copyright (c) 2015 Alejandro Blanco <[email protected]> // MIT License /* global sjcl */ import Ember from 'ember'; export default Ember.Component.extend({ errorMessage: '', showModal: Ember.observer('flag', function () { var that = this, $modal; if (this.get('flag')) { this.set('masterPassword', ''); $modal = Ember.$('#master-password-modal').modal({ show: false }); $modal.off('hidden.bs.modal').on('hidden.bs.modal', function () { that.set('flag', false); }); $modal.off('shown.bs.modal').on('shown.bs.modal', function () { $modal.find('input').focus(); }); $modal.find('input').off('keypress').on('keypress', function (evt) { if (evt.keyCode === 13) { // Enter key evt.preventDefault(); $modal.find('button.btn-primary').trigger('click'); } }); $modal.modal('show'); } }), actions: { sendToController: function () { var testPassword = this.get('testPassword'); if (!Ember.isNone(testPassword)) { try { sjcl.decrypt(this.get('masterPassword'), testPassword.get('secret')); } catch (err) { this.set('errorMessage', 'Wrong master password'); Ember.$('#master-password-modal input').select(); return; } } this.set('errorMessage', ''); Ember.$('#master-password-modal').modal('hide'); this.sendAction('action', this.get('masterPassword')); } } });
// Copyright (c) 2015 Alejandro Blanco <[email protected]> // MIT License /* global sjcl */ import Ember from 'ember'; export default Ember.Component.extend({ errorMessage: '', showModal: Ember.observer('flag', function () { var that = this, $modal; if (this.get('flag')) { this.set('masterPassword', ''); $modal = Ember.$('#master-password-modal').modal({ show: false }); $modal.off('hidden.bs.modal').on('hidden.bs.modal', function () { that.set('flag', false); }); $modal.off('shown.bs.modal').on('shown.bs.modal', function () { $modal.find('input').focus(); }); $modal.modal('show'); } }), actions: { sendToController: function () { var testPassword = this.get('testPassword'); if (!Ember.isNone(testPassword)) { try { sjcl.decrypt(this.get('masterPassword'), testPassword.get('secret')); } catch (err) { this.set('errorMessage', 'Wrong master password'); Ember.$('#master-password-modal input').select(); return; } } this.set('errorMessage', ''); Ember.$('#master-password-modal').modal('hide'); this.sendAction('action', this.get('masterPassword')); } } });
Fix path handling in dependencyLoader
"use strict"; angular.module('arethusa.core').service('dependencyLoader', [ '$ocLazyLoad', '$q', 'basePath', function($ocLazyLoad, $q, basePath) { function expand(p) { if (aU.isUrl(p)) { return p; } else { return basePath.path + '/' + p; } } function expandPath(path) { var res = []; if (angular.isArray(path)) { return aU.map(path, expand); } else { if (angular.isString(path)) { return expand(path); } else { var files = aU.map(path.files, expand); path.files = files; return path; } } } this.load = function(args) { return $ocLazyLoad.load(expandPath(args)); }; this.loadInOrder = function(args) { var start = $q.defer(); var promises = [start.promise]; angular.forEach(args, function(el, i) { var deferred = $q.defer(); promises.push(deferred.promise); promises[i].then(function() { $ocLazyLoad.load(expandPath(el))['finally'](aU.resolveFn(deferred)); }); }); start.resolve(); return aU.last(promises); }; } ]);
"use strict"; angular.module('arethusa.core').service('dependencyLoader', [ '$ocLazyLoad', '$q', 'basePath', function($ocLazyLoad, $q, basePath) { function expand(p) { return basePath.path + '/' + p; } function expandPath(path) { var res = []; if (angular.isArray(path)) { return aU.map(path, expand); } else { if (angular.isString(path)) { return expand(path); } else { var files = aU.map(path.files, expand); path.files = files; return path; } } } this.load = function(args) { return $ocLazyLoad.load(expandPath(args)); }; this.loadInOrder = function(args) { var start = $q.defer(); var promises = [start.promise]; angular.forEach(args, function(el, i) { var deferred = $q.defer(); promises.push(deferred.promise); promises[i].then(function() { $ocLazyLoad.load(expandPath(el))['finally'](aU.resolveFn(deferred)); }); }); start.resolve(); return aU.last(promises); }; } ]);
[tests] Remove deprecated "gen" parameter of NoReferencesBot Change-Id: I8140117cfc2278cfec751164a6d1d8f12bcaef84
"""Test noreferences bot module.""" # # (C) Pywikibot team, 2018-2021 # # Distributed under the terms of the MIT license. # import pywikibot from scripts.noreferences import NoReferencesBot from tests.aspects import TestCase, unittest class TestAddingReferences(TestCase): """Test adding references to section.""" family = 'wikipedia' code = 'cs' def test_add(self): """Test adding references section.""" page = pywikibot.Page(self.site, 'foo') bot = NoReferencesBot() bot.site = self.site page.text = '\n== Reference ==\n* [http://www.baz.org Baz]' new_text = bot.addReferences(page.text) expected = ('\n== Reference ==\n<references />' '\n\n* [http://www.baz.org Baz]') self.assertEqual(new_text, expected) def test_add_under_templates(self): """Test adding references section under templates in section.""" page = pywikibot.Page(self.site, 'foo') bot = NoReferencesBot() bot.site = self.site page.text = '\n== Reference ==\n{{Překlad|en|Baz|123456}}' new_text = bot.addReferences(page.text) expected = page.text + '\n<references />\n' self.assertEqual(new_text, expected) if __name__ == '__main__': # pragma: no cover unittest.main()
"""Test noreferences bot module.""" # # (C) Pywikibot team, 2018-2020 # # Distributed under the terms of the MIT license. # import pywikibot from scripts.noreferences import NoReferencesBot from tests.aspects import TestCase, unittest class TestAddingReferences(TestCase): """Test adding references to section.""" family = 'wikipedia' code = 'cs' def test_add(self): """Test adding references section.""" page = pywikibot.Page(self.site, 'foo') bot = NoReferencesBot(None) bot.site = self.site page.text = '\n== Reference ==\n* [http://www.baz.org Baz]' new_text = bot.addReferences(page.text) expected = ('\n== Reference ==\n<references />' '\n\n* [http://www.baz.org Baz]') self.assertEqual(new_text, expected) def test_add_under_templates(self): """Test adding references section under templates in section.""" page = pywikibot.Page(self.site, 'foo') bot = NoReferencesBot(None) bot.site = self.site page.text = '\n== Reference ==\n{{Překlad|en|Baz|123456}}' new_text = bot.addReferences(page.text) expected = page.text + '\n<references />\n' self.assertEqual(new_text, expected) if __name__ == '__main__': # pragma: no cover unittest.main()
Revert to simple class names as default entity names
package com.zakgof.db.velvet.impl.entity; import java.util.Collection; import java.util.List; import java.util.Locale; import com.zakgof.db.velvet.IVelvet.IStoreIndexDef; import com.zakgof.db.velvet.annotation.Kind; import com.zakgof.db.velvet.properties.IProperty; import com.zakgof.db.velvet.properties.IPropertyAccessor; public class AnnoEntityDef<K, V> extends EntityDef<K, V> implements IPropertyAccessor<K, V> { private AnnoKeyProvider<K, V> annoKeyProvider; public AnnoEntityDef(Class<V> valueClass, String kind, AnnoKeyProvider<K, V> annoKeyProvider, List<IStoreIndexDef<?, V>> indexes) { super(annoKeyProvider.getKeyClass(), valueClass, kind, annoKeyProvider, indexes); this.annoKeyProvider = annoKeyProvider; } public static String kindOf(Class<?> clazz) { Kind annotation = clazz.getAnnotation(Kind.class); if (annotation != null) return annotation.value(); String kind = clazz.getSimpleName().toLowerCase(Locale.ENGLISH); return kind; } @Override public Collection<String> getProperties() { return annoKeyProvider.getProperties(); } @Override public IProperty<?, V> get(String property) { return annoKeyProvider.get(property); } @Override public IProperty<K, V> getKey() { return annoKeyProvider.getKey(); } }
package com.zakgof.db.velvet.impl.entity; import java.util.Collection; import java.util.List; import java.util.Locale; import com.zakgof.db.velvet.IVelvet.IStoreIndexDef; import com.zakgof.db.velvet.annotation.Kind; import com.zakgof.db.velvet.properties.IProperty; import com.zakgof.db.velvet.properties.IPropertyAccessor; public class AnnoEntityDef<K, V> extends EntityDef<K, V> implements IPropertyAccessor<K, V> { private AnnoKeyProvider<K, V> annoKeyProvider; public AnnoEntityDef(Class<V> valueClass, String kind, AnnoKeyProvider<K, V> annoKeyProvider, List<IStoreIndexDef<?, V>> indexes) { super(annoKeyProvider.getKeyClass(), valueClass, kind, annoKeyProvider, indexes); this.annoKeyProvider = annoKeyProvider; } public static String kindOf(Class<?> clazz) { Kind annotation = clazz.getAnnotation(Kind.class); if (annotation != null) return annotation.value(); String kind = clazz.getName().toLowerCase(Locale.ENGLISH); return kind; } @Override public Collection<String> getProperties() { return annoKeyProvider.getProperties(); } @Override public IProperty<?, V> get(String property) { return annoKeyProvider.get(property); } @Override public IProperty<K, V> getKey() { return annoKeyProvider.getKey(); } }
Fix argument types in file type registry
<?php namespace Becklyn\AssetsBundle\File; use Becklyn\AssetsBundle\Asset\Asset; use Becklyn\AssetsBundle\File\Type\CssFile; use Becklyn\AssetsBundle\File\Type\FileType; use Becklyn\AssetsBundle\File\Type\GenericFile; use Becklyn\AssetsBundle\File\Type\JavaScriptFile; use Becklyn\AssetsBundle\File\Type\SvgFile; class FileTypeRegistry { /** * The file types mapped by file extension * * @var array<string,FileType> */ private $fileTypes = []; /** * @var FileType */ private $genericFileType; /** * @param array $fileTypes * @param FileType $genericFileType */ public function __construct (array $fileTypes, FileType $genericFileType) { $this->fileTypes = $fileTypes; $this->genericFileType = $genericFileType; } /** * @param Asset $asset * @return FileType */ public function getFileType (Asset $asset) : FileType { return $this->fileTypes[$asset->getFileType()] ?? $this->genericFileType; } /** * Returns whether the given asset should be imported deferred * * @param Asset $asset * @return bool */ public function importDeferred (Asset $asset) : bool { $fileType = $this->getFileType($asset); return $fileType->importDeferred(); } }
<?php namespace Becklyn\AssetsBundle\File; use Becklyn\AssetsBundle\Asset\Asset; use Becklyn\AssetsBundle\File\Type\CssFile; use Becklyn\AssetsBundle\File\Type\FileType; use Becklyn\AssetsBundle\File\Type\GenericFile; use Becklyn\AssetsBundle\File\Type\JavaScriptFile; use Becklyn\AssetsBundle\File\Type\SvgFile; class FileTypeRegistry { /** * The file types mapped by file extension * * @var array<string,FileType> */ private $fileTypes = []; /** * @var GenericFile */ private $genericFileType; /** * * @param array $fileTypes */ public function __construct (array $fileTypes, GenericFile $genericFileType) { $this->fileTypes = $fileTypes; $this->genericFileType = $genericFileType; } /** * @param Asset $asset * @return FileType */ public function getFileType (Asset $asset) : FileType { return $this->fileTypes[$asset->getFileType()] ?? $this->genericFileType; } /** * Returns whether the given asset should be imported deferred * * @param Asset $asset * @return bool */ public function importDeferred (Asset $asset) : bool { $fileType = $this->getFileType($asset); return $fileType->importDeferred(); } }
Add window and document to globals for tests
var gulp = require('gulp'), eslint = require('gulp-eslint'), mocha = require('gulp-mocha'), flow = require('gulp-flowtype'), babel = require('babel/register'); gulp.task('lint', function() { return gulp.src(['src/*.js', 'src/__tests__/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); }); gulp.task('typecheck', function() { return gulp.src(['src/*.js', 'src/__tests__/*.js']) .pipe(flow({ all: false, weak: false, declarations: './build/flow', killFlow: false, beep: true, abort: false })); }); gulp.task('test', ['lint'], function() { global.expect = require('chai').expect; global.sinon = require('sinon'); global.document = { location: { pathname: '' } }; global.window = { addEventListener() {} }; return gulp.src(['src/__tests__/{,*/}*-test.js']) .pipe(mocha({ compilers: { js: babel }, reporter: 'spec', ui: 'bdd' })); }); gulp.task('default', ['lint', 'test']);
var gulp = require('gulp'), eslint = require('gulp-eslint'), mocha = require('gulp-mocha'), flow = require('gulp-flowtype'), babel = require('babel/register'); gulp.task('lint', function() { return gulp.src(['src/*.js', 'src/__tests__/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); }); gulp.task('typecheck', function() { return gulp.src(['src/*.js', 'src/__tests__/*.js']) .pipe(flow({ all: false, weak: false, declarations: './build/flow', killFlow: false, beep: true, abort: false })); }); gulp.task('test', ['lint'], function() { global.expect = require('chai').expect; global.sinon = require('sinon'); return gulp.src(['src/__tests__/{,*/}*-test.js']) .pipe(mocha({ compilers: { js: babel }, reporter: 'spec', ui: 'bdd' })); }); gulp.task('default', ['lint', 'test']);
Fix crash on reset password page
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Forum\Controller; use DateTime; use Flarum\Core\Exception\InvalidConfirmationTokenException; use Flarum\Core\PasswordToken; use Flarum\Http\Controller\AbstractHtmlController; use Illuminate\Contracts\View\Factory; use Psr\Http\Message\ServerRequestInterface as Request; use Symfony\Component\Translation\TranslatorInterface; class ResetPasswordController extends AbstractHtmlController { /** * @var Factory */ protected $view; /** * @var TranslatorInterface */ protected $translator; /** * @param Factory $view */ public function __construct(Factory $view, TranslatorInterface $translator) { $this->view = $view; $this->translator = $translator; } /** * @param Request $request * @return \Illuminate\Contracts\View\View * @throws InvalidConfirmationTokenException */ public function render(Request $request) { $token = array_get($request->getQueryParams(), 'token'); $token = PasswordToken::findOrFail($token); if ($token->created_at < new DateTime('-1 day')) { throw new InvalidConfirmationTokenException; } return $this->view->make('flarum::reset') ->with('translator', $this->translator) ->with('passwordToken', $token->id) ->with('csrfToken', $request->getAttribute('session')->get('csrf_token')); } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Forum\Controller; use DateTime; use Flarum\Core\Exception\InvalidConfirmationTokenException; use Flarum\Core\PasswordToken; use Flarum\Http\Controller\AbstractHtmlController; use Illuminate\Contracts\View\Factory; use Psr\Http\Message\ServerRequestInterface as Request; class ResetPasswordController extends AbstractHtmlController { /** * @var Factory */ protected $view; /** * @param Factory $view */ public function __construct(Factory $view) { $this->view = $view; } /** * @param Request $request * @return \Illuminate\Contracts\View\View * @throws InvalidConfirmationTokenException */ public function render(Request $request) { $token = array_get($request->getQueryParams(), 'token'); $token = PasswordToken::findOrFail($token); if ($token->created_at < new DateTime('-1 day')) { throw new InvalidConfirmationTokenException; } return $this->view->make('flarum::reset') ->with('passwordToken', $token->id) ->with('csrfToken', $request->getAttribute('session')->get('csrf_token')); } }
Update lock plugin so admins could write messages
""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == update.message.from_user.username: return update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")
""" Echo plugin example """ import octeon global locked locked = [] PLUGINVERSION = 2 # Always name this variable as `plugin` # If you dont, module loader will fail to load the plugin! plugin = octeon.Plugin() @plugin.message(regex=".*") # You pass regex pattern def lock_check(bot, update): if update.message.chat_id in locked: update.message.delete() return @plugin.command(command="/lock", description="Locks chat", inline_supported=True, hidden=False) def lock(bot, update, user, args): if update.message.chat.type != "PRIVATE" and not update.message.chat_id in locked: for admin in update.message.chat.get_administrators(): if admin.user.username == bot.get_me().username: locked.append(update.message.chat_id) return octeon.message("Chat locked") return octeon.message("I am not admin of this chat...") else: return octeon.message("Why would you lock a private converstaion?") @plugin.command(command="/unlock", description="Unlocks chat", inline_supported=True, hidden=False) def unlock(bot, update, user, args): if update.message.chat_id in locked: locked.remove(update.message.chat_id) return octeon.message("Chat unlocked") else: return octeon.message("This chat wasnt locked at all")
Add id tot he beacon event dataset
# -*- coding: utf-8 -*- ''' This package contains the loader modules for the salt streams system ''' # Import salt libs import salt.loader class Beacon(object): ''' This class is used to eveluate and execute on the beacon system ''' def __init__(self, opts): self.opts = opts self.beacons = salt.loader.beacons(opts) def process(self, config): ''' Process the configured beacons The config must be a dict and looks like this in yaml code_block:: yaml beacons: inotify: - /etc/fstab - /var/cache/foo/* ''' ret = [] for mod in config: fun_str = '{0}.beacon'.format(mod) if fun_str in self.beacons: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) raw = self.beacons[fun_str](config[mod]) for data in raw: if 'tag' in data: tag += data.pop('tag') if not 'id' in data: data['id'] = self.opts['id'] ret.append({'tag': tag, 'data': data}) return ret
# -*- coding: utf-8 -*- ''' This package contains the loader modules for the salt streams system ''' # Import salt libs import salt.loader class Beacon(object): ''' This class is used to eveluate and execute on the beacon system ''' def __init__(self, opts): self.opts = opts self.beacons = salt.loader.beacons(opts) def process(self, config): ''' Process the configured beacons The config must be a dict and looks like this in yaml code_block:: yaml beacons: inotify: - /etc/fstab - /var/cache/foo/* ''' ret = [] for mod in config: fun_str = '{0}.beacon'.format(mod) if fun_str in self.beacons: tag = 'salt/beacon/{0}/{1}/'.format(self.opts['id'], mod) raw = self.beacons[fun_str](config[mod]) for data in raw: if 'tag' in data: tag += data.pop('tag') ret.append({'tag': tag, 'data': data}) return ret
Update error message display methods to take formatting arguments
package de.fu_berlin.cdv.chasingpictures.util; import android.content.Context; import android.support.annotation.StringRes; import android.widget.Toast; /** * Class that provides utility methods. * * @author Simon Kalt */ public class Utilities { /** * * @param context The current context * @param formatString The message to be displayed * @param args Arguments to be formatted into the string * @deprecated Use {@link #showError(Context, int, Object...)} if possible. */ @Deprecated public static void showError(Context context, String formatString, Object... args) { Toast.makeText( context, String.format(formatString, args), Toast.LENGTH_SHORT ).show(); } /** * Displays an error to the user. * Currently does the same thing as {@link #showToast(Context, int, Object...)} but * could later be changed to look differently. * @param context The current context * @param resID A string resource to be displayed * @param args Arguments to be formatted into the string */ public static void showError(Context context, @StringRes int resID, Object... args) { showToast(context, resID, args); } /** * Displays a message to the user. * @param context The current context * @param resID A string resource to be displayed * @param args Arguments to be formatted into the string */ public static void showToast(Context context, @StringRes int resID, Object... args) { Toast.makeText( context, String.format(context.getString(resID), args), Toast.LENGTH_SHORT ).show(); } }
package de.fu_berlin.cdv.chasingpictures.util; import android.content.Context; import android.support.annotation.StringRes; import android.widget.Toast; /** * Class that provides utility methods. * * @author Simon Kalt */ public class Utilities { /** * * @param context The current context * @param message The message to be displayed * @deprecated Use {@link #showError(Context, int)} if possible. */ @Deprecated public static void showError(Context context, String message) { Toast.makeText( context, message, Toast.LENGTH_SHORT ).show(); } /** * Displays an error to the user. * Currently does the same thing as {@link #showToast(Context, int)} but * could later be changed to look differently. * * @param context The current context * @param resID A string resource to be displayed */ public static void showError(Context context, @StringRes int resID) { Toast.makeText( context, resID, Toast.LENGTH_SHORT ).show(); } /** * Displays a message to the user. * * @param context The current context * @param resID A string resource to be displayed */ public static void showToast(Context context, @StringRes int resID) { Toast.makeText( context, resID, Toast.LENGTH_SHORT ).show(); } }
Change help text for parse configuration
// Requires var _ = require('underscore'); function setup(options, imports, register) { var deploy = imports.deploy; var shells = imports.shells; /* Documentation about parse command lien tool can be found at: https://parse.com/docs/cloud_code_guide */ deploy.add({ id: "parse", name: "Parse", settings: { app: { label: "Application", type: "text", help: "(optional) Name of your Parse Cloud Code application. If empty, it will use the configuration file config/global.json." } }, actions: [ { id: "deploy", name: "Deploy", action: function(config) { var shellId = "parse:deploy"; return shells.createShellCommand( shellId, ["parse", "deploy", config.app] ).then(function(shell) { return { 'shellId': shellId }; }); } }, { id: "logs", name: "Show Logs", action: function(config) { var shellId = "parse:logs"; return shells.createShellCommand( shellId, ["parse", "log", config.app, "-f"] ).then(function(shell) { return { 'shellId': shellId, 'title': "Parse Logs" }; }); } } ] }); // Register register(null, {}); } // Exports module.exports = setup;
// Requires var _ = require('underscore'); function setup(options, imports, register) { var deploy = imports.deploy; var shells = imports.shells; /* Documentation about parse command lien tool can be found at: https://parse.com/docs/cloud_code_guide */ deploy.add({ id: "parse", name: "Parse", settings: { app: { label: "Application", type: "text", help: "(optional) Name of your Parse Cloud Code application." } }, actions: [ { id: "deploy", name: "Deploy", action: function(config) { var shellId = "parse:deploy"; return shells.createShellCommand( shellId, ["parse", "deploy", config.app] ).then(function(shell) { return { 'shellId': shellId }; }); } }, { id: "logs", name: "Show Logs", action: function(config) { var shellId = "parse:logs"; return shells.createShellCommand( shellId, ["parse", "log", config.app, "-f"] ).then(function(shell) { return { 'shellId': shellId, 'title': "Parse Logs" }; }); } } ] }); // Register register(null, {}); } // Exports module.exports = setup;
[Fix] Add additional checks for no-hardrcoded-password rule
module.exports = context => { function inspectHardcodedPassword(node, value) { const isHardcoded = value.toLowerCase().includes('passw'); if (isHardcoded) { return context.report({ node, message : 'Do not use hadrcoded password' }); } } return { VariableDeclarator({ id, init }) { if (id && id.name && init && init.type === 'Literal' ) { return inspectHardcodedPassword(id, id.name); } }, Property({ key, value }) { if (!key || !value || value.type !== 'Literal') return; if (key.type === 'Identifier') { return inspectHardcodedPassword(key, key.name); } if (key.type === 'Literal') { return inspectHardcodedPassword(key, key.value); } if (key.type === 'TemplateLiteral') { return key.quasis.some(element => inspectHardcodedPassword(key, element.value.raw)); } } }; }; module.exports.schema = [];
module.exports = context => { function inspectHardcodedPassword(node, value) { const isHardcoded = value.toLowerCase().includes('passw'); if (isHardcoded) { return context.report({ node, message : 'Do not use hadrcoded password' }); } } return { VariableDeclarator({ id, init }) { if (id.name && init.type === 'Literal' ) { return inspectHardcodedPassword(id, id.name); } }, Property({ key, value }) { if (value.type !== 'Literal') return; if (key.type === 'Identifier') { return inspectHardcodedPassword(key, key.name); } if (key.type === 'Literal') { return inspectHardcodedPassword(key, key.value); } if (key.type === 'TemplateLiteral') { return key.quasis.some(element => inspectHardcodedPassword(key, element.value.raw)); } } }; }; module.exports.schema = [];
Extend page_size on grantor lookup
import Ember from 'ember'; export default Ember.Controller.extend({ store: Ember.inject.service(), contestSortProperties: [ 'organizationKindSort', 'awardQualifier', 'awardPrimary:desc', 'awardAgeSort', 'awardName', ], sortedContests: Ember.computed.sort( 'model.contests', 'contestSortProperties' ), awardSortProperties: [ 'organizationKindSort', 'isQualifier', 'isPrimary:desc', 'ageSort', 'name', ], rawAwards: Ember.computed( 'model', function() { return this.get('store').query('award', { 'organization__grantors__session': this.get('model.id'), 'page_size': 100, }); } ), filteredAwards: Ember.computed( 'rawAwards.@each.{kind,season}', 'model.kind', 'model.convention.season', function() { return this.get('rawAwards').filterBy('kind', this.get('model.kind')).filterBy('season', this.get('model.convention.season')); } ), uniqueAwards: Ember.computed.uniq( 'filteredAwards', ), sortedAwards: Ember.computed.sort( 'uniqueAwards', 'awardSortProperties', ), actions: { sortBy(contestSortProperties) { this.set('contestSortProperties', [contestSortProperties]); }, sortByAward(awardSortProperties) { this.set('awardSortProperties', [awardSortProperties]); }, } });
import Ember from 'ember'; export default Ember.Controller.extend({ store: Ember.inject.service(), contestSortProperties: [ 'organizationKindSort', 'awardQualifier', 'awardPrimary:desc', 'awardAgeSort', 'awardName', ], sortedContests: Ember.computed.sort( 'model.contests', 'contestSortProperties' ), awardSortProperties: [ 'organizationKindSort', 'isQualifier', 'isPrimary:desc', 'ageSort', 'name', ], rawAwards: Ember.computed( 'model', function() { return this.get('store').query('award', { 'organization__grantors__session': this.get('model.id'), }); } ), filteredAwards: Ember.computed( 'rawAwards.@each.{kind,season}', 'model.kind', 'model.convention.season', function() { return this.get('rawAwards').filterBy('kind', this.get('model.kind')).filterBy('season', this.get('model.convention.season')); } ), uniqueAwards: Ember.computed.uniq( 'filteredAwards', ), sortedAwards: Ember.computed.sort( 'uniqueAwards', 'awardSortProperties', ), actions: { sortBy(contestSortProperties) { this.set('contestSortProperties', [contestSortProperties]); }, sortByAward(awardSortProperties) { this.set('awardSortProperties', [awardSortProperties]); }, } });
Include '-' in ID, print IDs separated by ','
import re import sys # $ zmmailbox -z -m [email protected] search -l 200 "in:/inbox (before:today)" # num: 200, more: true # # Id Type From Subject Date # ------- ---- -------------------- -------------------------------------------------- -------------- # 1. -946182 conv admin Daily mail report 09/24/15 23:57 # 2. 421345 conv John Some great news for you 09/24/15 23:57 REGEX_HEAD = re.compile(r'^Id') REGEX_HEAD_SEP = re.compile(r'^---') REGEX_DATA = re.compile(r'^(\d+)\.\s+(\-?\d+)\s+(\S+)') def main(): lines = [line.strip() for line in sys.stdin.readlines() if line.strip()] while True: line = lines.pop(0) if REGEX_HEAD.search(line): break line = lines.pop(0) assert REGEX_HEAD_SEP.search(line) ids = [] for line in lines: matched = REGEX_DATA.match(line) if matched: ids.append(matched.group(2)) else: sys.stderr.write("Couldn't parse line: {0}\n".format(line)) sys.exit(1) print ','.join(ids) if __name__ == '__main__': main()
import re import sys # $ zmmailbox -z -m [email protected] search -l 200 "in:/inbox (before:today)" # num: 200, more: true # # Id Type From Subject Date # ------- ---- -------------------- -------------------------------------------------- -------------- # 1. -946182 conv admin Daily mail report 09/24/15 23:57 # 2. 421345 conv John Some great news for you 09/24/15 23:57 REGEX_HEAD = re.compile(r'^Id') REGEX_HEAD_SEP = re.compile(r'^---') REGEX_DATA = re.compile(r'^(\d+)\.\s+\-?(\d+)\s+(\S+)') def main(): lines = [line.strip() for line in sys.stdin.readlines() if line.strip()] while True: line = lines.pop(0) if REGEX_HEAD.search(line): break line = lines.pop(0) assert REGEX_HEAD_SEP.search(line) ids = [] for line in lines: matched = REGEX_DATA.match(line) if matched: ids.append(matched.group(2)) else: sys.stderr.write("Couldn't parse line: {0}\n".format(line)) sys.exit(1) for an_id in ids: print an_id if __name__ == '__main__': main()
Revert "Add query response minimizer parameter back" This reverts commit ead7b0d5c99c2e3d9ae14310af8f16bf56bf2a70.
package com.lloydtorres.stately.dto; import android.os.Parcel; import android.os.Parcelable; /** * Created by Lloyd on 2016-01-28. * An object containing text for one of the options in an issue. */ public class IssueOption implements Parcelable { public static final String QUERY = "https://www.nationstates.net/page=show_dilemma/dilemma=%d/template-overall=none"; public static final String POST_QUERY = "https://www.nationstates.net/page=enact_dilemma/dilemma=%d"; public static final String SELECTED_HEADER = "selected"; public static final String DISMISS_HEADER = "choice--1"; public int index; public String content; public String header; public IssueOption() { super(); } protected IssueOption(Parcel in) { index = in.readInt(); content = in.readString(); header = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(index); dest.writeString(content); dest.writeString(header); } @SuppressWarnings("unused") public static final Parcelable.Creator<IssueOption> CREATOR = new Parcelable.Creator<IssueOption>() { @Override public IssueOption createFromParcel(Parcel in) { return new IssueOption(in); } @Override public IssueOption[] newArray(int size) { return new IssueOption[size]; } }; }
package com.lloydtorres.stately.dto; import android.os.Parcel; import android.os.Parcelable; /** * Created by Lloyd on 2016-01-28. * An object containing text for one of the options in an issue. */ public class IssueOption implements Parcelable { public static final String QUERY = "https://www.nationstates.net/page=show_dilemma/dilemma=%d/template-overall=none"; public static final String POST_QUERY = "https://www.nationstates.net/page=enact_dilemma/dilemma=%d/template-overall=none"; public static final String SELECTED_HEADER = "selected"; public static final String DISMISS_HEADER = "choice--1"; public int index; public String content; public String header; public IssueOption() { super(); } protected IssueOption(Parcel in) { index = in.readInt(); content = in.readString(); header = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(index); dest.writeString(content); dest.writeString(header); } @SuppressWarnings("unused") public static final Parcelable.Creator<IssueOption> CREATOR = new Parcelable.Creator<IssueOption>() { @Override public IssueOption createFromParcel(Parcel in) { return new IssueOption(in); } @Override public IssueOption[] newArray(int size) { return new IssueOption[size]; } }; }
Use __name__ from data object to set the test method name, if available. Allows to provide user-friendly names for the user instead of the default raw data formatting.
from functools import wraps __version__ = '0.1.1' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, MAGIC, values) return func return wrapper def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. """ def feed_data(func, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) return wrapper for name, f in cls.__dict__.items(): if hasattr(f, MAGIC): i = 0 for v in getattr(f, MAGIC): test_name = getattr(v, "__name__", "{0}_{1}".format(name, v)) setattr(cls, test_name, feed_data(f, v)) i = i + 1 delattr(cls, name) return cls
from functools import wraps __version__ = '0.1.1' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, MAGIC, values) return func return wrapper def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. """ def feed_data(func, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) return wrapper for name, f in cls.__dict__.items(): if hasattr(f, MAGIC): i = 0 for v in getattr(f, MAGIC): setattr(cls, "{0}_{1}".format(name, v), feed_data(f, v)) i = i + 1 delattr(cls, name) return cls
Revert "enforce including configuration on gae" This reverts commit f60e153b
<?php $config = []; if (in_array('gs', stream_get_wrappers())) { $config = include 'gs://teach-242612.appspot.com/config/config.php'; } return array_merge_recursive([ 'DB' => [ 'CONNECTION' => getenv('DB_CONNECTION'), 'HOST' => getenv('DB_HOST'), 'PORT' => getenv('DB_PORT'), 'DATABASE' => getenv('DB_DATABASE'), 'USERNAME' => getenv('DB_USERNAME'), 'PASSWORD' => getenv('DB_PASSWORD'), 'PREFIX' => getenv('DB_PREFIX') ], 'OAUTH' => [ 'identifier' => getenv('OAUTH_CLIENT_ID'), "secret" => getenv('OAUTH_CLIENT_SECRET'), 'callback_uri' => getenv('OAUTH_CALLBACK_URI') ], 'MEMCACHED' => [ 'host' => getenv('MEMCACHED_HOST'), 'port' => getenv('MEMCACHED_PORT') ], 'BOOTSTRAP' => [ 'path' => __DIR__ . DIRECTORY_SEPARATOR . 'bootstrap' ], 'ROUTER' => [ 'path' => __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'GUI' ], 'PHPVIEW' => [ 'path' => __DIR__ . DIRECTORY_SEPARATOR . 'phpview' ], 'ASSETS' => [ 'path' => __DIR__ . DIRECTORY_SEPARATOR . 'assets' ] ], $config);
<?php $config = []; if (in_array('gs', stream_get_wrappers())) { $config = require 'gs://' . getenv('GOOGLE_CLOUD_PROJECT') .'.appspot.com/config/config.php'; } return array_merge_recursive([ 'DB' => [ 'CONNECTION' => getenv('DB_CONNECTION'), 'HOST' => getenv('DB_HOST'), 'PORT' => getenv('DB_PORT'), 'DATABASE' => getenv('DB_DATABASE'), 'USERNAME' => getenv('DB_USERNAME'), 'PASSWORD' => getenv('DB_PASSWORD'), 'PREFIX' => getenv('DB_PREFIX') ], 'OAUTH' => [ 'identifier' => getenv('OAUTH_CLIENT_ID'), "secret" => getenv('OAUTH_CLIENT_SECRET'), 'callback_uri' => getenv('OAUTH_CALLBACK_URI') ], 'MEMCACHED' => [ 'host' => getenv('MEMCACHED_HOST'), 'port' => getenv('MEMCACHED_PORT') ], 'BOOTSTRAP' => [ 'path' => __DIR__ . DIRECTORY_SEPARATOR . 'bootstrap' ], 'ROUTER' => [ 'path' => __DIR__ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'GUI' ], 'PHPVIEW' => [ 'path' => __DIR__ . DIRECTORY_SEPARATOR . 'phpview' ], 'ASSETS' => [ 'path' => __DIR__ . DIRECTORY_SEPARATOR . 'assets' ] ], $config);
Fix title of swagger api Used swagger options from different project (shame on me). Change title to ‘Microbrew.it Log Server’.
'use strict'; const Glue = require('glue'); const Package = require('../package.json'); const internals = { manifest: { connections: [ { host: process.env.LOG_SERVER_HOST || 'localhost', port: process.env.LOG_SERVER_PORT || 8080, labels: ['api'], } ], registrations: [ { plugin: { register: 'good', options: { opsInterval: 1000, reporters: [ { reporter: require('good-console'), events: { log: '*', response: '*' }, }, ], }, }, }, { plugin: { register: 'inert' } }, { plugin: { register: 'vision' } }, { plugin: { register: 'hapi-swagger', options: { info: { title: 'Microbrew.it Log Server', description: `${Package.name}:${Package.version} - ${Package.description}`, version: `v${Package.version.split('.')[0]}`, }, }, }, }, { plugin: { register: './log-api', } } ] } }; module.exports = Glue.compose.bind(Glue, internals.manifest, { relativeTo: __dirname });
'use strict'; const Glue = require('glue'); const Package = require('../package.json'); const internals = { manifest: { connections: [ { host: process.env.LOG_SERVER_HOST || 'localhost', port: process.env.LOG_SERVER_PORT || 8080, labels: ['api'], } ], registrations: [ { plugin: { register: 'good', options: { opsInterval: 1000, reporters: [ { reporter: require('good-console'), events: { log: '*', response: '*' }, }, ], }, }, }, { plugin: { register: 'inert' } }, { plugin: { register: 'vision' } }, { plugin: { register: 'hapi-swagger', options: { info: { title: 'Open Source Metadata Harvester API documentation', description: `${Package.name}:${Package.version} - ${Package.description}`, version: `v${Package.version.split('.')[0]}`, }, }, }, }, { plugin: { register: './log-api', } } ] } }; module.exports = Glue.compose.bind(Glue, internals.manifest, { relativeTo: __dirname });