text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix (JWT Service): Text files should end with a newline character
<?php namespace AppBundle\Service; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; /** * Class JwtService * @package AppBundle\Service */ class JwtService{ private $ts; /** * JwtService constructor. * @param TokenStorage $ts */ public function __construct(TokenStorage $ts, $jwtManager){ $this->ts = $ts; $this->jwtManager = $jwtManager; } /** * Create token acces * @return mixed */ public function getToken(){ $client = $this->ts->getToken()->getUser(); return $this->jwtManager->create($client); } }
<?php namespace AppBundle\Service; use Doctrine\ORM\Tools\Pagination\Paginator; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; use Doctrine\ORM\EntityManager; /** * Class JwtService * @package AppBundle\Service */ class JwtService{ private $ts; /** * JwtService constructor. * @param TokenStorage $ts */ public function __construct(TokenStorage $ts, $jwtManager){ $this->ts = $ts; $this->jwtManager = $jwtManager; } /** * Create token acces * @return mixed */ public function getToken(){ $client = $this->ts->getToken()->getUser(); return $this->jwtManager->create($client); } }
Set default value of property "initProperty" of custom object annotation.
<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\Utils\Mapping\Annotation; /** * Custom object annotation * * @Annotation * @Target("PROPERTY") */ final class CustomObject { const ANNOTATION = __CLASS__; /** * @var string */ public $class; /** * @var string */ public $classPropertyPath; /** * @var string */ public $initProperty = 'id'; /** * @var string */ public $initPropertyValuePath; }
<?php /** * @author Igor Nikolaev <igor.sv.n@gmail.com> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\Utils\Mapping\Annotation; /** * Custom object annotation * * @Annotation * @Target("PROPERTY") */ final class CustomObject { const ANNOTATION = __CLASS__; /** * @var string */ public $class; /** * @var string */ public $classPropertyPath; /** * @var string */ public $initProperty; /** * @var string */ public $initPropertyValuePath; }
Handle Edge as an IE browser. Edge was handled as a non IE browser, and no resize events was triggered. Not, when handling Edge as an IE browser, events are triggered again.
"use strict"; var detector = module.exports = {}; detector.isIE = function(version) { function isAnyIeVersion() { var agent = navigator.userAgent.toLowerCase(); return agent.indexOf("msie") !== -1 || agent.indexOf("trident") !== -1 || agent.indexOf(" edge/") !== -1; } if(!isAnyIeVersion()) { return false; } if(!version) { return true; } //Shamelessly stolen from https://gist.github.com/padolsey/527683 var ieVersion = (function(){ var undef, v = 3, div = document.createElement("div"), all = div.getElementsByTagName("i"); do { div.innerHTML = "<!--[if gt IE " + (++v) + "]><i></i><![endif]-->"; } while (all[0]); return v > 4 ? v : undef; }()); return version === ieVersion; }; detector.isLegacyOpera = function() { return !!window.opera; };
"use strict"; var detector = module.exports = {}; detector.isIE = function(version) { function isAnyIeVersion() { var agent = navigator.userAgent.toLowerCase(); return agent.indexOf("msie") !== -1 || agent.indexOf("trident") !== -1; } if(!isAnyIeVersion()) { return false; } if(!version) { return true; } //Shamelessly stolen from https://gist.github.com/padolsey/527683 var ieVersion = (function(){ var undef, v = 3, div = document.createElement("div"), all = div.getElementsByTagName("i"); do { div.innerHTML = "<!--[if gt IE " + (++v) + "]><i></i><![endif]-->"; } while (all[0]); return v > 4 ? v : undef; }()); return version === ieVersion; }; detector.isLegacyOpera = function() { return !!window.opera; };
Remove workaround for broken el.find()
import { NodeComponent } from 'substance' import katex from 'katex' export default class InlineFormulaComponent extends NodeComponent { render($$) { const node = this.props.node const texMath = node.find('tex-math') const el = $$('span').addClass('sc-inline-formula') el.append( $$(TexMathComponent, { node: texMath }).ref('math') ) if (this.props.isolatedNodeState) { el.addClass('sm-'+this.props.isolatedNodeState) } return el } } class TexMathComponent extends NodeComponent { render($$) { const node = this.props.node const texMath = node.textContent const el = $$('span').addClass('sc-math') if (!texMath) { el.append('???') } else { try { el.append( $$('span').html(katex.renderToString(texMath)) ) let blockerEl = $$('div').addClass('se-blocker') el.append(blockerEl) } catch (error) { el.addClass('sm-error') .text(error.message) } } return el } }
import { NodeComponent } from 'substance' import katex from 'katex' export default class InlineFormulaComponent extends NodeComponent { render($$) { const node = this.props.node // TODO: Find out why node.find('tex-math') returns null here const texMath = node.findChild('tex-math') const el = $$('span').addClass('sc-inline-formula') el.append( $$(TexMathComponent, { node: texMath }).ref('math') ) if (this.props.isolatedNodeState) { el.addClass('sm-'+this.props.isolatedNodeState) } return el } } class TexMathComponent extends NodeComponent { render($$) { const node = this.props.node const texMath = node.textContent const el = $$('span').addClass('sc-math') if (!texMath) { el.append('???') } else { try { el.append( $$('span').html(katex.renderToString(texMath)) ) let blockerEl = $$('div').addClass('se-blocker') el.append(blockerEl) } catch (error) { el.addClass('sm-error') .text(error.message) } } return el } }
Update to use primary key instead of ID Rule::unique($user->getTable())->ignore($user->getKey()) By default uses the user table of idColumn = id. Added additional attribute of getKeyName to use the primary key defined in the user table.
<?php namespace Backpack\Base\app\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; class AccountInfoRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { // only allow updates if the user is logged in return backpack_auth()->check(); } /** * Restrict the fields that the user can change. * * @return array */ protected function validationData() { return $this->only(backpack_authentication_column(), 'name'); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $user = backpack_auth()->user(); return [ backpack_authentication_column() => [ 'required', backpack_authentication_column() == 'email' ? 'email' : '', Rule::unique($user->getTable())->ignore($user->getKey(),$user->getKeyName()), ], 'name' => 'required', ]; } }
<?php namespace Backpack\Base\app\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; class AccountInfoRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { // only allow updates if the user is logged in return backpack_auth()->check(); } /** * Restrict the fields that the user can change. * * @return array */ protected function validationData() { return $this->only(backpack_authentication_column(), 'name'); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $user = backpack_auth()->user(); return [ backpack_authentication_column() => [ 'required', backpack_authentication_column() == 'email' ? 'email' : '', Rule::unique($user->getTable())->ignore($user->getKey()), ], 'name' => 'required', ]; } }
Fix redirection to home on invalid token
<?php namespace Watson\Autologin; use Auth, Redirect; use Illuminate\Routing\Controller; use Watson\Autologin\Interfaces\AuthenticationInterface; use Watson\Autologin\Interfaces\AutologinInterface; class AutologinController extends Controller { /** * AuthenticationInterface provider instance. * * @var \Studious\Autologin\Interfaces\AuthenticationInterface */ protected $provider; /** * Studious Autologin instance. * * @var \Studious\Autologin\Autologin */ protected $autologin; /** * Instantiate the controller. */ public function __construct(AuthenticationInterface $authProvider, Autologin $autologin) { $this->authProvider = $authProvider; $this->autologin = $autologin; } /** * Process the autologin token and perform the redirect. */ public function autologin($token) { if ($autologin = $this->autologin->validate($token)) { // Active token found, login the user and redirect to the // intended path. $this->authProvider->loginUsingId($autologin->getUserId()); return Redirect::to($autologin->getPath()); } // Token was invalid, redirect back to the home page. return Redirect::to('/'); } }
<?php namespace Watson\Autologin; use Auth, Redirect; use Illuminate\Routing\Controller; use Watson\Autologin\Interfaces\AuthenticationInterface; use Watson\Autologin\Interfaces\AutologinInterface; class AutologinController extends Controller { /** * AuthenticationInterface provider instance. * * @var \Studious\Autologin\Interfaces\AuthenticationInterface */ protected $provider; /** * Studious Autologin instance. * * @var \Studious\Autologin\Autologin */ protected $autologin; /** * Instantiate the controller. */ public function __construct(AuthenticationInterface $authProvider, Autologin $autologin) { $this->authProvider = $authProvider; $this->autologin = $autologin; } /** * Process the autologin token and perform the redirect. */ public function autologin($token) { if ($autologin = $this->autologin->validate($token)) { // Active token found, login the user and redirect to the // intended path. $this->authProvider->loginUsingId($autologin->getUserId()); return Redirect::to($autologin->getPath()); } // Token was invalid, redirect back to the home page. return Redirect::to(base_path()); } }
Add an id to the results.
const fetch = require('node-fetch') const url = 'https://api.tumblr.com/v2/tagged?tag=pitbull&api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4' module.exports = (pluginContext) => { return { respondsTo: (query) => { return query === 'pibble' }, search: (query, env = {}) => { return fetch(url).then((res) => { return res.json() }).then((data) => { return data.response.filter((post) => { return post.type === 'photo' // Just photo posts }).sort(() => { return Math.floor(Math.random() * 2) || -1 // Randomize Sort }).map((post) => { return { id: post.id, icon: 'fa-camera', title: 'Can i haz pibble!?', subtitle: post.summary, preview: `<img src='${post.photos[0].original_size.url}' />`, value: post.post_url, } }) }) }, } }
const fetch = require('node-fetch') const url = 'https://api.tumblr.com/v2/tagged?tag=pitbull&api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4' module.exports = (pluginContext) => { return { respondsTo: (query) => { return query === 'pibble' }, search: (query, env = {}) => { return fetch(url).then((res) => { return res.json() }).then((data) => { return data.response.filter((post) => { return post.type === 'photo' // Just photo posts }).sort(() => { return Math.floor(Math.random() * 2) || -1 // Randomize Sort }).map((post) => { return { icon: 'fa-camera', title: 'Can i haz pibble!?', subtitle: post.summary, preview: `<img src='${post.photos[0].original_size.url}' />`, value: post.post_url, } }) }) }, } }
Fix error when multiple objects were returned for coordinators in admin
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from locations.models import District class Coordinator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_manager = models.BooleanField() district = models.ForeignKey(District, verbose_name=_('District'), blank=True, null=True) def filter_by_district(qs, user, lookup): # superusers and managers see everything if (user.is_superuser or hasattr(user, 'coordinator') and user.coordinator.is_manager): return qs # don't show anything to unconfigured users if not hasattr(user, 'coordinator') or not user.coordinator.district: return qs.none() kwargs = { lookup: user.coordinator.district } return qs.filter(**kwargs).distinct()
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from locations.models import District class Coordinator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_manager = models.BooleanField() district = models.ForeignKey(District, verbose_name=_('District'), blank=True, null=True) def filter_by_district(qs, user, lookup): # superusers and managers see everything if (user.is_superuser or hasattr(user, 'coordinator') and user.coordinator.is_manager): return qs # don't show anything to unconfigured users if not hasattr(user, 'coordinator') or not user.coordinator.district: return qs.none() kwargs = { lookup: user.coordinator.district } return qs.filter(**kwargs)
Update the way we assert newly created contacts
const selectors = require('../../../../selectors') const userActions = require('../../support/user-actions') describe('Contacts', () => { const data = { name: 'NewAddress', lastName: 'Contact', jobTitle: 'Coffee machine operator', countryCode: '44', phone: '0778877778800', email: 'company.contact@dit.com', address1: 'Rua Candido Portinari', address2: 'Numero 521', city: 'Campinas', country: 'Brazil', } it('should create a primary contact with a different address to the companies address', () => { cy.visit('/contacts/create?company=0fb3379c-341c-4da4-b825-bf8d47b26baa') userActions.contacts.createWithNewAddress(data) cy.get(selectors.contactCreate.details) .should('contain', 'Coffee machine operator') .and('contain', '(44) 0778877778800') .and('contain', 'company.contact@dit.com') .and('contain', 'Rua Candido Portinari, Numero 521, Campinas, Brazil') }) })
const selectors = require('../../../../selectors') const userActions = require('../../support/user-actions') describe('Contacts', () => { const data = { name: 'NewAddress', lastName: 'Contact', jobTitle: 'Coffee machine operator', countryCode: '44', phone: '0778877778800', email: 'company.contact@dit.com', address1: 'Rua Candido Portinari', address2: 'Numero 521', city: 'Campinas', country: 'Brazil', } it('should create a primary contact with a different address to the companies address', () => { cy.visit('/contacts/create?company=0fb3379c-341c-4da4-b825-bf8d47b26baa') userActions.contacts.createWithNewAddress(data) cy.visit('/companies/0fb3379c-341c-4da4-b825-bf8d47b26baa/contacts') cy.contains('NewAddress Contact').click() cy.get(selectors.contactCreate.details) .should('contain', 'Coffee machine operator') .and('contain', '(44) 0778877778800') .and('contain', 'company.contact@dit.com') .and('contain', 'Rua Candido Portinari, Numero 521, Campinas, Brazil') }) })
Make callback loader take into account directory names in loadable module name
# -*- coding: latin-1 -*- ''' Created on 16.10.2012 @author: Teemu Pkknen ''' import imp import sys import os import ntpath from qsdl.simulator.errors.ConfigurationInvalidError import ConfigurationInvalidError def path_leaf(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) def get_callback_module( name ): scriptDir = os.path.dirname(os.path.realpath(__file__)) callback_module_dir = scriptDir + '/' + ntpath.dirname( name ) callback_module_name = path_leaf( name ) # Already loaded? try: return sys.modules[name] except KeyError: pass fp = pathname = description = None try: fp, pathname, description = imp.find_module(callback_module_name, [callback_module_dir, os.getcwdu(), scriptDir]) return imp.load_module(name, fp, pathname, description) except: return None finally: if fp: fp.close()
# -*- coding: latin-1 -*- ''' Created on 16.10.2012 @author: Teemu Pkknen ''' import imp import sys import os from qsdl.simulator.errors.ConfigurationInvalidError import ConfigurationInvalidError def get_callback_module( name ): scriptDir = os.path.dirname(os.path.realpath(__file__)) # Already loaded? try: return sys.modules[name] except KeyError: pass fp = pathname = description = None try: fp, pathname, description = imp.find_module(name, [os.getcwdu(), scriptDir]) return imp.load_module(name, fp, pathname, description) except: return None finally: if fp: fp.close()
Fix error accessing class variable
''' This module retrieves the course catalog and overviews of the Udacity API Link to Documentation: https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf ''' import json import requests class UdacityAPI(object): ''' This class defines attributes and methods for Udaciy API ''' UDACITY_API_ENDPOINT = 'https://udacity.com/public-api/v0/courses' def __init__(self): self.response = requests.get(UdacityAPI.UDACITY_API_ENDPOINT) self.courses = self.response.json()['courses'] self.tracks = self.response.json()['tracks'] def status_code(self): ''' Return status code of response object ''' return self.response.status_code def get_courses(self): ''' Return list of course objects for all courses offered by Udacity ''' return self.courses def get_tracks(self): ''' Return list of tracks offered by Udacity ''' return self.tracks if __name__ == '__main__': udacity_object = UdacityAPI() print len(udacity_object.get_courses()) print udacity_object.get_courses()[0].keys()
''' This module retrieves the course catalog and overviews of the Udacity API Link to Documentation: https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf ''' import json import requests class UdacityAPI(object): ''' This class defines attributes and methods for Udaciy API ''' UDACITY_API_ENDPOINT = 'https://udacity.com/public-api/v0/courses' def __init__(self): self.response = requests.get(UDACITY_API_ENDPOINT) self.courses = self.response.json()['courses'] self.tracks = self.response.json()['tracks'] def status_code(self): ''' Return status code of response object ''' return self.response.status_code def get_courses(self): ''' Return list of course objects for all courses offered by Udacity ''' return self.courses def get_tracks(self): ''' Return list of tracks offered by Udacity ''' return self.tracks if __name__ == '__main__': udacity_object = UdacityAPI() print len(udacity_object.get_courses()) print udacity_object.get_courses()[0].keys()
Fix failing bash completion function test signature.
import click import pytest if click.__version__ >= '3.0': def test_legacy_callbacks(runner): def legacy_callback(ctx, value): return value.upper() @click.command() @click.option('--foo', callback=legacy_callback) def cli(foo): click.echo(foo) with pytest.warns(Warning, match='Invoked legacy parameter callback'): result = runner.invoke(cli, ['--foo', 'wat']) assert result.exit_code == 0 assert 'WAT' in result.output def test_bash_func_name(): from click._bashcomplete import get_completion_script script = get_completion_script('foo-bar baz_blah', '_COMPLETE_VAR', 'bash').strip() assert script.startswith('_foo_barbaz_blah_completion()') assert '_COMPLETE_VAR=complete $1' in script
import click import pytest if click.__version__ >= '3.0': def test_legacy_callbacks(runner): def legacy_callback(ctx, value): return value.upper() @click.command() @click.option('--foo', callback=legacy_callback) def cli(foo): click.echo(foo) with pytest.warns(Warning, match='Invoked legacy parameter callback'): result = runner.invoke(cli, ['--foo', 'wat']) assert result.exit_code == 0 assert 'WAT' in result.output def test_bash_func_name(): from click._bashcomplete import get_completion_script script = get_completion_script('foo-bar baz_blah', '_COMPLETE_VAR').strip() assert script.startswith('_foo_barbaz_blah_completion()') assert '_COMPLETE_VAR=complete $1' in script
Update version, email and requirements [ci skip]
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': """MiniCPS is a lightweight simulator for accurate network traffic in an industrial control system, with basic support for physical layer interaction.""", 'author': 'scy-phy', 'url': 'https://github.com/scy-phy/minicps', 'download_url': 'https://github.com/scy-phy/minicps', 'author email': 'daniele_antonioli@sutd.edu.sg', 'version': '1.0.0', 'install_requires': [ 'cpppo', 'nose', 'coverage', ], 'package': ['minicps'], 'scripts': [], 'name': 'minicps' } setup(**config)
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': """MiniCPS is a lightweight simulator for accurate network traffic in an industrial control system, with basic support for physical layer interaction.""", 'author': 'scy-phy', 'url': 'https://github.com/scy-phy/minicps', 'download_url': 'https://github.com/scy-phy/minicps', 'author email': 'abc@gmail.com', 'version': '0.1.0', 'install_requires': [ 'cpppo', 'networkx', 'matplotlib', 'nose', 'nose-cover3', ], 'package': ['minicps'], 'scripts': [], 'name': 'minicps' } setup(**config)
Add TODO's for improving admin experience for Event Content Listing
from icekit.plugins.content_listing.forms import ContentListingAdminForm from icekit_events.models import EventBase from .models import EventContentListingItem class EventContentListingAdminForm(ContentListingAdminForm): # TODO Improve admin experience: # - horizontal filter for `limit_to_types` choice # - verbose_name for Content Type # - default (required) value for No Items Message. class Meta: model = EventContentListingItem fields = '__all__' def filter_content_types(self, content_type_qs): """ Filter the content types selectable to only event subclasses """ valid_ct_ids = [] for ct in content_type_qs: model = ct.model_class() if model and issubclass(model, EventBase): valid_ct_ids.append(ct.id) return content_type_qs.filter(pk__in=valid_ct_ids)
from icekit.plugins.content_listing.forms import ContentListingAdminForm from icekit_events.models import EventBase from .models import EventContentListingItem class EventContentListingAdminForm(ContentListingAdminForm): class Meta: model = EventContentListingItem fields = '__all__' def filter_content_types(self, content_type_qs): """ Filter the content types selectable to only event subclasses """ valid_ct_ids = [] for ct in content_type_qs: model = ct.model_class() if model and issubclass(model, EventBase): valid_ct_ids.append(ct.id) return content_type_qs.filter(pk__in=valid_ct_ids)
Fix a bug in node 0.10 (and presumably other browsers) where the zero-width space is erroneously trimmed.
'use strict'; var bind = require('function-bind'); var define = require('define-properties'); var replace = bind.call(Function.call, String.prototype.replace); var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*$/; var trimRight = function trimRight() { return replace(this, rightWhitespace, ''); }; var boundTrimRight = bind.call(Function.call, trimRight); define(boundTrimRight, { shim: function shimTrimRight() { var zeroWidthSpace = '\u200b'; define(String.prototype, { trimRight: trimRight }, { trimRight: function () { return zeroWidthSpace.trimRight() !== zeroWidthSpace; } }); return String.prototype.trimRight; } }); module.exports = boundTrimRight;
'use strict'; var bind = require('function-bind'); var define = require('define-properties'); var replace = bind.call(Function.call, String.prototype.replace); var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*$/; var trimRight = function trimRight() { return replace(this, rightWhitespace, ''); }; var boundTrimRight = bind.call(Function.call, trimRight); define(boundTrimRight, { shim: function shimTrimRight() { if (!String.prototype.trimRight) { define(String.prototype, { trimRight: trimRight }); } return String.prototype.trimRight; } }); module.exports = boundTrimRight;
Add Django version trove classifiers
# -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup from setuptools import find_packages setup( name='django-password-reset', version=__import__('password_reset').__version__, author='Bruno Renie', author_email='bruno@renie.fr', packages=find_packages(), include_package_data=True, url='https://github.com/brutasse/django-password-reset', license='BSD licence, see LICENSE file', description='Class-based views for password reset.', long_description=open('README.rst').read(), install_requires=[ 'Django>=1.8', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], test_suite='runtests.runtests', zip_safe=False, )
# -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup from setuptools import find_packages setup( name='django-password-reset', version=__import__('password_reset').__version__, author='Bruno Renie', author_email='bruno@renie.fr', packages=find_packages(), include_package_data=True, url='https://github.com/brutasse/django-password-reset', license='BSD licence, see LICENSE file', description='Class-based views for password reset.', long_description=open('README.rst').read(), install_requires=[ 'Django>=1.8', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], test_suite='runtests.runtests', zip_safe=False, )
Rename argument, remove unusued one
<?php /** *@file * Contains \Drupal\AppConsole\Generator\PluginImageEffectGenerator. */ namespace Drupal\AppConsole\Generator; class PluginImageEffectGenerator extends Generator { /** * Generator Plugin Image Effect * @param string $module Module name * @param string $class_name Plugin Class name * @param string $plugin_label Plugin label * @param string $plugin_id Plugin id * @param string $description Plugin description */ public function generate($module, $class_name, $plugin_label, $plugin_id, $description) { $parameters = [ 'module' => $module, 'class_name' => $class_name, 'plugin_label' => $plugin_label, 'plugin_id' => $plugin_id, 'description' => $description, ]; $this->renderFile( 'module/plugin-imageeffect.php.twig', $this->getPluginPath($module, 'ImageEffect').'/'.$class_name.'.php', $parameters ); } }
<?php /** *@file * Contains \Drupal\AppConsole\Generator\PluginImageEffectGenerator. */ namespace Drupal\AppConsole\Generator; class PluginImageEffectGenerator extends Generator { /** * Generator Plugin Image Effect * @param string $module Module name * @param string $class_name Plugin Class name * @param string $plugin_label Plugin label * @param string $plugin_id Plugin id * @param string $description Plugin description */ public function generate($module, $class_name, $plugin_label, $plugin_id, $description) { $parameters = [ 'module' => $module, 'class' => [ 'name' => $class_name, ], 'plugin_label' => $plugin_label, 'plugin_id' => $plugin_id, 'description' => $description, ]; $this->renderFile( 'module/plugin-imageeffect.php.twig', $this->getPluginPath($module, 'ImageEffect').'/'.$class_name.'.php', $parameters ); } }
lxd/firewall/firewall/interface: Add NetworkSetup and remove feature specific network setup functions Signed-off-by: Thomas Parrott <6b778ce645fb0e3dde76d79eccad490955b1ae74@canonical.com>
package firewall import ( "net" deviceConfig "github.com/lxc/lxd/lxd/device/config" drivers "github.com/lxc/lxd/lxd/firewall/drivers" ) // Firewall represents a LXD firewall. type Firewall interface { String() string Compat() (bool, error) NetworkSetup(networkName string, opts drivers.Opts) error NetworkClear(networkName string, ipVersion uint) error InstanceSetupBridgeFilter(projectName string, instanceName string, deviceName string, parentName string, hostName string, hwAddr string, IPv4 net.IP, IPv6 net.IP) error InstanceClearBridgeFilter(projectName string, instanceName string, deviceName string, parentName string, hostName string, hwAddr string, IPv4 net.IP, IPv6 net.IP) error InstanceSetupProxyNAT(projectName string, instanceName string, deviceName string, listen *deviceConfig.ProxyAddress, connect *deviceConfig.ProxyAddress) error InstanceClearProxyNAT(projectName string, instanceName string, deviceName string) error InstanceSetupRPFilter(projectName string, instanceName string, deviceName string, hostName string) error InstanceClearRPFilter(projectName string, instanceName string, deviceName string) error }
package firewall import ( "net" deviceConfig "github.com/lxc/lxd/lxd/device/config" ) // Firewall represents a LXD firewall. type Firewall interface { String() string Compat() (bool, error) NetworkSetupForwardingPolicy(networkName string, ipVersion uint, allow bool) error NetworkSetupOutboundNAT(networkName string, subnet *net.IPNet, srcIP net.IP, append bool) error NetworkSetupDHCPDNSAccess(networkName string, ipVersion uint) error NetworkSetupDHCPv4Checksum(networkName string) error NetworkClear(networkName string, ipVersion uint) error InstanceSetupBridgeFilter(projectName string, instanceName string, deviceName string, parentName string, hostName string, hwAddr string, IPv4 net.IP, IPv6 net.IP) error InstanceClearBridgeFilter(projectName string, instanceName string, deviceName string, parentName string, hostName string, hwAddr string, IPv4 net.IP, IPv6 net.IP) error InstanceSetupProxyNAT(projectName string, instanceName string, deviceName string, listen *deviceConfig.ProxyAddress, connect *deviceConfig.ProxyAddress) error InstanceClearProxyNAT(projectName string, instanceName string, deviceName string) error InstanceSetupRPFilter(projectName string, instanceName string, deviceName string, hostName string) error InstanceClearRPFilter(projectName string, instanceName string, deviceName string) error }
Add correct IIF and scope
/** * @license * Copyright (c) 2015 MediaMath Inc. All rights reserved. * This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt */ (function (scope) { scope.Action = Polymer({ is: "mm-action", behaviors: [ StrandTraits.Stylable ], properties: { ver:{ type:String, value:"<<version>>", }, href: { type: String, value: false, reflectToAttribute: true }, underline: { type: Boolean, value: false, reflectToAttribute: true }, target: { type: String, value: "_self", reflectToAttribute: true }, disabled: { type: Boolean, value: false, reflectToAttribute: true } }, PRIMARY_ICON_COLOR: Colors.D0, ready: function() { // if there is an icon - colorize it: var items = Array.prototype.slice.call(Polymer.dom(this.$.icon).getDistributedNodes()); if (items.length) { items[0].setAttribute("primary-color", this.PRIMARY_ICON_COLOR); } }, updateClass: function(underline) { var o = {}; o["action"] = true; o["underline"] = underline; return this.classList(o); } }); })(window.Strand = window.Strand || {});
/** * @license * Copyright (c) 2015 MediaMath Inc. All rights reserved. * This code may only be used under the BSD style license found at http://mediamath.github.io/strand/LICENSE.txt */ Polymer({ is: "mm-action", behaviors: [ StrandTraits.Stylable ], properties: { ver:{ type:String, value:"<<version>>", }, href: { type: String, value: false, reflectToAttribute: true }, underline: { type: Boolean, value: false, reflectToAttribute: true }, target: { type: String, value: "_self", reflectToAttribute: true }, disabled: { type: Boolean, value: false, reflectToAttribute: true } }, PRIMARY_ICON_COLOR: Colors.D0, ready: function() { // if there is an icon - colorize it: var items = Array.prototype.slice.call(Polymer.dom(this.$.icon).getDistributedNodes()); if (items.length) { items[0].setAttribute("primary-color", this.PRIMARY_ICON_COLOR); } }, updateClass: function(underline) { var o = {}; o["action"] = true; o["underline"] = underline; return this.classList(o); } });
Make sure the data is parse out as json from the server for SSE
'use strict'; var glimpse = require('glimpse'); var polyfill = require('event-source') var socket = (function() { var connection; var setup = function() { connection = new polyfill.EventSource('/Glimpse/MessageStream'); connection.onmessage = function(e) { if (!FAKE_SERVER) { glimpse.emit('data.message.summary.found.stream', JSON.parse(e.data)); } }; }; return { check: function() { if (!connection) { setup(); } } }; })(); module.exports = { subscribeToLastestSummaries: function () { socket.check(); }, subscribeToDetailsFor: function (requestId) { // TODO: Setup SSE code } };
'use strict'; var glimpse = require('glimpse'); var polyfill = require('event-source') var socket = (function() { var connection; var setup = function() { connection = new polyfill.EventSource('/Glimpse/MessageStream'); connection.onmessage = function(e) { if (!FAKE_SERVER) { glimpse.emit('data.message.summary.found.stream', e.data); } }; }; return { check: function() { if (!connection) { setup(); } } }; })(); module.exports = { subscribeToLastestSummaries: function () { socket.check(); }, subscribeToDetailsFor: function (requestId) { // TODO: Setup SSE code } };
Use 0x04 for reset event since 0x00 is not supported
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.nuklei.tcp.internal.types.stream; public final class Types { public static final int TYPE_ID_BEGIN = 0x00000001; public static final int TYPE_ID_DATA = 0x00000002; public static final int TYPE_ID_END = 0x00000003; public static final int TYPE_ID_RESET = 0x00000004; private Types() { // no instances } }
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.nuklei.tcp.internal.types.stream; public final class Types { public static final int TYPE_ID_RESET = 0x00000000; public static final int TYPE_ID_BEGIN = 0x00000001; public static final int TYPE_ID_DATA = 0x00000002; public static final int TYPE_ID_END = 0x00000003; private Types() { // no instances } }
Revert "Fixed da bug. Right?" This reverts commit 09c6aba54f7b73ab35b02b9f6b75462a3b3579a1.
// Auto-create new intput-groups $(".js-lists").on("focus", ".disabled", function () { var disabledRow = $(".input-group.disabled"); var newInputGroup = disabledRow.clone()[0]; disabledRow.removeClass("disabled").addClass("js-create-on-keypress"); $(".js-lists").one("keypress", ".js-create-on-keypress", function () { $(".js-create-on-keypress") .removeClass("js-create-on-keypress") .after(newInputGroup); }); }); $(".js-lists").on("keypress", recountTotals); // Count the non-blank inputs in each column function recountTotals () { $(".js-listcount").each(function (index, element) { var count = 0; $("input", $(".js-list").get(index)).each(function (i, el) { if (el.value) { ++count; console.log("Count is " + count); } }) $(element).text(count); }) }
// Auto-create new intput-groups $(".js-lists").on("focus", ".disabled", function () { var disabledRow = $(".input-group.disabled"); var newInputGroup = disabledRow.clone()[0]; disabledRow.removeClass("disabled").addClass("js-create-on-keypress"); $(".js-lists").one("keypress", ".js-create-on-keypress", function () { $(".js-create-on-keypress") .removeClass("js-create-on-keypress") .after(newInputGroup); }); }); $(".js-lists").on("keyup", recountTotals); $(".js-lists").on("blur", recountTotals); // Count the non-blank inputs in each column function recountTotals () { $(".js-listcount").each(function (index, element) { var count = 0; $("input", $(".js-list").get(index)).each(function (i, el) { if (el.value) { ++count; console.log("Count is " + count); } }) $(element).text(count); }) }
Remove Python 2.5 support, add support for Python 3.2
import os from setuptools import setup, find_packages def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() setup( name='gears-uglifyjs', version='0.1', url='https://github.com/gears/gears-uglifyjs', license='ISC', author='Mike Yumatov', author_email='mike@yumatov.org', description='UglifyJS compressor for Gears', long_description=read('README.rst'), packages=find_packages(), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', ], )
import os from setuptools import setup, find_packages def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() setup( name='gears-uglifyjs', version='0.1', url='https://github.com/gears/gears-uglifyjs', license='ISC', author='Mike Yumatov', author_email='mike@yumatov.org', description='UglifyJS compressor for Gears', long_description=read('README.rst'), packages=find_packages(), include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
Fix loading of posts (lob) (again)
/* * Copyright 2015 EuregJUG. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.euregjug.site.events; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.transaction.annotation.Transactional; /** * @author Michael J. Simons, 2015-12-26 */ public interface RegistrationRepository extends JpaRepository<RegistrationEntity, Integer> { /** * @param event * @param email * @return A registration for a given event by a user. */ public Optional<RegistrationEntity> findByEventAndEmail(final EventEntity event, final String email); @Transactional(readOnly = true) public List<RegistrationEntity> findAllByEventId(Integer eventId); }
/* * Copyright 2015 EuregJUG. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.euregjug.site.events; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; /** * @author Michael J. Simons, 2015-12-26 */ public interface RegistrationRepository extends JpaRepository<RegistrationEntity, Integer> { /** * @param event * @param email * @return A registration for a given event by a user. */ public Optional<RegistrationEntity> findByEventAndEmail(final EventEntity event, final String email); public List<RegistrationEntity> findAllByEventId(Integer eventId); }
Replace call to deprecated virtool.file.processor
import os import virtool.file import virtool.utils from virtool.handlers.utils import json_response, not_found async def find(req): db = req.app["db"] query = { "ready": True } file_type = req.query.get("type", None) if file_type: query["type"] = file_type cursor = db.files.find(query, virtool.file.PROJECTION) found_count = await cursor.count() documents = [virtool.utils.base_processor(d) for d in await cursor.to_list(15)] return json_response({ "documents": documents, "found_count": found_count }) async def remove(req): file_id = req.match_info["file_id"] file_path = os.path.join(req.app["settings"].get("data_path"), "files", file_id) delete_result = await req.app["db"].files.delete_one({"_id": file_id}) virtool.utils.rm(file_path) if delete_result.deleted_count == 0: return not_found("Document does not exist") await req.app["dispatcher"].dispatch("files", "remove", [file_id]) return json_response({ "file_id": file_id, "removed": True })
import os import virtool.file import virtool.utils from virtool.handlers.utils import json_response, not_found async def find(req): db = req.app["db"] query = { "ready": True } file_type = req.query.get("type", None) if file_type: query["type"] = file_type cursor = db.files.find(query, virtool.file.PROJECTION) found_count = await cursor.count() documents = [virtool.file.processor(d) for d in await cursor.to_list(15)] return json_response({ "documents": documents, "found_count": found_count }) async def remove(req): file_id = req.match_info["file_id"] file_path = os.path.join(req.app["settings"].get("data_path"), "files", file_id) delete_result = await req.app["db"].files.delete_one({"_id": file_id}) virtool.utils.rm(file_path) if delete_result.deleted_count == 0: return not_found("Document does not exist") await req.app["dispatcher"].dispatch("files", "remove", [file_id]) return json_response({ "file_id": file_id, "removed": True })
Make the Bugsy PyPI page link to GitHub Since there is currently no mention of the repo there. Signed-off-by: AutomatedTester <3d61f6450d7e43c8b567795ed24e9858346487a0@mozilla.com>
from setuptools import setup, find_packages setup(name='bugsy', version='0.4.1', description='A library for interacting Bugzilla Native REST API', author='David Burns', author_email='david.burns at theautomatedtester dot co dot uk', url='https://github.com/AutomatedTester/Bugsy', classifiers=['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Libraries', 'Programming Language :: Python'], packages = find_packages(), install_requires=['requests>=1.1.0'], )
from setuptools import setup, find_packages setup(name='bugsy', version='0.4.1', description='A library for interacting Bugzilla Native REST API', author='David Burns', author_email='david.burns at theautomatedtester dot co dot uk', url='http://oss.theautomatedtester.co.uk/bugzilla', classifiers=['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Libraries', 'Programming Language :: Python'], packages = find_packages(), install_requires=['requests>=1.1.0'], )
Use bootstrap utility to retrieve the configuration name from the environment.
#!/usr/bin/env python # -*- coding: utf-8 -*- """Run a worker for the job queue.""" import sys from redis import StrictRedis from rq import Connection, Queue, Worker from bootstrap.util import app_context, get_config_name_from_env if __name__ == '__main__': try: config_name = get_config_name_from_env() except Exception as e: sys.stderr.write(str(e) + '\n') sys.exit() with app_context(config_name) as app: redis = StrictRedis(app.config['REDIS_URL']) with Connection(redis): queues = [Queue()] worker = Worker(queues) worker.work()
#!/usr/bin/env python # -*- coding: utf-8 -*- """Run a worker for the job queue.""" import os import sys from redis import StrictRedis from rq import Connection, Queue, Worker from bootstrap.util import app_context if __name__ == '__main__': config_name = os.environ.get('ENVIRONMENT') if config_name is None: sys.stderr.write("Environment variable 'ENVIRONMENT' must be set but isn't.") sys.exit() with app_context(config_name) as app: redis = StrictRedis(app.config['REDIS_URL']) with Connection(redis): queues = [Queue()] worker = Worker(queues) worker.work()
Make the expected Age header value a string because all header values are strings
/* eslint-env mocha */ "use strict"; const request = require("supertest"); const host = require("../helpers").host; describe("Request with a If-None-Match value which is the same as the ETag", function() { it(`responds with a 304 and an Age reset to 0`, function() { this.timeout(30000); return request(host) .get("/v3/polyfill.min.js") .expect(200) .then(response => { const eTag = response.headers["etag"]; return request(host) .get("/v3/polyfill.min.js") .set("if-none-match", eTag) .expect(304) .expect("Age", "0"); }); }); }); describe("Request with a If-None-Match value which is different to the ETag", function() { it(`responds with a 200 and an Age reset to 0`, function() { this.timeout(30000); return request(host) .get("/v3/polyfill.min.js") .expect(200) .then(response => { const eTag = response.headers["etag"]; return request(host) .get("/v3/polyfill.min.js") .set("if-none-match", eTag) .expect(304) .expect("Age", "0"); }); }); });
/* eslint-env mocha */ "use strict"; const request = require("supertest"); const host = require("../helpers").host; describe("Request with a If-None-Match value which is the same as the ETag", function() { it(`responds with a 304 and an Age reset to 0`, function() { this.timeout(30000); return request(host) .get("/v3/polyfill.min.js") .expect(200) .then(response => { const eTag = response.headers["etag"]; return request(host) .get("/v3/polyfill.min.js") .set("if-none-match", eTag) .expect(304) .expect("Age", 0); }); }); }); describe("Request with a If-None-Match value which is the different to the ETag", function() { it(`responds with a 200 and an Age reset to 0`, function() { this.timeout(30000); return request(host) .get("/v3/polyfill.min.js") .expect(200) .then(response => { const eTag = response.headers["etag"]; return request(host) .get("/v3/polyfill.min.js") .set("if-none-match", eTag) .expect(304) .expect("Age", 0); }); }); });
Rename offer signal to remove unused conditions/benefits
from django.db.models.signals import post_delete from django.dispatch import receiver from oscar.core.loading import get_model ConditionalOffer = get_model('offer', 'ConditionalOffer') Condition = get_model('offer', 'Condition') Benefit = get_model('offer', 'Benefit') @receiver(post_delete, sender=ConditionalOffer) def delete_unused_related_conditions_and_benefits(instance, **kwargs): offer = instance # the object is no longer in the database condition_id = offer.condition_id condition = Condition.objects.get(id=condition_id) condition_is_unique = condition.offers.count() == 0 condition_is_not_custom = condition.proxy_class == '' if condition_is_not_custom and condition_is_unique: condition.delete() benefit_id = offer.benefit_id benefit = Benefit.objects.get(id=benefit_id) benefit_is_unique = benefit.offers.count() == 0 benefit_is_not_custom = benefit.proxy_class == '' if benefit_is_not_custom and benefit_is_unique: benefit.delete()
from django.db.models.signals import post_delete from django.dispatch import receiver from oscar.core.loading import get_model ConditionalOffer = get_model('offer', 'ConditionalOffer') Condition = get_model('offer', 'Condition') Benefit = get_model('offer', 'Benefit') @receiver(post_delete, sender=ConditionalOffer) def delete_related_useless_conditions_and_benefits(instance, **kwargs): offer = instance # the object is no longer in the database condition_id = offer.condition_id condition = Condition.objects.get(id=condition_id) condition_is_unique = condition.offers.count() == 0 condition_is_not_custom = condition.proxy_class == '' if condition_is_not_custom and condition_is_unique: condition.delete() benefit_id = offer.benefit_id benefit = Benefit.objects.get(id=benefit_id) benefit_is_unique = benefit.offers.count() == 0 benefit_is_not_custom = benefit.proxy_class == '' if benefit_is_not_custom and benefit_is_unique: benefit.delete()
Remove repeat option from coverage
# -*- coding: utf-8 -*- """py.test utilities.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import logging import numpy as np import warnings import matplotlib from phylib import add_default_handler from phylib.conftest import * # noqa #------------------------------------------------------------------------------ # Common fixtures #------------------------------------------------------------------------------ logger = logging.getLogger('phy') logger.setLevel(10) add_default_handler(5, logger=logger) # Fix the random seed in the tests. np.random.seed(2019) warnings.filterwarnings('ignore', category=matplotlib.cbook.mplDeprecation) warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") def pytest_addoption(parser): """Repeat option.""" parser.addoption('--repeat', action='store', help='Number of times to repeat each test') def pytest_generate_tests(metafunc): # pragma: no cover # Use --repeat option. if metafunc.config.option.repeat is not None: count = int(metafunc.config.option.repeat) metafunc.fixturenames.append('tmp_ct') metafunc.parametrize('tmp_ct', range(count))
# -*- coding: utf-8 -*- """py.test utilities.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import logging import numpy as np import warnings import matplotlib from phylib import add_default_handler from phylib.conftest import * # noqa #------------------------------------------------------------------------------ # Common fixtures #------------------------------------------------------------------------------ logger = logging.getLogger('phy') logger.setLevel(10) add_default_handler(5, logger=logger) # Fix the random seed in the tests. np.random.seed(2019) warnings.filterwarnings('ignore', category=matplotlib.cbook.mplDeprecation) warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") def pytest_addoption(parser): """Repeat option.""" parser.addoption('--repeat', action='store', help='Number of times to repeat each test') def pytest_generate_tests(metafunc): if metafunc.config.option.repeat is not None: count = int(metafunc.config.option.repeat) metafunc.fixturenames.append('tmp_ct') metafunc.parametrize('tmp_ct', range(count))
backend: Update logic on game controller
var inspect = require('eyes').inspector({ stream: null }); module.exports = { index: function(req, res, next){ var project_id = req.query.project_id; process.database.games.find({project_id: project_id}, function(error, games){ if(error){res.send(error); return false;} games.toArray(function(err, results){ if(err){res.send(err); return false;} res.send(results); }); }); }, create: function(req, res, next){ var game = { _id: req.body._id, name: req.body.name, project_id: req.body.projectId }; process.database.games.save(game, function(error, savedGame){ if(error){res.send(error); return false;} res.send({sucess: true}); }); }, update: function(req, res, next){ var _id = req.body._id; var name = req.body.name; process.database.games.update({_id: _id},{ $set: {name: name} }, function(error, savedGame){ if(error){res.send(error); return false;} res.send({sucess: true}); }); } };
var inspect = require('eyes').inspector({ stream: null }); module.exports = { index: function(req, res, next){ var project_id = req.query.project_id; process.database.games.find({project_id: project_id}, function(error, games){ if(error){res.send(error); return false;} games.toArray(function(err, results){ if(err){res.send(err); return false;} res.send(results); }); }); }, create: function(req, res, next){ var game = { _id: req.body._id, name: req.body.name, project_id: req.body.projectId }; console.log(inspect(game)); process.database.games.save(game, function(error, savedGame){ if(error){res.send(error); return false;} res.send({sucess: true}); }); } };
Add support for an index mode
'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; var getIndex = require( './get_index.js' ); // FUNCTIONS // /** * Returns an array element. * * @private * @param {...integer} idx - indices * @throws {TypeError} provided indices must be integer valued * @throws {RangeError} index exceeds array dimensions * @returns {*} array element */ function get() { /* eslint-disable no-invalid-this */ var len; var idx; var ind; var i; len = arguments.length; idx = this._offset; for ( i = 0; i < len; i++ ) { if ( !isInteger( arguments[ i ] ) ) { throw new TypeError( 'invalid input argument. Indices must be integer valued. Argument: '+i+'. Value: `'+arguments[i]+'`.' ); } ind = getIndex( arguments[ i ], this._shape[ i ], this._mode ); idx += this._strides[ i ] * ind; } return this._buffer[ idx ]; } // end FUNCTION get() // EXPORTS // module.exports = get;
'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // FUNCTIONS // /** * Returns an array element. * * @private * @param {...integer} idx - indices * @throws {TypeError} provided indices must be integer valued * @throws {RangeError} index exceeds array dimensions * @returns {*} array element */ function get() { /* eslint-disable no-invalid-this */ var len; var idx; var i; // TODO: support index modes len = arguments.length; idx = this._offset; for ( i = 0; i < len; i++ ) { if ( !isInteger( arguments[ i ] ) ) { throw new TypeError( 'invalid input argument. Indices must be integer valued. Argument: '+i+'. Value: `'+arguments[i]+'`.' ); } idx += this._strides[ i ] * arguments[ i ]; } return this._buffer[ idx ]; } // end FUNCTION get() // EXPORTS // module.exports = get;
Fix missing close for email logo file handle
from email.mime.image import MIMEImage from django.contrib.staticfiles import finders from .base import EmailBase class PlatformEmailMixin: """ Attaches the static file images/logo.png so it can be used in an html email. """ def get_attachments(self): attachments = super().get_attachments() filename = ( finders.find('images/email_logo.png') or finders.find('images/email_logo.svg') ) if filename: with open(filename, 'rb') as f: logo = MIMEImage(f.read()) logo.add_header('Content-ID', '<{}>'.format('logo')) return attachments + [logo] return attachments class SyncEmailMixin(EmailBase): """Send Emails synchronously.""" @classmethod def send(cls, object, *args, **kwargs): """Call dispatch immediately""" return cls().dispatch(object, *args, **kwargs)
from email.mime.image import MIMEImage from django.contrib.staticfiles import finders from .base import EmailBase class PlatformEmailMixin: """ Attaches the static file images/logo.png so it can be used in an html email. """ def get_attachments(self): attachments = super().get_attachments() filename = ( finders.find('images/email_logo.png') or finders.find('images/email_logo.svg') ) if filename: f = open(filename, 'rb') logo = MIMEImage(f.read()) logo.add_header('Content-ID', '<{}>'.format('logo')) return attachments + [logo] return attachments class SyncEmailMixin(EmailBase): """Send Emails synchronously.""" @classmethod def send(cls, object, *args, **kwargs): """Call dispatch immediately""" return cls().dispatch(object, *args, **kwargs)
Remove "test" prefix from test methods for consistency Fixes #19.
/* * Copyright 2015-2017 the original author or authors. * * 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 */ package com.example.project; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import static org.junit.jupiter.api.Assertions.assertEquals; @DisplayName("Nested test classes") public class NestedTest { private Calculator calculator = new Calculator(); @Nested @Tag("negative") class TestAddingNegativeNumber { @BeforeEach void setUp(TestInfo testInfo) { System.out.println("Executing: " + testInfo.getDisplayName()); } @Test @DisplayName("Tests adding zero") void addZero() { assertEquals(-2, calculator.add(-2, 0)); } @Test @DisplayName("Tests adding two negative numbers") void addNegativeNumber() { assertEquals(-3, calculator.add(-1, -2)); } } }
/* * Copyright 2015-2017 the original author or authors. * * 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 */ package com.example.project; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import static org.junit.jupiter.api.Assertions.assertEquals; @DisplayName("Nested test classes") public class NestedTest { private Calculator calculator = new Calculator(); @Nested @Tag("negative") class TestAddingNegativeNumber { @BeforeEach void setUp(TestInfo testInfo) { System.out.println("Executing: " + testInfo.getDisplayName()); } @Test @DisplayName("Tests adding zero") void testAddingZero() { assertEquals(-2, calculator.add(-2, 0)); } @Test @DisplayName("Tests adding two negative numbers") void testAddingNegative() { assertEquals(-3, calculator.add(-1, -2)); } } }
Test sending a fresh message
import os from flask import Flask, request import twilio.twiml from twilio.rest import TwilioRestClient app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def hello(): from_number = request.args.get('From') text_content = request.args.get('Body').lower() client = TwilioRestClient(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN']) client.sms.messages.create(to="+17187535039", from_=from_number, body="fresh message!") message = from_number + ", thanks for the donation!" resp = twilio.twiml.Response() resp.sms(message) return str(resp) if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
import os from flask import Flask, request, redirect, session import twilio.twiml from twilio.rest import TwilioRestClient from charity import Charity SECRET_KEY = os.environ['DONATION_SECRET_KEY'] app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def hello(): from_number = request.values.get('From', None) client = TwilioRestClient() charity = Charity() client.sms.messages.create(to="+17187535039", from_=from_number, body="fresh message!") message = from_number + ", thanks for the message!" resp = twilio.twiml.Response() resp.sms(message) return str(resp) if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
Replace hiding-face reaction with coffee reaction The coffee reaction is meant to represent "BRB".
import m from 'mithril'; class ReactionPickerComponent { oninit({ attrs: { game, session } }) { this.game = game; this.session = session; } sendReaction(reaction) { this.session.emit('send-reaction', { reaction }); } view() { return m('div#reaction-picker', ReactionPickerComponent.availableReactions.map((reaction) => { return m('div.available-reaction', m('div.available-reaction-symbol', { onclick: () => this.sendReaction(reaction) }, reaction.symbol)); })); } } ReactionPickerComponent.availableReactions = [ { symbol: '👏' }, { symbol: '😁' }, { symbol: '😮' }, { symbol: '😭' }, { symbol: '😉' }, { symbol: '😬' }, { symbol: '☕' } ]; export default ReactionPickerComponent;
import m from 'mithril'; class ReactionPickerComponent { oninit({ attrs: { game, session } }) { this.game = game; this.session = session; } sendReaction(reaction) { this.session.emit('send-reaction', { reaction }); } view() { return m('div#reaction-picker', ReactionPickerComponent.availableReactions.map((reaction) => { return m('div.available-reaction', m('div.available-reaction-symbol', { onclick: () => this.sendReaction(reaction) }, reaction.symbol)); })); } } ReactionPickerComponent.availableReactions = [ { symbol: '👏' }, { symbol: '😁' }, { symbol: '😮' }, { symbol: '😭' }, { symbol: '😉' }, { symbol: '😬' }, { symbol: '🙈' } ]; export default ReactionPickerComponent;
Downgrade pytest version to be able to use default shippable minion
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'pelican-do', 'author': 'Commands to automate common pelican tasks', 'url': '', 'download_url': '', 'author_email': 'gustavoajz@gmail.com', 'version': '0.1', 'install_requires': [ 'click==6.2', 'Jinja2==2.8', 'awesome-slugify==1.6.5', ], 'extras_require': { 'development': [ ], }, 'setup_requires': [ 'pytest-runner', ], 'tests_require': [ 'pytest>=2.6.4', 'pytest-cov==2.2.0' ], 'packages': ['pelican_do'], 'scripts': [], 'name': 'pelican-do', 'entry_points': { 'console_scripts': ['pelican-do=pelican_do.main:main'] } } setup(**config)
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'pelican-do', 'author': 'Commands to automate common pelican tasks', 'url': '', 'download_url': '', 'author_email': 'gustavoajz@gmail.com', 'version': '0.1', 'install_requires': [ 'click==6.2', 'Jinja2==2.8', 'awesome-slugify==1.6.5', ], 'extras_require': { 'development': [ ], }, 'setup_requires': [ 'pytest-runner', ], 'tests_require': [ 'pytest==2.8.5', 'pytest-cov==2.2.0' ], 'packages': ['pelican_do'], 'scripts': [], 'name': 'pelican-do', 'entry_points': { 'console_scripts': ['pelican-do=pelican_do.main:main'] } } setup(**config)
Update resource group unit test
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == self.provider.resource_group, "Resource Group should be {0}".format(rg.name)) def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be {0}".format(rg.name))
from cloudbridge.cloud.providers.azure.test.helpers import ProviderTestBase class AzureResourceGroupTestCase(ProviderTestBase): def test_resource_group_create(self): resource_group_params = {'location': self.provider.region_name} rg = self.provider.azure_client. \ create_resource_group(self.provider.resource_group, resource_group_params) print("Create Resource - " + str(rg)) self.assertTrue( rg.name == "cloudbridge", "Resource Group should be Cloudbridge") def test_resource_group_get(self): rg = self.provider.azure_client.get_resource_group('MyGroup') print("Get Resource - " + str(rg)) self.assertTrue( rg.name == "testResourceGroup", "Resource Group should be Cloudbridge")
Fix typo that was causing test failure. git-svn-id: a346edc3f722475ad04b72d65977aa35d4befd55@543 3a26569e-5468-0410-bb2f-b495330926e5
/* * Copyright 2010 55 Minutes (http://www.55minutes.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //= require <jquery-ui> //= require <strftime> jQuery("#${component.markupId}").datepicker( { showOn: "both" , buttonImage: "${behavior.buttonImageUrl}" , buttonImageOnly: true , changeMonth: true , changeYear: true } );
/* * Copyright 2010 55 Minutes (http://www.55minutes.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //= require <jquery-ui> //= require <strftime> jQuery("#${component.marukpId}").datepicker( { showOn: "both" , buttonImage: "${behavior.buttonImageUrl}" , buttonImageOnly: true , changeMonth: true , changeYear: true } );
Fix RDID reading code to ignore leading space
import serial class iButton(object): def __init__(self, ibutton_address, rfid_address, debug=False): # self.ibutton_serial = serial.Serial(ibutton_address) self.rfid_serial = serial.Serial(rfid_address) self.debug = debug def read(self): if self.debug: with open("ibutton.txt") as ibutton_file: return ibutton_file.readline().strip() code = '' while True: byte = self.rfid_serial.read() if byte == ' ': continue if len(code)==12: return code code += byte print("Reading ID: %s" % code)
import serial class iButton(object): def __init__(self, ibutton_address, rfid_address, debug=False): # self.ibutton_serial = serial.Serial(ibutton_address) self.rfid_serial = serial.Serial(rfid_address) self.debug = debug def read(self): if self.debug: with open("ibutton.txt") as ibutton_file: return ibutton_file.readline().strip() code = '' while True: byte = self.rfid_serial.read() if len(code)==12: return code code += byte print("Reading ID: %s" % code)
Handle ActionBar possibly not existing.
package com.dglogik.mobile; import android.app.ActivityManager; import android.app.Service; import android.app.*; import android.graphics.*; import android.graphics.drawable.*; import android.content.Context; import android.support.annotation.NonNull; public class Utils { public static boolean isServiceRunning(@NonNull Context context, @NonNull Class<? extends Service> clazz) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (service.service.getClassName().equals(clazz.getName())) { return true; } } return false; } @NonNull public static Thread startThread(Runnable action) { Thread thread = new Thread(action); thread.start(); return thread; } public static void applyDGTheme(Activity activity) { ActionBar bar = activity.getActionBar(); if (bar != null) { bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4dd0e1"))); } } }
package com.dglogik.mobile; import android.app.ActivityManager; import android.app.Service; import android.app.*; import android.graphics.*; import android.graphics.drawable.*; import android.content.Context; import android.support.annotation.NonNull; public class Utils { public static boolean isServiceRunning(@NonNull Context context, @NonNull Class<? extends Service> clazz) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (service.service.getClassName().equals(clazz.getName())) { return true; } } return false; } @NonNull public static Thread startThread(Runnable action) { Thread thread = new Thread(action); thread.start(); return thread; } public static void applyDGTheme(Activity activity) { ActionBar bar = activity.getActionBar(); bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4dd0e1"))); } }
Fix detection of relative clause
__author__ = 's7a' # All imports from nltk.tree import Tree # The Relative clauses class class RelativeClauses: # Constructor for the Relative Clauses class def __init__(self): self.has_wh_word = False # Break the tree def break_tree(self, tree): t = Tree.fromstring(str(tree)) self.has_wh_word = False self.parse_tree(t) print "Relative Clause: " + str(self.has_wh_word) result_string = "" return result_string # Parse the tree def parse_tree(self, tree): if type(tree) == Tree: if tree.label() == "SBAR": for node in tree: if type(node) == Tree: self.has_wh_word |= node.label() == "WHNP" for node in tree: self.parse_tree(node)
__author__ = 's7a' # All imports from nltk.tree import Tree # The Relative clauses class class RelativeClauses: # Constructor for the Relative Clauses class def __init__(self): self.has_wh_word = False # Break the tree def break_tree(self, tree): t = Tree.fromstring(str(tree)) self.has_wh_word = False self.parse_tree(t) print "Relative Clause: " + str(self.has_wh_word) result_string = "" return result_string # Parse the tree def parse_tree(self, tree): if type(tree) == Tree: self.has_wh_word |= tree.label() == "WHNP" for node in tree: self.parse_tree(node)
Change attribution message from 'by' to 'via'
var Twit = require('twit'); var config = require('./config.json'); var talks = require('libtlks').talk; var T = new Twit({ consumer_key: config.twitterConsumerKey, consumer_secret: config.twitterConsumerSecret, access_token: config.workers.twitter.token, access_token_secret: config.workers.twitter.secret }); function getUrl(talk) { return "http://tlks.io/talk/" + talk.slug; }; talks.getRandom(config.mongodb, function(err, docs) { if (err) { throw new Error(err); } var talk = docs[0]; var username = talk.author.username; var tweet = talk.title; tweet = tweet + ' ' + getUrl(talk) + ' via @' + username; T.post('statuses/update', { status: tweet }, function(err, data, response) { if (err) { console.log(err); } }); });
var Twit = require('twit'); var config = require('./config.json'); var talks = require('libtlks').talk; var T = new Twit({ consumer_key: config.twitterConsumerKey, consumer_secret: config.twitterConsumerSecret, access_token: config.workers.twitter.token, access_token_secret: config.workers.twitter.secret }); function getUrl(talk) { return "http://tlks.io/talk/" + talk.slug; }; talks.getRandom(config.mongodb, function(err, docs) { if (err) { throw new Error(err); } var talk = docs[0]; var username = talk.author.username; var tweet = talk.title; tweet = tweet + ' ' + getUrl(talk) + ' by @' + username; T.post('statuses/update', { status: tweet }, function(err, data, response) { if (err) { console.log(err); } }); });
Fix namespace to work with sf2.2
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\CoreBundle\Tests\Form\Type; use Sonata\CoreBundle\Form\Type\CollectionType; use Symfony\Component\Form\Tests\Extension\Core\Type\TypeTestCase; use Symfony\Component\OptionsResolver\OptionsResolver; class CollectionTypeTest extends TypeTestCase { public function testGetDefaultOptions() { $type = new CollectionType(); $optionResolver = new OptionsResolver(); $type->setDefaultOptions($optionResolver); $options = $optionResolver->resolve(); $this->assertFalse($options['modifiable']); $this->assertEquals('text', $options['type']); $this->assertEquals(0, count($options['type_options'])); $this->assertEquals('link_add', $options['btn_add']); $this->assertEquals('SonataCoreBundle', $options['btn_catalogue']); } }
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\CoreBundle\Tests\Form\Type; use Sonata\CoreBundle\Form\Type\CollectionType; use Symfony\Component\Form\Test\TypeTestCase; use Symfony\Component\OptionsResolver\OptionsResolver; class CollectionTypeTest extends TypeTestCase { public function testGetDefaultOptions() { $type = new CollectionType(); $optionResolver = new OptionsResolver(); $type->setDefaultOptions($optionResolver); $options = $optionResolver->resolve(); $this->assertFalse($options['modifiable']); $this->assertEquals('text', $options['type']); $this->assertEquals(0, count($options['type_options'])); $this->assertEquals('link_add', $options['btn_add']); $this->assertEquals('SonataCoreBundle', $options['btn_catalogue']); } }
Kill all running greenlets when ctrl+c (works a charm in Python 3, not so much in 2).
# pyinfra # File: pyinfra_cli/__main__.py # Desc: bootstrap stuff for the pyinfra CLI and provide it's entry point import signal import sys import click import gevent from colorama import init as colorama_init from .legacy import run_main_with_legacy_arguments from .main import cli, main # Init colorama for Windows ANSI color support colorama_init() # Don't write out deploy.pyc/config.pyc etc sys.dont_write_bytecode = True # Make sure imported files (deploy.py/etc) behave as if imported from the cwd sys.path.append('.') # Shut it click click.disable_unicode_literals_warning = True # noqa def _handle_interrupt(signum, frame): click.echo('Exiting upon user request!') sys.exit(0) gevent.signal(signal.SIGINT, gevent.kill) # kill any greenlets on ctrl+c signal.signal(signal.SIGINT, _handle_interrupt) # print the message and exit main def execute_pyinfra(): # Legacy support for pyinfra <0.4 using docopt if '-i' in sys.argv: run_main_with_legacy_arguments(main) else: cli()
# pyinfra # File: pyinfra_cli/__main__.py # Desc: bootstrap stuff for the pyinfra CLI and provide it's entry point import signal import sys import click from colorama import init as colorama_init from .legacy import run_main_with_legacy_arguments from .main import cli, main # Init colorama for Windows ANSI color support colorama_init() # Don't write out deploy.pyc/config.pyc etc sys.dont_write_bytecode = True # Make sure imported files (deploy.py/etc) behave as if imported from the cwd sys.path.append('.') # Shut it click click.disable_unicode_literals_warning = True # noqa # Handle ctrl+c def _signal_handler(signum, frame): print('Exiting upon user request!') sys.exit(0) signal.signal(signal.SIGINT, _signal_handler) # noqa def execute_pyinfra(): # Legacy support for pyinfra <0.4 using docopt if '-i' in sys.argv: run_main_with_legacy_arguments(main) else: cli()
Improve examples to make composition order clear Address comment made regarding ambiguous execution order: https://github.com/Gozala/functional/commit/dda3adec7201114ef53356d4b4d5b93ce3c5c639#commitcomment-3348727
"use strict"; var slicer = Array.prototype.slice module.exports = compose function compose() { /** Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. Usage: var square = function(x) { return x * x } var increment = function(x) { return x + 1 } var f1 = compose(increment, square) f1(5) // => 26 var f2 = compose(square, increment) f2(5) // => 36 **/ var lambdas = slicer.call(arguments) return function composed() { var params = slicer.call(arguments) var index = lambdas.length var result = [lambdas[--index].apply(this, params)] while (0 <= --index) result[0] = lambdas[index].apply(this, result) return result[0] } }
"use strict"; var slicer = Array.prototype.slice module.exports = compose function compose() { /** Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. Usage: var greet = function(name) { return 'hi: ' + name } var exclaim = function(statement) { return statement + '!' } var welcome = compose(exclaim, greet) welcome('moe') // => 'hi: moe!' **/ var lambdas = slicer.call(arguments) return function composed() { var params = slicer.call(arguments) var index = lambdas.length var result = [lambdas[--index].apply(this, params)] while (0 <= --index) result[0] = lambdas[index].apply(this, result) return result[0] } }
Update Item API handler to use api changes
<?php header('Content-type:application/json'); // Object require_once('./object/item.php'); // Service // Database require_once('./json/item.php'); // Initialize response. $status = 500; $body = []; $header = ''; // Method router. switch ($_SERVER['REQUEST_METHOD']) { case 'GET': get(); break; default: $status = 405; $header .= 'Allow: GET'; } // Get router. function get () { switch ( count($_GET) ) { case 0: getList(); break; case 1: getItem(); break; default: $status = 400; } } // Get item. function getItem () { // Retrieve item. $item = ItemJson::get($_GET['id']); // if not found. if (gettype($item) != 'array') { $status = 404; return; } $status = 200; $body = $item; return; } // Get item list. function getList () { // Retrieve item list. $list = ItemJson::list(); // If not found. if (gettype($item) != 'array') { $status = 503; return; } $status = 200; $body = $list; return; } HTTP::respond($status, $body, $header); ?>
<?php header('Content-type:application/json'); require_once('./json.php'); require_once('./objects/item.php'); /* routes */ switch ($_SERVER['REQUEST_METHOD']) { case 'GET': get(); break; default: http_response_code(405); header('Allow: GET'); } function get () { switch ( count($_GET) ) { case 0: getList(); break; case 1: getItem(); break; default: //http_response_code(400); } } /* end points */ function getItem () { $list = getJson('item'); foreach ($list as $i) { if ($_GET['id'] == $i['id']){ $item = new Item(); $item->createFromArray($i); exit($item->toJson()); } } exit(http_response_code(404)); } function getList () { $list = getJson('item'); exit(json_encode($list)); } ?>
Fix formatting and spelling in block comment
/* This package implements the leftpad function, inspired by the NPM (JS) package of the same name. Two functions are defined: import "leftpad" // pad with spaces str, err := LeftPad(s, n) // pad with specified character str, err := func LeftPadStr(s, n, c) */ package leftpad import ( "errors" "fmt" "strings" ) var ErrInvalidChar = errors.New("Invalid character") func doLeftPad(s string, n int, c string) (string, error) { if n < 0 { return "", errors.New(fmt.Sprintf("Invalid length %d", n)) } if len(c) != 1 { return "", ErrInvalidChar } toAdd := n - len(s) if toAdd <= 0 { return s, nil } return strings.Repeat(c, toAdd) + s, nil } func LeftPad(s string, n int) (string, error) { return doLeftPad(s, n, " ") } func LeftPadStr(s string, n int, c string) (string, error) { return doLeftPad(s, n, c) }
// leftpad.go /* This package implements the leftpad function, inspired by the NPM (JS) package of the same name. Two functions are defined: import "leftpad" // pad with spacex str, err := LeftPad(s, n) // pad with specified character str, err := func LeftPadStr(s, n, c) */ package leftpad import ( "errors" "fmt" "strings" ) var ErrInvalidChar = errors.New("Invalid character") func doLeftPad(s string, n int, c string) (string, error) { if n < 0 { return "", errors.New(fmt.Sprintf("Invalid length %d", n)) } if len(c) != 1 { return "", ErrInvalidChar } toAdd := n - len(s) if toAdd <= 0 { return s, nil } return strings.Repeat(c, toAdd) + s, nil } func LeftPad(s string, n int) (string, error) { return doLeftPad(s, n, " ") } func LeftPadStr(s string, n int, c string) (string, error) { return doLeftPad(s, n, c) }
Fix migration error 'project_id' doesn't exist
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProjectUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('project_user', function (Blueprint $table) { $table->increments('id'); $table->integer('project_id')->unsigned(); $table->integer('user_id')->unsigned(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('project_user'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProjectUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('project_user', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('project_user'); } }
Remove some more unecessary @property doc comments
<?php namespace PhpParser\Node\Expr; use PhpParser\Node\Expr; class AssignRef extends Expr { /** @var Expr Variable reference is assigned to */ public $var; /** @var Expr Variable which is referenced */ public $expr; /** * Constructs an assignment node. * * @param Expr $var Variable * @param Expr $expr Expression * @param array $attributes Additional attributes */ public function __construct(Expr $var, Expr $expr, array $attributes = array()) { parent::__construct($attributes); $this->var = $var; $this->expr = $expr; } public function getSubNodeNames() { return array('var', 'expr'); } }
<?php namespace PhpParser\Node\Expr; use PhpParser\Node\Expr; /** * @property Expr $var Variable reference is assigned to * @property Expr $expr Variable which is referenced */ class AssignRef extends Expr { /** @var Expr Variable reference is assigned to */ public $var; /** @var Expr Variable which is referenced */ public $expr; /** * Constructs an assignment node. * * @param Expr $var Variable * @param Expr $expr Expression * @param array $attributes Additional attributes */ public function __construct(Expr $var, Expr $expr, array $attributes = array()) { parent::__construct($attributes); $this->var = $var; $this->expr = $expr; } public function getSubNodeNames() { return array('var', 'expr'); } }
Fix button for new versions
<?php /* This template expects following variables: - Mandatory $d: the object holding the goal $p: the object describing the permissions - Optional */ $parent = $d->parent; $child = $d->child; ?> @include('field', array('name' => 'name')) @if(isset($p['own_page']) and $p['own_page']) {{ link_to_route('goals.create', trans('ui.goals.new'), array('original' => $d->id), array('class' => 'ajax button small')) }} @endif @if(isset($parent)) <div class="parent left"> {{ link_to_route('goals.show', trans('ui.goals.parent'), $parent->id) }} </div> @endif @if(isset($child)) <div class="child right"> {{ link_to_route('goals.show', trans('ui.goals.child'), $child->id) }} </div> @endif @include('feedback.index', array('d' => $d->feedbacks, 'obj_id' => $d->id, 'obj_type' => 'Goal')) @include('agrees.widget', array('d' => $d->agrees, 'obj_id' => $d->id, 'obj_type' => 'Goal'))
<?php /* This template expects following variables: - Mandatory $d: the object holding the goal $p: the object describing the permissions - Optional */ $parent = $d->parent; $child = $d->child; ?> @include('field', array('name' => 'name')) @if($p['own_page']) {{ link_to_route('goals.create', trans('ui.goals.new'), array('original' => $d->id), array('class' => 'ajax button small')) }} @endif @if(isset($parent)) <div class="parent left"> {{ link_to_route('goals.show', trans('ui.goals.parent'), $parent->id) }} </div> @endif @if(isset($child)) <div class="child right"> {{ link_to_route('goals.show', trans('ui.goals.child'), $child->id) }} </div> @endif @include('feedback.index', array('d' => $d->feedbacks, 'obj_id' => $d->id, 'obj_type' => 'Goal')) @include('agrees.widget', array('d' => $d->agrees, 'obj_id' => $d->id, 'obj_type' => 'Goal'))
Improve build task to run test before
/// var pkg = require("./package.json") , gulp = require("gulp") , plumber = require("gulp-plumber") /// // Lint JS /// var jshint = require("gulp-jshint") , jsonFiles = [".jshintrc", "*.json"] , jsFiles = ["*.js", "src/**/*.js"] gulp.task("scripts.lint", function() { gulp.src([].concat(jsonFiles).concat(jsFiles)) .pipe(plumber()) .pipe(jshint(".jshintrc")) .pipe(jshint.reporter("jshint-stylish")) }) var jscs = require("gulp-jscs") gulp.task("scripts.cs", function() { gulp.src(jsFiles) .pipe(plumber()) .pipe(jscs()) }) gulp.task("scripts", ["scripts.lint", "scripts.cs"]) gulp.task("watch", function() { gulp.watch(jsFiles, ["scripts"]) }) gulp.task("dist", ["scripts"]) gulp.task("test", ["dist"]) gulp.task("default", ["test", "watch"]) var buildBranch = require("buildbranch") gulp.task("publish", ["test"], function(cb) { buildBranch({folder: "src"} , function(err) { if (err) { throw err } console.log(pkg.name + " published.") cb() }) })
/// var pkg = require("./package.json") , gulp = require("gulp") , plumber = require("gulp-plumber") /// // Lint JS /// var jshint = require("gulp-jshint") , jsonFiles = [".jshintrc", "*.json"] , jsFiles = ["*.js", "src/**/*.js"] gulp.task("scripts.lint", function() { gulp.src([].concat(jsonFiles).concat(jsFiles)) .pipe(plumber()) .pipe(jshint(".jshintrc")) .pipe(jshint.reporter("jshint-stylish")) }) var jscs = require("gulp-jscs") gulp.task("scripts.cs", function() { gulp.src(jsFiles) .pipe(plumber()) .pipe(jscs()) }) gulp.task("scripts", ["scripts.lint", "scripts.cs"]) gulp.task("watch", function() { gulp.watch(jsFiles, ["scripts"]) }) gulp.task("default", ["scripts", "watch"]) var buildBranch = require("buildbranch") gulp.task("publish", function(cb) { buildBranch({folder: "src"} , function(err) { if (err) { throw err } console.log(pkg.name + " published.") cb() }) })
Define unicode in Python 3 __unicode__ was removed in Python 3 because all __str__ are Unicode. [flake8](http://flake8.pycqa.org) testing of https://github.com/mwouts/jupytext on Python 3.7.0 $ __flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics__ ``` ./.jupyter/jupyter_notebook_config.py:1:1: F821 undefined name 'c' c.NotebookApp.contents_manager_class = 'jupytext.TextFileContentsManager' ^ ./tests/test_unicode.py:15:65: F821 undefined name 'unicode' assert cell.source == '' or isinstance(cell.source, unicode) ^ ./tests/mirror/jupyter_again.py:32:1: E999 SyntaxError: invalid syntax ?next ^ 1 E999 SyntaxError: invalid syntax 2 F821 undefined name 'c' 3 ```
# coding: utf-8 import sys import pytest import jupytext from .utils import list_all_notebooks try: unicode # Python 2 except NameError: unicode = str # Python 3 @pytest.mark.parametrize('nb_file', list_all_notebooks('.ipynb') + list_all_notebooks('.Rmd')) def test_notebook_contents_is_unicode(nb_file): nb = jupytext.readf(nb_file) for cell in nb.cells: if sys.version_info < (3, 0): assert cell.source == '' or isinstance(cell.source, unicode) else: assert isinstance(cell.source, str) def test_write_non_ascii(tmpdir): nb = jupytext.reads(u'Non-ascii contênt', ext='.Rmd') jupytext.writef(nb, str(tmpdir.join('notebook.Rmd'))) jupytext.writef(nb, str(tmpdir.join('notebook.ipynb')))
# coding: utf-8 import sys import pytest import jupytext from .utils import list_all_notebooks @pytest.mark.parametrize('nb_file', list_all_notebooks('.ipynb') + list_all_notebooks('.Rmd')) def test_notebook_contents_is_unicode(nb_file): nb = jupytext.readf(nb_file) for cell in nb.cells: if sys.version_info < (3, 0): assert cell.source == '' or isinstance(cell.source, unicode) else: assert isinstance(cell.source, str) def test_write_non_ascii(tmpdir): nb = jupytext.reads(u'Non-ascii contênt', ext='.Rmd') jupytext.writef(nb, str(tmpdir.join('notebook.Rmd'))) jupytext.writef(nb, str(tmpdir.join('notebook.ipynb')))
Update to work with new versions of ember-cli
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-inject-asset-map', // Add asset map hash to asset-map controller postBuild: function (results) { var fs = require('fs'), path = require('path'), colors = require('colors'), tree = results['graph']['tree'], assetMap = tree._inputNodes[0].assetMap, jsPath = path.join(results.directory, assetMap['assets/art19.js']), // TODO: allow specifying name of js file js = fs.readFileSync(jsPath, 'utf-8'), assetMapKey = 'assetMapHash', expression = new RegExp(assetMapKey + ':\\s?(void 0|undefined)'), injectedJs = js.replace(expression, assetMapKey + ': ' + JSON.stringify(assetMap)); console.log('\nInjecting asset map hash...'.rainbow); // Write to temp and dist fs.writeFileSync(jsPath, injectedJs, 'utf-8'); fs.writeFileSync(path.join('./dist', assetMap['assets/art19.js']), injectedJs, 'utf-8'); console.log('Done! Asset paths are available in all components, controllers, and routes via assetMap.assetMapHash.'.rainbow); } };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-inject-asset-map', // Add asset map hash to asset-map controller postBuild: function (results) { console.log('Injecting asset map hash...'); var fs = require('fs'), path = require('path'), assetMap = results['graph']['tree']['assetMap'], jsPath = path.join(results.directory, assetMap['assets/art19.js']); // TODO: allow specifying name of js file // TODO: I'd love a cleaner way to do this, but I'm not sure sure how since this has to be done after build. var js = fs.readFileSync(jsPath, 'utf-8'), assetMapKey = 'assetMapHash', hackedJs = js.replace(new RegExp(assetMapKey + ': undefined'), assetMapKey + ': ' + JSON.stringify(assetMap)), hackedCompressed = js.replace(new RegExp(assetMapKey + ':void 0'), assetMapKey + ':' + JSON.stringify(assetMap)); // Inject in temp fs.writeFileSync(jsPath, hackedJs, 'utf-8'); // Inject in dist (this assumes dist is using JS compression.) fs.writeFileSync(path.join('./dist', assetMap['assets/art19.js']), hackedCompressed, 'utf-8'); console.log('Done! Asset paths are available in all components, controllers, and routes via assetMap.assetMapHash.'); } };
Clean GET and POST params before create an instance
<?php namespace AmoCRM; class Client { private $parameters = null; public function __construct($domain, $login, $apikey) { $this->parameters = new ParamsBag(); $this->parameters->addAuth('domain', $domain); $this->parameters->addAuth('login', $login); $this->parameters->addAuth('apikey', $apikey); } public function __get($name) { $classname = '\\AmoCRM\\' . ucfirst($name); if (!class_exists($classname)) { throw new ResourceException('Resource not exists: ' . $name); } // Чистим GET и POST от предыдущих вызовов $this->parameters->clearGet()->clearPost(); return new $classname($this->parameters); } }
<?php namespace AmoCRM; class Client { private $parameters = null; public function __construct($domain, $login, $apikey) { $this->parameters = new ParamsBag(); $this->parameters->addAuth('domain', $domain); $this->parameters->addAuth('login', $login); $this->parameters->addAuth('apikey', $apikey); } public function __get($name) { $classname = '\\AmoCRM\\' . ucfirst($name); if (!class_exists($classname)) { throw new ResourceException('Resource not exists: ' . $name); } return new $classname($this->parameters); } }
Disable debug toolbar. It creates import problems
from .default import * # NOQA # # Django Development # .......................... DEBUG = True TEMPLATE_DEBUG = True SOUTH_TESTS_MIGRATE = False # Tested at settings.tests # # Developper additions # .......................... INSTALLED_APPS = ( # 'debug_toolbar', 'django_extensions', ) + INSTALLED_APPS INTERNAL_IPS = ( '127.0.0.1', # localhost default '10.0.3.1', # lxc default ) # # Use some default tiles # .......................... LEAFLET_CONFIG['TILES'] = [ (gettext_noop('Scan'), 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', '(c) OpenStreetMap Contributors'), (gettext_noop('Ortho'), 'http://{s}.tiles.mapbox.com/v3/openstreetmap.map-4wvf9l0l/{z}/{x}/{y}.jpg', '(c) MapBox'), ] LEAFLET_CONFIG['OVERLAYS'] = [ (gettext_noop('Coeur de parc'), 'http://{s}.tilestream.makina-corpus.net/v2/coeur-ecrins/{z}/{x}/{y}.png', 'Ecrins'), ] LEAFLET_CONFIG['SRID'] = 3857 LOGGING['loggers']['geotrek']['level'] = 'DEBUG' LOGGING['loggers']['']['level'] = 'DEBUG' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
from .default import * # NOQA # # Django Development # .......................... DEBUG = True TEMPLATE_DEBUG = True SOUTH_TESTS_MIGRATE = False # Tested at settings.tests # # Developper additions # .......................... INSTALLED_APPS = ( 'debug_toolbar', 'django_extensions', ) + INSTALLED_APPS INTERNAL_IPS = ( '127.0.0.1', # localhost default '10.0.3.1', # lxc default ) # # Use some default tiles # .......................... LEAFLET_CONFIG['TILES'] = [ (gettext_noop('Scan'), 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', '(c) OpenStreetMap Contributors'), (gettext_noop('Ortho'), 'http://{s}.tiles.mapbox.com/v3/openstreetmap.map-4wvf9l0l/{z}/{x}/{y}.jpg', '(c) MapBox'), ] LEAFLET_CONFIG['OVERLAYS'] = [ (gettext_noop('Coeur de parc'), 'http://{s}.tilestream.makina-corpus.net/v2/coeur-ecrins/{z}/{x}/{y}.png', 'Ecrins'), ] LEAFLET_CONFIG['SRID'] = 3857 LOGGING['loggers']['geotrek']['level'] = 'DEBUG' LOGGING['loggers']['']['level'] = 'DEBUG' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Enable sourcemaps for easier debugging
var path = require('path'); var webpack = require('webpack') var modules = { preLoaders: [ { test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ } ], loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader", query: { presets: [ 'es2015', 'react' ], plugins: [ 'transform-object-rest-spread', 'transform-regenerator' ] } }, { test: /\.json$/, loader: 'json-loader' } ] }; var plugins = [ new webpack.DefinePlugin({ VERSION: JSON.stringify(require('./package.json').version) }), new webpack.DefinePlugin({ "global.GENTLY": false }) ]; module.exports = [{ entry: './renderer/index.js', devtool: 'cheap-module-eval-source-map', eslint: { configFile: './.eslintrc' }, output: { path: __dirname + '/build/', filename: 'bundle.js' }, target: 'atom', module: modules, plugins: plugins }, { entry: './main/main-develop.js', eslint: { configFile: './.eslintrc' }, output: { path: __dirname, filename: 'main.js' }, target: 'atom', node: { __dirname: false, __filename: false }, module: modules, plugins: plugins }];
var path = require('path'); var webpack = require('webpack') var modules = { preLoaders: [ { test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ } ], loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader", query: { presets: [ 'es2015', 'react' ], plugins: [ 'transform-object-rest-spread', 'transform-regenerator' ] } }, { test: /\.json$/, loader: 'json-loader' } ] }; var plugins = [ new webpack.DefinePlugin({ VERSION: JSON.stringify(require('./package.json').version) }), new webpack.DefinePlugin({ "global.GENTLY": false }) ]; module.exports = [{ entry: './renderer/index.js', eslint: { configFile: './.eslintrc' }, output: { path: __dirname + '/build/', filename: 'bundle.js' }, target: 'atom', module: modules, plugins: plugins }, { entry: './main/main-develop.js', eslint: { configFile: './.eslintrc' }, output: { path: __dirname, filename: 'main.js' }, target: 'atom', node: { __dirname: false, __filename: false }, module: modules, plugins: plugins }];
Add notice if config.php is missing
<?php /** * Gallery - A project for 'WPF - Moderne Webanwendungen' at * Cologne University of Applied Sciences. * * @author Dominik Schilling <dominik.schilling@smail.fh-koeln.de> * @author Laura Hermann * @author Dario Vizzaccaro * @link https://github.com/ocean90/wpfmw-gallery * @license MIT */ // Set application paths (has trailing slash) define( 'APP_PATH', dirname( dirname( __FILE__ ) ) . '/' ); define( 'APP_INCLUDES_PATH', APP_PATH . 'includes/' ); define( 'APP_VIEWS_PATH', APP_INCLUDES_PATH . 'views/' ); // Load some files require APP_INCLUDES_PATH . 'autoloader.php'; require APP_INCLUDES_PATH . 'functions.php'; check_php_mysql_version(); // Init the application global $app; $app = new Application(); // Load config file if ( is_file( APP_PATH . 'config.php' ) ) require APP_PATH . 'config.php'; else die( 'Config Error: Please copy <code>config-sample.php</code>, change the settings and name it <code>config.php</code>!' ); // Init the database $app->init_database(); // Parse the request global $request; $request = new Request(); // Check if application is installed maybe_install();
<?php /** * Gallery - A project for 'WPF - Moderne Webanwendungen' at * Cologne University of Applied Sciences. * * @author Dominik Schilling <dominik.schilling@smail.fh-koeln.de> * @author Laura Hermann * @author Dario Vizzaccaro * @link https://github.com/ocean90/wpfmw-gallery * @license MIT */ // Set application paths (has trailing slash) define( 'APP_PATH', dirname( dirname( __FILE__ ) ) . '/' ); define( 'APP_INCLUDES_PATH', APP_PATH . 'includes/' ); define( 'APP_VIEWS_PATH', APP_INCLUDES_PATH . 'views/' ); // Load some files require APP_INCLUDES_PATH . 'autoloader.php'; require APP_INCLUDES_PATH . 'functions.php'; check_php_mysql_version(); // Init the application global $app; $app = new Application(); // Load config file require APP_PATH . 'config.php'; // Init the database $app->init_database(); // Parse the request global $request; $request = new Request(); // Check if application is installed maybe_install();
Add method to check whether Vault is running.
'use strict'; const AWS = require('aws-sdk'); const Err = require('./error'); const upload = require('multer')(); const rp = require('request-promise'); // Hit the Vault health check endpoint to see if we're actually working with a Vault server /** * Checks whether there is an actual Vault server running at the Vault endpoint * * @returns {Promise} */ const checkVault = function() { const VAULT_ENDPOINT = Config.get('vault:endpoint'); return rp({uri: `${VAULT_ENDPOINT}/sys/health`, json: true}) .then(() => true) .catch(() => false); }; module.exports = function Index(app) { app.get('/', function(req, res, next) { const KMS = new AWS.KMS({region: Config.get('aws:region')}); if (Config.get('aws:key')) { return res.render('index', {title: 'ACS'}); } return new Promise((resolve, reject) => { KMS.listAliases({}, (err, data) => { if (err) { reject(err); } resolve(data); }); }).then((keys) => { res.render('index', {title: 'ACS', kms: keys.Aliases}); }).catch((err) => { next(err); }); }); app.post('/v1/vault', upload.none(), require('./vault')()); app.post('/v1/kms', upload.none(), require('./kms')()); app.use(Err); };
'use strict'; const AWS = require('aws-sdk'); const Err = require('./error'); const upload = require('multer')(); module.exports = function Index(app) { app.get('/', function(req, res, next) { const KMS = new AWS.KMS({region: Config.get('aws:region')}); if (Config.get('aws:key')) { return res.render('index', {title: 'ACS'}); } return new Promise((resolve, reject) => { KMS.listAliases({}, (err, data) => { if (err) { reject(err); } resolve(data); }); }).then((keys) => { res.render('index', {title: 'ACS', kms: keys.Aliases}); }).catch((err) => { next(err); }); }); app.post('/v1/vault', upload.none(), require('./vault')()); app.post('/v1/kms', upload.none(), require('./kms')()); app.use(Err); };
Enable development mode and source maps for webpack
module.exports = { entry: './src/app.js', devtool: 'inline-source-map', mode: 'development', output: { path: __dirname + '/dist', filename: 'bundle.js' }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] } };
module.exports = { entry: './src/app.js', output: { path: __dirname + '/dist', filename: 'bundle.js' }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] } };
Add an extension parameter to the save function.
#!/usr/bin/env python2 '''Read and write image files as NumPy arrays''' from numpy import asarray, float32 from PIL import Image from . import np from . import utils _DEFAULT_DTYPE = float32 _PIL_RGB = { 'R': 0, 'G': 1, 'B': 2, } def get_channels(img): '''Return a list of channels of an image array.''' if utils.depth(img) == 1: yield img else: for i in xrange(utils.depth(img)): yield img[:, :, i] def read(filename, dtype=_DEFAULT_DTYPE): '''Read an image file as an array.''' img = Image.open(filename) arr = asarray(img, dtype=dtype) arr = utils.swap_rgb(arr, _PIL_RGB) return arr def _pil_save(img, filename): pil_img = Image.fromarray(img) pil_img.save(filename) return def save(img, filename, random=False, ext=None): '''Save an image array and return its path.''' if random: newfile = utils.rand_filename(filename, ext=ext) else: newfile = filename np.normalize(img) uint8img = np.to_uint8(img) _pil_save(uint8img, newfile) return newfile if __name__ == '__main__': pass
#!/usr/bin/env python2 '''Read and write image files as NumPy arrays''' from numpy import asarray, float32 from PIL import Image from . import np from . import utils _DEFAULT_DTYPE = float32 _PIL_RGB = { 'R': 0, 'G': 1, 'B': 2, } def get_channels(img): '''Return a list of channels of an image array.''' if utils.depth(img) == 1: yield img else: for i in xrange(utils.depth(img)): yield img[:, :, i] def read(filename, dtype=_DEFAULT_DTYPE): '''Read an image file as an array.''' img = Image.open(filename) arr = asarray(img, dtype=dtype) arr = utils.swap_rgb(arr, _PIL_RGB) return arr def _pil_save(img, filename): pil_img = Image.fromarray(img) pil_img.save(filename) return def save(img, filename, random=False): '''Save an image array and return its path.''' if random: newfile = utils.rand_filename(filename) else: newfile = filename np.normalize(img) uint8img = np.to_uint8(img) _pil_save(uint8img, newfile) return newfile if __name__ == '__main__': pass
Drop TODO for getVmVersion method Review URL: https://codereview.chromium.org/12324002 git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@1139 fc8a088e-31da-11de-8fef-1f5ae417a2df
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk; import java.io.IOException; import org.chromium.sdk.util.MethodIsBlockingException; /** * Abstraction of a remote JavaScript virtual machine which is embedded into * some application and accessed via TCP/IP connection to a port opened by * DebuggerAgent. Clients can use it to conduct debugging process. */ public interface StandaloneVm extends JavascriptVm { /** * Connects to the target VM. * * @param listener to report the debug events to * @throws IOException if there was a transport layer error * @throws UnsupportedVersionException if the SDK protocol version is not * compatible with that supported by the browser * @throws MethodIsBlockingException because initialization implies couple of remote calls * (to request version etc) */ void attach(DebugEventListener listener) throws IOException, UnsupportedVersionException, MethodIsBlockingException; /** * @return name of embedding application as it wished to name itself; might be null */ String getEmbedderName(); /** * This version should correspond to {@link JavascriptVm#getVersion()}. However it gets available * earlier, at the transport handshake stage. * @return version of V8 implementation, format is unspecified; must not be null if * {@link StandaloneVm} has been attached */ String getVmVersion(); /** * @return message explaining why VM is detached; may be null */ String getDisconnectReason(); }
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.sdk; import java.io.IOException; import org.chromium.sdk.util.MethodIsBlockingException; /** * Abstraction of a remote JavaScript virtual machine which is embedded into * some application and accessed via TCP/IP connection to a port opened by * DebuggerAgent. Clients can use it to conduct debugging process. */ public interface StandaloneVm extends JavascriptVm { /** * Connects to the target VM. * * @param listener to report the debug events to * @throws IOException if there was a transport layer error * @throws UnsupportedVersionException if the SDK protocol version is not * compatible with that supported by the browser * @throws MethodIsBlockingException because initialization implies couple of remote calls * (to request version etc) */ void attach(DebugEventListener listener) throws IOException, UnsupportedVersionException, MethodIsBlockingException; /** * @return name of embedding application as it wished to name itself; might be null */ String getEmbedderName(); /** * @return version of V8 implementation, format is unspecified; must not be null if * {@link StandaloneVm} has been attached */ // TODO: align this with {@link JavascriptVm#getVersion()} method. String getVmVersion(); /** * @return message explaining why VM is detached; may be null */ String getDisconnectReason(); }
Add authentication for terminal websockets
"""Tornado handlers for the terminal emulator.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from tornado import web import terminado from ..base.handlers import IPythonHandler class TerminalHandler(IPythonHandler): """Render the terminal interface.""" @web.authenticated def get(self, term_name): self.write(self.render_template('terminal.html', ws_path="terminals/websocket/%s" % term_name)) class NewTerminalHandler(IPythonHandler): """Redirect to a new terminal.""" @web.authenticated def get(self): name, _ = self.application.terminal_manager.new_named_terminal() self.redirect("/terminals/%s" % name, permanent=False) class TermSocket(terminado.TermSocket, IPythonHandler): def get(self, *args, **kwargs): if not self.get_current_user(): raise web.HTTPError(403) return super(TermSocket, self).get(*args, **kwargs)
"""Tornado handlers for the terminal emulator.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from tornado import web import terminado from ..base.handlers import IPythonHandler class TerminalHandler(IPythonHandler): """Render the terminal interface.""" @web.authenticated def get(self, term_name): self.write(self.render_template('terminal.html', ws_path="terminals/websocket/%s" % term_name)) class NewTerminalHandler(IPythonHandler): """Redirect to a new terminal.""" @web.authenticated def get(self): name, _ = self.application.terminal_manager.new_named_terminal() self.redirect("/terminals/%s" % name, permanent=False) TermSocket = terminado.TermSocket
Add validation display_name and theme
from . import database def getAllSettings(): databaseConnection = database.ConnectionManager.getConnection("main") query = databaseConnection.session.query(database.tables.Setting) settings = query.all() return {setting.name: setting.value for setting in settings} def getSettingValue(name): databaseConnection = database.ConnectionManager.getConnection("main") query = (databaseConnection.session .query(database.tables.Setting) .filter(database.tables.Setting.name == name)) if query.count() > 0: return query.first().value return None def setSettingValue(name, value): valid = validateSetting(name, value) if valid: databaseConnection = database.ConnectionManager.getConnection("main") settingObj = database.tables.Setting(name = name, value = value) databaseConnection.session.merge(settingObj) databaseConnection.session.commit() return True return False def validateSetting(name, value): if name == "title": return len(value) > 0 elif name == "display_name": return value == "full_name" or value == "username" elif name == "theme": return value in getAvailableThemes()
from . import database def getAllSettings(): databaseConnection = database.ConnectionManager.getConnection("main") query = databaseConnection.session.query(database.tables.Setting) settings = query.all() return {setting.name: setting.value for setting in settings} def getSettingValue(name): databaseConnection = database.ConnectionManager.getConnection("main") query = (databaseConnection.session .query(database.tables.Setting) .filter(database.tables.Setting.name == name)) if query.count() > 0: return query.first().value return None def setSettingValue(name, value): valid = validateSetting(name, value) if valid: databaseConnection = database.ConnectionManager.getConnection("main") settingObj = database.tables.Setting(name = name, value = value) databaseConnection.session.merge(settingObj) databaseConnection.session.commit() return True return False def validateSetting(name, value): if name == "title": return len(value) > 0
Add combo editor tests Add tests for adding and deleting a task from the combo task.
import { mount } from 'enzyme'; import React from 'react'; import assert from 'assert'; import ComboEditor from './editor'; import { workflow } from '../../../pages/dev-classifier/mock-data'; const task = { type: 'combo', loosen_requirements: true, tasks: ['write', 'ask', 'features', 'draw', 'survey', 'slider'] }; describe('ComboEditor', () => { const wrapper = mount(<ComboEditor workflow={workflow} task={task} />); it('should render for a workflow and task', () => { assert.equal(wrapper.instance() instanceof ComboEditor, true); }); it('should add new tasks to the combo when selected', () => { wrapper.find('select[value="stuck"]').simulate('change', { target: { value: 'dropdown' }}); const { props } = wrapper.instance(); assert.notEqual(props.task.tasks.indexOf('dropdown'), -1); }); it('should allow tasks to be deleted from the combo', () => { wrapper.find('ul.drag-reorderable button').first().simulate('click'); const { props } = wrapper.instance(); assert.equal(props.task.tasks.indexOf('write'), -1); }); }); describe('deleting a workflow task', () => { const workflowCopy = Object.assign({}, workflow); const tasks = Object.assign({}, workflow.tasks); delete tasks.ask; workflowCopy.tasks = tasks; it('should render and update the combo task', () => { const wrapper = mount(<ComboEditor workflow={workflowCopy} task={task} />); const { props } = wrapper.instance(); assert.equal(props.task.tasks.indexOf('ask'), -1); }); });
import { shallow, mount } from 'enzyme'; import React from 'react'; import assert from 'assert'; import ComboEditor from './editor'; import { workflow } from '../../../pages/dev-classifier/mock-data'; const task = { type: 'combo', loosen_requirements: true, tasks: ['write', 'ask', 'features', 'draw', 'survey', 'slider'] }; describe('ComboEditor', function () { it('should render for a workflow and task', () => { const wrapper = shallow(<ComboEditor workflow={workflow} task={task} />); assert.equal(wrapper.instance() instanceof ComboEditor, true); }); }); describe('deleting a workflow task', () => { const workflowCopy = Object.assign({}, workflow); const tasks = Object.assign({}, workflow.tasks); delete tasks.ask; workflowCopy.tasks = tasks; it('should render and update the combo task', () => { const wrapper = mount(<ComboEditor workflow={workflowCopy} task={task} />); const { props } = wrapper.instance(); assert.equal(props.task.tasks.indexOf('ask'), -1); }); });
Make tag map available in Indonesian defaults
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .tag_map import TAG_MAP from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP tag_map = TAG_MAP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
# coding: utf8 from __future__ import unicode_literals from .stop_words import STOP_WORDS from .punctuation import TOKENIZER_SUFFIXES, TOKENIZER_PREFIXES, TOKENIZER_INFIXES from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .norm_exceptions import NORM_EXCEPTIONS from .lemmatizer import LOOKUP from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from ..tokenizer_exceptions import BASE_EXCEPTIONS from ..norm_exceptions import BASE_NORMS from ...language import Language from ...attrs import LANG, NORM from ...util import update_exc, add_lookups class IndonesianDefaults(Language.Defaults): lex_attr_getters = dict(Language.Defaults.lex_attr_getters) lex_attr_getters[LANG] = lambda text: "id" lex_attr_getters.update(LEX_ATTRS) lex_attr_getters[NORM] = add_lookups( Language.Defaults.lex_attr_getters[NORM], BASE_NORMS, NORM_EXCEPTIONS ) tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS) stop_words = STOP_WORDS prefixes = TOKENIZER_PREFIXES suffixes = TOKENIZER_SUFFIXES infixes = TOKENIZER_INFIXES syntax_iterators = SYNTAX_ITERATORS lemma_lookup = LOOKUP class Indonesian(Language): lang = "id" Defaults = IndonesianDefaults __all__ = ["Indonesian"]
Use the 'with' statement to create the PR2 object
#! /usr/bin/env python import logging logger = logging.getLogger("robots") logger.setLevel(logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)-15s %(name)s: %(levelname)s - %(message)s') console.setFormatter(formatter) logger.addHandler(console) import time import Queue as queue import pyoro import robots from robots import desires human = "HERAKLES_HUMAN1" incoming_desires = queue.Queue() def ondesires(e): logger.info("Incomig desires:" + str(e)) for d in e: incoming_desires.put(d) with robots.PR2(knowledge = pyoro.Oro()) as pr2: pr2.knowledge.subscribe([human + " desires ?d"], ondesires) try: logger.info("Waiting for desires...") while True: sit = incoming_desires.get() if sit: desire = desires.desire_factory(sit, pr2) desire.perform() time.sleep(0.1) except KeyboardInterrupt: pass
#! /usr/bin/env python import logging logger = logging.getLogger("robots") logger.setLevel(logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)-15s %(name)s: %(levelname)s - %(message)s') console.setFormatter(formatter) logger.addHandler(console) import time import Queue as queue import pyoro import robots from robots import desires human = "HERAKLES_HUMAN1" pr2 = robots.PR2() oro = pyoro.Oro() incoming_desires = queue.Queue() def ondesires(e): logger.info("Incomig desires:" + str(e)) for d in e: incoming_desires.put(d) oro.subscribe([human + " desires ?d"], ondesires) try: logger.info("Waiting for desires...") while True: sit = incoming_desires.get(False) if sit: desire = desires.desire_factory(sit, oro, pr2) desire.perform() time.sleep(0.1) except KeyboardInterrupt: pass oro.close() pr2.close()
Resolve directories in the app folder
var webpack = require('webpack'); var path = require('path'); module.exports = { context: __dirname + '/app', entry: './index.js', output: { path: __dirname + '/bin', publicPath: '/', filename: 'bundle.js', }, stats: { colors: true, progress: true, }, resolve: { extensions: ['', '.webpack.js', '.js'], modulesDirectories: [ 'app', 'node_modules', ], }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, query: { presets: ['es2015'], }, loader: 'babel', }, ], }, };
var webpack = require('webpack'); var path = require('path'); module.exports = { context: __dirname + '/app', entry: './index.js', output: { path: __dirname + '/bin', publicPath: '/', filename: 'bundle.js', }, stats: { colors: true, progress: true, }, resolve: { extensions: ['', '.webpack.js', '.js'], }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, query: { presets: ['es2015'], }, loader: 'babel', }, ], }, };
Use err variable of getCpuInfo()
package cpu import ( "io/ioutil" "strings" "regexp" ) type Cpu struct{} func (self *Cpu) Collect() (result map[string]map[string]string, err error) { cpuinfo, err := getCpuInfo() return map[string]map[string]string{ "cpu": cpuinfo, }, err } func getCpuInfo() (cpuinfo map[string]string, err error) { contents, err := ioutil.ReadFile("/proc/cpuinfo") if err != nil { return } lines := strings.Split(string(contents), "\n") cpuinfo = make(map[string]string) for _, line := range(lines) { fields := regSplit(line, "\t+: ") switch fields[0] { case "model name": cpuinfo["model_name"] = fields[1] } } return } func regSplit(text string, delimeter string) []string { reg := regexp.MustCompile(delimeter) indexes := reg.FindAllStringIndex(text, -1) laststart := 0 result := make([]string, len(indexes) + 1) for i, element := range indexes { result[i] = text[laststart:element[0]] laststart = element[1] } result[len(indexes)] = text[laststart:len(text)] return result }
package cpu import ( "io/ioutil" "strings" "regexp" ) type Cpu struct{} func (self *Cpu) Collect() (result map[string]map[string]string, err error) { return map[string]map[string]string{ "cpu": getCpuInfo(), }, err } func getCpuInfo() (cpuinfo map[string]string) { contents, err := ioutil.ReadFile("/proc/cpuinfo") if err != nil { return } lines := strings.Split(string(contents), "\n") cpuinfo = make(map[string]string) for _, line := range(lines) { fields := regSplit(line, "\t+: ") switch fields[0] { case "model name": cpuinfo["model_name"] = fields[1] } } return } func regSplit(text string, delimeter string) []string { reg := regexp.MustCompile(delimeter) indexes := reg.FindAllStringIndex(text, -1) laststart := 0 result := make([]string, len(indexes) + 1) for i, element := range indexes { result[i] = text[laststart:element[0]] laststart = element[1] } result[len(indexes)] = text[laststart:len(text)] return result }
Add way to unset static logger
<?php namespace Kronos\Log; use Kronos\Log\Writer\TriggerError; class LogLocator { /** * @var \Psr\Log\LoggerInterface */ private static $logger; /** * @param \Psr\Log\LoggerInterface $logger * @param bool $force */ public static function setLogger(\Psr\Log\LoggerInterface $logger, $force = false) { if (!self::isLoggerSet() || $force) { self::$logger = $logger; } } /** * @return bool */ public static function isLoggerSet() { return isset(self::$logger); } /** * @return \Psr\Log\LoggerInterface */ public static function getLogger() { if (!self::isLoggerSet()) { self::setLogger(self::createDefaultLogger()); } return self::$logger; } public static function unsetLogger() { self::$logger = null; } /** * @return Logger */ public static function createDefaultLogger() { $logger = new Logger(); $logger->addWriter(new TriggerError()); return $logger; } }
<?php namespace Kronos\Log; use Kronos\Log\Writer\TriggerError; class LogLocator { /** * @var \Psr\Log\LoggerInterface */ private static $logger; /** * @param \Psr\Log\LoggerInterface $logger * @param bool $force */ public static function setLogger(\Psr\Log\LoggerInterface $logger, $force = false) { if (!self::isLoggerSet() || $force) { self::$logger = $logger; } } /** * @return bool */ public static function isLoggerSet() { return isset(self::$logger); } /** * @return \Psr\Log\LoggerInterface */ public static function getLogger() { if (!self::isLoggerSet()) { self::setLogger(self::createDefaultLogger()); } return self::$logger; } /** * @return Logger */ public static function createDefaultLogger() { $logger = new Logger(); $logger->addWriter(new TriggerError()); return $logger; } }
[api] Make API look like `net.Server`
var util = require('util'), ws = require('ws'), WebSocketServer = ws.Server, EventEmitter2 = require('eventemitter2').EventEmitter2; exports.createServer = function createServer(target) { }; var WSProxy = exports.WSProxy = function (target) { if (!target) { throw new TypeError("No target given"); } this.target = target; this.server = null; EventEmitter2.call(this, { delimeter: '::', wildcard: true }); }; util.inherits(WSProxy, EventEmitter2); WSProxy.prototype.listen = function (port, host) { var self = this; function listening() { self.emit('listening'); } if (typeof arguments[arguments.length - 1] == 'function') { this.on('listening', arguments[arguments.length - 1]); } if (this.server) { throw new Error("Already running"); } if (typeof port == 'object') { this.server = new WebSocketServer({ server: port }, listening); } else { this.server = new WebSocketServer({ port: port, host: host }, listening); } this.server.on('connection', function (incoming) { var outgoing = new ws(self.target); incoming.on('message', function (msg) { outgoing.send(msg); }); outgoing.on('message', function (msg) { incoming.send(msg); }); }); }; WSProxy.prototype.close = function () { if (!this.server) { throw new Error("Not running"); } this.server.close(); this.server = null; };
var ws = require('ws'), WebSocketServer = ws.Server; var WSProxy = exports.WSProxy = function (options) { options || (options = {}); if (!options.target) { throw new TypeError("No target given"); } this.target = options.target; if (!options.proxy || !options.proxy.port) { throw new TypeError("No port to listen on given"); } this.proxy = options.proxy; this.proxy.host || (this.proxy.host = "127.0.0.1"); this.server = null; }; WSProxy.prototype.start = function () { var self = this; if (this.server) { throw new Error("Already running"); } this.server = new WebSocketServer(this.proxy); this.server.on('connection', function (incoming) { var outgoing = new ws(self.target); incoming.on('message', function (msg) { outgoing.send(msg); }); outgoing.on('message', function (msg) { incoming.send(msg); }); }); }; WSProxy.prototype.stop = function () { if (!this.server) { throw new Error("Not running"); } this.server.close(); this.server = null; };
Fix query for oldest (un-swapped) project
package uk.ac.ic.wlgitbridge.bridge.db.sqlite.query; import uk.ac.ic.wlgitbridge.bridge.db.sqlite.SQLQuery; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by winston on 23/08/2016. */ public class GetOldestProjectName implements SQLQuery<String> { private static final String GET_OLDEST_PROJECT_NAME = "SELECT `name`, MIN(`last_accessed`)\n" + " FROM `projects` \n" + " WHERE `last_accessed` IS NOT NULL;"; @Override public String getSQL() { return GET_OLDEST_PROJECT_NAME; } @Override public String processResultSet(ResultSet resultSet) throws SQLException { while (resultSet.next()) { return resultSet.getString("name"); } return null; } }
package uk.ac.ic.wlgitbridge.bridge.db.sqlite.query; import uk.ac.ic.wlgitbridge.bridge.db.sqlite.SQLQuery; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by winston on 23/08/2016. */ public class GetOldestProjectName implements SQLQuery<String> { private static final String GET_OLDEST_PROJECT_NAME = "SELECT `name`, MIN(`last_accessed`)\n" + " FROM `projects`"; @Override public String getSQL() { return GET_OLDEST_PROJECT_NAME; } @Override public String processResultSet(ResultSet resultSet) throws SQLException { while (resultSet.next()) { return resultSet.getString("name"); } return null; } }
Simplify the use of `phutil_get_library_root` Summary: Currently, in order to retrieve the library root of the current phutil module, the following code is required: ```lang=php $library = phutil_get_current_library_name(); $root = phutil_get_library_root($library); ``` This can be simplified by allowing the use of `phutil_get_library_root()` (without any arguments) to mean "get the library root for the current module". Test Plan: N/A Reviewers: #blessed_reviewers, epriestley Reviewed By: #blessed_reviewers, epriestley Subscribers: Korvin, epriestley Differential Revision: https://secure.phabricator.com/D11326
<?php function phutil_get_library_root($library = null) { if (!$library) { $library = phutil_get_current_library_name(); } $bootloader = PhutilBootloader::getInstance(); return $bootloader->getLibraryRoot($library); } function phutil_get_library_root_for_path($path) { foreach (Filesystem::walkToRoot($path) as $dir) { if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) { return $dir; } } return null; } function phutil_get_library_name_for_root($path) { $path = rtrim(Filesystem::resolvePath($path), '/'); $bootloader = PhutilBootloader::getInstance(); $libraries = $bootloader->getAllLibraries(); foreach ($libraries as $library) { $root = $bootloader->getLibraryRoot($library); if (rtrim(Filesystem::resolvePath($root), '/') == $path) { return $library; } } return null; } function phutil_get_current_library_name() { $caller = head(debug_backtrace(false)); $root = phutil_get_library_root_for_path($caller['file']); return phutil_get_library_name_for_root($root); } /** * Warns about use of deprecated behavior. */ function phutil_deprecated($what, $why) { PhutilErrorHandler::dispatchErrorMessage( PhutilErrorHandler::DEPRECATED, $what, array( 'why' => $why, )); }
<?php function phutil_get_library_root($library) { $bootloader = PhutilBootloader::getInstance(); return $bootloader->getLibraryRoot($library); } function phutil_get_library_root_for_path($path) { foreach (Filesystem::walkToRoot($path) as $dir) { if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) { return $dir; } } return null; } function phutil_get_library_name_for_root($path) { $path = rtrim(Filesystem::resolvePath($path), '/'); $bootloader = PhutilBootloader::getInstance(); $libraries = $bootloader->getAllLibraries(); foreach ($libraries as $library) { $root = $bootloader->getLibraryRoot($library); if (rtrim(Filesystem::resolvePath($root), '/') == $path) { return $library; } } return null; } function phutil_get_current_library_name() { $caller = head(debug_backtrace(false)); $root = phutil_get_library_root_for_path($caller['file']); return phutil_get_library_name_for_root($root); } /** * Warns about use of deprecated behavior. */ function phutil_deprecated($what, $why) { PhutilErrorHandler::dispatchErrorMessage( PhutilErrorHandler::DEPRECATED, $what, array( 'why' => $why, )); }
Add basic element pickle cycle test
import mdtraj as md import pytest import pickle from mdtraj import element from mdtraj.testing import eq def test_immutable(): def f(): element.hydrogen.mass = 1 def g(): element.radium.symbol = 'sdfsdfsdf' def h(): element.iron.name = 'sdfsdf' pytest.raises(AttributeError, f) pytest.raises(AttributeError, g) pytest.raises(AttributeError, h) assert element.hydrogen.mass == 1.007947 assert element.radium.symbol == 'Ra' assert element.iron.name == 'iron' def test_element_0(get_fn): t = md.load(get_fn('bpti.pdb')) a = t.top.atom(15) H = element.Element.getBySymbol('H') eq(a.element, element.hydrogen) def test_element_pickle(): """Test that every Element object can pickle and de-pickle""" for el in dir(element): if isinstance(el, element.Element): assert el == pickle.loads(pickle.dumps(el))
import mdtraj as md import pytest from mdtraj import element from mdtraj.testing import eq def test_immutable(): def f(): element.hydrogen.mass = 1 def g(): element.radium.symbol = 'sdfsdfsdf' def h(): element.iron.name = 'sdfsdf' pytest.raises(AttributeError, f) pytest.raises(AttributeError, g) pytest.raises(AttributeError, h) assert element.hydrogen.mass == 1.007947 assert element.radium.symbol == 'Ra' assert element.iron.name == 'iron' def test_element_0(get_fn): t = md.load(get_fn('bpti.pdb')) a = t.top.atom(15) H = element.Element.getBySymbol('H') eq(a.element, element.hydrogen)
Create variables and initial loop
// Harmless Ransom Note /* Rules: Takes two parameters First will be the note we want to write as a string. The second will be the magazine text we have available to make the note out of as a string The purpose of the algorithm is to see if we have enough words in the magazine text to write our note If yes, return true If no, return false NOTE: If one word is used 2 (or more) times in the note, but only seen once (or less) in magazine text then it fails. */ /* PSEUDOCODE 1) Turn the note into an array of words 2) Turn the mag into an array of words 3) Organize each new array alphabetically 4) Look at the first letter of each word in note array, and insert that letter into a reference array 5) compare the reference array with each first letter of each word in mag array. IF word starts with any letter inside note array, keep the word ELSE remove the word 6) Compare the actual words! IF there is a match, cool. Make note of that and move on to the next word ELSE IF there isn't a match, then that's enough already for you to return FALSE */ function harmlessNote(note, mag){ var noteArr = note.split(""); var magArr = mag.split(""); var noteMagArr = []; for (var i=0; i < note.length; i++){ if !(magArray.includes?(noteArray[i])) { return false; } else if (magArray.includes?(noteArray[i])) { noteMagArr.push(noteArray[i]); magArr.pop(WORD) } return true; } }
// Harmless Ransom Note /* Rules: Takes two parameters First will be the note we want to write as a string. The second will be the magazine text we have available to make the note out of as a string The purpose of the algorithm is to see if we have enough words in the magazine text to write our note If yes, return true If no, return false NOTE: If one word is used 2 (or more) times in the note, but only seen once (or less) in magazine text then it fails. */ /* PSEUDOCODE 1) Turn the note into an array of words 2) Turn the mag into an array of words 3) Organize each new array alphabetically 4) Look at the first letter of each word in note array, and insert that letter into a reference array 5) compare the reference array with each first letter of each word in mag array. IF word starts with any letter inside note array, keep the word ELSE remove the word 6) Compare the actual words! IF there is a match, cool. Make note of that and move on to the next word ELSE IF there isn't a match, then that's enough already for you to return FALSE */ function harmlessNote(note, mag){ }
Fix to use setOptions() syntax
<?php /* * This file is part of StashServiceProvider * * (c) Ben Tollakson <btollakson.os@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Bt51\Silex\Provider\StashServiceProvider; use Silex\Application; use Silex\ServiceProviderInterface; use Stash\Pool; class StashServiceProvider implements ServiceProviderInterface { public function register(Application $app) { if (! isset($app['stash.driver.class'])) { $app['stash.driver.class'] = 'Ephemeral'; } $app['stash.driver'] = $app->share(function ($app) { $options = (isset($app['stash.driver.options']) ? $app['stash.driver.options'] : array()); $class = sprintf('\\Stash\\Driver\\%s', $app['stash.driver.class']); $driver = new $class; $driver->setOptions($options); return $driver; }); $app['stash'] = $app->share(function ($app) { return new Pool($app['stash.driver']); }); } public function boot(Application $app) { } }
<?php /* * This file is part of StashServiceProvider * * (c) Ben Tollakson <btollakson.os@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Bt51\Silex\Provider\StashServiceProvider; use Silex\Application; use Silex\ServiceProviderInterface; use Stash\Pool; class StashServiceProvider implements ServiceProviderInterface { public function register(Application $app) { if (! isset($app['stash.driver.class'])) { $app['stash.driver.class'] = 'Ephemeral'; } $app['stash.driver'] = $app->share(function ($app) { $options = (isset($app['stash.driver.options']) ? $app['stash.driver.options'] : array()); $class = sprintf('\\Stash\\Driver\\%s', $app['stash.driver.class']); $driver = new \ReflectionClass($class); return $driver->newInstanceArgs(array($options)); }); $app['stash'] = $app->share(function ($app) { return new Pool($app['stash.driver']); }); } public function boot(Application $app) { } }
Add first name and last name to Admin employee list
from django.contrib import admin from .models import Employee, Role class RoleAdmin(admin.ModelAdmin): list_display = ("name",) class EmployeeAdmin(admin.ModelAdmin): list_display = ("username", "first_name", "last_name", "email",) fieldsets = ( (None, {'fields': ('username', 'email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name', 'role', 'skype_id', 'avatar')}), ('Personal score', {'fields': ('last_month_score', 'current_month_score', 'level', 'total_score')}), ('Permissions', {'fields': ('groups', 'user_permissions', 'is_superuser', 'is_staff', 'is_active',)}), ('History', {'fields': ('date_joined', 'last_login')}) ) admin.site.register(Employee, EmployeeAdmin) admin.site.register(Role, RoleAdmin)
from django.contrib import admin from .models import Employee, Role class RoleAdmin(admin.ModelAdmin): list_display = ("name",) class EmployeeAdmin(admin.ModelAdmin): list_display = ("username", "email",) fieldsets = ( (None, {'fields': ('username', 'email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name', 'role', 'skype_id', 'avatar')}), ('Personal score', {'fields': ('last_month_score', 'current_month_score', 'level', 'total_score')}), ('Permissions', {'fields': ('groups', 'user_permissions', 'is_superuser', 'is_staff', 'is_active',)}), ('History', {'fields': ('date_joined', 'last_login')}) ) admin.site.register(Employee, EmployeeAdmin) admin.site.register(Role, RoleAdmin)
Remove is_upcoming field from Event response and Add explicit fields to EventActivity serializer
from .models import Event, EventActivity from employees.serializers import LocationSerializer from rest_framework import serializers class EventSerializer(serializers.ModelSerializer): location = LocationSerializer() class Meta(object): model = Event depth = 1 fields = ("pk", "name", "image", "datetime", "address", "description", "is_active", "location") class EventSimpleSerializer(serializers.Serializer): pk = serializers.IntegerField() name = serializers.CharField(max_length=100) image = serializers.CharField(allow_blank=True, required=False) datetime = serializers.DateTimeField(required=False) address = serializers.CharField(allow_blank=True, required=False) description = serializers.CharField(allow_blank=True, required=False) is_registered = serializers.BooleanField() class EventActivitySerializer(serializers.ModelSerializer): class Meta(object): model = EventActivity fields = ("pk", "datetime", "text", "event")
from .models import Event, EventActivity from employees.serializers import LocationSerializer from rest_framework import serializers class EventSerializer(serializers.ModelSerializer): location = LocationSerializer() class Meta(object): model = Event depth = 1 fields = ("pk", "name", "image", "datetime", "address", "description", "is_active", "is_upcoming", "location") class EventSimpleSerializer(serializers.Serializer): pk = serializers.IntegerField() name = serializers.CharField(max_length=100) image = serializers.CharField(allow_blank=True, required=False) datetime = serializers.DateTimeField(required=False) address = serializers.CharField(allow_blank=True, required=False) description = serializers.CharField(allow_blank=True, required=False) is_registered = serializers.BooleanField() class EventActivitySerializer(serializers.ModelSerializer): class Meta(object): model = EventActivity
Fix getting wireframe property of instance instead of the material
/** * CG Space Invaders * CG45179 16'17 * * @author: Rui Ventura ( ist181045 ) * @author: Diogo Freitas ( ist181586 ) * @author: Sara Azinhal ( ist181700 ) */ import { Object3D } from '../lib/threejs/core/Object3D'; import { MeshNormalMaterial } from '../lib/threejs/materials/MeshNormalMaterial'; class GameObject extends Object3D { constructor ( x, y, z ) { super(); this.type = 'GameObject'; this.isGameObject = true; this.materials = [ new MeshNormalMaterial() ]; this.material = this.materials[0]; this.materialIndex = 0; this.phong = false; this.position.set( x || 0, y || 0, z || 0 ); } changeMaterial ( index ) { let newMaterial = this.materials[ index ]; newMaterial.wireframe = this.material.wireframe; this.materialIndex = index; this.children.forEach( function ( child ) { if ( child.isGameObject ) child.changeMaterial( index ); else if ( child.isMesh ) child.material = newMaterial; }); this.material = newMaterial; } } export default GameObject;
/** * CG Space Invaders * CG45179 16'17 * * @author: Rui Ventura ( ist181045 ) * @author: Diogo Freitas ( ist181586 ) * @author: Sara Azinhal ( ist181700 ) */ import { Object3D } from '../lib/threejs/core/Object3D'; import { MeshNormalMaterial } from '../lib/threejs/materials/MeshNormalMaterial'; class GameObject extends Object3D { constructor ( x, y, z ) { super(); this.type = 'GameObject'; this.isGameObject = true; this.materials = [ new MeshNormalMaterial() ]; this.material = this.materials[0]; this.materialIndex = 0; this.phong = false; this.position.set( x || 0, y || 0, z || 0 ); } changeMaterial ( index ) { let newMaterial = this.materials[ index ]; newMaterial.wireframe = this.wireframe; this.materialIndex = index; this.children.forEach( function ( child ) { if ( child.isGameObject ) child.changeMaterial( index ); else if ( child.isMesh ) child.material = newMaterial; }); this.material = newMaterial; } } export default GameObject;
Fix uptime and minor re-factoring
<?php function collect_kernel($debug) { $kernel = exec('uname -r') . " " . exec('uname -v'); if ($debug == TRUE) { echo "[DEBUG_COLLECT] Kernel: " . $kernel . "\n"; } return $kernel; } function collect_hostname($debug) { $hostname = exec('uname -n'); if ($debug == TRUE) { echo "[DEBUG_COLLECT] Hostname: " . $hostname . "\n"; } return $hostname; } function collect_uptime($debug) { $uptime = shell_exec('uptime'); $uptime = explode(' up ', $uptime); $uptime = explode(',', $uptime[1]); $uptimehourmin = explode(":", $uptime[1]); $uptime = str_replace("days", "", $uptime[0]); $uptime = $uptime[0].','.$uptimehourmin[0].','.$uptimehourmin[1]; $uptimearr = explode(",", $uptime); if ($debug == TRUE) { echo "[DEBUG_COLLECT] Uptime: " . $uptimearr[0] . " days " . $uptimearr[1] . " hours ".$uptimearr[2]." minutes\n"; } return $uptime; } ?>
<?php function collect_kernel($debug) { $kernel = exec('uname -r')." ".exec('uname -v'); if ($debug == TRUE) { echo "[DEBUG_COLLECT] Kernel: ".$kernel."\n"; } return $kernel; } function collect_hostname($debug) { $hostname = exec('uname -n'); if ($debug == TRUE) { echo "[DEBUG_COLLECT] Hostname: ".$hostname."\n"; } return $hostname; } function collect_uptime($debug) { $uptime = exec('uptime'); // Replace colons with commas $uptime = str_replace(":", ",", $uptime); $uptimearr = explode(",", $uptime); if ($debug == TRUE) { echo "[DEBUG_COLLECT] Uptime: ".$uptimearr[0]." days ".$uptimearr[1]." hours\n"; } return $uptime; } ?>
Make callable statements work again for JDK 1.5 builds. Any code int the jdbc3/Jdbc3 classes also needs to get into the corresponding jdbc3g/Jdbc3g class.
/*------------------------------------------------------------------------- * * Copyright (c) 2004-2005, PostgreSQL Global Development Group * * IDENTIFICATION * $PostgreSQL: pgjdbc/org/postgresql/jdbc3g/Jdbc3gCallableStatement.java,v 1.4 2005/01/11 08:25:47 jurka Exp $ * *------------------------------------------------------------------------- */ package org.postgresql.jdbc3g; import java.sql.*; import java.util.Map; class Jdbc3gCallableStatement extends Jdbc3gPreparedStatement implements CallableStatement { Jdbc3gCallableStatement(Jdbc3gConnection connection, String sql, int rsType, int rsConcurrency, int rsHoldability) throws SQLException { super(connection, sql, true, rsType, rsConcurrency, rsHoldability); if ( !connection.haveMinimumServerVersion("8.1") || connection.getProtocolVersion() == 2) { adjustIndex = true; } } public Object getObject(int i, Map < String, Class < ? >> map) throws SQLException { return getObjectImpl(i, map); } public Object getObject(String s, Map < String, Class < ? >> map) throws SQLException { return getObjectImpl(s, map); } }
/*------------------------------------------------------------------------- * * Copyright (c) 2004-2005, PostgreSQL Global Development Group * * IDENTIFICATION * $PostgreSQL: pgjdbc/org/postgresql/jdbc3g/Jdbc3gCallableStatement.java,v 1.3 2004/11/09 08:51:22 jurka Exp $ * *------------------------------------------------------------------------- */ package org.postgresql.jdbc3g; import java.sql.*; import java.util.Map; class Jdbc3gCallableStatement extends Jdbc3gPreparedStatement implements CallableStatement { Jdbc3gCallableStatement(Jdbc3gConnection connection, String sql, int rsType, int rsConcurrency, int rsHoldability) throws SQLException { super(connection, sql, true, rsType, rsConcurrency, rsHoldability); } public Object getObject(int i, Map < String, Class < ? >> map) throws SQLException { return getObjectImpl(i, map); } public Object getObject(String s, Map < String, Class < ? >> map) throws SQLException { return getObjectImpl(s, map); } }
Remove duplicate implementation (already done in parent class).
<?php namespace FluxBB\Markdown\Node; class Blockquote extends Container implements NodeAcceptorInterface { public function acceptParagraph(Paragraph $paragraph) { $this->addChild($paragraph); return $paragraph; } public function acceptBlockquote(Blockquote $blockquote) { $this->merge($blockquote); return $this; } public function acceptBlankLine(BlankLine $blankLine) { return $this->parent; } public function visit(NodeVisitorInterface $visitor) { $visitor->enterBlockquote($this); parent::visit($visitor); $visitor->leaveBlockquote($this); } }
<?php namespace FluxBB\Markdown\Node; class Blockquote extends Container implements NodeAcceptorInterface { public function acceptParagraph(Paragraph $paragraph) { $this->addChild($paragraph); return $paragraph; } public function acceptHeading(Heading $heading) { $this->addChild($heading); return $this; } public function acceptBlockquote(Blockquote $blockquote) { $this->merge($blockquote); return $this; } public function acceptBlankLine(BlankLine $blankLine) { return $this->parent; } public function visit(NodeVisitorInterface $visitor) { $visitor->enterBlockquote($this); parent::visit($visitor); $visitor->leaveBlockquote($this); } }
Update name of url mapping for ProjectEntriesListAPIView
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
Add Info to Weather Check Add current weather status to weather check features.
from configparser import ConfigParser from googletrans import Translator import pyowm import logging import re logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) cfg = ConfigParser() cfg.read('config') api_key = cfg.get('auth', 'owm_api_key') def weather(bot, update): owm = pyowm.OWM(api_key, language='zh_tw') translator = Translator() location = update.message.text location = re.sub(u'天氣 ','',location) trans = translator.translate(location).text logger.info("get weather at %s" %trans) try: obs = owm.weather_at_place(trans) w = obs.get_weather() update.message.reply_text(location+'的天氣\n'+'溫度:'+str(w.get_temperature(unit='celsius')['temp'])+ ' 濕度:'+str(w.get_humidity())+' 天氣狀況:'+str(w.get_status())) except: update.message.reply_text('Location fucking not found')
from configparser import ConfigParser from googletrans import Translator import pyowm import logging import re logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) cfg = ConfigParser() cfg.read('config') api_key = cfg.get('auth', 'owm_api_key') def weather(bot, update): owm = pyowm.OWM(api_key, language='zh_tw') translator = Translator() location = update.message.text location = re.sub(u'天氣 ','',location) trans = translator.translate(location).text logger.info("get weather at %s" %trans) try: obs = owm.weather_at_place(trans) w = obs.get_weather() update.message.reply_text(location+'的天氣\n'+'溫度:'+str(w.get_temperature(unit='celsius')['temp'])+ ' 濕度:'+str(w.get_humidity())) except: update.message.reply_text('Location fucking not found')
Increment PyPi package to 1.9.16.1
#!/usr/bin/env python """Setup specs for packaging, distributing, and installing MR lib.""" import distribute_setup # User may not have setuptools installed on their machines. # This script will automatically install the right version from PyPI. distribute_setup.use_setuptools() # pylint: disable=g-import-not-at-top import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleAppEngineMapReduce", version="1.9.16.1", packages=setuptools.find_packages(), author="Google App Engine", author_email="app-engine-pipeline-api@googlegroups.com", keywords="google app engine mapreduce data processing", url="https://code.google.com/p/appengine-mapreduce/", license="Apache License 2.0", description=("Enable MapReduce style data processing on " "App Engine"), zip_safe=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "GoogleAppEngineCloudStorageClient >= 1.9.15", "GoogleAppEnginePipeline >= 1.9.15", "Graphy >= 1.0.0", "simplejson >= 3.6.5", "mock >= 1.0.1", "mox >= 0.5.3", ] )
#!/usr/bin/env python """Setup specs for packaging, distributing, and installing MR lib.""" import distribute_setup # User may not have setuptools installed on their machines. # This script will automatically install the right version from PyPI. distribute_setup.use_setuptools() # pylint: disable=g-import-not-at-top import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleAppEngineMapReduce", version="1.9.15.0", packages=setuptools.find_packages(), author="Google App Engine", author_email="app-engine-pipeline-api@googlegroups.com", keywords="google app engine mapreduce data processing", url="https://code.google.com/p/appengine-mapreduce/", license="Apache License 2.0", description=("Enable MapReduce style data processing on " "App Engine"), zip_safe=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "GoogleAppEngineCloudStorageClient >= 1.9.15", "GoogleAppEnginePipeline >= 1.9.15", "Graphy >= 1.0.0", "simplejson >= 3.6.5", "mock >= 1.0.1", "mox >= 0.5.3", ] )
Add cast from varbinary to HLL
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.type; import com.facebook.presto.operator.scalar.ScalarOperator; import com.facebook.presto.spi.type.StandardTypes; import io.airlift.slice.Slice; import static com.facebook.presto.metadata.OperatorType.CAST; public class HyperLogLogOperators { private HyperLogLogOperators() { } @ScalarOperator(CAST) @SqlType(StandardTypes.VARBINARY) public static Slice castToBinary(@SqlType(StandardTypes.HYPER_LOG_LOG) Slice slice) { return slice; } @ScalarOperator(CAST) @SqlType(StandardTypes.HYPER_LOG_LOG) public static Slice castFromVarbinary(@SqlType(StandardTypes.VARBINARY) Slice slice) { return slice; } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.type; import com.facebook.presto.operator.scalar.ScalarOperator; import com.facebook.presto.spi.type.StandardTypes; import io.airlift.slice.Slice; import static com.facebook.presto.metadata.OperatorType.CAST; public class HyperLogLogOperators { private HyperLogLogOperators() { } @ScalarOperator(CAST) @SqlType(StandardTypes.VARBINARY) public static Slice castToBinary(@SqlType(StandardTypes.HYPER_LOG_LOG) Slice slice) { return slice; } }
Add all settings to populateStorage
'use strict' // Code thanks to MDN export function storageAvailable (type) { try { let storage = window[type] let x = '__storage_test__' storage.setItem(x, x) storage.removeItem(x) return true } catch (e) { let storage = window[type] return e instanceof DOMException && ( // everything except Firefox e.code === 22 || // Firefox e.code === 1014 || // test name field too, because code might not be present // everything except Firefox e.name === 'QuotaExceededError' || // Firefox e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && // acknowledge QuotaExceededError only if there's something already stored storage.length !== 0 } } export function storagePopulated () { if (window.localStorage.length !== 0) { console.log('populated') return true } } export function populateStorage () { window.localStorage.setItem('pomodoroTime', document.getElementById('pomodoroInput').value) window.localStorage.setItem('shortBreakTime', document.getElementById('shortBreakInput').value) window.localStorage.setItem('longBreakTime', document.getElementById('longBreakInput').value) window.localStorage.setItem('alarmDropdown', document.getElementById('alarmDropdown').value) window.localStorage.setItem('ticking', document.getElementById('tickToggle').checked) window.localStorage.setItem('storageToggle', document.getElementById('storageToggle').checked) }
'use strict' // Code thanks to MDN export function storageAvailable (type) { try { let storage = window[type] let x = '__storage_test__' storage.setItem(x, x) storage.removeItem(x) return true } catch (e) { let storage = window[type] return e instanceof DOMException && ( // everything except Firefox e.code === 22 || // Firefox e.code === 1014 || // test name field too, because code might not be present // everything except Firefox e.name === 'QuotaExceededError' || // Firefox e.name === 'NS_ERROR_DOM_QUOTA_REACHED') && // acknowledge QuotaExceededError only if there's something already stored storage.length !== 0 } } export function storagePopulated () { if (window.localStorage.length !== 0) { console.log('populated') return true } } export function populateStorage () { window.localStorage.setItem('pomodoroTime', document.getElementById('pomodoroInput').value) window.localStorage.setItem('shortBreakTime', document.getElementById('shortBreakInput').value) window.localStorage.setItem('longBreakTime', document.getElementById('longBreakInput').value) }
Print packet lengths in sniff
package main import ( "log" "time" "github.com/ecc1/medtronic" "github.com/ecc1/medtronic/packet" ) const ( verbose = true ) func main() { if verbose { log.SetFlags(log.Ltime | log.Lmicroseconds | log.LUTC) } pump := medtronic.Open() defer pump.Close() for pump.Error() == nil { p, rssi := pump.Radio.Receive(time.Hour) if pump.Error() != nil { log.Print(pump.Error()) pump.SetError(nil) continue } if verbose { log.Printf("raw data: % X (%d bytes, RSSI = %d)", p, len(p), rssi) } data, err := packet.Decode(p) if err != nil { log.Print(err) continue } if verbose { log.Printf("decoded: % X", data) } else { log.Printf("% X (%d bytes, RSSI = %d)", data, len(data), rssi) } } log.Fatal(pump.Error()) }
package main import ( "log" "time" "github.com/ecc1/medtronic" "github.com/ecc1/medtronic/packet" ) const ( verbose = true ) func main() { if verbose { log.SetFlags(log.Ltime | log.Lmicroseconds | log.LUTC) } pump := medtronic.Open() defer pump.Close() for pump.Error() == nil { p, rssi := pump.Radio.Receive(time.Hour) if pump.Error() != nil { log.Print(pump.Error()) pump.SetError(nil) continue } if verbose { log.Printf("raw data: % X (RSSI = %d)", p, rssi) } data, err := packet.Decode(p) if err != nil { log.Print(err) continue } if verbose { log.Printf("decoded: % X", data) } else { log.Printf("% X (RSSI = %d)", data, rssi) } } log.Fatal(pump.Error()) }
Make sure "yaml" files are compatible too
<?php namespace Orbitale\Bundle\EasyImpressBundle\DependencyInjection\Compiler; use Orbitale\Bundle\EasyImpressBundle\Configuration\ConfigProcessor; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Finder\Finder; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class PresentationsPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { $finder = (new Finder()) ->files() ->name('*.{yaml,yml}') ->in($container->getParameter('easy_impress.presentations_dir')) ; $configProcessor = new ConfigProcessor(); $presentations = []; foreach ($finder as $file) { /** @var \SplFileInfo $file */ $container->addResource(new FileResource($file->getRealPath())); $presentations[$file->getBasename('.yml')] = $configProcessor->processConfigurationFile($file); } $container->setParameter('easy_impress.presentations', $presentations); } }
<?php namespace Orbitale\Bundle\EasyImpressBundle\DependencyInjection\Compiler; use Orbitale\Bundle\EasyImpressBundle\Configuration\ConfigProcessor; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Finder\Finder; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class PresentationsPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { $finder = (new Finder()) ->files() ->name('*.yml') ->in($container->getParameter('easy_impress.presentations_dir')) ; $configProcessor = new ConfigProcessor(); $presentations = []; foreach ($finder as $file) { /** @var \SplFileInfo $file */ $container->addResource(new FileResource($file->getRealPath())); $presentations[$file->getBasename('.yml')] = $configProcessor->processConfigurationFile($file); } $container->setParameter('easy_impress.presentations', $presentations); } }
Simplify project banner on home page
import React from 'react' import { Card, Box, Text, Icon, Container, Flex, Link } from '@hackclub/design-system' export default () => ( <Container maxWidth={24} my={-3}> <Link href="challenge"> <Card bg="blue.1" p={[2, 3]}> <Flex justify="flex-start" align="center"> <Icon name="open_in_new" size={24} mr={[2, 3]} color="blue.6" /> <Box color="blue.6"> <Text f={3} bold> Check out student-built projects </Text> </Box> </Flex> </Card> </Link> </Container> )
import React from 'react' import { Card, Box, Text, Icon, Container, Flex, Link } from '@hackclub/design-system' export default () => ( <Container maxWidth={38}> <Link href="challenge"> <Card bg="blue.1" p={[2, 3]} mt={-2} mb={4}> <Flex justify="flex-start"> <Icon name="open_in_new" size={48} mr={[2, 3]} color="blue.6" /> <Box color="blue.6"> <Text f={3} bold> Check out the winning challenge submissions </Text> <Text f={2}> Our latest challenge just wrapped up. See the winning projects. </Text> </Box> </Flex> </Card> </Link> </Container> )
Return event dictionary at the end of the task.
from celery import Celery from settings import SETTINGS import requests HOOKS = SETTINGS.get('hooks', []) CELERY_SETTINGS = SETTINGS.get('celery', {}) app = Celery() app.conf.update(**CELERY_SETTINGS) @app.task def dispatch_event(event): event_repr = '%s:%s' % (event['id'][:10], event['status']) for url in HOOKS: dispatch_tuple = (event_repr, url) print '[DISPATCH START] Dispatching event %s --> %s' % dispatch_tuple try: response = requests.post(url, data=event) response_tuple = (response.status_code, response.reason) if response.status_code >= 400: print ' [FAILURE] %s: %s' % response_tuple else: print ' [SUCCESS] %s: %s' % response_tuple except Exception as e: print ' [ERROR] Exception: %s' % e print '[DISPATCH END] %s --> %s' % dispatch_tuple return event
from celery import Celery from settings import SETTINGS import requests HOOKS = SETTINGS.get('hooks', []) CELERY_SETTINGS = SETTINGS.get('celery', {}) app = Celery() app.conf.update(**CELERY_SETTINGS) @app.task def dispatch_event(event): event_repr = '%s:%s' % (event['id'][:10], event['status']) for url in HOOKS: dispatch_tuple = (event_repr, url) print '[DISPATCH START] Dispatching event %s --> %s' % dispatch_tuple try: response = requests.post(url, data=event) response_tuple = (response.status_code, response.reason) if response.status_code >= 400: print ' [FAILURE] %s: %s' % response_tuple else: print ' [SUCCESS] %s: %s' % response_tuple except Exception as e: print ' [ERROR] Exception: %s' % e print '[DISPATCH END] %s --> %s' % dispatch_tuple
Update help message to use -model.
/* word-server creates an HTTP server which exports endpoints for querying a word2vec model. */ package main import ( "flag" "fmt" "log" "net/http" "os" "github.com/sajari/word2vec" ) var listen, modelPath string func init() { flag.StringVar(&listen, "listen", "localhost:1234", "bind `address` for HTTP server") flag.StringVar(&modelPath, "model", "", "path to binary model data") } func main() { flag.Parse() if modelPath == "" { fmt.Println("must specify -model; see -h for more details") os.Exit(1) } log.Println("Loading model...") f, err := os.Open(modelPath) if err != nil { fmt.Printf("error opening binary model data file: %v\n", err) os.Exit(1) } defer f.Close() m, err := word2vec.FromReader(f) if err != nil { fmt.Printf("error reading binary model data: %v\n", err) os.Exit(1) } ms := word2vec.NewServer(m) log.Printf("Server listening on %v", listen) log.Println("Hit Ctrl-C to quit.") log.Fatal(http.ListenAndServe(listen, ms)) }
/* word-server creates an HTTP server which exports endpoints for querying a word2vec model. */ package main import ( "flag" "fmt" "log" "net/http" "os" "github.com/sajari/word2vec" ) var listen, modelPath string func init() { flag.StringVar(&listen, "listen", "localhost:1234", "bind `address` for HTTP server") flag.StringVar(&modelPath, "model", "", "path to binary model data") } func main() { flag.Parse() if modelPath == "" { fmt.Println("must specify -p; see -h for more details") os.Exit(1) } log.Println("Loading model...") f, err := os.Open(modelPath) if err != nil { fmt.Printf("error opening binary model data file: %v\n", err) os.Exit(1) } defer f.Close() m, err := word2vec.FromReader(f) if err != nil { fmt.Printf("error reading binary model data: %v\n", err) os.Exit(1) } ms := word2vec.NewServer(m) log.Printf("Server listening on %v", listen) log.Println("Hit Ctrl-C to quit.") log.Fatal(http.ListenAndServe(listen, ms)) }
Create an address if none exists for a user
from django.db import models from bluebottle.bb_accounts.models import BlueBottleBaseUser from bluebottle.utils.models import Address from djchoices.choices import DjangoChoices, ChoiceItem from django.conf import settings from django.utils.translation import ugettext as _ class Member(BlueBottleBaseUser): # Create an address if none exists def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super(Member, self).save(force_insert=False, force_update=False, using=None, update_fields=None) try: self.address except UserAddress.DoesNotExist: self.address = UserAddress.objects.create(user=self) self.address.save() class UserAddress(Address): class AddressType(DjangoChoices): primary = ChoiceItem('primary', label=_("Primary")) secondary = ChoiceItem('secondary', label=_("Secondary")) address_type = models.CharField(_("address type"),max_length=10, blank=True, choices=AddressType.choices, default=AddressType.primary) user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_("user"), related_name="address") class Meta: verbose_name = _("user address") verbose_name_plural = _("user addresses") #default_serializer = 'members.serializers.UserProfileSerializer'
from django.db import models from bluebottle.bb_accounts.models import BlueBottleBaseUser from bluebottle.utils.models import Address from djchoices.choices import DjangoChoices, ChoiceItem from django.conf import settings from django.utils.translation import ugettext as _ class Member(BlueBottleBaseUser): pass class UserAddress(Address): class AddressType(DjangoChoices): primary = ChoiceItem('primary', label=_("Primary")) secondary = ChoiceItem('secondary', label=_("Secondary")) address_type = models.CharField(_("address type"),max_length=10, blank=True, choices=AddressType.choices, default=AddressType.primary) user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_("user"), related_name="address") class Meta: verbose_name = _("user address") verbose_name_plural = _("user addresses") #default_serializer = 'members.serializers.UserProfileSerializer'
Remove spammy warning which doesn't apply when stores check emails
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from social_auth.utils import setting from social_auth.models import UserSocialAuth from social_auth.backends.pipeline import warn_setting from social_auth.backends.exceptions import AuthException def associate_by_email(details, user=None, *args, **kwargs): """Return user entry with same email address as one returned on details.""" if user: return None email = details.get('email') # Don't spam with a warning, this doesn't apply when providers check emails #warn_setting('SOCIAL_AUTH_ASSOCIATE_BY_MAIL', 'associate_by_email') if email and setting('SOCIAL_AUTH_ASSOCIATE_BY_MAIL', False): # try to associate accounts registered with the same email address, # only if it's a single object. AuthException is raised if multiple # objects are returned try: return {'user': UserSocialAuth.get_user_by_email(email=email)} except MultipleObjectsReturned: raise AuthException(kwargs['backend'], 'Not unique email address.') except ObjectDoesNotExist: pass
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from social_auth.utils import setting from social_auth.models import UserSocialAuth from social_auth.backends.pipeline import warn_setting from social_auth.backends.exceptions import AuthException def associate_by_email(details, user=None, *args, **kwargs): """Return user entry with same email address as one returned on details.""" if user: return None email = details.get('email') warn_setting('SOCIAL_AUTH_ASSOCIATE_BY_MAIL', 'associate_by_email') if email and setting('SOCIAL_AUTH_ASSOCIATE_BY_MAIL', False): # try to associate accounts registered with the same email address, # only if it's a single object. AuthException is raised if multiple # objects are returned try: return {'user': UserSocialAuth.get_user_by_email(email=email)} except MultipleObjectsReturned: raise AuthException(kwargs['backend'], 'Not unique email address.') except ObjectDoesNotExist: pass
Enable markdown extensions for TOC and linebreaks
import bbcode import markdown import html from c2corg_ui.format.wikilinks import C2CWikiLinkExtension from markdown.extensions.nl2br import Nl2BrExtension from markdown.extensions.toc import TocExtension _markdown_parser = None _bbcode_parser = None def _get_markdown_parser(): global _markdown_parser if not _markdown_parser: extensions = [ C2CWikiLinkExtension(), Nl2BrExtension(), TocExtension(marker='[toc]', baselevel=2), ] _markdown_parser = markdown.Markdown(output_format='xhtml5', extensions=extensions) return _markdown_parser def _get_bbcode_parser(): global _bbcode_parser if not _bbcode_parser: _bbcode_parser = bbcode.Parser(escape_html=False, newline='\n') return _bbcode_parser def parse_code(text, md=True, bb=True): if md: text = _get_markdown_parser().convert(text) if bb: text = _get_bbcode_parser().format(text) return text def sanitize(text): return html.escape(text)
import bbcode import markdown import html from c2corg_ui.format.wikilinks import C2CWikiLinkExtension _markdown_parser = None _bbcode_parser = None def _get_markdown_parser(): global _markdown_parser if not _markdown_parser: extensions = [ C2CWikiLinkExtension(), ] _markdown_parser = markdown.Markdown(output_format='xhtml5', extensions=extensions) return _markdown_parser def _get_bbcode_parser(): global _bbcode_parser if not _bbcode_parser: _bbcode_parser = bbcode.Parser(escape_html=False, newline='\n') return _bbcode_parser def parse_code(text, md=True, bb=True): if md: text = _get_markdown_parser().convert(text) if bb: text = _get_bbcode_parser().format(text) return text def sanitize(text): return html.escape(text)
Add todo note in ExclusiveRegistrationForm.
from django.contrib.auth import get_user_model from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.utils.translation import ugettext_lazy as _ from registration.forms import RegistrationForm from .models import WhitelistedUsername User = get_user_model() class ExclusiveRegistrationForm(RegistrationForm): def clean(self): # TODO: try catch KeyError here to avoid empty form error form_username = self.cleaned_data['username'] try: # If this runs without raising an exception, then the username is in # our database of whitelisted usernames. WhitelistedUsername.objects.get(username=form_username.lower()) except ObjectDoesNotExist: err = ValidationError(_('Unrecognised student number. Are you a CS1 student at UCT?s'), code='invalid') self.add_error(User.USERNAME_FIELD, err) super(ExclusiveRegistrationForm, self).clean()
from django.contrib.auth import get_user_model from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.utils.translation import ugettext_lazy as _ from registration.forms import RegistrationForm from .models import WhitelistedUsername User = get_user_model() class ExclusiveRegistrationForm(RegistrationForm): def clean(self): form_username = self.cleaned_data['username'] try: # If this runs without raising an exception, then the username is in # our database of whitelisted usernames. WhitelistedUsername.objects.get(username=form_username.lower()) except ObjectDoesNotExist: err = ValidationError(_('Unrecognised student number. Are you a CS1 student at UCT?s'), code='invalid') self.add_error(User.USERNAME_FIELD, err) super(ExclusiveRegistrationForm, self).clean()
Change default section to Home
// @flow import type { SectionType } from "../enums/Section.js"; import { ReduceStore } from "flux/utils"; import UniversalDispatcher from "./UniversalDispatcher.js"; import { Record } from "immutable"; import Section from "../enums/Section.js"; import url from "../utils/url.js"; export type NavigationActionType = { type: "SET_SECTION", section: SectionType, url: string, fromUrl: ?boolean, }; // TODO: Remove showsplash argument const DEFAULT_STATE = { section: Section.Home, url: url.section(Section.Home), }; class State extends Record(DEFAULT_STATE) { section: SectionType; url: string; } class NavigationStore extends ReduceStore<State> { constructor(): void { super(UniversalDispatcher); } getInitialState(): State { const state = new State(); return state; } reduce(state: State, action: NavigationActionType): State { switch (action.type) { case "SET_SECTION": if (action.fromUrl) { history.replaceState({}, "", action.url); } else { history.pushState({}, "", action.url); } return state.set("section", action.section); default: (action: empty); return state; } } getSection(): SectionType { return this.getState().section; } } export default new NavigationStore();
// @flow import type { SectionType } from "../enums/Section.js"; import { ReduceStore } from "flux/utils"; import UniversalDispatcher from "./UniversalDispatcher.js"; import { Record } from "immutable"; import Section from "../enums/Section.js"; import url from "../utils/url.js"; export type NavigationActionType = { type: "SET_SECTION", section: SectionType, url: string, fromUrl: ?boolean, }; // TODO: Remove showsplash argument const DEFAULT_STATE = { section: Section.FindProjects, url: url.section(Section.FindProjects, { showSplash: 1 }), }; class State extends Record(DEFAULT_STATE) { section: SectionType; url: string; } class NavigationStore extends ReduceStore<State> { constructor(): void { super(UniversalDispatcher); } getInitialState(): State { const state = new State(); return state; } reduce(state: State, action: NavigationActionType): State { switch (action.type) { case "SET_SECTION": if (action.fromUrl) { history.replaceState({}, "", action.url); } else { history.pushState({}, "", action.url); } return state.set("section", action.section); default: (action: empty); return state; } } getSection(): SectionType { return this.getState().section; } } export default new NavigationStore();
Update TRPO, inconsistent results between Travis and local.
# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import print_function from __future__ import division import unittest from tensorforce.tests.base_agent_test import BaseAgentTest from tensorforce.agents import TRPOAgent class TestTRPOAgent(BaseAgentTest, unittest.TestCase): agent = TRPOAgent deterministic = False config = dict( batch_size=16, learning_rate=0.005 ) multi_config = dict( batch_size=64, learning_rate=0.1 )
# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import print_function from __future__ import division import unittest from tensorforce.tests.base_agent_test import BaseAgentTest from tensorforce.agents import TRPOAgent class TestTRPOAgent(BaseAgentTest, unittest.TestCase): agent = TRPOAgent deterministic = False config = dict( batch_size=8, learning_rate=1e-2 ) multi_config = dict( batch_size=64, learning_rate=0.1 )
Add ability to specify iteration count in Hash class.
<?php namespace System; class Hash { /** * Hash a string using PHPass. * * PHPass provides reliable bcrypt hashing, and is used by many popular PHP * applications such as Wordpress and Joomla. * * @access public * @param string $value * @return string */ public static function make($value, $rounds = 10) { return static::hasher($rounds)->HashPassword($value); } /** * Determine if an unhashed value matches a given hash. * * @param string $value * @param string $hash * @return bool */ public static function check($value, $hash) { return static::hasher()->CheckPassword($value, $hash); } /** * Create a new PHPass instance. * * @param int $rounds * @return PasswordHash */ private static function hasher($rounds = 10) { require_once SYS_PATH.'vendor/phpass'.EXT; return new \PasswordHash($rounds, false); } }
<?php namespace System; class Hash { /** * Hash a string using PHPass. * * PHPass provides reliable bcrypt hashing, and is used by many popular PHP * applications such as Wordpress and Joomla. * * @access public * @param string $value * @return string */ public static function make($value) { return static::hasher()->HashPassword($value); } /** * Determine if an unhashed value matches a given hash. * * @param string $value * @param string $hash * @return bool */ public static function check($value, $hash) { return static::hasher()->CheckPassword($value, $hash); } /** * Create a new PHPass instance. * * @return PasswordHash */ private static function hasher() { require_once SYS_PATH.'vendor/phpass'.EXT; return new \PasswordHash(10, false); } }
Remove force as it may overwrite somthing unwanted.
const spawn = require("./spawn"); module.exports = function(workDir, isDebug){ function git() { var len = arguments.length; var args = new Array(len); for (var i = 0; i < len; i++) { args[i] = arguments[i]; } return spawn('git', args, { cwd: workDir, verbose: isDebug }); } return function pullFetchRebasePush(forkedRepoUrl, sourceRepoUrl, forkedDefaultBranch, sourceDefaultBranch) { return git('init') .then(() => git('remote', 'add', 'origin', forkedRepoUrl)) .then(() => git('pull', 'origin', forkedDefaultBranch)) .then(() => git('remote', 'add', 'upstream', sourceRepoUrl)) .then(() => git('fetch', 'upstream')) .then(() => git('checkout', 'origin/' + forkedDefaultBranch)) .then(() => git('merge', 'upstream/' + sourceDefaultBranch)) .then(() => git('push', 'origin', 'HEAD:' + forkedDefaultBranch)) .catch((err) => console.log(err)); } }
const spawn = require("./spawn"); module.exports = function(workDir, isDebug){ function git() { var len = arguments.length; var args = new Array(len); for (var i = 0; i < len; i++) { args[i] = arguments[i]; } return spawn('git', args, { cwd: workDir, verbose: isDebug }); } return function pullFetchRebasePush(forkedRepoUrl, sourceRepoUrl, forkedDefaultBranch, sourceDefaultBranch) { return git('init') .then(() => git('remote', 'add', 'origin', forkedRepoUrl)) .then(() => git('pull', 'origin', forkedDefaultBranch)) .then(() => git('remote', 'add', 'upstream', sourceRepoUrl)) .then(() => git('fetch', 'upstream')) .then(() => git('checkout', 'origin/' + forkedDefaultBranch)) .then(() => git('merge', 'upstream/' + sourceDefaultBranch)) .then(() => git('push', 'origin', 'HEAD:' + forkedDefaultBranch, '--force')) .catch((err) => console.log(err)); } }