text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update CT Transit feed fetcher CT Transit has changed their URLs.
"""Fetch CT Transit (Connecticut) feeds.""" import logging from FeedSource import FeedSource LOG = logging.getLogger(__name__) BASE_URL = 'http://www.cttransit.com/sites/default/files/gtfs/googlect_transit.zip' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' HARTFORD_URL = 'http://www.hartfordline.com/files/gtfs/gtfs.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() self.urls = { 'ct_transit.zip': BASE_URL, 'ct_shoreline_east.zip': SHORELINE_EAST_URL, 'ct_hartford_rail.zip': HARTFORD_URL }
"""Fetch CT Transit (Connecticut) feeds.""" import logging from FeedSource import FeedSource LOG = logging.getLogger(__name__) BASE_URL = 'http://www.cttransit.com/uploads_GTFS/' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() # feeds for Hartford, New Haven, Stamford, Waterbury, New Britain, Meridien, # and Shore Line East. Shore Line East has its own URL. ct_suffixes = {'Hartford': 'ha', 'New Haven': 'nh', 'Stamford': 'stam', 'Waterbury': 'wat', 'New Britain': 'nb', 'Meridien': 'me'} urls = {} for sfx in ct_suffixes: url = '%sgoogle%s_transit.zip' % (BASE_URL, ct_suffixes[sfx]) filename = 'ct_%s.zip' % ct_suffixes[sfx] urls[filename] = url urls['ct_shoreline_east.zip'] = SHORELINE_EAST_URL self.urls = urls
Remove depency to removed database.php
<?php $config = require 'app/config.php'; require 'app/services/net-usage-monitor.php'; $pdo = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['database'], $config['db']['username'], $config['db']['password']); $netUsageMonitor = new NetUsageMonitor($pdo); foreach ($config['routers'] AS $routerConfig) { require_once('app/router-interfaces/' . $routerConfig['routerInterface']); $router = new $routerConfig['class']($routerConfig); $usage = $router->getUsageSinceLastQuery(); $netUsageMonitor->save($usage['dataReceived'], $usage['dataSent']); } require_once 'app/services/speedtest.php'; $speedTest = new SpeedTest('http://jts.kapsi.fi/speedtest/1m.zip'); $info = $speedTest->run(); print_r($info);
<?php $config = require 'app/config.php'; require 'app/models/database.php'; require 'app/services/net-usage-monitor.php'; $pdo = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['database'], $config['db']['username'], $config['db']['password']); $netUsageMonitor = new NetUsageMonitor($pdo); foreach ($config['routers'] AS $routerConfig) { require_once('app/router-interfaces/' . $routerConfig['routerInterface']); $router = new $routerConfig['class']($routerConfig); $usage = $router->getUsageSinceLastQuery(); $netUsageMonitor->save($usage['dataReceived'], $usage['dataSent']); } require_once 'app/services/speedtest.php'; $speedTest = new SpeedTest('http://jts.kapsi.fi/speedtest/1m.zip'); $info = $speedTest->run(); print_r($info);
Remove stray print debug message Signed-off-by: Steven Dake <8638f3fce5db0278cfbc239bd581dfc00c29ec9d@redhat.com>
class LazyPluggable(object): """A pluggable backend loaded lazily based on some value.""" def __init__(self, pivot, **backends): self.__backends = backends self.__pivot = pivot self.__backend = None def __get_backend(self): if not self.__backend: backend_name = 'sqlalchemy' backend = self.__backends[backend_name] if isinstance(backend, tuple): name = backend[0] fromlist = backend[1] else: name = backend fromlist = backend self.__backend = __import__(name, None, None, fromlist) return self.__backend def __getattr__(self, key): backend = self.__get_backend() return getattr(backend, key)
class LazyPluggable(object): """A pluggable backend loaded lazily based on some value.""" def __init__(self, pivot, **backends): self.__backends = backends self.__pivot = pivot self.__backend = None def __get_backend(self): if not self.__backend: print self.__backends.values() backend_name = 'sqlalchemy' backend = self.__backends[backend_name] if isinstance(backend, tuple): name = backend[0] fromlist = backend[1] else: name = backend fromlist = backend self.__backend = __import__(name, None, None, fromlist) return self.__backend def __getattr__(self, key): backend = self.__get_backend() return getattr(backend, key)
Add entryCssClasses functionality to referenced list field.
export default function maReferencedListColumn(NgAdminConfiguration) { return { scope: { 'field': '&', 'datastore': '&' }, restrict: 'E', link: { pre: function(scope) { scope.field = scope.field(); var targetEntity = scope.field.targetEntity(); scope.entries = scope.datastore().getEntries(targetEntity.uniqueId + '_list'); scope.entity = NgAdminConfiguration().getEntity(targetEntity.name()); } }, template: ` <ma-datagrid ng-if="::entries.length > 0" name="{{ field.datagridName() }}" entries="::entries" fields="::field.targetFields()" list-actions="::field.listActions()" entity="::entity" datastore="::datastore()" entry-css-classes="::field.entryCssClasses()"> </ma-datagrid>` }; } maReferencedListColumn.$inject = ['NgAdminConfiguration'];
export default function maReferencedListColumn(NgAdminConfiguration) { return { scope: { 'field': '&', 'datastore': '&' }, restrict: 'E', link: { pre: function(scope) { scope.field = scope.field(); var targetEntity = scope.field.targetEntity(); scope.entries = scope.datastore().getEntries(targetEntity.uniqueId + '_list'); scope.entity = NgAdminConfiguration().getEntity(targetEntity.name()); } }, template: ` <ma-datagrid ng-if="::entries.length > 0" name="{{ field.datagridName() }}" entries="::entries" fields="::field.targetFields()" list-actions="::field.listActions()" entity="::entity" datastore="::datastore()"> </ma-datagrid>` }; } maReferencedListColumn.$inject = ['NgAdminConfiguration'];
Allow for static contents served over CDN
import json import stripe import os import flask from flask import g from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager, current_user from flask.ext.cdn import CDN from formspree import log from flask_redis import Redis import settings DB = SQLAlchemy() redis_store = Redis() stripe.api_key = settings.STRIPE_SECRET_KEY cdn = CDN() import routes from users.models import User def configure_login(app): login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'register' @login_manager.user_loader def load_user(id): return User.query.get(int(id)) @app.before_request def before_request(): g.user = current_user def create_app(): app = flask.Flask(__name__) app.config.from_object(settings) DB.init_app(app) redis_store.init_app(app) routes.configure_routes(app) configure_login(app) app.jinja_env.filters['json'] = json.dumps app.config['CDN_DOMAIN'] = os.getenv('CDN_URL') app.config['CDN_HTTPS'] = True cdn.init_app(app) return app
import json import stripe import flask from flask import g from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager, current_user from flask_redis import Redis import settings DB = SQLAlchemy() redis_store = Redis() stripe.api_key = settings.STRIPE_SECRET_KEY import routes from users.models import User def configure_login(app): login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'register' @login_manager.user_loader def load_user(id): return User.query.get(int(id)) @app.before_request def before_request(): g.user = current_user def create_app(): app = flask.Flask(__name__) app.config.from_object(settings) DB.init_app(app) redis_store.init_app(app) routes.configure_routes(app) configure_login(app) app.jinja_env.filters['json'] = json.dumps return app
Fix one more assertion call
<?php /** * validate field mapper */ namespace Graviton\GeneratorBundle\Tests\Generator\ResourceGenerator; use Graviton\GeneratorBundle\Generator\ResourceGenerator\FieldMapper; /** * @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors> * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link http://swisscom.ch */ class FieldMapperTest extends \PHPUnit_Framework_TestCase { /** * @return void */ public function testWillCallMapperr() { $sut = new FieldMapper; $context = new \StdClass; $mapperDouble = $this->getMock('\Graviton\GeneratorBundle\Generator\ResourceGenerator\FieldMapperInterface'); $mapperDouble->expects($this->exactly(2)) ->method('map') ->with([], $context) ->willReturn([]); $sut->addMapper($mapperDouble); $sut->addMapper($mapperDouble); $this->assertEquals([], $sut->map([], $context)); } }
<?php /** * validate field mapper */ namespace Graviton\GeneratorBundle\Tests\Generator\ResourceGenerator; use Graviton\GeneratorBundle\Generator\ResourceGenerator\FieldMapper; /** * @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors> * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link http://swisscom.ch */ class FieldMapperTest extends \PHPUnit_Framework_TestCase { /** * @return void */ public function testWillCallMapperr() { $sut = new FieldMapper; $context = new \StdClass; $mapperDouble = $this->getMock('\Graviton\GeneratorBundle\Generator\ResourceGenerator\FieldMapperInterface'); $mapperDouble->expects($this->exactly(2)) ->method('map') ->with([], $context) ->willReturn([]); $sut->addMapper($mapperDouble); $sut->addMapper($mapperDouble); $this->assertEquals($sut->map([], $context), []); } }
Adjust entry_points to fix autoscan
# -*- coding: utf-8 -*- from setuptools import setup, find_packages name = 'morepath_cerebral_todomvc' description = ( 'Morepath example of using React & Cerebral' ) version = '0.1.0' setup( name=name, version=version, description=description, author='Henri Hulski', author_email='henri.hulski@gazeta.pl', license='MIT', url="https://github.com/morepath/morepath_cerebral_todomvc", packages=find_packages(), include_package_data=True, zip_safe=False, platforms='any', install_requires=[ 'morepath>=0.14', ], extras_require=dict( test=[ 'pytest', 'webtest', ], ), entry_points=dict( morepath=[ 'scan = server', ], console_scripts=[ 'run-app = server.run:run', ], ), classifiers=[ 'Intended Audience :: Developers', 'Environment :: Web Environment', 'Topic :: Internet :: WWW/HTTP :: WSGI', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ] )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages name = 'morepath_cerebral_todomvc' description = ( 'Morepath example of using React & Cerebral' ) version = '0.1.0' setup( name=name, version=version, description=description, author='Henri Hulski', author_email='henri.hulski@gazeta.pl', license='MIT', url="https://github.com/morepath/morepath_cerebral_todomvc", packages=find_packages(), include_package_data=True, zip_safe=False, platforms='any', install_requires=[ 'morepath>=0.14', ], extras_require=dict( test=[ 'pytest', 'webtest', ], ), entry_points=dict( console_scripts=[ 'run-app = morepath_cerebral_todomvc.run:run', ] ), classifiers=[ 'Intended Audience :: Developers', 'Environment :: Web Environment', 'Topic :: Internet :: WWW/HTTP :: WSGI', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ] )
Sort the queues by name, so that they are deterministic across instances of `django_rq`.
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .queues import get_unique_connection_configs SHOW_ADMIN_LINK = getattr(settings, 'RQ_SHOW_ADMIN_LINK', False) QUEUES = getattr(settings, 'RQ_QUEUES', None) if QUEUES is None: raise ImproperlyConfigured("You have to define RQ_QUEUES in settings.py") NAME = getattr(settings, 'RQ_NAME', 'default') BURST = getattr(settings, 'RQ_BURST', False) # All queues in list format so we can get them by index, includes failed queues QUEUES_LIST = [] for key, value in sorted(QUEUES.items()): QUEUES_LIST.append({'name': key, 'connection_config': value}) for config in get_unique_connection_configs(): QUEUES_LIST.append({'name': 'failed', 'connection_config': config})
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .queues import get_unique_connection_configs SHOW_ADMIN_LINK = getattr(settings, 'RQ_SHOW_ADMIN_LINK', False) QUEUES = getattr(settings, 'RQ_QUEUES', None) if QUEUES is None: raise ImproperlyConfigured("You have to define RQ_QUEUES in settings.py") NAME = getattr(settings, 'RQ_NAME', 'default') BURST = getattr(settings, 'RQ_BURST', False) # All queues in list format so we can get them by index, includes failed queues QUEUES_LIST = [] for key, value in QUEUES.items(): QUEUES_LIST.append({'name': key, 'connection_config': value}) for config in get_unique_connection_configs(): QUEUES_LIST.append({'name': 'failed', 'connection_config': config})
Add ImplicitClawSolver1D to base namespace
# ===================================================================== # Package: petclaw # File: __init__.py # Authors: Amal Alghamdi # David Ketcheson # Aron Ahmadia # ====================================================================== """Main petclaw package""" import os import logging, logging.config # Default logging configuration file _DEFAULT_LOG_CONFIG_PATH = os.path.join(os.path.dirname(__file__),'log.config') del os # Setup loggers logging.config.fileConfig(_DEFAULT_LOG_CONFIG_PATH) __all__ = [] # Module imports __all__.extend(['Controller','Data','Dimension','Grid','Solution','State','riemann']) from controller import Controller from grid import Dimension from pyclaw.grid import Grid from pyclaw.data import Data from pyclaw.solution import Solution from state import State __all__.extend(['ClawSolver1D','ClawSolver2D','SharpClawSolver1D','SharpClawSolver2D']) from clawpack import ClawSolver1D from clawpack import ClawSolver2D from sharpclaw import SharpClawSolver1D from sharpclaw import SharpClawSolver2D from implicitclawpack import ImplicitClawSolver1D __all__.append('BC') from pyclaw.solver import BC # Sub-packages import limiters from limiters import * __all__.extend(limiters.__all__) import plot __all__.append('plot')
# ===================================================================== # Package: petclaw # File: __init__.py # Authors: Amal Alghamdi # David Ketcheson # Aron Ahmadia # ====================================================================== """Main petclaw package""" import os import logging, logging.config # Default logging configuration file _DEFAULT_LOG_CONFIG_PATH = os.path.join(os.path.dirname(__file__),'log.config') del os # Setup loggers logging.config.fileConfig(_DEFAULT_LOG_CONFIG_PATH) __all__ = [] # Module imports __all__.extend(['Controller','Data','Dimension','Grid','Solution','State','riemann']) from controller import Controller from grid import Dimension from pyclaw.grid import Grid from pyclaw.data import Data from pyclaw.solution import Solution from state import State __all__.extend(['ClawSolver1D','ClawSolver2D','SharpClawSolver1D','SharpClawSolver2D']) from clawpack import ClawSolver1D from clawpack import ClawSolver2D from sharpclaw import SharpClawSolver1D from sharpclaw import SharpClawSolver2D __all__.append('BC') from pyclaw.solver import BC # Sub-packages import limiters from limiters import * __all__.extend(limiters.__all__) import plot __all__.append('plot')
Fix read max-data-per-node correctly in memory connector config
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.plugin.memory; import io.airlift.configuration.Config; import io.airlift.units.DataSize; import javax.validation.constraints.NotNull; public class MemoryConfig { private int splitsPerNode = Runtime.getRuntime().availableProcessors(); private DataSize maxDataPerNode = new DataSize(128, DataSize.Unit.MEGABYTE); @NotNull public int getSplitsPerNode() { return splitsPerNode; } @Config("memory.splits-per-node") public MemoryConfig setSplitsPerNode(int splitsPerNode) { this.splitsPerNode = splitsPerNode; return this; } @NotNull public DataSize getMaxDataPerNode() { return maxDataPerNode; } @Config("memory.max-data-per-node") public MemoryConfig setMaxDataPerNode(DataSize maxDataPerNode) { this.maxDataPerNode = maxDataPerNode; return this; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.plugin.memory; import io.airlift.configuration.Config; import io.airlift.units.DataSize; import javax.validation.constraints.NotNull; public class MemoryConfig { private int splitsPerNode = Runtime.getRuntime().availableProcessors(); private DataSize maxDataPerNode = new DataSize(128, DataSize.Unit.MEGABYTE); @NotNull public int getSplitsPerNode() { return splitsPerNode; } @Config("splits-per-node") public MemoryConfig setSplitsPerNode(int splitsPerNode) { this.splitsPerNode = splitsPerNode; return this; } @NotNull public DataSize getMaxDataPerNode() { return maxDataPerNode; } @Config("max-data-per-node") public MemoryConfig setMaxDataPerNode(DataSize maxDataPerNode) { this.maxDataPerNode = maxDataPerNode; return this; } }
Make incrementing tests check the cache was actually used, too
<?php class IncrementingTest extends RememberTestCase { public function testIncrementingModelsPopsCache() { $group = Group::create(['id' => static::ID, 'name' => 'counter test', 'counter' => 0]); $cached = Group::find(static::ID); $group->increment('counter'); $new = Group::find(static::ID); $this->assertNotEquals($cached, $new); $this->assertEquals(1, $group->counter); $this->assertEquals(1, $new->counter); static::$sql = false; // check we've properly cached here. Group::find(static::ID); } public function testDecrementingModelsPopsCache() { $group = Group::create(['id' => static::ID, 'name' => 'counter test', 'counter' => 0]); $cached = Group::find(static::ID); $group->decrement('counter'); $new = Group::find(static::ID); $this->assertNotEquals($cached, $new); $this->assertEquals(-1, $group->counter); $this->assertEquals(-1, $new->counter); static::$sql = false; // check we've properly cached here. Group::find(static::ID); } }
<?php class IncrementingTest extends RememberTestCase { public function testIncrementingModelsPopsCache() { $group = Group::create(['id' => static::ID, 'name' => 'counter test', 'counter' => 0]); $cached = Group::find(static::ID); $group->increment('counter'); $new = Group::find(static::ID); $this->assertNotEquals($cached, $new); $this->assertEquals(1, $group->counter); $this->assertEquals(1, $new->counter); } public function testDecrementingModelsPopsCache() { $group = Group::create(['id' => static::ID, 'name' => 'counter test', 'counter' => 0]); $cached = Group::find(static::ID); $group->decrement('counter'); $new = Group::find(static::ID); $this->assertNotEquals($cached, $new); $this->assertEquals(-1, $group->counter); $this->assertEquals(-1, $new->counter); } }
Add the ability to pass in the an aws.Config object when creating a NewSQSClient
package worker import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sqs" ) // NewSQSClient returns a SQS Client and a Queue URL for you you to connect to func NewSQSClient(queueName string, cfgs ...*aws.Config) (*sqs.SQS, string) { sess, err := session.NewSession() if err != nil { fmt.Println("failed to create session,", err) return nil, "" } svc := sqs.New(sess, cfgs...) // try and find the queue url params := &sqs.GetQueueUrlInput{ QueueName: aws.String(queueName), // Required } resp, err := svc.GetQueueUrl(params) if err != nil { // Print the error, cast err to aws err.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return nil, "" } return svc, aws.StringValue(resp.QueueUrl) }
package worker import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sqs" ) // NewSQSClient returns a SQS Client and a Queue URL for you you to connect to func NewSQSClient(queueName string) (*sqs.SQS, string) { sess, err := session.NewSession() if err != nil { fmt.Println("failed to create session,", err) return nil, "" } svc := sqs.New(sess) // try and find the queue url params := &sqs.GetQueueUrlInput{ QueueName: aws.String(queueName), // Required } resp, err := svc.GetQueueUrl(params) if err != nil { // Print the error, cast err to aws err.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return nil, "" } return svc, aws.StringValue(resp.QueueUrl) }
HOTFIX: Fix cloudfoundry using wrong node version
var locationGraph = require('../assets/data/demo-picker-data-1.json') function isCanonicalNode (node) { return node.meta.canonical } function presentableName (node, locale) { var requestedName = node['names'][locale] var fallback = Object.keys(node['names']).map(k => node['names'][k])[0] return requestedName || fallback } var locationReverseMap = (preferredLocale) => Object.keys(locationGraph) .reduce((revMap, curie) => { var node = locationGraph[curie] Object.keys(node.names).forEach(locale => { var name = node.names[locale] // HACK to prevent overriding for example Antarctica, // where the en-GB and cy names are identical, and we want // en-GB to stay on top. var isntDefinedOrLocaleIsEnGb = !revMap[name] || locale === preferredLocale if (isntDefinedOrLocaleIsEnGb) { revMap[name] = { node, locale } } }) return revMap }, {}) var canonicalLocationList = (preferredLocale) => Object.keys(locationGraph) .reduce((list, curie) => { var node = locationGraph[curie] return isCanonicalNode(node) ? list.concat([presentableName(node, preferredLocale)]) : list }, []) .sort() module.exports = { canonicalLocationList: canonicalLocationList, locationGraph: locationGraph, locationReverseMap: locationReverseMap }
var locationGraph = require('../assets/data/demo-picker-data-1.json') function isCanonicalNode (node) { return node.meta.canonical } function presentableName (node, locale) { var requestedName = node['names'][locale] var fallback = Object.values(node['names'])[0] return requestedName || fallback } var locationReverseMap = (preferredLocale) => Object.keys(locationGraph) .reduce((revMap, curie) => { var node = locationGraph[curie] Object.keys(node.names).forEach(locale => { var name = node.names[locale] // HACK to prevent overriding for example Antarctica, // where the en-GB and cy names are identical, and we want // en-GB to stay on top. var isntDefinedOrLocaleIsEnGb = !revMap[name] || locale === preferredLocale if (isntDefinedOrLocaleIsEnGb) { revMap[name] = { node, locale } } }) return revMap }, {}) var canonicalLocationList = (preferredLocale) => Object.keys(locationGraph) .reduce((list, curie) => { var node = locationGraph[curie] return isCanonicalNode(node) ? list.concat([presentableName(node, preferredLocale)]) : list }, []) .sort() module.exports = { canonicalLocationList: canonicalLocationList, locationGraph: locationGraph, locationReverseMap: locationReverseMap }
Remove intentional unused import to clean branch
from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), )
import time from django.conf.urls import patterns, url, include urlpatterns = patterns('', url(r'', include(patterns('', url(r'^$', include('serrano.resources')), url(r'^fields/', include('serrano.resources.field')), url(r'^concepts/', include('serrano.resources.concept')), url(r'^contexts/', include('serrano.resources.context', namespace='contexts')), url(r'^queries/', include('serrano.resources.query', namespace='queries')), url(r'^views/', include('serrano.resources.view', namespace='views')), url(r'^data/', include(patterns('', url(r'^export/', include('serrano.resources.exporter')), url(r'^preview/', include('serrano.resources.preview')), ), namespace='data')), ), namespace='serrano')), )
Update displayName of wrapped component to include HoC name
import React, { Component } from 'react' import PropTypes from 'prop-types' export const getContextualizer = (propTypes, targetProp) => { class ContextProps extends Component { getChildContext () { const props = Object.keys(this.props).reduce((x, key) => { if (key !== 'children') { x[key] = this.props[key] } return x }, {}) return targetProp ? { [targetProp]: props } : props } render () { return <span>{this.props.children}</span> } } ContextProps.displayName = 'ContextProps' ContextProps.childContextTypes = targetProp ? { [targetProp]: PropTypes.shape(propTypes) } : propTypes return ContextProps } export const withPropsFromContext = propList => Target => { class WithPropsFromContext extends Component { render () { const props = { ...propList.reduce((x, prop) => { x[prop] = this.context[prop] return x }, {}), ...this.props } return <Target {...props} /> } } WithPropsFromContext.contextTypes = propList.reduce((x, prop) => { x[prop] = PropTypes.any return x }, {}) WithPropsFromContext.displayName = `withPropsFromContext(${Target.displayName || Target.name})` return WithPropsFromContext }
import React, { Component } from 'react' import PropTypes from 'prop-types' export const getContextualizer = (propTypes, targetProp) => { class ContextProps extends Component { getChildContext () { const props = Object.keys(this.props).reduce((x, key) => { if (key !== 'children') { x[key] = this.props[key] } return x }, {}) return targetProp ? { [targetProp]: props } : props } render () { return <span>{this.props.children}</span> } } ContextProps.displayName = 'ContextProps' ContextProps.childContextTypes = targetProp ? { [targetProp]: PropTypes.shape(propTypes) } : propTypes return ContextProps } export const withPropsFromContext = propList => Target => { class WithPropsFromContext extends Component { render () { const props = { ...propList.reduce((x, prop) => { x[prop] = this.context[prop] return x }, {}), ...this.props } return <Target {...props} /> } } WithPropsFromContext.contextTypes = propList.reduce((x, prop) => { x[prop] = PropTypes.any return x }, {}) WithPropsFromContext.displayName = Target.displayName || Target.name return WithPropsFromContext }
Set UI as best on OS
package ru.faulab.attendence; import com.google.inject.Guice; import com.google.inject.Injector; import ru.faulab.attendence.module.MainModule; import ru.faulab.attendence.ui.MainFrame; import javax.swing.*; public class Runner { /* * 1. Статистика * */ public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); String userHome = System.getProperty("user.home"); System.setProperty("derby.system.home", userHome); Injector injector = Guice.createInjector(new MainModule()); MainFrame mainFrame = injector.getInstance(MainFrame.class); mainFrame.init(); } }
package ru.faulab.attendence; import com.google.inject.Guice; import com.google.inject.Injector; import ru.faulab.attendence.module.MainModule; import ru.faulab.attendence.ui.MainFrame; public class Runner { /* * 1. Статистика * */ public static void main(String[] args) throws Exception { String userHome = System.getProperty("user.home"); System.setProperty("derby.system.home", userHome); Injector injector = Guice.createInjector(new MainModule()); MainFrame mainFrame = injector.getInstance(MainFrame.class); mainFrame.init(); } }
Add pyscopg2 to list of dependencies Former-commit-id: afed58eea17319b11e3fafc1ef45c7cdf590fac0 Former-commit-id: 257ed272462ca52cc15bae9040296ace91e15843 [formerly 19b9a870795fb176a9fb49b427a00b70fc6e2b35] [formerly 5b2ece2b396282c63c2902d6128e3a1f2c982708 [formerly 1a662bf08f6e4b81939fe16c4422c7201c9394f5]] Former-commit-id: 2336bd3da92c144e041fba0c6d8a06f8c5beb9d3 [formerly e493e91f63a6989ea1b5c3add83dec0a8a4de16b] Former-commit-id: a778516564b1489efffbb822760e23ead82c4467
#!/usr/bin/evn python2 from setuptools import setup, find_packages setup(name='pprof', version='0.9.6', packages=find_packages(), install_requires=["SQLAlchemy==1.0.4", "cloud==2.8.5", "plumbum==1.4.2", "regex==2015.5.28", "wheel==0.24.0", "parse==1.6.6", "virtualenv==13.1.0", "sphinxcontrib-napoleon", "psycopg2"], author="Andreas Simbuerger", author_email="simbuerg@fim.uni-passau.de", description="This is the experiment driver for the pprof study", license="MIT", entry_points={ 'console_scripts': ['pprof=pprof.driver:main'] })
#!/usr/bin/evn python2 from setuptools import setup, find_packages setup(name='pprof', version='0.9.6', packages=find_packages(), install_requires=["SQLAlchemy==1.0.4", "cloud==2.8.5", "plumbum==1.4.2", "regex==2015.5.28", "wheel==0.24.0", "parse==1.6.6", "virtualenv==13.1.0", "sphinxcontrib-napoleon"], author="Andreas Simbuerger", author_email="simbuerg@fim.uni-passau.de", description="This is the experiment driver for the pprof study", license="MIT", entry_points={ 'console_scripts': ['pprof=pprof.driver:main'] })
Add tested python version in classifiers
from setuptools import setup import generate generate.run() setup( name='nnpy', version='0.1', url='https://github.com/nanomsg/nnpy', license='MIT', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='cffi-based Python bindings for nanomsg', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', ], packages=['nnpy'], package_data={'nnpy': ['*.h']}, install_requires=['cffi'], )
from setuptools import setup import generate generate.run() setup( name='nnpy', version='0.1', url='https://github.com/nanomsg/nnpy', license='MIT', author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', description='cffi-based Python bindings for nanomsg', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], packages=['nnpy'], package_data={'nnpy': ['*.h']}, install_requires=['cffi'], )
Add method createLEDMatrixBuffer. Fix bug in writeLEDS. Add example of using createLEDMatrixBuffer
/** * To run example * * cd <project directory * npm install * ./node_modules/.bin/babel-node ./examples/cycle-leds.js */ import withNuimo from "../src"; import images from './led-images'; console.log('Looking for Nuimo device...'); withNuimo().then(nuimo => { var ledImages = []; var currentIndex = 0; console.log('Loading images...'); for(var key of Object.keys(images)){ ledImages.push(nuimo.createLEDMatrixBuffer(images[key])); } console.log('Images loaded. Press Nuimo to cycle through loaded images.'); nuimo.listen(data => { if(data.type === 'click' && data.down){ nuimo.writeLEDS(ledImages[currentIndex], .8, 2); currentIndex = (currentIndex+1) % ledImages.length; } }); }).catch(e => { console.log('ERROR', e); });
/** * To run example * * cd <project directory * npm install * ./node_modules/.bin/babel-node ./examples/cycle-leds.js */ import withNuimo from "../src"; import {ClickUpdate} from "../src/update" import images from './led-images'; console.log('Looking for Nuimo device...'); withNuimo().then(nuimo => { var ledImages = []; var currentIndex = 0; console.log('Loading images...'); for(var key of Object.keys(images)){ ledImages.push(nuimo.createLEDMatrixBuffer(images[key])); } console.log('Images loaded. Press button to cycle through loaded images.'); nuimo.listen(data => { if(data.type === 'click' && data.down){ nuimo.writeLEDS(ledImages[currentIndex], .8, 2); currentIndex = (currentIndex+1) % ledImages.length; } }); }).catch(e=>{ console.log('ERROR', e); });
Remove gutter to match the output
import React, { PropTypes } from 'react' import styled from 'styled-components' import AceEditor from 'react-ace' const PreviewContainer = styled.div` align-self: center; padding: 28px; width: 100%; height: 400px; background-color: white; border: 1px solid rgba(0, 0, 0, 0.35); box-shadow: 0 2px 16px 2px rgba(0, 0, 0, 0.25); box-sizing: border-box; overflow: scroll; ` function DynamicPreview({ value, fontface, language, theme }) { require(`brace/mode/${language}`) // eslint-disable-line require(`brace/theme/${theme}`) // eslint-disable-line return ( <PreviewContainer> <AceEditor mode={language} theme={theme} value={value} showGutter={false} style={{ fontFamily: fontface }} /> </PreviewContainer> ) } DynamicPreview.propTypes = { value: PropTypes.string.isRequired, fontface: PropTypes.string, language: PropTypes.string.isRequired, theme: PropTypes.string.isRequired } export default DynamicPreview
import React, { PropTypes } from 'react' import styled from 'styled-components' import AceEditor from 'react-ace' const PreviewContainer = styled.div` align-self: center; padding: 28px; width: 100%; height: 400px; background-color: white; border: 1px solid rgba(0, 0, 0, 0.35); box-shadow: 0 2px 16px 2px rgba(0, 0, 0, 0.25); box-sizing: border-box; overflow: scroll; ` function DynamicPreview({ value, fontface, language, theme }) { require(`brace/mode/${language}`) // eslint-disable-line require(`brace/theme/${theme}`) // eslint-disable-line return ( <PreviewContainer> <AceEditor mode={language} theme={theme} value={value} style={{ fontFamily: fontface }} /> </PreviewContainer> ) } DynamicPreview.propTypes = { value: PropTypes.string.isRequired, fontface: PropTypes.string, language: PropTypes.string.isRequired, theme: PropTypes.string.isRequired } export default DynamicPreview
Add a sanity check per @bbangert
import os from nose import SkipTest from sys import platform from kazoo.testing import KazooTestCase class KazooInterruptTests(KazooTestCase): def test_interrupted_systemcall(self): ''' Make sure interrupted system calls don't break the world, since we can't control what all signals our connection thread will get ''' if 'linux' not in platform: raise SkipTest('Unable to reproduce error case on non-linux platforms') path = 'interrupt_test' value = b"1" self.client.create(path, value) # set the euid to the current process' euid. # glibc sends SIGRT to all children, which will interrupt the system call os.seteuid(os.geteuid()) # basic sanity test that it worked alright assert self.client.get(path)[0] == value
import os from nose import SkipTest from sys import platform from kazoo.testing import KazooTestCase class KazooInterruptTests(KazooTestCase): def test_interrupted_systemcall(self): ''' Make sure interrupted system calls don't break the world, since we can't control what all signals our connection thread will get ''' if 'linux' not in platform: raise SkipTest('Unable to reproduce error case on non-linux platforms') path = 'interrupt_test' self.client.create(path, b"1") # set the euid to the current process' euid. # glibc sends SIGRT to all children, which will interrupt the system call os.seteuid(os.geteuid()) self.client.get_children(path)
Revert "do not test the dst for palmer (do not understand php behaviour for this one)" This reverts commit a830d15881d2aafb11357c4591568ea53c60a22b.
<?php declare(strict_types = 1); namespace Tests\Innmind\TimeContinuum\Timezone\Earth\Antarctica; use Innmind\TimeContinuum\{ Timezone\Earth\Antarctica\Palmer, TimezoneInterface }; class PalmerTest extends \PHPUnit_Framework_TestCase { public function testInterface() { $zone = new Palmer; $this->assertInstanceOf(TimezoneInterface::class, $zone); $this->assertSame(-3, $zone->hours()); $this->assertSame(0, $zone->minutes()); $this->assertSame('-03:00', (string) $zone); $this->assertFalse($zone->daylightSavingTimeApplied()); return; //seems php doesn't take into account the change of using DST since 2016 if ($zone->daylightSavingTimeApplied()) { $this->assertSame(-3, $zone->hours()); $this->assertSame(0, $zone->minutes()); $this->assertSame('-03:00', (string) $zone); } else { $this->assertSame(-4, $zone->hours()); $this->assertSame(0, $zone->minutes()); $this->assertSame('-04:00', (string) $zone); } } }
<?php declare(strict_types = 1); namespace Tests\Innmind\TimeContinuum\Timezone\Earth\Antarctica; use Innmind\TimeContinuum\{ Timezone\Earth\Antarctica\Palmer, TimezoneInterface }; class PalmerTest extends \PHPUnit_Framework_TestCase { public function testInterface() { $zone = new Palmer; $this->assertInstanceOf(TimezoneInterface::class, $zone); $this->assertSame(-3, $zone->hours()); $this->assertSame(0, $zone->minutes()); $this->assertSame('-03:00', (string) $zone); return; //seems php doesn't take into account the change of using DST since 2016 if ($zone->daylightSavingTimeApplied()) { $this->assertSame(-3, $zone->hours()); $this->assertSame(0, $zone->minutes()); $this->assertSame('-03:00', (string) $zone); } else { $this->assertSame(-4, $zone->hours()); $this->assertSame(0, $zone->minutes()); $this->assertSame('-04:00', (string) $zone); } } }
fix(date): Update date for new study year
package com.ssu.schedule.model; public class Day { private String start = "01.09.2017"; private String end = "01.07.2018"; private int weekday; private int week = 0; public void setWeekday(int weekday) { this.weekday = weekday; } public void setWeek(int week) { this.week = week; } public int getWeekday() { return weekday; } public int getWeek() { return week; } public String getStart() { return start; } public void setStart(String start) { this.start = start; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } }
package com.ssu.schedule.model; public class Day { private String start = "01.09.2016"; private String end = "01.07.2017"; private int weekday; private int week = 0; public void setWeekday(int weekday) { this.weekday = weekday; } public void setWeek(int week) { this.week = week; } public int getWeekday() { return weekday; } public int getWeek() { return week; } public String getStart() { return start; } public void setStart(String start) { this.start = start; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } }
Move parser object into port open
/* eslint-disable node/no-missing-require */ 'use strict'; const SerialPort = require('../../'); const ByteLength = SerialPort.parsers.ByteLength; const exec = require('child_process').exec; // Serial receiver device const port = process.env.TEST_PORT_RX; // Expected number of bytes to receive (should make `size` in drain.js) const expected = 512; if (!port) { console.error('Please pass TEST_PORT_RX environment variable'); process.exit(1); } // Create read device const serialPort = new SerialPort(port, (err) => { if (err) { throw err } }); serialPort.on('open', () => { // Run the drain script from the sender device exec('node drain.js', (err, stdout) => { if (err) { // node couldn't execute the command process.exit(1); } console.log(stdout); const parser = serialPort.pipe(new ByteLength({ length: expected })); // Read back the data received on the read device after a short timout to ensure transmission parser.on('data', (data) => { console.log(`Sucessfully received data dength: ${data.length} B`); process.exit(0); }); // Set a timeout so the process exits if no data received setTimeout(() => { console.log('Receive data timeout'); process.exit(1); }, 10000); }); });
/* eslint-disable node/no-missing-require */ 'use strict'; const SerialPort = require('../../'); const exec = require('child_process').exec; // Serial receiver device const port = process.env.TEST_PORT_RX; // Expected number of bytes to receive (should make `size` in drain.js) const expected = 512; const ByteLength = SerialPort.parsers.ByteLength; const parser = port.pipe(new ByteLength({ length: expected })); if (!port) { console.error('Please pass TEST_PORT_RX environment variable'); process.exit(1); } // Create read device const serialPort = new SerialPort(port, (err) => { if (err) { throw err } }); serialPort.on('open', () => { // Run the drain script from the sender device exec('node drain.js', (err, stdout) => { if (err) { // node couldn't execute the command process.exit(1); } console.log(stdout); // Read back the data received on the read device after a short timout to ensure transmission parser.on('data', (data) => { console.log(`Sucessfully received data dength: ${data.length} B`); process.exit(0); }); // Set a timeout so the process exits if no data received setTimeout(() => { console.log('Receive data timeout'); process.exit(1); }, 10000); }); });
Add method for creating keypair with default size
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.athenz.tls; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; /** * @author bjorncs */ public class KeyUtils { private KeyUtils() {} public static KeyPair generateKeypair(KeyAlgorithm algorithm, int keySize) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm.getAlgorithmName()); if (keySize != -1) { keyGen.initialize(keySize); } return keyGen.genKeyPair(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } public static KeyPair generateKeypair(KeyAlgorithm algorithm) { return generateKeypair(algorithm, -1); } }
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.athenz.tls; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; /** * @author bjorncs */ public class KeyUtils { private KeyUtils() {} public static KeyPair generateKeypair(KeyAlgorithm algorithm, int keySize) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm.getAlgorithmName()); keyGen.initialize(keySize); return keyGen.genKeyPair(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } }
Print the JSON dump, so it's prettier.
# Here's an example of stuff to copy and paste into an interactive Python # interpreter to get a connection loaded. # Or you can load it with 'python -i interactive_mode.py'. # Set some variables. bmrc = "~/.bmrc" site = "www" bmutilspath = "./lib" # Import everything, make a connection, and try to log in. import json import os import sys sys.path.append(os.path.expanduser(bmutilspath).rstrip("/")) import bmutils bmconnection = bmutils.BMClientParser(os.path.expanduser(bmrc), site) if not bmconnection.verify_login(): print "Could not login" # At this point you can do whatever you want. Here's how to load a game, # and print its info in nice JSON. gamenumber = 3038 game = bmconnection.wrap_load_game_data(gamenumber) print json.dumps(game, sys.stdout, indent=1, sort_keys=True)
# Here's an example of stuff to copy and paste into an interactive Python interpreter to get a connection loaded. # Or you can load it with 'python -i interactive-mode.py'. # Set some variables. bmrc = "~/.bmrc" site = "www" bmutilspath = "./lib" # Import everything, make a connection, and try to log in. import json import os import sys sys.path.append(os.path.expanduser(bmutilspath).rstrip("/")) import bmutils bmconnection = bmutils.BMClientParser(os.path.expanduser(bmrc), site) if not bmconnection.verify_login(): print "Could not login" # At this point you can do whatever you want. Here's how to load a game, and print its info in nice JSON. gamenumber = 3038 game = bmconnection.wrap_load_game_data(gamenumber) json.dump(game, sys.stdout, indent=1, sort_keys=True)
Add PyPI classifiers for Python 3.4, 3.5 and 3.6 Since the tests pass on Python 3.
from setuptools import setup setup( name = "wsgi-sslify", description = "WSGI middleware to force HTTPS.", version = "1.0.1", author = "Jacob Kaplan-Moss", author_email = "jacob@jacobian.org", url = "https://github.com/jacobian/wsgi-sslify", py_modules = ['wsgi_sslify'], install_requires = ['werkzeug>=0.10.1'], classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware' ] )
from setuptools import setup setup( name = "wsgi-sslify", description = "WSGI middleware to force HTTPS.", version = "1.0.1", author = "Jacob Kaplan-Moss", author_email = "jacob@jacobian.org", url = "https://github.com/jacobian/wsgi-sslify", py_modules = ['wsgi_sslify'], install_requires = ['werkzeug>=0.10.1'], classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware' ] )
sql: Change Ip => IP for idiomatic Go
package sql import "github.com/jen20/riviera/azure" type CreateOrUpdateFirewallRuleResponse struct { ID *string `mapstructure:"id"` Name *string `mapstructure:"name"` Location *string `mapstructure:"location"` StartIPAddress *string `json:"startIpAddress,omitempty"` EndIPAddress *string `json:"endIpAddress,omitempty"` } type CreateOrUpdateFirewallRule struct { Name string `json:"-"` ResourceGroupName string `json:"-"` ServerName string `json:"-"` StartIPAddress *string `json:"startIpAddress,omitempty"` EndIPAddress *string `json:"endIpAddress,omitempty"` } func (s CreateOrUpdateFirewallRule) APIInfo() azure.APIInfo { return azure.APIInfo{ APIVersion: apiVersion, Method: "PUT", URLPathFunc: sqlServerFirewallDefaultURLPath(s.ResourceGroupName, s.ServerName, s.Name), ResponseTypeFunc: func() interface{} { return &CreateOrUpdateFirewallRuleResponse{} }, } }
package sql import "github.com/jen20/riviera/azure" type CreateOrUpdateFirewallRuleResponse struct { ID *string `mapstructure:"id"` Name *string `mapstructure:"name"` Location *string `mapstructure:"location"` StartIpAddress *string `json:"startIpAddress,omitempty"` EndIpAddress *string `json:"endIpAddress,omitempty"` } type CreateOrUpdateFirewallRule struct { Name string `json:"-"` ResourceGroupName string `json:"-"` ServerName string `json:"-"` StartIpAddress *string `json:"startIpAddress,omitempty"` EndIpAddress *string `json:"endIpAddress,omitempty"` } func (s CreateOrUpdateFirewallRule) APIInfo() azure.APIInfo { return azure.APIInfo{ APIVersion: apiVersion, Method: "PUT", URLPathFunc: sqlServerFirewallDefaultURLPath(s.ResourceGroupName, s.ServerName, s.Name), ResponseTypeFunc: func() interface{} { return &CreateOrUpdateFirewallRuleResponse{} }, } }
Change route file to be used later
var artistController = require('../controllers/artist-controller'); var genreController = require('../controllers/genre-controller'); module.exports = function(app, passport) { app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect : '/', successRedirect : '/' })); app.get('/profile', function(req, res) { return res.send(200); }); app.post('/api/artist/:id/like', artistController.likeArtist); app.get('/api/artist/recommendation', artistController.getArtistRecommendations); app.get('/api/genre', genreController.getGenres); app.get('/api/genre/artists', genreController.getArtistsByGenre); app.get('*', function(req, res) { return res.render('index.html'); }); };
var artistController = require('../controllers/artist-controller'); var genreController = require('../controllers/genre-controller'); module.exports = function(app, passport) { app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect : '/' }), function(req, res) { return res.status(200).send(req.user); }); app.get('/profile', function(req, res) { return res.send(200); }); app.post('/api/artist/:id/like', artistController.likeArtist); app.get('/api/artist/recommendation', artistController.getArtistRecommendations); app.get('/api/genre', genreController.getGenres); app.get('/api/genre/artists', genreController.getArtistsByGenre); app.get('*', function(req, res) { return res.render('index.html'); }); };
Fix issue on match vm title
import Ember from 'ember'; export default Ember.Component.extend({ isShowingHover: false, commitTitle: function() { if (this.get('vm.commit.title') && this.get('vm.commit.title').match(/^Merge/)) { return this.get('vm.commit.title').replace(/ of.*/g,'').replace(/ into.*/g,''); } return this.get('vm.commit.title'); }.property('vm.commit.title'), setShowingHover: function() { var access_level = this.get('session').get('data.authenticated.access_level'); if (access_level >= 20) { this.set('isShowingHover', this.get('isShowingHovers') === this.get('vm').id); } else { this.set('isShowingHover', false); } }.observes('isShowingHovers'), // Return true if is running state isRunning: function() { if (parseInt(this.get('vm.status'), 10) > 0) { return true; } return false; }.property('vm.status'), // Return true if user is a Dev or more isDev: function() { var access_level = this.get('session').get('data.authenticated.access_level'); if (access_level >= 30) { return true; } return false; }.property('session.data.authenticated.access_level'), actions: { // close the modal, reset showing variable closeHover: function() { this.set('isShowingHovers', -1); } } });
import Ember from 'ember'; export default Ember.Component.extend({ isShowingHover: false, commitTitle: function() { if (this.get('vm.commit.title').match(/^Merge/)) { return this.get('vm.commit.title').replace(/ of.*/g,'').replace(/ into.*/g,''); } return this.get('vm.commit.title'); }.property('vm.commit.title'), setShowingHover: function() { var access_level = this.get('session').get('data.authenticated.access_level'); if (access_level >= 20) { this.set('isShowingHover', this.get('isShowingHovers') === this.get('vm').id); } else { this.set('isShowingHover', false); } }.observes('isShowingHovers'), // Return true if is running state isRunning: function() { if (parseInt(this.get('vm.status'), 10) > 0) { return true; } return false; }.property('vm.status'), // Return true if user is a Dev or more isDev: function() { var access_level = this.get('session').get('data.authenticated.access_level'); if (access_level >= 30) { return true; } return false; }.property('session.data.authenticated.access_level'), actions: { // close the modal, reset showing variable closeHover: function() { this.set('isShowingHovers', -1); } } });
Use built-in IP address functionality to unmap IPv4 addresses
from twisted.internet.protocol import ClientFactory, Factory from txircd.server import IRCServer from txircd.user import IRCUser from ipaddress import ip_address from typing import Union def unmapIPv4(ip: str) -> Union["IPv4Address", "IPv6Address"]: """ Converts an IPv6-mapped IPv4 address to a bare IPv4 address. """ addr = ip_address(ip) if addr.ipv4_mapped is None: return addr return addr.ipv4_mapped class UserFactory(Factory): protocol = IRCUser def __init__(self, ircd): self.ircd = ircd def buildProtocol(self, addr): return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host))) class ServerListenFactory(Factory): protocol = IRCServer def __init__(self, ircd): self.ircd = ircd def buildProtocol(self, addr): return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), True) class ServerConnectFactory(ClientFactory): protocol = IRCServer def __init__(self, ircd): self.ircd = ircd def buildProtocol(self, addr): return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), False)
from twisted.internet.protocol import ClientFactory, Factory from txircd.server import IRCServer from txircd.user import IRCUser from ipaddress import ip_address import re ipv4MappedAddr = re.compile("::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})") def unmapIPv4(ip: str) -> str: """ Converts an IPv6-mapped IPv4 address to a bare IPv4 address. """ mapped = ipv4MappedAddr.match(ip) if mapped: return mapped.group(1) return ip class UserFactory(Factory): protocol = IRCUser def __init__(self, ircd): self.ircd = ircd def buildProtocol(self, addr): return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host))) class ServerListenFactory(Factory): protocol = IRCServer def __init__(self, ircd): self.ircd = ircd def buildProtocol(self, addr): return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), True) class ServerConnectFactory(ClientFactory): protocol = IRCServer def __init__(self, ircd): self.ircd = ircd def buildProtocol(self, addr): return self.protocol(self.ircd, ip_address(unmapIPv4(addr.host)), False)
Enable strict types in menu item group class.
<?php declare(strict_types=1); /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\AdminBundle\Menu; /** * Menu item group */ class ItemGroup extends Item { /** * {@inheritdoc} */ public function __construct(string $name) { parent::__construct($name); $this->indexTitle = sprintf('menu.group.%s.title', $name); $this->indexUrl = '#'; $this->description = sprintf('menu.group.%s.description', $name); } }
<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\AdminBundle\Menu; /** * Menu item group */ class ItemGroup extends Item { /** * {@inheritdoc} */ public function __construct($name) { parent::__construct($name); $this->indexTitle = sprintf('menu.group.%s.title', $name); $this->indexUrl = '#'; $this->description = sprintf('menu.group.%s.description', $name); } }
Add angles to ball close decision
import math from dynamic_stack_decider.abstract_decision_element import AbstractDecisionElement class BallClose(AbstractDecisionElement): def __init__(self, blackboard, dsd, parameters=None): super(BallClose, self).__init__(blackboard, dsd, parameters) self.ball_close_distance = parameters.get("distance", self.blackboard.config['ball_close_distance']) self.ball_close_angle = parameters.get("angle", math.pi) def perform(self, reevaluate=False): """ Determines whether the ball is in close range to the robot. The distance threshold is set in the config file. :param reevaluate: :return: """ self.publish_debug_data("ball_distance", self.blackboard.world_model.get_ball_distance()) self.publish_debug_data("ball_angle", self.blackboard.world_model.get_ball_angle()) if self.blackboard.world_model.get_ball_distance() < self.ball_close_distance and \ abs(self.blackboard.world_model.get_ball_angle()) < self.ball_close_angle: return 'YES' return 'NO' def get_reevaluate(self): return True
from dynamic_stack_decider.abstract_decision_element import AbstractDecisionElement class BallClose(AbstractDecisionElement): def __init__(self, blackboard, dsd, parameters=None): super(BallClose, self).__init__(blackboard, dsd, parameters) self.ball_close_distance = parameters.get("distance", self.blackboard.config['ball_close_distance']) def perform(self, reevaluate=False): """ Determines whether the ball is in close range to the robot. The distance threshold is set in the config file. :param reevaluate: :return: """ self.publish_debug_data("ball_distance", self.blackboard.world_model.get_ball_distance()) if self.blackboard.world_model.get_ball_distance() < self.ball_close_distance: return 'YES' return 'NO' def get_reevaluate(self): return True
Send the restaurant name when creating sitting
<?php require_once 'dbHandler.php'; if(isset($_POST['action']) && !empty($_POST['action'])) { $dbHandler = new DatabaseHandler(); $action = $_POST['action']; switch($action) { case 'addSitting' : addSitting($dbHandler);break; case 'removeSitting' : removeSitting($dbHandler);break; } $dbHandler.disconnect(); } function addSitting($dbHandler){ if(isset($_POST['date']) && !empty($_POST['date'])) { $dbHandler->addSitting($_POST['date'], $_POST['preldate'], $_POST['paydate'], $_POST['resName']); } } function removeSitting($dbHandler){ if(isset($_POST['date']) && !empty($_POST['date'])) { $dbHandler->deleteSitting($_POST['date']); } } ?>
<?php require_once 'dbHandler.php'; if(isset($_POST['action']) && !empty($_POST['action'])) { $dbHandler = new DatabaseHandler(); $action = $_POST['action']; switch($action) { case 'addSitting' : addSitting($dbHandler);break; case 'removeSitting' : removeSitting($dbHandler);break; } $dbHandler.disconnect(); } function addSitting($dbHandler){ if(isset($_POST['date']) && !empty($_POST['date'])) { $dbHandler->addSitting($_POST['date'], $_POST['preldate'], $_POST['paydate']); } } function removeSitting($dbHandler){ if(isset($_POST['date']) && !empty($_POST['date'])) { $dbHandler->deleteSitting($_POST['date']); } } ?>
Hide error pages in page link dropdowns
/* * Do not display error pages in SiteTree or file selector * loaded only when !Permission::check('SITETREE_REORGANISE') */ (function($){ $.entwine('ss', function($){ /* Hide error pages in SiteTree */ $('li[data-pagetype="ErrorPage"]').entwine({ onmatch: function(){ this.hide(); } }); /* Hide error pages in page link dropdowns */ $('li.class-ErrorPage').entwine({ onmatch: function(){ this.hide(); } }); /* Hide error-xxx.html from file selector dropdowns */ $('li.class-File').entwine({ onmatch: function(){ var c = this.text().trim(); if (c.match(/^error-(\d+){3}\.html$/)) this.hide(); } }); /* Hide error-xxx.html from File gridfields */ $('td.col-Title').entwine({ onmatch: function(){ var c = this.text().trim(); if (c.match(/^error-(\d+){3}\.html$/)) this.parent().hide(); } }); }); })(jQuery);
/* * Do not display error pages in SiteTree or file selector * loaded only when !Permission::check('SITETREE_REORGANISE') */ (function($){ $.entwine('ss', function($){ /* Hide error pages in SiteTree */ $('li[data-pagetype="ErrorPage"]').entwine({ onmatch: function(){ this.hide(); } }); /* Hide error-xxx.html from file selector dropdowns */ $('li.class-File').entwine({ onmatch: function(){ var c = this.text().trim(); if (c.match(/^error-(\d+){3}\.html$/)) this.hide(); } }); /* Hide error-xxx.html from File gridfields */ $('td.col-Title').entwine({ onmatch: function(){ var c = this.text().trim(); if (c.match(/^error-(\d+){3}\.html$/)) this.parent().hide(); } }); }); })(jQuery);
Store latest etag in db
const request = require('superagent'); import * as requests from './requestFactory'; import * as data from '../../persistence'; module.exports = function (req, res) { const { type, project } = req.body; const filename = type === 'keywords' ? type + '.txt' : type + '.md'; const saveRepoFile = () => { requests .saveRepoFile(req, filename) .end((err, result) => { project.etag = result.headers.etag; project[type + '_sha'] = result.body.content.sha; data.saveProject(project).then((doc) => { res.json(doc); }); }); } const saveGistFile = () => { requests .saveGistFile(req, filename) .end((err, result) => { project.etag = result.headers.etag; data.saveProject(project).then((doc) => { res.json(doc); }); }); } if (project.isRepo) { saveRepoFile(); } else { saveGistFile(); } }
const request = require('superagent'); import * as requests from './requestFactory'; import * as data from '../../persistence'; module.exports = function (req, res) { const { type, project } = req.body; const filename = type === 'keywords' ? type + '.txt' : type + '.md'; const saveRepoFile = () => { requests .saveRepoFile(req, filename) .end((err, result) => { project[type + '_sha'] = result.body.content.sha; data.saveProject(project).then((doc) => { res.json(doc); }); }); } const saveGistFile = () => { requests .saveGistFile(req, filename) .end((err, results) => { data.saveProject(project).then((doc) => { res.json(doc); }); }); } if (project.isRepo) { saveRepoFile(); } else { saveGistFile(); } }
Fix router name generation at CollerGenerator * Replace hardcoded text DefaultController with passed argumnet {{name}}Controller when rendering routing yml file
<?php namespace Drupal\AppConsole\Generator; use Symfony\Component\DependencyInjection\Container; class ControllerGenerator extends Generator { private $filesystem; public function __construct() {} public function generate($module, $name, $controller, $services) { $path = DRUPAL_ROOT . '/' . drupal_get_path('module', $module); $path_controller = $path . '/lib/Drupal/' . $module . '/Controller'; $parameters = array( 'name' => $name, 'services' => $services, 'module' => $module ); $this->renderFile( 'module/module.'. $name .'Controller.php.twig', $path_controller . '/'. $name .'.php', $parameters ); $this->renderFile('module/controller-routing.yml.twig', DRUPAL_ROOT.'/modules/'.$module.'/'.$module.'.routing.yml', $parameters, FILE_APPEND); } }
<?php namespace Drupal\AppConsole\Generator; use Symfony\Component\DependencyInjection\Container; class ControllerGenerator extends Generator { private $filesystem; public function __construct() {} public function generate($module, $name, $controller, $services ) { $path = DRUPAL_ROOT . '/' . drupal_get_path('module', $module); $path_controller = $path . '/lib/Drupal/' . $module . '/Controller'; $parameters = array( 'name' => $name, 'services' => $services, 'module' => $module ); $this->renderFile( 'module/module.DefaultController.php.twig', $path_controller . '/'. $name .'.php', $parameters ); $this->renderFile('module/controller-routing.yml.twig', DRUPAL_ROOT.'/modules/'.$module.'/'.$module.'.routing.yml', $parameters, FILE_APPEND); } }
Fix removal of chat plugin
from spock.plugins.core import auth, event, net, ticker, timer from spock.plugins.helpers import chat, clientinfo, entities, interact, \ inventory, keepalive, movement, physics, respawn, start, world from spock.plugins.base import PluginBase # noqa core_plugins = [ ('auth', auth.AuthPlugin), ('event', event.EventPlugin), ('net', net.NetPlugin), ('ticker', ticker.TickerPlugin), ('timers', timer.TimerPlugin), ] helper_plugins = [ ('chat', chat.ChatPlugin), ('clientinfo', clientinfo.ClientInfoPlugin), ('entities', entities.EntitiesPlugin), ('interact', interact.InteractPlugin), ('inventory', inventory.InventoryPlugin), ('keepalive', keepalive.KeepalivePlugin), ('movement', movement.MovementPlugin), ('physics', physics.PhysicsPlugin), ('respawn', respawn.RespawnPlugin), ('start', start.StartPlugin), ('world', world.WorldPlugin), ] default_plugins = core_plugins + helper_plugins
from spock.plugins.core import auth, event, net, ticker, timer from spock.plugins.helpers import clientinfo, entities, interact, inventory,\ keepalive, movement, physics, respawn, start, world from spock.plugins.base import PluginBase # noqa core_plugins = [ ('auth', auth.AuthPlugin), ('event', event.EventPlugin), ('net', net.NetPlugin), ('ticker', ticker.TickerPlugin), ('timers', timer.TimerPlugin), ] helper_plugins = [ ('clientinfo', clientinfo.ClientInfoPlugin), ('entities', entities.EntitiesPlugin), ('interact', interact.InteractPlugin), ('inventory', inventory.InventoryPlugin), ('keepalive', keepalive.KeepalivePlugin), ('movement', movement.MovementPlugin), ('physics', physics.PhysicsPlugin), ('respawn', respawn.RespawnPlugin), ('start', start.StartPlugin), ('world', world.WorldPlugin), ] default_plugins = core_plugins + helper_plugins
Remove trailing slash for default configuration
<?php namespace EventStore\Bundle\ClientBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('event_store_client'); $rootNode ->children() ->scalarNode('base_url') ->cannotBeEmpty() ->defaultValue('http://127.0.0.1:2113') ->end() ->end(); return $treeBuilder; } }
<?php namespace EventStore\Bundle\ClientBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('event_store_client'); $rootNode ->children() ->scalarNode('base_url') ->cannotBeEmpty() ->defaultValue('http://127.0.0.1:2113/') ->end() ->end(); return $treeBuilder; } }
Order the tickets correctly in the API.
# -*- coding: utf-8 -*- from django.shortcuts import get_object_or_404 from rest_framework import viewsets from rest_framework.response import Response from apps.broadcasts.models import Broadcast, Host, Raid, Series from apps.games.models import Game from apps.subscribers.models import Ticket from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer, RaidSerializer, SeriesSerializer, TicketSerializer) class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): queryset = Broadcast.objects.all() serializer_class = BroadcastSerializer class HostViewSet(viewsets.ModelViewSet): queryset = Host.objects.all() serializer_class = HostSerializer class RaidViewSet(viewsets.ModelViewSet): queryset = Raid.objects.all() serializer_class = RaidSerializer class TicketViewSet(viewsets.ModelViewSet): queryset = Ticket.objects.order_by('-updated') serializer_class = TicketSerializer def retrieve(self, request, pk=None): queryset = Ticket.objects.all() ticket = get_object_or_404(queryset, name=pk) serializer = TicketSerializer(ticket) return Response(serializer.data)
# -*- coding: utf-8 -*- from django.shortcuts import get_object_or_404 from rest_framework import viewsets from rest_framework.response import Response from apps.broadcasts.models import Broadcast, Host, Raid, Series from apps.games.models import Game from apps.subscribers.models import Ticket from .serializers import (BroadcastSerializer, GameSerializer, HostSerializer, RaidSerializer, SeriesSerializer, TicketSerializer) class BroadcastViewSet(viewsets.ReadOnlyModelViewSet): queryset = Broadcast.objects.all() serializer_class = BroadcastSerializer class HostViewSet(viewsets.ModelViewSet): queryset = Host.objects.all() serializer_class = HostSerializer class RaidViewSet(viewsets.ModelViewSet): queryset = Raid.objects.all() serializer_class = RaidSerializer class TicketViewSet(viewsets.ModelViewSet): queryset = Ticket.objects.all() serializer_class = TicketSerializer def retrieve(self, request, pk=None): queryset = Ticket.objects.all() ticket = get_object_or_404(queryset, name=pk) serializer = TicketSerializer(ticket) return Response(serializer.data)
Fix Linux build by removing unused import
package taptun import ( "os" "syscall" "unsafe" ) type ifreq struct { name [syscall.IFNAMSIZ]byte // c string flags uint16 // c short _pad [24 - unsafe.Sizeof(uint16(0))]byte } func createInterface(flags uint16) (string, *os.File, error) { f, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0600) if err != nil { return "", nil, err } fd := f.Fd() ifr := ifreq{flags: flags} if err := ioctl(fd, syscall.TUNSETIFF, unsafe.Pointer(&ifr)); err != nil { return "", nil, err } return cstringToGoString(ifr.name[:]), f, nil } func destroyInterface(name string) error { return nil } func openTun() (string, *os.File, error) { return createInterface(syscall.IFF_TUN | syscall.IFF_NO_PI) } func openTap() (string, *os.File, error) { return createInterface(syscall.IFF_TAP | syscall.IFF_NO_PI) }
package taptun import ( "bytes" "os" "syscall" "unsafe" ) type ifreq struct { name [syscall.IFNAMSIZ]byte // c string flags uint16 // c short _pad [24 - unsafe.Sizeof(uint16(0))]byte } func createInterface(flags uint16) (string, *os.File, error) { f, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0600) if err != nil { return "", nil, err } fd := f.Fd() ifr := ifreq{flags: flags} if err := ioctl(fd, syscall.TUNSETIFF, unsafe.Pointer(&ifr)); err != nil { return "", nil, err } return cstringToGoString(ifr.name[:]), f, nil } func destroyInterface(name string) error { return nil } func openTun() (string, *os.File, error) { return createInterface(syscall.IFF_TUN | syscall.IFF_NO_PI) } func openTap() (string, *os.File, error) { return createInterface(syscall.IFF_TAP | syscall.IFF_NO_PI) }
Make `switch` command a bit more helpful
# -*- coding: utf-8 -*- # Gitless - a version control system built on top of Git. # Licensed under GNU GPL v2. """gl switch - Switch branches.""" from __future__ import unicode_literals from . import pprint def parser(subparsers, _): """Adds the switch parser to the given subparsers object.""" desc = 'switch branches' switch_parser = subparsers.add_parser( 'switch', help=desc, description=desc.capitalize()) switch_parser.add_argument('branch', help='switch to branch') switch_parser.add_argument( '-mo', '--move-over', help='move uncomitted changes made in the current branch to the ' 'destination branch', action='store_true') switch_parser.set_defaults(func=main) def main(args, repo): b = repo.lookup_branch(args.branch) if not b: pprint.err('Branch {0} doesn\'t exist'.format(args.branch)) pprint.err_exp('to list existing branches do gl branch') pprint.err_exp('to create a new branch do gl branch -c feature/foo') return False repo.switch_current_branch(b, move_over=args.move_over) pprint.ok('Switched to branch {0}'.format(args.branch)) return True
# -*- coding: utf-8 -*- # Gitless - a version control system built on top of Git. # Licensed under GNU GPL v2. """gl switch - Switch branches.""" from __future__ import unicode_literals from . import pprint def parser(subparsers, _): """Adds the switch parser to the given subparsers object.""" desc = 'switch branches' switch_parser = subparsers.add_parser( 'switch', help=desc, description=desc.capitalize()) switch_parser.add_argument('branch', help='switch to branch') switch_parser.add_argument( '-mo', '--move-over', help='move uncomitted changes made in the current branch to the ' 'destination branch', action='store_true') switch_parser.set_defaults(func=main) def main(args, repo): b = repo.lookup_branch(args.branch) if not b: pprint.err('Branch {0} doesn\'t exist'.format(args.branch)) pprint.err_exp('to list existing branches do gl branch') return False repo.switch_current_branch(b, move_over=args.move_over) pprint.ok('Switched to branch {0}'.format(args.branch)) return True
Fix not opening watchlist entries in browser
angular.module('proxtop').service('open', ['ipc', 'settings', '$state', function(ipc, settings, $state) { const self = this; ['Anime', 'Manga'].forEach(function(name) { const lower = name.toLowerCase(); self['open' + name] = function(id, ep, sub) { const actualSettings = settings.get(lower); // TODO refactor this, this looks hacky if(actualSettings && (actualSettings.open_with === 'internal' || (lower === 'anime' && actualSettings.open_with === 'external' && actualSettings.pass_raw_url))) { $state.go('watch', { id: id, ep: ep, sub: sub }); } else { ipc.send('open', lower, id, ep, sub); } }; }); this.openLink = function(link) { ipc.send('open-link', link); }; }]);
angular.module('proxtop').service('open', ['ipc', 'settings', '$state', function(ipc, settings, $state) { const self = this; ['Anime', 'Manga'].forEach(function(name) { const lower = name.toLowerCase(); self['open' + name] = function(id, ep, sub) { const actualSettings = settings.get(lower); // TODO refactor this, this looks hacky if(actualSettings && (actualSettings.open_with === 'internal' || (lower === 'anime' && actualSettings.pass_raw_url))) { $state.go('watch', { id: id, ep: ep, sub: sub }); } else { ipc.send('open', lower, id, ep, sub); } }; }); this.openLink = function(link) { ipc.send('open-link', link); }; }]);
Replace Preconditions.checkNonNull() from Guava with Java sdks Objects.requireNonNull()
package com.veyndan.redditclient.api.reddit.network.interceptor; import java.io.IOException; import java.util.Objects; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public final class UserAgentInterceptor implements Interceptor { private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private final String userAgentHeaderValue; public UserAgentInterceptor(final String userAgentHeaderValue) { this.userAgentHeaderValue = Objects.requireNonNull(userAgentHeaderValue); } @Override public Response intercept(final Chain chain) throws IOException { final Request originalRequest = chain.request(); final Request requestWithUserAgent = originalRequest.newBuilder() .header(USER_AGENT_HEADER_NAME, userAgentHeaderValue) .build(); return chain.proceed(requestWithUserAgent); } }
package com.veyndan.redditclient.api.reddit.network.interceptor; import com.google.common.base.Preconditions; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public final class UserAgentInterceptor implements Interceptor { private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private final String userAgentHeaderValue; public UserAgentInterceptor(final String userAgentHeaderValue) { this.userAgentHeaderValue = Preconditions.checkNotNull(userAgentHeaderValue); } @Override public Response intercept(final Chain chain) throws IOException { final Request originalRequest = chain.request(); final Request requestWithUserAgent = originalRequest.newBuilder() .header(USER_AGENT_HEADER_NAME, userAgentHeaderValue) .build(); return chain.proceed(requestWithUserAgent); } }
Comment devtool evals in Webpack (Source maps weren't working)
var path = require('path'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { // devtool: 'eval', // debug: true, entry: { main: path.resolve(__dirname, 'src/main.js'), style: path.resolve(__dirname, 'src/main.less') }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js', chunkFilename: '[id].js', sourceMapFilename: '[file].map' }, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel-loader' }, { test: /\.less$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader') } ] }, plugins: [ new ExtractTextPlugin('[name].css') ] };
var path = require('path'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { devtool: 'eval', debug: true, entry: { main: path.resolve(__dirname, 'src/main.js'), style: path.resolve(__dirname, 'src/main.less') }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js', chunkFilename: '[id].js', sourceMapFilename: '[file].map' }, module: { loaders: [ { test: /\.jsx?$/, loader: 'babel-loader' }, { test: /\.less$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader') } ] }, plugins: [ new ExtractTextPlugin('[name].css') ] };
Fix wrong pdb parser invocation
from peptide import PeptideBuilder import Bio.PDB def write_pdb(aa_sequence, fragment_angles, gap_length, filepath): """ Generate pdb file with results :param aa_sequence: Amino acid sequence :param fragment_angles: Backbone torsion angles :param gap_length: Length of the gap at the sequence start and end :param filepath: Path to the file to save the pdb """ phi, psi = zip(*fragment_angles) structure = PeptideBuilder.make_structure(aa_sequence, phi, psi) out = Bio.PDB.PDBIO() out.set_structure(structure) out.save(filepath) def rmsd(source, target): parser = Bio.PDB.PDBParser() source = parser.get_structure('source', source) target = parser.get_structure('target', target) superimposer = Bio.PDB.Superimposer() source_atoms = list(source.get_atoms()) target_atoms = list(target.get_atoms())[:len(source_atoms)] superimposer.set_atoms(source_atoms, target_atoms) return superimposer.rms
from peptide import PeptideBuilder import Bio.PDB def write_pdb(aa_sequence, fragment_angles, gap_length, filepath): """ Generate pdb file with results :param aa_sequence: Amino acid sequence :param fragment_angles: Backbone torsion angles :param gap_length: Length of the gap at the sequence start and end :param filepath: Path to the file to save the pdb """ phi, psi = zip(*fragment_angles) structure = PeptideBuilder.make_structure(aa_sequence, phi, psi) out = Bio.PDB.PDBIO() out.set_structure(structure) out.save(filepath) def rmsd(source, target): source = Bio.PDB.parser.get_structure('source', source) target = Bio.PDB.parser.get_structure('target', target) superimposer = Bio.PDB.Superimposer() source_atoms = list(source.get_atoms()) target_atoms = list(target.get_atoms())[:len(source_atoms)] superimposer.set_atoms(source_atoms, target_atoms) return superimposer.rms
calvinlib: Fix erroneous schema naming & others
# -*- coding: utf-8 -*- # Copyright (c) 2017 Ericsson AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from calvin.runtime.south.calvinlib import base_calvinlib_object import pystache class Pystache(base_calvinlib_object.BaseCalvinlibObject): """ Module for formatting strings using Mustache-style templates. """ render_schema = { "description": "Return template string rendered using given dictionary", "type": "object", "properties": { "template": {"type": "string"}, "dictionary": {"type": "dict"} } } def init(self): pass def render(self, template, dictionary): return pystache.render(template, **dictionary)
# -*- coding: utf-8 -*- # Copyright (c) 2017 Ericsson AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from calvin.runtime.south.calvinlib import base_calvinlib_object import pystache class Pystache(base_calvinlib_object.BaseCalvinlibObject): """ Functions for manipulating strings. """ init_schema = { "description": "setup mustache formated strings", "type": "object", "properties": {} } render = { "description": "convert dict structure into string", "type": "object", "properties": { "template": {"type": "string"}, "dictionary": {"type": "dict"} } } def init(self): pass def render(self, template, *context, **kwargs): return pystache.render(template, *context, **kwargs)
Fix JS string extraction for ngettext The definition for ngettext in extract-translatable-strings had incorrect argument positions, and as a result strings translated with ngettext were missed from the .po file.
const { GettextExtractor, JsExtractors } = require('gettext-extractor'); const extractor = new GettextExtractor(); extractor .createJsParser([ JsExtractors.callExpression('gettext', { arguments: { text: 0, context: 1, }, }), JsExtractors.callExpression('gettext_noop', { arguments: { text: 0, context: 1, }, }), JsExtractors.callExpression('ngettext', { arguments: { text: 0, textPlural: 1, context: 3, }, }), ]) .parseFilesGlob('./src/**/*.@(ts|js|tsx)'); extractor.savePotFile('../wagtail/admin/locale/en/LC_MESSAGES/djangojs.po'); extractor.printStats();
const { GettextExtractor, JsExtractors } = require('gettext-extractor'); const extractor = new GettextExtractor(); extractor .createJsParser([ JsExtractors.callExpression('gettext', { arguments: { text: 0, context: 1, }, }), JsExtractors.callExpression('gettext_noop', { arguments: { text: 0, context: 1, }, }), JsExtractors.callExpression('ngettext', { arguments: { text: 1, textPlural: 2, context: 3, }, }), ]) .parseFilesGlob('./src/**/*.@(ts|js|tsx)'); extractor.savePotFile('../wagtail/admin/locale/en/LC_MESSAGES/djangojs.po'); extractor.printStats();
Add language switcher to guestarea & memberarea
<?php declare(strict_types=1); use Spatie\Menu\Laravel\Link; use Cortex\Foundation\Models\Menu as MenuModel; if (config('cortex.foundation.route.locale_prefix')) { $langSwitcherHeader = Link::to('#', '<span class="fa fa-globe"></span> '.app('laravellocalization')->getCurrentLocaleNative().' <span class="caret"></span>')->addClass('dropdown-toggle')->setAttribute('data-toggle', 'dropdown'); $langSwitcherBody = function (MenuModel $menu) { $menu->addClass('dropdown-menu'); $menu->addParentClass('dropdown'); foreach (app('laravellocalization')->getSupportedLocales() as $key => $locale) { $menu->url(app('laravellocalization')->localizeURL(request()->fullUrl(), $key), $locale['name']); } }; Menu::adminareaTopbar()->submenu($langSwitcherHeader, $langSwitcherBody); Menu::memberareaTopbar()->submenu($langSwitcherHeader, $langSwitcherBody); Menu::guestareaTopbar()->submenu($langSwitcherHeader, $langSwitcherBody); }
<?php declare(strict_types=1); use Spatie\Menu\Laravel\Link; use Cortex\Foundation\Models\Menu as MenuModel; if (config('cortex.foundation.route.locale_prefix')) { $langSwitcherHeader = Link::to('#', '<span class="fa fa-globe"></span> '.app('laravellocalization')->getCurrentLocaleNative().' <span class="caret"></span>')->addClass('dropdown-toggle')->setAttribute('data-toggle', 'dropdown'); $langSwitcherBody = function (MenuModel $menu) { $menu->addClass('dropdown-menu'); $menu->addParentClass('dropdown'); foreach (app('laravellocalization')->getSupportedLocales() as $key => $locale) { $menu->url(app('laravellocalization')->localizeURL(request()->fullUrl(), $key), $locale['name']); } }; Menu::adminareaTopbar()->submenu($langSwitcherHeader, $langSwitcherBody); }
Fix exclusions for command queuer
package net.buycraft.plugin.execution.strategy; import lombok.EqualsAndHashCode; import lombok.Value; import net.buycraft.plugin.IBuycraftPlatform; import net.buycraft.plugin.data.QueuedCommand; import net.buycraft.plugin.data.QueuedPlayer; import java.util.concurrent.TimeUnit; @Value @EqualsAndHashCode(exclude = {"queueTime"}) public class ToRunQueuedCommand { private final QueuedPlayer player; private final QueuedCommand command; private final boolean requireOnline; private final long queueTime = System.currentTimeMillis(); public boolean canExecute(IBuycraftPlatform platform) { Integer requiredSlots = command.getConditions().get("slots"); if (requiredSlots != null || requireOnline) { if (!platform.isPlayerOnline(player)) { return false; } } if (requiredSlots != null) { int free = platform.getFreeSlots(player); if (free < requiredSlots) { return false; } } Integer delay = command.getConditions().get("delay"); if (delay != null && delay > 0 && System.currentTimeMillis() - queueTime < TimeUnit.SECONDS.toMillis(delay)) { return false; } return true; } }
package net.buycraft.plugin.execution.strategy; import lombok.Value; import net.buycraft.plugin.IBuycraftPlatform; import net.buycraft.plugin.data.QueuedCommand; import net.buycraft.plugin.data.QueuedPlayer; import java.util.concurrent.TimeUnit; @Value public class ToRunQueuedCommand { private final QueuedPlayer player; private final QueuedCommand command; private final boolean requireOnline; private final long queueTime = System.currentTimeMillis(); public boolean canExecute(IBuycraftPlatform platform) { Integer requiredSlots = command.getConditions().get("slots"); if (requiredSlots != null || requireOnline) { if (!platform.isPlayerOnline(player)) { return false; } } if (requiredSlots != null) { int free = platform.getFreeSlots(player); if (free < requiredSlots) { return false; } } Integer delay = command.getConditions().get("delay"); if (delay != null && delay > 0 && System.currentTimeMillis() - queueTime < TimeUnit.SECONDS.toMillis(delay)) { return false; } return true; } }
Use Georgia for more legibility
var Hexo = require('hexo'); var hexo = new Hexo(process.cwd(), {}); /** * russophile tag * * Syntax: * {% russophile [style] %} * text string * {% endrussophile %} * * Acceptable styles: * sb - serif bold * sp - serif plain * rsb - red serif bold * rsp - red serif plain **/ module.exports = function(args, content) { var style; if( args.length > 0 ) style = args[0]; else style = 'sp'; var css_style = 'font-family:Georgia,serif; '; var text_color; if( style.match(/r/)) text_color = "#b30000"; else text_color = "#0B0B0B"; css_style += 'color:' + text_color + '; '; if( style.match(/b/)) css_style += 'font-weight: bold; '; var text = '<span style="' + css_style + '">' + content + '</span>'; text = hexo.render.renderSync({text: text, engine: 'markdown'}); return text; }
var Hexo = require('hexo'); var hexo = new Hexo(process.cwd(), {}); /** * russophile tag * * Syntax: * {% russophile [style] %} * text string * {% endrussophile %} * * Acceptable styles: * sb - serif bold * sp - serif plain * rsb - red serif bold * rsp - red serif plain **/ module.exports = function(args, content) { var style; if( args.length > 0 ) style = args[0]; else style = 'sp'; var css_style = 'font-family:serif; '; var text_color; if( style.match(/r/)) text_color = "#b30000"; else text_color = "#0B0B0B"; css_style += 'color:' + text_color + '; '; if( style.match(/b/)) css_style += 'font-weight: bold; '; var text = '<span style="' + css_style + '">' + content + '</span>'; text = hexo.render.renderSync({text: text, engine: 'markdown'}); return text; }
Update download url to newer version.
#!/usr/bin/env python # setup.py """pyftpdlib installer. To install pyftpdlib just open a command shell and run: > python setup.py install """ from distutils.core import setup long_descr = """\ Python FTP server library, based on asyncore framework, provides an high-level portable interface to easily write asynchronous FTP servers with Python.""" setup( name='pyftpdlib', version="0.4.0", description='High-level asynchronous FTP server library', long_description=long_descr, license='MIT License', platforms='Platform Independent', author="Giampaolo Rodola'", author_email='g.rodola@gmail.com', url='http://code.google.com/p/pyftpdlib/', download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.4.0.tar.gz', packages=['pyftpdlib'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: File Transfer Protocol (FTP)', 'Topic :: Software Development :: Libraries :: Python Modules' ], )
#!/usr/bin/env python # setup.py """pyftpdlib installer. To install pyftpdlib just open a command shell and run: > python setup.py install """ from distutils.core import setup long_descr = """\ Python FTP server library, based on asyncore framework, provides an high-level portable interface to easily write asynchronous FTP servers with Python.""" setup( name='pyftpdlib', version="0.4.0", description='High-level asynchronous FTP server library', long_description=long_descr, license='MIT License', platforms='Platform Independent', author="Giampaolo Rodola'", author_email='g.rodola@gmail.com', url='http://code.google.com/p/pyftpdlib/', download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.3.0.tar.gz', packages=['pyftpdlib'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: File Transfer Protocol (FTP)', 'Topic :: Software Development :: Libraries :: Python Modules' ], )
Reorganize the SurveyModel using Prototype instead of closure.
var Survey = function() { this.surveys = []; } Survey.prototype = { fetch : function() { var url = Ti.App.Properties.getString('server_url') + '/api/mobile/surveys'; var that = this; var client = Ti.Network.createHTTPClient({ // function called when the response data is available onload : function(e) { Ti.API.info("Received text: " + this.responseText); that.surveys = JSON.parse(this.responseText); Ti.App.fireEvent('surveys.fetch.success'); }, // function called when an error occurs, including a timeout onerror : function(e) { Ti.API.debug(e.error); Ti.App.fireEvent('surveys.fetch.error'); }, timeout : 5000 // in milliseconds }); // Prepare the connection. client.open("GET", url); // Send the request. client.send(); }, list : function() { return this.surveys; } }; module.exports = Survey;
var Survey = function() { var surveys = []; return { fetch : function() { var url = Ti.App.Properties.getString('server_url') + '/api/mobile/surveys'; var client = Ti.Network.createHTTPClient({ // function called when the response data is available onload : function(e) { Ti.API.info("Received text: " + this.responseText); surveys = JSON.parse(this.responseText); Ti.App.fireEvent('surveys.fetch.success'); }, // function called when an error occurs, including a timeout onerror : function(e) { Ti.API.debug(e.error); Ti.App.fireEvent('surveys.fetch.error'); }, timeout : 5000 // in milliseconds }); // Prepare the connection. client.open("GET", url); // Send the request. client.send(); }, list : function() { return surveys; } }; } module.exports = Survey;
Fix graphql-php 0.11 breaking change
<?php namespace GraphQLGen\Generator\Interpreters\Main; use GraphQL\Language\AST\InterfaceTypeDefinitionNode; use GraphQLGen\Generator\InterpretedTypes\Main\InterfaceDeclarationInterpretedType; use GraphQLGen\Generator\InterpretedTypes\Nested\FieldInterpretedType; use GraphQLGen\Generator\Interpreters\Nested\FieldInterpreter; class InterfaceInterpreter extends MainTypeInterpreter { /** * @param InterfaceTypeDefinitionNode $astNode */ public function __construct($astNode) { $this->_astNode = $astNode; } /** * @return InterfaceDeclarationInterpretedType */ public function generateType() { $interpretedType = new InterfaceDeclarationInterpretedType(); $interpretedType->setName($this->interpretName()); $interpretedType->setDescription($this->interpretDescription()); $interpretedType->setFields($this->interpretFields()); return $interpretedType; } /** * @return FieldInterpretedType[] */ public function interpretFields() { $interpretedTypes = []; foreach($this->_astNode->fields as $fieldNode){ $fieldInterpreter = new FieldInterpreter($fieldNode); $interpretedTypes[] = $fieldInterpreter->generateType(); } return $interpretedTypes; } }
<?php namespace GraphQLGen\Generator\Interpreters\Main; use GraphQL\Language\AST\InterfaceTypeDefinitionNode; use GraphQLGen\Generator\InterpretedTypes\Main\InterfaceDeclarationInterpretedType; use GraphQLGen\Generator\InterpretedTypes\Nested\FieldInterpretedType; use GraphQLGen\Generator\Interpreters\Nested\FieldInterpreter; class InterfaceInterpreter extends MainTypeInterpreter { /** * @param InterfaceTypeDefinitionNode $astNode */ public function __construct($astNode) { $this->_astNode = $astNode; } /** * @return InterfaceDeclarationInterpretedType */ public function generateType() { $interpretedType = new InterfaceDeclarationInterpretedType(); $interpretedType->setName($this->interpretName()); $interpretedType->setDescription($this->interpretDescription()); $interpretedType->setFields($this->interpretFields()); return $interpretedType; } /** * @return FieldInterpretedType[] */ public function interpretFields() { return array_map(function ($fieldNode) { $fieldInterpreter = new FieldInterpreter($fieldNode); return $fieldInterpreter->generateType(); }, $this->_astNode->fields); } }
Update enabledFeatures to use a Set. This also fixes a bug where enabled features could be mutated via the global value as it was not dereferenced before.
/** * Feature flags. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const enabledFeatures = new Set( global?._googlesitekitBaseData?.enabledFeatures || [] ); /** * Returns true if a feature is enabled; false otherwise. * * @since 1.25.0 * * @param {string} feature The name of the feature to check. * @param {Set} [_enabledFeatures] Optional. The set of enabled features. Uses `enabledFeatures` set by the server in a global JS variable, by default. * @return {boolean} `true` if a feature is enabled; `false` otherwise. */ export const isFeatureEnabled = ( feature, _enabledFeatures = enabledFeatures ) => { return _enabledFeatures.has( feature ); };
/** * Feature flags. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export const enabledFeatures = global?._googlesitekitBaseData?.enabledFeatures || []; /** * Returns true if a feature is enabled; false otherwise. * * @since 1.25.0 * * @param {string} feature The name of the feature to check. * @param {?Array} _enabledFeatures Optional. The list of enabled features. Uses `enabledFeatures` set by the server in a global JS variable, by default. * @return {boolean} `true` if a feature is enabled; `false` otherwise. */ export const isFeatureEnabled = ( feature, _enabledFeatures = enabledFeatures ) => { return _enabledFeatures.includes( feature ); };
Change return type on empty arguments
VideoStream.utils.loadFileFromURL = function(file, dir = '.'){ if(!file){ return new Promise(function(resolve){resolve(null);}); } var path = file; if(file.startsWith('/') == false && file.startsWith(/http(s):\/\/|file:\/\//) == false){ path = dir.endsWith('/') ? dir + file : dir + '/' + file; } return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(this.readyState == 4){ if(this.status == 200){ resolve(this.responseText); } else{ reject(this.status, this); } } }; xhr.onerror = function(){ reject(this.status, this); }; xhr.open('GET', path, true); xhr.send(); }) .catch(function(status, xhr){ var errorText = 'Error while loading file! [Status: ' + status + ']'; console.log(errorText); console.log(xhr); throw new Error(errorText); }); }
VideoStream.utils.loadFileFromURL = function(file, dir = '.'){ if(!file){ return new Promise(function(resolve){resolve('');}); } var path = file; if(file.startsWith('/') == false && file.startsWith(/http(s):\/\/|file:\/\//) == false){ path = dir.endsWith('/') ? dir + file : dir + '/' + file; } return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(this.readyState == 4){ if(this.status == 200){ resolve(this.responseText); } else{ reject(this.status, this); } } }; xhr.onerror = function(){ reject(this.status, this); }; xhr.open('GET', path, true); xhr.send(); }) .catch(function(status, xhr){ var errorText = 'Error while loading file! [Status: ' + status + ']'; console.log(errorText); console.log(xhr); throw new Error(errorText); }); }
Add input field to control volume
import React from 'react' import {compose, withState} from 'recompose' import {clickable} from '../style.css' import {Audio, View, Text, TextInput} from '../components' let Player = compose( withState('volume', 'setVolume', 0.1) )(({volume, setVolume, time, URL}) => ( <View> <Audio volume={volume} src={`${URL}${time}.mp3`} autoPlay /> <TextInput style={{width: 30}} onTextChange={text => { let num = parseInt(text) if (!Number.isNaN(num)) { setVolume(num / 100) } else { setVolume(0) } }} value={Math.ceil(volume * 100)} />% <View> <View className={clickable} onClick={() => setVolume(Math.min(volume + 0.1, 1))}> HARDER { volume >= 1 && '(Nog harder heeft geen zin srry)'} </View> <View className={clickable} onClick={() => setVolume(Math.max(volume - 0.1, 0))}> ZACHTER { volume <= 0 && '(Hij is al op z\'n zachts)'} </View> </View> </View> )) export default Player
import React from 'react' import {compose, withState} from 'recompose' import {clickable} from '../style.css' import {Audio, View, Text} from '../components' let Player = compose( withState('volume', 'setVolume', 0.1) )(({volume, setVolume, time, URL}) => ( <View> <Audio volume={volume} src={`${URL}${time}.mp3`} autoPlay /> <View> {volume} <View className={clickable} onClick={() => setVolume(Math.min(volume + 0.1, 1))}> HARDER { volume === 1 && '(Nog harder heeft geen zin srry)'} </View> <View className={clickable} onClick={() => setVolume(Math.max(volume - 0.1, 0))}> ZACHTER { volume === 0 && '(Hij is al op z\'n zachts)'} </View> </View> </View> )) export default Player
Increment that pip package version to 1.3.1 I incremented the last value as I am suggesting that not requiring certain pip dependencies put the project into a bad state... Some may consider that a bug. Either way :)
from distutils.core import setup setup( name="simple_slack_bot", packages=["simple_slack_bot"], # this must be the same as the name above version="1.3.1", description="Simple Slack Bot makes writing your next Slack bot incredibly easy", long_description="Simple Slack Bot makes writing your next Slack bot incredibly easy. By factoring out common functionality all Slack Bots require, you can focus on writing your business logic by simply registering for Slack Events defined by the Slack API", author="Greg Hilston", author_email="Gregory.Hilston@gmail.com", url="https://github.com/GregHilston/Simple-Slack-Bot", # use the URL to the github repo download_url="https://github.com/GregHilston/Simple-Slack-Bot/tarball/v1.1.0", keywords=["slack", "bot", "chat", "simple"], # arbitrary keywords classifiers=[], install_requires=[ "slacker==0.9", "slacksocket>=0.7,!=0.8,<=0.9", "pyyaml", "websocket-client==0.48", # required to define as our dependency has a dependency which broke backwards compatibility ], )
from distutils.core import setup setup( name="simple_slack_bot", packages=["simple_slack_bot"], # this must be the same as the name above version="1.3.0", description="Simple Slack Bot makes writing your next Slack bot incredibly easy", long_description="Simple Slack Bot makes writing your next Slack bot incredibly easy. By factoring out common functionality all Slack Bots require, you can focus on writing your business logic by simply registering for Slack Events defined by the Slack API", author="Greg Hilston", author_email="Gregory.Hilston@gmail.com", url="https://github.com/GregHilston/Simple-Slack-Bot", # use the URL to the github repo download_url="https://github.com/GregHilston/Simple-Slack-Bot/tarball/v1.1.0", keywords=["slack", "bot", "chat", "simple"], # arbitrary keywords classifiers=[], install_requires=[ "slacker==0.9", "slacksocket>=0.7,!=0.8,<=0.9", "pyyaml", "websocket-client==0.48", # required to define as our dependency has a dependency which broke backwards compatibility ], )
Comment to say using logging.CRITICAL is faster
import time import logging from pythonjsonlogger import jsonlogger from flumine import FlumineBacktest, clients from strategies.lowestlayer import LowestLayer logger = logging.getLogger() custom_format = "%(asctime) %(levelname) %(message)" log_handler = logging.StreamHandler() formatter = jsonlogger.JsonFormatter(custom_format) formatter.converter = time.gmtime log_handler.setFormatter(formatter) logger.addHandler(log_handler) logger.setLevel(logging.INFO) # Set to logging.CRITICAL to speed up backtest client = clients.BacktestClient() framework = FlumineBacktest(client=client) markets = ["tests/resources/PRO-1.170258213"] strategy = LowestLayer( market_filter={"markets": markets}, max_order_exposure=1000, max_selection_exposure=105, context={"stake": 2}, ) framework.add_strategy(strategy) framework.run() for market in framework.markets: print("Profit: {0:.2f}".format(sum([o.simulated.profit for o in market.blotter]))) for order in market.blotter: print( order.selection_id, order.responses.date_time_placed, order.status, order.order_type.price, order.average_price_matched, order.size_matched, order.simulated.profit, )
import time import logging from pythonjsonlogger import jsonlogger from flumine import FlumineBacktest, clients from strategies.lowestlayer import LowestLayer logger = logging.getLogger() custom_format = "%(asctime) %(levelname) %(message)" log_handler = logging.StreamHandler() formatter = jsonlogger.JsonFormatter(custom_format) formatter.converter = time.gmtime log_handler.setFormatter(formatter) logger.addHandler(log_handler) logger.setLevel(logging.INFO) client = clients.BacktestClient() framework = FlumineBacktest(client=client) markets = ["tests/resources/PRO-1.170258213"] strategy = LowestLayer( market_filter={"markets": markets}, max_order_exposure=1000, max_selection_exposure=105, context={"stake": 2}, ) framework.add_strategy(strategy) framework.run() for market in framework.markets: print("Profit: {0:.2f}".format(sum([o.simulated.profit for o in market.blotter]))) for order in market.blotter: print( order.selection_id, order.responses.date_time_placed, order.status, order.order_type.price, order.average_price_matched, order.size_matched, order.simulated.profit, )
Address review comment: Better documentation.
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ This module defines the Eliot log events emitted by the API implementation. """ __all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field(u"method", lambda method: method, u"The HTTP method of the request.") REQUEST_PATH = Field( u"request_path", lambda path: path, u"The absolute path of the resource to which the request was issued.") JSON = Field.forTypes( u"json", [unicode, bytes, dict, list, None, bool, float], u"JSON, either request or response depending on context.") RESPONSE_CODE = Field.forTypes( u"code", [int], u"The response code for the request.") # It would be nice if RESPONSE_CODE was in REQUEST instead of # JSON_REQUEST; see FLOC-1586. REQUEST = ActionType( LOG_SYSTEM + u":request", [REQUEST_PATH, METHOD], [], u"A request was received on the public HTTP interface.") JSON_REQUEST = ActionType( LOG_SYSTEM + u":json_request", [JSON], [RESPONSE_CODE, JSON], u"A request containing JSON request and response bodies.")
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ This module defines the Eliot log events emitted by the API implementation. """ __all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field(u"method", lambda method: method, u"The HTTP method of the request.") REQUEST_PATH = Field( u"request_path", lambda path: path, u"The absolute path of the resource to which the request was issued.") JSON = Field.forTypes( u"json", [unicode, bytes, dict, list, None, bool, float], u"JSON, either request or response depending on context.") RESPONSE_CODE = Field.forTypes( u"code", [int], u"The response code for the request.") REQUEST = ActionType( LOG_SYSTEM + u":request", [REQUEST_PATH, METHOD], [], u"A request was received on the public HTTP interface.") JSON_REQUEST = ActionType( LOG_SYSTEM + u":json_request", [JSON], [RESPONSE_CODE, JSON], u"A request containing JSON request and response.")
Fix linting errors on server
'use strict'; const cookieParser = require('cookie-parser'); const csrf = require('csurf'); module.exports = function(server) { let secure = true; if (process.env.NODE_ENV === 'development') { secure = false; } server.use(cookieParser()); server.use(csrf({cookie: { key: 'XSRF-SECRET', secure, httpOnly: true, path: '/<%= applicationFolder %>' }})); server.use((err, req, res, next) => { // eslint-disable-line if (err.code !== 'EBADCSRFTOKEN') { return next(err); } // handle CSRF token errors here res.status(403); // eslint-disable-line no-magic-numbers res.send('invalid csrf token'); }); server.use((req, res, next) => { const token = req.csrfToken(); res.header('x-powered-by', ''); res.cookie('XSRF-TOKEN', token, { secure, path: '/<%= applicationFolder %>' }); next(); }); };
'use strict'; const cookieParser = require('cookie-parser'); const csrf = require('csurf'); module.exports = function(server) { let secure = true; if (process.env.NODE_ENV === 'development') { secure = false; } server.use(cookieParser()); server.use(csrf({cookie: { key: 'XSRF-SECRET', secure, httpOnly: true, path: '/<%= applicationFolder %>' }})); server.use((err, req, res, next) => { //eslint-disable-line if (err.code !== 'EBADCSRFTOKEN') { return next(err); } // handle CSRF token errors here res.status(403); //eslint-disable-line no-magic-numbers res.send('invalid csrf token'); }); server.use((req, res, next) => { const token = req.csrfToken(); res.header('x-powered-by', ''); res.cookie('XSRF-TOKEN', token, { secure, path: '/<%= applicationFolder %>' }); next(); }); };
Add example to code doc
import requests import json class MatrixClient: """ A minimal client for Mapzen Time-Distance Matrix Service Example: client = MatrixClient('your_api_key') locations = [{"lat":40.744014,"lon":-73.990508},{"lat":40.739735,"lon":-73.979713},{"lat":40.752522,"lon":-73.985015},{"lat":40.750117,"lon":-73.983704},{"lat":40.750552,"lon":-73.993519}] costing = 'pedestrian' print client.one_to_many(locations, costing) """ ONE_TO_MANY_URL = 'https://matrix.mapzen.com/one_to_many' def __init__(self, matrix_key): self._matrix_key = matrix_key """Get distances and times to a set of locations. See https://mapzen.com/documentation/matrix/api-reference/ Args: locations Array of {lat: y, lon: x} costing Costing model to use Returns: A dict with one_to_many, units and locations """ def one_to_many(self, locations, costing): request_params = { 'json': json.dumps({'locations': locations}), 'costing': costing, 'api_key': self._matrix_key } response = requests.get(self.ONE_TO_MANY_URL, params=request_params) return response.json()
import requests import json class MatrixClient: ONE_TO_MANY_URL = 'https://matrix.mapzen.com/one_to_many' def __init__(self, matrix_key): self._matrix_key = matrix_key """Get distances and times to a set of locations. See https://mapzen.com/documentation/matrix/api-reference/ Args: locations Array of {lat: y, lon: x} costing Costing model to use Returns: A dict with one_to_many, units and locations """ def one_to_many(self, locations, costing): request_params = { 'json': json.dumps({'locations': locations}), 'costing': costing, 'api_key': self._matrix_key } response = requests.get(self.ONE_TO_MANY_URL, params=request_params) return response.json()
Tests: Fix typo in test log.
module.exports.test = function(uiTestCtx) { describe('Module test: instances:stub', function() { const { config, helpers: { login, openApp, logout }, meta: { testVersion } } = uiTestCtx; const nightmare = new Nightmare(config.nightmare); this.timeout(Number(config.test_timeout)); describe('Login > Open module "Instances" > Logout', () => { before( done => { login(nightmare, config, done); // logs in with the default admin credentials }) after( done => { logout(nightmare, config, done); }) it('should open module "Instances" and find version tag ', done => { nightmare .use(openApp(nightmare, config, done, 'instances', testVersion)) .then(result => result ) }) }) }) }
module.exports.test = function(uiTestCtx) { describe('Module test: checkout:stub', function() { const { config, helpers: { login, openApp, logout }, meta: { testVersion } } = uiTestCtx; const nightmare = new Nightmare(config.nightmare); this.timeout(Number(config.test_timeout)); describe('Login > Open module "Instances" > Logout', () => { before( done => { login(nightmare, config, done); // logs in with the default admin credentials }) after( done => { logout(nightmare, config, done); }) it('should open module "Instances" and find version tag ', done => { nightmare .use(openApp(nightmare, config, done, 'instances', testVersion)) .then(result => result ) }) }) }) }
Test chmod of directory created by LocalStream
<?php namespace Gaufrette\Functional\FileStream; use Gaufrette\Filesystem; use Gaufrette\Adapter\Local as LocalAdapter; use Gaufrette\Functional\LocalDirectoryDeletor; class LocalTest extends FunctionalTestCase { protected $directory; public function setUp() { $this->directory = __DIR__.DIRECTORY_SEPARATOR.'filesystem'; @mkdir($this->directory.DIRECTORY_SEPARATOR.'subdir', 0777, true); $this->filesystem = new Filesystem(new LocalAdapter($this->directory, true, 0770)); $this->registerLocalFilesystemInStream(); } public function testDirectoryChmod() { $r = fopen('gaufrette://filestream/foo/bar', 'a+'); fclose($r); $perms = fileperms($this->directory . '/foo/'); $this->assertEquals('0770', substr(sprintf('%o', $perms), -4)); } public function tearDown() { LocalDirectoryDeletor::deleteDirectory($this->directory); } /** * @test */ public function shouldSupportsDirectory() { $this->assertTrue(file_exists('gaufrette://filestream/subdir')); $this->assertTrue(is_dir('gaufrette://filestream/subdir')); } }
<?php namespace Gaufrette\Functional\FileStream; use Gaufrette\Filesystem; use Gaufrette\Adapter\Local as LocalAdapter; use Gaufrette\Functional\LocalDirectoryDeletor; class LocalTest extends FunctionalTestCase { protected $directory; public function setUp() { $this->directory = __DIR__.DIRECTORY_SEPARATOR.'filesystem'; @mkdir($this->directory.DIRECTORY_SEPARATOR.'subdir', 0777, true); $this->filesystem = new Filesystem(new LocalAdapter($this->directory, true)); $this->registerLocalFilesystemInStream(); } public function tearDown() { LocalDirectoryDeletor::deleteDirectory($this->directory); } /** * @test */ public function shouldSupportsDirectory() { $this->assertTrue(file_exists('gaufrette://filestream/subdir')); $this->assertTrue(is_dir('gaufrette://filestream/subdir')); } }
Add moon phase tooltip detail Added moon phase detail to tooltip (you can see the numeric value of the moon phase now)
import {Component} from 'react'; class MoonPhaseIcon extends Component{ render() { // Set the default icon: var iconClass = "wi-moon-waning-gibbous-3"; if (this.props.phase < .09) { iconClass = "wi-moon-new"; } else if (this.props.phase < .18) { iconClass = "wi-moon-waxing-crescent-4"; } else if (this.props.phase < .26) { iconClass = "wi-moon-first-quarter"; } else if (this.props.phase < .37) { iconClass = "wi-moon-waxing-gibbous-3"; } else if (this.props.phase < .51) { iconClass = "wi-moon-full"; } else if (this.props.phase < .64) { iconClass = "wi-moon-waning-gibbous-3"; } else if (this.props.phase < .80) { iconClass = "wi-moon-third-quarter"; } // Make sure the additional 'wi' class is added: iconClass = "wi " + iconClass; return ( <i className={iconClass} rel="tooltip" title={this.props.phase}></i> ); } } export default MoonPhaseIcon;
import {Component} from 'react'; class MoonPhaseIcon extends Component{ render() { // Yahoo numeric codes are here: https://developer.yahoo.com/weather/documentation.html // Forecast.io icon codes are here: https://developer.forecast.io/docs/v2#forecast_call // Set the default icon: var iconClass = "wi-moon-waning-gibbous-3"; if (this.props.phase < .09) { iconClass = "wi-moon-new"; } else if (this.props.phase < .18) { iconClass = "wi-moon-waxing-crescent-4"; } else if (this.props.phase < .26) { iconClass = "wi-moon-first-quarter"; } else if (this.props.phase < .37) { iconClass = "wi-moon-waxing-gibbous-3"; } else if (this.props.phase < .51) { iconClass = "wi-moon-full"; } else if (this.props.phase < .64) { iconClass = "wi-moon-waning-gibbous-3"; } else if (this.props.phase < .80) { iconClass = "wi-moon-third-quarter"; } // Make sure the additional 'wi' class is added: iconClass = "wi " + iconClass; return ( <i className={iconClass}></i> ); } } export default MoonPhaseIcon;
Change mozlog use to ip from id
const assert = require("assert"); const csrf = require("csurf"); const mozlog = require("../logging").mozlog("csrf-middleware"); const { captureRavenException } = require("../ravenclient"); const { simpleResponse } = require("../responses"); const config = require("../config").getProperties(); const useSecureCsrfCookie = (config.expectProtocol && /^https$/.test(config.expectProtocol)); exports.csrfProtection = csrf({cookie: {httpOnly: true, secure: useSecureCsrfCookie}}); exports.csrf = function(req, res, next) { // The cookies library doesn't detect duplicates; check manually let rawCookies = req.get("cookie") || ""; let pairs = rawCookies.split(";"); let csrfTokens = pairs.filter(item => item.match(/_csrf=/)); if (csrfTokens.length > 1) { let exc = new Error("Duplicate CSRF cookies"); exc.headerValue = rawCookies; captureRavenException(exc); return simpleResponse(res, "Bad request", 400); } req.cookies._csrf = req.cookies.get("_csrf"); // csurf expects a property next(); }; exports.csrfErrorResponse = function(err, req, res) { assert(err.code === "EBADCSRFTOKEN", "Returning csrf response for non-csrf error code."); mozlog.info("bad-csrf", {ip: req.ip, url: req.url}); res.status(403); res.type("text"); res.send("Bad CSRF Token"); };
const assert = require("assert"); const csrf = require("csurf"); const mozlog = require("../logging").mozlog("csrf-middleware"); const { captureRavenException } = require("../ravenclient"); const { simpleResponse } = require("../responses"); const config = require("../config").getProperties(); const useSecureCsrfCookie = (config.expectProtocol && /^https$/.test(config.expectProtocol)); exports.csrfProtection = csrf({cookie: {httpOnly: true, secure: useSecureCsrfCookie}}); exports.csrf = function(req, res, next) { // The cookies library doesn't detect duplicates; check manually let rawCookies = req.get("cookie") || ""; let pairs = rawCookies.split(";"); let csrfTokens = pairs.filter(item => item.match(/_csrf=/)); if (csrfTokens.length > 1) { let exc = new Error("Duplicate CSRF cookies"); exc.headerValue = rawCookies; captureRavenException(exc); return simpleResponse(res, "Bad request", 400); } req.cookies._csrf = req.cookies.get("_csrf"); // csurf expects a property next(); }; exports.csrfErrorResponse = function(err, req, res) { assert(err.code === "EBADCSRFTOKEN", "Returning csrf response for non-csrf error code."); mozlog.info("bad-csrf", {id: req.ip, url: req.url}); res.status(403); res.type("text"); res.send("Bad CSRF Token"); };
Add outputBufferingActive property to clean up output buffer automatically
<?php namespace CLIFramework\Testing; use PHPUnit_Framework_TestCase; abstract class CommandTestCase extends PHPUnit_Framework_TestCase { public $app; public $outputBufferingActive = true; abstract public function setupApplication(); public function getApplication() { return $this->app; } public function setUp() { if ($this->outputBufferingActive) { ob_start(); } $this->app = $this->setupApplication(); } public function tearDown() { $this->app = NULL; if ($this->outputBufferingActive) { ob_end_clean(); } } public function runCommand($args) { if (is_string($args)) { $args = preg_split('/\s+/',$args); } return $this->app->run($args); } }
<?php namespace CLIFramework\Testing; use PHPUnit_Framework_TestCase; abstract class CommandTestCase extends PHPUnit_Framework_TestCase { public $app; abstract public function setupApplication(); public function getApplication() { return $this->app; } public function setUp() { $this->app = $this->setupApplication(); } public function tearDown() { $this->app = NULL; } public function runCommand($args) { if (is_string($args)) { $args = preg_split('/\s+/',$args); } return $this->app->run($args); } }
Change to firefox for tests
'use strict'; var http = require('http'), ecstatic = require('ecstatic'); var server = http.createServer(ecstatic({ root: __dirname + '/../dist' })); exports.config = { jasmineNodeOpts: { isVerbose: true, showColors: true, defaultTimeoutInterval: 30000 }, specs: [ 'e2e/**/*.js' ], capabilities: { 'browserName': 'firefox' }, beforeLaunch: function () { server.listen(9999); }, onComplete: function () { server.close(function () {}); }, baseUrl: 'http://localhost:9999/index_e2e.html' };
'use strict'; var http = require('http'), ecstatic = require('ecstatic'); var server = http.createServer(ecstatic({ root: __dirname + '/../dist' })); exports.config = { jasmineNodeOpts: { isVerbose: true, showColors: true, defaultTimeoutInterval: 30000 }, specs: [ 'e2e/**/*.js' ], capabilities: { 'browserName': 'chrome' }, beforeLaunch: function () { server.listen(9999); }, onComplete: function () { server.close(function () {}); }, baseUrl: 'http://localhost:9999/index_e2e.html' };
Extend params in correct order
var _ = require('lodash'), request = require('request'), savePage = require('./save').page; function getPageFromServer(params, pageResult) { request.get(params, function (error, response, body) { pageResult(error || (response.statusCode !== 200 || !body), arguments); }); } function getMain(params, callback) { var tmpParams = _.extend({}, params.request, params.main); getPageFromServer(tmpParams, function (err, reqRes) { // Save to cache var body = reqRes[2]; if (!err && params.save) savePage(tmpParams, params.save, body); callback(err, reqRes); }); } function getCache(params, callback) { if (params.cache) { var tmpParams = _.extend({}, params.request, params.cache); getPageFromServer(tmpParams, function (err, reqRes) { callback(err, reqRes); }); } else { callback(true); } } exports = { main: getMain, cache: getCache };
var _ = require('lodash'), request = require('request'), savePage = require('./save').page; function getPageFromServer(params, pageResult) { request.get(params, function (error, response, body) { pageResult(error || (response.statusCode !== 200 || !body), arguments); }); } function getMain(params, callback) { var tmpParams = _.extend({}, params.main, params.request); getPageFromServer(tmpParams, function (err, res) { // Save to cache var body = res[2]; if (!err && params.save) savePage(tmpParams, params.save, body); callback(err, res); }); } function getCache(params, callback) { if (params.cache) { var tmpParams = _.extend({}, params.cache, params.request); getPageFromServer(tmpParams, function (err, res) { callback(err, res); }); } else { callback(true); } } exports = { main: getMain, cache: getCache };
Change object name to more explicit name
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2014-2017, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / Admin / From / Processing */ namespace PH7; defined('PH7') or die('Restricted access'); use PH7\Framework\Layout\Tpl\Engine\PH7Tpl\PH7Tpl; use PH7\Framework\Mvc\Model\License as LicenseModel; class LicenseFormProcess extends Form { public function __construct($iLicenseId) { parent::__construct(); $oLicenseModel = new LicenseModel; $sKey = $this->httpRequest->post('copyright_key'); if (!$this->str->equals($sKey, $oLicenseModel->get($iLicenseId))) { $oLicenseModel->save($sKey, $iLicenseId); // Clean caches to remove the copyright notices $this->file->deleteDir(PH7_PATH_CACHE . PH7Tpl::COMPILE_DIR); $this->file->deleteDir(PH7_PATH_CACHE . PH7Tpl::CACHE_DIR); } unset($oLicenseModel); } }
<?php /** * @author Pierre-Henry Soria <ph7software@gmail.com> * @copyright (c) 2014-2017, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / Admin / From / Processing */ namespace PH7; defined('PH7') or die('Restricted access'); use PH7\Framework\Layout\Tpl\Engine\PH7Tpl\PH7Tpl; use PH7\Framework\Mvc\Model\License; class LicenseFormProcess extends Form { public function __construct($iLicenseId) { parent::__construct(); $oLicense = new License; $sKey = $this->httpRequest->post('copyright_key'); if (!$this->str->equals($sKey, $oLicense->get($iLicenseId))) { $oLicense->save($sKey, $iLicenseId); // Clean caches to remove the copyright notices $this->file->deleteDir(PH7_PATH_CACHE . PH7Tpl::COMPILE_DIR); $this->file->deleteDir(PH7_PATH_CACHE . PH7Tpl::CACHE_DIR); } unset($oLicense); } }
Add Salt specific exit code
# -*- coding: utf-8 -*- ''' Classification of Salt exit codes. These are intended to augment universal exit codes (found in Python's `os` module with the `EX_` prefix or in `sysexits.h`). ''' # Too many situations use "exit 1" - try not to use it when something # else is more appropriate. EX_GENERIC = 1 # Salt SSH "Thin" deployment failures EX_THIN_PYTHON_OLD = 10 EX_THIN_DEPLOY = 11 EX_THIN_CHECKSUM = 12 EX_MOD_DEPLOY = 13 # The os.EX_* exit codes are Unix only so in the interest of cross-platform # compatiblility define them explicitly here. # # These constants are documented here: # https://docs.python.org/2/library/os.html#os.EX_OK EX_OK = 0 EX_NOUSER = 67 EX_UNAVAILABLE = 69 EX_CANTCREAT = 73 EX_SOFTWARE = 70 EX_USAGE = 64 # The Salt specific exit codes are defined below: # SALT_BUILD_FAIL is used when salt fails to build something, like a container SALT_BUILD_FAIL = 101
# -*- coding: utf-8 -*- ''' Classification of Salt exit codes. These are intended to augment universal exit codes (found in Python's `os` module with the `EX_` prefix or in `sysexits.h`). ''' # Too many situations use "exit 1" - try not to use it when something # else is more appropriate. EX_GENERIC = 1 # Salt SSH "Thin" deployment failures EX_THIN_PYTHON_OLD = 10 EX_THIN_DEPLOY = 11 EX_THIN_CHECKSUM = 12 EX_MOD_DEPLOY = 13 # The os.EX_* exit codes are Unix only so in the interest of cross-platform # compatiblility define them explicitly here. # # These constants are documented here: # https://docs.python.org/2/library/os.html#os.EX_OK EX_OK = 0 EX_NOUSER = 67 EX_UNAVAILABLE = 69 EX_CANTCREAT = 73 EX_SOFTWARE = 70 EX_USAGE = 64
Set compilation adhesion on the command line.
<?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Repositories\RepositoryInterface; class CataclysmCache extends Command { /** * The console command name. * * @var string */ protected $name = 'cataclysm:rebuild'; /** * The console command description. * * @var string */ protected $description = 'Compile the database.'; protected $repo; /** * Create a new command instance. * * @return void */ public function __construct(Repositories\CompiledReader $repo) { $this->repo = $repo; parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { echo "rebuilding database cache...\n"; $this->repo->compile($this->argument('path'), $this->option('adhesion')); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( array('path', InputArgument::REQUIRED, 'Path to the game files') ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( array('adhesion', 'a', InputOption::VALUE_OPTIONAL, "Chunk adhesion, reduces the amount of files created", 100) ); } }
<?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Repositories\RepositoryInterface; class CataclysmCache extends Command { /** * The console command name. * * @var string */ protected $name = 'cataclysm:rebuild'; /** * The console command description. * * @var string */ protected $description = 'Compile the database.'; protected $repo; /** * Create a new command instance. * * @return void */ public function __construct(Repositories\CompiledReader $repo) { $this->repo = $repo; parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { echo "rebuilding database cache...\n"; $this->repo->compile($this->argument('path')); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( array('path', InputArgument::REQUIRED, 'Path to the game files') ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( ); } }
Fix socket location with Docker 1.11.1
'use strict'; var fs = require('fs'); var userHome = require('user-home'); var read = require('read-yaml'); var Docker = require('dockerode'); var fileExists = require('file-exists'); module.exports = (function () { var configFile = `${userHome}/.docker-indicator.yaml`; if (fileExists(configFile)) { var config = read.sync(configFile); return new Docker({ protocol: config.docker.protocol, host: config.docker.ip, port: config.docker.port, ca: fs.readFileSync(config.docker.ca), cert: fs.readFileSync(config.docker.cert), key: fs.readFileSync(config.docker.key), }); } return new Docker({socketPath: '/var/run/docker.sock'}); })();
'use strict'; var fs = require('fs'); var userHome = require('user-home'); var read = require('read-yaml'); var Docker = require('dockerode'); var fileExists = require('file-exists'); module.exports = (function () { var configFile = `${userHome}/.docker-indicator.yaml`; if (fileExists(configFile)) { var config = read.sync(configFile); return new Docker({ protocol: config.docker.protocol, host: config.docker.ip, port: config.docker.port, ca: fs.readFileSync(config.docker.ca), cert: fs.readFileSync(config.docker.cert), key: fs.readFileSync(config.docker.key), }); } return new Docker({socketPath: '/var/tmp/docker.sock'}); })();
Add headers to minified version.
/* --- description: Provides a fallback for the placeholder property on input elements for older browsers. license: - MIT-style license authors: - Matthias Schmidt (http://www.m-schmidt.eu) requires: core/1.2.5: '*' provides: - Form.Placeholder ... */ (function(){if(!this.Form){this.Form={}}var a=("placeholder" in document.createElement("input"));if(!("supportsPlaceholder" in this)&&this.supportsPlaceholder!==false&&a){return}this.Form.Placeholder=new Class({Implements:Options,options:{color:"#A9A9A9"},initialize:function(c,b){this.setOptions(b);this.element=$(c);this.placeholder=this.element.get("placeholder");this.original_color=this.element.getStyle("color");if(this.element.get("value")==""){this.element.setStyle("color",this.options.color);this.element.set("value",this.placeholder)}this.element.addEvents({focus:function(){if(this.element.get("value")==this.placeholder){this.element.set("value","");this.element.setStyle("color",this.original_color)}}.bind(this),blur:function(){if(this.element.get("value")==""){this.element.setStyle("color",this.options.color);this.element.set("value",this.placeholder)}}.bind(this)})}})})();
(function(){if(!this.Form){this.Form={}}var a=("placeholder" in document.createElement("input"));if(!("supportsPlaceholder" in this)&&this.supportsPlaceholder!==false&&a){return}this.Form.Placeholder=new Class({Implements:Options,options:{color:"#A9A9A9"},initialize:function(c,b){this.setOptions(b);this.element=$(c);this.placeholder=this.element.get("placeholder");this.original_color=this.element.getStyle("color");if(this.element.get("value")==""){this.element.setStyle("color",this.options.color);this.element.set("value",this.placeholder)}this.element.addEvents({focus:function(){if(this.element.get("value")==this.placeholder){this.element.set("value","");this.element.setStyle("color",this.original_color)}}.bind(this),blur:function(){if(this.element.get("value")==""){this.element.setStyle("color",this.options.color);this.element.set("value",this.placeholder)}}.bind(this)})}})})();
Create test for plot_zipcode to compare generated graphs.
""" Name: Paul Briant Date: 12/11/16 Class: Introduction to Python Assignment: Final Project Description: Tests for Final Project """ import clean_data as cd import matplotlib.pyplot as plt import pandas import pytest def get_data(): """ Retrieve data from csv file to test. """ data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv") return data def test_clean(): """ """ def test_rename_columns(): """ Test whether rename_columns successfully renames each column. """ data = get_data() data = data.drop(["Date Value"], axis=1) column_names = list(data.columns.values) column_list = cd.rename_columns(column_names) assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"] def test_find_low_water_use(): """ """ @pytest.mark.mpl_image_compare def test_plot_zipcode(): """ Test zipcode based wateruse graphs. """ data = get_data() cleaned = cd.clean(data) wateruse = cd.plot_zipcode(cleaned, "90012") return wateruse
""" Name: Paul Briant Date: 12/11/16 Class: Introduction to Python Assignment: Final Project Description: Tests for Final Project """ import clean_data as cd import pandas def get_data(): """ Retrieve data from csv file to test. """ data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv") return data def test_clean(): """ """ def test_rename_columns(): """ Test whether rename_columns successfully renames each column. """ data = get_data() data = data.drop(["Date Value"], axis=1) column_names = list(data.columns.values) column_list = cd.rename_columns(column_names) assert column_list[0:5] == ["Date", "90001", "90002", "90003", "90004"] def test_find_low_water_use(): """ """ def test_plot_zipcode(): """ """
Change wording in utils test
const { expect } = require('chai'); const { generateTitle } = require('../lib/utils'); describe('utils', function() { describe('.generateTitle()', function() { it('generates valid title', function () { const result = generateTitle('Base', 'First', 'Second'); expect(result).to.equal('Base | First | Second'); }); it('generates valid title when single part used', function () { const result = generateTitle('Base'); expect(result).to.equal('Base'); }); it('returns empty string without args', function () { const result = generateTitle(); expect(result).to.eq(''); }); it('combines titles correctly', function () { const result = generateTitle('Title', 'Generated | Title'); expect(result).to.eq('Title | Generated | Title'); }); }); });
const { expect } = require('chai'); const { generateTitle } = require('../lib/utils'); describe('utils', function() { describe('.generateTitle()', function() { it('should generate a valid title', function () { const result = generateTitle('Base', 'First', 'Second'); expect(result).to.equal('Base | First | Second'); }); it('should generate a valid title when some arguments missing', function () { const result = generateTitle('Base'); expect(result).to.equal('Base'); }); it('should return an empty string when all arguments missing', function () { const result = generateTitle(); expect(result).to.eq(''); }); it('should combine titles correctly', function () { const result = generateTitle('Title', 'Generated | Title'); expect(result).to.eq('Title | Generated | Title'); }); }); });
Call Filter constructor in UglifyJSFilter This allows passing in options like targetExtension when using this filter in a Brocfile.
var Filter = require('broccoli-filter') var UglifyJS = require('uglify-js') module.exports = UglifyJSFilter UglifyJSFilter.prototype = Object.create(Filter.prototype) UglifyJSFilter.prototype.constructor = UglifyJSFilter function UglifyJSFilter (inputTree, options) { if (!(this instanceof UglifyJSFilter)) return new UglifyJSFilter(inputTree, options) Filter.call(this, inputTree, options) this.options = options || {} } UglifyJSFilter.prototype.extensions = ['js'] UglifyJSFilter.prototype.targetExtension = 'js' UglifyJSFilter.prototype.processString = function (string) { var result = UglifyJS.minify(string, { fromString: true, mangle: this.options.mangle, compress: this.options.compress, output: this.options.output }) return result.code }
var Filter = require('broccoli-filter') var UglifyJS = require('uglify-js') module.exports = UglifyJSFilter UglifyJSFilter.prototype = Object.create(Filter.prototype) UglifyJSFilter.prototype.constructor = UglifyJSFilter function UglifyJSFilter (inputTree, options) { if (!(this instanceof UglifyJSFilter)) return new UglifyJSFilter(inputTree, options) this.inputTree = inputTree this.options = options || {} } UglifyJSFilter.prototype.extensions = ['js'] UglifyJSFilter.prototype.targetExtension = 'js' UglifyJSFilter.prototype.processString = function (string) { var result = UglifyJS.minify(string, { fromString: true, mangle: this.options.mangle, compress: this.options.compress, output: this.options.output }) return result.code }
Set svn:eol-style on new files
/****************************************************************************** * This program and the accompanying materials are made available under * the terms of the Common Public License v1.0 which accompanies this * distribution, and is available at the following URL: * http://www.eclipse.org/legal/cpl-v10.html * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * * All Rights are Reserved by the various authors. *******************************************************************************/ package org.tigris.subversion.subclipse.core.client; import org.eclipse.core.runtime.IProgressMonitor; /** * ISVNNotifyListener implementation which intercepts the logMessage() method * and used it to display the operation progress within the supplied progress monitor. * * @author Martin Letenay (letenay at tigris.org) */ public class OperationProgressNotifyListener extends ISVNNotifyAdapter { private IProgressMonitor monitor = null; public OperationProgressNotifyListener(final IProgressMonitor monitor) { super(); this.monitor = monitor; } /** * Display the log the message in the progress monitor and increase the progress by 1 */ public void logMessage(String message) { if (monitor != null) { monitor.worked(1); monitor.subTask(message); } } /** * The operation was completed, clear the progress' subTask. */ public void logCompleted(String message) { if (monitor != null) { monitor.subTask(" "); } } }
/****************************************************************************** * This program and the accompanying materials are made available under * the terms of the Common Public License v1.0 which accompanies this * distribution, and is available at the following URL: * http://www.eclipse.org/legal/cpl-v10.html * Copyright(c) 2003-2005 by the authors indicated in the @author tags. * * All Rights are Reserved by the various authors. *******************************************************************************/ package org.tigris.subversion.subclipse.core.client; import org.eclipse.core.runtime.IProgressMonitor; /** * ISVNNotifyListener implementation which intercepts the logMessage() method * and used it to display the operation progress within the supplied progress monitor. * * @author Martin Letenay (letenay at tigris.org) */ public class OperationProgressNotifyListener extends ISVNNotifyAdapter { private IProgressMonitor monitor = null; public OperationProgressNotifyListener(final IProgressMonitor monitor) { super(); this.monitor = monitor; } /** * Display the log the message in the progress monitor and increase the progress by 1 */ public void logMessage(String message) { if (monitor != null) { monitor.worked(1); monitor.subTask(message); } } /** * The operation was completed, clear the progress' subTask. */ public void logCompleted(String message) { if (monitor != null) { monitor.subTask(" "); } } }
Change URL pattern for contacts
from django.conf.urls import url from django.views.generic import TemplateView from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'), # url(r'^contact/$', views.contact, name='contact'), url(r'^projects/$', views.projects, name='projects'), url(r'^tribute/$', views.tribute, name='tribute'), url(r'^weather/$', views.weather, name='weather'), url(r'^randomquote/$', views.randomquote, name='randomquote'), url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'), url(r'^twitch/$', views.twitch, name='twitch'), url(r'^tictactoe/$', views.tictactoe, name='tictactoe'), # url(r'^react/', views.react, name='react'), url(r'^react/simon', views.react, name='simon'), url(r'^react/pomodoro', views.react, name='clock'), url(r'^react/calculator', views.react, name='calc'), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', views.contact, name='contact'), url(r'^projects/$', views.projects, name='projects'), url(r'^tribute/$', views.tribute, name='tribute'), url(r'^weather/$', views.weather, name='weather'), url(r'^randomquote/$', views.randomquote, name='randomquote'), url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'), url(r'^twitch/$', views.twitch, name='twitch'), url(r'^tictactoe/$', views.tictactoe, name='tictactoe'), # url(r'^react/', views.react, name='react'), url(r'^react/simon', views.react, name='simon'), url(r'^react/pomodoro', views.react, name='clock'), url(r'^react/calculator', views.react, name='calc'), ]
Use original value in toString()
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\Constraint\Constraint; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ final class MethodNameConstraint extends Constraint { /** * @var string */ private $methodName; public function __construct(string $methodName) { $this->methodName = $methodName; } public function toString(): string { return \sprintf( 'is "%s"', $this->methodName ); } protected function matches($other): bool { if (!\is_string($other)) { return false; } return \strtolower($this->methodName) === \strtolower($other); } }
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\Constraint\Constraint; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ final class MethodNameConstraint extends Constraint { /** * @var string */ private $methodName; public function __construct(string $methodName) { $this->methodName = \strtolower($methodName); } public function toString(): string { return \sprintf( 'is "%s"', $this->methodName ); } protected function matches($other): bool { if (!\is_string($other)) { return false; } return $this->methodName === \strtolower($other); } }
Fix WebUI crash when a toot with a playing video gets deleted Signed-off-by: Claire <82b964c50e9d1d222e48cf5046e6484a966a7b07@sitedethib.com>
// @ts-check export const PICTURE_IN_PICTURE_DEPLOY = 'PICTURE_IN_PICTURE_DEPLOY'; export const PICTURE_IN_PICTURE_REMOVE = 'PICTURE_IN_PICTURE_REMOVE'; /** * @typedef MediaProps * @property {string} src * @property {boolean} muted * @property {number} volume * @property {number} currentTime * @property {string} poster * @property {string} backgroundColor * @property {string} foregroundColor * @property {string} accentColor */ /** * @param {string} statusId * @param {string} accountId * @param {string} playerType * @param {MediaProps} props * @return {object} */ export const deployPictureInPicture = (statusId, accountId, playerType, props) => { return (dispatch, getState) => { // Do not open a player for a toot that does not exist if (getState().hasIn(['statuses', statusId])) { dispatch({ type: PICTURE_IN_PICTURE_DEPLOY, statusId, accountId, playerType, props, }); } }; }; /* * @return {object} */ export const removePictureInPicture = () => ({ type: PICTURE_IN_PICTURE_REMOVE, });
// @ts-check export const PICTURE_IN_PICTURE_DEPLOY = 'PICTURE_IN_PICTURE_DEPLOY'; export const PICTURE_IN_PICTURE_REMOVE = 'PICTURE_IN_PICTURE_REMOVE'; /** * @typedef MediaProps * @property {string} src * @property {boolean} muted * @property {number} volume * @property {number} currentTime * @property {string} poster * @property {string} backgroundColor * @property {string} foregroundColor * @property {string} accentColor */ /** * @param {string} statusId * @param {string} accountId * @param {string} playerType * @param {MediaProps} props * @return {object} */ export const deployPictureInPicture = (statusId, accountId, playerType, props) => ({ type: PICTURE_IN_PICTURE_DEPLOY, statusId, accountId, playerType, props, }); /* * @return {object} */ export const removePictureInPicture = () => ({ type: PICTURE_IN_PICTURE_REMOVE, });
Extend test for empty weights
package org.lodder.subtools.multisubdownloader.lib.control.subtitles.sorting.replacers; import java.util.HashMap; import org.junit.Before; import org.junit.Test; import org.lodder.subtools.sublibrary.model.Release; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class GroupReplacerTest { protected GroupReplacer replacer; @Before public void setUp() throws Exception { replacer = new GroupReplacer(); } @Test public void test_it_replaces_the_keyword_group_to_a_releasename() throws Exception { Release release = mock(Release.class); when(release.getReleasegroup()).thenReturn("Acme"); HashMap<String, Integer> definedWeights = new HashMap<>(); definedWeights.put("%GROUP%",5); replacer.replace(release, definedWeights); /* check if the weight there is only one weight */ assertEquals(1, definedWeights.size()); /* check if the weight is acme */ assertTrue(definedWeights.containsKey("acme")); } @Test public void testEmptyWeights() throws Exception { Release release = mock(Release.class); when(release.getReleasegroup()).thenReturn("Acme"); HashMap<String, Integer> definedWeights = new HashMap<>(); replacer.replace(release, definedWeights); /* check if the weight there is only one weight */ assertEquals(0, definedWeights.size()); /* check if the weight is acme */ assertFalse(definedWeights.containsKey("acme")); } }
package org.lodder.subtools.multisubdownloader.lib.control.subtitles.sorting.replacers; import java.util.HashMap; import org.junit.Before; import org.junit.Test; import org.lodder.subtools.sublibrary.model.Release; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class GroupReplacerTest { protected GroupReplacer replacer; @Before public void setUp() throws Exception { replacer = new GroupReplacer(); } @Test public void test_it_replaces_the_keyword_group_to_a_releasename() throws Exception { Release release = mock(Release.class); when(release.getReleasegroup()).thenReturn("Acme"); HashMap<String, Integer> definedWeights = new HashMap<>(); definedWeights.put("%GROUP%",5); replacer.replace(release, definedWeights); /* check if the weight there is only one weight */ assertEquals(1, definedWeights.size()); /* check if the weight is acme */ assertTrue(definedWeights.containsKey("acme")); } }
Allow custom domain in custom config example
<?php require __DIR__ . "/_bootstrap.php"; use Amp\Dns; use Amp\Loop; use Amp\Promise; $customConfigLoader = new class implements Dns\ConfigLoader { public function loadConfig(): Promise { return Amp\call(function () { $hosts = yield (new Dns\HostLoader)->loadHosts(); return new Dns\Config([ "8.8.8.8:53", "[2001:4860:4860::8888]:53", ], $hosts, $timeout = 5000, $attempts = 3); }); } }; Dns\resolver(new Dns\Rfc1035StubResolver(null, $customConfigLoader)); Loop::run(function () use ($argv) { $hostname = $argv[1] ?? "amphp.org"; try { pretty_print_records($hostname, yield Dns\resolve($hostname)); } catch (Dns\DnsException $e) { pretty_print_error($hostname, $e); } });
<?php require __DIR__ . "/_bootstrap.php"; use Amp\Dns; use Amp\Loop; use Amp\Promise; $customConfigLoader = new class implements Dns\ConfigLoader { public function loadConfig(): Promise { return Amp\call(function () { $hosts = yield (new Dns\HostLoader)->loadHosts(); return new Dns\Config([ "8.8.8.8:53", "[2001:4860:4860::8888]:53", ], $hosts, $timeout = 5000, $attempts = 3); }); } }; Dns\resolver(new Dns\Rfc1035StubResolver(null, $customConfigLoader)); Loop::run(function () { $hostname = "amphp.org"; try { pretty_print_records($hostname, yield Dns\resolve($hostname)); } catch (Dns\DnsException $e) { pretty_print_error($hostname, $e); } });
Add doc comment for top-down Merge sort.
package com.varunvats.practice.sorting; public class MergeTopDown extends MergeBase { /** * Sorts an array in-place using the top-down merge-sort algorithm. * * @param a The array to be sorted. */ public static <T extends Comparable<T>> void sort(T[] a) { final int N = a.length; aux = new Comparable[N]; sort(a, 0, N - 1); } private static <T extends Comparable<T>> void sort(T[] a, int low, int high) { if (low >= high) return; final int mid = (low + high) / 2; sort(a, low, mid); sort(a, mid + 1, high); if (!less(a[mid], a[mid + 1])) merge(a, low, mid, high); } }
package com.varunvats.practice.sorting; public class MergeTopDown extends MergeBase { public static <T extends Comparable<T>> void sort(T[] a) { final int N = a.length; aux = new Comparable[N]; sort(a, 0, N - 1); } private static <T extends Comparable<T>> void sort(T[] a, int low, int high) { if (low >= high) return; final int mid = (low + high) / 2; sort(a, low, mid); sort(a, mid + 1, high); if (!less(a[mid], a[mid + 1])) merge(a, low, mid, high); } }
:bug: Fix `port of undefined` error
import http from 'http'; import express from 'express'; import bodyParser from 'body-parser'; import cors from 'cors'; import { makeExecutableSchema } from 'graphql-tools'; import { graphqlExpress } from 'apollo-server-express'; import graphqlPlayground from 'graphql-playground-middleware-express'; import checkEnv from 'check-env'; import { graphqlSchema, graphqlResolvers } from './graphql'; import config from './constants/config'; checkEnv(['encryption_key']); const PORT = process.env.PORT || config.server.port; const app = express(); app.server = http.createServer(app); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cors()); const executableSchema = makeExecutableSchema({ typeDefs: [graphqlSchema], resolvers: graphqlResolvers, }); app.use( '/graphql', bodyParser.json(), graphqlExpress({ schema: executableSchema, formatError: error => ({ message: 'Internal Server Error', path: error.path, }), tracing: true, }), ); app.get('/playground', graphqlPlayground({ endpoint: '/graphql' })); app.get('/', (req, res) => res.redirect('/playground')); app.server.listen(PORT); // eslint-disable-next-line no-console console.log(`🚀 Server listening on port ${PORT}...`);
import http from 'http'; import express from 'express'; import bodyParser from 'body-parser'; import cors from 'cors'; import { makeExecutableSchema } from 'graphql-tools'; import { graphqlExpress } from 'apollo-server-express'; import graphqlPlayground from 'graphql-playground-middleware-express'; import checkEnv from 'check-env'; import { graphqlSchema, graphqlResolvers } from './graphql'; import config from './constants/config'; checkEnv(['encryption_key']); const app = express(); app.server = http.createServer(app); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cors()); const executableSchema = makeExecutableSchema({ typeDefs: [graphqlSchema], resolvers: graphqlResolvers, }); app.use( '/graphql', bodyParser.json(), graphqlExpress({ schema: executableSchema, formatError: error => ({ message: 'Internal Server Error', path: error.path, }), tracing: true, }), ); app.get('/playground', graphqlPlayground({ endpoint: '/graphql' })); app.get('/', (req, res) => res.redirect('/playground')); app.server.listen(process.env.PORT || config.server.port); // eslint-disable-next-line no-console console.log(`🚀 Server listening on port ${app.server.address().port}...`);
Check that .env file was generate as part of install
<?php namespace Tests\Unit; use \Dotenv; /** * Dotenv Test * * @author Leonid Mamchenkov <l.mamchenkov@qobo.biz> */ class DotenvTest extends \PHPUnit_Framework_TestCase { /** * Provide .env file locations */ public function dotEnvFilesProvider() { return array( '.env.example' => array(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR, '.env.example'), '.env' => array(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR, '.env'), ); } /** * Check that the file exists * * @dataProvider dotEnvFilesProvider */ public function testDotenvExampleFileExists($folder, $file) { $this->assertTrue(file_exists($folder . $file), $file . " file does not exist in " . $folder); } /** * Check that we can parse the file * * @dataProvider dotEnvFilesProvider */ public function testDotenvExampleFileIsParseable($folder, $file) { try { Dotenv::load($folder, $file); } catch (\Exception $e) { $this->fail("Failed to parse file " . $file . " in " . $folder . " : " . $e->getMessage()); } } }
<?php namespace Tests\Unit; use \Dotenv; /** * Dotenv Test * * @author Leonid Mamchenkov <l.mamchenkov@qobo.biz> */ class DotenvTest extends \PHPUnit_Framework_TestCase { protected $folder; protected $file; protected function setUp() { $this->folder = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR; $this->file = '.env.example'; } /** * Check that the file exists */ public function testDotenvExampleFileExists() { $this->assertTrue(file_exists($this->folder . $this->file), $this->file . " file does not exist in " . $this->folder); } /** * Check that we can parse the file */ public function testDotenvExampleFileIsParseable() { try { Dotenv::load($this->folder, $this->file); } catch (\Exception $e) { $this->fail("Failed to parse file " . $this->file . " in " . $this->folder . " : " . $e->getMessage()); } } }
Stop propagation for clicks (since a click on model view can toggle more information.
var app = require('ridge'); module.exports = require('ridge/view').extend({ events: { 'click button,select,input': function(e) { e.stopPropagation(); }, 'click button': function(e) { e.preventDefault(); }, 'click button[data-command="publish"]': 'publish', 'click button[data-command="unpublish"]': 'unpublish', 'click button[data-command="delete"]': 'delete' }, delete: function(e) { if(confirm('Are you sure you want to delete the ' + this.model.name + '?')) { this.model.destroy(); this.remove(); } }, unpublish: function(e) { this.model.save({ datePublished: null }, { patch: true, wait: true }); }, publish: function(e) { this.model.save({ datePublished: new Date() }, { patch: true, wait: true }); }, initialize: function(options) { this.listenTo(this.model, 'sync', this.render); this.listenTo(this.model, 'destroy', this.remove); this.listenTo(this.model, 'change:datePublished', function(model, value) { this.$el.toggleClass('published', !!value).toggleClass('unpublished', !value); }); } });
var app = require('ridge'); module.exports = require('ridge/view').extend({ events: { 'click button': function(e) { e.preventDefault(); e.stopPropagation(); }, 'click button[data-command="publish"]': 'publish', 'click button[data-command="unpublish"]': 'unpublish', 'click button[data-command="delete"]': 'delete' }, delete: function(e) { if(confirm('Are you sure you want to delete the ' + this.model.name + '?')) { this.model.destroy(); this.remove(); } }, unpublish: function(e) { this.model.save({ datePublished: null }, { patch: true, wait: true }); }, publish: function(e) { this.model.save({ datePublished: new Date() }, { patch: true, wait: true }); }, initialize: function(options) { this.listenTo(this.model, 'sync', this.render); this.listenTo(this.model, 'destroy', this.remove); this.listenTo(this.model, 'change:datePublished', function(model, value) { this.$el.toggleClass('published', !!value).toggleClass('unpublished', !value); }); } });
Clone Merit data as late as possible It's not necessary to clone the entire (original) data - especially since the MeritTransformator isn't reused - but instead we can shallow-clone each series, and replace the values with those sliced up or downsampled by the Transformator.
/*globals Downsampler,LoadSlicer*/ var MeritTransformator = (function () { 'use strict'; function transformSerieValues(serie) { if (this.scope.dateSelect.val() > 0) { return LoadSlicer.slice(serie, this.scope.dateSelect.val()); } else { return Downsampler.downsample(serie); } } MeritTransformator.prototype = { transform: function () { return this.data.map(function(serie) { return $.extend( {}, serie, { values: transformSerieValues.call(this, serie) } ); }.bind(this)); } }; function MeritTransformator (scope, data) { this.scope = scope; this.data = data; } return MeritTransformator; }());
/*globals Downsampler,LoadSlicer*/ var MeritTransformator = (function () { 'use strict'; function transformSerieValues(serie) { if (this.scope.dateSelect.val() > 0) { return LoadSlicer.slice(serie, this.scope.dateSelect.val()); } else { return Downsampler.downsample(serie); } } MeritTransformator.prototype = { transform: function () { this.data.forEach(function(serie) { serie.values = transformSerieValues.call(this, serie); }.bind(this)); return this.data; } }; function MeritTransformator (scope, data) { this.scope = scope; this.data = $.extend(true, [], data); } return MeritTransformator; }());
Fix the codes in the tests
import unittest import sys try: from StringIO import StringIO except ImportError: from io import StringIO # NOQA from flake8.mccabe import get_code_complexity _GLOBAL = """\ for i in range(10): pass def a(): def b(): def c(): pass c() b() """ class McCabeTest(unittest.TestCase): def setUp(self): self.old = sys.stdout self.out = sys.stdout = StringIO() def tearDown(self): sys.sdtout = self.old def test_sample(self): self.assertEqual(get_code_complexity(_GLOBAL, 1), 2) self.out.seek(0) res = self.out.read().strip().split('\n') wanted = ["stdin:5:1: C901 'a' is too complex (4)", "stdin:2:1: C901 'Loop 2' is too complex (2)"] self.assertEqual(res, wanted)
import unittest import sys try: from StringIO import StringIO except ImportError: from io import StringIO # NOQA from flake8.mccabe import get_code_complexity _GLOBAL = """\ for i in range(10): pass def a(): def b(): def c(): pass c() b() """ class McCabeTest(unittest.TestCase): def setUp(self): self.old = sys.stdout self.out = sys.stdout = StringIO() def tearDown(self): sys.sdtout = self.old def test_sample(self): self.assertEqual(get_code_complexity(_GLOBAL, 1), 2) self.out.seek(0) res = self.out.read().strip().split('\n') wanted = ["stdin:5:1: W901 'a' is too complex (4)", "stdin:2:1: W901 'Loop 2' is too complex (2)"] self.assertEqual(res, wanted)
Fix parameter name in `IAutoCompleteFormField`
<?php namespace wcf\system\form\builder\field; /** * Represents a form field that supports the `autocomplete` attribute. * * @author Matthias Schmidt * @copyright 2001-2020 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Form\Builder\Field * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute * @since 5.4 */ interface IAutoCompleteFormField { /** * Sets the `autocomplete` attribute of the form field. * * Multiple tokens can be separated by spaces and if `null` is given, the attribute is unset. * * @throws \InvalidArgumentException if an invalid `autocomplete` token is included in the attribute value */ public function autoComplete(?string $autoComplete): self; /** * Returns the `autocomplete` attribute of the form field. * * If `null` is returned, no `autocomplete` attribute will be set. */ public function getAutoComplete(): ?string; }
<?php namespace wcf\system\form\builder\field; /** * Represents a form field that supports the `autocomplete` attribute. * * @author Matthias Schmidt * @copyright 2001-2020 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Form\Builder\Field * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute * @since 5.4 */ interface IAutoCompleteFormField { /** * Sets the `autocomplete` attribute of the form field. * * Multiple tokens can be separated by spaces and if `null` is given, the attribute is unset. * * @throws \InvalidArgumentException if an invalid `autocomplete` token is included in the attribute value */ public function autoComplete(?string $autocomplete): self; /** * Returns the `autocomplete` attribute of the form field. * * If `null` is returned, no `autocomplete` attribute will be set. */ public function getAutoComplete(): ?string; }
Refactor para funfar via linha de comando
# -*- coding: utf-8 -*- from os import path import sys project_dir = path.dirname(__file__) project_dir = path.join('..') sys.path.append(project_dir) from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco from fase import Fase from placa_grafica_tkinter import rodar_fase if __name__ == '__main__': fase = Fase(intervalo_de_colisao=10) # Adicionar Pássaros Vermelhos for i in range(5): fase.adicionar_passaro(PassaroVermelho(30, 30)) # Adicionar Pássaros Amarelos for i in range(30): fase.adicionar_passaro(PassaroAmarelo(30, 30)) # Obstaculos for i in range(30, 480, 32): fase.adicionar_obstaculo(Obstaculo(300, i)) # Porcos for i in range(30, 300, 32): fase.adicionar_porco(Porco(600, i)) rodar_fase(fase)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco from fase import Fase from placa_grafica_tkinter import rodar_fase if __name__=='__main__': fase = Fase(intervalo_de_colisao=10) # Adicionar Pássaros Vermelhos for i in range(5): fase.adicionar_passaro(PassaroVermelho(30, 30)) # Adicionar Pássaros Amarelos for i in range(30): fase.adicionar_passaro(PassaroAmarelo(30, 30)) # Obstaculos for i in range(30, 480, 32): fase.adicionar_obstaculo(Obstaculo(300, i)) # Porcos for i in range(30, 300, 32): fase.adicionar_porco(Porco(600, i)) rodar_fase(fase)
Replace use of com.sun ObservableSetWrapper with FXCollections
package de.prob2.ui.states; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob.model.representation.AbstractElement; import javafx.collections.FXCollections; import javafx.collections.ObservableSet; @Singleton public final class ClassBlacklist { private final ObservableSet<Class<? extends AbstractElement>> blacklist; private final ObservableSet<Class<? extends AbstractElement>> knownClasses; @Inject @SuppressWarnings("unchecked") private ClassBlacklist() { super(); this.blacklist = FXCollections.observableSet(); this.knownClasses = FXCollections.observableSet(); } public ObservableSet<Class<? extends AbstractElement>> getBlacklist() { return this.blacklist; } public ObservableSet<Class<? extends AbstractElement>> getKnownClasses() { return this.knownClasses; } }
package de.prob2.ui.states; import java.util.HashSet; import com.google.inject.Inject; import com.google.inject.Singleton; import com.sun.javafx.collections.ObservableSetWrapper; import de.prob.model.representation.AbstractElement; import javafx.collections.ObservableSet; @Singleton public class ClassBlacklist { private final ObservableSet<Class<? extends AbstractElement>> blacklist; private final ObservableSet<Class<? extends AbstractElement>> knownClasses; @Inject private ClassBlacklist() { super(); this.blacklist = new ObservableSetWrapper<>(new HashSet<>()); this.knownClasses = new ObservableSetWrapper<>(new HashSet<>()); } public ObservableSet<Class<? extends AbstractElement>> getBlacklist() { return this.blacklist; } public ObservableSet<Class<? extends AbstractElement>> getKnownClasses() { return this.knownClasses; } }
Fix model relationship and ready to set online
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Node extends Model { // Properties protected $dateFormat = 'U'; // Relationships /** * Link to nodeGroup * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function nodeGroup() { return $this->belongsTo(NodeGroup::class, 'group_id', 'id'); } /** * Link to node logs * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function nodeStatusLog() { return $this->hasMany(NodeStatus::class, 'node_id', 'id'); } // Operation // Judgement public function isNodeBelongedToUser($userId) { return !empty($this->nodeGroup()->getRelated()->services()->get()->where('user_id', $userId)->first()); } }
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Node extends Model { // Properties protected $dateFormat = 'U'; // Relationships /** * Link to nodeGroup * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function nodeGroup() { return $this->belongsTo(NodeGroup::class, 'group_id', 'id'); } /** * Link to node logs * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function nodeStatusLog() { return $this->hasMany(NodeStatus::class, 'node_id', 'id'); } // Operation // Judgement public function isNodeBelongedToUser($userId) { return !empty($this->nodeGroup()->services()->where('user_id', $userId)->first()); } }
Add dots to pale things
import inspect import types from . import adapters from . import arguments from . import config from . import context from .endpoint import Endpoint from .resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances
import inspect import types import adapters import arguments import config import context from endpoint import Endpoint from resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances
Set premailer version to 3.1.1
#! /usr/bin/env python import os from setuptools import setup, find_packages def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except IOError: return '' setup( name='djpl-emailing', version='0.1', description='a django-productline feature to include schnipp.js', long_description=read('README.rst'), license='The MIT License', keywords='django, django-productline, email', author='Toni Michel', author_email='toni@schnapptack.de', url="https://github.com/tonimichel/djpl-emailing", packages=find_packages(), package_dir={'emailing': 'emailing'}, include_package_data=True, scripts=[], zip_safe=False, classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Operating System :: OS Independent' ], install_requires=[ 'django-productline', 'premailer==3.1.1' ] )
#! /usr/bin/env python import os from setuptools import setup, find_packages def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except IOError: return '' setup( name='djpl-emailing', version='0.1', description='a django-productline feature to include schnipp.js', long_description=read('README.rst'), license='The MIT License', keywords='django, django-productline, email', author='Toni Michel', author_email='toni@schnapptack.de', url="https://github.com/tonimichel/djpl-emailing", packages=find_packages(), package_dir={'emailing': 'emailing'}, include_package_data=True, scripts=[], zip_safe=False, classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Operating System :: OS Independent' ], install_requires=[ 'django-productline', 'premailer==3.0.1' ] )
Check for sys.platform == linux, not linux2
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': assert sorted(info['files']) == ['lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'] elif sys.platform.startswith('linux'): assert sorted(info['files']) == ['lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'] if __name__ == '__main__': main()
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': assert sorted(info['files']) == [u'lib/libpng.dylib', u'lib/libpng16.16.dylib', u'lib/libpng16.dylib'] elif sys.platform == 'linux2': assert sorted(info['files']) == ['lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'] if __name__ == '__main__': main()
Fix build failure for mac/ubuntu, which relies on an old version for keras-preprocessing. PiperOrigin-RevId: 273405152
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Keras data preprocessing utils.""" # pylint: disable=g-import-not-at-top from __future__ import absolute_import from __future__ import division from __future__ import print_function # TODO(mihaimaruseac): remove the import of keras_preprocessing and injecting # once we update to latest version of keras_preprocessing import keras_preprocessing from tensorflow.python.keras import backend from tensorflow.python.keras.utils import all_utils as utils # This exists for compatibility with prior version of keras_preprocessing. keras_preprocessing.set_keras_submodules(backend=backend, utils=utils) from tensorflow.python.keras.preprocessing import image from tensorflow.python.keras.preprocessing import sequence from tensorflow.python.keras.preprocessing import text del absolute_import del division del print_function
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Keras data preprocessing utils.""" # pylint: disable=g-import-not-at-top from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.keras.preprocessing import image from tensorflow.python.keras.preprocessing import sequence from tensorflow.python.keras.preprocessing import text del absolute_import del division del print_function
Put back set error (now in correct place)
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Http\Controllers; class FallbackController extends Controller { public function __construct() { if (is_api_request()) { $this->middleware('api'); } else { $this->middleware('web'); } parent::__construct(); } public function index() { app('route-section')->setError(404); if (is_json_request()) { return error_popup(trans('errors.missing_route'), 404); } return ext_view('layout.error', ['statusCode' => 404], 'html', 404); } }
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Http\Controllers; class FallbackController extends Controller { public function __construct() { if (is_api_request()) { $this->middleware('api'); } else { $this->middleware('web'); } parent::__construct(); } public function index() { if (is_json_request()) { return error_popup(trans('errors.missing_route'), 404); } return ext_view('layout.error', ['statusCode' => 404], 'html', 404); } }
Update user schema for application merge
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ _id: { type: Number }, profileImageName: { type: String, default: 'default.png' }, email: { type: String, unique: true }, age: { type: Number, min: 10, max: 100 }, grade: { type: Number, min: 8, max: 12 }, phoneNumber: { type: String }, name: { first: { type: String, trim: true }, last: { type: String, trim: true } }, application: { recommender: { type: Number, ref: 'User' }, why: String, writingFileName: String }, registeredDate: { type: Date, default: Date.now }, admin: { type: Boolean, default: false }, verified: { type: Boolean, default: false } }, { toObject: { virtuals: true }, toJSON: { virtuals: true } }); userSchema.methods.findCamps = function() { return this.model('Camp').find().or([{ ambassador: this._id }, { director: this._id}, { teachers: this._id }]).populate('location').exec(); } userSchema.virtual('name.full').get(function() { return this.name.first + ' ' + this.name.last; }); module.exports = { name: 'User', schema: userSchema };
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ _id: { type: Number }, profileImageName: { type: String, default: 'default.png' }, email: { type: String, unique: true }, phoneNumber: { type: String }, name: { first: { type: String, trim: true }, last: { type: String, trim: true } }, registeredDate: { type: Date, default: Date.now }, admin: { type: Boolean, default: false }, verified: { type: Boolean, default: false } }, { toObject: { virtuals: true }, toJSON: { virtuals: true } }); userSchema.methods.findCamps = function() { return this.model('Camp').find().or([{ ambassador: this._id }, { director: this._id}, { teachers: this._id }]).populate('location').exec(); } userSchema.virtual('name.full').get(function() { return this.name.first + ' ' + this.name.last; }); module.exports = { name: 'User', schema: userSchema };
Use pprint instead of json for formatting json.dumps fails to print anything for an object. I would prefer to show a representation of the object rather than filter it out so rely on pprint instead.
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import pprint import webob.dec @webob.dec.wsgify def echo_app(request): """A WSGI application that echoes the CGI environment to the user.""" return webob.Response(content_type='application/json', body=pprint.pformat(request.environ, indent=4)) def echo_app_factory(global_conf, **local_conf): return echo_app
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import webob.dec @webob.dec.wsgify def echo_app(request): """A WSGI application that echoes the CGI environment to the user.""" return webob.Response(content_type='application/json', body=json.dumps(request.environ, indent=4)) def echo_app_factory(global_conf, **local_conf): import ipdb; ipdb.set_trace() return echo_app