text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Convert function to a one-liner. See #1121.
const ascension = require('ascension') const sort = ascension([ Number ], entry => [ entry.when ]) const Isochronous = require('isochronous') class Printer { constructor (destructible, write, format, interval) { this._write = write this._entries = [] this._format = format const isochronous = new Isochronous(interval, true, this._check.bind(this)) destructible.durable('isochronous', isochronous.start()) destructible.destruct(() => isochronous.stop()) destructible.destruct(() => this._log(this._entries.splice(0).sort(sort))) } say (label, entry) { this._entries.push({ when: Date.now(), qualifier: 'prolific', label, ...entry }) } push (envelope) { this._entries.push.apply(this._entries, envelope.entries) } _log (entries) { if (entries.length != 0) { this._write.call(null, entries.map(this._format).join('\n')) } } _check (status) { this._entries.sort(sort) const stop = status.scheduled - Math.ceil(status.interval * 1.51) let i, I for (i = 0, I = this._entries.length; i < I; i++) { if (this._entries[i].when > stop) { break } } this._log(this._entries.splice(0, i)) } } module.exports = Printer
const ascension = require('ascension') const sort = ascension([ Number ], entry => [ entry.when ]) const Isochronous = require('isochronous') class Printer { constructor (destructible, write, format, interval) { this._write = write this._entries = [] this._format = format const isochronous = new Isochronous(interval, true, this._check.bind(this)) destructible.durable('isochronous', isochronous.start()) destructible.destruct(() => isochronous.stop()) destructible.destruct(() => { this._entries.sort(sort) this._log(this._entries.splice(0)) }) } say (label, entry) { this._entries.push({ when: Date.now(), qualifier: 'prolific', label, ...entry }) } push (envelope) { this._entries.push.apply(this._entries, envelope.entries) } _log (entries) { if (entries.length != 0) { this._write.call(null, entries.map(this._format).join('\n')) } } _check (status) { this._entries.sort(sort) const stop = status.scheduled - Math.ceil(status.interval * 1.51) let i, I for (i = 0, I = this._entries.length; i < I; i++) { if (this._entries[i].when > stop) { break } } this._log(this._entries.splice(0, i)) } } module.exports = Printer
Hide create analysis modal on success
import React, { PropTypes } from "react"; import { Modal } from "react-bootstrap"; import { AlgorithmSelect, Button } from "virtool/js/components/Base"; const getInitialState = () => ({ algorithm: "pathoscope_bowtie" }); export default class CreateAnalysis extends React.Component { constructor (props) { super(props); this.state = getInitialState(); } static propTypes = { show: PropTypes.bool, sampleId: PropTypes.string, onSubmit: PropTypes.func, onHide: PropTypes.func }; handleSubmit = (event) => { event.preventDefault(); this.props.onSubmit(this.props.sampleId, this.state.algorithm); this.props.onHide(); }; render = () => ( <Modal show={this.props.show} onHide={this.props.onHide} onExited={() => this.setState(getInitialState())}> <Modal.Header> New Analysis </Modal.Header> <form onSubmit={this.handleSubmit}> <Modal.Body> <div className="toolbar"> <AlgorithmSelect value={this.state.algorithm} onChange={(e) => this.setState({algorithm: e.target.value})} /> </div> </Modal.Body> <Modal.Footer> <Button type="submit" bsStyle="primary" icon="play" > Start </Button> </Modal.Footer> </form> </Modal> ); }
import React, { PropTypes } from "react"; import { Modal } from "react-bootstrap"; import { AlgorithmSelect, Button } from "virtool/js/components/Base"; const getInitialState = () => ({ algorithm: "pathoscope_bowtie" }); export default class CreateAnalysis extends React.Component { constructor (props) { super(props); this.state = getInitialState(); } static propTypes = { show: PropTypes.bool, sampleId: PropTypes.string, onSubmit: PropTypes.func }; handleSubmit = (event) => { event.preventDefault(); this.props.onSubmit(this.props.sampleId, this.state.algorithm); this.onHide(); }; render = () => ( <Modal show={this.props.show} onHide={this.props.onHide} onExited={() => this.setState(getInitialState())}> <Modal.Header> New Analysis </Modal.Header> <form onSubmit={this.handleSubmit}> <Modal.Body> <div className="toolbar"> <AlgorithmSelect value={this.state.algorithm} onChange={(e) => this.setState({algorithm: e.target.value})} /> </div> </Modal.Body> <Modal.Footer> <Button type="submit" bsStyle="primary" icon="play" > Start </Button> </Modal.Footer> </form> </Modal> ); }
Make ball fall through bottom wall again
/* * This class handles collisions. */ 'use strict'; import Vector from 'Vector.js'; export default class { constructor(actorsInstance) { this._actorsInstance = actorsInstance; this._canvasObj = {}; } moveComputerActors(canvasWidth, canvasHeight) { let actors = this._actorsInstance.get(); for (let actorName in actors) { let actor = actors[actorName]; if (Array.isArray(actor)) { actor.forEach((a)=> a.computer ? a.move():null); } else { actor.computer ? actor.move():null; } } this._actorsInstance.update(actors); this._handleCollision(canvasWidth, canvasHeight, actors); } // Handles both ball, brick, paddle, and wall collisions. // TODO: Implement real collision detection. _handleCollision(canvasWidth, canvasHeight, actors) { // Extremely simple collision detection only // for balls. for (let actorName in actors) { if (actorName === 'balls') { actors[actorName].forEach((ball)=> { let futureX = ball.position.x + ball.velocity.x; let futureY = ball.position.y + ball.velocity.y; if (futureX > canvasWidth - ball.radius || futureX < ball.radius) { ball.velocity.flipVertically(); } if (futureY < ball.radius) { ball.velocity.flipHorizontally(); } }); } } } }
/* * This class handles collisions. */ 'use strict'; import Vector from 'Vector.js'; export default class { constructor(actorsInstance) { this._actorsInstance = actorsInstance; this._canvasObj = {}; } moveComputerActors(canvasWidth, canvasHeight) { let actors = this._actorsInstance.get(); for (let actorName in actors) { let actor = actors[actorName]; if (Array.isArray(actor)) { actor.forEach((a)=> a.computer ? a.move():null); } else { actor.computer ? actor.move():null; } } this._actorsInstance.update(actors); this._handleCollision(canvasWidth, canvasHeight, actors); } // Handles both ball, brick, paddle, and wall collisions. // TODO: Implement real collision detection. _handleCollision(canvasWidth, canvasHeight, actors) { // Extremely simple collision detection only // for balls. for (let actorName in actors) { if (actorName === 'balls') { actors[actorName].forEach((ball)=> { let futureX = ball.position.x + ball.velocity.x; let futureY = ball.position.y + ball.velocity.y; if (futureX > canvasWidth - ball.radius || futureX < ball.radius) { ball.velocity.flipVertically(); } if (futureY > canvasHeight - ball.radius || futureY < ball.radius) { ball.velocity.flipHorizontally(); } }); } } } }
Add helpers for obtain indexes to connection manager.
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from threading import local from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import utils from . import base class ConnectionManager(object): def __init__(self): self._connections = local() def load_backend(self, alias="default"): try: conf = getattr(settings, "NEEDLESTACK_CONNECTIONS") except AttributeError as e: raise ImproperlyConfigured("needlestack not configured") from e if alias not in conf: raise ImproperlyConfigured("connection with alias {0} " "does not exists".format(alias)) _conf = conf[alias] cls = utils.load_class(_conf["engine"]) params = _conf["options"] return (cls, params) def get_connection(self, alias="default"): if hasattr(self._connections, alias): return getattr(self._connections, alias) cls, params = self.load_backend(alias) instance = cls(**params) setattr(self._connections, alias, instance) return instance def get_all_indexes(self): base._load_all_indexes() return base._get_all_indexes() def get_index_by_name(self, name): base._load_all_indexes() return base._get_index_by_name(name) def __getattr__(self, alias): return self.get_connection(alias) manager = ConnectionManager()
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from threading import local from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import utils class ConnectionManager(object): def __init__(self): self._connections = local() def load_backend(self, alias="default"): try: conf = getattr(settings, "NEEDLESTACK_CONNECTIONS") except AttributeError as e: raise ImproperlyConfigured("needlestack not configured") from e if alias not in conf: raise ImproperlyConfigured("connection with alias {0} " "does not exists".format(alias)) _conf = conf[alias] cls = utils.load_class(_conf["engine"]) params = _conf["options"] return (cls, params) def get_connection(self, alias="default"): if hasattr(self._connections, alias): return getattr(self._connections, alias) cls, params = self.load_backend(alias) instance = cls(**params) setattr(self._connections, alias, instance) return instance def __getattr__(self, alias): return self.get_connection(alias) manager = ConnectionManager()
Use Amp\call to run tasks Handles generator to coroutine convertion and React promises automatically.
<?php namespace Amp\Parallel\Worker\Internal; use Amp\Coroutine; use Amp\Parallel\Sync\Channel; use Amp\Parallel\Worker\Environment; use Amp\Promise; use function Amp\call; class TaskRunner { /** @var \Amp\Parallel\Sync\Channel */ private $channel; /** @var \Amp\Parallel\Worker\Environment */ private $environment; public function __construct(Channel $channel, Environment $environment) { $this->channel = $channel; $this->environment = $environment; } /** * Runs the task runner, receiving tasks from the parent and sending the result of those tasks. * * @return \Amp\Promise */ public function run(): Promise { return new Coroutine($this->execute()); } /** * @coroutine * * @return \Generator */ private function execute(): \Generator { $job = yield $this->channel->receive(); while ($job instanceof Job) { $task = $job->getTask(); $result = call([$task, 'run'], $this->environment); $result->onResolve(function ($exception, $value) use ($job) { if ($exception) { $result = new TaskFailure($job->getId(), $exception); } else { $result = new TaskSuccess($job->getId(), $value); } $this->channel->send($result); }); $job = yield $this->channel->receive(); } return $job; } }
<?php namespace Amp\Parallel\Worker\Internal; use Amp\Coroutine; use Amp\Failure; use Amp\Parallel\Sync\Channel; use Amp\Parallel\Worker\Environment; use Amp\Promise; use Amp\Success; class TaskRunner { /** @var \Amp\Parallel\Sync\Channel */ private $channel; /** @var \Amp\Parallel\Worker\Environment */ private $environment; public function __construct(Channel $channel, Environment $environment) { $this->channel = $channel; $this->environment = $environment; } /** * Runs the task runner, receiving tasks from the parent and sending the result of those tasks. * * @return \Amp\Promise */ public function run(): Promise { return new Coroutine($this->execute()); } /** * @coroutine * * @return \Generator */ private function execute(): \Generator { $job = yield $this->channel->receive(); while ($job instanceof Job) { $task = $job->getTask(); try { $result = $task->run($this->environment); if ($result instanceof \Generator) { $result = new Coroutine($result); } if (!$result instanceof Promise) { $result = new Success($result); } } catch (\Throwable $exception) { $result = new Failure($exception); } $result->onResolve(function ($exception, $value) use ($job) { if ($exception) { $result = new TaskFailure($job->getId(), $exception); } else { $result = new TaskSuccess($job->getId(), $value); } $this->channel->send($result); }); $job = yield $this->channel->receive(); } return $job; } }
Update for new node definition syntax
import base64 import json import Queue import time import logging from boto import sns from boto import sqs from boto.sqs.message import Message, RawMessage from nanomon.utils import yaml_includes from nanomon.message import NanoMessage from nanomon.queue import QueueWorker from nanomon.queue.backends.sns_sqs import SQSQueue, SNSTopic logger = logging.getLogger(__name__) class YamlNodeBackend(object): def __init__(self, path): self.path = path def get_nodes(self): logger.debug("Loading node config from %s" % (self.path)) return yaml_includes.load_config(self.path) class Scheduler(QueueWorker): def __init__(self, node_backend, topic, queue): self.node_backend = node_backend super(Scheduler, self).__init__(topic, queue) def run(self, sleep=300): while True: start = time.time() sleep = float(sleep) nodes = self.node_backend.get_nodes() for node in nodes: task = json.dumps(node) logger.debug("Sending task for node '%s'." % (node['name'])) self.send_task(task) real_sleep = sleep - (time.time() - start) if real_sleep <= 0: continue logger.debug("Sleeping for %.02f." % (real_sleep)) time.sleep(real_sleep)
import base64 import json import Queue import time import logging from boto import sns from boto import sqs from boto.sqs.message import Message, RawMessage from nanomon.utils import yaml_includes from nanomon.message import NanoMessage from nanomon.queue import QueueWorker from nanomon.queue.backends.sns_sqs import SQSQueue, SNSTopic logger = logging.getLogger(__name__) class YamlNodeBackend(object): def __init__(self, path): self.path = path def get_nodes(self): logger.debug("Loading node config from %s" % (self.path)) return yaml_includes.load_config(self.path) class Scheduler(QueueWorker): def __init__(self, node_backend, topic, queue): self.node_backend = node_backend super(Scheduler, self).__init__(topic, queue) def run(self, sleep=300): while True: start = time.time() sleep = float(sleep) nodes = self.node_backend.get_nodes() for node, settings in nodes.iteritems(): task = json.dumps({node: settings}) logger.debug("Sending task for node '%s'." % (node)) self.send_task(task) real_sleep = sleep - (time.time() - start) if real_sleep <= 0: continue logger.debug("Sleeping for %.02f." % (real_sleep)) time.sleep(real_sleep)
Refactor encoders to have base class
import datetime import decimal import logging import elasticsearch from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) class JSONEncoderMixin(object): def default(self, obj): if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) return super(JSONEncoderMixin, self).default(obj) class JSONEncoder(JSONEncoderMixin, _JSONEncoder): def default(self, obj): if hasattr(obj, 'to_dict'): # If it got to this point, it means its a nested object. # Outter objects would have been handled with DataProxy. return obj.to_dict(__nested=True) return super(JSONEncoder, self).default(obj) class ESJSONSerializer(JSONEncoderMixin, elasticsearch.serializer.JSONSerializer): def default(self, obj): try: return super(ESJSONSerializer, self).default(obj) except: import traceback log.error(traceback.format_exc())
import datetime import decimal import logging import elasticsearch from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) class JSONEncoder(_JSONEncoder): def default(self, obj): if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) if hasattr(obj, 'to_dict'): # If it got to this point, it means its a nested object. # Outter objects would have been handled with DataProxy. return obj.to_dict(__nested=True) return super(JSONEncoder, self).default(obj) class ESJSONSerializer(elasticsearch.serializer.JSONSerializer): def default(self, obj): if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) try: return super(ESJSONSerializer, self).default(obj) except: import traceback log.error(traceback.format_exc())
Remove showing of actual internal error to user and show in log instead
/** * Created by Omnius on 03/08/2016. */ 'use strict'; const Boom = require('boom'); module.exports = () => { return (request, reply) => { const server = request.server; const redis = request.redis; const dao = server.methods.dao; const userDao = dao.userDao; const authCredentials = request.auth.credentials; const userId = authCredentials.userId; const credentials = { hawkSessionToken: authCredentials.hawkSessionToken, algorithm: authCredentials.algorithm, userId: userId }; userDao.readUsername(redis, userId, (err, username) => { if (err) { server.log(err); return reply(Boom.internal()); } const details = { userId: userId, username: username }; return reply.view('welcome', details) .state('Hawk-Session-Token', credentials) .header('Cache-Control', 'no-cache, no-store, must-revalidate'); }); }; };
/** * Created by Omnius on 03/08/2016. */ 'use strict'; const Boom = require('boom'); module.exports = () => { return (request, reply) => { const server = request.server; const redis = request.redis; const dao = server.methods.dao; const userDao = dao.userDao; const authCredentials = request.auth.credentials; const userId = authCredentials.userId; const credentials = { hawkSessionToken: authCredentials.hawkSessionToken, algorithm: authCredentials.algorithm, userId: userId }; userDao.readUsername(redis, userId, (err, username) => { if (err) { server.log(err); return reply(Boom.internal(err)); } const details = { userId: userId, username: username }; return reply.view('welcome', details) .state('Hawk-Session-Token', credentials) .header('Cache-Control', 'no-cache, no-store, must-revalidate'); }); }; };
Allow use of alternate Django test cases
from __future__ import absolute_import from django.test import TestCase as dTestCase from django.test import SimpleTestCase as dSimpleTestCase from django.test.runner import DiscoverRunner from snapshottest.reporting import reporting_lines from .unittest import TestCase as uTestCase class TestRunner(DiscoverRunner): separator1 = "=" * 70 separator2 = "-" * 70 def __init__(self, snapshot_update=False, **kwargs): super(TestRunner, self).__init__(**kwargs) uTestCase.snapshot_should_update = snapshot_update @classmethod def add_arguments(cls, parser): super(TestRunner, cls).add_arguments(parser) parser.add_argument( '--snapshot-update', default=False, action='store_true', dest='snapshot_update', help='Update the snapshots automatically.', ) def run_tests(self, test_labels, extra_tests=None, **kwargs): result = super(TestRunner, self).run_tests( test_labels=test_labels, extra_tests=extra_tests, **kwargs ) self.print_report() return result def print_report(self): print("\n" + self.separator1) print('SnapshotTest summary') print(self.separator2) for line in reporting_lines('python manage.py test'): print(line) print(self.separator1) class TestCase(uTestCase, dTestCase): pass class SimpleTestCase(uTestCase, dSimpleTestCase): pass
from __future__ import absolute_import from django.test import TestCase as dTestCase from django.test.runner import DiscoverRunner from snapshottest.reporting import reporting_lines from .unittest import TestCase as uTestCase class TestRunner(DiscoverRunner): separator1 = "=" * 70 separator2 = "-" * 70 def __init__(self, snapshot_update=False, **kwargs): super(TestRunner, self).__init__(**kwargs) TestCase.snapshot_should_update = snapshot_update @classmethod def add_arguments(cls, parser): super(TestRunner, cls).add_arguments(parser) parser.add_argument( '--snapshot-update', default=False, action='store_true', dest='snapshot_update', help='Update the snapshots automatically.', ) def run_tests(self, test_labels, extra_tests=None, **kwargs): result = super(TestRunner, self).run_tests( test_labels=test_labels, extra_tests=extra_tests, **kwargs ) self.print_report() return result def print_report(self): print("\n" + self.separator1) print('SnapshotTest summary') print(self.separator2) for line in reporting_lines('python manage.py test'): print(line) print(self.separator1) class TestCase(uTestCase, dTestCase): pass
Fix duration formatting in status chart Numbers were not zero padded.
angular.module('ocWebGui.statusChart.service', ['ngResource']) .factory('AgentStatusStats', function ($http) { return { stats: function (startDate, endDate, reportType) { return $http.post('agent_statuses/stats', { report_type: reportType, team_name: 'Helpdesk', start_date: startDate, end_date: endDate }); } }; }) .factory('StatusChart', function (CustomDate) { return { options: function () { return { chart: { type: 'multiChart', bars1: { stacked: true }, height: 600, margin: { left: 150 }, x: function (d) { return d.hour; }, y: function (d) { return d.value; }, yAxis1: { tickFormat: function (seconds) { return CustomDate.niceFormatting(seconds); } } } }; } }; });
angular.module('ocWebGui.statusChart.service', ['ngResource']) .factory('AgentStatusStats', function ($http) { return { stats: function (startDate, endDate, reportType) { return $http.post('agent_statuses/stats', { report_type: reportType, team_name: 'Helpdesk', start_date: startDate, end_date: endDate }); } }; }) .factory('StatusChart', function () { return { options: function () { return { chart: { type: 'multiChart', bars1: { stacked: true }, height: 600, margin: { left: 150 }, x: function (d) { return d.hour; }, y: function (d) { return d.value; }, yAxis1: { tickFormat: function (seconds) { var hours = Math.floor(seconds / 3600); var mins = Math.floor(seconds % 3600 / 60); var secs = seconds % 3600 % 60; return hours + ':' + mins + ':' + secs; } } } }; } }; });
Use best practice for array emptiness check
<?php namespace Dotenv\Store; use Dotenv\Exception\InvalidPathException; use Dotenv\Store\File\Reader; class FileStore implements StoreInterface { /** * The file paths. * * @var string[] */ protected $filePaths; /** * Should file loading short circuit? * * @var bool */ protected $shortCircuit; /** * Create a new file store instance. * * @param string[] $filePaths * @param bool $shortCircuit * * @return void */ public function __construct(array $filePaths, $shortCircuit) { $this->filePaths = $filePaths; $this->shortCircuit = $shortCircuit; } /** * Read the content of the environment file(s). * * @throws \Dotenv\Exception\InvalidPathException * * @return string */ public function read() { if ($this->filePaths === []) { throw new InvalidPathException('At least one environment file path must be provided.'); } $contents = Reader::read($this->filePaths, $this->shortCircuit); if (count($contents) > 0) { return implode("\n", $contents); } throw new InvalidPathException( sprintf('Unable to read any of the environment file(s) at [%s].', implode(', ', $this->filePaths)) ); } }
<?php namespace Dotenv\Store; use Dotenv\Exception\InvalidPathException; use Dotenv\Store\File\Reader; class FileStore implements StoreInterface { /** * The file paths. * * @var string[] */ protected $filePaths; /** * Should file loading short circuit? * * @var bool */ protected $shortCircuit; /** * Create a new file store instance. * * @param string[] $filePaths * @param bool $shortCircuit * * @return void */ public function __construct(array $filePaths, $shortCircuit) { $this->filePaths = $filePaths; $this->shortCircuit = $shortCircuit; } /** * Read the content of the environment file(s). * * @throws \Dotenv\Exception\InvalidPathException * * @return string */ public function read() { if ($this->filePaths === []) { throw new InvalidPathException('At least one environment file path must be provided.'); } $contents = Reader::read($this->filePaths, $this->shortCircuit); if ($contents) { return implode("\n", $contents); } throw new InvalidPathException( sprintf('Unable to read any of the environment file(s) at [%s].', implode(', ', $this->filePaths)) ); } }
Adjust områder request query params to only get published and DNT official områder
/** * GET home page */ module.exports = function (app, options) { "use strict"; var underscore = require('underscore'); var userGroupsFetcher = options.userGroupsFetcher; var restProxy = options.restProxy; /** * GET list of routes (index page) */ var getRoutesIndex = function (req, res) { var userGroups = req.userGroups || []; var userDefaultRouteFetchQuery = (!!req.signedCookies) ? req.signedCookies['userDefaultRouteFetchQuery_' + req.session.userId] : undefined; var onCompleteOmraderRequest = function (data) { var areas = data.documents; var renderOptions = { title: 'Mine turer', areas: JSON.stringify(areas), userData: JSON.stringify(req.session.user), userGroups: JSON.stringify(userGroups), userDefaultRouteFetchQuery: JSON.stringify(userDefaultRouteFetchQuery), authType: req.session.authType, itemType: 'tur' }; res.render('routes/index', renderOptions); }; restProxy.makeApiRequest('/områder/?limit=100&fields=navn,_id&sort=navn&tilbyder=DNT&status=Offentlig', req, undefined, onCompleteOmraderRequest); }; app.get('/turer', userGroupsFetcher); app.get('/turer', getRoutesIndex); };
/** * GET home page */ module.exports = function (app, options) { "use strict"; var underscore = require('underscore'); var userGroupsFetcher = options.userGroupsFetcher; var restProxy = options.restProxy; /** * GET list of routes (index page) */ var getRoutesIndex = function (req, res) { var userGroups = req.userGroups || []; var userDefaultRouteFetchQuery = (!!req.signedCookies) ? req.signedCookies['userDefaultRouteFetchQuery_' + req.session.userId] : undefined; var onCompleteOmraderRequest = function (data) { var areas = data.documents; var renderOptions = { title: 'Mine turer', areas: JSON.stringify(areas), userData: JSON.stringify(req.session.user), userGroups: JSON.stringify(userGroups), userDefaultRouteFetchQuery: JSON.stringify(userDefaultRouteFetchQuery), authType: req.session.authType, itemType: 'tur' }; res.render('routes/index', renderOptions); }; restProxy.makeApiRequest('/områder/?limit=100&fields=navn,_id&sort=navn', req, undefined, onCompleteOmraderRequest); }; app.get('/turer', userGroupsFetcher); app.get('/turer', getRoutesIndex); };
Fix winmonitor script wrapper specification
import setuptools from simplemonitor.version import VERSION with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="simplemonitor", version=VERSION, author="James Seward", author_email="[email protected]", description="A simple network and host monitor", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/jamesoff/simplemonitor", packages=setuptools.find_packages(exclude="tests"), package_data={ "simplemonitor": ["html/header.html", "html/footer.html", "html/style.css"] }, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Environment :: No Input/Output (Daemon)", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", "Topic :: System :: Monitoring", "Typing :: Typed", ], python_requires=">=3.5", entry_points={ "console_scripts": [ "simplemonitor=simplemonitor.monitor:main", "winmonitor=simplemonitor.winmonitor:main", ] }, extras_require={"nc": ["pync"], "ring": ["ring-doorbell>=0.6.0"]}, install_requires=["requests", "boto3", "pyOpenSSL", "colorlog", "paho-mqtt"], )
import setuptools from simplemonitor.version import VERSION with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="simplemonitor", version=VERSION, author="James Seward", author_email="[email protected]", description="A simple network and host monitor", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/jamesoff/simplemonitor", packages=setuptools.find_packages(exclude="tests"), package_data={ "simplemonitor": ["html/header.html", "html/footer.html", "html/style.css"] }, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Environment :: No Input/Output (Daemon)", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", "Topic :: System :: Monitoring", "Typing :: Typed", ], python_requires=">=3.5", entry_points={ "console_scripts": [ "simplemonitor=simplemonitor.monitor:main", "winmonitor=simplemonitor.winmonitor.main", ] }, extras_require={"nc": ["pync"], "ring": ["ring-doorbell>=0.6.0"]}, install_requires=["requests", "boto3", "pyOpenSSL", "colorlog", "paho-mqtt"], )
Use proper placeholders for future functionalities
const {i18n, React} = Serverboards import Details from '../containers/details' class DetailsTab extends React.Component{ constructor(props){ super(props) this.state={ tab: "details" } } render(){ let Section = () => null const section = this.state.tab switch(section){ case "details": Section=Details break; } return ( <div className="ui expand with right side menu"> <Section {...this.props}/> <div className="ui side menu"> <a className={`item ${section == "details" ? "active" : ""}`} data-tooltip={i18n("Details")} data-position="left center" onClick={() => this.setState({tab:"details"})} > <i className="file text outline icon"></i> </a> <a className={`item ${section == "ssh" ? "active" : ""}`} data-tooltip={i18n("SSH Remote Terminal")} data-position="left center" onClick={() => this.setState({tab:"ssh"})} > <i className="code icon"></i> </a> <a className={`item ${section == "remote_desktop" ? "active" : ""}`} data-tooltip={i18n("Remote Desktop")} data-position="left center" onClick={() => this.setState({tab:"remote_desktop"})} > <i className="desktop icon"></i> </a> </div> </div> ) } } export default DetailsTab
const {i18n, React} = Serverboards import Details from '../containers/details' class DetailsTab extends React.Component{ constructor(props){ super(props) this.state={ tab: "details" } } render(){ let Section = () => null const section = this.state.tab switch(section){ case "details": Section=Details break; } return ( <div className="ui expand with right side menu"> <Section {...this.props}/> <div className="ui side menu"> <a className={`item ${section == "details" ? "active" : ""}`} data-tooltip={i18n("Details")} data-position="left center" onClick={() => this.setState({tab:"details"})} > <i className="file text outline icon"></i> </a> <a className={`item ${section == "edit" ? "active" : ""}`} data-tooltip={i18n("Edit")} data-position="left center" onClick={() => this.setState({tab:"edit"})} > <i className="code icon"></i> </a> <a className={`item ${section == "logs" ? "active" : ""}`} data-tooltip={i18n("Logs")} data-position="left center" onClick={() => this.setState({tab:"logs"})} > <i className="desktop icon"></i> </a> </div> </div> ) } } export default DetailsTab
Handle empty location and leads data
from django import forms from django.core.exceptions import ValidationError from wye.profiles.models import UserType from . import models class RegionalLeadForm(forms.ModelForm): class Meta: model = models.RegionalLead exclude = () def clean(self): error_message = [] if (self.cleaned_data.get('location', '') and self.cleaned_data.get('leads', '')): location = self.cleaned_data['location'] for u in self.cleaned_data['leads']: if not u.profile: error_message.append('Profile for user %s not found' % (u)) elif u.profile.location != location: error_message.append( "User %s doesn't belong to region %s" % (u, location)) if error_message: raise ValidationError(error_message) def save(self, force_insert=False, force_update=False, commit=True): m = super(RegionalLeadForm, self).save(commit=False) for u in self.cleaned_data['leads']: u.profile.usertype.add(UserType.objects.get(slug='lead')) return m class LocationForm(forms.ModelForm): class Meta: model = models.Location exclude = () class StateForm(forms.ModelForm): class Meta: model = models.State exclude = ()
from django import forms from django.core.exceptions import ValidationError from wye.profiles.models import UserType from . import models class RegionalLeadForm(forms.ModelForm): class Meta: model = models.RegionalLead exclude = () def clean(self): location = self.cleaned_data['location'] error_message = [] for u in self.cleaned_data['leads']: if not u.profile: error_message.append('Profile for user %s not found' % (u)) elif u.profile.location != location: error_message.append( "User %s doesn't belong to region %s" % (u, location)) if error_message: raise ValidationError(error_message) def save(self, force_insert=False, force_update=False, commit=True): m = super(RegionalLeadForm, self).save(commit=False) for u in self.cleaned_data['leads']: u.profile.usertype.add(UserType.objects.get(slug='lead')) return m class LocationForm(forms.ModelForm): class Meta: model = models.Location exclude = () class StateForm(forms.ModelForm): class Meta: model = models.State exclude = ()
Make txrudp the sole distributed package.
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.md'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.1.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='[email protected]', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=('txrudp'), install_requires=('jsonschema', 'twisted'), extras_require={ ':python_version<="3.4"': ('argparse',), 'dev': ('coverage', 'mock', 'nose', 'prospector') }, zip_safe=False )
"""Setup module for txrudp.""" import codecs from os import path import sys from setuptools import find_packages, setup _HERE = path.abspath(path.dirname(__file__)) with codecs.open(path.join(_HERE, 'README.md'), encoding='utf-8') as f: _LONG_DESCRIPTION = f.read() setup( name='txrudp', version='0.1.0', description='A Twisted extension implementing RUDP', long_description=_LONG_DESCRIPTION, url='https://github.com/Renelvon/txrudp', author='Nikolaos Korasidis', author_email='[email protected]', license='MIT', classifiers=( 'Development Status :: 3 - Alpha', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Topic :: System :: Networking' ), keywords='rudp twisted reliable', packages=find_packages(exclude=('tests',)), install_requires=('jsonschema', 'twisted'), extras_require={ ':python_version<="3.4"': ('argparse',), 'dev': ('coverage', 'mock', 'nose', 'prospector') }, zip_safe=False )
Fix ping to check each connection, not only first one (cherry picked from commit 72d4097)
<?php namespace Enqueue\Bundle\Consumption\Extension; use Doctrine\DBAL\Connection; use Enqueue\Consumption\Context; use Enqueue\Consumption\EmptyExtensionTrait; use Enqueue\Consumption\ExtensionInterface; use Symfony\Bridge\Doctrine\RegistryInterface; class DoctrinePingConnectionExtension implements ExtensionInterface { use EmptyExtensionTrait; /** * @var RegistryInterface */ protected $registry; /** * @param RegistryInterface $registry */ public function __construct(RegistryInterface $registry) { $this->registry = $registry; } /** * {@inheritdoc} */ public function onPreReceived(Context $context) { /** @var Connection $connection */ foreach ($this->registry->getConnections() as $connection) { if (!$connection->isConnected()) { continue; } if ($connection->ping()) { continue; } $context->getLogger()->debug( '[DoctrinePingConnectionExtension] Connection is not active trying to reconnect.' ); $connection->close(); $connection->connect(); $context->getLogger()->debug( '[DoctrinePingConnectionExtension] Connection is active now.' ); } } }
<?php namespace Enqueue\Bundle\Consumption\Extension; use Doctrine\DBAL\Connection; use Enqueue\Consumption\Context; use Enqueue\Consumption\EmptyExtensionTrait; use Enqueue\Consumption\ExtensionInterface; use Symfony\Bridge\Doctrine\RegistryInterface; class DoctrinePingConnectionExtension implements ExtensionInterface { use EmptyExtensionTrait; /** * @var RegistryInterface */ protected $registry; /** * @param RegistryInterface $registry */ public function __construct(RegistryInterface $registry) { $this->registry = $registry; } /** * {@inheritdoc} */ public function onPreReceived(Context $context) { /** @var Connection $connection */ foreach ($this->registry->getConnections() as $connection) { if (!$connection->isConnected()) { continue; } if ($connection->ping()) { return; } $context->getLogger()->debug( '[DoctrinePingConnectionExtension] Connection is not active trying to reconnect.' ); $connection->close(); $connection->connect(); $context->getLogger()->debug( '[DoctrinePingConnectionExtension] Connection is active now.' ); } } }
Remove the need for the Str facade
<?php namespace Schuppo\PasswordStrength; use Illuminate\Contracts\Validation\Factory; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Str; use Illuminate\Translation\Translator; class PasswordStrengthServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { app()->singleton('passwordStrength', function () { return new PasswordStrength(); }); app()->singleton('passwordStrength.translationProvider', function () { return new PasswordStrengthTranslationProvider(); }); } /** * Bootstrap application services. * * @return void */ public function boot(Factory $validator) { $passwordStrength = app('passwordStrength'); $translator = app('passwordStrength.translationProvider')->get($validator); foreach(['letters', 'numbers', 'caseDiff', 'symbols'] as $rule) { $snakeCasedRule = Str::snake($rule); $validator->extend($rule, function ($_, $value, $__) use ($passwordStrength, $rule) { $capitalizedRule = ucfirst($rule); return call_user_func([$passwordStrength, "validate{$capitalizedRule}"], $value); }, $translator->get("password-strength::validation.{$snakeCasedRule}")); } } }
<?php namespace Schuppo\PasswordStrength; use Illuminate\Contracts\Validation\Factory; use Illuminate\Support\ServiceProvider; use Illuminate\Translation\Translator; class PasswordStrengthServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { app()->singleton('passwordStrength', function () { return new PasswordStrength(); }); app()->singleton('passwordStrength.translationProvider', function () { return new PasswordStrengthTranslationProvider(); }); } /** * Bootstrap application services. * * @return void */ public function boot(Factory $validator) { $passwordStrength = app('passwordStrength'); $translator = app('passwordStrength.translationProvider')->get($validator); foreach(['letters', 'numbers', 'caseDiff', 'symbols'] as $rule) { $snakeCasedRule = \Str::snake($rule); $validator->extend($rule, function ($_, $value, $__) use ($passwordStrength, $rule) { $capitalizedRule = ucfirst($rule); return call_user_func([$passwordStrength, "validate{$capitalizedRule}"], $value); }, $translator->get("password-strength::validation.{$snakeCasedRule}")); } } }
Remove no longer valid comment - pdo_oci is maintaned by php people
<?php namespace Doctrine\DBAL\Driver\PDOOracle; use Doctrine\DBAL\Driver\AbstractOracleDriver; use Doctrine\DBAL\Driver\PDO; use Doctrine\DBAL\Exception; use PDOException; /** * PDO Oracle driver. * * @deprecated Use {@link PDO\OCI\Driver} instead. */ class Driver extends AbstractOracleDriver { /** * {@inheritdoc} */ public function connect(array $params, $username = null, $password = null, array $driverOptions = []) { try { return new PDO\Connection( $this->constructPdoDsn($params), $username, $password, $driverOptions ); } catch (PDOException $e) { throw Exception::driverException($this, $e); } } /** * Constructs the Oracle PDO DSN. * * @param mixed[] $params * * @return string The DSN. */ private function constructPdoDsn(array $params) { $dsn = 'oci:dbname=' . $this->getEasyConnectString($params); if (isset($params['charset'])) { $dsn .= ';charset=' . $params['charset']; } return $dsn; } /** * {@inheritdoc} */ public function getName() { return 'pdo_oracle'; } }
<?php namespace Doctrine\DBAL\Driver\PDOOracle; use Doctrine\DBAL\Driver\AbstractOracleDriver; use Doctrine\DBAL\Driver\PDO; use Doctrine\DBAL\Exception; use PDOException; /** * PDO Oracle driver. * * WARNING: PDO Oracle is not maintained by Oracle or anyone in the PHP community, * which leads us to the recommendation to use the "oci8" driver to connect * to Oracle instead. * * @deprecated Use {@link PDO\OCI\Driver} instead. */ class Driver extends AbstractOracleDriver { /** * {@inheritdoc} */ public function connect(array $params, $username = null, $password = null, array $driverOptions = []) { try { return new PDO\Connection( $this->constructPdoDsn($params), $username, $password, $driverOptions ); } catch (PDOException $e) { throw Exception::driverException($this, $e); } } /** * Constructs the Oracle PDO DSN. * * @param mixed[] $params * * @return string The DSN. */ private function constructPdoDsn(array $params) { $dsn = 'oci:dbname=' . $this->getEasyConnectString($params); if (isset($params['charset'])) { $dsn .= ';charset=' . $params['charset']; } return $dsn; } /** * {@inheritdoc} */ public function getName() { return 'pdo_oracle'; } }
Fix specifying loadSchema() function from webpack configuration Object.assign() assigns the properties to its first parameter, which results in ajvOptions immediately being overwritten with the defaults that are provided. The second time ajvOptions is passed, it has no effect, because configuration options have already been overwritten by their defaults.
const Ajv = require('ajv'); const ajvPack = require('ajv-pack'); const loaderUtils = require('loader-utils'); const path = require('path'); module.exports = function (schemaStr, sourceMap) { const done = this.async(); const loadSchema = uri => { const filePath = path.resolve(this.context, uri); return new Promise(function (resolve, reject) { try { const schema = require(filePath); resolve(schema); } catch (e) { e.message = `Couldn't load schema: ${e.message}`; reject(e); } }); }; const defaultAjvOptions = { loadSchema }; // Maybe will be used in future const options = loaderUtils.getOptions(this) || {}; // { sourceCode: true } should not be overridden const ajvOptions = Object.assign({}, defaultAjvOptions, options.ajv || {}, { sourceCode: true }); const ajv = new Ajv(ajvOptions); let schema; try { schema = JSON.parse(schemaStr); } catch (e) { e.message = 'Schema is not a valid JSON: ' + e.message; done(e); return; } ajv.compileAsync(schema) .then(validate => { let moduleCode = ajvPack(ajv, validate); done(null, moduleCode, sourceMap); }, e => { done(e); }); };
const Ajv = require('ajv'); const ajvPack = require('ajv-pack'); const loaderUtils = require('loader-utils'); const path = require('path'); module.exports = function (schemaStr, sourceMap) { const done = this.async(); const loadSchema = uri => { const filePath = path.resolve(this.context, uri); return new Promise(function (resolve, reject) { try { const schema = require(filePath); resolve(schema); } catch (e) { e.message = `Couldn't load schema: ${e.message}`; reject(e); } }); }; const defaultAjvOptions = { loadSchema }; // Maybe will be used in future const options = loaderUtils.getOptions(this) || {}; const ajvOptions = options.ajv || {}; // { sourceCode: true } should not be overridden Object.assign(ajvOptions, defaultAjvOptions, ajvOptions, { sourceCode: true }); const ajv = new Ajv(ajvOptions); let schema; try { schema = JSON.parse(schemaStr); } catch (e) { e.message = 'Schema is not a valid JSON: ' + e.message; done(e); return; } ajv.compileAsync(schema) .then(validate => { let moduleCode = ajvPack(ajv, validate); done(null, moduleCode, sourceMap); }, e => { done(e); }); };
Revert "require SQLAlchemy>=0.7.8 for readthedocs" This reverts commit 689712e7ec4035e03934a4f32e788c133fa7a13c.
from setuptools import setup, find_packages version = '0.1' install_requires = [ 'SQLAlchemy>0.7' ] setup_requires = [ 'nose' ] tests_require = install_requires + [ 'coverage', 'psycopg2', ] setup(name='GeoAlchemy2', version=version, description="Using SQLAlchemy with Spatial Databases", long_description=open('README.rst').read(), classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Plugins", "Operating System :: OS Independent", "Programming Language :: Python", "Intended Audience :: Information Technology", "License :: OSI Approved :: MIT License", "Topic :: Scientific/Engineering :: GIS" ], keywords='geo gis sqlalchemy orm', author='Eric Lemoine', author_email='[email protected]', url='http://geoalchemy.org/', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests', "doc"]), include_package_data=True, zip_safe=False, install_requires=install_requires, setup_requires=setup_requires, tests_require=tests_require, test_suite="geoalchemy2.tests", entry_points=""" # -*- Entry points: -*- """, )
from setuptools import setup, find_packages version = '0.1' install_requires = [ 'SQLAlchemy>=0.7.8' ] setup_requires = [ 'nose' ] tests_require = install_requires + [ 'coverage', 'psycopg2', ] setup(name='GeoAlchemy2', version=version, description="Using SQLAlchemy with Spatial Databases", long_description=open('README.rst').read(), classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Plugins", "Operating System :: OS Independent", "Programming Language :: Python", "Intended Audience :: Information Technology", "License :: OSI Approved :: MIT License", "Topic :: Scientific/Engineering :: GIS" ], keywords='geo gis sqlalchemy orm', author='Eric Lemoine', author_email='[email protected]', url='http://geoalchemy.org/', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests', "doc"]), include_package_data=True, zip_safe=False, install_requires=install_requires, setup_requires=setup_requires, tests_require=tests_require, test_suite="geoalchemy2.tests", entry_points=""" # -*- Entry points: -*- """, )
Rename test so it actually runs
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase class WhitespaceTest(PyxformTestCase): def test_over_trim(self): self.assertPyxformXform( name='issue96', md=""" | survey | | | | | | type | label | name | | | text | Ignored | var | | | note | ${var} text | label | """, xml__contains=[ '<label><output value=" /issue96/var "/> text </label>', ]) def test_empty_label_squashing(self): self.assertPyxformXform( name='empty_label', debug=True, ss_structure={'survey': [ { 'type':'note', 'label':'', 'name':'label' } ] }, xml__contains=[ '<label></label>', ])
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase class WhitespaceTest(PyxformTestCase): def test_over_trim(self): self.assertPyxformXform( name='issue96', md=""" | survey | | | | | | type | label | name | | | text | Ignored | var | | | note | ${var} text | label | """, xml__contains=[ '<label><output value=" /issue96/var "/> text </label>', ]) def empty_label_squashing(self): self.assertPyxformXform( name='empty_label', debug=True, ss_structure={'survey': [ { 'type':'note', 'label':'', 'name':'label' } ] }, xml__contains=[ '<label></label>', ])
Fix bad refactor on PersistenceProvider
const NotificationBuilder = require('./notification/notification-builder'); class PersistenceProvider { constructor(bridge) { this.toSave = []; this.bridge = bridge; this.toProcessAction = []; this.publications = []; this.fetches = []; this.toSave = []; } save(obj) { this.toSave.push(obj); } processAction(obj, action) { this.toProcessAction.push({ target: obj, action: action }); } createFetchRequest() { let [type, apiVersion, uid] = Array.prototype.slice.call(arguments); return this.bridge.newFetchRequest(type, apiVersion, uid); } publishOutbound() { if (!arguments.length) { return new NotificationBuilder((publication) => { this.publications.push(publication); }); } else if (arguments.length === 1) { throw new TypeError('Single parameter publishOutbound function is not supported at this time.'); } else if (arguments.length === 2) { this.publications.push({ target: arguments[0], topic: arguments[1] }); } else { throw new TypeError('Unsupported parameters used in publishOutbound function. Please check persistenceProvider API.'); } } getSaves() { return this.toSave.slice(); } getActionsToProcess() { return this.toProcessAction.slice(); } getPublications() { return this.publications.slice(); } reset() { this.toSave = []; this.toProcessAction = []; this.publications = []; } } module.exports = PersistenceProvider;
const NotificationBuilder = require('./notification/notification-builder'); class PersistenceProvider { constructor(bridge) { this.toSave = []; this.bridge = bridge; this.toProcessAction = []; this.publications = []; this.fetches = []; } save(obj) { this.toSave.push(obj); } processAction(obj, action) { this.toProcessAction.push({ target: obj, action: action }); } createFetchRequest() { let [type, apiVersion, uid] = Array.prototype.slice.call(arguments); return this.bridge.newFetchRequest(type, apiVersion, uid); } publishOutbound() { if (!arguments.length) { return new NotificationBuilder((publication) => { this.publications.push(publication); }); } else if (arguments.length === 1) { throw new TypeError('Single parameter publishOutbound function is not supported at this time.'); } else if (arguments.length === 2) { this.publications.push({ target: arguments[0], topic: arguments[1] }); } else { throw new TypeError('Unsupported parameters used in publishOutbound function. Please check persistenceProvider API.'); } } getSaves() { return this.toSave.slice(); } getActionsToProcess() { return this.toProcessAction.slice(); } getPublications() { return this.publications.slice(); } reset() { this.toSave = []; this.toProcessAction = []; this.publications = []; } } module.exports = PersistenceProvider;
Include the time in the email
#!/usr/bin/env python import log import time from jinja2 import Template import traceback class Report(object): TIME_FMT = ": %y/%m/%d %H:%M %z (%Z)" def __init__(self): self.logs = log.LogAggregator.new() self.started = time.strftime(TIME_FMT) def format_exception_as_reason(exc): return traceback.format_exc(exc) @log.make_loggable class UploadReport(Report): TEMPLATE_FILENAME = 'templates/uploader_report.jinja2' def __init__(self, mailer, mail_cfg): self.files = [] self.mailer = mailer self.mail_cfg = mail_cfg self.reason = None super(UploadReport, self).__init__() def add_uploaded_file(self, filename): self.files.append(filename) def finish_with_exception(self, exc): reason = format_exception_as_reason(exc) self.finish def finish(self, reason): self.reason = reason def render(self): tpl = Template(open(self.TEMPLATE_FILENAME).read()) return tpl.render( reason=self.reason, files=self.files, logs=self.logs ) def send(self): content = self.render() self.mailer.mail( self.mail_cfg['to'], self.mail_cfg['from'], self.mail_cfg['subject'] + self.started, content)
#!/usr/bin/env python import log from jinja2 import Template import traceback class Report(object): def __init__(self): self.logs = log.LogAggregator.new() def format_exception_as_reason(exc): return traceback.format_exc(exc) @log.make_loggable class UploadReport(Report): TEMPLATE_FILENAME = 'templates/uploader_report.jinja2' def __init__(self, mailer, mail_cfg): self.files = [] self.mailer = mailer self.mail_cfg = mail_cfg self.reason = None super(UploadReport, self).__init__() def add_uploaded_file(self, filename): self.files.append(filename) def finish_with_exception(self, exc): reason = format_exception_as_reason(exc) self.finish def finish(self, reason): self.reason = reason def render(self): tpl = Template(open(self.TEMPLATE_FILENAME).read()) return tpl.render( reason=self.reason, files=self.files, logs=self.logs ) def send(self): content = self.render() self.mailer.mail( self.mail_cfg['to'], self.mail_cfg['from'], self.mail_cfg['subject'], content)
Fix the compile error of define classes which derivate from other classes in class.
#--coding:utf-8-- #Platform class BasePlatform(object): """ A template for codes which are dependent on platform, whatever shell type or system type. Redefine members to modify the function. """ def __init__(self, shell = False): if shell: if os.name == 'posix': return self.Posix() if os.name == 'nt': return self.NT() return None else: import platform if platform.system()[:6] == 'Darwin': return self.OSX() if platform.system()[:5] == 'Linux': return self.Linux() if platform.system()[:7] == 'Windows': return self.Windows() if platform.system()[:6] == 'CYGWIN': return self.Cygwin() return None return None class Common(object): """ Redefine members here for those which will be inherited to all shells and systems. """ pass class Shell(Common): """ Redefine members here for those which will be inherited to all shells. """ pass class System(Common): """ Redefine members here for those which will be inherited to all systems. """ pass class Posix(Shell): pass class NT(Shell): pass class OSX(System): pass class Linux(System): pass class Windows(System): pass class Cygwin(System): pass if __name__ == '__main__': raise EnvironmentError ("DO NOT DIRECTLY RUN THIS TEMPLATE!")
#--coding:utf-8-- #Platform class BasePlatform(object): """ A template for codes which are dependent on platform, whatever shell type or system type. Redefine members to modify the function. """ def __init__(self, shell = False): if shell: if os.name == 'posix': return self.Posix() if os.name == 'nt': return self.NT() return None else: import platform if platform.system()[:6] == 'Darwin': return self.OSX() if platform.system()[:5] == 'Linux': return self.Linux() if platform.system()[:7] == 'Windows': return self.Windows() if platform.system()[:6] == 'CYGWIN': return self.Cygwin() return None return None class Common(object): """ Redefine members here for those which will be inherited to all shells and systems. """ pass class Shell(self.Common): """ Redefine members here for those which will be inherited to all shells. """ pass class System(self.Common): """ Redefine members here for those which will be inherited to all systems. """ pass class Posix(self.Shell): pass class NT(self.Shell): pass class OSX(self.System): pass class Linux(self.System): pass class Windows(self.System): pass class Cygwin(self.System): pass if __name__ == '__main__': raise EnvironmentError ("DO NOT DIRECTLY RUN THIS TEMPLATE!")
Fix react multi child error of FunctionsList If an error occured in func edit page and then switch back to func list, will cause an react multi child error
/** * * FunctionsList * */ import React, { PropTypes } from 'react'; import LoadingIndicator from 'components/LoadingIndicator'; import ErrorIndicator from 'components/ErrorIndicator'; import FunctionListItem from 'containers/FunctionListItem'; // import styled from 'styled-components'; import { FormattedMessage } from 'react-intl'; import commonMessages from 'messages'; function FunctionsList({ loading, error, items, onRemove }) { if (loading) { return <LoadingIndicator />; } if (error !== false) { return <ErrorIndicator error={error} />; } return ( <table className="table table-bordered"> <thead> <tr> <th><FormattedMessage {...commonMessages.name} /></th> <th><FormattedMessage {...commonMessages.environment} /></th> <th><FormattedMessage {...commonMessages.trigger} /></th> <th><FormattedMessage {...commonMessages.action} /></th> </tr> </thead> <tbody> { items.map((item, index) => ( <FunctionListItem item={item} key={`function-${index}`} onRemove={() => { onRemove(item); }} /> )) } </tbody> </table> ); } FunctionsList.propTypes = { loading: PropTypes.bool, error: PropTypes.any, items: PropTypes.oneOfType([ PropTypes.object, PropTypes.array, ]), onRemove: PropTypes.func, }; export default FunctionsList;
/** * * FunctionsList * */ import React, { PropTypes } from 'react'; import LoadingIndicator from 'components/LoadingIndicator'; import FunctionListItem from 'containers/FunctionListItem'; // import styled from 'styled-components'; import { FormattedMessage } from 'react-intl'; import commonMessages from 'messages'; function FunctionsList({ loading, error, items, onRemove }) { if (loading) { return <LoadingIndicator />; } if (error !== false) { return <h3>{ error }</h3>; } return ( <table className="table table-bordered"> <thead> <tr> <th><FormattedMessage {...commonMessages.name} /></th> <th><FormattedMessage {...commonMessages.environment} /></th> <th><FormattedMessage {...commonMessages.trigger} /></th> <th><FormattedMessage {...commonMessages.action} /></th> </tr> </thead> <tbody> { items.map((item, index) => ( <FunctionListItem item={item} key={`function-${index}`} onRemove={() => { onRemove(item); }} /> )) } </tbody> </table> ); } FunctionsList.propTypes = { loading: PropTypes.bool, error: PropTypes.any, items: PropTypes.oneOfType([ PropTypes.object, PropTypes.array, ]), onRemove: PropTypes.func, }; export default FunctionsList;
Create doctrine Annotations on Entity
<?php namespace WiContact\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; /** * @ORM\Entity * @ORM\Table(name="contacts") */ class Contact { /** * * @var int @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * * @var string @ORM\Column(type="string", nullable=true) */ protected $name; /** * * @var ArrayCollection; @ORM\OneToMany(targetEntity="WiContact\Entity\ContactPhone", mappedBy="contact", cascade={"persist"}) */ protected $phones; /** * Never forget to initialize collections */ public function __construct() { $this->phones = new ArrayCollection(); } /** * * @return the $id */ public function getId() { return $this->id; } /** * * @return the $name */ public function getName() { return $this->name; } /** * * @param string $name */ public function setName($name) { $this->name = $name; } /** * @param Collection $phones */ public function addPhones(Collection $phones) { foreach ($phones as $phone) { $phone->setContact($this); $this->phones->add($phone); } } /** * @param Collection $phones */ public function removePhones(Collection $phones) { foreach ($phones as $phone) { $phone->setContact($this); $this->phones->removeElement($phone); } } /** * * @return the $phones */ public function getPhones() { return $this->phones; } }
<?php namespace WiContact\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="contacts") */ class Contact { /** * * @var int * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue */ protected $id; /** * * @var string @ORM\Column(type="string", nullable=true) */ protected $name; /** * * @return the $id */ public function getId() { return $this->id; } /** * * @return the $name */ public function getName() { return $this->name; } /** * * @param int $id */ public function setId($id) { $this->id = $id; } /** * * @param string $name */ public function setName($name) { $this->name = $name; } }
Fix the issue that get_or_create returns a tuple instead of one object.
import os from optparse import make_option from django.core.management import BaseCommand from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase from obj_sys.models_ufs_obj import UfsObj class FileTagger(DjangoCmdBase): option_list = BaseCommand.option_list + ( make_option('--tags', action='store', dest='tags', type='string', help='Tags separated with ","'), make_option('--file_path', action='store', dest='file_path', type='string', help='Path of the file to be tagged'), make_option('--log-file', action='store', dest='log_file', help='Log file destination'), make_option('--log-std', action='store_true', dest='log_std', help='Redirect stdout and stderr to the logging system'), ) def msg_loop(self): # enum_method = enum_git_repo # pull_all_in_enumerable(enum_method) if os.path.exists(self.options["file_path"]): new_file_ufs_obj, is_created = UfsObj.objects.get_or_create(full_path=self.options["file_path"]) new_file_ufs_obj.tags = self.options["tags"] Command = FileTagger
import os from optparse import make_option from django.core.management import BaseCommand from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase from obj_sys.models_ufs_obj import UfsObj class FileTagger(DjangoCmdBase): option_list = BaseCommand.option_list + ( make_option('--tags', action='store', dest='tags', type='string', help='Tags separated with ","'), make_option('--file_path', action='store', dest='file_path', type='string', help='Path of the file to be tagged'), make_option('--log-file', action='store', dest='log_file', help='Log file destination'), make_option('--log-std', action='store_true', dest='log_std', help='Redirect stdout and stderr to the logging system'), ) def msg_loop(self): # enum_method = enum_git_repo # pull_all_in_enumerable(enum_method) if os.path.exists(self.options["file_path"]): new_file_ufs_obj = UfsObj.objects.get_or_create(full_path=self.options["file_path"]) new_file_ufs_obj.tags = self.options["tags"] Command = FileTagger
Change to reply only if target has karma
"""Keeps track of karma counts. @package ppbot @syntax .karma <item> """ import re from modules import * class Karmamod(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) def _register_events(self): self.add_command('karma', 'get_karma') self.add_event('pubmsg', 'parsekarma') @op def get_karma(self, event): karma = self.db.karma.find_one({'name': event['args'][0].lower(), 'source': event['target']}) try: result = karma['count'] self.reply('%s has %d karma.' % (event['args'][0], result)) except KeyError, TypeError: result = 0 def parsekarma(self, event): inc_pattern = re.compile('([^ ]{2,})\+\+') m = inc_pattern.findall(event['message']) for term in m: self.change(event, term, 1) dec_pattern = re.compile('([^ ]{2,})--') m = dec_pattern.findall(event['message']) for term in m: self.change(event, term, -1) def change(self, event, name, value): """Change karma count.""" self.db.karma.update({ 'name': name.lower(), 'source': event['target'] }, { '$inc': { 'count': 1 } }, True)
"""Keeps track of karma counts. @package ppbot @syntax .karma <item> """ import re from modules import * class Karmamod(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) def _register_events(self): self.add_command('karma', 'get_karma') self.add_event('pubmsg', 'parsekarma') @op def get_karma(self, event): karma = self.db.karma.find_one({'name': event['args'][0].lower(), 'source': event['target']}) try: result = karma['count'] except KeyError, TypeError: result = 0 self.msg(event['target'], '%s has %d karma.' % (event['args'][0], result)) def parsekarma(self, event): inc_pattern = re.compile('([^ ]{2,})\+\+') m = inc_pattern.findall(event['message']) for term in m: self.change(event, term, 1) dec_pattern = re.compile('([^ ]{2,})--') m = dec_pattern.findall(event['message']) for term in m: self.change(event, term, -1) def change(self, event, name, value): """Change karma count.""" self.db.karma.update({ 'name': name.lower(), 'source': event['target'] }, { '$inc': { 'count': 1 } }, True)
Update Google Analystics Key path
<?php include '../paasswd/analytics-key.inc.php'; // Override any of the default settings below: $config['site_title'] = 'schmitt.co'; // Site title $config['theme'] = 'default'; // Set the theme (defaults to "default") // adv-meta $config['adv_meta_values'] = array('description' => 'Description', 'tags' => 'Tags'); // Google Analytics $config['google_tracking_id'] = $ANALYTICS_TRACKING_ID; /* $config['base_url'] = ''; // Override base URL (e.g. http://example.com) $config['date_format'] = 'jS M Y'; // Set the PHP date format $config['twig_config'] = array( // Twig settings 'cache' => false, // To enable Twig caching change this to CACHE_DIR 'autoescape' => false, // Autoescape Twig vars 'debug' => false // Enable Twig debug ); $config['pages_order_by'] = 'alpha'; // Order pages by "alpha" or "date" $config['pages_order'] = 'asc'; // Order pages "asc" or "desc" $config['excerpt_length'] = 50; // The pages excerpt length (in words) // To add a custom config setting: $config['custom_setting'] = 'Hello'; // Can be accessed by {{ config.custom_setting }} in a theme */ ?>
<?php include '../analytics-key.inc.php'; // Override any of the default settings below: $config['site_title'] = 'schmitt.co'; // Site title $config['theme'] = 'default'; // Set the theme (defaults to "default") // adv-meta $config['adv_meta_values'] = array('description' => 'Description', 'tags' => 'Tags'); // Google Analytics $config['google_tracking_id'] = $ANALYTICS_TRACKING_ID; /* $config['base_url'] = ''; // Override base URL (e.g. http://example.com) $config['date_format'] = 'jS M Y'; // Set the PHP date format $config['twig_config'] = array( // Twig settings 'cache' => false, // To enable Twig caching change this to CACHE_DIR 'autoescape' => false, // Autoescape Twig vars 'debug' => false // Enable Twig debug ); $config['pages_order_by'] = 'alpha'; // Order pages by "alpha" or "date" $config['pages_order'] = 'asc'; // Order pages "asc" or "desc" $config['excerpt_length'] = 50; // The pages excerpt length (in words) // To add a custom config setting: $config['custom_setting'] = 'Hello'; // Can be accessed by {{ config.custom_setting }} in a theme */ ?>
Install the proper version of Django
#!/usr/bin/env python from subprocess import check_call, CalledProcessError from setuptools import setup import six requirements = ['setuptools', 'mongoengine>=0.10.0'] if six.PY3: requirements.append('django') else: requirements.append('django<2') def convert_readme(): try: check_call(["pandoc", "-f", "markdown_github", "-t", "rst", "-o", "README.rst", "README.md"]) except (OSError, CalledProcessError): return open('README.md').read() return open('README.rst').read() setup( name='django-mongoengine-forms', version='0.4.4', description="An implementation of django forms using mongoengine.", author='Thom Wiggers', author_email='[email protected]', packages=['mongodbforms', 'tests'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], license='New BSD License', long_description=convert_readme(), include_package_data=True, provides=['mongodbforms'], obsoletes=['mongodbforms'], url='https://github.com/thomwiggers/django-mongoengine-forms/', zip_safe=False, install_requires=requirements, tests_require=['mongomock'], test_suite="tests.suite", )
#!/usr/bin/env python from subprocess import check_call, CalledProcessError from setuptools import setup def convert_readme(): try: check_call(["pandoc", "-f", "markdown_github", "-t", "rst", "-o", "README.rst", "README.md"]) except (OSError, CalledProcessError): return open('README.md').read() return open('README.rst').read() setup( name='django-mongoengine-forms', version='0.4.4', description="An implementation of django forms using mongoengine.", author='Thom Wiggers', author_email='[email protected]', packages=['mongodbforms', 'tests'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], license='New BSD License', long_description=convert_readme(), include_package_data=True, provides=['mongodbforms'], obsoletes=['mongodbforms'], url='https://github.com/thomwiggers/django-mongoengine-forms/', zip_safe=False, install_requires=['setuptools', 'django>=1.8', 'mongoengine>=0.10.0'], tests_require=['mongomock'], test_suite="tests.suite", )
Update renderer test for Unix lines
<?php namespace Tga\OpenGraphBundle\Tests\Renderer; use Symfony\Component\Routing\Router; use Tga\OpenGraphBundle\Registry\Registry; use Tga\OpenGraphBundle\Renderer\OpenGraphMapRenderer; use Tga\OpenGraphBundle\Tests\Mock\Map; class OpenGraphMapRendererTest extends \PHPUnit_Framework_TestCase { public function testConstruct() { $router = new Router(); $registry = new Registry($router); $registry->register(new Map()); $renderer = new OpenGraphMapRenderer($registry); $this->assertEquals($renderer->getRegistry(), $registry); $this->assertEquals($renderer->getRegistry()->getRouter(), $registry->getRouter()); return $renderer; } /** * @depends testConstruct */ public function testRenderValid(OpenGraphMapRenderer $renderer) { $entity = new \stdClass(); $entity->name = 'TestName'; $this->assertTrue(strpos($renderer->render($entity), '<meta property="og:title" content="TestName" />') !== false); } /** * @expectedException \Tga\OpenGraphBundle\Renderer\Exception\EntityNotSupported */ public function testRenderInvalid() { $router = new Router(); $registry = new Registry($router); $renderer = new OpenGraphMapRenderer($registry); $entity = new \stdClass(); $entity->name = 'TestName'; $renderer->render($entity); } }
<?php namespace Tga\OpenGraphBundle\Tests\Renderer; use Symfony\Component\Routing\Router; use Tga\OpenGraphBundle\Registry\Registry; use Tga\OpenGraphBundle\Renderer\OpenGraphMapRenderer; use Tga\OpenGraphBundle\Tests\Mock\Map; class OpenGraphMapRendererTest extends \PHPUnit_Framework_TestCase { public function testConstruct() { $router = new Router(); $registry = new Registry($router); $registry->register(new Map()); $renderer = new OpenGraphMapRenderer($registry); $this->assertEquals($renderer->getRegistry(), $registry); $this->assertEquals($renderer->getRegistry()->getRouter(), $registry->getRouter()); return $renderer; } /** * @depends testConstruct */ public function testRenderValid(OpenGraphMapRenderer $renderer) { $entity = new \stdClass(); $entity->name = 'TestName'; $this->assertEquals("\t<meta property=\"og:title\" content=\"TestName\" />\r\n", $renderer->render($entity)); } /** * @expectedException \Tga\OpenGraphBundle\Renderer\Exception\EntityNotSupported */ public function testRenderInvalid() { $router = new Router(); $registry = new Registry($router); $renderer = new OpenGraphMapRenderer($registry); $entity = new \stdClass(); $entity->name = 'TestName'; $renderer->render($entity); } }
Rename disableText prop to removeText in UiIcon test
import Vue from 'vue'; import UiIcon from '../src/UiIcon.vue'; describe('UiIcon.vue', function() { it('should initialize with correct data/props', function() { const vm = new Vue({ template: '<div><ui-icon icon="mail" :remove-text="true" v-ref:icon></ui-icon></div>', components: { UiIcon } }).$mount(); expect(vm.$refs.icon.icon).toBe('mail'); expect(vm.$refs.icon.removeText).toBe(true); }); it('should add icon prop as a class', function() { const vm = new Vue({ template: '<div><ui-icon icon="mail" v-ref:icon></ui-icon></div>', components: { UiIcon } }).$mount(); expect(vm.$refs.icon.$el.className).toMatch(/mail/); }); it('should render icon prop as inner text', function() { const vm = new Vue({ template: '<div><ui-icon icon="mail" v-ref:icon></ui-icon></div>', components: { UiIcon } }).$mount(); expect(vm.$refs.icon.$el.textContent).toBe('mail'); }); it('should not render icon prop as inner text when removeText prop is true', function() { const vm = new Vue({ template: '<div><ui-icon icon="mail" :remove-text="true" v-ref:icon></ui-icon></div>', components: { UiIcon } }).$mount(); expect(vm.$refs.icon.$el.textContent).toBe(''); }); });
import Vue from 'vue'; import UiIcon from '../src/UiIcon.vue'; describe('UiIcon.vue', function() { it('should initialize with correct data/props', function() { const vm = new Vue({ template: '<div><ui-icon icon="mail" :disable-text="true" v-ref:icon></ui-icon></div>', components: { UiIcon } }).$mount(); expect(vm.$refs.icon.icon).toBe('mail'); expect(vm.$refs.icon.disableText).toBe(true); }); it('should add icon prop as a class', function() { const vm = new Vue({ template: '<div><ui-icon icon="mail" v-ref:icon></ui-icon></div>', components: { UiIcon } }).$mount(); expect(vm.$refs.icon.$el.className).toMatch(/mail/); }); it('should render icon prop as inner text', function() { const vm = new Vue({ template: '<div><ui-icon icon="mail" v-ref:icon></ui-icon></div>', components: { UiIcon } }).$mount(); expect(vm.$refs.icon.$el.textContent).toBe('mail'); }); it('should not render icon prop as inner text when disableText prop is true', function() { const vm = new Vue({ template: '<div><ui-icon icon="mail" :disable-text="true" v-ref:icon></ui-icon></div>', components: { UiIcon } }).$mount(); expect(vm.$refs.icon.$el.textContent).toBe(''); }); });
Fix IndexError when running command without arguments.
from getpass import getpass from scrapy.commands.crawl import Command as BaseCommand from scrapy.exceptions import UsageError def sanitize_query(query): return query.replace(' ', '+') class Command(BaseCommand): def short_desc(self): return "Scrap people from LinkedIn" def syntax(self): return "[options] <query>" def add_options(self, parser): super().add_options(parser) parser.add_option('-u', '--username', help='Name of LinkedIn account') parser.add_option('-p', '--password', help='Password for LinkedIn account') def process_options(self, args, opts): opts.output = opts.output or 'results.csv' opts.loglevel = opts.loglevel or 'INFO' super().process_options(args, opts) try: query = sanitize_query(args[0]) except IndexError: raise UsageError() people_search_options = { 'query': query, 'username': opts.username or input( 'Please provide your LinkedIn username: '), 'password': opts.password or getpass( 'Please provide password for your LinkedIn account: ') } opts.spargs.update(people_search_options) def run(self, args, opts): # Run people_search spider args = ['people_search'] super().run(args, opts)
from getpass import getpass from scrapy.commands.crawl import Command as BaseCommand def sanitize_query(query): return query.replace(' ', '+') class Command(BaseCommand): def short_desc(self): return "Scrap people from LinkedIn" def syntax(self): return "[options] <query>" def add_options(self, parser): super().add_options(parser) parser.add_option('-u', '--username', help='Name of LinkedIn account') parser.add_option('-p', '--password', help='Password for LinkedIn account') def process_options(self, args, opts): opts.output = opts.output or 'results.csv' opts.loglevel = opts.loglevel or 'INFO' super().process_options(args, opts) people_search_options = { 'query': sanitize_query(args[0]), 'username': opts.username or input( 'Please provide your LinkedIn username: '), 'password': opts.password or getpass( 'Please provide password for your LinkedIn account: ') } opts.spargs.update(people_search_options) def run(self, args, opts): # Run people_search spider args = ['people_search'] super().run(args, opts)
Add shouldComponentUpdate to excludeMethods array.
var excludeMethods = [ /^constructor$/, /^render$/, /^component[A-Za-z]+$/, /^shouldComponentUpdate$/ ]; var displayNameReg = /^function\s+([a-zA-Z]+)/; function isExcluded(methodName) { return excludeMethods.some(function (reg) { return reg.test(methodName) === false; }); } function bindToClass(scope, methods) { var componentName = scope.constructor.toString().match(displayNameReg)[1]; methods = Array.isArray(methods) ? methods : []; methods.forEach(function(methodName) { if (methodName in scope) { scope[methodName] = scope[methodName].bind(scope); } else { throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"'); } }); // for debugging purposes only? // if (process.env.NODE_ENV != 'production') { if (Object.getOwnPropertyNames) { var proto = scope.constructor.prototype; Object.getOwnPropertyNames(proto).forEach(function(methodName) { var original = scope[methodName]; if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) { scope[methodName] = function () { // test whether the scope is different if (this !== scope) { var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!'; console.error(e); } return original.apply(scope, arguments); }; } }); } // } } module.exports = bindToClass;
var excludeMethods = [ /^constructor$/, /^render$/, /^component[A-Za-z]+$/ ]; var displayNameReg = /^function\s+([a-zA-Z]+)/; function isExcluded(methodName) { return excludeMethods.some(function (reg) { return reg.test(methodName) === false; }); } function bindToClass(scope, methods) { var componentName = scope.constructor.toString().match(displayNameReg)[1]; methods = Array.isArray(methods) ? methods : []; methods.forEach(function(methodName) { if (methodName in scope) { scope[methodName] = scope[methodName].bind(scope); } else { throw new Error('Method "' + methodName + '" does not exists in "' + componentName + '"'); } }); // for debugging purposes only? // if (process.env.NODE_ENV != 'production') { if (Object.getOwnPropertyNames) { var proto = scope.constructor.prototype; Object.getOwnPropertyNames(proto).forEach(function(methodName) { var original = scope[methodName]; if (typeof original === 'function' && isExcluded(methodName) && methods.indexOf(methodName) === -1) { scope[methodName] = function () { // test whether the scope is different if (this !== scope) { var e = 'Warning: Method "' + methodName + '" of "' + componentName + '" is not bound. Bad you!'; console.error(e); } return original.apply(scope, arguments); }; } }); } // } } module.exports = bindToClass;
Remove hardcoded localhost in one more place.
/* * Exporst function that checks if given emails of users are shown * on the Teamview page. And if so how they are rendered: as text or link. * * It does not check exact emails, just count numbers. * * */ 'use strict'; var By = require('selenium-webdriver').By, expect = require('chai').expect, open_page_func = require('./open_page'), config = require('./config'), bluebird = require("bluebird"); module.exports = bluebird.promisify( function(args, callback){ var result_callback = callback, driver = args.driver, emails = args.emails || [], is_link = args.is_link || false, application_host = args.application_host || config.get_application_host(); if ( ! driver ) { throw "'driver' was not passed into the teamview_check_user!"; } return open_page_func({ url : application_host + 'calendar/teamview/', driver : driver, }) .then(function(data){ return data.driver .findElements(By.css( 'tr.teamview-user-list-row > td > ' + (is_link ? 'a' : 'span') )) .then(function(elements){ expect(elements.length).to.be.equal( emails.length ); return bluebird.resolve(data); }); }) .then(function(data){ // "export" current driver result_callback( null, { driver : data.driver, } ); }); });
/* * Exporst function that checks if given emails of users are shown * on the Teamview page. And if so how they are rendered: as text or link. * * It does not check exact emails, just count numbers. * * */ 'use strict'; var By = require('selenium-webdriver').By, expect = require('chai').expect, open_page_func = require('../lib/open_page'), bluebird = require("bluebird"); module.exports = bluebird.promisify( function(args, callback){ var result_callback = callback, driver = args.driver, emails = args.emails || [], is_link = args.is_link || false, application_host = args.application_host || 'http://localhost:3000/'; if ( ! driver ) { throw "'driver' was not passed into the teamview_check_user!"; } return open_page_func({ url : application_host + 'calendar/teamview/', driver : driver, }) .then(function(data){ return data.driver .findElements(By.css( 'tr.teamview-user-list-row > td > ' + (is_link ? 'a' : 'span') )) .then(function(elements){ expect(elements.length).to.be.equal( emails.length ); return bluebird.resolve(data); }); }) .then(function(data){ // "export" current driver result_callback( null, { driver : data.driver, } ); }); });
Enforce events to be arrays
<?php /* * This file is part of Rocketeer * * (c) Maxime Fabre <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace Rocketeer\Services\Config\Definition; use Symfony\Component\Config\Definition\TreeBuilder\NodeBuilder; class HooksDefinition extends AbstractDefinition { /** * @var string */ protected $name = 'hooks'; /** * @var string */ protected $description = 'Here you can customize Rocketeer by adding tasks, strategies, etc.'; /** * @param NodeBuilder $node * * @return NodeBuilder */ protected function getChildren(NodeBuilder $node) { return $node ->arrayNode('events') ->children() ->arrayNode('before') ->useAttributeAsKey('name') ->prototype('array') ->prototype('variable')->end() ->end() ->end() ->arrayNode('after') ->useAttributeAsKey('name') ->prototype('array') ->prototype('variable')->end() ->end() ->end() ->end() ->end() ->arrayNode('tasks') ->info('Here you can quickly add custom tasks to Rocketeer, as well as to its CLI') ->useAttributeAsKey('name') ->prototype('variable')->end() ->end() ->arrayNode('roles') ->info('Define roles to assign to tasks'.PHP_EOL."eg. 'db' => ['Migrate']") ->useAttributeAsKey('name') ->prototype('variable')->end() ->end(); } }
<?php /* * This file is part of Rocketeer * * (c) Maxime Fabre <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace Rocketeer\Services\Config\Definition; use Symfony\Component\Config\Definition\TreeBuilder\NodeBuilder; class HooksDefinition extends AbstractDefinition { /** * @var string */ protected $name = 'hooks'; /** * @var string */ protected $description = 'Here you can customize Rocketeer by adding tasks, strategies, etc.'; /** * @param NodeBuilder $node * * @return NodeBuilder */ protected function getChildren(NodeBuilder $node) { return $node ->arrayNode('events') ->children() ->arrayNode('before') ->useAttributeAsKey('name') ->prototype('variable')->end() ->end() ->arrayNode('after') ->useAttributeAsKey('name') ->prototype('variable')->end() ->end() ->end() ->end() ->arrayNode('tasks') ->info('Here you can quickly add custom tasks to Rocketeer, as well as to its CLI') ->useAttributeAsKey('name') ->prototype('variable')->end() ->end() ->arrayNode('roles') ->info('Define roles to assign to tasks'.PHP_EOL."eg. 'db' => ['Migrate']") ->useAttributeAsKey('name') ->prototype('variable')->end() ->end(); } }
Disable logging while running tests
var _ = require('underscore'); module.exports = function(opts) { var config = { base_url: '/database/:dbname/table/:table', grainstore: {datasource: global.environment.postgres}, redis: global.environment.redis, enable_cors: global.environment.enable_cors, unbuffered_logging: true, // for smoother teardown from tests log_format: null, // do not log anything req2params: function(req, callback){ // no default interactivity. to enable specify the database column you'd like to interact with req.params.interactivity = null; // this is in case you want to test sql parameters eg ...png?sql=select * from my_table limit 10 req.params = _.extend({}, req.params); _.extend(req.params, req.query); // send the finished req object on callback(null,req); }, beforeTileRender: function(req, res, callback) { res.header('X-BeforeTileRender', 'called'); callback(null); }, afterTileRender: function(req, res, tile, headers, callback) { res.header('X-AfterTileRender','called'); headers['X-AfterTileRender2'] = 'called'; callback(null, tile, headers); } } _.extend(config, opts || {}); return config; }();
var _ = require('underscore'); module.exports = function(opts) { var config = { base_url: '/database/:dbname/table/:table', grainstore: {datasource: global.environment.postgres}, redis: global.environment.redis, enable_cors: global.environment.enable_cors, unbuffered_logging: true, // for smoother teardown from tests req2params: function(req, callback){ // no default interactivity. to enable specify the database column you'd like to interact with req.params.interactivity = null; // this is in case you want to test sql parameters eg ...png?sql=select * from my_table limit 10 req.params = _.extend({}, req.params); _.extend(req.params, req.query); // send the finished req object on callback(null,req); }, beforeTileRender: function(req, res, callback) { res.header('X-BeforeTileRender', 'called'); callback(null); }, afterTileRender: function(req, res, tile, headers, callback) { res.header('X-AfterTileRender','called'); headers['X-AfterTileRender2'] = 'called'; callback(null, tile, headers); } } _.extend(config, opts || {}); return config; }();
Fix typo in comment-space-inside message
import { report, ruleMessages } from "../../utils" export const ruleName = "comment-space-inside" export const messages = ruleMessages(ruleName, { expectedOpening: `Expected single space after "/*"`, rejectedOpening: `Unexpected whitespace after "/*"`, expectedClosing: `Expected single space before "*/"`, rejectedClosing: `Unexpected whitespace before "*/"`, }) /** * @param {"always"|"never"} expectation */ export default function (expectation) { return function (root, result) { root.eachComment(function (comment) { const left = comment.left const right = comment.right if (left !== "" && expectation === "never") { report({ message: messages.rejectedOpening, node: comment, result, ruleName, }) } if (left !== " " && expectation === "always") { report({ message: messages.expectedOpening, node: comment, result, ruleName, }) } if (right !== "" && expectation === "never") { report({ message: messages.rejectedClosing, node: comment, result, ruleName, }) } if (right !== " " && expectation === "always") { report({ message: messages.expectedClosing, node: comment, result, ruleName, }) } }) } }
import { report, ruleMessages } from "../../utils" export const ruleName = "comment-space-inside" export const messages = ruleMessages(ruleName, { expectedOpening: `Expected single space after "/*`, rejectedOpening: `Unexpected whitespace after "/*`, expectedClosing: `Expected single space before "*/"`, rejectedClosing: `Unexpected whitespace before "*/"`, }) /** * @param {"always"|"never"} expectation */ export default function (expectation) { return function (root, result) { root.eachComment(function (comment) { const left = comment.left const right = comment.right if (left !== "" && expectation === "never") { report({ message: messages.rejectedOpening, node: comment, result, ruleName, }) } if (left !== " " && expectation === "always") { report({ message: messages.expectedOpening, node: comment, result, ruleName, }) } if (right !== "" && expectation === "never") { report({ message: messages.rejectedClosing, node: comment, result, ruleName, }) } if (right !== " " && expectation === "always") { report({ message: messages.expectedClosing, node: comment, result, ruleName, }) } }) } }
Use PHP 8 constructor property promotion
<?php declare(strict_types = 1); /** * /src/Request/ParamConverter/RestResourceConverter.php * * @author TLe, Tarmo Leppänen <[email protected]> */ namespace App\Request\ParamConverter; use App\Resource\ResourceCollection; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface; use Symfony\Component\HttpFoundation\Request; use Throwable; /** * Class RestResourceConverter * * Purpose of this param converter is to use exactly same methods and workflow * as in basic REST API requests. * * @package App\Request\ParamConverter * @author TLe, Tarmo Leppänen <[email protected]> */ class RestResourceConverter implements ParamConverterInterface { public function __construct( private ResourceCollection $collection, ) { } /** * {@inheritdoc} * * @throws Throwable */ public function apply(Request $request, ParamConverter $configuration): bool { $name = $configuration->getName(); $identifier = (string)$request->attributes->get($name, ''); $resource = $this->collection->get($configuration->getClass()); if ($identifier !== '') { $request->attributes->set($name, $resource->findOne($identifier, true)); } return true; } public function supports(ParamConverter $configuration): bool { return $this->collection->has($configuration->getClass()); } }
<?php declare(strict_types = 1); /** * /src/Request/ParamConverter/RestResourceConverter.php * * @author TLe, Tarmo Leppänen <[email protected]> */ namespace App\Request\ParamConverter; use App\Resource\ResourceCollection; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface; use Symfony\Component\HttpFoundation\Request; use Throwable; /** * Class RestResourceConverter * * Purpose of this param converter is to use exactly same methods and workflow as in basic REST API requests. * * @package App\Request\ParamConverter * @author TLe, Tarmo Leppänen <[email protected]> */ class RestResourceConverter implements ParamConverterInterface { private ResourceCollection $collection; public function __construct(ResourceCollection $collection) { $this->collection = $collection; } /** * {@inheritdoc} * * @throws Throwable */ public function apply(Request $request, ParamConverter $configuration): bool { $name = $configuration->getName(); $identifier = (string)$request->attributes->get($name, ''); $resource = $this->collection->get($configuration->getClass()); if ($identifier !== '') { $request->attributes->set($name, $resource->findOne($identifier, true)); } return true; } public function supports(ParamConverter $configuration): bool { return $this->collection->has($configuration->getClass()); } }
Change to use read-only router for data-apis
""" API Builder Build dynamic API based on the provided SQLAlchemy model """ from managers import AlchemyModelManager from viewsets import AlchemyModelViewSet from routers import ReadOnlyRouter class APIModelBuilder(object): def __init__(self, models, base_managers, base_viewsets=None, *args, **kwargs): self.models = models if not isinstance(base_managers, (tuple, list)): base_managers = [base_managers] if not isinstance(base_managers, tuple): base_managers = tuple(base_managers) if base_viewsets is None: base_viewsets = (AlchemyModelViewSet,) self.base_managers = base_managers self.base_viewsets = base_viewsets @property def urls(self): router = ReadOnlyRouter() for model in self.models: manager = type( str('{}Manager'.format(model.__name__)), self.base_managers + (AlchemyModelManager,), { 'model_class': model, } ) viewset = type( str('{}ModelViewSet'.format(model.__name__)), self.base_viewsets, { 'manager_class': manager, 'paginate_by': 10, } ) router.register('data-api/' + model.__name__.lower() + 's', viewset, base_name=model.__name__) return router.urls
""" API Builder Build dynamic API based on the provided SQLAlchemy model """ from managers import AlchemyModelManager from viewsets import AlchemyModelViewSet from rest_framework_nested import routers class APIModelBuilder(object): def __init__(self, models, base_managers, base_viewsets=None, *args, **kwargs): self.models = models if not isinstance(base_managers, (tuple, list)): base_managers = [base_managers] if not isinstance(base_managers, tuple): base_managers = tuple(base_managers) if base_viewsets is None: base_viewsets = (AlchemyModelViewSet,) self.base_managers = base_managers self.base_viewsets = base_viewsets @property def urls(self): router = routers.SimpleRouter() for model in self.models: manager = type( str('{}Manager'.format(model.__name__)), self.base_managers + (AlchemyModelManager,), { 'model_class': model, } ) viewset = type( str('{}ModelViewSet'.format(model.__name__)), self.base_viewsets, { 'manager_class': manager, 'paginate_by': 10, } ) router.register('data-api/' + model.__name__.lower() + 's', viewset, base_name=model.__name__) return router.urls
Fix new method signature and moved delta variable in lcs recorder
/** * @file: Subclass of LCS which allows to observe progress of the algorithm * by intercepting function calls. */ DeltaJS.lcs.InstallLCSRecorder = function(lcs, recorder) { var orig = {}; orig.compute = lcs.compute; lcs.compute = function(callback, T, limit) { if (typeof limit === 'undefined') { limit = this.defaultLimit(); } recorder.onCompute.call(recorder, callback, T, limit); orig.compute.apply(this, arguments); } orig.nextSnakeHeadForward = lcs.nextSnakeHeadForward; lcs.nextSnakeHeadForward = function(head, k, kmin, kmax, limits, V) { var k0 = orig.nextSnakeHeadForward.apply(this, arguments); var d = kmax; recorder.onSnakeHead.call(recorder, head, k0, d, false); return k0; } orig.nextSnakeHeadBackward = lcs.nextSnakeHeadBackward; lcs.nextSnakeHeadBackward = function(head, k, kmin, kmax, limits, V) { var k0 = orig.nextSnakeHeadBackward.apply(this, arguments); var d = kmax-limits.delta; recorder.onSnakeHead.call(recorder, head, k0, d, true); return k0; } orig.middleSnake = lcs.middleSnake; lcs.middleSnake = function(lefthead, righthead) { var d = orig.middleSnake.apply(this, arguments); recorder.onMiddleSnake.call(recorder, lefthead, righthead, d); return d; } }
/** * @file: Subclass of LCS which allows to observe progress of the algorithm * by intercepting function calls. */ DeltaJS.lcs.InstallLCSRecorder = function(lcs, recorder) { var orig = {}; orig.compute = lcs.compute; lcs.compute = function(callback, T, limit) { if (typeof limit === 'undefined') { limit = this.defaultLimit(); } recorder.onCompute.call(recorder, callback, T, limit); orig.compute.apply(this, arguments); } orig.nextSnakeHeadForward = lcs.nextSnakeHeadForward; lcs.nextSnakeHeadForward = function(head, k, kmin, kmax, V) { var k0 = orig.nextSnakeHeadForward.apply(this, arguments); var d = kmax; recorder.onSnakeHead.call(recorder, head, k0, d, false); return k0; } orig.nextSnakeHeadBackward = lcs.nextSnakeHeadBackward; lcs.nextSnakeHeadBackward = function(head, k, kmin, kmax, V) { var k0 = orig.nextSnakeHeadBackward.apply(this, arguments); var d = kmax-this.delta; recorder.onSnakeHead.call(recorder, head, k0, d, true); return k0; } orig.middleSnake = lcs.middleSnake; lcs.middleSnake = function(lefthead, righthead) { var d = orig.middleSnake.apply(this, arguments); recorder.onMiddleSnake.call(recorder, lefthead, righthead, d); return d; } }
Replace _.pick by _.pickBy to support Lodash 4
var Sequelize = require('sequelize'), _ = Sequelize.Utils._; module.exports = function(target) { if (target instanceof Sequelize.Model) { // Model createHook(target); } else { // Sequelize instance target.afterDefine(createHook); } } function createHook(model) { model.hook('beforeFindAfterOptions', function(options) { if (options.role) { var role = options.role, attributes = options.attributes, includes = options.include; options.attributes = attrAccessible(model, role, attributes); cleanIncludesRecursive(includes, role); } }); } function attrAccessible(model, role, attributes) { var attrsToReject = attrProtected(model, role); return rejectAttributes(attributes, attrsToReject); } function attrProtected(model, role) { return _.keys(_.pickBy(model.attributes, function(attr, name) { return !_.isUndefined(attr.access) && ( attr.access === false || attr.access[role] === false ); })); } function rejectAttributes(attributes, attrsToRemove) { return _.reject(attributes, function(attr) { if (_.isArray(attr)) { attr = attr[1]; } return _.includes(attrsToRemove, attr); }); } function cleanIncludesRecursive(includes, role) { _.each(includes, function(include) { var model = include.model, attributes = include.attributes; include.attributes = attrAccessible(model, role, attributes); if (include.include) { cleanIncludesRecursive(include.include, role); } }); }
var Sequelize = require('sequelize'), _ = Sequelize.Utils._; module.exports = function(target) { if (target instanceof Sequelize.Model) { // Model createHook(target); } else { // Sequelize instance target.afterDefine(createHook); } } function createHook(model) { model.hook('beforeFindAfterOptions', function(options) { if (options.role) { var role = options.role, attributes = options.attributes, includes = options.include; options.attributes = attrAccessible(model, role, attributes); cleanIncludesRecursive(includes, role); } }); } function attrAccessible(model, role, attributes) { var attrsToReject = attrProtected(model, role); return rejectAttributes(attributes, attrsToReject); } function attrProtected(model, role) { return _.keys(_.pick(model.attributes, function(attr, name) { return !_.isUndefined(attr.access) && ( attr.access === false || attr.access[role] === false ); })); } function rejectAttributes(attributes, attrsToRemove) { return _.reject(attributes, function(attr) { if (_.isArray(attr)) { attr = attr[1]; } return _.includes(attrsToRemove, attr); }); } function cleanIncludesRecursive(includes, role) { _.each(includes, function(include) { var model = include.model, attributes = include.attributes; include.attributes = attrAccessible(model, role, attributes); if (include.include) { cleanIncludesRecursive(include.include, role); } }); }
Add dock block and todo task
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace KawaiiGherkin\Formatter; /** * @author Jefersson Nathan <[email protected]> * @license MIT */ final class FeatureDescription extends AbstractFormatter { /** * @param string $shortDescription * @param array $descriptionLines * * @return string */ public function format($shortDescription, array $descriptionLines) { // TODO: get keyword here, can't say `feature` hardcoded $shortDesc = 'Feature: ' . $shortDescription . PHP_EOL; $longDesc = implode( array_map( function ($descriptionLine) { return $this->indent() . trim($descriptionLine) . PHP_EOL; }, $descriptionLines ) ); return $shortDesc . rtrim($longDesc); } }
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace KawaiiGherkin\Formatter; /** * @author Jefersson Nathan <[email protected]> * @license MIT */ final class FeatureDescription extends AbstractFormatter { public function format($shortDescription, array $descriptionLines) { $shortDesc = 'Feature: ' . $shortDescription . PHP_EOL; $longDesc = implode( array_map( function ($descriptionLine) { return $this->indent() . trim($descriptionLine) . PHP_EOL; }, $descriptionLines ) ); return $shortDesc . rtrim($longDesc); } }
Fix to remove DeprecationWarning message from test log
# -*- coding: ISO-8859-1 -*- #----------------------------------------------------------------------------- # Copyright (c) 2014, HFTools Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import os import pdb import numpy as np import hftools.dataset.helper as helper from hftools.testing import TestCase, make_load_tests from hftools.dataset import hfarray #uncomment to enable doctests #load_tests = make_load_tests(helper) basepath = os.path.split(__file__)[0] from hftools.constants import unit_to_multiplier class Test_add_var_guess(TestCase): def setUp(self): self.old = helper._varname_unit_guess_db.copy() def tearDown(self): helper._varname_unit_guess_db = self.old def test_1(self): helper.add_var_guess("R", "Ohm") self.assertIn("R", helper._varname_unit_guess_db) self.assertEqual("Ohm", helper._varname_unit_guess_db["R"]) class Test_guess_unit_from_varname(TestCase): def setUp(self): self.old = helper._varname_unit_guess_db.copy() def tearDown(self): helper._varname_unit_guess_db = self.old def test_1(self): unit = helper.guess_unit_from_varname("Vds") self.assertEqual(unit, "V")
# -*- coding: ISO-8859-1 -*- #----------------------------------------------------------------------------- # Copyright (c) 2014, HFTools Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- import os import pdb import numpy as np import hftools.dataset.helper as helper from hftools.testing import TestCase, make_load_tests from hftools.dataset import hfarray #uncomment to enable doctests #load_tests = make_load_tests(helper) basepath = os.path.split(__file__)[0] from hftools.constants import unit_to_multiplier class Test_add_var_guess(TestCase): def setUp(self): self.old = helper._varname_unit_guess_db.copy() def tearDown(self): helper._varname_unit_guess_db = self.old def test_1(self): helper.add_var_guess("R", "Ohm") self.assertDictContainsSubset(dict(R="Ohm"), helper._varname_unit_guess_db) class Test_guess_unit_from_varname(TestCase): def setUp(self): self.old = helper._varname_unit_guess_db.copy() def tearDown(self): helper._varname_unit_guess_db = self.old def test_1(self): unit = helper.guess_unit_from_varname("Vds") self.assertEqual(unit, "V")
Fix is blocked check for user status
<?php namespace SumoCoders\FrameworkMultiUserBundle\ValueObject; use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidStatusException; final class Status { const ACTIVE = 'active'; const BLOCKED = 'blocked'; /** @var string */ private $status; /** * @param string $status * * @throws InvalidStatusException */ private function __construct($status) { if (!in_array($status, self::getPossibleStatuses())) { throw InvalidStatusException::withStatus($status); } $this->status = $status; } /** * @param string $status * * @return Status */ public static function fromString($status) { return new self($status); } /** * @return array */ public static function getPossibleStatuses() { $statuses = [ self::ACTIVE, self::BLOCKED, ]; return array_combine($statuses, $statuses); } /** * @return Status */ public static function active() { return new self(self::ACTIVE); } /** * @return Status */ public static function blocked() { return new self(self::BLOCKED); } /** * @return bool */ public function isBlocked() { return $this->status === self::BLOCKED; } /** * @return string */ public function __toString() { return $this->status; } }
<?php namespace SumoCoders\FrameworkMultiUserBundle\ValueObject; use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidStatusException; final class Status { const ACTIVE = 'active'; const BLOCKED = 'blocked'; /** @var string */ private $status; /** * @param string $status * * @throws InvalidStatusException */ private function __construct($status) { if (!in_array($status, self::getPossibleStatuses())) { throw InvalidStatusException::withStatus($status); } $this->status = $status; } /** * @param string $status * * @return Status */ public static function fromString($status) { return new self($status); } /** * @return array */ public static function getPossibleStatuses() { $statuses = [ self::ACTIVE, self::BLOCKED, ]; return array_combine($statuses, $statuses); } /** * @return Status */ public static function active() { return new self(self::ACTIVE); } /** * @return Status */ public static function blocked() { return new self(self::BLOCKED); } /** * @return bool */ public function isBlocked() { return $this->status === self::blocked(); } /** * @return string */ public function __toString() { return $this->status; } }
[MAILWEB-801] Use larger modal for Custom CSS
import React, { useState } from 'react'; import { c } from 'ttag'; import PropTypes from 'prop-types'; import { FormModal, PrimaryButton, Label, Alert, TextArea } from 'react-components'; const CustomThemeModal = ({ onSave, theme: initialTheme = '', ...rest }) => { const [theme, setTheme] = useState(initialTheme); const handleChange = ({ target }) => setTheme(target.value); const handleSubmit = async () => { await onSave(theme); rest.onClose(); }; return ( <FormModal submit={<PrimaryButton type="submit">{c('Action').t`Save`}</PrimaryButton>} onSubmit={handleSubmit} title={c('Title').t`Custom mode`} {...rest} > <Alert type="warning">{c('Warning') .t`Custom modes from third parties can potentially betray your privacy. Only use modes from trusted sources.`}</Alert> <Label className="bl mb0-5" htmlFor="themeTextarea">{c('Label').t`CSS code`}</Label> <TextArea className="mb1" id="themeTextarea" value={theme} placeholder={c('Action').t`Insert CSS code here`} onChange={handleChange} /> </FormModal> ); }; CustomThemeModal.propTypes = { onSave: PropTypes.func.isRequired, theme: PropTypes.string }; export default CustomThemeModal;
import React, { useState } from 'react'; import { c } from 'ttag'; import PropTypes from 'prop-types'; import { FormModal, PrimaryButton, Label, Alert, TextArea } from 'react-components'; const CustomThemeModal = ({ onSave, theme: initialTheme = '', ...rest }) => { const [theme, setTheme] = useState(initialTheme); const handleChange = ({ target }) => setTheme(target.value); const handleSubmit = async () => { await onSave(theme); rest.onClose(); }; return ( <FormModal submit={<PrimaryButton type="submit">{c('Action').t`Save`}</PrimaryButton>} onSubmit={handleSubmit} title={c('Title').t`Custom mode`} small {...rest} > <Alert type="warning">{c('Warning') .t`Custom modes from third parties can potentially betray your privacy. Only use modes from trusted sources.`}</Alert> <Label className="mb1" htmlFor="themeTextarea">{c('Label').t`CSS code`}</Label> <TextArea className="mb1" id="themeTextarea" value={theme} placeholder={c('Action').t`Insert CSS code here`} onChange={handleChange} /> </FormModal> ); }; CustomThemeModal.propTypes = { onSave: PropTypes.func.isRequired, theme: PropTypes.string }; export default CustomThemeModal;
Add correct project id to projects details webservice. The test fails
<?php namespace fennecweb\ajax\details; use \PDO as PDO; /** * Web Service. * Returns a project according to the project ID. */ class Projects extends \fennecweb\WebService { /** * @param $querydata[] * @returns Array $result * <code> * array('project_id': {biomfile}); * </code> */ public function execute($querydata) { $db = $this->openDbConnection($querydata); $result = array(); $project_id = $querydata['id']; if (!isset($_SESSION)) { session_start(); } $query_get_project_details = <<<EOF SELECT project FROM full_webuser_data WHERE webuser_data_id = :project_id AND provider = :provider AND oauth_id = :oauth_id EOF; $stm_get_project_details = $db->prepare($query_get_project_details); $stm_get_project_details->bindValue('project_id', $project_id); $stm_get_project_details->bindValue('provider', $_SESSION['user']['provider']); $stm_get_project_details->bindValue('oauth_id', $_SESSION['user']['id']); $stm_get_project_details->execute(); while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) { $result[$project_id] = $row['project']; } return $result; } }
<?php namespace fennecweb\ajax\details; use \PDO as PDO; /** * Web Service. * Returns a project according to the project ID. */ class Projects extends \fennecweb\WebService { /** * @param $querydata[] * @returns Array $result * <code> * array('project_id': {biomfile}); * </code> */ public function execute($querydata) { $db = $this->openDbConnection($querydata); $result = array(); $project_id = $querydata['id']; if (!isset($_SESSION)) { session_start(); } $query_get_project_details = <<<EOF SELECT project FROM full_webuser_data WHERE project->>'id' = :project_id AND provider = :provider AND oauth_id = :oauth_id EOF; $stm_get_project_details = $db->prepare($query_get_project_details); $stm_get_project_details->bindValue('project_id', $project_id); $stm_get_project_details->bindValue('provider', $_SESSION['user']['provider']); $stm_get_project_details->bindValue('oauth_id', $_SESSION['user']['id']); $stm_get_project_details->execute(); while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) { $result[$project_id] = $row['project']; } return $result; } }
Change script add API call
define('app/controllers/scripts', ['app/controllers/base_array', 'app/models/script'], // // Scripts Controller // // @returns Class // function (BaseArrayController, ScriptModel) { 'use strict'; return BaseArrayController.extend({ model: ScriptModel, addScript: function (args) { var that = this; that.set('addingScript', true); Mist.ajax.POST('/scripts/', { 'name': args.script.name, 'exec_type': args.script.type.value, 'locaction_type': args.script.source.value, 'entry_point': args.script.entryPoint, 'script': args.script.script || args.script.url }).success(function (script) { that._addObject(script); }).error(function (message) { Mist.notificationController.notify(message); }).complete(function (success) { that.set('addingScript', false); if (args.callback) args.callback(success); }) } }); } );
define('app/controllers/scripts', ['app/controllers/base_array', 'app/models/script'], // // Scripts Controller // // @returns Class // function (BaseArrayController, ScriptModel) { 'use strict'; return BaseArrayController.extend({ model: ScriptModel, addScript: function (args) { var that = this; that.set('addingScript', true); Mist.ajax.POST('/scripts/', { 'name': args.script.name, 'type': args.script.type.value, 'source': args.script.source.value, 'url': args.script.url, 'entry_point': args.script.entryPoint, 'script': args.script.script }).success(function (script) { that._addObject(script); }).error(function (message) { Mist.notificationController.notify(message); }).complete(function (success) { that.set('addingScript', false); if (args.callback) args.callback(success); }) } }); } );
Fix typo in variable name
import {Transform} from 'stream'; import SVGOptim from 'svgo'; import {PluginError} from 'gulp-util'; const PLUGIN_NAME = 'gulp-svgmin'; module.exports = function (opts) { const stream = new Transform({objectMode: true}); let svgo; if (typeof opts !== 'function') { svgo = new SVGOptim(opts); } stream._transform = function (file, encoding, cb) { if (file.isNull()) { return cb(null, file); } if (file.isStream()) { return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported')); } if (file.isBuffer()) { if (typeof opts === 'function') { svgo = new SVGOptim(opts(file)); } svgo.optimize(String(file.contents), result => { if (result.error) { return cb(new PluginError(PLUGIN_NAME, result.error)); } file.contents = new Buffer(result.data); cb(null, file); }); } }; return stream; };
import {Transform} from 'stream'; import SVGOptim from 'svgo'; import {PluginError} from 'gulp-util'; const PLUGIN_NAME = 'gulp-svgmin'; module.exports = function (opts) { const stream = new Transform({objectMode: true}); let svgo; if (typeof options !== 'function') { svgo = new SVGOptim(opts); } stream._transform = function (file, encoding, cb) { if (file.isNull()) { return cb(null, file); } if (file.isStream()) { return cb(new PluginError(PLUGIN_NAME, 'Streaming not supported')); } if (file.isBuffer()) { if (typeof opts === 'function') { svgo = new SVGOptim(opts(file)); } svgo.optimize(String(file.contents), result => { if (result.error) { return cb(new PluginError(PLUGIN_NAME, result.error)); } file.contents = new Buffer(result.data); cb(null, file); }); } }; return stream; };
BAP-10749: Develop data-collection provider for Permissions and Capabilities - Mark unit tests as incomplete, because it's requre additional work
<?php namespace Oro\Bundle\UserBundle\Tests\Unit\Provider; use Oro\Bundle\UserBundle\Provider\RolePrivilegeCategoryProvider; class CategoryProviderTest extends \PHPUnit_Framework_TestCase { /** @var RolePrivilegeCategoryProvider */ private $categoryProvider; protected function setUp() { $this->categoryProvider = new RolePrivilegeCategoryProvider(); } public function testCategoryListFetchSuccess() { $this->markTestIncomplete( 'This test have to be rewritten because of interface changes' ); $this->assertEquals( [ 'account_management' => [ 'label' => 'Account Management', 'tab' => true ], 'marketing' => [ 'label' => 'Marketing', 'tab' => true ], 'sales_data' => [ 'label' => 'Sales Data', 'tab' => true ], 'address' => [ 'label' => 'Address', 'tab' => false ], 'calendar' => [ 'label' => 'Calendar', 'tab' => false ] ], $this->categoryProvider->getPermissionCategories() ); } }
<?php namespace Oro\Bundle\UserBundle\Tests\Unit\Provider; use Oro\Bundle\UserBundle\Provider\RolePrivilegeCategoryProvider; class CategoryProviderTest extends \PHPUnit_Framework_TestCase { /** @var RolePrivilegeCategoryProvider */ private $categoryProvider; protected function setUp() { $this->categoryProvider = new RolePrivilegeCategoryProvider(); } public function testCategoryListFetchSuccess() { $this->assertEquals( [ 'account_management' => [ 'label' => 'Account Management', 'tab' => true ], 'marketing' => [ 'label' => 'Marketing', 'tab' => true ], 'sales_data' => [ 'label' => 'Sales Data', 'tab' => true ], 'address' => [ 'label' => 'Address', 'tab' => false ], 'calendar' => [ 'label' => 'Calendar', 'tab' => false ] ], $this->categoryProvider->getPermissionCategories() ); } }
Use return value in subgenerator test
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val return val + 2 @send_self def func(this): ret = yield from func2.func(this) assert ret == val + 2 ts.run = True wrapper = func() wait_until_finished(wrapper) assert ts.run
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_send(): ts = State() val = 123 def subgenerator(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_throw(): ts = State() def subgenerator(this): with pytest.raises(CustomError): yield defer(this.throw, CustomError) ts.run = True @send_self def func(this): yield from subgenerator(this) wrapper = func() wait_until_finished(wrapper) assert ts.run def test_subgenerator_repurpose(): ts = State() val = 1234 @send_self def func2(this): assert (yield defer(this.send, val)) == val ts.run = True @send_self def func(this): yield from func2.func(this) wrapper = func() wait_until_finished(wrapper) assert ts.run
Send welcome message at very first of communication channel
#!/usr/bin/env python3 """Example for aiohttp.web websocket server """ import os from aiohttp import web WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html') async def wshandler(request): resp = web.WebSocketResponse() available = resp.can_prepare(request) if not available: with open(WS_FILE, 'rb') as fp: return web.Response(body=fp.read(), content_type='text/html') await resp.prepare(request) await resp.send_str('Welcome!!!') try: print('Someone joined.') for ws in request.app['sockets']: await ws.send_str('Someone joined') request.app['sockets'].append(resp) async for msg in resp: if msg.type == web.WSMsgType.TEXT: for ws in request.app['sockets']: if ws is not resp: await ws.send_str(msg.data) else: return resp return resp finally: request.app['sockets'].remove(resp) print('Someone disconnected.') for ws in request.app['sockets']: await ws.send_str('Someone disconnected.') async def on_shutdown(app): for ws in app['sockets']: await ws.close() def init(): app = web.Application() app['sockets'] = [] app.router.add_get('/', wshandler) app.on_shutdown.append(on_shutdown) return app web.run_app(init())
#!/usr/bin/env python3 """Example for aiohttp.web websocket server """ import os from aiohttp import web WS_FILE = os.path.join(os.path.dirname(__file__), 'websocket.html') async def wshandler(request): resp = web.WebSocketResponse() available = resp.can_prepare(request) if not available: with open(WS_FILE, 'rb') as fp: return web.Response(body=fp.read(), content_type='text/html') await resp.prepare(request) try: print('Someone joined.') for ws in request.app['sockets']: await ws.send_str('Someone joined') request.app['sockets'].append(resp) async for msg in resp: if msg.type == web.WSMsgType.TEXT: for ws in request.app['sockets']: if ws is not resp: await ws.send_str(msg.data) else: return resp return resp finally: request.app['sockets'].remove(resp) print('Someone disconnected.') for ws in request.app['sockets']: await ws.send_str('Someone disconnected.') async def on_shutdown(app): for ws in app['sockets']: await ws.close() def init(): app = web.Application() app['sockets'] = [] app.router.add_get('/', wshandler) app.on_shutdown.append(on_shutdown) return app web.run_app(init())
Check if has session with its own method
<?php namespace Cart; use Cart\Contracts\SessionContract; /** * Class Session * @package Cart */ class Session implements SessionContract { /** * @var string */ protected $name = '_cart'; /** * Session constructor. */ public function __construct() { if ( ! $this->isStarted()) { @session_start(); } } /** * @return bool */ private function isStarted() { return session_status() === PHP_SESSION_ACTIVE ? true : false; } /** * @param $key * @param $value * * @return mixed */ public function put($key, $value) { $_SESSION[$this->name][$key] = serialize($value); return $_SESSION[$this->name][$key]; } /** * @param $key * * @return mixed */ public function get($key) { if ($this->has($key)) { return unserialize($_SESSION[$this->name][$key]); } return false; } /** * @param $key * * @return string */ public function has($key) { return isset($_SESSION[$this->name][$key]); } /** * @param $key * * @return bool */ public function forget($key) { if ($this->has($key)) { unset($_SESSION[$this->name][$key]); return true; } return false; } /** * @return bool */ public function flush() { $_SESSION[$this->name] = []; return true; } }
<?php namespace Cart; use Cart\Contracts\SessionContract; /** * Class Session * @package Cart */ class Session implements SessionContract { /** * @var string */ protected $name = '_cart'; /** * Session constructor. */ public function __construct() { if ( ! $this->isStarted()) { @session_start(); } } /** * @return bool */ private function isStarted() { return session_status() === PHP_SESSION_ACTIVE ? true : false; } /** * @param $key * @param $value * * @return mixed */ public function put($key, $value) { $_SESSION[$this->name][$key] = serialize($value); return $_SESSION[$this->name][$key]; } /** * @param $key * * @return mixed */ public function get($key) { if (isset($_SESSION[$this->name][$key])) { return unserialize($_SESSION[$this->name][$key]); } return false; } /** * @param $key * * @return string */ public function has($key) { return isset($_SESSION[$this->name][$key]); } /** * @param $key * * @return bool */ public function forget($key) { unset($_SESSION[$this->name][$key]); return true; } /** * @return bool */ public function flush() { $_SESSION[$this->name] = []; return true; } }
Return immediately if request is not json Fetching the contents before this check may result in OutOfMemory excpetion if the request is multipart with files.
<?php /* * This file is part of the qandidate/symfony-json-request-transformer package. * * (c) Qandidate.com <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Qandidate\Common\Symfony\HttpKernel\EventListener; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\GetResponseEvent; /** * Transforms the body of a json request to POST parameters. */ class JsonRequestTransformerListener { /** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); if (! $this->isJsonRequest($request)) { return; } $content = $request->getContent(); if (empty($content)) { return; } if (! $this->transformJsonBody($request)) { $response = Response::create('Unable to parse request.', 400); $event->setResponse($response); } } private function isJsonRequest(Request $request) { return 'json' === $request->getContentType(); } private function transformJsonBody(Request $request) { $data = json_decode($request->getContent(), true); if (json_last_error() !== JSON_ERROR_NONE) { return false; } if ($data === null) { return true; } $request->request->replace($data); return true; } }
<?php /* * This file is part of the qandidate/symfony-json-request-transformer package. * * (c) Qandidate.com <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Qandidate\Common\Symfony\HttpKernel\EventListener; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\GetResponseEvent; /** * Transforms the body of a json request to POST parameters. */ class JsonRequestTransformerListener { /** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); $content = $request->getContent(); if (empty($content)) { return; } if (! $this->isJsonRequest($request)) { return; } if (! $this->transformJsonBody($request)) { $response = Response::create('Unable to parse request.', 400); $event->setResponse($response); } } private function isJsonRequest(Request $request) { return 'json' === $request->getContentType(); } private function transformJsonBody(Request $request) { $data = json_decode($request->getContent(), true); if (json_last_error() !== JSON_ERROR_NONE) { return false; } if ($data === null) { return true; } $request->request->replace($data); return true; } }
Disable JPEG decoder test for now.
package us.ihmc.codecs; import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Random; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import us.ihmc.codecs.generated.FilterModeEnum; import us.ihmc.codecs.generated.YUVPicture; import us.ihmc.codecs.yuv.JPEGDecoder; import us.ihmc.codecs.yuv.JPEGEncoder; public class JPEGTest { @Disabled("Initialization error, need to fix") @Test public void testEncodeDecode() throws IOException { JPEGDecoder decoder = new JPEGDecoder(); JPEGEncoder encoder = new JPEGEncoder(); Random random = new Random(9872412L); for (int i = 0; i < 1000; i++) { YUVPicture jpeg = decoder.readJPEG(JPEGExample.class.getClassLoader().getResource("testImage.jpg")); int w = random.nextInt(3000); int h = random.nextInt(3000); jpeg.scale(w + 1, h + 1, FilterModeEnum.kFilterLinear); ByteBuffer buffer = encoder.encode(jpeg, 90); YUVPicture res = decoder.decode(buffer); assertEquals(jpeg.getWidth(), res.getWidth()); assertEquals(jpeg.getHeight(), res.getHeight()); jpeg.delete(); res.delete(); } } }
package us.ihmc.codecs; import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Random; import org.junit.jupiter.api.Test; import us.ihmc.codecs.generated.FilterModeEnum; import us.ihmc.codecs.generated.YUVPicture; import us.ihmc.codecs.yuv.JPEGDecoder; import us.ihmc.codecs.yuv.JPEGEncoder; public class JPEGTest { @Test public void testEncodeDecode() throws IOException { JPEGDecoder decoder = new JPEGDecoder(); JPEGEncoder encoder = new JPEGEncoder(); Random random = new Random(9872412L); for (int i = 0; i < 1000; i++) { YUVPicture jpeg = decoder.readJPEG(JPEGExample.class.getClassLoader().getResource("testImage.jpg")); int w = random.nextInt(3000); int h = random.nextInt(3000); jpeg.scale(w + 1, h + 1, FilterModeEnum.kFilterLinear); ByteBuffer buffer = encoder.encode(jpeg, 90); YUVPicture res = decoder.decode(buffer); assertEquals(jpeg.getWidth(), res.getWidth()); assertEquals(jpeg.getHeight(), res.getHeight()); jpeg.delete(); res.delete(); } } }
Add a new spec to test the simpler placemark
/*global defineSuite*/ defineSuite(['DynamicScene/KmlDataSource', 'DynamicScene/DynamicObjectCollection', 'Core/loadXML', 'Core/Event' ], function( KmlDataSource, loadXML, DynamicObjectCollection, Event) { "use strict"; /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/ it('default constructor has expected values', function() { var dataSource = new KmlDataSource(); expect(dataSource.getChangedEvent()).toBeInstanceOf(Event); expect(dataSource.getErrorEvent()).toBeInstanceOf(Event); expect(dataSource.getClock()).toBeUndefined(); expect(dataSource.getDynamicObjectCollection()).toBeInstanceOf(DynamicObjectCollection); expect(dataSource.getDynamicObjectCollection().getObjects().length).toEqual(0); expect(dataSource.getIsTimeVarying()).toEqual(false); }); it('Simple Test loading Kml', function() { var dataSource = new KmlDataSource(); var url = 'http://localhost:8080/Apps/CesiumViewer/Gallery/simplePlacemark.kml'; dataSource.loadUrl(url); }); it('Test loading Kml', function() { var dataSource = new KmlDataSource(); var url = 'http://localhost:8080/Apps/CesiumViewer/Gallery/KML_Samples.kml'; dataSource.loadUrl(url); }); });
/*global defineSuite*/ defineSuite(['DynamicScene/KmlDataSource', 'DynamicScene/DynamicObjectCollection', 'Core/loadXML', 'Core/Event' ], function( KmlDataSource, loadXML, DynamicObjectCollection, Event) { "use strict"; /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/ it('default constructor has expected values', function() { var dataSource = new KmlDataSource(); expect(dataSource.getChangedEvent()).toBeInstanceOf(Event); expect(dataSource.getErrorEvent()).toBeInstanceOf(Event); expect(dataSource.getClock()).toBeUndefined(); expect(dataSource.getDynamicObjectCollection()).toBeInstanceOf(DynamicObjectCollection); expect(dataSource.getDynamicObjectCollection().getObjects().length).toEqual(0); expect(dataSource.getIsTimeVarying()).toEqual(false); }); it('Test loading Kml', function() { var dataSource = new KmlDataSource(); var url = 'http://localhost:8080/Apps/CesiumViewer/Gallery/KML_Samples.kml'; dataSource.loadUrl(url); }); });
Read HTTP error stream before closing it It wasn't causing problems, but it looks odd.
package io.bitsquare.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; // TODO route over tor public class HttpClient { private final String baseUrl; public HttpClient(String baseUrl) { this.baseUrl = baseUrl; } public String requestWithGET(String param) throws IOException, HttpException { HttpURLConnection connection = null; try { URL url = new URL(baseUrl + param); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(10_000); connection.setReadTimeout(10_000); if (connection.getResponseCode() == 200) { return convertInputStreamToString(connection.getInputStream()); } else { String error = convertInputStreamToString(connection.getErrorStream()); connection.getErrorStream().close(); throw new HttpException(error); } } finally { if (connection != null) connection.getInputStream().close(); } } private String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString(); } @Override public String toString() { return "HttpClient{" + "baseUrl='" + baseUrl + '\'' + '}'; } }
package io.bitsquare.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; // TODO route over tor public class HttpClient { private final String baseUrl; public HttpClient(String baseUrl) { this.baseUrl = baseUrl; } public String requestWithGET(String param) throws IOException, HttpException { HttpURLConnection connection = null; try { URL url = new URL(baseUrl + param); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); if (connection.getResponseCode() == 200) { return convertInputStreamToString(connection.getInputStream()); } else { connection.getErrorStream().close(); throw new HttpException(convertInputStreamToString(connection.getErrorStream())); } } finally { if (connection != null) connection.getInputStream().close(); } } private String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString(); } @Override public String toString() { return "HttpClient{" + "baseUrl='" + baseUrl + '\'' + '}'; } }
Make sure $_SERVER['HTTP_HOST'] is defined
<?php namespace Systemblast\Engine\Http; class Request { private static $instance = null; public static function make() { // Check if instance is already exists if (self::$instance == null) { self::$instance = (new Request())->create(); } return self::$instance; } protected function create() { /** * to get the same $_SERVER['REQUEST_URI'] on both localhost and live server */ if (isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'localhost') { $url = preg_replace('#^https?://#', '', $_SERVER['APP_URL']); $url = str_replace($_SERVER['HTTP_HOST'], '', $url); $_SERVER['REQUEST_URI'] = str_replace($url, '', $_SERVER['REQUEST_URI']); } return \Zend\Diactoros\ServerRequestFactory::fromGlobals( $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES ); } private function __clone() { // Stopping Clonning of Object } private function __wakeup() { // Stopping unserialize of object } }
<?php namespace Systemblast\Engine\Http; class Request { private static $instance = null; public static function make() { // Check if instance is already exists if (self::$instance == null) { self::$instance = (new Request())->create(); } return self::$instance; } protected function create() { /** * to get the same $_SERVER['REQUEST_URI'] on both localhost and live server */ if ($_SERVER['HTTP_HOST'] == 'localhost') { $url = preg_replace('#^https?://#', '', $_SERVER['APP_URL']); $url = str_replace($_SERVER['HTTP_HOST'], '', $url); $_SERVER['REQUEST_URI'] = str_replace($url, '', $_SERVER['REQUEST_URI']); } return \Zend\Diactoros\ServerRequestFactory::fromGlobals( $_SERVER, $_GET, $_POST, $_COOKIE, $_FILES ); } private function __clone() { // Stopping Clonning of Object } private function __wakeup() { // Stopping unserialize of object } }
Add support for task-specific workers
;(function (name, definition) { var theModule = definition(), hasDefine = typeof define === 'function' && define.amd, hasExports = typeof module !== 'undefined' && module.exports; if(hasDefine) // AMD Module define(theModule); else if(hasExports) // Node.js Module module.exports = theModule; else this[name] = theModule; })('SerialQueue', function() { 'use strict'; var Q = function(worker) { this._running = false; this._worker = worker; this._q = []; }; Q.prototype = { constructor: Q, push: function(item, worker) { this._q.push({item: item, worker: worker}); this._run(); }, _runNext: function(done) { var self = this; var next = function() { if(self._q.length) { var task = self._q.shift(); (task.worker || self._worker)(task.item, next); } else { done(); } } next(); }, _run: function() { var self = this; if(!self._running) { self._running = true; self._runNext(function() { self._running = false; }); } } }; return Q; });
;(function (name, definition) { var theModule = definition(), hasDefine = typeof define === 'function' && define.amd, hasExports = typeof module !== 'undefined' && module.exports; if(hasDefine) // AMD Module define(theModule); else if(hasExports) // Node.js Module module.exports = theModule; else this[name] = theModule; })('SerialQueue', function() { 'use strict'; var Q = function(worker) { this._running = false; this._worker = worker; this._q = []; }; Q.prototype = { constructor: Q, push: function(item) { this._q.push(item); this._run(); }, _runNext: function(done) { var self = this; var workerDone = function() { if(self._q.length) self._worker(self._q.shift(), workerDone); else done(); } workerDone(); }, _run: function() { var self = this; if(!self._running) { self._running = true; self._runNext(function() { self._running = false; }); } } }; return Q; });
Revert "fix genetics accessRules problem" This reverts commit 6284919a9db8b401b0506cffea048da399b765cf.
<?php class DefaultController extends BaseEventTypeController { public function volumeRemaining($event_id) { $volume_remaining = 0; if ($api = Yii::app()->moduleAPI->get('OphInDnaextraction')) { $volume_remaining = $api->volumeRemaining($event_id); } return $volume_remaining; } public function accessRules() { return array( array('allow', 'actions' => array('Create', 'Update', 'View', 'Print','saveCanvasImages','PDFprint' ), 'roles' => array('OprnEditDnaSample'), ), array('allow', 'actions' => array('View', 'Print','saveCanvasImages','PDFprint'), 'roles' => array('OprnViewDnaSample'), ), ); } public function actionCreate() { parent::actionCreate(); } public function actionUpdate($id) { parent::actionUpdate($id); } public function actionView($id) { parent::actionView($id); } public function actionPrint($id) { parent::actionPrint($id); } public function isRequiredInUI(BaseEventTypeElement $element) { return true; } }
<?php class DefaultController extends BaseEventTypeController { public function volumeRemaining($event_id) { $volume_remaining = 0; if ($api = Yii::app()->moduleAPI->get('OphInDnaextraction')) { $volume_remaining = $api->volumeRemaining($event_id); } return $volume_remaining; } public function checkCreateAccess() { return $this->checkAccess('OprnEditDnaSample')||; } public function checkUpdateAccess() { return $this->checkAccess('OprnEditDnaSample'); } public function checkViewAccess() { return $this->checkAccess('OprnEditDnaSample') || $this->checkAccess('OprnViewDnaSample') } public function checkPrintAccess() { return $this->checkAccess('OprnEditDnaSample') || $this->checkAccess('OprnViewDnaSample'); } public function actionCreate() { parent::actionCreate(); } public function actionUpdate($id) { parent::actionUpdate($id); } public function actionView($id) { parent::actionView($id); } public function actionPrint($id) { parent::actionPrint($id); } public function isRequiredInUI(BaseEventTypeElement $element) { return true; } }
Update shebang to use /usr/bin/env. Remove the /ms/dist reference.
#!/usr/bin/env python2.6 # ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # Copyright (C) 2008 Morgan Stanley # # This module is part of Aquilon """Add /ms/dist to traceback of files compiled in /ms/dev.""" import sys import py_compile import re def main(args=None): """Except for the custom dfile, this is stolen directly from py_compile. Compile all of the given filename arguments. This custom version replaces /ms/dev in the path with /ms/dist to match our environment usage. """ if args is None: args = sys.argv[1:] dev_re = re.compile(r'/ms/dev/(?P<meta>[^/]+)/(?P<proj>[^/]+)' r'/(?P<release>[^/]+)/install/(?P<path>.*)') for filename in args: try: m = dev_re.match(filename) if m: dfile = "/ms/dist/%(meta)s/PROJ/%(proj)s" \ "/%(release)s/%(path)s" % m.groupdict() else: dfile = filename py_compile.compile(filename, dfile=dfile, doraise=True) except py_compile.PyCompileError, e: sys.stderr.write(e.msg) if __name__ == "__main__": main()
#!/ms/dist/python/PROJ/core/2.5.2-1/bin/python # ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # Copyright (C) 2008 Morgan Stanley # # This module is part of Aquilon """Add /ms/dist to traceback of files compiled in /ms/dev.""" import sys import py_compile import re def main(args=None): """Except for the custom dfile, this is stolen directly from py_compile. Compile all of the given filename arguments. This custom version replaces /ms/dev in the path with /ms/dist to match our environment usage. """ if args is None: args = sys.argv[1:] dev_re = re.compile(r'/ms/dev/(?P<meta>[^/]+)/(?P<proj>[^/]+)' r'/(?P<release>[^/]+)/install/(?P<path>.*)') for filename in args: try: m = dev_re.match(filename) if m: dfile = "/ms/dist/%(meta)s/PROJ/%(proj)s" \ "/%(release)s/%(path)s" % m.groupdict() else: dfile = filename py_compile.compile(filename, dfile=dfile, doraise=True) except py_compile.PyCompileError, e: sys.stderr.write(e.msg) if __name__ == "__main__": main()
Fix PandA firmware issue with a hack
from malcolm.compat import str_ from malcolm.core.serializable import Serializable, deserialize_object from malcolm.core.vmeta import VMeta @Serializable.register_subclass("malcolm:core/ChoiceMeta:1.0") class ChoiceMeta(VMeta): """Meta object containing information for a enum""" endpoints = ["description", "choices", "tags", "writeable", "label"] def __init__(self, description="", choices=None, tags=None, writeable=False, label=""): super(ChoiceMeta, self).__init__(description, tags, writeable, label) if choices is None: choices = [] self.set_choices(choices) def set_choices(self, choices, notify=True): """Set the choices list""" choices = [deserialize_object(c, str_) for c in choices] self.set_endpoint_data("choices", choices, notify) def validate(self, value): """ Check if the value is valid returns it Args: value: Value to validate Returns: Value if it is valid Raises: ValueError: If value not valid """ if value is None: if self.choices: return self.choices[0] else: return "" elif value in self.choices: return value elif isinstance(value, int) and value < len(self.choices): return self.choices[value] else: # Hack for PANDA as we get STATUS overriding status return value raise ValueError( "%s is not a valid value in %s" % (value, self.choices))
from malcolm.compat import str_ from malcolm.core.serializable import Serializable, deserialize_object from malcolm.core.vmeta import VMeta @Serializable.register_subclass("malcolm:core/ChoiceMeta:1.0") class ChoiceMeta(VMeta): """Meta object containing information for a enum""" endpoints = ["description", "choices", "tags", "writeable", "label"] def __init__(self, description="", choices=None, tags=None, writeable=False, label=""): super(ChoiceMeta, self).__init__(description, tags, writeable, label) if choices is None: choices = [] self.set_choices(choices) def set_choices(self, choices, notify=True): """Set the choices list""" choices = [deserialize_object(c, str_) for c in choices] self.set_endpoint_data("choices", choices, notify) def validate(self, value): """ Check if the value is valid returns it Args: value: Value to validate Returns: Value if it is valid Raises: ValueError: If value not valid """ if value is None: if self.choices: return self.choices[0] else: return "" elif value in self.choices: return value elif isinstance(value, int) and value < len(self.choices): return self.choices[value] else: raise ValueError( "%s is not a valid value in %s" % (value, self.choices))
Fix vex dialog being off topic
(function() { 'use strict'; angular.module('app.controllers.channels', []). controller('Channels', Channels); Channels.$inject = ['$rootScope', 'chat']; function Channels($rootScope, chat) { var vm = this; $rootScope.selected = '#roomtest'; vm.select = function(channel) { console.log(channel); vm.selected = channel; $rootScope.selected = channel; }; vm.add = function() { vex.dialog.prompt({ message: 'What channel do you want to join?', placeholder: 'Channel name #...', callback: function(value) { if (!value) { return; } $rootScope.logs[value] = []; chat.scrollback(value); vm.select(value); chat.join(value); return console.log(value); } }); }; } })();
(function() { 'use strict'; angular.module('app.controllers.channels', []). controller('Channels', Channels); Channels.$inject = ['$rootScope', 'chat']; function Channels($rootScope, chat) { var vm = this; $rootScope.selected = '#roomtest'; vm.select = function(channel) { console.log(channel); vm.selected = channel; $rootScope.selected = channel; }; vm.add = function() { vex.dialog.prompt({ message: 'What planet did the aliens come from?', placeholder: 'Planet name', callback: function(value) { if (!value) { return; } $rootScope.logs[value] = []; chat.scrollback(value); vm.select(value); chat.join(value); return console.log(value); } }); }; } })();
Stop sharing the query builder, this was a bad idea
<?php namespace ZerobRSS; use \Auryn\Injector; class Middlewares { /** @var Injector */ private $injector; public function __construct(Injector $injector) { $this->injector = $injector; } /** * Closure to load controllers */ public function controllerLoader($controller, $method) { $injector = $this->injector; return function () use ($controller, $method, $injector) { $controller = $injector->make('ZerobRSS\Controllers\\'.$controller); return call_user_func_array([$controller, $method], func_get_args()); }; } /** * Middleware to initiate the database connection */ public function db() { $injector = $this->injector; return function () use ($injector) { $config = require(PROJECT_ROOT.'/config.php'); $dbConfig = $config['environments']['database']; // Connect to database $dbalConfig = new \Doctrine\DBAL\Configuration(); $dbalConn = \Doctrine\DBAL\DriverManager::getConnection([ 'url' => $dbConfig['adapter'].'://'.$dbConfig['user'].':'.$dbConfig['pass'].'@'.$dbConfig['host'].':' .$dbConfig['port'].'/'.$dbConfig['name'].'?charset='.$dbConfig['charset'] ], $dbalConfig); // Set default fetch-mode to fetch objects $dbalConn->setFetchMode(\PDO::FETCH_OBJ); // Share \Doctrine\DBAL\Connection $injector->share($dbalConn); }; } }
<?php namespace ZerobRSS; use \Auryn\Injector; class Middlewares { /** @var Injector */ private $injector; public function __construct(Injector $injector) { $this->injector = $injector; } /** * Closure to load controllers */ public function controllerLoader($controller, $method) { $injector = $this->injector; return function () use ($controller, $method, $injector) { $controller = $injector->make('ZerobRSS\Controllers\\'.$controller); return call_user_func_array([$controller, $method], func_get_args()); }; } /** * Middleware to initiate the database connection */ public function db() { $injector = $this->injector; return function () use ($injector) { $config = require(PROJECT_ROOT.'/config.php'); $dbConfig = $config['environments']['database']; $dbalConfig = new \Doctrine\DBAL\Configuration(); $dbalConn = \Doctrine\DBAL\DriverManager::getConnection([ 'url' => $dbConfig['adapter'].'://'.$dbConfig['user'].':'.$dbConfig['pass'].'@'.$dbConfig['host'].':' .$dbConfig['port'].'/'.$dbConfig['name'].'?charset='.$dbConfig['charset'] ], $dbalConfig); $dbalConn->setFetchMode(\PDO::FETCH_OBJ); $injector->share($dbalConn); // Share \Doctrine\DBAL\Connection $injector->share($dbalConn->createQueryBuilder()); // Share \Doctrine\DBAL\Query\QueryBuilder }; } }
Add track number and album artist to info
var osa = require('osa2') function play(uri) { if (uri) return playTrack(uri) return osa(() => Application('Spotify').play())() } function playTrack(uri) { return osa((uri) => Application('Spotify').playTrack(uri))(uri) } function pause() { return osa(() => Application('Spotify').pause())() } function toggle() { return osa(() => Application('Spotify').playpause())() } function next() { return osa(() => Application('Spotify').nextTrack())() } function prev() { return osa(() => Application('Spotify').previousTrack())() } function getCurrentTrack() { return osa(() => { var track = Application('Spotify').currentTrack return { id: track.id(), name: track.name(), album: track.album(), artist: track.artist(), number: track.trackNumber(), duration: track.duration(), artwork: track.artworkUrl(), popularity: track.popularity(), albumArtist: track.albumArtist(), } })() } function getPlayerState() { return osa(() => { var s = Application('Spotify') return { state: s.playerState(), volume: s.soundVolume(), position: s.playerPosition(), repeating: s.repeating(), shuffling: s.shuffling(), } })() } module.exports = { play, pause, toggle, next, prev, getCurrentTrack, getPlayerState }
var osa = require('osa2') function play(uri) { if (uri) return playTrack(uri) return osa(() => Application('Spotify').play())() } function playTrack(uri) { return osa((uri) => Application('Spotify').playTrack(uri))(uri) } function pause() { return osa(() => Application('Spotify').pause())() } function toggle() { return osa(() => Application('Spotify').playpause())() } function next() { return osa(() => Application('Spotify').nextTrack())() } function prev() { return osa(() => Application('Spotify').previousTrack())() } function getCurrentTrack() { return osa(() => { var track = Application('Spotify').currentTrack return { id: track.id(), name: track.name(), album: track.album(), artist: track.artist(), duration: track.duration(), artwork: track.artworkUrl(), popularity: track.popularity() } })() } function getPlayerState() { return osa(() => { var s = Application('Spotify') return { state: s.playerState(), volume: s.soundVolume(), position: s.playerPosition(), repeating: s.repeating(), shuffling: s.shuffling(), } })() } module.exports = { play, pause, toggle, next, prev, getCurrentTrack, getPlayerState }
Fix: Make sure includePaths default is specific for each file
var map = require('map-stream') , sass = require('node-sass') , path = require('path') , gutil = require('gulp-util') , ext = gutil.replaceExtension ; module.exports = function (options) { var opts = options ? options : {}; function nodeSass (file, cb) { var fileDir = path.dirname(file.path); var addedLocalDirPath = false; if (file.isNull()) { return cb(null, file); } if (path.basename(file.path).indexOf('_') === 0) { return cb(); } opts.data = file.contents.toString(); if (opts.includePaths && Array.isArray(opts.includePaths)) { if (opts.includePaths.indexOf(fileDir) === -1) { opts.includePaths.push(fileDir); addedLocalDirPath = true; } } else { opts.includePaths = [fileDir]; } opts.success = function (css) { file.path = ext(file.path, '.css'); file.contents = new Buffer(css); cb(null, file); }; opts.error = function (err) { if (opts.errLogToConsole) { gutil.log('[gulp-sass] ' + err); return cb(); } return cb(new gutil.PluginError('gulp-sass', err)); }; sass.render(opts); if (addedLocalDirPath) opts.includePaths.pop(); } return map(nodeSass); };
var map = require('map-stream') , sass = require('node-sass') , path = require('path') , gutil = require('gulp-util') , ext = gutil.replaceExtension ; module.exports = function (options) { var opts = options ? options : {}; function nodeSass (file, cb) { if (file.isNull()) { return cb(null, file); } if (path.basename(file.path).indexOf('_') === 0) { return cb(); } opts.data = file.contents.toString(); var fileDir = path.dirname(file.path); if (opts.includePaths && Array.isArray(opts.includePaths)) { if (opts.includePaths.indexOf(fileDir) === -1) { opts.includePaths.push(fileDir) } } else { opts.includePaths = [fileDir]; } opts.success = function (css) { file.path = ext(file.path, '.css'); file.contents = new Buffer(css); cb(null, file); }; opts.error = function (err) { if (opts.errLogToConsole) { gutil.log('[gulp-sass] ' + err); return cb(); } return cb(new gutil.PluginError('gulp-sass', err)); }; sass.render(opts); } return map(nodeSass); };
Fix incorrect redirection after log in.
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import view from './view'; //==================================================================== export default angular.module('xoWebApp.login', [ uiRouter, ]) .config(function ($stateProvider) { $stateProvider.state('login', { url: '/login', controller: 'LoginCtrl', template: view, }); }) .controller('LoginCtrl', function($scope, $state, $rootScope, xoApi) { var toState, toStateParams; { let tmp = $rootScope._login; if (tmp) { toState = tmp.state.name; toStateParams = tmp.stateParams; delete $rootScope._login; } else { toState = 'index'; } } $scope.$watch(() => xoApi.user, function (user) { // When the user is logged in, go the wanted view, fallbacks on // the index view if necessary. if (user) { $state.go(toState, toStateParams).catch(function () { $state.go('index'); }); } }); Object.defineProperties($scope, { user: { get() { return xoApi.user; }, }, status: { get() { return xoApi.status; } }, }); $scope.logIn = xoApi.logIn; }) // A module exports its name. .name ;
import angular from 'angular'; import uiRouter from 'angular-ui-router'; import view from './view'; //==================================================================== export default angular.module('xoWebApp.login', [ uiRouter, ]) .config(function ($stateProvider) { $stateProvider.state('login', { url: '/login', controller: 'LoginCtrl', template: view, }); }) .controller('LoginCtrl', function($scope, $state, $rootScope, xoApi) { var toState, toStateParams; { let state = $rootScope._login; if (state && (state = state.state)) { toState = state.name; toStateParams = state.stateParams; delete $rootScope._login; } else { toState = 'index'; } } $scope.$watch(() => xoApi.user, function (user) { // When the user is logged in, go the wanted view, fallbacks on // the index view if necessary. if (user) { $state.go(toState, toStateParams).catch(function () { $state.go('index'); }); } }); Object.defineProperties($scope, { user: { get() { return xoApi.user; }, }, status: { get() { return xoApi.status; } }, }); $scope.logIn = xoApi.logIn; }) // A module exports its name. .name ;
feature: Create markdown doc files from source
/* * grunt-dox * https://github.com/iVantage/grunt-dox * * Copyright (c) 2014 Evan Sheffield * Licensed under the MIT license. */ 'use strict'; var dox = require('../node_modules/dox/index.js'); module.exports = function(grunt) { grunt.registerMultiTask('dox', 'Creates documentation markdown for your source code', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ lang: 'js' }); // Iterate over all specified file groups. this.files.forEach(function(filePair) { filePair.src.forEach(function(src) { if(grunt.file.isDir(src)) { return; } var data = grunt.file.read(src) , comments = dox.parseComments(data, {language: options.lang}) , markdown , dest = filePair.dest; try { markdown = dox.api(comments); } catch (e) { grunt.log.error('Error generating documentation for file ' + src.cyan + ': ' + e); return; } // Write the generated markdown to a file grunt.file.write(dest, markdown); grunt.log.writeln('Created documentation for ' + src.cyan +'--> ' + dest.cyan + ''); }); }); }); };
/* * grunt-dox * https://github.com/iVantage/grunt-dox * * Copyright (c) 2014 Evan Sheffield * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('dox', 'Creates documentation markdown for your source code', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ punctuation: '.', separator: ', ' }); // Iterate over all specified file groups. this.files.forEach(function(f) { // Concat specified files. var src = f.src.filter(function(filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function(filepath) { // Read file source. return grunt.file.read(filepath); }).join(grunt.util.normalizelf(options.separator)); // Handle options. src += options.punctuation; // Write the destination file. grunt.file.write(f.dest, src); // Print a success message. grunt.log.writeln('File "' + f.dest + '" created.'); }); }); };
Remove JWT_AUTH check from settings JWT settings has been removed in OpenID change and currently there isn't use for this.
from .util import get_settings, load_local_settings, load_secret_key from . import base settings = get_settings(base) load_local_settings(settings, "local_settings") load_secret_key(settings) settings['CKEDITOR_CONFIGS'] = { 'default': { 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {'class': 'lead'}, }, ], 'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'], 'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);', 'extraPlugins': 'video,dialog,fakeobjects,iframe', 'toolbar': [ ['Styles', 'Format'], ['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['BulletedList', 'NumberedList'], ['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'] ] }, } globals().update(settings) # Export the settings for Django to use.
from .util import get_settings, load_local_settings, load_secret_key from . import base settings = get_settings(base) load_local_settings(settings, "local_settings") load_secret_key(settings) if not settings["DEBUG"] and settings["JWT_AUTH"]["JWT_SECRET_KEY"] == "kerrokantasi": raise ValueError("Refusing to run out of DEBUG mode with insecure JWT secret key.") settings['CKEDITOR_CONFIGS'] = { 'default': { 'stylesSet': [ { "name": 'Lead', "element": 'p', "attributes": {'class': 'lead'}, }, ], 'contentsCss': ['%sckeditor/ckeditor/contents.css' % settings['STATIC_URL'], '.lead { font-weight: bold;}'], 'extraAllowedContent': 'video [*]{*}(*);source [*]{*}(*);', 'extraPlugins': 'video,dialog,fakeobjects,iframe', 'toolbar': [ ['Styles', 'Format'], ['Bold', 'Italic', 'Underline', 'StrikeThrough', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['BulletedList', 'NumberedList'], ['Image', 'Video', 'Iframe', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'] ] }, } globals().update(settings) # Export the settings for Django to use.
Correct error in client for streaming
define([ "Underscore", "yapp/yapp", "vendors/socket.io" ], function(_, yapp, io) { var logging = yapp.Logger.addNamespace("updates"); var Updates = new (yapp.Class.extend({ /* Constructor */ initialize: function() { this.url = [window.location.protocol, '//', window.location.host].join(''); logging.log("Connexion to "+this.url); this.socket = io.connect(this.url); // Video streaming stats this.socket.on('stats', _.bind(function(data) { //logging.log("streaming stats ", data); this.trigger("streaming:stats", data); }, this)); // Remote control connected this.socket.on('remote', _.bind(function() { logging.log("remote is connected"); this.trigger("remote:start"); }, this)); // Touch input from remote this.socket.on('remote_input', _.bind(function(data) { logging.log("remote input ", data); this.trigger("remote:input", data); }, this)); // Search from remote this.socket.on('remote_search', _.bind(function(q) { logging.log("remote search ", q); this.trigger("remote:search", q); yapp.History.navigate("search/:q", { "q": q }); }, this)); // Connexion error this.socket.on('error', _.bind(function(data) { logging.error("error in socket.io") }, this)); return this; }, })); return Updates; });
define([ "Underscore", "yapp/yapp", "vendors/socket.io" ], function(_, yapp, io) { var logging = yapp.Logger.addNamespace("updates"); var Updates = new (yapp.Class.extend({ /* Constructor */ initialize: function() { this.url = [window.location.protocol, '//', window.location.host].join(''); logging.log("Connexion to "+this.url); this.socket = io.connect(this.url); // Video streaming stats this.socket.on('stats', function(data) { //logging.log("streaming stats ", data); this.trigger("streaming:stats", data); }); // Remote control connected this.socket.on('remote', _.bind(function() { logging.log("remote is connected"); this.trigger("remote:start"); }, this)); // Touch input from remote this.socket.on('remote_input', _.bind(function(data) { logging.log("remote input ", data); this.trigger("remote:input", data); }, this)); // Search from remote this.socket.on('remote_search', _.bind(function(q) { logging.log("remote search ", q); this.trigger("remote:search", q); yapp.History.navigate("search/:q", { "q": q }); }, this)); // Connexion error this.socket.on('error', _.bind(function(data) { logging.error("error in socket.io") }, this)); return this; }, })); return Updates; });
Set deprecated php-ext-zip used class
<?php /** * Created by PhpStorm. * User: LPALQUILER-11 * Date: 29/08/2018 * Time: 17:30. */ namespace Greenter\Zip; use ZipArchive; /** * Class ZipFileDecompress. * @deprecated deprecated since version v4.0.3, use ZipFlyDecompress */ class ZipFileDecompress implements DecompressInterface { /** * Extract files. * * @param string $content * @param callable|null $filter * * @return array */ public function decompress(?string $content, callable $filter = null): ?array { $temp = tempnam(sys_get_temp_dir(), time().'.zip'); file_put_contents($temp, $content); $zip = new ZipArchive(); $output = []; if (true === $zip->open($temp) && $zip->numFiles > 0) { $output = iterator_to_array($this->getFiles($zip, $filter)); } $zip->close(); unlink($temp); return $output; } private function getFiles(ZipArchive $zip, $filter) { $total = $zip->numFiles; for ($i = 0; $i < $total; ++$i) { $name = $zip->getNameIndex($i); if (!$filter || $filter($name)) { yield [ 'filename' => $name, 'content' => $zip->getFromIndex($i), ]; } } } }
<?php /** * Created by PhpStorm. * User: LPALQUILER-11 * Date: 29/08/2018 * Time: 17:30. */ namespace Greenter\Zip; use ZipArchive; /** * Class ZipFileDecompress. */ class ZipFileDecompress implements DecompressInterface { /** * Extract files. * * @param string $content * @param callable|null $filter * * @return array */ public function decompress(?string $content, callable $filter = null): ?array { $temp = tempnam(sys_get_temp_dir(), time().'.zip'); file_put_contents($temp, $content); $zip = new ZipArchive(); $output = []; if (true === $zip->open($temp) && $zip->numFiles > 0) { $output = iterator_to_array($this->getFiles($zip, $filter)); } $zip->close(); unlink($temp); return $output; } private function getFiles(ZipArchive $zip, $filter) { $total = $zip->numFiles; for ($i = 0; $i < $total; ++$i) { $name = $zip->getNameIndex($i); if (!$filter || $filter($name)) { yield [ 'filename' => $name, 'content' => $zip->getFromIndex($i), ]; } } } }
Add errer handling for python code
#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.srv import ApplyGoals from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def get_waypoints(): sequence = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) sequence.waypoints.append(waypoint) return sequence if __name__ == '__main__': rospy.init_node('yaml_reader', anonymous=True) goal_sequence = get_waypoints() rospy.wait_for_service('apply_goals') try: apply_goals = rospy.ServiceProxy('apply_goals', ApplyGoals) resp = apply_goals(goal_sequence) print resp.message except rospy.ServiceException, e: print e except rospy.ROSInterruptException: pass
#!/usr/bin/env python # coding UTF-8 import yaml import rospy from goal_sender_msgs.srv import ApplyGoals from goal_sender_msgs.msg import GoalSequence from goal_sender_msgs.msg import Waypoint def read_yaml(path): f = open(path, 'r') waypoints = yaml.load(f) f.close() return waypoints def get_waypoints(): sequence = GoalSequence() for waypoint_data in read_yaml(rospy.get_param('~path', 'waypoints.yaml')): waypoint = Waypoint(name = waypoint_data.get('name', ""), x = waypoint_data['x'], # required y = waypoint_data['y'], # required radius = waypoint_data['radius'], # required importance = waypoint_data.get('importance', 0), drag = waypoint_data.get('drag', 0)) sequence.waypoints.append(waypoint) return sequence if __name__ == '__main__': rospy.init_node('yaml_reader', anonymous=True) goal_sequence = get_waypoints() rospy.wait_for_service('apply_goals') try: apply_goals = rospy.ServiceProxy('apply_goals', ApplyGoals) resp = apply_goals(goal_sequence) print resp.message except rospy.ServiceException, e: print e
Add showname to playlist API view. * Even though it's obsolete now, we need it for old shows.
from rest_framework import serializers from .models import Cd, Cdtrack, Show, Playlist, PlaylistEntry class TrackSerializer(serializers.ModelSerializer): album = serializers.StringRelatedField( read_only=True ) class Meta: model = Cdtrack fields = ('trackid', 'url', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'album') class ReleaseSerializer(serializers.HyperlinkedModelSerializer): tracks = serializers.PrimaryKeyRelatedField( many=True, read_only=True ) class Meta: model = Cd fields = ('id', 'url', 'arrivaldate', 'artist', 'title', 'year', 'local', 'compilation', 'female', 'tracks') class ShowSerializer(serializers.ModelSerializer): class Meta: model = Show fields = ('id', 'name', 'startTime', 'endTime', 'defaultHost') class PlaylistEntrySerializer(serializers.ModelSerializer): playlist = serializers.PrimaryKeyRelatedField( queryset = Playlist.objects.all() ) class Meta: model = PlaylistEntry fields = ('id', 'artist','album','title','duration','local','australian','female','newRelease','playlist' ) pass class PlaylistSerializer(serializers.ModelSerializer): entries =PlaylistEntrySerializer( many=True, read_only=True ) class Meta: model = Playlist fields = ('id', 'show','showname', 'host', 'date', 'notes', 'entries')
from rest_framework import serializers from .models import Cd, Cdtrack, Show, Playlist, PlaylistEntry class TrackSerializer(serializers.ModelSerializer): album = serializers.StringRelatedField( read_only=True ) class Meta: model = Cdtrack fields = ('trackid', 'url', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'album') class ReleaseSerializer(serializers.HyperlinkedModelSerializer): tracks = serializers.PrimaryKeyRelatedField( many=True, read_only=True ) class Meta: model = Cd fields = ('id', 'url', 'arrivaldate', 'artist', 'title', 'year', 'local', 'compilation', 'female', 'tracks') class ShowSerializer(serializers.ModelSerializer): class Meta: model = Show fields = ('id', 'name', 'startTime', 'endTime', 'defaultHost') class PlaylistEntrySerializer(serializers.ModelSerializer): playlist = serializers.PrimaryKeyRelatedField( queryset = Playlist.objects.all() ) class Meta: model = PlaylistEntry fields = ('id', 'artist','album','title','duration','local','australian','female','newRelease','playlist' ) pass class PlaylistSerializer(serializers.ModelSerializer): entries =PlaylistEntrySerializer( many=True, read_only=True ) class Meta: model = Playlist fields = ('id', 'show', 'host', 'date', 'notes', 'entries')
Check if duration is null or undefined
/* |-------------------------------------------------------------------------- | Utils |-------------------------------------------------------------------------- */ export default { /** * Parse an int to a more readable string * * @param int duration * @return string */ parseDuration: function (duration) { if(duration !== null && duration !== undefined) { var hours = parseInt(duration / 3600) % 24; var minutes = parseInt(duration / 60) % 60; var seconds = parseInt(duration % 60); hours = hours < 10 ? '0' + hours : hours; var result = hours > 0 ? hours + ':' : ''; result += (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds); return result; } else { return '00:00'; } }, /** * Sort an array of int by ASC or DESC, then remove all duplicates * * @param array array of int to be sorted * @param string 'asc' or 'desc' depending of the sort needed * @return array */ simpleSort: function(array, sorting) { if(sorting == 'asc') { array.sort(function(a, b) { return a - b; }); } else if (sorting == 'desc') { array.sort(function(a, b) { return b - a; }); } var result = []; array.forEach(function(item) { if(result.indexOf(item) < 0) { result.push(item); } }); return result; } }
/* |-------------------------------------------------------------------------- | Utils |-------------------------------------------------------------------------- */ export default { /** * Parse an int to a more readable string * * @param int duration * @return string */ parseDuration: function (duration) { var hours = parseInt(duration / 3600) % 24; var minutes = parseInt(duration / 60) % 60; var seconds = parseInt(duration % 60); hours = hours < 10 ? '0' + hours : hours; var result = hours > 0 ? hours + ':' : ''; result += (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds); return result; }, /** * Sort an array of int by ASC or DESC, then remove all duplicates * * @param array array of int to be sorted * @param string 'asc' or 'desc' depending of the sort needed * @return array */ simpleSort: function(array, sorting) { if(sorting == 'asc') { array.sort(function(a, b) { return a - b; }); } else if (sorting == 'desc') { array.sort(function(a, b) { return b - a; }); } var result = []; array.forEach(function(item) { if(result.indexOf(item) < 0) { result.push(item); } }); return result; } }
Use decode from the encoder
<?php namespace Nats; /** * Class EncodedConnection * @package Nats */ class EncodedConnection extends Connection { /** * @var Encoder|null */ private $encoder = null; /** * EncodedConnection constructor. * @param ConnectionOptions|null $options * @param Encoder|null $encoder */ public function __construct(ConnectionOptions $options = null, Encoder $encoder = null) { $this->encoder = $encoder; parent::__construct($options); } /** * @param string $subject * @param string $payload * @param mixed $callback * @param int $wait */ public function request($subject, $payload, $callback, $wait = 1) { $payload = $this->encoder->encode($payload); $decode_callback = function ($payload) use ($callback) { $callback($this->encoder->decode($payload)); }; parent::request($subject, $payload, $decode_callback, $wait); } /** * @param string $subject * @param null $payload */ public function publish($subject, $payload = null) { $payload = $this->encoder->encode($payload); parent::publish($subject, $payload); } /** * @param string $subject * @param \Closure $callback */ public function subscribe($subject, \Closure $callback) { $decode_callback = function ($payload) use ($callback) { $callback($this->encoder->decode($payload)); }; parent::subscribe($subject, $decode_callback); } }
<?php namespace Nats; /** * Class EncodedConnection * @package Nats */ class EncodedConnection extends Connection { /** * @var Encoder|null */ private $encoder = null; /** * EncodedConnection constructor. * @param ConnectionOptions|null $options * @param Encoder|null $encoder */ public function __construct(ConnectionOptions $options = null, Encoder $encoder = null) { $this->encoder = $encoder; parent::__construct($options); } /** * @param string $subject * @param string $payload * @param mixed $callback * @param int $wait */ public function request($subject, $payload, $callback, $wait = 1) { $payload = $this->encoder->encode($payload); $decode_callback = function ($payload) use ($callback) { $callback(json_decode($payload)); }; parent::request($subject, $payload, $decode_callback, $wait); } /** * @param string $subject * @param null $payload */ public function publish($subject, $payload = null) { $payload = $this->encoder->encode($payload); parent::publish($subject, $payload); } /** * @param string $subject * @param \Closure $callback */ public function subscribe($subject, \Closure $callback) { $decode_callback = function ($payload) use ($callback) { $callback(json_decode($payload)); }; parent::subscribe($subject, $decode_callback); } }
Fix lookup in survey view
from rest_framework import serializers from django.contrib.auth.models import User from .models import Alert, HouseholdSurveyJSON, TeamMember class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = [ 'url', 'username', 'email'] class SimpleUserSerializer(UserSerializer): class Meta: model = User fields = [ 'username', 'email' ] class TeamMemberSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='teammember-detail', lookup_field="member_id") class Meta: model = TeamMember fields = [ 'url', 'member_id', 'name', 'phone', 'email'] class HouseholdSurveyJSONSerializer(serializers.HyperlinkedModelSerializer): team_lead = serializers.HyperlinkedIdentityField(view_name='teammember-detail', lookup_field="member_id") team_assistant = serializers.HyperlinkedIdentityField(view_name='teammember-detail', lookup_field="member_id") team_anthropometrist = serializers.HyperlinkedIdentityField(view_name='teammember-detail', lookup_field="member_id") class Meta: model = HouseholdSurveyJSON class AlertSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Alert fields = ( 'url', 'id', # fields 'category', 'text', 'archived', 'created', 'completed', # TODO fields still in json 'team_id', 'team_name', 'cluster_id', 'location', 'type', 'survey_id', )
from rest_framework import serializers from django.contrib.auth.models import User from .models import Alert, HouseholdSurveyJSON, TeamMember class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = [ 'url', 'username', 'email'] class SimpleUserSerializer(UserSerializer): class Meta: model = User fields = [ 'username', 'email' ] class TeamMemberSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='teammember-detail', lookup_field="member_id") class Meta: model = TeamMember fields = [ 'url', 'member_id', 'name', 'phone', 'email'] class HouseholdSurveyJSONSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = HouseholdSurveyJSON class AlertSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Alert fields = ( 'url', 'id', # fields 'category', 'text', 'archived', 'created', 'completed', # TODO fields still in json 'team_id', 'team_name', 'cluster_id', 'location', 'type', 'survey_id', )
Add data files to python packaging
import setuptools import versioneer if __name__ == "__main__": my_packages=setuptools.find_packages() setuptools.setup( name='basis_set_exchange', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='The Quantum Chemistry Basis Set Exchange', author='The Molecular Sciences Software Institute', author_email='[email protected]', url="https://github.com/MolSSI/basis_set_exchange", license='BSD-3C', packages=my_packages, install_requires=[ 'jsonschema', ], extras_require={ 'docs': [ 'sphinx', 'sphinxcontrib-napoleon', 'sphinx_rtd_theme', 'numpydoc', ], 'tests': [ 'pytest', 'pytest-cov' ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 3', ], package_data={'basis_set_exchange': ['data/*', 'data/*/*']}, zip_safe=True, )
import setuptools import versioneer if __name__ == "__main__": setuptools.setup( name='basis_set_exchange', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), description='The Quantum Chemistry Basis Set Exchange', author='The Molecular Sciences Software Institute', author_email='[email protected]', url="https://github.com/MolSSI/basis_set_exchange", license='BSD-3C', packages=setuptools.find_packages(), install_requires=[ 'jsonschema', ], extras_require={ 'docs': [ 'sphinx', 'sphinxcontrib-napoleon', 'sphinx_rtd_theme', 'numpydoc', ], 'tests': [ 'pytest', 'pytest-cov' ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'Programming Language :: Python :: 3', ], zip_safe=True, )
Remove use of assert statements since this does not conform to general best practice. This is unfortunate, because the code is much more verbose than before and NOT as clear.
""" Functions related to HTTP Basic Authorization """ from functools import wraps from flask import request, jsonify, current_app def basic_auth(original_function): """ Wrapper. Verify that request.authorization exists and that its contents match the application's config.basic_auth_credentials dict. Args: original_function (function): The function to wrap. Returns: flask.Response: When credentials are missing or don't match. original_function (function): The original function. """ @wraps(original_function) def decorated(*args, **kwargs): try: if not (request.authorization.username, request.authorization.password) == ( current_app.config.basic_auth_credentials['username'], current_app.config.basic_auth_credentials['password']): unauthorized_response = jsonify( {'message': 'Could not verify your access level ' 'for that URL. \nYou have to login ' 'with proper credentials', 'statusCode': 401}) unauthorized_response.status_code = 401 return unauthorized_response except AttributeError: unauthorized_response = jsonify( {'message': 'Could not verify your access level ' 'for that URL. \nYou have to login ' 'with proper credentials', 'statusCode': 401}) unauthorized_response.status_code = 401 return original_function(*args, **kwargs) return decorated
""" Functions related to HTTP Basic Authorization """ from functools import wraps from flask import request, Response, current_app def basic_auth(original_function): """ Wrapper. Verify that request.authorization exists and that its contents match the application's config.basic_auth_credentials dict. Args: original_function (function): The function to wrap. Returns: flask.Response: When credentials are missing or don't match. original_function (function): The original function. """ @wraps(original_function) def decorated(*args, **kwargs): try: assert request.authorization.username == \ current_app.config['APP_USERNAME'] assert request.authorization.password == \ current_app.config['APP_PASSWORD'] except AttributeError: return Response( 'You must provide access credentials for this url.', 401, {'WWW-Authenticate': 'Basic'}) except AssertionError: return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic'}) return original_function(*args, **kwargs) return decorated
Create missing tables when lifting sails
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#!/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // This is specified in config/env/development.js and config/env/production.js /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'alter', schema: true, autoPK: true, autoCreatedAt: true, autoUpdatedAt: true };
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#!/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // This is specified in config/env/development.js and config/env/production.js /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'safe', schema: true, autoPK: true, autoCreatedAt: true, autoUpdatedAt: true };
Add checking if lastPropId is undefined
"use strict"; module.exports = { rules: { "sort-object-props": function(context) { var caseSensitive = context.options[0].caseSensitive; var ignoreMethods = context.options[0].ignoreMethods; var ignorePrivate = context.options[0].ignorePrivate; var MSG = "Property names in object literals should be sorted"; return { "ObjectExpression": function(node) { node.properties.reduce(function(lastProp, prop) { if (ignoreMethods && prop.value.type === "FunctionExpression") { return prop; } var lastPropId, propId; if (prop.key.type === "Identifier") { lastPropId = lastProp.key.name; propId = prop.key.name; } else if (prop.key.type === "Literal") { lastPropId = lastProp.key.value; propId = prop.key.value; } if ((caseSensitive) && (lastPropId !== undefined)) { lastPropId = lastPropId.toLowerCase(); propId = propId.toLowerCase(); } if (ignorePrivate && /^_/.test(propId)) { return prop; } if (propId < lastPropId) { context.report(prop, MSG); } return prop; }, node.properties[0]); } }; } }, rulesConfig: { "sort-object-props": [ 1, { caseSensitive: false, ignoreMethods: false } ] } };
"use strict"; module.exports = { rules: { "sort-object-props": function(context) { var caseSensitive = context.options[0].caseSensitive; var ignoreMethods = context.options[0].ignoreMethods; var ignorePrivate = context.options[0].ignorePrivate; var MSG = "Property names in object literals should be sorted"; return { "ObjectExpression": function(node) { node.properties.reduce(function(lastProp, prop) { if (ignoreMethods && prop.value.type === "FunctionExpression") { return prop; } var lastPropId, propId; if (prop.key.type === "Identifier") { lastPropId = lastProp.key.name; propId = prop.key.name; } else if (prop.key.type === "Literal") { lastPropId = lastProp.key.value; propId = prop.key.value; } if (caseSensitive) { lastPropId = lastPropId.toLowerCase(); propId = propId.toLowerCase(); } if (ignorePrivate && /^_/.test(propId)) { return prop; } if (propId < lastPropId) { context.report(prop, MSG); } return prop; }, node.properties[0]); } }; } }, rulesConfig: { "sort-object-props": [ 1, { caseSensitive: false, ignoreMethods: false } ] } };
Remove unnecessary login during build model frontend test
casper.test.begin('build model', function suite(test) { casper.start('http://localhost:5000', function() { this.page.viewportSize = { width: 1920, height: 1080 }; // Build model casper.then(function(){ this.evaluate(function() { document.querySelector('#buildmodel_project_name_select').selectedIndex = 0; document.querySelector('#modelbuild_featset_name_select').selectedIndex = 0; document.querySelector('#model_type_select').selectedIndex = 0; return true; }); this.click('#model_build_submit_button'); }); casper.then(function(){ casper.waitForText( "New model successfully created", function(){ test.assertTextExists("New model successfully created", "New model successfully created"); }, function(){ test.assertTextExists("New model successfully created", "New model successfully created"); }, 10000); }); }); casper.run(function() { test.done(); }); });
casper.test.begin('build model', function suite(test) { casper.start('http://localhost:5000', function() { this.page.viewportSize = { width: 1920, height: 1080 }; if(this.exists('form.login-form')){ this.fill('form.login-form', { 'login': '[email protected]', 'password': 'TestPass15' }, true); } // Build model casper.then(function(){ this.evaluate(function() { document.querySelector('#buildmodel_project_name_select').selectedIndex = 0; document.querySelector('#modelbuild_featset_name_select').selectedIndex = 0; document.querySelector('#model_type_select').selectedIndex = 0; return true; }); this.click('#model_build_submit_button'); }); casper.then(function(){ casper.waitForText( "New model successfully created", function(){ test.assertTextExists("New model successfully created", "New model successfully created"); }, function(){ test.assertTextExists("New model successfully created", "New model successfully created"); }, 10000); }); }); casper.run(function() { test.done(); }); });
Remove `body_html_escaped`. Add rendering filtered by formats.
# -*- coding: utf-8 -*- from django.conf import settings from django.utils.encoding import smart_str from mail_factory.messages import EmailMultiRelated class PreviewMessage(EmailMultiRelated): def has_body_html(self): """Test if a message contains an alternative rendering in text/html""" return 'text/html' in self.rendering_formats @property def body_html(self): """Return an alternative rendering in text/html""" return self.rendering_formats.get('text/html', '') @property def rendering_formats(self): return dict((v, k) for k, v in self.alternatives) class BasePreviewMail(object): """Abstract class that helps creating preview emails. You also may overwrite: * get_context_data: to add global context such as SITE_NAME """ message_class = PreviewMessage def get_message(self, lang=None): """Return a new message instance based on your MailClass""" return self.mail.create_email_msg(self.get_email_receivers(), lang=lang, message_class=self.message_class) @property def mail(self): return self.mail_class(self.get_context_data()) def get_email_receivers(self): """Returns email receivers.""" return [settings.SERVER_EMAIL, ] def get_context_data(): """Returns automatic context_data.""" return {} @property def mail_class(self): raise NotImplementedError
from base64 import b64encode from django.conf import settings from mail_factory.messages import EmailMultiRelated class PreviewMessage(EmailMultiRelated): def has_body_html(self): """Test if a message contains an alternative rendering in text/html""" return 'text/html' in self.alternatives @property def body_html(self): """Return an alternative rendering in text/html""" return self.alternatives.get('text/html', '') @property def body_html_escaped(self): """Return an alternative rendering in text/html escaped to work in a iframe""" return b64encode(self.body_html) class BasePreviewMail(object): """Abstract class that helps creating preview emails. You also may overwrite: * get_context_data: to add global context such as SITE_NAME """ message_class = PreviewMessage def get_message(self, lang=None): """Return a new message instance based on your MailClass""" return self.mail.create_email_msg(self.get_email_receivers(), lang=lang, message_class=self.message_class) @property def mail(self): return self.mail_class(self.get_context_data()) def get_email_receivers(self): """Returns email receivers.""" return [settings.SERVER_EMAIL, ] def get_context_data(): """Returns automatic context_data.""" return {} @property def mail_class(self): raise NotImplementedError
Fix id column in migration
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePhpdebugbarStorageTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('phpdebugbar', function (Blueprint $table) { $table->string('id'); $table->text('data'); $table->string('meta_utime'); $table->dateTime('meta_datetime'); $table->string('meta_uri'); $table->string('meta_ip'); $table->string('meta_method'); $table->primary('id'); $table->index('meta_utime'); $table->index('meta_datetime'); $table->index('meta_uri'); $table->index('meta_ip'); $table->index('meta_method'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('phpdebugbar'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePhpdebugbarStorageTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('phpdebugbar', function (Blueprint $table) { $table->increments('id'); $table->text('data'); $table->string('meta_utime'); $table->dateTime('meta_datetime'); $table->string('meta_uri'); $table->string('meta_ip'); $table->string('meta_method'); $table->index('meta_utime'); $table->index('meta_datetime'); $table->index('meta_uri'); $table->index('meta_ip'); $table->index('meta_method'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('phpdebugbar'); } }
Add suport for development installs.
# -*- coding: utf-8 -*- try: from setuptools import setup from setuptools.command.install import install except ImportError: from distutils.core import setup from distutils.core.command.install import install class InstallCommand(install): """Install as noteboook extension""" develop = False def install_extension(self): from os.path import dirname, abspath, join from IPython.html.nbextensions import install_nbextension from IPython.html.services.config import ConfigManager print("Installing nbextension ...") flightwidgets = join(dirname(abspath(__file__)), 'flightwidgets', 'js') install_nbextension(flightwidgets, destination='flightwidgets', symlink=self.develop, user=True) def run(self): print "Installing Python module..." install.run(self) # Install Notebook extension self.install_extension() class DevelopCommand(InstallCommand): """Install as noteboook extension""" develop = True from glob import glob setup( name='flightwidgets', version='0.1', description='Flight attitude and compass widgets for the Jupyter notebook.', author='Jonathan Frederic', author_email='[email protected]', license='New BSD License', url='https://github.com/jdfreder/ipython-flightwidgets', keywords='data visualization interactive interaction python ipython widgets widget', classifiers=['Development Status :: 4 - Beta', 'Programming Language :: Python', 'License :: OSI Approved :: MIT License'], packages=['flightwidgets', 'flightwidgets/py'], include_package_data=True, cmdclass={ 'install': InstallCommand, 'develop': DevelopCommand, } )
# -*- coding: utf-8 -*- try: from setuptools import setup from setuptools.command.install import install except ImportError: from distutils.core import setup from distutils.core.command.install import install class CustomInstallCommand(install): """Install as noteboook extension""" def install_extension(self): from os.path import dirname, abspath, join from IPython.html.nbextensions import install_nbextension from IPython.html.services.config import ConfigManager print("Installing nbextension ...") flightwidgets = join(dirname(abspath(__file__)), 'flightwidgets', 'js') install_nbextension(flightwidgets, destination='flightwidgets') def run(self): print "Installing Python module..." install.run(self) # Install Notebook extension self.install_extension() from glob import glob setup( name='flightwidgets', version='0.1', description='Flight attitude and compass widgets for the Jupyter notebook.', author='Jonathan Frederic', author_email='[email protected]', license='New BSD License', url='https://github.com/jdfreder/ipython-flightwidgets', keywords='data visualization interactive interaction python ipython widgets widget', classifiers=['Development Status :: 4 - Beta', 'Programming Language :: Python', 'License :: OSI Approved :: MIT License'], packages=['flightwidgets', 'flightwidgets/py'], include_package_data=True, cmdclass={ 'install': CustomInstallCommand, 'develop': CustomInstallCommand, } )
Check if ip is in whitelist and not in blacklist This can be useful when we define a subnet as whitelist but we want to exclude a particular ip, for example: whitelist 192.168.0.* blacklist 192.168.0.50
<?php namespace Overflowsith\Firewall; use Config; use Str; class Firewall { public static function isAllowed($ip) { switch(Config::get('firewall::config.mode')) { case 'disabled': return true; break; case 'enforcing': return self::isInWhiteList($ip) && !(self::isInBlackList($ip)); break; case 'permissive': return !(self::isInBlackList($ip)); break; default: return false; } } public static function isInWhiteList($ip) { return self::check(Config::get('firewall::config.whitelist', []), $ip); } public static function isInBlackList($ip) { return self::check(Config::get('firewall::config.blacklist', []), $ip); } private static function check($source, $ip) { foreach($source as $pattern) { if (Str::is($pattern, $ip)) { return true; } } return false; } }
<?php namespace Overflowsith\Firewall; use Config; use Str; class Firewall { public static function isAllowed($ip) { switch(Config::get('firewall::config.mode')) { case 'disabled': return true; break; case 'enforcing': return self::isInWhiteList($ip); break; case 'permissive': return !(self::isInBlackList($ip)); break; default: return false; } } public static function isInWhiteList($ip) { return self::check(Config::get('firewall::config.whitelist', []), $ip); } public static function isInBlackList($ip) { return self::check(Config::get('firewall::config.blacklist', []), $ip); } private static function check($source, $ip) { foreach($source as $pattern) { if (Str::is($pattern, $ip)) { return true; } } return false; } }
Change bulk order email address to Tory
import logging from django.core.mail import EmailMessage from django.http import JsonResponse from django.middleware import csrf from django.views.decorators.csrf import csrf_exempt from django.shortcuts import redirect from rest_framework.decorators import api_view @csrf_exempt @api_view(['POST', 'GET']) def send_contact_message(request): if request.method == 'POST': from_name = request.POST.get("from_name", "") from_address = request.POST.get("from_address", "") from_string = '{} <{}>'.format(from_name, from_address) subject = request.POST.get("subject", "") message_body = request.POST.get("message_body", "") # Add subject: to_address to this dict to add a new email address. # Subject will map to the email being sent to to prevent misuse of our email server. emails = { 'Bulk Order': '[email protected]', } try: to_address = emails[subject].split(',') email = EmailMessage(subject, message_body, '[email protected]', to_address, reply_to=[from_string]) email.send() except KeyError: logging.error("EMAIL FAILED TO SEND: subject:{}") return redirect('/confirmation?contact') # if this is not posting a message, let's send the csfr token back else: csrf_token = csrf.get_token(request) data = {'csrf_token': csrf_token} return JsonResponse(data)
import logging from django.core.mail import EmailMessage from django.http import JsonResponse from django.middleware import csrf from django.views.decorators.csrf import csrf_exempt from django.shortcuts import redirect from rest_framework.decorators import api_view @csrf_exempt @api_view(['POST', 'GET']) def send_contact_message(request): if request.method == 'POST': from_name = request.POST.get("from_name", "") from_address = request.POST.get("from_address", "") from_string = '{} <{}>'.format(from_name, from_address) subject = request.POST.get("subject", "") message_body = request.POST.get("message_body", "") # Add subject: to_address to this dict to add a new email address. # Subject will map to the email being sent to to prevent misuse of our email server. emails = { 'Bulk Order': '[email protected]', } try: to_address = emails[subject].split(',') email = EmailMessage(subject, message_body, '[email protected]', to_address, reply_to=[from_string]) email.send() except KeyError: logging.error("EMAIL FAILED TO SEND: subject:{}") return redirect('/confirmation?contact') # if this is not posting a message, let's send the csfr token back else: csrf_token = csrf.get_token(request) data = {'csrf_token': csrf_token} return JsonResponse(data)
Fix start for bin script.
"use strict"; var path = require("path"); exports.port = process.env.ARGO_PORT || 8000; exports.staticFiles = path.resolve(__dirname, "../../client/"); exports.apiUrl = "/api"; exports.streamUrl = "/stream"; exports.environment = process.env.OANDA_ENVIRONMENT || "practice"; exports.accessToken = process.env.OANDA_TOKEN || "ACCESS_TOKEN"; exports.accountId = process.env.OANDA_ACCOUNTID || "1234567890"; exports.sessionId = process.env.OANDA_SESSIONID || "1"; exports.instruments = [ "EUR_USD", "USD_JPY", "GBP_USD", "EUR_GBP", "USD_CHF", "EUR_JPY", "EUR_CHF", "USD_CAD", "AUD_USD", "GBP_JPY" ]; exports.getUrl = getUrl; function getUrl(environment, type) { var endpoints = { live: { stream: "https://stream-fxtrade.oanda.com", api: "https://api-fxtrade.oanda.com" }, practice: { stream: "https://stream-fxpractice.oanda.com", api: "https://api-fxpractice.oanda.com" }, sandbox: { stream: "http://stream-sandbox.oanda.com", api: "https://api-sandbox.oanda.com" } }; return endpoints[environment][type]; }
"use strict"; exports.port = process.env.ARGO_PORT || 8000; exports.staticFiles = "./src/client/"; exports.apiUrl = "/api"; exports.streamUrl = "/stream"; exports.environment = process.env.OANDA_ENVIRONMENT || "practice"; exports.accessToken = process.env.OANDA_TOKEN || "ACCESS_TOKEN"; exports.accountId = process.env.OANDA_ACCOUNTID || "1234567890"; exports.sessionId = process.env.OANDA_SESSIONID || "1"; exports.instruments = [ "EUR_USD", "USD_JPY", "GBP_USD", "EUR_GBP", "USD_CHF", "EUR_JPY", "EUR_CHF", "USD_CAD", "AUD_USD", "GBP_JPY" ]; exports.getUrl = getUrl; function getUrl(environment, type) { var endpoints = { live: { stream: "https://stream-fxtrade.oanda.com", api: "https://api-fxtrade.oanda.com" }, practice: { stream: "https://stream-fxpractice.oanda.com", api: "https://api-fxpractice.oanda.com" }, sandbox: { stream: "http://stream-sandbox.oanda.com", api: "https://api-sandbox.oanda.com" } }; return endpoints[environment][type]; }
Include filename in reported output.
'use strict' var standard = require('standard') var format = require('util').format var loaderUtils = require('loader-utils') var snazzy = require('snazzy') module.exports = function standardLoader (text) { var self = this var callback = this.async() var config = loaderUtils.getOptions(this) config.filename = this.resourcePath this.cacheable() standard.lintText(text, config, function (err, result) { if (err) return callback(err, text) if (result.errorCount === 0) return callback(err, text) var warnings = result.results.reduce(function (items, result) { return items.concat(result.messages.map(function (message) { return format( '%s:%d:%d: %s%s', result.filePath, message.line || 0, message.column || 0, message.message, !config.verbose ? ' (' + message.ruleId + ')' : '' ) })) }, []) .join('\n') if (config.snazzy !== false) { snazzy({encoding: 'utf8'}) .on('data', function (data) { if (config.emitErrors) { self.emitError(data) } else { self.emitWarning(data) } }) .end(warnings) } else { if (config.emitErrors) { self.emitError(warnings) } else { self.emitWarning(warnings) } } callback(err, text) }) }
'use strict' var standard = require('standard') var format = require('util').format var loaderUtils = require('loader-utils') var snazzy = require('snazzy') module.exports = function standardLoader (text) { var self = this var callback = this.async() var config = loaderUtils.getOptions(this) this.cacheable() standard.lintText(text, config, function (err, result) { if (err) return callback(err, text) if (result.errorCount === 0) return callback(err, text) var warnings = result.results.reduce(function (items, result) { return items.concat(result.messages.map(function (message) { return format( '%s:%d:%d: %s%s', result.filePath, message.line || 0, message.column || 0, message.message, !config.verbose ? ' (' + message.ruleId + ')' : '' ) })) }, []) .join('\n') if (config.snazzy !== false) { snazzy({encoding: 'utf8'}) .on('data', function (data) { if (config.emitErrors) { self.emitError(data) } else { self.emitWarning(data) } }) .end(warnings) } else { if (config.emitErrors) { self.emitError(warnings) } else { self.emitWarning(warnings) } } callback(err, text) }) }
Read the body selector from the module config (if present)
define(['module', 'knockout', 'jquery'], function (module, ko, $) { var defaultBodySelector; if (module && typeof module.config === 'function' && typeof module.config().bodySelector === 'string') { defaultBodySelector = module.config().bodySelector; } else { defaultBodySelector = 'body'; } var createGetContext = function createGetContext () { return function getContext (elementAccessor) { var context; var element; if (!elementAccessor) { return; } element = $(elementAccessor)[0]; if (!element) { return; } context = ko.contextFor(element); if (!context) { return; } return context; } }; var createGetViewModel = function createGetViewModel (getContext) { return function getViewModel (elementAccessor) { var viewModel; var context = getContext(elementAccessor); if (context) { viewModel = context.$data; } else { viewModel = {}; } return viewModel; }; }; var createGetRoot = function createGetRoot (getContext, bodySelector) { if (typeof bodySelector !== 'string') { bodySelector = defaultBodySelector; } return function getRoot () { var context; var root; context = getContext(bodySelector); if (!context) { return; } root = context.$root; if (!root) { return; } return root; } }; var getContext = createGetContext(); return { getContext: getContext, getRoot: createGetRoot(getContext), getViewModel: createGetViewModel(getContext) }; });
define(['knockout', 'jquery'], function (ko, $) { var defaultBodySelector = 'body'; var createGetContext = function createGetContext () { return function getContext (elementAccessor) { var context; var element; if (!elementAccessor) { return; } element = $(elementAccessor)[0]; if (!element) { return; } context = ko.contextFor(element); if (!context) { return; } return context; } }; var createGetViewModel = function createGetViewModel (getContext) { return function getViewModel (elementAccessor) { var viewModel; var context = getContext(elementAccessor); if (context) { viewModel = context.$data; } else { viewModel = {}; } return viewModel; }; }; var createGetRoot = function createGetRoot (getContext, bodySelector) { if (typeof bodySelector !== 'string') { bodySelector = defaultBodySelector; } return function getRoot () { var context; var root; context = getContext(bodySelector); if (!context) { return; } root = context.$root; if (!root) { return; } return root; } }; var getContext = createGetContext(); var module = { getContext: getContext, getRoot: createGetRoot(getContext), getViewModel: createGetViewModel(getContext) } module.create = function create (bodySelector) { return $.extend({}, module, { getRoot: createGetRoot(module.getContext, bodySelector) }); }; return module; });
Refresh angular controllers after login
/// <reference path="../Services/AccountService.js" /> (function () { 'use strict'; angular .module('GVA.Common') .controller('AccountLoginController', AccountLoginController); AccountLoginController.$inject = ['$scope', '$rootScope', '$route', 'AccountService']; function AccountLoginController($scope, $rootScope, $route, AccountService) { $scope.loginAccount = loginAccount; $scope.forgottenPassword = forgottenPassword; function loginAccount(form) { clearError(); AccountService.login(form.email, form.password) .then(function () { closeDialog(); $route.reload(); }) .catch(displayErrorMessage); } function displayErrorMessage() { showError($rootScope.error.readableMessage); $rootScope.error = null; } function forgottenPassword(form) { clearError(); if (form.email === undefined) { showError('Please supply email address.'); } else { AccountService.forgotPassword(form.email) .then(closeDialog) .catch(function (data) { showError(data.Message || data.error_description); }); } } function closeDialog() { $scope.closeThisDialog(); } function clearError() { $scope.displayError = null; } function showError(errorMessage) { $scope.displayError = errorMessage; } } })();
/// <reference path="../Services/AccountService.js" /> (function () { 'use strict'; angular .module('GVA.Common') .controller('AccountLoginController', AccountLoginController); AccountLoginController.$inject = ['$scope', '$rootScope', 'AccountService']; function AccountLoginController($scope, $rootScope, AccountService) { $scope.loginAccount = loginAccount; $scope.forgottenPassword = forgottenPassword; function loginAccount(form) { clearError(); AccountService.login(form.email, form.password) .then(function () { closeDialog(); //setTimeout(function () { // window.location.reload(); //}, 300); }) .catch(displayErrorMessage); } function displayErrorMessage() { showError($rootScope.error.readableMessage); $rootScope.error = null; } function forgottenPassword(form) { clearError(); if (form.email === undefined) { showError('Please supply email address.'); } else { AccountService.forgotPassword(form.email) .then(closeDialog) .catch(function (data) { showError(data.Message || data.error_description); }); } } function closeDialog() { $scope.closeThisDialog(); } function clearError() { $scope.displayError = null; } function showError(errorMessage) { $scope.displayError = errorMessage; } } })();
Implement a better way of validating incoming requests. Signed-off-by: Jason Lewis <[email protected]>
<?php namespace Dingo\Api\Http; use Illuminate\Container\Container; use Illuminate\Http\Request as IlluminateRequest; class Validator { /** * Container instance. * * @var \Illuminate\Container\Container */ protected $container; /** * Array of request validators. * * @var array */ protected $validators = [ 'Dingo\Api\Http\Matching\DomainValidator', 'Dingo\Api\Http\Matching\PrefixValidator', 'Dingo\Api\Http\Matching\AcceptValidator' ]; /** * Create a new request validator instance. * * @param \Illuminate\Container\Container $container * * @return void */ public function __construct(Container $container) { $this->container = $container; } /** * Validate a request. * * @param \Illuminate\Http\Request $request * * @return bool */ public function validateRequest(IlluminateRequest $request) { foreach ($this->validators as $validator) { $validator = $this->container->make($validator); if (! $validator->matches($request)) { return false; } } return true; } }
<?php namespace Dingo\Api\Http; use Illuminate\Http\Request as IlluminateRequest; class Validator { protected $domain; protected $prefix; /** * Create a new request validator instance. * * @param string $domain * @param string $prefix * * @return void */ public function __construct($domain = null, $prefix = null) { $this->domain = $domain; $this->prefix = $prefix; } /** * Validate a request. * * @param \Illuminate\Http\Request $request * * @return bool */ public function validateRequest(IlluminateRequest $request) { return $this->validateDomain($request) || $this->validatePrefix($request); } /** * Validates domain in the request. * * @param \Illuminate\Http\Request $request * * @return bool */ public function validateDomain(IlluminateRequest $request) { return ! is_null($this->domain) && $request->header('host') == $this->domain; } /** * Validates prefix in the request. * * @param \Illuminate\Http\Request $request * * @return bool */ public function validatePrefix(IlluminateRequest $request) { $prefix = $this->filterAndExplode($this->prefix); $path = $this->filterAndExplode($request->getPathInfo()); return ! is_null($this->prefix) && $prefix == array_slice($path, 0, count($prefix)); } /** * Explode array on slash and remove empty values. * * @param array $array * * @return array */ protected function filterAndExplode($array) { return array_filter(explode('/', $array)); } }
Fix relative portion of link.
from pyshelf.cloud.stream_iterator import StreamIterator from flask import Response class ArtifactListManager(object): def __init__(self, container): self.container = container def get_artifact(self, path): """ Gets artifact or artifact list information. Args: path(string): path or name of artifact. Returns: flask.Response """ with self.container.create_master_bucket_storage() as storage: if path[-1] == "/": self.container.logger.debug("Artifact with path {} is a directory.".format(path)) child_list = storage.get_directory_contents(path) links = [] for child in child_list: title = child.name url = "/artifact/" + title rel = "child" if child.name == path: rel = "self" links.append(self._format_link(url=url, rel=rel, title=title)) response = Response() response.headers["Link"] = ",".join(links) response.status_code = 204 else: stream = storage.get_artifact(path) response = Response(stream) response.headers["Content-Type"] = stream.headers["content-type"] return response def _format_link(self, **kwargs): link = "<{url}>; rel={rel}; title={title}".format(**kwargs) return link
from pyshelf.cloud.stream_iterator import StreamIterator from flask import Response class ArtifactListManager(object): def __init__(self, container): self.container = container def get_artifact(self, path): """ Gets artifact or artifact list information. Args: path(string): path or name of artifact. Returns: flask.Response """ with self.container.create_master_bucket_storage() as storage: if path[-1] == "/": self.container.logger.debug("Artifact with path {} is a directory.".format(path)) child_list = storage.get_directory_contents(path) links = [] for child in child_list: title = child.name path = "/artifact/" + title rel = "child" if child.name == path: rel = "self" links.append(self._format_link(path=path, rel=rel, title=title)) response = Response() response.headers["Link"] = ",".join(links) response.status_code = 204 else: stream = storage.get_artifact(path) response = Response(stream) response.headers["Content-Type"] = stream.headers["content-type"] return response def _format_link(self, **kwargs): link = "<{path}>; rel={rel}; title={title}".format(**kwargs) return link
[AC-4857] Switch from () to __call__()
from abc import ( ABCMeta, abstractmethod, ) from impact.v1.helpers import ( STRING_FIELD, ) class BaseHistoryEvent(object): __metaclass__ = ABCMeta CLASS_FIELDS = { "event_type": STRING_FIELD, "datetime": STRING_FIELD, "latest_datetime": STRING_FIELD, "description": STRING_FIELD, } def __init__(self): self.earliest = None self.latest = None @classmethod def all_fields(cls): result = {} for base_class in cls.__bases__: if hasattr(base_class, "all_fields"): result.update(base_class.all_fields()) if hasattr(cls, "CLASS_FIELDS"): result.update(cls.CLASS_FIELDS) return result @classmethod def event_type(cls): return cls.EVENT_TYPE @abstractmethod def calc_datetimes(self): pass # pragma: no cover def datetime(self): self._check_date_cache() return self.earliest def latest_datetime(self): self._check_date_cache() return self.latest def _check_date_cache(self): if not self.earliest and hasattr(self, "calc_datetimes"): self.calc_datetimes() def description(self): return None # pragma: no cover def serialize(self): result = {} for key in self.all_fields().keys(): value = getattr(self, key).__call__() if value is not None: result[key] = value return result
from abc import ( ABCMeta, abstractmethod, ) from impact.v1.helpers import ( STRING_FIELD, ) class BaseHistoryEvent(object): __metaclass__ = ABCMeta CLASS_FIELDS = { "event_type": STRING_FIELD, "datetime": STRING_FIELD, "latest_datetime": STRING_FIELD, "description": STRING_FIELD, } def __init__(self): self.earliest = None self.latest = None @classmethod def all_fields(cls): result = {} for base_class in cls.__bases__: if hasattr(base_class, "all_fields"): result.update(base_class.all_fields()) if hasattr(cls, "CLASS_FIELDS"): result.update(cls.CLASS_FIELDS) return result @classmethod def event_type(cls): return cls.EVENT_TYPE @abstractmethod def calc_datetimes(self): pass # pragma: no cover def datetime(self): self._check_date_cache() return self.earliest def latest_datetime(self): self._check_date_cache() return self.latest def _check_date_cache(self): if not self.earliest and hasattr(self, "calc_datetimes"): self.calc_datetimes() def description(self): return None # pragma: no cover def serialize(self): result = {} for key in self.all_fields().keys(): value = getattr(self, key)() if value is not None: result[key] = value return result
FIX Use userforms template for member list field, fixes display rule issue
<?php /** * Creates an editable field that displays members in a given group * * @package userforms */ class EditableMemberListField extends EditableFormField { private static $singular_name = 'Member List Field'; private static $plural_name = 'Member List Fields'; private static $has_one = array( 'Group' => 'Group' ); /** * @return FieldList */ public function getCMSFields() { $fields = parent::getCMSFields(); $fields->removeByName('Default'); $fields->removeByName('Validation'); $fields->addFieldToTab( 'Root.Main', DropdownField::create( "GroupID", _t('EditableFormField.GROUP', 'Group'), Group::get()->map() )->setEmptyString(' ') ); return $fields; } public function getFormField() { if (empty($this->GroupID)) { return false; } $members = Member::map_in_groups($this->GroupID); $field = DropdownField::create($this->Name, $this->EscapedTitle, $members) ->setTemplate('UserFormsDropdownField') ->setFieldHolderTemplate('UserFormsField_holder'); $this->doUpdateFormField($field); return $field; } public function getValueFromData($data) { if (isset($data[$this->Name])) { $memberID = $data[$this->Name]; $member = Member::get()->byID($memberID); return $member ? $member->getName() : ""; } return false; } }
<?php /** * Creates an editable field that displays members in a given group * * @package userforms */ class EditableMemberListField extends EditableFormField { private static $singular_name = 'Member List Field'; private static $plural_name = 'Member List Fields'; private static $has_one = array( 'Group' => 'Group' ); /** * @return FieldList */ public function getCMSFields() { $fields = parent::getCMSFields(); $fields->removeByName('Default'); $fields->removeByName('Validation'); $fields->addFieldToTab( 'Root.Main', DropdownField::create( "GroupID", _t('EditableFormField.GROUP', 'Group'), Group::get()->map() )->setEmptyString(' ') ); return $fields; } public function getFormField() { if (empty($this->GroupID)) { return false; } $members = Member::map_in_groups($this->GroupID); $field = new DropdownField($this->Name, $this->EscapedTitle, $members); $this->doUpdateFormField($field); return $field; } public function getValueFromData($data) { if (isset($data[$this->Name])) { $memberID = $data[$this->Name]; $member = Member::get()->byID($memberID); return $member ? $member->getName() : ""; } return false; } }
Fix using HAPPO_IS_ASYNC with Storybook plugin We weren't passing the right things to the remoteRunner, causing async report rendering to fail with a cryptic "is not iterable (cannot read property Symbol(Symbol.iterator))" error.
import { performance } from 'perf_hooks'; import Logger from './Logger'; import constructReport from './constructReport'; import loadCSSFile from './loadCSSFile'; export default async function remoteRunner( { apiKey, apiSecret, endpoint, targets, plugins, stylesheets }, { generateStaticPackage }, { isAsync }, ) { const logger = new Logger(); try { logger.info('Generating static package...'); const staticPackage = await generateStaticPackage(); const targetNames = Object.keys(targets); const tl = targetNames.length; const cssBlocks = await Promise.all(stylesheets.map(loadCSSFile)); plugins.forEach(({ css }) => cssBlocks.push(css || '')); logger.info(`Generating screenshots in ${tl} target${tl > 1 ? 's' : ''}...`); const outerStartTime = performance.now(); const results = await Promise.all( targetNames.map(async (name) => { const startTime = performance.now(); const result = await targets[name].execute({ targetName: name, asyncResults: isAsync, staticPackage, apiKey, apiSecret, endpoint, globalCSS: cssBlocks.join('').replace(/\n/g, ''), }); logger.start(` - ${name}`, { startTime }); logger.success(); return { name, result }; }), ); logger.start(undefined, { startTime: outerStartTime }); logger.success(); if (isAsync) { return results; } return constructReport(results); } catch (e) { logger.fail(); throw e; } }
import { performance } from 'perf_hooks'; import Logger from './Logger'; import constructReport from './constructReport'; import loadCSSFile from './loadCSSFile'; export default async function remoteRunner( { apiKey, apiSecret, endpoint, targets, plugins, stylesheets }, { generateStaticPackage, isAsync }, ) { const logger = new Logger(); try { logger.info('Generating static package...'); const staticPackage = await generateStaticPackage(); const targetNames = Object.keys(targets); const tl = targetNames.length; const cssBlocks = await Promise.all(stylesheets.map(loadCSSFile)); plugins.forEach(({ css }) => cssBlocks.push(css || '')); logger.info(`Generating screenshots in ${tl} target${tl > 1 ? 's' : ''}...`); const outerStartTime = performance.now(); const results = await Promise.all( targetNames.map(async (name) => { const startTime = performance.now(); const result = await targets[name].execute({ targetName: name, asyncResults: isAsync, staticPackage, apiKey, apiSecret, endpoint, globalCSS: cssBlocks.join('').replace(/\n/g, ''), }); logger.start(` - ${name}`, { startTime }); logger.success(); return { name, result }; }), ); logger.start(undefined, { startTime: outerStartTime }); logger.success(); if (isAsync) { return results; } return constructReport(results); } catch (e) { logger.fail(); throw e; } }
Set staging db name as the live one.
"use strict"; var os = require("os"), path = require("path"), express = require("express"), routes = require("./routes"); var app = express(), hostname = os.hostname(), port = process.env.CONPA_PORT || 8080, documentRoot = path.resolve(__dirname, "../client"), nodeModules = path.resolve(__dirname, "../../node_modules/"), liveUrl = process.env.CONPA_LIVE_URL || "http://localhost:5984", testingUrl = process.env.CONPA_TEST_URL || "http://localhost:5984"; process.on("uncaughtException", function (err) { console.log(err.stack); }); app.get("/status", function (req, res) { res.send("ConPA is running on " + hostname + " on " + process.version); }); app.use(express.static(documentRoot)); app.use("/node_modules", express.static(nodeModules)); routes.configure(app, { crm: { liveDomain: hostname, // liveDomain: "foo.com", liveUrl: liveUrl, liveDb: "conpa", testingUrl: testingUrl, testingDb: "conpa", design: "ConPA" } }); app.listen(port, function () { console.log("ConPA document root is " + documentRoot); console.log("ConPA node_modules root is " + nodeModules); console.log("ConPA listening on http://" + hostname + ":" + port); });
"use strict"; var os = require("os"), path = require("path"), express = require("express"), routes = require("./routes"); var app = express(), hostname = os.hostname(), port = process.env.CONPA_PORT || 8080, documentRoot = path.resolve(__dirname, "../client"), nodeModules = path.resolve(__dirname, "../../node_modules/"), liveUrl = process.env.CONPA_LIVE_URL || "http://localhost:5984", testingUrl = process.env.CONPA_TEST_URL || "http://localhost:5984"; process.on("uncaughtException", function (err) { console.log(err.stack); }); app.get("/status", function (req, res) { res.send("ConPA is running on " + hostname + " on " + process.version); }); app.use(express.static(documentRoot)); app.use("/node_modules", express.static(nodeModules)); routes.configure(app, { crm: { liveDomain: hostname, // liveDomain: "foo.com", liveUrl: liveUrl, liveDb: "conpa", testingUrl: testingUrl, testingDb: "conpa-staging", design: "ConPA" } }); app.listen(port, function () { console.log("ConPA document root is " + documentRoot); console.log("ConPA node_modules root is " + nodeModules); console.log("ConPA listening on http://" + hostname + ":" + port); });
Fix debug plugin after hiding app title
enabled(){ this.isDebugging = false; this.onKeyDown = (e) => { // ========================== // F4 key - toggle debug mode // ========================== if (e.keyCode === 115){ this.isDebugging = !this.isDebugging; $(".nav-user-info").first().css("background-color", this.isDebugging ? "#5A6B75" : "#292F33"); } // Debug mode handling else if (this.isDebugging){ e.preventDefault(); // =================================== // N key - simulate popup notification // S key - simulate sound notification // =================================== if (e.keyCode === 78 || e.keyCode === 83){ var col = TD.controller.columnManager.getAllOrdered()[0]; var prevPopup = col.model.getHasNotification(); var prevSound = col.model.getHasSound(); col.model.setHasNotification(e.keyCode === 78); col.model.setHasSound(e.keyCode === 83); $.publish("/notifications/new",[{ column: col, items: [ col.updateArray[Math.floor(Math.random()*col.updateArray.length)] ] }]); setTimeout(function(){ col.model.setHasNotification(prevPopup); col.model.setHasSound(prevSound); }, 1); } } }; } ready(){ $(document).on("keydown", this.onKeyDown); } disabled(){ $(document).off("keydown", this.onKeyDown); }
enabled(){ this.isDebugging = false; this.onKeyDown = (e) => { // ========================== // F4 key - toggle debug mode // ========================== if (e.keyCode === 115){ this.isDebugging = !this.isDebugging; $(".app-title").first().css("background-color", this.isDebugging ? "#5A6B75" : "#292F33"); } // Debug mode handling else if (this.isDebugging){ e.preventDefault(); // =================================== // N key - simulate popup notification // S key - simulate sound notification // =================================== if (e.keyCode === 78 || e.keyCode === 83){ var col = TD.controller.columnManager.getAllOrdered()[0]; var prevPopup = col.model.getHasNotification(); var prevSound = col.model.getHasSound(); col.model.setHasNotification(e.keyCode === 78); col.model.setHasSound(e.keyCode === 83); $.publish("/notifications/new",[{ column: col, items: [ col.updateArray[Math.floor(Math.random()*col.updateArray.length)] ] }]); setTimeout(function(){ col.model.setHasNotification(prevPopup); col.model.setHasSound(prevSound); }, 1); } } }; } ready(){ $(document).on("keydown", this.onKeyDown); } disabled(){ $(document).off("keydown", this.onKeyDown); }
Fix custom template tag to work with django 1.8
from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value new_context = context.new(new_context) return self.nodelist.render(new_context) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:])
from django import template register = template.Library() class InContextNode(template.Node): def __init__(self, nodelist, subcontext_names): self.nodelist = nodelist self.subcontext_names = subcontext_names def render(self, context): new_context = {} for field in self.subcontext_names: value = context.get(field, {}) if isinstance(value, dict): new_context.update(context.get(field, {})) else: new_context[field] = value return self.nodelist.render(template.Context(new_context)) @register.tag('begincontext') def in_context(parser, token): """ Replaces the context (inside of this block) for easy (and safe) inclusion of sub-content. For example, if the context is {'name': 'Kitty', 'sub': {'size': 5}} 1: {{ name }} {{ size }} {% begincontext sub %} 2: {{ name }} {{ size }} {% endcontext %} 3: {{ name }} {{ size }} Will print 1: Kitty 2: 5 3: Kitty Arguments which are not dictionaries will 'cascade' into the inner context. """ nodelist = parser.parse(('endcontext',)) parser.delete_first_token() return InContextNode(nodelist, token.split_contents()[1:])
Add Servlet Request Parameters Supports
package org.qfox.jestful.form; import org.qfox.jestful.core.BeanContainer; import org.qfox.jestful.core.Initialable; import org.qfox.jestful.core.annotation.DELETE; import org.qfox.jestful.core.annotation.GET; import org.qfox.jestful.core.annotation.POST; import org.qfox.jestful.core.annotation.PUT; import org.qfox.jestful.interception.Interceptor; import org.qfox.jestful.interception.Invocation; import javax.servlet.ServletRequest; /** * Created by yangchangpei on 17/8/23. */ public class TokenInterceptor implements Interceptor, Initialable { private String tokenName = "form-token"; private TokenManager tokenManager; @Override public void initialize(BeanContainer beanContainer) { tokenManager = beanContainer.get(TokenManager.class); } @GET("/.*") @POST("/.*") @PUT("/.*") @DELETE("/.*") @Override public Object intercept(Invocation invocation) throws Exception { boolean needed = invocation.getMapping().isAnnotationPresent(TokenValidate.class); if (needed) { ServletRequest request = (ServletRequest) invocation.getRequest(); String token = request.getParameter(tokenName); if (token == null) throw new TokenRequiredException(); tokenManager.verify(token); } return invocation.invoke(); } public String getTokenName() { return tokenName; } public void setTokenName(String tokenName) { this.tokenName = tokenName; } }
package org.qfox.jestful.form; import org.qfox.jestful.core.BeanContainer; import org.qfox.jestful.core.Initialable; import org.qfox.jestful.core.annotation.DELETE; import org.qfox.jestful.core.annotation.GET; import org.qfox.jestful.core.annotation.POST; import org.qfox.jestful.core.annotation.PUT; import org.qfox.jestful.interception.Interceptor; import org.qfox.jestful.interception.Invocation; import javax.servlet.ServletRequest; /** * Created by yangchangpei on 17/8/23. */ public class TokenInterceptor implements Interceptor, Initialable { private String name = "form-token"; private TokenManager tokenManager; @Override public void initialize(BeanContainer beanContainer) { tokenManager = beanContainer.get(TokenManager.class); } @GET("/.*") @POST("/.*") @PUT("/.*") @DELETE("/.*") @Override public Object intercept(Invocation invocation) throws Exception { boolean needed = invocation.getMapping().isAnnotationPresent(TokenValidate.class); if (needed) { ServletRequest request = (ServletRequest) invocation.getRequest(); String token = request.getParameter(name); if (token == null) throw new TokenRequiredException(); tokenManager.verify(token); } return invocation.invoke(); } public String getName() { return name; } public void setName(String name) { this.name = name; } }