text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix alert change type controller test
<?php namespace Ilios\CoreBundle\Tests\DataLoader; class AlertChangeTypeData extends AbstractDataLoader { protected function getData() { $arr = array(); $arr[] = array( 'id' => 1, 'title' => $this->faker->text(25), 'alerts' => ['1', '2'] ); $arr[] = array( 'id' => 2, 'title' => $this->faker->text(25), 'alerts' => [] ); return $arr; } public function create() { return [ 'id' => 3, 'title' => $this->faker->text(10), 'alerts' => [] ]; } public function createInvalid() { return [ 'id' => $this->faker->text, 'alerts' => [424524] ]; } }
<?php namespace Ilios\CoreBundle\Tests\DataLoader; class AlertChangeTypeData extends AbstractDataLoader { protected function getData() { $arr = array(); $arr[] = array( 'id' => 1, 'title' => $this->faker->text(25), 'alerts' => ['1'] ); $arr[] = array( 'id' => 2, 'title' => $this->faker->text(25), 'alerts' => [] ); return $arr; } public function create() { return [ 'id' => 3, 'title' => $this->faker->text(10), 'alerts' => [] ]; } public function createInvalid() { return [ 'id' => $this->faker->text, 'alerts' => [424524] ]; } }
Fix typo in the HelpPage module
(function (h) { 'use strict'; function HelpPage(chromeTabs, extensionURL) { this.showHelpForError = function (tab, error) { if (error instanceof h.LocalFileError) { return this.showLocalFileHelpPage(tab); } else if (error instanceof h.NoFileAccessError) { return this.showNoFileAccessHelpPage(tab); } throw new Error('showHelpForError does not support the error: ' + error.message); }; this.showLocalFileHelpPage = showHelpPage.bind(null, 'local-file'); this.showNoFileAccessHelpPage = showHelpPage.bind(null, 'no-file-access'); // Render the help page. The helpSection should correspond to the id of a // section within the help page. function showHelpPage(helpSection, tab) { chromeTabs.update(tab.id, { url: extensionURL('/help/permissions.html#' + helpSection) }); } } h.HelpPage = HelpPage; })(window.h || (window.h = {}));
(function (h) { 'use strict'; function HelpPage(chromeTabs, extensionURL) { this.showHelpForError = function (tab, error) { if (error instanceof h.LocalFileError) { return this.showLocalFileHelpPage(tab); } else if (error instanceof h.NoFileAccessError) { return this.showNoFileAccessHelpPage(tab); } throw new Error('showHelpForError does not support the error: ' + e.message); }; this.showLocalFileHelpPage = showHelpPage.bind(null, 'local-file'); this.showNoFileAccessHelpPage = showHelpPage.bind(null, 'no-file-access'); // Render the help page. The helpSection should correspond to the id of a // section within the help page. function showHelpPage(helpSection, tab) { chromeTabs.update(tab.id, { url: extensionURL('/help/permissions.html#' + helpSection) }); } } h.HelpPage = HelpPage; })(window.h || (window.h = {}));
Make use of MarkdownLanguageConfig constants
package flow.netbeans.markdown; import flow.netbeans.markdown.csl.MarkdownLanguageConfig; import flow.netbeans.markdown.highlighter.MarkdownLanguageHierarchy; import flow.netbeans.markdown.highlighter.MarkdownTokenId; import org.netbeans.api.lexer.InputAttributes; import org.netbeans.api.lexer.Language; import org.netbeans.api.lexer.LanguagePath; import org.netbeans.api.lexer.Token; import org.netbeans.spi.lexer.LanguageEmbedding; import org.netbeans.spi.lexer.LanguageProvider; @org.openide.util.lookup.ServiceProvider(service = org.netbeans.spi.lexer.LanguageProvider.class) public class MarkdownLanguageProvider extends LanguageProvider { @Override public Language<MarkdownTokenId> findLanguage(String mimeType) { if (MarkdownLanguageConfig.MIME_TYPE.equals(mimeType)) { return new MarkdownLanguageHierarchy().language(); } return null; } @Override public LanguageEmbedding<?> findLanguageEmbedding( Token arg0, LanguagePath arg1, InputAttributes arg2) { return null; } }
package flow.netbeans.markdown; import org.netbeans.api.lexer.InputAttributes; import org.netbeans.api.lexer.Language; import org.netbeans.api.lexer.LanguagePath; import org.netbeans.api.lexer.Token; import org.netbeans.spi.lexer.LanguageEmbedding; import org.netbeans.spi.lexer.LanguageProvider; import flow.netbeans.markdown.highlighter.MarkdownLanguageHierarchy; import flow.netbeans.markdown.highlighter.MarkdownTokenId; @org.openide.util.lookup.ServiceProvider(service = org.netbeans.spi.lexer.LanguageProvider.class) public class MarkdownLanguageProvider extends LanguageProvider { public Language<MarkdownTokenId> findLanguage(String mimeType) { if ("text/x-markdown".equals(mimeType)) { return new MarkdownLanguageHierarchy().language(); } return null; } @Override public LanguageEmbedding<?> findLanguageEmbedding( Token arg0, LanguagePath arg1, InputAttributes arg2) { return null; } }
Fix logos on 'Browse' page ('/directory')
'use strict'; import React from 'react'; import { browserHistory } from 'react-router'; import EnterpriseSummary from './EnterpriseSummaryComponent.js'; class DirectoryComponent extends React.Component { render() { var directory = this.props.directory, jsx = [], app = this; // Directory hasn't loaded yet, display 'loading' notice if (directory === null) { jsx.push(<li key="loading" >Loading...</li>); } else { jsx.push( directory.map(function(enterprise) { return ( <li className='directory-item' key={enterprise.id}> <EnterpriseSummary enterprise={enterprise} api_root={app.props.config.api_root} /> </li> ); }) ); } return ( <div className="directory-component page"> <a className="back" onClick={browserHistory.goBack}>Back</a> <ol className="directory__list"> {jsx} </ol> </div> ); } } DirectoryComponent.displayName = 'DirectoryComponent'; // Uncomment properties you need // DirectoryComponent.propTypes = {}; // DirectoryComponent.defaultProps = {}; export default DirectoryComponent;
'use strict'; import React from 'react'; import { browserHistory } from 'react-router'; import EnterpriseSummary from './EnterpriseSummaryComponent.js'; class DirectoryComponent extends React.Component { render() { var directory = this.props.directory, jsx = []; // Directory hasn't loaded yet, display 'loading' notice if (directory === null) { jsx.push(<li>Loading...</li>); } else { jsx.push( directory.map(function(enterprise, index) { return ( <li className='directory-item' key={index}> <EnterpriseSummary enterprise={enterprise} /> </li> ); }) ); } return ( <div className="directory-component page"> <a className="back" onClick={browserHistory.goBack}>Back</a> <ol className="directory__list"> {jsx} </ol> </div> ); } } DirectoryComponent.displayName = 'DirectoryComponent'; // Uncomment properties you need // DirectoryComponent.propTypes = {}; // DirectoryComponent.defaultProps = {}; export default DirectoryComponent;
Add pyscopg2 to list of dependencies
#!/usr/bin/evn python2 from setuptools import setup, find_packages setup(name='pprof', version='0.9.6', packages=find_packages(), install_requires=["SQLAlchemy==1.0.4", "cloud==2.8.5", "plumbum==1.4.2", "regex==2015.5.28", "wheel==0.24.0", "parse==1.6.6", "virtualenv==13.1.0", "sphinxcontrib-napoleon", "psycopg2"], author="Andreas Simbuerger", author_email="simbuerg@fim.uni-passau.de", description="This is the experiment driver for the pprof study", license="MIT", entry_points={ 'console_scripts': ['pprof=pprof.driver:main'] })
#!/usr/bin/evn python2 from setuptools import setup, find_packages setup(name='pprof', version='0.9.6', packages=find_packages(), install_requires=["SQLAlchemy==1.0.4", "cloud==2.8.5", "plumbum==1.4.2", "regex==2015.5.28", "wheel==0.24.0", "parse==1.6.6", "virtualenv==13.1.0", "sphinxcontrib-napoleon"], author="Andreas Simbuerger", author_email="simbuerg@fim.uni-passau.de", description="This is the experiment driver for the pprof study", license="MIT", entry_points={ 'console_scripts': ['pprof=pprof.driver:main'] })
Use jshint option for mozilla addons
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), less: { development: { files: { "data/css/sidebar.css": "data/css/sidebar.less" }, options: {} } }, jshint: { options: { moz: true }, all: ['Gruntfile.js', 'index.js', 'data/**/*.js', 'test/**/*.js'] } }); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-jshint'); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), less: { development: { files: { "data/css/sidebar.css": "data/css/sidebar.less" }, options: {} } }, jshint: { all: ['Gruntfile.js', 'index.js', 'data/**/*.js', 'test/**/*.js'] } }); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-jshint'); };
Trim code a little more
import _ from './utils'; function getTransitions(value) { if (_.isArray(value)) return value; if (_.isObject(value)) return value.transitions; } export default { has: (value = {}, conditions = {}) => { return !!_.find(getTransitions(value), conditions); }, find: (value = {}, conditions = {}) => { return _.find(getTransitions(value), conditions); }, filter: (value = {}, conditions = {}) => { return _.filter(getTransitions(value), conditions); }, metaAttributes: (obj = {}) => { if (!_.isObject(obj)) return {}; if (!_.isObject(obj.meta)) return {}; return obj.meta.attributes || {}; }, metaLinks: (obj = {}) => { if (!_.isObject(obj)) return []; if (!_.isObject(obj.meta)) return []; return obj.meta.links || []; }, attributes: (obj = {}) => { if (!_.isObject(obj)) return {}; return obj.attributes || {}; }, transitions: (obj = {}) => { if (!_.isObject(obj)) return []; return obj.transitions || []; }, get: _.get, };
import _ from './utils'; export default { has: (value = {}, conditions = {}) => { if (!_.isObject(conditions)) return false; if (_.isArray(value)) return !!_.find(value, conditions); if (_.isObject(value)) return !!_.find(value.transitions, conditions); return false; }, find: (value = {}, conditions = {}) => { if (!_.isObject(conditions) && typeof (conditions) !== 'function') return undefined; if (_.isArray(value)) return _.find(value, conditions); if (_.isObject(value)) return _.find(value.transitions, conditions); return undefined; }, filter: (value = {}, conditions = {}) => { if (!_.isObject(conditions) && typeof (conditions) !== 'function') return []; if (_.isArray(value)) return _.filter(value, conditions); if (_.isObject(value)) return _.filter(value.transitions, conditions); return []; }, metaAttributes: (obj = {}) => { if (!_.isObject(obj)) return {}; if (!_.isObject(obj.meta)) return {}; return obj.meta.attributes || {}; }, metaLinks: (obj = {}) => { if (!_.isObject(obj)) return []; if (!_.isObject(obj.meta)) return []; return obj.meta.links || []; }, attributes: (obj = {}) => { if (!_.isObject(obj)) return {}; return obj.attributes || {}; }, transitions: (obj = {}) => { if (!_.isObject(obj)) return []; return obj.transitions || []; }, get: _.get, };
Fix issue when root is being ignored if passed as an empty string.
// TODO: Make options linear. // Would make configuration more user friendly. 'use strict' var path = require('path') var packageName = 'chewingum' module.exports = function (options) { function n (pathString) { return path.normalize(pathString) } var opts = options || {} opts.location = (opts.location) ? opts.location : {} opts.extensions = (opts.extensions) ? opts.extensions : {} opts.location.src = n(opts.location.src || 'src/components/') opts.location.dest = n(opts.location.dest || 'dest/components/') opts.location.styleguide = n(opts.location.styleguide || 'node_modules/' + packageName + '/doc-template/') opts.extensions.template = opts.extensions.template || '.twig' opts.extensions.output = opts.extensions.output || '.html' /** * Set root folder * * If pattern library is not located at the root, it's possible to set different root folder * Default vale: '/' */ if (typeof opts.location.root !== 'undefined') { opts.location.root = (opts.location.root === '') ? '': n(opts.location.root) } else { opts.location.root = n('/') } /** * Navigation filter options * * Example = [ * { * "title": "Organisms", * "regex": "02-organisms" * }] */ opts.filterItems = opts.filterItems || {} return opts }
// TODO: Make options linear. // Would make configuration more user friendly. 'use strict' var path = require('path') var packageName = 'chewingum' module.exports = function (options) { function n (pathString) { return path.normalize(pathString) } var opts = options || {} opts.location = (opts.location) ? opts.location : {} opts.extensions = (opts.extensions) ? opts.extensions : {} opts.location.root = n(opts.location.root || '/') opts.location.src = n(opts.location.src || 'src/components/') opts.location.dest = n(opts.location.dest || 'dest/components/') opts.location.styleguide = n(opts.location.styleguide || 'node_modules/' + packageName + '/doc-template/') opts.extensions.template = opts.extensions.template || '.twig' opts.extensions.output = opts.extensions.output || '.html' /** * Navigation filter options * * Example = [ * { * "title": "Organisms", * "regex": "02-organisms" * }] */ opts.filterItems = opts.filterItems || {} return opts }
Add note createAction with sample data
<?php namespace AppBundle\Controller; use AppBundle\Entity\Note; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; class NoteController extends Controller { /** * @Route("/note") */ public function indexAction() { $notes = $this->getDoctrine() ->getRepository('AppBundle:Note') ->findAll(); return $this->render( 'note/index.html.twig', array('notes' => $notes) ); } /** * @Route("/note/{id}") * @ParamConverter("note", class="AppBundle:Note") */ public function showAction(Note $note) { } /** * @Route("/note/create") */ public function createAction() { $note = new Note(); $note->setContent('My very first note'); $em = $this->getDoctrine()->getManager(); $em->persist($note); $em->flush(); return new Response('Created note id '.$note->getId()); } }
<?php namespace AppBundle\Controller; use AppBundle\Entity\Note; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; class NoteController extends Controller { /** * @Route("/note") */ public function indexAction() { $notes = $this->getDoctrine() ->getRepository('AppBundle:Note') ->findAll(); return $this->render( 'note/index.html.twig', array('notes' => $notes) ); } /** * @Route("/note/{id}") * @ParamConverter("note", class="AppBundle:Note") */ public function showAction(Note $note) { } }
Fix url resolution with regards to querysting parameters.
<?php namespace Markup\OEmbedBundle\Client; use Markup\OEmbedBundle\Provider\ProviderInterface; /** * A superclass for client implementations. */ abstract class AbstractClient implements ClientInterface { /** * Resolves the media ID and an oEmbed provider to a URL. * * @param ProviderInterface $provider * @param string $mediaId * @param array $parameters * @return string **/ protected function resolveOEmbedUrl(ProviderInterface $provider, $mediaId, array $parameters = array()) { $mediaUrl = str_replace('$ID$', $mediaId, $provider->getUrlScheme()); $mediaUrlHasQueryString = (bool) parse_url($mediaUrl, PHP_URL_QUERY); $queryStingPrefix = ($mediaUrlHasQueryString) ? '&' : '?'; $queryStringSuffix = (!empty($parameters)) ? $queryStingPrefix . http_build_query($parameters) : ''; return sprintf( '%s?url=%s%s', $provider->getApiEndpoint(), $mediaUrl, rawurlencode($queryStringSuffix) ); } }
<?php namespace Markup\OEmbedBundle\Client; use Markup\OEmbedBundle\Provider\ProviderInterface; /** * A superclass for client implementations. */ abstract class AbstractClient implements ClientInterface { /** * Resolves the media ID and an oEmbed provider to a URL. * * @param ProviderInterface $provider * @param string $mediaId * @param array $parameters * @return string **/ protected function resolveOEmbedUrl(ProviderInterface $provider, $mediaId, array $parameters = array()) { $mediaUrl = str_replace('$ID$', $mediaId, $provider->getUrlScheme()); $queryStringSuffix = (!empty($parameters)) ? '?' . http_build_query($parameters) : ''; return sprintf('%s?url=%s%s', $provider->getApiEndpoint(), $mediaUrl, rawurlencode($queryStringSuffix)); } }
Correct IIFE global variable name
(function(global, f){ 'use strict'; /*istanbul ignore next*/ if(module && typeof module.exports !== 'undefined'){ module.exports = f( require('fluture'), require('sanctuary-def'), require('sanctuary-type-identifiers') ); }else{ global.flutureSanctuaryTypes = f( global.Fluture, global.sanctuaryDef, global.sanctuaryTypeIdentifiers ); } }(/*istanbul ignore next*/(global || window || this), function(Future, $, type){ 'use strict'; // $$type :: String var $$type = '@@type'; // FutureType :: (Type, Type) -> Type var FutureType = $.BinaryType( type.parse(Future[$$type]).name, 'https://github.com/fluture-js/Fluture#readme', Future.isFuture, Future.extractLeft, Future.extractRight ); // ConcurrentFutureType :: (Type, Type) -> Type var ConcurrentFutureType = $.BinaryType( type.parse(Future.Par[$$type]).name, 'https://github.com/fluture-js/Fluture#concurrentfuture', function(x){ return type(x) === Future.Par[$$type] }, function(f){ return Future.seq(f).extractLeft() }, function(f){ return Future.seq(f).extractRight() } ); return { FutureType: FutureType, ConcurrentFutureType: ConcurrentFutureType }; }));
(function(global, f){ 'use strict'; /*istanbul ignore next*/ if(module && typeof module.exports !== 'undefined'){ module.exports = f( require('fluture'), require('sanctuary-def'), require('sanctuary-type-identifiers') ); }else{ global.concurrify = f( global.Fluture, global.sanctuaryDef, global.sanctuaryTypeIdentifiers ); } }(/*istanbul ignore next*/(global || window || this), function(Future, $, type){ 'use strict'; // $$type :: String var $$type = '@@type'; // FutureType :: (Type, Type) -> Type var FutureType = $.BinaryType( type.parse(Future[$$type]).name, 'https://github.com/fluture-js/Fluture#readme', Future.isFuture, Future.extractLeft, Future.extractRight ); // ConcurrentFutureType :: (Type, Type) -> Type var ConcurrentFutureType = $.BinaryType( type.parse(Future.Par[$$type]).name, 'https://github.com/fluture-js/Fluture#concurrentfuture', function(x){ return type(x) === Future.Par[$$type] }, function(f){ return Future.seq(f).extractLeft() }, function(f){ return Future.seq(f).extractRight() } ); return { FutureType: FutureType, ConcurrentFutureType: ConcurrentFutureType }; }));
Add section session varialbes to facilitate redirects
from collections import namedtuple CONTENT_TYPES = [ ("core.ArticlePage", "Article"), ("core.SectionPage", "Section"), ] ENDPOINTS = [ ("page", "api/v1/pages") ] SESSION_VARS = namedtuple( "SESSION_VARS", ["first", "second", ] ) ARTICLE_SESSION_VARS = SESSION_VARS( first=("url", "article_content_type"), second="article_parent_page_id" ) SECTION_SESSION_VARS = SESSION_VARS( first=("url", "section_content_type"), second="section_parent_page_id" ) API_PAGES_ENDPOINT = "/api/v2/pages/" API_IMAGES_ENDPOINT = "/api/v2/images/" KEYS_TO_EXCLUDE = ["id", "meta", ] # Form error messages MAIN_IMPORT_FORM_MESSAGES = { "connection_error": "Please enter a valid URL.", "bad_request": "Please try again later.", }
from collections import namedtuple CONTENT_TYPES = [ ("core.ArticlePage", "Article"), ("core.SectionPage", "Section"), ] ENDPOINTS = [ ("page", "api/v1/pages") ] SESSION_VARS = namedtuple( "SESSION_VARS", ["first", "second", ] ) ARTICLE_SESSION_VARS = SESSION_VARS( first=("url", "article_content_type"), second="article_parent_page_id" ) API_PAGES_ENDPOINT = "/api/v2/pages/" API_IMAGES_ENDPOINT = "/api/v2/images/" KEYS_TO_EXCLUDE = ["id", "meta", ] # Form error messages MAIN_IMPORT_FORM_MESSAGES = { "connection_error": "Please enter a valid URL.", "bad_request": "Please try again later.", }
Make abstract or it run
/** * */ package org.javacc; import junit.framework.TestCase; /** * An ancestor class to enable transition to a different directory structure. * * @author timp * @since 2 Nov 2007 * */ public abstract class JavaCCTestCase extends TestCase { /** * */ public JavaCCTestCase() { super(); } /** * @param name the test name */ public JavaCCTestCase(String name) { super(name); } /** * @return the documentation output directory name String relative to the root */ public String getJJDocOutputDirectory() { return "www/doc/"; //return "src/site/resources/"; } /** * Where the input jj files are located * @return the directory name String relative to the root */ public String getJJInputDirectory() { return "src/org/javacc/parser/"; //return "src/main/javacc/org/javacc/parser/"; } }
/** * */ package org.javacc; import junit.framework.TestCase; /** * An ancestor class to enable transition to a different directory structure. * * @author timp * @since 2 Nov 2007 * */ public class JavaCCTestCase extends TestCase { /** * */ public JavaCCTestCase() { super(); } /** * @param name the test name */ public JavaCCTestCase(String name) { super(name); } /** * @return the documentation output directory name String relative to the root */ public String getJJDocOutputDirectory() { return "www/doc/"; //return "src/site/resources/"; } /** * Where the input jj files are located * @return the directory name String relative to the root */ public String getJJInputDirectory() { return "src/org/javacc/parser/"; //return "src/main/javacc/org/javacc/parser/"; } }
Use full paths due to dependency injection
<?php namespace Dealer4dealer\Xcore\Model; class RestManagement implements \Dealer4dealer\Xcore\Api\RestManagementInterface { const MODULE_NAME = 'Dealer4dealer_Xcore'; protected $productMetadata; protected $moduleList; public function __construct(\Magento\Framework\App\ProductMetadataInterface $productMetadata, \Magento\Framework\Module\ModuleListInterface $moduleList) { $this->productMetadata = $productMetadata; $this->moduleList = $moduleList; } /** * {@inheritdoc} */ public function getVersion() { $magentoVersion = $this->productMetadata->getVersion(); $magentoEdition = $this->productMetadata->getEdition(); $restVersion = $this->moduleList->getOne(self::MODULE_NAME)['setup_version']; $result = new Version; $result->setMagentoVersion($magentoVersion); $result->setMagentoEdition($magentoEdition); $result->setRestVersion($restVersion); return $result; } }
<?php namespace Dealer4dealer\Xcore\Model; class RestManagement implements \Dealer4dealer\Xcore\Api\RestManagementInterface { const MODULE_NAME = 'Dealer4dealer_Xcore'; protected $productMetadata; protected $moduleList; public function __construct(\Magento\Framework\App\ProductMetadataInterface $productMetadata, \ModuleListInterface $moduleList) { $this->productMetadata = $productMetadata; $this->moduleList = $moduleList; } /** * {@inheritdoc} */ public function getVersion() { $magentoVersion = $this->productMetadata->getVersion(); $magentoEdition = $this->productMetadata->getEdition(); $restVersion = $this->moduleList->getOne(self::MODULE_NAME)['setup_version']; $result = new Version; $result->setMagentoVersion($magentoVersion); $result->setMagentoEdition($magentoEdition); $result->setRestVersion($restVersion); return $result; } }
Put jQuery back. Removed in error.
<meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title><?php echo $title; ?></title> <link rel="stylesheet" href="/css/bootstrap.css" /> <link rel="stylesheet" media="screen" href="/css/superfish.css" /> <link rel="stylesheet" media="screen" href="/css/slides.css" /> <link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet"> <link rel="stylesheet" href="/css/sf.css" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700' rel='stylesheet' type='text/css'> <script src="/js/lib/jquery-1.8.0.min.js"></script>
<meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title><?php echo $title; ?></title> <link rel="stylesheet" href="/css/bootstrap.css" /> <link rel="stylesheet" media="screen" href="/css/superfish.css" /> <link rel="stylesheet" media="screen" href="/css/slides.css" /> <link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet"> <link rel="stylesheet" href="/css/sf.css" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700' rel='stylesheet' type='text/css'>
Change null namespaces to empty string on upgrade Former-commit-id: d7c529c257869772bce5cf4b06520a241904a808
<?php namespace Concrete\Core\Updater\Migrations\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Comparator; use Doctrine\DBAL\Schema\Schema; class Version5704 extends AbstractMigration { public function getName() { return '20140930000000'; } public function up(Schema $schema) { \Database::query('UPDATE Config SET configNamespace="" WHERE configNamespace IS NULL'); $config = $schema->getTable('Config'); $fromConfig = clone $config; $db = \Database::get(); $platform = $db->getDatabasePlatform(); $config->dropPrimaryKey(); $config->setPrimaryKey(array('configNamespace', 'configGroup', 'configItem')); $comparator = new Comparator(); $diff = $comparator->diffTable($fromConfig, $config); $sql = $platform->getAlterTableSQL($diff); if (is_array($sql) && count($sql)) { foreach ($sql as $q) { $db->query($q); } } } public function down(Schema $schema) { } }
<?php namespace Concrete\Core\Updater\Migrations\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Comparator; use Doctrine\DBAL\Schema\Schema; class Version5704 extends AbstractMigration { public function getName() { return '20140930000000'; } public function up(Schema $schema) { $config = $schema->getTable('Config'); $fromConfig = clone $config; $db = \Database::get(); $platform = $db->getDatabasePlatform(); $config->dropPrimaryKey(); $config->setPrimaryKey(array('configNamespace', 'configGroup', 'configItem')); $comparator = new Comparator(); $diff = $comparator->diffTable($fromConfig, $config); $sql = $platform->getAlterTableSQL($diff); if (is_array($sql) && count($sql)) { foreach ($sql as $q) { $db->query($q); } } } public function down(Schema $schema) { } }
Fix bug in action serializer Don't try to get URL of items that have been deleted
from rest_framework import serializers from editorsnotes.main.models.auth import (LogActivity, ADDITION, CHANGE, DELETION) VERSION_ACTIONS = { ADDITION: 'added', CHANGE: 'changed', DELETION: 'deleted' } # TODO: make these fields nested, maybe class ActivitySerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') project = serializers.ReadOnlyField(source='project.slug') type = serializers.ReadOnlyField(source='content_type.model') url = serializers.SerializerMethodField('get_object_url') title = serializers.ReadOnlyField(source='display_title') action = serializers.SerializerMethodField('get_action_repr') class Meta: model = LogActivity fields = ('user', 'project', 'time', 'type', 'url', 'title', 'action',) def get_object_url(self, obj): if obj.action == DELETION or obj.content_object is None: return None else: return obj.content_object.get_absolute_url() def get_action_repr(self, version_obj): return VERSION_ACTIONS[version_obj.action]
from rest_framework import serializers from editorsnotes.main.models.auth import (LogActivity, ADDITION, CHANGE, DELETION) VERSION_ACTIONS = { ADDITION: 'added', CHANGE: 'changed', DELETION: 'deleted' } # TODO: make these fields nested, maybe class ActivitySerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') project = serializers.ReadOnlyField(source='project.slug') type = serializers.ReadOnlyField(source='content_type.model') url = serializers.SerializerMethodField('get_object_url') title = serializers.ReadOnlyField(source='display_title') action = serializers.SerializerMethodField('get_action_repr') class Meta: model = LogActivity fields = ('user', 'project', 'time', 'type', 'url', 'title', 'action',) def get_object_url(self, obj): return None if obj.action == DELETION else obj.content_object.get_absolute_url() def get_action_repr(self, version_obj): return VERSION_ACTIONS[version_obj.action]
Read contents of files in archive as well
import {useCallback} from 'react'; import {useDropzone} from 'react-dropzone'; import JSZip from 'jszip'; export default function Dropzone() { const onDrop = useCallback(async acceptedFiles => { const zip = await JSZip.loadAsync(acceptedFiles[0]); for (let name in zip.files) { console.log(name); const file = zip.files[name]; // Skip over directories if (file.dir) continue; const stream = file.nodeStream(); // Too bad stream is not a native stream, but instead a node stream // with a totally different API... stream.on('data', chunk => { console.log(chunk); }); await new Promise(resolve => { stream.on('end', resolve); }); }; }, []); const {getRootProps, getInputProps, isDragActive} = useDropzone({onDrop}); return ( <div {...getRootProps()}> <input {...getInputProps()} /> { isDragActive ? <p>Drop the files here...</p> : <p>Drag 'n' drop some files here, or click to select files</p> } </div> ); }
import {useCallback} from 'react'; import {useDropzone} from 'react-dropzone'; import JSZip from 'jszip'; export default function Dropzone() { const onDrop = useCallback(async acceptedFiles => { const zip = await JSZip.loadAsync(acceptedFiles[0]); zip.forEach((name, file) => { console.log(name); console.log(file); }); }, []); const {getRootProps, getInputProps, isDragActive} = useDropzone({onDrop}); return ( <div {...getRootProps()}> <input {...getInputProps()} /> { isDragActive ? <p>Drop the files here...</p> : <p>Drag 'n' drop some files here, or click to select files</p> } </div> ); }
Fix usage of some helper in form loss preventer service
import Ember from 'ember'; import {some} from 'ember-form-object/utils/core'; const {Service, computed, $, A: emberArray} = Ember; export default Service.extend({ registeredFormObjects: computed(() => emberArray()), init() { this._super(...arguments); this.setupBeforeUnloadListener(); }, setupBeforeUnloadListener() { $(window).on('beforeunload', (ev) => this.onWindowBeforeUnload(ev)); }, registerFormObject(formObject) { this.set('registeredFormObjects', this.get('registeredFormObjects').concat(formObject)); }, unregisterFormObject(formObject) { this.set('registeredFormObjects', this.get('registeredFormObjects').without(formObject)); }, hasSomeDirtyForms() { return some(this.get('registeredFormObjects'), (formObject) => formObject.get('isDirty')); }, onWindowBeforeUnload() { if (this.hasSomeDirtyForms()) { return 'You have attempted to leave this page. There are some changes that need to be saved.'; } } });
import Ember from 'ember'; import {some} from 'ember-form-object/utils/core'; const {Service, computed, $, A: emberArray} = Ember; export default Service.extend({ registeredFormObjects: computed(() => emberArray()), init() { this._super(...arguments); this.setupBeforeUnloadListener(); }, setupBeforeUnloadListener() { $(window).on('beforeunload', (ev) => this.onWindowBeforeUnload(ev)); }, registerFormObject(formObject) { this.set('registeredFormObjects', this.get('registeredFormObjects').concat(formObject)); }, unregisterFormObject(formObject) { this.set('registeredFormObjects', this.get('registeredFormObjects').without(formObject)); }, hasSomeDirtyForms() { return some(this.get('registeredFormObjects').map((formObject) => formObject.get('isDirty'))); }, onWindowBeforeUnload() { if (this.hasSomeDirtyForms()) { return 'You have attempted to leave this page. There are some changes that need to be saved.'; } } });
Add exception to to return extended height of the show
from django import template from datetime import datetime, time, timedelta register = template.Library() @register.simple_tag def height(start, end): if start.year == 2020 and int(start.strftime('%V')) >= 5 and start.hour == 12 and start.minute == 0: if end.minute == 5: return '30' return '%d' % (((end - start).seconds / 60) + 25) else: return '%d' % ((end - start).seconds / 60) @register.simple_tag def height_until(end): start = datetime.combine(end.date(), time(6, 0)) return '%d' % ((end - start).seconds / 60) @register.simple_tag def height_since(start): if start.time() < time(23, 59): end = datetime.combine(start.date() + timedelta(days=1), time(6, 0)) else: end = datetime.combine(start.date(), time(6, 0)) return '%d' % ((end - start).seconds / 60)
from django import template from datetime import datetime, time, timedelta register = template.Library() @register.simple_tag def height(start, end): if start.year == 2020 and int(start.strftime('%V')) >= 5 and start.hour == 12 and start.minute == 0: return '30' else: return '%d' % ((end - start).seconds / 60) @register.simple_tag def height_until(end): start = datetime.combine(end.date(), time(6, 0)) return '%d' % ((end - start).seconds / 60) @register.simple_tag def height_since(start): if start.time() < time(23, 59): end = datetime.combine(start.date() + timedelta(days=1), time(6, 0)) else: end = datetime.combine(start.date(), time(6, 0)) return '%d' % ((end - start).seconds / 60)
Autoloader: Support PSR-4 style namespace/directory mapping Signed-off-by: Florian Pritz <753f544d2d01592750fb4bd29251b78abcfc8ecd@xinu.at>
<?php /* * Copyright 2014 Florian "Bluewind" Pritz <bluewind@server-speed.net> * * Licensed under AGPLv3 * (see COPYING for full license text) * */ // Original source: http://stackoverflow.com/a/9526005/953022 class CustomAutoloader{ public function __construct() { spl_autoload_register(array($this, 'loader')); } public function loader($className) { $namespaces = array( '' => [ ["path" => APPPATH], ["path" => APPPATH."/third_party/mockery/library/"] ], ); foreach ($namespaces as $namespace => $search_items) { if ($namespace === '' || strpos($className, $namespace) === 0) { foreach ($search_items as $search_item) { $nameToLoad = str_replace($namespace, '', $className); $path = $search_item['path'].str_replace('\\', DIRECTORY_SEPARATOR, $nameToLoad).'.php'; if (file_exists($path)) { require $path; return; } } } } } }
<?php /* * Copyright 2014 Florian "Bluewind" Pritz <bluewind@server-speed.net> * * Licensed under AGPLv3 * (see COPYING for full license text) * */ // Original source: http://stackoverflow.com/a/9526005/953022 class CustomAutoloader{ public function __construct() { spl_autoload_register(array($this, 'loader')); } public function loader($className) { $base_paths = array( APPPATH, APPPATH."/third_party/mockery/library/", ); foreach ($base_paths as $base_path) { $path = $base_path.str_replace('\\', DIRECTORY_SEPARATOR, $className).'.php'; if (file_exists($path)) { require $path; return; } } } }
Add support for single files There may be a time where a user would like to pass just a single file to the formatter instead of an entire directory.
<?php /* * This file is part of MITRE's ACE project * * Copyright (c) 2015 MITRE Corporation * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * * @author MITRE's ACE Team <ace-team@mitre.org> */ namespace Mmoreram\PHPFormatter\Finder; use Symfony\Component\Finder\Finder; /** * Class FileFinder */ class FileFinder { /** * Find all php files by path * * @param string $path Path * * @return Finder Finder iterable object with all PHP found files in path */ public function findPHPFilesByPath($path) { $finder = new Finder(); if (file_exists($path) && !is_dir($path)) { $finder->append([0 => $path]); } else { $finder ->files() ->in($path) ->name('*.php'); } return $finder; } }
<?php /* * This file is part of the php-formatter package * * Copyright (c) 2014 Marc Morera * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Marc Morera <yuhu@mmoreram.com> */ namespace Mmoreram\PHPFormatter\Finder; use Symfony\Component\Finder\Finder; /** * Class FileFinder */ class FileFinder { /** * Find all php files by path * * @param string $path Path * * @return Finder Finder iterable object with all PHP found files in path */ public function findPHPFilesByPath($path) { $finder = new Finder(); $finder ->files() ->in($path) ->name('*.php'); return $finder; } }
Use SiteFeed to get a category listing
# encoding: utf-8 """ List categories and their IDs in a Discourse forum. """ import os from argparse import ArgumentParser from community_mailbot.discourse import SiteFeed def main(): args = parse_args() site_feed = SiteFeed(args.url, user=args.user, key=args.key) for c_id, name in site_feed.category_names.items(): print(c_id, name) def parse_args(): parser = ArgumentParser(description=__doc__) parser.add_argument( '--key', default=os.getenv('DISCOURSE_KEY', None), help='Discourse API key') parser.add_argument( '--user', default=os.getenv('DISCOURSE_USER', None), help='Discourse API user') parser.add_argument( '--url', default='http://community.lsst.org', help='Base URL of the discourse forum') return parser.parse_args() if __name__ == '__main__': main()
# encoding: utf-8 """ List categories and their IDs in a Discourse forum. """ import os from argparse import ArgumentParser from urllib.parse import urljoin import requests def main(): args = parse_args() params = {} if args.key is not None: params['api_key'] = args.key if args.user is not None: params['api_username'] = args.user url = urljoin(args.url, 'site.json') r = requests.get(url, params=params) r.raise_for_status() site_feed = r.json() for c in site_feed['categories']: print(c['id'], c['name']) def parse_args(): parser = ArgumentParser(description=__doc__) parser.add_argument( '--key', default=os.getenv('DISCOURSE_KEY', None), help='Discourse API key') parser.add_argument( '--user', default=os.getenv('DISCOURSE_KEY', None), help='Discourse API user') parser.add_argument( '--url', default='http://community.lsst.org', help='Base URL of the discourse forum') return parser.parse_args() if __name__ == '__main__': main()
Update tests for `res.url` and `err.url`
'use strict'; var assert = require('assert'); var Response = require('../'); var res = new Response(200, { 'Foo-Bar': 'baz-Bosh', 'bar-foo': 'bish-Bosh' }, 'foo bar baz', 'http://example.com'); assert(res.statusCode = 200); assert(res.headers['foo-bar'] === 'baz-Bosh'); assert(res.headers['bar-foo'] === 'bish-Bosh'); assert(res.body === 'foo bar baz'); assert(res.url === 'http://example.com'); assert(res.getBody() === 'foo bar baz'); res = new Response(404, { 'Foo-Bar': 'baz-Bosh' }, 'Could not find page', 'http://example.com'); assert(res.statusCode = 404); assert(res.headers['foo-bar'] === 'baz-Bosh'); assert(res.body === 'Could not find page'); assert(res.url === 'http://example.com'); var errored = false; try { res.getBody(); } catch (ex) { assert(ex.statusCode === 404); assert(ex.headers['foo-bar'] === 'baz-Bosh'); assert(ex.body === 'Could not find page'); assert(ex.url === 'http://example.com'); errored = true; } if (!errored) { throw new Error('res.getBody() should throw an error when the status code is 404'); } console.log('tests passed');
'use strict'; var assert = require('assert'); var Response = require('../'); var res = new Response(200, { 'Foo-Bar': 'baz-Bosh', 'bar-foo': 'bish-Bosh' }, 'foo bar baz'); assert(res.statusCode = 200); assert(res.headers['foo-bar'] === 'baz-Bosh'); assert(res.headers['bar-foo'] === 'bish-Bosh'); assert(res.body === 'foo bar baz'); assert(res.getBody() === 'foo bar baz'); res = new Response(404, { 'Foo-Bar': 'baz-Bosh' }, 'Could not find page'); assert(res.statusCode = 404); assert(res.headers['foo-bar'] === 'baz-Bosh'); assert(res.body === 'Could not find page'); var errored = false; try { res.getBody(); } catch (ex) { assert(ex.statusCode === 404); assert(ex.headers['foo-bar'] === 'baz-Bosh'); assert(res.body === 'Could not find page'); errored = true; } if (!errored) { throw new Error('res.getBody() should throw an error when the status code is 404'); } console.log('tests passed');
Add more tests back in
<?php class Purity5Test extends PHPUnit_Framework_TestCase { // Tests public function test_SimpleParse() { $html = '<html> <head> <title>Welcome</title> </head> <body> <h1>Heading</h1> <p>Welcome to Purity5!</p> </body> </html>'; $func = SkylarK\Purity5\Purity5::parse($html); $this->assertEquals("Welcome", $func("title")); $this->assertEquals("Welcome", $func("head title")); $this->assertEquals("Welcome", $func("head")->title); $this->assertEquals("Welcome to Purity5!", $func("html> body >p")); $this->assertEquals("Welcome to Purity5!", $func("html")->body->p); } }
<?php class Purity5Test extends PHPUnit_Framework_TestCase { // Tests public function test_SimpleParse() { $html = '<html> <head> <title>Welcome</title> </head> <body> <h1>Heading</h1> <p>Welcome to Purity5!</p> </body> </html>'; $func = SkylarK\Purity5\Purity5::parse($html); //$this->assertEquals("Welcome", $func("title")); //$this->assertEquals("Welcome", $func("head title")); //$this->assertEquals("Welcome", $func("head")->title); //$this->assertEquals("Welcome to Purity5!", $func("html> body >p")); //$this->assertEquals("Welcome to Purity5!", $func("html")->body->p); } }
Insert example directories in path before all others in the example test.
# -*- coding: utf-8 -*- ####################################################################### # Name: test_examples # Purpose: Test that examples run without errors. # Author: Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com> # Copyright: (c) 2014-2015 Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com> # License: MIT License ####################################################################### import pytest import os, sys import glob import imp def test_examples(): examples_pat = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../examples/*/*.py') # Filter out __init__.py examples = [f for f in glob.glob(examples_pat) if f != '__init__.py'] for e in examples: example_dir = os.path.dirname(e) sys.path.insert(0, example_dir) (module_name, _) = os.path.splitext(os.path.basename(e)) (module_file, module_path, desc) = \ imp.find_module(module_name, [example_dir]) m = imp.load_module(module_name, module_file, module_path, desc) if hasattr(m, 'main'): m.main(debug=False)
# -*- coding: utf-8 -*- ####################################################################### # Name: test_examples # Purpose: Test that examples run without errors. # Author: Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com> # Copyright: (c) 2014-2015 Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com> # License: MIT License ####################################################################### import pytest import os, sys import glob import imp def test_examples(): examples_pat = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../examples/*/*.py') # Filter out __init__.py examples = [f for f in glob.glob(examples_pat) if f != '__init__.py'] for e in examples: example_dir = os.path.dirname(e) sys.path.append(example_dir) (module_name, _) = os.path.splitext(os.path.basename(e)) (module_file, module_path, desc) = \ imp.find_module(module_name, [example_dir]) m = imp.load_module(module_name, module_file, module_path, desc) if hasattr(m, 'main'): m.main(debug=False)
Simplify object in ChatServer constructor.
import connect from 'connect'; import faker from 'faker'; import path from 'path'; import serveStatic from 'serve-static'; import uuid from 'node-uuid'; import {Server as WebSocketServer} from 'ws'; connect().use(serveStatic(path.join(__dirname, '../'))).listen(8080); class ChatServer { constructor(port) { this.wss = new WebSocketServer({port}); this.wss.on('connection', this.handleConnection); } sendMessage = (nick, event, data) => { const payload = JSON.stringify({ id: uuid.v4(), nick, event, message: data }); this.wss.clients.forEach(client => client.send(payload)); }; handleConnection = (ws) => { const nick = faker.internet.userName(); this.sendMessage(nick, 'join'); ws.on('message', message => this.sendMessage(nick, 'message', message)); ws.on('close', message => this.sendMessage(nick, 'leave')); } } let server = new ChatServer(6639); process.on('SIGINT', () => { setTimeout(process.exit, 100); });
import connect from 'connect'; import faker from 'faker'; import path from 'path'; import serveStatic from 'serve-static'; import uuid from 'node-uuid'; import {Server as WebSocketServer} from 'ws'; connect().use(serveStatic(path.join(__dirname, '../'))).listen(8080); class ChatServer { constructor(port) { this.wss = new WebSocketServer({port: port}); this.wss.on('connection', this.handleConnection); } sendMessage = (nick, event, data) => { const payload = JSON.stringify({ id: uuid.v4(), nick, event, message: data }); this.wss.clients.forEach(client => client.send(payload)); }; handleConnection = (ws) => { const nick = faker.internet.userName(); this.sendMessage(nick, 'join'); ws.on('message', message => this.sendMessage(nick, 'message', message)); ws.on('close', message => this.sendMessage(nick, 'leave')); } } let server = new ChatServer(6639); process.on('SIGINT', () => { setTimeout(process.exit, 100); });
[TASK] Fix small error in model naming -InvoiceNumber should have been InvoiceId
package org.killbill.billing.plugin.notification.womplyClient; public class EmailRequestModel { private String emailType; private String invoiceId; private String subscriptionId; private String businessLocationId; public EmailRequestModel(String emailType, String invoiceId, String subscriptionId, String businessLocationId) { this.emailType = emailType; this.invoiceId = invoiceId; this.subscriptionId = subscriptionId; this.businessLocationId = businessLocationId; } public String getEmailType() { return emailType; } public void setEmailType(String emailType) { this.emailType = emailType; } public String getInvoiceId() { return invoiceId; } public void setInvoiceId(String invoiceId) { this.invoiceId = invoiceId; } public String getSubscriptionId() { return subscriptionId; } public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } public String getBusinessLocationId() { return businessLocationId; } public void setBusinessLocationId(String businessLocationId) { this.businessLocationId = businessLocationId; } }
package org.killbill.billing.plugin.notification.womplyClient; public class EmailRequestModel { private String emailType; private String invoiceNumber; private String subscriptionId; private String businessLocationId; public EmailRequestModel(String emailType, String invoiceNumber, String subscriptionId, String businessLocationId) { this.emailType = emailType; this.invoiceNumber = invoiceNumber; this.subscriptionId = subscriptionId; this.businessLocationId = businessLocationId; } public String getEmailType() { return emailType; } public void setEmailType(String emailType) { this.emailType = emailType; } public String getInvoiceNumber() { return invoiceNumber; } public void setInvoiceNumber(String invoiceNumber) { this.invoiceNumber = invoiceNumber; } public String getSubscriptionId() { return subscriptionId; } public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } public String getBusinessLocationId() { return businessLocationId; } public void setBusinessLocationId(String businessLocationId) { this.businessLocationId = businessLocationId; } }
Test + travis = error
package main import ( "fmt" "testing" "github.com/spf13/viper" ) func TestSomething(t *testing.T) { viper.SetConfigName("config") viper.AddConfigPath(".") if err := viper.ReadInConfig(); err != nil { fmt.Printf("%v", err) } } /* func TestMain(m *testing.M) { i18n.MustLoadTranslationFile("lang/en-US.all.json") i18n.MustLoadTranslationFile("lang/fr.all.json") mylog.Init(mylog.ERROR) os.Exit(m.Run()) } func TestReadConfigFound(t *testing.T) { if err := readConfig("configForTest"); err != nil { fmt.Printf("%v", err) } }*/ /*func TestReadConfigNotFound(t *testing.T) { if err := readConfig("configError"); err != nil { fmt.Printf("%v", err) } }*/
package main import ( "fmt" "os" "testing" "github.com/nicksnyder/go-i18n/i18n" mylog "github.com/patrickalin/GoMyLog" "github.com/spf13/viper" ) func TestSomething(t *testing.T) { viper.SetConfigName("config") viper.AddConfigPath(".") if err := viper.ReadInConfig(); err != nil { fmt.Printf("%v", err) } } func TestMain(m *testing.M) { i18n.MustLoadTranslationFile("lang/en-US.all.json") i18n.MustLoadTranslationFile("lang/fr.all.json") mylog.Init(mylog.ERROR) os.Exit(m.Run()) } func TestReadConfigFound(t *testing.T) { if err := readConfig("configForTest"); err != nil { fmt.Printf("%v", err) } } /*func TestReadConfigNotFound(t *testing.T) { if err := readConfig("configError"); err != nil { fmt.Printf("%v", err) } }*/
Remove GS from internal header
var fetch = require('node-fetch'); var FormData = require('form-data'); module.exports = () => { const scriptURL = 'https://script.google.com/macros/s/---/exec'; // Add submit handler to 'internal header' form const wikiform = document.forms['wikidata-form']; if (wikiform) { wikiform.addEventListener('submit', e => { e.preventDefault(); handleSuccess('success'); fetch(scriptURL, { method: 'POST', body: new FormData(wikiform) }) .then(response => handleSuccess(response)) .catch(error => handleError(error)); }); } }; function handleSuccess (response) { document.getElementById('wikidata-form').hidden = true; document.getElementById('sucessMessage').hidden = false; console.log('Success!', response); } function handleError (error) { document.getElementById('wikidata-form').hidden = true; document.getElementById('errorMessage').hidden = false; console.error('Error!', error.message); }
var fetch = require('node-fetch'); var FormData = require('form-data'); module.exports = () => { const scriptURL = 'https://script.google.com/macros/s/AKfycbxavhMbZpTlCuRHdUauf2hkGcx4uHTZ2TpSx5jr4B8p4Luy3u4/exec'; // Add submit handler to 'internal header' form const wikiform = document.forms['wikidata-form']; if (wikiform) { wikiform.addEventListener('submit', e => { e.preventDefault(); handleSuccess('success'); fetch(scriptURL, { method: 'POST', body: new FormData(wikiform) }) .then(response => handleSuccess(response)) .catch(error => handleError(error)); }); } }; function handleSuccess (response) { document.getElementById('wikidata-form').hidden = true; document.getElementById('sucessMessage').hidden = false; console.log('Success!', response); } function handleError (error) { document.getElementById('wikidata-form').hidden = true; document.getElementById('errorMessage').hidden = false; console.error('Error!', error.message); }
Add deselectCountry method to WorldComponent.
/** @jsx React.DOM */ var CountriesComponent = require('./countries_component'); var PathsComponent = require('./paths_component'); var PolygonsComponent = require('./polygons_component'); var React = require('react'); module.exports = React.createClass({ // Selects a given country. selectCountry: function(country) { this.refs.countries.setState({selectedCountry: country}); }, // Deselects the currently selected country. deselectCountry: function() { this.selectCountry(null); }, render: function() { var world = this.props.world; return <svg width={world.width} height={world.height}> <PolygonsComponent className="hexgrid" polygons={world.hexagons} /> <CountriesComponent ref="countries" className="PiYG" countries={world.countries} stream={this.props.stream} /> <PathsComponent className="voronoi" paths={world.cells} /> </svg>; } });
/** @jsx React.DOM */ var CountriesComponent = require('./countries_component'); var PathsComponent = require('./paths_component'); var PolygonsComponent = require('./polygons_component'); var React = require('react'); module.exports = React.createClass({ selectCountry: function(country) { this.refs.countries.setState({selectedCountry: country}); }, render: function() { var world = this.props.world; return <svg width={world.width} height={world.height}> <PolygonsComponent className="hexgrid" polygons={world.hexagons} /> <CountriesComponent ref="countries" className="PiYG" countries={world.countries} stream={this.props.stream} /> <PathsComponent className="voronoi" paths={world.cells} /> </svg>; } });
Throw errors to stop the promise chain
'use strict'; // External modules var Bluebird = require('bluebird'); // Local modules var Support = require('./support'); module.exports = { bump: function (args) { return Bluebird .resolve(args) .tap(logWrap('Updating the changelog', Support.changelog.update)) .tap(logWrap('Updating the package', Support.npm.updatePackage)) .tap(logWrap('Pushing changes', Support.git.push)) .tap(logWrap('Pushing tags', Support.git.pushTags)); }, release: function (args) { return this .bump(args) .tap(logWrap('Publishing package', Support.npm.publishPackage)); } }; function logWrap (s, fun) { return function () { var args = [].slice.apply(arguments); return Bluebird .resolve() .then(function () { console.log(s + ' ... '); }) .then(function () { return fun.apply(null, args); }) .then(function () { console.log(s + ' ... done.'); }) .catch(function (e) { console.log(s + ' ... failed:'); console.log(e); throw e; }); }; }
'use strict'; // External modules var Bluebird = require('bluebird'); // Local modules var Support = require('./support'); module.exports = { bump: function (args) { return Bluebird .resolve(args) .tap(logWrap('Updating the changelog', Support.changelog.update)) .tap(logWrap('Updating the package', Support.npm.updatePackage)) .tap(logWrap('Pushing changes', Support.git.push)) .tap(logWrap('Pushing tags', Support.git.pushTags)); }, release: function (args) { return this .bump(args) .tap(logWrap('Publishing package', Support.npm.publishPackage)); } }; function logWrap (s, fun) { return function () { var args = [].slice.apply(arguments); return Bluebird .resolve() .then(function () { console.log(s + ' ... '); }) .then(function () { return fun.apply(null, args); }) .then(function () { console.log(s + ' ... done.'); }) .catch(function (e) { console.log(s + ' ... failed:'); console.log(e); }); }; }
Remove second type element if empty
const DocumentedItem = require('./item'); class DocumentedVarType extends DocumentedItem { registerMetaInfo(data) { this.directData = data; } serialize() { const names = []; for(const name of this.directData.names) names.push(this.constructor.splitVarName(name)); return { types: names }; } static splitVarName(str) { if(str === '*') return ['*']; const matches = str.match(/([\w]+)([^\w]+)/g); const output = []; if(matches) { for(const match of matches) { const groups = match.match(/([\w]+)([^\w]+)/); output.push([groups[1], groups[2]]); } } else { output.push([str.match(/(\w+)/g)[0]]); } return output; } } /* { "names":[ "String" ] } */ module.exports = DocumentedVarType;
const DocumentedItem = require('./item'); class DocumentedVarType extends DocumentedItem { registerMetaInfo(data) { this.directData = data; } serialize() { const names = []; for(const name of this.directData.names) names.push(this.constructor.splitVarName(name)); return { types: names }; } static splitVarName(str) { if(str === '*') return ['*', '']; const matches = str.match(/([\w]+)([^\w]+)/g); const output = []; if(matches) { for(const match of matches) { const groups = match.match(/([\w]+)([^\w]+)/); output.push([groups[1], groups[2]]); } } else { output.push([str.match(/(\w+)/g)[0], '']); } return output; } } /* { "names":[ "String" ] } */ module.exports = DocumentedVarType;
Make sure the OEmbed type can never be used to control filenames. Minor risk, as it's still a template path, but better be safe then sorry.
""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem import re re_safe = re.compile(r'[^\w_-]') @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ safe_filename = re_safe.sub('', instance.type or 'default') return [ "fluent_contents/plugins/oembed/{type}.html".format(type=safe_filename), self.render_template ]
""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem @plugin_pool.register class OEmbedPlugin(ContentPlugin): model = OEmbedItem category = _('Online content') form = OEmbedItemForm render_template = "fluent_contents/plugins/oembed/default.html" class Media: css = { 'screen': ( 'fluent_contents/plugins/oembed/oembed_admin.css', ) } def get_render_template(self, request, instance, **kwargs): """ Allow to style the item based on the type. """ return ["fluent_contents/plugins/oembed/{type}.html".format(type=instance.type or 'default'), self.render_template]
Delete useless username at link Now that the image upload is at the edit page username isn't needed as a method.
<?php class ImageController { public static function create( $image ) { include_once 'models/image.php'; include_once 'models/extentions.php'; if ( !isset( $_SESSION[ 'user' ][ 'username' ] ) ) { throw new HTTPUnauthorizedException(); } $user = User::findByUsername( $_SESSION[ 'user' ][ 'username' ] ); $user->image = new Image(); $user->image->tmp_name = $image[ 'tmp_name' ]; $user->image->name = $image[ 'name' ]; $user->image->userid = $user->id; try { $user->image->save(); $user->save(); } catch ( ModelValidationException $e ) { go( 'user', 'update', array( $e->error => true ) ); } go( 'user', 'view', array( 'username' => $user->username ) ); } } ?>
<?php class ImageController { public static function create( $image ) { include_once 'models/image.php'; include_once 'models/extentions.php'; if ( !isset( $_SESSION[ 'user' ][ 'username' ] ) ) { throw new HTTPUnauthorizedException(); } $user = User::findByUsername( $_SESSION[ 'user' ][ 'username' ] ); $user->image = new Image(); $user->image->tmp_name = $image[ 'tmp_name' ]; $user->image->name = $image[ 'name' ]; $user->image->userid = $user->id; try { $user->image->save(); $user->save(); } catch ( ModelValidationException $e ) { go( 'user', 'update', array( 'username' => $user->username, $e->error => true ) ); } go( 'user', 'view', array( 'username' => $user->username ) ); } } ?>
Use open instead of file.
# -*- encoding: utf8 -*- from setuptools import setup, find_packages import os setup( name = "django-prefetch", version = "0.1.1", url = 'https://github.com/ionelmc/django-prefetch', download_url = '', license = 'BSD', description = "Generic model related data prefetch framework for Django", long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), author = 'Ionel Cristian Mărieș', author_email = 'contact@ionelmc.ro', packages = find_packages('src'), package_dir = {'':'src'}, py_modules = ['prefetch'], include_package_data = True, zip_safe = False, classifiers = [ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', ] )
# -*- encoding: utf8 -*- from setuptools import setup, find_packages import os setup( name = "django-prefetch", version = "0.1.1", url = 'https://github.com/ionelmc/django-prefetch', download_url = '', license = 'BSD', description = "Generic model related data prefetch framework for Django", long_description = file(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), author = 'Ionel Cristian Mărieș', author_email = 'contact@ionelmc.ro', packages = find_packages('src'), package_dir = {'':'src'}, py_modules = ['prefetch'], include_package_data = True, zip_safe = False, classifiers = [ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', ] )
Drop trailing arg list comma to support Python 3.5
"""Version tools set.""" import os from setuptools_scm import get_version def get_version_from_scm_tag( *, root='.', relative_to=None, local_scheme='node-and-date' ): """Retrieve the version from SCM tag in Git or Hg.""" try: return get_version( root=root, relative_to=relative_to, local_scheme=local_scheme, ) except LookupError: return 'unknown' def cut_local_version_on_upload(version): """Return empty local version if uploading to PyPI.""" is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true' if is_pypi_upload: return '' import setuptools_scm.version # only available during setup time return setuptools_scm.version.get_local_node_and_date(version) def get_self_version(): """Calculate the version of the dist itself.""" return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
"""Version tools set.""" import os from setuptools_scm import get_version def get_version_from_scm_tag( *, root='.', relative_to=None, local_scheme='node-and-date', ): """Retrieve the version from SCM tag in Git or Hg.""" try: return get_version( root=root, relative_to=relative_to, local_scheme=local_scheme, ) except LookupError: return 'unknown' def cut_local_version_on_upload(version): """Return empty local version if uploading to PyPI.""" is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true' if is_pypi_upload: return '' import setuptools_scm.version # only available during setup time return setuptools_scm.version.get_local_node_and_date(version) def get_self_version(): """Calculate the version of the dist itself.""" return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
Refactor simple select path logic
function q(path) { var fn = selectPath(path); if (arguments.length > 1) { return fn(arguments[1]); } else { return fn; } } function selectPath(path) { function nonEmpty(part) { return part.length > 0; } var defaultValue = undefined; path = path.split("/").filter(nonEmpty); return function(item) { var branch = item; var field = path.shift(); while (typeof field !== 'undefined') { branch = branch[field]; field = path.shift(); if (typeof branch === 'undefined') { return defaultValue; } } return branch; }; } module.exports = q;
function q(path) { var fn = selectPath(path); if (arguments.length > 1) { return fn(arguments[1]); } else { return fn; } } function selectPath(path) { function nonEmpty(part) { return part.length > 0; } var parts = path.split("/").filter(nonEmpty); var partsLength = parts.length; var defaultValue = undefined; return function(item) { var branch = item; for (var idx = 0; idx < partsLength; idx++) { var key = parts[idx]; branch = branch[key]; if (typeof branch === 'undefined') { // return default return defaultValue; } } return branch; }; } module.exports = q;
core: Modify constructor to be compatible with caller method ConnectDomainToStorageCommand is being called without context although its constructor is only supported with context parameter, so we will always get runtime exception when the command is being called. The proposed fix is to add a constructor which also supports to get only paramteres Change-Id: Ic120c4b33b40a122895c2088b8365f26c05eb517 Signed-off-by: Maor Lipchuk <37a323a8cadba73c2b6c8d3f850c79092d0199e6@redhat.com>
package org.ovirt.engine.core.bll.storage; import org.ovirt.engine.core.bll.context.CommandContext; import java.util.Date; import org.ovirt.engine.core.bll.InternalCommandAttribute; import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute; import org.ovirt.engine.core.common.action.StorageDomainPoolParametersBase; @InternalCommandAttribute @NonTransactiveCommandAttribute public class ConnectDomainToStorageCommand<T extends StorageDomainPoolParametersBase> extends StorageDomainCommandBase<T> { public ConnectDomainToStorageCommand(T parameters) { super(parameters, null); } public ConnectDomainToStorageCommand(T parameters, CommandContext cmdContext) { super(parameters, cmdContext); } @Override protected void executeCommand() { log.infoFormat("ConnectDomainToStorage. Before Connect all hosts to pool. Time:{0}", new Date()); connectAllHostsToPool(); log.infoFormat("ConnectDomainToStorage. After Connect all hosts to pool. Time:{0}", new Date()); } }
package org.ovirt.engine.core.bll.storage; import org.ovirt.engine.core.bll.context.CommandContext; import java.util.Date; import org.ovirt.engine.core.bll.InternalCommandAttribute; import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute; import org.ovirt.engine.core.common.action.StorageDomainPoolParametersBase; @InternalCommandAttribute @NonTransactiveCommandAttribute public class ConnectDomainToStorageCommand<T extends StorageDomainPoolParametersBase> extends StorageDomainCommandBase<T> { public ConnectDomainToStorageCommand(T parameters, CommandContext cmdContext) { super(parameters, cmdContext); } @Override protected void executeCommand() { log.infoFormat("ConnectDomainToStorage. Before Connect all hosts to pool. Time:{0}", new Date()); connectAllHostsToPool(); log.infoFormat("ConnectDomainToStorage. After Connect all hosts to pool. Time:{0}", new Date()); } }
Revert "Fix for blank page on Safari reload"
/** * Expose `fresh()`. */ module.exports = fresh; /** * Check freshness of `req` and `res` headers. * * When the cache is "fresh" __true__ is returned, * otherwise __false__ is returned to indicate that * the cache is now stale. * * @param {Object} req * @param {Object} res * @return {Boolean} * @api public */ function fresh(req, res) { // defaults var etagMatches = true; var notModified = true; // fields var modifiedSince = req['if-modified-since']; var noneMatch = req['if-none-match']; var lastModified = res['last-modified']; var etag = res['etag']; var cc = req['cache-control']; // unconditional request if (!modifiedSince && !noneMatch) return false; // check for no-cache cache request directive if (cc && cc.indexOf('no-cache') !== -1) return false; // parse if-none-match if (noneMatch) noneMatch = noneMatch.split(/ *, */); // if-none-match if (noneMatch) etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0]; // if-modified-since if (modifiedSince) { modifiedSince = new Date(modifiedSince); lastModified = new Date(lastModified); notModified = lastModified <= modifiedSince; } return !! (etagMatches && notModified); }
/** * Expose `fresh()`. */ module.exports = fresh; /** * Check freshness of `req` and `res` headers. * * When the cache is "fresh" __true__ is returned, * otherwise __false__ is returned to indicate that * the cache is now stale. * * @param {Object} req * @param {Object} res * @return {Boolean} * @api public */ function fresh(req, res) { // defaults var etagMatches = true; var notModified = true; // fields var modifiedSince = req['if-modified-since']; var noneMatch = req['if-none-match']; var lastModified = res['last-modified']; var etag = res['etag']; var cc = req['cache-control']; // unconditional request if (!modifiedSince && !noneMatch) return false; // check for no-cache or max-age=0 cache request directive if (cc && (cc.indexOf('no-cache') !== -1 || cc.indexOf('max-age=0') !== -1)) return false; // parse if-none-match if (noneMatch) noneMatch = noneMatch.split(/ *, */); // if-none-match if (noneMatch) etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0]; // if-modified-since if (modifiedSince) { modifiedSince = new Date(modifiedSince); lastModified = new Date(lastModified); notModified = lastModified <= modifiedSince; } return !! (etagMatches && notModified); }
Drop database before every test run, too, to remove data from failed tests.
# -*- coding: utf-8 -*- from unittest import TestCase from byceps.application import create_app from byceps.blueprints.brand.models import Brand from byceps.blueprints.party.models import Party from byceps.database import db class AbstractAppTestCase(TestCase): def setUp(self): self.app = create_app('test', initialize=False) self.db = db db.app = self.app db.drop_all() db.create_all() self.create_brand_and_party() self.client = self.app.test_client() def create_brand_and_party(self): brand = Brand(id='acme', title='ACME') db.session.add(brand) party = Party(id='acme-2014', brand=brand, title='ACME 2014') db.session.add(party) db.session.commit() def tearDown(self): db.session.remove() db.drop_all()
# -*- coding: utf-8 -*- from unittest import TestCase from byceps.application import create_app from byceps.blueprints.brand.models import Brand from byceps.blueprints.party.models import Party from byceps.database import db class AbstractAppTestCase(TestCase): def setUp(self): self.app = create_app('test', initialize=False) self.db = db db.app = self.app db.create_all() self.create_brand_and_party() self.client = self.app.test_client() def create_brand_and_party(self): brand = Brand(id='acme', title='ACME') db.session.add(brand) party = Party(id='acme-2014', brand=brand, title='ACME 2014') db.session.add(party) db.session.commit() def tearDown(self): db.session.remove() db.drop_all()
Fix JSHint issues with template node test file
'use strict'; var <%= slugname %> = require('../lib/<%= slugname %>.js'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports['<%= slugname %>'] = { setUp: function(done) { // setup here done(); }, 'no args': function(test) { test.expect(1); // tests here test.equal(<%= slugname %>.awesome(), 'awesome', 'should be awesome.'); test.done(); } };
'use strict'; var <%= slugname %> = require('../lib/<%= slugname %>.js'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports['<%= slugname %>'] = { setUp: function(done) { // setup here done(); }, 'no args': function(test) { test.expect(1); // tests here test.equal(<%= slugname %>.awesome(), 'awesome', 'should be awesome.'); test.done(); }, };
Set default for STATS to true to get byte counts for messages git-svn-id: f22e84ca493ccad7df8d2727bca69d1c9fc2e5c5@2714 aaf88347-d911-0410-b711-e54d386773bb
package ibis.impl.tcp; import ibis.util.TypedProperties; interface Config { static final String PROPERTY_PREFIX = "ibis.tcp."; static final String s_debug = PROPERTY_PREFIX + "debug"; static final String s_stats = PROPERTY_PREFIX + "stats"; static final String s_asserts = PROPERTY_PREFIX + "asserts"; static final String s_cache = PROPERTY_PREFIX + "cache"; static final boolean DEBUG = TypedProperties.booleanProperty(s_debug); static final boolean STATS = TypedProperties.booleanProperty(s_stats, true); static final boolean ASSERTS = TypedProperties.booleanProperty(s_asserts); static final boolean CONNECTION_CACHE = TypedProperties.booleanProperty(s_cache, true); static final String[] sysprops = { s_debug, s_stats, s_asserts, s_cache }; }
package ibis.impl.tcp; import ibis.util.TypedProperties; interface Config { static final String PROPERTY_PREFIX = "ibis.tcp."; static final String s_debug = PROPERTY_PREFIX + "debug"; static final String s_stats = PROPERTY_PREFIX + "stats"; static final String s_asserts = PROPERTY_PREFIX + "asserts"; static final String s_cache = PROPERTY_PREFIX + "cache"; static final boolean DEBUG = TypedProperties.booleanProperty(s_debug); static final boolean STATS = TypedProperties.booleanProperty(s_stats); static final boolean ASSERTS = TypedProperties.booleanProperty(s_asserts); static final boolean CONNECTION_CACHE = TypedProperties.booleanProperty(s_cache, true); static final String[] sysprops = { s_debug, s_stats, s_asserts, s_cache }; }
Use commit suggestion to use types Co-authored-by: Pedro Algarvio <4410d99cefe57ec2c2cdbd3f1d5cf862bb4fb6f8@algarvio.me>
import subprocess import types import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key) @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) def test_ssh_shell_key_gen(keys): """ Test ssh key_gen """ shell.gen_key(str(keys.priv_key)) assert keys.priv_key.exists() assert keys.pub_key.exists() # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa")
import os import subprocess import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" yield {"pub_key": str(pub_key), "priv_key": str(priv_key)} @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) class TestSSHShell: def test_ssh_shell_key_gen(self, keys): """ Test ssh key_gen """ shell.gen_key(keys["priv_key"]) for fp in keys.keys(): assert os.path.exists(keys[fp]) # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", keys["priv_key"], "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa")
Fix tests now that we have added Redux
import React from 'react' import { Provider } from 'react-redux' import { shallow, render } from 'enzyme' import { shallowToJson } from 'enzyme-to-json' import store from './store' import { setSearchTerm } from './actionCreators' import Search, { Unwrapped as UnwrappedSearch } from './Search' import ShowCard from './ShowCard' import preload from '../public/data.json' test('Search snapshot test', () => { const component = shallow(<UnwrappedSearch shows={preload.shows} searchTerm='' />) const tree = shallowToJson(component) expect(tree).toMatchSnapshot() }) test('Search should render a ShowCard for each show', () => { const component = shallow(<UnwrappedSearch shows={preload.shows} searchTerm='' />) expect(component.find(ShowCard).length).toEqual(preload.shows.length) }) test('Search should render correct amount of shows based on search', () => { const searchWord = 'house' store.dispatch(setSearchTerm(searchWord)) const component = render(<Provider store={store}><Search shows={preload.shows} /></Provider>) const showCount = preload.shows.filter((show) => `${show.title} ${show.description}`.toUpperCase().indexOf(searchWord.toUpperCase()) >= 0).length expect(component.find('.show-card').length).toEqual(showCount) }) // const component = shallow(<Search />) // component.find('input').simulate('change', {target: {value: searchWord}})
import React from 'react' import { shallow } from 'enzyme' import { shallowToJson } from 'enzyme-to-json' import Search from './Search' import ShowCard from './ShowCard' import preload from '../public/data.json' test('Search snapshot test', () => { const component = shallow(<Search />) const tree = shallowToJson(component) expect(tree).toMatchSnapshot() }) test('Search should render a ShowCard for each show', () => { const component = shallow(<Search />) expect(component.find(ShowCard).length).toEqual(preload.shows.length) }) test('Search should render correct amount of shows based on search', () => { const searchWord = 'house' const component = shallow(<Search />) component.find('input').simulate('change', {target: {value: searchWord}}) const showCount = preload.shows.filter((show) => `${show.title} ${show.description}`.toUpperCase().indexOf(searchWord.toUpperCase()) >= 0).length expect(component.find(ShowCard).length).toEqual(showCount) })
Fix tests: add module function docstring
# -*- coding: utf-8 -*- # Import Python libs from __future__ import absolute_import import time # Import Salt libs import salt.utils.decorators def _fallbackfunc(): return False, 'fallback' def working_function(): ''' CLI Example: .. code-block:: bash ''' return True @salt.utils.decorators.depends(True) def booldependsTrue(): ''' CLI Example: .. code-block:: bash ''' return True @salt.utils.decorators.depends(False) def booldependsFalse(): return True @salt.utils.decorators.depends('time') def depends(): ret = {'ret': True, 'time': time.time()} return ret @salt.utils.decorators.depends('time123') def missing_depends(): return True @salt.utils.decorators.depends('time', fallback_function=_fallbackfunc) def depends_will_not_fallback(): ''' CLI Example: .. code-block:: bash ''' ret = {'ret': True, 'time': time.time()} return ret @salt.utils.decorators.depends('time123', fallback_function=_fallbackfunc) def missing_depends_will_fallback(): ret = {'ret': True, 'time': time.time()} return ret
# -*- coding: utf-8 -*- # Import Python libs from __future__ import absolute_import import time # Import Salt libs import salt.utils.decorators def _fallbackfunc(): return False, 'fallback' def working_function(): ''' CLI Example: .. code-block:: bash ''' return True @salt.utils.decorators.depends(True) def booldependsTrue(): ''' CLI Example: .. code-block:: bash ''' return True @salt.utils.decorators.depends(False) def booldependsFalse(): return True @salt.utils.decorators.depends('time') def depends(): ret = {'ret': True, 'time': time.time()} return ret @salt.utils.decorators.depends('time123') def missing_depends(): return True @salt.utils.decorators.depends('time', fallback_function=_fallbackfunc) def depends_will_not_fallback(): ret = {'ret': True, 'time': time.time()} return ret @salt.utils.decorators.depends('time123', fallback_function=_fallbackfunc) def missing_depends_will_fallback(): ret = {'ret': True, 'time': time.time()} return ret
Add 1 more checklist item about publish
const readline = require('readline') console.log(`Preparing to publish version: ${process.env.npm_package_version}`) const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) function pleaseFix() { console.warn('Please fix the checklist first then come back again ;)') process.exit(1) } const questions = [ 'Have you set correct **--tag** value in npm publish command?', 'Have you **committed** all files into Git?', 'Have you **tagged** the version in Git?', 'Have you **pushed** all commits to GitHub?', 'Have you update the version number in **package.json**?', 'Have you logged all changes in **README.md**?', ] let finishedQuestions = 0 function askQuestionsResc() { if (questions[finishedQuestions] == null) { rl.close() console.log('Checklist is finished! Let\'s roll!') process.exit(0) return // Next will invoke `npm run build` in `package.json` } rl.question(`${questions[finishedQuestions]} (y/N)? `, (ans) => { if (ans.toLowerCase() !== 'y') { return pleaseFix() } finishedQuestions += 1 askQuestionsResc() }) } askQuestionsResc()
const readline = require('readline') console.log(`Preparing to publish version: ${process.env.npm_package_version}`) const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) function pleaseFix() { console.warn('Please fix the checklist first then come back again ;)') process.exit(1) } const questions = [ 'Have you **committed** all files into Git?', 'Have you **tagged** the version in Git?', 'Have you **pushed** all commits to GitHub?', 'Have you update the version number in **package.json**?', 'Have you logged all changes in **README.md**?', ] let finishedQuestions = 0 function askQuestionsResc() { if (questions[finishedQuestions] == null) { rl.close() console.log('Checklist is finished! Let\'s roll!') process.exit(0) return // Next will invoke `npm run build` in `package.json` } rl.question(`${questions[finishedQuestions]} (y/N)? `, (ans) => { if (ans.toLowerCase() !== 'y') { return pleaseFix() } finishedQuestions += 1 askQuestionsResc() }) } askQuestionsResc()
Fix test 4.2 to test for stream error The test sends an oversized data frame, so the server is required to reset the stream with FRAME_SIZE_ERROR. The server may treat this error as fatal for the connection and send GOAWAY( FRAME_SIZE_ERROR ), or drop the connection instead. These upgraded errors are already handled by TestStreamError
package h2spec import ( "github.com/bradfitz/http2" "github.com/bradfitz/http2/hpack" ) func FrameSizeTestGroup() *TestGroup { tg := NewTestGroup("4.2", "Frame Size") tg.AddTestCase(NewTestCase( "Sends large size frame that exceeds the SETTINGS_MAX_FRAME_SIZE", "The endpoint MUST send a FRAME_SIZE_ERROR error.", func(ctx *Context) (expected []Result, actual Result) { http2Conn := CreateHttp2Conn(ctx, false) defer http2Conn.conn.Close() http2Conn.fr.WriteSettings() hdrs := []hpack.HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", ctx.Authority()), } var hp http2.HeadersFrameParam hp.StreamID = 1 hp.EndStream = false hp.EndHeaders = true hp.BlockFragment = http2Conn.EncodeHeader(hdrs) http2Conn.fr.WriteHeaders(hp) http2Conn.fr.WriteData(1, true, []byte(dummyData(16385))) actualCodes := []http2.ErrCode{http2.ErrCodeFrameSize} return TestStreamError(ctx, http2Conn, actualCodes) }, )) return tg }
package h2spec import ( "github.com/bradfitz/http2" "github.com/bradfitz/http2/hpack" ) func FrameSizeTestGroup() *TestGroup { tg := NewTestGroup("4.2", "Frame Size") tg.AddTestCase(NewTestCase( "Sends large size frame that exceeds the SETTINGS_MAX_FRAME_SIZE", "The endpoint MUST send a FRAME_SIZE_ERROR error.", func(ctx *Context) (expected []Result, actual Result) { http2Conn := CreateHttp2Conn(ctx, false) defer http2Conn.conn.Close() http2Conn.fr.WriteSettings() hdrs := []hpack.HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", ctx.Authority()), } var hp http2.HeadersFrameParam hp.StreamID = 1 hp.EndStream = false hp.EndHeaders = true hp.BlockFragment = http2Conn.EncodeHeader(hdrs) http2Conn.fr.WriteHeaders(hp) http2Conn.fr.WriteData(1, true, []byte(dummyData(16385))) actualCodes := []http2.ErrCode{http2.ErrCodeFrameSize} return TestConnectionError(ctx, http2Conn, actualCodes) }, )) return tg }
Change unicode rep to use Subject text
# -*- coding: utf-8 -*- from django.db import models from website.util import api_v2_url from osf.models.base import BaseModel, ObjectIDMixin class Subject(ObjectIDMixin, BaseModel): """A subject discipline that may be attached to a preprint.""" modm_model_path = 'website.project.taxonomies.Subject' modm_query = None text = models.CharField(null=False, max_length=256, unique=True) # max length on prod: 73 parents = models.ManyToManyField('self', symmetrical=False, related_name='children') def __unicode__(self): return '{} with id {}'.format(self.text, self.id) @property def absolute_api_v2_url(self): return api_v2_url('taxonomies/{}/'.format(self._id)) @property def child_count(self): """For v1 compat.""" return self.children.count() def get_absolute_url(self): return self.absolute_api_v2_url @property def hierarchy(self): if self.parents.exists(): return self.parents.first().hierarchy + [self._id] return [self._id]
# -*- coding: utf-8 -*- from django.db import models from website.util import api_v2_url from osf.models.base import BaseModel, ObjectIDMixin class Subject(ObjectIDMixin, BaseModel): """A subject discipline that may be attached to a preprint.""" modm_model_path = 'website.project.taxonomies.Subject' modm_query = None text = models.CharField(null=False, max_length=256, unique=True) # max length on prod: 73 parents = models.ManyToManyField('self', symmetrical=False, related_name='children') def __unicode__(self): return '{} with id {}'.format(self.name, self.id) @property def absolute_api_v2_url(self): return api_v2_url('taxonomies/{}/'.format(self._id)) @property def child_count(self): """For v1 compat.""" return self.children.count() def get_absolute_url(self): return self.absolute_api_v2_url @property def hierarchy(self): if self.parents.exists(): return self.parents.first().hierarchy + [self._id] return [self._id]
Add rtd import to master
import shutil import os from readthedocs.projects.models import Project slugs = [p.slug for p in Project.objects.all()] build_projects = os.listdir('/home/docs/checkouts/readthedocs.org/user_builds/') final = [] for slug in build_projects: if slug not in slugs and slug.replace('_', '-') not in slugs: final.append(slug) print "To delete: %s" % len(final) for to_del in final: root = '/home/docs/checkouts/readthedocs.org' print "Deleting " + to_del shutil.rmtree('{root}/user_builds/{slug}'.format(root=root, slug=to_del), ignore_errors=True) shutil.rmtree('{root}/media/pdf/{slug}'.format(root=root, slug=to_del), ignore_errors=True) shutil.rmtree('{root}/media/epub/{slug}'.format(root=root, slug=to_del), ignore_errors=True) shutil.rmtree('{root}/media/json/{slug}'.format(root=root, slug=to_del), ignore_errors=True) shutil.rmtree('{root}/media/man/{slug}'.format(root=root, slug=to_del), ignore_errors=True) shutil.rmtree('{root}/media/htmlzip/{slug}'.format(root=root, slug=to_del), ignore_errors=True)
import shutil import os from projects.models import Project slugs = [p.slug for p in Project.objects.all()] build_projects = os.listdir('/home/docs/checkouts/readthedocs.org/user_builds/') final = [] for slug in build_projects: if slug not in slugs and slug.replace('_', '-') not in slugs: final.append(slug) print "To delete: %s" % len(final) for to_del in final: root = '/home/docs/checkouts/readthedocs.org' print "Deleting " + to_del shutil.rmtree('{root}/user_builds/{slug}'.format(root=root, slug=to_del), ignore_errors=True) shutil.rmtree('{root}/media/pdf/{slug}'.format(root=root, slug=to_del), ignore_errors=True) shutil.rmtree('{root}/media/epub/{slug}'.format(root=root, slug=to_del), ignore_errors=True) shutil.rmtree('{root}/media/json/{slug}'.format(root=root, slug=to_del), ignore_errors=True) shutil.rmtree('{root}/media/man/{slug}'.format(root=root, slug=to_del), ignore_errors=True) shutil.rmtree('{root}/media/htmlzip/{slug}'.format(root=root, slug=to_del), ignore_errors=True)
Refactor Zendesk client code for smoketest
# -*- coding: utf-8 -*- "Zendesk" import json import requests from flask import current_app TICKETS_URL = 'https://ministryofjustice.zendesk.com/api/v2/tickets.json' def zendesk_auth(): return ( '{username}/token'.format( username=current_app.config['ZENDESK_API_USERNAME']), current_app.config['ZENDESK_API_TOKEN'] ) def create_ticket(payload): "Create a new Zendesk ticket" return requests.post( TICKETS_URL, data=json.dumps(payload), auth=zendesk_auth(), headers={'content-type': 'application/json'}) def tickets(): "List Zendesk tickets" return requests.get( TICKETS_URL, auth=zendesk_auth())
# -*- coding: utf-8 -*- "Zendesk" import json import requests from flask import current_app TICKETS_URL = 'https://ministryofjustice.zendesk.com/api/v2/tickets.json' def create_ticket(payload): "Create a new Zendesk ticket" return requests.post( TICKETS_URL, data=json.dumps(payload), auth=( '{username}/token'.format( username=current_app.config['ZENDESK_API_USERNAME']), current_app.config['ZENDESK_API_TOKEN'] ), headers={'content-type': 'application/json'})
Update compilerOutputFormatting value in the unit test
<?php class SassHandlerTest extends PHPUnit_Framework_TestCase { /** * @var SassHandler */ private $sassHandler; /** * Path to the directory with fixture files * @var string */ private $fixturesDirectory; protected function setUp() { $this->sassHandler = new SassHandler; $this->sassHandler->compilerPath = __DIR__ . '/../vendor/leafo/scssphp/scss.inc.php'; // Use "compressed" formatting to simplify code with assertions $this->sassHandler->compilerOutputFormatting = SassHandler::OUTPUT_FORMATTING_COMPRESSED; $this->fixturesDirectory = __DIR__ . '/fixtures/'; } /** * Test integration with scssphp compiler */ public function testCompile() { $scssFile = $this->fixturesDirectory . 'compile.scss'; $this->assertEquals( 'body a{color:red;}', $this->sassHandler->compile($scssFile) ); } }
<?php class SassHandlerTest extends PHPUnit_Framework_TestCase { /** * @var SassHandler */ private $sassHandler; /** * Path to the directory with fixture files * @var string */ private $fixturesDirectory; protected function setUp() { $this->sassHandler = new SassHandler; $this->sassHandler->compilerPath = __DIR__ . '/../vendor/leafo/scssphp/scss.inc.php'; // Use "compressed" formatting to simplify code with assertions $this->sassHandler->compilerOutputFormatting = 'compressed'; $this->fixturesDirectory = __DIR__ . '/fixtures/'; } /** * Test integration with scssphp compiler */ public function testCompile() { $scssFile = $this->fixturesDirectory . 'compile.scss'; $this->assertEquals( 'body a{color:red;}', $this->sassHandler->compile($scssFile) ); } }
Remove FLOWER_ prefix for non flower based vars
import os AMPQ_ADMIN_USERNAME = os.getenv('AMQP_ADMIN_USERNAME', 'guest') AMPQ_ADMIN_PASSWORD = os.getenv('AMQP_ADMIN_PASSWORD', 'guest') AMQP_ADMIN_HOST = os.getenv('AMQP_ADMIN_HOST', '172.17.42.1') AMQP_ADMIN_PORT = int(os.getenv('AMQP_ADMIN_PORT', '15672')) DEFAULT_BROKER_API = 'http://%s:%s@%s:%d/api/' \ % (AMPQ_ADMIN_USERNAME, AMPQ_ADMIN_PASSWORD, AMQP_ADMIN_HOST, AMQP_ADMIN_PORT) USERNAME = os.getenv('USERNAME', 'root') PASSWORD = os.getenv('PASSWORD', 'changeit') port = int(os.getenv('FLOWER_PORT', '5555')) broker_api = os.getenv('FLOWER_BROKER_API', DEFAULT_BROKER_API) max_tasks = int(os.getenv('FLOWER_MAX_TASKS', '3600')) basic_auth = [os.getenv('FLOWER_BASIC_AUTH', '%s:%s' % (USERNAME, PASSWORD))]
import os AMPQ_ADMIN_USERNAME = os.getenv('AMQP_ADMIN_USERNAME', 'guest') AMPQ_ADMIN_PASSWORD = os.getenv('AMQP_ADMIN_PASSWORD', 'guest') AMQP_ADMIN_HOST = os.getenv('AMQP_ADMIN_HOST', '172.17.42.1') AMQP_ADMIN_PORT = int(os.getenv('AMQP_ADMIN_PORT', '15672')) DEFAULT_BROKER_API = 'http://%s:%s@%s:%d/api/' \ % (AMPQ_ADMIN_USERNAME, AMPQ_ADMIN_PASSWORD, AMQP_ADMIN_HOST, AMQP_ADMIN_PORT) FLOWER_USERNAME = os.getenv('FLOWER_USERNAME', 'root') FLOWER_PASSWORD = os.getenv('FLOWER_PASSWORD', 'changeit') port = int(os.getenv('FLOWER_PORT', '5555')) broker_api = os.getenv('FLOWER_BROKER_API', DEFAULT_BROKER_API) max_tasks = int(os.getenv('FLOWER_MAX_TASKS', '3600')) basic_auth = [os.getenv('FLOWER_BASIC_AUTH', '%s:%s' % (FLOWER_USERNAME, FLOWER_PASSWORD))]
Select next item with j key
// ==UserScript== // @name Rightmove Enhancement Suite // @namespace https://github.com/chigley/ // @description Keyboard shortcuts // @include http://www.rightmove.co.uk/* // @version 1 // @grant GM_addStyle // @grant GM_getResourceText // @resource style style.css // ==/UserScript== var $ = unsafeWindow.jQuery; GM_addStyle(GM_getResourceText("style")); var listItems = $("[name=summary-list-item]"); var currentlySelected; // Remove grey background on premium listings. Otherwise, my active item doesn't // stand out against such listings $(".premium").css("background", "white"); listItems.click(function () { listItems.removeClass("RES-active-list-item"); $(this).addClass("RES-active-list-item"); currentlySelected = $(this); }); $('body').bind('keyup', function(e) { var code = e.keyCode || e.which; if (e.keyCode == 74) { // j var next = currentlySelected.next("[name=summary-list-item]"); if (next.length == 1) { listItems.removeClass("RES-active-list-item"); next.addClass("RES-active-list-item"); currentlySelected = next; } } });
// ==UserScript== // @name Rightmove Enhancement Suite // @namespace https://github.com/chigley/ // @description Keyboard shortcuts // @include http://www.rightmove.co.uk/* // @version 1 // @grant GM_addStyle // @grant GM_getResourceText // @resource style style.css // ==/UserScript== var $ = unsafeWindow.jQuery; GM_addStyle(GM_getResourceText("style")); var listItems = $("[name=summary-list-item]"); // Remove grey background on premium listings. Otherwise, my active item doesn't // stand out against such listings $(".premium").css("background", "white"); listItems.click(function () { listItems.removeClass("RES-active-list-item"); $(this).addClass("RES-active-list-item"); }); $('body').bind('keyup', function(e) { var code = e.keyCode || e.which; if (e.keyCode == 74) { // j alert("j!"); } });
Check weather data validity on refresh Related to #76
var RefreshWeather = function (options) { options = options || {}; options.elem = options.elem || "#weather-general"; options.update_interval = options.update_interval || 15 * 60 * 1000; var elem = $(options.elem), update_interval; function setWeatherInfo (icon, temperature) { elem.html("<img src='/homecontroller/static/images/" + icon + ".png'><br> " + temperature + "&deg;C"); } function resetWeatherInfo() { elem.html("<i class='fa fa-question-circle'></i>"); } function update() { $.get("/homecontroller/weather/get_json?"+(new Date()).getTime(), function (data) { resetWeatherInfo(); if (data && data.current) { setWeatherInfo(data.current.icon, data.current.feels_like); } }); } function startInterval() { update(); update_interval = setInterval(update, options.update_interval); } function stopInterval() { update_interval = clearInterval(update_interval); } this.update = update; this.startInterval = startInterval; this.stopInterval = stopInterval; }; var refresh_weather; $(document).ready(function () { refresh_weather = new RefreshWeather({"elem": "#weather-general"}); refresh_weather.startInterval(); });
var RefreshWeather = function (options) { options = options || {}; options.elem = options.elem || "#weather-general"; options.update_interval = options.update_interval || 15 * 60 * 1000; var elem = $(options.elem), update_interval; function setWeatherInfo (icon, temperature) { elem.html("<img src='/homecontroller/static/images/" + icon + ".png'><br> " + temperature + "&deg;C"); } function resetWeatherInfo() { elem.html("<i class='fa fa-question-circle'></i>"); } function update() { $.get("/homecontroller/weather/get_json?"+(new Date()).getTime(), function (data) { resetWeatherInfo(); setWeatherInfo(data.current.icon, data.current.feels_like); }); } function startInterval() { update(); update_interval = setInterval(update, options.update_interval); } function stopInterval() { update_interval = clearInterval(update_interval); } this.update = update; this.startInterval = startInterval; this.stopInterval = stopInterval; }; var refresh_weather; $(document).ready(function () { refresh_weather = new RefreshWeather({"elem": "#weather-general"}); refresh_weather.startInterval(); });
Improve LocaleToggle messages definition syntax
/* * * LanguageToggle * */ import React from 'react'; import { connect } from 'react-redux'; import { selectLocale } from '../LanguageProvider/selectors'; import { changeLocale } from '../LanguageProvider/actions'; import { languages } from '../../i18n'; import { createSelector } from 'reselect'; import styles from './styles.scss'; import Toggle from 'components/Toggle'; export class LocaleToggle extends React.Component { // eslint-disable-line render() { const messages = languages.reduce((result, locale) => { const resultsObj = result; resultsObj[locale] = locale.toUpperCase(); return resultsObj; }, {}); return ( <div className={styles.localeToggle}> <Toggle values={languages} messages={messages} onToggle={this.props.onLocaleToggle} /> </div> ); } } LocaleToggle.propTypes = { onLocaleToggle: React.PropTypes.func, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); export function mapDispatchToProps(dispatch) { return { onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
/* * * LanguageToggle * */ import React from 'react'; import { connect } from 'react-redux'; import { selectLocale } from '../LanguageProvider/selectors'; import { changeLocale } from '../LanguageProvider/actions'; import { languages } from '../../i18n'; import { createSelector } from 'reselect'; import styles from './styles.scss'; import Toggle from 'components/Toggle'; export class LocaleToggle extends React.Component { // eslint-disable-line render() { const messages = {}; languages.forEach(locale => { messages[locale] = locale.toUpperCase(); }); return ( <div className={styles.localeToggle}> <Toggle values={languages} messages={messages} onToggle={this.props.onLocaleToggle} /> </div> ); } } LocaleToggle.propTypes = { onLocaleToggle: React.PropTypes.func, }; const mapStateToProps = createSelector( selectLocale(), (locale) => ({ locale }) ); export function mapDispatchToProps(dispatch) { return { onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)), dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
Send msg from bot to channel
const TeleBot = require('telebot'); const config = require('./config'); const bot = new TeleBot({ token: config.token, // Add telegram token bot here. sleep: 1000, // Optional. How often check updates (in ms). timeout: 0, // Optional. Update pulling timeout (0 - short polling). limit: 100, // Optional. Limits the number of updates to be retrieved. retryTimeout: 5000, // Optional. Reconnecting timeout (in ms). }); // console logs bot.on('text', function(msg) { console.log(`[Logs] ${ msg.from.first_name } ${ msg.chat.id } ${ msg.text }`); }); // ping telechan bot bot.on('/ping', msg => { // var id = msg.chat.id; var chan = '@ChannelName'; console.log(chan) let firstName = msg.from.first_name; bot.sendMessage(chan, `Pong,Test...`); }); bot.on('/about', msg => { let id = msg.from.id; let reply = msg.message_id; const execSync = require('child_process').execSync; uptime = execSync('uptime'); bot.sendMessage(id, `Telechan v0.1` + '\n' + uptime, { reply }); }); bot.connect();
const TeleBot = require('telebot'); const config = require('./config'); const bot = new TeleBot({ token: config.token, // Add telegram token bot here. sleep: 1000, // Optional. How often check updates (in ms). timeout: 0, // Optional. Update pulling timeout (0 - short polling). limit: 100, // Optional. Limits the number of updates to be retrieved. retryTimeout: 5000, // Optional. Reconnecting timeout (in ms). }); // console logs bot.on('text', function(msg) { console.log(`[Logs] ${ msg.from.first_name } ${ msg.chat.id } ${ msg.text }`); }); // ping telechan bot.on('/ping', msg => { var id = msg.chat.id; let firstName = msg.from.first_name; bot.sendMessage(id, `Pong, ${ firstName }! Testing`); }); bot.on('/about', msg => { let id = msg.from.id; let reply = msg.message_id; const execSync = require('child_process').execSync; uptime = execSync('uptime'); bot.sendMessage(id, `Telechan v0.1` + '\n' + uptime, { reply }); }); bot.connect();
Fix desktop notifications when changing wallpaper is invoked
#!/usr/bin/env node /* jshint node: true */ 'use strict'; var timer, pattern, interval; var rotate = require('./rotate-wallpaper'); var notify = false; process.on('message', function(params) { pattern = params.pattern; interval = params.interval; timer = setInterval(rotate, interval, pattern); notify = params.notify; rotate(pattern, params.notify).then(function() { process.send({ running: true }); }); }); process.on('SIGUSR1', function() { if (timer) { clearInterval(timer); timer = 0; } else { rotate(pattern).then(function() { timer = setInterval(rotate, interval, pattern); }); } }); process.on('SIGUSR2', function() { if (pattern) { rotate(pattern, notify); } }); process.on('SIGTERM', function() { clearInterval(timer); process.exit(); });
#!/usr/bin/env node /* jshint node: true */ 'use strict'; var timer, pattern, interval; var rotate = require('./rotate-wallpaper'); process.on('message', function(params) { pattern = params.pattern; interval = params.interval; timer = setInterval(rotate, interval, pattern); rotate(pattern, params.notify).then(function() { process.send({ running: true }); }); }); process.on('SIGUSR1', function() { if (timer) { clearInterval(timer); timer = 0; } else { rotate(pattern).then(function() { timer = setInterval(rotate, interval, pattern); }); } }); process.on('SIGUSR2', function() { if (pattern) { rotate(pattern); } }); process.on('SIGTERM', function() { clearInterval(timer); process.exit(); });
Add JSDoc comments to explain what's going on
/** * Checks if the page title contains the given value. * * ``` * this.demoTest = function (client) { * browser.assert.titleContains("Nightwatch"); * }; * ``` * * @method title * @param {string} expected The expected page title substring. * @param {string} [message] Optional log message to display in the output. If missing, one is displayed by default. * @api assertions */ var util = require('util'); exports.assertion = function(expected, msg) { /** * The message which will be used in the test output and * inside the XML reports * @type {string} */ this.message = msg || util.format('Testing if the page title contains "%s".', expected); /** * A value to perform the assertion on. If a function is * defined, its result will be used. * @type {function|*} */ this.expected = expected; /** * The method which performs the actual assertion. It is * called with the result of the value method as the argument. * @type {function} */ this.pass = function(value) { return value.indexOf(this.expected) > -1; }; /** * The method which returns the value to be used on the * assertion. It is called with the result of the command's * callback as argument. * @type {function} */ this.value = function(result) { return result.value; }; /** * Performs a protocol command/action and its result is * passed to the value method via the callback argument. * @type {function} */ this.command = function(callback) { this.api.title(callback); return this; }; };
/** * Checks if the page title contains the given value. * * ``` * this.demoTest = function (client) { * browser.assert.titleContains("Nightwatch"); * }; * ``` * * @method title * @param {string} expected The expected page title substring. * @param {string} [message] Optional log message to display in the output. If missing, one is displayed by default. * @api assertions */ var util = require('util'); exports.assertion = function(expected, msg) { this.message = msg || util.format('Testing if the page title contains "%s".', expected); this.expected = expected; this.pass = function(value) { return value.indexOf(this.expected) > -1; }; this.value = function(result) { return result.value; }; this.command = function(callback) { this.api.title(callback); return this; }; };
Remove async that's not required for now.
import fs from 'fs' import http from 'http'; import path from 'path'; import React from 'react'; import Baobab from 'baobab'; import {root} from 'baobab-react/higher-order'; import defaultData from './data'; import Html from './components/Html'; import Layout from './components/Layout'; function renderHtml(res, data, webpackAssets) { const BaobabEnrichedLayout = root(Layout, data); const markup = React.renderToString(<BaobabEnrichedLayout />); const html = React.renderToStaticMarkup( <Html webpackAssets={webpackAssets} markup={markup} state={data.get()} /> ); res.send(`<!doctype html>\n${html}`); } export default function(req, res, next, webpackAssets) { defaultData.addedKey1ThatWorks = 'addedValue1'; const data = new Baobab(defaultData, { syncwrite: true }); //data.select('addedKey2ThatFails').set('addedValue2'); renderHtml(res, data, webpackAssets); }
import fs from 'fs' import http from 'http'; import path from 'path'; import React from 'react'; import Baobab from 'baobab'; import {root} from 'baobab-react/higher-order'; import defaultData from './data'; import Html from './components/Html'; import Layout from './components/Layout'; function renderHtml(res, data, webpackAssets) { const BaobabEnrichedLayout = root(Layout, data); const markup = React.renderToString(<BaobabEnrichedLayout />); const html = React.renderToStaticMarkup( <Html webpackAssets={webpackAssets} markup={markup} state={data.get()} /> ); res.send(`<!doctype html>\n${html}`); } export default async function(req, res, next, webpackAssets) { defaultData.addedKey1ThatWorks = 'addedValue1'; const data = new Baobab(defaultData, { syncwrite: true }); //data.select('addedKey2ThatFails').set('addedValue2'); renderHtml(res, data, webpackAssets); }
Move framework downloads to github release
#!/usr/bin/env python import sys import os from lib.util import safe_mkdir, extract_zip, tempdir, download SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) FRAMEWORKS_URL = 'https://github.com/atom/atom-shell/releases/download/v0.11.10' def main(): os.chdir(SOURCE_ROOT) safe_mkdir('frameworks') download_and_unzip('Mantle') download_and_unzip('ReactiveCocoa') download_and_unzip('Squirrel') def download_and_unzip(framework): zip_path = download_framework(framework) if zip_path: extract_zip(zip_path, 'frameworks') def download_framework(framework): framework_path = os.path.join('frameworks', framework) + '.framework' if os.path.exists(framework_path): return filename = framework + '.framework.zip' url = FRAMEWORKS_URL + '/' + filename download_dir = tempdir(prefix='atom-shell-') path = os.path.join(download_dir, filename) download('Download ' + framework, url, path) return path if __name__ == '__main__': sys.exit(main())
#!/usr/bin/env python import sys import os from lib.util import safe_mkdir, extract_zip, tempdir, download SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) FRAMEWORKS_URL = 'http://atom-alpha.s3.amazonaws.com' def main(): os.chdir(SOURCE_ROOT) safe_mkdir('frameworks') download_and_unzip('Mantle') download_and_unzip('ReactiveCocoa') download_and_unzip('Squirrel') def download_and_unzip(framework): zip_path = download_framework(framework) if zip_path: extract_zip(zip_path, 'frameworks') def download_framework(framework): framework_path = os.path.join('frameworks', framework) + '.framework' if os.path.exists(framework_path): return filename = framework + '.framework.zip' url = FRAMEWORKS_URL + '/' + filename download_dir = tempdir(prefix='atom-shell-') path = os.path.join(download_dir, filename) download('Download ' + framework, url, path) return path if __name__ == '__main__': sys.exit(main())
Bump client library version to 0.1.0.dev3
from setuptools import setup requirements = [ 'pyserial', ] with open('README') as f: long_description = f.read() setup( name='removinator', version='0.1.0.dev3', description='A library for controlling the Smart Card Removinator', long_description=long_description, url='https://github.com/nkinder/smart-card-removinator', author='Smart Card Removinator contributors', author_email='nkinder@redhat.com', license='APLv2', packages=['removinator'], classifiers=[ 'Intended Audience :: Developers', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Libraries :: Python Modules', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=requirements, )
from setuptools import setup requirements = [ 'pyserial', ] with open('README') as f: long_description = f.read() setup( name='removinator', version='0.1.0.dev2', description='A library for controlling the Smart Card Removinator', long_description=long_description, url='https://github.com/nkinder/smart-card-removinator', author='Smart Card Removinator contributors', author_email='nkinder@redhat.com', license='APLv2', packages=['removinator'], classifiers=[ 'Intended Audience :: Developers', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Libraries :: Python Modules', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=requirements, )
Upgrade libchromiumcontent to remove dom storage quota Closes #897.
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e375124044f9044ac88076eba0cd17361ee0997c' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'aa87035cc012ce0d533bb56b947bca81a6e71b82' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
Check if request is a built-in module
var Module = require('module') var path = require('path') var fs = require('fs') function exists (target, extensions) { if (fs.existsSync(target)) { return target } if (path.extname(target) === '') { for (var i = 0; i < extensions.length; i++) { var resolvedPath = target + extensions[i] if (fs.existsSync(resolvedPath)) { return resolvedPath } } } } module.exports = function resolver (request, parent) { if (typeof request !== 'string' || /^[./]/.test(request)) { return request } // Check if it's a built-in module if (!Module._resolveLookupPaths(request, parent)[1].length) { return request } var resolvedPath var i = 0 var extensions = Object.keys(Module._extensions) for (i = 0; i < parent.paths.length; i++) { resolvedPath = exists(path.resolve(parent.paths[i], request), extensions) if (resolvedPath) { return resolvedPath } } for (i = 0; i < parent.paths.length; i++) { resolvedPath = path.resolve(parent.paths[i].slice(0, parent.paths[i].lastIndexOf('node_modules')), request) resolvedPath = exists(resolvedPath, extensions) if (resolvedPath) { return resolvedPath } } return request }
var Module = require('module') var path = require('path') var fs = require('fs') function exists (target, extensions) { if (fs.existsSync(target)) { return target } if (path.extname(target) === '') { for (var i = 0; i < extensions.length; i++) { var resolvedPath = target + extensions[i] if (fs.existsSync(resolvedPath)) { return resolvedPath } } } } module.exports = function resolver (request, parent) { if (typeof request !== 'string' || /^[./]/.test(request)) { return request } var resolvedPath var i = 0 var extensions = Object.keys(Module._extensions) for (i = 0; i < parent.paths.length; i++) { resolvedPath = exists(path.resolve(parent.paths[i], request), extensions) if (resolvedPath) { return resolvedPath } } for (i = 0; i < parent.paths.length; i++) { resolvedPath = path.resolve(parent.paths[i].slice(0, parent.paths[i].lastIndexOf('node_modules')), request) resolvedPath = exists(resolvedPath, extensions) if (resolvedPath) { return resolvedPath } } return request }
Fix to deal with invalid commands.
# coding: utf-8 """ Mission simulation. """ from rover import Plateau, Rover, Heading, Command if __name__ == '__main__': instructions = open('instructions.txt', 'r') # Prepare the plateau to landings. data = instructions.readline().split() x, y = map(int, data) plateau = Plateau(x, y) # Deploy Rovers on the plateau. for data in instructions: x, y, heading = data.split() rover = Rover(int(x), int(y), getattr(Heading, heading), plateau) # Parse and run instructions. commands = instructions.readline().strip() for cmd in commands: command = getattr(Command, cmd, None) rover.execute(command) print(rover) instructions.close()
# coding: utf-8 """ Mission simulation. """ from rover import Plateau, Rover, Heading, Command if __name__ == '__main__': instructions = open('instructions.txt', 'r') # Prepare the plateau to landings. data = instructions.readline().split() x, y = map(int, data) plateau = Plateau(x, y) # Deploy Rovers on the plateau. for data in instructions: x, y, heading = data.split() rover = Rover(int(x), int(y), getattr(Heading, heading), plateau) # Parse and run instructions. commands = instructions.readline().strip() for cmd in commands: command = getattr(Command, cmd) rover.execute(command) print(rover) instructions.close()
Add tumblr->yahoo info for server
'use strict'; var hosts = { 'bbc.co.uk': 'bbc', 'm.bbc.co.uk': 'bbc', 'reddit.com': 'reddit', 'www.reddit.com': 'reddit', 'condenast.co.uk': 'condenast' 'tumblr.com' : 'tumblr' }; var organisations = { 'bbc': { 'owner': null, 'info': 'British Broadcasting Corporation' }, 'reddit': { 'owner': 'condenast', 'info': 'Reddit' }, 'condenast': { 'owner': 'advancepublications', 'info': 'Condé Nast' }, 'advancepublications': { 'owner': null, 'info': 'Advance Publications' }, 'tumblr': { 'owner': 'yahoo', 'info': 'Tumblr' }, 'yahoo': { 'owner': null, 'info': 'Yahoo' } }; function getInfoString (organisationKey) { var infoString = ''; for (;;) { var organisation = organisations[organisationKey]; console.log(organisation); if (!organisation) { return infoString; } if (infoString.length) { infoString += " -> "; } infoString += organisation.info; organisationKey = organisation.owner; } }; module.exports = { getInfo: function (host) { console.log(host); var siteKey = hosts[host]; return getInfoString(siteKey); } };
'use strict'; var hosts = { 'bbc.co.uk': 'bbc', 'm.bbc.co.uk': 'bbc', 'reddit.com': 'reddit', 'www.reddit.com': 'reddit', 'condenast.co.uk': 'condenast' }; var organisations = { 'bbc': { 'owner': null, 'info': 'British Broadcasting Corporation' }, 'reddit': { 'owner': 'condenast', 'info': 'Reddit' }, 'condenast': { 'owner': 'advancepublications', 'info': 'Condé Nast' }, 'advancepublications': { 'owner': null, 'info': 'Advance Publications' } }; function getInfoString (organisationKey) { var infoString = ''; for (;;) { var organisation = organisations[organisationKey]; console.log(organisation); if (!organisation) { return infoString; } if (infoString.length) { infoString += " -> "; } infoString += organisation.info; organisationKey = organisation.owner; } }; module.exports = { getInfo: function (host) { console.log(host); var siteKey = hosts[host]; return getInfoString(siteKey); } };
patron-client: Fix for reducer hot loading
import { browserHistory } from 'react-router' import thunkMiddleware from 'redux-thunk' import { createStore, applyMiddleware, compose } from 'redux' import { routerMiddleware } from 'react-router-redux' import createLogger from 'redux-logger' import persistState from 'redux-localstorage' import adapter from 'redux-localstorage/lib/adapters/localStorage' import filter from 'redux-localstorage-filter' import rootReducer from '../reducers' const storage = compose( filter([ 'application.locale' ]) )(adapter(window.localStorage)) const reduxRouterMiddleware = routerMiddleware(browserHistory) const middleware = [ thunkMiddleware, reduxRouterMiddleware ] if (process.env.NODE_ENV !== 'production') { const loggerMiddleware = createLogger() middleware.push(loggerMiddleware) } const composeEnhancers = process.env.NODE_ENV !== 'production' && typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose export default (initialState) => { const store = createStore( rootReducer, initialState, composeEnhancers( applyMiddleware(...middleware), persistState(storage, 'patron-client') )) if (module.hot) { module.hot.accept('../reducers', () => { store.replaceReducer(require('../reducers').default) }) } return store }
import { browserHistory } from 'react-router' import thunkMiddleware from 'redux-thunk' import { createStore, applyMiddleware, compose } from 'redux' import { routerMiddleware } from 'react-router-redux' import createLogger from 'redux-logger' import persistState from 'redux-localstorage' import adapter from 'redux-localstorage/lib/adapters/localStorage' import filter from 'redux-localstorage-filter' import rootReducer from '../reducers' const storage = compose( filter([ 'application.locale' ]) )(adapter(window.localStorage)) const reduxRouterMiddleware = routerMiddleware(browserHistory) const middleware = [ thunkMiddleware, reduxRouterMiddleware ] if (process.env.NODE_ENV !== 'production') { const loggerMiddleware = createLogger() middleware.push(loggerMiddleware) } const composeEnhancers = process.env.NODE_ENV !== 'production' && typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose export default (initialState) => { const store = createStore( rootReducer, initialState, composeEnhancers( applyMiddleware(...middleware), persistState(storage, 'patron-client') )) if (module.hot) { module.hot.accept('../reducers', () => { store.replaceReducer(require('../reducers')) }) } return store }
Fix spaces in previous commit
const webpack = require('webpack'); const ora = require('ora'); const rm = require('rimraf'); const chalk = require('chalk'); const config = require('./webpack.config.js'); const env = process.env.NODE_ENV || 'development'; const target = process.env.TARGET || 'web'; const spinner = ora(env === 'production' ? 'building for production...' : 'building development version...'); spinner.start(); rm('./www/', (removeErr) => { if (removeErr) throw removeErr; webpack(config, (err, stats) => { if (err) throw err; spinner.stop(); process.stdout.write(`${stats.toString({ colors: true, modules: false, children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build. chunks: false, chunkModules: false, })}\n\n`); if (stats.hasErrors()) { console.log(chalk.red('Build failed with errors.\n')); process.exit(1); } console.log(chalk.cyan('Build complete.\n')); if (env == 'development') process.exit(0); }); });
const webpack = require('webpack'); const ora = require('ora'); const rm = require('rimraf'); const chalk = require('chalk'); const config = require('./webpack.config.js'); const env = process.env.NODE_ENV || 'development'; const target = process.env.TARGET || 'web'; const spinner = ora(env === 'production' ? 'building for production...' : 'building development version...'); spinner.start(); rm('./www/', (removeErr) => { if (removeErr) throw removeErr; webpack(config, (err, stats) => { if (err) throw err; spinner.stop(); process.stdout.write(`${stats.toString({ colors: true, modules: false, children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build. chunks: false, chunkModules: false, })}\n\n`); if (stats.hasErrors()) { console.log(chalk.red('Build failed with errors.\n')); process.exit(1); } console.log(chalk.cyan('Build complete.\n')); if (env == 'development') process.exit(0); }); });
Add global for default template name.
""" ydf/templating ~~~~~~~~~~~~~~ Contains functions to be exported into the Jinja2 environment and accessible from templates. """ import jinja2 import os from ydf import instructions, __version__ DEFAULT_TEMPLATE_NAME = 'default.tpl' DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates') def render_vars(yaml_vars): """ Build a dict containing all variables accessible to a template during the rendering process. This is a merge of the YAML variables parsed from the file + build variables defined by :mod:`~ydf` itself. :param yaml_vars: Parsed from the parsed YAML file. :return: Dict of all variables available to template. """ return dict(ydf=dict(version=__version__), **yaml_vars) def environ(path=DEFAULT_TEMPLATE_PATH, **kwargs): """ Build a Jinja2 environment for the given template directory path and options. :param path: Path to search for Jinja2 template files :param kwargs: Options to configure the environment :return: :class:`~jinja2.Environment` instance """ kwargs.setdefault('trim_blocks', True) kwargs.setdefault('lstrip_blocks', True) env = jinja2.Environment(loader=jinja2.FileSystemLoader(path), **kwargs) env.globals[instructions.convert_instruction.__name__] = instructions.convert_instruction return env
""" ydf/templating ~~~~~~~~~~~~~~ Contains functions to be exported into the Jinja2 environment and accessible from templates. """ import jinja2 import os from ydf import instructions, __version__ DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates') def render_vars(yaml_vars): """ Build a dict containing all variables accessible to a template during the rendering process. This is a merge of the YAML variables parsed from the file + build variables defined by :mod:`~ydf` itself. :param yaml_vars: Parsed from the parsed YAML file. :return: Dict of all variables available to template. """ return dict(ydf=dict(version=__version__), **yaml_vars) def environ(path=DEFAULT_TEMPLATE_PATH, **kwargs): """ Build a Jinja2 environment for the given template directory path and options. :param path: Path to search for Jinja2 template files :param kwargs: Options to configure the environment :return: :class:`~jinja2.Environment` instance """ kwargs.setdefault('trim_blocks', True) kwargs.setdefault('lstrip_blocks', True) env = jinja2.Environment(loader=jinja2.FileSystemLoader(path), **kwargs) env.globals[instructions.convert_instruction.__name__] = instructions.convert_instruction return env
Implement PEP 246 compliant environment markers
#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except ImportError: tests_require = ['mock'] else: tests_require = [] with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], extras_require={ 'mock:"2" in python_version': ['mock'] }, tests_require = tests_require, test_suite='tests', zip_safe=True)
#!/usr/bin/env python # -*- encoding: utf-8 -*- from setuptools import setup try: from unittest import mock # noqa except: kwargs = { 'tests_require': 'mock', 'extras_require': { 'mock': 'mock' } } else: kwargs = {} with open('README.rst') as f: readme = f.read() setup( name='syringe', version='0.3.0', author='Remco Haszing', author_email='remcohaszing@gmail.com', url='https://github.com/remcohaszing/python-syringe', license='MIT', description='A simple dependency injection library', long_description=readme, py_modules=['syringe'], test_suite='tests', zip_safe=True, **kwargs)
Fix for usage of PagingAndSortingRepository
/** * Copyright 2015 Smart Community Lab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it.smartcommunitylab.carpooling.mongo.repos; import it.smartcommunitylab.carpooling.model.Travel; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface TravelRepository extends PagingAndSortingRepository<Travel, String>, TravelRepositoryCustom { @Query("{'userId':?0}") List<Travel> findTravelByDriverId(String userId); @Query("{'userId':?0}") Page<Travel> findTravelByDriverId(String userId, Pageable pageable); @Query("{'id':?0, 'userId':?1}") Travel findTravelByIdAndDriverId(String id, String userId); }
/** * Copyright 2015 Smart Community Lab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it.smartcommunitylab.carpooling.mongo.repos; import it.smartcommunitylab.carpooling.model.Travel; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; public interface TravelRepository extends MongoRepository<Travel, String>, TravelRepositoryCustom { @Query("{'userId':?0}") List<Travel> findTravelByDriverId(String userId); @Query("{'id':?0, 'userId':?1}") Travel findTravelByIdAndDriverId(String id, String userId); }
Change type to shipment in dispatching.
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class EcontDispatching extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->create('econt_dispatching', function (Blueprint $table) { $table->unsignedInteger('settlement_id'); $table->enum('direction', ['from', 'to'])->index('idx_direction'); $table->enum('shipment', ['courier', 'cargo_pallet', 'cargo_express', 'post'])->index('idx_shipment'); $table->unsignedInteger('office_code'); $table->primary(['settlement_id', 'direction', 'shipment', 'office_code']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->dropIfExists('econt_dispatching'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class EcontDispatching extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->create('econt_dispatching', function (Blueprint $table) { $table->unsignedInteger('settlement_id'); $table->enum('direction', ['from', 'to'])->index('idx_direction'); $table->enum('shipment', ['courier', 'cargo_pallet', 'cargo_express', 'post'])->index('idx_shipment'); $table->unsignedInteger('office_code'); $table->primary(['settlement_id', 'direction', 'type', 'office_code']); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::setConnection(DB::connection(Config::get('econt.connection')))->dropIfExists('econt_dispatching'); } }
Change 1 based range so it counts up to n
#!/usr/bin/env python from nodes import Node class Sort(Node): char = "S" args = 1 results = 1 @Node.test_func([[2,3,4,1]], [[1,2,3,4]]) @Node.test_func(["test"], ["estt"]) def func(self, a: Node.indexable): """sorted(a) - returns the same type as given""" if isinstance(a, tuple): return [tuple(sorted(a))] if isinstance(a, str): return "".join(sorted(a)) return [sorted(a)] @Node.test_func([3], [[1,2,3]]) def one_range(self, a:int): """range(1,a)""" return [list(range(1,a+1))]
#!/usr/bin/env python from nodes import Node class Sort(Node): char = "S" args = 1 results = 1 @Node.test_func([[2,3,4,1]], [[1,2,3,4]]) @Node.test_func(["test"], ["estt"]) def func(self, a: Node.indexable): """sorted(a) - returns the same type as given""" if isinstance(a, tuple): return [tuple(sorted(a))] if isinstance(a, str): return "".join(sorted(a)) return [sorted(a)] @Node.test_func([3], [[1,2]]) def one_range(self, a:int): """range(1,a)""" return [list(range(1,a))]
Add link to contributors graph
<?php /** * The template for displaying the footer. * * Contains the closing of the #content div and all content after * * @package socket.io-website */ ?> </div><!-- #content --> <footer id="colophon" class="site-footer" role="contentinfo"> <div class="site-info"> <span class="footer-left">SOCKET.IO IS OPEN-SOURCE (MIT) AND RUN BY <a href="https://github.com/LearnBoost/socket.io/graphs/contributors">CONTRIBUTORS</a></span> <span class="footer-right"><a href="http://automattic.com">SUPPORTED BY<div id="a8c-image"></div></a></span> </div><!-- .site-info --> </footer><!-- #colophon --> </div><!-- #page --> <?php wp_footer(); ?> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://cdn.socket.io/socket.io-1.0.0-pre5.js"></script> <script src="/wp-content/themes/socket.io-website/js/javascripts.js"></script> <?php if (is_home()): ?> <script src="/wp-content/themes/socket.io-website/js/home.js"></script> <?php endif; ?> </body> </html>
<?php /** * The template for displaying the footer. * * Contains the closing of the #content div and all content after * * @package socket.io-website */ ?> </div><!-- #content --> <footer id="colophon" class="site-footer" role="contentinfo"> <div class="site-info"> <span class="footer-left">SOCKET.IO IS OPEN-SOURCE (MIT) AND RUN BY <a href="#">CONTRIBUTORS</a></span> <span class="footer-right"><a href="http://automattic.com">SUPPORTED BY<div id="a8c-image"></div></a></span> </div><!-- .site-info --> </footer><!-- #colophon --> </div><!-- #page --> <?php wp_footer(); ?> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://cdn.socket.io/socket.io-1.0.0-pre5.js"></script> <script src="/wp-content/themes/socket.io-website/js/javascripts.js"></script> <?php if (is_home()): ?> <script src="/wp-content/themes/socket.io-website/js/home.js"></script> <?php endif; ?> </body> </html>
Update parseLxcInfo to comply with new lxc1.0 format Docker-DCO-1.1-Signed-off-by: Guillaume J. Charmes <guillaume@charmes.net> (github: creack)
package lxc import ( "bufio" "errors" "strconv" "strings" ) var ( ErrCannotParse = errors.New("cannot parse raw input") ) type lxcInfo struct { Running bool Pid int } func parseLxcInfo(raw string) (*lxcInfo, error) { if raw == "" { return nil, ErrCannotParse } var ( err error s = bufio.NewScanner(strings.NewReader(raw)) info = &lxcInfo{} ) for s.Scan() { text := s.Text() if s.Err() != nil { return nil, s.Err() } parts := strings.Split(text, ":") if len(parts) < 2 { continue } switch strings.ToLower(strings.TrimSpace(parts[0])) { case "state": info.Running = strings.TrimSpace(parts[1]) == "RUNNING" case "pid": info.Pid, err = strconv.Atoi(strings.TrimSpace(parts[1])) if err != nil { return nil, err } } } return info, nil }
package lxc import ( "bufio" "errors" "strconv" "strings" ) var ( ErrCannotParse = errors.New("cannot parse raw input") ) type lxcInfo struct { Running bool Pid int } func parseLxcInfo(raw string) (*lxcInfo, error) { if raw == "" { return nil, ErrCannotParse } var ( err error s = bufio.NewScanner(strings.NewReader(raw)) info = &lxcInfo{} ) for s.Scan() { text := s.Text() if s.Err() != nil { return nil, s.Err() } parts := strings.Split(text, ":") if len(parts) < 2 { continue } switch strings.TrimSpace(parts[0]) { case "state": info.Running = strings.TrimSpace(parts[1]) == "RUNNING" case "pid": info.Pid, err = strconv.Atoi(strings.TrimSpace(parts[1])) if err != nil { return nil, err } } } return info, nil }
Replace .map with .some, get rid of intermediate array
import { enqueueRender } from './component'; export let i = 0; /** * * @param {any} defaultValue */ export function createContext(defaultValue) { let context = { _id: '__cC' + i++, _defaultValue: defaultValue }; function Consumer(props, context) { return props.children(context); } Consumer.contextType = context; context.Consumer = Consumer; let ctx = {}; function initProvider(comp) { const subs = []; comp.getChildContext = () => { ctx[context._id] = comp; return ctx; }; comp.shouldComponentUpdate = props => { subs.some(c => { // Check if still mounted if (c._parentDom) { c.context = props.value; enqueueRender(c); } }); }; comp.sub = (c) => { subs.push(c); let old = c.componentWillUnmount; c.componentWillUnmount = () => { subs.splice(subs.indexOf(c), 1); old && old(); }; }; } function Provider(props) { if (!this.getChildContext) initProvider(this); return props.children; } context.Provider = Provider; return context; }
import { enqueueRender } from './component'; export let i = 0; /** * * @param {any} defaultValue */ export function createContext(defaultValue) { let context = { _id: '__cC' + i++, _defaultValue: defaultValue }; function Consumer(props, context) { return props.children(context); } Consumer.contextType = context; context.Consumer = Consumer; let ctx = {}; function initProvider(comp) { const subs = []; comp.getChildContext = () => { ctx[context._id] = comp; return ctx; }; comp.shouldComponentUpdate = props => { subs.map(c => { // Check if still mounted if (c._parentDom) { c.context = props.value; enqueueRender(c); } }); }; comp.sub = (c) => { subs.push(c); let old = c.componentWillUnmount; c.componentWillUnmount = () => { subs.splice(subs.indexOf(c), 1); old && old(); }; }; } function Provider(props) { if (!this.getChildContext) initProvider(this); return props.children; } context.Provider = Provider; return context; }
Set UTC time zone for DB time conversion
const Errors = use('core/errors'); const DefaultProperty = require('./default'); class DateProperty extends DefaultProperty { constructor() { super(); this._addValidator((value, propertyName) => { const originalValue = value; if (typeof value !== 'object') { value = new Date(value); } if (value && (!(value instanceof Date) || isNaN(value.getTime()))) { throw new Errors.Validation(`property ${propertyName} should be a valid DateTime, given '${originalValue}'`); } }); this._inputModification = (value) => { return (typeof value === "object" && value instanceof Date) ? value : new Date(value + (value.length > 10 ? ' Z' : '') ); }; } } module.exports = DateProperty;
const Errors = use('core/errors'); const DefaultProperty = require('./default'); class DateProperty extends DefaultProperty { constructor() { super(); this._addValidator((value, propertyName) => { const originalValue = value; if (typeof value !== 'object') { value = new Date(value); } if (value && (!(value instanceof Date) || isNaN(value.getTime()))) { throw new Errors.Validation(`property ${propertyName} should be a valid DateTime, given '${originalValue}'`); } }); this._inputModification = (value) => { return (typeof value === "object" && value instanceof Date) ? value : new Date(value); }; } } module.exports = DateProperty;
Add more assertions find key near
package dht import ( "testing" assert "github.com/stretchr/testify/assert" ) func TestFindKeysNearestTo(t *testing.T) { s, err := newStore() assert.Nil(t, err) s.Put(KeyPrefixPeer+"a1", "0.0.0.0", true) s.Put(KeyPrefixPeer+"a2", "0.0.0.1", true) s.Put(KeyPrefixPeer+"a3", "0.0.0.3", true) s.Put(KeyPrefixPeer+"a4", "0.0.0.4", true) s.Put(KeyPrefixPeer+"a5", "0.0.0.5", true) k1, err := s.FindKeysNearestTo(KeyPrefixPeer, KeyPrefixPeer+"a1", 1) assert.Nil(t, err) k2, err := s.FindKeysNearestTo(KeyPrefixPeer, KeyPrefixPeer+"a2", 1) assert.Nil(t, err) assert.NotEqual(t, k1[0], k2[0]) assert.Equal(t, trimKey(k1[0], KeyPrefixPeer), "a1") assert.Equal(t, trimKey(k2[0], KeyPrefixPeer), "a2") }
package dht import ( "testing" assert "github.com/stretchr/testify/assert" ) func TestFindKeysNearestToNotEqual(t *testing.T) { s, err := newStore() assert.Nil(t, err) s.Put(KeyPrefixPeer+"a1", "0.0.0.0", true) s.Put(KeyPrefixPeer+"a2", "0.0.0.1", true) s.Put(KeyPrefixPeer+"a3", "0.0.0.3", true) s.Put(KeyPrefixPeer+"a4", "0.0.0.4", true) s.Put(KeyPrefixPeer+"a5", "0.0.0.5", true) k1, err := s.FindKeysNearestTo(KeyPrefixPeer, KeyPrefixPeer+"a1", 1) assert.Nil(t, err) k2, err := s.FindKeysNearestTo(KeyPrefixPeer, KeyPrefixPeer+"a2", 1) assert.Nil(t, err) assert.NotEqual(t, k1, k2) }
Update the test for character count
import { expect } from './spec_helper' import * as api from '../src/api' describe('api.js', () => { it('.communitiesPath', () => { expect(api.communitiesPath).to.equal('https://ello-staging.herokuapp.com/api/v2/interest_categories/members?name=onboarding&per_page=25') }) it('.awesomePeoplePath', () => { expect(api.awesomePeoplePath).to.equal('https://ello-staging.herokuapp.com/api/v2/discover/users/onboarding?per_page=25') }) it('.relationshipBatchPath', () => { expect(api.relationshipBatchPath).to.equal('https://ello-staging.herokuapp.com/api/v2/relationships/batches') }) it('.profilePath', () => { expect(api.profilePath).to.equal('https://ello-staging.herokuapp.com/api/v2/profile') }) it('.s3CredentialsPath', () => { expect(api.s3CredentialsPath).to.equal('https://ello-staging.herokuapp.com/api/v2/assets/credentials') }) })
import { expect } from './spec_helper' import * as api from '../src/api' describe('api.js', () => { it('.communitiesPath', () => { expect(api.communitiesPath).to.equal('https://ello-staging.herokuapp.com/api/v2/interest_categories/members?name=onboarding&per_page=25') }) it('.awesomePeoplePath', () => { expect(api.awesomePeoplePath).to.equal('https://ello-staging.herokuapp.com/api/v2/discover/users/onboarding?per_page=20') }) it('.relationshipBatchPath', () => { expect(api.relationshipBatchPath).to.equal('https://ello-staging.herokuapp.com/api/v2/relationships/batches') }) it('.profilePath', () => { expect(api.profilePath).to.equal('https://ello-staging.herokuapp.com/api/v2/profile') }) it('.s3CredentialsPath', () => { expect(api.s3CredentialsPath).to.equal('https://ello-staging.herokuapp.com/api/v2/assets/credentials') }) })
Change minimimum required PHP version to 5.3.23 - Remove [] array notation
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZF\ContentValidation; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; class ContentValidationListenerFactory implements FactoryInterface { /** * @param ServiceLocatorInterface $services * @return ContentValidationListener */ public function createService(ServiceLocatorInterface $services) { $config = array(); if ($services->has('Config')) { $allConfig = $services->get('Config'); if (isset($allConfig['zf-content-validation'])) { $config = $allConfig['zf-content-validation']; } } return new ContentValidationListener($config, $services); } }
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZF\ContentValidation; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; class ContentValidationListenerFactory implements FactoryInterface { /** * @param ServiceLocatorInterface $services * @return ContentValidationListener */ public function createService(ServiceLocatorInterface $services) { $config = []; if ($services->has('Config')) { $allConfig = $services->get('Config'); if (isset($allConfig['zf-content-validation'])) { $config = $allConfig['zf-content-validation']; } } return new ContentValidationListener($config, $services); } }
Add tests and configuration for editing
<?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. */ declare(strict_types=1); namespace Sylius\Component\Core\Formatter; final class StringInflector { public static function nameToCode(string $value): string { return str_replace([' ', '-'], '_', $value); } public static function nameToSlug(string $value): string { return str_replace([' '], '-', strtolower($value)); } public static function nameToLowercaseCode(string $value): string { return strtolower(self::nameToCode($value)); } public static function nameToUppercaseCode(string $value): string { return strtoupper(self::nameToCode($value)); } private function __construct() { } }
<?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. */ declare(strict_types=1); namespace Sylius\Component\Core\Formatter; final class StringInflector { public static function nameToCode(string $value): string { return str_replace([' ', '-'], '_', $value); } public static function nameToLowercaseCode(string $value): string { return strtolower(self::nameToCode($value)); } public static function nameToUppercaseCode(string $value): string { return strtoupper(self::nameToCode($value)); } private function __construct() { } }
Fix end to end testing by increasing mocha timeout Signed-off-by: Joe Walker <7a17872fbb32c7d760c9a16ee3076daead11efcf@mozilla.com>
/* eslint prefer-arrow-callback: 0 */ import expect from 'expect'; import { Application } from 'spectron'; import { quickTest } from '../../build-config'; import { getBuiltExecutable } from '../../build/utils'; describe('application launch', function() { if (quickTest) { it.skip('all tests'); return; } this.timeout(20000); const executable = getBuiltExecutable(); beforeEach(function() { this.app = new Application({ path: executable.fullPath, cwd: executable.cwd, env: process.env, }); return this.app.start(); }); it('shows an initial window', async function() { const count = await this.app.client.getWindowCount(); expect(count).toEqual(1); }); afterEach(function() { if (this.app && this.app.isRunning()) { return this.app.stop(); } return undefined; }); });
/* eslint prefer-arrow-callback: 0 */ import expect from 'expect'; import { Application } from 'spectron'; import { quickTest } from '../../build-config'; import { getBuiltExecutable } from '../../build/utils'; describe('application launch', function() { if (quickTest) { it.skip('all tests'); return; } this.timeout(10000); const executable = getBuiltExecutable(); beforeEach(function() { this.app = new Application({ path: executable.fullPath, cwd: executable.cwd, env: process.env, }); return this.app.start(); }); it('shows an initial window', async function() { const count = await this.app.client.getWindowCount(); expect(count).toEqual(1); }); afterEach(function() { if (this.app && this.app.isRunning()) { return this.app.stop(); } return undefined; }); });
Update to appease the inquirer
'use strict'; var taskOpts = require('./tasks'); var _ = require('lodash'); module.exports = function(kbox, drupal, appName) { var drushVersions = _.pluck(drupal, 'drush'); // Add an option kbox.create.add(appName, { option: { name: 'drush-version', task: taskOpts.drushVersion, inquire: { type: 'list', message: 'Major Drush version?', default: function(answers) { if (answers['drupal-version']) { return drupal[answers['drupal-version']].drush; } else { return '6'; } }, choices: drushVersions }, conf: { type: 'plugin', plugin: 'kalabox-plugin-drush', key: 'drush-version' } } }); };
'use strict'; var taskOpts = require('./tasks'); module.exports = function(kbox, appName) { var deps = kbox.core.deps; // Add an option kbox.create.add(appName, { option: { name: 'drush-version', task: taskOpts.drushVersion, properties: { message: 'Drush version'.green, required: false, type: 'string', validator: /drush(5|6|7)/, warning: 'Answer must be drush plus a major version. ie "drush6".', default: 'drush6' }, conf: { type: 'plugin', plugin: 'kalabox-plugin-drush', key: 'drush-version' } } }); };
Make sure the UUIDs are unique too :)
<?php if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) { print "This script must be run from the command line\n"; exit(); } define('INSTALLDIR', realpath(dirname(__FILE__) . '/..')); define('STATUSNET', true); require_once INSTALLDIR . '/lib/common.php'; class UUIDTest extends PHPUnit_Framework_TestCase { public function testGenerate() { $result = UUID::gen(); $this->assertRegExp('/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/', $result); // Check version number $this->assertEquals(0x4000, hexdec(substr($result, 14, 4)) & 0xF000); $this->assertEquals(0x8000, hexdec(substr($result, 19, 4)) & 0xC000); } public function testUnique() { $reps = 100; $ids = array(); for ($i = 0; $i < $reps; $i++) { $ids[] = UUID::gen(); } $this->assertEquals(count($ids), count(array_unique($ids)), "UUIDs must be unique"); } }
<?php if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) { print "This script must be run from the command line\n"; exit(); } define('INSTALLDIR', realpath(dirname(__FILE__) . '/..')); define('STATUSNET', true); require_once INSTALLDIR . '/lib/common.php'; class UUIDTest extends PHPUnit_Framework_TestCase { public function testGenerate() { $result = UUID::gen(); $this->assertRegExp('/^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$/', $result); // Check version number $this->assertEquals(0x4000, hexdec(substr($result, 14, 4)) & 0xF000); $this->assertEquals(0x8000, hexdec(substr($result, 19, 4)) & 0xC000); } }
Allow user styles to override default styles Just moved the `...styles` spread to the end of the style object.
import React from 'react'; import PropTypes from 'prop-types'; import SvgIcon from './SvgIcon'; export const Icon = (props) => { const { style, className, icon, ...others} = props; //eslint-disable-line return ( <div {...others} style={{display: 'inline-flex', justifyContent: 'center', alignItems:'center', ...style}} className={className}> <SvgIcon size={props.size} icon={props.icon}/> </div> ); }; export const withBaseIcon = (defaultProps) => props => { const propsToUse = {...defaultProps}; return <Icon {...propsToUse} {...props}/>; }; Icon.defaultProps = { size: 16, fill: 'currentColor' }; Icon.propTypes = { icon: PropTypes.object.isRequired, size: PropTypes.number, style: PropTypes.object, className: PropTypes.string }; export default Icon;
import React from 'react'; import PropTypes from 'prop-types'; import SvgIcon from './SvgIcon'; export const Icon = (props) => { const { style, className, icon, ...others} = props; //eslint-disable-line return ( <div {...others} style={{...style, display: 'inline-flex', justifyContent: 'center', alignItems:'center'}} className={className}> <SvgIcon size={props.size} icon={props.icon}/> </div> ); }; export const withBaseIcon = (defaultProps) => props => { const propsToUse = {...defaultProps}; return <Icon {...propsToUse} {...props}/>; }; Icon.defaultProps = { size: 16, fill: 'currentColor' }; Icon.propTypes = { icon: PropTypes.object.isRequired, size: PropTypes.number, style: PropTypes.object, className: PropTypes.string }; export default Icon;
Remove default label from AttachmentValue
<?php namespace Opifer\CmsBundle\ValueProvider; use Opifer\EavBundle\ValueProvider\AbstractValueProvider; use Opifer\EavBundle\ValueProvider\ValueProviderInterface; use Symfony\Component\Form\FormBuilderInterface; class AttachmentValueProvider extends AbstractValueProvider implements ValueProviderInterface { /** * {@inheritDoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('file', 'file', [ 'label' => false, ]); } /** * {@inheritDoc} */ public function getEntity() { return 'Opifer\CmsBundle\Entity\AttachmentValue'; } /** * {@inheritDoc} */ public function getLabel() { return 'Attachment'; } }
<?php namespace Opifer\CmsBundle\ValueProvider; use Opifer\EavBundle\ValueProvider\AbstractValueProvider; use Opifer\EavBundle\ValueProvider\ValueProviderInterface; use Symfony\Component\Form\FormBuilderInterface; class AttachmentValueProvider extends AbstractValueProvider implements ValueProviderInterface { /** * {@inheritDoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('file', 'file', [ 'label' => $options['attribute']->getDisplayName(), ]); } /** * {@inheritDoc} */ public function getEntity() { return 'Opifer\CmsBundle\Entity\AttachmentValue'; } /** * {@inheritDoc} */ public function getLabel() { return 'Attachment'; } }
Move crawl options to crawl command
#! /usr/bin/env node 'use strict'; (function () { var yargs = require('yargs'); var packageJson = require('../package.json'); var version = packageJson.version; var argv = yargs .usage('Usage: $0 <command> [options]') .command('crawl', 'Crawl a domain') .example('$0 crawl domain.com --depth 100', '(Crawl a domain to a depth of 100)') .alias('crawl', 'c') .command('crawl', 'Crawl a domain', { url: { alias : 'u', required: true, type: 'string', describe: 'URL to crawl' }, depth: { alias : 'd', default : 10, type: 'number', describe: 'Depth to crawl' }, format: { alias : 'f', default : 'json', type: 'string', describe: 'Format to return', choices: ['json'] } }) .help('help') .alias('help', 'h') .version('version', 'Return the version number', version) .alias('version', 'v') .demand(1) .strict() .argv; console.log(argv); })();
#! /usr/bin/env node 'use strict'; (function () { var yargs = require('yargs'); var packageJson = require('../package.json'); var version = packageJson.version; var argv = yargs .usage('Usage: $0 <command> [options]') .command('crawl', 'Crawl a domain') .example('$0 crawl domain.com --depth 100', '(Crawl a domain to a depth of 100)') .alias('crawl', 'c') .option( 'url', { group: 'crawl options:', alias : 'u', required: true, type: 'string', describe: 'URL to crawl' } ) .option( 'depth', { group: 'crawl options:', alias : 'd', default : 10, type: 'number', describe: 'Depth to crawl' } ) .option( 'format', { group: 'crawl options:', alias : 'f', default : 'json', type: 'string', describe: 'Format to return', choices: ['json'] } ) .help('help') .alias('help', 'h') .version('version', 'Return the version number', version) .alias('version', 'v') .demand(1) .strict() .argv; console.log(argv); })();
Allow to pass array to scraper-genres
<?php class Denkmal_Scraper_Genres { /** @var string[] */ private $_genreList = array(); /** * @param string|string[] $genres */ function __construct($genres) { if (!is_array($genres)) { $genres = Functional\map(preg_split('#[,|/]#', $genres), function ($genre) { return strtolower(trim($genre)); }); } $genres = array_filter($genres); $this->_genreList = $genres; } /** * @return int */ public function count() { return count($this->_genreList); } /** * @return string */ public function __toString() { $genres = $this->_genreList; if (count($genres) > 0) { $genres[0] = ucfirst($genres[0]); } return implode(', ', $genres); } }
<?php class Denkmal_Scraper_Genres { /** @var string[] */ private $_genreList = array(); /** * @param string $genres Genres list as string */ function __construct($genres) { foreach (preg_split('#[,|/]#', $genres) as $genre) { if ($genre = strtolower(trim($genre))) { $this->_genreList[] = $genre; } } } /** * @return int */ public function count() { return count($this->_genreList); } /** * @return string */ public function __toString() { $genres = $this->_genreList; if (count($genres) > 0) { $genres[0] = ucfirst($genres[0]); } return implode(', ', $genres); } }
Fix file opening and make tests pass.
#!/usr/bin/env python # -*- coding: utf-8 -*- def get_starting_chunk(filename): with open(filename, 'r') as f: chunk = f.read(1024) return chunk def is_binary_string(bytes_to_check): """ :param bytes: A chunk of bytes to check. :returns: True if appears to be a binary, otherwise False. """ textchars = ''.join(map(chr, [7,8,9,10,12,13,27] + range(0x20, 0x100))) result = bytes_to_check.translate(None, textchars) return bool(result) def is_binary(filename): """ :param filename: File to check. :returns: True if it's a binary file, otherwise False. """ chunk = get_starting_chunk(filename) return is_binary_string(chunk)
#!/usr/bin/env python # -*- coding: utf-8 -*- def get_starting_chunk(filename): with(filename, 'r') as f: chunk = open(filename).read(1024) return chunk def is_binary_string(bytes_to_check): """ :param bytes: A chunk of bytes to check. :returns: True if appears to be a binary, otherwise False. """ textchars = ''.join(map(chr, [7,8,9,10,12,13,27] + range(0x20, 0x100))) result = bytes_to_check.translate(None, textchars) return bool(result) def is_binary(filename): """ :param filename: File to check. :returns: True if it's a binary file, otherwise False. """ chunk = get_starting_chunk(filename) return is_binary_string(chunk)
Set python2 explicitly as interpreter
#!/usr/bin/env python2 from setuptools import setup, find_packages import os version = __import__('cms_themes').__version__ install_requires = [ 'setuptools', 'django', 'django-cms', ] setup( name = "django-cms-themes", version = version, url = 'http://github.com/megamark16/django-cms-themes', license = 'BSD', platforms=['OS Independent'], description = "Load prepackaged themes (templates and accompanying media) into Django CMS projects through the admin", author = "Mark Ransom", author_email = 'megamark16@gmail.com', packages=find_packages(), install_requires = install_requires, include_package_data=True, zip_safe=False, classifiers = [ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], package_dir={ 'cms_themes': 'cms_themes', }, )
from setuptools import setup, find_packages import os version = __import__('cms_themes').__version__ install_requires = [ 'setuptools', 'django', 'django-cms', ] setup( name = "django-cms-themes", version = version, url = 'http://github.com/megamark16/django-cms-themes', license = 'BSD', platforms=['OS Independent'], description = "Load prepackaged themes (templates and accompanying media) into Django CMS projects through the admin", author = "Mark Ransom", author_email = 'megamark16@gmail.com', packages=find_packages(), install_requires = install_requires, include_package_data=True, zip_safe=False, classifiers = [ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], package_dir={ 'cms_themes': 'cms_themes', }, )
Remove null type in docblock before assigning to array variable
<?php declare(strict_types=1); namespace Roave\BetterReflection\TypesFinder; use phpDocumentor\Reflection\Type; use phpDocumentor\Reflection\TypeResolver; use phpDocumentor\Reflection\Types\Context; class ResolveTypes { /** @var TypeResolver */ private $typeResolver; public function __construct() { $this->typeResolver = new TypeResolver(); } /** * @param string[] $stringTypes * @return Type[] */ public function __invoke(array $stringTypes, Context $context) : array { $resolvedTypes = []; foreach ($stringTypes as $stringType) { /** @var Type $resolvedType */ $resolvedType = $this->typeResolver->resolve($stringType, $context); $resolvedTypes[] = $resolvedType; } return $resolvedTypes; } }
<?php declare(strict_types=1); namespace Roave\BetterReflection\TypesFinder; use phpDocumentor\Reflection\Type; use phpDocumentor\Reflection\TypeResolver; use phpDocumentor\Reflection\Types\Context; class ResolveTypes { /** @var TypeResolver */ private $typeResolver; public function __construct() { $this->typeResolver = new TypeResolver(); } /** * @param string[] $stringTypes * @return Type[] */ public function __invoke(array $stringTypes, Context $context) : array { $resolvedTypes = []; foreach ($stringTypes as $stringType) { $resolvedTypes[] = $this->typeResolver->resolve($stringType, $context); } /** @var Type[] */ return $resolvedTypes; } }
Add support for converting arrays
'use strict'; /** * Attempts to convert object properties recursively to numbers. * @param {Object} obj - Object to iterate over. * @param {Object} options - Options. * @param {Function} options.parser - Parser to process string with. Should return NaN if not a valid number. Defaults to parseInt. * @return {Object} Returns new object with same properties (shallow copy). */ function parseNums(obj, options) { var result = Array.isArray(obj) ? [] : {}, key, value, parsedValue; for (key in obj) { if (obj.hasOwnProperty(key)) { value = obj[key]; parsedValue = options.parser.call(null, value, 10, key); if (typeof value === 'string' && !isNaN(parsedValue)) { result[key] = parsedValue; } else if (value.constructor === Object || Array.isArray(value)) { result[key] = parseNums(value, options); } else { result[key] = value; } } } return result; } module.exports = parseNums;
'use strict'; /** * Attempts to convert object properties recursively to numbers. * @param {Object} obj - Object to iterate over. * @param {Object} options - Options. * @param {Function} options.parser - Parser to process string with. Should return NaN if not a valid number. Defaults to parseInt. * @return {Object} Returns new object with same properties (shallow copy). */ function parseNums(obj, options) { var result = {}, key, value, parsedValue; for (key in obj) { if (obj.hasOwnProperty(key)) { value = obj[key]; parsedValue = options.parser.call(null, value, 10, key); if (typeof value === 'string' && !isNaN(parsedValue)) { result[key] = parsedValue; } else if (value.constructor === Object) { result[key] = parseNums(value, options); } else { result[key] = value; } } } return result; } module.exports = parseNums;
Read URL and Token from environment
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = True WTF_CSRF_ENABLED = True SESSION_COOKIE_NAME = 'notify_admin_session' SESSION_COOKIE_PATH = '/admin' SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET') NOTIFY_DATA_API_URL = os.getenv('NOTIFY_API_URL', "http://localhost:6001") NOTIFY_DATA_API_AUTH_TOKEN = os.getenv('NOTIFY_API_TOKEN', "valid-token") STATIC_URL_PATH = '/admin/static' ASSET_PATH = STATIC_URL_PATH + '/' BASE_TEMPLATE_DATA = { 'header_class': 'with-proposition', 'asset_path': ASSET_PATH } class Test(Config): DEBUG = True SECRET_KEY = "not-so-secret" class Development(Config): DEBUG = True SESSION_COOKIE_SECURE = False SECRET_KEY = "not-so-secret" class Live(Config): DEBUG = False class Staging(Config): DEBUG = False configs = { 'development': Development, 'preview': Live, 'staging': Staging, 'production': Live, 'test': Test, }
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = True WTF_CSRF_ENABLED = False SESSION_COOKIE_NAME = 'notify_admin_session' SESSION_COOKIE_PATH = '/admin' SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SECRET_KEY = os.getenv('NOTIFY_ADMIN_FRONTEND_COOKIE_SECRET') NOTIFY_DATA_API_URL = "http://localhost:6001" NOTIFY_DATA_API_AUTH_TOKEN = "valid-token" STATIC_URL_PATH = '/admin/static' ASSET_PATH = STATIC_URL_PATH + '/' BASE_TEMPLATE_DATA = { 'header_class': 'with-proposition', 'asset_path': ASSET_PATH } class Test(Config): DEBUG = True SECRET_KEY = "not-so-secret" class Development(Config): DEBUG = True SESSION_COOKIE_SECURE = False SECRET_KEY = "not-so-secret" class Live(Config): DEBUG = False class Staging(Config): DEBUG = False configs = { 'development': Development, 'preview': Live, 'staging': Staging, 'production': Live, 'test': Test, }
fix(server): Add field data to team controller
'use strict'; let mongoose = require('mongoose'); let Schema = mongoose.Schema; let teamSchema = new Schema({ name : { type: String, required: true, unique: true }, email : { type: String, required: true, unique: true }, description : { type: String }, logisticsRequirements : { type: String }, application : { open : { type: Boolean, default: true }, list : [{ type: mongoose.Schema.Types.ObjectId }] }, cremiRoom : { type: String }, data : mongoose.Schema.Types.Mixed }); require('./team.controller')(teamSchema); module.exports = mongoose.model('Team', teamSchema);
'use strict'; let mongoose = require('mongoose'); let Schema = mongoose.Schema; let teamSchema = new Schema({ name : { type: String, required: true, unique: true }, email : { type: String, required: true, unique: true }, description : { type: String }, logisticsRequirements : { type: String }, application : { open : { type: Boolean, default: true }, list : [{ type: mongoose.Schema.Types.ObjectId }] }, cremiRoom : { type: String } }); require('./team.controller')(teamSchema); module.exports = mongoose.model('Team', teamSchema);
Use the `css` property of `Result`
#!/usr/bin/env node const fs = require('fs') const path = require('path') const concise = require('../src/index') const command = { name: process.argv[2], input: process.argv[3], output: process.argv[4] } const build = (input, output) => { concise.process(fs.readFileSync(input, 'utf8'), { from: input }).then(result => { // Create all the parent directories if required fs.mkdirSync(path.dirname(output), { recursive: true }) // Write the CSS fs.writeFile(output, result.css, err => { if (err) throw err console.log(`File written: ${output}\nFrom: ${input}`); }) }); }; const watch = path => { console.log(`Currently watching for changes in: ${path}`); fs.watch(path, {recursive: true}, (eventType, filename) => { console.log(`${eventType.charAt(0).toUpperCase() + eventType.slice(1)} in: ${filename}`); build(); }); }; switch (command.name) { case 'compile': build(command.input, command.output); break case 'watch': build(command.input, command.output); watch(path.dirname(command.input)); break default: console.log('Unknown command') break }
#!/usr/bin/env node const fs = require('fs') const path = require('path') const concise = require('../src/index') const command = { name: process.argv[2], input: process.argv[3], output: process.argv[4] } const build = (input, output) => { concise.process(fs.readFileSync(input, 'utf8'), { from: input }).then(css => { // Create all the parent directories if required fs.mkdirSync(path.dirname(output), { recursive: true }) // Write the CSS fs.writeFile(output, css, err => { if (err) throw err console.log(`File written: ${output}\nFrom: ${input}`); }) }); }; const watch = path => { console.log(`Currently watching for changes in: ${path}`); fs.watch(path, {recursive: true}, (eventType, filename) => { console.log(`${eventType.charAt(0).toUpperCase() + eventType.slice(1)} in: ${filename}`); build(); }); }; switch (command.name) { case 'compile': build(command.input, command.output); break case 'watch': build(command.input, command.output); watch(path.dirname(command.input)); break default: console.log('Unknown command') break }
Update whitespace removal to convert underscores to spaces
var removeExcessSpaces = function(htmlString) { var processedString = htmlString.replace(/\s+</g, '<'); processedString = processedString.replace(/>\s+/g, '>'); processedString = processedString.replace(/_/g, ' '); return processedString; } var ready = function(fn) { if(document.readyState != 'loading') { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } ready(function() { document.querySelector('body').innerHTML = removeExcessSpaces(document.querySelector('body').innerHTML); // Ensure the periodic table overlay is positioned correctly var tableLeft = document.querySelector('#tetris-table').offsetLeft; var tableTop = document.querySelector('#tetris-table').offsetTop; document.querySelector('#table-overlay').style.left = tableLeft + 1 + 'px'; document.querySelector('#table-overlay').style.top = tableTop + 1 + 'px'; // This variable is global for the purposes of development and debugging // Once the game is complete, remove the variable assignment window.gameControl = new Controller(); });
var removeExcessSpaces = function(htmlString) { var processedString = htmlString.replace(/\s+</g, '<'); processedString = processedString.replace(/>\s+/g, '>'); processedString = processedString.replace(/\:</g, ': <'); return processedString; } var ready = function(fn) { if(document.readyState != 'loading') { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } ready(function() { document.querySelector('body').innerHTML = removeExcessSpaces(document.querySelector('body').innerHTML); // Ensure the periodic table overlay is positioned correctly var tableLeft = document.querySelector('#tetris-table').offsetLeft; var tableTop = document.querySelector('#tetris-table').offsetTop; document.querySelector('#table-overlay').style.left = tableLeft + 1 + 'px'; document.querySelector('#table-overlay').style.top = tableTop + 1 + 'px'; // This variable is global for the purposes of development and debugging // Once the game is complete, remove the variable assignment window.gameControl = new Controller(); });
Fix issues with findUser refactor
const Q = require('q'); // Regex to test if the string is likely a facebook user ID const USER_ID_REGEX = /^\d+$/; async function getFBUserInfoByID(api, id) { return await Q.nfcall(api.getUserInfo, id); } async function findFBUser(api, search_str, allowNonFriends) { let userID = search_str; // If the search string isnt a userID, we should search // for the user by name if (!USER_ID_REGEX.test(search_str)) { let userData = await Q.nfcall(api.getUserID, search_str); userID = userData[0].userID; } const userInfoMap = await getFBUserInfoByID(api, userID); const userInfo = userInfoMap[userID]; if (!userInfo.isFriend && !allowNonFriends) throw new Error( 'User not your friend, they may not be your top ' + name + ", try using '@facebot friends <partial_name>' to get their id or fb vanity name to use" ); // The userinfo object doesnt have an id with it, so add it as its useful userInfo.id = userID; return userInfo; } module.exports = { findFBUser, };
const Q = require('q'); // Regex to test if the string is likely a facebook user ID const USER_ID_REGEX = /^\d+$/; async function getFBUserInfoByID(api, id) { return await Q.nfcall(api.getUserInfo, id); } async function findFBUser(api, search_str, allowNonFriends) { let userID = search_str; // If the search string isnt a userID, we should search // for the user by name if (!USER_ID_REGEX.test(search_str)) { let userData = await Q.nfcall(api.getUserID, name); userID = userData[0].userID; } const userInfoMap = await getFBUserInfoByID(api, userID); const userInfo = userInfoMap[userID]; if (!userInfo.isFriend && !allowNonFriends) throw new Error( 'User not your friend, they may not be your top ' + name + ", try using '@facebot friends <partial_name>' to get their id or fb vanity name to use" ); // The userinfo object doesnt have an id with it, so add it as its useful userID.id = userID; return userInfo; } module.exports = { findFBUser, };
Remove karma-commonjs settings for avoiding error. - If you require commonjs modules, Add settings below: - Add `commonjs` to `frameworks`. ``` frameworks: ["jasmine", 'commonjs'], ``` - Add `preprocessors` and `commonjsPreprocessor` setting. ``` preprocessors: { "node_modules/dummy/*.js": ['commonjs'] }, commonjsPreprocessor: { modulesRoot: './' }, ```
/*eslint-env node */ var sourceList = require("../../src/source-list"); var sourceFiles = sourceList.list.map(function(src) { return "src/" + src; }); var commonJsSourceFiles = sourceList.commonJsModuleList; var testFiles = [ "test/util/dom.js", "test/util/matchers.js", "test/util/mock/vivliostyle/logging-mock.js", "test/util/mock/vivliostyle/plugin-mock.js", "test/spec/**/*.js" ]; module.exports = function(config) { return { basePath: "../..", frameworks: ["jasmine"], files: sourceFiles.concat(testFiles).concat(commonJsSourceFiles), // frameworks: ["jasmine", 'commonjs'], // preprocessors: { // "node_modules/dummy/*.js": ['commonjs'] // }, // commonjsPreprocessor: { // modulesRoot: './' // }, port: 9876, colors: true, logLevel: config.LOG_INFO }; };
/*eslint-env node */ var sourceList = require("../../src/source-list"); var sourceFiles = sourceList.list.map(function(src) { return "src/" + src; }); var commonJsSourceFiles = sourceList.commonJsModuleList; var testFiles = [ "test/util/dom.js", "test/util/matchers.js", "test/util/mock/vivliostyle/logging-mock.js", "test/util/mock/vivliostyle/plugin-mock.js", "test/spec/**/*.js" ]; module.exports = function(config) { return { basePath: "../..", frameworks: ["jasmine", 'commonjs'], files: sourceFiles.concat(testFiles).concat(commonJsSourceFiles), preprocessors: { }, commonjsPreprocessor: { modulesRoot: './' }, port: 9876, colors: true, logLevel: config.LOG_INFO }; };
refactor: Make test variables more descriptive
import unittest2 from cfn_sphere.stack_configuration import Config, StackConfig, NoConfigException class ConfigTests(unittest2.TestCase): def test_properties_parsing(self): config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'any-stack': {'template-url': 'foo.json', 'tags': {'any-tag': 'any-tag-value'}, 'parameters': {'any-parameter': 'any-value'}}}}) self.assertEqual('eu-west-1', config.region) self.assertEqual(1, len(config.stacks.keys())) self.assertTrue(isinstance(config.stacks['any-stack'], StackConfig)) self.assertEqual('foo.json', config.stacks['any-stack'].template_url) self.assertEqual({'any-tag': 'any-tag-value'}, config.stacks['any-stack'].tags) self.assertEqual({'any-parameter': 'any-value'}, config.stacks['any-stack'].parameters) def test_raises_exception_if_no_region_key(self): with self.assertRaises(NoConfigException): Config(config_dict={'foo': '', 'stacks': {'any-stack': {'template': 'foo.json'}}}) def test_raises_exception_if_no_stacks_key(self): with self.assertRaises(NoConfigException): Config(config_dict={'region': 'eu-west-1'})
import unittest2 from cfn_sphere.stack_configuration import Config, StackConfig, NoConfigException class ConfigTests(unittest2.TestCase): def test_properties_parsing(self): config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'foo': {'template-url': 'foo.json'}}}) self.assertEqual('eu-west-1', config.region) self.assertEqual(1, len(config.stacks.keys())) self.assertTrue(isinstance(config.stacks['foo'], StackConfig)) self.assertEqual('foo.json', config.stacks['foo'].template_url) def test_raises_exception_if_no_region_key(self): with self.assertRaises(NoConfigException): Config(config_dict={'foo': '', 'stacks': {'foo': {'template': 'foo.json'}}}) def test_raises_exception_if_no_stacks_key(self): with self.assertRaises(NoConfigException): Config(config_dict={'region': 'eu-west-1'})
refactor: Change parameter name for Rate limit
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.repository.ratelimit.api; import io.gravitee.repository.ratelimit.model.RateLimitResult; import java.io.Serializable; import java.util.concurrent.TimeUnit; /** * @author David BRASSELY (brasseld at gmail.com) */ public interface RateLimitRepository<T extends Serializable> { RateLimitResult acquire(T key, int weigth, long limit, long periodTime, TimeUnit periodTimeUnit); }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.repository.ratelimit.api; import io.gravitee.repository.ratelimit.model.RateLimitResult; import java.io.Serializable; import java.util.concurrent.TimeUnit; /** * @author David BRASSELY (brasseld at gmail.com) */ public interface RateLimitRepository<T extends Serializable> { RateLimitResult acquire(T key, int pound, long limit, long periodTime, TimeUnit periodTimeUnit); }