text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix typo (OCA => OCP)
<?php /** * ownCloud - ImgCrawl * * @author Ackinty Strappa <[email protected]> * @copyright 2014 Ackinty * @license This file is licensed under the Affero General Public License version 3 or later. See the COPYING file. */ namespace OCA\ImgCrawl\Controller; use \OCP\AppFramework\APIController; use \OCP\AppFramework\Http\JSONResponse; use \OCP\IRequest; use \OCP\IConfig; class ImgCrawlAPIController extends APIController { protected $imgCrawlService; public function __construct($appName, IRequest $request, ImgCrawlService $imgCrawlService){ parent::__construct($appName, $request, 'GET'); $this->imgCrawlService = $imgCrawlService; } /** * Returns list of imgs * @NoCSRFRequired * @CORS */ public function index() { $images = array(); try { $images = $this->imgCrawlService->imgCrawl(); } catch (Exception $e) { $response = new JSONResponse(); return $response->setStatus(\OCP\AppFramework\Http::STATUS_NOT_FOUND); } if (empty($images)) { $response = new JSONResponse(); return $response->setStatus(\OCP\AppFramework\Http::STATUS_NOT_FOUND); } return new JSONResponse($images); } }
<?php /** * ownCloud - ImgCrawl * * @author Ackinty Strappa <[email protected]> * @copyright 2014 Ackinty * @license This file is licensed under the Affero General Public License version 3 or later. See the COPYING file. */ namespace OCA\ImgCrawl\Controller; use \OCP\AppFramework\APIController; use \OCP\AppFramework\Http\JSONResponse; use \OCP\IRequest; use \OCP\IConfig; class ImgCrawlAPIController extends APIController { protected $imgCrawlService; public function __construct($appName, IRequest $request, ImgCrawlService $imgCrawlService){ parent::__construct($appName, $request, 'GET'); $this->imgCrawlService = $imgCrawlService; } /** * Returns informations from history * @NoCSRFRequired * @CORS */ public function index() { $images = array(); try { $images = $this->imgCrawlService->imgCrawl(); } catch (Exception $e) { $response = new JSONResponse(); return $response->setStatus(\OCA\AppFramework\Http::STATUS_NOT_FOUND); } if (empty($images)) { $response = new JSONResponse(); return $response->setStatus(\OCA\AppFramework\Http::STATUS_NOT_FOUND); } return new JSONResponse($images); } }
Update FancyScrollBar to use arrow properties
import React, {Component, PropTypes} from 'react' import classnames from 'classnames' import {Scrollbars} from 'react-custom-scrollbars' class FancyScrollbar extends Component { constructor(props) { super(props) } static defaultProps = { autoHide: true, autoHeight: false, } handleMakeDiv = className => props => { return <div {...props} className={`fancy-scroll--${className}`} /> } render() { const {autoHide, autoHeight, children, className, maxHeight} = this.props return ( <Scrollbars className={classnames('fancy-scroll--container', { [className]: className, })} autoHide={autoHide} autoHideTimeout={1000} autoHideDuration={250} autoHeight={autoHeight} autoHeightMax={maxHeight} renderTrackHorizontal={this.handleMakeDiv('track-h')} renderTrackVertical={this.handleMakeDiv('track-v')} renderThumbHorizontal={this.handleMakeDiv('thumb-h')} renderThumbVertical={this.handleMakeDiv('thumb-v')} renderView={this.handleMakeDiv('view')} > {children} </Scrollbars> ) } } const {bool, node, number, string} = PropTypes FancyScrollbar.propTypes = { children: node.isRequired, className: string, autoHide: bool, autoHeight: bool, maxHeight: number, } export default FancyScrollbar
import React, {Component, PropTypes} from 'react' import classnames from 'classnames' import {Scrollbars} from 'react-custom-scrollbars' class FancyScrollbar extends Component { constructor(props) { super(props) } static defaultProps = { autoHide: true, autoHeight: false, } render() { const {autoHide, autoHeight, children, className, maxHeight} = this.props return ( <Scrollbars className={classnames('fancy-scroll--container', { [className]: className, })} autoHide={autoHide} autoHideTimeout={1000} autoHideDuration={250} autoHeight={autoHeight} autoHeightMax={maxHeight} renderTrackHorizontal={props => <div {...props} className="fancy-scroll--track-h" />} renderTrackVertical={props => <div {...props} className="fancy-scroll--track-v" />} renderThumbHorizontal={props => <div {...props} className="fancy-scroll--thumb-h" />} renderThumbVertical={props => <div {...props} className="fancy-scroll--thumb-v" />} renderView={props => <div {...props} className="fancy-scroll--view" />} > {children} </Scrollbars> ) } } const {bool, node, number, string} = PropTypes FancyScrollbar.propTypes = { children: node.isRequired, className: string, autoHide: bool, autoHeight: bool, maxHeight: number, } export default FancyScrollbar
Change property for painting element
/** * Class for drawing elements in canvas * @param {object} canvasElem handler of canvas */ var CanvasScreen = function ( canvasElem ) { const SIZE = 40; //size of square let ctx = canvasElem.getContext( "2d" ), currentX = 0, currentY = 0; let = drawSingleSquare = ( obj ) => { ctx.beginPath(); ctx.moveTo( currentX, currentY ); ctx.rect( currentX,currentY,SIZE,SIZE ); setBgSquare( obj ); ctx.fill(); ctx.stroke();//TODO delete } let setBgSquare = ( obj ) => { let bg; if ( obj.isActived ) { bg = obj.bgColor; } else { bg = "white"; } ctx.fillStyle = bg; } /** Public function, draw elements in canvas @param {array} array array of objects */ this.draw = function ( array ) { currentX = 0, currentY = 0; array.forEach( (v) => { v.forEach( (sq) => { //console.log(sq); drawSingleSquare(sq); currentX += SIZE; }); currentX = 0; currentY += SIZE; }); } }
/** * Class for drawing elements in canvas * @param {object} canvasElem handler of canvas */ var CanvasScreen = function ( canvasElem ) { const SIZE = 40; //size of square let ctx = canvasElem.getContext( "2d" ), currentX = 0, currentY = 0; let = drawSingleSquare = ( obj ) => { ctx.beginPath(); ctx.moveTo( currentX, currentY ); ctx.rect( currentX,currentY,SIZE,SIZE ); setBgSquare( obj ); ctx.fill(); ctx.stroke();//TODO delete } let setBgSquare = ( obj ) => { let bg; if ( obj.isFilled ) { bg = obj.bgColor; } else { bg = "white"; } ctx.fillStyle = bg; } /** Public function, draw elements in canvas @param {array} array array of objects */ this.draw = function ( array ) { currentX = 0, currentY = 0; array.forEach( (v) => { v.forEach( (sq) => { drawSingleSquare(sq); currentX += SIZE; }); currentX = 0; currentY += SIZE; }); } }
Update for current version of ZF2 tutorial.
<?php namespace Album; return array( 'controllers' => array( 'invokables' => array( 'Album\Controller\Album' => 'Album\Controller\AlbumController', ), ), // The following section is new and should be added to your file 'router' => array( 'routes' => array( 'album' => array( 'type' => 'segment', 'options' => array( 'route' => '/album[/][:action][/:id]', 'constraints' => array( 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'id' => '[0-9]+', ), 'defaults' => array( 'controller' => 'Album\Controller\Album', 'action' => 'index', ), ), ), ), ), 'view_manager' => array( 'template_path_stack' => array( 'album' => __DIR__ . '/../view', ), ), // Doctrine config 'doctrine' => array( 'driver' => array( __NAMESPACE__ . '_driver' => array( 'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver', 'cache' => 'array', 'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity') ), 'orm_default' => array( 'drivers' => array( __NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver' ) ) ) ) );
<?php return array( 'controllers' => array( 'invokables' => array( 'Album\Controller\Album' => 'Album\Controller\AlbumController', ), ), // The following section is new and should be added to your file 'router' => array( 'routes' => array( 'album' => array( 'type' => 'segment', 'options' => array( 'route' => '/album[/][:action][/:id]', 'constraints' => array( 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', 'id' => '[0-9]+', ), 'defaults' => array( 'controller' => 'Album\Controller\Album', 'action' => 'index', ), ), ), ), ), 'view_manager' => array( 'template_path_stack' => array( 'album' => __DIR__ . '/../view', ), ), );
Use the same colour for all activities
<?php namespace AppBundle\Services; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use CMEN\GoogleChartsBundle\GoogleCharts\Charts\Timeline; use AppBundle\Entity\MemberRegistration; class PersonReportService { private $em; private $formFactory; public function __construct(\Doctrine\ORM\EntityManagerInterface $em, \Symfony\Component\Form\FormFactoryInterface $formFactory) { $this->em = $em; $this->formFactory = $formFactory; } public function buildParticipationTimeline($person) { $currentMembershipPeriod = $person->getCurrentMemberRegistration()->getMembershipTypePeriod()->getMembershipPeriod(); $rows = []; foreach ($person->getParticipant() as $p) { if ( $p->getManagedActivity()->getActivityStart() <= $currentMembershipPeriod->getFromDate() && $p->getManagedActivity()->getActivityStart() < $currentMembershipPeriod->getToDate() ) { continue; } $rows[] = [ 'Participation', $p->getManagedActivity()->getName(), $p->getManagedActivity()->getActivityStart(), $p->getManagedActivity()->getActivityEnd() ]; } $timeline = new Timeline(); $timeline->getData()->setArrayToDataTable($rows, true); $timeline->getOptions()->getTimeline()->setColorByRowLabel(true); return $timeline; } }
<?php namespace AppBundle\Services; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use CMEN\GoogleChartsBundle\GoogleCharts\Charts\Timeline; use AppBundle\Entity\MemberRegistration; class PersonReportService { private $em; private $formFactory; public function __construct(\Doctrine\ORM\EntityManagerInterface $em, \Symfony\Component\Form\FormFactoryInterface $formFactory) { $this->em = $em; $this->formFactory = $formFactory; } public function buildParticipationTimeline($person) { $currentMembershipPeriod = $person->getCurrentMemberRegistration()->getMembershipTypePeriod()->getMembershipPeriod(); $rows = []; foreach ($person->getParticipant() as $p) { if ( $p->getManagedActivity()->getActivityStart() <= $currentMembershipPeriod->getFromDate() && $p->getManagedActivity()->getActivityStart() < $currentMembershipPeriod->getToDate() ) { continue; } $rows[] = [ 'Participation', $p->getManagedActivity()->getName(), $p->getManagedActivity()->getActivityStart(), $p->getManagedActivity()->getActivityEnd() ]; } $timeline = new Timeline(); $timeline->getData()->setArrayToDataTable($rows, true); return $timeline; } }
Remove request membership feature from project - add in euth.memberships app
from django.shortcuts import redirect from django.views import generic from rules.contrib import views as rules_views from . import mixins, models class ProjectDetailView(rules_views.PermissionRequiredMixin, mixins.PhaseDispatchMixin, generic.DetailView): model = models.Project permission_required = 'a4projects.view_project' @property def raise_exception(self): return self.request.user.is_authenticated() def handle_no_permission(self): """ Check if user clould join """ user = self.request.user is_member = user.is_authenticated() and self.project.has_member(user) if not is_member: return self.handle_no_membership() else: return super().handle_no_permission() def handle_no_membership(self): """ Handle that an authenticated user is not member of project. Override this function to configure the behaviour if a user has no permissions to view the project and is not member of the project. """ return super().handle_no_permission() @property def project(self): """ Emulate ProjectMixin interface for template sharing. """ return self.get_object()
from django.shortcuts import redirect from django.views import generic from rules.contrib import views as rules_views from . import mixins, models class ProjectDetailView(rules_views.PermissionRequiredMixin, mixins.PhaseDispatchMixin, generic.DetailView): model = models.Project permission_required = 'a4projects.view_project' @property def raise_exception(self): return self.request.user.is_authenticated() def handle_no_permission(self): """ Check if user clould join """ membership_impossible = ( not self.request.user.is_authenticated() or self.project.is_draft or self.project.has_member(self.request.user) ) if membership_impossible: return super().handle_no_permission() else: return self._redirect_membership_request() def _redirect_membership_request(self): return redirect('memberships-request', project_slug=self.project.slug) @property def project(self): """ Emulate ProjectMixin interface for template sharing. """ return self.get_object()
Fix up a typo in utilities
class ConfigItem(object): """The configuration item which may be bound with a instance. :param name: the property name. :param namespace: optional. the name of the attribute which contains all configuration nested in the instance. :param default: optional. the value which be provided while the configuration item has been missed. :param required: optional. if this paramater be ``True`` , getting missed configuration item without default value will trigger a ``RuntimeError`` . """ def __init__(self, name, namespace="config", default=None, required=False): self.name = name self.namespace = namespace self.default = default self.required = required def __repr__(self): template = "ConfigItem(%r, namespace=%r, default=%r, required=%r)" return template % (self.name, self.name, self.default, self.required) def __get__(self, instance, owner): if instance is None: return self namespace = self._namespace(instance) if self.name not in namespace and self.required: raise RuntimeError("missing %s['%s'] in %r" % (self.namespace, self.name, instance)) return namespace.get(self.name, self.default) def __set__(self, instance, value): namespace = self._namespace(instance) namespace[self.name] = value def _namespace(self, instance): """Gets exists namespace or creates it.""" if not hasattr(instance, self.namespace): setattr(instance, self.namespace, {}) return getattr(instance, self.namespace)
class ConfigItem(object): """The configuration item which may be bound with a instance. :param name: the property name. :param namespace: optional. the name of the attribute which contains all configuration nested in the instance. :param default: optional. the value which be provided while the configuration item has been missed. :param required: optional. if this paramater be ``True`` , getting missed configuration item without default value will trigger a ``RuntimeError`` . """ def __init__(self, name, namespace="config", default=None, required=False): self.name = name self.namespace = namespace self.default = default self.is_required = required def __repr__(self): template = "ConfigItem(%r, namespace=%r, default=%r, required=%r)" return template % (self.name, self.name, self.default, self.required) def __get__(self, instance, owner): if instance is None: return self namespace = self._namespace(instance) if self.name not in namespace and self.required: raise RuntimeError("missing %s['%s'] in %r" % (self.namespace, self.name, instance)) return namespace.get(self.name, self.default) def __set__(self, instance, value): namespace = self._namespace(instance) namespace[self.name] = value def _namespace(self, instance): """Gets exists namespace or creates it.""" if not hasattr(instance, self.namespace): setattr(instance, self.namespace, {}) return getattr(instance, self.namespace)
Add links to Github for source and bug tracker
import io from setuptools import setup AUTHOR = "Brian Curtin" EMAIL = "[email protected]" setup(name="deprecation", version="2.0.1", description="A library to handle automated deprecations", license="Apache 2", url="http://deprecation.readthedocs.io/", author=AUTHOR, author_email=EMAIL, maintainer=AUTHOR, maintainer_email=EMAIL, install_requires=["packaging"], keywords=["deprecation"], long_description=io.open("README.rst", encoding="utf-8").read(), py_modules=["deprecation"], classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules"], project_urls={"Documentation": "http://deprecation.readthedocs.io/en/latest/", "Source": "https://github.com/briancurtin/deprecation", "Bug Tracker": "https://github.com/briancurtin/deprecation/issues"}, )
import io from setuptools import setup AUTHOR = "Brian Curtin" EMAIL = "[email protected]" setup(name="deprecation", version="2.0", description="A library to handle automated deprecations", license="Apache 2", url="http://deprecation.readthedocs.io/", author=AUTHOR, author_email=EMAIL, maintainer=AUTHOR, maintainer_email=EMAIL, install_requires=["packaging"], keywords=["deprecation"], long_description=io.open("README.rst", encoding="utf-8").read(), py_modules=["deprecation"], classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules"] )
Update FAQ from 1.0 -> 4.0
<?php namespace CodeDay\Http\Controllers; use Symfony\Component\Yaml\Yaml; class FaqController extends Controller { public function getAll() { $result = ''; foreach (glob(resource_path('faq/*.yaml')) as $file) { $yaml = Yaml::parse(file_get_contents($file)); foreach ($yaml as $qa) { $result .= "<article><h1>{$qa['q']}</h1><p>{$qa['a']}</p></article>"; } } return response($result); } public function getIndex() { $q = \Input::get('q'); if (!$q) { return; } $host = \Config::get('azqna.host'); $kb = \Config::get('azqna.kb'); $key = \Config::get('azqna.key'); $url = "https://$host.azurewebsites.net/qnamaker/knowledgebases/$kb/generateAnswer"; $opts = ['http' => [ 'method' => 'POST', 'header' => [ 'Content-type: application/json', "Authorization: EndpointKey $key", 'Cache-Control: no-cache', ], 'content' => json_encode(['question' => $q]), ], ]; $context = stream_context_create($opts); $answer = json_decode(file_get_contents($url, false, $context))->answers[0]; if ($answer->score == 0) { return; } return $answer->answer; } }
<?php namespace CodeDay\Http\Controllers; use Symfony\Component\Yaml\Yaml; class FaqController extends Controller { public function getAll() { $result = ''; foreach (glob(resource_path('faq/*.yaml')) as $file) { $yaml = Yaml::parse(file_get_contents($file)); foreach ($yaml as $qa) { $result .= "<article><h1>{$qa['q']}</h1><p>{$qa['a']}</p></article>"; } } return response($result); } public function getIndex() { $q = \Input::get('q'); if (!$q) { return; } $kb = \Config::get('azqna.kb'); $key = \Config::get('azqna.key'); $url = "https://westus.api.cognitive.microsoft.com/qnamaker/v1.0/knowledgebases/$kb/generateAnswer"; $opts = ['http' => [ 'method' => 'POST', 'header' => [ 'Content-type: application/json', "Ocp-Apim-Subscription-Key: $key", 'Cache-Control: no-cache', ], 'content' => json_encode(['question' => $q]), ], ]; $context = stream_context_create($opts); $answer = json_decode(file_get_contents($url, false, $context)); if ($answer->score == 0) { return; } return $answer->answer; } }
Improve finding onElementReady Dependencies autmatically
<?php class Kwf_Assets_Provider_KwfUtils extends Kwf_Assets_Provider_Abstract { public function getDependenciesForDependency(Kwf_Assets_Dependency_Abstract $dependency) { if ($dependency instanceof Kwf_Assets_Dependency_File_Js) { $deps = array(); $c = $dependency->getContents('en'); if (preg_match('#^\s*Kwf\.Utils\.ResponsiveEl\(#m', $c)) { $deps[] = 'KwfResponsiveEl'; } if (preg_match('#^\s*Kwf\.on(Element|Content)(Ready|Show|Hide|WidthChange)\(#m', $c)) { $deps[] = 'KwfOnReady'; } if (preg_match('#^\s*Kwf\.onJElement(Ready|Show|Hide|WidthChange)\(#m', $c)) { $deps[] = 'KwfOnReadyJQuery'; } $ret = array(); foreach ($deps as $i) { $d = $this->_providerList->findDependency($i); if (!$d) throw new Kwf_Exception("Can't find dependency '$i'"); $ret[] = $d; } return array( Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_REQUIRES => $ret ); } return array(); } public function getDependency($dependencyName) { return null; } }
<?php class Kwf_Assets_Provider_KwfUtils extends Kwf_Assets_Provider_Abstract { public function getDependenciesForDependency(Kwf_Assets_Dependency_Abstract $dependency) { if ($dependency instanceof Kwf_Assets_Dependency_File_Js) { $deps = array(); $c = $dependency->getContents('en'); if (preg_match('#^\s*Kwf\.Utils\.ResponsiveEl\(#m', $c)) { $deps[] = 'KwfResponsiveEl'; } if (preg_match('#^\s*Kwf\.on(Element|Content)Ready\(#m', $c)) { $deps[] = 'KwfOnReady'; } if (preg_match('#^\s*Kwf\.onJElementReady\(#m', $c)) { $deps[] = 'KwfOnReadyJQuery'; } $ret = array(); foreach ($deps as $i) { $d = $this->_providerList->findDependency($i); if (!$d) throw new Kwf_Exception("Can't find dependency '$i'"); $ret[] = $d; } return array( Kwf_Assets_Dependency_Abstract::DEPENDENCY_TYPE_REQUIRES => $ret ); } return array(); } public function getDependency($dependencyName) { return null; } }
Fix extension detection in JSON generation
#!/usr/bin/python3 import os import json import glob data = {} data['comparisonfiles'] = {} for subset in next(os.walk("comparisonfiles/"))[1]: data['comparisonfiles'][subset] = {} data['comparisonfiles'][subset]["format"] = [] format_list = [ format for format in next(os.walk("comparisonfiles/" + subset + "/large"))[1] ] for format in format_list: extension = [ os.path.splitext(os.path.basename(fn))[1][1:] for fn in glob.glob( "comparisonfiles/" + subset + "/large/" + format + "/*") if os.path.splitext(os.path.basename(fn))[1] != ".png" ][0] data['comparisonfiles'][subset]["format"].append({ "extension": extension, "name": format }) data['comparisonfiles'][subset]["format"].append({ "extension": "png", "name": "Original" }) filenames_list = [ os.path.splitext(os.path.basename(files))[0] for files in next( os.walk("comparisonfiles/" + subset + "/Original/"))[2] ] data['comparisonfiles'][subset]["files"] = [] for filename in filenames_list: data['comparisonfiles'][subset]["files"].append({ "title": "", "filename": filename }) with open('comparisonfiles.json', 'w') as outfile: json.dump(data, outfile, indent=4)
#!/usr/bin/python3 import os import json import glob data = {} data['comparisonfiles'] = {} for subset in next(os.walk("comparisonfiles/"))[1]: data['comparisonfiles'][subset] = {} data['comparisonfiles'][subset]["format"] = [] format_list = [ format for format in next(os.walk("comparisonfiles/" + subset + "/large"))[1] ] for format in format_list: extension = [ os.path.splitext(os.path.basename(fn))[1][1:] for fn in glob.glob( "comparisonfiles/" + subset + "/large/" + format + "/*") if os.path.splitext(os.path.basename(fn))[1] != "png" ][0] data['comparisonfiles'][subset]["format"].append({ "extension": extension, "name": format }) data['comparisonfiles'][subset]["format"].append({ "extension": "png", "name": "Original" }) filenames_list = [ os.path.splitext(os.path.basename(files))[0] for files in next( os.walk("comparisonfiles/" + subset + "/Original/"))[2] ] data['comparisonfiles'][subset]["files"] = [] for filename in filenames_list: data['comparisonfiles'][subset]["files"].append({ "title": "", "filename": filename }) with open('comparisonfiles.json', 'w') as outfile: json.dump(data, outfile, indent=4)
Fix bug when generating random values with multiple editors
import { commands, window, Position, Selection } from 'vscode' import { extensionCommands, extensionCommandsWithInput } from './commands' import { MSG_NO_ACTIVE_TEXT_EDITOR } from './constants' export const activate = (context) => { extensionCommands.map(cmd => { context.subscriptions.push( commands.registerCommand(cmd.key, () => editorInsert(cmd.callback)) ) }) extensionCommandsWithInput.map(cmd => { context.subscriptions.push( commands.registerCommand(cmd.key, () => window.showInputBox({prompt: cmd.prompt}) .then(inputValue => { if (cmd.validation(inputValue)) { editorInsert(cmd.callback, {inputValue}) } else { window.showErrorMessage(cmd.errorMsg) } }) ) ) }) } const editorInsert = (generator, params = {}) => { const editor = window.activeTextEditor if (!editor) { window.showErrorMessage(MSG_NO_ACTIVE_TEXT_EDITOR) return } const newSelections = [] editor.edit((builder) => { editor.selections.map(selection => { const text = generator(params) builder.replace(selection, text) newSelections.push(getEndPosition(selection, text)) }) }).then(() => { editor.selections = newSelections }) } const getEndPosition = (selection, text) => { var endPosition = new Position(selection.start.line, selection.start.character + text.length) return new Selection(endPosition, endPosition) }
import { commands, window, Position, Selection } from 'vscode' import { extensionCommands, extensionCommandsWithInput } from './commands' import { MSG_NO_ACTIVE_TEXT_EDITOR } from './constants' export const activate = (context) => { extensionCommands.map(cmd => { context.subscriptions.push( commands.registerCommand(cmd.key, () => editorInsert(cmd.callback({}))) ) }) extensionCommandsWithInput.map(cmd => { context.subscriptions.push( commands.registerCommand(cmd.key, () => window.showInputBox({prompt: cmd.prompt}) .then(inputValue => { if (cmd.validation(inputValue)) { editorInsert(cmd.callback({inputValue})) } else { window.showErrorMessage(cmd.errorMsg) } }) ) ) }) } const editorInsert = (text) => { const editor = window.activeTextEditor if (!editor) { window.showErrorMessage(MSG_NO_ACTIVE_TEXT_EDITOR) return } const newSelections = [] editor.edit((builder) => { editor.selections.map(selection => { builder.replace(selection, text) newSelections.push(getEndPosition(selection, text)) }) }).then(() => { editor.selections = newSelections }) } const getEndPosition = (selection, text) => { var endPosition = new Position(selection.start.line, selection.start.character + text.length) return new Selection(endPosition, endPosition) }
Fix opps template engine (name list) on DetailView
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.views.generic.detail import DetailView as DjangoDetailView from django.contrib.sites.models import get_current_site from django.utils import timezone from opps.views.generic.base import View class DetailView(View, DjangoDetailView): def get_template_names(self): templates = [] domain_folder = self.get_template_folder() templates.append('{}/{}/{}/detail.html'.format(domain_folder, self.long_slug, self.slug)) templates.append('{}/{}/detail.html'.format(domain_folder, self.long_slug)) templates.append('{}/detail.html'.format(domain_folder)) return templates def get_queryset(self): self.site = get_current_site(self.request) self.slug = self.kwargs.get('slug') self.long_slug = self.get_long_slug() if not self.long_slug: return None self.set_channel_rules() filters = {} filters['site_domain'] = self.site.domain filters['channel_long_slug'] = self.long_slug filters['slug'] = self.slug preview_enabled = self.request.user and self.request.user.is_staff if not preview_enabled: filters['date_available__lte'] = timezone.now() filters['published'] = True queryset = super(DetailView, self).get_queryset() return queryset.filter(**filters)._clone()
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.core.exceptions import ImproperlyConfigured from django.views.generic.detail import DetailView as DjangoDetailView from django.contrib.sites.models import get_current_site from django.utils import timezone from opps.views.generic.base import View class DetailView(View, DjangoDetailView): def get_template_names(self): names = [] domain_folder = self.get_template_folder() names.append(u'{}/{}/{}.html'.format( domain_folder, self.long_slug, self.slug)) names.append(u'{}/{}.html'.format(domain_folder, self.long_slug)) try: names = names + super(DetailView, self).get_template_names() except ImproperlyConfigured: pass return names def get_queryset(self): self.site = get_current_site(self.request) self.slug = self.kwargs.get('slug') self.long_slug = self.get_long_slug() if not self.long_slug: return None self.set_channel_rules() filters = {} filters['site_domain'] = self.site.domain filters['channel_long_slug'] = self.long_slug filters['slug'] = self.slug preview_enabled = self.request.user and self.request.user.is_staff if not preview_enabled: filters['date_available__lte'] = timezone.now() filters['published'] = True queryset = super(DetailView, self).get_queryset() return queryset.filter(**filters)._clone()
Add sleep before new Chatbot instance is created on crash
import ConfigParser import threading import time import chatbot def runbot(t): config = ConfigParser.ConfigParser() config.readfp(open('./config.ini')) ws = chatbot.Chatbot(config.get('Chatbot', 'server'), protocols=['http-only', 'chat']) try: ws.connect() ws.run_forever() except Exception as e: print 'Exception: {0}\nArguments:\n{1!r}'.format(type(e).__name__, e.args) print 'Unable to connect. Timing out for %s seconds...' % t time.sleep(t) runbot(t+2) if __name__ == '__main__': while True: try: if 'chatbot' not in [x.name for x in threading.enumerate()]: time.sleep(10) bot = threading.Thread(target=runbot, name='chatbot', args=([2])) # Entire program exits when there are only daemon threads bot.daemon = True bot.start() except (KeyboardInterrupt, SystemExit): # Entire program will exit, since MainThread is the only non-daemon thread # The sole purpose of this is so CTRL+C etc. will close the whole program exit()
import ConfigParser import threading import time import chatbot def runbot(t): config = ConfigParser.ConfigParser() config.readfp(open('./config.ini')) ws = chatbot.Chatbot(config.get('Chatbot', 'server'), protocols=['http-only', 'chat']) try: ws.connect() ws.run_forever() except Exception as e: print 'Exception: {0}\nArguments:\n{1!r}'.format(type(e).__name__, e.args) print 'Unable to connect. Timing out for %s seconds...' % t time.sleep(t) runbot(t+2) if __name__ == '__main__': while True: try: if 'chatbot' not in [x.name for x in threading.enumerate()]: bot = threading.Thread(target=runbot, name='chatbot', args=([2])) # Entire program exits when there are only daemon threads bot.daemon = True bot.start() time.sleep(10) except (KeyboardInterrupt, SystemExit): # Entire program will exit, since MainThread is the only non-daemon thread # The sole purpose of this is so CTRL+C etc. will close the whole program exit()
Add documentation for Permutations class
from .misc import DancingLinks from .permutation import Permutation import random class Permutations(object): """Class for iterating through all Permutations of length n""" def __init__(self, n): """Returns an object giving all permutations of length n""" assert 0 <= n self.n = n def __iter__(self): """Iterates through permutations of length n in lexical order""" left = DancingLinks(range(1, self.n+1)) res = [] def gen(): if len(left) == 0: yield Permutation(list(res)) else: cur = left.front while cur is not None: left.erase(cur) res.append(cur.value) for p in gen(): yield p res.pop() left.restore(cur) cur = cur.next return gen() def random_element(self): """Returns a random permutation of length n""" p = [i+1 for i in range(self.n)] for i in range(self.n-1, -1, -1): j = random.randint(0, i) p[i], p[j] = p[j], p[i] return Permutation(p) def __str__(self): return 'The set of Permutations of length %d' % self.n def __repr__(self): return 'Permutations(%d)' % self.n
from .misc import DancingLinks from .permutation import Permutation import random class Permutations(object): def __init__(self, n): assert 0 <= n self.n = n def __iter__(self): left = DancingLinks(range(1, self.n+1)) res = [] def gen(): if len(left) == 0: yield Permutation(list(res)) else: cur = left.front while cur is not None: left.erase(cur) res.append(cur.value) for p in gen(): yield p res.pop() left.restore(cur) cur = cur.next return gen() def random_element(self): p = [ i+1 for i in range(self.n) ] for i in range(self.n-1, -1, -1): j = random.randint(0, i) p[i],p[j] = p[j],p[i] return Permutation(p) def __str__(self): return 'The set of Permutations of length %d' % self.n def __repr__(self): return 'Permutations(%d)' % self.n
Set abandoned clause in osio_topic_publisher.
""" Created on 9 Nov 2016 @author: Bruno Beloff ([email protected]) """ from scs_core.data.json import JSONify from scs_core.data.path_dict import PathDict # -------------------------------------------------------------------------------------------------------------------- class TopicClient(object): """ classdocs """ __HOST = "mqtt.opensensors.io" # hard-coded URL __TIMEOUT = 30.0 # ---------------------------------------------------------------------------------------------------------------- def __init__(self, message_client, auth): """ Constructor """ self.__message_client = message_client self.__auth = auth # ---------------------------------------------------------------------------------------------------------------- def connect(self): self.__message_client.connect(TopicClient.__HOST, self.__auth.client_id, self.__auth.user_id, self.__auth.client_password) def disconnect(self): self.__message_client.disconnect() # ---------------------------------------------------------------------------------------------------------------- def publish(self, topic, datum): datum_jstr = JSONify.dumps(datum) success = self.__message_client.publish(topic, datum_jstr, TopicClient.__TIMEOUT) return success def subscribe(self, topic): for payload_jstr in self.__message_client.subscribe(topic): path_dict = PathDict.construct_from_jstr(payload_jstr) yield (path_dict) # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return "TopicClient:{message_client:%s, auth:%s}" % (self.__message_client, self.__auth)
""" Created on 9 Nov 2016 @author: Bruno Beloff ([email protected]) """ from scs_core.data.json import JSONify from scs_core.data.path_dict import PathDict # -------------------------------------------------------------------------------------------------------------------- class TopicClient(object): """ classdocs """ __HOST = "mqtt.opensensors.io" # hard-coded URL __TIMEOUT = 10.0 # ---------------------------------------------------------------------------------------------------------------- def __init__(self, message_client, auth): """ Constructor """ self.__message_client = message_client self.__auth = auth # ---------------------------------------------------------------------------------------------------------------- def connect(self): self.__message_client.connect(TopicClient.__HOST, self.__auth.client_id, self.__auth.user_id, self.__auth.client_password) def disconnect(self): self.__message_client.disconnect() # ---------------------------------------------------------------------------------------------------------------- def publish(self, topic, datum): datum_jstr = JSONify.dumps(datum) success = self.__message_client.publish(topic, datum_jstr, TopicClient.__TIMEOUT) return success def subscribe(self, topic): for payload_jstr in self.__message_client.subscribe(topic): path_dict = PathDict.construct_from_jstr(payload_jstr) yield (path_dict) # ---------------------------------------------------------------------------------------------------------------- def __str__(self, *args, **kwargs): return "TopicClient:{message_client:%s, auth:%s}" % (self.__message_client, self.__auth)
Fix check for content type
"use strict"; function abortRequest(res) { res.statusCode = 415; res.end(); } function checkContentType(acceptedTypes, encoding) { var actualType, acceptedType, i, l; for (i = 0, l = acceptedTypes.length; i < l; i++) { acceptedTypes[i] = acceptedTypes[i].toLowerCase(); } return function checkContentType(req, res, next) { actualType = req.headers["content-type"] || ""; if (req.method === "POST" || req.method === "PUT") { actualType = actualType.toLowerCase(); if (encoding && actualType.search(encoding) === -1) { abortRequest(res); next(new Error("(alamid) Invalid request type: " + req.headers['content-type'])); return; } actualType = actualType.replace(/; *charset *=.*/gi, ''); for (i = 0, l = acceptedTypes.length; i < l; i++) { acceptedType = acceptedTypes[i]; if (acceptedType === actualType) { next(); return; } } abortRequest(res); next(new Error("(alamid) Invalid request type: " + req.headers["content-type"])); return; } next(); }; } module.exports = checkContentType;
"use strict"; function abortRequest(res) { res.statusCode = 415; res.end(); } function checkContentType(acceptedTypes, encoding) { var actualType, acceptedType, i, l; for (i = 0, l = acceptedTypes.length; i < l; i++) { acceptedTypes[i] = acceptedTypes[i].toLowerCase(); } return function checkContentType(req, res, next) { actualType = req.headers['content-type']; if (req.method === 'POST' || req.method === 'PUT') { actualType = actualType.toLowerCase(); if (encoding && actualType.search(encoding) === -1) { abortRequest(res); next(new Error("(alamid) Invalid request type: " + req.headers['content-type'])); return; } actualType = actualType.replace(/; *charset *=.*/gi, ''); for (i = 0, l = acceptedTypes.length; i < l; i++) { acceptedType = acceptedTypes[i]; if (acceptedType === actualType) { next(); return; } } abortRequest(res); next(new Error("(alamid) Invalid request type: " + req.headers['content-type'])); return; } next(); }; } module.exports = checkContentType;
Add an option to retrieve all fields, not only visible
<?php namespace Gloomy\PagerBundle\DataGrid; use Gloomy\PagerBundle\Pager\Wrapper; class DataGrid { protected $_request; protected $_router; protected $_pager; protected $_config; protected $_title; public function __construct($request, $router, $pager, array $config = array(), $title = '') { $this->_request = $request; $this->_router = $router; $this->_pager = $pager; $this->_config = $config; $this->_title = $title; } public function getPager() { return $this->_pager; } public function getFields($all = false) { $fields = array(); foreach ($this->getPager()->getFields() as $alias => $field) { if ($all || $field->isVisible()) { $fields[$alias] = $field; } } return $fields; } public function getItems() { return $this->getPager()->getItems(); } public function path($page = null, array $parameters = array()) { return $this->getPager()->path($page, $parameters); } public function setTitle($title) { $this->_title = $title; return $this; } public function getTitle() { return $this->_title; } }
<?php namespace Gloomy\PagerBundle\DataGrid; use Gloomy\PagerBundle\Pager\Wrapper; class DataGrid { protected $_request; protected $_router; protected $_pager; protected $_config; protected $_title; public function __construct($request, $router, $pager, array $config = array(), $title = '') { $this->_request = $request; $this->_router = $router; $this->_pager = $pager; $this->_config = $config; $this->_title = $title; } public function getPager() { return $this->_pager; } public function getFields() { $fields = array(); foreach ($this->getPager()->getFields() as $alias => $field) { if ($field->isVisible()) { $fields[$alias] = $field; } } return $fields; } public function getItems() { return $this->getPager()->getItems(); } public function path($page = null, array $parameters = array()) { return $this->getPager()->path($page, $parameters); } public function setTitle($title) { $this->_title = $title; return $this; } public function getTitle() { return $this->_title; } }
Fix creating link with prefix system
<?php use Ouzo\ControllerUrl; use OuzoBreadcrumb\Breadcrumb; class BreadcrumbHelper { public static function showBreadcrumbs($options = array()) { $options['class'] = isset($options['class']) ? $options['class'] : 'breadcrumb'; $attr = self::_prepareAttributes($options); $breadcrumbs = '<ol '.$attr.'>'; $breadcrumbsMap = Breadcrumb::getBreadcrumbs(); foreach ($breadcrumbsMap as $breadcrumb) { $name = $breadcrumb->getName(); $attribute = ''; if (end($breadcrumbsMap) === $breadcrumb) { $attribute = 'class="active"'; } else { $url = ControllerUrl::createUrl(array('string' => $breadcrumb->getPath())); $name = '<a href="' . $url . '">' . $breadcrumb->getName() . '</a>'; } $breadcrumbs .= ' <li ' . $attribute . '>' . $name . '</li> '; } $breadcrumbs .= '</ol> '; return $breadcrumbs; } private static function _prepareAttributes(array $attributes = array()) { $attr = ''; foreach ($attributes as $opt_key => $opt_value) { $attr .= $opt_key . '="' . $opt_value . '" '; } return trim($attr); } }
<?php use OuzoBreadcrumb\Breadcrumb; class BreadcrumbHelper { public static function showBreadcrumbs($options = array()) { $options['class'] = isset($options['class']) ? $options['class'] : 'breadcrumb'; $attr = self::_prepareAttributes($options); $breadcrumbs = '<ol '.$attr.'>'; $breadcrumbsMap = Breadcrumb::getBreadcrumbs(); foreach ($breadcrumbsMap as $breadcrumb) { $name = $breadcrumb->getName(); $attribute = ''; if (end($breadcrumbsMap) === $breadcrumb) { $attribute = 'class="active"'; } else { $name = '<a href="' . $breadcrumb->getPath() . '">' . $breadcrumb->getName() . '</a>'; } $breadcrumbs .= ' <li ' . $attribute . '>' . $name . '</li> '; } $breadcrumbs .= '</ol> '; return $breadcrumbs; } private static function _prepareAttributes(array $attributes = array()) { $attr = ''; foreach ($attributes as $opt_key => $opt_value) { $attr .= $opt_key . '="' . $opt_value . '" '; } return trim($attr); } }
Use the value directly cause it's carbon from the model
<?php namespace Anomaly\Streams\Addon\FieldType\Datetime; use Anomaly\Streams\Platform\Addon\FieldType\FieldTypePresenter; use Carbon\Carbon; /** * Class DatetimeFieldTypePresenter * * @link http://anomaly.is/streams-platform * @author AnomalyLabs, Inc. <[email protected]> * @author Ryan Thompson <[email protected]> * @package Anomaly\Streams\Addon\FieldType\Datetime */ class DatetimeFieldTypePresenter extends FieldTypePresenter { /** * Return the difference from now or * other in human readable format. * * @return null|string */ public function diffForHumans($other = null) { $value = $this->resource->getValue(); if ($value instanceof Carbon) { return $value->diffForHumans($other); } return null; } /** * Return the value and difference from now * or other in human readable format. * * @param null $other * @return null|string */ public function valueAndDiffForHumans($other = null) { $value = $this->resource->getValue(); if ($value instanceof Carbon) { $diff = $value->diffForHumans($other); return "{$value} <span class=\"text-muted\">({$diff})</span>"; } return null; } }
<?php namespace Anomaly\Streams\Addon\FieldType\Datetime; use Anomaly\Streams\Platform\Addon\FieldType\FieldTypePresenter; use Carbon\Carbon; /** * Class DatetimeFieldTypePresenter * * @link http://anomaly.is/streams-platform * @author AnomalyLabs, Inc. <[email protected]> * @author Ryan Thompson <[email protected]> * @package Anomaly\Streams\Addon\FieldType\Datetime */ class DatetimeFieldTypePresenter extends FieldTypePresenter { /** * The carbon instance loaded with our value. * * @var \Carbon\Carbon */ protected $carbon; /** * Create a new DatetimeFieldTypePresenter instance. * * @param $resource */ public function __construct(DatetimeFieldType $resource) { $value = $resource->getValue(); if ($value and !$resource->isZeros()) { $this->carbon = new Carbon($value); } parent::__construct($resource); } /** * Return the difference from now or * other in human readable format. * * @return null|string */ public function diffForHumans($other = null) { if ($this->carbon instanceof Carbon) { return $this->carbon->diffForHumans($other); } return null; } /** * Return the value and difference from now * or other in human readable format. * * @param null $other * @return null|string */ public function valueAndDiffForHumans($other = null) { if ($this->carbon instanceof Carbon) { $value = $this->resource->getValue(); $diff = $this->carbon->diffForHumans($other); return "{$value} <span class=\"text-muted\">({$diff})</span>"; } return null; } }
Use with to open file in read_stru
"""Theses functions read the legacy DISCUS stru file format in ASE Atoms.""" from __future__ import absolute_import from ase.atoms import Atoms from javelin.utils import unit_cell_to_vectors def read_stru(filename): with open(filename) as f: lines = f.readlines() a = b = c = alpha = beta = gamma = 0 reading_atom_list = False symbols = [] positions = [] for l in lines: line = l.replace(',', ' ').split() if not reading_atom_list: # Wait for 'atoms' line before reading atoms if line[0] == 'cell': a, b, c, alpha, beta, gamma = [float(x) for x in line[1:7]] cell = unit_cell_to_vectors(a, b, c, alpha, beta, gamma) if line[0] == 'atoms': if a == 0: print("Cell not found") cell = None reading_atom_list = True else: symbol, x, y, z = line[:4] symbol = symbol.capitalize() symbols.append(symbol) positions.append([float(x), float(y), float(z)]) # Return ASE Atoms object return Atoms(symbols=symbols, scaled_positions=positions, cell=cell)
"""Theses functions read the legacy DISCUS stru file format in ASE Atoms.""" from __future__ import absolute_import from ase.atoms import Atoms from javelin.utils import unit_cell_to_vectors def read_stru(filename): f = open(filename) lines = f.readlines() f.close() a = b = c = alpha = beta = gamma = 0 reading_atom_list = False symbols = [] positions = [] for l in lines: line = l.replace(',', ' ').split() if not reading_atom_list: # Wait for 'atoms' line before reading atoms if line[0] == 'cell': a, b, c, alpha, beta, gamma = [float(x) for x in line[1:7]] cell = unit_cell_to_vectors(a, b, c, alpha, beta, gamma) if line[0] == 'atoms': if a == 0: print("Cell not found") cell = None reading_atom_list = True else: symbol, x, y, z = line[:4] symbol = symbol.capitalize() symbols.append(symbol) positions.append([float(x), float(y), float(z)]) # Return ASE Atoms object return Atoms(symbols=symbols, scaled_positions=positions, cell=cell)
Add TODO to send these to quasar when tagging happens
<?php namespace Rogue\Console\Commands; use Rogue\Models\Tag; use Rogue\Models\Post; use Illuminate\Console\Command; class TagPosts extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'rogue:tagposts {--tag=: The id of the tag to use.} {--posts=: Comma-separated list of the post_ids to update.}'; /** * The console command description. * * @var string */ protected $description = 'Tag a set of posts with the given tag id'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $postIds = explode(',', $this->option('posts')); $posts = Post::find($postIds); $tag = Tag::findOrFail($this->option('tag')); if ($posts) { foreach ($posts as $post) { $this->info('Tagging post_id: '.$post->id.' as '.$tag->tag_slug); // @TODO - Send to quasar when tagged. $post->tag($tag->tag_name); } } } }
<?php namespace Rogue\Console\Commands; use Rogue\Models\Tag; use Rogue\Models\Post; use Illuminate\Console\Command; class TagPosts extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'rogue:tagposts {--tag=: The id of the tag to use.} {--posts=: Comma-separated list of the post_ids to update.}'; /** * The console command description. * * @var string */ protected $description = 'Tag a set of posts with the given tag id'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $postIds = explode(',', $this->option('posts')); $posts = Post::find($postIds); $tag = Tag::findOrFail($this->option('tag')); if ($posts) { foreach ($posts as $post) { $this->info('Tagging post_id: '.$post->id.' as '.$tag->tag_slug); $post->tag($tag->tag_name); } } } }
Enable requests on fixture station.
<?php namespace App\Entity\Fixture; use App\Radio\Adapters; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; use App\Entity; class Station extends AbstractFixture { public function load(ObjectManager $em) { $station = new Entity\Station; $station->setName('AzuraTest Radio'); $station->setDescription('A test radio station.'); $station->setEnableRequests(true); $station->setFrontendType(Adapters::FRONTEND_ICECAST); $station->setBackendType(Adapters::BACKEND_LIQUIDSOAP); $station->setRadioBaseDir('/var/azuracast/stations/azuratest_radio'); // Ensure all directories exist. $radio_dirs = [ $station->getRadioBaseDir(), $station->getRadioMediaDir(), $station->getRadioAlbumArtDir(), $station->getRadioPlaylistsDir(), $station->getRadioConfigDir(), $station->getRadioTempDir(), ]; foreach ($radio_dirs as $radio_dir) { if (!file_exists($radio_dir) && !mkdir($radio_dir, 0777) && !is_dir($radio_dir)) { throw new \RuntimeException(sprintf('Directory "%s" was not created', $radio_dir)); } } $station_quota = getenv('INIT_STATION_QUOTA'); if (!empty($station_quota)) { $station->setStorageQuota($station_quota); } $em->persist($station); $em->flush(); $this->addReference('station', $station); } }
<?php namespace App\Entity\Fixture; use App\Radio\Adapters; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\Persistence\ObjectManager; use App\Entity; class Station extends AbstractFixture { public function load(ObjectManager $em) { $station = new Entity\Station; $station->setName('AzuraTest Radio'); $station->setDescription('A test radio station.'); $station->setFrontendType(Adapters::FRONTEND_ICECAST); $station->setBackendType(Adapters::BACKEND_LIQUIDSOAP); $station->setRadioBaseDir('/var/azuracast/stations/azuratest_radio'); // Ensure all directories exist. $radio_dirs = [ $station->getRadioBaseDir(), $station->getRadioMediaDir(), $station->getRadioAlbumArtDir(), $station->getRadioPlaylistsDir(), $station->getRadioConfigDir(), $station->getRadioTempDir(), ]; foreach ($radio_dirs as $radio_dir) { if (!file_exists($radio_dir) && !mkdir($radio_dir, 0777) && !is_dir($radio_dir)) { throw new \RuntimeException(sprintf('Directory "%s" was not created', $radio_dir)); } } $station_quota = getenv('INIT_STATION_QUOTA'); if (!empty($station_quota)) { $station->setStorageQuota($station_quota); } $em->persist($station); $em->flush(); $this->addReference('station', $station); } }
Fix FeatureBrowser Accordion example tab captions svn changeset:8011/svn branch:6.0
package com.vaadin.demo.featurebrowser; import com.vaadin.ui.Accordion; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.Label; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; /** * Accordion is a derivative of TabSheet, a vertical tabbed layout that places * the tab contents between the vertical tabs. */ @SuppressWarnings("serial") public class AccordionExample extends CustomComponent { public AccordionExample() { // Create a new accordion final Accordion accordion = new Accordion(); setCompositionRoot(accordion); // Add a few tabs to the accordion. for (int i = 0; i < 5; i++) { // Create a root component for a accordion tab VerticalLayout layout = new VerticalLayout(); // The accordion tab label is taken from the caption of the root // component. Notice that layouts can have a caption too. layout.setCaption("Tab " + (i + 1)); accordion.addComponent(layout); // Add some components in each accordion tab Label label = new Label("These are the contents of Tab " + (i + 1) + "."); layout.addComponent(label); TextField textfield = new TextField("Some text field"); layout.addComponent(textfield); } } }
package com.vaadin.demo.featurebrowser; import com.vaadin.ui.Accordion; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.Label; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; /** * Accordion is a derivative of TabSheet, a vertical tabbed layout that places * the tab contents between the vertical tabs. */ @SuppressWarnings("serial") public class AccordionExample extends CustomComponent { public AccordionExample() { // Create a new accordion final Accordion accordion = new Accordion(); setCompositionRoot(accordion); // Add a few tabs to the accordion. for (int i = 0; i < 5; i++) { // Create a root component for a accordion tab VerticalLayout layout = new VerticalLayout(); accordion.addComponent(layout); // The accordion tab label is taken from the caption of the root // component. Notice that layouts can have a caption too. layout.setCaption("Tab " + (i + 1)); // Add some components in each accordion tab Label label = new Label("These are the contents of Tab " + (i + 1) + "."); layout.addComponent(label); TextField textfield = new TextField("Some text field"); layout.addComponent(textfield); } } }
Fix an issue where .focus() is scrolling the page, same as in UrlUI
const LoaderView = require('./Loader') const { h, Component } = require('preact') class AuthBlock extends Component { componentDidMount () { setTimeout(() => { this.connectButton.focus({ preventScroll: true }) }, 150) } render () { return <div class="uppy-Provider-auth"> <div class="uppy-Provider-authIcon">{this.props.pluginIcon()}</div> <h1 class="uppy-Provider-authTitle">Please authenticate with <span class="uppy-Provider-authTitleName">{this.props.pluginName}</span><br /> to select files</h1> <button type="button" class="uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Provider-authBtn" onclick={this.props.handleAuth} ref={(el) => { this.connectButton = el }} > Connect to {this.props.pluginName} </button> {this.props.demo && <button class="uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Provider-authBtn" onclick={this.props.handleDemoAuth}>Proceed with Demo Account</button> } </div> } } class AuthView extends Component { componentDidMount () { this.props.checkAuth() } render () { return ( <div style={{ height: '100%' }}> {this.props.checkAuthInProgress ? <LoaderView /> : <AuthBlock {...this.props} /> } </div> ) } } module.exports = AuthView
const LoaderView = require('./Loader') const { h, Component } = require('preact') class AuthBlock extends Component { componentDidMount () { this.connectButton.focus() } render () { return <div class="uppy-Provider-auth"> <div class="uppy-Provider-authIcon">{this.props.pluginIcon()}</div> <h1 class="uppy-Provider-authTitle">Please authenticate with <span class="uppy-Provider-authTitleName">{this.props.pluginName}</span><br /> to select files</h1> <button type="button" class="uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Provider-authBtn" onclick={this.props.handleAuth} ref={(el) => { this.connectButton = el }} > Connect to {this.props.pluginName} </button> {this.props.demo && <button class="uppy-u-reset uppy-c-btn uppy-c-btn-primary uppy-Provider-authBtn" onclick={this.props.handleDemoAuth}>Proceed with Demo Account</button> } </div> } } class AuthView extends Component { componentDidMount () { this.props.checkAuth() } render () { return ( <div style={{ height: '100%' }}> {this.props.checkAuthInProgress ? <LoaderView /> : <AuthBlock {...this.props} /> } </div> ) } } module.exports = AuthView
Copy facebook image on deployment
var webpack = require('webpack'); var path = require('path'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var CopyWebpackPlugin = require('copy-webpack-plugin'); var BUILD_DIR = path.resolve(__dirname, 'out'); var APP_DIR = path.resolve(__dirname, 'src'); var config = { entry: APP_DIR + '/index.jsx', output: { path: BUILD_DIR, publicPath: '/', filename: 'bundle.js', }, module: { loaders: [ { test: /\.jsx?/, include: APP_DIR, loader: 'babel', }, { test: /\.json$/, loader: 'json', }, { test: /\.css$/, loader: 'style!css', }, ], }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new HtmlWebpackPlugin({ template: 'index.ejs', }), new CopyWebpackPlugin([ { from: 'CNAME' }, { from: '404.html' }, { from: 'images/facebook4.png', to: 'images/facebook4.png' } ]), ], }; module.exports = config;
var webpack = require('webpack'); var path = require('path'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var CopyWebpackPlugin = require('copy-webpack-plugin'); var BUILD_DIR = path.resolve(__dirname, 'out'); var APP_DIR = path.resolve(__dirname, 'src'); var config = { entry: APP_DIR + '/index.jsx', output: { path: BUILD_DIR, publicPath: '/', filename: 'bundle.js', }, module: { loaders: [ { test: /\.jsx?/, include: APP_DIR, loader: 'babel', }, { test: /\.json$/, loader: 'json', }, { test: /\.css$/, loader: 'style!css', }, ], }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new HtmlWebpackPlugin({ template: 'index.ejs', }), new CopyWebpackPlugin([ { from: 'CNAME' }, { from: '404.html' }, ]), ], }; module.exports = config;
Use all lower pypi keywords and add command-line
# -*- coding: utf-8 -*- import pathlib from setuptools import setup def read(file_name): file_path = pathlib.Path(__file__).parent / file_name return file_path.read_text('utf-8') setup( name='cibopath', version='0.1.0', author='Raphael Pierzina', author_email='[email protected]', maintainer='Raphael Pierzina', maintainer_email='[email protected]', license='BSD', url='https://github.com/hackebrot/cibopath', description='Search Cookiecutters on GitHub.', long_description=read('README.rst'), packages=[ 'cibopath', ], package_dir={'cibopath': 'cibopath'}, include_package_data=True, zip_safe=False, install_requires=[ 'click', 'aiohttp', ], entry_points={ 'console_scripts': [ 'cibopath = cibopath.cli:main', ] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', ], keywords=['cookiecutter', 'web scraping', 'asyncio', 'command-line'], )
# -*- coding: utf-8 -*- import pathlib from setuptools import setup def read(file_name): file_path = pathlib.Path(__file__).parent / file_name return file_path.read_text('utf-8') setup( name='cibopath', version='0.1.0', author='Raphael Pierzina', author_email='[email protected]', maintainer='Raphael Pierzina', maintainer_email='[email protected]', license='BSD', url='https://github.com/hackebrot/cibopath', description='Search Cookiecutters on GitHub.', long_description=read('README.rst'), packages=[ 'cibopath', ], package_dir={'cibopath': 'cibopath'}, include_package_data=True, zip_safe=False, install_requires=[ 'click', 'aiohttp', ], entry_points={ 'console_scripts': [ 'cibopath = cibopath.cli:main', ] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', ], keywords=['Cookiecutter', 'Web Scraping', 'Asyncio'], )
Add missing behaviour in StripeJS mock
class Element { mount(el) { if (typeof el === "string") { el = document.querySelector(el); } el.classList.add('StripeElement'); el.innerHTML = ` <input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text"> <input name="exp-date" placeholder="MM / YY" size="6" type="text"> <input name="cvc" placeholder="CVC" size="3" type="text"> `; } addEventListener(event) { return true; } } window.Stripe = () => { const fetchLastFour = () => { return document.getElementById("stripe-cardnumber").value.substr(-4, 4); }; return { createPaymentMethod: () => { return new Promise(resolve => { resolve({ paymentMethod: { id: "pm_123", card: { brand: 'visa', last4: fetchLastFour(), exp_month: "10", exp_year: "2050" } } }); }); }, elements: () => { return { create: (type, options) => new Element() }; }, createToken: card => { return new Promise(resolve => { resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } }); }); } }; };
class Element { mount(el) { if (typeof el === "string") { el = document.querySelector(el); } el.innerHTML = ` <input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text"> <input name="exp-date" placeholder="MM / YY" size="6" type="text"> <input name="cvc" placeholder="CVC" size="3" type="text"> `; } addEventListener(event) { return true; } } window.Stripe = () => { const fetchLastFour = () => { return document.getElementById("stripe-cardnumber").value.substr(-4, 4); }; return { createPaymentMethod: () => { return new Promise(resolve => { resolve({ paymentMethod: { id: "pm_123", card: { brand: 'visa', last4: fetchLastFour(), exp_month: "10", exp_year: "2050" } } }); }); }, elements: () => { return { create: (type, options) => new Element() }; }, createToken: card => { return new Promise(resolve => { resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } }); }); } }; };
BLD: Use PEP 508 version markers. So that environment tooling, e.g. `pipenv` can use the python version markers when determining dependencies.
#!/usr/bin/env python from setuptools import setup, find_packages import sys long_description = '' if 'upload' in sys.argv: with open('README.rst') as f: long_description = f.read() def extras_require(): return { 'test': [ 'tox>=2.0', 'pytest>=2.8.5', 'pytest-cov>=1.8.1', 'pytest-pep8>=1.0.6', ], } def install_requires(): return [ 'six', 'typing>=3.5.2;python_version<"3.5"', 'funcsigs>=1.0.2;python_version<"3"' ] setup( name='python-interface', version='1.4.0', description="Pythonic Interface definitions", author="Scott Sanderson", author_email="[email protected]", packages=find_packages(), long_description=long_description, license='Apache 2.0', classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Pre-processors', ], url='https://github.com/ssanderson/interface', install_requires=install_requires(), extras_require=extras_require(), )
#!/usr/bin/env python from setuptools import setup, find_packages import sys long_description = '' if 'upload' in sys.argv: with open('README.rst') as f: long_description = f.read() def extras_require(): return { 'test': [ 'tox>=2.0', 'pytest>=2.8.5', 'pytest-cov>=1.8.1', 'pytest-pep8>=1.0.6', ], } def install_requires(): requires = ['six'] if sys.version_info[:2] < (3, 5): requires.append("typing>=3.5.2") if sys.version_info[0] == 2: requires.append("funcsigs>=1.0.2") return requires setup( name='python-interface', version='1.4.0', description="Pythonic Interface definitions", author="Scott Sanderson", author_email="[email protected]", packages=find_packages(), long_description=long_description, license='Apache 2.0', classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Pre-processors', ], url='https://github.com/ssanderson/interface', install_requires=install_requires(), extras_require=extras_require(), )
Use assertIn instead of assertTrue to test membership.
from __future__ import unicode_literals import unittest from mopidy.core import History from mopidy.models import Artist, Track class PlaybackHistoryTest(unittest.TestCase): def setUp(self): self.tracks = [ Track(uri='dummy1:a', name='foo', artists=[Artist(name='foober'), Artist(name='barber')]), Track(uri='dummy2:a', name='foo'), Track(uri='dummy3:a', name='bar') ] self.history = History() def test_add_track(self): self.history.add(self.tracks[0]) self.history.add(self.tracks[1]) self.history.add(self.tracks[2]) self.assertEqual(self.history.size, 3) def test_unsuitable_add(self): size = self.history.size self.history.add(self.tracks[0]) self.history.add(object()) self.history.add(self.tracks[1]) self.assertEqual(self.history.size, size + 2) def test_history_sanity(self): track = self.tracks[0] self.history.add(track) stored_history = self.history.get_history() track_ref = stored_history[0][1] self.assertEqual(track_ref.uri, track.uri) self.assertIn(track.name, track_ref.name) if track.artists: for artist in track.artists: self.assertIn(artist.name, track_ref.name)
from __future__ import unicode_literals import unittest from mopidy.core import History from mopidy.models import Artist, Track class PlaybackHistoryTest(unittest.TestCase): def setUp(self): self.tracks = [ Track(uri='dummy1:a', name='foo', artists=[Artist(name='foober'), Artist(name='barber')]), Track(uri='dummy2:a', name='foo'), Track(uri='dummy3:a', name='bar') ] self.history = History() def test_add_track(self): self.history.add(self.tracks[0]) self.history.add(self.tracks[1]) self.history.add(self.tracks[2]) self.assertEqual(self.history.size, 3) def test_unsuitable_add(self): size = self.history.size self.history.add(self.tracks[0]) self.history.add(object()) self.history.add(self.tracks[1]) self.assertEqual(self.history.size, size + 2) def test_history_sanity(self): track = self.tracks[0] self.history.add(track) stored_history = self.history.get_history() track_ref = stored_history[0][1] self.assertEqual(track_ref.uri, track.uri) self.assertTrue(track.name in track_ref.name) if track.artists: for artist in track.artists: self.assertTrue(artist.name in track_ref.name)
Change single quotes to double
#!/usr/bin/env python import unittest import ghstats class TestStats(unittest.TestCase): def test_cli(self): """ Test command line arguments. """ count = ghstats.main_cli(["kefir500/apk-icon-editor", "-q", "-d"]) self.assertTrue(count > 0) def test_releases(self): """ Download all releases. """ stats = ghstats.download_stats("kefir500", "apk-icon-editor", None, False, ghstats.get_env_token(), False) self.assertTrue(isinstance(stats, list)) count = ghstats.get_stats_downloads(stats, True) self.assertTrue(count > 0) def test_release(self): """ Download latest release. """ stats = ghstats.download_stats("kefir500", "apk-icon-editor", None, True, ghstats.get_env_token(), False) self.assertTrue(isinstance(stats, dict)) count = ghstats.get_stats_downloads(stats, True) self.assertTrue(count > 0) def test_invalid(self): """ Check nonexistent repository. """ self.assertRaises(ghstats.GithubRepoError, lambda: ghstats.download_stats("kefir500", "foobar", None, False, ghstats.get_env_token(), True)) if __name__ == "__main__": unittest.main()
#!/usr/bin/env python import unittest import ghstats class TestStats(unittest.TestCase): def test_cli(self): """ Test command line arguments. """ count = ghstats.main_cli(["kefir500/apk-icon-editor", "-q", "-d"]) self.assertTrue(count > 0) def test_releases(self): """ Download all releases. """ stats = ghstats.download_stats("kefir500", "apk-icon-editor", None, False, ghstats.get_env_token(), False) self.assertTrue(isinstance(stats, list)) count = ghstats.get_stats_downloads(stats, True) self.assertTrue(count > 0) def test_release(self): """ Download latest release. """ stats = ghstats.download_stats("kefir500", "apk-icon-editor", None, True, ghstats.get_env_token(), False) self.assertTrue(isinstance(stats, dict)) count = ghstats.get_stats_downloads(stats, True) self.assertTrue(count > 0) def test_invalid(self): """ Check nonexistent repository. """ self.assertRaises(ghstats.GithubRepoError, lambda: ghstats.download_stats("kefir500", "foobar", None, False, ghstats.get_env_token(), True)) if __name__ == '__main__': unittest.main()
THEATRE-113: Sort employees by group if it passed as a parameter
<?php namespace App\Repository; use App\Entity\Employee; use App\Entity\EmployeeGroup; use Doctrine\Common\Persistence\ManagerRegistry; use Symfony\Contracts\Translation\TranslatorInterface; class EmployeeRepository extends AbstractRepository { private TranslatorInterface $translator; public function __construct(ManagerRegistry $registry, TranslatorInterface $translator) { parent::__construct($registry, Employee::class); $this->translator = $translator; } /** * @return Employee[] * @throws \Doctrine\ORM\ORMException */ public function rand(int $limit, int $page, int $seed, string $locale, ?EmployeeGroup $group = null): array { $qb = $this->createQueryBuilder('e') ->setFirstResult(($page-1) * $limit) ->setMaxResults($limit); if (0 != $seed) { $qb->orderBy('RAND(:seed)') ->setParameter('seed', $seed); } else { $qb->orderBy('e.lastName', 'ASC'); } if ($group) { $qb->andWhere('e.employeeGroup = :group') ->setParameter('group', $group); } $employees = $qb ->getQuery() ->execute() ; $employeesTranslated = []; foreach ($employees as $employee) { $employee->setLocale($locale); $this->_em->refresh($employee); if ($employee->getTranslations()) { $employee->unsetTranslations(); } $this->translator->setLocale($locale); $employee->setPosition($this->translator->trans($employee->getPosition())); $employeesTranslated[] = $employee; } return $employeesTranslated; } }
<?php namespace App\Repository; use App\Entity\Employee; use Doctrine\Common\Persistence\ManagerRegistry; use Symfony\Contracts\Translation\TranslatorInterface; class EmployeeRepository extends AbstractRepository { private TranslatorInterface $translator; public function __construct(ManagerRegistry $registry, TranslatorInterface $translator) { parent::__construct($registry, Employee::class); $this->translator = $translator; } /** * @return Employee[] * @throws \Doctrine\ORM\ORMException */ public function rand(int $limit, int $page, int $seed, string $locale): array { $qb = $this->createQueryBuilder('e') ->setFirstResult(($page-1) * $limit) ->setMaxResults($limit); if (0 != $seed) { $qb->orderBy('RAND(:seed)') ->setParameter('seed', $seed); } else { $qb->orderBy('e.lastName', 'ASC'); } $employees = $qb ->getQuery() ->execute() ; $employeesTranslated = []; foreach ($employees as $employee) { $employee->setLocale($locale); $this->_em->refresh($employee); if ($employee->getTranslations()) { $employee->unsetTranslations(); } $this->translator->setLocale($locale); $employee->setPosition($this->translator->trans($employee->getPosition())); $employeesTranslated[] = $employee; } return $employeesTranslated; } }
Revert "Ensure store[uniqueId].path is defined"
'use strict'; var through = require('through2'); var stream = require('stream'); var File = require('vinyl'); module.exports = new NgStore(); function NgStore() { this.store = {}; } NgStore.prototype.register = function register(type) { if (!this.store[type]) { this.store[type] = []; } var store = this.store[type]; return through.obj(_register); function _register(file, enc, done) { var uniqueId = file.data.dirname + '.' + file.data.name; if (!store[uniqueId]) { store[uniqueId] = file.data; } //Override if more specific if (store[uniqueId].path.length < file.data.path.length) { store[uniqueId] = file.data; } return done(null, file); } }; NgStore.prototype.stream = function toStream() { var storeStream = new stream.Readable({ objectMode: true }); var store = this.store; var contents = {}; var type; for (type in store) { contents[type] = Object.keys(store[type]).map(function(path) { return store[type][path]; }); } storeStream._read = Function.prototype; storeStream.push(new File({ contents: new Buffer(JSON.stringify(contents)) })); storeStream.push(null); return storeStream; };
'use strict'; var through = require('through2'); var stream = require('stream'); var File = require('vinyl'); module.exports = new NgStore(); function NgStore() { this.store = {}; } NgStore.prototype.register = function register(type) { if (!this.store[type]) { this.store[type] = []; } var store = this.store[type]; return through.obj(_register); function _register(file, enc, done) { var uniqueId = file.data.dirname + '.' + file.data.name; if (!store[uniqueId]) { store[uniqueId] = file.data; } //Override if more specific if (store[uniqueId].path && store[uniqueId].path.length < file.data.path.length) { store[uniqueId] = file.data; } return done(null, file); } }; NgStore.prototype.stream = function toStream() { var storeStream = new stream.Readable({ objectMode: true }); var store = this.store; var contents = {}; var type; for (type in store) { contents[type] = Object.keys(store[type]).map(function(path) { return store[type][path]; }); } storeStream._read = Function.prototype; storeStream.push(new File({ contents: new Buffer(JSON.stringify(contents)) })); storeStream.push(null); return storeStream; };
Add --config "ui.merge=internal:fail" to merge call
/******************************************************************************* * Copyright (c) 2008 VecTrace (Zingo Andersen) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Bastian Doetsch - implementation *******************************************************************************/ package com.vectrace.MercurialEclipse.commands; import org.eclipse.core.resources.IResource; import com.vectrace.MercurialEclipse.exception.HgException; import com.vectrace.MercurialEclipse.preferences.MercurialPreferenceConstants; public class HgMergeClient extends AbstractClient { public static String merge(IResource res, String revision) throws HgException { HgCommand command = new HgCommand("merge", getWorkingDirectory(res), false); command .setUsePreferenceTimeout(MercurialPreferenceConstants.IMERGE_TIMEOUT); command.addOptions("--config","ui.merge=internal:fail"); if (revision != null) { command.addOptions("-r", revision); } try { String result = command.executeToString(); return result; } catch (HgException e) { // if conflicts aren't resolved and no merge tool is started, hg // exits with 1 if (!e.getMessage().startsWith("Process error, return code: 1")) { throw new HgException(e); } return e.getMessage(); } } }
/******************************************************************************* * Copyright (c) 2008 VecTrace (Zingo Andersen) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Bastian Doetsch - implementation *******************************************************************************/ package com.vectrace.MercurialEclipse.commands; import org.eclipse.core.resources.IResource; import com.vectrace.MercurialEclipse.exception.HgException; import com.vectrace.MercurialEclipse.preferences.MercurialPreferenceConstants; public class HgMergeClient extends AbstractClient { public static String merge(IResource res, String revision) throws HgException { HgCommand command = new HgCommand("merge", getWorkingDirectory(res), false); command .setUsePreferenceTimeout(MercurialPreferenceConstants.IMERGE_TIMEOUT); if (revision != null) { command.addOptions("-r", revision); } try { String result = command.executeToString(); return result; } catch (HgException e) { // if conflicts aren't resolved and no merge tool is started, hg // exits with 1 if (!e.getMessage().startsWith("Process error, return code: 1")) { throw new HgException(e); } return e.getMessage(); } } }
Improve all migrations command output formatting
<?php /* * This file is part of the Active Collab DatabaseMigrations project. * * (c) A51 doo <[email protected]>. All rights reserved. */ namespace ActiveCollab\DatabaseMigrations\Command; use ActiveCollab\DatabaseMigrations\MigrationsInterface; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @package ActiveCollab\DatabaseMigrations\Command */ trait All { /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $migrations = $this->getMigrations()->getMigrations(); if ($migrations_count = count($migrations)) { if ($migrations_count === 1) { $output->writeln('<info>One</info> migration found:'); } else { $output->writeln("<info>{$migrations_count}</info> migrations found:"); } $output->writeln(''); foreach ($migrations as $migration) { $execution_status = $this->getMigrations()->isExecuted($migration) ? '<info>Executed</info>' : '<comment>Not executed</comment>'; $output->writeln(' <comment>*</comment> ' . get_class($migration) . " ($execution_status)"); } $output->writeln(''); } else { $output->writeln('No migrations found'); } return 0; } /** * @return MigrationsInterface */ abstract protected function &getMigrations(); }
<?php /* * This file is part of the Active Collab DatabaseMigrations project. * * (c) A51 doo <[email protected]>. All rights reserved. */ namespace ActiveCollab\DatabaseMigrations\Command; use ActiveCollab\DatabaseMigrations\MigrationsInterface; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @package ActiveCollab\DatabaseMigrations\Command */ trait All { /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $migrations = $this->getMigrations()->getMigrations(); if ($migrations_count = count($migrations)) { if ($migrations_count === 1) { $output->writeln('One migration found:'); } else { $output->writeln("{$migrations_count} migrations found:"); } $output->writeln(''); foreach ($migrations as $migration) { $output->writeln(' <comment>*</comment> ' . get_class($migration)); } } else { $output->writeln('No migrations found'); } return 0; } /** * @return MigrationsInterface */ abstract protected function &getMigrations(); }
Add schema comparator to diff command.
<?php namespace LazyRecord\Command; use Exception; use CLIFramework\Command; use LazyRecord\Schema; use LazyRecord\Schema\SchemaFinder; use LazyRecord\ConfigLoader; class DiffCommand extends Command { public function brief() { return 'diff database schema.'; } public function options($opts) { // --data-source $opts->add('D|data-source:', 'specify data source id'); } public function execute() { $options = $this->options; $logger = $this->logger; $loader = ConfigLoader::getInstance(); $loader->load(); $loader->initForBuild(); $connectionManager = \LazyRecord\ConnectionManager::getInstance(); $logger->info("Initialize connection manager..."); // XXX: from config files $id = $options->{'data-source'} ?: 'default'; $conn = $connectionManager->getConnection($id); $driver = $connectionManager->getQueryDriver($id); $finder = new SchemaFinder; if( $paths = $loader->getSchemaPaths() ) { $finder->paths = $paths; } $finder->loadFiles(); $classes = $finder->getSchemaClasses(); // XXX: currently only mysql support $parser = \LazyRecord\TableParser::create( $driver, $conn ); $tableSchemas = array(); $tables = $parser->getTables(); foreach( $tables as $table ) { $tableSchemas[ $table ] = $parser->getTableSchema( $table ); } $comparator = new \LazyRecord\Schema\Comparator; foreach( $classes as $class ) { $b = new $class; $t = $b->getTable(); if( isset( $tableSchemas[ $t ] ) ) { $a = $tableSchemas[ $t ]; $diff = $comparator->compare( $a , $b ); $printer = new \LazyRecord\Schema\Comparator\ConsolePrinter($diff); $printer->output(); } } } }
<?php namespace LazyRecord\Command; use Exception; use CLIFramework\Command; use LazyRecord\Schema; use LazyRecord\Schema\SchemaFinder; use LazyRecord\ConfigLoader; class DiffCommand extends Command { public function brief() { return 'diff database schema.'; } public function options($opts) { // --data-source $opts->add('D|data-source:', 'specify data source id'); } public function execute() { $options = $this->options; $logger = $this->logger; $loader = ConfigLoader::getInstance(); $loader->load(); $loader->initForBuild(); $connectionManager = \LazyRecord\ConnectionManager::getInstance(); $logger->info("Initialize connection manager..."); // XXX: from config files $id = $options->{'data-source'} ?: 'default'; $conn = $connectionManager->getConnection($id); $driver = $connectionManager->getQueryDriver($id); // XXX: currently only mysql support $parser = \LazyRecord\TableParser::create( $driver, $conn ); $tableSchemas = array(); $tables = $parser->getTables(); foreach( $tables as $table ) { $tableSchemas[ $table ] = $parser->getTableSchema( $table ); } } }
scripts: Fix MySQL command executing (MySQL commit).
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") cnx.commit() # Close connection and database cursor.close() cnx.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=config['mysql_root_pass']) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") # Close connection and database cursor.close() cnx.close()
Make endpoints api cors friendly
<?php namespace OParl\Website\API\Controllers; use App\Model\Endpoint; use Illuminate\Http\Request; class EndpointApiController { /** * @SWG\Get( * path="/endpoints", * tags={ "endpoints" }, * summary="list endpoints", * @SWG\Response( * response="200", * description="A listing of known OParl endpoints", * @SWG\Schema( * @SWG\Property( property="data", type="array", @SWG\Items( ref="#/definitions/Endpoint" )) * ) * ) * ) * * @param Request $request * * @return \Illuminate\Http\JsonResponse */ public function index(Request $request) { $page = 0; $itemsPerPage = 25; if ($request->has('page')) { $page = intval($request->get('page')); } $endpoints = Endpoint::with('bodies')->get()->forPage($page, $itemsPerPage); $pageCount = floor($endpoints->count() / $itemsPerPage); return response()->json([ 'data' => $endpoints, 'meta' => [ 'page' => $page, 'total' => $pageCount, 'next' => ($pageCount > $page) ? route('api.endpoints.index', ['page' => ++$page]) : null, ], ], 200, [ 'Content-Type' => 'application/json', 'Access-Control-Allow-Origin' => '*', ]); } }
<?php namespace OParl\Website\API\Controllers; use App\Model\Endpoint; use Illuminate\Http\Request; class EndpointApiController { /** * @SWG\Get( * path="/endpoints", * tags={ "endpoints" }, * summary="list endpoints", * @SWG\Response( * response="200", * description="A listing of known OParl endpoints", * @SWG\Schema( * @SWG\Property( property="data", type="array", @SWG\Items( ref="#/definitions/Endpoint" )) * ) * ) * ) * * @param Request $request * * @return \Illuminate\Http\JsonResponse */ public function index(Request $request) { $page = 0; $itemsPerPage = 25; if ($request->has('page')) { $page = intval($request->get('page')); } $endpoints = Endpoint::with('bodies')->get()->forPage($page, $itemsPerPage); $pageCount = floor($endpoints->count() / $itemsPerPage); return response()->json([ 'data' => $endpoints, 'meta' => [ 'page' => $page, 'total' => $pageCount, 'next' => ($pageCount > $page) ? route('api.endpoints.index', ['page' => ++$page]) : null, ], ]); } }
Add validation before Add To Cart
<?php namespace hipanel\actions; use hiqdev\hiart\Collection; use Yii; use yii\base\Action; class AddToCartAction extends Action { public $productClass; public $bulkLoad = false; public function run() { $data = null; $collection = new Collection([ 'model' => new $this->productClass ]); $cart = Yii::$app->cart; $request = Yii::$app->request; // $data = $request->isPost ? $request->post() : $request->get(); if (!$this->bulkLoad) { $data = [Yii::$app->request->post() ?: Yii::$app->request->get()]; } if ($collection->load($data) && $collection->validate()) { foreach ($collection->models as $position) { if (!$cart->hasPosition($position->getId())) { $cart->put($position); Yii::$app->session->addFlash('success', Yii::t('app', 'Item is added to cart')); } else { Yii::$app->session->addFlash('warning', Yii::t('app', 'Item already exists in the cart')); } } } else { Yii::$app->session->addFlash('warning', Yii::t('app', 'Item does not exists')); } if ($request->isAjax) { Yii::$app->end(); } else { return $this->controller->redirect(Yii::$app->request->referrer); } } }
<?php namespace hipanel\actions; use hiqdev\hiart\Collection; use Yii; use yii\base\Action; class AddToCartAction extends Action { public $productClass; public $bulkLoad = false; public function run() { $data = null; $collection = new Collection([ 'model' => new $this->productClass ]); $cart = Yii::$app->cart; $request = Yii::$app->request; // $data = $request->isPost ? $request->post() : $request->get(); if (!$this->bulkLoad) { $data = [Yii::$app->request->post() ?: Yii::$app->request->get()]; } if ($collection->load($data)) { foreach ($collection->models as $position) { if (!$cart->hasPosition($position->getId())) { $cart->put($position); Yii::$app->session->addFlash('success', Yii::t('app', 'Item is added to cart')); } else { Yii::$app->session->addFlash('warning', Yii::t('app', 'Item already exists in the cart')); } } } if ($request->isAjax) { Yii::$app->end(); } else { return $this->controller->redirect(Yii::$app->request->referrer); } } }
Remove JSX element left by mistake
var React = require('react'); var Header = require('./header'); var Feed = require('./feed'); var App = React.createClass({ getInitialState: function() { return { requests: [] } }, render: function() { return ( <div> <Header clearHandler={this._handleClear} pauseHandler={this._handlePause} resumeHandler={this._handleResume} /> <Feed requests={this.state.requests} /> </div> ); }, updateState: function() { var isScrolledToBottom = this._isScrolledToBottom(); this.setState({requests: this.props.messageParser.requests}); if(isScrolledToBottom) { this._scrollToBottom(); } }, _handleClear: function() { this.props.messageParser.clear(); this.updateState(); }, _handlePause: function() { this.props.webSocketManager.pause(); }, _handleResume: function() { this.props.webSocketManager.resume(); }, _isScrolledToBottom: function() { return ((window.innerHeight + window.scrollY) >= document.body.offsetHeight); }, _scrollToBottom: function() { window.scrollTo(0,document.body.scrollHeight); } }); module.exports = App;
var React = require('react'); var Header = require('./header'); var Feed = require('./feed'); var App = React.createClass({ getInitialState: function() { return { requests: [] } }, render: function() { return ( <div> <Header Header clearHandler={this._handleClear} pauseHandler={this._handlePause} resumeHandler={this._handleResume} /> <Feed requests={this.state.requests} /> </div> ); }, updateState: function() { var isScrolledToBottom = this._isScrolledToBottom(); this.setState({requests: this.props.messageParser.requests}); if(isScrolledToBottom) { this._scrollToBottom(); } }, _handleClear: function() { this.props.messageParser.clear(); this.updateState(); }, _handlePause: function() { this.props.webSocketManager.pause(); }, _handleResume: function() { this.props.webSocketManager.resume(); }, _isScrolledToBottom: function() { return ((window.innerHeight + window.scrollY) >= document.body.offsetHeight); }, _scrollToBottom: function() { window.scrollTo(0,document.body.scrollHeight); } }); module.exports = App;
Throw an error for unrecoverable exceptions.
package com.cjmalloy.torrentfs.server; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.glassfish.jersey.servlet.ServletContainer; public class Entry { public static final int DEFAULT_PORT = 8080; public static void main(String[] args) { int port = DEFAULT_PORT; if (args.length == 1) { port = Integer.parseInt(args[0]); } else if (args.length != 0) { System.out.println("Usage: torrent-fs [PORT]"); return; } Server server = new Server(port); ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); ServletHolder sh = context.addServlet(ServletContainer.class, "/*"); sh.setInitOrder(1); sh.setInitParameter("jersey.config.server.provider.packages","com.cjmalloy.torrentfs.server.remote.rest"); try { server.start(); System.out.println("Server started on port " + port); server.join(); } catch (Exception e) { throw new Error(e); } } }
package com.cjmalloy.torrentfs.server; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.glassfish.jersey.servlet.ServletContainer; public class Entry { public static final int DEFAULT_PORT = 8080; public static void main(String[] args) { int port = DEFAULT_PORT; if (args.length == 1) { port = Integer.parseInt(args[0]); } else if (args.length != 0) { System.out.println("Usage: torrent-fs [PORT]"); return; } Server server = new Server(port); ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); ServletHolder sh = context.addServlet(ServletContainer.class, "/*"); sh.setInitOrder(1); sh.setInitParameter("jersey.config.server.provider.packages","com.cjmalloy.torrentfs.server.remote.rest"); try { server.start(); System.out.println("Server started on port " + port); server.join(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Add return types to internal & magic methods when possible
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Workflow; /** * A list of transition blockers. * * @author Grégoire Pineau <[email protected]> */ final class TransitionBlockerList implements \IteratorAggregate, \Countable { private $blockers; /** * @param TransitionBlocker[] $blockers */ public function __construct(array $blockers = []) { $this->blockers = []; foreach ($blockers as $blocker) { $this->add($blocker); } } public function add(TransitionBlocker $blocker): void { $this->blockers[] = $blocker; } public function has(string $code): bool { foreach ($this->blockers as $blocker) { if ($code === $blocker->getCode()) { return true; } } return false; } public function clear(): void { $this->blockers = []; } public function isEmpty(): bool { return !$this->blockers; } /** * {@inheritdoc} * * @return \ArrayIterator|TransitionBlocker[] */ public function getIterator(): \Traversable { return new \ArrayIterator($this->blockers); } public function count(): int { return \count($this->blockers); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Workflow; /** * A list of transition blockers. * * @author Grégoire Pineau <[email protected]> */ final class TransitionBlockerList implements \IteratorAggregate, \Countable { private $blockers; /** * @param TransitionBlocker[] $blockers */ public function __construct(array $blockers = []) { $this->blockers = []; foreach ($blockers as $blocker) { $this->add($blocker); } } public function add(TransitionBlocker $blocker): void { $this->blockers[] = $blocker; } public function has(string $code): bool { foreach ($this->blockers as $blocker) { if ($code === $blocker->getCode()) { return true; } } return false; } public function clear(): void { $this->blockers = []; } public function isEmpty(): bool { return !$this->blockers; } /** * {@inheritdoc} * * @return \ArrayIterator|TransitionBlocker[] */ public function getIterator() { return new \ArrayIterator($this->blockers); } public function count(): int { return \count($this->blockers); } }
Revert to ES search results
<?php namespace makeandship\elasticsearch\transformer; use makeandship\elasticsearch\Config; class SearchTransformer { public function transform($response) { $val = array( 'total' => $response->getTotalHits(), 'facets' => array(), 'ids' => array(), 'results' => array() ); foreach ($response->getAggregations() as $name => $agg) { if (isset($agg['facet']['buckets'])) { foreach ($agg['facet']['buckets'] as $bucket) { $val['facets'][$name][$bucket['key']] = $bucket['doc_count']; } } if (isset($agg['range']['buckets'])) { foreach ($agg['range']['buckets'] as $bucket) { $from = isset($bucket['from']) ? $bucket['from'] : ''; $to = isset($bucket['to']) && $bucket['to'] != '*' ? $bucket['to'] : ''; $val['facets'][$name][$from . '-' . $to] = $bucket['doc_count']; } } } foreach ($response->getResults() as $result) { $id = $result->getId(); $source = $result->getSource(); $source['id'] = $id; $val['ids'][] = $id; $val['results'][] = $source; } return Config::apply_filters('searcher_results', $val, $response); } }
<?php namespace makeandship\elasticsearch\transformer; use makeandship\elasticsearch\Config; class SearchTransformer { public function transform($response) { $val = array( 'total' => $response->getTotalHits(), 'facets' => array(), 'ids' => array() ); foreach ($response->getAggregations() as $name => $agg) { if (isset($agg['facet']['buckets'])) { foreach ($agg['facet']['buckets'] as $bucket) { $val['facets'][$name][$bucket['key']] = $bucket['doc_count']; } } if (isset($agg['range']['buckets'])) { foreach ($agg['range']['buckets'] as $bucket) { $from = isset($bucket['from']) ? $bucket['from'] : ''; $to = isset($bucket['to']) && $bucket['to'] != '*' ? $bucket['to'] : ''; $val['facets'][$name][$from . '-' . $to] = $bucket['doc_count']; } } } foreach ($response->getResults() as $result) { $val['ids'][] = $result->getId(); } return Config::apply_filters('searcher_results', $val, $response); } }
Update to using Request::current() method
<?php defined('SYSPATH') or die('No direct script access.'); class Prophet { public static function exception_handler(Exception $e) { if (Kohana::$environment === Kohana::DEVELOPMENT) { Kohana_Exception::handler($e); } // It's a nice time to log :) Kohana::$log->add(Kohana_Log::ERROR, Kohana_Exception::text($e)); if ( ! defined('SUPPRESS_REQUEST')) { $request = array( // Get status from current request 'action' => Request::current()->status(), // If exception has a message this can be passed on 'message' => rawurlencode($e->getMessage()), ); // Override status if HTTP_Exception thrown if ($e instanceof HTTP_Exception) { $request['action'] = $e->getCode(); } echo Request::factory(Route::get('prophet_error')->uri($request)) ->execute() ->send_headers() ->response; } } }
<?php defined('SYSPATH') or die('No direct script access.'); class Prophet { public static function exception_handler(Exception $e) { if (Kohana::$environment === Kohana::DEVELOPMENT) { Kohana_Exception::handler($e); } // It's a nice time to log :) Kohana::$log->add(Kohana_Log::ERROR, Kohana_Exception::text($e)); if ( ! defined('SUPPRESS_REQUEST')) { $request = array( // Get status from current request 'action' => Request::$current->status(), // If exception has a message this can be passed on 'message' => rawurlencode($e->getMessage()), ); // Override status if HTTP_Exception thrown if ($e instanceof HTTP_Exception) { $request['action'] = $e->getCode(); } echo Request::factory(Route::get('prophet_error')->uri($request)) ->execute() ->send_headers() ->response; } } }
Replace php 5.4 array notation
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\Bundle\DemoBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Symfony\Component\Validator\Constraints as Assert; /** * @author Thomas Rabaix <[email protected]> */ class InspectionAdmin extends Admin { /** * {@inheritdoc} */ protected function configureDatagridFilters(DatagridMapper $filter) { $filter ->add('date') ->add('car') ; } /** * {@inheritdoc} */ protected function configureListFields(ListMapper $list) { $list ->addIdentifier('date') ->add('car') ; } /** * {@inheritdoc} */ protected function configureFormFields(FormMapper $formMapper) { if (!$this->hasParentFieldDescription()) { $formMapper->add('car', null, array('constraints' => new Assert\NotNull())); } $formMapper->add('date', null, array('widget' => 'single_text')); } }
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\Bundle\DemoBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Symfony\Component\Validator\Constraints as Assert; /** * @author Thomas Rabaix <[email protected]> */ class InspectionAdmin extends Admin { /** * {@inheritdoc} */ protected function configureDatagridFilters(DatagridMapper $filter) { $filter ->add('date') ->add('car') ; } /** * {@inheritdoc} */ protected function configureListFields(ListMapper $list) { $list ->addIdentifier('date') ->add('car') ; } /** * {@inheritdoc} */ protected function configureFormFields(FormMapper $formMapper) { if (!$this->hasParentFieldDescription()) { $formMapper->add('car', null, array('constraints' => new Assert\NotNull())); } $formMapper->add('date', null, ['widget' => 'single_text']); } }
Include README to data_files properly
#!/usr/bin/env python # -*- coding: utf-8 -*- import websitepoller from setuptools import setup description = "Polls specified websites and alerts using system notifications." try: from pypandoc import convert long_description = convert('README.md', 'rst') except (ImportError, IOError, OSError): print 'check that you have installed pandoc properly and that ' + \ 'README.md exists!' long_description = description setup( name="website-poller", version=websitepoller.__version__, url='http://koodilehto.github.com/website-poller', license='MIT', description=description, long_description=long_description, author=websitepoller.__author__, author_email='[email protected]', packages=['websitepoller', ], package_dir={'websitepoller': 'websitepoller', }, install_requires=['setuptools', ], data_files=[('', ['README.md'])], entry_points=""" [console_scripts] websitepoller = websitepoller:run """, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Internet', 'Topic :: Internet :: WWW/HTTP', 'Topic :: System :: Networking :: Monitoring', ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- import websitepoller from setuptools import setup description = "Polls specified websites and alerts using system notifications." try: from pypandoc import convert long_description = convert('README.md', 'rst') except (ImportError, IOError, OSError): print 'check that you have installed pandoc properly and that ' + \ 'README.md exists!' long_description = description setup( name="website-poller", version=websitepoller.__version__, url='http://koodilehto.github.com/website-poller', license='MIT', description=description, long_description=long_description, author=websitepoller.__author__, author_email='[email protected]', packages=['websitepoller', ], package_dir={'websitepoller': 'websitepoller', }, install_requires=['setuptools', ], data_files=['README.md'], entry_points=""" [console_scripts] websitepoller = websitepoller:run """, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Internet', 'Topic :: Internet :: WWW/HTTP', 'Topic :: System :: Networking :: Monitoring', ], )
Modify the start_date to date.
// GraphQL types import { GraphQLObjectType, GraphQLString, GraphQLID, GraphQLInt, GraphQLFloat } from 'graphql'; const WorkLog_TYPE = new GraphQLObjectType({ name: 'worklog', descriptyion: 'An bug object', fields: () => ({ 'id': { type: GraphQLID, description: 'work log ID' }, 'employee_id': { type: GraphQLString, description: 'employee ID' }, 'date': { type: GraphQLFloat, description: 'date' }, 'content': { type: GraphQLString, description: 'work log content' }, 'progress': { type: GraphQLInt, description: 'progress' }, 'type': { type: GraphQLString, description: 'workday/pto/holiday' }, 'tag': { type: GraphQLString, description: 'worklog tag' }, 'status': { type: GraphQLInt, description: 'is completed or not' }, 'task': { type: GraphQLString, description: 'task title' }, 'duration': { type: GraphQLInt, description: 'task duration' }, 'release': { type: GraphQLString, description: 'release name' }, 'creater': { type: GraphQLString, description: 'task creater' } }) }); export default WorkLog_TYPE;
// GraphQL types import { GraphQLObjectType, GraphQLString, GraphQLID, GraphQLInt, GraphQLFloat } from 'graphql'; const WorkLog_TYPE = new GraphQLObjectType({ name: 'worklog', descriptyion: 'An bug object', fields: () => ({ 'id': { type: GraphQLID, description: 'work log ID' }, 'employee_id': { type: GraphQLString, description: 'employee ID' }, 'start_date': { type: GraphQLFloat, description: 'date' }, 'content': { type: GraphQLString, description: 'work log content' }, 'progress': { type: GraphQLInt, description: 'progress' }, 'type': { type: GraphQLString, description: 'workday/pto/holiday' }, 'tag': { type: GraphQLString, description: 'worklog tag' }, 'status': { type: GraphQLInt, description: 'is completed or not' }, 'task': { type: GraphQLString, description: 'task title' }, 'duration': { type: GraphQLInt, description: 'task duration' }, 'release': { type: GraphQLString, description: 'release name' }, 'creater': { type: GraphQLString, description: 'task creater' } }) }); export default WorkLog_TYPE;
Update the namespace during inflection
<?php namespace Cerbero\FluentApi\Inflectors; /** * Resource inflector using the PSR-4 standard. * * @author Andrea Marco Sartori */ class Psr4ResourceInflector implements ResourceInflectorInterface { /** * The base namespace. * * @author Andrea Marco Sartori * @var string */ protected $namespace; /** * The version number. * * @author Andrea Marco Sartori * @var string */ protected $version; /** * Set the base namespace. * * @author Andrea Marco Sartori * @param string $namespace * @return $this */ public function baseNamespace($namespace) { $this->namespace = $namespace; return $this; } /** * Set the version number. * * @author Andrea Marco Sartori * @param string $version * @return $this */ public function version($version) { $this->version = ucfirst($version); return $this; } /** * Inflect the given name returning the full resource name. * * @author Andrea Marco Sartori * @param string $name * @return string */ public function inflect($name) { $segments = [$this->namespace, $this->version, ucfirst($name)]; return $this->namespace = implode('\\', array_filter($segments)); } }
<?php namespace Cerbero\FluentApi\Inflectors; /** * Resource inflector using the PSR-4 standard. * * @author Andrea Marco Sartori */ class Psr4ResourceInflector implements ResourceInflectorInterface { /** * The base namespace. * * @author Andrea Marco Sartori * @var string */ protected $namespace; /** * The version number. * * @author Andrea Marco Sartori * @var string */ protected $version; /** * Set the base namespace. * * @author Andrea Marco Sartori * @param string $namespace * @return $this */ public function baseNamespace($namespace) { $this->namespace = $namespace; return $this; } /** * Set the version number. * * @author Andrea Marco Sartori * @param string $version * @return $this */ public function version($version) { $this->version = ucfirst($version); return $this; } /** * Inflect the given name returning the full resource name. * * @author Andrea Marco Sartori * @param string $name * @return string */ public function inflect($name) { $segments = [$this->namespace, $this->version, ucfirst($name)]; return implode('\\', array_filter($segments)); } }
Check that map isn't being called passing in null arguments. (This seems wrong; see JIRA entry GSA-211) git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@1907 348d0f76-0448-11de-a6fe-93d51630548a
package org.broadinstitute.sting.gatk.walkers.fasta; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.refdata.ReferenceOrderedDatum; import org.broadinstitute.sting.gatk.walkers.RodWalker; import org.broadinstitute.sting.utils.genotype.Variation; import java.util.Iterator; public class CreateSequenomMask extends RodWalker<Integer, Integer> { public void initialize() {} public Integer map(RefMetaDataTracker rodData, ReferenceContext ref, AlignmentContext context) { int result = 0; if ( rodData == null ) // apparently, RodWalkers make funky map calls return 0; Iterator<ReferenceOrderedDatum> rods = rodData.getAllRods().iterator(); while (rods.hasNext()) { ReferenceOrderedDatum rod = rods.next(); if ( rod instanceof Variation && ((Variation)rod).isSNP() ) { out.println(context.getLocation()); result = 1; break; } } return result; } public Integer reduceInit() { return 0; } public Integer reduce(Integer value, Integer sum) { return value + sum; } public void onTraversalDone(Integer sum) { logger.info("Found " + sum + " masking sites."); } }
package org.broadinstitute.sting.gatk.walkers.fasta; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.refdata.ReferenceOrderedDatum; import org.broadinstitute.sting.gatk.walkers.RodWalker; import org.broadinstitute.sting.utils.genotype.Variation; import java.util.Iterator; public class CreateSequenomMask extends RodWalker<Integer, Integer> { public void initialize() {} public Integer map(RefMetaDataTracker rodData, ReferenceContext ref, AlignmentContext context) { int result = 0; Iterator<ReferenceOrderedDatum> rods = rodData.getAllRods().iterator(); while (rods.hasNext()) { ReferenceOrderedDatum rod = rods.next(); if ( rod instanceof Variation && ((Variation)rod).isSNP() ) { out.println(context.getLocation()); result = 1; break; } } return result; } public Integer reduceInit() { return 0; } public Integer reduce(Integer value, Integer sum) { return value + sum; } public void onTraversalDone(Integer sum) { logger.info("Found " + sum + " masking sites."); } }
Remove request-payload as a dependency
/* * Server * */ // Define dependencies const http = require('http'); const StringDecoder = require('string_decoder').StringDecoder; // Create module object var server = {}; // Is listening already server.isListening = false; // Listen server.listen = function(){ if(!server.isListening){ server.httpServer = http.createServer((req,res) => { // Add the payload to the request var decoder = new StringDecoder('utf-8'); var buffer = ''; // This section inspired by the 'request-payload' npm module req.on('data', function(data) { buffer += decoder.write(data); }); req.on('end', function() { req.body = buffer + decoder.end(); // Pass the request to the request processor app.lib.req.process(req,res); }); }); var port = typeof(app.config.port) == 'number' ? app.config.port : 3000; server.httpServer.listen(port); server.isListening = true; app.lib.log.msg('Petite microservice listening on port '+port); return true; } else { return false; } }; // Stop listening server.close = function(callback){ callback = typeof(callback) == 'function' ? callback : false; if(server.isListening){ server.httpServer.close(function () { server.isListening = false; if(callback){ callback(true); } }); } else { if(callback){ callback(false); } } }; // Export the module module.exports = server;
/* * Server * */ // Define dependencies const http = require('http'); const payload = require('request-payload'); // Create module object var server = {}; // Is listening already server.isListening = false; // Listen server.listen = function(){ if(!server.isListening){ server.httpServer = http.createServer((req,res) => { // Add the payload to the request payload(req, function(body) { req.body = body; // Pass the request to the request processor app.lib.req.process(req,res); }); }); var port = typeof(app.config.port) == 'number' ? app.config.port : 3000; server.httpServer.listen(port); server.isListening = true; app.lib.log.msg('Petite microservice listening on port '+port); return true; } else { return false; } }; // Stop listening server.close = function(callback){ callback = typeof(callback) == 'function' ? callback : false; if(server.isListening){ server.httpServer.close(function () { server.isListening = false; if(callback){ callback(true); } }); } else { if(callback){ callback(false); } } }; // Export the module module.exports = server;
Make test ignore JSON semantics
<?php /* * This file is part of the Silex framework. * * (c) Fabien Potencier <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Silex\Tests; use Silex\Application; /** * JSON test cases. * * @author Igor Wiedler <[email protected]> */ class JsonTest extends \PHPUnit_Framework_TestCase { public function testJsonReturnsJsonResponse() { $app = new Application(); $response = $app->json(); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); $response = json_decode($response->getContent(), true); $this->assertSame(array(), $response); } public function testJsonUsesData() { $app = new Application(); $response = $app->json(array('foo' => 'bar')); $this->assertSame('{"foo":"bar"}', $response->getContent()); } public function testJsonUsesStatus() { $app = new Application(); $response = $app->json(array(), 202); $this->assertSame(202, $response->getStatusCode()); } public function testJsonUsesHeaders() { $app = new Application(); $response = $app->json(array(), 200, array('ETag' => 'foo')); $this->assertSame('foo', $response->headers->get('ETag')); } }
<?php /* * This file is part of the Silex framework. * * (c) Fabien Potencier <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Silex\Tests; use Silex\Application; /** * JSON test cases. * * @author Igor Wiedler <[email protected]> */ class JsonTest extends \PHPUnit_Framework_TestCase { public function testJsonReturnsJsonResponse() { $app = new Application(); $response = $app->json(); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); $this->assertSame('{}', $response->getContent()); } public function testJsonUsesData() { $app = new Application(); $response = $app->json(array('foo' => 'bar')); $this->assertSame('{"foo":"bar"}', $response->getContent()); } public function testJsonUsesStatus() { $app = new Application(); $response = $app->json(array(), 202); $this->assertSame(202, $response->getStatusCode()); } public function testJsonUsesHeaders() { $app = new Application(); $response = $app->json(array(), 200, array('ETag' => 'foo')); $this->assertSame('foo', $response->headers->get('ETag')); } }
Store local IP address for next call
/* * UG Name Util for Syndicate */ package SyndicateHadoop.util; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; /** * * @author iychoi */ public class UGNameUtil { private static String ipAddress = null; private static boolean ipAddressChecked = false; private static String getIPAddress() { if(!ipAddressChecked) { try { Enumeration e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); if (i instanceof Inet4Address) { if (i.isLoopbackAddress()) { continue; } if (i.isMulticastAddress()) { continue; } if (i.isSiteLocalAddress()) { continue; } // get first ipaddress ipAddress = i.getHostAddress(); ipAddressChecked = true; return ipAddress; } } } } catch (SocketException ex) { ipAddress = null; ipAddressChecked = true; return null; } } return ipAddress; } public static String getUGName(String prefix) { String address = null; address = getIPAddress(); if(address == null || address.isEmpty()) { return null; } else { if(prefix == null) return address.replaceAll("\\.", "_"); else return prefix + address.replaceAll("\\.", "_"); } } }
/* * UG Name Util for Syndicate */ package SyndicateHadoop.util; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import org.apache.hadoop.conf.Configuration; /** * * @author iychoi */ public class UGNameUtil { private static String getIPAddress() throws SocketException { Enumeration e = NetworkInterface.getNetworkInterfaces(); while(e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); Enumeration ee = n.getInetAddresses(); while(ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); if(i instanceof Inet4Address) { if(i.isLoopbackAddress()) continue; if(i.isMulticastAddress()) continue; if(i.isSiteLocalAddress()) continue; return i.getHostAddress(); } } } return null; } public static String getUGName(String prefix) { String address = null; try { address = getIPAddress(); } catch (SocketException ex) {} if(address == null || address.isEmpty()) { return null; } else { if(prefix == null) return address.replaceAll("\\.", "_"); else return prefix + address.replaceAll("\\.", "_"); } } }
Add UUID on user update
package br.com.alura.agenda.modelo; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; public class Aluno implements Serializable { @JsonProperty("idCliente") private Long id; private String nome; private String endereco; private String telefone; private String site; private Double nota; private String caminhoFoto; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public Double getNota() { return nota; } public void setNota(Double nota) { this.nota = nota; } public String getCaminhoFoto() { return caminhoFoto; } public void setCaminhoFoto(String caminhoFoto) { this.caminhoFoto = caminhoFoto; } @Override public String toString() { return getId() + " - " + getNome(); } }
package br.com.alura.agenda.modelo; import java.io.Serializable; /** * Created by alura on 12/08/15. */ public class Aluno implements Serializable { private Long id; private String nome; private String endereco; private String telefone; private String site; private Double nota; private String caminhoFoto; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public Double getNota() { return nota; } public void setNota(Double nota) { this.nota = nota; } public String getCaminhoFoto() { return caminhoFoto; } public void setCaminhoFoto(String caminhoFoto) { this.caminhoFoto = caminhoFoto; } @Override public String toString() { return getId() + " - " + getNome(); } }
Remove @ from user on Dab command
package com.nincraft.ninbot.command; import com.nincraft.ninbot.util.MessageUtils; import lombok.val; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; public class DabCommand extends AbstractCommand { public DabCommand() { length = 3; name = "dab"; description = "Adds all dab emojis to the last message of the user named"; } @Override public void executeCommand(MessageReceivedEvent event) { val content = event.getMessage().getContent(); if (isCommandLengthCorrect(content)) { val channel = event.getChannel(); val dabUser = content.split(" ")[2].replaceFirst("@", ""); int count = 0; int maxDab = 10; for (Message message : channel.getIterableHistory()) { if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) { dabOnMessage(message); break; } if (count >= maxDab) { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); break; } count++; } } else { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); } } private void dabOnMessage(Message message) { val guild = message.getGuild(); for (val emote : guild.getEmotes()) { if (emote.getName().contains("dab")) { MessageUtils.addReaction(message, emote); } } } }
package com.nincraft.ninbot.command; import com.nincraft.ninbot.util.MessageUtils; import lombok.val; import net.dv8tion.jda.core.entities.Message; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; public class DabCommand extends AbstractCommand { public DabCommand() { length = 3; name = "dab"; description = "Adds all dab emojis to the last message of the user named"; } @Override public void executeCommand(MessageReceivedEvent event) { val content = event.getMessage().getContent(); if (isCommandLengthCorrect(content)) { val channel = event.getChannel(); val dabUser = content.split(" ")[2]; int count = 0; int maxDab = 10; for (Message message : channel.getIterableHistory()) { if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) { dabOnMessage(message); break; } if (count >= maxDab) { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); break; } count++; } } else { MessageUtils.reactUnsuccessfulResponse(event.getMessage()); } } private void dabOnMessage(Message message) { val guild = message.getGuild(); for (val emote : guild.getEmotes()) { if (emote.getName().contains("dab")) { MessageUtils.addReaction(message, emote); } } } }
Use \Page instead of Concrete\Core\Page\Page
<?php namespace Concrete\Core\Page\Type\Composer\Control\CorePageProperty; use Core; use UserInfo; use Page; class UserCorePageProperty extends CorePageProperty { public function __construct() { $this->setCorePagePropertyHandle('user'); $this->setPageTypeComposerControlName(tc('PageTypeComposerControlName', 'User')); $this->setPageTypeComposerControlIconSRC(ASSETS_URL . '/attributes/text/icon.png'); } public function publishToPage(Page $c, $data, $controls) { if (Core::make('helper/validation/numbers')->integer($data['user'])) { $this->addPageTypeComposerControlRequestValue('uID', $data['user']); } parent::publishToPage($c, $data, $controls); } public function validate() { $uID = $this->getPageTypeComposerControlDraftValue(); $ux = UserInfo::getByID($uID); $e = Core::make('helper/validation/error'); if (!is_object($ux)) { $control = $this->getPageTypeComposerFormLayoutSetControlObject(); $e->add(t('You haven\'t chosen a valid %s', $control->getPageTypeComposerControlLabel())); return $e; } } public function getPageTypeComposerControlDraftValue() { if (is_object($this->page)) { $c = $this->page; return $c->getCollectionUserID(); } } }
<?php namespace Concrete\Core\Page\Type\Composer\Control\CorePageProperty; use Core; use UserInfo; use Concrete\Core\Page\Page; class UserCorePageProperty extends CorePageProperty { public function __construct() { $this->setCorePagePropertyHandle('user'); $this->setPageTypeComposerControlName(tc('PageTypeComposerControlName', 'User')); $this->setPageTypeComposerControlIconSRC(ASSETS_URL . '/attributes/text/icon.png'); } public function publishToPage(Page $c, $data, $controls) { if (Core::make('helper/validation/numbers')->integer($data['user'])) { $this->addPageTypeComposerControlRequestValue('uID', $data['user']); } parent::publishToPage($c, $data, $controls); } public function validate() { $uID = $this->getPageTypeComposerControlDraftValue(); $ux = UserInfo::getByID($uID); $e = Core::make('helper/validation/error'); if (!is_object($ux)) { $control = $this->getPageTypeComposerFormLayoutSetControlObject(); $e->add(t('You haven\'t chosen a valid %s', $control->getPageTypeComposerControlLabel())); return $e; } } public function getPageTypeComposerControlDraftValue() { if (is_object($this->page)) { $c = $this->page; return $c->getCollectionUserID(); } } }
Fix concurrency bug in ls tests
from tests.framework.cli_testcase import CliTestCase from tests.framework.constants import GO_EP1_ID class LsTests(CliTestCase): """ Tests globus ls command """ def test_path(self): """ Does an ls on EP1:/, confirms expected results. """ path = "/" output = self.run_line("globus ls {}:{}".format(GO_EP1_ID, path)) expected = ["home/", "mnt/", "not shareable/", "share/"] for item in expected: self.assertIn(item, output) def test_recursive(self): """ Confirms --recursive ls on EP1:/share/ finds file1.txt """ output = self.run_line("globus ls -r {}:/share/".format(GO_EP1_ID)) self.assertIn("file1.txt", output) def test_depth(self): """ Confirms setting depth to 1 on a --recursive ls of EP1:/ finds godata but not file1.txt """ output = self.run_line(("globus ls -r --recursive-depth-limit 1 {}:/" .format(GO_EP1_ID))) self.assertNotIn("file1.txt", output) def test_recursive_json(self): """ Confirms -F json works with the RecursiveLsResponse """ output = self.run_line( "globus ls -r -F json {}:/share".format(GO_EP1_ID)) self.assertIn('"DATA":', output) self.assertIn('"name": "godata/file1.txt"', output)
from tests.framework.cli_testcase import CliTestCase from tests.framework.constants import GO_EP1_ID class LsTests(CliTestCase): """ Tests globus ls command """ def test_path(self): """ Does an ls on EP1:/, confirms expected results. """ path = "/" output = self.run_line("globus ls {}:{}".format(GO_EP1_ID, path)) expected = ["home/", "mnt/", "not shareable/", "share/"] for item in expected: self.assertIn(item, output) def test_recursive(self): """ Confirms --recursive ls on EP1:/share/ finds file1.txt """ output = self.run_line("globus ls -r {}:/share/".format(GO_EP1_ID)) self.assertIn("file1.txt", output) def test_depth(self): """ Confirms setting depth to 1 on a --recursive ls of EP1:/ finds godata but not file1.txt """ output = self.run_line(("globus ls -r --recursive-depth-limit 1 {}:/" .format(GO_EP1_ID))) self.assertNotIn("file1.txt", output) def test_recursive_json(self): """ Confirms -F json works with the RecursiveLsResponse """ output = self.run_line("globus ls -r -F json {}:/".format(GO_EP1_ID)) self.assertIn('"DATA":', output) self.assertIn('"name": "share/godata/file1.txt"', output)
Fix opening links in browser on Windows
'use strict' var opn = require('open') var http = require('http') var fs = require('fs') var url = require('url') var path = require('path') var Promise = require('bluebird') function hostLogin (domain, options) { return new Promise(function (resolve) { var server = http .createServer(function (req, res) { if (/favicon/.test(req.url)) { res.statusCode = 404 res.statusMessage = 'Not found' res.end() return } if (/^\/somefile/.test(req.url)) { var urlObj = url.parse(req.url, true) server.close() return resolve({ access_token: urlObj.query.access_token }) } var f = req.url.split('?')[0] var file = path.join(__dirname, '/public/' + f) res.writeHead(200, { 'Content-Length': fs.statSync(file).size }) var readStream = fs.createReadStream(file) readStream.pipe(res) }) .listen(8000, function () { opn( 'http://localhost:8000/index.html?domain=' + JSON.stringify(domain) + '&options=' + JSON.stringify(options), { url: true } ) }) }) } module.exports = hostLogin
'use strict'; var opn = require('open'); var http = require('http'); var fs = require('fs'); var url = require('url'); var path = require('path'); var Promise = require('bluebird'); function hostLogin(domain, options) { return new Promise(function(resolve) { var server = http.createServer(function(req, res) { if (/favicon/.test(req.url)) { res.statusCode = 404; res.statusMessage = "Not found"; res.end(); return; } if (/^\/somefile/.test(req.url)) { var urlObj = url.parse(req.url, true); server.close(); return resolve({access_token: urlObj.query.access_token}); } var f = req.url.split('?')[0]; var file = path.join(__dirname, '/public/' + f); res.writeHead(200, { 'Content-Length': fs.statSync(file).size }); var readStream = fs.createReadStream(file); readStream.pipe(res); }).listen(8000, function() { opn('http://localhost:8000/index.html?domain=' + JSON.stringify(domain) + '&options=' + JSON.stringify(options)); }) }); } module.exports = hostLogin;
Remove me from the debug e-mail recipient.
''' Simple module to aid in command-line debugging of notification related issues. ''' from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.core.mail import EmailMessage from timetracker.overtime.models import PendingApproval, Tbluser def send_approval_digest(market): approvals = PendingApproval.objects.filter(closed=False, approver__market=market) if not len(approvals): return if len({entry.approver for entry in approvals}) > 1: error_log.critical( "Cannot send e-mails as a clear approval chain cannot be established." ) return message = "Hi,\n\n" \ "You have %d approvals pending in the timetracker." \ "\n\n" \ "Kind Regards,\n" \ "Timetracker team" message = message % len(approvals) email = EmailMessage(from_email='[email protected]') email.body = message email.to = approvals[0].entry.user.get_manager_email() email.subject = "Pending Approvals in the Timetracker." email.send() class Command(BaseCommand): def handle(self, *args, **options): for market in Tbluser.MARKET_CHOICES: if settings.SENDING_APPROVAL_DIGESTS.get(market[0]): send_approval_digest(market[0])
''' Simple module to aid in command-line debugging of notification related issues. ''' from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.core.mail import EmailMessage from timetracker.overtime.models import PendingApproval, Tbluser def send_approval_digest(market): approvals = PendingApproval.objects.filter(closed=False, approver__market=market) if not len(approvals): return if len({entry.approver for entry in approvals}) > 1: error_log.critical( "Cannot send e-mails as a clear approval chain cannot be established." ) return message = "Hi,\n\n" \ "You have %d approvals pending in the timetracker." \ "\n\n" \ "Kind Regards,\n" \ "Timetracker team" message = message % len(approvals) email = EmailMessage(from_email='[email protected]') email.body = message email.to = ["[email protected]"] #approvals[0].user.get_manager_email() email.subject = "Pending Approvals in the Timetracker." email.send() class Command(BaseCommand): def handle(self, *args, **options): for market in Tbluser.MARKET_CHOICES: if settings.SENDING_APPROVAL_DIGESTS.get(market[0]): send_approval_digest(market[0])
ref: Simplify query plan for repo tests
from datetime import timedelta from sqlalchemy.sql import func from zeus.config import db from zeus.constants import Result, Status from zeus.models import Repository, TestCase, Job from zeus.utils import timezone from .base_repository import BaseRepositoryResource from ..schemas import TestCaseStatisticsSchema testcases_schema = TestCaseStatisticsSchema(many=True) class RepositoryTestsResource(BaseRepositoryResource): def get(self, repo: Repository): """ Return a list of testcases for the given repository. """ runs_failed = ( func.count(TestCase.result) .filter(TestCase.result == Result.failed) .label("runs_failed") ) query = ( db.session.query( TestCase.hash, TestCase.name, func.count(TestCase.hash).label("runs_total"), runs_failed, func.avg(TestCase.duration).label("avg_duration"), ) .filter( TestCase.job_id.in_( db.session.query(Job.id) .filter( Job.repository_id == repo.id, Job.date_finished >= timezone.now() - timedelta(days=14), Job.status == Status.finished, ) .subquery() ) ) .group_by(TestCase.hash, TestCase.name) .order_by(runs_failed.desc()) ) return self.paginate_with_schema(testcases_schema, query)
from datetime import timedelta from sqlalchemy.sql import func from zeus.config import db from zeus.constants import Result, Status from zeus.models import Repository, TestCase, Job from zeus.utils import timezone from .base_repository import BaseRepositoryResource from ..schemas import TestCaseStatisticsSchema testcases_schema = TestCaseStatisticsSchema(many=True) class RepositoryTestsResource(BaseRepositoryResource): def get(self, repo: Repository): """ Return a list of testcases for the given repository. """ runs_failed = ( func.count(TestCase.result) .filter(TestCase.result == Result.failed) .label("runs_failed") ) query = ( db.session.query( TestCase.hash, TestCase.name, func.count(TestCase.hash).label("runs_total"), runs_failed, func.avg(TestCase.duration).label("avg_duration"), ) .join(Job, TestCase.job_id == Job.id) .filter( Job.repository_id == repo.id, Job.date_finished >= timezone.now() - timedelta(days=14), Job.status == Status.finished, TestCase.repository_id == repo.id, ) .group_by(TestCase.hash, TestCase.name) .order_by(runs_failed.desc()) ) return self.paginate_with_schema(testcases_schema, query)
Fix active locale method call
<?php namespace rkgrep\Locales; use Illuminate\Support\ServiceProvider; class LocalesServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { // merge default config $this->mergeConfigFrom( __DIR__.'/../config/locales.php', 'locales' ); $this->app->singleton('locales', function($app) { return new LocaleManager($app); }); $this->app->singleton('locales.driver', function ($app) { return $app['locales']->driver(); }); $this->app->bind(Contracts\Locale::class, function ($app) { return $app['locales']->active(); }); // Register a separate console commands provider as deferred $this->app->registerDeferredProvider(ConsoleServiceProvider::class); } /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes(array( __DIR__.'/../config/locales.php' => config_path('locales.php') )); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return [ 'locales', 'locales.driver', 'rkgrep\Locales\Contracts\Locale', ]; } }
<?php namespace rkgrep\Locales; use Illuminate\Support\ServiceProvider; class LocalesServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { // merge default config $this->mergeConfigFrom( __DIR__.'/../config/locales.php', 'locales' ); $this->app->singleton('locales', function($app) { return new LocaleManager($app); }); $this->app->singleton('locales.driver', function ($app) { return $app['locales']->driver(); }); $this->app->bind(Contracts\Locale::class, function ($app) { return $app['locales']->locale(); }); // Register a separate console commands provider as deferred $this->app->registerDeferredProvider(ConsoleServiceProvider::class); } /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes(array( __DIR__.'/../config/locales.php' => config_path('locales.php') )); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return [ 'locales', 'locales.driver', 'rkgrep\Locales\Contracts\Locale', ]; } }
Revise flow of 'start' method
/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; /** * The main stage of the front-end program for interfacing with the electronic system. * * @since September 27, 2016 * @author Ted Frohlich <[email protected]> * @author Abby Walker <[email protected]> */ public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { primaryStage.setScene(new Scene( FXMLLoader.load(getClass().getResource("scene/sicu_sms.fxml")))); primaryStage.setTitle("SICU Stress Measurement System"); primaryStage.getIcons() .add(new Image("http://s3.amazonaws.com/libapps/customers/558/images/CWRU_Logo.jpg")); primaryStage.setMaximized(true); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; /** * The main stage of the front-end program for interfacing with the electronic system. * * @since September 27, 2016 * @author Ted Frohlich <[email protected]> * @author Abby Walker <[email protected]> */ public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load( getClass().getResource("scene/sicu_sms.fxml") ); primaryStage.getIcons().add(new Image( "http://s3.amazonaws.com/libapps/customers/558/images/CWRU_Logo.jpg")); primaryStage.setTitle("SICU Stress Measurement System"); primaryStage.setScene(new Scene(root)); primaryStage.setMaximized(true); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
Update stats daemon to update ZSets and memoization as necessary
#!/usr/bin/env python3 import api import api.group from api.stats import (get_all_team_scores, get_group_scores, get_problem_solves, get_registration_count, get_top_teams_score_progressions) def run(): """Run the stat caching daemon.""" with api.create_app().app_context(): def cache(f, *args, **kwargs): result = f(reset_cache=True, *args, **kwargs) return result print("Caching registration stats.") cache(get_registration_count) print("Caching the public scoreboard entries...") get_all_team_scores() get_all_team_scores(include_ineligible=True) print("Caching the public scoreboard graph...") cache(get_top_teams_score_progressions) cache(get_top_teams_score_progressions, include_ineligible=True) print("Caching the scoreboard graph for each group...") for group in api.group.get_all_groups(): get_group_scores(gid=group['gid']) cache(get_top_teams_score_progressions, gid=group['gid'], include_ineligible=True) print("Caching number of solves for each problem.") for problem in api.problem.get_all_problems(): print(problem["name"], cache(get_problem_solves, problem["pid"])) if __name__ == '__main__': run()
#!/usr/bin/env python3 import api import api.group import api.stats def run(): """Run the stat caching daemon.""" with api.create_app().app_context(): def cache(f, *args, **kwargs): result = f(reset_cache=True, *args, **kwargs) return result print("Caching registration stats.") cache(api.stats.get_registration_count) print("Caching the public scoreboard entries...") cache(api.stats.get_all_team_scores) cache(api.stats.get_all_team_scores, include_ineligible=True) print("Caching the public scoreboard graph...") cache(api.stats.get_top_teams_score_progressions) cache(api.stats.get_top_teams_score_progressions, include_ineligible=True) print("Caching the scoreboard graph for each group...") for group in api.group.get_all_groups(): # cache( # api.stats.get_top_teams_score_progressions, # gid=group['gid']) cache( api.stats.get_top_teams_score_progressions, gid=group['gid'], include_ineligible=True) cache(api.stats.get_group_scores, gid=group['gid']) print("Caching number of solves for each problem.") for problem in api.problem.get_all_problems(): print(problem["name"], cache(api.stats.get_problem_solves, problem["pid"])) if __name__ == '__main__': run()
Refactor channel override to environment variable.
package com.playlist; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * Helper class for posting to the pre-configured Slack Incoming Webhook Integration URL. */ public class SlackClient { private String slackWebHookUrl = System.getenv("SLACK_WEBHOOK_URL"); private String slackChannelOverride = System.getenv("SLACK_CHANNEL_OVERRIDE"); public void postMessageToSlack(String message) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(slackWebHookUrl); JSONObject json = new JSONObject(); json.put("text", message); //Include a channel override if one has been provided if(!StringUtils.isEmpty(slackChannelOverride)) { json.put("channel", slackChannelOverride); } StringEntity entity = new StringEntity(json.toString()); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); try { if(response.getStatusLine().getStatusCode() != 200) { throw new Exception("Error occurred posting message to slack: " + EntityUtils.toString(response.getEntity())); } } finally { response.close(); } } finally { httpClient.close(); } } }
package com.playlist; import net.sf.json.JSONObject; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * Helper class for posting to the pre-configured Slack Incoming Webhook Integration URL. */ public class SlackClient { private String slackWebHookUrl = System.getenv("SLACK_WEBHOOK_URL"); public void postMessageToSlack(String message) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(slackWebHookUrl); JSONObject json = new JSONObject(); json.put("text", message); json.put("channel", "#test-integrations");//TODO: remove channel override StringEntity entity = new StringEntity(json.toString()); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); try { if(response.getStatusLine().getStatusCode() != 200) { throw new Exception("Error occurred posting message to slack: " + EntityUtils.toString(response.getEntity())); } } finally { response.close(); } } finally { httpClient.close(); } } }
Trim the email before logging-in
var TopLevelView = require('ui/common/components/TopLevelView'); var NetworkHelper = require('helpers/NetworkHelper'); function LoginView() { var loginUrl = Ti.App.Properties.getString('server_url') + '/api/login'; var self = new TopLevelView('Login'); var emailField = Ti.UI.createTextField({ width : '80%', hintText : 'Email', top : 20 }); var passwordField = Ti.UI.createTextField({ width : '80%', hintText : 'Password', passwordMask : true }); var loginButton = Ti.UI.createButton({ width : '60%', title : 'Login' }); self.add(emailField); self.add(passwordField); self.add(loginButton); loginButton.addEventListener('click', function() { NetworkHelper.pingSurveyWebWithoutLoggedInCheck( onSuccess = function() { var email = emailField.getValue().trim(); var password = passwordField.getValue(); var client = Ti.Network.createHTTPClient(); client.autoRedirect = false; client.onload = function() { var cookie = this.getResponseHeader('Set-Cookie'); Ti.App.Properties.setString('auth_cookie', cookie); self.fireEvent('login:completed'); } client.onerror = function() { alert("Login failed, sorry!"); } client.open('POST', loginUrl); client.send({ username : email, password : password }); }); }); return self; } module.exports = LoginView;
var TopLevelView = require('ui/common/components/TopLevelView'); var NetworkHelper = require('helpers/NetworkHelper'); function LoginView() { var loginUrl = Ti.App.Properties.getString('server_url') + '/api/login'; var self = new TopLevelView('Login'); var emailField = Ti.UI.createTextField({ width : '80%', hintText : 'Email', top : 20 }); var passwordField = Ti.UI.createTextField({ width : '80%', hintText : 'Password', passwordMask : true }); var loginButton = Ti.UI.createButton({ width : '60%', title : 'Login' }); self.add(emailField); self.add(passwordField); self.add(loginButton); loginButton.addEventListener('click', function() { NetworkHelper.pingSurveyWebWithoutLoggedInCheck( onSuccess = function() { var email = emailField.getValue(); var password = passwordField.getValue(); var client = Ti.Network.createHTTPClient(); client.autoRedirect = false; client.onload = function() { var cookie = this.getResponseHeader('Set-Cookie'); Ti.App.Properties.setString('auth_cookie', cookie); self.fireEvent('login:completed'); } client.onerror = function() { alert("Login failed, sorry!"); } client.open('POST', loginUrl); client.send({ username : email, password : password }); }); }); return self; } module.exports = LoginView;
Make MpdFrontend ignore unknown messages
import logging from mopidy.frontends.base import BaseFrontend from mopidy.frontends.mpd.dispatcher import MpdDispatcher from mopidy.frontends.mpd.process import MpdProcess from mopidy.utils.process import unpickle_connection logger = logging.getLogger('mopidy.frontends.mpd') class MpdFrontend(BaseFrontend): """ The MPD frontend. **Settings:** - :attr:`mopidy.settings.MPD_SERVER_HOSTNAME` - :attr:`mopidy.settings.MPD_SERVER_PORT` """ def __init__(self, *args, **kwargs): super(MpdFrontend, self).__init__(*args, **kwargs) self.process = None self.dispatcher = MpdDispatcher(self.backend) def start(self): """Starts the MPD server.""" self.process = MpdProcess(self.core_queue) self.process.start() def destroy(self): """Destroys the MPD server.""" self.process.destroy() def process_message(self, message): """ Processes messages with the MPD frontend as destination. :param message: the message :type message: dict """ assert message['to'] == 'frontend', \ u'Message recipient must be "frontend".' if message['command'] == 'mpd_request': response = self.dispatcher.handle_request(message['request']) connection = unpickle_connection(message['reply_to']) connection.send(response) else: pass # Ignore messages for other frontends
import logging from mopidy.frontends.base import BaseFrontend from mopidy.frontends.mpd.dispatcher import MpdDispatcher from mopidy.frontends.mpd.process import MpdProcess from mopidy.utils.process import unpickle_connection logger = logging.getLogger('mopidy.frontends.mpd') class MpdFrontend(BaseFrontend): """ The MPD frontend. **Settings:** - :attr:`mopidy.settings.MPD_SERVER_HOSTNAME` - :attr:`mopidy.settings.MPD_SERVER_PORT` """ def __init__(self, *args, **kwargs): super(MpdFrontend, self).__init__(*args, **kwargs) self.process = None self.dispatcher = MpdDispatcher(self.backend) def start(self): """Starts the MPD server.""" self.process = MpdProcess(self.core_queue) self.process.start() def destroy(self): """Destroys the MPD server.""" self.process.destroy() def process_message(self, message): """ Processes messages with the MPD frontend as destination. :param message: the message :type message: dict """ assert message['to'] == 'frontend', \ u'Message recipient must be "frontend".' if message['command'] == 'mpd_request': response = self.dispatcher.handle_request(message['request']) connection = unpickle_connection(message['reply_to']) connection.send(response) else: logger.warning(u'Cannot handle message: %s', message)
Check for callback before execution
'use strict'; var fs = require('fs'); var request = require('request'); var USER_AGENT_STRING = 'SubDB/1.0 (subfil/1.1; ' + 'https://github.com/divijbindlish/subfil)'; var download = function (hash, language, destination, callback) { callback = arguments[arguments.length - 1]; if (typeof callback !== 'function') { throw new Error('Invalid callback'); } request({ url: 'http://api.thesubdb.com', qs: { action: 'download', language: language, hash: hash, }, method: 'GET', headers: { 'User-Agent': USER_AGENT_STRING, } }, function(err, response, body) { if (err) { callback(err); return; } if (response.statusCode === 404) { err = new Error('No subtitles for hash'); callback(err); return; } if (response.statusCode !== 200) { err = new Error('Invalid request'); callback(err); return; } fs.open(destination, 'w', function (err, fd) { if (err) { callback(err); return; } fs.write(fd, body, function (err, bytesWritten, string) { if (err) { callback(err); return; } fs.close(fd, function (err) { if (err) { callback(err); return; } callback(null, destination); }); }); }); }); }; module.exports = download;
'use strict'; var fs = require('fs'); var request = require('request'); var USER_AGENT_STRING = 'SubDB/1.0 (subfil/1.1; ' + 'https://github.com/divijbindlish/subfil)'; var download = function (hash, language, destination, callback) { request({ url: 'http://api.thesubdb.com', qs: { action: 'download', language: language, hash: hash, }, method: 'GET', headers: { 'User-Agent': USER_AGENT_STRING, } }, function(err, response, body) { if (err) { callback(err); return; } if (response.statusCode === 404) { err = new Error('No subtitles for hash'); callback(err); return; } if (response.statusCode !== 200) { err = new Error('Invalid request'); callback(err); return; } fs.open(destination, 'w', function (err, fd) { if (err) { callback(err); return; } fs.write(fd, body, function (err, bytesWritten, string) { if (err) { callback(err); return; } fs.close(fd, function (err) { if (err) { callback(err); return; } callback(null, destination); }); }); }); }); }; module.exports = download;
Add semicolon and rewrite line to be more readable
var command = { command: "help", description: "Display information about a given command", userHelp: { usage: "truffle help <command>", parameters: [], }, builder: {}, run: function (options, callback) { var commands = require("./index"); if (options._.length === 0) { this.displayHelpInformation("help"); return; } var selectedCommand = options._[0]; if (commands[selectedCommand]) { this.displayHelpInformation(selectedCommand); } else { console.log(`\n Cannot find the given command '${selectedCommand}'`); console.log(" Please ensure your command is one of the following: "); Object.keys(commands).sort().forEach((command) => console.log(` ${command}`)); console.log(""); } }, displayHelpInformation: function (selectedCommand) { var commands = require("./index"); var commandHelp = commands[selectedCommand].userHelp; console.log(`\n COMMAND NAME: ${commands[selectedCommand].command}`); console.log(` DESCRIPTION: ${commands[selectedCommand].description}`); console.log(` USAGE: ${commandHelp.usage}`); if (commandHelp.parameters.length > 0) { console.log(` PARAMETERS: `); commandHelp.parameters.forEach((parameter) => { console.log(` ${parameter.parameter}: ${parameter.description}`); }); } console.log(""); } } module.exports = command;
var command = { command: "help", description: "Display information about a given command", userHelp: { usage: "truffle help <command>", parameters: [], }, builder: {}, run: function (options, callback) { var commands = require("./index"); if (options._.length === 0) { this.displayHelpInformation("help"); return; } var selectedCommand = options._[0]; if (commands[selectedCommand]) { this.displayHelpInformation(selectedCommand); } else { console.log(`\n Cannot find the given command '${selectedCommand}'`); console.log(" Please ensure your command is one of the following: "); Object.keys(commands).sort().forEach((command) => console.log(` ${command}`)) console.log(""); } }, displayHelpInformation: function (selectedCommand) { var commands = require("./index"); var commandHelp = commands[selectedCommand].userHelp; console.log(`\n COMMAND NAME: ${commands[selectedCommand].command}`); console.log(` DESCRIPTION: ${commands[selectedCommand].description}`); console.log(` USAGE: ${commandHelp.usage}`); if (commandHelp.parameters.length > 0) { console.log(` PARAMETERS: `); commandHelp.parameters.forEach((parameter) => console.log(` ${parameter.parameter}: ${parameter.description}`)); } console.log(""); } } module.exports = command;
Change sha fetching to use --parent-only and removed ref parameter
import collections import contextlib import shutil import subprocess import tempfile from util.iter import chunk_iter Commit = collections.namedtuple('Commit', ['sha', 'date', 'name']) class RepoParser(object): def __init__(self, git_repo): self.git_repo = git_repo self.tempdir = None @contextlib.contextmanager def repo_checked_out(self): assert not self.tempdir self.tempdir = tempfile.mkdtemp(suffix='temp-repo') try: subprocess.check_call( ['git', 'clone', self.git_repo, self.tempdir], stdout=None, ) yield finally: shutil.rmtree(self.tempdir) self.tempdir = None def get_commit_shas(self, since=None): """Returns a list of Commit objects. Args: since - (optional) A timestamp to look from. """ assert self.tempdir cmd = ['git', 'log', 'master', '--first-parent', '--format=%H%n%at%n%cN'] if since: cmd += ['--after={0}'.format(since)] output = subprocess.check_output( cmd, cwd=self.tempdir, ) commits = [] for sha, date, name in chunk_iter(output.splitlines(), 3): commits.append(Commit(sha, int(date), name)) return commits
import collections import contextlib import shutil import subprocess import tempfile from util.iter import chunk_iter Commit = collections.namedtuple('Commit', ['sha', 'date', 'name']) class RepoParser(object): def __init__(self, git_repo, ref): self.git_repo = git_repo self.ref = ref self.tempdir = None @contextlib.contextmanager def repo_checked_out(self): assert not self.tempdir self.tempdir = tempfile.mkdtemp(suffix='temp-repo') try: subprocess.call( ['git', 'clone', self.git_repo, self.tempdir], stdout=None, ) subprocess.call( ['git', 'checkout', self.ref], cwd=self.tempdir, stdout=None, ) yield finally: shutil.rmtree(self.tempdir) self.tempdir = None def get_commit_shas(self, since=None): """Returns a list of Commit objects. Args: since - (optional) A timestamp to look from. """ assert self.tempdir cmd = ['git', 'log', self.ref, '--topo-order', '--format=%H%n%at%n%cN'] if since: cmd += ['--after={0}'.format(since)] output = subprocess.check_output( cmd, cwd=self.tempdir, ) commits = [] for sha, date, name in chunk_iter(output.splitlines(), 3): commits.append(Commit(sha, int(date), name)) return commits
Simplify extended error number parsing.
<?php /** * This file is part of the LdapTools package. * * (c) Chad Sikorra <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace LdapTools\Connection\AD; use LdapTools\Connection\ADResponseCodes; use LdapTools\Connection\LastErrorStrategy; /** * Try to retrieve a more detailed error message based on the specific AD response code. * * @author Chad Sikorra <[email protected]> */ class ADLastErrorStrategy extends LastErrorStrategy { /** * {@inheritdoc} */ public function getLastErrorMessage() { $extendedError = $this->getExtendedErrorNumber(); if (array_key_exists($extendedError, ADResponseCodes::RESPONSE_MESSAGE)) { $message = ADResponseCodes::RESPONSE_MESSAGE[$extendedError]; } else { $message = parent::getLastErrorMessage(); } return $message; } /** * {@inheritdoc} */ public function getExtendedErrorNumber() { $errorNumber = 0; $extendedError = $this->getDiagnosticMessage(); if (!empty($extendedError) && preg_match('/, data (\d+),?/', $extendedError, $matches)) { $errorNumber = hexdec(intval($matches[1])); } return $errorNumber; } }
<?php /** * This file is part of the LdapTools package. * * (c) Chad Sikorra <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace LdapTools\Connection\AD; use LdapTools\Connection\ADResponseCodes; use LdapTools\Connection\LastErrorStrategy; /** * Try to retrieve a more detailed error message based on the specific AD response code. * * @author Chad Sikorra <[email protected]> */ class ADLastErrorStrategy extends LastErrorStrategy { /** * {@inheritdoc} */ public function getLastErrorMessage() { $extendedError = $this->getExtendedErrorNumber(); if (array_key_exists($extendedError, ADResponseCodes::RESPONSE_MESSAGE)) { $message = ADResponseCodes::RESPONSE_MESSAGE[$extendedError]; } else { $message = parent::getLastErrorMessage(); } return $message; } /** * {@inheritdoc} */ public function getExtendedErrorNumber() { ldap_get_option($this->connection, self::DIAGNOSTIC_MESSAGE_OPT, $extendedError); $errorNumber = 0; if (!empty($extendedError)) { $errorNumber = explode(',', $extendedError); if (!isset($errorNumber[2])) { return 0; }; $errorNumber = explode(' ', $errorNumber[2]); if (!isset($errorNumber[2])) { return 0; }; $errorNumber = hexdec(intval($errorNumber[2])); } return $errorNumber; } }
Fix where db name should be used in db operations (name conflict!)
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' module_db = 'karma.json' module_version = '0.1.0' listen_for_reaction = True async def parse_command(self, message, client): pass async def on_reaction(self, reaction, client): target_user = self.karma.Query() if self.karma.get(target_user.userid == reaction.message.author.id) == None: self.karma.insert({'userid': reaction.message.author.id, 'karma': 1}) msg = 'New entry for ' + reaction.message.author.id + ' added.' await client.send_message(reaction.message.channel, msg) else: new_karma = self.karma.get(target_user.userid == reaction.message.author.id)['karma'] + 1 self.karma.update({'karma': new_karma}, target_user.userid == reaction.message.author.id) msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma await client.send_message(reaction.message.channel, msg) #msg = "I saw that!" + reaction.message.author.name + reaction.emoji #await client.send_message(reaction.message.channel, msg)
import discord from modules.botModule import BotModule class Karma(BotModule): name = 'karma' description = 'Monitors messages for reactions and adds karma accordingly.' help_text = 'This module has no callable functions' trigger_string = '!reddit' module_db = 'karma.json' module_version = '0.1.0' listen_for_reaction = True async def parse_command(self, message, client): pass async def on_reaction(self, reaction, client): target_user = self.module_db.Query() if self.module_db.get(target_user.userid == reaction.message.author.id) == None: self.module_db.insert({'userid': reaction.message.author.id, 'karma': 1}) msg = 'New entry for ' + reaction.message.author.id + ' added.' await client.send_message(reaction.message.channel, msg) else: new_karma = self.module_db.get(target_user.userid == reaction.message.author.id)['karma'] + 1 self.module_db.update({'karma': new_karma}, target_user.userid == reaction.message.author.id) msg = 'Karma for ' + reaction.message.author.id + ' updated to ' + new_karma await client.send_message(reaction.message.channel, msg) #msg = "I saw that!" + reaction.message.author.name + reaction.emoji #await client.send_message(reaction.message.channel, msg)
Update tags for new syntax
from .utils import TemplateTestCase, Mock class BlockTagTest(TemplateTestCase): def test_block_parse(self): self.assertRendered('{% block name %}%{% endblock %}', '%') class ForTagTest(TemplateTestCase): def test_simple_for(self): self.assertRendered( '{% for item in seq %}{{ item }} {% endfor %}', 'a b c d e ', {'seq': 'abcde'}, ) def test_unpack_for(self): self.assertRendered( '{% for a, b in seq %}{{ a }} == {{ b }},{% endfor %}', 'a == 1,b == 2,', {'seq': (('a', 1), ('b', 2))} ) class IfTagTest(TemplateTestCase): def test_simple_if(self): self.assertRendered( '{% if a == 1 %}Yes!{% endif %}', 'Yes!', {'a': 1} ) self.assertRendered( '{% if a == 1 %}Yes!{% endif %}', '', {'a': 2} ) def test_if_else(self): tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}' self.assertRendered(tmpl, 'Yes!', {'a': 1}) self.assertRendered(tmpl, 'No!', {'a': 2})
from .utils import TemplateTestCase, Mock class BlockTagTest(TemplateTestCase): def test_block_parse(self): self.assertRendered('{% block name %}%{% endblock %}', '%') class ForTagTest(TemplateTestCase): def test_simple_for(self): self.assertRendered( '{% for _in=seq %}{{ item }} {% endfor %}', 'a b c d e ', {'seq': 'abcde'}, ) def test_unpack_for(self): self.assertRendered( '{% for a, b, _in=seq %}{{ a }} == {{ b }},{% endfor %}', 'a == 1,b == 2,', {'seq': (('a', 1), ('b', 2))} ) class IfTagTest(TemplateTestCase): def test_simple_if(self): self.assertRendered( '{% if a == 1 %}Yes!{% endif %}', 'Yes!', {'a': 1} ) self.assertRendered( '{% if a == 1 %}Yes!{% endif %}', '', {'a': 2} ) def test_if_else(self): tmpl = '{% if a == 1 %}Yes!{% else %}No!{% endif %}' self.assertRendered(tmpl, 'Yes!', {'a': 1}) self.assertRendered(tmpl, 'No!', {'a': 2})
Add support for income accounts via a -1 polarity.
<?php return function(MongoDB $db) { $collection = $db->budgets; $findOne = function($id) use($collection) { return $collection->findOne(['_id' => new MongoID($id)]); }; return [ 'find' => function(array $conditions = array()) use($collection) { return array_map(function($budget) { $budget['total'] = array_sum(array_map(function($item) { return $item['amount']; }, $budget['items'])); $budget['overrun'] = $budget['polarity'] * $budget['total'] > 0; return $budget; }, iterator_to_array($collection->find($conditions)->sort(['polarity' => 1, 'title' => 1]))); }, 'findOne' => $findOne, 'addItem' => function($id, array $item) use($collection) { if (empty($item['description']) || empty($item['amount'])) { throw new Exception('You must enter both a description and an amount.'); } $collection->update(['_id' => new MongoID($id)], ['$push' => ['items' => $item]]); }, 'removeItem' => function($id, $index) use($collection, $findOne) { $budget = $findOne($id); unset($budget['items'][$index]); $collection->update(['_id' => new MongoID($id)], ['$set' => ['items' => array_values($budget['items'])]]); }, ]; };
<?php return function(MongoDB $db) { $collection = $db->budgets; $findOne = function($id) use($collection) { return $collection->findOne(['_id' => new MongoID($id)]); }; return [ 'find' => function(array $conditions = array()) use($collection) { return array_map(function($budget) { $budget['total'] = array_sum(array_map(function($item) { return $item['amount']; }, $budget['items'])); $budget['overrun'] = $budget['total'] > 0; return $budget; }, iterator_to_array($collection->find($conditions)->sort(['title' => 1]))); }, 'findOne' => $findOne, 'addItem' => function($id, array $item) use($collection) { if (empty($item['description']) || empty($item['amount'])) { throw new Exception('You must enter both a description and an amount.'); } $collection->update(['_id' => new MongoID($id)], ['$push' => ['items' => $item]]); }, 'removeItem' => function($id, $index) use($collection, $findOne) { $budget = $findOne($id); unset($budget['items'][$index]); $collection->update(['_id' => new MongoID($id)], ['$set' => ['items' => array_values($budget['items'])]]); }, ]; };
Rename person to item in TestItem class
package seedu.address.testutil; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.item.*; import seedu.address.model.tag.Tag; /** * */ public class ItemBuilder { private TestItem item; public ItemBuilder() { this.item = new TestItem(); } public ItemBuilder withItemType(String itemType) throws IllegalValueException { this.item.setItemType(new ItemType(itemType)); return this; } public ItemBuilder withTags(String ... tags) throws IllegalValueException { for (String tag: tags) { item.getTags().add(new Tag(tag)); } return this; } public ItemBuilder withEndDate(String endDate) throws IllegalValueException { this.item.setEndDate(new Date(endDate)); return this; } public ItemBuilder withEndTime(String endTime) throws IllegalValueException { this.item.setEndTime(new Time(endTime)); return this; } public ItemBuilder withName(String name) throws IllegalValueException { this.item.setName(new Name(name)); return this; } public ItemBuilder withStartDate(String startDate) throws IllegalValueException { this.item.setStartDate(new Date(startDate)); return this; } public ItemBuilder withStartTime(String startTime) throws IllegalValueException { this.item.setStartTime(new Time(startTime)); return this; } public TestItem build() { return this.item; } }
package seedu.address.testutil; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.item.*; import seedu.address.model.tag.Tag; /** * */ public class ItemBuilder { private TestItem person; public ItemBuilder() { this.person = new TestItem(); } public ItemBuilder withItemType(String itemType) throws IllegalValueException { this.person.setItemType(new ItemType(itemType)); return this; } public ItemBuilder withTags(String ... tags) throws IllegalValueException { for (String tag: tags) { person.getTags().add(new Tag(tag)); } return this; } public ItemBuilder withEndDate(String endDate) throws IllegalValueException { this.person.setEndDate(new Date(endDate)); return this; } public ItemBuilder withEndTime(String endTime) throws IllegalValueException { this.person.setEndTime(new Time(endTime)); return this; } public ItemBuilder withName(String name) throws IllegalValueException { this.person.setName(new Name(name)); return this; } public ItemBuilder withStartDate(String startDate) throws IllegalValueException { this.person.setStartDate(new Date(startDate)); return this; } public ItemBuilder withStartTime(String startTime) throws IllegalValueException { this.person.setStartTime(new Time(startTime)); return this; } public TestItem build() { return this.person; } }
Enable console api and remove warning
var axsPath = require.resolve('../vendor/axs_testing') exports.addCommand = function (client, requireName) { client.addCommand('auditAccessibility', function () { return this.execute(function (axsPath, requireName) { var axs = window[requireName](axsPath) var config = { withConsoleApi: true, showUnsupportedRulesWarning: false } var failures = axs.Audit.run().filter(function (result) { return result.result === 'FAIL' }) if (failures.length > 0) { var message = 'Accessibilty audit failed\n\n' message += failures.map(function (result) { return axs.Audit.accessibilityErrorMessage(result) }).join('\n\n') return { message: message, failed: true, results: failures.map(function (result) { return { code: result.rule.code, elements: result.elements.map(function (element) { return axs.utils.getQuerySelectorText(element) }), message: result.rule.heading, severity: result.rule.severity, url: result.rule.url } }) } } else { return { message: 'Accessibilty audit passed', results: [], failed: false } } }, axsPath, requireName).then(function (response) { return response.value }) }) }
var axsPath = require.resolve('../vendor/axs_testing') exports.addCommand = function (client, requireName) { client.addCommand('auditAccessibility', function () { return this.execute(function (axsPath, requireName) { var axs = window[requireName](axsPath) var failures = axs.Audit.run().filter(function (result) { return result.result === 'FAIL' }) if (failures.length > 0) { var message = 'Accessibilty audit failed\n\n' message += failures.map(function (result) { return axs.Audit.accessibilityErrorMessage(result) }).join('\n\n') return { message: message, failed: true, results: failures.map(function (result) { return { code: result.rule.code, elements: result.elements.map(function (element) { return axs.utils.getQuerySelectorText(element) }), message: result.rule.heading, severity: result.rule.severity, url: result.rule.url } }) } } else { return { message: 'Accessibilty audit passed', results: [], failed: false } } }, axsPath, requireName).then(function (response) { return response.value }) }) }
Add the output_frame_size parameter to PitchgramTransformer. Without it the deserialization via jsonpickle fails.
from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, output_frame_size=None, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # if no output frame size is specified the input hop size is the default self.output_frame_size = output_frame_size if output_frame_size is not None else hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self
from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # TODO: make this configurable self.output_frame_size = hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self
Sort blog entries by date.
import React from 'react' import Link from 'gatsby-link' import './index.scss' export default ({ data }) => { return ( <section> <div className="container"> <header className="major"> <h2>Blog</h2> </header> {data.allMarkdownRemark.edges.map(({ node }) => ( <section key={node.id} className="blog-preview"> <article > <Link to={node.frontmatter.path}><h3>{node.frontmatter.title}</h3></Link> <h4>{node.frontmatter.date}</h4> <p>{node.excerpt}</p> </article> </section> ))} </div> </section> ) } export const query = graphql` query BlogListQuery { allMarkdownRemark( filter: {fileAbsolutePath: {regex: "/blog/.*\\.md$/"}}, sort: {fields: [frontmatter___date], order: DESC} ) { edges { node { id frontmatter { date title path } excerpt(pruneLength: 300) } } } } `
import React from 'react' import Link from 'gatsby-link' import './index.scss' export default ({ data }) => { return ( <section> <div className="container"> <header className="major"> <h2>Blog</h2> </header> {data.allMarkdownRemark.edges.map(({ node }) => ( <section key={node.id} className="blog-preview"> <article > <Link to={node.frontmatter.path}><h3>{node.frontmatter.title}</h3></Link> <h4>{node.frontmatter.date}</h4> <p>{node.excerpt}</p> </article> </section> ))} </div> </section> ) } export const query = graphql` query BlogListQuery { allMarkdownRemark(filter: {fileAbsolutePath: {regex: "/blog/.*\\.md$/"}}) { edges { node { id frontmatter { date title path } excerpt(pruneLength: 300) } } } } `
Set browserStack timeout in an attempt to fix failing CI builds
module.exports = function (config) { config.set({ frameworks: ['mocha'], exclude: ['build/test/external.spec.js'], files: [ 'vendor/rsvp.js', 'vendor/unexpected-magicpen.min.js', 'build/test/promisePolyfill.js', 'unexpected.js', 'build/test/common.js', 'build/test/**/*.spec.js', ], browsers: ['ChromeHeadlessNoSandbox', 'ie11'], browserDisconnectTimeout: '60000', browserNoActivityTimeout: '60000', client: { mocha: { reporter: 'html', timeout: 60000, }, }, browserStack: { video: false, project: process.env.TRAVIS_BRANCH === 'master' && !process.env.TRAVIS_PULL_REQUEST_BRANCH // Catch Travis "PR" builds ? 'unexpected' : 'unexpected-dev', // Attempt to fix timeouts on CI: // https://github.com/karma-runner/karma-browserstack-launcher/pull/168#issuecomment-582373514 timeout: 1800, }, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'], }, ie11: { base: 'BrowserStack', browser: 'IE', browser_version: '11', os: 'Windows', os_version: '7', }, }, reporters: ['dots', 'BrowserStack'], }); };
module.exports = function (config) { config.set({ frameworks: ['mocha'], exclude: ['build/test/external.spec.js'], files: [ 'vendor/rsvp.js', 'vendor/unexpected-magicpen.min.js', 'build/test/promisePolyfill.js', 'unexpected.js', 'build/test/common.js', 'build/test/**/*.spec.js', ], browsers: ['ChromeHeadlessNoSandbox', 'ie11'], browserDisconnectTimeout: '60000', browserNoActivityTimeout: '60000', client: { mocha: { reporter: 'html', timeout: 60000, }, }, browserStack: { video: false, project: process.env.TRAVIS_BRANCH === 'master' && !process.env.TRAVIS_PULL_REQUEST_BRANCH // Catch Travis "PR" builds ? 'unexpected' : 'unexpected-dev', }, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox'], }, ie11: { base: 'BrowserStack', browser: 'IE', browser_version: '11', os: 'Windows', os_version: '7', }, }, reporters: ['dots', 'BrowserStack'], }); };
Replace header dashboard links with new post button
import React from 'react'; import { Link } from 'react-router'; class HeaderDashboard extends React.Component { shouldComponentUpdate(nextProps, nextState, nextContext) { const { location: key, currentUser } = this.context; return key !== nextContext.location.key || currentUser !== nextContext.currentUser; } _signUpView() { return ( <div className="header-sign-up"> <Link to="/sign-up" className="header-sign-up-button button red ">Sign Up</Link> </div> ); } _userView() { const dashboardLinks = [ 'messages', 'notifications', ]; return ( <div className="header-dashboard"> <span className="header-primary-divider header-dashboard-divider"></span> { dashboardLinks.map((link, i) => { const className = `icon icon-${link}`; return ( <span key={i} className="header-dashboard-item"> <Link to={`/${link}`} className={className} /> </span> ); }) } <Link to="/post" className="header-post-button button red ">New Post</Link> </div> ); } render() { const view = this.context.currentUser ? this._userView() : this._signUpView(); return view; } } HeaderDashboard.contextTypes = { location: React.PropTypes.object.isRequired, currentUser: React.PropTypes.object, }; export default HeaderDashboard;
import React from 'react'; import { Link } from 'react-router'; class HeaderDashboard extends React.Component { shouldComponentUpdate(nextProps, nextState, nextContext) { const { location: key, currentUser } = this.context; return key !== nextContext.location.key || currentUser !== nextContext.currentUser; } _signUpView() { return ( <div className="header-sign-up"> <Link to="/sign-up" className="header-sign-up-button button red ">Sign Up</Link> </div> ); } _userView() { const dashboardLinks = [ 'dashboard', 'cart', 'messages', 'notifications', ]; const style = { width: `${(100 / dashboardLinks.length)}%`, }; return ( <div className="header-dashboard"> <span className="header-primary-divider header-dashboard-divider"></span> { dashboardLinks.map((link, i) => { const className = `icon icon-${link}`; return ( <span key={i} className="header-dashboard-item" style={style}> <Link to={`/${link}`} className={className} /> </span> ); }) } </div> ); } render() { const view = this.context.currentUser ? this._userView() : this._signUpView(); return view; } } HeaderDashboard.contextTypes = { location: React.PropTypes.object.isRequired, currentUser: React.PropTypes.object, }; export default HeaderDashboard;
Add some global tpl vars
Template.login.events({ 'submit .login-user': function(event) { var email = event.target.email.value; var password = event.target.password.value; Meteor.loginWithPassword(email, password, function(err) { if (err) { event.target.email.value = email; event.target.password.value = password; FlashMessages.sendError(err.reason); } else { FlashMessages.sendSuccess('You are logged in!'); Router.go('/admin/projects'); } }); event.target.email.value = ''; event.target.password.value = ''; return false; } }); Template.layout.events({ 'click .logout-user': function(event){ Meteor.logout(function(err){ if (err) { FlashMessages.sendError(err.reason); } else { FlashMessages.sendSuccess('You are logged out by now!'); Router.go('/'); // Redirect to homepage } }); return false; // Prevent submit } }); // Add Datepicker Template.layout.onRendered(function() { this.$('.datetimepicker').datetimepicker(); }); // Add formatDate filter for nicer date render Template.registerHelper('formatDate', function(date){ return moment(date).format('Do MMMM YYYY, h:mm:ss a'); }); // Create helpers to store some global tpl variables Template.registerHelper('siteName', function(){ return 'pH7Ortfolio'; }); Template.registerHelper('authorImage', function(){ return '/assets/img/user.png'; });
Template.login.events({ 'submit .login-user': function(event) { var email = event.target.email.value; var password = event.target.password.value; Meteor.loginWithPassword(email, password, function(err) { if (err) { event.target.email.value = email; event.target.password.value = password; FlashMessages.sendError(err.reason); } else { FlashMessages.sendSuccess('You are logged in!'); Router.go('/admin/projects'); } }); event.target.email.value = ''; event.target.password.value = ''; return false; } }); Template.layout.events({ 'click .logout-user': function(event){ Meteor.logout(function(err){ if (err) { FlashMessages.sendError(err.reason); } else { FlashMessages.sendSuccess('You are logged out by now!'); Router.go('/'); // Redirect to homepage } }); return false; // Prevent submit } }); // Add Datepicker Template.layout.onRendered(function() { this.$('.datetimepicker').datetimepicker(); }); // Add formatDate filter for nicer date render Template.registerHelper('formatDate', function(date){ return moment(date).format('Do MMMM YYYY, h:mm:ss a'); });
Add hotkey info to placeholder text
import React from 'react' import debounce from 'lodash/debounce' const searchFor = debounce(term => window.routerHistory.push(`/search/${term}`), 500) export default class SearchBox extends React.Component { static defaultProps = { className: '', placeholder: 'Search... (Ctrl+Shift+F)', term: '', } constructor(props) { super(props) this.state = { term: props.term } } componentDidMount() { window.addEventListener('keyup', this.onKeyUp) } componentWillReceiveProps(props) { if (props.term !== this.state.term) this.setState({ term: props.term }) } componentWillUnmount() { window.removeEventListener('keyup', this.onKeyUp) } onKeyUp = (e) => { if (e.ctrlKey && e.shiftKey && e.code === 'KeyF') { e.preventDefault() e.stopPropagation() this.input.focus() } } createRef = (input) => { this.input = input } render() { const { className, placeholder } = this.props return ( <div className={`search-box ${className}`}> <input type="text" placeholder={placeholder} value={this.state.term} onChange={(event) => { this.setState({ term: event.target.value }) searchFor(event.target.value) }} ref={this.createRef} /> <i className="icon icon-search fa" /> </div> ) } }
import React from 'react' import debounce from 'lodash/debounce' const searchFor = debounce(term => window.routerHistory.push(`/search/${term}`), 500) export default class SearchBox extends React.Component { static defaultProps = { className: '', placeholder: 'Search...', term: '', } constructor(props) { super(props) this.state = { term: props.term } } componentDidMount() { window.addEventListener('keyup', this.onKeyUp) } componentWillReceiveProps(props) { if (props.term !== this.state.term) this.setState({ term: props.term }) } componentWillUnmount() { window.removeEventListener('keyup', this.onKeyUp) } onKeyUp = (e) => { if (e.ctrlKey && e.shiftKey && e.code === 'KeyF') { e.preventDefault() e.stopPropagation() this.input.focus() } } createRef = (input) => { this.input = input } render() { const { className, placeholder } = this.props return ( <div className={`search-box ${className}`}> <input type="text" placeholder={placeholder} value={this.state.term} onChange={(event) => { this.setState({ term: event.target.value }) searchFor(event.target.value) }} ref={this.createRef} /> <i className="icon icon-search fa" /> </div> ) } }
Add bullet hit function to destroy self.
from tkinter import Label import threading class Bullet(Label): def __init__(self, x, y, space): self.space = space self.bullet_timer = 0.01 self.bullet_indicator = "'" self.damage = -100 Label.__init__(self, text=self.bullet_indicator) self.pack() self._x = x self._y = y self._observers = [] def start(self): process = threading.Thread(target=self.place_bullet) process.start() def place_bullet(self): if self._y > 0: self.set_y(-1) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() else: self.set_y(self.space.height) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() def get_y(self): return self._y def set_y(self, value): self._y += value for callback in self._observers: callback(thing=self) y = property(get_y, set_y) def bind_to(self, callback): self._observers.append(callback) def hit(self): self.destroy()
from tkinter import Label import threading class Bullet(Label): def __init__(self, x, y, space): self.space = space self.bullet_timer = 0.01 self.bullet_indicator = "'" self.damage = -100 Label.__init__(self, text=self.bullet_indicator) self.pack() self._x = x self._y = y self._observers = [] def start(self): process = threading.Thread(target=self.place_bullet) process.start() def place_bullet(self): if self._y > 0: self.set_y(-1) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() else: self.set_y(self.space.height) self.place(x=self._x, y=self._y) process = threading.Timer(self.bullet_timer, self.place_bullet, []) process.start() def get_y(self): return self._y def set_y(self, value): self._y += value for callback in self._observers: callback(x=self._x, y=self._y, thing=self) y = property(get_y, set_y) def bind_to(self, callback): self._observers.append(callback)
Add support for smart transactional emails
<?php namespace Casinelli\CampaignMonitor; class CampaignMonitor { protected $app; public function __construct($app) { $this->app = $app; } public function campaigns($campaignId = null) { return new \CS_REST_Campaigns($campaignId, $this->getAuthTokens()); } public function clients($clientId = null) { return new \CS_REST_Clients($clientId, $this->getAuthTokens()); } public function lists($listId = null) { return new \CS_REST_Lists($listId, $this->getAuthTokens()); } public function segments($segmentId = null) { return new \CS_REST_Segments($segmentId, $this->getAuthTokens()); } public function template($templateId = null) { return new \CS_REST_Templates($templateId, $this->getAuthTokens()); } public function subscribers($listId = null) { return new \CS_REST_Subscribers($listId, $this->getAuthTokens()); } public function classicSend($clientId = null) { return new \CS_REST_Transactional_ClassicEmail($this->getAuthTokens(), $clientId); } public function smartSend($smartId = null, $clientId) { return new \CS_REST_Transactional_SmartEmail($smartId, $this->getAuthTokens(), $clientId); } protected function getAuthTokens() { return [ 'api_key' => $this->app['config']['campaignmonitor.api_key'], ]; } }
<?php namespace Casinelli\CampaignMonitor; class CampaignMonitor { protected $app; public function __construct($app) { $this->app = $app; } public function campaigns($campaignId = null) { return new \CS_REST_Campaigns($campaignId, $this->getAuthTokens()); } public function clients($clientId = null) { return new \CS_REST_Clients($clientId, $this->getAuthTokens()); } public function lists($listId = null) { return new \CS_REST_Lists($listId, $this->getAuthTokens()); } public function segments($segmentId = null) { return new \CS_REST_Segments($segmentId, $this->getAuthTokens()); } public function template($templateId = null) { return new \CS_REST_Templates($templateId, $this->getAuthTokens()); } public function subscribers($listId = null) { return new \CS_REST_Subscribers($listId, $this->getAuthTokens()); } public function classicSend($clientId = null) { return new \CS_REST_Transactional_ClassicEmail($this->getAuthTokens(), $clientId); } protected function getAuthTokens() { return [ 'api_key' => $this->app['config']['campaignmonitor.api_key'], ]; } }
Test DictionaryObjectModel: correct usage of property '_' instead of '-' in property names, this fixes the build.
const Eknc = imports.gi.EosKnowledgeContent; const InstanceOfMatcher = imports.tests.InstanceOfMatcher; describe('Dictionary Object Model', function() { let dictionaryObject, jsonld; beforeEach(function() { jasmine.addMatchers(InstanceOfMatcher.customMatchers); jsonld = { '@id': 'ekn:word/Entreaty', 'word': 'entreaty', 'definition': 'An earnest request or petition; a plea.', 'partOfSpeech': 'noun', 'title': 'June 23rd', }; dictionaryObject = Eknc.DictionaryObjectModel.new_from_json(jsonld); }); describe('type', function() { it('should be a ContentObjectModel', function() { expect(dictionaryObject).toBeA(Eknc.ContentObjectModel); }); it('should be a DictionaryObjectModel', function() { expect(dictionaryObject).toBeA(Eknc.DictionaryObjectModel); }); }); describe('JSON-LD marshaler', function() { it('should construct from a JSON-LD document', function() { expect(dictionaryObject).toBeDefined(); }); it('should marshal properties', function() { expect(dictionaryObject.word).toBe('entreaty'); expect(dictionaryObject.definition).toBe('An earnest request or petition; a plea.'); expect(dictionaryObject.part_of_speech).toBe('noun'); }); it('should inherit properties set by parent class (ContentObjectModel)', function() { expect(dictionaryObject.title).toBe('June 23rd'); }); }); });
const Eknc = imports.gi.EosKnowledgeContent; const InstanceOfMatcher = imports.tests.InstanceOfMatcher; describe('Dictionary Object Model', function() { let dictionaryObject, jsonld; beforeEach(function() { jasmine.addMatchers(InstanceOfMatcher.customMatchers); jsonld = { '@id': 'ekn:word/Entreaty', 'word': 'entreaty', 'definition': 'An earnest request or petition; a plea.', 'partOfSpeech': 'noun', 'title': 'June 23rd', }; dictionaryObject = Eknc.DictionaryObjectModel.new_from_json(jsonld); }); describe('type', function() { it('should be a ContentObjectModel', function() { expect(dictionaryObject).toBeA(Eknc.ContentObjectModel); }); it('should be a DictionaryObjectModel', function() { expect(dictionaryObject).toBeA(Eknc.DictionaryObjectModel); }); }); describe('JSON-LD marshaler', function() { it('should construct from a JSON-LD document', function() { expect(dictionaryObject).toBeDefined(); }); it('should marshal properties', function() { expect(dictionaryObject.word).toBe('entreaty'); expect(dictionaryObject.definition).toBe('An earnest request or petition; a plea.'); expect(dictionaryObject.part-of-speech).toBe('noun'); }); it('should inherit properties set by parent class (ContentObjectModel)', function() { expect(dictionaryObject.title).toBe('June 23rd'); }); }); });
Update the text to match
@extends('layout') @section('content') @include('partials.standardHeader') <section class="section home"> <div class="container"> <div class="column is-half is-offset-one-quarter"> <div class="box"> <form action="/upload" class="dropzone" id="that-zone"> <input type="hidden" name="filePath" id="filePath"> <div class="dz-message needsclick"> <h2>Drop files here or click to upload</h2> <br> <span class="note needsclick"> Max: 5GB/file </span> </div> {{ csrf_field() }} </form> </div> <form action="{{ url('/zip/' . Session::get('hash')) }}" method="POST" id="form"> {{ csrf_field() }} @component('components.uploadTrigger', ['label' => 'Zip up', 'icon' => 'zip'])@endcomponent </form> <label class="help">Note: you can upload folders using drag and drop on your desktop devices</label> </div> </div> </section> @stop
@extends('layout') @section('content') @include('partials.standardHeader') <section class="section home"> <div class="container"> <div class="column is-half is-offset-one-quarter"> <div class="box"> <form action="/upload" class="dropzone" id="that-zone"> <input type="hidden" name="filePath" id="filePath"> <div class="dz-message needsclick"> <h2>Drop files here or click to upload</h2> <br> <span class="note needsclick"> Max: 50Mb/file </span> </div> {{ csrf_field() }} </form> </div> <form action="{{ url('/zip/' . Session::get('hash')) }}" method="POST" id="form"> {{ csrf_field() }} @component('components.uploadTrigger', ['label' => 'Zip up', 'icon' => 'zip'])@endcomponent </form> <label class="help">Note: you can upload folders using drag and drop on your desktop devices</label> </div> </div> </section> @stop
git: Fix top level hook to not use renames
#!/usr/bin/env python3 import os import subprocess import sys if __name__ == '__main__': ref_name = sys.argv[1] old_commit = sys.argv[2] new_commit = sys.argv[3] # no need to check if old_commit or new_commit are 0, master can't be deleted or created if ref_name == 'refs/heads/master' and os.environ.get('REMOTE_USER') is not None: # push not coming from MarkUs # check 1: created/deleted top level files/directories old_ls = subprocess.run(['git', 'ls-tree', '--name-only', old_commit], stdout=subprocess.PIPE, universal_newlines=True) new_ls = subprocess.run(['git', 'ls-tree', '--name-only', new_commit], stdout=subprocess.PIPE, universal_newlines=True) if old_ls.stdout != new_ls.stdout: print('[MARKUS] Error: creating/deleting top level files and directories is not allowed on master!') exit(1) # check 2: modified top level files changes = subprocess.run(['git', 'diff', '--name-only', '--no-renames', old_commit, new_commit], stdout=subprocess.PIPE, universal_newlines=True) if any(os.sep not in change for change in changes.stdout.splitlines()): print('[MARKUS] Error: modifying top level files is not allowed on master!') exit(1)
#!/usr/bin/env python3 import os import subprocess import sys if __name__ == '__main__': ref_name = sys.argv[1] old_commit = sys.argv[2] new_commit = sys.argv[3] # no need to check if old_commit or new_commit are 0, master can't be deleted or created if ref_name == 'refs/heads/master' and os.environ.get('REMOTE_USER') is not None: # push not coming from MarkUs # check 1: created/deleted top level files/directories old_ls = subprocess.run(['git', 'ls-tree', '--name-only', old_commit], stdout=subprocess.PIPE, universal_newlines=True) new_ls = subprocess.run(['git', 'ls-tree', '--name-only', new_commit], stdout=subprocess.PIPE, universal_newlines=True) if old_ls.stdout != new_ls.stdout: print('[MARKUS] Error: creating/deleting top level files and directories is not allowed on master!') exit(1) # check 2: modified top level files changes = subprocess.run(['git', 'diff', '--name-only', old_commit, new_commit], stdout=subprocess.PIPE, universal_newlines=True) if any(os.sep not in change for change in changes.stdout.splitlines()): print('[MARKUS] Error: modifying top level files is not allowed on master!') exit(1)
Fix bad method name in test task
<?php namespace Amp\Test\Thread; use Amp\Promise; use Amp\Future; use Amp\Thread\Thread; use Amp\Thread\Dispatcher; function multiply($x, $y) { return $x * $y; } function exception() { throw new \Exception('test'); } function fatal() { $nonexistentObj->nonexistentMethod(); } class FatalStackable extends \Stackable { public function run() { $nonexistentObj->nonexistentMethod(); } } class ThrowingStackable extends \Stackable { public function run() { throw new \Exception('test'); } } class TestAutoloaderStackable extends \Stackable { public function run() { spl_autoload_register(function() { require_once __DIR__ . '/AutoloadableClassFixture.php'; }); } } class TestStreamStackable extends \Stackable { public function run() { $this->worker->update(1); $this->worker->update(2); $this->worker->update(3); $this->worker->update(4); $this->worker->registerResult(Thread::SUCCESS, null); } } function testUpdate($reactor) { $dispatcher = new Dispatcher($reactor); $promise = $dispatcher->execute(new TestStreamStackable); $promise->watch(function($update) { echo "$update\n"; }); $promise->when(function($error, $result) use ($reactor) { assert($result === null); $reactor->stop(); }); }
<?php namespace Amp\Test\Thread; use Amp\Promise; use Amp\Future; use Amp\Thread\Thread; use Amp\Thread\Dispatcher; function multiply($x, $y) { return $x * $y; } function exception() { throw new \Exception('test'); } function fatal() { $nonexistentObj->nonexistentMethod(); } class FatalStackable extends \Stackable { public function run() { $nonexistentObj->nonexistentMethod(); } } class ThrowingStackable extends \Stackable { public function run() { throw new \Exception('test'); } } class TestAutoloaderStackable extends \Stackable { public function run() { spl_autoload_register(function() { require_once __DIR__ . '/AutoloadableClassFixture.php'; }); } } class TestStreamStackable extends \Stackable { public function run() { $this->worker->updateProgress(1); $this->worker->updateProgress(2); $this->worker->updateProgress(3); $this->worker->updateProgress(4); $this->worker->registerResult(Thread::SUCCESS, null); } } function testUpdate($reactor) { $dispatcher = new Dispatcher($reactor); $promise = $dispatcher->execute(new TestStreamStackable); $promise->watch(function($update) { echo "$update\n"; }); $promise->when(function($error, $result) use ($reactor) { assert($result === null); $reactor->stop(); }); }
Replace older BooleanTransform to ValueTransform
<?php namespace AdobeConnectClient\Commands; use AdobeConnectClient\Command; use AdobeConnectClient\Converter\Converter; use AdobeConnectClient\Helpers\StatusValidate; use AdobeConnectClient\Helpers\ValueTransform as VT; use AdobeConnectClient\Helpers\StringCaseTransform as SCT; /** * Set a feature * * @link https://helpx.adobe.com/adobe-connect/webservices/meeting-feature-update.html */ class MeetingFeatureUpdate extends Command { /** @var array */ protected $parameters; /** * @param int $accountId * @param string $featureId * @param bool $enable */ public function __construct($accountId, $featureId, $enable) { $this->parameters = [ 'action' => 'meeting-feature-update', 'account-id' => (int) $accountId, 'enable' => VT::toString($enable), ]; $featureId = SCT::toHyphen($featureId); if (mb_strpos($featureId, 'fid-') === false) { $featureId = 'fid-' . $featureId; } $this->parameters['feature-id'] = $featureId; } protected function process() { $response = Converter::convert( $this->client->doGet( $this->parameters + ['session' => $this->client->getSession()] ) ); StatusValidate::validate($response['status']); return true; } }
<?php namespace AdobeConnectClient\Commands; use AdobeConnectClient\Command; use AdobeConnectClient\Converter\Converter; use AdobeConnectClient\Helpers\StatusValidate; use AdobeConnectClient\Helpers\BooleanTransform as BT; use AdobeConnectClient\Helpers\StringCaseTransform as SCT; /** * Set a feature * * @link https://helpx.adobe.com/adobe-connect/webservices/meeting-feature-update.html */ class MeetingFeatureUpdate extends Command { /** @var array */ protected $parameters; /** * @param int $accountId * @param string $featureId * @param bool $enable */ public function __construct($accountId, $featureId, $enable) { $this->parameters = [ 'action' => 'meeting-feature-update', 'account-id' => (int) $accountId, 'enable' => BT::toString($enable), ]; $featureId = SCT::toHyphen($featureId); if (mb_strpos($featureId, 'fid-') === false) { $featureId = 'fid-' . $featureId; } $this->parameters['feature-id'] = $featureId; } protected function process() { $response = Converter::convert( $this->client->doGet( $this->parameters + ['session' => $this->client->getSession()] ) ); StatusValidate::validate($response['status']); return true; } }
Change group function to string
var ipc = window.require('ipc'); var _ = require('underscore'); var Reflux = require('reflux'); var Actions = require('../actions/actions'); var AuthStore = require('../stores/auth'); var apiRequests = require('../utils/api-requests'); var NotificationsStore = Reflux.createStore({ listenables: Actions, init: function () { this._notifications = undefined; }, updateTrayIcon: function (notifications) { if (notifications.length > 0) { ipc.sendChannel('update-icon', "IconGreen"); } else { ipc.sendChannel('update-icon', "IconPlain"); } }, onGetNotifications: function () { var self = this; var tokens = AuthStore.authStatus(); apiRequests .getAuth('https://api.github.com/notifications') .end(function (err, response) { if (response && response.ok) { // Success - Do Something. Actions.getNotifications.completed(response.body); self.updateTrayIcon(response.body); } else { // Error - Show messages. Actions.getNotifications.failed(err); } }); }, onGetNotificationsCompleted: function (notifications) { var groupedNotifications = _.groupBy(notifications, 'repository.name'); this._notifications = groupedNotifications; this.trigger(groupedNotifications); }, onGetNotificationsFailed: function (error) { console.log("Errored." + error); } }); module.exports = NotificationsStore;
var ipc = window.require('ipc'); var _ = require('underscore'); var Reflux = require('reflux'); var Actions = require('../actions/actions'); var AuthStore = require('../stores/auth'); var apiRequests = require('../utils/api-requests'); var NotificationsStore = Reflux.createStore({ listenables: Actions, init: function () { this._notifications = undefined; }, updateTrayIcon: function (notifications) { if (notifications.length > 0) { ipc.sendChannel('update-icon', "IconGreen"); } else { ipc.sendChannel('update-icon', "IconPlain"); } }, onGetNotifications: function () { var self = this; var tokens = AuthStore.authStatus(); apiRequests .getAuth('https://api.github.com/notifications') .end(function (err, response) { if (response && response.ok) { // Success - Do Something. Actions.getNotifications.completed(response.body); self.updateTrayIcon(response.body); } else { // Error - Show messages. Actions.getNotifications.failed(err); } }); }, onGetNotificationsCompleted: function (notifications) { var groupedNotifications = _.groupBy(notifications, function(object){ return object.repository.name; }); this._notifications = groupedNotifications; this.trigger(groupedNotifications); }, onGetNotificationsFailed: function (error) { console.log("Errored." + error); } }); module.exports = NotificationsStore;
Handle values to be compared being `None`.
# -*- coding: utf-8 -*- """ byceps.blueprints.snippet_admin.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from difflib import HtmlDiff from ...database import db from ..party.models import Party from ..snippet.models.snippet import Snippet def get_parties_with_snippet_counts(): """Yield (party, snippet count) pairs.""" parties = Party.query.all() snippet_counts_by_party_id = _get_snippet_counts_by_party_id() for party in parties: snippet_count = snippet_counts_by_party_id.get(party.id, 0) yield party, snippet_count def _get_snippet_counts_by_party_id(): return dict(db.session \ .query( Snippet.party_id, db.func.count(Snippet.id) ) \ .group_by(Snippet.party_id) \ .all()) def create_html_diff(from_text, to_text, from_description, to_description, *, numlines=3): """Calculate the difference between the two texts and render it as HTML.""" from_lines = (from_text or '').split('\n') to_lines = (to_text or '').split('\n') return HtmlDiff().make_table(from_lines, to_lines, from_description, to_description, context=True, numlines=numlines)
# -*- coding: utf-8 -*- """ byceps.blueprints.snippet_admin.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from difflib import HtmlDiff from ...database import db from ..party.models import Party from ..snippet.models.snippet import Snippet def get_parties_with_snippet_counts(): """Yield (party, snippet count) pairs.""" parties = Party.query.all() snippet_counts_by_party_id = _get_snippet_counts_by_party_id() for party in parties: snippet_count = snippet_counts_by_party_id.get(party.id, 0) yield party, snippet_count def _get_snippet_counts_by_party_id(): return dict(db.session \ .query( Snippet.party_id, db.func.count(Snippet.id) ) \ .group_by(Snippet.party_id) \ .all()) def create_html_diff(from_text, to_text, from_description, to_description, *, numlines=3): """Calculate the difference between the two texts and render it as HTML.""" from_lines = from_text.split('\n') to_lines = to_text.split('\n') return HtmlDiff().make_table(from_lines, to_lines, from_description, to_description, context=True, numlines=numlines)
Add email subject for exception reporting
<?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Mail; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ 'Symfony\Component\HttpKernel\Exception\HttpException' ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(Exception $e) { if (env('APP_ENV', 'local')!='local') { Mail::raw($e, function ($message) { $message->subject('[ROOT] Exception Report'); $message->from(env('MAIL_FROM_ADDRESS', 'root@localhost'), env('SYSLOG_APPNAME', '')); $message->to(env('ROOT_REPORT_MAIL', 'root@localhost')); }); } return parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { return parent::render($request, $e); } }
<?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Mail; class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ 'Symfony\Component\HttpKernel\Exception\HttpException' ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $e * @return void */ public function report(Exception $e) { if (env('APP_ENV', 'local')!='local') { Mail::raw($e, function ($message) { $message->from(env('MAIL_FROM_ADDRESS', 'root@localhost'), env('SYSLOG_APPNAME', '')); $message->to(env('ROOT_REPORT_MAIL', 'root@localhost')); }); } return parent::report($e); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $e * @return \Illuminate\Http\Response */ public function render($request, Exception $e) { return parent::render($request, $e); } }
Enable a test case which was failing previously.
'use strict'; var csslint = require('../lib/csslint'), fs = require('fs'), path = require('path'); var formatter = csslint.getFormatter('compact'); module.exports = (function() { var tests = {}; fs.readdirSync('test/less').forEach(function(file) { if (!/\.less/.test(file)) { return; } tests[file] = function(test) { var basename = path.basename(file, '.less'); file = path.join('test/less', file); test.expect(4); fs.readFile(file, 'utf8', function(err, data) { test.ifError(err); csslint.verify(file, data, csslint.getRuleset(), function(err, results) { test.ifError(err); fs.readFile(path.join('test/less', basename + '.txt'), 'utf8', function(err, expectedResults) { test.ifError(err); test.equal(formatter.formatResults(results, file), expectedResults); test.done(); }); }); }); }; }); return tests; }());
'use strict'; var csslint = require('../lib/csslint'), fs = require('fs'), path = require('path'); var formatter = csslint.getFormatter('compact'); module.exports = (function() { var tests = {}; fs.readdirSync('test/less').forEach(function(file) { if (!/\.less/.test(file)) { return; } if (file === 'utility.less') { return; } tests[file] = function(test) { var basename = path.basename(file, '.less'); file = path.join('test/less', file); test.expect(4); fs.readFile(file, 'utf8', function(err, data) { test.ifError(err); csslint.verify(file, data, csslint.getRuleset(), function(err, results) { test.ifError(err); fs.readFile(path.join('test/less', basename + '.txt'), 'utf8', function(err, expectedResults) { test.ifError(err); test.equal(formatter.formatResults(results, file), expectedResults); test.done(); }); }); }); }; }); return tests; }());
Add tooltips to the requirements on the node list.
package net.sourceforge.javydreamercsw.client.ui.nodes; import com.validation.manager.core.db.Requirement; import com.validation.manager.core.server.core.RequirementServer; import java.beans.IntrospectionException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.Action; import net.sourceforge.javydreamercsw.client.ui.nodes.actions.EditRequirementAction; import org.openide.util.lookup.InstanceContent; /** * * @author Javier A. Ortiz Bultron <[email protected]> */ public class UIRequirementNode extends AbstractVMBeanNode { public UIRequirementNode(Requirement req) throws IntrospectionException { super(req, null, new InstanceContent()); setIconBaseWithExtension("com/validation/manager/resources/icons/Papermart/Document.png"); setShortDescription(req.getDescription()); } @Override public String getName() { return getLookup().lookup(Requirement.class).getUniqueId(); } @Override public Action[] getActions(boolean b) { List<Action> actions = new ArrayList<>(); actions.addAll(Arrays.asList(super.getActions(b))); actions.add(new EditRequirementAction()); return actions.toArray(new Action[actions.size()]); } @Override public void refreshMyself() { RequirementServer rs = new RequirementServer(getLookup().lookup(Requirement.class)); rs.update((Requirement) getBean(), rs.getEntity()); } }
package net.sourceforge.javydreamercsw.client.ui.nodes; import com.validation.manager.core.db.Requirement; import com.validation.manager.core.server.core.RequirementServer; import java.beans.IntrospectionException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.Action; import net.sourceforge.javydreamercsw.client.ui.nodes.actions.EditRequirementAction; import org.openide.util.lookup.InstanceContent; /** * * @author Javier A. Ortiz Bultron <[email protected]> */ public class UIRequirementNode extends AbstractVMBeanNode { public UIRequirementNode(Requirement req) throws IntrospectionException { super(req, null, new InstanceContent()); setIconBaseWithExtension("com/validation/manager/resources/icons/Papermart/Document.png"); } @Override public String getName() { return getLookup().lookup(Requirement.class).getUniqueId(); } @Override public Action[] getActions(boolean b) { List<Action> actions = new ArrayList<>(); actions.addAll(Arrays.asList(super.getActions(b))); actions.add(new EditRequirementAction()); return actions.toArray(new Action[actions.size()]); } @Override public void refreshMyself() { RequirementServer rs = new RequirementServer(getLookup().lookup(Requirement.class)); rs.update((Requirement) getBean(), rs.getEntity()); } }
Add scripts.js to scripts gulp pipe
'use strict'; var autoprefixer = require('gulp-autoprefixer'); var cleanCSS = require('gulp-clean-css'); var concat = require('gulp-concat'); var gulp = require('gulp'); var sass = require('gulp-sass'); var uglify = require('gulp-uglify'); gulp.task('default', function () { gulp.start('styles', 'scripts', 'fonts'); }); gulp.task('watch', ['styles', 'scripts', 'fonts'], function () { gulp.watch('./assets/stylesheets/**/*.scss', ['styles']); gulp.watch('./assets/javascripts/**/*.js', ['scripts']); gulp.watch('./assets/fonts/bootstrap/*', ['fonts']); }); gulp.task('styles', function () { return gulp.src('./assets/stylesheets/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(concat('all.css')) .pipe(autoprefixer()) .pipe(cleanCSS()) .pipe(gulp.dest('./public/stylesheets')); }); gulp.task('scripts', function () { return gulp.src([ './assets/javascripts/jquery/jquery-2.2.1.js', './assets/javascripts/bootstrap/bootstrap.js', './assets/javascripts/scripts.js' ]) .pipe(concat('all.js')) .pipe(uglify()) .pipe(gulp.dest('./public/javascripts')); }); gulp.task('fonts', function () { return gulp.src('./assets/fonts/bootstrap/*') .pipe(gulp.dest('./public/fonts/bootstrap')); });
'use strict'; var autoprefixer = require('gulp-autoprefixer'); var cleanCSS = require('gulp-clean-css'); var concat = require('gulp-concat'); var gulp = require('gulp'); var sass = require('gulp-sass'); var uglify = require('gulp-uglify'); gulp.task('default', function () { gulp.start('styles', 'scripts', 'fonts'); }); gulp.task('watch', ['styles', 'scripts', 'fonts'], function () { gulp.watch('./assets/stylesheets/**/*.scss', ['styles']); gulp.watch('./assets/javascripts/**/*.js', ['scripts']); gulp.watch('./assets/fonts/bootstrap/*', ['fonts']); }); gulp.task('styles', function () { return gulp.src('./assets/stylesheets/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(concat('all.css')) .pipe(autoprefixer()) .pipe(cleanCSS()) .pipe(gulp.dest('./public/stylesheets')); }); gulp.task('scripts', function () { return gulp.src([ './assets/javascripts/jquery/jquery-2.2.1.js', './assets/javascripts/bootstrap/bootstrap.js' ]) .pipe(concat('all.js')) .pipe(uglify()) .pipe(gulp.dest('./public/javascripts')); }); gulp.task('fonts', function () { return gulp.src('./assets/fonts/bootstrap/*') .pipe(gulp.dest('./public/fonts/bootstrap')); });
Use importlib to load custom fields by str
from django import forms from django.contrib import admin from django.utils.importlib import import_module from setmagic import settings from setmagic.models import Setting _denied = lambda *args: False class SetMagicAdmin(admin.ModelAdmin): list_display = 'label', 'current_value', list_editable = 'current_value', list_display_links = None has_add_permission = _denied has_delete_permission = _denied # Make all fields read-only at the change form def get_readonly_fields(self, *args, **kwargs): return self.opts.get_all_field_names() def changelist_view(self, *args, **kwargs): settings._sync() return super(SetMagicAdmin, self).changelist_view(*args, **kwargs) def get_queryset(self, request): return Setting.objects.filter(name__in=settings.defs) def get_changelist_form(self, *args, **kwargs): class Form(forms.ModelForm): class Meta: fields = self.list_editable def __init__(self, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) # Do nothing for empty forms if not self.instance.pk: return # Set a custom field custom_field = settings.defs[self.instance.name].get('field') if custom_field: if isinstance(custom_field, str): module, name = custom_field.rsplit('.', 1) custom_field = getattr(import_module(module), name)() self.fields['current_value'] = custom_field return Form admin.site.register(Setting, SetMagicAdmin)
from django import forms from django.contrib import admin from setmagic import settings from setmagic.models import Setting _denied = lambda *args: False class SetMagicAdmin(admin.ModelAdmin): list_display = 'label', 'current_value', list_editable = 'current_value', list_display_links = None has_add_permission = _denied has_delete_permission = _denied # Make all fields read-only at the change form def get_readonly_fields(self, *args, **kwargs): return self.opts.get_all_field_names() def changelist_view(self, *args, **kwargs): settings._sync() return super(SetMagicAdmin, self).changelist_view(*args, **kwargs) def get_queryset(self, request): return Setting.objects.filter(name__in=settings.defs) def get_changelist_form(self, *args, **kwargs): class Form(forms.ModelForm): class Meta: fields = self.list_editable def __init__(self, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) # Do nothing for empty forms if not self.instance.pk: return # Set a custom field custom_field = settings.defs[self.instance.name].get('field') if custom_field: self.fields['current_value'] = custom_field return Form admin.site.register(Setting, SetMagicAdmin)
Add API doc link to key management page
@title('Manage API keys: '.$user->name) @extends('app') @section('content') <h1>Manage API keys: {{ $user->name }}</h1> <ol class="breadcrumb"> <li><a href="{{ act('panel', 'index', $user->id) }}">Control Panel</a></li> <li class="active">Manage API keys</li> </ol> <p> <a href="{{ url('/wiki/page/TWHL_API_Documentation') }}">See this page for how to use the API.</a> </p> <h2>Active API Keys</h2> <table class="table"> <tr> <th>Key</th> <th>Generated</th> <th></th> </tr> @foreach ($user->api_keys as $key) <tr> <td> <code>{{ $key->key }}</code><br/> <em>Context: {{ $key->app }}</em> </td> <td> @date($key->created_at)<br> from {{ $key->ip }} </td> <td> @form(panel/delete-key) @hidden(id $key) <button class="btn btn-danger btn-xs" type="submit"> <span class="fa fa-remove"></span> Delete </button> @endform </td> </tr> @endforeach </table> <h2>Generate a new API key</h2> @form(panel/add-key) @hidden(id $user) @text(app) = Context (what the key will be used for) @submit = Create Key @endform @endsection
@title('Manage API keys: '.$user->name) @extends('app') @section('content') <h1>Manage API keys: {{ $user->name }}</h1> <ol class="breadcrumb"> <li><a href="{{ act('panel', 'index', $user->id) }}">Control Panel</a></li> <li class="active">Manage API keys</li> </ol> <h2>Active API Keys</h2> <table class="table"> <tr> <th>Key</th> <th>Generated</th> <th></th> </tr> @foreach ($user->api_keys as $key) <tr> <td> <code>{{ $key->key }}</code><br/> <em>Context: {{ $key->app }}</em> </td> <td> @date($key->created_at)<br> from {{ $key->ip }} </td> <td> @form(panel/delete-key) @hidden(id $key) <button class="btn btn-danger btn-xs" type="submit"> <span class="fa fa-remove"></span> Delete </button> @endform </td> </tr> @endforeach </table> <h2>Generate a new API key</h2> @form(panel/add-key) @hidden(id $user) @text(app) = Context (what the key will be used for) @submit = Create Key @endform @endsection
Store uploaded images in public/storage/images/uploaded
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Validator; class FileuploaderController extends Controller { public function upload() { $input = Input::all(); $error = ''; $callback = Input::get('CKEditorFuncNum'); $rules = array( 'upload' => 'image|max:15000|required', ); $validation = Validator::make($input, $rules); if ($validation->fails()) { return response($validation->messages(), 400); } $file = Input::file('upload'); $extension = $file->getClientOriginalExtension(); $filename = md5(date("YmdHis").rand(5, 50)) . "." . $extension; $destinationPath = '/storage/images/uploaded/'; $file->move(public_path() . $destinationPath, $filename); $http_path = $destinationPath . $filename; // return '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.', "'.$http_path.'", "'.$error.'" );</script>'; return [ "uploaded" => 1, "fileName" => $filename, "url" => $http_path, ]; } }
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Validator; class FileuploaderController extends Controller { public function upload() { $input = Input::all(); $error = ''; $callback = Input::get('CKEditorFuncNum'); $rules = array( 'upload' => 'image|max:15000|required', ); $validation = Validator::make($input, $rules); if ($validation->fails()) { return response($validation->messages(), 400); } $file = Input::file('upload'); $extension = $file->getClientOriginalExtension(); $filename = md5(date("YmdHis").rand(5, 50)) . "." . $extension; $destinationPath = '/images/uploaded/'; $file->move(public_path() . $destinationPath, $filename); $http_path = $destinationPath . $filename; // return '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.', "'.$http_path.'", "'.$error.'" );</script>'; return [ "uploaded" => 1, "fileName" => $filename, "url" => $http_path, ]; } }
Fix pull request from berwie. Just terrible.
<?php use \Entity\Station; use \Entity\Song; use \Entity\Schedule; class Api_NowplayingController extends \PVL\Controller\Action\Api { public function indexAction() { $file_path_api = DF_INCLUDE_STATIC.'/api/nowplaying_api.json'; $np_raw = file_get_contents($file_path_api); // Sanity check for now playing data. if (empty($np_raw)) { $this->returnError('Now Playing data has not loaded into the cache. Wait for file reload.'); return; } if ($this->hasParam('id') || $this->hasParam('station')) { $np_arr = @json_decode($np_raw, TRUE); $np = $np_arr['result']; if ($this->hasParam('id')) { $id = (int)$this->getParam('id'); foreach($np as $key => $station) { if($station->id === $id) { $sc = $key; break; } } if (!$sc) return $this->returnError('Station not found!'); } elseif ($this->hasParam('station')) { $sc = $this->getParam('station'); } if (isset($np[$sc])) $this->returnSuccess($np[$sc]); else return $this->returnError('Station not found!'); } else { $this->returnRaw($np_raw, 'json'); } } }
<?php use \Entity\Station; use \Entity\Song; use \Entity\Schedule; class Api_NowplayingController extends \PVL\Controller\Action\Api { public function indexAction() { $file_path_api = DF_INCLUDE_STATIC.'/api/nowplaying_api.json'; $np_raw = file_get_contents($file_path_api); // Sanity check for now playing data. if (empty($np_raw)) { $this->returnError('Now Playing data has not loaded into the cache. Wait for file reload.'); return; } if ($this->hasParam('id') || $this->hasParam('station')) { $np_arr = @json_decode($np_raw, TRUE); $np = $np_arr['result']; if ($this->hasParam('id')) { $id = (int)$this->getParam('id'); foreach($np as $key => $station) { if($station->id === $id) { $sc = $key; break; } } return $this->returnError('Station not found!'); } elseif ($this->hasParam('station')) { $sc = $this->getParam('station'); } if (isset($np[$sc])) $this->returnSuccess($np[$sc]); else return $this->returnError('Station not found!'); } else { $this->returnRaw($np_raw, 'json'); } } }
Make the A look better. ('Cause it matters, right?)
function makeFont(width, height, sparsity) { return { a: function (x, y) { var cx = 0, i = 0, cy = 0; var f = [ function (x) { if (x < width/2) { return height - height * (x)/(width/2); } else { return height * (x - width/2)/(width/2); } }, function (x) { if (x > width/4 && x < 3*width/4 && (x % 2)) return 2*height/3; } ]; var points = []; while (cx <= width) { for (i = 0; i < f.length; i += 1) { cy = f[i](cx); if (cy !== null) points[points.length] = [x + cx, y + cy]; } cx += sparsity; } return points; }, b: undefined, d: undefined, e: undefined, h: undefined, i: undefined, o: undefined, p: undefined, r: undefined, s: undefined, t: undefined, y: undefined, comma: undefined, space: function (x, y) { return []; }, }; }
function makeFont(width, height, sparsity) { return { a: function (x, y) { var cx = 0, i = 0, cy = 0; var f = [ function (x) { if (x < width/2) { return height - height * (x)/(width/2); } else { return height * (x - width/2)/(width/2); } }, function (x) { if (x > width/4 && x < 3*width/4 && !(x % 2)) return height/2; } ]; var points = []; while (cx <= width) { for (i = 0; i < f.length; i += 1) { cy = f[i](cx); if (cy !== null) points[points.length] = [x + cx, y + cy]; } cx += sparsity; } return points; }, b: undefined, d: undefined, e: undefined, h: undefined, i: undefined, o: undefined, p: undefined, r: undefined, s: undefined, t: undefined, y: undefined, comma: undefined, space: function (x, y) { return []; }, }; }
Add path field to preview file
from sqlalchemy_utils import UUIDType from zou.app import db from zou.app.models.serializer import SerializerMixin from zou.app.models.base import BaseMixin class PreviewFile(db.Model, BaseMixin, SerializerMixin): """ Describes a file which is aimed at being reviewed. It is not a publication neither a working file. """ name = db.Column(db.String(250)) revision = db.Column(db.Integer(), default=1) description = db.Column(db.Text()) path = db.Column(db.String(400)) source = db.Column(db.String(40)) shotgun_id = db.Column(db.Integer, unique=True) is_movie = db.Column(db.Boolean, default=False) url = db.Column(db.String(600)) uploaded_movie_url = db.Column(db.String(600)) uploaded_movie_name = db.Column(db.String(150)) task_id = db.Column( UUIDType(binary=False), db.ForeignKey("task.id"), index=True ) person_id = db.Column(UUIDType(binary=False), db.ForeignKey("person.id")) source_file_id = db.Column( UUIDType(binary=False), db.ForeignKey("output_file.id") ) __table_args__ = ( db.UniqueConstraint( "name", "task_id", "revision", name="preview_uc" ), ) def __repr__(self): return "<PreviewFile %s>" % self.id
from sqlalchemy_utils import UUIDType from zou.app import db from zou.app.models.serializer import SerializerMixin from zou.app.models.base import BaseMixin class PreviewFile(db.Model, BaseMixin, SerializerMixin): """ Describes a file which is aimed at being reviewed. It is not a publication neither a working file. """ name = db.Column(db.String(250)) revision = db.Column(db.Integer(), default=1) description = db.Column(db.Text()) source = db.Column(db.String(40)) shotgun_id = db.Column(db.Integer, unique=True) is_movie = db.Column(db.Boolean, default=False) url = db.Column(db.String(600)) uploaded_movie_url = db.Column(db.String(600)) uploaded_movie_name = db.Column(db.String(150)) task_id = db.Column( UUIDType(binary=False), db.ForeignKey("task.id"), index=True ) person_id = db.Column(UUIDType(binary=False), db.ForeignKey("person.id")) source_file_id = db.Column( UUIDType(binary=False), db.ForeignKey("output_file.id") ) __table_args__ = ( db.UniqueConstraint( "name", "task_id", "revision", name="preview_uc" ), ) def __repr__(self): return "<PreviewFile %s>" % self.id
Remove debugging code added in bec782c
<?php namespace AlgoliaSearch; /** * Class Json. */ class Json { public static function encode($value, $options = 0) { $json = json_encode($value, $options); self::checkError(); return $json; } public static function decode($json, $assoc = false, $depth = 512) { $value = json_decode($json, $assoc, $depth); self::checkError(); return $value; } private static function checkError() { $error = json_last_error(); if (!$error) { return; } $errorMsg = 'JSON error'; switch ($error) { case JSON_ERROR_DEPTH: $errorMsg = 'JSON parsing error: maximum stack depth exceeded'; break; case JSON_ERROR_CTRL_CHAR: $errorMsg = 'JSON parsing error: unexpected control character found'; break; case JSON_ERROR_SYNTAX: $errorMsg = 'JSON parsing error: syntax error, malformed JSON'; break; case JSON_ERROR_STATE_MISMATCH: $errorMsg = 'JSON parsing error: underflow or the modes mismatch'; break; // PHP 5.3 less than 1.2.2 (Ubuntu 10.04 LTS) case defined('JSON_ERROR_UTF8') ? JSON_ERROR_UTF8 : -1: $errorMsg = 'JSON parsing error: malformed UTF-8 characters, possibly incorrectly encoded'; break; } throw new AlgoliaException($errorMsg, $error); } }
<?php namespace AlgoliaSearch; /** * Class Json. */ class Json { public static function encode($value, $options = 0) { $json = json_encode($value, $options); self::checkError(); return $json; } public static function decode($json, $assoc = false, $depth = 512) { $value = json_decode($json, $assoc, $depth); if (null === $value) print_r($json); self::checkError(); return $value; } private static function checkError() { $error = json_last_error(); if (!$error) { return; } $errorMsg = 'JSON error'; switch ($error) { case JSON_ERROR_DEPTH: $errorMsg = 'JSON parsing error: maximum stack depth exceeded'; break; case JSON_ERROR_CTRL_CHAR: $errorMsg = 'JSON parsing error: unexpected control character found'; break; case JSON_ERROR_SYNTAX: $errorMsg = 'JSON parsing error: syntax error, malformed JSON'; break; case JSON_ERROR_STATE_MISMATCH: $errorMsg = 'JSON parsing error: underflow or the modes mismatch'; break; // PHP 5.3 less than 1.2.2 (Ubuntu 10.04 LTS) case defined('JSON_ERROR_UTF8') ? JSON_ERROR_UTF8 : -1: $errorMsg = 'JSON parsing error: malformed UTF-8 characters, possibly incorrectly encoded'; break; } throw new AlgoliaException($errorMsg, $error); } }