text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add staticmethod annotation + docstrings to module, class, and all public methods
"""Module with class representing common API.""" import requests import os class Api: """Class representing common API.""" _API_ENDPOINT = 'api/v1' def __init__(self, url, token=None): """Set the API endpoint and store the authorization token if provided.""" self.url = Api.add_slash(url) self.token = token def is_api_running(self): """Check if the API is available for calls.""" try: res = requests.get(self.url) if res.status_code in {200, 401}: return True except requests.exceptions.ConnectionError: pass return False @staticmethod def add_slash(url): """Add a slash at end of URL, if the slash is not provided.""" if url and not url.endswith('/'): url += '/' return url def get(self): """Use GET method to access API.""" return requests.get(self.url) def print_error_response(self, response, message_key): """Print error message if anything goes wrong.""" print(" Server returned HTTP code {c}".format(c=response.status_code)) print(" Error message: {m}".format(m=error_message))
import requests import os class Api: _API_ENDPOINT = 'api/v1' def __init__(self, url, token=None): self.url = Api.add_slash(url) self.token = token def is_api_running(self): try: res = requests.get(self.url) if res.status_code in {200, 401}: return True except requests.exceptions.ConnectionError: pass return False def add_slash(url): if url and not url.endswith('/'): url += '/' return url def get(self): return requests.get(self.url) def print_error_response(self, response, message_key): error_message = response.json().get(message_key, "Server does not sent error message") print(" Server returned HTTP code {c}".format(c=response.status_code)) print(" Error message: {m}".format(m=error_message))
Use absolute url path for css asset
<?php defined('THISPATH') or die('Can\'t access directly!'); class Controller_home extends Panada { public function __construct(){ parent::__construct(); } public function index(){ $views['doc_type'] = $this->html->doctype('xhtml1-strict'); $views['css_file'] = $this->html->load_css( $this->config->base_url() . 'apps/asset/css/main.css', false); $views['page_title'] = 'Hello World!'; $views['head'] = 'Panada has been installed successfully!'; $views['content'] = '<p>This is sample page. You find this file at:</p>'; $views['content'] .= '<code>'.pathinfo(APPLICATION, PATHINFO_BASENAME).'/view/index.php</code>'; $views['content'] .= '<code>'.pathinfo(APPLICATION, PATHINFO_BASENAME).'/controller/home.php</code>'; $views['footer'] = '<div id="foot">Powered by <a href="http://panadaframework.com/">Panada</a> version '.PANADA_VERSION.''; $views['footer'] .= '<span class="right">Page rendered in '.Library_time_execution::stop().' seconds</span></div>'; $this->view_index($views); } }
<?php defined('THISPATH') or die('Can\'t access directly!'); class Controller_home extends Panada { public function __construct(){ parent::__construct(); } public function index(){ $views['doc_type'] = $this->html->doctype('xhtml1-strict'); $views['css_file'] = $this->html->load_css('apps/asset/css/main.css', false); $views['page_title'] = 'Hello World!'; $views['head'] = 'Panada has been installed successfully!'; $views['content'] = '<p>This is sample page. You find this file at:</p>'; $views['content'] .= '<code>'.pathinfo(APPLICATION, PATHINFO_BASENAME).'/view/home.php</code>'; $views['content'] .= '<code>'.pathinfo(APPLICATION, PATHINFO_BASENAME).'/controller/home.php</code>'; $views['footer'] = '<div id="foot">Powered by <a href="http://panadaframework.com/">Panada</a> version '.PANADA_VERSION.''; $views['footer'] .= '<span class="right">Page rendered in '.Library_time_execution::stop().' seconds</span></div>'; $this->view_index($views); } }
Add argument handling for path and project name
import argparse import sys from django.core.management import setup_environ import settings setup_environ(settings) from django.db.utils import DatabaseError from django.db.transaction import rollback_unless_managed from django.db import models def get_model_info(): ''' Dump all models and their row counts to the screen ''' project_models = models.get_models(include_auto_created=True) for them in project_models: try: print them._meta.db_table + " " + str(them.objects.all().count()) except DatabaseError: print "Unexpected error and continuing:", sys.exc_info()[0] , " ", them rollback_unless_managed() except: print "Unexpected error and abending:", sys.exc_info()[0] break def process_args(): ''' Process command line args ''' parser = argparse.ArgumentParser() parser.add_argument("path_to_project_root") parser.add_argument("project_name") args = parser.parse_args() return args def main(): ''' Handle main processing ''' args = process_args() get_model_info() if __name__ == "__main__": main()
import sys from django.core.management import setup_environ import settings setup_environ(settings) from django.db.utils import DatabaseError from django.db.transaction import rollback_unless_managed from django.db import models def get_model_info(): ''' Dump all models and their row counts to the screen ''' project_models = models.get_models(include_auto_created=True) for them in project_models: try: print them._meta.db_table + " " + str(them.objects.all().count()) except DatabaseError: print "Unexpected error and continuing:", sys.exc_info()[0] , " ", them rollback_unless_managed() except: print "Unexpected error and abending:", sys.exc_info()[0] break def main(): ''' Handle main processing ''' get_model_info() if __name__ == "__main__": main()
Return the authorization url when `authorize` fails s.t. the user can manually authorize and set the token in `config.js`
/** * The authorization token with which calls to the API are made. * @type {String} */ let token = ''; const AUTHORIZE_ENDPOINT = 'https://www.dropbox.com/oauth2/authorize'; const getAuthorizationUrl = (clientId) => { return AUTHORIZE_ENDPOINT + '?' + 'response_type=token' + 'client_id=' + clientId; }; /** * Authorize via OAuth 2.0 for Dropbox API calls. * * @parameter {string} clientId your app's key * @parameter {string} redirectUri the uri where the user should be redirected * to, after authorization has completed * @return {function} a promise that resolves or fails both with the returned * HTTP status code */ const authorize = (clientId, redirectUri = '') => { return new Promise((resolve, reject) => { reject('Not implemented yet, please obtain a token manually by calling ' + getAuthorizationUrl(clientId)); }); }; /** * Set the token that is used for all Dropbox API calls to the given value. * @param {string} t The new token value. */ const setToken = (t) => { if (typeof t !== 'string') { throw new Error('invalid argument ' + t + ' (expected: string)'); } token = t; }; module.exports = { authorize, setToken };
/** * The authorization token with which calls to the API are made. * @type {String} */ let token = ''; /** * Authorize via OAuth 2.0 for Dropbox API calls. * * @parameter {string} clientId your app's key * @parameter {string} redirectUri the uri where the user should be redirected * to, after authorization has completed * @return {function} a promise that resolves or fails both with the returned * HTTP status code */ const authorize = (clientId, redirectUri = '') => { return new Promise((resolve, reject) => { reject('not implemented yet'); }); }; /** * Set the token that is used for all Dropbox API calls to the given value. * @param {string} t The new token value. */ const setToken = (t) => { if (typeof t !== 'string') { throw new Error('invalid argument ' + t + ' (expected: string)'); } token = t; }; module.exports = { authorize, setToken };
Make imports work when in .sublime-package
import os import sys try: # ST3 from .Lib.sublime_lib.path import get_package_name PLUGIN_NAME = get_package_name() path = os.path.dirname(__file__) libpath = os.path.join(path, "Lib") except ValueError: # ST2 # For some reason the import does only work when RELOADING the plugin, not # when ST is loading it initially. # from lib.sublime_lib.path import get_package_name, get_package_path path = os.path.normpath(os.getcwdu()) PLUGIN_NAME = os.path.basename(path) libpath = os.path.join(path, "Lib") def add(path): if not path in sys.path: sys.path.append(path) print("[%s] Added %s to sys.path." % (PLUGIN_NAME, path)) # Make sublime_lib (and more) available for all packages. add(libpath) # Differentiate between Python 2 and Python 3 packages (split by folder) add(os.path.join(libpath, "_py%d" % sys.version_info[0]))
import os import sys try: # ST3 from .Lib.sublime_lib.path import get_package_name, get_package_path PLUGIN_NAME = get_package_name() libpath = os.path.join(get_package_path(), "Lib") except ValueError: # ST2 # For some reason the import does only work when RELOADING the plugin, not # when ST is loading it initially. # from lib.sublime_lib.path import get_package_name, get_package_path path = os.path.normpath(os.getcwdu()) PLUGIN_NAME = os.path.basename(path) libpath = os.path.join(path, "Lib") def add(path): if not path in sys.path: sys.path.append(path) print("[%s] Added %s to sys.path." % (PLUGIN_NAME, path)) # Make sublime_lib (and more) available for all packages. add(libpath) # Differentiate between Python 2 and Python 3 packages (split by folder) add(os.path.join(libpath, "_py%d" % sys.version_info[0]))
Reset fields after document create
import Ember from 'ember'; export default Ember.Controller.extend({ previewVisible: false, actions: { togglePreview: function() { this.toggleProperty('previewVisible'); }, saveDocument: function() { var self = this; var doc = this.store.createRecord('document', { name: this.get('name'), text: this.get('text'), created: new Date() }); doc.save().then(function() { self.setProperties({name: '', text: ''}); self.transitionToRoute('document', doc); }); }, cancelDocument: function() { this.set('name', ''); this.set('text', ''); this.transitionToRoute('documents.index'); } } });
import Ember from 'ember'; export default Ember.Controller.extend({ previewVisible: false, actions: { togglePreview: function() { this.toggleProperty('previewVisible'); }, saveDocument: function() { var self = this; var doc = this.store.createRecord('document', { name: this.get('name'), text: this.get('text'), created: new Date() }); doc.save().then(function() { self.transitionToRoute('document', doc); }); }, cancelDocument: function() { this.set('name', ''); this.set('text', ''); this.transitionToRoute('documents.index'); } } });
Make configuration overrideable from /etc
<?php require_once('IP2Country.php'); define('DB_SERVER', 'localhost'); define('DB_PORT', 3306); define('DB_NAME', 'dnscheckng'); define('DB_USER', 'dnscheckng'); define('DB_PASS', 'dnscheckng'); define('STATUS_OK', 'OK'); define('STATUS_WARN', 'WARNING'); define('STATUS_ERROR', 'ERROR'); define('STATUS_DOMAIN_DOES_NOT_EXIST', 'ERROR_DOMAIN_DOES_NOT_EXIST'); define('STATUS_DOMAIN_SYNTAX', 'ERROR_DOMAIN_SYNTAX'); define('STATUS_NO_NAMESERVERS', 'ERROR_NO_NAMESERVERS'); define('STATUS_IN_PROGRESS', 'IN_PROGRESS'); define('STATUS_INTERNAL_ERROR', 'INTERNAL_ERROR'); define('PAGER_SIZE', 10); define('GUI_TIMEOUT', 300); $sourceIdentifiers = array( 'standard' => 'webgui', 'undelegated' => 'webgui-undelegated' ); define('DEFAULT_LANGUAGE_ID', getDefaultLanguage()); /* Provide a place where settings can be overridden, to make Debian packaging easier. */ if (is_readable('/etc/dnscheck.php')) { require_once('/etc/dnscheck.php'); } ?>
<?php require_once('IP2Country.php'); define('DB_SERVER', 'localhost'); define('DB_PORT', 3306); define('DB_NAME', 'dnscheckng'); define('DB_USER', 'dnscheckng'); define('DB_PASS', 'dnscheckng'); define('STATUS_OK', 'OK'); define('STATUS_WARN', 'WARNING'); define('STATUS_ERROR', 'ERROR'); define('STATUS_DOMAIN_DOES_NOT_EXIST', 'ERROR_DOMAIN_DOES_NOT_EXIST'); define('STATUS_DOMAIN_SYNTAX', 'ERROR_DOMAIN_SYNTAX'); define('STATUS_NO_NAMESERVERS', 'ERROR_NO_NAMESERVERS'); define('STATUS_IN_PROGRESS', 'IN_PROGRESS'); define('STATUS_INTERNAL_ERROR', 'INTERNAL_ERROR'); define('PAGER_SIZE', 10); define('GUI_TIMEOUT', 300); $sourceIdentifiers = array( 'standard' => 'webgui', 'undelegated' => 'webgui-undelegated' ); define('DEFAULT_LANGUAGE_ID', getDefaultLanguage()); ?>
Make export button only export jpegs
export default { standard: { credits: { enabled: false }, chart: { spacingBottom: 20, style: { fontFamily: "'proxima', 'Helvetica', sans-serif' ", paddingTop: '20px' // Make room for buttons } }, exporting: { buttons: { contextButton: { onclick: function () { this.exportChart({type: 'jpeg'}) }, symbol: null, text: 'Export', x: -20, y: -30, theme: { style: { color: '#039', textDecoration: 'underline' } } } } }, title: '' } }
export default { standard: { credits: { enabled: false }, chart: { spacingBottom: 20, style: { fontFamily: "'proxima', 'Helvetica', sans-serif' ", paddingTop: '20px' // Make room for buttons } }, exporting: { buttons: { contextButton: { symbol: null, text: 'Export', x: -20, y: -30, theme: { style: { color: '#039', textDecoration: 'underline' } } } } }, title: '' } }
Improve trainer logging and print every logged message to console
from sft.sim.PathWorldGenerator import PathWorldGenerator class SimplePathWorldGenerator(PathWorldGenerator): def __init__(self, logger, view_size, world_size, sampler, path_in_init_view=False, target_not_in_init_view=False): # enforce simple paths consisting of one step, i.e. straight lines super(SimplePathWorldGenerator, self).__init__(logger, view_size, world_size, sampler, path_length_min=1, path_length_max=1, path_step_length_min=max(world_size.tuple()) / 3, path_in_init_view=path_in_init_view, target_not_in_init_view=target_not_in_init_view)
from sim.PathWorldGenerator import PathWorldGenerator class SimplePathWorldGenerator(PathWorldGenerator): def __init__(self, logger, view_size, world_size, sampler, path_in_init_view=False, target_not_in_init_view=False): # enforce simple paths consisting of one step, i.e. straight lines super(SimplePathWorldGenerator, self).__init__(logger, view_size, world_size, sampler, path_length_min=1, path_length_max=1, path_step_length_min=max(world_size.tuple()) / 3, path_in_init_view=path_in_init_view, target_not_in_init_view=target_not_in_init_view)
Move variable declaration out of loop.
'use strict'; angular.module('arachne.widgets.directives') .directive('con10tSearchQuery', function() { return { restrict: 'A', link: function(scope, element, attrs) { attrs.$observe('con10tSearchQuery', function(value) { scope.q = value; updateHref(); }); attrs.$observe('con10tSearchFacet', function(value) { scope.fq = value; updateHref(); }); function updateHref() { var href = "http://arachne.dainst.org/search?q=" + scope.q; if (scope.fq) { var split, fqs = scope.fq.split(','); fqs.forEach(function(fq) { split = fq.split(':'); href += '&fq='+split[0]+':"'+split[1]+'"'; }); } element.attr("href", href); } } }});
'use strict'; angular.module('arachne.widgets.directives') .directive('con10tSearchQuery', function() { return { restrict: 'A', link: function(scope, element, attrs) { attrs.$observe('con10tSearchQuery', function(value) { scope.q = value; updateHref(); }); attrs.$observe('con10tSearchFacet', function(value) { scope.fq = value; updateHref(); }); function updateHref() { var href = "http://arachne.dainst.org/search?q=" + scope.q; if (scope.fq) { var fqs = scope.fq.split(','); fqs.forEach(function(fq) { var split = fq.split(':'); href += '&fq='+split[0]+':"'+split[1]+'"'; }); } element.attr("href", href); } } }});
Update author to Blanc Ltd
#!/usr/bin/env python from setuptools import find_packages, setup setup( name='blanc-basic-events', version='0.3.2', description='Blanc Basic Events for Django', long_description=open('README.rst').read(), url='https://github.com/blancltd/blanc-basic-events', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], install_requires=[ 'blanc-basic-assets>=0.3', 'icalendar>=3.6', ], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], license='BSD', )
#!/usr/bin/env python from setuptools import find_packages, setup setup( name='blanc-basic-events', version='0.3.2', description='Blanc Basic Events for Django', long_description=open('README.rst').read(), url='https://github.com/blancltd/blanc-basic-events', maintainer='Alex Tomkins', maintainer_email='alex@blanc.ltd.uk', platforms=['any'], install_requires=[ 'blanc-basic-assets>=0.3', 'icalendar>=3.6', ], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], license='BSD', )
Revert "Need a check for an emtpy hash" This reverts commit 07100389c363710260f4c0f5799da548672ad06a.
package ca.corefacility.bioinformatics.irida.model.sample; import java.util.HashMap; import java.util.Map; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; /** * Stores unstructured metadata for a given {@link Sample}. */ @Document public class SampleMetadata { @Field(value = "metadata") Map<String, Object> metadata; @Id Long sampleId; public SampleMetadata() { metadata = new HashMap<>(); } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } public Long getSampleId() { return sampleId; } public void setSampleId(Long sampleId) { this.sampleId = sampleId; } }
package ca.corefacility.bioinformatics.irida.model.sample; import java.util.HashMap; import java.util.Map; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; /** * Stores unstructured metadata for a given {@link Sample}. */ @Document public class SampleMetadata { @Field(value = "metadata") Map<String, Object> metadata; @Id Long sampleId; public SampleMetadata() { metadata = new HashMap<>(); } public Map<String, Object> getMetadata() { if (this.metadata == null) { this.metadata = new HashMap<>(); } return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } public Long getSampleId() { return sampleId; } public void setSampleId(Long sampleId) { this.sampleId = sampleId; } }
Use new obit config to lookup sources and strategies
import { getOwner } from '@ember/application'; import Coordinator from '@orbit/coordinator'; import modulesOfType from '../system/modules-of-type'; export default { create(injections = {}) { const app = getOwner(injections); let orbitConfig = app.lookup('ember-orbit:config'); let sourceNames; if (injections.sourceNames) { sourceNames = injections.sourceNames; delete injections.sourceNames; } else { sourceNames = modulesOfType(app.base.modulePrefix, orbitConfig.collections.sources); sourceNames.push('store'); } let strategyNames; if (injections.strategyNames) { strategyNames = injections.strategyNames; delete injections.strategyNames; } else { strategyNames = modulesOfType(app.base.modulePrefix, orbitConfig.collections.strategies); } injections.sources = sourceNames.map(name => app.lookup(`${orbitConfig.types.source}:${name}`)); injections.strategies = strategyNames.map(name => app.lookup(`${orbitConfig.types.strategy}:${name}`)); return new Coordinator(injections); } }
import { getOwner } from '@ember/application'; import Coordinator from '@orbit/coordinator'; import modulesOfType from '../system/modules-of-type'; export default { create(injections = {}) { const owner = getOwner(injections); let sourceNames; if (injections.sourceNames) { sourceNames = injections.sourceNames; delete injections.sourceNames; } else { sourceNames = modulesOfType(owner.base.modulePrefix, 'data-sources'); sourceNames.push('store'); } let strategyNames; if (injections.strategyNames) { strategyNames = injections.strategyNames; delete injections.strategyNames; } else { strategyNames = modulesOfType(owner.base.modulePrefix, 'data-strategies'); } injections.sources = sourceNames.map(name => owner.lookup(`data-source:${name}`)); injections.strategies = strategyNames.map(name => owner.lookup(`data-strategy:${name}`)); return new Coordinator(injections); } }
Change slider scroll count to 3 instead of 5
$(function() { //tabs $('ul.tabs li').click(function(){ var tab_id = $(this).attr('data-tab'); $('ul.tabs li').removeClass('current'); $('.tab-content').removeClass('current'); $(this).addClass('current'); $("#"+tab_id).addClass('current'); }) //retina retinajs(); //sticky navigation $("#sticker").sticky({ topSpacing: 105 }).on('sticky-end', function() { //$("#sticker").addClass("sticky-end"); //setTimeout(function(){ // $("#sticker").removeClass("sticky-end"); //}, 1000); }); //slider settings $('.slick-slider').slick({ arrows: false, infinite: true, slidesToShow: 6, slidesToScroll: 3, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 3, slidesToScroll: 2, infinite: true, } }, { breakpoint: 700, settings: { slidesToShow: 2, slidesToScroll: 1 } } ] }); $('header .next').click(function(){ $(".slick-slider").slick('slickNext'); }); });
$(function() { //tabs $('ul.tabs li').click(function(){ var tab_id = $(this).attr('data-tab'); $('ul.tabs li').removeClass('current'); $('.tab-content').removeClass('current'); $(this).addClass('current'); $("#"+tab_id).addClass('current'); }) //retina retinajs(); //sticky navigation $("#sticker").sticky({ topSpacing: 105 }).on('sticky-end', function() { //$("#sticker").addClass("sticky-end"); //setTimeout(function(){ // $("#sticker").removeClass("sticky-end"); //}, 1000); }); //slider settings $('.slick-slider').slick({ arrows: false, infinite: true, slidesToShow: 6, slidesToScroll: 5, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 3, slidesToScroll: 2, infinite: true, } }, { breakpoint: 700, settings: { slidesToShow: 2, slidesToScroll: 1 } } ] }); $('header .next').click(function(){ $(".slick-slider").slick('slickNext'); }); });
Make pip log world writable
""" Python Blueprint ================ Does not install python itself, only develop and setup tools. Contains pip helper for other blueprints to use. **Fabric environment:** .. code-block:: yaml blueprints: - blues.python """ from fabric.decorators import task from refabric.api import run, info from refabric.context_managers import sudo from . import debian __all__ = ['setup'] pip_log_file = '/tmp/pip.log' @task def setup(): """ Install python develop tools """ install() def install(): with sudo(): info('Install python dependencies') debian.apt_get('install', 'python-dev', 'python-setuptools') run('easy_install -0 pip') run('touch {}'.format(pip_log_file)) debian.chmod(pip_log_file, mode=777) def pip(command, *options): info('Running pip {}', command) run('pip {0} {1} -v --log={2} --log-file={2}'.format(command, ' '.join(options), pip_log_file))
""" Python Blueprint ================ Does not install python itself, only develop and setup tools. Contains pip helper for other blueprints to use. **Fabric environment:** .. code-block:: yaml blueprints: - blues.python """ from fabric.decorators import task from refabric.api import run, info from refabric.context_managers import sudo from . import debian __all__ = ['setup'] @task def setup(): """ Install python develop tools """ install() def install(): with sudo(): info('Install python dependencies') debian.apt_get('install', 'python-dev', 'python-setuptools') run('easy_install -0 pip') def pip(command, *options): info('Running pip {}', command) run('pip {} {} -v --log=/tmp/pip.log --log-file=/tmp/pip.log'.format(command, ' '.join(options)))
Add testStyles and prefixed to the depedencies.
define(['Modernizr', 'createElement', 'docElement', 'prefixed', 'testStyles'], function( Modernizr, createElement, docElement, prefixed, testStyles ) { // http://www.w3.org/TR/css3-exclusions // http://www.w3.org/TR/css3-exclusions/#shapes // Examples: http://html.adobe.com/webstandards/cssexclusions // Separate test for CSS shapes as WebKit has just implemented this alone Modernizr.addTest('shapes', function () { var prefixedProperty = prefixed('shapeInside'); if (!prefixedProperty) return false; var shapeInsideProperty = prefixedProperty.replace(/([A-Z])/g, function (str, m1) { return '-' + m1.toLowerCase(); }).replace(/^ms-/, '-ms-'); return testStyles('#modernizr { ' + shapeInsideProperty + ':rectangle(0,0,0,0) }', function (elem) { // Check against computed value var styleObj = window.getComputedStyle ? getComputedStyle(elem, null) : elem.currentStyle; return styleObj[prefixed('shapeInside', docElement.style, false)] == 'rectangle(0px, 0px, 0px, 0px)'; }); }); });
define(['Modernizr', 'createElement', 'docElement'], function( Modernizr, createElement, docElement ) { // http://www.w3.org/TR/css3-exclusions // http://www.w3.org/TR/css3-exclusions/#shapes // Examples: http://html.adobe.com/webstandards/cssexclusions // Separate test for CSS shapes as WebKit has just implemented this alone Modernizr.addTest('shapes', function () { var prefixedProperty = Modernizr.prefixed('shapeInside'); if (!prefixedProperty) return false; var shapeInsideProperty = prefixedProperty.replace(/([A-Z])/g, function (str, m1) { return '-' + m1.toLowerCase(); }).replace(/^ms-/, '-ms-'); return Modernizr.testStyles('#modernizr { ' + shapeInsideProperty + ':rectangle(0,0,0,0) }', function (elem) { // Check against computed value var styleObj = window.getComputedStyle ? getComputedStyle(elem, null) : elem.currentStyle; return styleObj[prefixed('shapeInside', docElement.style, false)] == 'rectangle(0px, 0px, 0px, 0px)'; }); }); });
Disable cleaning of staged participants when retain interval specified is 0 days.
package com.krishagni.catissueplus.core.biospecimen.services.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import com.krishagni.catissueplus.core.administrative.domain.ScheduledJobRun; import com.krishagni.catissueplus.core.administrative.services.ScheduledTask; import com.krishagni.catissueplus.core.biospecimen.ConfigParams; import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory; import com.krishagni.catissueplus.core.common.PlusTransactional; import com.krishagni.catissueplus.core.common.util.ConfigUtil; @Configurable public class StagedParticipantsCleanupTask implements ScheduledTask { private static final int DEF_CLEANUP_INT = 90; @Autowired private DaoFactory daoFactory; @Override @PlusTransactional public void doJob(ScheduledJobRun jobRun) throws Exception { int olderThanDays = ConfigUtil.getInstance().getIntSetting( ConfigParams.MODULE, ConfigParams.STAGED_PART_CLEANUP_INT, DEF_CLEANUP_INT); if (olderThanDays > 0) { daoFactory.getStagedParticipantDao().cleanupOldParticipants(olderThanDays); } } }
package com.krishagni.catissueplus.core.biospecimen.services.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import com.krishagni.catissueplus.core.administrative.domain.ScheduledJobRun; import com.krishagni.catissueplus.core.administrative.services.ScheduledTask; import com.krishagni.catissueplus.core.biospecimen.ConfigParams; import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory; import com.krishagni.catissueplus.core.common.PlusTransactional; import com.krishagni.catissueplus.core.common.util.ConfigUtil; @Configurable public class StagedParticipantsCleanupTask implements ScheduledTask { private static final int DEF_CLEANUP_INT = 90; @Autowired private DaoFactory daoFactory; @Override @PlusTransactional public void doJob(ScheduledJobRun jobRun) throws Exception { int olderThanDays = ConfigUtil.getInstance().getIntSetting( ConfigParams.MODULE, ConfigParams.STAGED_PART_CLEANUP_INT, DEF_CLEANUP_INT); daoFactory.getStagedParticipantDao().cleanupOldParticipants(olderThanDays); } }
Raise NotImplementedError instead of just passing in AttributeObject That way, if somebody uses it directly, it will fail with a proper error.
class AttributeObject: def __init__(self, *excluded_keys): self._excluded_keys = excluded_keys def __getattr__(self, item): return self._getattr(item) def __setattr__(self, key, value): if key == "_excluded_keys" or key in self._excluded_keys: super().__setattr__(key, value) else: self._setattr(key, value) def _getattr(self, item): raise NotImplementedError() def _setattr(self, key, value): raise NotImplementedError() class DictionaryObject(AttributeObject): def __init__(self, initial_items={}): super().__init__("_dictionary") self._dictionary = dict(initial_items) def _getattr(self, item): return self._dictionary.get(item) def _setattr(self, key, value): self._dictionary[key] = value def _copy(self): return DictionaryObject(self._dictionary)
class AttributeObject: def __init__(self, *excluded_keys): self._excluded_keys = excluded_keys def __getattr__(self, item): return self._getattr(item) def __setattr__(self, key, value): if key == "_excluded_keys" or key in self._excluded_keys: super().__setattr__(key, value) else: self._setattr(key, value) def _getattr(self, item): pass def _setattr(self, key, value): pass class DictionaryObject(AttributeObject): def __init__(self, initial_items={}): super().__init__("_dictionary") self._dictionary = dict(initial_items) def _getattr(self, item): return self._dictionary.get(item) def _setattr(self, key, value): self._dictionary[key] = value def _copy(self): return DictionaryObject(self._dictionary)
Stop using deprecated list_dir in the examples. Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@gmail.com>
#!/usr/bin/python2 # This is a simple example program to show how to use PyCdlib to open up an # existing ISO passed on the command-line, and print out all of the file names # at the root of the ISO. # Import standard python modules. import sys # Import pycdlib itself. import pycdlib # Check that there are enough command-line arguments. if len(sys.argv) != 2: print("Usage: %s <iso>" % (sys.argv[0])) sys.exit(1) # Create a new PyCdlib object. iso = pycdlib.PyCdlib() # Open up a file object. This causes PyCdlib to parse all of the metadata on the # ISO, which is used for later manipulation. iso.open(sys.argv[1]) # Now iterate through each of the files on the root of the ISO, printing out # their names. for child in iso.list_children('/'): print(child.file_identifier()) # Close the ISO object. After this call, the PyCdlib object has forgotten # everything about the previous ISO, and can be re-used. iso.close()
#!/usr/bin/python2 # This is a simple example program to show how to use PyCdlib to open up an # existing ISO passed on the command-line, and print out all of the file names # at the root of the ISO. # Import standard python modules. import sys # Import pycdlib itself. import pycdlib # Check that there are enough command-line arguments. if len(sys.argv) != 2: print("Usage: %s <iso>" % (sys.argv[0])) sys.exit(1) # Create a new PyCdlib object. iso = pycdlib.PyCdlib() # Open up a file object. This causes PyCdlib to parse all of the metadata on the # ISO, which is used for later manipulation. iso.open(sys.argv[1]) # Now iterate through each of the files on the root of the ISO, printing out # their names. for child in iso.list_dir('/'): print(child.file_identifier()) # Close the ISO object. After this call, the PyCdlib object has forgotten # everything about the previous ISO, and can be re-used. iso.close()
Change treeData to be explicitly declared.
// Auto-magically referenced. Yay. $(document).ready(function() { var rubyFolders = gon.folders; var folders = {}; var currentId = gon.currentFolder.id; // Convert all the folders to tree nodes. rubyFolders.forEach(function(folder) { var nameAndCount = folder.name + " (" + folder.count + ")"; folders[folder.id] = { id: folder.id, label: nameAndCount, url: folder.url, parentId: folder.parent_folder_id, children: [] }; }); var rootFolder; // Generate the tree we need for jqTree. for (var id in folders) { var folder = folders[id]; var parentId = folder.parentId; if (!parentId) { rootFolder = folder; } else { folders[parentId].children.push(folder); } } var treeData = [rootFolder]; // Set up the tree. var treeElement = $('#file-tree'); treeElement.tree({ data: treeData, autoOpen: true }); // Select the folder we're currently in. var currentFolderNode = treeElement.tree('getNodeById', currentId); treeElement.tree('selectNode', currentFolderNode); // Set up bindings on the tree. treeElement.bind('tree.select', function(event) { var selectedNode = treeElement.tree('getSelectedNode'); var selectedFolderUrl = selectedNode.url; window.location.href = selectedFolderUrl; }); });
// Auto-magically referenced. Yay. $(document).ready(function() { var rubyFolders = gon.folders; var folders = {}; var currentId = gon.currentFolder.id; // Convert all the folders to tree nodes. rubyFolders.forEach(function(folder) { var nameAndCount = folder.name + " (" + folder.count + ")"; folders[folder.id] = { id: folder.id, label: nameAndCount, url: folder.url, parentId: folder.parent_folder_id, children: [] }; }); var treeData = []; var rootFolder; // Generate the tree we need for jqTree. for (var id in folders) { var folder = folders[id]; var parentId = folder.parentId; if (!parentId) { rootFolder = folder; } else { folders[parentId].children.push(folder); } } treeData.push(rootFolder); // Set up the tree. var treeElement = $('#file-tree'); treeElement.tree({ data: treeData, autoOpen: true }); // Select the folder we're currently in. var currentFolderNode = treeElement.tree('getNodeById', currentId); treeElement.tree('selectNode', currentFolderNode); // Set up bindings on the tree. treeElement.bind('tree.select', function(event) { var selectedNode = treeElement.tree('getSelectedNode'); var selectedFolderUrl = selectedNode.url; window.location.href = selectedFolderUrl; }); });
Fix model id to auto increment
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. # # Also note: You'll have to insert the output of 'django-admin sqlcustom [app_label]' # into your database. from __future__ import unicode_literals from django.db import models import django_pgjsonb class Feed(models.Model): id = models.AutoField(primary_key=True) article_id = models.BigIntegerField(unique=True) article_json = django_pgjsonb.JSONField() class Meta: db_table = 'feed' class Image(models.Model): id = models.AutoField(primary_key=True) article = models.ForeignKey(Feed, blank=True, null=True) url = models.TextField() nude_percent = models.IntegerField(blank=True, null=True) path = models.ImageField(null=True) class Meta: db_table = 'image' unique_together = (('url', 'article'),)
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. # # Also note: You'll have to insert the output of 'django-admin sqlcustom [app_label]' # into your database. from __future__ import unicode_literals from django.db import models import django_pgjsonb class Feed(models.Model): id = models.BigIntegerField(primary_key=True) article_id = models.BigIntegerField(unique=True) article_json = django_pgjsonb.JSONField() class Meta: db_table = 'feed' class Image(models.Model): article = models.ForeignKey(Feed, blank=True, null=True) url = models.TextField() nude_percent = models.IntegerField(blank=True, null=True) path = models.ImageField(null=True) class Meta: db_table = 'image' unique_together = (('url', 'article'),)
Add DirectoriesToChange field to sub.UpdateRequest message.
package sub import ( "github.com/Symantec/Dominator/lib/filesystem" "github.com/Symantec/Dominator/lib/hash" "github.com/Symantec/Dominator/lib/triggers" "github.com/Symantec/Dominator/proto/common" "github.com/Symantec/Dominator/sub/scanner" ) type Configuration struct { ScanSpeedPercent uint NetworkSpeedPercent uint ScanExclusionList []string } type FetchRequest struct { ServerAddress string Hashes []hash.Hash } type FetchResponse common.StatusResponse type GetConfigurationRequest struct { } type GetConfigurationResponse Configuration type PollRequest struct { HaveGeneration uint64 } type PollResponse struct { NetworkSpeed uint64 FetchInProgress bool // Fetch() and Update() are mutually exclusive. UpdateInProgress bool GenerationCount uint64 FileSystem *scanner.FileSystem } type SetConfigurationRequest Configuration type SetConfigurationResponse common.StatusResponse type Directory struct { Name string Mode filesystem.FileMode Uid uint32 Gid uint32 } type UpdateRequest struct { PathsToDelete []string DirectoriesToMake []Directory DirectoriesToChange []Directory Triggers *triggers.Triggers } type UpdateResponse struct{}
package sub import ( "github.com/Symantec/Dominator/lib/filesystem" "github.com/Symantec/Dominator/lib/hash" "github.com/Symantec/Dominator/lib/triggers" "github.com/Symantec/Dominator/proto/common" "github.com/Symantec/Dominator/sub/scanner" ) type Configuration struct { ScanSpeedPercent uint NetworkSpeedPercent uint ScanExclusionList []string } type FetchRequest struct { ServerAddress string Hashes []hash.Hash } type FetchResponse common.StatusResponse type GetConfigurationRequest struct { } type GetConfigurationResponse Configuration type PollRequest struct { HaveGeneration uint64 } type PollResponse struct { NetworkSpeed uint64 FetchInProgress bool // Fetch() and Update() are mutually exclusive. UpdateInProgress bool GenerationCount uint64 FileSystem *scanner.FileSystem } type SetConfigurationRequest Configuration type SetConfigurationResponse common.StatusResponse type Directory struct { Name string Mode filesystem.FileMode Uid uint32 Gid uint32 } type UpdateRequest struct { PathsToDelete []string DirectoriesToMake []Directory Triggers *triggers.Triggers } type UpdateResponse struct{}
Downgrade 'Failed to reconcile' from error to warning
from __future__ import absolute_import from celery import shared_task from django.core.exceptions import ValidationError from wellsfargo.connector import actions from wellsfargo.models import AccountMetadata import logging logger = logging.getLogger(__name__) @shared_task(bind=True, ignore_result=True) def reconcile_accounts(self): for m in AccountMetadata.objects.order_by('account_id').all(): account = m.account logger.info('Reconciling account %s' % account) try: resp = actions.submit_inquiry(account) resp.reconcile() except ValidationError as e: logging.warning('Failed to reconcile account %s due to ValidationError[%s]' % (account, e.message))
from __future__ import absolute_import from celery import shared_task from django.core.exceptions import ValidationError from wellsfargo.connector import actions from wellsfargo.models import AccountMetadata import logging logger = logging.getLogger(__name__) @shared_task(bind=True, ignore_result=True) def reconcile_accounts(self): for m in AccountMetadata.objects.order_by('account_id').all(): account = m.account logger.info('Reconciling account %s' % account) try: resp = actions.submit_inquiry(account) resp.reconcile() except ValidationError as e: logging.error('Failed to reconcile account %s due to ValidationError[%s]' % (account, e.message))
Fix typo in prop name
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; class CandidateMatchCategory extends Component { render() { return ( <div className="candidate-match-category"> <div className="match-rate"> {this.props.matchRate} </div> <div className="category-name"> {this.props.categoryName} </div> </div> ); } } CandidateMatchCategory.propTypes = { matchRate: PropTypes.number, categoryName: PropTypes.string }; export default CandidateMatchCategory;
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; class CandidateMatchCategory extends Component { render() { return ( <div className="candidate-match-category"> <div className="match-rate"> {this.props.matchRate} </div> <div className="category-name"> {this.props.categoryName} </div> </div> ); } } CandidateMatchCategory.propTypes = { matchRate: PropTypes.number, category: PropTypes.string }; export default CandidateMatchCategory;
Change to fireteam email address.
# -*- coding: utf-8 -*- import os from setuptools import setup from setuptools.dist import Distribution with open(os.path.join(os.path.dirname(__file__), 'README')) as f: doc = f.read() class BinaryDistribution(Distribution): def is_pure(self): return False setup( name='json-stream', version='1.0.1', url='http://fireteam.net/', license='BSD', author='Fireteam Ltd.', author_email='info@fireteam.net', description='A small wrapper around YAJL\'s lexer', long_description=doc, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ], packages=['jsonstream'], include_package_data=True, distclass=BinaryDistribution, )
# -*- coding: utf-8 -*- import os from setuptools import setup from setuptools.dist import Distribution with open(os.path.join(os.path.dirname(__file__), 'README')) as f: doc = f.read() class BinaryDistribution(Distribution): def is_pure(self): return False setup( name='json-stream', version='1.0.1', url='http://fireteam.net/', license='BSD', author='Fireteam Ltd.', author_email='armin@fireteam.net', description='A small wrapper around YAJL\'s lexer', long_description=doc, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ], packages=['jsonstream'], include_package_data=True, distclass=BinaryDistribution, )
Use wraps decorator for requires_nltk_corpus
# -*- coding: utf-8 -*- '''Custom decorators.''' from __future__ import absolute_import from functools import wraps from textblob.exceptions import MissingCorpusException class cached_property(object): '''A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. Credit to Marcel Hellkamp, author of bottle.py. ''' def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value def requires_nltk_corpus(func): '''Wraps a function that requires an NLTK corpus. If the corpus isn't found, raise a MissingCorpusException. ''' @wraps(func) def decorated(*args, **kwargs): try: return func(*args, **kwargs) except LookupError as err: print(err) raise MissingCorpusException() return decorated
# -*- coding: utf-8 -*- '''Custom decorators.''' from __future__ import absolute_import from textblob.exceptions import MissingCorpusException class cached_property(object): '''A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. Credit to Marcel Hellkamp, author of bottle.py. ''' def __init__(self, func): self.__doc__ = getattr(func, '__doc__') self.func = func def __get__(self, obj, cls): if obj is None: return self value = obj.__dict__[self.func.__name__] = self.func(obj) return value def requires_nltk_corpus(func): '''Wraps a function that requires an NLTK corpus. If the corpus isn't found, raise a MissingCorpusException. ''' def decorated(*args, **kwargs): try: return func(*args, **kwargs) except LookupError as err: print(err) raise MissingCorpusException() return decorated
Update the mpl rcparams for mpl 2.0+
def setup_text_plots(fontsize=8, usetex=True): """ This function adjusts matplotlib settings so that all figures in the textbook have a uniform format and look. """ import matplotlib from distutils.version import LooseVersion matplotlib.rc('legend', fontsize=fontsize, handlelength=3) matplotlib.rc('axes', titlesize=fontsize) matplotlib.rc('axes', labelsize=fontsize) matplotlib.rc('xtick', labelsize=fontsize) matplotlib.rc('ytick', labelsize=fontsize) matplotlib.rc('text', usetex=usetex) matplotlib.rc('font', size=fontsize, family='serif', style='normal', variant='normal', stretch='normal', weight='normal') matplotlib.rc('patch', force_edgecolor=True) if LooseVersion(matplotlib.__version__) < LooseVersion("3.1"): matplotlib.rc('_internal', classic_mode=True) else: # New in mpl 3.1 matplotlib.rc('scatter.edgecolors', 'b') matplotlib.rc('grid', linestyle=':')
def setup_text_plots(fontsize=8, usetex=True): """ This function adjusts matplotlib settings so that all figures in the textbook have a uniform format and look. """ import matplotlib matplotlib.rc('legend', fontsize=fontsize, handlelength=3) matplotlib.rc('axes', titlesize=fontsize) matplotlib.rc('axes', labelsize=fontsize) matplotlib.rc('xtick', labelsize=fontsize) matplotlib.rc('ytick', labelsize=fontsize) matplotlib.rc('text', usetex=usetex) matplotlib.rc('font', size=fontsize, family='serif', style='normal', variant='normal', stretch='normal', weight='normal')
Add new action : fetchData
import "babel-polyfill" import React from 'react' import ReactDOM from 'react-dom' import { createStore, applyMiddleware } from 'redux' import createSagaMiddleware from 'redux-saga' import Counter from './Counter' import reducer from './reducers' import rootSaga from './sagas' const sagaMiddleware = createSagaMiddleware() const store = createStore( reducer, applyMiddleware(sagaMiddleware) ) sagaMiddleware.run(rootSaga) import { helloSaga } from './sagas' sagaMiddleware.run(helloSaga); const action = type => store.dispatch({type}) import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import MyAwesomeReactComponent from './MyAwesomeReactComponent'; const App = () => ( <MuiThemeProvider> <MyAwesomeReactComponent /> </MuiThemeProvider> ); function render() { ReactDOM.render( //<App />, <Counter value={store.getState()} onIncrement={() => action('INCREMENT')} onDecrement={() => action('DECREMENT')} onIncrementAsync={() => action('INCREMENT_ASYNC')} onFetchData={() => action('FETCHDATA')} />, document.getElementById('root') ) } render() store.subscribe(render)
import "babel-polyfill" import React from 'react' import ReactDOM from 'react-dom' import { createStore, applyMiddleware } from 'redux' import createSagaMiddleware from 'redux-saga' import Counter from './Counter' import reducer from './reducers' import rootSaga from './sagas' const sagaMiddleware = createSagaMiddleware() const store = createStore( reducer, applyMiddleware(sagaMiddleware) ) sagaMiddleware.run(rootSaga) import { helloSaga } from './sagas' sagaMiddleware.run(helloSaga); const action = type => store.dispatch({type}) import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import MyAwesomeReactComponent from './MyAwesomeReactComponent'; const App = () => ( <MuiThemeProvider> <MyAwesomeReactComponent /> </MuiThemeProvider> ); function render() { ReactDOM.render( <App />, /* <Counter value={store.getState()} onIncrement={() => action('INCREMENT')} onDecrement={() => action('DECREMENT')} onIncrementAsync={() => action('INCREMENT_ASYNC')}/>, */ document.getElementById('root') ) } render() store.subscribe(render)
Refactor code and added new comments
/*Author: Peter Chow * * * SudokuCapture will capture images from a webcam, * using still image capture from the video, another thread will approximate the bounds of the board * and try to scan in the values of the board for the program to use. * After a successful scan, the program will solve the board and display the answer using an overlay over the camera view * * */ public class SudokuCapture { public static void main (String args[]){ init(); CaptureWebcam webcam = new CaptureWebcam(); webcam.display(); } //Load up OpenCV lib by checking if the machine is 64-bit or 32-bit private static void init() { System.out.println("starting webcam capture"); String answer = System.getProperty("sun.arch.data.model"); if(answer.matches("64")) { System.loadLibrary("./build/x64/opencv_java300"); } else if(answer.matches("32")) { System.loadLibrary("./build/x86/opencv_java300"); } else { System.err.println("Your platform is not comptable"); System.exit(0); } } }
import javax.swing.JFrame; /*Author: Peter Chow * * * SudokuCapture will capture images from a webcam, * using still image capture from the video, another thread will approximate the bounds of the board * and try to scan in the values of the board for the program to use. * After a successful scan, the program will solve the board and display the answer using an overlay over the camera view * * */ public class SudokuCapture { public static void main (String args[]){ init(); CaptureWebcam webcam = new CaptureWebcam(); webcam.display(); } private static void init() { System.out.println("start"); String answer = System.getProperty("sun.arch.data.model"); if(answer.matches("64")){ System.loadLibrary("./build/x64/opencv_java300"); }else if(answer.matches("32")){ System.loadLibrary("./build/x86/opencv_java300"); }else{ System.err.println("Your platform is not comptable"); System.exit(0); } } }
Modify db client to __new__ change db singlton from instance() staticmethod to __new__()
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2012 Ethan Zhang<http://github.com/Ethan-Zhang> # # 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. from tornado.options import define, options import tornadoasyncmemcache define("db_addr_list", type=list, default=['192.168.0.176:19803']) class MemcachedClient(object): def __new__(cls): if not hasattr(cls, '_instance'): cls._instance = \ tornadoasyncmemcache.ClientPool(options.db_addr_list, maxclients=100) return cls._instance def get_memcached(key, callback): MemcachedClient.instance().get(key, callback=callback)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2012 Ethan Zhang<http://github.com/Ethan-Zhang> # # 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. from tornado.options import define, options import tornadoasyncmemcache define("db_addr_list", type=list, default=['192.168.0.176:19803']) class MemcachedClient(object): @staticmethod def instance(): if not hasattr(MemcachedClient, "_instance"): MemcachedClient._instance = \ tornadoasyncmemcache.ClientPool(options.db_addr_list, maxclients=100) return MemcachedClient._instance def get(key, callback): MemcachedClient.instance().get(key, callback=callback)
Fix CI for node 6 Summary: This file is executed without transforms so we can't have trailing commas in function calls until we drop node 6. Closes https://github.com/facebook/relay/pull/2424 Differential Revision: D7754622 Pulled By: kassens fbshipit-source-id: a3a54348cc4890616304c9ed5a739d4a92a9e305
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @noformat */ 'use strict'; module.exports = function(options) { options = Object.assign( { env: 'production', moduleMap: {}, plugins: [], }, options ); const fbjsPreset = require('babel-preset-fbjs/configure')({ autoImport: options.autoImport || false, objectAssign: false, inlineRequires: true, stripDEV: options.env === 'production', }); // The module rewrite transform needs to be positioned relative to fbjs's // many other transforms. fbjsPreset.presets[0].plugins.push([ require('./rewrite-modules'), { map: Object.assign({}, require('fbjs/module-map'), options.moduleMap), }, ]); if (options.postPlugins) { fbjsPreset.presets.push({ plugins: options.postPlugins, }); } return { plugins: options.plugins.concat('transform-es2015-spread'), presets: [fbjsPreset], }; };
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ 'use strict'; module.exports = function(options) { options = Object.assign( { env: 'production', moduleMap: {}, plugins: [], }, options, ); const fbjsPreset = require('babel-preset-fbjs/configure')({ autoImport: options.autoImport || false, objectAssign: false, inlineRequires: true, stripDEV: options.env === 'production', }); // The module rewrite transform needs to be positioned relative to fbjs's // many other transforms. fbjsPreset.presets[0].plugins.push([ require('./rewrite-modules'), { map: Object.assign({}, require('fbjs/module-map'), options.moduleMap), }, ]); if (options.postPlugins) { fbjsPreset.presets.push({ plugins: options.postPlugins, }); } return { plugins: options.plugins.concat('transform-es2015-spread'), presets: [fbjsPreset], }; };
Remove duplicated db_object_type=protein from the test value for annotation properties.
package uk.ac.ebi.quickgo.index.annotation; /** * A class for creating stubbed annotations, representing rows of data read from * annotation source files. * * Created 22/04/16 * @author Edd */ public class AnnotationMocker { public static Annotation createValidAnnotation() { Annotation annotation = new Annotation(); annotation.db = "IntAct"; annotation.dbObjectId = "EBI-10043081"; annotation.dbReferences = "PMID:12871976"; annotation.qualifier = "enables"; annotation.goId = "GO:0000977"; annotation.interactingTaxonId = "taxon:12345"; annotation.evidenceCode = "ECO:0000353"; annotation.with = "GO:0036376,GO:1990573"; annotation.assignedBy = "IntAct"; annotation.annotationExtension = "occurs_in(CL:1000428)"; annotation.annotationProperties = "go_evidence=IEA|taxon_id=35758|db_subset=TrEMBL|db_object_symbol=moeA5|db_object_type=protein" + "|target_set=BHF-UCL,Exosome,KRUK|taxon_lineage=1,2,3,4"; return annotation; } }
package uk.ac.ebi.quickgo.index.annotation; /** * A class for creating stubbed annotations, representing rows of data read from * annotation source files. * * Created 22/04/16 * @author Edd */ public class AnnotationMocker { public static Annotation createValidAnnotation() { Annotation annotation = new Annotation(); annotation.db = "IntAct"; annotation.dbObjectId = "EBI-10043081"; annotation.dbReferences = "PMID:12871976"; annotation.qualifier = "enables"; annotation.goId = "GO:0000977"; annotation.interactingTaxonId = "taxon:12345"; annotation.evidenceCode = "ECO:0000353"; annotation.with = "GO:0036376,GO:1990573"; annotation.assignedBy = "IntAct"; annotation.annotationExtension = "occurs_in(CL:1000428)"; annotation.annotationProperties = "go_evidence=IEA|taxon_id=35758|db_subset=TrEMBL|db_object_symbol=moeA5|db_object_type=protein|db_object_type=protein|target_set=BHF-UCL,Exosome,KRUK|taxon_lineage=1,2,3,4"; return annotation; } }
Add amount to payment at creation
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\CoreBundle\OrderProcessing; use Sylius\Bundle\CoreBundle\Model\OrderInterface; use Sylius\Bundle\ResourceBundle\Model\RepositoryInterface; /** * Payment processor. * * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ class PaymentProcessor implements PaymentProcessorInterface { /** * Payment repository. * * @var RepositoryInterface */ protected $paymentRepository; /** * Constructor. * * @param RepositoryInterface $paymentRepository */ public function __construct(RepositoryInterface $paymentRepository) { $this->paymentRepository = $paymentRepository; } /** * {@inheritdoc} */ public function createPayment(OrderInterface $order) { $payment = $this->paymentRepository->createNew(); $payment->setCurrency($order->getCurrency()); $payment->setAmount($order->getTotal()); $order->setPayment($payment); return $payment; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\CoreBundle\OrderProcessing; use Sylius\Bundle\CoreBundle\Model\OrderInterface; use Sylius\Bundle\ResourceBundle\Model\RepositoryInterface; /** * Payment processor. * * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ class PaymentProcessor implements PaymentProcessorInterface { /** * Payment repository. * * @var RepositoryInterface */ protected $paymentRepository; /** * Constructor. * * @param RepositoryInterface $paymentRepository */ public function __construct(RepositoryInterface $paymentRepository) { $this->paymentRepository = $paymentRepository; } /** * {@inheritdoc} */ public function createPayment(OrderInterface $order) { $payment = $this->paymentRepository->createNew(); $payment->setCurrency($order->getCurrency()); $order->setPayment($payment); return $payment; } }
Add the missing docs for the parameter.
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.query; import com.google.errorprone.annotations.Immutable; import java.util.function.UnaryOperator; /** * A lambda serving to fill the current predicate {@linkplain QueryBuilder query builders} * with the parameters joined in {@linkplain LogicalOperator#OR disjunction}. * * @param <B> the type of the query builder */ @Immutable @FunctionalInterface public interface Either<B extends QueryBuilder<?, ?, ?, ?, ?>> extends UnaryOperator<B> { }
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.query; import com.google.errorprone.annotations.Immutable; import java.util.function.UnaryOperator; /** * A lambda serving to fill the current predicate {@linkplain QueryBuilder query builders} * with the parameters joined in {@linkplain LogicalOperator#OR disjunction}. */ @Immutable @FunctionalInterface public interface Either<B extends QueryBuilder<?, ?, ?, ?, ?>> extends UnaryOperator<B> { }
Move init_app after DJANGO_SETTINGS_MODULE set up
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings') from django.core.management import execute_from_command_line from website.app import init_app init_app(set_backends=True, routes=False, attach_request_handlers=False) if 'livereload' in sys.argv: from django.core.wsgi import get_wsgi_application from livereload import Server import django.conf as conf conf.settings.STATIC_URL = '/static/' application = get_wsgi_application() server = Server(application) server.watch('api/') server.serve(port=8000) else: execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys from website.app import init_app if __name__ == "__main__": os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.base.settings') from django.core.management import execute_from_command_line init_app(set_backends=True, routes=False, attach_request_handlers=False) if 'livereload' in sys.argv: from django.core.wsgi import get_wsgi_application from livereload import Server import django.conf as conf conf.settings.STATIC_URL = '/static/' application = get_wsgi_application() server = Server(application) server.watch('api/') server.serve(port=8000) else: execute_from_command_line(sys.argv)
Remove unnecessary else from formatAmount() method.
<?php namespace Laravel\Cashier; class Cashier { /** * The custom currency formatter. * * @var callable */ protected static $formatCurrencyUsing; /** * Set the custom currency formatter. * * @param callable $callback * @return void */ public static function formatCurrencyUsing(callable $callback) { static::$formatCurrencyUsing = $callback; } /** * Format the given amount into a displayable currency. * * @param int $amount * @return string */ public static function formatAmount($amount) { if (static::$formatCurrencyUsing) { return call_user_func(static::$formatCurrencyUsing, $amount); } $amount = number_format($amount / 100, 2); if (starts_with($amount, '-')) { return '-$'.ltrim($amount, '-'); } return '$'.$amount; } }
<?php namespace Laravel\Cashier; class Cashier { /** * The custom currency formatter. * * @var callable */ protected static $formatCurrencyUsing; /** * Set the custom currency formatter. * * @param callable $callback * @return void */ public static function formatCurrencyUsing(callable $callback) { static::$formatCurrencyUsing = $callback; } /** * Format the given amount into a displayable currency. * * @param int $amount * @return string */ public static function formatAmount($amount) { if (static::$formatCurrencyUsing) { return call_user_func(static::$formatCurrencyUsing, $amount); } $amount = number_format($amount / 100, 2); if (starts_with($amount, '-')) { return '-$'.ltrim($amount, '-'); } else { return '$'.$amount; } } }
[template] Change bare template to use function component
import * as React from 'react'; import { Platform, StyleSheet, Text, View } from 'react-native'; const instructions = Platform.select({ ios: `Press Cmd+R to reload,\nCmd+D or shake for dev menu`, android: `Double tap R on your keyboard to reload,\nShake or press menu button for dev menu`, }); export default function App() { return ( <View style={styles.container}> <Text style={styles.welcome}>Welcome to React Native!</Text> <Text style={styles.instructions}>To get started, edit App.js</Text> <Text style={styles.instructions}>{instructions}</Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View } from 'react-native'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', }); export default class App extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}>Welcome to React Native!</Text> <Text style={styles.instructions}>To get started, edit App.js</Text> <Text style={styles.instructions}>{instructions}</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
Remove old and uneeded test dependencies
#!/usr/bin/env python from setuptools import setup __about__ = {} with open("nacl/__about__.py") as fp: exec(fp.read(), None, __about__) try: import nacl.nacl except ImportError: # installing - there is no cffi yet ext_modules = [] else: # building bdist - cffi is here! ext_modules = [nacl.nacl.ffi.verifier.get_extension()] setup( name=__about__["__title__"], version=__about__["__version__"], description=__about__["__summary__"], long_description=open("README.rst").read(), url=__about__["__uri__"], license=__about__["__license__"], author=__about__["__author__"], author_email=__about__["__email__"], install_requires=[ "cffi", ], extras_require={ "tests": ["pytest"], }, tests_require=["pytest"], packages=[ "nacl", ], ext_package="nacl", ext_modules=ext_modules, zip_safe=False, )
#!/usr/bin/env python from setuptools import setup __about__ = {} with open("nacl/__about__.py") as fp: exec(fp.read(), None, __about__) try: import nacl.nacl except ImportError: # installing - there is no cffi yet ext_modules = [] else: # building bdist - cffi is here! ext_modules = [nacl.nacl.ffi.verifier.get_extension()] setup( name=__about__["__title__"], version=__about__["__version__"], description=__about__["__summary__"], long_description=open("README.rst").read(), url=__about__["__uri__"], license=__about__["__license__"], author=__about__["__author__"], author_email=__about__["__email__"], install_requires=[ "cffi", ], extras_require={ "tests": [ "pep8", "pylint", "pytest", ], }, tests_require=[ "pytest", ], packages=[ "nacl", ], ext_package="nacl", ext_modules=ext_modules, zip_safe=False, )
Add more fields to Release serializer.
from rest_framework import serializers from .models import Release, Track, Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'comment') class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'release') class ReleaseSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedIdentityField(view_name='release-tracks') comments = serializers.HyperlinkedIdentityField(view_name='release-comments') class Meta: model = Release fields = ('id', 'arrivaldate', 'artist', 'title', 'year','company','genre','format', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments')
from rest_framework import serializers from .models import Release, Track, Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'comment') class TrackSerializer(serializers.ModelSerializer): cdid = serializers.StringRelatedField( read_only=True ) class Meta: model = Track fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'cdid') class ReleaseSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedIdentityField(view_name='release-tracks') comments = serializers.HyperlinkedIdentityField(view_name='release-comments') class Meta: model = Release fields = ('id', 'arrivaldate', 'artist', 'title', 'year', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments')
Remove lat/long from zika download
import os,datetime from download import download from download import get_parser class zika_download(download): def __init__(self, **kwargs): download.__init__(self, **kwargs) if __name__=="__main__": parser = get_parser() args = parser.parse_args() fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'source', 'locus', 'authors'] args.fasta_fields = fasta_fields current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d')) if args.fstem is None: args.fstem = args.virus + '_' + current_date if not os.path.isdir(args.path): os.makedirs(args.path) connfluVDB = zika_download(**args.__dict__) connfluVDB.download(**args.__dict__)
import os,datetime from download import download from download import get_parser class zika_download(download): def __init__(self, **kwargs): download.__init__(self, **kwargs) if __name__=="__main__": parser = get_parser() args = parser.parse_args() fasta_fields = ['strain', 'virus', 'accession', 'collection_date', 'region', 'country', 'division', 'location', 'source', 'locus', 'authors', 'latitude', 'longitude'] args.fasta_fields = fasta_fields current_date = str(datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d')) if args.fstem is None: args.fstem = args.virus + '_' + current_date if not os.path.isdir(args.path): os.makedirs(args.path) connfluVDB = zika_download(**args.__dict__) connfluVDB.download(**args.__dict__)
Remove line breaks from method signatures
package heroku.template.controller; import heroku.template.model.Person; import heroku.template.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.Map; @Controller public class PersonController { @Autowired private PersonService personService; @RequestMapping("/") public String listPeople(Map<String, Object> map) { map.put("person", new Person()); map.put("peopleList", personService.listPeople()); return "people"; } @RequestMapping(value = "/add", method = RequestMethod.POST) public String addPerson(@ModelAttribute("person") Person person, BindingResult result) { personService.addPerson(person); return "redirect:/people/"; } @RequestMapping("/delete/{personId}") public String deletePerson(@PathVariable("personId") Integer personId) { personService.removePerson(personId); return "redirect:/people/"; } }
package heroku.template.controller; import heroku.template.model.Person; import heroku.template.service.PersonService; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class PersonController { @Autowired private PersonService personService; @RequestMapping("/") public String listPeople(Map<String, Object> map) { map.put("person", new Person()); map.put("peopleList", personService.listPeople()); return "people"; } @RequestMapping(value = "/add", method = RequestMethod.POST) public String addPerson(@ModelAttribute("person") Person person, BindingResult result) { personService.addPerson(person); return "redirect:/people/"; } @RequestMapping("/delete/{personId}") public String deletePerson(@PathVariable("personId") Integer personId) { personService.removePerson(personId); return "redirect:/people/"; } }
Use insert_text instead of changed
#!/usr/bin/env python import gtk from kiwi.controllers import BaseController from kiwi.ui.views import BaseView from kiwi.ui.gadgets import quit_if_last class FarenControl(BaseController): def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__insert_text(self, entry, *args): try: temp = float(entry.get_text()) except ValueError: temp = 0 celsius = (temp - 32) * 5/9.0 farenheit = (temp * 9/5.0) + 32 self.view.celsius.set_text("%.2f" % celsius) self.view.farenheit.set_text("%.2f" % farenheit) widgets = ["quitbutton", "temperature", "celsius", "farenheit"] view = BaseView(gladefile="faren", delete_handler=quit_if_last, widgets=widgets) ctl = FarenControl(view) view.show() gtk.main()
#!/usr/bin/env python import gtk from kiwi.controllers import BaseController from kiwi.ui.views import BaseView from kiwi.ui.gadgets import quit_if_last class FarenControl(BaseController): def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__changed(self, entry, *args): try: temp = float(entry.get_text()) except ValueError: temp = 0 celsius = (temp - 32) * 5/9.0 farenheit = (temp * 9/5.0) + 32 self.view.celsius.set_text("%.2f" % celsius) self.view.farenheit.set_text("%.2f" % farenheit) widgets = ["quitbutton", "temperature", "celsius", "farenheit"] view = BaseView(gladefile="faren", delete_handler=quit_if_last, widgets=widgets) ctl = FarenControl(view) view.show() gtk.main()
Allow null being passed to fromXML
<?php declare(strict_types=1); namespace SAML2\XML; use DOMElement; /** * Abstract class to be implemented by all the classes in this namespace * * @author Tim van Dijen, <tvdijen@gmail.com> * @package SimpleSAMLphp */ abstract class AbstractConvertable { /** * Output the class as an XML-formatted string * * @return string */ public function __toString(): string { $xml = $this->toXML(); return $xml->ownerDocument->saveXML($xml); } /** * Create XML from this class * * @param \DOMElement|null $parent * @return \DOMElement */ abstract public function toXML(DOMElement $parent = null): DOMElement; /** * Create a class from XML * * @param \DOMElement|null $xml * @return self|null */ abstract public static function fromXML(?DOMElement $xml): ?object; }
<?php declare(strict_types=1); namespace SAML2\XML; use DOMElement; /** * Abstract class to be implemented by all the classes in this namespace * * @author Tim van Dijen, <tvdijen@gmail.com> * @package SimpleSAMLphp */ abstract class AbstractConvertable { /** * Output the class as an XML-formatted string * * @return string */ public function __toString(): string { $xml = $this->toXML(); return $xml->ownerDocument->saveXML($xml); } /** * Create XML from this class * * @param \DOMElement|null $parent * @return \DOMElement */ abstract public function toXML(DOMElement $parent = null): DOMElement; /** * Create a class from XML * * @param \DOMElement $xml * @return self */ abstract public static function fromXML(DOMElement $xml): object; }
Fix missing @api (see comment of Joachim Van der Auwera on GBE-247)
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.configuration.client; import java.io.Serializable; import org.geomajas.annotation.Api; /** * Enumeration class for the available options to limit (e.g. the mapview's) bounds when applying * the maxBounds limitation. * * @author An Buyle * * @since 1.10.0 */ @Api public enum BoundsLimitOption implements Serializable { /** * View center must be within maxBounds. */ CENTER_WITHIN_MAX_BOUNDS, /** * The whole map view must lay completely within the maximum allowed bounds (maxBounds). */ COMPLETELY_WITHIN_MAX_BOUNDS; private static final long serialVersionUID = 1100L; }
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.configuration.client; import java.io.Serializable; /** * Enumeration class for the available options to limit (e.g. the mapview's) bounds when applying * the maxBounds limitation. * * @author An Buyle * * @since 1.10.0 */ public enum BoundsLimitOption implements Serializable { /** * View center must be within maxBounds. */ CENTER_WITHIN_MAX_BOUNDS, /** * The whole map view must lay completely within the maximum allowed bounds (maxBounds). */ COMPLETELY_WITHIN_MAX_BOUNDS; private static final long serialVersionUID = 1100L; }
Update parallel convergence test runs to not spawn OMP threads
import os import time import multiprocessing threads = 4 os.environ["OMP_NUM_THREADS"] = "1" dev_null = "/dev/null" input_dir = "./convergence_inputs/" log_file = "log.log" call = "nice -n 19 ionice -c2 -n7 ../build/main.x " call_end = " >> " + log_file syscall_arr = [] input_files = os.listdir(input_dir) if __name__ == "__main__": pool = multiprocessing.Pool(processes=threads) for fname in input_files: inp_path = input_dir + fname syscall = call + inp_path + call_end syscall_arr.append(syscall) if log_file is not dev_null: try: os.remove(log_file) except: pass start_time = time.time() pool.map(os.system, syscall_arr) pool.close() pool.join() end_time = time.time() print("Runtime: ", end_time-start_time)
import os import time import multiprocessing threads = 4 dev_null = "/dev/null" input_dir = "./convergence_inputs/" log_file = dev_null call = "nice -n 19 ionice -c2 -n7 ../build/main.x " call_end = " >> " + log_file syscall_arr = [] input_files = os.listdir(input_dir) if __name__ == "__main__": pool = multiprocessing.Pool(processes=threads) for fname in input_files: inp_path = input_dir + fname syscall = call + inp_path + call_end syscall_arr.append(syscall) if log_file is not dev_null: os.remove(log_file) start_time = time.time() pool.map(os.system, syscall_arr) pool.close() pool.join() end_time = time.time() print("Runtime: ", end_time-start_time)
Trim whitespace from url input
if (Meteor.isClient) { // This code only runs on the client Template.body.helpers({ giblets: [ { text: "This is task 1" }, { text: "This is task 2" }, { text: "This is task 3" } ] }); // This code only runs on the client Template.body.helpers({ giblets: function () { return Giblets.find({}); } }); Template.addGiblet.events({ "submit .addGiblet": function (event) { event.preventDefault(); // // Get values from form var taskname = event.target.taskname.value; var url = event.target.url.value.trim(); var keywords = event.target.keywords.value.split(', '); var SMS = event.target.SMS.checked; var email = event.target.email.checked; var frequency = event.target.frequency.value; var giblet = { taskname: taskname, url: url, keywords: keywords, SMS: SMS, email: email, frequency: frequency }; Meteor.call('addGiblet', giblet); } }); Accounts.ui.config({ passwordSignupFields: 'USERNAME_ONLY', }); }
if (Meteor.isClient) { // This code only runs on the client Template.body.helpers({ giblets: [ { text: "This is task 1" }, { text: "This is task 2" }, { text: "This is task 3" } ] }); // This code only runs on the client Template.body.helpers({ giblets: function () { return Giblets.find({}); } }); Template.addGiblet.events({ "submit .addGiblet": function (event) { event.preventDefault(); // // Get values from form var taskname = event.target.taskname.value; var url = event.target.url.value; var keywords = event.target.keywords.value.split(', '); var SMS = event.target.SMS.checked; var email = event.target.email.checked; var frequency = event.target.frequency.value; var giblet = { taskname: taskname, url: url, keywords: keywords, SMS: SMS, email: email, frequency: frequency }; Meteor.call('addGiblet', giblet); } }); Accounts.ui.config({ passwordSignupFields: 'USERNAME_ONLY', }); }
Set up continuous integration script
/*global desc, task, jake, fail, complete */ (function() { "use strict"; desc("Build and test"); task("default", ["lint"]); desc("Lint everything"); task("lint", [], function() { var lint = require("./build/lint/lint_runner.js"); var files = new jake.FileList(); files.include("**/*.js"); files.exclude("node_modules"); var options = nodeLintOptions(); lint.validateFileList(files.toArray(), options, {}); }); desc("Integrate"); task("integrate", ["default"], function() { console.log("1. Make sure 'git status' is clean."); console.log("2. Build on the integration box."); console.log(" a. Walk over to integration box."); console.log(" b. 'git pull'"); console.log(" c. 'jake'"); console.log("3. 'git checkout integration'"); console.log("4. 'git merge master --no-ff --log'"); console.log("5. 'git checkout master'"); }); function nodeLintOptions() { return { bitwise:true, curly:false, eqeqeq:true, forin:true, immed:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, regexp:true, undef:true, strict:true, trailing:true, node:true }; } }());
/*global desc, task, jake, fail, complete */ (function() { "use strict"; task("default", ["lint"]); desc("Lint everything"); task("lint", [], function() { var lint = require("./build/lint/lint_runner.js"); var files = new jake.FileList(); files.include("**/*.js"); files.exclude("node_modules"); var options = nodeLintOptions(); lint.validateFileList(files.toArray(), options, {}); }); function nodeLintOptions() { return { bitwise:true, curly:false, eqeqeq:true, forin:true, immed:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, regexp:true, undef:true, strict:true, trailing:true, node:true }; } }());
Set min requirement for tornado-botocore
# coding: utf-8 from setuptools import setup, find_packages setup( name='tc_aws', version='6.0.5', description='Thumbor AWS extensions', author='Thumbor-Community & William King', author_email='willtrking@gmail.com', zip_safe=False, include_package_data=True, packages=find_packages(), install_requires=[ 'python-dateutil', 'thumbor>=6.0.0,<7', 'tornado-botocore>=1.3.1', ], extras_require={ 'tests': [ 'pyvows', 'coverage', 'tornado_pyvows', 'boto', 'moto', 'mock', ], }, )
# coding: utf-8 from setuptools import setup, find_packages setup( name='tc_aws', version='6.0.5', description='Thumbor AWS extensions', author='Thumbor-Community & William King', author_email='willtrking@gmail.com', zip_safe=False, include_package_data=True, packages=find_packages(), install_requires=[ 'python-dateutil', 'thumbor>=6.0.0,<7', 'tornado-botocore', ], extras_require={ 'tests': [ 'pyvows', 'coverage', 'tornado_pyvows', 'boto', 'moto', 'mock', ], }, )
Remove .md extension from CONTRIBUTING file
/* * grunt-contrib-internal * http://gruntjs.com/ * * Copyright (c) 2012 Tyler Kellen, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Add custom template delimiters. grunt.template.addDelimiters('build-cfpb', '{%', '%}'); grunt.registerTask('build-cfpb', 'Generate CFPB README', function() { var path = require('path'), fs = require('fs'), asset = path.join.bind(null, __dirname, 'assets'), meta = grunt.file.readJSON('package.json'); meta.changelog = grunt.file.readYAML('CHANGELOG'); meta.license = grunt.file.read('LICENSE'); grunt.file.expand('docs/*.md').forEach( function(filepath) { var filename = path.basename( filepath, '.md' ); meta.docs[filename] = grunt.file.read( filepath ); }); // Generate readme. var tmpl = grunt.file.read( asset('README.tmpl.md') ), appendix = grunt.template.process( tmpl, {data: meta, delimiters: 'build-cfpb'} ), readme = grunt.file.exists('README.md') ? grunt.file.read('README.md') : ''; grunt.file.write( 'README.md', readme + appendix ); grunt.log.ok('Created README.md'); // Fail task if any errors were logged. if ( this.errorCount > 0 ) { return false; } }); };
/* * grunt-contrib-internal * http://gruntjs.com/ * * Copyright (c) 2012 Tyler Kellen, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Add custom template delimiters. grunt.template.addDelimiters('build-cfpb', '{%', '%}'); grunt.registerTask('build-cfpb', 'Generate CFPB README', function() { var path = require('path'), fs = require('fs'), asset = path.join.bind(null, __dirname, 'assets'), meta = grunt.file.readJSON('package.json'); meta.changelog = grunt.file.readYAML('CHANGELOG.md'); meta.license = grunt.file.read('LICENSE'); grunt.file.expand('docs/*.md').forEach( function(filepath) { var filename = path.basename( filepath, '.md' ); meta.docs[filename] = grunt.file.read( filepath ); }); // Generate readme. var tmpl = grunt.file.read( asset('README.tmpl.md') ), appendix = grunt.template.process( tmpl, {data: meta, delimiters: 'build-cfpb'} ), readme = grunt.file.exists('README.md') ? grunt.file.read('README.md') : ''; grunt.file.write( 'README.md', readme + appendix ); grunt.log.ok('Created README.md'); // Fail task if any errors were logged. if ( this.errorCount > 0 ) { return false; } }); };
Remove extra view from safeImage component
import React from 'react' import { ImageBackground, ActivityIndicator, View } from 'react-native' import css from '../../styles/css' class SafeImage extends React.Component { constructor(props) { super(props) this.state = { validImage: true, loading: true } } _handleError = (event) => { console.log(`Error loading image ${this.props.source.uri}:`, event.nativeEvent.error) this.setState({ validImage: false }) } _handleOnLoadEnd = () => { this.setState({ loading: false }) } render() { let selectedResizeMode = 'contain' if (this.props.resizeMode) { selectedResizeMode = this.props.resizeMode } if (this.props.source && this.props.source.uri && this.state.validImage) { return ( <ImageBackground {...this.props} onError={this._handleError} resizeMode={selectedResizeMode} onLoadEnd={this._handleOnLoadEnd} > {this.state.loading ? <ActivityIndicator size="small" style={css.safe_image_loading_activity_indicator} /> : null} </ImageBackground> ) } else if (this.props.onFailure) { return this.props.onFailure } else { return null } } } export default SafeImage
import React from 'react' import { ImageBackground, ActivityIndicator, View } from 'react-native' import css from '../../styles/css' class SafeImage extends React.Component { constructor(props) { super(props) this.state = { validImage: true, loading: true } } _handleError = (event) => { console.log(`Error loading image ${this.props.source.uri}:`, event.nativeEvent.error) this.setState({ validImage: false }) } _handleOnLoadEnd = () => { this.setState({ loading: false }) } render() { let selectedResizeMode = 'contain' if (this.props.resizeMode) { selectedResizeMode = this.props.resizeMode } if (this.props.source && this.props.source.uri && this.state.validImage) { return ( <View> <ImageBackground {...this.props} onError={this._handleError} resizeMode={selectedResizeMode} onLoadEnd={this._handleOnLoadEnd} > {this.state.loading ? <ActivityIndicator size="small" style={css.safe_image_loading_activity_indicator} /> : null} </ImageBackground> </View> ) } else if (this.props.onFailure) { return this.props.onFailure } else { return null } } } export default SafeImage
Change to id from className
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { // Number of entries to be pulled. // TODO: Determine true value for number of entries. const NUMBER = 2; // The starting point from which the entries are selected. // Relative to the starting index. // TODO: vary multiplier based on page number. const OFFSET = NUMBER * 0; const SOURCE = `/builders/number=${NUMBER}/offset=${OFFSET}`; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE) .then(res => res.json()) .then(json => setData(json)) .catch(setData([])); }, []); return ( <div id='build-snapshot-container'> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> ); } );
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { // Number of entries to be pulled. // TODO: Determine true value for number of entries. const NUMBER = 2; // The starting point from which the entries are selected. // Relative to the starting index. // TODO: vary multiplier based on page number. const OFFSET = NUMBER * 0; const SOURCE = `/builders/number=${NUMBER}/offset=${OFFSET}`; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE) .then(res => res.json()) .then(json => setData(json)) .catch(setData([])); }, []); return ( <div className='build-snapshot-container'> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> ); } );
Make it work with Py3
from curses import wrapper from ui import ChatUI from client import Client import configparser def main(stdscr): cp = configparser.ConfigParser() cp.read('config.cfg') username = cp.get('credentials', 'username') password = cp.get('credentials', 'password').encode('utf-8') stdscr.clear() ui = ChatUI(stdscr) client = Client(username, password, ui) client.subscribe_to_channel('main') client.subscribe_to_users() message = '' while message != '/quit': message = ui.wait_input() if message[0:6] == '/join ': client.subscribe_to_channel(message[6:]) else: client.client.insert('messages', {'channel': client.current_channel, 'text': message}) wrapper(main)
from curses import wrapper from ui import ChatUI from client import Client import ConfigParser def main(stdscr): cp = ConfigParser.ConfigParser() cp.read('config.cfg') username = cp.get('credentials', 'username') password = cp.get('credentials', 'password') stdscr.clear() ui = ChatUI(stdscr) client = Client(username, password, ui) client.subscribe_to_channel('main') client.subscribe_to_users() message = '' while message != '/quit': message = ui.wait_input() if message[0:6] == '/join ': client.subscribe_to_channel(message[6:]) else: client.client.insert('messages', {'channel': client.current_channel, 'text': message}) wrapper(main)
fix(routes): Update to match express v4 API
/** * Module dependencies */ var oidc = require('../oidc') , settings = require('../boot/settings') , User = require('../models/User') ; /** * Exports */ module.exports = function (server) { /** * UserInfo Endpoint */ server.get('/userinfo', oidc.parseAuthorizationHeader, oidc.getBearerToken, oidc.verifyAccessToken({ iss: settings.issuer, key: settings.publicKey, scope: 'profile' }), function (req, res, next) { User.get(req.claims.sub, function (err, user) { if (err) { return next(err); } if (!user) { return next(new NotFoundError()); } res.status(200).json(user.project('userinfo')); }); }); };
/** * Module dependencies */ var oidc = require('../oidc') , settings = require('../boot/settings') , User = require('../models/User') ; /** * Exports */ module.exports = function (server) { /** * UserInfo Endpoint */ server.get('/userinfo', oidc.parseAuthorizationHeader, oidc.getBearerToken, oidc.verifyAccessToken({ iss: settings.issuer, key: settings.publicKey, scope: 'profile' }), function (req, res, next) { User.get(req.claims.sub, function (err, user) { if (err) { return next(err); } if (!user) { return next(new NotFoundError()); } res.json(200, user.project('userinfo')); }); }); };
Move namedtuple definition outside of argspec function
import sys import itertools import inspect from collections import namedtuple _PY2 = sys.version_info.major == 2 if _PY2: range_ = xrange zip_ = itertools.izip def iteritems(d): return d.iteritems() def itervalues(d): return d.itervalues() def iterkeys(d): return d.iterkeys() zip_longest = itertools.izip_longest def getargspec(f): return inspect.getargspec(f) else: range_ = range zip_ = zip def iteritems(d): return iter(d.items()) def itervalues(d): return iter(d.values()) def iterkeys(d): return iter(d.keys()) zip_longest = itertools.zip_longest _ArgSpec = namedtuple('ArgSpec', ('args', 'varargs', 'keywords', 'defaults')) def getargspec(f): argspec = inspect.getfullargspec(f) # FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations) return _ArgSpec(argspec.args, argspec.varargs, argspec.varkw, argspec.defaults)
import sys import itertools import inspect from collections import namedtuple _PY2 = sys.version_info.major == 2 if _PY2: range_ = xrange zip_ = itertools.izip def iteritems(d): return d.iteritems() def itervalues(d): return d.itervalues() def iterkeys(d): return d.iterkeys() zip_longest = itertools.izip_longest def getargspec(f): return inspect.getargspec(f) else: range_ = range zip_ = zip def iteritems(d): return iter(d.items()) def itervalues(d): return iter(d.values()) def iterkeys(d): return iter(d.keys()) zip_longest = itertools.zip_longest def getargspec(f): ArgSpec = namedtuple('ArgSpec', ('args', 'varargs', 'keywords', 'defaults')) # FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations) argspec = inspect.getfullargspec(f) return ArgSpec(argspec.args, argspec.varargs, argspec.varkw, argspec.defaults)
Configure single run of tests
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, '../../coverage/hslayers'), reports: ['html', 'lcovonly', 'text-summary'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], singleRun: typeof process.env.watch == 'undefined' ? true : !process.env.watch, restartOnFileChange: true }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, '../../coverage/hslayers'), reports: ['html', 'lcovonly', 'text-summary'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], singleRun: false, restartOnFileChange: true }); };
Fix incorrect ATerms being emitted for booleans
package org.metaborg.meta.interpreter.framework; import org.spoofax.interpreter.core.Tools; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; public class TermUtils { public static boolean boolFromTerm(IStrategoTerm term) { if (Tools.isTermAppl(term)) { IStrategoAppl tAppl = (IStrategoAppl) term; if (Tools.hasConstructor(tAppl, "___DS_False___", 0)) { return false; } else if (Tools.hasConstructor(tAppl, "___DS_True___", 0)) { return true; } } throw new RuntimeException("Malformed boolean: " + term); } public static IStrategoTerm termFromBool(boolean bV, ITermFactory factory) { return factory.makeAppl(factory.makeConstructor(bV ? "___DS_True___" : "___DS_False___", 0)); } }
package org.metaborg.meta.interpreter.framework; import org.spoofax.interpreter.core.Tools; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; public class TermUtils { public static boolean boolFromTerm(IStrategoTerm term) { if (Tools.isTermAppl(term)) { IStrategoAppl tAppl = (IStrategoAppl) term; if (Tools.hasConstructor(tAppl, "$__DS_False__$", 0)) { return false; } else if (Tools.hasConstructor(tAppl, "$__DS_True__$", 0)) { return true; } } throw new RuntimeException("Malformed boolean: " + term); } public static IStrategoTerm termFromBool(boolean bV, ITermFactory factory) { return factory.makeAppl(factory.makeConstructor(bV ? "$__DS_True__$" : "$__DS_False__$", 0)); } }
Drop unused variables (make Uglify happy)
let React = require("react") let ReactDOM = require("react-dom") let Colr = require('colr') let draggable = require('./higher_order_components/draggable.js') @draggable({ updateClientCoords({clientY}) { let rect = ReactDOM.findDOMNode(this).getBoundingClientRect() let hue = this.getScaledValue((rect.bottom - clientY) / rect.height) let colr = Colr.fromHsv(hue, this.props.hsv.s, this.props.hsv.v) this.props.colrLink.requestChange(colr) }, }) export default class extends React.Component { static displayName = "HueSlider" static defaultProps = Object.assign(require("../../default_props.js")) render() { return ( <div className="frigb-slider frigb-vertical" onMouseDown={this.props.startDragging} onTouchStart={this.props.startDragging} > <div className="frigb-track" /> <div className="frigb-pointer" style={{ "bottom": this.props.getPercentageValue(this.props.hsv.h), }} /> </div> ) } }
let React = require("react") let ReactDOM = require("react-dom") let Colr = require('colr') let draggable = require('./higher_order_components/draggable.js') let { div } = React.DOM @draggable({ updateClientCoords({clientX, clientY}) { let rect = ReactDOM.findDOMNode(this).getBoundingClientRect() let hue = this.getScaledValue((rect.bottom - clientY) / rect.height) let colr = Colr.fromHsv(hue, this.props.hsv.s, this.props.hsv.v) this.props.colrLink.requestChange(colr) }, }) export default class extends React.Component { static displayName = "HueSlider" static defaultProps = Object.assign(require("../../default_props.js")) render() { return ( <div className="frigb-slider frigb-vertical" onMouseDown={this.props.startDragging} onTouchStart={this.props.startDragging} > <div className="frigb-track" /> <div className="frigb-pointer" style={{ "bottom": this.props.getPercentageValue(this.props.hsv.h), }} /> </div> ) } }
Set DEBUG = False in production
from local_settings import * settings.DEBUG = False ALLOWED_HOSTS = ['uchicagohvz.org'] # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'uchicagohvz', # Or path to database file if using sqlite3. 'USER': 'user', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # REST framework settings REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } # Mandrill email settings EMAIL_HOST = 'smtp.mandrillapp.com' from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD EMAIL_PORT = '587' EMAIL_USE_TLS = True
from local_settings import * ALLOWED_HOSTS = ['uchicagohvz.org'] # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'uchicagohvz', # Or path to database file if using sqlite3. 'USER': 'user', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # REST framework settings REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } # Mandrill email settings EMAIL_HOST = 'smtp.mandrillapp.com' from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD EMAIL_PORT = '587' EMAIL_USE_TLS = True
Enable much stricter CSP on the iframe
<?php namespace Korobi\WebBundle\Controller; use Korobi\WebBundle\Exception\NotImplementedException; use Michelf\Markdown; use Symfony\Component\HttpFoundation\Response; class DocsController extends BaseController { public function renderAction($file) { if (!preg_match("/^[A-Za-z0-9_]+$/", $file)) { throw $this->createNotFoundException("Invalid doc"); } $fn = $this->get('kernel')->getRootDir() . "/../docs/" . $file . ".md"; if (!file_exists($fn) || $file === "README") { throw $this->createNotFoundException("Doc does not exist, " . $fn); } $parser = new Markdown; $parser->no_entities = true; $parser->no_markup = true; $content = $this->render('KorobiWebBundle::doc_item.html.twig', ["content" => $parser->transform(file_get_contents($fn))]); return new Response($content, 200, ["Content-Security-Policy" => "default-src 'self'"]); } public function indexAction() { return $this->render('KorobiWebBundle::docs.html.twig'); } }
<?php namespace Korobi\WebBundle\Controller; use Korobi\WebBundle\Exception\NotImplementedException; use Michelf\Markdown; use Symfony\Component\HttpFoundation\Response; class DocsController extends BaseController { public function renderAction($file) { if (!preg_match("/^[A-Za-z0-9_]+$/", $file)) { throw $this->createNotFoundException("Invalid doc"); } $fn = $this->get('kernel')->getRootDir() . "/../docs/" . $file . ".md"; if (!file_exists($fn) || $file === "README") { throw $this->createNotFoundException("Doc does not exist, " . $fn); } $parser = new Markdown; $parser->no_entities = true; $parser->no_markup = true; return $this->render('KorobiWebBundle::doc_item.html.twig', ["content" => $parser->transform(file_get_contents($fn))]); } public function indexAction() { return $this->render('KorobiWebBundle::docs.html.twig'); } }
Fix in error when analyze directories without duplicates
import os from threading import Thread def _delete(path: str, src: str, link: bool): os.remove(path) if link: os.symlink(src, path) def manager_files(paths, link): # The first file is preserved to not delete all files in directories. first = True src = "" deleted_files = [] linked_files = [] errors = [] for path in paths: if os.path.isfile(path): if first: first = False src = path else: Thread(target=_delete, args=(path, src, link)).start() deleted_files.append(path) if link: linked_files.append(path) else: errors.append("Not identified by file: \"{}\"".format(path)) return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors} # Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect def manager(duplicates, create_link=False): if len(duplicates) == 0: # Return empty list object return [] processed_files = [] for files_by_hash in duplicates.values(): processed_files.append(manager_files(files_by_hash, create_link)) return processed_files def delete(duplicates): return manager(duplicates) def link(duplicates): return manager(duplicates, True)
import os from threading import Thread def _delete(path: str, src: str, link: bool): os.remove(path) if link: os.symlink(src, path) def manager_files(paths, link): # The first file is preserved to not delete all files in directories. first = True src = "" deleted_files = [] linked_files = [] errors = [] for path in paths: if os.path.isfile(path): if first: first = False src = path else: Thread(target=_delete, args=(path, src, link)).start() deleted_files.append(path) if link: linked_files.append(path) else: errors.append("Not identified by file: \"{}\"".format(path)) return {"preserved": src, "linked_files": linked_files, "deleted_files": deleted_files, "errors": errors} # Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect def manager(duplicates, create_link=False): if len(duplicates) == 0: return None processed_files = [] for files_by_hash in duplicates.values(): processed_files.append(manager_files(files_by_hash, create_link)) return processed_files def delete(duplicates): return manager(duplicates) def link(duplicates): return manager(duplicates, True)
Remove default class switch-off (fix css bug when a switcher is set to true by default)
angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function() { return { restrict: 'EA', replace: true, scope: { model: '=' }, template: '<div class="switch" ng-click="toggle()"><div class="switch-animate" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left">On</span><span class="knob">&nbsp;</span><span class="switch-right">Off</span></div></div>', link: function($scope, element, attrs) { if ($scope.model == null) { $scope.model = false; } return $scope.toggle = function() { return $scope.model = !$scope.model; }; } }; });
angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function() { return { restrict: 'EA', replace: true, scope: { model: '=' }, template: '<div class="switch" ng-click="toggle()"><div class="switch-animate switch-off" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left">On</span><span class="knob">&nbsp;</span><span class="switch-right">Off</span></div></div>', link: function($scope, element, attrs) { if ($scope.model == null) { $scope.model = false; } return $scope.toggle = function() { return $scope.model = !$scope.model; }; } }; });
Add unique constraint to rid
# -*- coding: utf-8 -*- """ app.models ~~~~~~~~~~ Provides the SQLAlchemy models """ from __future__ import ( absolute_import, division, print_function, with_statement, unicode_literals) import savalidation.validators as val from datetime import datetime as dt from app import db from savalidation import ValidationMixin class HDRO(db.Model, ValidationMixin): # auto keys id = db.Column(db.Integer, primary_key=True) utc_created = db.Column(db.DateTime, nullable=False, default=dt.utcnow()) utc_updated = db.Column( db.DateTime, nullable=False, default=dt.utcnow(), onupdate=dt.utcnow()) # other keys rid = db.Column(db.String(16), nullable=False, index=True, unique=True) country = db.Column(db.String(32), nullable=False) indicator = db.Column(db.String(128), nullable=False) value = db.Column(db.Numeric, nullable=False) year = db.Column(db.Integer, nullable=False) # validation val.validates_constraints() def __repr__(self): return ('<HDRO(%r, %r)>' % (self.country, self.indicator))
# -*- coding: utf-8 -*- """ app.models ~~~~~~~~~~ Provides the SQLAlchemy models """ from __future__ import ( absolute_import, division, print_function, with_statement, unicode_literals) import savalidation.validators as val from datetime import datetime as dt from app import db from savalidation import ValidationMixin class HDRO(db.Model, ValidationMixin): # auto keys id = db.Column(db.Integer, primary_key=True) utc_created = db.Column(db.DateTime, nullable=False, default=dt.utcnow()) utc_updated = db.Column( db.DateTime, nullable=False, default=dt.utcnow(), onupdate=dt.utcnow()) # other keys rid = db.Column(db.String(16), nullable=False, index=True) country = db.Column(db.String(32), nullable=False) indicator = db.Column(db.String(128), nullable=False) value = db.Column(db.Numeric, nullable=False) year = db.Column(db.Integer, nullable=False) # validation val.validates_constraints() def __repr__(self): return ('<HDRO(%r, %r)>' % (self.country, self.indicator))
Fix class name in doc block When putting the annotation back we forgot to use the aliased name. This fixes it, making static analysers and IDEs work as expected. More info: 31df2e805fe0cf184bdfcb528a696dc1daae40c3
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\MockObject\Builder\InvocationMocker as BuilderInvocationMocker; use PHPUnit\Framework\MockObject\Matcher\Invocation; /** * @method BuilderInvocationMocker method($constraint) */ interface MockObject /*extends Verifiable*/ { public function __phpunit_setOriginalObject($originalObject): void; public function __phpunit_getInvocationMocker(): InvocationMocker; public function __phpunit_verify(bool $unsetInvocationMocker = true): void; public function __phpunit_hasMatchers(): bool; public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration): void; public function expects(Invocation $matcher): BuilderInvocationMocker; }
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\MockObject\Builder\InvocationMocker as BuilderInvocationMocker; use PHPUnit\Framework\MockObject\Matcher\Invocation; /** * @method InvocationMocker method($constraint) */ interface MockObject /*extends Verifiable*/ { public function __phpunit_setOriginalObject($originalObject): void; public function __phpunit_getInvocationMocker(): InvocationMocker; public function __phpunit_verify(bool $unsetInvocationMocker = true): void; public function __phpunit_hasMatchers(): bool; public function __phpunit_setReturnValueGeneration(bool $returnValueGeneration): void; public function expects(Invocation $matcher): BuilderInvocationMocker; }
Add cache support for ASN1_Packet() --HG-- branch : fix-padding-after-pull-request-18
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): if self.raw_packet_cache is not None: return self.raw_packet_cache return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x)
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x)
Remove temporary code to tell if networktables is running on the robot, as it no longer works with the RoboRIO.
package org.ingrahamrobotics.robottables.util; public class Platform { private static final Object LOCK = new Object(); private static boolean ready = false; private static boolean onRobot = false; public static boolean onRobot() { synchronized (LOCK) { if (!ready) { init(); } } return onRobot; } private static void init() { onRobot = false; // // One of these (or a combination thereof) will let me figure out if we're running on the robot // System.getProperty("java.version"); // System.getProperty("java.vendor"); // System.getProperty("java.compiler"); // System.getProperty("os.name"); // onRobot = false; ready = true; } }
package org.ingrahamrobotics.robottables.util; public class Platform { private static final Object LOCK = new Object(); private static boolean ready = false; private static boolean onRobot = false; public static boolean onRobot() { synchronized (LOCK) { if (!ready) { init(); } } return onRobot; } private static void init() { try { Class.forName("java.util.ArrayList"); onRobot = false; } catch (ClassNotFoundException ex) { onRobot = true; } // // One of these (or a combination thereof) will let me figure out if we're running on the robot // System.getProperty("java.version"); // System.getProperty("java.vendor"); // System.getProperty("java.compiler"); // System.getProperty("os.name"); // onRobot = false; ready = true; } }
Revert "apply caveman rate limiting to europe pmc api calls" This reverts commit f2d0b4ab961325dfffaf3a54603b56e848f46da0.
#!/usr/bin/python # -*- coding: utf-8 -*- from cachetools import LRUCache from kids.cache import cache from http_cache import http_get # examples # https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC3039489&resulttype=core&format=json&tool=oadoi # https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC3606428&resulttype=core&format=json&tool=oadoi # https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=10.1093/jisesa/iex068&resulttype=core&format=json&tool=oadoi @cache(use=LRUCache(maxsize=32)) def query_pmc(query_text): if not query_text: return None url_template = u"https://www.ebi.ac.uk/europepmc/webservices/rest/search?query={}&resulttype=core&format=json&tool=oadoi" url = url_template.format(query_text) r = http_get(url) data = r.json() result_list = data["resultList"]["result"] return result_list
#!/usr/bin/python # -*- coding: utf-8 -*- from time import sleep from cachetools import LRUCache from kids.cache import cache from http_cache import http_get # examples # https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC3039489&resulttype=core&format=json&tool=oadoi # https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC3606428&resulttype=core&format=json&tool=oadoi # https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=10.1093/jisesa/iex068&resulttype=core&format=json&tool=oadoi @cache(use=LRUCache(maxsize=32)) def query_pmc(query_text): if not query_text: return None # TODO: remove sleep once europe pmc pages are backfilled # (pmh_version_first_available is populated for records from endpoint b5e840539009389b1a6) sleep(3) url_template = u"https://www.ebi.ac.uk/europepmc/webservices/rest/search?query={}&resulttype=core&format=json&tool=oadoi" url = url_template.format(query_text) r = http_get(url) data = r.json() result_list = data["resultList"]["result"] return result_list
Remove include that may be problematic on Azure Web Apps
const dotenv = require('dotenv'); const webpack = require('webpack'); dotenv.config({ silent: true }); module.exports = { entry: [ 'whatwg-fetch', './src/client/app.js' ], output: { path: './public/lib', filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', query: { presets: ['es2015'] } } ] }, plugins: [ new webpack.EnvironmentPlugin([ "IMAGE_RETRIEVER" ]) ], devTool: 'source-map' };
const path = require('path'); const dotenv = require('dotenv'); const webpack = require('webpack'); dotenv.config({ silent: true }); module.exports = { entry: [ 'whatwg-fetch', './src/client/app.js' ], output: { path: './public/lib', filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, loader: 'babel-loader', include: [ path.resolve(__dirname, 'src') ], query: { presets: ['es2015'] } } ] }, plugins: [ new webpack.EnvironmentPlugin([ "IMAGE_RETRIEVER" ]) ], devTool: 'source-map' };
Check if username was actually changed by the CSRF
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const models = require('../models/index') const insecurity = require('../lib/insecurity') const utils = require('../lib/utils') const cache = require('../data/datacache') const challenges = cache.challenges module.exports = function updateUserProfile () { return (req, res, next) => { const loggedInUser = insecurity.authenticatedUsers.get(req.cookies.token) if (loggedInUser) { models.User.findByPk(loggedInUser.data.id).then(user => { utils.solveIf(challenges.csrfChallenge, () => { return (req.headers.origin.includes('://htmledit.squarefree.com') && req.body.username !== user.username }) return user.update({ username: req.body.username }) }).catch(error => { next(error) }) } else { next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress)) } res.location('/profile') res.redirect('/profile') } }
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const models = require('../models/index') const insecurity = require('../lib/insecurity') const utils = require('../lib/utils') const cache = require('../data/datacache') const challenges = cache.challenges module.exports = function updateUserProfile () { return (req, res, next) => { const loggedInUser = insecurity.authenticatedUsers.get(req.cookies.token) if (loggedInUser) { models.User.findByPk(loggedInUser.data.id).then(user => { /* Challenge is solved if request originated from a known HTML ODE and sets a new username */ if (req.headers.origin.includes('://htmledit.squarefree.com') && req.body.username && utils.notSolved(challenges.csrfChallenge)) { utils.solve(challenges.csrfChallenge) } return user.update({ username: req.body.username }) }).catch(error => { next(error) }) } else { next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress)) } res.location('/profile') res.redirect('/profile') } }
Add new "critically low" foreground trim level Differential Revision: D10369483 fbshipit-source-id: c4a55701c31e8a9375f0ab6a9238e5247758d57d
/* * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.common.memory; /** * Types of memory trim. * * <p>Each type of trim will provide a suggested trim ratio. * * <p>A {@link MemoryTrimmableRegistry} implementation sends out memory trim events with this type. */ public enum MemoryTrimType { /** The application is approaching the device-specific Java heap limit. */ OnCloseToDalvikHeapLimit(0.5), /** The system as a whole is running critically low on memory, and app is in the foreground. */ OnSystemMemoryCriticallyLowWhileAppInForeground(1), /** The system as a whole is running low of memory, and this application is in the foreground. */ OnSystemLowMemoryWhileAppInForeground(0.5), /** The system as a whole is running out of memory, and this application is in the background. */ OnSystemLowMemoryWhileAppInBackground(1), /** This app is moving into the background, usually because the user navigated to another app. */ OnAppBackgrounded(1); private double mSuggestedTrimRatio; private MemoryTrimType(double suggestedTrimRatio) { mSuggestedTrimRatio = suggestedTrimRatio; } /** Get the recommended percentage by which to trim the cache on receiving this event. */ public double getSuggestedTrimRatio () { return mSuggestedTrimRatio; } }
/* * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.common.memory; /** * Types of memory trim. * * <p>Each type of trim will provide a suggested trim ratio. * * <p>A {@link MemoryTrimmableRegistry} implementation sends out memory trim events with this type. */ public enum MemoryTrimType { /** The application is approaching the device-specific Java heap limit. */ OnCloseToDalvikHeapLimit(0.5), /** The system as a whole is running out of memory, and this application is in the foreground. */ OnSystemLowMemoryWhileAppInForeground(0.5), /** The system as a whole is running out of memory, and this application is in the background. */ OnSystemLowMemoryWhileAppInBackground(1), /** This app is moving into the background, usually because the user navigated to another app. */ OnAppBackgrounded(1); private double mSuggestedTrimRatio; private MemoryTrimType(double suggestedTrimRatio) { mSuggestedTrimRatio = suggestedTrimRatio; } /** Get the recommended percentage by which to trim the cache on receiving this event. */ public double getSuggestedTrimRatio () { return mSuggestedTrimRatio; } }
Make install_requires into an array
import os import sys from distutils.core import setup # Don't import stripe module here, since deps may not be installed sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'stripe')) import importer import version path, script = os.path.split(sys.argv[0]) os.chdir(os.path.abspath(path)) # Get simplejson if we don't already have json install_requires = ['requests'] try: importer.import_json() except ImportError: install_requires.append('simplejson') try: import json _json_loaded = hasattr(json, 'loads') except ImportError: pass setup(name='stripe', version=version.VERSION, description='Stripe python bindings', author='Stripe', author_email='support@stripe.com', url='https://stripe.com/', packages=['stripe'], package_data={'stripe' : ['data/ca-certificates.crt', '../VERSION']}, install_requires=install_requires )
import os import sys from distutils.core import setup # Don't import stripe module here, since deps may not be installed sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'stripe')) import importer import version path, script = os.path.split(sys.argv[0]) os.chdir(os.path.abspath(path)) # Get simplejson if we don't already have json install_requires = 'requests' try: importer.import_json() except ImportError: install_requires.append('simplejson') try: import json _json_loaded = hasattr(json, 'loads') except ImportError: pass setup(name='stripe', version=version.VERSION, description='Stripe python bindings', author='Stripe', author_email='support@stripe.com', url='https://stripe.com/', packages=['stripe'], package_data={'stripe' : ['data/ca-certificates.crt', '../VERSION']}, install_requires=install_requires )
Remove query from Sizes collection url (cherry picked from commit ca808fb15f0ce3b6da46fb2198d88b8ed807fce1)
define(function (require) { "use strict"; var Backbone = require('backbone'), _ = require('underscore'), Size = require('models/Size'), globals = require('globals'); return Backbone.Collection.extend({ model: Size, url: globals.API_V2_ROOT + "/sizes", parse: function (response) { this.meta = { count: response.count, next: response.next, previous: response.previous }; return response.results; }, comparator: function (sizeA, sizeB) { var aliasA = parseInt(sizeA.get('alias')); var aliasB = parseInt(sizeB.get('alias')); if (aliasA === aliasB) return 0; return aliasA < aliasB ? -1 : 1; } }); });
define(function (require) { "use strict"; var Backbone = require('backbone'), _ = require('underscore'), Size = require('models/Size'), globals = require('globals'); return Backbone.Collection.extend({ model: Size, url: globals.API_V2_ROOT + "/sizes?archived=true", parse: function (response) { this.meta = { count: response.count, next: response.next, previous: response.previous }; return response.results; }, comparator: function (sizeA, sizeB) { var aliasA = parseInt(sizeA.get('alias')); var aliasB = parseInt(sizeB.get('alias')); if (aliasA === aliasB) return 0; return aliasA < aliasB ? -1 : 1; } }); });
Improve fetchOne to only return 1 result Inspired by meteor's findOne
import createGraph from './lib/createGraph.js'; import prepareForProcess from './lib/prepareForProcess.js'; import hypernova from './hypernova/hypernova.js'; import Base from './query.base'; export default class Query extends Base { /** * Retrieves the data. * @param context * @returns {*} */ fetch(context = {}) { const node = createGraph( this.collection, prepareForProcess(this.body, this.params) ); return hypernova(node, context.userId, {params: this.params}); } /** * @param context * @returns {*} */ fetchOne(context = {}) { context.$options = context.$options || {}; context.$options.limit = 1; return this.fetch(context); } /** * Gets the count of matching elements. * @returns {integer} */ getCount() { return this.collection.find(this.body.$filters || {}, {}).count(); } }
import createGraph from './lib/createGraph.js'; import prepareForProcess from './lib/prepareForProcess.js'; import hypernova from './hypernova/hypernova.js'; import Base from './query.base'; export default class Query extends Base { /** * Retrieves the data. * @param context * @returns {*} */ fetch(context = {}) { const node = createGraph( this.collection, prepareForProcess(this.body, this.params) ); return hypernova(node, context.userId, {params: this.params}); } /** * @param args * @returns {*} */ fetchOne(...args) { return _.first(this.fetch(...args)); } /** * Gets the count of matching elements. * @returns {integer} */ getCount() { return this.collection.find(this.body.$filters || {}, {}).count(); } }
Add method to serve prediction result files
import flask from cref.app.web import app from cref.app.web.tasks import predict_structure def success(result): return flask.jsonify({ 'status': 'success', 'retval': result }) def failure(reason='Unknown'): return flask.jsonify({ 'status': 'failure', 'reason': reason }) @app.route('/predict/', methods=['POST']) def predict(): params = flask.request.get_json(force=True) resp = predict_structure.delay(params['sequence']) return success({'task_id': resp.id}) @app.route('/predict/<sequence>', methods=['GET']) def predict_test(sequence): resp = predict_structure.delay(sequence) return success({'task_id': resp.id}) @app.route('/status/<task_id>') def status(task_id): result = predict_structure.AsyncResult(task_id) return success({'state': result.state}) @app.route('/result/<task_id>') def result(task_id): result = predict_structure.AsyncResult(task_id) if result.ready(): return success({'pdb_file': result.get()}) else: return failure('Task is pending') @app.route('/predictions/<task_id>/<path:filename>') def download_file(filename): return flask.send_from_directory( '/home/mchelem/dev/cref2/predictions/', filename, as_attachment=True )
import flask from cref.app.web import app from cref.app.web.tasks import predict_structure def success(result): return flask.jsonify({ 'status': 'success', 'retval': result }) def failure(reason='Unknown'): return flask.jsonify({ 'status': 'failure', 'reason': reason }) @app.route('/predict/', methods=['POST']) def predict(): sequence = flask.request.get_json(force=True)['sequence'] resp = predict_structure.delay(sequence) return success({'task_id': resp.id}) @app.route('/predict/<sequence>', methods=['GET']) def predict_test(sequence): resp = predict_structure.delay(sequence) return success({'task_id': resp.id}) @app.route('/status/<task_id>') def status(task_id): result = predict_structure.AsyncResult(task_id) return success({'state': result.state}) @app.route('/result/<task_id>') def result(task_id): result = predict_structure.AsyncResult(task_id) if result.ready(): return success({'pdb_file': result.get()}) else: return failure('Task is pending')
Fix SDK check methods NPE. Summary: Ref T9503 Test Plan: done Reviewers: fenghonghua, durunnan, xiewenliang Reviewed By: durunnan Maniphest Tasks: T9503 Differential Revision: https://phabricator.d.xiaomi.net/D63687
package com.xiaomi.infra.galaxy.emq.client; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; /** * Copyright 2015, Xiaomi. * All rights reserved. * Author: shenyuannan@xiaomi.com */ public class EMQClient { private static class EMQClientHandler<T> implements InvocationHandler { private final Object instance; public EMQClientHandler(Class<T> interfaceClass, Object instance) { this.instance = instance; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (!Arrays.asList(Object.class.getMethods()).contains(method)) { EMQRequestCheckUtils.checkRequest(args); } try { return method.invoke(instance, args); } catch (InvocationTargetException e) { throw e.getCause(); } } } /** * Create client wrapper which validate parameters of client. */ @SuppressWarnings("unchecked") public static <T> T getClient(Class<T> interfaceClass, Object instance) { return (T) Proxy.newProxyInstance(EMQClient.class.getClassLoader(), new Class[]{interfaceClass}, new EMQClientHandler(interfaceClass, instance)); } }
package com.xiaomi.infra.galaxy.emq.client; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Copyright 2015, Xiaomi. * All rights reserved. * Author: shenyuannan@xiaomi.com */ public class EMQClient { private static class EMQClientHandler<T> implements InvocationHandler { private final Object instance; public EMQClientHandler(Class<T> interfaceClass, Object instance) { this.instance = instance; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { EMQRequestCheckUtils.checkRequest(args); try { return method.invoke(instance, args); } catch (InvocationTargetException e) { throw e.getCause(); } } } /** * Create client wrapper which validate parameters of client. */ @SuppressWarnings("unchecked") public static <T> T getClient(Class<T> interfaceClass, Object instance) { return (T) Proxy.newProxyInstance(EMQClient.class.getClassLoader(), new Class[]{interfaceClass}, new EMQClientHandler(interfaceClass, instance)); } }
Exit with code 1 if tests fail. Fixes #621 and Travis.
#!/usr/bin/python import optparse import sys # Install the Python unittest2 package before you run this script. import unittest2 USAGE = """%prog SDK_PATH Run unit tests for App Engine apps. The SDK Path is probably /usr/local/google_appengine on Mac OS SDK_PATH Path to the SDK installation""" def main(sdk_path, test_pattern): sys.path.insert(0, sdk_path) import dev_appserver dev_appserver.fix_sys_path() suite = unittest2.loader.TestLoader().discover("tests", test_pattern) tests = unittest2.TextTestRunner(verbosity=2).run(suite) if tests.wasSuccessful() == True: sys.exit(0) else: sys.exit(1) if __name__ == '__main__': parser = optparse.OptionParser(USAGE) options, args = parser.parse_args() if len(args) < 1: print 'Warning: Trying default SDK path.' sdk_path = "/usr/local/google_appengine" else: sdk_path = args[0] test_pattern = "test*.py" if len(args) > 1: test_pattern = args[1] main(sdk_path, test_pattern)
#!/usr/bin/python import optparse import sys # Install the Python unittest2 package before you run this script. import unittest2 USAGE = """%prog SDK_PATH Run unit tests for App Engine apps. The SDK Path is probably /usr/local/google_appengine on Mac OS SDK_PATH Path to the SDK installation""" def main(sdk_path, test_pattern): sys.path.insert(0, sdk_path) import dev_appserver dev_appserver.fix_sys_path() suite = unittest2.loader.TestLoader().discover("tests", test_pattern) unittest2.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': parser = optparse.OptionParser(USAGE) options, args = parser.parse_args() if len(args) < 1: print 'Warning: Trying default SDK path.' sdk_path = "/usr/local/google_appengine" else: sdk_path = args[0] test_pattern = "test*.py" if len(args) > 1: test_pattern = args[1] main(sdk_path, test_pattern)
Add ctrl-c support to quit. Closes #4
package main import "github.com/nsf/termbox-go" import "time" import "flag" func main() { loops := flag.Int("loops", 0, "number of times to loop (default: infinite)") flag.Parse() err := termbox.Init() if err != nil { panic(err) } defer termbox.Close() event_queue := make(chan termbox.Event) go func() { for { event_queue <- termbox.PollEvent() } }() termbox.SetOutputMode(termbox.Output256) loop_index := 0 draw() loop: for { select { case ev := <-event_queue: if ev.Type == termbox.EventKey && (ev.Key == termbox.KeyEsc || ev.Key == termbox.KeyCtrlC) { break loop } default: loop_index++ if *loops > 0 && (loop_index/9) >= *loops { break loop } draw() time.Sleep(75 * time.Millisecond) } } }
package main import "github.com/nsf/termbox-go" import "time" import "flag" func main() { loops := flag.Int("loops", 0, "number of times to loop (default: infinite)") flag.Parse() err := termbox.Init() if err != nil { panic(err) } defer termbox.Close() event_queue := make(chan termbox.Event) go func() { for { event_queue <- termbox.PollEvent() } }() termbox.SetOutputMode(termbox.Output256) loop_index := 0 draw() loop: for { select { case ev := <-event_queue: if ev.Type == termbox.EventKey && ev.Key == termbox.KeyEsc { break loop } default: loop_index++ if *loops > 0 && (loop_index/9) >= *loops { break loop } draw() time.Sleep(75 * time.Millisecond) } } }
Fix soname generation on non-Darwin Unix platforms. Change-Id: Ifc2d7edf883072067b76a51368ea3e89172cff94 Reviewed-by: Christian Kandeler <3aa99dcdd3f0cac61fb81c2a11771c0cc2497607@theqtcompany.com>
var FileInfo = loadExtension("qbs.FileInfo"); function soname(product, outputFileName) { if (product.moduleProperty("qbs", "targetOS").contains("darwin")) { if (product.moduleProperty("bundle", "isBundle")) outputFileName = product.moduleProperty("bundle", "executablePath"); var prefix = product.moduleProperty("cpp", "installNamePrefix"); if (prefix) outputFileName = FileInfo.joinPaths(prefix, outputFileName); return outputFileName; } function majorVersion(version, defaultValue) { var n = parseInt(version, 10); return isNaN(n) ? defaultValue : n; } var version = product.moduleProperty("cpp", "internalVersion"); if (version) { var major = majorVersion(version); if (major) { return outputFileName.substr(0, outputFileName.length - version.length) + major; } } return outputFileName; }
var FileInfo = loadExtension("qbs.FileInfo"); function soname(product, outputFileName) { if (product.moduleProperty("qbs", "targetOS").contains("darwin")) { if (product.moduleProperty("bundle", "isBundle")) outputFileName = product.moduleProperty("bundle", "executablePath"); var prefix = product.moduleProperty("cpp", "installNamePrefix"); if (prefix) outputFileName = FileInfo.joinPaths(prefix, outputFileName); return outputFileName; } function majorVersion(version, defaultValue) { var n = parseInt(version, 10); return isNaN(n) ? defaultValue : n; } if (product.version) { var major = majorVersion(product.version); if (major) { return outputFileName.substr(0, outputFileName.length - product.version.length) + major; } } return outputFileName; }
Remove queue too big logging.
package abra; import htsjdk.samtools.DefaultSAMRecordFactory; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SamInputResource; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import java.io.IOException; import java.io.InputStream; import java.util.Queue; public class ReadInputStreamRunnable implements Runnable { private static final int MAX_QUEUE_SIZE = 600000; private InputStream is; private Queue<SAMRecord> queue; public ReadInputStreamRunnable(InputStream is, Queue<SAMRecord> queue) { this.is = is; this.queue = queue; } public void run() { final SamReader reader = SamReaderFactory.make() .validationStringency(ValidationStringency.SILENT) .samRecordFactory(DefaultSAMRecordFactory.getInstance()) .open(SamInputResource.of(is)); for (SAMRecord read : reader) { while (queue.size() > MAX_QUEUE_SIZE) { // System.out.println("Queue too big"); try { Thread.sleep(100); } catch (InterruptedException e) { } } queue.add(read); } try { reader.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } }
package abra; import htsjdk.samtools.DefaultSAMRecordFactory; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SamInputResource; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.ValidationStringency; import java.io.IOException; import java.io.InputStream; import java.util.Queue; public class ReadInputStreamRunnable implements Runnable { private static final int MAX_QUEUE_SIZE = 600000; private InputStream is; private Queue<SAMRecord> queue; public ReadInputStreamRunnable(InputStream is, Queue<SAMRecord> queue) { this.is = is; this.queue = queue; } public void run() { final SamReader reader = SamReaderFactory.make() .validationStringency(ValidationStringency.SILENT) .samRecordFactory(DefaultSAMRecordFactory.getInstance()) .open(SamInputResource.of(is)); for (SAMRecord read : reader) { while (queue.size() > MAX_QUEUE_SIZE) { System.out.println("Queue too big"); try { Thread.sleep(100); } catch (InterruptedException e) { } } queue.add(read); } try { reader.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } }
Remove uneccessary event reference from anonymous callback
import '@material/mwc-dialog'; import '@material/mwc-button'; import '@material/mwc-textfield'; import '../shared/demo-header'; addEventListener('load', function() { document.body.classList.remove('unresolved'); }); const buttons = document.body.querySelectorAll('mwc-button[data-num]'); for (let i = 0; i < buttons.length; i++) { const button = buttons[i]; const buttonNum = button.dataset.num; const listenerFactory = (numButton) => { return function() { const dialog = document.body.querySelector('#dialog' + numButton); dialog.open = true; }; }; const listener = listenerFactory(buttonNum); button.addEventListener('click', listener); } window.toggleActions.onclick = function() { const dialog = document.body.querySelector('#dialog4'); const hideActionSpan = document.body.querySelector('#hideActionVal'); const hideAction = !dialog.hideActions; dialog.hideActions = hideAction; hideActionSpan.innerText = hideAction; }; const dialog = document.querySelector('#dialog8'); const textField = document.querySelector('#dialog8-text-field'); const primaryButton = document.querySelector('#dialog8-primary-action-button'); primaryButton.addEventListener('click', () => { // validate, possible asynchronous such as a server response const isValid = textField.checkValidity(); if (isValid) { dialog.close(); return; } textField.reportValidity(); });
import '@material/mwc-dialog'; import '@material/mwc-button'; import '@material/mwc-textfield'; import '../shared/demo-header'; addEventListener('load', function() { document.body.classList.remove('unresolved'); }); const buttons = document.body.querySelectorAll('mwc-button[data-num]'); for (let i = 0; i < buttons.length; i++) { const button = buttons[i]; const buttonNum = button.dataset.num; const listenerFactory = (numButton) => { return function() { const dialog = document.body.querySelector('#dialog' + numButton); dialog.open = true; }; }; const listener = listenerFactory(buttonNum); button.addEventListener('click', listener); } window.toggleActions.onclick = function() { const dialog = document.body.querySelector('#dialog4'); const hideActionSpan = document.body.querySelector('#hideActionVal'); const hideAction = !dialog.hideActions; dialog.hideActions = hideAction; hideActionSpan.innerText = hideAction; }; const dialog = document.querySelector('#dialog8'); const textField = document.querySelector('#dialog8-text-field'); const primaryButton = document.querySelector('#dialog8-primary-action-button'); primaryButton.addEventListener('click', (e) => { // validate, possible asynchronous such as a server response const isValid = textField.checkValidity(); if (isValid) { dialog.close(); return; } textField.reportValidity(); });
Add missed json to json() tweak
from __future__ import print_function import json from argh import ArghParser, arg from ghtools import cli from ghtools.api import GithubAPIClient parser = ArghParser(description="Browse the GitHub API") @arg('github', nargs='?', help='GitHub instance nickname (e.g "enterprise")') @arg('url', help='URL to browse') @arg('-m', '--method', default='get', choices=('get', 'delete'), help='HTTP method to use.') def browse(args): """ Print the GitHub API response at the given URL """ with cli.catch_api_errors(): client = GithubAPIClient(nickname=args.github) res = client.request(args.method, args.url, _raise=False) print('HTTP/1.1 {0} {1}'.format(res.status_code, res.reason)) for k, v in res.headers.items(): print("{0}: {1}".format(k, v)) print() if res.json() is not None: print(json.dumps(res.json(), indent=2)) else: print(res.content) parser.set_default_command(browse) def main(): parser.dispatch() if __name__ == '__main__': main()
from __future__ import print_function import json from argh import ArghParser, arg from ghtools import cli from ghtools.api import GithubAPIClient parser = ArghParser(description="Browse the GitHub API") @arg('github', nargs='?', help='GitHub instance nickname (e.g "enterprise")') @arg('url', help='URL to browse') @arg('-m', '--method', default='get', choices=('get', 'delete'), help='HTTP method to use.') def browse(args): """ Print the GitHub API response at the given URL """ with cli.catch_api_errors(): client = GithubAPIClient(nickname=args.github) res = client.request(args.method, args.url, _raise=False) print('HTTP/1.1 {0} {1}'.format(res.status_code, res.reason)) for k, v in res.headers.items(): print("{0}: {1}".format(k, v)) print() if res.json() is not None: print(json.dumps(res.json, indent=2)) else: print(res.content) parser.set_default_command(browse) def main(): parser.dispatch() if __name__ == '__main__': main()
Use domain name instead of localhost when it's available to make webpack works with local domain names
process.traceDeprecation = true; const path = require('path'); const webpack = require('webpack'); const WebpackCommon = require('./webpack.common'); const BundleTracker = require('webpack-bundle-tracker'); var isPublicDomainDefined = process.env.KOBOFORM_PUBLIC_SUBDOMAIN && process.env.PUBLIC_DOMAIN_NAME; var publicDomain = isPublicDomainDefined ? process.env.KOBOFORM_PUBLIC_SUBDOMAIN + '.' + process.env.PUBLIC_DOMAIN_NAME : 'localhost'; var publicPath = 'http://' + publicDomain + ':3000/static/compiled/'; module.exports = WebpackCommon({ mode: "development", entry: { app: ['react-hot-loader/patch', './jsapp/js/main.es6'], tests: path.resolve(__dirname, '../test/index.js') }, output: { library: 'KPI', path: path.resolve(__dirname, '../jsapp/compiled/'), publicPath: publicPath, filename: "[name]-[hash].js" }, devServer: { publicPath: publicPath, disableHostCheck: true, hot: true, headers: {'Access-Control-Allow-Origin': '*'}, port: 3000, host: '0.0.0.0' }, plugins: [ new BundleTracker({path: __dirname, filename: '../webpack-stats.json'}), new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin() ] });
process.traceDeprecation = true; const path = require('path'); const webpack = require('webpack'); const WebpackCommon = require('./webpack.common'); const BundleTracker = require('webpack-bundle-tracker'); var publicPath = 'http://kpi.kobo.local:3000/static/compiled/'; module.exports = WebpackCommon({ mode: "development", entry: { app: ['react-hot-loader/patch', './jsapp/js/main.es6'], tests: path.resolve(__dirname, '../test/index.js') }, output: { library: 'KPI', path: path.resolve(__dirname, '../jsapp/compiled/'), publicPath: publicPath, filename: "[name]-[hash].js" }, devServer: { publicPath: publicPath, disableHostCheck: true, hot: true, headers: {'Access-Control-Allow-Origin': '*'}, port: 3000, host: '0.0.0.0' }, plugins: [ new BundleTracker({path: __dirname, filename: '../webpack-stats.json'}), new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin() ] });
Update example to allow downgrading to http1
var path = require('path'); var fs = require('fs'); var pino = require('pino'); var restify = require('../../lib'); var srv = restify.createServer({ http2: { cert: fs.readFileSync(path.join(__dirname, './keys/http2-cert.pem')), key: fs.readFileSync(path.join(__dirname, './keys/http2-key.pem')), ca: fs.readFileSync(path.join(__dirname, 'keys/http2-csr.pem')), allowHTTP1: true //allow incoming connections that do not support HTTP/2 to be downgraded to HTTP/1.x } }); srv.get('/', function(req, res, next) { res.send({ hello: 'world' }); next(); }); srv.on( 'after', restify.plugins.auditLogger({ event: 'after', body: true, log: pino( { name: 'audit' }, process.stdout ) }) ); srv.listen(8080, function() { console.log('ready on %s', srv.url); });
var path = require('path'); var fs = require('fs'); var pino = require('pino'); var restify = require('../../lib'); var srv = restify.createServer({ http2: { cert: fs.readFileSync(path.join(__dirname, './keys/http2-cert.pem')), key: fs.readFileSync(path.join(__dirname, './keys/http2-key.pem')), ca: fs.readFileSync(path.join(__dirname, 'keys/http2-csr.pem')) } }); srv.get('/', function(req, res, next) { res.send({ hello: 'world' }); next(); }); srv.on( 'after', restify.plugins.auditLogger({ event: 'after', body: true, log: pino( { name: 'audit' }, process.stdout ) }) ); srv.listen(8080, function() { console.log('ready on %s', srv.url); });
Improve message in version command when it cannot get server version
package io.digdag.cli.client; import io.digdag.cli.SystemExitException; import io.digdag.client.DigdagClient; import java.util.Map; import static io.digdag.cli.SystemExitException.systemExit; public class Version extends ClientCommand { @Override public void mainWithClientException() throws Exception { ln("Client version: " + version); try { DigdagClient client = buildClient(false); Map<String, Object> remoteVersion = client.getVersion(); ln("Server version: " + remoteVersion.getOrDefault("version", "")); } catch (Exception e) { ln("An error happened during getting Server version."); throw e; } } @Override public SystemExitException usage(String error) { err.println("Usage: " + programName + " version"); err.println(" Options:"); showCommonOptions(); return systemExit(error); } }
package io.digdag.cli.client; import io.digdag.cli.SystemExitException; import io.digdag.client.DigdagClient; import java.util.Map; import static io.digdag.cli.SystemExitException.systemExit; public class Version extends ClientCommand { @Override public void mainWithClientException() throws Exception { DigdagClient client = buildClient(false); Map<String, Object> remoteVersion = client.getVersion(); ln("Client version: " + version); ln("Server version: " + remoteVersion.getOrDefault("version", "")); } @Override public SystemExitException usage(String error) { err.println("Usage: " + programName + " version"); err.println(" Options:"); showCommonOptions(); return systemExit(error); } }
Add generic Python 3 trove classifier
from setuptools import setup setup( name='tangled.mako', version='0.1a3.dev0', description='Tangled Mako integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.mako/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', include_package_data=True, packages=[ 'tangled', 'tangled.mako', 'tangled.mako.tests', ], install_requires=[ 'tangled.web>=0.1a5', 'Mako>=0.9.1', ], extras_require={ 'dev': [ 'tangled.web[dev]>=0.1a5', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
from setuptools import setup setup( name='tangled.mako', version='0.1a3.dev0', description='Tangled Mako integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', download_url='https://github.com/TangledWeb/tangled.mako/tags', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', include_package_data=True, packages=[ 'tangled', 'tangled.mako', 'tangled.mako.tests', ], install_requires=[ 'tangled.web>=0.1a5', 'Mako>=0.9.1', ], extras_require={ 'dev': [ 'tangled.web[dev]>=0.1a5', ], }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], )
Make SVG dimensions normalized and remove width and height attrs.
// @flow import { NARROW_SPACE, WIDE_SPACE, NARROW_BAR, WIDE_BAR } from "../Core/Characters" const NARROW_WIDTH = 1 const WIDE_WIDTH = 3 export function rect(x: number, wide: boolean, filled: boolean): string { return `<rect x="${x}" y="0" width="${wide ? WIDE_WIDTH : NARROW_WIDTH}" height="1" fill="${filled ? "black" : "white"}"/>` } export function renderBarcodeToSVG(input: string): string { let svg = "" let x = 0 for (const char of input) { switch (char) { case NARROW_SPACE: svg += rect(x, false, false) x += NARROW_WIDTH break case WIDE_SPACE: svg += rect(x, true, false) x += WIDE_WIDTH break case NARROW_BAR: svg += rect(x, false, true) x += NARROW_WIDTH break case WIDE_BAR: svg += rect(x, true, true) x += WIDE_WIDTH break } } return `<svg viewBox="0 0 ${x} 1">${svg}</svg>` }
// @flow import { NARROW_SPACE, WIDE_SPACE, NARROW_BAR, WIDE_BAR } from "../Core/Characters" export function rect(x: number, height: number, width: number, filled: boolean): string { return `<rect x="${x}" y="0" width="${width}" height="${height}" fill="${filled ? "black" : "white"}"/>` } export function renderBarcodeToSVG(input: string, height: number, baseWidth: number): string { let svg = "" let x = 0 for (const char of input) { switch (char) { case NARROW_SPACE: svg += rect(x, height, baseWidth, false) x += baseWidth break case WIDE_SPACE: svg += rect(x, height, baseWidth * 3, false) x += baseWidth * 3 break case NARROW_BAR: svg += rect(x, height, baseWidth, true) x += baseWidth break case WIDE_BAR: svg += rect(x, height, baseWidth * 3, true) x += baseWidth * 3 break } } return `<svg viewBox="0 0 ${x} ${height}">${svg}</svg>` }
Fix trait, methods are declared as abstract instead of inside docblock
<?php namespace GenericCollections\Traits; /** * This methods apply to BaseCollectionInterface and * its shared between all the different AbstractCollections like * AbstractCollection and AbstractMap * * This methods are declared to avoid warnings * * @package GenericCollections\Traits */ trait CollectionMethods { abstract public function getElementType(); abstract public function add($element); abstract public function contains($element); public function addAll(array $elements) { $added = false; foreach ($elements as $element) { $added = $this->add($element) || $added; } return $added; } public function containsAll(array $elements) { foreach ($elements as $element) { if (! $this->contains($element)) { return false; } } return true; } public function containsAny(array $elements) { foreach ($elements as $element) { if ($this->contains($element)) { return true; } } return false; } }
<?php namespace GenericCollections\Traits; /** * This methods apply to BaseCollectionInterface and * its shared between all the different AbstractCollections like * AbstractCollection and AbstractMap * * This methods are declared to avoid warnings * @method string getElementType() * @method bool add(mixed $element) * @method bool contains(array $elements) * * @package GenericCollections\Traits */ trait CollectionMethods { public function addAll(array $elements) { $added = false; foreach ($elements as $element) { $added = $this->add($element) || $added; } return $added; } public function containsAll(array $elements) { foreach ($elements as $element) { if (! $this->contains($element)) { return false; } } return true; } public function containsAny(array $elements) { foreach ($elements as $element) { if ($this->contains($element)) { return true; } } return false; } }
Check whether or not email is taken already upon registration
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; // use App\Http\Controllers\Controller; use App\Currency; use App\User; use Hash; class RegisterController extends Controller { public function index() { $currencies = Currency::all(); return view('register', compact('currencies')); } public function store(Request $request) { $request->validate([ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => 'required|confirmed', 'currency' => 'required' ]); $user = new User; $user->name = $request->name; $user->email = $request->email; $user->password = Hash::make($request->password); $user->currency_id = $request->currency; $user->language = 'en'; $user->save(); return redirect('/register'); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; // use App\Http\Controllers\Controller; use App\Currency; use App\User; use Hash; class RegisterController extends Controller { public function index() { $currencies = Currency::all(); return view('register', compact('currencies')); } public function store(Request $request) { $request->validate([ 'name' => 'required', 'email' => 'required|email', 'password' => 'required|confirmed', 'currency' => 'required' ]); $user = new User; $user->name = $request->name; $user->email = $request->email; $user->password = Hash::make($request->password); $user->currency_id = $request->currency; $user->language = 'en'; $user->save(); return redirect('/register'); } }
Fix comment; They were never runes
// See LICENSE.txt for licensing information. package main import ( "fmt" "strings" ) var ( SPINNER_STRINGS = []string{"◢ ", "◣ ", "◤ ", "◥ "} SPINNER_LEN = len(SPINNER_STRINGS) ) type Spinner struct { running bool // indiacte we're actually printing msg string // current message pos int // position in SPINNER_STRINGS last_len int // total length of last status } func (s *Spinner) Finish() { fmt.Println() s.running = false s.msg = "" s.pos = 0 s.last_len = 0 } func (s *Spinner) Tick() { if s.running { fmt.Print("\r", strings.Repeat(" ", s.last_len), "\r") } else { s.running = true } fmt.Print(SPINNER_STRINGS[s.pos]) fmt.Print(s.msg) s.pos = (s.pos + 1) % SPINNER_LEN s.last_len = 2 + len(s.msg) } func (s *Spinner) Msg(msg string) { s.msg = msg s.Tick() }
// See LICENSE.txt for licensing information. package main import ( "fmt" "strings" ) var ( SPINNER_STRINGS = []string{"◢ ", "◣ ", "◤ ", "◥ "} SPINNER_LEN = len(SPINNER_STRINGS) ) type Spinner struct { running bool // indiacte we're actually printing msg string // current message pos int // position in SPINNER_RUNES last_len int // total length of last status } func (s *Spinner) Finish() { fmt.Println() s.running = false s.msg = "" s.pos = 0 s.last_len = 0 } func (s *Spinner) Tick() { if s.running { fmt.Print("\r", strings.Repeat(" ", s.last_len), "\r") } else { s.running = true } fmt.Print(SPINNER_STRINGS[s.pos]) fmt.Print(s.msg) s.pos = (s.pos + 1) % SPINNER_LEN s.last_len = 2 + len(s.msg) } func (s *Spinner) Msg(msg string) { s.msg = msg s.Tick() }
Remove dead code from `getNamesFromPattern`.
"use strict"; exports.getNamesFromPattern = function (pattern) { var queue = [pattern]; var names = []; for (var i = 0; i < queue.length; ++i) { var pattern = queue[i]; switch (pattern.type) { case "Identifier": names.push(pattern.name); break; case "Property": case "ObjectProperty": queue.push(pattern.value); break; case "AssignmentPattern": queue.push(pattern.left); break; case "ObjectPattern": queue.push.apply(queue, pattern.properties); break; case "ArrayPattern": queue.push.apply(queue, pattern.elements); break; case "RestElement": queue.push(pattern.argument); break; } } return names; };
"use strict"; exports.getNamesFromPattern = function (pattern) { var queue = [pattern]; var names = []; for (var i = 0; i < queue.length; ++i) { var pattern = queue[i]; if (! pattern) { continue; } switch (pattern.type) { case "Identifier": names.push(pattern.name); break; case "Property": case "ObjectProperty": queue.push(pattern.value); break; case "AssignmentPattern": queue.push(pattern.left); break; case "ObjectPattern": queue.push.apply(queue, pattern.properties); break; case "ArrayPattern": queue.push.apply(queue, pattern.elements); break; case "RestElement": queue.push(pattern.argument); break; } } return names; };
Allow Glazebrook to be executed in a multi-pass fashion + parallelise
#!/usr/bin/env python # -*- coding: utf-8 -*- """Produces IPHAS Data Release 2 using an MPI computing cluster.""" from IPython import parallel from astropy import log __author__ = 'Geert Barentsen' # Create the cluster view client = parallel.Client('/home/gb/.config/ipython/profile_mpi/security/ipcontroller-seaming-client.json') cluster = client[:] log.info('Using {0} cores'.format(len(cluster))) # Sync imports across all nodes with client[:].sync_imports(): # Make sure the IPHAS DR2 module is in the path import os import sys sys.path.append('/home/gb/dev/iphas-dr2') client[:].execute("sys.path.append('/home/gb/dev/iphas-dr2')", block=True) # Import DR2 generation modules from dr2 import constants from dr2 import seaming from dr2 import concatenating client[:].execute('reload(constants)', block=True) client[:].execute('reload(seaming)', block=True) client[:].execute('reload(concatenating)', block=True) #seaming.seam(cluster) concatenating.concatenate(client[0,4,8,12])
#!/usr/bin/env python # -*- coding: utf-8 -*- """Produces IPHAS Data Release 2 using an MPI computing cluster.""" from IPython import parallel from astropy import log __author__ = 'Geert Barentsen' # Create the cluster view client = parallel.Client('/home/gb/.config/ipython/profile_mpi/security/ipcontroller-seaming-client.json') cluster = client[:] log.info('Using {0} cores'.format(len(cluster))) # Sync imports across all nodes with client[:].sync_imports(): # Make sure the IPHAS DR2 module is in the path import os import sys sys.path.append('/home/gb/dev/iphas-dr2') client[:].execute("sys.path.append('/home/gb/dev/iphas-dr2')", block=True) # Import DR2 generation modules from dr2 import constants from dr2 import seaming from dr2 import concatenating client[:].execute('reload(constants)', block=True) client[:].execute('reload(seaming)', block=True) client[:].execute('reload(concatenating)', block=True) seaming.seam(cluster) #concatenating.concatenate(cluster)
Update example autograding code to use heading names
from nose.tools import eq_ as assert_eq @score(problem="Problem 1/Part A", points=0.5) def grade_hello1(): """Grade 'hello' with input 'Jessica'""" msg = hello("Jessica") assert_eq(msg, "Hello, Jessica!") @score(problem="Problem 1/Part A", points=0.5) def grade_hello2(): """Grade 'hello' with input 'Python'""" msg = hello("Python") assert_eq(msg, "Hello, Python!") @score(problem="Problem 1/Part B", points=0.5) def grade_goodbye1(): """Grade 'goodbye' with input 'Jessica'""" msg = goodbye("Jessica") assert_eq(msg, "Goodbye, Jessica") @score(problem="Problem 1/Part B", points=0.5) def grade_goodbye2(): """Grade 'goodbye' with input 'Python'""" msg = goodbye("Python") assert_eq(msg, "Goodbye, Python")
from nose.tools import eq_ as assert_eq @score(problem="hello", points=0.5) def grade_hello1(): """Grade 'hello' with input 'Jessica'""" msg = hello("Jessica") assert_eq(msg, "Hello, Jessica!") @score(problem="hello", points=0.5) def grade_hello2(): """Grade 'hello' with input 'Python'""" msg = hello("Python") assert_eq(msg, "Hello, Python!") @score(problem="goodbye", points=0.5) def grade_goodbye1(): """Grade 'goodbye' with input 'Jessica'""" msg = goodbye("Jessica") assert_eq(msg, "Goodbye, Jessica") @score(problem="goodbye", points=0.5) def grade_goodbye2(): """Grade 'goodbye' with input 'Python'""" msg = goodbye("Python") assert_eq(msg, "Goodbye, Python")
:bug: Fix a bug affecting shared workers
'use babel' import {Disposable, CompositeDisposable} from 'sb-event-kit' import Communication from 'sb-communication' class Exchange { constructor(worker) { this.worker = worker this.port = worker.port || worker this.communication = new Communication() this.subscriptions = new CompositeDisposable() this.subscriptions.add(this.communication) const callback = message => { this.communication.parseMessage(message.data) } this.port.addEventListener('message', callback) this.subscriptions.add(new Disposable(() => { this.port.removeEventListener('message', callback) })) this.communication.onShouldSend(message => { this.port.postMessage(message) }) this.onRequest('ping', function(_, message) { message.response = 'pong' }) } request(name, data = {}) { return this.communication.request(name, data) } onRequest(name, callback) { return this.communication.onRequest(name, callback) } terminate() { this.worker.terminate() this.dispose() } dispose() { this.subscriptions.dispose() } static create(filePath) { return new Exchange(new Worker(filePath)) } static createShared(filePath) { const worker = new SharedWorker(filePath) const exchange = new Exchange(worker) worker.port.start() return exchange } } module.exports = Exchange
'use babel' import {Disposable, CompositeDisposable} from 'sb-event-kit' import Communication from 'sb-communication' class Exchange { constructor(worker) { this.worker = worker this.port = worker.port || worker this.communication = new Communication() this.subscriptions = new CompositeDisposable() this.subscriptions.add(this.communication) const callback = message => { this.communication.parseMessage(message.data) } this.worker.addEventListener('message', callback) this.subscriptions.add(new Disposable(() => { this.worker.removeEventListener('message', callback) })) this.communication.onShouldSend(message => { this.port.postMessage(message) }) this.onRequest('ping', function(_, message) { message.response = 'pong' }) this.request('ping') } request(name, data = {}) { return this.communication.request(name, data) } onRequest(name, callback) { return this.communication.onRequest(name, callback) } terminate() { this.worker.terminate() this.dispose() } dispose() { this.subscriptions.dispose() } static create(filePath) { return new Exchange(new Worker(filePath)) } static createShared(filePath) { const worker = new SharedWorker(filePath) worker.port.start() return new Exchange(worker) } } module.exports = Exchange
Improve security by creating a much stronger secret by default Webs using vkwf are not effected by this as they use hashPrivatePart config setting
<?php class Kwf_Util_Hash { public static function getPrivatePart() { $salt = Kwf_Cache_SimpleStatic::fetch('hashpp-'); if (!$salt) { if ($salt = Kwf_Config::getValue('hashPrivatePart')) { //defined in config, required if multiple webservers should share the same salt } else { $hashFile = 'cache/hashprivatepart'; if (!file_exists($hashFile)) { if (!function_exists('random_bytes')) { require 'vendor/paragonie/random_compat/lib/random.php'; } file_put_contents($hashFile, bin2hex(random_bytes(32))); } $salt = file_get_contents($hashFile); Kwf_Cache_SimpleStatic::add('hashpp-', $salt); } } return $salt; } public static function hash($str) { return md5(self::getPrivatePart().$str); } }
<?php class Kwf_Util_Hash { public static function getPrivatePart() { $salt = Kwf_Cache_SimpleStatic::fetch('hashpp-'); if (!$salt) { if ($salt = Kwf_Config::getValue('hashPrivatePart')) { //defined in config, required if multiple webservers should share the same salt } else { $hashFile = 'cache/hashprivatepart'; if (!file_exists($hashFile)) { file_put_contents($hashFile, time().rand(100000, 1000000)); } $salt = file_get_contents($hashFile); Kwf_Cache_SimpleStatic::add('hashpp-', $salt); } } return $salt; } public static function hash($str) { return md5(self::getPrivatePart().$str); } }
Fix code style for custom attribute value
# Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: laran@reciprocitylabs.com # Maintained By: laran@reciprocitylabs.com from ggrc import db from ggrc.models.mixins import Base from ggrc.models.mixins import deferred class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column(db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' ]
# Copyright (C) 2014 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: laran@reciprocitylabs.com # Maintained By: laran@reciprocitylabs.com from ggrc import db from .mixins import ( deferred, Base ) class CustomAttributeValue(Base, db.Model): __tablename__ = 'custom_attribute_values' custom_attribute_id = deferred( db.Column( db.Integer, db.ForeignKey('custom_attribute_definitions.id')), 'CustomAttributeValue') attributable_id = deferred(db.Column(db.Integer), 'CustomAttributeValue') attributable_type = deferred(db.Column(db.String), 'CustomAttributeValue') attribute_value = deferred(db.Column(db.String), 'CustomAttributeValue') @property def attributable_attr(self): return '{0}_attributable'.format(self.attributable_type) @property def attributable(self): return getattr(self, self.attributable_attr) @attributable.setter def attributable(self, value): self.attributable_id = value.id if value is not None else None self.attributable_type = value.__class__.__name__ if value is not None \ else None return setattr(self, self.attributable_attr, value) _publish_attrs = [ 'custom_attribute_id', 'attributable_id', 'attributable_type', 'attribute_value' ]
Change the order of execution of various commands
<?php namespace Rafni\LaravelToolkit\Console\Scaffolding; use Illuminate\Console\Command; class PackageBuilder extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'toolkit:package {name : Name of the service package in singular}'; /** * The console command description. * * @var string */ protected $description = 'Create a new service package'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->call('toolkit:model', ['name' => $this->argument('name')]); $this->call('toolkit:migration', ['name' => $this->argument('name')]); $this->call('toolkit:contract', ['name' => $this->argument('name')]); $this->call('toolkit:service', ['name' => $this->argument('name')]); $this->call('toolkit:controller', ['name' => $this->argument('name')]); $this->call('toolkit:views', ['name' => $this->argument('name')]); $this->call('toolkit:routes', ['name' => $this->argument('name')]); } }
<?php namespace Rafni\LaravelToolkit\Console\Scaffolding; use Illuminate\Console\Command; class PackageBuilder extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'toolkit:package {name : Name of the service package in singular}'; /** * The console command description. * * @var string */ protected $description = 'Create a new service package'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->call('toolkit:model', ['name' => $this->argument('name')]); $this->call('toolkit:migration', ['name' => $this->argument('name')]); $this->call('toolkit:contract', ['name' => $this->argument('name')]); $this->call('toolkit:service', ['name' => $this->argument('name')]); $this->call('toolkit:controller', ['name' => $this->argument('name')]); $this->call('toolkit:routes', ['name' => $this->argument('name')]); $this->call('toolkit:views', ['name' => $this->argument('name')]); } }
Fix the path to fake database data
import json from meetup_facebook_bot import server from meetup_facebook_bot.models import base, talk, speaker base.Base.metadata.create_all(bind=server.engine) session = server.Session() # This part of the script provides the app with mockup data # TODO: replace it with actually working method json_talks = [] with open('meetup_facebook_bot/example_talks.json') as json_file: json_talks = json.load(json_file) for fake_facebook_id, json_talk in enumerate(json_talks): fake_speaker = speaker.Speaker(facebook_id=fake_facebook_id, name=json_talk['speaker']) fake_talk = talk.Talk( title=json_talk['title'], description=json_talk['description'], speaker_facebook_id=fake_speaker.facebook_id ) session.add(fake_speaker) session.add(fake_talk) session.commit() print('DB created!')
import json from meetup_facebook_bot import server from meetup_facebook_bot.models import base, talk, speaker base.Base.metadata.create_all(bind=server.engine) session = server.Session() # This part of the script provides the app with mockup data # TODO: replace it with actually working method json_talks = [] with open('app/example_talks.json') as json_file: json_talks = json.load(json_file) for fake_facebook_id, json_talk in enumerate(json_talks): fake_speaker = speaker.Speaker(facebook_id=fake_facebook_id, name=json_talk['speaker']) fake_talk = talk.Talk( title=json_talk['title'], description=json_talk['description'], speaker_facebook_id=fake_speaker.facebook_id ) session.add(fake_speaker) session.add(fake_talk) session.commit() print('DB created!')
Fix task to output coverage for every files
var es = require("event-stream"); var path = require("path"); "use strict"; var istanbul = require("istanbul"); var hook = istanbul.hook; var Report = istanbul.Report; var Collector = istanbul.Collector; var instrumenter = new istanbul.Instrumenter(); var plugin = module.exports = function () { var fileMap = {}; hook.hookRequire(function (path) { return !!fileMap[path]; }, function (code, path) { return fileMap[path]; }); return es.map(function (file, cb) { if (!file.contents instanceof Buffer) { return cb(new Error("gulp-istanbul: streams not supported"), undefined); } instrumenter.instrument(file.contents.toString(), file.path, function (err, code) { if (!err) file.contents = new Buffer(code); fileMap[file.path] = file.contents.toString(); cb(err, file); }); }); }; plugin.writeReports = function (dir) { dir = dir || path.join(process.cwd(), "coverage"); return es.through(function () {}, function () { var collector = new Collector(); collector.add(global.__coverage__); var reports = [ Report.create("lcov", { dir: dir }), Report.create("text"), Report.create("text-summary") ]; reports.forEach(function (report) { report.writeReport(collector, true); }) }); };
var es = require("event-stream"); var path = require("path"); "use strict"; var istanbul = require("istanbul"); var hook = istanbul.hook; var Report = istanbul.Report; var Collector = istanbul.Collector; var instrumenter = new istanbul.Instrumenter(); var plugin = module.exports = function (param) { function createMatcher(path) { return function (requestedPath) { return path === requestedPath; }; } function bypassContent(code) { return function() { return String(code); }; } return es.map(function (file, cb) { if (!file.contents instanceof Buffer) { return cb(new Error("gulp-istanbul: streams not supported"), undefined); } instrumenter.instrument(String(file.contents), file.path, function(err, code) { if (!err) file.contents = new Buffer(code); hook.hookRequire(createMatcher(file.path), bypassContent(file.contents)); cb(err, file); }); }); }; plugin.writeReports = function (dir) { dir = dir || path.join(process.cwd(), "coverage"); var collector = new Collector(); collector.add(global.__coverage__); var reports = [ Report.create("lcov", { dir: dir }), Report.create("text"), Report.create("text-summary") ]; reports.forEach(function (report) { report.writeReport(collector, true); }) };
REF: Isolate import error to DataBroker.
import warnings import logging logger = logging.getLogger(__name__) try: from .databroker import DataBroker except ImportError: warnings.warn("The top-level functions (get_table, get_events, etc.)" "cannot be created because " "the necessary configuration was not found.") else: from .databroker import (DataBroker, DataBroker as db, get_events, get_table, stream, get_fields, restream, process) from .pims_readers import get_images from .handler_registration import register_builtin_handlers # register all built-in filestore handlers register_builtin_handlers() del register_builtin_handlers from .broker import Broker, ArchiverPlugin # set version string using versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions
import warnings import logging logger = logging.getLogger(__name__) try: from .databroker import (DataBroker, DataBroker as db, get_events, get_table, stream, get_fields, restream, process) from .pims_readers import get_images from .handler_registration import register_builtin_handlers # register all built-in filestore handlers register_builtin_handlers() del register_builtin_handlers except ImportError: warnings.warn("The top-level functions (get_table, get_events, etc.)" "cannot be created because " "the necessary configuration was not found.") from .broker import Broker, ArchiverPlugin # set version string using versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions
Rename mana level to mana pool
import React from 'react'; import PropTypes from 'prop-types'; import ManaLevelGraph from 'Main/ManaLevelGraph'; import ManaUsageGraph from 'Main/ManaUsageGraph'; const Mana = ({ parser }) => ( <div> <h1>Mana pool</h1> <ManaLevelGraph reportCode={parser.report.code} actorId={parser.playerId} start={parser.fight.start_time} end={parser.fight.end_time} manaUpdates={parser.modules.manaValues.manaUpdates} currentTimestamp={parser.currentTimestamp} /> {/* the currentTimestamp makes sure the Mana tab re-renders after parsing events*/} <h1>Mana usage</h1> <ManaUsageGraph start={parser.fight.start_time} end={parser.fight.end_time} healingBySecond={parser.modules.healingDone.bySecond} manaUpdates={parser.modules.manaValues.manaUpdates} timestamp={parser.currentTimestamp} /> {/* the currentTimestamp makes sure the Mana tab re-renders after parsing events*/} </div> ); Mana.propTypes = { parser: PropTypes.object.isRequired, }; export default Mana;
import React from 'react'; import PropTypes from 'prop-types'; import ManaLevelGraph from 'Main/ManaLevelGraph'; import ManaUsageGraph from 'Main/ManaUsageGraph'; const Mana = ({ parser }) => ( <div> <h1>Mana level</h1> <ManaLevelGraph reportCode={parser.report.code} actorId={parser.playerId} start={parser.fight.start_time} end={parser.fight.end_time} manaUpdates={parser.modules.manaValues.manaUpdates} currentTimestamp={parser.currentTimestamp} /> {/* the currentTimestamp makes sure the Mana tab re-renders after parsing events*/} <h1>Mana usage</h1> <ManaUsageGraph start={parser.fight.start_time} end={parser.fight.end_time} healingBySecond={parser.modules.healingDone.bySecond} manaUpdates={parser.modules.manaValues.manaUpdates} timestamp={parser.currentTimestamp} /> {/* the currentTimestamp makes sure the Mana tab re-renders after parsing events*/} </div> ); Mana.propTypes = { parser: PropTypes.object.isRequired, }; export default Mana;
Switch to Iriscouch in production
var cradle = require('cradle'); var applyDesignDocuments = require('./design-documents'); var couchLocation = process.env.IRISCOUCH; // var couchLocation = process.env.CLOUDANT_URL || process.env.COUCHDB || 'http://localhost'; var couch = new(cradle.Connection)(couchLocation, 5984, { cache: true, raw: false }); var db = couch.database('emergencybadges'); db.setup = function (callback) { db.exists(function (err, exists) { if (err) { console.log('error', err); } else if (exists) { console.log('Database exists.'); if (typeof callback === 'function') callback(); } else { console.log('Database does not exist. Creating.'); db.create(function (err, res) { if (!err) { applyDesignDocuments(db); if (typeof callback === 'function') callback(); } }); } }); }; db.updateDesignDocuments = function (callback) { applyDesignDocuments(db); if (typeof callback === 'function') callback(); }; module.exports = db;
var cradle = require('cradle'); var applyDesignDocuments = require('./design-documents'); var couchLocation = process.env.CLOUDANT_URL || process.env.COUCHDB || 'http://localhost'; var couch = new(cradle.Connection)(couchLocation, 5984, { cache: true, raw: false }); var db = couch.database('emergencybadges'); db.setup = function (callback) { db.exists(function (err, exists) { if (err) { console.log('error', err); } else if (exists) { console.log('Database exists.'); if (typeof callback === 'function') callback(); } else { console.log('Database does not exist. Creating.'); db.create(function (err, res) { if (!err) { applyDesignDocuments(db); if (typeof callback === 'function') callback(); } }); } }); }; db.updateDesignDocuments = function (callback) { applyDesignDocuments(db); if (typeof callback === 'function') callback(); }; module.exports = db;