text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update version string to 2.6.0-pre.16
'use strict'; var platform = require('enyo/platform'), dispatcher = require('enyo/dispatcher'), gesture = require('enyo/gesture'); exports = module.exports = require('./src/options'); exports.version = '2.6.0-pre.16'; // Override the default holdpulse config to account for greater delays between keydown and keyup // events in Moonstone with certain input devices. gesture.drag.configureHoldPulse({ events: [{name: 'hold', time: 400}], endHold: 'onLeave' }); /** * Registers key mappings for webOS-specific device keys related to media control. * * @private */ if (platform.webos >= 4) { // Table of default keyCode mappings for webOS device dispatcher.registerKeyMap({ 415 : 'play', 413 : 'stop', 19 : 'pause', 412 : 'rewind', 417 : 'fastforward', 461 : 'back' }); } // ensure that these are registered require('./src/resolution'); require('./src/fonts');
'use strict'; var platform = require('enyo/platform'), dispatcher = require('enyo/dispatcher'), gesture = require('enyo/gesture'); exports = module.exports = require('./src/options'); exports.version = '2.6.0-pre.14.1'; // Override the default holdpulse config to account for greater delays between keydown and keyup // events in Moonstone with certain input devices. gesture.drag.configureHoldPulse({ events: [{name: 'hold', time: 400}], endHold: 'onLeave' }); /** * Registers key mappings for webOS-specific device keys related to media control. * * @private */ if (platform.webos >= 4) { // Table of default keyCode mappings for webOS device dispatcher.registerKeyMap({ 415 : 'play', 413 : 'stop', 19 : 'pause', 412 : 'rewind', 417 : 'fastforward', 461 : 'back' }); } // ensure that these are registered require('./src/resolution'); require('./src/fonts');
Return last 50 messages only from cache
var express = require('express'); var eventStream = require('express-eventsource')(); var clientSSDP = require('./clients/ssdp'); var clientMDNS = require('./clients/mdns'); var app = express(), messages = []; // Serve all static files in /public app.use(require('serve-static')('public')); // Shared eventsource // To send data call: eventStream.send(dataObj, 'eventName'); app.use('/events', eventStream.middleware()); // Perform a scan, sending results // through the event stream app.get('/scan', function (req, res) { ssdp.search(); mdns.start(); res.send(); }); // Return all previous messages app.get('/cache', function (req, res) { res.send( JSON.stringify(messages.slice(-50)) ); }); var ssdp = clientSSDP.create(); ssdp.on('*', function (msg) { console.log(log(msg)); eventStream.send(msg); messages.push(msg); }); ssdp.search(); var mdns = clientMDNS.create(); mdns.on('*', function (msg) { console.log(log(msg)); eventStream.send(msg); messages.push(msg); }); function log(msg) { return msg.protocol + ':\t\t' + msg.state + '\t' + msg.type + '\t\t\t' + msg.id; } app.listen(process.env.PORT || 3000);
var express = require('express'); var eventStream = require('express-eventsource')(); var clientSSDP = require('./clients/ssdp'); var clientMDNS = require('./clients/mdns'); var app = express(), messages = []; // Serve all static files in /public app.use(require('serve-static')('public')); // Shared eventsource // To send data call: eventStream.send(dataObj, 'eventName'); app.use('/events', eventStream.middleware()); // Perform a scan, sending results // through the event stream app.get('/scan', function (req, res) { ssdp.search(); mdns.start(); res.send(); }); // Return all previous messages app.get('/cache', function (req, res) { res.send( JSON.stringify(messages) ); }); var ssdp = clientSSDP.create(); ssdp.on('*', function (msg) { console.log(log(msg)); eventStream.send(msg); messages.push(msg); }); ssdp.search(); var mdns = clientMDNS.create(); mdns.on('*', function (msg) { console.log(log(msg)); eventStream.send(msg); messages.push(msg); }); function log(msg) { return msg.protocol + ':\t\t' + msg.state + '\t' + msg.type + '\t\t\t' + msg.id; } app.listen(process.env.PORT || 3000);
[previews] Fix wrong resolving of referenced type
import React, {PropTypes} from 'react' import resolveRefType from './resolveRefType' import {resolver as previewResolver} from 'part:@sanity/base/preview' export default class SanityPreview extends React.PureComponent { static propTypes = { value: PropTypes.object, type: PropTypes.object.isRequired }; state = { loading: true, materialized: null, refType: null } componentDidMount() { const {type, value} = this.props this.subscribeRefType(value, type) } componentWillUnmount() { this.unsubscribe() } subscribeRefType(value, type) { this.unsubscribe() this.subscription = resolveRefType(value, type) .subscribe(refType => { this.setState({refType}) }) } unsubscribe() { if (this.subscription) { this.subscription.unsubscribe() this.subscription = null } } componentWillReceiveProps(nextProps) { if (this.props.type !== nextProps.type || this.props.value !== nextProps.value) { this.subscribeRefType(nextProps.value, nextProps.type) } } render() { const {refType} = this.state if (!refType) { return null } const Preview = previewResolver(refType) return ( <Preview {...this.props} type={refType} /> ) } }
import React, {PropTypes} from 'react' import resolveRefType from './resolveRefType' import {resolver as previewResolver} from 'part:@sanity/base/preview' export default class SanityPreview extends React.PureComponent { static propTypes = { value: PropTypes.object, type: PropTypes.object.isRequired }; state = { loading: true, materialized: null, refType: null } resolveRefType(value, type) { resolveRefType(value, type).then(refType => { this.setState({ refType }) }) } componentDidMount() { const {type, value} = this.props this.resolveRefType(value, type) } componentWillReceiveProps(nextProps) { if (this.props.type !== nextProps.type || this.props.value !== nextProps.value) { this.resolveRefType(nextProps.value, nextProps.type) } } render() { const {refType} = this.state if (!refType) { return null } const Preview = previewResolver(refType) return ( <Preview {...this.props} type={refType} /> ) } }
Make the widget error message shorter and more understandable.
from .widget import Widget, DOMWidget, CallbackDispatcher, register from .widget_bool import Checkbox, ToggleButton from .widget_button import Button from .widget_box import Box, Popup, FlexBox, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .interaction import interact, interactive, fixed, interact_manual from .widget_link import Link, link, DirectionalLink, dlink # Deprecated classes from .widget_bool import CheckboxWidget, ToggleButtonWidget from .widget_button import ButtonWidget from .widget_box import ContainerWidget, PopupWidget from .widget_float import FloatTextWidget, BoundedFloatTextWidget, FloatSliderWidget, FloatProgressWidget from .widget_image import ImageWidget from .widget_int import IntTextWidget, BoundedIntTextWidget, IntSliderWidget, IntProgressWidget from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget from .widget_selectioncontainer import TabWidget, AccordionWidget from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget # Warn on import from warnings import warn warn("IPython widgets are experimental and may change in the future.", FutureWarning, stacklevel=2)
from .widget import Widget, DOMWidget, CallbackDispatcher, register from .widget_bool import Checkbox, ToggleButton from .widget_button import Button from .widget_box import Box, Popup, FlexBox, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .interaction import interact, interactive, fixed, interact_manual from .widget_link import Link, link, DirectionalLink, dlink # Deprecated classes from .widget_bool import CheckboxWidget, ToggleButtonWidget from .widget_button import ButtonWidget from .widget_box import ContainerWidget, PopupWidget from .widget_float import FloatTextWidget, BoundedFloatTextWidget, FloatSliderWidget, FloatProgressWidget from .widget_image import ImageWidget from .widget_int import IntTextWidget, BoundedIntTextWidget, IntSliderWidget, IntProgressWidget from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget from .widget_selectioncontainer import TabWidget, AccordionWidget from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget # Warn on import from warnings import warn warn("""The widget API is still considered experimental and may change in the future.""", FutureWarning, stacklevel=2)
Switch to using vars for hostname in gh resolver.
/* @flow */ import type {ExplodedFragment} from './hosted-git-resolver.js'; import HostedGitResolver from './hosted-git-resolver.js'; export default class GitHubResolver extends HostedGitResolver { static protocol = 'github'; static hostname = 'github.com'; static isVersion(pattern: string): boolean { // github proto if (pattern.startsWith('github:')) { return true; } // github shorthand if (/^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(pattern)) { return true; } return false; } static getTarballUrl(parts: ExplodedFragment, hash: string): string { return `https://codeload.${this.hostname}/${parts.user}/${parts.repo}/tar.gz/${hash}`; } static getGitSSHUrl(parts: ExplodedFragment): string { return `git@${this.hostname}:${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`; } static getGitHTTPUrl(parts: ExplodedFragment): string { return `https://${this.hostname}/${parts.user}/${parts.repo}.git`; } static getHTTPFileUrl(parts: ExplodedFragment, filename: string, commit: string): string { return `https://raw.githubusercontent.com/${parts.user}/${parts.repo}/${commit}/${filename}`; } }
/* @flow */ import type {ExplodedFragment} from './hosted-git-resolver.js'; import HostedGitResolver from './hosted-git-resolver.js'; export default class GitHubResolver extends HostedGitResolver { static protocol = 'github'; static hostname = 'github.com'; static isVersion(pattern: string): boolean { // github proto if (pattern.startsWith('github:')) { return true; } // github shorthand if (/^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(pattern)) { return true; } return false; } static getTarballUrl(parts: ExplodedFragment, hash: string): string { return `https://codeload.github.com/${parts.user}/${parts.repo}/tar.gz/${hash}`; } static getGitSSHUrl(parts: ExplodedFragment): string { return `git@github.com:${parts.user}/${parts.repo}.git${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`; } static getGitHTTPUrl(parts: ExplodedFragment): string { return `https://github.com/${parts.user}/${parts.repo}.git`; } static getHTTPFileUrl(parts: ExplodedFragment, filename: string, commit: string): string { return `https://raw.githubusercontent.com/${parts.user}/${parts.repo}/${commit}/${filename}`; } }
Use regular malloc for logserver-container
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.api.container.ContainerServiceType; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.vespa.model.container.Container; import com.yahoo.vespa.model.container.component.AccessLogComponent; import com.yahoo.vespa.model.container.component.AccessLogComponent.AccessLogType; import com.yahoo.vespa.model.container.component.AccessLogComponent.CompressionType; /** * Container that should be running on same host as the logserver. Sets up a handler for getting logs from logserver. * Only in use in hosted Vespa. */ public class LogserverContainer extends Container { public LogserverContainer(AbstractConfigProducer<?> parent, boolean isHostedVespa) { super(parent, "" + 0, 0, isHostedVespa); LogserverContainerCluster cluster = (LogserverContainerCluster) parent; addComponent(new AccessLogComponent( cluster, AccessLogType.jsonAccessLog, CompressionType.GZIP, cluster.getName(), true)); } @Override public ContainerServiceType myServiceType() { return ContainerServiceType.LOGSERVER_CONTAINER; } @Override public String defaultPreload() { return ""; } }
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.api.container.ContainerServiceType; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.vespa.model.container.Container; import com.yahoo.vespa.model.container.component.AccessLogComponent; import com.yahoo.vespa.model.container.component.AccessLogComponent.AccessLogType; import com.yahoo.vespa.model.container.component.AccessLogComponent.CompressionType; /** * Container that should be running on same host as the logserver. Sets up a handler for getting logs from logserver. * Only in use in hosted Vespa. */ public class LogserverContainer extends Container { public LogserverContainer(AbstractConfigProducer<?> parent, boolean isHostedVespa) { super(parent, "" + 0, 0, isHostedVespa); LogserverContainerCluster cluster = (LogserverContainerCluster) parent; addComponent(new AccessLogComponent( cluster, AccessLogType.jsonAccessLog, CompressionType.GZIP, cluster.getName(), true)); } @Override public ContainerServiceType myServiceType() { return ContainerServiceType.LOGSERVER_CONTAINER; } }
Fix broken setting of postgres password
""" Creates a database for Molly, and appropriate users, once given login information as super user, or by running as root. """ import os from molly.installer.utils import quiet_exec, CommandFailed def create(dba_user, dba_pass, username, password, database): creds = [] if dba_user: creds += ['-U', dba_user] if dba_pass: os.environ['PGPASSWORD'] = dba_pass try: quiet_exec(['psql'] + creds + ['-c',"CREATE USER %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate') except CommandFailed: pass quiet_exec(['psql'] + creds + ['-c',"ALTER ROLE %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate') try: quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate') except CommandFailed: quiet_exec(['dropdb'] + creds + [database], 'dbcreate') quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate') quiet_exec(['psql'] + creds + ['-c',"GRANT ALL ON DATABASE %s TO %s;" % (database, username)], 'dbcreate') if dba_pass: del os.environ['PGPASSWORD']
""" Creates a database for Molly, and appropriate users, once given login information as super user, or by running as root. """ from molly.installer.utils import quiet_exec, CommandFailed def create(dba_user, dba_pass, username, password, database): creds = [] if dba_user: creds += ['-U', dba_user] if dba_pass: os.environ['PGPASSWORD'] = dba_pass try: quiet_exec(['psql'] + creds + ['-c',"CREATE USER %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate') except CommandFailed: pass quiet_exec(['psql'] + creds + ['-c',"ALTER ROLE %s WITH PASSWORD '%s';" % (username, password)], 'dbcreate') try: quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate') except CommandFailed: quiet_exec(['dropdb'] + creds + [database], 'dbcreate') quiet_exec(['createdb'] + creds + ['-T','template_postgis',database], 'dbcreate') quiet_exec(['psql'] + creds + ['-c',"GRANT ALL ON DATABASE %s TO %s;" % (database, username)], 'dbcreate') if dba_pass: del os.environ['PGPASSWORD']
Insert into stat_page_views with LOW_PRIORITY
<?php /** * ocs-webserver * * Copyright 2016 by pling GmbH. * * This file is part of ocs-webserver. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ class Default_Model_DbTable_StatPageViews extends Zend_Db_Table_Abstract { protected $_name = "stat_page_views"; public function savePageView($project_id, $clientIp, $member_id) { $this->_db->query("INSERT LOW_PRIORITY INTO {$this->_name} (`project_id`, `ip`, `member_id`) VALUES (:param1, :param2, :param3);", array( 'param1' => $project_id, 'param2' => $clientIp, 'param3' => $member_id )); $this->_db->commit(); } }
<?php /** * ocs-webserver * * Copyright 2016 by pling GmbH. * * This file is part of ocs-webserver. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ class Default_Model_DbTable_StatPageViews extends Zend_Db_Table_Abstract { protected $_name = "stat_page_views"; public function savePageView($project_id, $clientIp, $member_id) { $newData = array( 'project_id' => $project_id, 'ip' => $clientIp, 'member_id' => $member_id ); $this->insert($newData); } }
Fix demo being loaded regardless of ESP_PROD
const webpack = require('webpack') const { execSync } = require('child_process') const path = require('path') let hash = execSync('git rev-parse --short HEAD').toString().trim() let lang = process.env.ESP_LANG || 'en' let plugins = [] let devtool = 'source-map' if (process.env.ESP_PROD) { // ignore demo plugins.push(new webpack.IgnorePlugin(/(term|\.)\/demo(?:\.js)?$/)) // no source maps devtool = '' } plugins.push(new webpack.optimize.UglifyJsPlugin({ sourceMap: devtool === 'source-map' })) // replace "locale-data" with path to locale data let locale = process.env.ESP_LANG || 'en' plugins.push(new webpack.NormalModuleReplacementPlugin( /^locale-data$/, path.resolve(`lang/${locale}.php`) )) module.exports = { entry: './js', output: { path: path.resolve(__dirname, 'out', 'js'), filename: `app.${hash}-${lang}.js` }, module: { rules: [ { test: /\.js$/, exclude: [ path.resolve(__dirname, 'node_modules') ], loader: 'babel-loader' }, { test: /lang\/.+?\.php$/, loader: './lang/_js-lang-loader.js' } ] }, devtool, plugins }
const webpack = require('webpack') const { execSync } = require('child_process') const path = require('path') let hash = execSync('git rev-parse --short HEAD').toString().trim() let lang = process.env.ESP_LANG || 'en' let plugins = [] let devtool = 'source-map' if (process.env.ESP_PROD) { // ignore demo plugins.push(new webpack.IgnorePlugin(/\.\/demo(?:\.js)?$/)) // no source maps devtool = '' } plugins.push(new webpack.optimize.UglifyJsPlugin({ sourceMap: devtool === 'source-map' })) // replace "locale-data" with path to locale data let locale = process.env.ESP_LANG || 'en' plugins.push(new webpack.NormalModuleReplacementPlugin( /^locale-data$/, path.resolve(`lang/${locale}.php`) )) module.exports = { entry: './js', output: { path: path.resolve(__dirname, 'out', 'js'), filename: `app.${hash}-${lang}.js` }, module: { rules: [ { test: /\.js$/, exclude: [ path.resolve(__dirname, 'node_modules') ], loader: 'babel-loader' }, { test: /lang\/.+?\.php$/, loader: './lang/_js-lang-loader.js' } ] }, devtool, plugins }
Fix wrong http code for errors
package errors import ( "encoding/json" "net/http" ) type HttpError struct { Code int `json:"code"` Message string `json:"message"` } var HttpErrors map[string]*HttpError = map[string]*HttpError { "ErrorApiKeyMandatory": &HttpError{Code: 401, Message: "apikey is mandatory"}, "ErrorApiKeyInvalid": &HttpError{Code: 401,Message: "given apikey is invalid"}, } func NewHttpError(w http.ResponseWriter, err string) { w.Header().Set("Content-Type", "application/json") w.Header().Set("X-Content-Type-Options", "nosniff") w.WriteHeader(HttpErrors[err].Code) w.Write(HttpErrors[err].getJSON()) } func (e *HttpError) getJSON() []byte { jsonError, _ := json.Marshal(e) return jsonError }
package errors import ( "encoding/json" "net/http" ) type HttpError struct { Code int `json:"code"` Message string `json:"message"` } var HttpErrors map[string]*HttpError = map[string]*HttpError { "ErrorApiKeyMandatory": &HttpError{Code: 403, Message: "apikey is mandatory"}, "ErrorApiKeyInvalid": &HttpError{Code: 403, Message: "given apikey is invalid"}, } func NewHttpError(w http.ResponseWriter, err string) { w.Header().Set("Content-Type", "application/json") w.Header().Set("X-Content-Type-Options", "nosniff") w.WriteHeader(HttpErrors[err].Code) w.Write(HttpErrors[err].getJSON()) } func (e *HttpError) getJSON() []byte { jsonError, _ := json.Marshal(e) return jsonError }
Add more return types after fixing a typo in my script
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Authorization\Voter; use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Event\VoteEvent; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * Decorates voter classes to send result events. * * @author Laurent VOULLEMIER <laurent.voullemier@gmail.com> * * @internal */ class TraceableVoter implements VoterInterface { private $voter; private $eventDispatcher; public function __construct(VoterInterface $voter, EventDispatcherInterface $eventDispatcher) { $this->voter = $voter; $this->eventDispatcher = LegacyEventDispatcherProxy::decorate($eventDispatcher); } public function vote(TokenInterface $token, $subject, array $attributes): int { $result = $this->voter->vote($token, $subject, $attributes); $this->eventDispatcher->dispatch(new VoteEvent($this->voter, $subject, $attributes, $result), 'debug.security.authorization.vote'); return $result; } public function getDecoratedVoter(): VoterInterface { return $this->voter; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Authorization\Voter; use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Event\VoteEvent; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * Decorates voter classes to send result events. * * @author Laurent VOULLEMIER <laurent.voullemier@gmail.com> * * @internal */ class TraceableVoter implements VoterInterface { private $voter; private $eventDispatcher; public function __construct(VoterInterface $voter, EventDispatcherInterface $eventDispatcher) { $this->voter = $voter; $this->eventDispatcher = LegacyEventDispatcherProxy::decorate($eventDispatcher); } public function vote(TokenInterface $token, $subject, array $attributes) { $result = $this->voter->vote($token, $subject, $attributes); $this->eventDispatcher->dispatch(new VoteEvent($this->voter, $subject, $attributes, $result), 'debug.security.authorization.vote'); return $result; } public function getDecoratedVoter(): VoterInterface { return $this->voter; } }
Check the shape of input data earlier Using geo.nVoxel to check the input img shape earlier, before geo is casted to float32 (geox). We should use any() instead of all(), since "!=" is used?
from _Ax import _Ax_ext import numpy as np import copy def Ax(img, geo, angles, projection_type="Siddon"): if img.dtype != np.float32: raise TypeError("Input data should be float32, not "+ str(img.dtype)) if not np.isreal(img).all(): raise ValueError("Complex types not compatible for projection.") if any(img.shape != geo.nVoxel): raise ValueError("Input data should be of shape geo.nVoxel: "+ str(geo.nVoxel) + " not:" + str(img.shape)) geox = copy.deepcopy(geo) geox.check_geo(angles) """ Here we cast all values in geo to single point precision float. This way we know what behaviour to expect from pytigre to Cuda and can change single parameters accordingly. """ geox.cast_to_single() #geox.checknans() return _Ax_ext(img, geox, geox.angles, projection_type, geox.mode)
from _Ax import _Ax_ext import numpy as np import copy def Ax(img, geo, angles, projection_type="Siddon"): if img.dtype != np.float32: raise TypeError("Input data should be float32, not "+ str(img.dtype)) if not np.isreal(img).all(): raise ValueError("Complex types not compatible for projection.") geox = copy.deepcopy(geo) geox.check_geo(angles) """ Here we cast all values in geo to single point precision float. This way we know what behaviour to expect from pytigre to Cuda and can change single parameters accordingly. """ geox.cast_to_single() #geox.checknans() if abs(img.shape - geox.nVoxel).max()>1e-8: raise ValueError("Input data should be of shape geo.nVoxel: "+ str(geox.nVoxel) + " not:" + str(img.shape)) return _Ax_ext(img, geox, geox.angles, projection_type, geox.mode)
Fix message type in factory
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ use App\Models\BeatmapDiscussion; $factory->define(BeatmapDiscussion::class, function (Faker\Generator $faker) use ($factory) { $type = rand(0, 1) === 0 ? 'timeline' : 'general'; return $factory->raw(BeatmapDiscussion::class, $type); }); $factory->defineAs(BeatmapDiscussion::class, 'timeline', function () { return [ 'timestamp' => 0, 'message_type' => array_rand(BeatmapDiscussion::RESOLVABLE_TYPES), ]; }); $factory->defineAs(BeatmapDiscussion::class, 'general', function () { return [ 'timestamp' => null, 'message_type' => array_rand(BeatmapDiscussion::RESOLVABLE_TYPES), ]; });
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ use App\Models\BeatmapDiscussion; $factory->define(BeatmapDiscussion::class, function (Faker\Generator $faker) use ($factory) { $type = rand(0, 1) === 0 ? 'timeline' : 'general'; return $factory->raw(BeatmapDiscussion::class, $type); }); $factory->defineAs(BeatmapDiscussion::class, 'timeline', function () { return [ 'timestamp' => 0, 'message_type' => array_rand(BeatmapDiscussion::MESSAGE_TYPES), ]; }); $factory->defineAs(BeatmapDiscussion::class, 'general', function () { return [ 'timestamp' => null, 'message_type' => null, ]; });
Fix regex to support Mininet 20.30.40+++
#!/usr/bin/python from subprocess import check_output as co from sys import exit # Actually run bin/mn rather than importing via python path version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True ) version = version.strip() # Find all Mininet path references lines = co( "grep -or 'Mininet \w\+\.\w\+\.\w\+[+]*' *", shell=True ) error = False for line in lines.split( '\n' ): if line and 'Binary' not in line: fname, fversion = line.split( ':' ) if version != fversion: print "%s: incorrect version '%s' (should be '%s')" % ( fname, fversion, version ) error = True if error: exit( 1 )
#!/usr/bin/python from subprocess import check_output as co from sys import exit # Actually run bin/mn rather than importing via python path version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True ) version = version.strip() # Find all Mininet path references lines = co( "grep -or 'Mininet \w\.\w\.\w[\w\+]*' *", shell=True ) error = False for line in lines.split( '\n' ): if line and 'Binary' not in line: fname, fversion = line.split( ':' ) if version != fversion: print "%s: incorrect version '%s' (should be '%s')" % ( fname, fversion, version ) error = True if error: exit( 1 )
Fix Env command for switching php
<?php namespace PhpBrew\Command; use PhpBrew\Config; class EnvCommand extends \CLIFramework\Command { public function brief() { return 'export environment variables'; } public function execute($version = null) { // get current version if( ! $version ) $version = getenv('PHPBREW_PHP'); // $currentVersion; $root = Config::getPhpbrewRoot(); $home = Config::getPhpbrewHome(); $buildDir = Config::getBuildDir(); // $versionBuildPrefix = Config::getVersionBuildPrefix($version); // $versionBinPath = Config::getVersionBinPath($version); echo 'export PHPBREW_ROOT=' . $root . "\n"; echo 'export PHPBREW_HOME=' . $home . "\n"; echo 'export PHPBREW_PHP=' . $version . "\n"; echo 'export PHPBREW_PATH=' . ($version ? Config::getVersionBinPath($version) : '') . "\n"; } }
<?php namespace PhpBrew\Command; use PhpBrew\Config; class EnvCommand extends \CLIFramework\Command { public function brief() { return 'export environment variables'; } public function execute($version = null) { // get current version if( ! $version ) $version = getenv('PHPBREW_PHP'); // $currentVersion; $root = Config::getPhpbrewRoot(); $buildDir = Config::getBuildDir(); // $versionBuildPrefix = Config::getVersionBuildPrefix($version); // $versionBinPath = Config::getVersionBinPath($version); echo 'export PHPBREW_ROOT=' . $root . "\n"; echo 'export PHPBREW_HOME=' . $root . "\n"; echo 'export PHPBREW_PHP=' . $version . "\n"; echo 'export PHPBREW_PATH=' . ($version ? Config::getVersionBinPath($version) : '') . "\n"; } }
Set default if includeXferAsWithdrawn is not set
<?php namespace TmlpStats\Reports\Arrangements; class TeamMembersByQuarter extends BaseArrangement { /* * Builds an array of TDO attendance for each team member */ public function build($data) { $teamMembersData = $data['teamMembersData']; $includeXferAsWithdrawn = array_get($data, 'includeXferAsWithdrawn', false); $reportData = [ 'team1' => [], 'team2' => [], 'withdrawn' => [], ]; foreach ($teamMembersData as $memberData) { $index = "team{$memberData->teamMember->teamYear}"; if ($memberData->withdrawCodeId !== null || ($includeXferAsWithdrawn && $memberData->xferOut) ) { $index = 'withdrawn'; } $reportData[$index]["Q{$memberData->teamMember->quarterNumber}"][] = $memberData; } return compact('reportData'); } }
<?php namespace TmlpStats\Reports\Arrangements; class TeamMembersByQuarter extends BaseArrangement { /* * Builds an array of TDO attendance for each team member */ public function build($data) { $teamMembersData = $data['teamMembersData']; $includeXferAsWithdrawn = $data['includeXferAsWithdrawn']; $reportData = [ 'team1' => [], 'team2' => [], 'withdrawn' => [], ]; foreach ($teamMembersData as $memberData) { $index = "team{$memberData->teamMember->teamYear}"; if ($memberData->withdrawCodeId !== null || ($includeXferAsWithdrawn && $memberData->xferOut) ) { $index = 'withdrawn'; } $reportData[$index]["Q{$memberData->teamMember->quarterNumber}"][] = $memberData; } return compact('reportData'); } }
Fix import error for missing file.
# (c) 2013, AnsibleWorks # # This file is part of Ansible Commander # # Ansible Commander is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible Commander is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible Commander. If not, see <http://www.gnu.org/licenses/>. from lib.main.tests.organizations import OrganizationsTest from lib.main.tests.users import UsersTest from lib.main.tests.inventory import InventoryTest # FIXME: Uncomment the next line when projects.py is added to git. # from lib.main.tests.projects import ProjectsTest from lib.main.tests.commands import AcomInventoryTest from lib.main.tests.tasks import RunLaunchJobTest
# (c) 2013, AnsibleWorks # # This file is part of Ansible Commander # # Ansible Commander is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible Commander is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible Commander. If not, see <http://www.gnu.org/licenses/>. from lib.main.tests.organizations import OrganizationsTest from lib.main.tests.users import UsersTest from lib.main.tests.inventory import InventoryTest from lib.main.tests.projects import ProjectsTest from lib.main.tests.commands import AcomInventoryTest from lib.main.tests.tasks import RunLaunchJobTest
Remove BeautifulSoup from direct dependency list.
from setuptools import setup, find_packages from tiddlywebwiki import __version__ as VERSION setup( name = 'tiddlywebwiki', version = VERSION, description = 'A TiddlyWeb plugin to provide a multi-user TiddlyWiki environment.', author = 'FND', author_email = 'FNDo@gmx.net', packages = find_packages(exclude=['test']), scripts = ['twinstance'], platforms = 'Posix; MacOS X; Windows', install_requires = [ 'tiddlyweb>=0.9.96', 'tiddlywebplugins.wikklytextrender', 'tiddlywebplugins.status>=0.5', 'tiddlywebplugins.differ', 'tiddlywebplugins.atom', 'tiddlywebplugins.twimport', 'tiddlywebplugins.utils', 'tiddlywebplugins.instancer>=0.5.5', 'wikklytext'], include_package_data = True, zip_safe = False )
from setuptools import setup, find_packages from tiddlywebwiki import __version__ as VERSION setup( name = 'tiddlywebwiki', version = VERSION, description = 'A TiddlyWeb plugin to provide a multi-user TiddlyWiki environment.', author = 'FND', author_email = 'FNDo@gmx.net', packages = find_packages(exclude=['test']), scripts = ['twinstance'], platforms = 'Posix; MacOS X; Windows', install_requires = [ 'tiddlyweb>=0.9.96', 'tiddlywebplugins.wikklytextrender', 'tiddlywebplugins.status>=0.5', 'tiddlywebplugins.differ', 'tiddlywebplugins.atom', 'tiddlywebplugins.twimport', 'tiddlywebplugins.utils', 'tiddlywebplugins.instancer>=0.5.5', 'BeautifulSoup', 'wikklytext'], include_package_data = True, zip_safe = False )
Fix :bug: to display ours/theirs deleted status
/** @babel */ /** @jsx etch.dom */ import etch from 'etch' import {classNameForStatus} from '../helpers' const statusSymbolMap = { added: '+', deleted: '-', modified: '*' } export default class FilePatchListItemView { constructor (props) { this.props = props etch.initialize(this) this.props.registerItemElement(this.props.mergeConflict, this.element) } update (props) { this.props = props this.props.registerItemElement(this.props.mergeConflict, this.element) return etch.update(this) } render () { const {mergeConflict, selected, ...others} = this.props const status = classNameForStatus[mergeConflict.getFileStatus()] const className = selected ? 'is-selected' : '' return ( <div {...others} className={`git-FilePatchListView-item is-${status} ${className}`}> <span className={`git-FilePatchListView-icon icon icon-diff-${status} status-${status}`} /> <span className='git-FilePatchListView-path'>{mergeConflict.getPath()}</span> <span className={'git-FilePatchListView ours-theirs-info'}> {statusSymbolMap[mergeConflict.getOursStatus()]} {statusSymbolMap[mergeConflict.getTheirsStatus()]} </span> </div> ) } }
/** @babel */ /** @jsx etch.dom */ import etch from 'etch' import {classNameForStatus} from '../helpers' const statusSymbolMap = { added: '+', removed: '-', modified: '*' } export default class FilePatchListItemView { constructor (props) { this.props = props etch.initialize(this) this.props.registerItemElement(this.props.mergeConflict, this.element) } update (props) { this.props = props this.props.registerItemElement(this.props.mergeConflict, this.element) return etch.update(this) } render () { const {mergeConflict, selected, ...others} = this.props const status = classNameForStatus[mergeConflict.getFileStatus()] const className = selected ? 'is-selected' : '' return ( <div {...others} className={`git-FilePatchListView-item is-${status} ${className}`}> <span className={`git-FilePatchListView-icon icon icon-diff-${status} status-${status}`} /> <span className='git-FilePatchListView-path'>{mergeConflict.getPath()}</span> <span className={'git-FilePatchListView ours-theirs-info'}> {statusSymbolMap[mergeConflict.getOursStatus()]} {statusSymbolMap[mergeConflict.getTheirsStatus()]} </span> </div> ) } }
Add table name to bans model.
<?php /** * FluxBB - fast, light, user-friendly PHP forum software * Copyright (C) 2008-2012 FluxBB.org * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public license for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @category FluxBB * @package Core * @copyright Copyright (c) 2008-2012 FluxBB (http://fluxbb.org) * @license http://www.gnu.org/licenses/gpl.html GNU General Public License */ namespace FluxBB\Models; class Ban extends Base { protected $table = 'bans'; public function creator() { return $this->belongsTo('FluxBB\\Models\\User', 'ban_creator'); } }
<?php /** * FluxBB - fast, light, user-friendly PHP forum software * Copyright (C) 2008-2012 FluxBB.org * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public license for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @category FluxBB * @package Core * @copyright Copyright (c) 2008-2012 FluxBB (http://fluxbb.org) * @license http://www.gnu.org/licenses/gpl.html GNU General Public License */ namespace FluxBB\Models; class Ban extends Base { public function creator() { return $this->belongsTo('FluxBB\\Models\\User', 'ban_creator'); } }
Use const instead of var
#!/usr/bin/env node /** * * @typedef {{ * cwd: string, * require: Array, * configNameSearch: string[], * configPath: string, * configBase: string, * modulePath: string, * modulePackage: *, * }} LiftoffEnvironment */ const Liftoff = require("liftoff"); const run = require("../src/run"); const minimist = require('minimist'); const argv = minimist(process.argv.slice(2), { boolean: ["dev", "debug", "d", "v"] }); const Kaba = new Liftoff({ name: "kaba", extensions: { ".js": null }, v8flags: ['--harmony'] }); Kaba.launch({ cwd: argv.cwd, configPath: argv.kabafile, require: argv.require, completion: argv.completion }, (env) => run(env, argv));
#!/usr/bin/env node /** * * @typedef {{ * cwd: string, * require: Array, * configNameSearch: string[], * configPath: string, * configBase: string, * modulePath: string, * modulePackage: *, * }} LiftoffEnvironment */ var Liftoff = require("liftoff"); var run = require("../src/run"); var minimist = require('minimist'); const argv = minimist(process.argv.slice(2), { boolean: ["dev", "debug", "d", "v"] }); const Kaba = new Liftoff({ name: "kaba", extensions: { ".js": null }, v8flags: ['--harmony'] }); Kaba.launch({ cwd: argv.cwd, configPath: argv.kabafile, require: argv.require, completion: argv.completion }, (env) => run(env, argv));
Change id field unicode string to ascii string
from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, 'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add)
from django.test import TestCase from django.conf import settings from phonenumber_field.modelfields import PhoneNumberField from whats_fresh.models import * from django.contrib.gis.db import models import os import time import sys import datetime class ImageTestCase(TestCase): def setUp(self): self.expected_fields = { 'image': models.ImageField, 'caption': models.TextField, 'created': models.DateTimeField, 'modified': models.DateTimeField, u'id': models.AutoField } def test_fields_exist(self): model = models.get_model('whats_fresh', 'Image') for field, field_type in self.expected_fields.items(): self.assertEqual( field_type, type(model._meta.get_field_by_name(field)[0])) def test_no_additional_fields(self): fields = Image._meta.get_all_field_names() self.assertTrue(sorted(fields) == sorted(self.expected_fields.keys())) def test_created_modified_fields(self): self.assertTrue(Image._meta.get_field('modified').auto_now) self.assertTrue(Image._meta.get_field('created').auto_now_add)
Enable Flux logger only for dev
import appReducer from './app/reducer'; import createLogger from 'redux-logger'; import fetch from 'isomorphic-fetch'; import injectDependencies from './lib/injectDependencies'; import promiseMiddleware from 'redux-promise-middleware'; import stateToJS from './lib/stateToJS'; import validate from './validate'; import {applyMiddleware, createStore} from 'redux'; export default function configureStore(initialState) { const dependenciesMiddleware = injectDependencies( {fetch}, {validate} ); const middlewares = [ dependenciesMiddleware, promiseMiddleware ]; const loggerEnabled = process.env.IS_BROWSER && // eslint-disable-line no-undef process.env.NODE_ENV !== 'production'; // eslint-disable-line no-undef if (loggerEnabled) { const logger = createLogger({ collapsed: () => true, transformer: stateToJS }); middlewares.push(logger); } const store = applyMiddleware(...middlewares)(createStore)( appReducer, initialState); if (module.hot) { // eslint-disable-line no-undef // Enable Webpack hot module replacement for reducers. module.hot.accept('./app/reducer', () => { // eslint-disable-line no-undef const nextAppReducer = require('./app/reducer'); // eslint-disable-line no-undef store.replaceReducer(nextAppReducer); }); } return store; }
import appReducer from './app/reducer'; import createLogger from 'redux-logger'; import fetch from 'isomorphic-fetch'; import injectDependencies from './lib/injectDependencies'; import promiseMiddleware from 'redux-promise-middleware'; import stateToJS from './lib/stateToJS'; import validate from './validate'; import {applyMiddleware, createStore} from 'redux'; export default function configureStore(initialState) { const dependenciesMiddleware = injectDependencies( {fetch}, {validate} ); const middlewares = [ dependenciesMiddleware, promiseMiddleware ]; if (process.env.NODE_ENV !== 'production') { // eslint-disable-line no-undef const logger = createLogger({ collapsed: () => true, transformer: stateToJS }); middlewares.push(logger); } const store = applyMiddleware(...middlewares)(createStore)( appReducer, initialState); if (module.hot) { // eslint-disable-line no-undef // Enable Webpack hot module replacement for reducers. module.hot.accept('./app/reducer', () => { // eslint-disable-line no-undef const nextAppReducer = require('./app/reducer'); // eslint-disable-line no-undef store.replaceReducer(nextAppReducer); }); } return store; }
Fix tests to work with responses 0.3.0
import pytest from responses import RequestsMock from netvisor import Netvisor @pytest.fixture def netvisor(): kwargs = dict( sender='Test client', partner_id='xxx_yyy', partner_key='E2CEBB1966C7016730C70CA92CBB93DD', customer_id='xx_yyyy_zz', customer_key='7767899D6F5FB333784A2520771E5871', organization_id='1967543-8', language='EN' ) return Netvisor(host='http://koulutus.netvisor.fi', **kwargs) @pytest.yield_fixture(autouse=True) def responses(): r = RequestsMock() with r: yield r
import pytest from responses import RequestsMock from netvisor import Netvisor @pytest.fixture def netvisor(): kwargs = dict( sender='Test client', partner_id='xxx_yyy', partner_key='E2CEBB1966C7016730C70CA92CBB93DD', customer_id='xx_yyyy_zz', customer_key='7767899D6F5FB333784A2520771E5871', organization_id='1967543-8', language='EN' ) return Netvisor(host='http://koulutus.netvisor.fi', **kwargs) @pytest.yield_fixture(autouse=True) def responses(): requests_mock = RequestsMock() requests_mock._start() yield requests_mock requests_mock._stop() requests_mock.reset()
Make email field optional when creating reservation as an admin
<?php namespace Admin\Requests; use System\Classes\FormRequest; class Reservation extends FormRequest { protected function useDataFrom() { return static::DATA_TYPE_POST; } public function rules() { return [ ['location_id', 'admin::lang.reservations.text_restaurant', 'sometimes|required|integer'], ['first_name', 'admin::lang.reservations.label_first_name', 'required|between:1,48'], ['last_name', 'admin::lang.reservations.label_last_name', 'required|between:1,48'], ['email', 'admin::lang.label_email', 'email:filter|max:96'], ['telephone', 'admin::lang.reservations.label_customer_telephone', 'sometimes'], ['reserve_date', 'admin::lang.reservations.label_reservation_date', 'required|valid_date'], ['reserve_time', 'admin::lang.reservations.label_reservation_time', 'required|valid_time'], ['guest_num', 'admin::lang.reservations.label_guest', 'required|integer'], ]; } }
<?php namespace Admin\Requests; use System\Classes\FormRequest; class Reservation extends FormRequest { protected function useDataFrom() { return static::DATA_TYPE_POST; } public function rules() { return [ ['location_id', 'admin::lang.reservations.text_restaurant', 'sometimes|required|integer'], ['first_name', 'admin::lang.reservations.label_first_name', 'required|between:1,48'], ['last_name', 'admin::lang.reservations.label_last_name', 'required|between:1,48'], ['email', 'admin::lang.label_email', 'required|email:filter|max:96'], ['telephone', 'admin::lang.reservations.label_customer_telephone', 'sometimes'], ['reserve_date', 'admin::lang.reservations.label_reservation_date', 'required|valid_date'], ['reserve_time', 'admin::lang.reservations.label_reservation_time', 'required|valid_time'], ['guest_num', 'admin::lang.reservations.label_guest', 'required|integer'], ]; } }
Use threshold for the initial fps state
import React, {Component} from 'react' import collectFps from 'collect-fps' const noop = () => {} export default ({ threshold = 30, fpsCollector = collectFps }) => (Target) => { let endFPSCollection = noop const handleStartFPSCollection = (component) => { if (endFPSCollection !== noop) { endFPSCollection() } endFPSCollection = fpsCollector() } class MonitorAnimationSpeed extends Component { constructor () { super() this.state = {fps: threshold} } render () { return <Target {...this.props} onStartFPSCollection={handleStartFPSCollection} onEndFPSCollection={() => { if (endFPSCollection !== noop) { this.setState({fps: endFPSCollection()}) endFPSCollection = noop } }} lowFPS={this.state.fps < threshold} /> } } MonitorAnimationSpeed.displayName = Target.displayName || Target.name return MonitorAnimationSpeed }
import React, {Component} from 'react' import collectFps from 'collect-fps' const noop = () => {} export default ({ threshold = 30, fpsCollector = collectFps }) => (Target) => { let endFPSCollection = noop const handleStartFPSCollection = (component) => { if (endFPSCollection !== noop) { endFPSCollection() } endFPSCollection = fpsCollector() } class MonitorAnimationSpeed extends Component { constructor () { super() this.state = {fps: 60} } render () { return <Target {...this.props} onStartFPSCollection={handleStartFPSCollection} onEndFPSCollection={() => { if (endFPSCollection !== noop) { this.setState({fps: endFPSCollection()}) endFPSCollection = noop } }} lowFPS={this.state.fps < threshold} /> } } MonitorAnimationSpeed.displayName = Target.displayName || Target.name return MonitorAnimationSpeed }
Configure graceful_timeout to actually do something
import multiprocessing from os import getenv bind = '127.0.0.1:8001' workers = multiprocessing.cpu_count() * 3 graceful_timeout = 15 timeout = 30 threads = multiprocessing.cpu_count() * 3 pidfile = '/var/run/gunicorn.pid' errorlog = '/var/log/gunicorn/gunicorn-error.log' loglevel = 'critical' # Read the DEBUG setting from env var try: if getenv('DOCKER_SAL_DEBUG').lower() == 'true': accesslog = '/var/log/gunicorn/gunicorn-access.log' loglevel = 'info' except Exception: pass # Protect against memory leaks by restarting each worker every 1000 # requests, with a randomized jitter of 0-50 requests. max_requests = 1000 max_requests_jitter = 50 worker_class = 'gevent'
import multiprocessing from os import getenv bind = '127.0.0.1:8001' workers = multiprocessing.cpu_count() * 3 # graceful_timeout = 600 # timeout = 60 threads = multiprocessing.cpu_count() * 3 # max_requests = 300 pidfile = '/var/run/gunicorn.pid' # max_requests_jitter = 50 errorlog = '/var/log/gunicorn/gunicorn-error.log' loglevel = 'critical' # Read the DEBUG setting from env var try: if getenv('DOCKER_SAL_DEBUG').lower() == 'true': accesslog = '/var/log/gunicorn/gunicorn-access.log' loglevel = 'info' except Exception: pass # Protect against memory leaks by restarting each worker every 1000 # requests, with a randomized jitter of 0-50 requests. max_requests = 1000 max_requests_jitter = 50 worker_class = 'gevent'
Update API to support datasources
// +build !noglobals package inj ////////////////////////////////////////////// // Interface definitions ////////////////////////////////////////////// // A Grapher is anything that can represent an application graph type Grapher interface { Provide(inputs ...interface{}) error Inject(fn interface{}, args ...interface{}) Assert() (valid bool, errors []string) AddDatasource(...interface{}) error } ////////////////////////////////////////////// // The one true global variable ////////////////////////////////////////////// // A default grapher to use in the public API var graph Grapher = NewGraph() // Fetch the current grapher instance func GetGrapher() Grapher { return graph } // Set a specific grapher instance func SetGrapher(g Grapher) { graph = g } ////////////////////////////////////////////// // Public API ////////////////////////////////////////////// // Insert a set of arbitrary objects into the // application graph func Provide(inputs ...interface{}) error { return graph.Provide(inputs...) } // Given a function, call it with arguments assigned // from the graph. Additional arguments can be provided // for the sake of utility. func Inject(fn interface{}, args ...interface{}) { graph.Inject(fn, args...) } // Make sure that all provided dependencies have their // requirements met, and return a list of errors if they // don't. func Assert() (valid bool, errors []string) { return graph.Assert() } // Add zero or more datasources to the global graph func AddDatasource(ds ...interface{}) error { return graph.AddDatasource(ds) }
// +build !noglobals package inj ////////////////////////////////////////////// // Interface definitions ////////////////////////////////////////////// // A Grapher is anything that can represent an application graph type Grapher interface { Provide(inputs ...interface{}) error Inject(fn interface{}, args ...interface{}) Assert() (valid bool, errors []string) } ////////////////////////////////////////////// // The one true global variable ////////////////////////////////////////////// // A default grapher to use in the public API var graph Grapher = NewGraph() // Fetch the current grapher instance func GetGrapher() Grapher { return graph } // Set a specific grapher instance func SetGrapher(g Grapher) { graph = g } ////////////////////////////////////////////// // Public API ////////////////////////////////////////////// // Insert a set of arbitrary objects into the // application graph func Provide(inputs ...interface{}) error { return graph.Provide(inputs...) } // Given a function, call it with arguments assigned // from the graph. Additional arguments can be provided // for the sake of utility. func Inject(fn interface{}, args ...interface{}) { graph.Inject(fn, args...) } // Make sure that all provided dependencies have their // requirements met, and return a list of errors if they // don't. func Assert() (valid bool, errors []string) { return graph.Assert() }
Move string above the imports so it becomes a docstring
#!/usr/bin/env python """ Simple AFP mock to allow testing the afp-cli. """ from bottle import route from textwrap import dedent from bottledaemon import daemon_run @route('/account') def account(): return """{"test_account": ["test_role"]}""" @route('/account/<account>/<role>') def credentials(account, role): return dedent(""" {"Code": "Success", "LastUpdated": "1970-01-01T00:00:00Z", "AccessKeyId": "XXXXXXXXXXXX", "SecretAccessKey": "XXXXXXXXXXXX", "Token": "XXXXXXXXXXXX", "Expiration": "2032-01-01T00:00:00Z", "Type": "AWS-HMAC"}""").strip() daemon_run(host='localhost', port=5555)
#!/usr/bin/env python from bottle import route from textwrap import dedent from bottledaemon import daemon_run """ Simple AFP mock to allow testing the afp-cli. """ @route('/account') def account(): return """{"test_account": ["test_role"]}""" @route('/account/<account>/<role>') def credentials(account, role): return dedent(""" {"Code": "Success", "LastUpdated": "1970-01-01T00:00:00Z", "AccessKeyId": "XXXXXXXXXXXX", "SecretAccessKey": "XXXXXXXXXXXX", "Token": "XXXXXXXXXXXX", "Expiration": "2032-01-01T00:00:00Z", "Type": "AWS-HMAC"}""").strip() daemon_run(host='localhost', port=5555)
Add regex to validate email in user schema
var mongoose = require('mongoose'), urlFormatter = require('../../app/models/url_formatter.server.model'), Schema = mongoose.Schema; var UserSchema = new Schema({ firstName: String, lastName: String, email: { type: String, index: true, match: /.+\@.+\..+/ }, username: { type: String, trim: true, unique: true, required: true }, password: String, created: { type: Date, default: Date.now }, website: { type: String, set: urlFormatter.addHttpIfNotPresent, get: urlFormatter.addHttpIfNotPresent } }); UserSchema.virtual('fullName').get(function() { return this.firstName + ' ' + this.lastName; }); // You add Static methods this way /*UserSchema.statics.findOneByUsername = function (username, callback) { this.findOne({ username: new RegExp(username, 'i') }, callback); };*/ // You add instance methods this way /*UserSchema.methods.authenticate = function(password) { return this.password === password; };*/ UserSchema.set('toJSON', { getters: true , virtuals: true }); mongoose.model('User', UserSchema);
var mongoose = require('mongoose'), urlFormatter = require('../../app/models/url_formatter.server.model'), Schema = mongoose.Schema; var UserSchema = new Schema({ firstName: String, lastName: String, email: { type: String, index: true }, username: { type: String, trim: true, unique: true, required: true }, password: String, created: { type: Date, default: Date.now }, website: { type: String, set: urlFormatter.addHttpIfNotPresent, get: urlFormatter.addHttpIfNotPresent } }); UserSchema.virtual('fullName').get(function() { return this.firstName + ' ' + this.lastName; }); // You add Static methods this way /*UserSchema.statics.findOneByUsername = function (username, callback) { this.findOne({ username: new RegExp(username, 'i') }, callback); };*/ // You add instance methods this way /*UserSchema.methods.authenticate = function(password) { return this.password === password; };*/ UserSchema.set('toJSON', { getters: true , virtuals: true }); mongoose.model('User', UserSchema);
Make sphinx building actually work
from distutils.core import setup version = '1.0.2' # If sphinx is installed, enable the command try: from sphinx.setup_command import BuildDoc cmdclass = {'build_sphinx': BuildDoc} command_options = { 'build_sphinx': { 'version': ('setup.py', version), 'release': ('setup.py', version), } } except ImportError: cmdclass = {} command_options = {} setup(name='simplemediawiki', version=version, description='Extremely low-level wrapper to the MediaWiki API', author='Ian Weller', author_email='iweller@redhat.com', url='https://github.com/ianweller/python-simplemediawiki', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public ' 'License (LGPL)', ], requires=[ 'kitchen', 'simplejson', ], py_modules=['simplemediawiki'], cmdclass=cmdclass, command_options=command_options)
from distutils.core import setup # If sphinx is installed, enable the command try: from sphinx.setup_command import BuildDoc cmdclass = {'build_sphinx': BuildDoc} command_options = { 'build_sphinx': { 'version': ('setup.py', version), 'release': ('setup.py', version), } } except ImportError: cmdclass = {} command_options = {} version = '1.0.2' setup(name='simplemediawiki', version=version, description='Extremely low-level wrapper to the MediaWiki API', author='Ian Weller', author_email='iweller@redhat.com', url='https://github.com/ianweller/python-simplemediawiki', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public ' 'License (LGPL)', ], requires=[ 'kitchen', 'simplejson', ], py_modules=['simplemediawiki'], cmdclass=cmdclass, command_options=command_options)
Replace the placeholder in the live demo
"""Insert the demo into the codemirror site.""" import os import fileinput import shutil proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) code_mirror_path = os.path.join( proselint_path, "plugins", "webeditor") code_mirror_demo_path = os.path.join(code_mirror_path, "index.html") live_write_path = os.path.join(proselint_path, "site", "write") shutil.copytree(code_mirror_path, live_write_path) demo_path = os.path.join(proselint_path, "demo.md") with open(demo_path, "r") as f: demo = f.read() for line in fileinput.input( os.path.join(live_write_path, "index.html"), inplace=True): if "##DEMO_PLACEHOLDER##" in line: print demo, else: print line,
"""Insert the demo into the codemirror site.""" import os import fileinput import shutil proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) code_mirror_path = os.path.join( proselint_path, "plugins", "webeditor") code_mirror_demo_path = os.path.join(code_mirror_path, "index.html") live_write_path = os.path.join(proselint_path, "site", "write") shutil.copytree(code_mirror_path, live_write_path) demo_path = os.path.join(proselint_path, "demo.md") with open(demo_path, "r") as f: demo = f.read() for line in fileinput.input(code_mirror_demo_path, inplace=True): if "##DEMO_PLACEHOLDER##" in line: print demo, else: print line,
Fix regression: 'import pytest' error when starting adhocracy
""" Catalog utilities.""" from substanced import catalog from substanced.interfaces import IIndexingActionProcessor from zope.interface import Interface @catalog.catalog_factory('adhocracy') class AdhocracyCatalogFactory: tag = catalog.Keyword() def includeme(config): """Register catalog utilities.""" config.add_view_predicate('catalogable', catalog._CatalogablePredicate) config.add_directive('add_catalog_factory', catalog.add_catalog_factory) config.add_directive('add_indexview', catalog.add_indexview, action_wrap=False) config.registry.registerAdapter(catalog.deferred.BasicActionProcessor, (Interface,), IIndexingActionProcessor) config.scan('substanced.catalog') config.add_catalog_factory('adhocracy', AdhocracyCatalogFactory)
""" Catalog utilities.""" from substanced import catalog from substanced.interfaces import IIndexingActionProcessor from zope.interface import Interface @catalog.catalog_factory('adhocracy') class AdhocracyCatalogFactory: tag = catalog.Keyword() def includeme(config): """Register catalog utilities.""" config.add_view_predicate('catalogable', catalog._CatalogablePredicate) config.add_directive('add_catalog_factory', catalog.add_catalog_factory) config.add_directive('add_indexview', catalog.add_indexview, action_wrap=False) config.registry.registerAdapter(catalog.deferred.BasicActionProcessor, (Interface,), IIndexingActionProcessor) config.scan('substanced.catalog') config.scan('.')
Make 'name' and 'index' columns non-nullable for IndexFile model
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String, nullable=False) index = Column(String, nullable=False) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \ f"size={self.size} "
import enum from sqlalchemy import Column, Integer, String, Enum from virtool.pg.utils import Base, SQLEnum class IndexType(str, SQLEnum): """ Enumerated type for index file types """ json = "json" fasta = "fasta" bowtie2 = "bowtie2" class IndexFile(Base): """ SQL model to store new index files """ __tablename__ = "index_files" id = Column(Integer, primary_key=True) name = Column(String) index = Column(String) type = Column(Enum(IndexType)) size = Column(Integer) def __repr__(self): return f"<IndexFile(id={self.id}, name={self.name}, index={self.index}, type={self.type}, " \ f"size={self.size} "
[eslint] Remove no-else-return from being checked Test Plan: - You can write if (something) { return somethingElse; else { return somethingElseEntirely; } without eslint getting mad about the else Change-Id: I92e5bbb2d9dbaed5a903986b7bbfe9f7e5518a62 Reviewed-on: https://gerrit.instructure.com/108037 Reviewed-by: Eric Coan <e4674042a0b1aef8cb92a5ded6745c5cf4620423@instructure.com> Tested-by: Jenkins Reviewed-by: Andrew Huff <b334cc62d1472ff334a155064665c29200a80f59@instructure.com> Reviewed-by: Ryan Shaw <ea3cd978650417470535f3a4725b6b5042a6ab59@instructure.com> Product-Review: Ryan Shaw <ea3cd978650417470535f3a4725b6b5042a6ab59@instructure.com> QA-Review: Ryan Shaw <ea3cd978650417470535f3a4725b6b5042a6ab59@instructure.com>
/* * This file can be used to convey information to other eslint files inside * Canvas. */ module.exports = { globals: { ENV: true, INST: true, }, plugins: [ "promise", "import" ], // 0 - off, 1 - warning, 2 - error rules: { "class-methods-use-this": [0], "comma-dangle": [2, "only-multiline"], "func-names": [0], "max-len": [1, {"code": 140}], "no-continue": [0], "no-else-return": [0], "no-plusplus": [0], "no-underscore-dangle": [0], "no-unused-vars": [2, { "argsIgnorePattern": "^_"}], "object-curly-spacing": [0], "semi": [0], "space-before-function-paren": [2, "always"], // allows 'i18n!webzip_exports' and 'compiled/foo/bar' "import/no-extraneous-dependencies": [0], "import/named": [2], "import/no-unresolved": [0], "import/no-webpack-loader-syntax": [0], "import/no-commonjs": [2], "react/jsx-filename-extension": [2, { "extensions": [".js"] }], "import/extensions": [1, { "js": "never", "jsx": "never", "json": "always" }], "promise/avoid-new": [0], } };
/* * This file can be used to convey information to other eslint files inside * Canvas. */ module.exports = { globals: { ENV: true, INST: true, }, plugins: [ "promise", "import" ], // 0 - off, 1 - warning, 2 - error rules: { "class-methods-use-this": [0], "comma-dangle": [2, "only-multiline"], "func-names": [0], "max-len": [1, {"code": 140}], "no-continue": [0], "no-plusplus": [0], "no-underscore-dangle": [0], "no-unused-vars": [2, { "argsIgnorePattern": "^_"}], "object-curly-spacing": [0], "semi": [0], "space-before-function-paren": [2, "always"], // allows 'i18n!webzip_exports' and 'compiled/foo/bar' "import/no-extraneous-dependencies": [0], "import/named": [2], "import/no-unresolved": [0], "import/no-webpack-loader-syntax": [0], "import/no-commonjs": [2], "react/jsx-filename-extension": [2, { "extensions": [".js"] }], "import/extensions": [1, { "js": "never", "jsx": "never", "json": "always" }], "promise/avoid-new": [0], } };
Disable dropdown when question marked as answered
$(document).ready(function() { $(document).on('change', '.question-answered-box', function(){ the_id = $(this).data('the-id') text_answer_field = $(this).closest('.text-answer').find('.text-answer-field') if($(this).prop('checked')) { $(text_answer_field).attr("readonly", true) $(text_answer_field).addClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", true) $("li.answer-option-"+the_id+" textarea").attr("disabled", true) $("select#answers_"+the_id).attr("disabled", true) } else { $(text_answer_field).attr("disabled", false) $(text_answer_field).attr("readonly", false) $(text_answer_field).removeClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", false) $("li.answer-option-"+the_id+" textarea").attr("disabled", false) $("select#answers_"+the_id).attr("disabled", false) $('.sticky_save_all').click(); } }); });
$(document).ready(function() { $(document).on('change', '.question-answered-box', function(){ the_id = $(this).data('the-id') text_answer_field = $(this).closest('.text-answer').find('.text-answer-field') if($(this).prop('checked')) { $(text_answer_field).attr("readonly", true) $(text_answer_field).addClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", true) $("li.answer-option-"+the_id+" textarea").attr("disabled", true) } else { $(text_answer_field).attr("disabled", false) $(text_answer_field).attr("readonly", false) $(text_answer_field).removeClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", false) $("li.answer-option-"+the_id+" textarea").attr("disabled", false) $('.sticky_save_all').click(); } }); });
Add skip attribute for CayleyClient send test.
from unittest import TestCase import unittest from pyley import CayleyClient, GraphObject class CayleyClientTests(TestCase): @unittest.skip('Disabled for now!') def test_send(self): client = CayleyClient() g = GraphObject() query = g.V().Has("name", "Casablanca") \ .Out("/film/film/starring") \ .Out("/film/performance/actor") \ .Out("name") \ .All() response = client.Send(query) print response.result self.assertTrue(response.r.status_code == 200) self.assertTrue(response.r is not None) self.assertTrue(len(response.result) > 0)
from unittest import TestCase from pyley import CayleyClient, GraphObject class CayleyClientTests(TestCase): def test_send(self): client = CayleyClient() g = GraphObject() query = g.V().Has("name", "Casablanca") \ .Out("/film/film/starring") \ .Out("/film/performance/actor") \ .Out("name") \ .All() response = client.Send(query) print response.result self.assertTrue(response.r.status_code == 200) self.assertTrue(response.r is not None) self.assertTrue(len(response.result) > 0)
Fix Argcomplete Tests on Python <3.2
"""Tests for cement.ext.ext_argcomplete.""" import os from cement.ext import ext_argcomplete from cement.ext.ext_argparse import ArgparseController, expose from cement.utils import test from cement.utils.misc import rando APP = rando()[:12] class MyBaseController(ArgparseController): class Meta: label = 'base' @expose() def default(self): pass class ArgcompleteExtTestCase(test.CementExtTestCase): def setUp(self): super(ArgcompleteExtTestCase, self).setUp() self.app = self.make_app(APP, argv=['default'], base_controller=MyBaseController, extensions=[ 'argparse', 'argcomplete' ], ) def test_argcomplete(self): # not really sure how to test this for reals... but let's atleast get # coverage with self.app as app: app.run()
"""Tests for cement.ext.ext_argcomplete.""" import os from cement.ext import ext_argcomplete from cement.ext.ext_argparse import ArgparseController, expose from cement.utils import test from cement.utils.misc import rando APP = rando()[:12] class MyBaseController(ArgparseController): class Meta: label = 'base' @expose() def default(self): pass class ArgcompleteExtTestCase(test.CementExtTestCase): def setUp(self): super(ArgcompleteExtTestCase, self).setUp() self.app = self.make_app(APP, base_controller=MyBaseController, extensions=[ 'argparse', 'argcomplete' ], ) def test_argcomplete(self): # not really sure how to test this for reals... but let's atleast get # coverage with self.app as app: app.run()
Fix mess-up with variable names.
var util = require('util'), events = require('events'); function Carrier(reader, listener, encoding, separator) { var self = this; self.reader = reader; if (!separator) { separator = /\r?\n/; } if (listener) { self.addListener('line', listener); } var buffer = ''; reader.setEncoding(encoding || 'utf8'); reader.on('data', function(data) { var lines = data.split(separator); lines[0] = buffer + lines[0]; buffer = lines.pop(); lines.forEach(function(line, index) { self.emit('line', line); }); }); var ender = function() { if (buffer.length > 0) { self.emit('line', buffer); buffer = ''; } self.emit('end'); } reader.on('end', ender); } util.inherits(Carrier, events.EventEmitter); exports.carry = function(reader, listener, encoding, separator) { return new Carrier(reader, listener, encoding, separator); }
var util = require('util'), events = require('events'); function Carrier(reader, listener, encoding, separator) { var self = this; self.reader = reader; if (!separator) { separator = /\r?\n/; } if (listener) { self.addListener('line', listener); } var buffer = ''; reader.setEncoding(encoding || 'utf8'); reader.on('data', function(data) { var lines = data.split(separator); data[0] = buffer + data[0]; buffer = lines.pop(); lines.forEach(function(line, index) { self.emit('line', line); }); }); var ender = function() { if (buffer.length > 0) { self.emit('line', buffer); buffer = ''; } self.emit('end'); } reader.on('end', ender); } util.inherits(Carrier, events.EventEmitter); exports.carry = function(reader, listener, encoding, separator) { return new Carrier(reader, listener, encoding, separator); }
Set callback param to false
<?php use Proud\Core; class Submenu extends Core\ProudWidget { function __construct() { parent::__construct( 'submenu', // Base ID __( 'Submenu', 'wp-agency' ), // Name array( 'description' => __( "Display a submenu", 'wp-agency' ), ) // Args ); } function initialize() { } /** * Outputs the content of the widget * * @param array $args * @param array $instance */ public function printWidget( $args, $instance ) { global $pageInfo; if ( $pageInfo['parent_link'] > 0 ) { $args = array( 'menu' => $pageInfo['menu'], 'submenu' => $pageInfo['parent_link'], 'menu_class' => 'nav nav-pills nav-stacked submenu', 'fallback_cb' => false, ); wp_nav_menu( $args ); } } } // register Foo_Widget widget function register_submenu_widget() { register_widget( 'Submenu' ); } add_action( 'widgets_init', 'register_submenu_widget' );
<?php use Proud\Core; class Submenu extends Core\ProudWidget { function __construct() { parent::__construct( 'submenu', // Base ID __( 'Submenu', 'wp-agency' ), // Name array( 'description' => __( "Display a submenu", 'wp-agency' ), ) // Args ); } function initialize() { } /** * Outputs the content of the widget * * @param array $args * @param array $instance */ public function printWidget( $args, $instance ) { global $pageInfo; if ( $pageInfo['parent_link'] > 0 ) { $args = array( 'menu' => $pageInfo['menu'], 'submenu' => $pageInfo['parent_link'], 'menu_class' => 'nav nav-pills nav-stacked', ); wp_nav_menu( $args ); } } } // register Foo_Widget widget function register_submenu_widget() { register_widget( 'Submenu' ); } add_action( 'widgets_init', 'register_submenu_widget' );
Fix check that would crash if folder didn’t contain a package.json file
import { join } from 'path' import { statSync } from 'fs' import buildWebpackConfig from './config/build-webpack-config' import buildKarmaConfig from './config/build-karma-config' import startDevelop from './action/start-develop' import runTest from './action/run-test' import install from './action/install' import json from './util/json' export default { develop (env, options) { check(env) const webpackConfig = buildWebpackConfig(env, options) startDevelop(webpackConfig) }, test (env, options) { check(env) const webpackConfig = buildWebpackConfig(env, options) const karmaConfig = buildKarmaConfig(env, options, webpackConfig) runTest(karmaConfig) }, install (env, options) { check(env) install(env.projectPath) } } function check ({ projectPath }) { const packagePath = join(projectPath, 'package.json') if (!fileExists(packagePath)) throw new InvalidUsage() const packageJSON = json.read(packagePath) if (packageJSON.name === 'sagui') throw new InvalidUsage() } function fileExists (file) { try { statSync(file) return true } catch (e) { return false } } export class InvalidUsage extends Error { constructor () { super() this.name = 'InvalidUsage' } }
import { join } from 'path' import buildWebpackConfig from './config/build-webpack-config' import buildKarmaConfig from './config/build-karma-config' import startDevelop from './action/start-develop' import runTest from './action/run-test' import install from './action/install' import json from './util/json' export default { develop (env, options) { check(env) const webpackConfig = buildWebpackConfig(env, options) startDevelop(webpackConfig) }, test (env, options) { check(env) const webpackConfig = buildWebpackConfig(env, options) const karmaConfig = buildKarmaConfig(env, options, webpackConfig) runTest(karmaConfig) }, install (env, options) { check(env) install(env.projectPath) } } function check ({ projectPath }) { const packagePath = join(projectPath, 'package.json') const packageJSON = json.read(packagePath) if (packageJSON.name === 'sagui') throw new InvalidUsage() } export class InvalidUsage extends Error { constructor () { super() this.name = 'InvalidUsage' } }
feat(example): Remove dev code in production
const path = require('path') const webpack = require('webpack') module.exports = { entry: './src/index.js', output: { filename: './bundle.js', path: path.resolve('public') }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin(), new webpack.IgnorePlugin(/\.dev$/, /lingui-i18n/) ], devServer: { hot: true, inline: true, contentBase: path.resolve('public') } }
const path = require('path') const webpack = require('webpack') module.exports = { entry: './src/index.js', output: { filename: './bundle.js', path: path.resolve('public') }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.IgnorePlugin(/(languageData|compile).*\.dev$/) ], devServer: { hot: true, inline: true, contentBase: path.resolve('public') } }
Add back offline emitting that mysteriously disappeared
'use strict'; import { log, LOG_TYPES } from './log'; import config from './config'; import { io, EVENT_TYPES } from './socketIO'; let peerJSOptions = config.peerJSOptions; export default function (server, app) { let ExpressPeerServer = require('peer').ExpressPeerServer(server, peerJSOptions); ExpressPeerServer.on('connection', (id) => { log('PeerJS Connection from: ' + id); //TODO: Proper way of doing online contacts, not this! io.emit(EVENT_TYPES.CONTACT_ONLINE, { peerJSId: id }); }); ExpressPeerServer.on('disconnect', (id) => { log('PeerJS Disconnection from: ' + id, LOG_TYPES.WARN); io.emit(EVENT_TYPES.CONTACT_OFFLINE, { peerJSId: id }); }); app.use('/peerjs', ExpressPeerServer); }
'use strict'; import { log, LOG_TYPES } from './log'; import config from './config'; import { io, EVENT_TYPES } from './socketIO'; let peerJSOptions = config.peerJSOptions; export default function (server, app) { let ExpressPeerServer = require('peer').ExpressPeerServer(server, peerJSOptions); ExpressPeerServer.on('connection', (id) => { log('PeerJS Connection from: ' + id); //TODO: Proper way of doing online contacts, not this! io.emit(EVENT_TYPES.CONTACT_ONLINE, { peerJSId: id }); }); ExpressPeerServer.on('disconnect', (id) => { log('PeerJS Disconnection from: ' + id, LOG_TYPES.WARN); }); app.use('/peerjs', ExpressPeerServer); }
Add comments describing the build status enum
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 org.jboss.pnc.model; /** * Status of a running or completed build. * * @author Jakub Bartecek &lt;jbartece@redhat.com&gt; * */ public enum BuildStatus { /** * Build completed successfully */ SUCCESS, /** * Build failed */ FAILED, /** * Build completed with test failures */ UNSTABLE, /** * Build currently running */ BUILDING, /** * Build rejected due to conflict with another build, or failed dependency build */ REJECTED, /** * User cancelled the build */ CANCELLED, /** * A system error prevented the build from completing */ SYSTEM_ERROR, /** * It is not known what the build status is at this time */ UNKNOWN }
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 org.jboss.pnc.model; /** * Statuses of build process. * * @author Jakub Bartecek &lt;jbartece@redhat.com&gt; * */ public enum BuildStatus { SUCCESS, FAILED, UNSTABLE, BUILDING, REJECTED, CANCELLED, SYSTEM_ERROR, UNKNOWN }
refactor: Fix a hard coding of the configuration file name
#!/usr/bin/env node const co = require('co'); const util = require('./lib/util'); const m = require('./lib/main'); const initCommand = require('./lib/init.cmd'); const constants = require('./lib/constants'); const main = function* (argv) { if (argv.help) { return util.writeLn(yield util.help()); } if (argv.version) { return util.writeLn(yield util.version()); } if (argv._.length && argv._[0] === 'init') { return yield initCommand(); } const config = yield util.findConf(process.cwd(), constants.CONFIG_FILE_NAME); if (!config) { util.writeLn(`Error: ${constants.CONFIG_FILE_NAME} is not found`); process.exit(1); } config.config = util.setDefaultConf(config.config); for (const key in config.config.keys) { yield m.main(key, config); } }; if (!module.parent) { co(function* () { const argv = util.parseArg(); yield main(argv); }); }
#!/usr/bin/env node const co = require('co'); const util = require('./lib/util'); const m = require('./lib/main'); const initCommand = require('./lib/init.cmd'); const constants = require('./lib/constants'); const main = function* (argv) { if (argv.help) { return util.writeLn(yield util.help()); } if (argv.version) { return util.writeLn(yield util.version()); } if (argv._.length && argv._[0] === 'init') { return yield initCommand(); } const config = yield util.findConf(process.cwd(), constants.CONFIG_FILE_NAME); if (!config) { util.writeLn('Error: ssh-seed.yml is not found'); process.exit(1); } config.config = util.setDefaultConf(config.config); for (const key in config.config.keys) { yield m.main(key, config); } }; if (!module.parent) { co(function* () { const argv = util.parseArg(); yield main(argv); }); }
Add cache dependency to improve web requests Also add filecache optional to control locks.
from setuptools import setup, find_packages setup(name='tst', version='0.9a18', description='TST Student Testing', url='http://github.com/daltonserey/tst', author='Dalton Serey', author_email='daltonserey@gmail.com', license='MIT', packages=find_packages(), include_package_data=True, scripts=[ 'bin/runjava', 'bin/tst', 'commands/tst-test', 'commands/tst-completion', 'commands/tst-config', 'commands/tst-status', 'commands/tst-checkout', 'commands/tst-checkout2', 'commands/tst-commit', 'commands/tst-delete', 'commands/tst-login', 'commands/tst-new', ], install_requires=[ 'pyyaml', 'requests', 'cachecontrol[filecache]' ], entry_points = { 'console_scripts': [ 'tst=tst.commands:main', ] }, zip_safe=False)
from setuptools import setup, find_packages setup(name='tst', version='0.9a18', description='TST Student Testing', url='http://github.com/daltonserey/tst', author='Dalton Serey', author_email='daltonserey@gmail.com', license='MIT', packages=find_packages(), include_package_data=True, scripts=[ 'bin/runjava', 'bin/tst', 'commands/tst-test', 'commands/tst-completion', 'commands/tst-config', 'commands/tst-status', 'commands/tst-checkout', 'commands/tst-checkout2', 'commands/tst-commit', 'commands/tst-delete', 'commands/tst-login', 'commands/tst-new', ], install_requires=[ 'pyyaml', 'requests' ], entry_points = { 'console_scripts': [ 'tst=tst.commands:main', ] }, zip_safe=False)
Fix for https ajax request update payment plans
<?php /** * Created by PhpStorm. * User: jesper * Date: 2015-01-27 * Time: 15:52 */ class Billmate_PartPayment_Block_Adminhtml_System_Config_Form_Updateplans extends Mage_Adminhtml_Block_System_Config_Form_Field { protected function _construct() { parent::_construct(); $this->setTemplate('billmate/system/config/updateplans.phtml'); } protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element) { return $this->_toHtml(); } public function getAjaxCheckUrl() { return Mage::helper('adminhtml')->getUrl('adminhtml/adminhtml_billmatepartpayment/updateplans',array('_secure' => true)); } public function getButtonHtml() { $button = $this->getLayout()->createBlock('adminhtml/widget_button') ->setData(array( 'id' => 'partpayment_update', 'label' => $this->helper('adminhtml')->__('Update'), 'onclick' => 'javascript:updateplans(); return false' )); return $button->toHtml(); } }
<?php /** * Created by PhpStorm. * User: jesper * Date: 2015-01-27 * Time: 15:52 */ class Billmate_PartPayment_Block_Adminhtml_System_Config_Form_Updateplans extends Mage_Adminhtml_Block_System_Config_Form_Field { protected function _construct() { parent::_construct(); $this->setTemplate('billmate/system/config/updateplans.phtml'); } protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element) { return $this->_toHtml(); } public function getAjaxCheckUrl() { return Mage::helper('adminhtml')->getUrl('adminhtml/adminhtml_billmatepartpayment/updateplans'); } public function getButtonHtml() { $button = $this->getLayout()->createBlock('adminhtml/widget_button') ->setData(array( 'id' => 'partpayment_update', 'label' => $this->helper('adminhtml')->__('Update'), 'onclick' => 'javascript:updateplans(); return false' )); return $button->toHtml(); } }
Add path to requirements.txt so installation from pip succeeds cf http://lorenamesa.com/packaging-my-first-python-egg.html
import os from pip.download import PipSession from pip.req import parse_requirements from setuptools import setup BASE_DIR = os.path.dirname(os.path.realpath(__file__)) reqs_file = os.path.join(BASE_DIR, 'requirements.txt') install_reqs = parse_requirements(reqs_file, session=PipSession()) setup( name='aws-portknock', version='0.1', py_modules=['aws_portknock'], description='Port knocking for AWS security groups', author='Michel Alexandre Salim', author_email='michel@michel-slm.name', url='https://github.com/michel-slm/aws-portknock', download_url='https://github.com/michel-slm/aws-portknock/tarball/0.1', keywords=['aws'], classifiers=[], install_requires=[str(r.req) for r in install_reqs], entry_points=''' [console_scripts] aws-portknock=aws_portknock:cli ''', )
from pip.download import PipSession from pip.req import parse_requirements from setuptools import setup setup( name='aws-portknock', version='0.1', py_modules=['aws_portknock'], description='Port knocking for AWS security groups', author='Michel Alexandre Salim', author_email='michel@michel-slm.name', url='https://github.com/michel-slm/aws-portknock', download_url='https://github.com/michel-slm/aws-portknock/tarball/0.1', keywords=['aws'], classifiers=[], install_requires=[str(r.req) for r in parse_requirements( 'requirements.txt', session=PipSession())], entry_points=''' [console_scripts] aws-portknock=aws_portknock:cli ''', )
Remove prefix and use name as procId.
package main import ( "bufio" "io" "log" "regexp" "time" "github.com/logplex/logplexc" ) var prefix = regexp.MustCompile(`^(\[\d*\] [^-*#]+|.*)`) func lineWorker(die dieCh, r *bufio.Reader, cfg logplexc.Config, sr *serveRecord) { cfg.Logplex = sr.u target, err := logplexc.NewClient(&cfg) if err != nil { log.Fatalf("could not create logging client: %v", err) } for { select { case <-die: return default: break } l, _, err := r.ReadLine() l = prefix.ReplaceAll(l, []byte("")) if len(l) > 0 { target.BufferMessage(134, time.Now(), "redis", sr.Name, l) } if err != nil { if err == io.EOF { continue } log.Fatal(err) } } }
package main import ( "bufio" "io" "log" "time" "github.com/logplex/logplexc" ) func lineWorker(die dieCh, r *bufio.Reader, cfg logplexc.Config, sr *serveRecord) { cfg.Logplex = sr.u target, err := logplexc.NewClient(&cfg) if err != nil { log.Fatalf("could not create logging client: %v", err) } for { select { case <-die: return default: break } l, _, err := r.ReadLine() if len(l) > 0 { target.BufferMessage(134, time.Now(), "app", "redis", l) } if err != nil { if err == io.EOF { continue } log.Fatal(err) } } }
Stop the context menu from injecting multiple times. Otherwise this causes an infinite loop on KitKat, since loading more scripts triggers onPageFinished to fire again, which triggers injection of the context menu again, etc.
(function() { 'use strict'; /* global myApp */ /* global appIndexPlaceHolder */ myApp.factory('ContextMenuInjectScript', [ function () { var toInject = function() { if (window.__cordovaAppHarnessData) return; // Short-circuit if I've run on this page before. console.log('Menu script injected.'); var contextScript = document.createElement('script'); contextScript.setAttribute('src', 'app-harness:///cdvahcm/ContextMenu.js'); window.__cordovaAppHarnessData = { 'appIndex': appIndexPlaceHolder, 'appName': 'appNamePlaceHolder' }; document.getElementsByTagName('head')[0].appendChild(contextScript); }; return { getInjectString : function(appName, appIndex) { var string = '\n(' + toInject.toString() + ')();'; string = string.replace('appNamePlaceHolder', appName); string = string.replace('appIndexPlaceHolder', appIndex); return string; } }; }]); })();
(function() { 'use strict'; /* global myApp */ /* global appIndexPlaceHolder */ myApp.factory('ContextMenuInjectScript', [ function () { var toInject = function() { console.log('Menu script injected.'); var contextScript = document.createElement('script'); contextScript.setAttribute('src', 'app-harness:///cdvahcm/ContextMenu.js'); window.__cordovaAppHarnessData = { 'appIndex': appIndexPlaceHolder, 'appName': 'appNamePlaceHolder' }; document.getElementsByTagName('head')[0].appendChild(contextScript); }; return { getInjectString : function(appName, appIndex) { var string = '\n(' + toInject.toString() + ')();'; string = string.replace('appNamePlaceHolder', appName); string = string.replace('appIndexPlaceHolder', appIndex); return string; } }; }]); })();
Load boardsLink from local storage.
/** * Created by xubt on 5/26/16. */ kanbanApp.directive('boardBanner', function () { return { restrict: 'E', templateUrl: 'component/board/partials/board-banner.html', replace: true, controller: ['$scope', '$location', 'boardsService', 'localStorageService', function ($scope, $location, boardsService, localStorageService) { var boardLink = localStorageService.get("boardLink"); var boardsLink = localStorageService.get("identity.userName") + '/boards'; var boardPromise = boardsService.loadBoardByLink(boardLink); boardPromise.then(function (_board) { $scope.board = _board; }); $scope.toBoards = function () { $location.path(boardsLink); }; }] }; });
/** * Created by xubt on 5/26/16. */ kanbanApp.directive('boardBanner', function () { return { restrict: 'E', templateUrl: 'component/board/partials/board-banner.html', replace: true, controller: ['$scope', '$location', 'boardsService', 'localStorageService', function ($scope, $location, boardsService, localStorageService) { var boardLink = localStorageService.get("boardLink"); var boardPromise = boardsService.loadBoardByLink(boardLink); boardPromise.then(function (_board) { $scope.board = _board; }); $scope.toBoards = function () { $location.path('/boards'); }; }] }; });
Fix compilation error in deltaspike quickstart
/* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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 org.jboss.as.quickstarts.deltaspike.exceptionhandling.util; import java.util.logging.Logger; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import javax.faces.context.FacesContext; /** * CDI Resource aliases * * @author <a href="mailto:benevides@redhat.com">Rafael Benevides</a> * */ public class Resources { @Produces public Logger produceLog(InjectionPoint injectionPoint) { return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName()); } @Produces @RequestScoped public FacesContext produceFacesContext() { return FacesContext.getCurrentInstance(); } }
/* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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 org.jboss.as.quickstarts.deltaspike.exceptionhandling.util; import java.util.logging.Logger; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import javax.faces.context.FacesContext; /** * CDI Resource aliases * * @author <a href="mailto:benevides@redhat.com">Rafael Benevides</a> * */ public class Resources { @Produces public Logger produceLog(InjectionPoint injectionPoint) { return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName()); } @Produces @RequestScoped public FacesContext produceFacesContext() { return FacesContext.getCurrentInstance(); } }
Refactor utility method to FunctionalInterfaceCaller
package es.sandbox.spikes.java8.interfaces; import es.sandbox.spikes.java8.InvocationSpy; import org.junit.Before; import org.junit.Test; import static es.sandbox.spikes.java8.FunctionalInterfaceCaller.call; import static es.sandbox.spikes.java8.InvocationSpy.spy; import static org.assertj.core.api.Assertions.assertThat; /** * Created by jeslopalo on 30/12/15. */ public class FunctionalInterfaceSpecs { private InvocationSpy spy; @Before public void setup() { this.spy = spy(); } @Test public void has_one_callable_method() { call(() -> this.spy.invocation()); assertThat(this.spy.invoked()).isTrue(); } }
package es.sandbox.spikes.java8.interfaces; import es.sandbox.spikes.java8.InvocationSpy; import org.junit.Before; import org.junit.Test; import static es.sandbox.spikes.java8.InvocationSpy.spy; import static org.assertj.core.api.Assertions.assertThat; /** * Created by jeslopalo on 30/12/15. */ public class FunctionalInterfaceSpecs { private InvocationSpy spy; private static final void callFunctionalInterface(SimpleFunctionalInterface functionalInterface) { functionalInterface.doWork(); } @Before public void setup() { this.spy = spy(); } @Test public void has_one_callable_method() { callFunctionalInterface(() -> this.spy.invocation()); assertThat(this.spy.invoked()).isTrue(); } }
Fix absence of variable reference
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Notification\Event; use Flarum\Notification\Blueprint\BlueprintInterface; class Sending { /** * The blueprint for the notification. * * @var BlueprintInterface */ public $blueprint; /** * The users that the notification will be sent to. * * @var array */ public $users; /** * @param \Flarum\Notification\Blueprint\BlueprintInterface $blueprint * @param \Flarum\User\User[] $users */ public function __construct(BlueprintInterface $blueprint, array &$users) { $this->blueprint = $blueprint; $this->users = &$users; } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Notification\Event; use Flarum\Notification\Blueprint\BlueprintInterface; class Sending { /** * The blueprint for the notification. * * @var BlueprintInterface */ public $blueprint; /** * The users that the notification will be sent to. * * @var array */ public $users; /** * @param \Flarum\Notification\Blueprint\BlueprintInterface $blueprint * @param \Flarum\User\User[] $users */ public function __construct(BlueprintInterface $blueprint, array &$users) { $this->blueprint = $blueprint; $this->users = $users; } }
Package count chart: fixed labels of x axis
import csv import sqlite3 from flask import Flask, request, render_template, g, jsonify app = Flask(__name__) db_filename = 'db.sqlite' def connect_db(): conn = sqlite3.connect(db_filename) curs = conn.execute('PRAGMA foreign_keys = ON') return conn @app.before_request def before_request(): g.db = connect_db() @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if db is not None: db.close() @app.route('/json') def json(): cur = g.db.execute(''' SELECT strftime('%s', snapshot_time), count(*) FROM snapshot_content sc JOIN snapshot s ON sc.snapshot_id = s.id GROUP BY snapshot_id ORDER BY s.snapshot_time''') data = [(int(unix_timestamp)*1000, count) for unix_timestamp, count in cur] return jsonify({'chart_data': data}) @app.route('/') def index(): return render_template('chart.html') if __name__ == '__main__': app.run(debug=True)
import csv import sqlite3 from flask import Flask, request, render_template, g, jsonify app = Flask(__name__) db_filename = 'db.sqlite' def connect_db(): conn = sqlite3.connect(db_filename) curs = conn.execute('PRAGMA foreign_keys = ON') return conn @app.before_request def before_request(): g.db = connect_db() @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if db is not None: db.close() @app.route('/json') def json(): cur = g.db.execute(''' SELECT snapshot_time, count(*) FROM snapshot_content sc JOIN snapshot s ON sc.snapshot_id = s.id GROUP BY snapshot_id ORDER BY s.snapshot_time''') return jsonify({'chart_data': list(cur)}) @app.route('/') def index(): return render_template('chart.html') if __name__ == '__main__': app.run(debug=True)
Add toggle of loading class to map
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); function startLoading() { $("#map").toggleClass("loading"); loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 500); $("#map").toggleClass("loading"); }
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 500); }
Add use financial resource in ObjectUpdater
<?php namespace AppBundle\Tests\Services; use AppBundle\Tests\Controller\AbstractApiTest; use AppBundle\Document\Dream; use AppBundle\Document\FinancialResource; class ObjectUpdaterTest extends AbstractApiTest { public function testUpdateObject() { $client = static::createClient(); $dreamOld = $client->getContainer() ->get('doctrine_mongodb.odm.document_manager') ->getRepository('AppBundle:Dream') ->findOneBySlug('sunt'); $financial_resource = new FinancialResource(); $financial_resource->setTitle('ex'); $financial_resource->setQuantity(50); $dreamTmp = new Dream(); $dreamTmp->setTitle('test1'); $dreamTmp->setDescription('test2'); $dreamTmp->addDreamFinancialResource($financial_resource); $dreamNew = $client->getContainer()->get('app.services.object_updater')->updateObject($dreamOld, $dreamTmp); $this->assertEquals($dreamNew->getTitle(), $dreamTmp->getTitle()); $this->assertEquals($dreamNew->getDescription(), $dreamTmp->getDescription()); } }
<?php namespace AppBundle\Tests\Services; use AppBundle\Tests\Controller\AbstractApiTest; use AppBundle\Document\Dream; class ObjectUpdaterTest extends AbstractApiTest { public function testUpdateObject() { $client = static::createClient(); $dreamOld = $client->getContainer() ->get('doctrine_mongodb.odm.document_manager') ->getRepository('AppBundle:Dream') ->findOneBySlug('sunt'); $financial_resource = new FinancialResource(); $financial_resource->setTitle('ex'); $financial_resource->setQuantity(50); $dreamTmp = new Dream(); $dreamTmp->setTitle('test1'); $dreamTmp->setDescription('test2'); $dreamTmp->addDreamFinancialResource($financial_resource); $dreamNew = $client->getContainer()->get('app.services.object_updater')->updateObject($dreamOld, $dreamTmp); $this->assertEquals($dreamNew->getTitle(), $dreamTmp->getTitle()); $this->assertEquals($dreamNew->getDescription(), $dreamTmp->getDescription()); } }
Create mongoengine connection when taking phantom snapshots
import os import mongoengine as me import rmc.shared.constants as c import rmc.models as m FILE_DIR = os.path.dirname(os.path.realpath(__file__)) HTML_DIR = os.path.join(c.SHARED_DATA_DIR, 'html_snapshots') me.connect(c.MONGO_DB_RMC, host=c.MONGO_HOST, port=c.MONGO_PORT) def write(file_path, content): ensure_dir(file_path) with open(file_path, 'w') as f: f.write(content) def ensure_dir(file_path): d = os.path.dirname(file_path) if not os.path.exists(d): os.makedirs(d) def generate_urls(): urls = [] # Home page urls.append('') # Course pages for course in m.Course.objects: course_id = course.id urls.append('course/' + course_id) return urls
import os import rmc.shared.constants as c import rmc.models as m FILE_DIR = os.path.dirname(os.path.realpath(__file__)) HTML_DIR = os.path.join(c.SHARED_DATA_DIR, 'html_snapshots') def write(file_path, content): ensure_dir(file_path) with open(file_path, 'w') as f: f.write(content) def ensure_dir(file_path): d = os.path.dirname(file_path) if not os.path.exists(d): os.makedirs(d) def generate_urls(): urls = [] # Home page urls.append('') # Course pages for course in m.Course.objects: course_id = course.id urls.append('course/' + course_id) return urls
Fix variable name in Python snippet
#!/usr/bin/env python """Generate fixtures.""" import os import json import math as m import numpy as np from scipy import special # Get the file path: FILE = os.path.realpath(__file__) # Extract the directory in which this file resides: DIR = os.path.dirname(FILE) def gen(x, name): """Generate fixture data and write to file. # Arguments * `x`: domain * `name::str`: output filename # Examples ``` python python> x = linspace(-1000, 1000, 2001) python> gen(x, \"./data.json\") ``` """ # TODO: generate fixtures # Store data to be written to file as a dictionary: data = { "x": x.tolist(), "expected": y.tolist() } # Based on the script directory, create an output filepath: filepath = os.path.join(DIR, name) with open(filepath, 'w') as outfile: json.dump(data, outfile) def main(): """Generate fixture data.""" gen(x, "TODO") if __name__ == "__main__": main()
#!/usr/bin/env python """Generate fixtures.""" import os import json import math as m import numpy as np from scipy import special # Get the file path: FILE = os.path.realpath(__file__) # Extract the directory in which this file resides: DIR = os.path.dirname(file) def gen(x, name): """Generate fixture data and write to file. # Arguments * `x`: domain * `name::str`: output filename # Examples ``` python python> x = linspace(-1000, 1000, 2001) python> gen(x, \"./data.json\") ``` """ # TODO: generate fixtures # Store data to be written to file as a dictionary: data = { "x": x.tolist(), "expected": y.tolist() } # Based on the script directory, create an output filepath: filepath = os.path.join(DIR, name) with open(filepath, 'w') as outfile: json.dump(data, outfile) def main(): """Generate fixture data.""" gen(x, "TODO") if __name__ == "__main__": main()
Increase lock timeout for refreshing engagement data task
import logging import time from dash.orgs.tasks import org_task logger = logging.getLogger(__name__) @org_task("refresh-engagement-data", 60 * 60 * 4) def refresh_engagement_data(org, since, until): from .models import PollStats start = time.time() time_filters = list(PollStats.DATA_TIME_FILTERS.keys()) segments = list(PollStats.DATA_SEGMENTS.keys()) metrics = list(PollStats.DATA_METRICS.keys()) for time_filter in time_filters: for segment in segments: for metric in metrics: PollStats.refresh_engagement_data(org, metric, segment, time_filter) logger.info( f"Task: refresh_engagement_data org {org.id} in progress for {time.time() - start}s, for time_filter - {time_filter}, segment - {segment}, metric - {metric}" ) PollStats.calculate_average_response_rate(org) logger.info(f"Task: refresh_engagement_data org {org.id} finished in {time.time() - start}s")
import logging import time from dash.orgs.tasks import org_task logger = logging.getLogger(__name__) @org_task("refresh-engagement-data", 60 * 60) def refresh_engagement_data(org, since, until): from .models import PollStats start = time.time() time_filters = list(PollStats.DATA_TIME_FILTERS.keys()) segments = list(PollStats.DATA_SEGMENTS.keys()) metrics = list(PollStats.DATA_METRICS.keys()) for time_filter in time_filters: for segment in segments: for metric in metrics: PollStats.refresh_engagement_data(org, metric, segment, time_filter) logger.info( f"Task: refresh_engagement_data org {org.id} in progress for {time.time() - start}s, for time_filter - {time_filter}, segment - {segment}, metric - {metric}" ) PollStats.calculate_average_response_rate(org) logger.info(f"Task: refresh_engagement_data org {org.id} finished in {time.time() - start}s")
Update the gulp config, test only the main module
var gulp = require('gulp'); var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); var docco = require('gulp-docco'); var del = require('del'); gulp.task('docs', function () { del(['./docs'], function() { gulp.src('./lib/telegram.link.js') .pipe(docco(/*{'layout': 'linear'}*/)) .pipe(gulp.dest('./docs')); }); }); gulp.task('quality', function () { return gulp.src('./lib/**') .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('test', function () { return gulp.src('./test/telegram.link.test.js') .pipe(mocha({reporter: 'mocha-better-spec-reporter', timeout: '20s'})); }); gulp.task('cover', function () { return gulp.src('./test/telegram.link.test.js') .pipe(mocha({reporter: 'mocha-lcov-reporter', timeout: '120s'})); }); gulp.task('default', ['quality', 'test']);
var gulp = require('gulp'); var jshint = require('gulp-jshint'); var mocha = require('gulp-mocha'); var docco = require('gulp-docco'); var del = require('del'); gulp.task('docs', function () { del(['./docs'], function() { gulp.src('./lib/telegram.link.js') .pipe(docco(/*{'layout': 'linear'}*/)) .pipe(gulp.dest('./docs')); }); }); gulp.task('quality', function () { return gulp.src('./lib/**') .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('test', function () { return gulp.src('./test/*.js') .pipe(mocha({reporter: 'mocha-better-spec-reporter', timeout: '20s'})); }); gulp.task('cover', function () { return gulp.src('./test/*.js') .pipe(mocha({reporter: 'mocha-lcov-reporter', timeout: '120s'})); }); gulp.task('default', ['quality', 'test']);
Hide errors for when database not connected
<?php namespace App\Providers; use App\Meetup; use Illuminate\Support\ServiceProvider; use Barryvdh\Debugbar\ServiceProvider as DebugbarServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { if ($this->app->environment() == 'local') { $this->app->register(DebugbarServiceProvider::class); } if (config('app.force_https')) { $this->app['url']->forceScheme('https'); } $this->registerGlobalViewVariables(); } /** * Register any application services. * * @return void */ public function register() { // } protected function registerGlobalViewVariables() { try { $group = (new Meetup)->groupDetailsWithNextEvent(); $next_event = $group->get('next_event'); view()->share('meetup__group', $group); view()->share('meetup__next_event', $next_event); } catch (\Exception $e) { // Fails likely because database connection! } } }
<?php namespace App\Providers; use App\Meetup; use Illuminate\Support\ServiceProvider; use Barryvdh\Debugbar\ServiceProvider as DebugbarServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { if ($this->app->environment() == 'local') { $this->app->register(DebugbarServiceProvider::class); } if (config('app.force_https')) { $this->app['url']->forceScheme('https'); } $this->registerGlobalViewVariables(); } /** * Register any application services. * * @return void */ public function register() { // } protected function registerGlobalViewVariables() { $group = (new Meetup)->groupDetailsWithNextEvent(); $next_event = $group->get('next_event'); view()->share('meetup__group', $group); view()->share('meetup__next_event', $next_event); } }
Make exec play nicely with gulp
'use strict'; const { exec } = require('child_process'); const gutil = require('gulp-util'); module.exports = (gulp) => { /** * Sync the site (_site/) with the S3 bucket */ gulp.task('deploy:site', (cb) => { const command = 'aws s3 sync _site/ s3://www.westeleventh.media/'; return exec(command, (error, stdout, stderr) => { gutil.log(stdout); gutil.log(gutil.colors.magenta(stderr)); cb(error); }); }); /** * Sync the _audio/final folder with the S3 bucket */ gulp.task('deploy:audio', (cb) => { const command = 'aws s3 sync _audio/final/ s3://episodes.westeleventh.media/ --acl \'public-read\''; return exec(command, (error, stdout, stderr) => { gutil.log(stdout); gutil.log(gutil.colors.magenta(stderr)); cb(error); }); }); };
'use strict'; const { exec } = require('child_process'); const gutil = require('gulp-util'); module.exports = (gulp) => { /** * Sync the site (_site/) with the S3 bucket */ gulp.task('deploy:site', () => { const command = 'aws s3 sync _site/ s3://www.westeleventh.media/'; exec(command, (error, stdout, stderr) => { if (error) { gutil.log(gutil.colors.magenta(`exec error: ${error}`)); return; } gutil.log(stdout); gutil.log(gutil.colors.magenta(stderr)); }); }); /** * Sync the _audio/final folder with the S3 bucket */ gulp.task('deploy:audio', () => { const command = 'aws s3 sync _audio/final/ s3://episodes.westeleventh.media/ --acl \'public-read\''; exec(command, (error, stdout, stderr) => { if (error) { gutil.log(gutil.colors.magenta(`exec error: ${error}`)); return; } gutil.log(stdout); gutil.log(gutil.colors.magenta(stderr)); }); }); };
Remove package namespace in the URLS since it was useless.
from django.conf.urls.defaults import * from piston.resource import Resource from pony_server.api.handlers import PackageHandler, RootHandler, BuildHandler, TagHandler package_handler = Resource(PackageHandler) root_handler = Resource(RootHandler) build_handler = Resource(BuildHandler) tag_handler = Resource(TagHandler) urlpatterns = patterns('', url(r'^(?P<slug>[^/]+)/builds/latest/', build_handler, {'latest': True }), url(r'^(?P<slug>[^/]+)/builds/(?P<data>[^/]+)/', build_handler), url(r'^(?P<slug>[^/]+)/builds/', build_handler), url(r'^(?P<slug>[^/]+)/tags/(?P<data>[^/]+)/latest/', tag_handler, {'latest': True }), url(r'^(?P<slug>[^/]+)/tags/(?P<data>[^/]+)/', tag_handler), url(r'^(?P<slug>[^/]+)/tags/', tag_handler), url(r'^(?P<slug>[^/]+)/', package_handler), url(r'^$', root_handler), )
from django.conf.urls.defaults import * from piston.resource import Resource from pony_server.api.handlers import PackageHandler, RootHandler, BuildHandler, TagHandler package_handler = Resource(PackageHandler) root_handler = Resource(RootHandler) build_handler = Resource(BuildHandler) tag_handler = Resource(TagHandler) urlpatterns = patterns('', url(r'^package/(?P<slug>[^/]+)/builds/latest/', build_handler, {'latest': True }), url(r'^package/(?P<slug>[^/]+)/builds/(?P<data>[^/]+)/', build_handler), url(r'^package/(?P<slug>[^/]+)/builds/', build_handler), url(r'^package/(?P<slug>[^/]+)/tags/(?P<data>[^/]+)/latest/', tag_handler, {'latest': True }), url(r'^package/(?P<slug>[^/]+)/tags/(?P<data>[^/]+)/', tag_handler), url(r'^package/(?P<slug>[^/]+)/tags/', tag_handler), url(r'^package/(?P<slug>[^/]+)/', package_handler), url(r'^$', root_handler), )
Fix problem on letter list display when the letter is a <space> Work around for now for issue #10. And will need to be permanant, since the real fix to the database import would make removing the space optional.
# encoding: cinje : from cinje.std.html import link, div, span : from urllib.parse import urlencode, quote_plus : def letterscountsbar ctx, letterscountslist : try : selected_letter = ctx.selected_letter : except AttributeError : selected_letter = None : end <div class="col-sm-1 list-group"> : for row in letterscountslist : if row.letter == '' : print("Skip Letter: |{}|".format(row.letter), dir(row.letter)) : continue :end : l = quote_plus(row.letter) <a href="/${ctx.resource.__resource__}/?letter=${l}" tip='${row.count}' class='list-group-item #{"active" if selected_letter == row.letter else ""}'> : if row.letter == ' ' &nbsp; : else ${row.letter} : end </span> <span class='badge'>${row.count}</span> </a> : end </div> : end
# encoding: cinje : from cinje.std.html import link, div, span : from urllib.parse import urlencode, quote_plus : def letterscountsbar ctx, letterscountslist : try : selected_letter = ctx.selected_letter : except AttributeError : selected_letter = None : end <div class="col-sm-1 list-group"> : for row in letterscountslist : if row.letter == '' : print("Skip Letter: |{}|".format(row.letter), dir(row.letter)) : continue :end : l = quote_plus(row.letter) <a href="/${ctx.resource.__resource__}/?letter=${l}" tip='${row.count}' class='list-group-item #{"active" if selected_letter == row.letter else ""}'> ${row.letter} <span class='badge'>${row.count}</span> </a> : end </div> : end
Use dedicated port range for length-based TcpServer tests
/* * Copyright (c) 2013 Ramon Servadei * * 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.fimtra.tcpchannel; import com.fimtra.tcpchannel.TcpServer; import com.fimtra.tcpchannel.TcpChannel.FrameEncodingFormatEnum; /** * Tests the {@link TcpServer} using {@link FrameEncodingFormatEnum#LENGTH_BASED} * * @author Ramon Servadei */ public class TestTcpServerWithLengthBasedFrameEncodingFormat extends TestTcpServer { static { PORT = 14000; } public TestTcpServerWithLengthBasedFrameEncodingFormat() { super(); this.frameEncodingFormat = FrameEncodingFormatEnum.LENGTH_BASED; } }
/* * Copyright (c) 2013 Ramon Servadei * * 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.fimtra.tcpchannel; import com.fimtra.tcpchannel.TcpServer; import com.fimtra.tcpchannel.TcpChannel.FrameEncodingFormatEnum; /** * Tests the {@link TcpServer} using {@link FrameEncodingFormatEnum#LENGTH_BASED} * * @author Ramon Servadei */ public class TestTcpServerWithLengthBasedFrameEncodingFormat extends TestTcpServer { public TestTcpServerWithLengthBasedFrameEncodingFormat() { super(); this.frameEncodingFormat = FrameEncodingFormatEnum.LENGTH_BASED; } }
Google+: Change the name from "Google Plus" to "Google+" It's just not how it's styled.
function ddg_spice_google_plus (api_result) { "use strict"; if(!api_result || !api_result.items || api_result.items.length === 0) { return Spice.failed("googleplus"); } Spice.add({ id: 'googleplus', name: 'Google+', data: api_result.items, meta: { sourceName : 'Google+', sourceUrl : 'http://plus.google.com', itemType: "Google+ Profile" + (api_result.items.length > 1 ? 's' : '') }, templates: { group: 'products_simple', item_detail: false, detail: false }, normalize : function(item) { var image = item.image.url.replace(/sz=50$/, "sz=200"); return { image : image.replace(/^https/, "http"), title: item.displayName }; } }); };
function ddg_spice_google_plus (api_result) { "use strict"; if(!api_result || !api_result.items || api_result.items.length === 0) { return Spice.failed("googleplus"); } Spice.add({ id: 'googleplus', name: 'Google Plus', data: api_result.items, meta: { sourceName : 'Google+', sourceUrl : 'http://plus.google.com', itemType: "Google+ Profile" + (api_result.items.length > 1 ? 's' : '') }, templates: { group: 'products_simple', item_detail: false, detail: false }, normalize : function(item) { var image = item.image.url.replace(/sz=50$/, "sz=200"); return { image : image.replace(/^https/, "http"), title: item.displayName }; } }); };
Allow dots in callback names.
module.exports = function(options) { var cb = (options && options.variable) || 'cb'; var regexp = new RegExp('(?:\\b|&)' + cb + '=([a-zA-Z$_][\.a-zA-Z0-9$_]*)(?:&|$)'); return { reshook: function(server, tile, req, res, result, callback) { if (result.headers['Content-Type'] !== 'application/json') return callback(); if (!tile.qs) return callback(); var match = tile.qs.match(regexp); if (!match) return callback(); var callbackName = match[1]; var callbackLength = callbackName.length; var newBuffer = new Buffer(result.buffer.length + callbackLength + 2); newBuffer.write(callbackName + '('); newBuffer.write(result.buffer.toString('utf8'), callbackLength + 1); newBuffer.write(')', newBuffer.length - 1); result.buffer = newBuffer; result.headers['Content-Type'] = 'text/javascript'; callback(); } }; };
module.exports = function(options) { var cb = (options && options.variable) || 'cb'; var regexp = new RegExp('(?:\\b|&)' + cb + '=([a-zA-Z$_][a-zA-Z0-9$_]*)(?:&|$)'); return { reshook: function(server, tile, req, res, result, callback) { if (result.headers['Content-Type'] !== 'application/json') return callback(); if (!tile.qs) return callback(); var match = tile.qs.match(regexp); if (!match) return callback(); var callbackName = match[1]; var callbackLength = callbackName.length; var newBuffer = new Buffer(result.buffer.length + callbackLength + 2); newBuffer.write(callbackName + '('); newBuffer.write(result.buffer.toString('utf8'), callbackLength + 1); newBuffer.write(')', newBuffer.length - 1); result.buffer = newBuffer; result.headers['Content-Type'] = 'text/javascript'; callback(); } }; };
Update student from server after checkout completes
import { Store } from 'consus-core/flux'; import CartStore from './cart-store'; import { searchStudent } from '../lib/api-client'; let student = null; class StudentStore extends Store{ hasOverdueItems(items){ return items.some(element => { return element.timestamp <= new Date().getTime(); }); } getStudent() { return student; } } const store = new StudentStore(); store.registerHandler('STUDENT_FOUND', data => { student = { //NOTE: this data is tentative id : data.id, name: data.name, items: data.items, hasOverdueItem: store.hasOverdueItems(data.items) }; store.emitChange(); }); store.registerHandler('CLEAR_ALL_DATA', () => { student = null; }); store.registerHandler('CHECKOUT_SUCCESS', () => { /*API call made from store to update student from server after checkout completes, then the store will emit change when student is found.*/ searchStudent(student.id); }); store.registerHandler('CHECKIN_SUCCESS', data => { let index = student.items.findIndex(element => { return element.address === data.itemAddress; }); student.items.splice(index, 1); store.emitChange(); }); export default store;
import { Store } from 'consus-core/flux'; import CartStore from './cart-store'; let student = null; class StudentStore extends Store{ hasOverdueItems(items){ return items.some(element => { return element.timestamp <= new Date().getTime(); }); } getStudent() { return student; } } const store = new StudentStore(); store.registerHandler('STUDENT_FOUND', data => { student = { //NOTE: this data is tentative id : data.id, name: data.name, items: data.items, hasOverdueItem: store.hasOverdueItems(data.items) }; store.emitChange(); }); store.registerHandler('CLEAR_ALL_DATA', () => { student = null; }); store.registerHandler('CHECKOUT_SUCCESS', () => { student.items = student.items.concat(CartStore.getItems()); store.emitChange(); }); store.registerHandler('CHECKIN_SUCCESS', data => { let index = student.items.findIndex(element => { return element.address === data.itemAddress; }); student.items.splice(index, 1); store.emitChange(); }); export default store;
Set default race and class without extra database queries
from django.shortcuts import get_object_or_404, redirect, render from characters.forms import CharacterForm from characters.models import Character, Class, Race def index(request): all_characters = Character.objects.all() context = {'all_characters': all_characters} return render(request, 'characters/index.html', context) def view_character(request, character_id): character = get_object_or_404(Character, pk=character_id) context = {'character': character} return render(request, 'characters/view_character.html', context) def create_character(request): form = CharacterForm(request.POST or None) if request.method == 'POST' and form.is_valid(): character = Character( name=request.POST['name'], background=request.POST['background'], race_id=1, cclass_id=1 ) character.save() return redirect('characters:view', character_id=character.id) context = {'form': form} return render(request, 'characters/create_character.html', context)
from django.shortcuts import get_object_or_404, redirect, render from characters.forms import CharacterForm from characters.models import Character, Class, Race def index(request): all_characters = Character.objects.all() context = {'all_characters': all_characters} return render(request, 'characters/index.html', context) def view_character(request, character_id): character = get_object_or_404(Character, pk=character_id) context = {'character': character} return render(request, 'characters/view_character.html', context) def create_character(request): form = CharacterForm(request.POST or None) if request.method == 'POST' and form.is_valid(): race = Race.objects.get(id=1) cclass = Class.objects.get(id=1) character = Character( name=request.POST['name'], background=request.POST['background'], race=race, cclass=cclass ) character.save() return redirect('characters:view', character_id=character.id) context = {'form': form} return render(request, 'characters/create_character.html', context)
Replace singleton to bind main class. Bind Class name instead hardcoding a string.
<?php namespace Edujugon\Skeleton\Providers; use Edujugon\Skeleton\Skeleton; use Illuminate\Support\ServiceProvider; class SkeletonServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $config_path = function_exists('config_path') ? config_path('skeleton.php') : 'skeleton.php'; $this->publishes([ __DIR__.'/../Config/config.php' => $config_path, ], 'config'); } /** * Register the application services. * * @return void */ public function register() { $this->app->bind(Skeleton::class, function ($app) { return new Skeleton(); }); } }
<?php namespace Edujugon\Skeleton\Providers; use Edujugon\Skeleton\Skeleton; use Illuminate\Support\ServiceProvider; class SkeletonServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { $config_path = function_exists('config_path') ? config_path('skeleton.php') : 'skeleton.php'; $this->publishes([ __DIR__.'/../Config/config.php' => $config_path, ], 'config'); } /** * Register the application services. * * @return void */ public function register() { $this->app->singleton('skeleton', function ($app) { return new Skeleton(); }); } }
Fix authors in databrary citation
module.filter('cite', [ 'pageService', function (page) { return function (volume) { if (!angular.isObject(volume) || angular.isUndefined(volume.access) || angular.isUndefined(volume.name) || angular.isUndefined(volume.id)) { return ''; } var names = []; angular.forEach(volume.access, function (access) { if (angular.isUndefined(access.individual) || access.individual < page.permission.ADMIN) { return; } var parts = access.party.name.split(' '), name = parts.pop(); if (parts.length > 0) { name += ', ' + parts.map(function (n) { return n.charAt(0); }).join('. ') + '.'; } names.push(name); }); names = names.join(', '); // var created = page.$filter('date')(new Date(volume.creation), 'yyyy'); var retrieved = page.$filter('date')(new Date(), 'longDate'); // return page.$filter('escape')(names) + ', ' + created + '. ' + page.$filter('escape')(volume.name) + '. <em>Databrary</em>. Retrieved ' + retrieved + ' from <a href="http://databrary.org/volume/' + volume.id + '" title="' + page.$filter('escape')(volume.name) + '">http://databrary.org/volume/' + volume.id + '</a>.'; }; } ]);
module.filter('cite', [ 'pageService', function (page) { return function (volume) { if (!angular.isObject(volume) || angular.isUndefined(volume.access) || angular.isUndefined(volume.name) || angular.isUndefined(volume.id)) { return ''; } var names = []; angular.forEach(volume.access, function (access) { if (angular.isUndefined(access.access) || access.access < page.permission.ADMIN) { return; } var parts = access.party.name.split(' '), name = parts.pop(); if (parts.length > 0) { name += ', ' + parts.map(function (n) { return n.charAt(0); }).join('. ') + '.'; } names.push(name); }); names = names.join(', '); // var created = page.$filter('date')(new Date(volume.creation), 'yyyy'); var retrieved = page.$filter('date')(new Date(), 'longDate'); // return page.$filter('escape')(names) + ', ' + created + '. ' + page.$filter('escape')(volume.name) + '. <em>Databrary</em>. Retrieved ' + retrieved + ' from <a href="http://databrary.org/volume/' + volume.id + '" title="' + page.$filter('escape')(volume.name) + '">http://databrary.org/volume/' + volume.id + '</a>.'; }; } ]);
Update module version and tag as v0.4
#!/usr/bin/env python from distutils.core import setup, Extension setup( name='mapcode', ext_modules=[Extension('mapcode', sources=['mapcodemodule.c', 'mapcodelib/mapcoder.c'], include_dirs=['mapcodelib'] )], # version number format is clibrary - python version='0.4', description='A Python module to do mapcode encoding and decoding. See http://www.mapcode.com for more information.', author='Erik Bos', author_email='erik@xs4all.nl', url='https://github.com/mapcode-foundation/mapcode-python', download_url='https://github.com/mapcode-foundation/mapcode-python/tarball/v0.4', license='Apache License 2.0', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License' ], )
#!/usr/bin/env python from distutils.core import setup, Extension setup( name='mapcode', ext_modules=[Extension('mapcode', sources=['mapcodemodule.c', 'mapcodelib/mapcoder.c'], include_dirs=['mapcodelib'] )], version='0.3', description='A Python module to do mapcode encoding and decoding. See http://www.mapcode.com for more information.', author='Erik Bos', author_email='erik@xs4all.nl', url='https://github.com/mapcode-foundation/mapcode-python', download_url='https://github.com/mapcode-foundation/mapcode-python/tarball/v0.3', license='Apache License 2.0', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License' ], )
Fix provider check causing Devshell auth failure This commit builds on commit 13c4926, allowing Devshell credentials to be used only with Google storage.
# -*- coding: utf-8 -*- # Copyright 2015 Google Inc. 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. """Developer Shell auth bridge. This enables Boto API auth in Developer Shell environment. """ from __future__ import absolute_import from boto.auth_handler import AuthHandler from boto.auth_handler import NotReadyToAuthenticate import oauth2client.contrib.devshell as devshell class DevshellAuth(AuthHandler): """Developer Shell authorization plugin class.""" capability = ['s3'] def __init__(self, path, config, provider): # Provider here is a boto.provider.Provider object (as opposed to the # provider attribute of CloudApi objects, which is a string). if provider.name != 'google': # Devshell credentials are valid for Google only and can't be used for s3. raise NotReadyToAuthenticate() try: self.creds = devshell.DevshellCredentials() except: raise NotReadyToAuthenticate() def add_auth(self, http_request): http_request.headers['Authorization'] = ('Bearer %s' % self.creds.access_token)
# -*- coding: utf-8 -*- # Copyright 2015 Google Inc. 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. """Developer Shell auth bridge. This enables Boto API auth in Developer Shell environment. """ from __future__ import absolute_import from boto.auth_handler import AuthHandler from boto.auth_handler import NotReadyToAuthenticate import oauth2client.contrib.devshell as devshell class DevshellAuth(AuthHandler): """Developer Shell authorization plugin class.""" capability = ['s3'] def __init__(self, path, config, provider): if provider != 'gs': # Devshell credentials are valid for Google only and can't be used for s3. raise NotReadyToAuthenticate() try: self.creds = devshell.DevshellCredentials() except: raise NotReadyToAuthenticate() def add_auth(self, http_request): http_request.headers['Authorization'] = ('Bearer %s' % self.creds.access_token)
Fix broken router path tests
package com.continuuity.gateway.router; import com.continuuity.common.conf.Constants; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; /** * To test the RouterPathLookup regular expression tests. */ public class RouterPathTest { @Before public void beforeTests() { RouterPathLookup.init(); } @Test public void testRouterFlowPathLookUp() throws Exception { String flowPath = "/v2//apps/ResponseCodeAnalytics/flows/LogAnalyticsFlow/status"; String result = RouterPathLookup.getRoutingPath(flowPath, "GET"); Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result); } @Test public void testRouterWorkFlowPathLookUp() throws Exception { String procPath = "/v2/apps/PurchaseHistory/workflows/PurchaseHistoryWorkflow/status"; String result = RouterPathLookup.getRoutingPath(procPath, "GET"); Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result); } @Test public void testRouterProcedurePathLookUp() throws Exception { String procPath = "/v2//apps/ResponseCodeAnalytics/procedures/StatusCodeProcedure/status"; String result = RouterPathLookup.getRoutingPath(procPath, "GET"); Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result); } @Test public void testRouterDeployPathLookUp() throws Exception { String procPath = "/v2//apps/"; String result = RouterPathLookup.getRoutingPath(procPath, "PUT"); Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result); } }
package com.continuuity.gateway.router; import com.continuuity.common.conf.Constants; import junit.framework.Assert; import org.junit.Test; /** * To test the RouterPathLookup regular expression tests. */ public class RouterPathTest { @Test public void testRouterFlowPathLookUp() throws Exception { String flowPath = "/v2//apps/ResponseCodeAnalytics/flows/LogAnalyticsFlow/status"; String result = RouterPathLookup.getRoutingPath(flowPath, "GET"); Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result); } @Test public void testRouterWorkFlowPathLookUp() throws Exception { String procPath = "/v2/apps/PurchaseHistory/workflows/PurchaseHistoryWorkflow/status"; String result = RouterPathLookup.getRoutingPath(procPath, "GET"); Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result); } @Test public void testRouterProcedurePathLookUp() throws Exception { String procPath = "/v2//apps/ResponseCodeAnalytics/procedures/StatusCodeProcedure/status"; String result = RouterPathLookup.getRoutingPath(procPath, "GET"); Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result); } @Test public void testRouterDeployPathLookUp() throws Exception { String procPath = "/v2//apps/"; String result = RouterPathLookup.getRoutingPath(procPath, "PUT"); Assert.assertEquals(Constants.Service.APP_FABRIC_HTTP, result); } }
Extend CoreTestCase for access to assertPositve/Negative, others git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@136 0d517254-b314-0410-acde-c619094fa49f
package edu.northwestern.bioinformatics.studycalendar.testing; import edu.nwu.bioinformatics.commons.testing.CoreTestCase; import junit.framework.TestCase; import java.lang.reflect.Method; import java.util.Set; import java.util.HashSet; import org.easymock.classextension.EasyMock; /** * @author Rhett Sutphin */ public abstract class StudyCalendarTestCase extends CoreTestCase { protected Set<Object> mocks = new HashSet<Object>(); ////// MOCK REGISTRATION AND HANDLING protected <T> T registerMockFor(Class<T> forClass) { return registered(EasyMock.createMock(forClass)); } protected <T> T registerMockFor(Class<T> forClass, Method[] methodsToMock) { return registered(EasyMock.createMock(forClass, methodsToMock)); } protected void replayMocks() { for (Object mock : mocks) EasyMock.replay(mock); } protected void verifyMocks() { for (Object mock : mocks) EasyMock.verify(mock); } protected void resetMocks() { for (Object mock : mocks) EasyMock.reset(mock); } private <T> T registered(T mock) { mocks.add(mock); return mock; } }
package edu.northwestern.bioinformatics.studycalendar.testing; import junit.framework.TestCase; import java.lang.reflect.Method; import java.util.Set; import java.util.HashSet; import org.easymock.classextension.EasyMock; /** * @author Rhett Sutphin */ public abstract class StudyCalendarTestCase extends TestCase { protected Set<Object> mocks = new HashSet<Object>(); ////// MOCK REGISTRATION AND HANDLING protected <T> T registerMockFor(Class<T> forClass) { return registered(EasyMock.createMock(forClass)); } protected <T> T registerMockFor(Class<T> forClass, Method[] methodsToMock) { return registered(EasyMock.createMock(forClass, methodsToMock)); } protected void replayMocks() { for (Object mock : mocks) EasyMock.replay(mock); } protected void verifyMocks() { for (Object mock : mocks) EasyMock.verify(mock); } protected void resetMocks() { for (Object mock : mocks) EasyMock.reset(mock); } private <T> T registered(T mock) { mocks.add(mock); return mock; } }
:wrench: Add reference on comment fixtures
<?php namespace OAuthBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use WordPressBundle\Entity\Comment; class LoadCommentData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $comment1 = new Comment(); $comment1->setCommentPostId($this->getReference("post-1")->getId()); $comment1->setCommentAuthor("Doctor strange"); $comment1->setCommentAuthorEmail("doctor@strange.com"); $comment1->setCommentAuthorUrl("http://doctorstrange.com"); $comment1->setCommentDate(new \DateTime("now")); $comment1->setCommentDateGmt(new \DateTime("now")); $comment1->setCommentContent("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex cupiditate, quo possimus. Asperiores hic temporibus dolores voluptates vel vero, cumque expedita ipsam aut veritatis perspiciatis dicta, iste minus, optio facilis?"); $this->addReference('comment-1', $comment1); $manager->persist($comment1); $manager->flush(); } public function getOrder(){ return 2; } }
<?php namespace OAuthBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use WordPressBundle\Entity\Comment; class LoadCommentData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $comment1 = new Comment(); $comment1->setCommentPostId($this->getReference("post-1")->getId()); $comment1->setCommentAuthor("Doctor strange"); $comment1->setCommentAuthorEmail("doctor@strange.com"); $comment1->setCommentAuthorUrl("http://doctorstrange.com"); $comment1->setCommentDate(new \DateTime("now")); $comment1->setCommentDateGmt(new \DateTime("now")); $comment1->setCommentContent("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex cupiditate, quo possimus. Asperiores hic temporibus dolores voluptates vel vero, cumque expedita ipsam aut veritatis perspiciatis dicta, iste minus, optio facilis?"); $manager->persist($comment1); $manager->flush(); } public function getOrder(){ return 2; } }
Set protractor host to 8080 instead of 3000.
/** * @author: @AngularClass */ require('ts-node/register'); var helpers = require('./helpers'); exports.config = { baseUrl: 'http://localhost:8080/', // use `npm run e2e` specs: [ helpers.root('src/**/**.e2e.ts'), helpers.root('src/**/*.e2e.ts') ], exclude: [], framework: 'jasmine2', allScriptsTimeout: 110000, jasmineNodeOpts: { showTiming: true, showColors: true, isVerbose: false, includeStackTrace: false, defaultTimeoutInterval: 400000 }, directConnect: true, capabilities: { 'browserName': 'chrome', 'chromeOptions': { 'args': ['show-fps-counter=true'] } }, onPrepare: function() { browser.ignoreSynchronization = true; }, /** * Angular 2 configuration * * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching * `rootEl` */ useAllAngular2AppRoots: true };
/** * @author: @AngularClass */ require('ts-node/register'); var helpers = require('./helpers'); exports.config = { baseUrl: 'http://localhost:3000/', // use `npm run e2e` specs: [ helpers.root('src/**/**.e2e.ts'), helpers.root('src/**/*.e2e.ts') ], exclude: [], framework: 'jasmine2', allScriptsTimeout: 110000, jasmineNodeOpts: { showTiming: true, showColors: true, isVerbose: false, includeStackTrace: false, defaultTimeoutInterval: 400000 }, directConnect: true, capabilities: { 'browserName': 'chrome', 'chromeOptions': { 'args': ['show-fps-counter=true'] } }, onPrepare: function() { browser.ignoreSynchronization = true; }, /** * Angular 2 configuration * * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching * `rootEl` */ useAllAngular2AppRoots: true };
Update path filename for printing
<?php $url = $_POST['url']; $name = preg_split("/\//", $url, 0, PREG_SPLIT_NO_EMPTY); $fileName = dirname(__FILE__) . '/pdf/' . $name[sizeof($name) - 1] . '.pdf'; $baseUrl = $name[0] . '//' . $name[1] . '/cache/'; // $baseUrl = $name[0] . '//' . $name[1] . '/' . $name[2] . '/' . $name[3] . '/'; $output = 'phantomjs --ignore-ssl-errors=true "' . dirname(__FILE__) . '/js/rasterize.js" "' . $baseUrl . $name[sizeof($name) - 1] . '.html' . '" "' . $fileName . '"'; exec($output); if (file_exists($fileName)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($fileName)); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($fileName)); readfile($fileName); exit; } ?>
<?php $url = $_POST['url']; $name = preg_split("/\//", $url, 0, PREG_SPLIT_NO_EMPTY); $fileName = dirname(__FILE__) . '/pdf/' . $name[sizeof($name) - 1] . '.pdf'; $baseUrl = $name[0] . '//' . $name[1] . '/cached/'; // $baseUrl = $name[0] . '//' . $name[1] . '/' . $name[2] . '/' . $name[3] . '/'; $output = 'phantomjs --ignore-ssl-errors=true "' . dirname(__FILE__) . '/js/rasterize.js" "' . $baseUrl . $name[sizeof($name) - 1] . '.html' . '" "' . $fileName . '"'; exec($output); if (file_exists($fileName)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($fileName)); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($fileName)); readfile($fileName); exit; } ?>
Add form for accepting contract variation
from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide the full name of the person signing on behalf of the company."), Length(max=255, message="You must provide a name under 256 characters.") ]) signerRole = StripWhitespaceStringField( 'Role at the company', validators=[ DataRequired(message="You must provide the role of the person signing on behalf of the company."), Length(max=255, message="You must provide a role under 256 characters.") ], description='The person signing must have the authority to agree to the framework terms, ' 'eg director or company secretary.' ) class ContractReviewForm(Form): authorisation = BooleanField( 'Authorisation', validators=[DataRequired(message="You must confirm you have the authority to return the agreement.")] ) class AcceptAgreementVariationForm(Form): accept_changes = BooleanField( 'I accept these proposed changes', validators=[ DataRequired(message="If you agree to the proposed changes then you must check the box before saving.") ] )
from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide the full name of the person signing on behalf of the company."), Length(max=255, message="You must provide a name under 256 characters.") ]) signerRole = StripWhitespaceStringField( 'Role at the company', validators=[ DataRequired(message="You must provide the role of the person signing on behalf of the company."), Length(max=255, message="You must provide a role under 256 characters.") ], description='The person signing must have the authority to agree to the framework terms, ' 'eg director or company secretary.' ) class ContractReviewForm(Form): authorisation = BooleanField( 'Authorisation', validators=[DataRequired(message="You must confirm you have the authority to return the agreement.")] )
Fix problem with system sending empty answers Some web browsers do not trigger the keyup or keydown events. One of those web browsers is BluStar Agent. This caused the system to think nothing had been entered into the fields. Solve this problem by both listenting to change and keyup event.
function ComponentTextfield( id ) { var self = _ComponentFormControl(id); self.setDefaultState('text-value'); self.bind = function() { self.attachChangeAction( self.node(), self.identifier() ); self.attachKeyUpAction( self.node(), self.identifier() ); }; self.registerAction('change', function() { self.setState('text-value', self.node().value); }); self.registerAction('keyup', function() { self._states['text-value'] = self.node().value; }); self.select = function() { if( self.node() ) { self.node().select(); } }; self.textValue = function() { self.setState('text-value', self.node().value); return self.getState('text-value'); }; self.setTextValue = function( value ) { self.setState('text-value', value); self.node().value = value; }; self.enable = function() { self._enabled = true; self.node().readOnly = false; }; self.disable = function() { self._enabled = false; self.node().readOnly = true; }; return self; }
function ComponentTextfield( id ) { var self = _ComponentFormControl(id); self.setDefaultState('text-value'); self.bind = function() { self.attachKeyUpAction( self.node(), self.identifier() ); }; self.registerAction('keyup', function() { self._states['text-value'] = self.node().value; }); self.select = function() { if( self.node() ) { self.node().select(); } }; self.textValue = function() { self.setState('text-value', self.node().value); return self.getState('text-value'); }; self.setTextValue = function( value ) { self.setState('text-value', value); self.node().value = value; }; self.enable = function() { self._enabled = true; self.node().readOnly = false; }; self.disable = function() { self._enabled = false; self.node().readOnly = true; }; return self; }
Stop using console.log on the web. It seems to only sometimes work in IE.
"use strict"; var Codesearch = function() { return { socket: null, delegate: null, connect: function(delegate) { if (Codesearch.socket !== null) return; Codesearch.remote = null; Codesearch.delegate = delegate; var socket = io.connect("http://" + document.location.host.replace(/:\d+$/, '') + ":8910"); socket.on('connect', function () { Codesearch.socket = socket; if (Codesearch.delegate.on_connect) Codesearch.delegate.on_connect(); }); socket.on('regex_error', Codesearch.delegate.error); socket.on('match', Codesearch.delegate.match); socket.on('search_done', Codesearch.delegate.search_done); }, new_search: function(re, file, id) { if (Codesearch.socket !== null) Codesearch.socket.emit('new_search', re, file, id); } }; }();
"use strict"; var Codesearch = function() { return { socket: null, delegate: null, connect: function(delegate) { if (Codesearch.socket !== null) return; console.log("Connecting..."); Codesearch.remote = null; Codesearch.delegate = delegate; var socket = io.connect("http://" + document.location.host.replace(/:\d+$/, '') + ":8910"); socket.on('connect', function () { Codesearch.socket = socket; if (Codesearch.delegate.on_connect) Codesearch.delegate.on_connect(); }); socket.on('regex_error', Codesearch.delegate.error); socket.on('match', Codesearch.delegate.match); socket.on('search_done', Codesearch.delegate.search_done); }, new_search: function(re, file, id) { if (Codesearch.socket !== null) Codesearch.socket.emit('new_search', re, file, id); } }; }();
Remove only links that have not the data.role class.
var Bind = require("github/jillix/bind"); var Events = require("github/jillix/events"); module.exports = function(config) { var self = this; Events.call(self, config); for (var i in config.roles) { $("." + config.roles[i]).hide(); } var cache; self.updateLinks = function (data) { cache = cache || data; data = cache || {}; data.role = data.role || config.publicRole; $("." + data.role).fadeIn(); var index = config.roles.indexOf(data.role); if (index !== -1) { config.roles.splice(index, 1); } for (var i in config.roles) { $("." + config.roles[i] + ":not('." + data.role + "')").remove(); } self.emit("updatedLinks", data); }; };
var Bind = require("github/jillix/bind"); var Events = require("github/jillix/events"); module.exports = function(config) { var self = this; Events.call(self, config); for (var i in config.roles) { $("." + config.roles[i]).hide(); } var cache; self.updateLinks = function (data) { cache = cache || data; data = cache || {}; data.role = data.role || config.publicRole; $("." + data.role).fadeIn(); var index = config.roles.indexOf(data.role); if (index !== -1) { config.roles.splice(index, 1); } for (var i in config.roles) { $("." + config.roles[i]).remove(); } self.emit("updatedLinks", data); }; };
Add route to handle ticket filtering by status
<?php /* |-------------------------------------------------------------------------- | Application Routers |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::group(['before' => 'Sentinel\auth'], function() { Route::resource('projects', 'ProjectsController'); Route::resource('tickets', 'TicketsController'); Route::resource('invoices', 'InvoicesController'); Route::get('/tickets/status/{status}', ['as' => 'ticket.by.status', 'uses' => 'TicketsController@filterByStatus']); Route::post('tickets/{id}/reply', 'TicketsController@reply'); Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']); # Override Sentinel's Default user routes with our own filter requirement Route::get('/users/{id}', ['as' => 'sl_user.show', 'uses' => 'SimpleLance\UserController@show'])->where('id', '[0-9]+'); Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@index']); }); Route::group(['before' => 'Sentinel\inGroup:Admins'], function() { Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]); Route::resource('statuses', 'StatusesController', ['except' => ['show']]); });
<?php /* |-------------------------------------------------------------------------- | Application Routers |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::group(['before' => 'Sentinel\auth'], function() { Route::resource('projects', 'ProjectsController'); Route::resource('tickets', 'TicketsController'); Route::resource('invoices', 'InvoicesController'); Route::post('tickets/{id}/reply', 'TicketsController@reply'); Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']); # Override Sentinel's Default user routes with our own filter requirement Route::get('/users/{id}', ['as' => 'sl_user.show', 'uses' => 'SimpleLance\UserController@show'])->where('id', '[0-9]+'); Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@index']); }); Route::group(['before' => 'Sentinel\inGroup:Admins'], function() { Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]); Route::resource('statuses', 'StatusesController', ['except' => ['show']]); });
Add path for laptop for fixtures
# Statement for enabling the development environment DEBUG = True TESTING = True # Define the application directory import os BASE_DIR = os.path.abspath(os.path.dirname(__file__)) # Define the database - we are working with # SQLite for this example SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/ontheside' DATABASE_CONNECT_OPTIONS = {} # Application threads. A common general assumption is # using 2 per available processor cores - to handle # incoming requests using one and performing background # operations using the other. THREADS_PER_PAGE = 2 # Enable protection agains *Cross-site Request Forgery (CSRF)* CSRF_ENABLED = True # Use a secure, unique and absolutely secret key for # signing the data. CSRF_SESSION_KEY = "secret" # Secret key for signing cookies SECRET_KEY = "secret" FIXTURES_DIRS = [ '/home/ganemone/Documents/dev/ontheside/server/tests/fixtures/', '/Users/giancarloanemone/Documents/dev/web/ontheside/server/tests/fixtures/' ]
# Statement for enabling the development environment DEBUG = True TESTING = True # Define the application directory import os BASE_DIR = os.path.abspath(os.path.dirname(__file__)) # Define the database - we are working with # SQLite for this example SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@localhost/ontheside' DATABASE_CONNECT_OPTIONS = {} # Application threads. A common general assumption is # using 2 per available processor cores - to handle # incoming requests using one and performing background # operations using the other. THREADS_PER_PAGE = 2 # Enable protection agains *Cross-site Request Forgery (CSRF)* CSRF_ENABLED = True # Use a secure, unique and absolutely secret key for # signing the data. CSRF_SESSION_KEY = "secret" # Secret key for signing cookies SECRET_KEY = "secret" FIXTURES_DIRS = [ '/home/ganemone/Documents/dev/ontheside/server/tests/fixtures/' ]
Add API version into response header
from flask import Flask, g, request import uuid import requests app = Flask(__name__) app.config.from_pyfile("config.py") @app.before_request def before_request(): # Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller. # Generate a new one if it has not. We will use this in log messages. trace_id = request.headers.get('X-Trace-ID', None) if trace_id is None: trace_id = uuid.uuid4().hex g.trace_id = trace_id # We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it. # These lines can be removed if the app will not make requests to other LR APIs! g.requests = requests.Session() g.requests.headers.update({'X-Trace-ID': trace_id}) @app.after_request def after_request(response): # Add the API version (as in the interface spec, not the app) to the header. Semantic versioning applies - see the # API manual. A major version update will need to go in the URL. All changes should be documented though, for # reusing teams to take advantage of. response.headers["X-API-Version"] = "1.0.0" return response
from flask import Flask, g, request import uuid import requests app = Flask(__name__) app.config.from_pyfile("config.py") @app.before_request def before_request(): # Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller. # Generate a new one if it has not. We will use this in log messages. trace_id = request.headers.get('X-Trace-ID', None) if trace_id is None: trace_id = uuid.uuid4().hex g.trace_id = trace_id # We also create a session-level requests object for the app to use with the header pre-set, so other APIs will receive it. # These lines can be removed if the app will not make requests to other LR APIs! g.requests = requests.Session() g.requests.headers.update({'X-Trace-ID': trace_id})
Add imageBase64: prefix alongside image: for ticket element values
package com.quicktravel.ticket_printer; public class TicketElement { private int x = 0; private int y = 0; protected String value = ""; private int fontSize = 10; private boolean bold = false; private boolean italic = false; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public boolean isImage() { return isImageUrl() || isImageBase64(); } public boolean isImageUrl() { return this.value.startsWith("image:"); } public boolean isImageBase64() { return this.value.startsWith("imageBase64:"); } public int getFontSize() { return fontSize; } public void setFontSize(int fontSize) { this.fontSize = fontSize; } public boolean isBold() { return bold; } public void setBold(boolean bold) { this.bold = bold; } public boolean isItalic() { return italic; } public void setItalic(boolean italic) { this.italic = italic; } public String getImageValue() { return this.value.substring(6); } }
package com.quicktravel.ticket_printer; public class TicketElement { private int x = 0; private int y = 0; private int fontSize = 10; private boolean bold = false; private boolean italic = false; private String value = ""; public boolean isImage() { return this.value.startsWith("image:"); } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getFontSize() { return fontSize; } public void setFontSize(int fontSize) { this.fontSize = fontSize; } public boolean isBold() { return bold; } public void setBold(boolean bold) { this.bold = bold; } public boolean isItalic() { return italic; } public void setItalic(boolean italic) { this.italic = italic; } public String getValue() { return value; } public String getImageValue() { return this.value.substring(6); } public void setValue(String value) { this.value = value; } }
Fix requestAnimationFrame case for SSR
/** @flow */ type Callback = (timestamp: number) => void; type CancelAnimationFrame = (requestId: number) => void; type RequestAnimationFrame = (callback: Callback) => number; // Properly handle server-side rendering. let win; if (typeof window !== "undefined") { win = window; } else if (typeof self !== "undefined") { win = self; } else { win = {}; } // requestAnimationFrame() shim by Paul Irish // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ const request = win.requestAnimationFrame || win.webkitRequestAnimationFrame || win.mozRequestAnimationFrame || win.oRequestAnimationFrame || win.msRequestAnimationFrame || function(callback: Callback): RequestAnimationFrame { return (win: any).setTimeout(callback, 1000 / 60); }; const cancel = win.cancelAnimationFrame || win.webkitCancelAnimationFrame || win.mozCancelAnimationFrame || win.oCancelAnimationFrame || win.msCancelAnimationFrame || function(id: number) { (win: any).clearTimeout(id); }; export const raf: RequestAnimationFrame = (request: any); export const caf: CancelAnimationFrame = (cancel: any);
/** @flow */ type Callback = (timestamp: number) => void; type CancelAnimationFrame = (requestId: number) => void; type RequestAnimationFrame = (callback: Callback) => number; // Properly handle server-side rendering. let win; if (typeof window !== "undefined") { win = window; } else if (typeof self !== "undefined") { win = self; } else { win = this; } // requestAnimationFrame() shim by Paul Irish // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ const request = win.requestAnimationFrame || win.webkitRequestAnimationFrame || win.mozRequestAnimationFrame || win.oRequestAnimationFrame || win.msRequestAnimationFrame || function(callback: Callback): RequestAnimationFrame { return (win: any).setTimeout(callback, 1000 / 60); }; const cancel = win.cancelAnimationFrame || win.webkitCancelAnimationFrame || win.mozCancelAnimationFrame || win.oCancelAnimationFrame || win.msCancelAnimationFrame || function(id: number) { (win: any).clearTimeout(id); }; export const raf: RequestAnimationFrame = (request: any); export const caf: CancelAnimationFrame = (cancel: any);
Fix missing default value for RateLimitExceeded constructor
"""errors and exceptions.""" from flask.wrappers import Response from werkzeug import exceptions from .typing import Optional from .wrappers import Limit class RateLimitExceeded(exceptions.TooManyRequests): """Exception raised when a rate limit is hit.""" def __init__(self, limit: Limit, response: Optional[Response] = None) -> None: """ :param limit: The actual rate limit that was hit. Used to construct the default response message :param response: Optional pre constructed response. If provided it will be rendered by flask instead of the default error response of :class:`~werkzeug.exceptions.HTTPException` """ self.limit = limit self.response = response if limit.error_message: description = ( limit.error_message if not callable(limit.error_message) else limit.error_message() ) else: description = str(limit.limit) super().__init__(description=description, response=response)
"""errors and exceptions.""" from flask.wrappers import Response from werkzeug import exceptions from .typing import Optional from .wrappers import Limit class RateLimitExceeded(exceptions.TooManyRequests): """Exception raised when a rate limit is hit.""" def __init__(self, limit: Limit, response: Optional[Response]) -> None: """ :param limit: The actual rate limit that was hit. Used to construct the default response message :param response: Optional pre constructed response. If provided it will be rendered by flask instead of the default error response of :class:`~werkzeug.exceptions.HTTPException` """ self.limit = limit self.response = response if limit.error_message: description = ( limit.error_message if not callable(limit.error_message) else limit.error_message() ) else: description = str(limit.limit) super().__init__(description=description, response=response)
Fix name parsing for roads
#!/usr/bin/env python # -*- encoding: utf8 -*- import json import sys result = {} INDEX = { "AREA": 5 + 3 * 3 + 3 * 3, "CITY": 5 + 3 * 3, "CODE": 5 } for line in open("ORIGIN.txt"): code = line[:INDEX["CODE"]] city = line[INDEX["CODE"]: INDEX["CITY"]] if not city in result: result[city] = {} area_index = INDEX["AREA"] if line[INDEX["AREA"]] != " ": area_index += 3 area = line[INDEX["CITY"]: area_index].strip() if not area in result[city]: result[city][area] = {} line = line[area_index:].strip() road = line.split(" ")[0] if len(line.split(" ")) == 1: road = line[:-3] if not road in result[city][area]: result[city][area][road] = {} condition = line[line.find(" "):].replace(" ", "").strip() json.dump(result, open("zipcode.json", "w"), ensure_ascii=False, indent=4 ) sys.exit(0)
#!/usr/bin/env python # -*- encoding: utf8 -*- import json import sys result = {} INDEX = { "AREA": 5 + 3 * 3 + 3 * 3, "CITY": 5 + 3 * 3, "CODE": 5 } for line in open("ORIGIN.txt"): code = line[:INDEX["CODE"]] city = line[INDEX["CODE"]: INDEX["CITY"]] if not city in result: result[city] = {} area = line[INDEX["CITY"]: INDEX["AREA"]] if not area in result[city]: result[city][area] = {} line = line[line.find(" "):].strip() road = line[:line.find(" ")] condition = line[line.find(" "):].replace(" ", "").strip() json.dump(result, open("zipcode.json", "w"), ensure_ascii=False, indent=4 ) sys.exit(0)
Add details field to launchpads
const mongoose = require('mongoose'); const mongoosePaginate = require('mongoose-paginate-v2'); const idPlugin = require('mongoose-id'); const launchpadSchema = new mongoose.Schema({ name: { type: String, default: null, }, full_name: { type: String, default: null, }, status: { type: String, enum: ['active', 'inactive', 'unknown', 'retired', 'lost', 'under construction'], required: true, }, locality: { type: String, default: null, }, region: { type: String, default: null, }, timezone: { type: String, default: null, }, latitude: { type: Number, default: null, }, longitude: { type: Number, default: null, }, launch_attempts: { type: Number, default: 0, }, launch_successes: { type: Number, default: 0, }, rockets: [{ type: mongoose.ObjectId, ref: 'Rocket', }], launches: [{ type: mongoose.ObjectId, ref: 'Launch', }], details: { type: String, default: null, }, }, { autoCreate: true }); launchpadSchema.plugin(mongoosePaginate); launchpadSchema.plugin(idPlugin); const Launchpad = mongoose.model('Launchpad', launchpadSchema); module.exports = Launchpad;
const mongoose = require('mongoose'); const mongoosePaginate = require('mongoose-paginate-v2'); const idPlugin = require('mongoose-id'); const launchpadSchema = new mongoose.Schema({ name: { type: String, default: null, }, full_name: { type: String, default: null, }, status: { type: String, enum: ['active', 'inactive', 'unknown', 'retired', 'lost', 'under construction'], required: true, }, locality: { type: String, default: null, }, region: { type: String, default: null, }, timezone: { type: String, default: null, }, latitude: { type: Number, default: null, }, longitude: { type: Number, default: null, }, launch_attempts: { type: Number, default: 0, }, launch_successes: { type: Number, default: 0, }, rockets: [{ type: mongoose.ObjectId, ref: 'Rocket', }], launches: [{ type: mongoose.ObjectId, ref: 'Launch', }], }, { autoCreate: true }); launchpadSchema.plugin(mongoosePaginate); launchpadSchema.plugin(idPlugin); const Launchpad = mongoose.model('Launchpad', launchpadSchema); module.exports = Launchpad;
Fix bug when env.queries is a function
/** * Resolves queries from a map to arrays of maps to field values. * * @param queries A map to arrays of maps to field values. * @param name Query name. * @param rank Query result rank. * @param field Query result field name. * @return Resolved value, or '' if there was an error. */ function queriesObjectReader (queries, name, rank, field) { if (!Object.prototype.hasOwnProperty.call(queries, name)) { return '' } const items = queries[name] if (rank - 1 >= items.length) { return '' } const item = queries[name][rank - 1] if (!Object.prototype.hasOwnProperty.call(item, field)) { return '' } return item[field] } /** * Resolves a query in an environment. * * @param env The environment to evaluate the query in. * @return A function that resolves a query given its name, rank, and field. */ function resolveQuery (env) { return (name, rank, field) => { if (!env || !env.queries) { return '' } const reader = typeof env.queries === 'function' ? env.queries : queriesObjectReader.bind(null, env.queries) const value = reader(name, rank, field) if (['number', 'string'].indexOf(typeof value) === -1) { return '' } return value } } module.exports = { query: resolveQuery }
/** * Resolves queries from a map to arrays of maps to field values. * * @param queries A map to arrays of maps to field values. * @param name Query name. * @param rank Query result rank. * @param field Query result field name. * @return Resolved value, or '' if there was an error. */ function queriesObjectReader (queries, name, rank, field) { const items = queries[name] if (rank - 1 >= items.length) { return '' } const item = queries[name][rank - 1] if (!Object.prototype.hasOwnProperty.call(item, field)) { return '' } return item[field] } /** * Resolves a query in an environment. * * @param env The environment to evaluate the query in. * @return A function that resolves a query given its name, rank, and field. */ function resolveQuery (env) { return (name, rank, field) => { if (!env || !env.queries || !Object.prototype.hasOwnProperty.call(env.queries, name)) { return '' } const reader = typeof env.queries === 'function' ? env.queries : queriesObjectReader.bind(null, env.queries) const value = reader(name, rank, field) if (['number', 'string'].indexOf(typeof value) === -1) { return '' } return value } } module.exports = { query: resolveQuery }
Add readonly text to form
from django.shortcuts import get_object_or_404, render from django import forms class ExampleForm(forms.Form): text = forms.CharField() disabled_text = forms.CharField(disabled=True) readonly_text = forms.CharField( widget=forms.TextInput(attrs={'readonly':'readonly'}) ) checkbox1 = forms.BooleanField() checkbox2 = forms.BooleanField() select = forms.ChoiceField(choices=[('', "Select an Option"), (1, 'one'), (2, 'two'), (3, 'three')]) radio = forms.ChoiceField(choices=[(1, 'one'), (2, 'two'), (3, 'three')], widget=forms.RadioSelect()) form_initial = { "text": "", "disabled_text": "This field can't be changed", "readonly_text": "This field is read only", } def styleguide(request): return render(request, "styleguide/styleguide.html", { }) def styleguide_page(request, name): return render(request, "styleguide/styleguide-%s.html" % name, { "example_form": ExampleForm(initial=form_initial), }) def styleguide_sub_page(request, name, sub_page): return render(request, "styleguide/styleguide-%s-%s.html" % (name, sub_page), { "example_form": ExampleForm(initial=form_initial), })
from django.shortcuts import get_object_or_404, render from django import forms class ExampleForm(forms.Form): text = forms.CharField() disabled_text = forms.CharField(disabled=True) readonly_text = forms.CharField( widget=forms.TextInput(attrs={'readonly':'readonly'}) ) checkbox1 = forms.BooleanField() checkbox2 = forms.BooleanField() select = forms.ChoiceField(choices=[('', "Select an Option"), (1, 'one'), (2, 'two'), (3, 'three')]) radio = forms.ChoiceField(choices=[(1, 'one'), (2, 'two'), (3, 'three')], widget=forms.RadioSelect()) form_initial = { "text": "", "disabled_text": "This field can't be changed", } def styleguide(request): return render(request, "styleguide/styleguide.html", { }) def styleguide_page(request, name): return render(request, "styleguide/styleguide-%s.html" % name, { "example_form": ExampleForm(initial=form_initial), }) def styleguide_sub_page(request, name, sub_page): return render(request, "styleguide/styleguide-%s-%s.html" % (name, sub_page), { "example_form": ExampleForm(initial=form_initial), })
Change newline character to LF
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import Tool import time from Tieba import Tieba def main(): print("Local Time:", time.asctime(time.localtime())) # Read Cookies cookies = Tool.load_cookies_path(".") for cookie in cookies: # Login user = Tieba(cookie) # List Likes print(user.get_likes()) # Sign print(user.username, "Signing") for name in user.get_likes(): if user.sign_Wap(name): time.sleep(10) main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import Tool import time from Tieba import Tieba def main(): print("Local Time:", time.asctime(time.localtime())) # Read Cookies cookies = Tool.load_cookies_path(".") for cookie in cookies: # Login user = Tieba(cookie) # List Likes print(user.get_likes()) # Sign print(user.username, "Signing") for name in user.get_likes(): if user.sign_Wap(name): time.sleep(10) main()
Fix a bug not passing license properly
var path = require('path') var tmp = require('tmp') var html = require('./html.js') var pdf = require('./pdf.js') module.exports = ribosome = {} ribosome.translate = function(url, success, error, license) { tmp.dir(function(err, dirPath) { if (err) { error(err) } else { var htmlPath = path.join(dirPath, "tmp.html") var pdfPath = path.join(dirPath, "tmp.pdf") html.save(url, htmlPath, function() { pdf.generate(htmlPath, pdfPath, function(pdfContent) { success(pdfContent) }, function(err) { error(err) }, license) }, function(err) { error(err) }) } }) }
var path = require('path') var tmp = require('tmp') var html = require('./html.js') var pdf = require('./pdf.js') module.exports = ribosome = {} ribosome.translate = function(url, success, error, license) { tmp.dir(function(err, dirPath) { if (err) { error(err) } else { var htmlPath = path.join(dirPath, "tmp.html") var pdfPath = path.join(dirPath, "tmp.pdf") html.save(url, htmlPath, function() { pdf.generate(htmlPath, pdfPath, function(pdfContent) { success(pdfContent) }, function(err) { error(err) }) }, function(err) { error(err) }) } }, license) }
Fix conditional for recipient name/playername
var l10n_file = __dirname + '/../l10n/commands/tell.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { var message = args.split(' '); var recipient = message.shift(); message = message.join(' '); if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( playerIsOnline, tellPlayer ); return; } player.sayL10n(l10n, 'NOTHING_TOLD'); return; function tellPlayer(p) { if (recipient.toLowercase() !== player.getName().toLowercase()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } function playerIsOnline(p) { if (p) return (recipient.getName() === p.getName()); }; } };
var l10n_file = __dirname + '/../l10n/commands/tell.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { var message = args.split(' '); var recipient = message.shift(); message = message.join(' '); if (recipient) { player.sayL10n(l10n, 'YOU_TELL', recipient, message); players.eachIf( playerIsOnline, tellPlayer ); return; } player.sayL10n(l10n, 'NOTHING_TOLD'); return; function tellPlayer(p) { if (recipient.getName() !== player.getName()) p.sayL10n(l10n, 'THEY_TELL', player.getName(), message); } function playerIsOnline(p) { if (p) return (recipient.getName() === p.getName()); }; } };
[Debug] Fix deprecated use of DebugClassLoader
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\DebugBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * Registers the file link format for the {@link \Symfony\Component\HttpKernel\DataCollector\DumpDataCollector}. * * @author Christian Flothmann <christian.flothmann@xabbuh.de> */ class DumpDataCollectorPass implements CompilerPassInterface { /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition('data_collector.dump')) { return; } $definition = $container->getDefinition('data_collector.dump'); if ($container->hasParameter('templating.helper.code.file_link_format')) { $definition->replaceArgument(1, $container->getParameter('templating.helper.code.file_link_format')); } } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\DebugBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * Registers the file link format for the {@link \Symfony\Component\HttpKernel\DataCollector\DumpDataCollector\DumpDataCollector}. * * @author Christian Flothmann <christian.flothmann@xabbuh.de> */ class DumpDataCollectorPass implements CompilerPassInterface { /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { if (!$container->hasDefinition('data_collector.dump')) { return; } $definition = $container->getDefinition('data_collector.dump'); if ($container->hasParameter('templating.helper.code.file_link_format')) { $definition->replaceArgument(1, $container->getParameter('templating.helper.code.file_link_format')); } } }
Fix preview still being slightly different.
from django.views.decorators.csrf import csrf_exempt from django.views.generic import View from django.utils.decorators import method_decorator from django.shortcuts import render # Create your views here. class MarkdownPreview(View): template_name = "markdown_preview.html" @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): return render(request, self.template_name, {'body': request.POST['md'].strip()}) # Create your views here. class MarkdownPreviewSafe(View): template_name = "markdown_preview_safe.html" @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): return render(request, self.template_name, {'body': request.POST['md'].strip()}) class MarkdownPreviewNewsletter(View): template_name = "markdown_preview_newsletter.html" @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): return render(request, self.template_name, {'body': request.POST['md'].strip()}) class MarkdownPreviewText(View): template_name = "markdown_preview_text.html" @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): return render(request, self.template_name, {'body': request.POST['md'].strip()})
from django.views.decorators.csrf import csrf_exempt from django.views.generic import View from django.utils.decorators import method_decorator from django.shortcuts import render # Create your views here. class MarkdownPreview(View): template_name = "markdown_preview.html" @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): return render(request, self.template_name, {'body': request.POST['md'].strip()}) # Create your views here. class MarkdownPreviewSafe(View): template_name = "markdown_preview_safe.html" @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): return render(request, self.template_name, {'body': request.POST['md'].strip()}) class MarkdownPreviewNewsletter(View): template_name = "markdown_preview_newsletter.html" @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): return render(request, self.template_name, {'body': request.POST['md'].strip()}) class MarkdownPreviewText(View): template_name = "markdown_preview_newsletter.html" @method_decorator(csrf_exempt) def post(self, request, *args, **kwargs): return render(request, self.template_name, {'body': request.POST['md'].strip()})
Remove initial forward slash from url
<?php require 'src/EndpointRouter.php'; require 'src/endpoints/EndpointHandler.php'; require 'src/endpoints/SummaryEndpoint.php'; require 'src/endpoints/IPEndpoint.php'; require 'src/endpoints/RandomColorEndpoint.php'; require 'src/endpoints/TimeEndpoint.php'; header('Content-Type: application/json'); $router = new EndpointRouter(); $passiveEndpoints = array( new IPEndpoint('ip'), new TimeEndpoint('time'), new RandomColorEndpoint('color') ); $activeEndpoints = array(); $summaryEndpoint = new SummaryEndpoint('summary'); $summaryEndpoint->addHandlers($passiveEndpoints); $router->addEndpoint($summaryEndpoint); array_walk($passiveEndpoints, array($router, 'addEndpoint')); array_walk($activeEndpoints, array($router, 'addEndpoint')); $url = strtok($_SERVER["REQUEST_URI"],'?'); $url = ltrim($url, '/'); echo $router->process($url, $_GET, $_POST, array( 'ip' => $_SERVER['REMOTE_ADDR'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ));
<?php require 'src/EndpointRouter.php'; require 'src/endpoints/EndpointHandler.php'; require 'src/endpoints/SummaryEndpoint.php'; require 'src/endpoints/IPEndpoint.php'; require 'src/endpoints/RandomColorEndpoint.php'; require 'src/endpoints/TimeEndpoint.php'; header('Content-Type: application/json'); $router = new EndpointRouter(); $passiveEndpoints = array( new IPEndpoint('ip'), new TimeEndpoint('time'), new RandomColorEndpoint('color') ); $activeEndpoints = array(); $summaryEndpoint = new SummaryEndpoint('summary'); $summaryEndpoint->addHandlers($passiveEndpoints); $router->addEndpoint($summaryEndpoint); array_walk($passiveEndpoints, array($router, 'addEndpoint')); array_walk($activeEndpoints, array($router, 'addEndpoint')); $url = strtok($_SERVER["REQUEST_URI"],'?'); echo $router->process($url, $_GET, $_POST, array( 'ip' => $_SERVER['REMOTE_ADDR'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ));
Add an aipy version requirement
from setuptools import setup import glob import os.path as op from os import listdir from pyuvdata import version import json data = [version.git_origin, version.git_hash, version.git_description, version.git_branch] with open(op.join('pyuvdata', 'GIT_INFO'), 'w') as outfile: json.dump(data, outfile) setup_args = { 'name': 'pyuvdata', 'author': 'HERA Team', 'url': 'https://github.com/HERA-Team/pyuvdata', 'license': 'BSD', 'description': 'an interface for astronomical interferometeric datasets in python', 'package_dir': {'pyuvdata': 'pyuvdata'}, 'packages': ['pyuvdata', 'pyuvdata.tests'], 'scripts': glob.glob('scripts/*'), 'version': version.version, 'include_package_data': True, 'install_requires': ['numpy>=1.10', 'scipy', 'astropy>=1.2', 'pyephem', 'aipy>=2.1.5'], 'classifiers': ['Development Status :: 5 - Production/Stable', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Astronomy'], 'keywords': 'radio astronomy interferometry' } if __name__ == '__main__': apply(setup, (), setup_args)
from setuptools import setup import glob import os.path as op from os import listdir from pyuvdata import version import json data = [version.git_origin, version.git_hash, version.git_description, version.git_branch] with open(op.join('pyuvdata', 'GIT_INFO'), 'w') as outfile: json.dump(data, outfile) setup_args = { 'name': 'pyuvdata', 'author': 'HERA Team', 'url': 'https://github.com/HERA-Team/pyuvdata', 'license': 'BSD', 'description': 'an interface for astronomical interferometeric datasets in python', 'package_dir': {'pyuvdata': 'pyuvdata'}, 'packages': ['pyuvdata', 'pyuvdata.tests'], 'scripts': glob.glob('scripts/*'), 'version': version.version, 'include_package_data': True, 'install_requires': ['numpy>=1.10', 'scipy', 'astropy>=1.2', 'pyephem', 'aipy'], 'classifiers': ['Development Status :: 5 - Production/Stable', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Astronomy'], 'keywords': 'radio astronomy interferometry' } if __name__ == '__main__': apply(setup, (), setup_args)