text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Add time to debug log format
from flask import Flask import os import os.path __version__ = "0.1.0" def create_app(config=None): app = Flask(__name__, instance_relative_config=True) config_name = "eyeflask.cfg" # Use user specified config file if provided. if config: config_path = os.path.abspath(config) # Load from `instance` folder # http://flask.pocoo.org/docs/0.10/config/#instance-folders else: config_path = config_name try: app.config.from_pyfile(config_path) except FileNotFoundError: sample_conf = os.path.join(os.path.dirname(__file__), "extras", "eyeflask-sample.cfg") no_conf_msg = ("Unable to load your config file.\n" "Either specify one with the `-c` flag, or put one " "named `{}` in the Flask\n" "instance folder at the path below. You may have to " "create the instance\n" "folder if it doesn't already " "exist.\n".format(config_name)) print(no_conf_msg) print("Sample config: {}".format(sample_conf)) print("Instance folder: {}\n".format(app.instance_path)) raise app.debug_log_format = '\n'.join([ 80 * '-', '%(asctime)s %(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:', '%(message)s', 80 * '-' ]) from .server import server app.register_blueprint(server) return app
from flask import Flask import os import os.path __version__ = "0.1.0" def create_app(config=None): app = Flask(__name__, instance_relative_config=True) config_name = "eyeflask.cfg" # Use user specified config file if provided. if config: config_path = os.path.abspath(config) # Load from `instance` folder # http://flask.pocoo.org/docs/0.10/config/#instance-folders else: config_path = config_name try: app.config.from_pyfile(config_path) except FileNotFoundError: sample_conf = os.path.join(os.path.dirname(__file__), "extras", "eyeflask-sample.cfg") no_conf_msg = ("Unable to load your config file.\n" "Either specify one with the `-c` flag, or put one " "named `{}` in the Flask\n" "instance folder at the path below. You may have to " "create the instance\n" "folder if it doesn't already " "exist.\n".format(config_name)) print(no_conf_msg) print("Sample config: {}".format(sample_conf)) print("Instance folder: {}\n".format(app.instance_path)) raise from .server import server app.register_blueprint(server) return app
Switch order of next trip and totals
/* global fetch */ import React from 'react'; import TotalWidget from './TotalWidget'; import NextTripWidget from './NextTripWidget'; import TripTable from './TripTable'; import VisitedMap from './VisitedMap'; import WishlistMap from './WishlistMap'; import './scss/overview.scss'; class Overview extends React.Component { constructor() { super(); this.loading = true; this.state = { trips: [] }; } componentDidMount() { this.getData(); } getData() { fetch('http://localhost:4444/trips') .then((response) => { return response.json(); }) .then((trips) => { this.loading = false; this.setState({ trips }); }); } render() { return ( <div className="container"> { this.loading ? <span>Loading..</span> : <section> <div className="row"> <NextTripWidget color="light" nextTrip={this.state.trips.next} /> <TotalWidget color="medium" totals={this.state.trips.total} /> </div> <VisitedMap countries={this.state.trips.allCountries} selector="visitedMap" /> <TripTable trips={this.state.trips.visited} /> <h1>Wishlist</h1> <WishlistMap countries={this.state.trips.wishlist} selector="wishlistMap" /> </section> } </div> ); } } export default Overview;
/* global fetch */ import React from 'react'; import TotalWidget from './TotalWidget'; import NextTripWidget from './NextTripWidget'; import TripTable from './TripTable'; import VisitedMap from './VisitedMap'; import WishlistMap from './WishlistMap'; import './scss/overview.scss'; class Overview extends React.Component { constructor() { super(); this.loading = true; this.state = { trips: [] }; } componentDidMount() { this.getData(); } getData() { fetch('http://localhost:4444/trips') .then((response) => { return response.json(); }) .then((trips) => { this.loading = false; this.setState({ trips }); }); } render() { return ( <div className="container"> { this.loading ? <span>Loading..</span> : <section> <div className="row"> <TotalWidget color="medium" totals={this.state.trips.total} /> <NextTripWidget color="light" nextTrip={this.state.trips.next} /> </div> <VisitedMap countries={this.state.trips.allCountries} selector="visitedMap" /> <TripTable trips={this.state.trips.visited} /> <h1>Wishlist</h1> <WishlistMap countries={this.state.trips.wishlist} selector="wishlistMap" /> </section> } </div> ); } } export default Overview;
Create a variable in scope to avoid being override
var mongoose = require('mongoose'); var ShortId = require('./shortid'); var defaultSave = mongoose.Model.prototype.save; mongoose.Model.prototype.save = function(cb) { for (key in this.schema.tree) { var fieldName = key if (this.isNew && this[fieldName] === undefined) { var idType = this.schema.tree[fieldName]; if (idType === ShortId || idType.type === ShortId) { var idInfo = this.schema.path(fieldName); var retries = idInfo.retries; var self = this; function attemptSave() { idInfo.generator(idInfo.generatorOptions, function(err, id) { if (err) { cb(err); return; } self[fieldName] = id; defaultSave.call(self, function(err, obj) { if (err && err.code == 11000 && err.err.indexOf(fieldName) !== -1 && retries > 0 ) { --retries; attemptSave(); } else { // TODO check these args cb(err, obj); } }); }); } attemptSave(); return; } } } defaultSave.call(this, cb); }; module.exports = exports = ShortId;
var mongoose = require('mongoose'); var ShortId = require('./shortid'); var defaultSave = mongoose.Model.prototype.save; mongoose.Model.prototype.save = function(cb) { for (fieldName in this.schema.tree) { if (this.isNew && this[fieldName] === undefined) { var idType = this.schema.tree[fieldName]; if (idType === ShortId || idType.type === ShortId) { var idInfo = this.schema.path(fieldName); var retries = idInfo.retries; var self = this; function attemptSave() { idInfo.generator(idInfo.generatorOptions, function(err, id) { if (err) { cb(err); return; } self[fieldName] = id; defaultSave.call(self, function(err, obj) { if (err && err.code == 11000 && err.err.indexOf(fieldName) !== -1 && retries > 0 ) { --retries; attemptSave(); } else { // TODO check these args cb(err, obj); } }); }); } attemptSave(); return; } } } defaultSave.call(this, cb); }; module.exports = exports = ShortId;
Fix unmerged content from last commit
import { applyMiddleware, combineReducers, compose, createStore } from 'redux'; import userReducer from './reducers/userReducer.js'; import applicationReducer from './reducers/applicationReducer.js'; import serverReducer from './reducers/serverReducer.js'; import getDataReducer from './reducers/getDataReducer.js'; import logger from 'redux-logger'; import { routerReducer } from 'react-router-redux'; const middleware = [logger()]; const getInitialState = () => { if (localStorage.getItem('state')) { const restoredState = JSON.parse(localStorage.getItem('state')); restoredState.routing = []; return restoredState; } else { return { routing: [], applications: [], user: { isLogged: 'false', handle: '', }, servers: [], graphData: [ {route: "init", data: [{ time: 0, hits: 0}] //quick fix for async data retrival, probs a better way }, ], }; } }; // configure store with initial state and allow Redux Chrome extension to view store export default function configureStore(browserHistory, initialState = getInitialState()) { console.log(initialState); const store = createStore(combineReducers({ routing: routerReducer, applications: applicationReducer, user: userReducer, servers: serverReducer, graphData: getDataReducer, }), initialState, compose( applyMiddleware(...middleware), window.devToolsExtension ? window.devToolsExtension() : f => f )); return store; }
import { applyMiddleware, combineReducers, compose, createStore } from 'redux'; import userReducer from './reducers/userReducer.js'; import applicationReducer from './reducers/applicationReducer.js'; import serverReducer from './reducers/serverReducer.js'; import getDataReducer from './reducers/getDataReducer.js'; import logger from 'redux-logger'; import { routerReducer } from 'react-router-redux'; const middleware = [logger()]; const getInitialState = () => { if (localStorage.getItem('state')) { const restoredState = JSON.parse(localStorage.getItem('state')); restoredState.routing = []; return restoredState; } else { return { routing: [], applications: [], user: { email: '[email protected]', handle: 'QQQQQQQ', }, servers: [], graphData: [ {route: "init", data: [{ time: 0, hits: 0}] //quick fix for async data retrival, probs a better way }, ], }; } }; // configure store with initial state and allow Redux Chrome extension to view store export default function configureStore(browserHistory, initialState = getInitialState()) { console.log(initialState); const store = createStore(combineReducers({ routing: routerReducer, applications: applicationReducer, user: userReducer, servers: serverReducer, graphData: getDataReducer, }), initialState, compose( applyMiddleware(...middleware), window.devToolsExtension ? window.devToolsExtension() : f => f )); return store; }
Fix to use correct nicks when showing comments.
"use strict"; var React = require("react"); var PlayerStore = require("../stores/PlayerStore.react"); var moment = require("moment"); var momentLocale = require("moment/locale/nb.js"); moment.locale("nb", momentLocale); var _ = require("underscore"); var NewsComments = React.createClass({ displayName: "News Comments Widget", render: function() { var item = this.props.item; var nick = "Ukjent"; var author = item ? item.author : null; var currentLoggedInPlayer = PlayerStore.getFromUser(this.props.user); var comments = item.comments ? item.comments : []; return ( <div> {comments.map(function(comment, i) { var paras = comment.content.split('\\n').map(function(para, j) { return <p key={"comment-" + i + "-para-" + j}>{para}</p>; }); var p = PlayerStore.getFromUUID(comment.player); if (p && p.nick) { nick = p.nick; } return ( <div key={"comment-" + i} className="panel panel-default"> <div className="panel-heading"> {nick} kommenterte {moment(comment.created).fromNow()} </div> <div className="panel-body"> {paras} </div> </div> ); })} </div> ); } }); module.exports = NewsComments;
"use strict"; var React = require("react"); var PlayerStore = require("../stores/PlayerStore.react"); var moment = require("moment"); var momentLocale = require("moment/locale/nb.js"); moment.locale("nb", momentLocale); var _ = require("underscore"); var NewsComments = React.createClass({ displayName: "News Comments Widget", render: function() { var item = this.props.item; var nick = "Ukjent"; var author = item ? item.author : null; var p = PlayerStore.getFromUUID(item.author); if (p && p.nick) { nick = p.nick; } var currentLoggedInPlayer = PlayerStore.getFromUser(this.props.user); var comments = item.comments ? item.comments : []; return ( <div> {comments.map(function(comment, i) { var paras = comment.content.split('\\n').map(function(para, j) { return <p key={"comment-" + i + "-para-" + j}>{para}</p>; }); return ( <div key={"comment-" + i} className="panel panel-default"> <div className="panel-heading"> {nick} kommenterte {moment(comment.created).fromNow()} </div> <div className="panel-body"> {paras} </div> </div> ); })} </div> ); } }); module.exports = NewsComments;
Disable user-defined artifacts testing module
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.sleuthkit.autopsy.modules.UserArtifacts; import org.openide.util.NbBundle; import org.openide.util.lookup.ServiceProvider; import org.python.apache.xmlcommons.Version; import org.sleuthkit.autopsy.ingest.DataSourceIngestModule; import org.sleuthkit.autopsy.ingest.IngestModuleFactory; import org.sleuthkit.autopsy.ingest.IngestModuleFactoryAdapter; import org.sleuthkit.autopsy.ingest.IngestModuleIngestJobSettings; /** * * @author oliver */ //@ServiceProvider(service = IngestModuleFactory.class) public class UserArtifactIngestModuleFactory extends IngestModuleFactoryAdapter { static String getModuleName() { return NbBundle.getMessage(UserArtifactIngestModuleFactory.class, "UserArtifactIngestModuleFactory.moduleName"); } @Override public String getModuleDisplayName() { return getModuleName(); } @Override public String getModuleDescription() { return NbBundle.getMessage(UserArtifactIngestModuleFactory.class, "UserArtifactIngestModuleFactory.moduleDescription"); } @Override public String getModuleVersionNumber() { return Version.getVersion(); } @Override public DataSourceIngestModule createDataSourceIngestModule(IngestModuleIngestJobSettings ingestOptions) { return new UserArtifactIngestModule(); } @Override public boolean isDataSourceIngestModuleFactory() { return true; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.sleuthkit.autopsy.modules.UserArtifacts; import org.openide.util.NbBundle; import org.openide.util.lookup.ServiceProvider; import org.python.apache.xmlcommons.Version; import org.sleuthkit.autopsy.ingest.DataSourceIngestModule; import org.sleuthkit.autopsy.ingest.IngestModuleFactory; import org.sleuthkit.autopsy.ingest.IngestModuleFactoryAdapter; import org.sleuthkit.autopsy.ingest.IngestModuleIngestJobSettings; /** * * @author oliver */ @ServiceProvider(service = IngestModuleFactory.class) public class UserArtifactIngestModuleFactory extends IngestModuleFactoryAdapter { static String getModuleName() { return NbBundle.getMessage(UserArtifactIngestModuleFactory.class, "UserArtifactIngestModuleFactory.moduleName"); } @Override public String getModuleDisplayName() { return getModuleName(); } @Override public String getModuleDescription() { return NbBundle.getMessage(UserArtifactIngestModuleFactory.class, "UserArtifactIngestModuleFactory.moduleDescription"); } @Override public String getModuleVersionNumber() { return Version.getVersion(); } @Override public DataSourceIngestModule createDataSourceIngestModule(IngestModuleIngestJobSettings ingestOptions) { return new UserArtifactIngestModule(); } @Override public boolean isDataSourceIngestModuleFactory() { return true; } }
Add github adapter module dependency
'use strict'; angular.module('main', [ 'ionic', 'ngCordova', 'ui.router', 'pascalprecht.github-adapter' ]) .config(function ($stateProvider, $urlRouterProvider, $githubProvider) { // ROUTING with ui.router $urlRouterProvider.otherwise('/main/list'); $stateProvider // this state is placed in the <ion-nav-view> in the index.html .state('main', { url: '/main', abstract: true, templateUrl: 'main/templates/menu.html', controller: 'MenuCtrl as menu' }) .state('main.list', { url: '/list', views: { 'pageContent': { templateUrl: 'main/templates/list.html', // controller: '<someCtrl> as ctrl' } } }) .state('main.listDetail', { url: '/list/detail', views: { 'pageContent': { templateUrl: 'main/templates/list-detail.html', // controller: '<someCtrl> as ctrl' } } }) .state('main.debug', { url: '/debug', views: { 'pageContent': { templateUrl: 'main/templates/debug.html', controller: 'DebugCtrl as ctrl' } } }); });
'use strict'; angular.module('main', [ 'ionic', 'ngCordova', 'ui.router', // TODO: load other modules selected during generation ]) .config(function ($stateProvider, $urlRouterProvider) { // ROUTING with ui.router $urlRouterProvider.otherwise('/main/list'); $stateProvider // this state is placed in the <ion-nav-view> in the index.html .state('main', { url: '/main', abstract: true, templateUrl: 'main/templates/menu.html', controller: 'MenuCtrl as menu' }) .state('main.list', { url: '/list', views: { 'pageContent': { templateUrl: 'main/templates/list.html', // controller: '<someCtrl> as ctrl' } } }) .state('main.listDetail', { url: '/list/detail', views: { 'pageContent': { templateUrl: 'main/templates/list-detail.html', // controller: '<someCtrl> as ctrl' } } }) .state('main.debug', { url: '/debug', views: { 'pageContent': { templateUrl: 'main/templates/debug.html', controller: 'DebugCtrl as ctrl' } } }); });
Upgrade to sendmail 4.3, fixed old bug with transaction
from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() except IOError: README = '' version = "0.1.0" test_requirements = [ 'nose', 'webtest', ] setup(name='tgext.mailer', version=version, description="TurboGears extension for sending emails with transaction manager integration", long_description=README, classifiers=[ "Environment :: Web Environment", "Framework :: TurboGears" ], keywords='turbogears2.extension', author='Alessandro Molina', author_email='[email protected]', url='https://github.com/amol-/tgext.mailer', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tgext.mailer.tests']), namespace_packages = ['tgext'], include_package_data=True, zip_safe=False, install_requires=[ "TurboGears2 >= 2.3.2", "repoze.sendmail == 4.3", ], extras_require={ # Used by Travis and Coverage due to setup.py nosetests # causing a coredump when used with coverage 'testing': test_requirements, }, test_suite='nose.collector', tests_require=test_requirements, entry_points=""" # -*- Entry points: -*- """, )
from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() except IOError: README = '' version = "0.1.0" test_requirements = [ 'nose', 'webtest', ] setup(name='tgext.mailer', version=version, description="TurboGears extension for sending emails with transaction manager integration", long_description=README, classifiers=[ "Environment :: Web Environment", "Framework :: TurboGears" ], keywords='turbogears2.extension', author='Alessandro Molina', author_email='[email protected]', url='https://github.com/amol-/tgext.mailer', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tgext.mailer.tests']), namespace_packages = ['tgext'], include_package_data=True, zip_safe=False, install_requires=[ "TurboGears2 >= 2.3.2", "repoze.sendmail == 4.1", ], extras_require={ # Used by Travis and Coverage due to setup.py nosetests # causing a coredump when used with coverage 'testing': test_requirements, }, test_suite='nose.collector', tests_require=test_requirements, entry_points=""" # -*- Entry points: -*- """, )
Read data set up updated git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@11903 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
import mmcorej.TaggedImage; import org.json.JSONObject; import org.micromanager.acquisition.TaggedImageStorageDiskDefault; import org.micromanager.api.MMTags; import org.micromanager.api.TaggedImageStorage; public class ReadDataSet { public static void main(String[] args) { String rootName = "C:/AcqusitionData/Tests/Test-A_1"; try { TaggedImageStorage storage = new TaggedImageStorageDiskDefault(rootName); JSONObject summary = storage.getSummaryMetadata(); System.out.println(summary.toString(3)); int numChannels = summary.getInt(MMTags.Summary.CHANNELS); int numSlices = summary.getInt(MMTags.Summary.SLICES); int numFrames = summary.getInt(MMTags.Summary.FRAMES); int numPositions = summary.getInt(MMTags.Summary.POSITIONS); for (int pos=0; pos < numPositions; pos++) { for (int t=0; t<numFrames; t++) { for (int z=0; z<numSlices; z++) { for (int ch=0; ch<numChannels; ch++) { TaggedImage img = storage.getImage(ch, z, t, pos); Object pixels = img.pix; // TODO: do something with pixels System.out.println(img.tags.toString(3)); } } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
import mmcorej.TaggedImage; import org.json.JSONObject; import org.micromanager.acquisition.TaggedImageStorageDiskDefault; import org.micromanager.api.TaggedImageStorage; public class ReadDataSet { public static void main(String[] args) { //String rootName = "C:/AcqusitionData/Tests/Test-A_1"; String rootName = "C:/AcqusitionData/20130813 Oxidative Stress Test 3/NIH3T3_1"; try { TaggedImageStorage storage = new TaggedImageStorageDiskDefault(rootName); JSONObject summary = storage.getSummaryMetadata(); System.out.println(summary.toString(3)); int numChannels = summary.getInt("Channels"); int numSlices = summary.getInt("Slices"); int numFrames = summary.getInt("Frames"); int numPositions = summary.getInt("Positions"); for (int pos=0; pos < numPositions; pos++) { for (int fr=0; fr<numFrames; fr++) { TaggedImage img = storage.getImage(0, 0, fr, pos); System.out.println(img.tags.toString(3)); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Revert "[twig] make method to be protected." This reverts commit a677e9f8a3480937f1bdc3b322d978222d4157c1.
<?php namespace Payum\Core\Bridge\Twig; class TwigFactory { /** * @return string[] */ public static function createGenericPaths() { return array_flip(array_filter(array( 'PayumCore' => self::guessViewsPath('Payum\Core\Payment'), 'PayumStripe' => self::guessViewsPath('Payum\Stripe\JsPaymentFactory'), 'PayumKlarnaCheckout' => self::guessViewsPath('Payum\Klarna\Checkout\PaymentFactory'), 'PayumSymfonyBridge' => self::guessViewsPath('Payum\Core\Bridge\Symfony\ReplyToSymfonyResponseConverter'), ))); } /** * @return \Twig_Environment */ public static function createGeneric() { $loader = new \Twig_Loader_Filesystem(); foreach (static::createGenericPaths() as $path => $namespace) { $loader->addPath($path, $namespace); } return new \Twig_Environment($loader); } /** * @param string $paymentFactoryOrRootClass * * @return string|null */ public static function guessViewsPath($paymentFactoryOrRootClass) { if (false == class_exists($paymentFactoryOrRootClass)) { return; } $rc = new \ReflectionClass($paymentFactoryOrRootClass); return dirname($rc->getFileName()).'/Resources/views'; } }
<?php namespace Payum\Core\Bridge\Twig; class TwigFactory { /** * @return \Twig_Environment */ public static function createGeneric() { $loader = new \Twig_Loader_Filesystem(); foreach (static::createGenericPaths() as $path => $namespace) { $loader->addPath($path, $namespace); } return new \Twig_Environment($loader); } /** * @param string $paymentFactoryOrRootClass * * @return string|null */ public static function guessViewsPath($paymentFactoryOrRootClass) { if (false == class_exists($paymentFactoryOrRootClass)) { return; } $rc = new \ReflectionClass($paymentFactoryOrRootClass); return dirname($rc->getFileName()).'/Resources/views'; } /** * @return string[] */ protected static function createGenericPaths() { return array_flip(array_filter(array( 'PayumCore' => self::guessViewsPath('Payum\Core\Payment'), 'PayumStripe' => self::guessViewsPath('Payum\Stripe\JsPaymentFactory'), 'PayumKlarnaCheckout' => self::guessViewsPath('Payum\Klarna\Checkout\PaymentFactory'), 'PayumSymfonyBridge' => self::guessViewsPath('Payum\Core\Bridge\Symfony\ReplyToSymfonyResponseConverter'), ))); } }
Fix deprecated ZipCode validator methods calls
<?php namespace SLLH\IsoCodesValidator\Constraints; use IsoCodes; use SLLH\IsoCodesValidator\IsoCodesConstraintValidator; use Symfony\Component\Validator\Constraint; /** * @author Sullivan Senechal <[email protected]> */ class ZipCodeValidator extends IsoCodesConstraintValidator { /** * @param mixed $value * @param ZipCode|Constraint $constraint */ public function validate($value, Constraint $constraint) { parent::validate($value, $constraint); if (!$value) { return; } if ($constraint->country == ZipCode::ALL) { $validated = false; foreach (ZipCode::$countries as $country) { if ($this->validateCountry($value, $country)) { $validated = true; break; } } if ($validated === false) { $this->createViolation($constraint->message); } } elseif (!$this->validateCountry($value, $constraint->country)) { $this->createViolation($constraint->message); } } /** * @deprecated To be removed when bumping requirements to ronanguilloux/isocodes ~1.2 * * @param mixed $value * @param string $country * * @return bool */ private function validateCountry($value, $country) { $deprecatedOptionsBridge = [ 'US' => 'US', 'Canada' => 'CA', 'France' => 'FR', 'Netherlands' => 'NL', ]; return IsoCodes\ZipCode::validate($value, method_exists('Isocodes\ZipCode', 'getAvailableCountries') ? $deprecatedOptionsBridge[$country] : $country); } }
<?php namespace SLLH\IsoCodesValidator\Constraints; use IsoCodes; use SLLH\IsoCodesValidator\IsoCodesConstraintValidator; use Symfony\Component\Validator\Constraint; /** * @author Sullivan Senechal <[email protected]> */ class ZipCodeValidator extends IsoCodesConstraintValidator { /** * @param mixed $value * @param ZipCode|Constraint $constraint */ public function validate($value, Constraint $constraint) { parent::validate($value, $constraint); if (!$value) { return; } if ($constraint->country == ZipCode::ALL) { $validated = false; foreach (ZipCode::$countries as $country) { if (IsoCodes\ZipCode::validate($value, $country)) { $validated = true; break; } } if ($validated === false) { $this->createViolation($constraint->message); } } elseif (!IsoCodes\ZipCode::validate($value, $constraint->country)) { $this->createViolation($constraint->message); } } }
Allow changing domain to own
from flask_wtf import Form from flask_security.core import current_user from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField from wtforms.validators import Required, Length, Regexp from ..core.db import db from ..core.security import User from .. import app class ApplicationForm(Form): start = SubmitField('Start') stop = SubmitField('Stop') class ApplicationSettingsForm(Form): domain = StringField('Domain', description="If you change it then make sure you also configure it with your DNS provider") submit = SubmitField('Update') def validate(self): rv = Form.validate(self) if not rv: return False if self.domain.data: server_name = app.config["SERVER_NAME_FULL"] if (server_name != "localhost" and not self.domain.data.endswith(current_user.login + "." + server_name) and self.domain.data.endswith(server_name)): self.domain.errors.append('Invalid domain, cannot end with ' + server_name) return False return True class ProfileForm(Form): login = StringField('Login') email = StringField('Email') name = StringField('Name', validators=[Required(), Length(1, 64), Regexp(r'^[A-Za-z0-9_\- ]+$', 0, 'Name must have only letters, numbers, spaces, dots, dashes or underscores')]) submit = SubmitField('Update')
from flask_wtf import Form from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField from wtforms.validators import Required, Length, Regexp from ..core.db import db from ..core.security import User from .. import app class ApplicationForm(Form): start = SubmitField('Start') stop = SubmitField('Stop') class ApplicationSettingsForm(Form): domain = StringField('Domain', description="If you change it then make sure you also configure it with your DNS provider") submit = SubmitField('Update') def validate(self): rv = Form.validate(self) if not rv: return False if self.domain.data: server_name = app.config["SERVER_NAME_FULL"] if (server_name != "localhost" and not self.domain.data.endswith(current_user.login + "." + server_name) and self.domain.data.endswith(server_name)): self.domain.errors.append('Invalid domain, cannot end with ' + server_name) return False return True class ProfileForm(Form): login = StringField('Login') email = StringField('Email') name = StringField('Name', validators=[Required(), Length(1, 64), Regexp(r'^[A-Za-z0-9_\- ]+$', 0, 'Name must have only letters, numbers, spaces, dots, dashes or underscores')]) submit = SubmitField('Update')
Fix unknown textDecoration style prop being passed to React Native
// @flow import React, {Component} from 'react' import {Box, Text} from './' import {globalStyles, globalColors} from '../styles/style-guide' import {isMobile} from '../constants/platform' import type {Props} from './usernames' export function usernameText ({type, users, style, inline}: Props) { return users.map((u, i) => { const userStyle = {...style} if (!isMobile) { userStyle.textDecoration = 'inherit' } if (u.broken) { userStyle.color = globalColors.red } if (inline) { userStyle.display = 'inline-block' } if (u.you) { Object.assign(userStyle, globalStyles.italic) } return ( <Text key={u.username} type={type} style={userStyle}>{u.username} { (i !== users.length - 1) && // Injecting the commas here so we never wrap and have newlines starting with a , <Text type={type} style={{...style, marginRight: 1}}>,</Text>} </Text> ) }) } export default class Usernames extends Component<void, Props, void> { render () { const containerStyle = this.props.inline ? {display: 'inline'} : {...globalStyles.flexBoxRow, flexWrap: 'wrap'} return ( <Box style={{...containerStyle, textDecoration: 'inherit'}}> {usernameText(this.props)} </Box> ) } }
// @flow import React, {Component} from 'react' import {Box, Text} from './' import {globalStyles, globalColors} from '../styles/style-guide' import type {Props} from './usernames' export function usernameText ({type, users, style, inline}: Props) { return users.map((u, i) => { const userStyle = { textDecoration: 'inherit', ...style, } if (u.broken) { userStyle.color = globalColors.red } if (inline) { userStyle.display = 'inline-block' } if (u.you) { Object.assign(userStyle, globalStyles.italic) } return ( <Text key={u.username} type={type} style={userStyle}>{u.username} { (i !== users.length - 1) && // Injecting the commas here so we never wrap and have newlines starting with a , <Text type={type} style={{...style, marginRight: 1}}>,</Text>} </Text> ) }) } export default class Usernames extends Component<void, Props, void> { render () { const containerStyle = this.props.inline ? {display: 'inline'} : {...globalStyles.flexBoxRow, flexWrap: 'wrap'} return ( <Box style={{...containerStyle, textDecoration: 'inherit'}}> {usernameText(this.props)} </Box> ) } }
Check Campaign Existence for Delete/Set/Get Purposes
var configuration = require('../../config/configuration.json') var utility = require('../../public/method/utility') module.exports = { checkCampaignModel: function (redisClient, accountHashID, payload, callback) { var begTime = utility.getUnixTimeStamp() - configuration.MinimumDelay var endTime = utility.getUnixTimeStamp() + configuration.MinimumDeuration var tableName = configuration.TableMAAccountModelAnnouncerAccountModel + accountHashID redisClient.hget(tableName, configuration.ConstantAMAAMBudget, function (err, replies) { if (err) { callback(err, null) return } if (parseInt(payload[configuration.ConstantCMBudget]) <= parseInt(replies)) { // First Check Pass if (parseInt(payload[configuration.ConstantCMBeginningTime]) >= begTime) { // Second Check Pass if (parseInt(payload[configuration.ConstantCMEndingTime]) >= endTime) { // Third Check Pass callback(null, 'Successful Check') } else { callback(new Error('Ending Time Problem'), null) return } } else { callback(new Error('Beginning Time Problem'), null) return } } else { callback(new Error('Budget Problem'), null) return } }) }, checkCampaignModelForExistence: function (redisClient, accountHashID, campaignHashID, callback) { var tableName = configuration.TableMSAccountModelCampaignModel + accountHashID redisClient.zscore(tableName, campaignHashID, function (err, replies) { if (err) { callback(err, null) return } if (replies == null || replies == undefined) callback(new Error(configuration.message.campaign.notExist), null) else callback(null, configuration.message.campaign.exist) }) } }
var configuration = require('../../config/configuration.json') var utility = require('../../public/method/utility') module.exports = { checkCampaignModel: function (redisClient, accountHashID, payload, callback) { var begTime = utility.getUnixTimeStamp() - configuration.MinimumDelay var endTime = utility.getUnixTimeStamp() + configuration.MinimumDeuration var tableName = configuration.TableMAAccountModelAnnouncerAccountModel + accountHashID redisClient.hget(tableName, configuration.ConstantAMAAMBudget, function (err, replies) { if (err) { callback(err, null) return } if (parseInt(payload[configuration.ConstantCMBudget]) <= parseInt(replies)) { // First Check Pass if (parseInt(payload[configuration.ConstantCMBeginningTime]) >= begTime) { // Second Check Pass if (parseInt(payload[configuration.ConstantCMEndingTime]) >= endTime) { // Third Check Pass callback(null, 'Successful Check') } else { callback(new Error('Ending Time Problem'), null) return } } else { callback(new Error('Beginning Time Problem'), null) return } } else { callback(new Error('Budget Problem'), null) return } }) }, } }
Select all on input elements when navigating to them
import React from 'react'; import ImmutableComponent from '../../../ImmutableComponent'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import SuggestionsList from '../suggestions-list'; import { getEditValue, getDefaultValue } from '../format'; export default class InteractiveEditable extends ImmutableComponent { constructor(props) { super(props); this.input = null; } componentDidMount() { setImmediate(() => { if (this.input && this.input.focus && this.input.select) { this.input.focus(); this.input.select(); } }); } render() { const { item, value, onChange } = this.props; const inputRef = input => { this.input = input; }; const onInputChange = evt => onChange(getEditValue(item, value, evt.target.value)); const className = classNames('active', 'editable', `editable-${item}`); const inputClassName = classNames('editable-input'); return <span className={className}> <input ref={inputRef} className={inputClassName} type="text" defaultValue={getDefaultValue(item, value)} onChange={onInputChange} /> <SuggestionsList /> </span>; } } InteractiveEditable.propTypes = { item: PropTypes.string.isRequired, value: PropTypes.any, onChange: PropTypes.func.isRequired };
import { List as list } from 'immutable'; import React from 'react'; import ImmutableComponent from '../../../ImmutableComponent'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import SuggestionsList from '../suggestions-list'; import { getEditValue, getDefaultValue } from '../format'; export default class InteractiveEditable extends ImmutableComponent { constructor(props) { super(props); this.input = null; } componentDidMount() { setImmediate(() => { if (this.input && this.input.focus) { this.input.focus(); } }); } render() { const { item, value, onChange } = this.props; const inputRef = input => { this.input = input; }; const onInputChange = evt => onChange(getEditValue(item, value, evt.target.value)); const className = classNames('active', 'editable', `editable-${item}`); const inputClassName = classNames('editable-input'); return <span className={className}> <input ref={inputRef} className={inputClassName} type="text" defaultValue={getDefaultValue(item, value)} onChange={onInputChange} /> <SuggestionsList /> </span>; } } InteractiveEditable.propTypes = { item: PropTypes.string.isRequired, value: PropTypes.any, onChange: PropTypes.func.isRequired };
Fix overflowing text bug by replacing the tags. Fix weird text overflowing bug/glitch by replacing <pre> tags with <div>. This should fix the overflowing/xyz bug/glitch thing since <div> is block-shaped. Not sure about <pre> but I think it's not block-shaped.. Maybe this might be the problem. More about <pre>'s: http://www.w3.org/TR/html-markup/pre.html
<!DOCTYPE html> <html> <head> <title>OpenSprites Blog</title> <?php include("header.php"); ?> </head> <body> <!-- This is slightly inspired by andrewjcole's blog, those who haven't should check it out at blog.opensprites.x10.mx/andrewjcole/ --> <?php include("includes.php"); ?> <div id="entries"></div> <script> var on_page_limit = 5; var count = <?php if(isset($_GET['count'])) { $number = $_GET['count']; } else { $number = 0; foreach(glob("entries/*.xml") as $filename) { if(is_numeric(substr($filename, 8, -4))) { $number++; } } } echo $number; ?>; var entries = ""; for (var i = count; i > count - on_page_limit && i > 0; i--) { entries += blog_load_html(i.toString(), function(r) { $("#entries").append(r).append('<hr>'); $('code').wrap('<div>').each(function(i, block) { hljs.highlightBlock(block); }); }); } </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>OpenSprites Blog</title> <?php include("header.php"); ?> </head> <body> <!-- This is slightly inspired by andrewjcole's blog, those who haven't should check it out at blog.opensprites.x10.mx/andrewjcole/ --> <?php include("includes.php"); ?> <div id="entries"></div> <script> var on_page_limit = 5; var count = <?php if(isset($_GET['count'])) { $number = $_GET['count']; } else { $number = 0; foreach(glob("entries/*.xml") as $filename) { if(is_numeric(substr($filename, 8, -4))) { $number++; } } } echo $number; ?>; var entries = ""; for (var i = count; i > count - on_page_limit && i > 0; i--) { entries += blog_load_html(i.toString(), function(r) { $("#entries").append(r).append('<hr>'); $('code').wrap('<pre>').each(function(i, block) { hljs.highlightBlock(block); }); }); } </script> </body> </html>
Add default fallback to mapping logic.
(function () { 'use strict'; define( [ 'lodash', 'knockout' ], function (_, ko) { return function (selectedSearchTypeObservable, resultFieldsObservable, detailUrlTemplate) { return { mapType: function (searchType) { return { key: searchType.key, label: '<span class="small glyphicon glyphicon-' + searchType.glyphicon + '"></span> ' + searchType.labelText, placeholder: 'Search by ' + searchType.labelText + '...', active: ko.pureComputed(function () { return selectedSearchTypeObservable() === searchType.key; }), makeActive: function () { selectedSearchTypeObservable(searchType.key); } }; }, mapResult: function (result) { return _(result) .defaults(_.zipObject( _.map(resultFieldsObservable(), 'key'), _.map(Object.keys(resultFieldsObservable()), _.constant('')) )) .mapValues(function (value, key) { var field = _.find(resultFieldsObservable(), { key: key }) || {}; return { key: key, value: value, displayValue: _.isFunction(field.displayValue) ? field.displayValue(value) : '' + value }; }) .merge({ // jshint sub: true detailUrl: detailUrlTemplate.replace(':id', result['object_id']) }) .value(); } }; }; } ); }());
(function () { 'use strict'; define( [ 'lodash', 'knockout' ], function (_, ko) { return function (selectedSearchTypeObservable, resultFieldsObservable, detailUrlTemplate) { return { mapType: function (searchType) { return { key: searchType.key, label: '<span class="small glyphicon glyphicon-' + searchType.glyphicon + '"></span> ' + searchType.labelText, placeholder: 'Search by ' + searchType.labelText + '...', active: ko.pureComputed(function () { return selectedSearchTypeObservable() === searchType.key; }), makeActive: function () { selectedSearchTypeObservable(searchType.key); } }; }, mapResult: function (result) { return _(result) .mapValues(function (value, key) { var field = _.find(resultFieldsObservable(), { key: key }) || {}; return { key: key, value: value, displayValue: _.isFunction(field.displayValue) ? field.displayValue(value) : '' + value }; }) .merge({ // jshint sub: true detailUrl: detailUrlTemplate.replace(':id', result['object_id']) }) .value(); } }; }; } ); }());
Use TreeBuilder constructor, deprecated using RootNode
<?php namespace Bookboon\ApiBundle\DependencyInjection; use Bookboon\Api\Cache\RedisCache; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { /** * Generates the configuration tree builder. * * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('bookboonapi'); $treeBuilder ->getRootNode() ->children() ->scalarNode('id')->isRequired()->end() ->scalarNode('secret')->isRequired()->end() ->scalarNode('branding')->end() ->scalarNode('rotation')->end() ->scalarNode('currency')->end() ->scalarNode('impersonator_id')->defaultNull()->end() ->scalarNode('redirect')->defaultNull()->end() ->scalarNode('cache_service')->defaultValue(RedisCache::class)->end() ->arrayNode('languages')->isRequired()->prototype('scalar')->end()->end() ->arrayNode('scopes')->isRequired()->prototype('scalar')->end()->end() ->integerNode('premium_level')->end() ->scalarNode('override_api_uri')->defaultNull()->end() ->scalarNode('override_auth_uri')->defaultNull()->end() ; return $treeBuilder; } }
<?php namespace Bookboon\ApiBundle\DependencyInjection; use Bookboon\Api\Cache\RedisCache; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { /** * Generates the configuration tree builder. * * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('bookboonapi'); $rootNode->children() ->scalarNode('id')->isRequired()->end() ->scalarNode('secret')->isRequired()->end() ->scalarNode('branding')->end() ->scalarNode('rotation')->end() ->scalarNode('currency')->end() ->scalarNode('impersonator_id')->defaultNull()->end() ->scalarNode('redirect')->defaultNull()->end() ->scalarNode('cache_service')->defaultValue(RedisCache::class)->end() ->arrayNode('languages')->isRequired()->prototype('scalar')->end()->end() ->arrayNode('scopes')->isRequired()->prototype('scalar')->end()->end() ->integerNode('premium_level')->end() ->scalarNode('override_api_uri')->defaultNull()->end() ->scalarNode('override_auth_uri')->defaultNull()->end() ; return $treeBuilder; } }
Set better description to superhelio:reload
<?php namespace Superhelio\Commands\Commands; use Illuminate\Console\Command; class Reload extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'superhelio:reload'; /** * The console command description. * * @var string */ protected $description = 'Rollback migrations, migrate and run seeds'; /** * Create a new command instance. */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { if ($this->confirm('Rollback all your database tables, recreate them and seed?')) { $this->call( 'migrate:reset', [ '--no-interaction' => true, '--env' => 'development', '--verbose' => 3 ] ); $this->call( 'migrate', [ '--seed' => true, '--no-interaction' => true, '--env' => 'development', '--verbose' => 3 ] ); } } }
<?php namespace Superhelio\Commands\Commands; use Illuminate\Console\Command; class Reload extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'superhelio:reload'; /** * The console command description. * * @var string */ protected $description = 'Delete database tables, migrate and run seeds'; /** * Create a new command instance. */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { if ($this->confirm('Rollback all your database tables, recreate them and seed?')) { $this->call( 'migrate:reset', [ '--no-interaction' => true, '--env' => 'development', '--verbose' => 3 ] ); $this->call( 'migrate', [ '--seed' => true, '--no-interaction' => true, '--env' => 'development', '--verbose' => 3 ] ); } } }
Add 'treq' as a requirement for GitHubStatusPush.
from setuptools import setup, find_packages setup( name='autobuilder', version='1.0.3', packages=find_packages(), license='MIT', author='Matt Madison', author_email='[email protected]', entry_points={ 'console_scripts': [ 'update-sstate-mirror = autobuilder.scripts.update_sstate_mirror:main', 'update-downloads = autobuilder.scripts.update_downloads:main', 'install-sdk = autobuilder.scripts.install_sdk:main', 'autorev-report = autobuilder.scripts.autorev_report:main' ] }, include_package_data=True, package_data={ 'autobuilder': ['templates/*.txt'] }, install_requires=['buildbot[tls]>=1.4.0', 'buildbot-worker>=1.4.0', 'buildbot-www>=1.4.0', 'buildbot-console-view>=1.4.0', 'buildbot-grid-view>=1.4.0', 'buildbot-waterfall-view>=1.4.0' 'buildbot-badges>=1.4.0', 'boto3', 'botocore', 'treq', 'twisted'] )
from setuptools import setup, find_packages setup( name='autobuilder', version='1.0.2', packages=find_packages(), license='MIT', author='Matt Madison', author_email='[email protected]', entry_points={ 'console_scripts': [ 'update-sstate-mirror = autobuilder.scripts.update_sstate_mirror:main', 'update-downloads = autobuilder.scripts.update_downloads:main', 'install-sdk = autobuilder.scripts.install_sdk:main', 'autorev-report = autobuilder.scripts.autorev_report:main' ] }, include_package_data=True, package_data={ 'autobuilder': ['templates/*.txt'] }, install_requires=['buildbot[tls]>=1.4.0', 'buildbot-worker>=1.4.0', 'buildbot-www>=1.4.0', 'buildbot-console-view>=1.4.0', 'buildbot-grid-view>=1.4.0', 'buildbot-waterfall-view>=1.4.0' 'buildbot-badges>=1.4.0', 'boto3', 'botocore', 'twisted'] )
Fix jslint warning in null checks
/*! * Wef * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ /** * wef module */ (function(global) { var wef = function() { return new wef.prototype.init(); }; wef.prototype = { constructor:wef, version: "0.0.1", init: function() { return this; } }; wef.fn = wef.prototype; wef.prototype.init.prototype = wef.prototype; wef.fn.extend = function (receiver, giver) { var tmp = receiver; //both must be objects if (typeof receiver === "object" && typeof giver === "object") { if (tmp === null) { tmp = {}; } if (receiver === null) { return tmp; } for (var property in giver) { tmp[property] = giver[property]; } return tmp } wef.f.error("InvalidArgumentException: incorrect argument type"); return null; }; wef.fn.isFunction = function (obj) { return typeof obj == "function"; }; wef.fn.isString = function (obj) { return typeof obj == "string"; }; wef.fn.error = function (message) { throw new Error(message); }; //registering global variable if (global.wef) { throw new Error("wef has already been defined"); } else { global.wef = wef(); } })(window);
/*! * Wef * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ /** * wef module */ (function(global) { var wef = function() { return new wef.prototype.init(); }; wef.prototype = { constructor:wef, version: "0.0.1", init: function() { return this; } }; wef.fn = wef.prototype; wef.prototype.init.prototype = wef.prototype; wef.fn.extend = function (receiver, giver) { var tmp = receiver; //both must be objects if (typeof receiver === "object" && typeof giver === "object") { if (tmp == null) { tmp = {}; } if (receiver == null) { return tmp; } for (var property in giver) { tmp[property] = giver[property]; } return tmp } wef.f.error("InvalidArgumentException: incorrect argument type"); return null; }; wef.fn.isFunction = function (obj) { return typeof obj == "function"; }; wef.fn.isString = function (obj) { return typeof obj == "string"; }; wef.fn.error = function (message) { throw new Error(message); }; //registering global variable if (global.wef) { throw new Error("wef has already been defined"); } else { global.wef = wef(); } })(window);
Add LOGIN_URL setting for Oauth2
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'oauth2_provider.ext.rest_framework.OAuth2Authentication', ), 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',), 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } # API login URL for oauth2_provider (based on default routing in urls.py) LOGIN_URL = "/api/auth/login/" SWAGGER_SETTINGS = { 'exclude_namespaces': [], 'api_version': '', 'api_path': '/', 'api_key': '', # Your OAuth2 Access Token 'token_type': 'Bearer', 'is_authenticated': False, 'is_superuser': False, 'permission_denied_handler': None, 'info': { 'title': 'API Resource Documentation', 'description': 'The RESTful web API exposes Mezzanine data using JSON serialization and OAuth2 protection. ' 'This interactive document will guide you through the relevant API endpoints, data structures, ' 'and query parameters for filtering, searching and pagination. Otherwise, for further ' 'information and examples, consult the general ' '<a href="http://gcushen.github.io/mezzanine-api" target="_blank">Mezzanine API Documentation' '</a>.', }, 'doc_expansion': 'none', }
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'oauth2_provider.ext.rest_framework.OAuth2Authentication', ), 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',), 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } SWAGGER_SETTINGS = { 'exclude_namespaces': [], 'api_version': '', 'api_path': '/', 'api_key': '', # Your OAuth2 Access Token 'token_type': 'Bearer', 'is_authenticated': False, 'is_superuser': False, 'permission_denied_handler': None, 'info': { 'title': 'API Resource Documentation', 'description': 'The RESTful web API exposes Mezzanine data using JSON serialization and OAuth2 protection. ' 'This interactive document will guide you through the relevant API endpoints, data structures, ' 'and query parameters for filtering, searching and pagination. Otherwise, for further ' 'information and examples, consult the general ' '<a href="http://gcushen.github.io/mezzanine-api" target="_blank">Mezzanine API Documentation' '</a>.', }, 'doc_expansion': 'none', }
Create helpers to create a raven instance
package net.kencochrane.raven; import java.util.ServiceLoader; /** * Factory in charge of creating {@link Raven} instances. * <p> * The factories register themselves through the {@link ServiceLoader} system. * </p> */ public abstract class RavenFactory { private static final ServiceLoader<RavenFactory> RAVEN_FACTORIES = ServiceLoader.load(RavenFactory.class); public static Raven ravenInstance() { return ravenInstance(Dsn.dsnLookup()); } public static Raven ravenInstance(String dsn) { return ravenInstance(new Dsn(dsn)); } public static Raven ravenInstance(Dsn dsn) { for (RavenFactory ravenFactory : RAVEN_FACTORIES) { Raven raven = ravenFactory.createRavenInstance(dsn); if (raven != null) { return raven; } } throw new IllegalStateException("Couldn't create a raven instance for '" + dsn + "'"); } public static Raven ravenInstance(Dsn dsn, String ravenFactoryName) { if (ravenFactoryName == null) return ravenInstance(dsn); for (RavenFactory ravenFactory : RAVEN_FACTORIES) { if (!ravenFactoryName.equals(ravenFactory.getClass().getName())) continue; Raven raven = ravenFactory.createRavenInstance(dsn); if (raven != null) { return raven; } } throw new IllegalStateException("Couldn't create a raven instance for '" + dsn + "'"); } protected abstract Raven createRavenInstance(Dsn dsn); }
package net.kencochrane.raven; import java.util.ServiceLoader; /** * Factory in charge of creating {@link Raven} instances. * <p> * The factories register themselves through the {@link ServiceLoader} system. * </p> */ public abstract class RavenFactory { private static final ServiceLoader<RavenFactory> RAVEN_FACTORIES = ServiceLoader.load(RavenFactory.class); public static Raven ravenInstance(Dsn dsn) { for (RavenFactory ravenFactory : RAVEN_FACTORIES) { Raven raven = ravenFactory.createRavenInstance(dsn); if (raven != null) { return raven; } } throw new IllegalStateException("Couldn't create a raven instance for '" + dsn + "'"); } public static Raven ravenInstance(Dsn dsn, String ravenFactoryName) { if (ravenFactoryName == null) return ravenInstance(dsn); for (RavenFactory ravenFactory : RAVEN_FACTORIES) { if (!ravenFactoryName.equals(ravenFactory.getClass().getName())) continue; Raven raven = ravenFactory.createRavenInstance(dsn); if (raven != null) { return raven; } } throw new IllegalStateException("Couldn't create a raven instance for '" + dsn + "'"); } protected abstract Raven createRavenInstance(Dsn dsn); }
Remove unused imports to fix Travis
package seedu.taskmanager.ui; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Region; import seedu.taskmanager.commons.util.FxViewUtil; import seedu.taskmanager.model.task.ReadOnlyTask; /** * The Browser Panel of the App. */ public class BrowserPanel extends UiPart<Region> { private static final String FXML = "BrowserPanel.fxml"; /* * @FXML private WebView browser; */ @FXML private AnchorPane browser; /** * @param placeholder * The AnchorPane where the BrowserPanel must be inserted */ public BrowserPanel(AnchorPane placeholder) { super(FXML); placeholder.setOnKeyPressed(Event::consume); // To prevent triggering // events for typing inside // the // loaded Web page. FxViewUtil.applyAnchorBoundaryParameters(browser, 0.0, 0.0, 0.0, 0.0); placeholder.getChildren().add(browser); } public void loadTaskPage(ReadOnlyTask task) { // loadPage("https://www.google.com.sg/#safe=off&q=" + // task.getTaskName().fullTaskName.replaceAll(" ", "+")); } /* * public void loadPage(String url) { browser.getEngine().load(url); } */ /** * Frees resources allocated to the browser. */ // public void freeResources() { // browser = null; // } }
package seedu.taskmanager.ui; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Region; import javafx.scene.web.WebView; import seedu.taskmanager.commons.util.FxViewUtil; import seedu.taskmanager.model.task.ReadOnlyTask; /** * The Browser Panel of the App. */ public class BrowserPanel extends UiPart<Region> { private static final String FXML = "BrowserPanel.fxml"; /* * @FXML private WebView browser; */ @FXML private AnchorPane browser; /** * @param placeholder * The AnchorPane where the BrowserPanel must be inserted */ public BrowserPanel(AnchorPane placeholder) { super(FXML); placeholder.setOnKeyPressed(Event::consume); // To prevent triggering // events for typing inside // the // loaded Web page. FxViewUtil.applyAnchorBoundaryParameters(browser, 0.0, 0.0, 0.0, 0.0); placeholder.getChildren().add(browser); } public void loadTaskPage(ReadOnlyTask task) { // loadPage("https://www.google.com.sg/#safe=off&q=" + // task.getTaskName().fullTaskName.replaceAll(" ", "+")); } /* * public void loadPage(String url) { browser.getEngine().load(url); } */ /** * Frees resources allocated to the browser. */ // public void freeResources() { // browser = null; // } }
Add some javadoc. Detect if the limit is a negative number. Extract method for processing the limit value as a numeric.
package uk.ac.ebi.quickgo.ontology.coterms; /** * Logic for determining the limit to use for retrieving co-occurring terms * * @author Tony Wardell * Date: 29/09/2016 * Time: 16:08 * Created with IntelliJ IDEA. */ public class CoTermLimit { int defaultLimit; /** * * @param defaultLimit The limit to use under some circumstances. */ public CoTermLimit(int defaultLimit) { this.defaultLimit = defaultLimit; } /** * Determine the limit value to use for retrieving co-occurring terms. * @param limit value to be checked. * @return */ public int workoutLimit(String limit) { int limitNumeric; if (limit == null) { limitNumeric = defaultLimit; } else { if (LimitValue.ALL.toString().equalsIgnoreCase(limit)) { limitNumeric = Integer.MAX_VALUE; } else { if (limit.trim().length() == 0) { limitNumeric = defaultLimit; } else { limitNumeric = processLimitAsANumeric(limit); } } } return limitNumeric; } /** * Now that other values for limit have been attempted, treat the argument as a numeric and deal with any * problems that occur if it is not. * @param limit * @return a limit value. */ private int processLimitAsANumeric(String limit) { int limitNumeric; try { limitNumeric = Integer.parseInt(limit); if(limitNumeric < 0){ throw new IllegalArgumentException("The value for limit cannot be negative"); } if (limitNumeric == 0) { limitNumeric = defaultLimit; } } catch (NumberFormatException e) { throw new IllegalArgumentException("The value for co-occurring terms limit is not ALL, or a " + "number"); } return limitNumeric; } enum LimitValue { ALL } }
package uk.ac.ebi.quickgo.ontology.coterms; /** * @author Tony Wardell * Date: 29/09/2016 * Time: 16:08 * Created with IntelliJ IDEA. */ public class CoTermLimit { int defaultLimit; public CoTermLimit(int defaultLimit) { this.defaultLimit = defaultLimit; } public int workoutLimit(String limit) { int limitNumeric = 0; if (limit == null) { limitNumeric = defaultLimit; } else { if (LimitValue.ALL.toString().equalsIgnoreCase(limit)) { limitNumeric = Integer.MAX_VALUE; } else { if (limit.trim().length() == 0) { limitNumeric = defaultLimit; } else { try { limitNumeric = Integer.parseInt(limit); if (limitNumeric == 0) { limitNumeric = defaultLimit; } } catch (NumberFormatException e) { throw new IllegalArgumentException("The value for co-occurring terms limit is not ALL, or a " + "number"); } } } } return limitNumeric; } enum LimitValue { ALL } }
:lipstick: Fix coding style - lowercase keywords
<?php namespace Clippings\Freezable; /** * @author Haralan Dobrev <[email protected]> * @copyright 2014, Clippings Ltd. * @license http://spdx.org/licenses/BSD-3-Clause */ trait FreezableCollectionTrait { use FreezableTrait; private static function ensureItemsAreTraversable($items) { if (! is_array($items) and ! $items instanceof \Traversable) { throw new \UnexpectedValueException( 'Collection returned from getItems() should be either an array or a Traversable object.' ); } } /** * {@inheritdoc} */ public function performFreeze() { $items = $this->getItems(); self::ensureItemsAreTraversable($items); foreach ($items as $item) { if (! method_exists($item, 'freeze')) { throw new \UnexpectedValueException('Item should use the FreezableTrait to be freezed'); } $item->freeze(); } } /** * {@inheritdoc} */ public function performUnfreeze() { $items = $this->getItems(); self::ensureItemsAreTraversable($items); foreach ($items as $item) { if (! method_exists($item, 'unfreeze')) { throw new \UnexpectedValueException('Item should use the FreezableTrait to be unfreezed'); } $item->unfreeze(); } } /** * @return array|Traversable */ abstract public function getItems(); }
<?php namespace Clippings\Freezable; /** * @author Haralan Dobrev <[email protected]> * @copyright 2014, Clippings Ltd. * @license http://spdx.org/licenses/BSD-3-Clause */ trait FreezableCollectionTrait { use FreezableTrait; private static function ensureItemsAreTraversable($items) { if (! is_array($items) AND ! $items instanceof \Traversable) { throw new \UnexpectedValueException( 'Collection returned from getItems() should be either an array or a Traversable object.' ); } } /** * {@inheritdoc} */ public function performFreeze() { $items = $this->getItems(); self::ensureItemsAreTraversable($items); foreach ($items as $item) { if (! method_exists($item, 'freeze')) { throw new \UnexpectedValueException('Item should use the FreezableTrait to be freezed'); } $item->freeze(); } } /** * {@inheritdoc} */ public function performUnfreeze() { $items = $this->getItems(); self::ensureItemsAreTraversable($items); foreach ($items as $item) { if (! method_exists($item, 'unfreeze')) { throw new \UnexpectedValueException('Item should use the FreezableTrait to be unfreezed'); } $item->unfreeze(); } } /** * @return array|Traversable */ abstract public function getItems(); }
Allow Local LAN devices to access the livereload machine
const rewrite = require('connect-modrewrite'); const serveIndex = require('serve-index'); const serveStatic = require('serve-static'); module.exports = function (grunt) { return { livereload: { options: { hostname : '0.0.0.0', port : 443, protocol : 'https', base : 'dist', open : 'https://localhost.localdomain', middleware: (connect, options) => { const middlewares = [ require('connect-livereload')(), ]; const rules = [ '^/binary-static/(.*)$ /$1', ]; middlewares.push(rewrite(rules)); if (!Array.isArray(options.base)) { options.base = [options.base]; } options.base.forEach((base) => { middlewares.push(serveStatic(base)); }); const directory = options.directory || options.base[options.base.length - 1]; middlewares.push(serveIndex(directory)); middlewares.push((req, res) => { const path_404 = `${options.base[0]}/404.html`; if (grunt.file.exists(path_404)) { require('fs').createReadStream(path_404).pipe(res); return; } res.statusCode(404); // 404.html not found res.end(); }); return middlewares; } } }, }; };
const rewrite = require('connect-modrewrite'); const serveIndex = require('serve-index'); const serveStatic = require('serve-static'); module.exports = function (grunt) { return { livereload: { options: { hostname : '127.0.0.1', port : 443, protocol : 'https', base : 'dist', open : 'https://localhost.localdomain', middleware: (connect, options) => { const middlewares = [ require('connect-livereload')(), ]; const rules = [ '^/binary-static/(.*)$ /$1', ]; middlewares.push(rewrite(rules)); if (!Array.isArray(options.base)) { options.base = [options.base]; } options.base.forEach((base) => { middlewares.push(serveStatic(base)); }); const directory = options.directory || options.base[options.base.length - 1]; middlewares.push(serveIndex(directory)); middlewares.push((req, res) => { const path_404 = `${options.base[0]}/404.html`; if (grunt.file.exists(path_404)) { require('fs').createReadStream(path_404).pipe(res); return; } res.statusCode(404); // 404.html not found res.end(); }); return middlewares; } } }, }; };
Include an uglified version when compiling
module.exports = function(grunt) { var requirejsOptions = require('./config'); requirejsOptions.optimize = 'none'; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: ['Gruntfile.js', 'js/**/*.js', 'tests/*.js'] }, karma: { options: { configFile: 'tests/karma.conf.js', runnerPort: 9999, browsers: ['Chrome'] }, dev: { autoWatch: true }, ci: { singleRun: true, reporters: ['dots', 'junit', 'coverage'], junitReporter: { outputFile: 'test-results.xml' }, coverageReporter: { type : 'cobertura', dir : 'coverage/' } // SauceLabs stuff comes here } }, requirejs: { options: requirejsOptions, bundle: { options: { name: 'node_modules/almond/almond.js', include: '<%= _.slugify(packageName) %>-bundle', insertRequire: ['<%= _.slugify(packageName) %>-bundle'], out: 'build/bundle.js', excludeShallow: ['jquery'] } } }, uglify: { widgets: { files: { 'build/bundle.min.js': ['build/bundle.js'] } } } }); grunt.loadNpmTasks('grunt-contrib-requirejs'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('default', ['requirejs:bundle']); };
module.exports = function(grunt) { var requirejsOptions = require('./config'); requirejsOptions.optimize = 'none'; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: ['Gruntfile.js', 'js/**/*.js', 'tests/*.js'] }, karma: { options: { configFile: 'tests/karma.conf.js', runnerPort: 9999, browsers: ['Chrome'] }, dev: { autoWatch: true }, ci: { singleRun: true, reporters: ['dots', 'junit', 'coverage'], junitReporter: { outputFile: 'test-results.xml' }, coverageReporter: { type : 'cobertura', dir : 'coverage/' } // SauceLabs stuff comes here } }, requirejs: { options: requirejsOptions, bundle: { options: { name: 'node_modules/almond/almond.js', include: '<%= _.slugify(packageName) %>-bundle', insertRequire: ['<%= _.slugify(packageName) %>-bundle'], out: 'build/bundle.min.js', excludeShallow: ['jquery'] } } } }); grunt.loadNpmTasks('grunt-contrib-requirejs'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('default', ['requirejs:bundle']); };
Change path to site no requested authorization.
package bj.pranie.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * Created by noon on 13.10.16. */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests() .antMatchers("/", "/week" ,"/week/*", "/wm/*/*", "/user/registration", "/user/restore", "/images/*", "/js/*").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("admin").roles("USER"); } }
package bj.pranie.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * Created by noon on 13.10.16. */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests() .antMatchers("/", "/week" ,"/week/*", "/wm/*", "/user/registration", "/user/restore", "/images/*", "/js/*").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("admin").roles("USER"); } }
Declare wizard abstract factory in service manager
<?php return array( 'wizard' => array( 'default_layout_template' => 'wizard/layout', 'default_class' => 'Wizard\Wizard', ), 'service_manager' => array( 'invokables' => array( 'Wizard\Form\Element\Button\Cancel' => 'Wizard\Form\Element\Button\Cancel', 'Wizard\Form\Element\Button\Next' => 'Wizard\Form\Element\Button\Next', 'Wizard\Form\Element\Button\Previous' => 'Wizard\Form\Element\Button\Previous', 'Wizard\Form\Element\Button\Valid' => 'Wizard\Form\Element\Button\Valid', 'Wizard\Form\FormFactory' => 'Wizard\Form\FormFactory', ), 'factories' => array( 'Wizard\Config' => 'Wizard\Factory\ConfigFactory', 'Wizard\Factory' => 'Wizard\Factory\WizardFactoryFactory', 'Wizard\WizardRenderer' => 'Wizard\Factory\WizardRendererFactory', ), 'abstract_factories' => array( 'Wizard\WizardAbstractServiceFactory' ), ), 'view_manager' => array( 'template_map' => array( 'wizard/layout' => __DIR__ . '/../view/wizard/layout.phtml', 'wizard/header' => __DIR__ . '/../view/wizard/header.phtml', 'wizard/buttons' => __DIR__ . '/../view/wizard/buttons.phtml', ), 'template_path_stack' => array( __DIR__ . '/../view', ), ), );
<?php return array( 'wizard' => array( 'default_layout_template' => 'wizard/layout', 'default_class' => 'Wizard\Wizard', ), 'service_manager' => array( 'factories' => array( 'Wizard\Config' => 'Wizard\Factory\ConfigFactory', 'Wizard\Factory' => 'Wizard\Factory\WizardFactoryFactory', 'Wizard\WizardRenderer' => 'Wizard\Factory\WizardRendererFactory', ), 'invokables' => array( 'Wizard\Form\Element\Button\Cancel' => 'Wizard\Form\Element\Button\Cancel', 'Wizard\Form\Element\Button\Next' => 'Wizard\Form\Element\Button\Next', 'Wizard\Form\Element\Button\Previous' => 'Wizard\Form\Element\Button\Previous', 'Wizard\Form\Element\Button\Valid' => 'Wizard\Form\Element\Button\Valid', 'Wizard\Form\FormFactory' => 'Wizard\Form\FormFactory', ), ), 'view_manager' => array( 'template_map' => array( 'wizard/layout' => __DIR__ . '/../view/wizard/layout.phtml', 'wizard/header' => __DIR__ . '/../view/wizard/header.phtml', 'wizard/buttons' => __DIR__ . '/../view/wizard/buttons.phtml', ), 'template_path_stack' => array( __DIR__ . '/../view', ), ), );
Reduce visibility from public to package
package org.gdg.frisbee.android.about; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import org.gdg.frisbee.android.R; class AboutPagerAdapter extends FragmentStatePagerAdapter { private Context mContext; public AboutPagerAdapter(Context ctx, FragmentManager fm) { super(fm); mContext = ctx; } @Override public int getItemPosition(Object object) { return POSITION_NONE; } @Override public int getCount() { return mContext.getResources().getStringArray(R.array.about_tabs).length; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new AboutFragment(); case 1: return new ContributorsFragment(); case 2: return new TranslatorsFragment(); case 3: return new ChangelogFragment(); case 4: return new GetInvolvedFragment(); case 5: return new ExtLibrariesFragment(); } return null; } @Override public CharSequence getPageTitle(int position) { return mContext.getResources().getStringArray(R.array.about_tabs)[position]; } }
package org.gdg.frisbee.android.about; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import org.gdg.frisbee.android.R; public class AboutPagerAdapter extends FragmentStatePagerAdapter { private Context mContext; public AboutPagerAdapter(Context ctx, FragmentManager fm) { super(fm); mContext = ctx; } @Override public int getItemPosition(Object object) { return POSITION_NONE; } @Override public int getCount() { return mContext.getResources().getStringArray(R.array.about_tabs).length; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new AboutFragment(); case 1: return new ContributorsFragment(); case 2: return new TranslatorsFragment(); case 3: return new ChangelogFragment(); case 4: return new GetInvolvedFragment(); case 5: return new ExtLibrariesFragment(); } return null; } @Override public CharSequence getPageTitle(int position) { return mContext.getResources().getStringArray(R.array.about_tabs)[position]; } }
Add file dimensions when we read in images
import { Meteor } from 'meteor/meteor'; import { ImageFiles } from '/imports/api/imageFiles/imageFiles'; import fs from 'fs'; import _ from 'lodash'; import sizeOf from 'image-size'; import mime from 'mime'; // Path to our images folder const collectionImages = `${process.env.PWD}/public/images/collection/`; // Read the files in the collections folder and build a collection Meteor.startup(() => { // Clear out the ImageFiles collection before reading from the directory ImageFiles.remove({}); fs.readdir( collectionImages, // Handle the async file read process inside of Meteor's fiber Meteor.bindEnvironment( (err, imageFiles) => { /** * If the image file is an allowed file type, insert it into the * ImageFiles db collection */ _.each(imageFiles, imageFile => { const allowedTypes = [ 'image/jpeg', 'image/png', ]; const filePath = collectionImages + imageFile; const mimeType = mime.lookup(filePath); if (_.includes(allowedTypes, mimeType)) { const imageFileObject = { filename: imageFile }; // Add dimension details to the database for better sizing on screen const dimensions = sizeOf(filePath); imageFileObject.width = dimensions.width; imageFileObject.height = dimensions.height; ImageFiles.insert(imageFileObject); } else { console.log(mimeType); } }); } ) ); });
import { Meteor } from 'meteor/meteor'; import { ImageFiles } from '/imports/api/imageFiles/imageFiles'; import fs from 'fs'; import _ from 'lodash'; import sizeOf from 'image-size'; import mime from 'mime'; // Path to our images folder const collectionImages = `${process.env.PWD}/public/images/collection/`; // Read the files in the collections folder and build a collection Meteor.startup(() => { // Clear out the ImageFiles collection before reading from the directory ImageFiles.remove({}); fs.readdir( collectionImages, // Handle the async file read process inside of Meteor's fiber Meteor.bindEnvironment( (err, imageFiles) => { /** * If the image file is an allowed file type, insert it into the * ImageFiles db collection */ _.each(imageFiles, imageFile => { const allowedTypes = [ 'image/jpeg', 'image/png', ]; const filePath = collectionImages + imageFile; const mimeType = mime.lookup(filePath); if (_.includes(allowedTypes, mimeType)) { const imageFileObject = { filename: imageFile }; ImageFiles.insert(imageFileObject); } else { console.log(mimeType); } }); } ) ); });
Use 'include' to check for file existance. As it uses the include path.
<?php // Load console class for autoloader? $use_console = false; // Optional mapping of Namespace to directories. $namespace_mapping = array( 'NigeLib' => 'src', ); if( $use_console ) { require( 'src/Console.php' ); } function PSR0_autoload($className) { global $use_console; global $namespace_mapping; $className = ltrim($className, '\\'); $fileName = ''; $namespace = ''; if ($lastNsPos = strripos($className, '\\')) { $namespace = substr($className, 0, $lastNsPos); $className = substr($className, $lastNsPos + 1); if( isset( $namespace_mapping[$namespace] ) ) { $path = $namespace_mapping[$namespace]; } else { $path = $namespace; } $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $path) . DIRECTORY_SEPARATOR; } $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; if( $use_console ) { NigeLib\Console::output( "Loading: $fileName for class $className in $namespace" ); } $found = @include $fileName; if( !$found && $use_console ) { NigeLib\Console::output( "Loading: $fileName does not exist." ); } } spl_autoload_register( 'PSR0_autoload' );
<?php // Load console class for autoloader? $use_console = true; // Optional mapping of Namespace to directories. $namespace_mapping = array( 'NigeLib' => 'src', ); if( $use_console ) { require( 'src/Console.php' ); } function PSR0_autoload($className) { global $use_console; global $namespace_mapping; $className = ltrim($className, '\\'); $fileName = ''; $namespace = ''; if ($lastNsPos = strripos($className, '\\')) { $namespace = substr($className, 0, $lastNsPos); $className = substr($className, $lastNsPos + 1); if( isset( $namespace_mapping[$namespace] ) ) { $path = $namespace_mapping[$namespace]; } else { $path = $namespace; } $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $path) . DIRECTORY_SEPARATOR; } $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; if( $use_console ) { NigeLib\Console::output( "Loading: $fileName for class $className in $namespace" ); } if( file_exists( $fileName ) ) { include $fileName; } else if( $use_console ) { NigeLib\Console::output( "Loading: $fileName does not exist." ); } } spl_autoload_register( 'PSR0_autoload' );
Make test Callback a little more reusable
<?php namespace Respect\Validation\Rules; class CallbackTest extends \PHPUnit_Framework_TestCase { private $truthy, $falsy; function setUp() { $this->truthy = new Callback(function() { return true; }); $this->falsy = new Callback(function() { return false; }); } public function thisIsASampleCallbackUsedInsideThisTest() { return true; } public function testCallbackValidatorShouldReturnTrueIfCallbackReturnsTrue() { $this->assertTrue($this->truthy->assert('wpoiur')); } /** * @expectedException Respect\Validation\Exceptions\CallbackException */ public function testCallbackValidatorShouldReturnFalseIfCallbackReturnsFalse() { $this->assertTrue($this->falsy->assert('w poiur')); } public function testCallbackValidatorShouldAcceptArrayCallbackDefinitions() { $v = new Callback(array($this, 'thisIsASampleCallbackUsedInsideThisTest')); $this->assertTrue($v->assert('test')); } public function testCallbackValidatorShouldAcceptFunctionNamesAsString() { $v = new Callback('is_string'); $this->assertTrue($v->assert('test')); } /** * @expectedException Respect\Validation\Exceptions\ComponentException */ public function testInvalidCallbacksShouldRaiseComponentExceptionUponInstantiation() { $v = new Callback(new \stdClass); $this->assertTrue($v->assert('w poiur')); } }
<?php namespace Respect\Validation\Rules; class CallbackTest extends \PHPUnit_Framework_TestCase { public function thisIsASampleCallbackUsedInsideThisTest() { return true; } public function testCallbackValidatorShouldReturnTrueIfCallbackReturnsTrue() { $v = new Callback(function() { return true; }); $this->assertTrue($v->assert('wpoiur')); } /** * @expectedException Respect\Validation\Exceptions\CallbackException */ public function testCallbackValidatorShouldReturnFalseIfCallbackReturnsFalse() { $v = new Callback(function() { return false; }); $this->assertTrue($v->assert('w poiur')); } public function testCallbackValidatorShouldAcceptArrayCallbackDefinitions() { $v = new Callback(array($this, 'thisIsASampleCallbackUsedInsideThisTest')); $this->assertTrue($v->assert('test')); } public function testCallbackValidatorShouldAcceptFunctionNamesAsString() { $v = new Callback('is_string'); $this->assertTrue($v->assert('test')); } /** * @expectedException Respect\Validation\Exceptions\ComponentException */ public function testInvalidCallbacksShouldRaiseComponentExceptionUponInstantiation() { $v = new Callback(new \stdClass); $this->assertTrue($v->assert('w poiur')); } }
Throw the right error from failing second request Fixes #4.
// @flow type Configuration = { refreshToken: () => Promise<void>, shouldRefreshToken: (error: any) => boolean, fetch: (url: any, options: Object) => Promise<any> } function configureRefreshFetch (configuration: Configuration) { const { refreshToken, shouldRefreshToken, fetch } = configuration let refreshingTokenPromise = null return (url: any, options: Object) => { if (refreshingTokenPromise !== null) { return ( refreshingTokenPromise .then(() => fetch(url, options)) // Even if the refreshing fails, do the fetch so we reject with // error of that request .catch(() => fetch(url, options)) ) } return fetch(url, options).catch(error => { if (shouldRefreshToken(error)) { if (refreshingTokenPromise === null) { refreshingTokenPromise = new Promise((resolve, reject) => { refreshToken() .then(() => { refreshingTokenPromise = null resolve() }) .catch(refreshTokenError => { refreshingTokenPromise = null reject(refreshTokenError) }) }) } return refreshingTokenPromise .catch(() => { // If refreshing fails, continue with original error throw error }) .then(() => fetch(url, options)) } else { throw error } }) } } export default configureRefreshFetch
// @flow type Configuration = { refreshToken: () => Promise<void>, shouldRefreshToken: (error: any) => boolean, fetch: (url: any, options: Object) => Promise<any> } function configureRefreshFetch (configuration: Configuration) { const { refreshToken, shouldRefreshToken, fetch } = configuration let refreshingTokenPromise = null return (url: any, options: Object) => { if (refreshingTokenPromise !== null) { return ( refreshingTokenPromise .then(() => fetch(url, options)) // Even if the refreshing fails, do the fetch so we reject with // error of that request .catch(() => fetch(url, options)) ) } return fetch(url, options).catch(error => { if (shouldRefreshToken(error)) { if (refreshingTokenPromise === null) { refreshingTokenPromise = new Promise((resolve, reject) => { refreshToken() .then(() => { refreshingTokenPromise = null resolve() }) .catch(refreshTokenError => { refreshingTokenPromise = null reject(refreshTokenError) }) }) } return refreshingTokenPromise .then(() => fetch(url, options)) .catch(() => { // If refreshing fails, continue with original error throw error }) } else { throw error } }) } } export default configureRefreshFetch
Return the data not gzip decoded Requests does that by default so you need to use the underlying raw data and let webtest decode it itself instead.
# -*- coding: utf-8 -*- import requests from functools import partial class HttpClient(object): """A HTTP client using requests""" default_options = dict(verify=False, allow_redirects=False) def __init__(self, chunk_size=1024 * 24, session=None, **requests_options): options = self.default_options.copy() options.update(requests_options) self.options = options self.chunk_size = chunk_size self.session = session def __call__(self, uri, method, body, headers): kwargs = self.options.copy() kwargs['headers'] = headers if 'Transfer-Encoding' in headers: del headers['Transfer-Encoding'] if headers.get('Content-Length'): kwargs['data'] = body.read(int(headers['Content-Length'])) kwargs['stream'] = True if self.session is None: session = requests.sessions.Session() else: session = self.session response = session.request(method, uri, **kwargs) location = response.headers.get('location') or None status = '%s %s' % (response.status_code, response.reason) headers = [(k.title(), v) for k, v in response.headers.items()] return (status, location, headers, iter(partial(response.raw.read, self.chunk_size), ''))
# -*- coding: utf-8 -*- import requests class HttpClient(object): """A HTTP client using requests""" default_options = dict(verify=False, allow_redirects=False) def __init__(self, chunk_size=1024 * 24, session=None, **requests_options): options = self.default_options.copy() options.update(requests_options) self.options = options self.chunk_size = chunk_size self.session = session def __call__(self, uri, method, body, headers): kwargs = self.options.copy() kwargs['headers'] = headers if 'Transfer-Encoding' in headers: del headers['Transfer-Encoding'] if headers.get('Content-Length'): kwargs['data'] = body.read(int(headers['Content-Length'])) if self.session is None: session = requests.sessions.Session() else: session = self.session response = session.request(method, uri, **kwargs) location = response.headers.get('location') or None status = '%s %s' % (response.status_code, response.reason) headers = [(k.title(), v) for k, v in response.headers.items()] return (status, location, headers, response.iter_content(chunk_size=self.chunk_size))
Include analysis detail view URL in message
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView, TemplateView from .forms import AbstractAnalysisCreateForm from .pipelines import AVAILABLE_PIPELINES User = get_user_model() class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView): template_name = "analyses/new_analysis_by_type.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['available_pipelines'] = AVAILABLE_PIPELINES return context class AbstractAnalysisFormView(LoginRequiredMixin, CreateView): form_class = AbstractAnalysisCreateForm template_name = None analysis_type = 'AbstractAnalysis' analysis_description = '' analysis_create_url = None def get_form_kwargs(self): """Pass request object for form creation""" kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): response = super().form_valid(form) messages.add_message( self.request, messages.INFO, _( 'You just created a %(analysis_type)s analysis! ' 'View its detail <a href="%(analysis_detail_url)s">here</a>.' ) % { 'analysis_type': self.analysis_type, 'analysis_detail_url': self.object.get_absolute_url(), }, extra_tags='safe', ) return response
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView, TemplateView from .forms import AbstractAnalysisCreateForm from .pipelines import AVAILABLE_PIPELINES User = get_user_model() class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView): template_name = "analyses/new_analysis_by_type.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['available_pipelines'] = AVAILABLE_PIPELINES return context class AbstractAnalysisFormView(LoginRequiredMixin, CreateView): form_class = AbstractAnalysisCreateForm template_name = None analysis_type = 'AbstractAnalysis' analysis_description = '' analysis_create_url = None def get_form_kwargs(self): """Pass request object for form creation""" kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): response = super().form_valid(form) messages.add_message( self.request, messages.INFO, _('You just created a %(analysis_type)s analysis!') % { 'analysis_type': self.analysis_type } ) return response
Use maximum instead of if-statement
import numpy from chainer import cuda from chainer import function from chainer.utils import type_check class BinaryAccuracy(function.Function): ignore_label = -1 def check_type_forward(self, in_types): type_check.expect(in_types.size() == 2) x_type, t_type = in_types type_check.expect( x_type.dtype == numpy.float32, t_type.dtype == numpy.int32, t_type.shape == x_type.shape, ) def forward(self, inputs): xp = cuda.get_array_module(*inputs) y, t = inputs # flatten y = y.ravel() t = t.ravel() c = (y >= 0) count = xp.maximum(1, (t != self.ignore_label).sum()) return xp.asarray((c == t).sum(dtype='f') / count, dtype='f'), def binary_accuracy(y, t): """Computes binary classification accuracy of the minibatch. Args: y (Variable): Variable holding a matrix whose i-th element indicates the score of positive at the i-th example. t (Variable): Variable holding an int32 vector of groundtruth labels. If ``t[i] == -1``, correspondig ``x[i]`` is ignored. Accuracy is zero if all groundtruth labels are ``-1``. Returns: Variable: A variable holding a scalar array of the accuracy. .. note:: This function is non-differentiable. """ return BinaryAccuracy()(y, t)
import numpy from chainer import cuda from chainer import function from chainer.utils import type_check class BinaryAccuracy(function.Function): ignore_label = -1 def check_type_forward(self, in_types): type_check.expect(in_types.size() == 2) x_type, t_type = in_types type_check.expect( x_type.dtype == numpy.float32, t_type.dtype == numpy.int32, t_type.shape == x_type.shape, ) def forward(self, inputs): xp = cuda.get_array_module(*inputs) y, t = inputs # flatten y = y.ravel() t = t.ravel() c = (y >= 0) count = (t != self.ignore_label).sum() if int(count) == 0: count = 1 return xp.asarray((c == t).sum(dtype='f') / count, dtype='f'), def binary_accuracy(y, t): """Computes binary classification accuracy of the minibatch. Args: y (Variable): Variable holding a matrix whose i-th element indicates the score of positive at the i-th example. t (Variable): Variable holding an int32 vector of groundtruth labels. If ``t[i] == -1``, correspondig ``x[i]`` is ignored. Accuracy is zero if all groundtruth labels are ``-1``. Returns: Variable: A variable holding a scalar array of the accuracy. .. note:: This function is non-differentiable. """ return BinaryAccuracy()(y, t)
Use xdg-screensaver instead of xset
#pylint: disable=C0111,R0903 """Enable/disable automatic screen locking. Requires the following executables: * xdg-screensaver * notify-send """ import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): super(Module, self).__init__(engine, config, bumblebee.output.Widget(full_text="") ) self._active = False self.interval(1) engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE, cmd=self._toggle ) def state(self, widget): if self._active: return "activated" return "deactivated" def _toggle(self, event): self._active = not self._active if self._active: bumblebee.util.execute("xdg-screensaver reset") bumblebee.util.execute("notify-send \"Consuming caffeine\"") else: bumblebee.util.execute("notify-send \"Out of coffee\"") def update(self, widgets): if self._active: bumblebee.util.execute("xdg-screensaver reset") # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
# pylint: disable=C0111,R0903 """Enable/disable automatic screen locking. Requires the following executables: * xset * notify-send """ import bumblebee.input import bumblebee.output import bumblebee.engine class Module(bumblebee.engine.Module): def __init__(self, engine, config): super(Module, self).__init__(engine, config, bumblebee.output.Widget(full_text=self.caffeine) ) engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE, cmd=self._toggle ) def caffeine(self, widget): return "" def state(self, widget): if self._active(): return "activated" return "deactivated" def _active(self): for line in bumblebee.util.execute("xset q").split("\n"): if "timeout" in line: timeout = int(line.split(" ")[4]) if timeout == 0: return True return False return False def _toggle(self, widget): if self._active(): bumblebee.util.execute("xset +dpms") bumblebee.util.execute("xset s default") bumblebee.util.execute("notify-send \"Out of coffee\"") else: bumblebee.util.execute("xset -dpms") bumblebee.util.execute("xset s off") bumblebee.util.execute("notify-send \"Consuming caffeine\"") # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Fix weird bug when creating new exhibition
@extends('layouts.app') @section('sidemenu') @include('layouts.menu') @endsection @section('content') <div class="panel panel-default"> <div class="panel-heading"> Exhibitions </div> <div class="panel-body"> @foreach($exhibitions as $exhibition) <a href="/section/{{ $exhibition->id }}"> <div class="panel panel-default"> <div class="panel-body"> @foreach($exhibition->titles as $title) {{ $title->language }}:{{ $title->text }}<br/> @endforeach @if (sizeof($exhibition->titles)==0) <div > (untitled) </div> @endif </div> </div> </a> @endforeach </div> </div> <div class="panel panel-default"> <div class="panel-heading">Add new exhibition</div> <div class="panel-body"> <form action="{{ route('newSection') }}" method="POST"> <input type="submit" name="submit" value="Add new exhibition"/> <input type="hidden" name="_token" value="{{ csrf_token() }}"> </form> </div> </div> @endsection
@extends('layouts.app') @section('sidemenu') @include('layouts.menu') @endsection @section('content') <div class="panel panel-default"> <div class="panel-heading"> Exhibitions </div> <div class="panel-body"> @foreach($exhibitions as $exhibition) <a href="/section/{{ $exhibition->id }}"> <div class="panel panel-default"> <div class="panel-body"> @foreach($exhibition->titles as $title) {{ $title->language }}:{{ $title->text }}<br/> @endforeach @if (sizeof($exhibition->titles)==0) <div > (untitled) </div> @endif </div> </div> </a> @endforeach </div> </div> <div class="panel panel-default"> <div class="panel-heading">Add new exhibition</div> <div class="panel-body"> <form action="newSection" method="POST"> <input type="submit" name="submit" value="Add new exhibition"/> <input type="hidden" name="_token" value="{{ csrf_token() }}"> </form> </div> </div> @endsection
Add icon information for views
angular.module('Mccy.routes', [ 'ngRoute' ]) .config(function ($routeProvider) { $routeProvider .when('/view', { templateUrl: 'views/view-containers.html', controller: 'ViewContainersCtrl' }) .when('/new-server', { templateUrl: 'views/create-container.html', controller: 'NewContainerCtrl' }) .when('/upload-mod', { templateUrl: 'views/upload-mod.html', controller: 'UploadModCtrl' }) .when('/manage-mods', { templateUrl: 'views/manage-mods.html', controller: 'ManageModsCtrl' }) .otherwise('/view') }) .constant('MccyViews', [ { view: '/view', label: 'Current Containers' icon: 'icon fa fa-heartbeat' show: true }, { view: '/new-server', label: 'New Container' icon: 'icon fa fa-magic' show: true }, { view: '/upload-mod', label: 'Upload Mods' icon: 'icon fa fa-upload' show: true }, { view: '/manage-mods', label: 'Manage Mods' icon: 'icon fa fa-flask' show: true } ]) ;
angular.module('Mccy.routes', [ 'ngRoute' ]) .config(function ($routeProvider) { $routeProvider .when('/view', { templateUrl: 'views/view-containers.html', controller: 'ViewContainersCtrl' }) .when('/new-server', { templateUrl: 'views/create-container.html', controller: 'NewContainerCtrl' }) .when('/upload-mod', { templateUrl: 'views/upload-mod.html', controller: 'UploadModCtrl' }) .when('/manage-mods', { templateUrl: 'views/manage-mods.html', controller: 'ManageModsCtrl' }) .otherwise('/view') }) .constant('MccyViews', [ { view: '/view', label: 'Current Containers' }, { view: '/new-server', label: 'New Container' }, { view: '/upload-mod', label: 'Upload Mods' }, { view: '/manage-mods', label: 'Manage Mods' } ]) ;
Fix typo in debugging comment
// namespace var App = App || {}; App.WebSocketState = (function () { "use strict"; console.log("WebSocketState Compiling ..."); var fn = function (game) { console.log("WebSocketState.constructor Running..."); Phaser.State.call(this, game); }; fn.prototype = Object.create(Phaser.State.prototype); fn.prototype.constructor = fn; fn.prototype.init = function () { console.log("WebSocketState.init Running..."); }; fn.prototype.preload = function () { console.log("WebSocketState.preload Running..."); // load assets this.game.asset_manager.loadAssets(); }; fn.prototype.create = function () { console.log("WebSocketState.create Running..."); var game = this.game; // Connect to WebSocket server console.log("Connecting to WebSocket server..."); game.global.readyWS = false; game.global.eurecaClient = new Eureca.Client(); game.global.eurecaClient.exports = exports; // Defined in hooks.js game.global.eurecaClient.ready(function (proxy) { console.log("WebSocket client is ready!"); game.global.eurecaServer = proxy; game.global.readyWS = true; }); }; return fn; })();
// namespace var App = App || {}; App.WebSocketState = (function () { "use strict"; console.log("WebSocketState.create Compiling ..."); var fn = function (game) { Phaser.State.call(this, game); console.log("WebSocketState.constructor Running..."); }; fn.prototype = Object.create(Phaser.State.prototype); fn.prototype.constructor = fn; fn.prototype.init = function () { console.log("WebSocketState.init Running..."); }; fn.prototype.preload = function () { console.log("WebSocketState.preload Running..."); // load assets this.game.asset_manager.loadAssets(); }; fn.prototype.create = function () { console.log("WebSocketState.create Running..."); var game = this.game; // Connect to WebSocket server console.log("Connecting to WebSocket server..."); game.global.readyWS = false; game.global.eurecaClient = new Eureca.Client(); game.global.eurecaClient.exports = exports; // Defined in hooks.js game.global.eurecaClient.ready(function (proxy) { console.log("WebSocket client is ready!"); game.global.eurecaServer = proxy; game.global.readyWS = true; }); }; return fn; })();
Make it possible to pass in null as the logger, if you don't want to login exceptions when closing a resource. Not really advisable, but useful when testing and should only really be used for that.
package org.carlspring.strongbox.resource; import javax.naming.Context; import javax.naming.NamingEnumeration; import java.io.Closeable; import java.io.IOException; import org.slf4j.Logger; /** * A utility class for safely closing resources and logging eventual errors. * The purpose of this class is to avoid boiler-plate code. * * @author mtodorov */ public class ResourceCloser { public static void close(Closeable resource, Logger logger) { if (resource != null) { try { resource.close(); } catch (IOException e) { if (logger != null) { logger.error(e.getMessage(), e); } } } } public static void close(AutoCloseable resource, Logger logger) { if (resource != null) { try { resource.close(); } catch (Exception e) { if (logger != null) { logger.error(e.getMessage(), e); } } } } public static void close(Context resource, Logger logger) { if (resource != null) { try { resource.close(); } catch (Exception e) { if (logger != null) { logger.error(e.getMessage(), e); } } } } public static void close(NamingEnumeration resource, Logger logger) { if (resource != null) { try { resource.close(); } catch (Exception e) { if (logger != null) { logger.error(e.getMessage(), e); } } } } }
package org.carlspring.strongbox.resource; import javax.naming.Context; import javax.naming.NamingEnumeration; import java.io.Closeable; import java.io.IOException; import org.slf4j.Logger; /** * A utility class for safely closing resources and logging eventual errors. * The purpose of this class is to avoid boiler-plate code. * * @author mtodorov */ public class ResourceCloser { public static void close(Closeable resource, Logger logger) { if (resource != null) { try { resource.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } public static void close(AutoCloseable resource, Logger logger) { if (resource != null) { try { resource.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public static void close(Context resource, Logger logger) { if (resource != null) { try { resource.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public static void close(NamingEnumeration resource, Logger logger) { if (resource != null) { try { resource.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } }
Make the last function also a generator, so that the explanation flows better
#!/usr/bin/env python import sys, operator, string def characters(filename): for line in open(filename): for c in line: yield c def all_words(filename): start_char = True for c in characters(filename): if start_char == True: word = "" if c.isalnum(): # We found the start of a word word = c.lower() start_char = False else: pass else: if c.isalnum(): word += c.lower() else: # We found end of word, emit it start_char = True yield word def non_stop_words(filename): stopwords = set(open('../stop_words.txt').read().split(',') + list(string.ascii_lowercase)) for w in all_words(filename): if not w in stopwords: yield w def count_and_sort(filename): freqs, i = {}, 1 for w in non_stop_words(filename): freqs[w] = 1 if w not in freqs else freqs[w]+1 if i % 5000 == 0: yield sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True) i = i+1 yield sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True) # # The main function # for word_freqs in count_and_sort(sys.argv[1]): print "-----------------------------" for (w, c) in word_freqs[0:25]: print w, ' - ', c
#!/usr/bin/env python import sys, operator, string def characters(filename): for line in open(filename): for c in line: yield c def all_words(filename): start_char = True for c in characters(filename): if start_char == True: word = "" if c.isalnum(): # We found the start of a word word = c.lower() start_char = False else: pass else: if c.isalnum(): word += c.lower() else: # We found end of word, emit it start_char = True yield word def non_stop_words(filename): stopwords = set(open('../stop_words.txt').read().split(',') + list(string.ascii_lowercase)) for w in all_words(filename): if not w in stopwords: yield w def count_and_sort(filename): freqs = {} for w in non_stop_words(filename): freqs[w] = 1 if w not in freqs else freqs[w]+1 return sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True) # # The main function # word_freqs = count_and_sort(sys.argv[1]) for (w, c) in word_freqs[0:25]: print w, ' - ', c
Add error handling to Read book page
// @flow /** * Part of GDL gdl-frontend. * Copyright (C) 2017 GDL * * See LICENSE */ import * as React from 'react'; import { fetchBook } from '../../fetch'; import type { BookDetails, Context } from '../../types'; import defaultPage from '../../hocs/defaultPage'; import errorPage from '../../hocs/errorPage'; import Head from '../../components/Head'; import Reader from '../../components/Reader'; type Props = { book: BookDetails, url: { query: { chapter?: string } } }; class Read extends React.Component<Props> { static async getInitialProps({ query }: Context) { const bookRes = await fetchBook(query.id, query.lang); if (!bookRes.isOk) { return { statusCode: bookRes.statusCode }; } const book = bookRes.data; // Make sure the chapters are sorted by the chapter numbers // Cause further down we rely on the array indexes book.chapters.sort((a, b) => a.seqNo - b.seqNo); return { book }; } render() { let { book, url } = this.props; return ( <React.Fragment> <Head title={book.title} isBookType description={book.description} imageUrl={book.coverPhoto ? book.coverPhoto.large : null} /> <Reader book={book} initialChapter={url.query.chapter} /> </React.Fragment> ); } } export default defaultPage(errorPage(Read));
// @flow /** * Part of GDL gdl-frontend. * Copyright (C) 2017 GDL * * See LICENSE */ import * as React from 'react'; import { fetchBook } from '../../fetch'; import type { BookDetails, Context } from '../../types'; import defaultPage from '../../hocs/defaultPage'; import Head from '../../components/Head'; import Reader from '../../components/Reader'; type Props = { book: BookDetails, url: { query: { chapter?: string } } }; class Read extends React.Component<Props> { static async getInitialProps({ query }: Context) { const bookRes = await fetchBook(query.id, query.lang); if (!bookRes.isOk) { return { statusCode: bookRes.statusCode }; } const book = bookRes.data; // Make sure the chapters are sorted by the chapter numbers // Cause further down we rely on the array indexes book.chapters.sort((a, b) => a.seqNo - b.seqNo); return { book }; } render() { let { book, url } = this.props; return ( <React.Fragment> <Head title={book.title} isBookType description={book.description} imageUrl={book.coverPhoto ? book.coverPhoto.large : null} /> <Reader book={book} initialChapter={url.query.chapter} /> </React.Fragment> ); } } export default defaultPage(Read);
Add default values to posts table migration Add default values to all new columns in the posts table restructuring migration so that these migrations can be run on an sqlite database. Fixes #22
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class RestructurePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->string('subtitle')->after('title')->default(''); $table->renameColumn('content', 'content_raw'); $table->text('content_html')->after('content')->default(''); $table->string('page_image')->after('content_html')->default(''); $table->string('meta_description')->after('page_image')->default(''); $table->boolean('is_draft')->after('meta_description')->default(false); $table->string('layout')->after('is_draft')->default('frontend.blog.post'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function (Blueprint $table) { $table->dropColumn('layout'); $table->dropColumn('is_draft'); $table->dropColumn('meta_description'); $table->dropColumn('page_image'); $table->dropColumn('content_html'); $table->renameColumn('content_raw', 'content'); $table->dropColumn('subtitle'); }); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class RestructurePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->string('subtitle')->after('title'); $table->renameColumn('content', 'content_raw'); $table->text('content_html')->after('content'); $table->string('page_image')->after('content_html'); $table->string('meta_description')->after('page_image'); $table->boolean('is_draft')->after('meta_description'); $table->string('layout')->after('is_draft')->default('frontend.blog.post'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function (Blueprint $table) { $table->dropColumn('layout'); $table->dropColumn('is_draft'); $table->dropColumn('meta_description'); $table->dropColumn('page_image'); $table->dropColumn('content_html'); $table->renameColumn('content_raw', 'content'); $table->dropColumn('subtitle'); }); } }
Improve status display for reports.
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} def fixup_report(report): if report['status'] == 'paid': report['status'] = 'paid, check #%s' % report.pop('memo') elif report['status'] == 'rejected': report['status'] = 'rejected, #%s' % report.pop('memo') return report @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': [fixup_report(report) for report in list_reports(employee_id)], } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': fixup_report(get_report_info(employee_id, report_id))} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, )
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_name='home', renderer='templates/home.pt') def home_page(request): return {} @view_config(route_name='employees', renderer='templates/employees.pt') def show_employees(request): return {'employees': list_employees()} @view_config(route_name='employee', renderer='templates/employee.pt') def show_employee(request): employee_id = request.matchdict['employee_id'] return {'employee_id': employee_id, 'reports': list_reports(employee_id), } @view_config(route_name='report', renderer='templates/report.pt') def show_report(request): employee_id = request.matchdict['employee_id'] report_id = request.matchdict['report_id'] return {'report': get_report_info(employee_id, report_id)} def includeme(config): config.add_request_method(callable=get_main_template, name='main_template', property=True, reify=True, )
:bug: Make sure to filter any classification associated with affiliations when the curator is NOT curating as part of an affiliation
'use strict'; import { userMatch, affiliationMatch } from '../components/globals'; /** * Traverse the GDM object tree to find the embedded provisionalClassification object * @param {object} gdm - GDM object prop * @param {object} affiliation - Affiliation object prop * @param {object} session - User session object prop */ export function GetProvisionalClassification(gdm, affiliation, session) { let result = { provisionalExist: false, provisional: null }; if (gdm.provisionalClassifications && gdm.provisionalClassifications.length > 0) { gdm.provisionalClassifications.forEach(item => { if (affiliation && Object.keys(affiliation).length) { if (affiliationMatch(item, affiliation)) { return result = { provisionalExist: true, provisional: item }; } return result; } else if (userMatch(item.submitted_by, session) && !item.affiliation) { return result = { provisionalExist: true, provisional: item }; } return result; }); } return result; }
'use strict'; import { userMatch, affiliationMatch } from '../components/globals'; /** * Traverse the GDM object tree to find the embedded provisionalClassification object * @param {object} gdm - GDM object prop * @param {object} affiliation - Affiliation object prop * @param {object} session - User session object prop */ export function GetProvisionalClassification(gdm, affiliation, session) { let result = { provisionalExist: false, provisional: null }; if (gdm.provisionalClassifications && gdm.provisionalClassifications.length > 0) { gdm.provisionalClassifications.forEach(item => { if (affiliation && Object.keys(affiliation).length) { if (affiliationMatch(item, affiliation)) { return result = { provisionalExist: true, provisional: item }; } return result; } else if (userMatch(item.submitted_by, session)) { return result = { provisionalExist: true, provisional: item }; } return result; }); } return result; }
Fix missing request body in API client
import fetch from 'unfetch' const apiBase = 'https://api.hackclub.com/' const methods = ['get', 'put', 'post', 'patch'] const generateMethod = method => (path, options) => { // authToken is shorthand for Authorization: Bearer `authtoken` let filteredOptions = {} for (let [key, value] of Object.entries(options)) { switch (key) { case 'authToken': filteredOptions.headers = filteredOptions.headers || {} filteredOptions.headers['Authorization'] = `Bearer ${value}` break case 'data': filteredOptions.body = JSON.stringify(value) filteredOptions.headers = filteredOptions.headers || {} filteredOptions.headers['Content-Type'] = 'application/json' break default: filteredOptions[key] = value break } } return fetch(apiBase + path, { method: method, ...filteredOptions }) .then(res => { if (res.ok) { const contentType = res.headers.get('content-type') if (contentType && contentType.indexOf('application/json') !== -1) { return res.json() } else { return res.text() } } else { throw res } }) .catch(e => { console.error(e) throw e }) } let api = {} methods.forEach(method => { api[method] = generateMethod(method) }) export default api
import fetch from 'unfetch' const apiBase = 'https://api.hackclub.com/' const methods = ['get', 'put', 'post', 'patch'] const generateMethod = method => (path, options) => { // authToken is shorthand for Authorization: Bearer `authtoken` let filteredOptions = {} for (let [key, value] of Object.entries(options)) { switch (key) { case 'authToken': filteredOptions = { ...filteredOptions, ...{ headers: { Authorization: `Bearer ${value}` } } } break case 'data': filteredOptions = { ...filteredOptions, ...{ body: JSON.stringify(value), headers: { 'Content-Type': 'application/json' } } } break default: filteredOptions[key] = value break } } return fetch(apiBase + path, { method: method, ...filteredOptions }) .then(res => { if (res.ok) { const contentType = res.headers.get('content-type') if (contentType && contentType.indexOf('application/json') !== -1) { return res.json() } else { return res.text() } } else { throw res } }) .catch(e => { console.error(e) throw e }) } let api = {} methods.forEach(method => { api[method] = generateMethod(method) }) export default api
docs: Fix incorrect text for MQTT publish Fixes #262
const apiPutMqttMessage = { schema: { summary: 'Publish a message to a MQTT topic.', description: '', body: { type: 'object', properties: { topic: { type: 'string', description: 'Topic to which message should be published.', example: 'qliksense/new_data_notification/sales', }, message: { type: 'string', description: 'The message is a generic text string and can thus contain anything that can be represented in a string, including JSON, key-value pairs, plain text etc.', example: 'dt=20201028', }, }, required: ['topic', 'message'], }, response: { 201: { description: 'MQTT message successfully published.', type: 'object', }, 400: { description: 'Required parameter missing.', type: 'object', properties: { statusCode: { type: 'number' }, code: { type: 'string' }, error: { type: 'string' }, message: { type: 'string' }, time: { type: 'string' }, }, }, 500: { description: 'Internal error.', type: 'object', properties: { statusCode: { type: 'number' }, code: { type: 'string' }, error: { type: 'string' }, message: { type: 'string' }, time: { type: 'string' }, }, }, }, }, }; module.exports = { apiPutMqttMessage, };
const apiPutMqttMessage = { schema: { summary: 'Retrieve a list of all keys present in the specified namespace.', description: '', body: { type: 'object', properties: { topic: { type: 'string', description: 'Name of namespace whose keys should be returned.', example: 'qliksense/new_data_notification/sales', }, message: { type: 'string', description: 'The message is a generic text string and can thus contain anything that can be represented in a string, including JSON, key-value pairs, plain text etc.', example: 'dt=20201028', }, }, required: ['topic', 'message'], }, response: { 201: { description: 'MQTT message successfully published.', type: 'object', }, 400: { description: 'Required parameter missing.', type: 'object', properties: { statusCode: { type: 'number' }, code: { type: 'string' }, error: { type: 'string' }, message: { type: 'string' }, time: { type: 'string' }, }, }, 500: { description: 'Internal error.', type: 'object', properties: { statusCode: { type: 'number' }, code: { type: 'string' }, error: { type: 'string' }, message: { type: 'string' }, time: { type: 'string' }, }, }, }, }, }; module.exports = { apiPutMqttMessage, };
Remove sdbus++ template search workaround sdbus++ was fixed upstream to find its templates automatically. Change-Id: I29020b9d1ea4ae8baaca5fe869625a3d96cd6eaf Signed-off-by: Brad Bishop <[email protected]>
#!/usr/bin/env python import os import sys import yaml import subprocess if __name__ == '__main__': genfiles = { 'server-cpp': lambda x: '%s.cpp' % x, 'server-header': lambda x: os.path.join( os.path.join(*x.split('.')), 'server.hpp') } with open(os.path.join('example', 'interfaces.yaml'), 'r') as fd: interfaces = yaml.load(fd.read()) for i in interfaces: for process, f in genfiles.iteritems(): dest = f(i) parent = os.path.dirname(dest) if parent and not os.path.exists(parent): os.makedirs(parent) with open(dest, 'w') as fd: subprocess.call([ 'sdbus++', '-r', os.path.join('example', 'interfaces'), 'interface', process, i], stdout=fd) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
#!/usr/bin/env python import os import sys import yaml import subprocess class SDBUSPlus(object): def __init__(self, path): self.path = path def __call__(self, *a, **kw): args = [ os.path.join(self.path, 'sdbus++'), '-t', os.path.join(self.path, 'templates') ] subprocess.call(args + list(a), **kw) if __name__ == '__main__': sdbusplus = None for p in os.environ.get('PATH', "").split(os.pathsep): if os.path.exists(os.path.join(p, 'sdbus++')): sdbusplus = SDBUSPlus(p) break if sdbusplus is None: sys.stderr.write('Cannot find sdbus++\n') sys.exit(1) genfiles = { 'server-cpp': lambda x: '%s.cpp' % x, 'server-header': lambda x: os.path.join( os.path.join(*x.split('.')), 'server.hpp') } with open(os.path.join('example', 'interfaces.yaml'), 'r') as fd: interfaces = yaml.load(fd.read()) for i in interfaces: for process, f in genfiles.iteritems(): dest = f(i) parent = os.path.dirname(dest) if parent and not os.path.exists(parent): os.makedirs(parent) with open(dest, 'w') as fd: sdbusplus( '-r', os.path.join('example', 'interfaces'), 'interface', process, i, stdout=fd) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
Fix CI to ignore system install of asn1crypto
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) # In case any of the deps are installed system-wide sys.path.insert(0, deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: from .lint import run as run_lint else: run_lint = None if sys.version_info[0:2] != (3, 2): from .coverage import run as run_coverage from .coverage import coverage run_tests = None else: from .tests import run as run_tests run_coverage = None def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ _preload(requires_oscrypto, True) if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py %s)' % coverage.__version__) sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests(ci=True) sys.stdout.flush() return lint_result and tests_result
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: from .lint import run as run_lint else: run_lint = None if sys.version_info[0:2] != (3, 2): from .coverage import run as run_coverage from .coverage import coverage run_tests = None else: from .tests import run as run_tests run_coverage = None def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ _preload(requires_oscrypto, True) if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py %s)' % coverage.__version__) sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests(ci=True) sys.stdout.flush() return lint_result and tests_result
tools: Store the depth (d) on the stack and restore when backtracking
# Module: __init__ # Date: 8th November 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """Circuits Tools circuits.tools contains a standard set of tools for circuits. These tools are installed as executables with a prefix of "circuits." """ try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: stack.append((i, d, children)) children = list(x.components) i = 0 else: if stack: i, d, children = stack.pop() else: done = True return s.getvalue()
# Module: __init__ # Date: 8th November 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """Circuits Tools circuits.tools contains a standard set of tools for circuits. These tools are installed as executables with a prefix of "circuits." """ try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: stack.append((i, children)) children = list(x.components) i = 0 else: if stack: i, children = stack.pop() d -= 1 else: done = True return s.getvalue()
Move extension requirement logic into PHPUnit phpDoc annotation
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Db\Adapter\Driver\Pgsql; use Zend\Db\Adapter\Driver\Pgsql\Connection; use Zend\Db\Adapter\Exception as AdapterException; class ConnectionTest extends \PHPUnit_Framework_TestCase { /** * @var Connection */ protected $connection = null; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->connection = new Connection(); } /** * Test getResource method if it tries to connect to the database. * * @covers Zend\Db\Adapter\Driver\Pgsql\Connection::getResource * @requires extension pgsql */ public function testResource() { try { $resource = $this->connection->getResource(); // connected with empty string $this->assertTrue(is_resource($resource)); } catch (AdapterException\RuntimeException $exc) { // If it throws an exception it has failed to connect $this->setExpectedException('Zend\Db\Adapter\Exception\RuntimeException'); throw $exc; } } }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Db\Adapter\Driver\Pgsql; use Zend\Db\Adapter\Driver\Pgsql\Connection; use Zend\Db\Adapter\Exception as AdapterException; class ConnectionTest extends \PHPUnit_Framework_TestCase { /** * @var Connection */ protected $connection = null; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->connection = new Connection(); } /** * Test getResource method if it tries to connect to the database. * * @covers Zend\Db\Adapter\Driver\Pgsql\Connection::getResource */ public function testResource() { if (extension_loaded('pgsql')) { try { $resource = $this->connection->getResource(); // connected with empty string $this->assertTrue(is_resource($resource)); } catch (AdapterException\RuntimeException $exc) { // If it throws an exception it has failed to connect $this->setExpectedException('Zend\Db\Adapter\Exception\RuntimeException'); throw $exc; } } else { $this->markTestSkipped('pgsql extension not loaded'); } } }
Test for new twig function
<?php namespace Tests\Becklyn\AssetsBundle\Twig; use Becklyn\AssetsBundle\Html\AssetHtmlGenerator; use Becklyn\AssetsBundle\Loader\FileLoader; use Becklyn\AssetsBundle\Twig\AssetsTwigExtension; use Becklyn\AssetsBundle\Url\AssetUrl; use PHPUnit\Framework\TestCase; class AssetsTwigExtensionTest extends TestCase { /** * Assert that the exposed twig functions don't change */ public function testMethodNames () { $htmlReferences = $this->getMockBuilder(AssetHtmlGenerator::class) ->disableOriginalConstructor() ->getMock(); $assetUrl = $this->getMockBuilder(AssetUrl::class) ->disableOriginalConstructor() ->getMock(); $fileLoader = $this->getMockBuilder(FileLoader::class) ->disableOriginalConstructor() ->getMock(); $extension = new AssetsTwigExtension($htmlReferences, $assetUrl, $fileLoader); $functions = \array_map( function (\Twig_SimpleFunction $f) { return $f->getName(); }, $extension->getFunctions() ); self::assertContains("assets_css", $functions); self::assertContains("assets_js", $functions); self::assertContains("asset", $functions); self::assertContains("asset_inline", $functions); } }
<?php namespace Tests\Becklyn\AssetsBundle\Twig; use Becklyn\AssetsBundle\Html\AssetHtmlGenerator; use Becklyn\AssetsBundle\Loader\FileLoader; use Becklyn\AssetsBundle\Twig\AssetsTwigExtension; use Becklyn\AssetsBundle\Url\AssetUrl; use PHPUnit\Framework\TestCase; class AssetsTwigExtensionTest extends TestCase { /** * Assert that the exposed twig functions don't change */ public function testMethodNames () { $htmlReferences = $this->getMockBuilder(AssetHtmlGenerator::class) ->disableOriginalConstructor() ->getMock(); $assetUrl = $this->getMockBuilder(AssetUrl::class) ->disableOriginalConstructor() ->getMock(); $fileLoader = $this->getMockBuilder(FileLoader::class) ->disableOriginalConstructor() ->getMock(); $extension = new AssetsTwigExtension($htmlReferences, $assetUrl, $fileLoader); $functions = \array_map( function (\Twig_SimpleFunction $f) { return $f->getName(); }, $extension->getFunctions() ); self::assertContains("assets_css", $functions); self::assertContains("assets_js", $functions); self::assertContains("asset", $functions); } }
Replace usage of magic class constant with FQCN string
<?php namespace Liip\RMT\Tests\Functional; use Exception; use Liip\RMT\Context; use Liip\RMT\Prerequisite\TestsCheck; class TestsCheckTest extends \PHPUnit_Framework_TestCase { protected function setUp() { $informationCollector = $this->createMock('Liip\RMT\Information\InformationCollector'); $informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false); $output = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); $output->method('write'); $context = Context::getInstance(); $context->setService('information-collector', $informationCollector); $context->setService('output', $output); } /** @test */ public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s() { $check = new TestsCheck(['command' => 'echo OK']); $check->execute(); } /** @test */ public function succeeds_when_command_finished_within_configured_timeout() { $check = new TestsCheck(['command' => 'echo OK', 'timeout' => 0.100]); $check->execute(); } /** @test */ public function fails_when_the_command_exceeds_the_timeout() { $this->setExpectedException('Exception', 'exceeded the timeout'); $check = new TestsCheck(['command' => 'sleep 1', 'timeout' => 0.100]); $check->execute(); } }
<?php namespace Liip\RMT\Tests\Functional; use Exception; use Liip\RMT\Context; use Liip\RMT\Prerequisite\TestsCheck; class TestsCheckTest extends \PHPUnit_Framework_TestCase { protected function setUp() { $informationCollector = $this->createMock('Liip\RMT\Information\InformationCollector'); $informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false); $output = $this->createMock('Symfony\Component\Console\Output\OutputInterface'); $output->method('write'); $context = Context::getInstance(); $context->setService('information-collector', $informationCollector); $context->setService('output', $output); } /** @test */ public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s() { $check = new TestsCheck(['command' => 'echo OK']); $check->execute(); } /** @test */ public function succeeds_when_command_finished_within_configured_timeout() { $check = new TestsCheck(['command' => 'echo OK', 'timeout' => 0.100]); $check->execute(); } /** @test */ public function fails_when_the_command_exceeds_the_timeout() { $this->setExpectedException(Exception::class, 'exceeded the timeout'); $check = new TestsCheck(['command' => 'sleep 1', 'timeout' => 0.100]); $check->execute(); } }
Add MIDDLEWARE_CLASSES to settings, remove warnings
import sys try: from django.conf import settings settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, ROOT_URLCONF="holonet.urls", INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "holonet_django", ], MIDDLEWARE_CLASSES=[], SITE_ID=1, NOSE_ARGS=['-s'], ) try: import django setup = django.setup except AttributeError: pass else: setup() from django_nose import NoseTestSuiteRunner except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements-test.txt") def run_tests(*test_args): if not test_args: test_args = ['tests'] # Run tests test_runner = NoseTestSuiteRunner(verbosity=1) failures = test_runner.run_tests(test_args) if failures: sys.exit(failures) if __name__ == '__main__': run_tests(*sys.argv[1:])
import sys try: from django.conf import settings settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", } }, ROOT_URLCONF="holonet.urls", INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "holonet_django", ], SITE_ID=1, NOSE_ARGS=['-s'], ) try: import django setup = django.setup except AttributeError: pass else: setup() from django_nose import NoseTestSuiteRunner except ImportError: import traceback traceback.print_exc() raise ImportError("To fix this error, run: pip install -r requirements-test.txt") def run_tests(*test_args): if not test_args: test_args = ['tests'] # Run tests test_runner = NoseTestSuiteRunner(verbosity=1) failures = test_runner.run_tests(test_args) if failures: sys.exit(failures) if __name__ == '__main__': run_tests(*sys.argv[1:])
Update function help interact with User
(function () { var User = require('../database/mongodb').Users, jwt = require('jwt-simple'), async = require('async'), crypto = require('crypto'); function _getUserInfo(userId, callback) { User.findById(userId, function (err, resp) { callback(err, resp); }) } function _updateUserInfo(userId, data, callback) { User.findByIdAndUpdate(userId, data, function (err, resp) { callback(err, resp); }) } function _registerUser(userInfo, callback) { User.create(userInfo, function (err, resp) { callback(err, resp); }) } function _login(username, password, callback) { async.waterfall([ function (callback) { User.findOne({username: username}, function (err, data) { if (err) return callback(err, null); if (data.length > 0) { callback(null, data); } else { callback('ERROR.USER', null); } }) }, function (user){ var userPass = crypto.createHash('md5').update(password).digest('hex'); if(user.password == userPass){ callback(null, user); }else { callback('ERROR.PASSWORD', null) } } ], function (err, resp) { callback(err, resp); }) } return { getUserInfo : _getUserInfo, updateUserInfo: _updateUserInfo, register: _registerUser, login: _login } })();
(function () { var User = require('../database/mongodb').Users, jwt = require('jwt-simple'), async = require('async'), crypto = require('crypto'); function _getUserInfo(userId, callback) { User.findById(userId, function (err, resp) { callback(err, resp); }) } function _updateUserInfo(userId, data, callback) { User.findByIdAndUpdate(userId, data, function (err, resp) { callback(err, resp); }) } function _registerUser(userInfo, callback) { User.create(userInfo, function (err, resp) { callback(err, resp); }) } function _login(username, password, callback) { async.waterfall([ function (callback) { User.findOne({username: username}, function (err, data) { if (err) return callback(err, null); if (data.length > 0) { callback(null, data); } else { callback('ERROR.USER', null); } }) }, function (user){ var userPass = crypto.createHash('md5').update(password).digest('hex'); if(user.password == userPass){ callback(null, user); }else { callback('ERROR.PASSWORD', null) } } ], function (err, resp) { callback(err, resp); }) } })();
Fix the bootstrap js path
const minimist = require("minimist"); const options = minimist(process.argv.slice(2)); const isProduction = options.env === 'production'; config = { console_options: options, isProduction: isProduction, src: { js: "./sec/js/**/*.js", vue: "./src/js/app.js", vue_watch: "./src/js/**/*.{js,vue}", scss: "./src/scss/**/*.scss", fonts: [ "./node_modules/font-awesome/fonts/**", ], lib: { js: [ "./node_modules/jquery/dist/jquery.min.js", "./node_modules/bootstrap/dist/js/bootstrap.min.js", ] }, }, dist: { js: "./assets/js", css: "./assets/css", fonts: "./assets/fonts", vue: "app.js", }, map: "./.map", lib: { js: "lib.js", }, options: { eslint: { configFile: ".eslintrc.yml", }, }, plugins : require("gulp-load-plugins")(), }; module.exports = config;
const minimist = require("minimist"); const options = minimist(process.argv.slice(2)); const isProduction = options.env === 'production'; config = { console_options: options, isProduction: isProduction, src: { js: "./sec/js/**/*.js", vue: "./src/js/app.js", vue_watch: "./src/js/**/*.{js,vue}", scss: "./src/scss/**/*.scss", fonts: [ "./node_modules/font-awesome/fonts/**", ], lib: { js: [ "./node_modules/jquery/dist/jquery.min.js", "./node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js", ] }, }, dist: { js: "./assets/js", css: "./assets/css", fonts: "./assets/fonts", vue: "app.js", }, map: "./.map", lib: { js: "lib.js", }, options: { eslint: { configFile: ".eslintrc.yml", }, }, plugins : require("gulp-load-plugins")(), }; module.exports = config;
Add the heyu-notifier command line script.
#!/usr/bin/env python from setuptools import setup def readreq(filename): result = [] with open(filename) as f: for req in f: req = req.partition('#')[0].strip() if not req: continue result.append(req) return result def readfile(filename): with open(filename) as f: return f.read() setup( name='heyu', version='0.1.0', author='Kevin L. Mitchell', author_email='[email protected]', url='http://github.com/klmitch/heyu', description='Self-Notification Utility', long_description=readfile('README.rst'), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: Apache Software License', 'Environment :: No Input/Output (Daemon)', 'Operating System :: OS Independent', 'Programming Language :: Python', ], packages=['heyu'], requires=readreq('requirements.txt'), tests_require=readreq('test-requirements.txt'), entry_points={ 'console_scripts': [ 'heyu-notify = heyu.submitter:send_notification.console', 'heyu-hub = heyu.hub:start_hub.console', 'heyu-notifier = heyu.notifier:notification_server.console', ], }, )
#!/usr/bin/env python from setuptools import setup def readreq(filename): result = [] with open(filename) as f: for req in f: req = req.partition('#')[0].strip() if not req: continue result.append(req) return result def readfile(filename): with open(filename) as f: return f.read() setup( name='heyu', version='0.1.0', author='Kevin L. Mitchell', author_email='[email protected]', url='http://github.com/klmitch/heyu', description='Self-Notification Utility', long_description=readfile('README.rst'), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: Apache Software License', 'Environment :: No Input/Output (Daemon)', 'Operating System :: OS Independent', 'Programming Language :: Python', ], packages=['heyu'], requires=readreq('requirements.txt'), tests_require=readreq('test-requirements.txt'), entry_points={ 'console_scripts': [ 'heyu-notify = heyu.submitter:send_notification.console', 'heyu-hub = heyu.hub:start_hub.console', ], }, )
[minor] Correct link in code comment
var util = require('util'); var log = require('minilog')('http'); module.exports = function requestLogger(req, res, next) { // // Pretty much copypasta from // https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js#L135-L158 // // Monkey punching res.end. It's dirty but, maan I wanna log my status // codes! // var end = res.end; res.end = function (chunk, encoding) { res.end = end; res.end(chunk, encoding); var remoteAddr = (function () { if (req.ip) return req.ip; var sock = req.socket; if (sock.socket) return sock.socket.remoteAddress; return sock.remoteAddress; })(), date = new Date().toUTCString(), // DEFINITELY not CLF-compatible. method = req.method, url = req.originalUrl || req.url, httpVersion = req.httpVersionMajor + '.' + req.httpVersionMinor, status = res.statusCode; // Similar to, but not anywhere near compatible with, CLF. So don't try // parsing it as CLF. // log.info(util.format( '%s - - [%s] "%s %s HTTP/%s" %s', remoteAddr, date, method, url, httpVersion, status )); }; next(); };
var util = require('util'); var log = require('minilog')('http'); module.exports = function requestLogger(req, res, next) { // // Pretty much copypasta from // https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js#L168-L174 // // Monkey punching res.end. It's dirty but, maan I wanna log my status // codes! // var end = res.end; res.end = function (chunk, encoding) { res.end = end; res.end(chunk, encoding); var remoteAddr = (function () { if (req.ip) return req.ip; var sock = req.socket; if (sock.socket) return sock.socket.remoteAddress; return sock.remoteAddress; })(), date = new Date().toUTCString(), // DEFINITELY not CLF-compatible. method = req.method, url = req.originalUrl || req.url, httpVersion = req.httpVersionMajor + '.' + req.httpVersionMinor, status = res.statusCode; // Similar to, but not anywhere near compatible with, CLF. So don't try // parsing it as CLF. // log.info(util.format( '%s - - [%s] "%s %s HTTP/%s" %s', remoteAddr, date, method, url, httpVersion, status )); }; next(); };
Fix Salmon Run tweet mystery weapon detection
const TwitterPostBase = require('./TwitterPostBase'); const { captureSalmonRunScreenshot } = require('../screenshots'); const { readData } = require('../utilities'); class SalmonRunTweet extends TwitterPostBase { getKey() { return 'salmonrun'; } getName() { return 'Salmon Run'; } getSalmonRunSchedules() { let results = {}; let coopSchedules = readData('coop-schedules.json'); for (let schedule of coopSchedules.schedules) results[schedule.start_time] = schedule; for (let schedule of coopSchedules.details) results[schedule.start_time] = schedule; return Object.values(results); } getData() { return this.getSalmonRunSchedules().find(s => s.start_time == this.getDataTime()); } getTestData() { return this.getSalmonRunSchedules()[0]; } getImage(data) { return captureSalmonRunScreenshot(data.start_time); } getText(data) { let hasMysteryWeapon = data.weapons.some(w => w === null || w.coop_special_weapon); if (hasMysteryWeapon) return `Salmon Run is now open on ${data.stage.name} with MYSTERY WEAPONS! #salmonrun #splatoon2`; return `Salmon Run is now open on ${data.stage.name}! #salmonrun #splatoon2`; } } module.exports = SalmonRunTweet;
const TwitterPostBase = require('./TwitterPostBase'); const { captureSalmonRunScreenshot } = require('../screenshots'); const { readData } = require('../utilities'); class SalmonRunTweet extends TwitterPostBase { getKey() { return 'salmonrun'; } getName() { return 'Salmon Run'; } getSalmonRunSchedules() { let results = {}; let coopSchedules = readData('coop-schedules.json'); for (let schedule of coopSchedules.schedules) results[schedule.start_time] = schedule; for (let schedule of coopSchedules.details) results[schedule.start_time] = schedule; return Object.values(results); } getData() { return this.getSalmonRunSchedules().find(s => s.start_time == this.getDataTime()); } getTestData() { return this.getSalmonRunSchedules()[0]; } getImage(data) { return captureSalmonRunScreenshot(data.start_time); } getText(data) { let hasMysteryWeapon = data.weapons.some(w => w === null); if (hasMysteryWeapon) return `Salmon Run is now open on ${data.stage.name} with MYSTERY WEAPONS! #salmonrun #splatoon2`; return `Salmon Run is now open on ${data.stage.name}! #salmonrun #splatoon2`; } } module.exports = SalmonRunTweet;
Fix moveForward() not checking environment range when the bot falls.
package de.craften.plugins.educraft.luaapi.functions; import de.craften.plugins.educraft.luaapi.EduCraftApiFunction; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; /** * Lua API function to move one block forward. */ public class MoveForwardFunction extends EduCraftApiFunction { @Override public Varargs execute(Varargs varargs) { Block targetBlock = getTargetBlock(); Location targetLocation = targetBlock.getLocation(); if (!targetBlock.getType().isSolid() && !targetBlock.getRelative(BlockFace.UP).getType().isSolid() && !getApi().getEnvironment().isAliveEntityAt(targetLocation) && getApi().getEnvironment().contains(targetLocation)) { getApi().moveTo(targetLocation, false); //fall on solid block (without falling out of the environment) while (!targetBlock.getRelative(BlockFace.DOWN).getType().isSolid() && getApi().getEnvironment().contains(targetBlock.getLocation().subtract(0, -1, 0))) { targetBlock = targetBlock.getRelative(BlockFace.DOWN); } getApi().moveTo(targetBlock.getLocation(), false); } return LuaValue.NIL; } /** * Gets the block this function will move the entity to. * * @return target block */ protected Block getTargetBlock() { return getApi().getBlockAhead(); } }
package de.craften.plugins.educraft.luaapi.functions; import de.craften.plugins.educraft.luaapi.EduCraftApiFunction; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; /** * Lua API function to move one block forward. */ public class MoveForwardFunction extends EduCraftApiFunction { @Override public Varargs execute(Varargs varargs) { Block targetBlock = getTargetBlock(); Location targetLocation = targetBlock.getLocation(); if (!targetBlock.getType().isSolid() && !targetBlock.getRelative(BlockFace.UP).getType().isSolid() && !getApi().getEnvironment().isAliveEntityAt(targetLocation) && getApi().getEnvironment().contains(targetLocation)) { getApi().moveTo(targetLocation, false); while (!targetBlock.getRelative(BlockFace.DOWN).getType().isSolid() && targetBlock.getY() > 0) { targetBlock = targetBlock.getRelative(BlockFace.DOWN); } getApi().moveTo(targetBlock.getLocation(), false); } return LuaValue.NIL; } /** * Gets the block this function will move the entity to. * * @return target block */ protected Block getTargetBlock() { return getApi().getBlockAhead(); } }
Allow entry of generic protocols too without forcing a search E.g. if you try to open ftp:.... we should actually try to open that instead of searching (in future we will try to search for apps that actually support ftp, followed by falling back to the unsupported protocol error page).
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils; import android.net.Uri; import android.text.TextUtils; public class UrlUtils { public static String normalize(String input) { Uri uri = Uri.parse(input); if (TextUtils.isEmpty(uri.getScheme())) { uri = Uri.parse("http://" + input); } return uri.toString(); } public static boolean isHttps(String url) { // TODO: This should actually check the certificate! return url.startsWith("https:"); } /** * Is the given string a URL or should we perform a search? * * TODO: This is a super simple and probably stupid implementation. */ public static boolean isUrl(String url) { if (url.contains(" ")) { return false; } return url.contains(".") || url.contains(":"); } public static boolean isSearchQuery(String text) { return text.contains(" "); } public static String createSearchUrl(String rawUrl) { return Uri.parse("https://duckduckgo.com/").buildUpon() .appendQueryParameter("q", rawUrl) .build() .toString(); } }
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils; import android.net.Uri; import android.text.TextUtils; public class UrlUtils { public static String normalize(String input) { Uri uri = Uri.parse(input); if (TextUtils.isEmpty(uri.getScheme())) { uri = Uri.parse("http://" + input); } return uri.toString(); } public static boolean isHttps(String url) { // TODO: This should actually check the certificate! return url.startsWith("https:"); } /** * Is the given string a URL or should we perform a search? * * TODO: This is a super simple and probably stupid implementation. */ public static boolean isUrl(String url) { if (url.contains(" ")) { return false; } return url.contains("."); } public static boolean isSearchQuery(String text) { return text.contains(" "); } public static String createSearchUrl(String rawUrl) { return Uri.parse("https://duckduckgo.com/").buildUpon() .appendQueryParameter("q", rawUrl) .build() .toString(); } }
chore(Desktop): Fix resolution of native Node modules See https://github.com/electron-userland/electron-forge/pull/2449
const plugins = require('./webpack.plugins') const webpack = require('webpack') module.exports = { /** * This is the main entry point for your application, it's the first file * that runs in the main process. */ entry: './src/index.ts', plugins: [ ...plugins, new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify( process.env.NODE_ENV ?? 'development' ), 'process.env.SENTRY_DSN': JSON.stringify(process.env.SENTRY_DSN), 'process.type': '"browser"', }), ], module: { rules: [ // Add support for native node modules { test: /native_modules\/.+\.node$/, use: 'node-loader', }, { test: /\.(m?js|node)$/, parser: { amd: false }, use: { loader: '@marshallofsound/webpack-asset-relocator-loader', options: { outputAssetBase: 'native_modules', debugLog: true, }, }, }, { test: /\.tsx?$/, exclude: /(node_modules|\.webpack)/, use: { loader: 'ts-loader', options: { configFile: 'tsconfig.main.json', transpileOnly: true, }, }, }, ], }, resolve: { extensions: ['.js', '.mjs', '.ts', '.json'], }, }
const plugins = require('./webpack.plugins') const webpack = require('webpack') module.exports = { /** * This is the main entry point for your application, it's the first file * that runs in the main process. */ entry: './src/index.ts', plugins: [ ...plugins, new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify( process.env.NODE_ENV ?? 'development' ), 'process.env.SENTRY_DSN': JSON.stringify(process.env.SENTRY_DSN), 'process.type': '"browser"', }), ], module: { rules: [ // Add support for native node modules // TODO: Investigate. Seems to cause issues, and things seem to work without this loader // { // test: /\.node$/, // use: 'node-loader', // }, { test: /\.(m?js|node)$/, parser: { amd: false }, use: { loader: '@marshallofsound/webpack-asset-relocator-loader', options: { outputAssetBase: 'native_modules', debugLog: true, }, }, }, { test: /\.tsx?$/, exclude: /(node_modules|\.webpack)/, use: { loader: 'ts-loader', options: { configFile: 'tsconfig.main.json', transpileOnly: true, }, }, }, ], }, resolve: { extensions: ['.js', '.mjs', '.ts', '.json'], }, }
Include locale in package hash
# -*- coding: utf-8 -*- import os import waptpackage from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey def download(remote, path, pkg): """Downloads package""" if not pkg.package: return False res = remote.download_packages(pkg, path) if res['errors']: return False pkg_path = res['downloaded'] and res['downloaded'][0] or res['skipped'][0] if not pkg_path: return False return pkg_path def check_signature(pkg): """Check package signature if /etc/ssl/certs exists""" if not os.path.exists('/etc/ssl/certs'): return True if not waptpackage.PackageEntry(waptfile=pkg.localpath).check_control_signature(SSLCABundle('/etc/ssl/certs')): return False return True def overwrite_signature(pkg): """Overwrite imported package signature""" cert_file = os.environ.get('WAPT_CERT') key_file = os.environ.get('WAPT_KEY') password = os.environ.get('WAPT_PASSWD') if not (cert_file and key_file and password): return False crt = SSLCertificate(cert_file) key = SSLPrivateKey(key_file, password=password) return pkg.sign_package(crt, key) def hash(pkg): """Creates a hash based on package properties""" return "%s:%s:%s" % (pkg.package, pkg.architecture, pkg.locale)
# -*- coding: utf-8 -*- import os import waptpackage from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey def download(remote, path, pkg): """Downloads package""" if not pkg.package: return False res = remote.download_packages(pkg, path) if res['errors']: return False pkg_path = res['downloaded'] and res['downloaded'][0] or res['skipped'][0] if not pkg_path: return False return pkg_path def check_signature(pkg): """Check package signature if /etc/ssl/certs exists""" if not os.path.exists('/etc/ssl/certs'): return True if not waptpackage.PackageEntry(waptfile=pkg.localpath).check_control_signature(SSLCABundle('/etc/ssl/certs')): return False return True def overwrite_signature(pkg): """Overwrite imported package signature""" cert_file = os.environ.get('WAPT_CERT') key_file = os.environ.get('WAPT_KEY') password = os.environ.get('WAPT_PASSWD') if not (cert_file and key_file and password): return False crt = SSLCertificate(cert_file) key = SSLPrivateKey(key_file, password=password) return pkg.sign_package(crt, key) def hash(pkg): """Creates a hash based on package properties""" return "%s:%s" % (pkg.package, pkg.architecture)
Convert all the ids to strings
# -*- coding: utf-8 -*- """A Flask app to visualize the infection algorithm.""" from flask import Flask, request, abort, jsonify from werkzeug.exceptions import BadRequest from infection import User, total_infection, limited_infection app = Flask(__name__) def load_user_graph(): """Get the JSON-encoded user graph from the request body.""" json_users = request.get_json() if json_users is None: raise BadRequest('You need to supply a JSON user graph.') try: users = dict((str(id), User(str(id))) for id in json_users) for id in json_users: for adjacent_id in json_users[id]: users[str(id)].connect(users[str(adjacent_id)]) except KeyError as e: raise BadRequest('Unknown connection in graph: {0}.'.format(e.args[0])) except TypeError: raise BadRequest('Users must be a dictionary of lists.') return users @app.route('/infect', methods=['POST']) def infect(): """Run the specified infection algorithm on a given user graph.""" users = load_user_graph() if request.args.get('type') == 'total': try: user = users[request.args['user']] except KeyError: raise BadRequest('Expected a valid user in param user.') infected = total_infection(user) return jsonify({'users': [user.id for user in infected]}) elif request.args.get('type') == 'limited': return jsonify({'users': []}) raise BadRequest('Expected total or limited from query param type.')
# -*- coding: utf-8 -*- """A Flask app to visualize the infection algorithm.""" from flask import Flask, request, abort, jsonify from werkzeug.exceptions import BadRequest from infection import User, total_infection, limited_infection app = Flask(__name__) def load_user_graph(): """Get the JSON-encoded user graph from the request body.""" json_users = request.get_json() if json_users is None: raise BadRequest('You need to supply a JSON user graph.') try: users = dict((id, User(id)) for id in json_users) for id in json_users: for adjacent_id in json_users[id]: users[id].connect(users[adjacent_id]) except KeyError as e: raise BadRequest('Unknown connection in graph: {0}.'.format(e.args[0])) except TypeError: raise BadRequest('Users must be a dictionary of lists.') return users @app.route('/infect', methods=['POST']) def infect(): """Run the specified infection algorithm on a given user graph.""" users = load_user_graph() if request.args.get('type') == 'total': try: user = users[request.args['user']] except KeyError: raise BadRequest('Expected a valid user in param user.') infected = total_infection(user) return jsonify({'users': [user.id for user in infected]}) elif request.args.get('type') == 'limited': return jsonify({'users': []}) raise BadRequest('Expected total or limited from query param type.')
Update translate plugin to new message format
""" Yandex Translation API """ import logging from urllib.parse import quote from telegram import Bot, Update from telegram.ext import Updater from requests import post import constants # pylint: disable=E0401 import settings import octeon LOGGER = logging.getLogger("YTranslate") YAURL = "https://translate.yandex.net/api/v1.5/tr.json/translate?" YAURL += "key=%s" % settings.YANDEX_TRANSLATION_TOKEN def preload(updater: Updater, level): """ This loads whenever plugin starts Even if you dont need it, you SHOULD put at least return None, otherwise your plugin wont load """ return def translate(bot: Bot, update: Update, user, args): # pylint: disable=W0613 """/tl""" if update.message.reply_to_message: if len(args) > 0: lang = args[0].lower() else: lang = "en" yandex = post(YAURL, params={"text":update.message.reply_to_message.text, "lang":lang}).json() try: return octeon.message(yandex["lang"].upper() + "\n" + yandex["text"][0]) except KeyError: return octeon.message(yandex["error"], failed=True) COMMANDS = [ { "command":"/tl", "function":translate, "description":"Translates message to english. Example: [In Reply To Message] /tl", "inline_support":True } ]
""" Yandex Translation API """ import logging from urllib.parse import quote from telegram import Bot, Update from telegram.ext import Updater from requests import post import constants # pylint: disable=E0401 import settings LOGGER = logging.getLogger("YTranslate") YAURL = "https://translate.yandex.net/api/v1.5/tr.json/translate?" YAURL += "key=%s" % settings.YANDEX_TRANSLATION_TOKEN def preload(updater: Updater, level): """ This loads whenever plugin starts Even if you dont need it, you SHOULD put at least return None, otherwise your plugin wont load """ return def translate(bot: Bot, update: Update, user, args): # pylint: disable=W0613 """/tl""" if update.message.reply_to_message: if len(args) > 0: lang = args[0].lower() else: lang = "en" yandex = post(YAURL, params={"text":update.message.reply_to_message.text, "lang":lang}).json() try: return yandex["lang"].upper() + "\n" + yandex["text"][0], constants.TEXT except KeyError: return "Unknown language:%s" % args[0].upper(), constants.TEXT COMMANDS = [ { "command":"/tl", "function":translate, "description":"Translates message to english. Example: [In Reply To Message] /tl", "inline_support":True } ]
Test even more PHP decoding cases
<?php use Gettext\Utils\Strings; class StringsTest extends PHPUnit_Framework_TestCase { public function stringFromPhpProvider() { return array( array('"test"', 'test'), array("'test'", 'test'), array("'DATE \a\\t TIME'", 'DATE \a\t TIME'), array("'DATE \a\\t TIME$'", 'DATE \a\t TIME$'), array("'DATE \a\\t TIME\$'", 'DATE \a\t TIME$'), array("'DATE \a\\t TIME\$a'", 'DATE \a\t TIME$a'), array('"FIELD\\tFIELD"', "FIELD\tFIELD"), array('"$"', '$'), array('"Hi $"', 'Hi $'), array('"$ hi"', '$ hi'), array('"Hi\t$name"', "Hi\t\$name"), array('"Hi\\\\"', 'Hi\\'), array('"{$obj->name}"', '{$obj->name}'), array('"a\x20b $c"', 'a b $c'), array('"a\x01b\2 \1 \01 \001 \r \n \t \v \f"', "a\1b\2 \1 \1 \1 \r \n \t \v \f"), array('"$ \$a \""', '$ $a "') ); } /** * @dataProvider stringFromPhpProvider */ public function testStringFromPhp($source, $decoded) { $this->assertSame($decoded, Strings::fromPhp($source)); } }
<?php use Gettext\Utils\Strings; class StringsTest extends PHPUnit_Framework_TestCase { public function stringFromPhpProvider() { return array( array('"test"', 'test'), array("'test'", 'test'), array("'DATE \a\\t TIME'", 'DATE \a\t TIME'), array("'DATE \a\\t TIME$'", 'DATE \a\t TIME$'), array("'DATE \a\\t TIME\$'", 'DATE \a\t TIME$'), array("'DATE \a\\t TIME\$a'", 'DATE \a\t TIME$a'), array('"FIELD\\tFIELD"', "FIELD\tFIELD"), array('"$"', '$'), array('"Hi $"', 'Hi $'), array('"$ hi"', '$ hi'), array('"Hi\t$name"', "Hi\t\$name"), array('"Hi\\\\"', 'Hi\\'), array('"{$obj->name}"', '{$obj->name}'), array('"a\x20b $c"', 'a b $c'), ); } /** * @dataProvider stringFromPhpProvider */ public function testStringFromPhp($source, $decoded) { $this->assertSame($decoded, Strings::fromPhp($source)); } }
Remove file extension from default file This will allow it to import scss or css files.
var findup = require('findup'), path = require('path'); function find(dir, file, callback) { var name = file.split('/')[0], modulePath = './node_modules/' + name + '/package.json'; findup(dir, modulePath, function (err, moduleDir) { if (err) { return callback(err); } var root = path.dirname(path.resolve(moduleDir, modulePath)); // if import is just a module name if (file.split('/').length === 0) { var json = require(path.resolve(moduleDir, modulePath)); // look for styles declaration in package.json if (json.styles) { callback(null, path.resolve(root, json.styles)); // otherwise assume ./styles.scss } else { callback(null, path.resolve(root, './styles')); } // if a full path is provided } else { callback(null, path.resolve(root, '../', file)); } }); } function importer(url, file, done) { find(path.dirname(file), url, function (err, location) { if (err) { done({ file: url }); } else { done({ file: location }); }; }); } module.exports = importer;
var findup = require('findup'), path = require('path'); function find(dir, file, callback) { var name = file.split('/')[0], modulePath = './node_modules/' + name + '/package.json'; findup(dir, modulePath, function (err, moduleDir) { if (err) { return callback(err); } var root = path.dirname(path.resolve(moduleDir, modulePath)); // if import is just a module name if (file.split('/').length === 0) { var json = require(path.resolve(moduleDir, modulePath)); // look for styles declaration in package.json if (json.styles) { callback(null, path.resolve(root, json.styles)); // otherwise assume ./styles.scss } else { callback(null, path.resolve(root, './styles.scss')); } // if a full path is provided } else { callback(null, path.resolve(root, '../', file)); } }); } function importer(url, file, done) { find(path.dirname(file), url, function (err, location) { if (err) { done({ file: url }); } else { done({ file: location }); }; }); } module.exports = importer;
Use interface in main to access SmlForwarder
package de.diesner.ehzlogger; import java.io.IOException; import java.util.List; import gnu.io.PortInUseException; import gnu.io.UnsupportedCommOperationException; import org.openmuc.jsml.structures.*; import org.openmuc.jsml.tl.SML_SerialReceiver; public class EhzLogger { public static void main(String[] args) throws IOException, PortInUseException, UnsupportedCommOperationException { System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyUSB0"); final SML_SerialReceiver receiver = new SML_SerialReceiver(); receiver.setupComPort("/dev/ttyUSB0"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { receiver.close(); } catch (IOException e) { System.err.println("Error while trying to close serial port: " + e.getMessage()); } } }); SmlForwarder forwarder = new CmdLinePrint(); while (true) { SML_File smlFile = receiver.getSMLFile(); System.out.println("Got SML_File"); forwarder.messageReceived(smlFile.getMessages()); } } }
package de.diesner.ehzlogger; import java.io.IOException; import java.util.List; import gnu.io.PortInUseException; import gnu.io.UnsupportedCommOperationException; import org.openmuc.jsml.structures.*; import org.openmuc.jsml.tl.SML_SerialReceiver; public class EhzLogger { public static void main(String[] args) throws IOException, PortInUseException, UnsupportedCommOperationException { System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyUSB0"); final SML_SerialReceiver receiver = new SML_SerialReceiver(); receiver.setupComPort("/dev/ttyUSB0"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { receiver.close(); } catch (IOException e) { System.err.println("Error while trying to close serial port: " + e.getMessage()); } } }); CmdLinePrint cmdLinePrint = new CmdLinePrint(); while (true) { SML_File smlFile = receiver.getSMLFile(); System.out.println("Got SML_File"); cmdLinePrint.messageReceived(smlFile.getMessages()); } } }
Move locus tag attribute key name into the function that uses it
#!/usr/bin/env python import jargparse ################# ### CONSTANTS ### ################# metadataPrefix = '#' accessionKey = '#!genome-build-accession NCBI_Assembly:' ################# ### FUNCTIONS ### ################# def parseRecord(record, locusTags): locusTagAttributeKey = 'locus_tag' components = record.split() type = components[2] rawAttributes = components[8] if type == 'gene': attributes = rawAttributes.split(';') for a in attributes: (key, value) = a.split('=') # print a if key == locusTagAttributeKey: locusTags.append(value) parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file') parser.add_argument('gffPath', help='path to the GFF') parser.add_argument('outPath', help='path to output the n-quads') args = parser.parse_args() accessionIdentifier = 'NONE FOUND' locusTags = [] with open(args.gffPath) as f: for line in f: line = line.strip() if line.startswith(metadataPrefix): if line.startswith(accessionKey): accessionIdentifier = line[len(accessionKey):] else: parseRecord(line, locusTags) with open(args.outPath, 'w') as f: for locusTag in locusTags: f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
#!/usr/bin/env python import jargparse ################# ### CONSTANTS ### ################# metadataPrefix = '#' accessionKey = '#!genome-build-accession NCBI_Assembly:' locusTagAttributeKey = 'locus_tag' ################# ### FUNCTIONS ### ################# def parseRecord(record, locusTags): components = record.split() type = components[2] rawAttributes = components[8] if type == 'gene': attributes = rawAttributes.split(';') for a in attributes: (key, value) = a.split('=') # print a if key == locusTagAttributeKey: locusTags.append(value) parser = jargparse.ArgParser('Convert Genbank GFF into an n-quad file') parser.add_argument('gffPath', help='path to the GFF') parser.add_argument('outPath', help='path to output the n-quads') args = parser.parse_args() accessionIdentifier = 'NONE FOUND' locusTags = [] with open(args.gffPath) as f: for line in f: line = line.strip() if line.startswith(metadataPrefix): if line.startswith(accessionKey): accessionIdentifier = line[len(accessionKey):] else: parseRecord(line, locusTags) with open(args.outPath, 'w') as f: for locusTag in locusTags: f.write('<%s> <locus> "%s" .\n' % (accessionIdentifier, locusTag))
Write exceptions to jobs logger
import logging from datetime import datetime from flask import current_app from changes.backends.jenkins.builder import JenkinsBuilder from changes.config import db, queue from changes.constants import Status, Result from changes.models import Build, RemoteEntity logger = logging.getLogger('jobs') def sync_build(build_id): try: build = Build.query.get(build_id) if not build: return if build.status == Status.finished: return # HACK(dcramer): this definitely is a temporary fix for our "things are # only a single builder" problem entity = RemoteEntity.query.filter_by( provider='jenkins', internal_id=build.id, type='build', ).first() if not entity: build.status = Status.finished build.result = Result.aborted else: builder = JenkinsBuilder( app=current_app, base_url=current_app.config['JENKINS_URL'], ) builder.sync_build(build) build.date_modified = datetime.utcnow() db.session.add(build) if build.status != Status.finished: queue.delay('sync_build', build_id=build.id.hex) except Exception: # Ensure we continue to synchronize this build as this could be a # temporary failure queue.retry('sync_build', build_id=build.id.hex) logger.exception('Failed to sync build') raise
from datetime import datetime from flask import current_app from changes.backends.jenkins.builder import JenkinsBuilder from changes.config import db, queue from changes.constants import Status, Result from changes.models import Build, RemoteEntity def sync_build(build_id): try: build = Build.query.get(build_id) if not build: return if build.status == Status.finished: return # HACK(dcramer): this definitely is a temporary fix for our "things are # only a single builder" problem entity = RemoteEntity.query.filter_by( provider='jenkins', internal_id=build.id, type='build', ).first() if not entity: build.status = Status.finished build.result = Result.aborted else: builder = JenkinsBuilder( app=current_app, base_url=current_app.config['JENKINS_URL'], ) builder.sync_build(build) build.date_modified = datetime.utcnow() db.session.add(build) if build.status != Status.finished: queue.delay('sync_build', build_id=build.id.hex) except Exception: # Ensure we continue to synchronize this build as this could be a # temporary failure queue.retry('sync_build', build_id=build.id.hex) raise
Increase page size to 100 on getAllPrograms to minimize number of requests required
<?php namespace AppBundle\WebService\SR; use AppBundle\WebService\SR\Responses\AllProgramsResponse; use Ci\RestClientBundle\Services\RestClient; use JMS\Serializer\Serializer; /** * Class SrWebServiceClient */ class SrWebServiceClient { /** @var RestClient */ protected $client; /** @var Serializer */ protected $serializer; const API_BASE_URI = 'http://api.sr.se/api/v2/'; /** * SrWebServiceClient constructor. * * @param RestClient $client */ public function __construct(RestClient $client, Serializer $serializer) { $this->client = $client; $this->serializer = $serializer; } public function getAllPrograms() { $programs = $this->doGetAllPrograms(); return $programs; } protected function doGetAllPrograms($programs = [], $nextPage = null) { $url = $nextPage ?: static::API_BASE_URI.'programs/index?format=json&size=100'; $rawResponse = $this->client->get($url); $serializedResponse = $this->serializer->deserialize( $rawResponse->getContent(), AllProgramsResponse::class, 'json' ); $programs = array_merge($programs, $serializedResponse->getPrograms()); if ($serializedResponse->getPagination()->getPage() < $serializedResponse->getPagination()->getTotalPages()) { return $this->doGetAllPrograms($programs, $serializedResponse->getPagination()->getNextPage()); } return $programs; } }
<?php namespace AppBundle\WebService\SR; use AppBundle\WebService\SR\Responses\AllProgramsResponse; use Ci\RestClientBundle\Services\RestClient; use JMS\Serializer\Serializer; /** * Class SrWebServiceClient */ class SrWebServiceClient { /** @var RestClient */ protected $client; /** @var Serializer */ protected $serializer; const API_BASE_URI = 'http://api.sr.se/api/v2/'; /** * SrWebServiceClient constructor. * * @param RestClient $client */ public function __construct(RestClient $client, Serializer $serializer) { $this->client = $client; $this->serializer = $serializer; } public function getAllPrograms() { $programs = $this->doGetAllPrograms(); return $programs; } protected function doGetAllPrograms($programs = [], $nextPage = null) { $url = $nextPage ?: static::API_BASE_URI.'programs/index?format=json'; $rawResponse = $this->client->get($url); $serializedResponse = $this->serializer->deserialize( $rawResponse->getContent(), AllProgramsResponse::class, 'json' ); $programs = array_merge($programs, $serializedResponse->getPrograms()); if ($serializedResponse->getPagination()->getPage() < $serializedResponse->getPagination()->getTotalPages()) { return $this->doGetAllPrograms($programs, $serializedResponse->getPagination()->getNextPage()); } return $programs; } }
Handle GFM line break by default in MD transformer
<?php namespace Code16\Sharp\Utils\Transformers\Attributes; use Code16\Sharp\Utils\Transformers\SharpAttributeTransformer; class MarkdownAttributeTransformer implements SharpAttributeTransformer { /** @var bool */ protected $handleImages = false; /** @var int */ protected $imageWidth; /** @var int */ protected $imageHeight; /** @var array */ protected $imageFilters; /** * @param int|null $width * @param int|null $height * @param array $filters * @return MarkdownAttributeTransformer */ public function handleImages(int $width = null, int $height = null, array $filters = []) { $this->handleImages = true; $this->imageWidth = $width; $this->imageHeight = $height; $this->imageFilters = $filters; return $this; } /** * Transform a model attribute to array (json-able). * * @param mixed $value * @param object $instance * @param string $attribute * @return mixed */ function apply($value, $instance = null, $attribute = null) { if(!$instance->$attribute) { return null; } $html = (new \Parsedown()) ->setBreaksEnabled(true) ->parse($instance->$attribute); if($this->handleImages) { return sharp_markdown_thumbnails( $html, "", $this->imageWidth, $this->imageHeight, $this->imageFilters ); } return $html; } }
<?php namespace Code16\Sharp\Utils\Transformers\Attributes; use Code16\Sharp\Utils\Transformers\SharpAttributeTransformer; class MarkdownAttributeTransformer implements SharpAttributeTransformer { /** @var bool */ protected $handleImages = false; /** @var int */ protected $imageWidth; /** @var int */ protected $imageHeight; /** @var array */ protected $imageFilters; /** * @param int|null $width * @param int|null $height * @param array $filters * @return MarkdownAttributeTransformer */ public function handleImages(int $width = null, int $height = null, array $filters = []) { $this->handleImages = true; $this->imageWidth = $width; $this->imageHeight = $height; $this->imageFilters = $filters; return $this; } /** * Transform a model attribute to array (json-able). * * @param mixed $value * @param object $instance * @param string $attribute * @return mixed */ function apply($value, $instance = null, $attribute = null) { if(!$instance->$attribute) { return null; } $html = (new \Parsedown())->parse($instance->$attribute); if($this->handleImages) { return sharp_markdown_thumbnails( $html, "", $this->imageWidth, $this->imageHeight, $this->imageFilters ); } return $html; } }
Make search a search input instead of text
<?php namespace ProcessWire; ?> <header class="stripe stripe--fluid header header--reduced"> <div layout="column" layout-gt-sm="row" layout-align="start stretch"> <a class="site__logo site__logo--reduced" href="<?=$homepage->httpUrl?>"> <img srcset="<?=$homepage->image->get('name%=light')->size(92,92)->httpUrl?> 2x" src="<?=$homepage->image->get('name%=light')->size(180,180)->httpUrl?>" alt="" height="46" width="46"> </a> <nav class="site__nav site__nav--short" layout-gt-sm="row" layout="column"> <? foreach ($homepage->children('template=page|overview') as $key => $child):?> <style> #nav-<?=$child->name?>:hover, #nav-<?=$child->name?>:focus, #nav-<?=$child->name?>.active { background-color: <?=$child->color?> } </style> <a class="<?= $child->id == $page->rootParent->id ? 'active' : ''?>" id="nav-<?=$child->name?>" href="<?=$child->url?>"><?=$child->title?></a> <? endforeach; ?> </nav> <form action="<?=$pages->get('/search/')->httpUrl?>" class="search" flex-end layout="row" layout-align="center center"> <input type="search" name="for" size="20" placeholder="Search topics" value="<?=$input->get->for?>"> </form> </div> </header>
<?php namespace ProcessWire; ?> <header class="stripe stripe--fluid header header--reduced"> <div layout="column" layout-gt-sm="row" layout-align="start stretch"> <a class="site__logo site__logo--reduced" href="<?=$homepage->httpUrl?>"> <img srcset="<?=$homepage->image->get('name%=light')->size(92,92)->httpUrl?> 2x" src="<?=$homepage->image->get('name%=light')->size(180,180)->httpUrl?>" alt="" height="46" width="46"> </a> <nav class="site__nav site__nav--short" layout-gt-sm="row" layout="column"> <? foreach ($homepage->children('template=page|overview') as $key => $child):?> <style> #nav-<?=$child->name?>:hover, #nav-<?=$child->name?>:focus, #nav-<?=$child->name?>.active { background-color: <?=$child->color?> } </style> <a class="<?= $child->id == $page->rootParent->id ? 'active' : ''?>" id="nav-<?=$child->name?>" href="<?=$child->url?>"><?=$child->title?></a> <? endforeach; ?> </nav> <form action="<?=$pages->get('/search/')->httpUrl?>" class="search" flex-end layout="row" layout-align="center center"> <input type="text" name="for" size="20" placeholder="Search topics" value="<?=$input->get->for?>"> </form> </div> </header>
[Customer][Core] Rename DashboardStatistic customers count() method to countCustomers()
<?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\Dashboard; use Sylius\Component\Core\Model\ChannelInterface; use Sylius\Component\Core\Repository\CustomerRepositoryInterface; use Sylius\Component\Core\Repository\OrderRepositoryInterface; /** * @author Paweł Jędrzejewski <[email protected]> */ class DashboardStatisticsProvider implements DashboardStatisticsProviderInterface { /** * @var OrderRepositoryInterface */ private $orderRepository; /** * @var CustomerRepositoryInterface */ private $customerRepository; /** * @param OrderRepositoryInterface $orderRepository * @param CustomerRepositoryInterface $customerRepository */ public function __construct( OrderRepositoryInterface $orderRepository, CustomerRepositoryInterface $customerRepository ) { $this->orderRepository = $orderRepository; $this->customerRepository = $customerRepository; } /** * {@inheritdoc} */ public function getStatisticsForChannel(ChannelInterface $channel): DashboardStatistics { return new DashboardStatistics( $this->orderRepository->getTotalSalesForChannel($channel), $this->orderRepository->countFulfilledByChannel($channel), $this->customerRepository->countCustomers() ); } }
<?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\Dashboard; use Sylius\Component\Core\Model\ChannelInterface; use Sylius\Component\Core\Repository\CustomerRepositoryInterface; use Sylius\Component\Core\Repository\OrderRepositoryInterface; /** * @author Paweł Jędrzejewski <[email protected]> */ class DashboardStatisticsProvider implements DashboardStatisticsProviderInterface { /** * @var OrderRepositoryInterface */ private $orderRepository; /** * @var CustomerRepositoryInterface */ private $customerRepository; /** * @param OrderRepositoryInterface $orderRepository * @param CustomerRepositoryInterface $customerRepository */ public function __construct( OrderRepositoryInterface $orderRepository, CustomerRepositoryInterface $customerRepository ) { $this->orderRepository = $orderRepository; $this->customerRepository = $customerRepository; } /** * {@inheritdoc} */ public function getStatisticsForChannel(ChannelInterface $channel): DashboardStatistics { return new DashboardStatistics( $this->orderRepository->getTotalSalesForChannel($channel), $this->orderRepository->countFulfilledByChannel($channel), $this->customerRepository->count() ); } }
Add a missing field to the fetch list of deny rule
Meteor.methods({ storeEncryptedPrivateKey: function (encryptedKey) { Meteor.users.update({ _id: this.userId }, { $set: { 'profile.privateKey': encryptedKey } }); }, initEncryptionSchema: function (collectionName, fieldKey) { var schema = {}; schema[fieldKey] = { type: Boolean, defaultValue: false }; // add ecrypted field to the collection schema Mongo.Collection.get(collectionName).attachSchema(schema); } }); Security.defineMethod("ifCurrentUserIsOwner", { fetch: ['ownerId'], transform: null, deny: function (type, arg, userId, doc) { return userId !== doc.ownerId; } }); Principals.permit(['insert']).apply(); Principals.permit(['update', 'remove']) .never().apply(); Principals.permit(['update', 'remove']) .ifLoggedIn() .ifCurrentUserIsOwner() .apply(); Meteor.publish("principals", function (dataId) { if (dataId) { // subscribe to all own principals and the user principal of the partner return Principals.find({ $or: [{ dataId: dataId }, { ownerId: this.userId }, { 'encryptedPrivateKeys.userId': this.userId }] }); } // subscribe to all own principals return Principals.find({ $or: [{ ownerId: this.userId }, { 'encryptedPrivateKeys.userId': this.userId }] }); });
Meteor.methods({ storeEncryptedPrivateKey: function (encryptedKey) { Meteor.users.update({ _id: this.userId }, { $set: { 'profile.privateKey': encryptedKey } }); }, initEncryptionSchema: function (collectionName, fieldKey) { var schema = {}; schema[fieldKey] = { type: Boolean, defaultValue: false }; // add ecrypted field to the collection schema Mongo.Collection.get(collectionName).attachSchema(schema); } }); Security.defineMethod("ifCurrentUserIsOwner", { fetch: [], transform: null, deny: function (type, arg, userId, doc) { return userId !== doc.ownerId; } }); Principals.permit(['insert']).apply(); Principals.permit(['update', 'remove']) .never().apply(); Principals.permit(['update', 'remove']) .ifLoggedIn() .ifCurrentUserIsOwner() .apply(); Meteor.publish("principals", function (dataId) { if (dataId) { // subscribe to all own principals and the user principal of the partner return Principals.find({ $or: [{ dataId: dataId }, { ownerId: this.userId }, { 'encryptedPrivateKeys.userId': this.userId }] }); } // subscribe to all own principals return Principals.find({ $or: [{ ownerId: this.userId }, { 'encryptedPrivateKeys.userId': this.userId }] }); });
Add missing comma to requirements.
import os from setuptools import setup version = '0.9.2.dev0' def read_file(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as fp: return fp.read() setup(name='django-ogmios', version=version, author="Fusionbox, Inc.", author_email="[email protected]", url="https://github.com/fusionbox/django-ogmios", keywords="email send easy simple helpers django", description="Just sends email. Simple, easy, multiformat.", long_description=read_file('README.rst') + '\n\n' + read_file('CHANGELOG.rst'), classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Communications :: Email', 'Topic :: Software Development :: Libraries' ], install_requires=[ 'Django>=1.7,<1.9', 'PyYAML', 'Markdown', 'html2text', ], packages=['ogmios'], )
import os from setuptools import setup version = '0.9.2.dev0' def read_file(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as fp: return fp.read() setup(name='django-ogmios', version=version, author="Fusionbox, Inc.", author_email="[email protected]", url="https://github.com/fusionbox/django-ogmios", keywords="email send easy simple helpers django", description="Just sends email. Simple, easy, multiformat.", long_description=read_file('README.rst') + '\n\n' + read_file('CHANGELOG.rst'), classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Communications :: Email', 'Topic :: Software Development :: Libraries' ], install_requires=[ 'Django>=1.7,<1.9' 'PyYAML', 'Markdown', 'html2text', ], packages=['ogmios'], )
Handle UTF errors with invalid bytes.
import logging import requests def scrape(url, extractor): """ Function to request and parse a given URL. Returns only the "relevant" text. Parameters ---------- url : String. URL to request and parse. extractor : Goose class instance. An instance of Goose that allows for parsing of content. Returns ------- text : String. Parsed text from the specified website. meta : String. Parsed meta description of an article. Usually equivalent to the lede. """ logger = logging.getLogger('scraper_log') try: headers = {'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"} page = requests.get(url, headers=headers) try: try: article = extractor.extract(raw_html=page.content) except UnicodeDecodeError: article = extractor.extract(raw_html=page.content.decode('utf-8', errors='replace')) text = article.cleaned_text meta = article.meta_description return text, meta #Generic error catching is bad except Exception, e: print 'There was an error. Check the log file for more information.' logger.warning('Problem scraping URL: {}. {}.'.format(url, e)) except Exception, e: print 'There was an error. Check the log file for more information.' logger.warning('Problem requesting url: {}. {}'.format(url, e))
import logging import requests def scrape(url, extractor): """ Function to request and parse a given URL. Returns only the "relevant" text. Parameters ---------- url : String. URL to request and parse. extractor : Goose class instance. An instance of Goose that allows for parsing of content. Returns ------- text : String. Parsed text from the specified website. meta : String. Parsed meta description of an article. Usually equivalent to the lede. """ logger = logging.getLogger('scraper_log') try: headers = {'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"} page = requests.get(url, headers=headers) try: article = extractor.extract(raw_html=page.content) text = article.cleaned_text meta = article.meta_description return text, meta #Generic error catching is bad except Exception, e: print 'There was an error. Check the log file for more information.' logger.warning('Problem scraping URL: {}. {}.'.format(url, e)) except Exception, e: print 'There was an error. Check the log file for more information.' logger.warning('Problem requesting url: {}. {}'.format(url, e))
Include answer count in stored data.
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer): namespaces_for_post = {} for name, n in namespaces.items(): namespace_tags = n.get_tags() if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)): ids = n.get_ids(title, body, tags) for a in answers: ids = list(set(ids) | set(n.get_ids(title, a["body"], tags))) if len(ids) > 0: ids = map(lambda x: x.lower(), ids) namespaces_for_post[name] = ids if len(namespaces_for_post): post = { "question_id": id, "url": "http://stackoverflow.com/questions/%s" % id, "namespaces": namespaces_for_post, "title": title, "score": int(score), "answers": len(answers), "accepted_answer": has_accepted_answer, "last_activity": last_activity_date, "last_updated": last_updated_date } if upsert: posts.update({"question_id": id}, post, True) else: posts.insert(post) print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer): namespaces_for_post = {} for name, n in namespaces.items(): namespace_tags = n.get_tags() if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)): ids = n.get_ids(title, body, tags) for a in answers: ids = list(set(ids) | set(n.get_ids(title, a["body"], tags))) if len(ids) > 0: ids = map(lambda x: x.lower(), ids) namespaces_for_post[name] = ids if len(namespaces_for_post): post = { "question_id": id, "url": "http://stackoverflow.com/questions/%s" % id, "namespaces": namespaces_for_post, "title": title, "score": int(score), "accepted_answer": has_accepted_answer, "last_activity": last_activity_date, "last_updated": last_updated_date } if upsert: posts.update({"question_id": id}, post, True) else: posts.insert(post) print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
Fix handling of URLs, that result in no actual model Add $callback to scope of Closure.
<?php namespace Felixkiss\SlugRoutes; use Illuminate\Routing\Router; class SlugRouter extends Router { public function model($key, $class, Closure $callback = null) { return $this->bind($key, function($value) use ($class, $callback) { if (is_null($value)) return null; // For model binders, we will attempt to retrieve the model using the find // method on the model instance. If we cannot retrieve the models we'll // throw a not found exception otherwise we will return the instance. $model = new $class; if($model instanceof SluggableInterface) { $model = $model->where($model->getSlugIdentifier(), $value)->first(); } else { $model = $model->find($value); } if ( ! is_null($model)) { return $model; } // If a callback was supplied to the method we will call that to determine // what we should do when the model is not found. This just gives these // developer a little greater flexibility to decide what will happen. if ($callback instanceof Closure) { return call_user_func($callback); } throw new NotFoundHttpException; }); } }
<?php namespace Felixkiss\SlugRoutes; use Illuminate\Routing\Router; class SlugRouter extends Router { public function model($key, $class, Closure $callback = null) { return $this->bind($key, function($value) use ($class) { if (is_null($value)) return null; // For model binders, we will attempt to retrieve the model using the find // method on the model instance. If we cannot retrieve the models we'll // throw a not found exception otherwise we will return the instance. $model = new $class; if($model instanceof SluggableInterface) { $model = $model->where($model->getSlugIdentifier(), $value)->first(); } else { $model = $model->find($value); } if ( ! is_null($model)) { return $model; } // If a callback was supplied to the method we will call that to determine // what we should do when the model is not found. This just gives these // developer a little greater flexibility to decide what will happen. if ($callback instanceof Closure) { return call_user_func($callback); } throw new NotFoundHttpException; }); } }
Add links to fixture and casedb specs
from casexml.apps.case.xml.generator import safe_element from casexml.apps.phone.xml import get_casedb_element class CaseDBFixture(object): """Used to provide a casedb-like structure as a fixture Does not follow the standard FixtureGenerator pattern since it is currently not used during a regular sync operation, and is user-agnostic """ id = "case" def __init__(self, cases): if not isinstance(cases, list): self.cases = [cases] else: self.cases = cases @property def fixture(self): """For a list of cases, return a fixture with all case properties <fixture id="case"> <case case_id="" case_type="" owner_id="" status=""> <case_name/> <date_opened/> <last_modified/> <case_property /> <index> <a12345 case_type="" relationship="" /> </index> <attachment> <a12345 /> </attachment> </case> <case> ... </case> </fixture> https://github.com/dimagi/commcare/wiki/casedb https://github.com/dimagi/commcare/wiki/fixtures """ element = safe_element("fixture") element.attrib = {'id': self.id} for case in self.cases: element.append(get_casedb_element(case)) return element
from casexml.apps.case.xml.generator import safe_element from casexml.apps.phone.xml import get_casedb_element class CaseDBFixture(object): """Used to provide a casedb-like structure as a fixture Does not follow the standard FixtureGenerator pattern since it is currently not used during a regular sync operation, and is user-agnostic """ id = "case" def __init__(self, cases): if not isinstance(cases, list): self.cases = [cases] else: self.cases = cases @property def fixture(self): """For a list of cases, return a fixture with all case properties <fixture id="case"> <case case_id="" case_type="" owner_id="" status=""> <case_name/> <date_opened/> <last_modified/> <case_property /> <index> <a12345 case_type="" relationship="" /> </index> <attachment> <a12345 /> </attachment> </case> <case> ... </case> </fixture> """ element = safe_element("fixture") element.attrib = {'id': self.id} for case in self.cases: element.append(get_casedb_element(case)) return element
Add Python 3.5 to PyPI classifiers
#!/usr/bin/env python3 from setuptools import setup from doxhooks import __version__ with open("README.rst") as readme: lines = list(readme) for line_no, line in enumerate(lines): if line.startswith("Doxhooks helps you"): long_description = "".join(lines[line_no:]) break else: raise RuntimeError("Cannot find long description in README.") setup( name="Doxhooks", version=__version__, description=( "Abstract away the content and maintenance of files in your project." ), long_description=long_description, license="MIT", platforms=["any"], url="https://github.com/nre/doxhooks", author="Nick Evans", author_email="[email protected]", keywords=( "abstract build code document file hook " "preprocessor project resource source text" ), classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Software Development :: Build Tools", "Topic :: Software Development :: Pre-processors", ], packages=["doxhooks"], zip_safe=True, )
#!/usr/bin/env python3 from setuptools import setup from doxhooks import __version__ with open("README.rst") as readme: lines = list(readme) for line_no, line in enumerate(lines): if line.startswith("Doxhooks helps you"): long_description = "".join(lines[line_no:]) break else: raise RuntimeError("Cannot find long description in README.") setup( name="Doxhooks", version=__version__, description=( "Abstract away the content and maintenance of files in your project." ), long_description=long_description, license="MIT", platforms=["any"], url="https://github.com/nre/doxhooks", author="Nick Evans", author_email="[email protected]", keywords=( "abstract build code document file hook " "preprocessor project resource source text" ), classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Topic :: Software Development :: Build Tools", "Topic :: Software Development :: Pre-processors", ], packages=["doxhooks"], zip_safe=True, )
Remove layout dependency in candlestick visual
define(function (require) { var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor']; var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0']; var positiveColorQuery = ['itemStyle', 'normal', 'color']; var negativeColorQuery = ['itemStyle', 'normal', 'color0']; return function (ecModel, api) { ecModel.eachRawSeriesByType('candlestick', function (seriesModel) { var data = seriesModel.getData(); data.setVisual({ legendSymbol: 'roundRect' }); // Only visible series has each data be visual encoded if (!ecModel.isSeriesFiltered(seriesModel)) { data.each(function (idx) { var itemModel = data.getItemModel(idx); var openVal = data.get('open', idx); var closeVal = data.get('close', idx); var sign = openVal > closeVal ? -1 : openVal < closeVal ? 1 : 0; data.setItemVisual( idx, { color: itemModel.get( sign > 0 ? positiveColorQuery : negativeColorQuery ), borderColor: itemModel.get( sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery ) } ); }); } }); }; });
define(function (require) { var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor']; var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0']; var positiveColorQuery = ['itemStyle', 'normal', 'color']; var negativeColorQuery = ['itemStyle', 'normal', 'color0']; return function (ecModel, api) { ecModel.eachRawSeriesByType('candlestick', function (seriesModel) { var data = seriesModel.getData(); data.setVisual({ legendSymbol: 'roundRect' }); // Only visible series has each data be visual encoded if (!ecModel.isSeriesFiltered(seriesModel)) { data.each(function (idx) { var itemModel = data.getItemModel(idx); var sign = data.getItemLayout(idx).sign; data.setItemVisual( idx, { color: itemModel.get( sign > 0 ? positiveColorQuery : negativeColorQuery ), borderColor: itemModel.get( sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery ) } ); }); } }); }; });
Fix tests when Pushover is not configured
from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from hc.api.models import Channel class AddChannelTestCase(TestCase): def setUp(self): self.alice = User(username="alice") self.alice.set_password("password") self.alice.save() settings.PUSHOVER_API_TOKEN = "bogus_token" settings.PUSHOVER_SUBSCRIPTION_URL = "bogus_url" def test_it_works(self): url = "/integrations/add/" form = {"kind": "email", "value": "[email protected]"} self.client.login(username="alice", password="password") r = self.client.post(url, form) assert r.status_code == 302 assert Channel.objects.count() == 1 def test_it_rejects_bad_kind(self): url = "/integrations/add/" form = {"kind": "dog", "value": "Lassie"} self.client.login(username="alice", password="password") r = self.client.post(url, form) assert r.status_code == 400, r.status_code def test_instructions_work(self): self.client.login(username="alice", password="password") for frag in ("email", "webhook", "pd", "pushover", "slack", "hipchat"): url = "/integrations/add_%s/" % frag r = self.client.get(url) self.assertContains(r, "Integration Settings", status_code=200)
from django.contrib.auth.models import User from django.test import TestCase from hc.api.models import Channel class AddChannelTestCase(TestCase): def setUp(self): self.alice = User(username="alice") self.alice.set_password("password") self.alice.save() def test_it_works(self): url = "/integrations/add/" form = {"kind": "email", "value": "[email protected]"} self.client.login(username="alice", password="password") r = self.client.post(url, form) assert r.status_code == 302 assert Channel.objects.count() == 1 def test_it_rejects_bad_kind(self): url = "/integrations/add/" form = {"kind": "dog", "value": "Lassie"} self.client.login(username="alice", password="password") r = self.client.post(url, form) assert r.status_code == 400, r.status_code def test_instructions_work(self): self.client.login(username="alice", password="password") for frag in ("email", "webhook", "pd", "pushover", "slack", "hipchat"): url = "/integrations/add_%s/" % frag r = self.client.get(url) self.assertContains(r, "Integration Settings", status_code=200)
Change instaflights name in flights_to tests
import unittest import datetime import json import sys sys.path.append('..') import sabre_dev_studio import sabre_dev_studio.sabre_exceptions as sabre_exceptions ''' requires config.json in the same directory for api authentication { "sabre_client_id": -----, "sabre_client_secret": ----- } ''' class TestBasicFlightsTo(unittest.TestCase): def read_config(self): raw_data = open('config.json').read() data = json.loads(raw_data) client_secret = data['sabre_client_secret'] client_id = data['sabre_client_id'] return (client_id, client_secret) def setUp(self): # Read from config self.client_id, self.client_secret = self.read_config() self.sds = sabre_dev_studio.SabreDevStudio() self.sds.set_credentials(self.client_id, self.client_secret) self.sds.authenticate() def test_basic_request(self): city = 'YTO' flights_to_city = self.sds.flights_to(city) print(flights_to_city) self.assertIsNotNone(flights_to_city) def test_no_authorization(self): sds = sabre_dev_studio.SabreDevStudio() with self.assertRaises(sabre_exceptions.NotAuthorizedError): resp = sds.flights_to('YTO') if __name__ == '__main__': unittest.main()
import unittest import datetime import json import sys sys.path.append('..') import sabre_dev_studio import sabre_dev_studio.sabre_exceptions as sabre_exceptions ''' requires config.json in the same directory for api authentication { "sabre_client_id": -----, "sabre_client_secret": ----- } ''' class TestBasicInstaflights(unittest.TestCase): def read_config(self): raw_data = open('config.json').read() data = json.loads(raw_data) client_secret = data['sabre_client_secret'] client_id = data['sabre_client_id'] return (client_id, client_secret) def setUp(self): # Read from config self.client_id, self.client_secret = self.read_config() self.sds = sabre_dev_studio.SabreDevStudio() self.sds.set_credentials(self.client_id, self.client_secret) self.sds.authenticate() def test_basic_request(self): city = 'YTO' instaf = self.sds.flights_to(city) self.assertIsNotNone(instaf) def test_no_authorization(self): sds = sabre_dev_studio.SabreDevStudio() with self.assertRaises(sabre_exceptions.NotAuthorizedError): resp = sds.flights_to('YTO') if __name__ == '__main__': unittest.main()
:bug: Fix a dead lock in App.lock
(function(target) { 'use strict' function ajax(Url, Method, Contents) { return new Promise(function(resolve, reject) { const XHR = new XMLHttpRequest() XHR.open(Method, Url, true) XHR.addEventListener('load', () => { resolve(XHR.responseText) }) XHR.addEventListener('error', reject) XHR.setRequestHeader('X-Auth', 'COOKIE'); XHR.send(typeof Contents === 'object' ? JSON.stringify(Contents) : Contents) }) } function lock(Callback) { let InProgress = false const Callable = function(Param) { if (!InProgress) { const ReturnValue = Callback.call(this, Param) InProgress = true if (ReturnValue && ReturnValue.constructor.name === 'Promise') { ReturnValue.then(function() { InProgress = false }, function(e) { console.error(e) InProgress = false }) } else InProgress = false } } Callable.prototype = Callable.prototype return Callable } function getElements(form) { const elements = {} Array.prototype.forEach.call(form.querySelectorAll('[name]'), function(element) { elements[element.name] = element }) return elements } function getValues(elements) { const values = {} for (const key in elements) { const element = elements[key] values[key] = element.value } return values } window.App = {lock, ajax, getElements, getValues} })(window)
(function(target) { 'use strict' function ajax(Url, Method, Contents) { return new Promise(function(resolve, reject) { const XHR = new XMLHttpRequest() XHR.open(Method, Url, true) XHR.addEventListener('load', () => { resolve(XHR.responseText) }) XHR.addEventListener('error', reject) XHR.setRequestHeader('X-Auth', 'COOKIE'); XHR.send(typeof Contents === 'object' ? JSON.stringify(Contents) : Contents) }) } function lock(Callback) { let InProgress = false const Callable = function(Param) { if (!InProgress) { const ReturnValue = Callback.call(this, Param) InProgress = true if (ReturnValue && ReturnValue.constructor.name === 'Promise') { ReturnValue.then(function() { InProgress = false }, function(e) { console.error(e) }) } else InProgress = false } } Callable.prototype = Callable.prototype return Callable } function getElements(form) { const elements = {} Array.prototype.forEach.call(form.querySelectorAll('[name]'), function(element) { elements[element.name] = element }) return elements } function getValues(elements) { const values = {} for (const key in elements) { const element = elements[key] values[key] = element.value } return values } window.App = {lock, ajax, getElements, getValues} })(window)
DIsable dimmer for question files modal
import React from 'react' import PropTypes from 'prop-types' import { Card, Image, Modal } from 'semantic-ui-react' const propTypes = { files: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, }) ), } const defaultProps = { files: [], } const QuestionFiles = ({ files }) => ( <div className="questionFiles"> {files.map(({ id, name }, ix) => { const fileSrc = `${process.env.S3_BASE_PATH}/${name}` const previewImage = ( <Card> <Image height="auto" src={fileSrc} width="100%" /> <Card.Content extra>#{ix + 1}</Card.Content> </Card> ) return ( <div className="file" key={id}> <Modal closeIcon dimmer={false} trigger={previewImage}> <Modal.Content image> <Image wrapped src={fileSrc} /> </Modal.Content> </Modal> </div> ) })} <style jsx>{` .questionFiles { display: flex; flex-flow: row wrap; .file { margin-right: 0.3rem; width: 60px; :global(.extra) { padding: 0 0.3rem; text-align: center; } } } `}</style> </div> ) QuestionFiles.propTypes = propTypes QuestionFiles.defaultProps = defaultProps export default QuestionFiles
import React from 'react' import PropTypes from 'prop-types' import { Card, Image, Modal } from 'semantic-ui-react' const propTypes = { files: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, }) ), } const defaultProps = { files: [], } const QuestionFiles = ({ files }) => ( <div className="questionFiles"> {files.map(({ id, name }, ix) => { const fileSrc = `${process.env.S3_BASE_PATH}/${name}` const previewImage = ( <Card> <Image height="auto" src={fileSrc} width="100%" /> <Card.Content extra>#{ix + 1}</Card.Content> </Card> ) return ( <div className="file" key={id}> <Modal closeIcon trigger={previewImage}> <Modal.Content image> <Image wrapped src={fileSrc} /> </Modal.Content> </Modal> </div> ) })} <style jsx>{` .questionFiles { display: flex; flex-flow: row wrap; .file { margin-right: 0.3rem; width: 60px; :global(.extra) { padding: 0 0.3rem; text-align: center; } } } `}</style> </div> ) QuestionFiles.propTypes = propTypes QuestionFiles.defaultProps = defaultProps export default QuestionFiles
Remove React from bundle. Declared as peer dependency. 📦
const path = require('path'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); // const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = { mode: 'production', entry: path.resolve(__dirname, 'lib/index'), externals: { 'styled-components': 'styled-components', react: 'react' }, output: { path: path.resolve(__dirname, 'dist'), filename: 'react-simple-chatbot.js', publicPath: 'dist/', library: 'ReactSimpleChatbot', libraryTarget: 'umd', globalObject: 'typeof self !== \'undefined\' ? self : this', }, resolve: { extensions: ['.js', '.jsx'], }, plugins: [ new CleanWebpackPlugin(['dist']), new UglifyJsPlugin({ comments: false, }), // new BundleAnalyzerPlugin(), ], module: { rules: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: [ '@babel/plugin-transform-arrow-functions', '@babel/plugin-proposal-class-properties', ], }, }, }, ], }, };
const path = require('path'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); // const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = { mode: 'production', entry: path.resolve(__dirname, 'lib/index'), externals: { 'styled-components': 'styled-components' }, output: { path: path.resolve(__dirname, 'dist'), filename: 'react-simple-chatbot.js', publicPath: 'dist/', library: 'ReactSimpleChatbot', libraryTarget: 'umd', globalObject: 'typeof self !== \'undefined\' ? self : this', }, resolve: { extensions: ['.js', '.jsx'], }, plugins: [ new CleanWebpackPlugin(['dist']), new UglifyJsPlugin({ comments: false, }), // new BundleAnalyzerPlugin(), ], module: { rules: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: [ '@babel/plugin-transform-arrow-functions', '@babel/plugin-proposal-class-properties', ], }, }, }, ], }, };
Remove continuous test grunt task in favor of single-run test
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'Gruntfile.js', 'public/js/**/*.js', 'test/client/**/*.js', 'lib/**/*.js', 'app.js' ], options: { expr: true, browser: true, node: true } }, watch: { scripts: { files: ['public/js/**/*.js', 'test/client/**/*.js'], tasks: ['jshint'] }, karma: { files: ['public/js/**/*.js', 'test/client/**/*.js'], tasks: ['karma:unit:run'] } }, karma: { unit: { configFile: 'config/karma.conf.js', background: true }, single: { configFile: 'config/karma.conf.js', singleRun: true }, dev: { reporters: 'dots' } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('test', ['karma:single']); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { all: [ 'Gruntfile.js', 'public/js/**/*.js', 'test/client/**/*.js', 'lib/**/*.js', 'app.js' ], options: { expr: true, browser: true, node: true } }, watch: { scripts: { files: ['public/js/**/*.js', 'test/client/**/*.js'], tasks: ['jshint'] }, karma: { files: ['public/js/**/*.js', 'test/client/**/*.js'], tasks: ['karma:unit:run'] } }, karma: { unit: { configFile: 'config/karma.conf.js', background: true }, continuous: { singleRun: true, browsers: ['Firefox'] }, dev: { reporters: 'dots' } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-karma'); grunt.registerTask('test', ['karma:continuous']); };
Create a collection for Forms
define( ['data/data', 'collections/v3/interactions', 'collections/v3/datasuitcases', 'models/v3/DataSuitcase', 'collections/v3/forms', 'models/v3/form'], function (Backbone, InteractionCollection, DataSuitcaseCollection, DataSuitcase, FormCollection, Form) { "use strict"; var Application = Backbone.Model.extend({ initialize: function () { // Nested interactions this.interactions = new InteractionCollection(); // Nested Data Suitcases this.datasuitcases = new DataSuitcaseCollection(); this.forms = new FormCollection(); this.on('change', this.update); }, update: function () { var modelArray = this.get("DataSuitcases"), count, model, children = { DataSuitcases: this.datasuitcases, Forms: this.forms }; if (this.has("DataSuitcases")) { modelArray = this.get("DataSuitcases"); for (count = 0; count < modelArray.length; count = count + 1) { if (this.datasuitcases.where({name: modelArray[count]}).length === 0) { model = new DataSuitcase({ name: modelArray[count], siteName: this.get("siteName"), BICtype: "DataSuitcase" }); this.datasuitcases.add(model); model.fetch(); } } } } }), app; app = new Application(); return app; } );
define( ['data/data', 'collections/v3/interactions', 'collections/v3/datasuitcases', 'models/v3/DataSuitcase', 'collections/v3/forms', 'models/v3/form'], function (Backbone, InteractionCollection, DataSuitcaseCollection, DataSuitcase, FormCollection, Form) { "use strict"; var Application = Backbone.Model.extend({ initialize: function () { // Nested interactions this.interactions = new InteractionCollection(); // Nested Data Suitcases this.datasuitcases = new DataSuitcaseCollection(); this.on('change', this.update); }, update: function () { if (this.has("DataSuitcases")) { var ds = this.get("DataSuitcases"), count, dsmodel; for (count = 0; count < ds.length; count = count + 1) { if (this.datasuitcases.where({name: ds[count]}).length === 0) { dsmodel = new DataSuitcase({ name: ds[count], siteName: this.get("siteName"), BICtype: "DataSuitcase" }); this.datasuitcases.add(dsmodel); dsmodel.fetch(); } } } } }), app; app = new Application(); return app; } );
Improve check for single by only issuing search once
<?php class AlgorithmConnectedComponents extends Algorithm{ /** * * @var Graph */ private $graph; /** * * @param Graph $graph */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * check whether this graph consists of only a single component * * could be improved by not checking for actual number of components but stopping when there's more than one * * @return boolean * @uses AlgorithmSearchBreadthFirst::getNumberOfVertices() */ public function isSingle(){ $alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst()); return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices()); } /** * @return int number of components * @uses Graph::getVertices() * @uses AlgorithmSearchDepthFirst::getVertices() */ public function getNumberOfComponents(){ $visitedVertices = array(); $components = 0; foreach ($this->graph->getVertices() as $vertex){ //for each vertices if ( ! isset( $visitedVertices[$vertex->getId()] ) ){ //did I visit this vertex before? $alg = new AlgorithmSearchDepthFirst($vertex); $newVertices = $alg->getVertices(); //get all vertices of this component $components++; foreach ($newVertices as $v){ //mark the vertices of this component as visited $visitedVertices[$v->getId()] = true; } } } return $components; //return number of components } }
<?php class AlgorithmConnectedComponents extends Algorithm{ /** * * @var Graph */ private $graph; /** * * @param Graph $graph */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * check whether this graph consists of only a single component * * could be improved by not checking for actual number of components but stopping when there's more than one * * @return boolean * @uses AlgorithmConnectedComponents::getNumberOfComponents() */ public function isSingle(){ return ($this->getNumberOfComponents() === 1); } /** * @return int number of components * @uses Graph::getVertices() * @uses AlgorithmSearchDepthFirst::getVertices() */ public function getNumberOfComponents(){ $visitedVertices = array(); $components = 0; foreach ($this->graph->getVertices() as $vertex){ //for each vertices if ( ! isset( $visitedVertices[$vertex->getId()] ) ){ //did I visit this vertex before? $alg = new AlgorithmSearchDepthFirst($vertex); $newVertices = $alg->getVertices(); //get all vertices of this component $components++; foreach ($newVertices as $v){ //mark the vertices of this component as visited $visitedVertices[$v->getId()] = true; } } } return $components; //return number of components } }
[FIX] stock_planning: Fix condition cond.append(('date', '>=', from_date))
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '>=', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models class StockMove(models.Model): _inherit = 'stock.move' def _find_moves_from_stock_planning( self, company, to_date, from_date=None, category=None, template=None, product=None, location_id=None, location_dest_id=None): cond = [('company_id', '=', company.id), ('date', '<=', to_date), ('state', 'not in', ('done', 'cancel'))] if from_date: cond.append(('date', '=>', from_date)) if product: cond.append(('product_id', '=', product.id)) if location_id: cond.append(('location_id', '=', location_id.id)) if location_dest_id: cond.append(('location_dest_id', '=', location_dest_id.id)) moves = self.search(cond) if category: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.categ_id.id == category.id) if template: moves = moves.filtered( lambda x: x.product_id.product_tmpl_id.id == template.id) return moves
Fix Config loading in DownloadCsv
<?php namespace NemC\IP2LocLite\Commands; use Illuminate\Console\Config, Illuminate\Console\Command, NemC\IP2LocLite\Services\IP2LocLiteService, NemC\IP2LocLite\Exceptions\NotLoggedInResponseException, NemC\IP2LocLite\Exceptions\UnsupportedDatabaseCommandException; class DownloadCsvCommand extends Command { protected $name = 'ip2loclite:download-csv'; protected $description = 'Login to IP2Location user panel and download required csv'; protected $ip2LocLite; public function __construct(IP2LocLiteService $IP2LocLiteService) { parent::__construct(); $this->ip2LocLite = $IP2LocLiteService; } public function fire() { $database = Config::get('ip2loc-lite.database'); try { $this->ip2LocLite->isSupportedDatabase($database); } catch (UnsupportedDatabaseCommandException $e) { $this->error('Free IP2Location database "' . $database . '"" is not supported by IP2LocLite at this point'); return false; } try { $this->ip2LocLite->login(); } catch (NotLoggedInResponseException $e) { $this->error('Could not log you in with user authentication details provided'); return false; } $this->ip2LocLite->downloadCsv($database); $this->info('Latest version of IP2Location database ' . $database . ' has been downloaded'); } }
<?php namespace NemC\IP2LocLite\Commands; use Illuminate\Console\Command, NemC\IP2LocLite\Services\IP2LocLiteService, NemC\IP2LocLite\Exceptions\NotLoggedInResponseException, NemC\IP2LocLite\Exceptions\UnsupportedDatabaseCommandException; class DownloadCsvCommand extends Command { protected $name = 'ip2loclite:download-csv'; protected $description = 'Login to IP2Location user panel and download required csv'; protected $ip2LocLite; public function __construct(IP2LocLiteService $IP2LocLiteService) { parent::__construct(); $this->ip2LocLite = $IP2LocLiteService; } public function fire() { $database = Config::get('ip2loc-lite.database'); try { $this->ip2LocLite->isSupportedDatabase($database); } catch (UnsupportedDatabaseCommandException $e) { $this->error('Free IP2Location database "' . $database . '"" is not supported by IP2LocLite at this point'); return false; } try { $this->ip2LocLite->login(); } catch (NotLoggedInResponseException $e) { $this->error('Could not log you in with user authentication details provided'); return false; } $this->ip2LocLite->downloadCsv($database); $this->info('Latest version of IP2Location database ' . $database . ' has been downloaded'); } }
Change lint errors to warnings
module.exports = { root: true, parserOptions: { ecmaVersion: 2017, sourceType: 'module' }, plugins: [ 'ember' ], extends: [ 'eslint:recommended', 'plugin:ember/recommended' ], env: { browser: true }, rules: { 'no-console': 'warn' }, overrides: [ // node files { files: [ 'index.js', 'testem.js', 'ember-cli-build.js', 'config/**/*.js', 'tests/dummy/config/**/*.js' ], excludedFiles: [ 'app/**', 'addon/**', 'tests/dummy/app/**' ], parserOptions: { sourceType: 'script', ecmaVersion: 2015 }, env: { browser: false, node: true }, plugins: ['node'], rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, { // add your custom rules and overrides for node files here }) }, // test files { files: ['tests/**/*.js'], excludedFiles: ['tests/dummy/**/*.js'], env: { embertest: true }, rules: { 'ember/new-module-imports': 'warn' } } ] };
module.exports = { root: true, parserOptions: { ecmaVersion: 2017, sourceType: 'module' }, plugins: [ 'ember' ], extends: [ 'eslint:recommended', 'plugin:ember/recommended' ], env: { browser: true }, rules: { }, overrides: [ // node files { files: [ 'index.js', 'testem.js', 'ember-cli-build.js', 'config/**/*.js', 'tests/dummy/config/**/*.js' ], excludedFiles: [ 'app/**', 'addon/**', 'tests/dummy/app/**' ], parserOptions: { sourceType: 'script', ecmaVersion: 2015 }, env: { browser: false, node: true }, plugins: ['node'], rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, { // add your custom rules and overrides for node files here }) }, // test files { files: ['tests/**/*.js'], excludedFiles: ['tests/dummy/**/*.js'], env: { embertest: true } } ] };
Update closest match adapter docstring.
# -*- coding: utf-8 -*- from fuzzywuzzy import fuzz from .base_match import BaseMatchAdapter class ClosestMatchAdapter(BaseMatchAdapter): """ The ClosestMatchAdapter logic adapter selects a known response to an input by searching for a known statement that most closely matches the input based on the Levenshtein Distance between the text of each statement. """ def get(self, input_statement): """ Takes a statement string and a list of statement strings. Returns the closest matching statement from the list. """ statement_list = self.context.storage.get_response_statements() if not statement_list: if self.has_storage_context: # Use a randomly picked statement self.logger.info( u'No statements have known responses. ' + u'Choosing a random response to return.' ) return 0, self.context.storage.get_random() else: raise self.EmptyDatasetException() confidence = -1 closest_match = input_statement # Find the closest matching known statement for statement in statement_list: ratio = fuzz.ratio(input_statement.text.lower(), statement.text.lower()) if ratio > confidence: confidence = ratio closest_match = statement # Convert the confidence integer to a percent confidence /= 100.0 return confidence, closest_match
# -*- coding: utf-8 -*- from fuzzywuzzy import fuzz from .base_match import BaseMatchAdapter class ClosestMatchAdapter(BaseMatchAdapter): """ The ClosestMatchAdapter logic adapter creates a response by using fuzzywuzzy's process class to extract the most similar response to the input. This adapter selects a response to an input statement by selecting the closest known matching statement based on the Levenshtein Distance between the text of each statement. """ def get(self, input_statement): """ Takes a statement string and a list of statement strings. Returns the closest matching statement from the list. """ statement_list = self.context.storage.get_response_statements() if not statement_list: if self.has_storage_context: # Use a randomly picked statement self.logger.info( u'No statements have known responses. ' + u'Choosing a random response to return.' ) return 0, self.context.storage.get_random() else: raise self.EmptyDatasetException() confidence = -1 closest_match = input_statement # Find the closest matching known statement for statement in statement_list: ratio = fuzz.ratio(input_statement.text.lower(), statement.text.lower()) if ratio > confidence: confidence = ratio closest_match = statement # Convert the confidence integer to a percent confidence /= 100.0 return confidence, closest_match
Add email field to subscription db model.
'use strict'; const BaseRepository = require('@gfcc/mongo-tenant-repository/BaseRepository'); class SubscriptionRepository extends BaseRepository { getSchemaDefinition() { return { subscriberId: { type: String, required: true, index: true, }, releaseNotesId: { type: String, required: true, index: true, }, releaseNotesScope: { type: String, required: true, index: true, }, releaseNotesName: { type: String, required: true, }, email: { type: String, }, }; } /** * Lookup all subscriptions of the given subscriber. * * @param {string} subscriberId * @param {function} callback * @return {SubscriptionRepository} */ findBySubscriberId(subscriberId, callback) { return this.find({ subscriberId, }, callback); } /** * Lookup all subscriptions of a subscriber on a specific release notes. * * @param subscriberId * @param releaseNotesScope * @param releaseNotesName * @param callback * @return {BaseRepository} */ findBySubscriberAndReleaseNotes({ subscriberId, releaseNotesScope, releaseNotesName }, callback) { return this.find({ subscriberId, releaseNotesScope, releaseNotesName, }, callback); } } module.exports = SubscriptionRepository;
'use strict'; const BaseRepository = require('@gfcc/mongo-tenant-repository/BaseRepository'); class SubscriptionRepository extends BaseRepository { getSchemaDefinition() { return { subscriberId: { type: String, required: true, index: true, }, releaseNotesId: { type: String, required: true, index: true, }, releaseNotesScope: { type: String, required: true, index: true, }, releaseNotesName: { type: String, required: true, } }; } /** * Lookup all subscriptions of the given subscriber. * * @param {string} subscriberId * @param {function} callback * @return {SubscriptionRepository} */ findBySubscriberId(subscriberId, callback) { return this.find({ subscriberId, }, callback); } /** * Lookup all subscriptions of a subscriber on a specific release notes. * * @param subscriberId * @param releaseNotesScope * @param releaseNotesName * @param callback * @return {BaseRepository} */ findBySubscriberAndReleaseNotes({ subscriberId, releaseNotesScope, releaseNotesName }, callback) { return this.find({ subscriberId, releaseNotesScope, releaseNotesName, }, callback); } } module.exports = SubscriptionRepository;
Replace uneccessary .replace syntax in aria-labelledby attribute
// @flow import React from 'react'; import type { Node } from 'react'; import classNames from 'classnames'; import { inject, observer } from 'mobx-react'; import { type Store } from '../accordionStore/accordionStore'; const defaultProps = { className: 'accordion__body', hideBodyClassName: 'accordion__body--hidden', }; type AccordionItemBodyProps = { children: Node, className: string, hideBodyClassName: string, accordionStore: Store, uuid: string | number, }; const AccordionItemBody = (props: AccordionItemBodyProps) => { const { uuid, children, className, hideBodyClassName } = props; const { items, accordion } = props.accordionStore; const foundItem = items.find(item => item.uuid === uuid); if (!foundItem) return null; const { expanded } = foundItem; const id = `accordion__body-${uuid}`; const ariaLabelledby = `accordion__title-${uuid}`; const role = accordion ? 'tabpanel' : null; const bodyClass = classNames(className, { [hideBodyClassName]: !expanded, }); const ariaHidden = !expanded; return ( <div id={id} className={bodyClass} aria-hidden={ariaHidden} aria-labelledby={ariaLabelledby} role={role} > {children} </div> ); }; AccordionItemBody.defaultProps = defaultProps; export default inject('accordionStore', 'uuid')(observer(AccordionItemBody));
// @flow import React from 'react'; import type { Node } from 'react'; import classNames from 'classnames'; import { inject, observer } from 'mobx-react'; import { type Store } from '../accordionStore/accordionStore'; const defaultProps = { className: 'accordion__body', hideBodyClassName: 'accordion__body--hidden', }; type AccordionItemBodyProps = { children: Node, className: string, hideBodyClassName: string, accordionStore: Store, uuid: string | number, }; const AccordionItemBody = (props: AccordionItemBodyProps) => { const { uuid, children, className, hideBodyClassName } = props; const { items, accordion } = props.accordionStore; const foundItem = items.find(item => item.uuid === uuid); if (!foundItem) return null; const { expanded } = foundItem; const id = `accordion__body-${uuid}`; const role = accordion ? 'tabpanel' : null; const bodyClass = classNames(className, { [hideBodyClassName]: !expanded, }); const ariaHidden = !expanded; return ( <div id={id} className={bodyClass} aria-hidden={ariaHidden} aria-labelledby={id.replace( 'accordion__body-', 'accordion__title-', )} role={role} > {children} </div> ); }; AccordionItemBody.defaultProps = defaultProps; export default inject('accordionStore', 'uuid')(observer(AccordionItemBody));
Use the env prefix setting
import os import pydot from kitchen.settings import STATIC_ROOT, REPO def generate_node_map(nodes): """Generates a graphviz nodemap""" graph = pydot.Dot(graph_type='digraph') graph_nodes = {} for node in nodes: label = node['name'] + "\n" + "\n".join( [role for role in node['role'] \ if not role.startswith(REPO['ENV_PREFIX'])]) node_el = pydot.Node(label, style="filled", fillcolor="red") graph_nodes[node['name']] = node_el graph.add_node(node_el) for node in nodes: for attr in node.keys(): if isinstance(node[attr], dict) and 'client_roles' in node[attr]: for client_node in nodes: if set.intersection(set(node[attr]['client_roles']), set(client_node['roles'])): graph.add_edge(pydot.Edge( graph_nodes[client_node['name']], graph_nodes[node['name']])) keys = graph_nodes.keys() graph.add_edge(pydot.Edge(graph_nodes[keys[3]], graph_nodes[keys[5]])) graph.write_png(os.path.join(STATIC_ROOT, 'img', 'node_map.png'))
import os import pydot from kitchen.settings import STATIC_ROOT def generate_node_map(nodes): """Generates a graphviz nodemap""" graph = pydot.Dot(graph_type='digraph') graph_nodes = {} for node in nodes: label = node['name'] + "\n" + "\n".join( [role for role in node['role'] if not role.startswith("env")]) node_el = pydot.Node(label, style="filled", fillcolor="red") graph_nodes[node['name']] = node_el graph.add_node(node_el) for node in nodes: for attr in node.keys(): if isinstance(node[attr], dict) and 'client_roles' in node[attr]: for client_node in nodes: if set.intersection(set(node[attr]['client_roles']), set(client_node['roles'])): graph.add_edge(pydot.Edge( graph_nodes[client_node['name']], graph_nodes[node['name']])) keys = graph_nodes.keys() graph.add_edge(pydot.Edge(graph_nodes[keys[3]], graph_nodes[keys[5]])) graph.write_png(os.path.join(STATIC_ROOT, 'img', 'node_map.png'))