text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Allow original exception to be provided if necessary git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1329661 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: 91e8c0fd7a04cfa172a34abfb5d0296d040843c0
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.jmeter.exceptions; /** */ public class IllegalUserActionException extends Exception { private static final long serialVersionUID = 240L; /** * @deprecated - use IllegalUserActionException(String) */ @Deprecated // Needed for serialisation testing public IllegalUserActionException() { super(); } public IllegalUserActionException(String name) { super(name); } public IllegalUserActionException(String name, Throwable t) { super(name, t); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.jmeter.exceptions; /** */ public class IllegalUserActionException extends Exception { private static final long serialVersionUID = 240L; /** * @deprecated - use IllegalUserActionException(String) */ @Deprecated // Needed for serialisation testing public IllegalUserActionException() { super(); } public IllegalUserActionException(String name) { super(name); } }
Update user model with confirmed and confirmed_at
import datetime from project import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String, unique=True, nullable=False) password = db.Column(db.String, nullable=False) registered_on = db.Column(db.DateTime, nullable=False) admin = db.Column(db.Boolean, nullable=False, default=False) confirmed = db.Column(db.Boolean, nullable=False, default=False) confirmed_on = db.Column(db.DateTime, nullable=True) def __init__(self, email, password, paid=False, admin=False): self.email = email self.password = bcrypt.generate_password_hash(password) self.registered_on = datetime.datetime.now() self.admin = admin self.confirmed = confirmed self.confirmed_on = confirmed_on def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.id def __repr__(self): return '<email {}'.format(self.email)
import datetime from project import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String, unique=True, nullable=False) password = db.Column(db.String, nullable=False) registered_on = db.Column(db.DateTime, nullable=False) admin = db.Column(db.Boolean, nullable=False, default=False) def __init__(self, email, password, paid=False, admin=False): self.email = email self.password = bcrypt.generate_password_hash(password) self.registered_on = datetime.datetime.now() self.admin = admin def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.id def __repr__(self): return '<email {}'.format(self.email)
FIX : Attribute map (TI)
<?php namespace DoL\LdapBundle\Tests\Hydrator; use FOS\UserBundle\Model\UserManagerInterface; use DoL\LdapBundle\Hydrator\LegacyHydrator; use DoL\LdapBundle\Tests\TestUser; class LegacyHydratorTest extends AbstractHydratorTestCase { protected function setUp() { parent::setUp(); /** @var UserManagerInterface|\PHPUnit_Framework_MockObject_MockObject $userManager */ $userManager = $this->getMock('FOS\UserBundle\Model\UserManagerInterface'); $userManager->expects($this->any()) ->method('createUser') ->will($this->returnValue(new TestUser())); $this->hydrator = new LegacyHydrator($userManager); $config = $this->getDefaultUserConfig(); $this->hydrator->setAttributeMap($config['attributes']); } }
<?php namespace DoL\LdapBundle\Tests\Hydrator; use FOS\UserBundle\Model\UserManagerInterface; use DoL\LdapBundle\Hydrator\LegacyHydrator; use DoL\LdapBundle\Tests\TestUser; class LegacyHydratorTest extends AbstractHydratorTestCase { protected function setUp() { parent::setUp(); /** @var UserManagerInterface|\PHPUnit_Framework_MockObject_MockObject $userManager */ $userManager = $this->getMock('FOS\UserBundle\Model\UserManagerInterface'); $userManager->expects($this->any()) ->method('createUser') ->will($this->returnValue(new TestUser())); $this->hydrator = new LegacyHydrator($userManager); $this->hydrator->setAttributeMap($this->getDefaultUserConfig()); } }
Prepend the tester name in the composite item name formatter
package se.fnord.katydid.internal; import se.fnord.katydid.ComparisonStatus; import se.fnord.katydid.DataTester; import se.fnord.katydid.TestingContext; import java.nio.ByteBuffer; import static java.lang.Math.max; public abstract class CompositeTester extends AbstractTester { private final DataTester[] values; public CompositeTester(String name, DataTester... values) { super(name); this.values = values; } @Override public ComparisonStatus compareItem(TestingContext context, int pass, int itemIndex) { return context.compareTo(values[itemIndex], pass); } @Override public int passCount() { int mp = 0; for (DataTester c : values) mp = max(mp, c.passCount()); return mp; } @Override public int lengthOfItem(int itemIndex) { return values[itemIndex].length(); } @Override public int itemCount() { return values.length; } @Override public String formatItem(String name, int itemIndex) { checkItemIndex(itemIndex); return name + formatChild(itemIndex, values[itemIndex]); } @Override public void toBuffer(ByteBuffer bb) { for (DataTester c : values) { c.toBuffer(bb); } } }
package se.fnord.katydid.internal; import se.fnord.katydid.ComparisonStatus; import se.fnord.katydid.DataTester; import se.fnord.katydid.TestingContext; import java.nio.ByteBuffer; import static java.lang.Math.max; public abstract class CompositeTester extends AbstractTester { private final DataTester[] values; public CompositeTester(String name, DataTester... values) { super(name); this.values = values; } @Override public ComparisonStatus compareItem(TestingContext context, int pass, int itemIndex) { return context.compareTo(values[itemIndex], pass); } @Override public int passCount() { int mp = 0; for (DataTester c : values) mp = max(mp, c.passCount()); return mp; } @Override public int lengthOfItem(int itemIndex) { return values[itemIndex].length(); } @Override public int itemCount() { return values.length; } @Override public String formatItem(String name, int itemIndex) { return formatChild(itemIndex, values[itemIndex]); checkItemIndex(itemIndex); } @Override public void toBuffer(ByteBuffer bb) { for (DataTester c : values) { c.toBuffer(bb); } } }
Replace void 0 with undefined
/* eslint import/no-extraneous-dependencies: [2, { "devDependencies": true }] */ import expect from 'expect'; import { map, toUpper } from 'ramda'; import React from 'react'; import { shallow } from 'enzyme'; import createElement, { mapElementPropsWith } from './createElement'; describe('createElement', () => { it('supports omitting props', () => { const expected = React.createElement( 'div', {}, React.createElement('span', {}, 't'), 'est' ); const actual = createElement('div', createElement('span', 't'), 'est'); expect(actual).toEqual(expected); }); it('handles undefined props properly', () => { const expected = React.createElement('div', undefined); const actual = createElement('div', undefined); expect(actual).toEqual(expected); }); it('lets the innerHtml prop insert unescaped HTML into the element', () => { const expected = '<div><strong>Dangerous</strong> HTML!</div>'; const actual = shallow( createElement('div', { innerHtml: '<strong>Dangerous</strong> HTML!' }) ).html(); expect(actual).toBe(expected); }); }); describe('mapElementPropsWith', () => { it('takes a props mapper, and returns a createElement function', () => { const fn = mapElementPropsWith(map(toUpper)); const expected = React.createElement( 'div', { className: 'BAR', id: 'FOO' } ); const actual = fn('div', { className: 'bar', id: 'foo' }); expect(actual).toEqual(expected); }); });
/* eslint import/no-extraneous-dependencies: [2, { "devDependencies": true }] */ import expect from 'expect'; import { map, toUpper } from 'ramda'; import React from 'react'; import { shallow } from 'enzyme'; import createElement, { mapElementPropsWith } from './createElement'; describe('createElement', () => { it('supports omitting props', () => { const expected = React.createElement( 'div', {}, React.createElement('span', {}, 't'), 'est' ); const actual = createElement('div', createElement('span', 't'), 'est'); expect(actual).toEqual(expected); }); it('handles undefined props properly', () => { const expected = React.createElement('div', void 0); const actual = createElement('div', void 0); expect(actual).toEqual(expected); }); it('lets the innerHtml prop insert unescaped HTML into the element', () => { const expected = '<div><strong>Dangerous</strong> HTML!</div>'; const actual = shallow( createElement('div', { innerHtml: '<strong>Dangerous</strong> HTML!' }) ).html(); expect(actual).toBe(expected); }); }); describe('mapElementPropsWith', () => { it('takes a props mapper, and returns a createElement function', () => { const fn = mapElementPropsWith(map(toUpper)); const expected = React.createElement( 'div', { className: 'BAR', id: 'FOO' } ); const actual = fn('div', { className: 'bar', id: 'foo' }); expect(actual).toEqual(expected); }); });
Switch console to use tracing-develop
import logging logging.basicConfig(level=logging.DEBUG) import mdk_tracing import time import quark # tracer = mdk_tracing.Tracer.withURLsAndToken("ws://localhost:52690/ws", None, None) tracer = mdk_tracing.Tracer.withURLsAndToken("wss://tracing-develop.datawire.io/ws", None, None) def goodHandler(result): # logging.info("Good!") for record in result: logging.info(record.toString()) def badHandler(result): logging.info("Failure: %s" % result.toString()) def formatLogRecord(record): return("%.3f %s %s" % (record.timestamp, record.record.level, record.record.text)) def poller(hrm=None): # logging.info("POLLING") tracer.poll() \ .andEither(goodHandler, badHandler) \ .andFinally(lambda x: quark.IO.schedule(1)) \ .andFinally(poller) poller()
import logging logging.basicConfig(level=logging.DEBUG) import mdk_tracing import time import quark tracer = mdk_tracing.Tracer.withURLsAndToken("ws://localhost:52690/ws", None, None) # tracer = mdk_tracing.Tracer.withURLsAndToken("wss://tracing-develop.datawire.io/ws", None, None) def goodHandler(result): # logging.info("Good!") for record in result: logging.info(record.toString()) def badHandler(result): logging.info("Failure: %s" % result.toString()) def formatLogRecord(record): return("%.3f %s %s" % (record.timestamp, record.record.level, record.record.text)) def poller(hrm=None): # logging.info("POLLING") tracer.poll() \ .andEither(goodHandler, badHandler) \ .andFinally(lambda x: quark.IO.schedule(1)) \ .andFinally(poller) poller()
Change return type of getView() and getPresenter() for Dialogs.
package com.philliphsu.bottomsheetpickers.view.numberpad; import com.philliphsu.bottomsheetpickers.view.LocaleModel; public class NumberPadTimePickerDialogPresenterTest extends NumberPadTimePickerPresenterTest { @Override INumberPadTimePicker.DialogView getView(int mode) { return (INumberPadTimePicker.DialogView) super.getView(mode); } @Override INumberPadTimePicker.DialogPresenter getPresenter(int mode) { return (INumberPadTimePicker.DialogPresenter) super.getPresenter(mode); } @Override Class<? extends INumberPadTimePicker.DialogView> getViewClass() { return INumberPadTimePicker.DialogView.class; } @Override INumberPadTimePicker.DialogPresenter createPresenter(INumberPadTimePicker.View view, LocaleModel localeModel, boolean is24HourMode) { return new NumberPadTimePickerDialogPresenter((INumberPadTimePicker.DialogView) view, localeModel, is24HourMode); } }
package com.philliphsu.bottomsheetpickers.view.numberpad; import com.philliphsu.bottomsheetpickers.view.LocaleModel; public class NumberPadTimePickerDialogPresenterTest extends NumberPadTimePickerPresenterTest { @Override Class<? extends INumberPadTimePicker.DialogView> getViewClass() { return INumberPadTimePicker.DialogView.class; } @Override INumberPadTimePicker.DialogPresenter createPresenter(INumberPadTimePicker.View view, LocaleModel localeModel, boolean is24HourMode) { return new NumberPadTimePickerDialogPresenter((INumberPadTimePicker.DialogView) view, localeModel, is24HourMode); } }
Store the rotation matrix corresponding to the orientation in the item.
"""Provide the class Image corresponding to an IdxItem. """ import os.path import re from PySide import QtGui class ImageNotFoundError(Exception): pass class Image(object): def __init__(self, basedir, item): self.item = item self.fileName = os.path.join(basedir, item.filename) self.name = item.name or os.path.basename(self.fileName) def getPixmap(self): image = QtGui.QImage(self.fileName) if image.isNull(): raise ImageNotFoundError("Cannot load %s." % self.fileName) pixmap = QtGui.QPixmap.fromImage(image) rm = None try: rm = self.item.rotmatrix except AttributeError: if self.item.orientation: m = re.match(r"Rotate (\d+) CW", self.item.orientation) if m: rm = QtGui.QMatrix().rotate(int(m.group(1))) self.item.rotmatrix = rm if rm: return pixmap.transformed(rm) else: return pixmap
"""Provide the class Image corresponding to an IdxItem. """ import os.path import re from PySide import QtGui class ImageNotFoundError(Exception): pass class Image(object): def __init__(self, basedir, item): self.item = item self.fileName = os.path.join(basedir, item.filename) self.name = item.name or os.path.basename(self.fileName) def getPixmap(self): image = QtGui.QImage(self.fileName) if image.isNull(): raise ImageNotFoundError("Cannot load %s." % self.fileName) pixmap = QtGui.QPixmap.fromImage(image) if self.item.orientation: rm = QtGui.QMatrix() m = re.match(r"Rotate (\d+) CW", self.item.orientation) if m: rm = rm.rotate(int(m.group(1))) return pixmap.transformed(rm) else: return pixmap
Remove redundant lookup from field type process
<?php namespace Statamic\Addons\LinkOgData; use Statamic\Extend\Fieldtype; class LinkOgDataFieldtype extends Fieldtype { /** * The blank/default value * * @return array */ public function blank() { return [ 'url' => null ]; } /** * Pre-process the data before it gets sent to the publish page * * @param mixed $data * @return array|mixed */ public function preProcess($data) { return $data; } /** * Process the data before it gets saved * * @param mixed $data * @return array|mixed */ public function process($data) { return $data; } }
<?php namespace Statamic\Addons\LinkOgData; use Statamic\Extend\Fieldtype; class LinkOgDataFieldtype extends Fieldtype { protected function init() { $this->linkogdata = new LinkOgData; } /** * The blank/default value * * @return array */ public function blank() { return [ 'url' => null ]; } /** * Pre-process the data before it gets sent to the publish page * * @param mixed $data * @return array|mixed */ public function preProcess($data) { return $data; } /** * Process the data before it gets saved * * @param mixed $data * @return array|mixed */ public function process($data) { $url = $data['url']; $data = [ 'url' => $data['url'], ]; $result = $this->linkogdata->getOgData($url); return array_merge($data, $result); } }
Add coverage as a testing requirement
#!/usr/bin/env python from setuptools import setup, find_packages VERSION = '0.4.2' def readme(): with open('README.rst') as f: return f.read() setup( name='django-backupdb', version=VERSION, description='Management commands for backing up and restoring databases in Django.', long_description=readme(), author='Fusionbox programmers', author_email='programmers@fusionbox.com', keywords='django database backup', url='https://github.com/fusionbox/django-backupdb', packages=find_packages(exclude=('tests',)), platforms='any', license='BSD', test_suite='nose.collector', setup_requires=[ 'nose==1.2.1', 'mock==1.0.1', 'coverage==3.6', ], tests_require=[ 'nose==1.2.1', 'mock==1.0.1', 'coverage==3.6', ], install_requires=[ 'django>=1.3', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', ], )
#!/usr/bin/env python from setuptools import setup, find_packages VERSION = '0.4.2' def readme(): with open('README.rst') as f: return f.read() setup( name='django-backupdb', version=VERSION, description='Management commands for backing up and restoring databases in Django.', long_description=readme(), author='Fusionbox programmers', author_email='programmers@fusionbox.com', keywords='django database backup', url='https://github.com/fusionbox/django-backupdb', packages=find_packages(exclude=('tests',)), platforms='any', license='BSD', test_suite='nose.collector', setup_requires=[ 'nose==1.2.1', 'mock==1.0.1', ], tests_require=[ 'nose==1.2.1', 'mock==1.0.1', ], install_requires=[ 'django>=1.3', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', ], )
Add the -v flag to work with linux nc
# (C) Datadog, Inc. 2010-2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) import os import pytest from .common import INSTANCE, HOST from datadog_checks.dev import docker_run, get_here, run_command from datadog_checks.dev.conditions import CheckCommandOutput @pytest.fixture(scope='session') def dd_environment(): compose_file = os.path.join(get_here(), 'compose', 'docker-compose.yaml') # Build the topology jar to use in the environment with docker_run(compose_file, build=True, service_name='topology-maker', sleep=15): run_command( ['docker', 'cp', 'topology-build:/topology.jar', os.path.join(get_here(), 'compose')] ) nimbus_condition = CheckCommandOutput(['nc', '-zv', HOST, '6627'], 'succeeded') with docker_run(compose_file, service_name='storm-nimbus', conditions=[nimbus_condition]): with docker_run(compose_file, service_name='storm-ui', log_patterns=[r'org.apache.storm.ui.core']): with docker_run( compose_file, service_name='topology', log_patterns=['Finished submitting topology: topology'] ): yield INSTANCE
# (C) Datadog, Inc. 2010-2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) import os import pytest from .common import INSTANCE, HOST from datadog_checks.dev import docker_run, get_here, run_command from datadog_checks.dev.conditions import CheckCommandOutput @pytest.fixture(scope='session') def dd_environment(): compose_file = os.path.join(get_here(), 'compose', 'docker-compose.yaml') # Build the topology jar to use in the environment with docker_run(compose_file, build=True, service_name='topology-maker', sleep=15): run_command( ['docker', 'cp', 'topology-build:/topology.jar', os.path.join(get_here(), 'compose')] ) nimbus_condition = CheckCommandOutput(['nc', '-z', HOST, '6627'], 'succeeded') with docker_run(compose_file, service_name='storm-nimbus', conditions=[nimbus_condition]): with docker_run(compose_file, service_name='storm-ui', log_patterns=[r'org.apache.storm.ui.core']): with docker_run( compose_file, service_name='topology', log_patterns=['Finished submitting topology: topology'] ): yield INSTANCE
Correct endpoints for mocking data
import { expect, isFSA, hasStreamMetadata } from '../spec_helper' import * as subject from '../../src/actions/onboarding' describe('actions', () => { it('#loadChannels returns the expected action', () => { const action = subject.loadChannels() expect(isFSA(action)).to.be.true expect(hasStreamMetadata(action)).to.be.true expect(action.type).to.equal('LOAD_STREAM') expect(action.payload.endpoint).to.be.equal('/test/mock/data/channels.json') expect(action.payload.vo).to.be.empty expect(action.meta.mappingType).to.equal('users') expect(action.meta.renderStream).to.be.a('function') }) it('#loadAwesomePeople returns the expected action', () => { const action = subject.loadAwesomePeople() expect(isFSA(action)).to.be.true expect(hasStreamMetadata(action)).to.be.true expect(action.type).to.equal('LOAD_STREAM') expect(action.payload.endpoint).to.be.equal('/test/mock/data/awesome_people.json') expect(action.payload.vo).to.be.empty expect(action.meta.mappingType).to.equal('users') expect(action.meta.renderStream).to.be.a('function') }) })
import { expect, isFSA, hasStreamMetadata } from '../spec_helper' import * as subject from '../../src/actions/onboarding' describe('actions', () => { it('#loadChannels returns the expected action', () => { const action = subject.loadChannels() expect(isFSA(action)).to.be.true expect(hasStreamMetadata(action)).to.be.true expect(action.type).to.equal('LOAD_STREAM') expect(action.payload.endpoint).to.be.equal('/_data/channels.json') expect(action.payload.vo).to.be.empty expect(action.meta.mappingType).to.equal('users') expect(action.meta.renderStream).to.be.a('function') }) it('#loadAwesomePeople returns the expected action', () => { const action = subject.loadAwesomePeople() expect(isFSA(action)).to.be.true expect(hasStreamMetadata(action)).to.be.true expect(action.type).to.equal('LOAD_STREAM') expect(action.payload.endpoint).to.be.equal('/_data/awesome_people.json') expect(action.payload.vo).to.be.empty expect(action.meta.mappingType).to.equal('users') expect(action.meta.renderStream).to.be.a('function') }) })
Update method creation syntax to ES6 LookAction.js iamtienng
L.LockAction = L.EditAction.extend({ initialize(map, overlay, options) { var edit = overlay.editing; var use; var tooltip; if (edit instanceof L.DistortableImage.Edit) { L.DistortableImage.action_map.u = '_unlock'; L.DistortableImage.action_map.l = '_lock'; tooltip = overlay.options.translation.lockMode; use = edit.isMode('lock') ? 'lock' : 'unlock'; } else { L.DistortableImage.group_action_map.l = '_lockGroup'; tooltip = overlay.options.translation.lockImages; use = 'lock'; } options = options || {}; options.toolbarIcon = { svg: true, html: use, tooltip: tooltip, className: 'lock', }; L.EditAction.prototype.initialize.call(this, map, overlay, options); }, addHooks() { var edit = this._overlay.editing; if (edit instanceof L.DistortableImage.Edit) { edit._toggleLockMode(); } else { edit._lockGroup(); } }, });
L.LockAction = L.EditAction.extend({ initialize: function(map, overlay, options) { var edit = overlay.editing; var use; var tooltip; if (edit instanceof L.DistortableImage.Edit) { L.DistortableImage.action_map.u = '_unlock'; L.DistortableImage.action_map.l = '_lock'; tooltip = overlay.options.translation.lockMode; use = edit.isMode('lock') ? 'lock' : 'unlock'; } else { L.DistortableImage.group_action_map.l = '_lockGroup'; tooltip = overlay.options.translation.lockImages; use = 'lock'; } options = options || {}; options.toolbarIcon = { svg: true, html: use, tooltip: tooltip, className: 'lock', }; L.EditAction.prototype.initialize.call(this, map, overlay, options); }, addHooks: function() { var edit = this._overlay.editing; if (edit instanceof L.DistortableImage.Edit) { edit._toggleLockMode(); } else { edit._lockGroup(); } }, });
Add condition to replace Translation extension
<?php /* * This file is part of the Cocorico package. * * (c) Cocolabs SAS <contact@cocolabs.io> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Cocorico\CoreBundle\DependencyInjection\Compiler; use Cocorico\CoreBundle\Twig\TranslationExtension; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class TwigTranslationExtensionCompilerPass implements CompilerPassInterface { /** * {@inheritDoc} */ public function process(ContainerBuilder $container) { /** * Override Twig Translation extension */ if ($container->getParameter('cocorico.check_translation') === true) { if ($container->hasDefinition('twig.extension.trans')) { $definition = $container->getDefinition('twig.extension.trans'); $definition->setClass(TranslationExtension::class); $definition->addMethodCall( 'setCheckTranslation', array($container->getParameter('cocorico.check_translation')) ); } } } }
<?php /* * This file is part of the Cocorico package. * * (c) Cocolabs SAS <contact@cocolabs.io> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Cocorico\CoreBundle\DependencyInjection\Compiler; use Cocorico\CoreBundle\Twig\TranslationExtension; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class TwigTranslationExtensionCompilerPass implements CompilerPassInterface { /** * {@inheritDoc} */ public function process(ContainerBuilder $container) { /** * Override Twig Translation extension */ if ($container->hasDefinition('twig.extension.trans')) { $definition = $container->getDefinition('twig.extension.trans'); $definition->setClass(TranslationExtension::class); $definition->addMethodCall( 'setCheckTranslation', array($container->getParameter('cocorico.check_translation')) ); } } }
Check if verification is enabled
package org.jboss.aerogear.unifiedpush.service.impl; import javax.ejb.Asynchronous; import javax.ejb.Stateless; import javax.enterprise.inject.Alternative; import javax.inject.Inject; import org.jboss.aerogear.unifiedpush.api.Installation; import org.jboss.aerogear.unifiedpush.api.Variant; import org.jboss.aerogear.unifiedpush.service.ClientInstallationService; import org.jboss.aerogear.unifiedpush.service.Configuration; import org.jboss.aerogear.unifiedpush.service.VerificationService; /** * An alternative class which disables the installation prior to adding it. Once the installation is added, * this implementation fires a verification request to the newly added installation. */ @Stateless @Alternative public class VerifyingClientInstallationServiceImpl extends ClientInstallationServiceImpl implements ClientInstallationService { private static final String ENABLE_VERIFICATION = "aerogear.config.enable_sms_verification"; @Inject private Configuration configuration; @Inject private VerificationService verificationService; // TODO: this logic might be worth moving to ClientInstallationServiceImpl itself (and then removing this class). // The decision whether to verify installations or not could be made part of the Application. @Override @Asynchronous public void addInstallation(Variant variant, Installation entity) { boolean shouldVerifiy = configuration.getBooleanProperty(ENABLE_VERIFICATION, false); if (shouldVerifiy) { entity.setEnabled(false); super.addInstallation(variant, entity); verificationService.initiateDeviceVerification(entity); } else { super.addInstallation(variant, entity); } } }
package org.jboss.aerogear.unifiedpush.service.impl; import javax.ejb.Asynchronous; import javax.ejb.Stateless; import javax.enterprise.inject.Alternative; import javax.inject.Inject; import org.jboss.aerogear.unifiedpush.api.Installation; import org.jboss.aerogear.unifiedpush.api.Variant; import org.jboss.aerogear.unifiedpush.service.ClientInstallationService; import org.jboss.aerogear.unifiedpush.service.VerificationService; /** * An alternative class which disables the installation prior to adding it. Once the installation is added, * this implementation fires a verification request to the newly added installation. */ @Stateless @Alternative public class VerifyingClientInstallationServiceImpl extends ClientInstallationServiceImpl implements ClientInstallationService { @Inject private VerificationService verificationService; // TODO: this logic might be worth moving to ClientInstallationServiceImpl itself (and then removing this class). // The decision whether to verify installations or not could be made part of the Application. @Override @Asynchronous public void addInstallation(Variant variant, Installation entity) { entity.setEnabled(false); super.addInstallation(variant, entity); verificationService.initiateDeviceVerification(entity); } }
Put new sentence in Javadoc on new line
/* * Copyright 2019 the original author or authors. * * 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.gradle.internal.vfs; /** * Identifies if a path is underneath one of Gradle's "additive caches". * * Over time more files can be added to an additive cache, but existing files * can never be modified. * Files in additive caches can only be deleted as part of cleanup. * * This quasi-immutability about additive caches allows for some * optimizations wrt retaining file system state in-memory. */ public interface AdditiveCacheLocations { /** * Checks if a given path is inside one of Gradle's additive caches. */ boolean isInsideAdditiveCache(String path); }
/* * Copyright 2019 the original author or authors. * * 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.gradle.internal.vfs; /** * Identifies if a path is underneath one of Gradle's "additive caches". * * Over time more files can be added to an additive cache, but existing files * can never be modified. Files in additive caches can only be deleted as part * of cleanup. * * This quasi-immutability about additive caches allows for some * optimizations wrt retaining file system state in-memory. */ public interface AdditiveCacheLocations { /** * Checks if a given path is inside one of Gradle's additive caches. */ boolean isInsideAdditiveCache(String path); }
Remove unused call to 'bestOrder'
import { polygonCentroid, distance } from "./math.js"; // With 8 or fewer shapes, find the best permutation // Skip if array is huge (9+ shapes) export default function(start, end) { let distances = start.map(p1 => end.map(p2 => squaredDistance(p1, p2))); if (start.length > 8) { return start.map((d, i) => i); } return bestOrder(start, end, distances); } export function bestOrder(start, end, distances) { let min = Infinity, best = start.map((d, i) => i); function permute(arr, order = [], sum = 0) { for (let i = 0; i < arr.length; i++) { let cur = arr.splice(i, 1), dist = distances[cur[0]][order.length]; if (sum + dist < min) { if (arr.length) { permute(arr.slice(), order.concat(cur), sum + dist); } else { min = sum + dist; best = order.concat(cur); } } if (arr.length) { arr.splice(i, 0, cur[0]); } } } permute(best); return best; } function squaredDistance(p1, p2) { let d = distance(polygonCentroid(p1), polygonCentroid(p2)); return d * d; }
import { polygonCentroid, distance } from "./math.js"; // With 8 or fewer shapes, find the best permutation // Skip if array is huge (9+ shapes) export default function(start, end) { let distances = start.map(p1 => end.map(p2 => squaredDistance(p1, p2))), order = bestOrder(start, end, distances); if (start.length > 8) { return start.map((d, i) => i); } return bestOrder(start, end, distances); } export function bestOrder(start, end, distances) { let min = Infinity, best = start.map((d, i) => i); function permute(arr, order = [], sum = 0) { for (let i = 0; i < arr.length; i++) { let cur = arr.splice(i, 1), dist = distances[cur[0]][order.length]; if (sum + dist < min) { if (arr.length) { permute(arr.slice(), order.concat(cur), sum + dist); } else { min = sum + dist; best = order.concat(cur); } } if (arr.length) { arr.splice(i, 0, cur[0]); } } } permute(best); return best; } function squaredDistance(p1, p2) { let d = distance(polygonCentroid(p1), polygonCentroid(p2)); return d * d; }
Remove operation specific to Volley
package com.insa.rocketlyonandroid.utils; import android.app.Activity; import android.support.v4.app.Fragment; import butterknife.ButterKnife; import trikita.log.Log; /* With this Base Class, we can access to parent activity of fragment very easily */ public abstract class BaseFragment extends Fragment { protected Activity mActivity; @Override public void onAttach(Activity activity) { super.onAttach(activity); mActivity = activity; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onStop() { super.onStop(); Log.d(mActivity.getClass().toString()); } }
package com.insa.rocketlyonandroid.utils; import android.app.Activity; import android.support.v4.app.Fragment; import butterknife.ButterKnife; import trikita.log.Log; /* With this Base Class, we can access to parent activity of fragment very easily */ public abstract class BaseFragment extends Fragment { protected Activity mActivity; @Override public void onAttach(Activity activity) { super.onAttach(activity); mActivity = activity; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onStop() { super.onStop(); Log.d(mActivity.getClass().toString()); //VolleySingleton.getInstance().getRequestQueue().cancelAll(getClass().toString()); } }
[Python] Fix the sample python plugin. PyGI doesn't handle default values for introspected methods, so we need to specify all the arguments for pack_start()
# -*- coding: utf-8 -*- # ex:set ts=4 et sw=4 ai: import gobject from gi.repository import Peas from gi.repository import Gtk LABEL_STRING="Python Says Hello!" class PythonHelloPlugin(gobject.GObject, Peas.Activatable): __gtype_name__ = 'PythonHelloPlugin' def do_activate(self, window): print "PythonHelloPlugin.do_activate", repr(window) window._pythonhello_label = Gtk.Label() window._pythonhello_label.set_text(LABEL_STRING) window._pythonhello_label.show() window.get_child().pack_start(window._pythonhello_label, True, True, 0) def do_deactivate(self, window): print "PythonHelloPlugin.do_deactivate", repr(window) window.get_child().remove(window._pythonhello_label) window._pythonhello_label.destroy() def do_update_state(self, window): print "PythonHelloPlugin.do_update_state", repr(window)
# -*- coding: utf-8 -*- # ex:set ts=4 et sw=4 ai: import gobject from gi.repository import Peas from gi.repository import Gtk LABEL_STRING="Python Says Hello!" class PythonHelloPlugin(gobject.GObject, Peas.Activatable): __gtype_name__ = 'PythonHelloPlugin' def do_activate(self, window): print "PythonHelloPlugin.do_activate", repr(window) window._pythonhello_label = Gtk.Label() window._pythonhello_label.set_text(LABEL_STRING) window._pythonhello_label.show() window.get_child().pack_start(window._pythonhello_label) def do_deactivate(self, window): print "PythonHelloPlugin.do_deactivate", repr(window) window.get_child().remove(window._pythonhello_label) window._pythonhello_label.destroy() def do_update_state(self, window): print "PythonHelloPlugin.do_update_state", repr(window)
Use most recent Ubuntu AMI to minimize the cloud instance spin-up time (=> less system updates to apply at startup)
package org.lamport.tla.toolbox.jcloud; public class EC2CloudTLCInstanceParameters extends CloudTLCInstanceParameters { @Override public String getOwnerId() { // ubuntu official return "owner-id=owner-id=099720109477;state=available;image-type=machine"; } @Override public String getCloudProvier() { return "aws-ec2"; } @Override public String getImageId() { // ubuntu 64bit 14.04 precise paravirtual release // https://cloud-images.ubuntu.com/releases/14.04/release/ return "us-east-1/ami-30837058"; } @Override public String getHardwareId() { return "m2.4xlarge"; } @Override public String getJavaSystemProperties() { return "-Dtlc2.tool.fp.FPSet.impl=tlc2.tool.fp.OffHeapDiskFPSet"; } @Override public String getJavaVMArgs() { return "-Xmx24G -Xms24G -XX:MaxDirectMemorySize=32g"; } @Override public String getTLCParameters() { return "-workers 12"; } }
package org.lamport.tla.toolbox.jcloud; public class EC2CloudTLCInstanceParameters extends CloudTLCInstanceParameters { @Override public String getOwnerId() { // ubuntu official return "owner-id=owner-id=099720109477;state=available;image-type=machine"; } @Override public String getCloudProvier() { return "aws-ec2"; } @Override public String getImageId() { // ubuntu 64bit 14.04 precise paravirtual return "us-east-1/ami-7fe7fe16"; } @Override public String getHardwareId() { return "m2.4xlarge"; } @Override public String getJavaSystemProperties() { return "-Dtlc2.tool.fp.FPSet.impl=tlc2.tool.fp.OffHeapDiskFPSet"; } @Override public String getJavaVMArgs() { return "-Xmx24G -Xms24G -XX:MaxDirectMemorySize=32g"; } @Override public String getTLCParameters() { return "-workers 12"; } }
Fix lib/raczlib build for CGO_ENABLED=0
// Copyright 2019 The Wuffs Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build cgo package raczlib import ( "io" "github.com/google/wuffs/lib/cgozlib" "github.com/google/wuffs/lib/rac" ) // MakeDecompressor implements rac.CodecReader. func (r *CodecReader) MakeDecompressor(compressed io.Reader, rctx rac.ReaderContext) (io.Reader, error) { if r.cachedZlibReader == nil { r.cachedZlibReader = &cgozlib.Reader{} } if err := r.cachedZlibReader.Reset(compressed, rctx.Secondary); err != nil { return nil, err } return r.cachedZlibReader, nil }
// Copyright 2019 The Wuffs Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package raczlib import ( "io" "github.com/google/wuffs/lib/cgozlib" "github.com/google/wuffs/lib/rac" ) // MakeDecompressor implements rac.CodecReader. func (r *CodecReader) MakeDecompressor(compressed io.Reader, rctx rac.ReaderContext) (io.Reader, error) { if r.cachedZlibReader == nil { r.cachedZlibReader = &cgozlib.Reader{} } if err := r.cachedZlibReader.Reset(compressed, rctx.Secondary); err != nil { return nil, err } return r.cachedZlibReader, nil }
Change canceling icon to 'spinning orange'
import JobStatus from 'girder_plugins/jobs/JobStatus'; JobStatus.registerStatus({ WORKER_FETCHING_INPUT: { value: 820, text: 'Fetching input', icon: 'icon-download', color: '#89d2e2' }, WORKER_CONVERTING_INPUT: { value: 821, text: 'Converting input', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_CONVERTING_OUTPUT: { value: 822, text: 'Converting output', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_PUSHING_OUTPUT: { value: 823, text: 'Pushing output', icon: 'icon-upload', color: '#89d2e2' }, WORKER_CANCELING: { value: 824, text: 'Canceling', icon: 'icon-spin3 animate-spin', color: '#f89406' } });
import JobStatus from 'girder_plugins/jobs/JobStatus'; JobStatus.registerStatus({ WORKER_FETCHING_INPUT: { value: 820, text: 'Fetching input', icon: 'icon-download', color: '#89d2e2' }, WORKER_CONVERTING_INPUT: { value: 821, text: 'Converting input', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_CONVERTING_OUTPUT: { value: 822, text: 'Converting output', icon: 'icon-shuffle', color: '#92f5b5' }, WORKER_PUSHING_OUTPUT: { value: 823, text: 'Pushing output', icon: 'icon-upload', color: '#89d2e2' }, WORKER_CANCELING: { value: 824, text: 'Canceling', icon: 'icon-cancel', color: '#f89406' } });
Reduce number of tweets to reduce CPU compuation time of the unoptimised models
from flask import Blueprint, request, render_template from ..load import processing_results, api import string import tweepy twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static') ascii_chars = set(string.printable) ascii_chars.remove(' ') ascii_chars.add('...') def takeout_non_ascii(s): return list(filter(lambda x: x not in ascii_chars, s)) @twitter_mod.route('/twitter', methods=['GET', 'POST']) def twitter(): if request.method == 'POST': text = [] for tweet in tweepy.Cursor(api.search, request.form['topic'], lang='hi').items(50): temp = ''.join(takeout_non_ascii(tweet.text)) if not len(temp) in range(3): text.append(temp) data, emotion_sents, score, line_sentiment, text, length = processing_results(text) return render_template('projects/twitter.html', data=[data, emotion_sents, score, zip(text, line_sentiment), length]) else: return render_template('projects/twitter.html')
from flask import Blueprint, request, render_template from ..load import processing_results, api import string import tweepy twitter_mod = Blueprint('twitter', __name__, template_folder='templates', static_folder='static') ascii_chars = set(string.printable) ascii_chars.remove(' ') ascii_chars.add('...') def takeout_non_ascii(s): return list(filter(lambda x: x not in ascii_chars, s)) @twitter_mod.route('/twitter', methods=['GET', 'POST']) def twitter(): if request.method == 'POST': text = [] for tweet in tweepy.Cursor(api.search, request.form['topic'], lang='hi').items(100): temp = ''.join(takeout_non_ascii(tweet.text)) if not len(temp) in range(3): text.append(temp) data, emotion_sents, score, line_sentiment, text, length = processing_results(text) return render_template('projects/twitter.html', data=[data, emotion_sents, score, zip(text, line_sentiment), length]) else: return render_template('projects/twitter.html')
Use service client factory method for resource group command
from msrest import Serializer from ..commands import command, description from ._command_creation import get_service_client from .._profile import Profile @command('resource group list') @description('List resource groups') # TODO: waiting on Python Azure SDK bug fixes # @option('--tag-name -g <tagName>', L('the resource group's tag name')) # @option('--tag-value -g <tagValue>', L('the resource group's tag value')) # @option('--top -g <number>', L('Top N resource groups to retrieve')) def list_groups(args, unexpected): #pylint: disable=unused-argument from azure.mgmt.resource.resources import ResourceManagementClient, \ ResourceManagementClientConfiguration from azure.mgmt.resource.resources.models import ResourceGroup, ResourceGroupFilter rmc = get_service_client(ResourceManagementClient, ResourceManagementClientConfiguration) # TODO: waiting on Python Azure SDK bug fixes #group_filter = ResourceGroupFilter(args.get('tag-name'), args.get('tag-value')) #groups = rmc.resource_groups.list(filter=None, top=args.get('top')) groups = rmc.resource_groups.list() serializable = Serializer().serialize_data(groups, "[ResourceGroup]") return serializable
from msrest import Serializer from ..commands import command, description from .._profile import Profile @command('resource group list') @description('List resource groups') # TODO: waiting on Python Azure SDK bug fixes # @option('--tag-name -g <tagName>', L('the resource group's tag name')) # @option('--tag-value -g <tagValue>', L('the resource group's tag value')) # @option('--top -g <number>', L('Top N resource groups to retrieve')) def list_groups(args, unexpected): #pylint: disable=unused-argument from azure.mgmt.resource.resources import ResourceManagementClient, \ ResourceManagementClientConfiguration from azure.mgmt.resource.resources.models import ResourceGroup, ResourceGroupFilter rmc = ResourceManagementClient( ResourceManagementClientConfiguration(*Profile().get_login_credentials())) # TODO: waiting on Python Azure SDK bug fixes #group_filter = ResourceGroupFilter(args.get('tag-name'), args.get('tag-value')) #groups = rmc.resource_groups.list(filter=None, top=args.get('top')) groups = rmc.resource_groups.list() serializable = Serializer().serialize_data(groups, "[ResourceGroup]") return serializable
Include subfolders of `demo` and `test` folders for linting
'use strict'; var gulp = require('gulp'); var eslint = require('gulp-eslint'); var htmlExtract = require('gulp-html-extract'); var stylelint = require('gulp-stylelint'); gulp.task('lint', ['lint:js', 'lint:html', 'lint:css']); gulp.task('lint:js', function() { return gulp.src([ '*.js', 'test/**/*.js' ]) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('lint:html', function() { return gulp.src([ '*.html', 'demo/**/*.html', 'test/**/*.html' ]) .pipe(htmlExtract({ sel: 'script, code-example code', strip: true })) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('lint:css', function() { return gulp.src([ '*.html', 'demo/**/*.html', 'test/**/*.html' ]) .pipe(htmlExtract({ sel: 'style' })) .pipe(stylelint({ reporters: [ {formatter: 'string', console: true} ] })); });
'use strict'; var gulp = require('gulp'); var eslint = require('gulp-eslint'); var htmlExtract = require('gulp-html-extract'); var stylelint = require('gulp-stylelint'); gulp.task('lint', ['lint:js', 'lint:html', 'lint:css']); gulp.task('lint:js', function() { return gulp.src([ '*.js', 'test/*.js' ]) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('lint:html', function() { return gulp.src([ '*.html', 'demo/*.html', 'test/*.html' ]) .pipe(htmlExtract({ sel: 'script, code-example code', strip: true })) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('lint:css', function() { return gulp.src([ '*.html', 'demo/*.html', 'test/*.html' ]) .pipe(htmlExtract({ sel: 'style' })) .pipe(stylelint({ reporters: [ {formatter: 'string', console: true} ] })); });
Improve signal handling in balancer
package main import ( "fmt" "os" "os/exec" "os/signal" "syscall" "github.com/squaremo/ambergreen/balancer" "github.com/squaremo/ambergreen/balancer/fatal" ) func iptables(args []string) ([]byte, error) { return exec.Command("iptables", args...).CombinedOutput() } func main() { // Catch some signals for whcih we want to clean up on exit sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) fatalSink := fatal.New() i := balancer.Start(os.Args, fatalSink, iptables) exitCode := 0 var exitSignal os.Signal select { case err := <-fatalSink: fmt.Fprintln(os.Stderr, err) exitCode = 1 case exitSignal = <-sigs: exitCode = 2 } i.Stop() if sig, ok := exitSignal.(syscall.Signal); ok { // Now we have cleaned up, re-kill the process with // the signal in order to produce a signal exit // status: signal.Reset(sig) syscall.Kill(syscall.Getpid(), sig) } os.Exit(exitCode) }
package main import ( "fmt" "os" "os/exec" "os/signal" "syscall" "github.com/squaremo/ambergreen/balancer" "github.com/squaremo/ambergreen/balancer/fatal" ) func iptables(args []string) ([]byte, error) { return exec.Command("iptables", args...).CombinedOutput() } func main() { exitCode := 0 defer os.Exit(exitCode) sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) fatalSink := fatal.New() i := balancer.Start(os.Args, fatalSink, iptables) defer i.Stop() select { case <-sigs: case err := <-fatalSink: fmt.Fprintln(os.Stderr, err) exitCode = 1 } }
Fix test case for challenge2
package challenge2 import "testing" func TestCase1(t *testing.T) { cases := []struct { in int want bool }{ {120, false}, {166, true}, {141, true}, {79, false}, {26, true}, {158, true}, {174, false}, {141, true}, {169, true}, {129, true}, {199, false}, {27, false}, {57, true}, {183, true}, {173, false}, {5, false}, {111, true}, {145, true}, {59, false}, {64, false}, } for _, c := range cases { got := Run(c.in) if got != c.want { t.Errorf("Run(%v) == %v, want %v", c.in, got, c.want) } } }
package challenge2 import "testing" func TestCase1(t *testing.T) { cases := []struct { in int want bool }{ {120, false}, {166, true}, {141, true}, {79, false}, {26, true}, {158, true}, {174, false}, {141, true}, {169, true}, {129, false}, {199, false}, {27, false}, {57, true}, {183, true}, {173, false}, {5, false}, {111, true}, {145, true}, {59, false}, {64, false}, } for _, c := range cases { got := Run(c.in) if got != c.want { t.Errorf("Run(%v) == %v, want %v", c.in, got, c.want) } } }
Fix deprecated twig filter syntax
<?php namespace Liip\ImagineBundle\Templating; use Liip\ImagineBundle\Imagine\Cache\CacheManager; class ImagineExtension extends \Twig_Extension { /** * @var CacheManager */ private $cacheManager; /** * Constructor. * * @param CacheManager $cacheManager */ public function __construct(CacheManager $cacheManager) { $this->cacheManager = $cacheManager; } /** * {@inheritDoc} */ public function getFilters() { return array( new \Twig_SimpleFunction('imagine_filter', array($this, 'filter')), ); } /** * Gets the browser path for the image and filter to apply. * * @param string $path * @param string $filter * @param array $runtimeConfig * * @return \Twig_Markup */ public function filter($path, $filter, array $runtimeConfig = array()) { return $this->cacheManager->getBrowserPath($path, $filter, $runtimeConfig); } /** * {@inheritDoc} */ public function getName() { return 'liip_imagine'; } }
<?php namespace Liip\ImagineBundle\Templating; use Liip\ImagineBundle\Imagine\Cache\CacheManager; class ImagineExtension extends \Twig_Extension { /** * @var CacheManager */ private $cacheManager; /** * Constructor. * * @param CacheManager $cacheManager */ public function __construct(CacheManager $cacheManager) { $this->cacheManager = $cacheManager; } /** * {@inheritDoc} */ public function getFilters() { return array( 'imagine_filter' => new \Twig_Filter_Method($this, 'filter'), ); } /** * Gets the browser path for the image and filter to apply. * * @param string $path * @param string $filter * @param array $runtimeConfig * * @return \Twig_Markup */ public function filter($path, $filter, array $runtimeConfig = array()) { return $this->cacheManager->getBrowserPath($path, $filter, $runtimeConfig); } /** * {@inheritDoc} */ public function getName() { return 'liip_imagine'; } }
changed: Enable `referers` as parameter of GenerateSecuredAPIKey
package algoliasearch func checkGenerateSecuredAPIKey(params Map) error { if err := checkQuery(params, "restrictIndices", "restrictSources", "userToken", "validUntil", "referers", ); err != nil { return err } for k, v := range params { switch k { case "restrictIndices", "restrictSources", "userToken": if _, ok := v.(string); !ok { return invalidType(k, "string") } case "validUntil": if _, ok := v.(int); !ok { return invalidType(k, "int") } case "referers": if _, ok := v.([]string); !ok { return invalidType(k, "[]string") } default: // OK } } return nil } func checkKey(params Map) error { for k, v := range params { switch k { case "acl", "indexes", "referers": if _, ok := v.([]string); !ok { return invalidType(k, "[]string") } case "description", "queryParameters": if _, ok := v.(string); !ok { return invalidType(k, "string") } case "maxHitsPerQuery", "maxQueriesPerIPPerHour", "validity": if _, ok := v.(int); !ok { return invalidType(k, "int") } default: // OK } } return nil }
package algoliasearch func checkGenerateSecuredAPIKey(params Map) error { if err := checkQuery(params, "restrictIndices", "restrictSources", "userToken", "validUntil", ); err != nil { return err } for k, v := range params { switch k { case "restrictIndices", "restrictSources", "userToken": if _, ok := v.(string); !ok { return invalidType(k, "string") } case "validUntil": if _, ok := v.(int); !ok { return invalidType(k, "int") } default: // OK } } return nil } func checkKey(params Map) error { for k, v := range params { switch k { case "acl", "indexes", "referers": if _, ok := v.([]string); !ok { return invalidType(k, "[]string") } case "description", "queryParameters": if _, ok := v.(string); !ok { return invalidType(k, "string") } case "maxHitsPerQuery", "maxQueriesPerIPPerHour", "validity": if _, ok := v.(int); !ok { return invalidType(k, "int") } default: // OK } } return nil }
Make button list more fault tolerant
// ==UserScript== // @name Selfish Youtube // @namespace https://github.com/ASzc/selfish-youtube // @description On the watch page, remove the share panel. // @include http://youtube.com/watch* // @include http://*.youtube.com/watch* // @include https://youtube.com/watch* // @include https://*.youtube.com/watch* // ==/UserScript== var panelName = "action-panel-share"; // Remove panel var actionPanelShare = document.getElementById(panelName); actionPanelShare.parentNode.removeChild(actionPanelShare); // Remove buttons targeting the panel var buttons = document.body.getElementsByTagName("button"); if (buttons != null && buttons instanceof NodeList) { for (var i = 0; i < buttons.length; i++) { var button = buttons[i]; var buttonDTF = button.getAttribute("data-trigger-for"); if (buttonDTF != null && buttonDTF == panelName) { button.parentNode.removeChild(button); } } }
// ==UserScript== // @name Selfish Youtube // @namespace https://github.com/ASzc/selfish-youtube // @description On the watch page, remove the share panel. // @include http://youtube.com/watch* // @include http://*.youtube.com/watch* // @include https://youtube.com/watch* // @include https://*.youtube.com/watch* // ==/UserScript== var panelName = "action-panel-share"; // Remove panel var actionPanelShare = document.getElementById(panelName); actionPanelShare.parentNode.removeChild(actionPanelShare); // Remove buttons targeting the panel var buttons = document.body.getElementsByTagName("button"); for (var i = 0; i < buttons.length; i++) { var button = buttons[i]; var buttonDTF = button.getAttribute("data-trigger-for"); if (buttonDTF != null && buttonDTF == panelName) { button.parentNode.removeChild(button); } }
Make differential.querydiffs more liberal about arguments Summary: Fixes T12092. D17164 made `DiffQuery` more strict about arguments using modern conventions, but `differential.querydiffs` uses bizarre ancient conventions. Give it more modern conventions instead. Test Plan: Made a `querydiffs` call with only revision IDs. Reviewers: chad Reviewed By: chad Maniphest Tasks: T12092 Differential Revision: https://secure.phabricator.com/D17172
<?php final class DifferentialQueryDiffsConduitAPIMethod extends DifferentialConduitAPIMethod { public function getAPIMethodName() { return 'differential.querydiffs'; } public function getMethodDescription() { return pht('Query differential diffs which match certain criteria.'); } protected function defineParamTypes() { return array( 'ids' => 'optional list<uint>', 'revisionIDs' => 'optional list<uint>', ); } protected function defineReturnType() { return 'list<dict>'; } protected function execute(ConduitAPIRequest $request) { $ids = $request->getValue('ids', array()); $revision_ids = $request->getValue('revisionIDs', array()); if (!$ids && !$revision_ids) { // This method just returns nothing if you pass no constraints because // pagination hadn't been invented yet in 2008 when this method was // written. return array(); } $query = id(new DifferentialDiffQuery()) ->setViewer($request->getUser()) ->needChangesets(true); if ($ids) { $query->withIDs($ids); } if ($revision_ids) { $query->withRevisionIDs($revision_ids); } $diffs = $query->execute(); return mpull($diffs, 'getDiffDict', 'getID'); } }
<?php final class DifferentialQueryDiffsConduitAPIMethod extends DifferentialConduitAPIMethod { public function getAPIMethodName() { return 'differential.querydiffs'; } public function getMethodDescription() { return pht('Query differential diffs which match certain criteria.'); } protected function defineParamTypes() { return array( 'ids' => 'optional list<uint>', 'revisionIDs' => 'optional list<uint>', ); } protected function defineReturnType() { return 'list<dict>'; } protected function execute(ConduitAPIRequest $request) { $ids = $request->getValue('ids', array()); $revision_ids = $request->getValue('revisionIDs', array()); $diffs = array(); if ($ids || $revision_ids) { $diffs = id(new DifferentialDiffQuery()) ->setViewer($request->getUser()) ->withIDs($ids) ->withRevisionIDs($revision_ids) ->needChangesets(true) ->execute(); } return mpull($diffs, 'getDiffDict', 'getID'); } }
Fix the __file__ is not defined bug
#!/usr/bin/env python """ Create wordcloud with Arabic =============== Generating a wordcloud from Arabic text Dependencies: - bidi.algorithm - arabic_reshaper Dependencies installation: pip install python-bidi arabic_reshape """ import os import codecs from wordcloud import WordCloud import arabic_reshaper from bidi.algorithm import get_display # get data directory (using getcwd() is needed to support running example in generated IPython notebook) d = os.path.dirname(__file__) if "__file__" in locals() else os.getcwd() # Read the whole text. f = codecs.open(os.path.join(d, 'arabicwords.txt'), 'r', 'utf-8') # Make text readable for a non-Arabic library like wordcloud text = arabic_reshaper.reshape(f.read()) text = get_display(text) # Generate a word cloud image wordcloud = WordCloud(font_path='fonts/NotoNaskhArabic/NotoNaskhArabic-Regular.ttf').generate(text) # Export to an image wordcloud.to_file("arabic_example.png")
#!/usr/bin/env python """ Create wordcloud with Arabic =============== Generating a wordcloud from Arabic text Dependencies: - bidi.algorithm - arabic_reshaper Dependencies installation: pip install python-bidi arabic_reshape """ from os import path import codecs from wordcloud import WordCloud import arabic_reshaper from bidi.algorithm import get_display d = path.dirname(__file__) # Read the whole text. f = codecs.open(path.join(d, 'arabicwords.txt'), 'r', 'utf-8') # Make text readable for a non-Arabic library like wordcloud text = arabic_reshaper.reshape(f.read()) text = get_display(text) # Generate a word cloud image wordcloud = WordCloud(font_path='fonts/NotoNaskhArabic/NotoNaskhArabic-Regular.ttf').generate(text) # Export to an image wordcloud.to_file("arabic_example.png")
Set USE_TZ in test settings
""" Test Django settings """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'fake-key' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'chatterbot.ext.django_chatterbot', 'tests_django', ] CHATTERBOT = { 'name': 'Test Django ChatterBot', 'trainer': 'chatterbot.trainers.ChatterBotCorpusTrainer', 'training_data': [ 'chatterbot.corpus.english.greetings' ], 'initialize': False } ROOT_URLCONF = 'chatterbot.ext.django_chatterbot.urls' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } USE_TZ = True
""" Test Django settings """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'fake-key' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'chatterbot.ext.django_chatterbot', 'tests_django', ] CHATTERBOT = { 'name': 'Test Django ChatterBot', 'trainer': 'chatterbot.trainers.ChatterBotCorpusTrainer', 'training_data': [ 'chatterbot.corpus.english.greetings' ], 'initialize': False } ROOT_URLCONF = 'chatterbot.ext.django_chatterbot.urls' MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
Raise pypeSyntaxError in pype test
from pytest import raises from pype.lexer import lexer from pype.pipeline import Pipeline example_error_ppl='test/samples/example_error.ppl' example0_ppl='test/samples/example0.ppl' example0_token='test/samples/example0.tokens' example1_ppl='test/samples/example1.ppl' example1_token='test/samples/example1.tokens' def test_lexer(): lexer.input(open(example1_ppl).read()) output=open(example1_token) for token, line in zip(lexer, output): assert str(token) == line.strip() lexer.input(open(example_error_ppl).read()) for token in lexer: print (token) def test_example0(): with raises(PypeSyntaxError): t=Pipeline(example0_ppl) def test_example1(): with raises(PypeSyntaxError): t=Pipeline(example1_ppl)
from pype.lexer import lexer from pype.pipeline import Pipeline example_error_ppl='test/samples/example_error.ppl' example0_ppl='test/samples/example0.ppl' example0_token='test/samples/example0.tokens' example1_ppl='test/samples/example1.ppl' example1_token='test/samples/example1.tokens' def test_lexer(): lexer.input(open(example1_ppl).read()) output=open(example1_token) for token, line in zip(lexer, output): assert str(token) == line.strip() lexer.input(open(example_error_ppl).read()) for token in lexer: print (token) def test_example0(): t=Pipeline(example0_ppl) def test_example1(): t=Pipeline(example1_ppl)
Correct pytest setup and teardown
import pytest from tests import base from buildercore import cfngen, project import logging LOG = logging.getLogger(__name__) logging.disable(logging.NOTSET) # re-enables logging during integration testing # Depends on talking to AWS. class TestValidationFixtures(base.BaseCase): def test_validation(self): "dummy projects and their alternative configurations pass validation" for pname in project.aws_projects().keys(): cfngen.validate_project(pname) class TestValidationElife(): @classmethod def setup_class(cls): # HERE BE DRAGONS # resets the testing config.SETTINGS_FILE we set in the base.BaseCase class base.switch_out_test_settings() @classmethod def teardown_class(cls): base.switch_in_test_settings() @pytest.mark.parametrize("project_name", project.aws_projects().keys()) def test_validation_elife_projects(self, project_name, filter_project_name): "elife projects (and their alternative configurations) that come with the builder pass validation" if filter_project_name: if project_name != filter_project_name: pytest.skip("Filtered out through filter_project_name") cfngen.validate_project(project_name)
import pytest from tests import base from buildercore import cfngen, project import logging LOG = logging.getLogger(__name__) logging.disable(logging.NOTSET) # re-enables logging during integration testing # Depends on talking to AWS. class TestValidationFixtures(base.BaseCase): def test_validation(self): "dummy projects and their alternative configurations pass validation" for pname in project.aws_projects().keys(): cfngen.validate_project(pname) class TestValidationElife(): def setUp(self): # HERE BE DRAGONS # resets the testing config.SETTINGS_FILE we set in the base.BaseCase class base.switch_out_test_settings() def tearDown(self): base.switch_in_test_settings() @pytest.mark.parametrize("project_name", project.aws_projects().keys()) def test_validation_elife_projects(self, project_name, filter_project_name): "elife projects (and their alternative configurations) that come with the builder pass validation" if filter_project_name: if project_name != filter_project_name: pytest.skip("Filtered out through filter_project_name") cfngen.validate_project(project_name)
Tag version 0.5 with bytes/text fix
#!/usr/bin/env python # coding: utf-8 from setuptools import setup setup( name='requests-jwt', version='0.5', url='https://github.com/tgs/requests-jwt', modules=['requests_jwt'], install_requires=[ 'requests', 'PyJWT' ], tests_require=['httpretty'], test_suite='tests.suite', provides=[ 'requests_jwt' ], author='Thomas Grenfell Smith', author_email='thomathom@gmail.com', description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.', license='ISC', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", 'License :: OSI Approved :: ISC License (ISCL)', ], )
#!/usr/bin/env python # coding: utf-8 from setuptools import setup setup( name='requests-jwt', version='0.4', url='https://github.com/tgs/requests-jwt', modules=['requests_jwt'], install_requires=[ 'requests', 'PyJWT' ], tests_require=['httpretty'], test_suite='tests.suite', provides=[ 'requests_jwt' ], author='Thomas Grenfell Smith', author_email='thomathom@gmail.com', description='This package allows for HTTP JSON Web Token (JWT) authentication using the requests library.', license='ISC', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", 'License :: OSI Approved :: ISC License (ISCL)', ], )
Revert to original solution for vcf type determination
package com.hartwig.healthchecks.nesbit.extractor; import com.hartwig.healthchecks.nesbit.model.VCFType; import org.jetbrains.annotations.NotNull; final class VCFExtractorFunctions { private static final int ALT_INDEX = 4; private static final int REF_INDEX = 3; private static final String MULTIPLE_ALTS_IDENTIFIER = ","; private VCFExtractorFunctions() { } @NotNull static VCFType getVCFType(@NotNull final String[] values) { final String refValue = values[REF_INDEX]; final String altValue = values[ALT_INDEX]; final String[] allAlts = altValue.split(MULTIPLE_ALTS_IDENTIFIER); VCFType type = VCFType.SNP; for (String alt : allAlts) { if (refValue.length() != alt.length()) { type = VCFType.INDELS; } } return type; } }
package com.hartwig.healthchecks.nesbit.extractor; import com.hartwig.healthchecks.nesbit.model.VCFType; import org.jetbrains.annotations.NotNull; final class VCFExtractorFunctions { private static final int ALT_INDEX = 4; private static final int REF_INDEX = 3; private static final String MULTIPLE_ALTS_IDENTIFIER = ","; private VCFExtractorFunctions() { } @NotNull static VCFType getVCFType(@NotNull final String[] values) { final String refValue = values[REF_INDEX]; final String altValue = values[ALT_INDEX]; final String[] allAlts = altValue.split(MULTIPLE_ALTS_IDENTIFIER); return allAlts[0].length() != refValue.length() ? VCFType.INDELS : VCFType.SNP; // VCFType type = VCFType.SNP; // // for (String alt : allAlts) { // if (refValue.length() != alt.length()) { // type = VCFType.INDELS; // } // } // return type; } }
Delete commented out loaddata command. git-svn-id: d73fdb991549f9d1a0affa567d55bb0fdbd453f3@8436 f04a3889-0f81-4131-97fb-bc517d1f583d
from fabric.api import local, run from fabric.colors import green from fabric.contrib import django from fabric.decorators import task @task def run_tests(test='src'): django.settings_module('texas_choropleth.settings.test') local('./src/manage.py test {0}'.format(test)) def build(): print(green("[ Installing Bowering Components ]")) local('bower install --allow-root --config.interactive=false') print(green("\n[ Syncing Database ]")) local('./src/manage.py syncdb --noinput') print(green("\n[ Running Database Migrations ]")) local('./src/manage.py migrate') print(green("\n[ Loading Fixtures ]")) local('./src/manage.py loaddata texas.json') local('./src/manage.py loaddata palettes.json') @task def build_dev(): django.settings_module('texas_choropleth.settings.local') build() @task def build_prod(): django.settings_module('texas_choropleth.settings.production') build() print(green("\n [ Collecting Staticfiles ]")) local('./src/manage.py collectstatic --noinput')
from fabric.api import local, run from fabric.colors import green from fabric.contrib import django from fabric.decorators import task @task def run_tests(test='src'): django.settings_module('texas_choropleth.settings.test') local('./src/manage.py test {0}'.format(test)) def build(): print(green("[ Installing Bowering Components ]")) local('bower install --allow-root --config.interactive=false') print(green("\n[ Syncing Database ]")) local('./src/manage.py syncdb --noinput') print(green("\n[ Running Database Migrations ]")) local('./src/manage.py migrate') print(green("\n[ Loading Fixtures ]")) local('./src/manage.py loaddata texas.json') # local('./src/manage.py loaddata licenses.json') local('./src/manage.py loaddata palettes.json') @task def build_dev(): django.settings_module('texas_choropleth.settings.local') build() @task def build_prod(): django.settings_module('texas_choropleth.settings.production') build() print(green("\n [ Collecting Staticfiles ]")) local('./src/manage.py collectstatic --noinput')
Fix typo in POST request
/* eslint-env jquery */ start(); function start () { 'use strict'; $(document).ready(() => { $('form').submit(event => { event.preventDefault(); const username = $('#username').val(); const password = $('#password').val(); const loginObj = { username, password }; console.log(loginObj); $.post({ url: '/login', data: JSON.stringify(loginObj), dataType: 'JSON', contentType: "application/json; charset=utf-8", success: (result) => console.log(result) }); }); }); }
/* eslint-env jquery */ start(); function start () { 'use strict'; $(document).ready(() => { $('form').submit(event => { event.preventDefault(); const username = $('#username').val(); const password = $('#password').val(); const loginObj = { username, password }; console.log(loginObj); $.post({ url: '/login', data: JSON.stringify(loginObj), dataType: 'JSON', contentType: "application/json; charset=utf-8", sucess: (result) => console.log(result) }); }); }); }
Split call into two lines
package beaform.gui; import java.awt.BorderLayout; import java.awt.Component; import javax.swing.JPanel; import javax.swing.JScrollPane; import beaform.gui.debug.DebugUtilities; /** * This class represents the main panel where all views will work in. * * @author Steven Post * */ public class MainPanel extends JPanel { /** A serial */ private static final long serialVersionUID = 1207348877338520359L; /** An inner panel for the actual content */ private final JPanel panel = new JPanel(new BorderLayout()); /** A scroll panel */ private final JScrollPane scrollPane = new JScrollPane(this.panel); /** * Constructor */ public MainPanel() { super(new BorderLayout()); this.add(this.scrollPane); } /** * This method will replace the current active window. * * @param comp The new window to display */ public void replaceWindow(final Component comp) { if (this.panel.getComponentCount() > 0) { this.panel.remove(0); } this.panel.add(comp); this.panel.revalidate(); } /** * A method to assist in debugging. * It draws borders on all descendant JPanel objects. */ public void enableDebugBorders() { final JPanel panel = this.panel; DebugUtilities.drawBorders(panel); } }
package beaform.gui; import java.awt.BorderLayout; import java.awt.Component; import javax.swing.JPanel; import javax.swing.JScrollPane; import beaform.gui.debug.DebugUtilities; /** * This class represents the main panel where all views will work in. * * @author Steven Post * */ public class MainPanel extends JPanel { /** A serial */ private static final long serialVersionUID = 1207348877338520359L; /** An inner panel for the actual content */ private final JPanel panel = new JPanel(new BorderLayout()); /** A scroll panel */ private final JScrollPane scrollPane = new JScrollPane(this.panel); /** * Constructor */ public MainPanel() { super(new BorderLayout()); this.add(this.scrollPane); } /** * This method will replace the current active window. * * @param comp The new window to display */ public void replaceWindow(final Component comp) { if (this.panel.getComponentCount() > 0) { this.panel.remove(0); } this.panel.add(comp); this.panel.revalidate(); } /** * A method to assist in debugging. * It draws borders on all descendant JPanel objects. */ public void enableDebugBorders() { DebugUtilities.drawBorders(this.panel); } }
Fix the counter concatenating when updating donation amount animate counter when donated
Template.logo.helpers({ logoUrl: function(){ return Settings.get("logoUrl"); }, // Add total counter totalDonation: function() { $('span.total-counter').text(''); var collection = 0; var posts = Posts.find().fetch(); for (i = 0; i < posts.length; i++) { collection += posts[i].Donations; }; setTimeout(function() { $('.total-counter').each(function () { $(this).prop('Counter',0).animate({ Counter: collection }, { duration: 4000, easing: 'swing', step: function (now) { $(this).text(Math.ceil(now)); } }); }); }, 1); return collection; } }); Template.logo.onRendered(function () { $(".side-nav .logo-text").quickfit({ min: 16, max: 40, truncate: false }); });
Template.logo.helpers({ logoUrl: function(){ return Settings.get("logoUrl"); }, // Add total counter totalDonation: function() { var collection = 0; var posts = Posts.find().fetch(); for (i = 0; i < posts.length; i++) { // debugger; collection += posts[i].Donations; }; //alert(collection); return collection; } }); Template.logo.onRendered(function () { $(".side-nav .logo-text").quickfit({ min: 16, max: 40, truncate: false }); //Henry's version, and is moved as a callback function to the custom_post_vote.js. //Once the a new donation goes through, the counter updates. $('.total-counter').each(function () { $(this).text(now); $(this).prop('Counter',0).animate({ Counter: $(this).text() }, { duration: 4000, easing: 'swing', step: function (now) { $(this).text(Math.ceil(now)); } }); }); });
Set command reducer memo to undefined
import {Command} from '@grid/core/command'; import {noop} from '../utility'; export class Composite { static func(list, reduce = noop, memo = null) { return (...args) => { for (const f of list) { memo = reduce(memo, f(...args)); } return memo; }; } static command(list) { return new Command({ source: 'composite', canExecute: (...args) => { return list.reduce((memo, cmd) => memo || cmd.canExecute(...args), false); }, execute: (...args) => { return list .filter(cmd => cmd.canExecute(...args)) .reduce((memo, cmd) => cmd.execute(...args) || memo); } }); } static list(list) { return list.reduce((memo, xs) => memo.concat(xs), []); } static object(list, memo = {}) { return Object.assign(memo, ...list); } }
import {Command} from '@grid/core/command'; import {noop} from '../utility'; export class Composite { static func(list, reduce = noop, memo = null) { return (...args) => { for (const f of list) { memo = reduce(memo, f(...args)); } return memo; }; } static command(list) { return new Command({ source: 'composite', canExecute: (...args) => { return list.reduce((memo, cmd) => memo || cmd.canExecute(...args), false); }, execute: (...args) => { return list .filter(cmd => cmd.canExecute(...args)) .reduce((memo, cmd) => cmd.execute(...args) || memo, false); } }); } static list(list) { return list.reduce((memo, xs) => memo.concat(xs), []); } static object(list, memo = {}) { return Object.assign(memo, ...list); } }
Trim email address before submitting to API.
(function (window, document, $) { var app = window.devsite; app.pages.signup = function () { var $btn = $('.notify-btn'); $btn.on('click', function() { $btn.addClass('disabled'); $.post('/api/developer-plus/coming-soon', { email: $('input[name="email"]').val().trim() }, function(data, status, xhr) { $btn.addClass('btn-success') .removeClass('btn-primary') .text('Success!'); setTimeout(function () { $('input[name="email"]').val(''); $btn.addClass('btn-primary') .removeClass('btn-success disabled') .text('Notify Me!'); }, 2500); }) .fail(function(e) { $btn.addClass('btn-danger') .removeClass('btn-primary') .text('Error'); setTimeout(function() { $btn.addClass('btn-primary') .removeClass('btn-danger disabled') .text('Notify Me!'); }, 2500); }); }); }; }(window, document, jQuery));
(function (window, document, $) { var app = window.devsite; app.pages.signup = function () { var $btn = $('.notify-btn'); $btn.on('click', function() { $btn.addClass('disabled'); $.post('/api/developer-plus/coming-soon', { email: $('input[name="email"]').val() }, function(data, status, xhr) { $btn.addClass('btn-success') .removeClass('btn-primary') .text('Success!'); setTimeout(function () { $('input[name="email"]').val(''); $btn.addClass('btn-primary') .removeClass('btn-success disabled') .text('Notify Me!'); }, 2500); }) .fail(function(e) { $btn.addClass('btn-danger') .removeClass('btn-primary') .text('Error'); setTimeout(function() { $btn.addClass('btn-primary') .removeClass('btn-danger disabled') .text('Notify Me!'); }, 2500); }); }); }; }(window, document, jQuery));
Fix test after JUnit upgrade
package patterns.document; import java.util.HashMap; import java.util.Map; import java.util.OptionalDouble; import java.util.OptionalInt; import org.junit.Assert; import org.junit.Test; public class CarTest { private static final double DELTA = 0.000001; private static final double PRICE = 100.0; private static final String MODEL = "Audi"; private static final String COLOR = "red"; private static final int WHEELS_COUNT = 4; @Test public void testCreateCar() throws Exception { Map<String, Object> entries = new HashMap<>(); Car car = new Car(entries); car.put(ColorTrait.KEY, COLOR); car.put(ModelTrait.KEY, MODEL); car.put(PriceTrait.KEY, PRICE); car.put(WheelsTrait.KEY, WHEELS_COUNT); String color = car.getColor(); Assert.assertEquals(COLOR, color); String model = car.getModel(); Assert.assertEquals(MODEL, model); OptionalDouble price = car.getPrice(); Assert.assertEquals(PRICE, price.getAsDouble(), DELTA); OptionalInt wheels = car.getWheels(); Assert.assertEquals(WHEELS_COUNT, wheels.getAsInt()); } }
package patterns.document; import java.util.HashMap; import java.util.Map; import java.util.OptionalDouble; import java.util.OptionalInt; import org.junit.Test; import org.junit.Assert; public class CarTest { private static final double PRICE = 100.0; private static final String MODEL = "Audi"; private static final String COLOR = "red"; private static final int WHEELS_COUNT = 4; @Test public void testCreateCar() throws Exception { Map<String, Object> entries = new HashMap<>(); Car car = new Car(entries); car.put(ColorTrait.KEY, COLOR); car.put(ModelTrait.KEY, MODEL); car.put(PriceTrait.KEY, PRICE); car.put(WheelsTrait.KEY, WHEELS_COUNT); String color = car.getColor(); Assert.assertEquals(COLOR, color); String model = car.getModel(); Assert.assertEquals(MODEL, model); OptionalDouble price = car.getPrice(); Assert.assertEquals(PRICE, price.getAsDouble()); OptionalInt wheels = car.getWheels(); Assert.assertEquals(WHEELS_COUNT, wheels.getAsInt()); } }
Fix schema version for api demo
<?php return [ 'itemsPerPage' => 100, 'rootURL' => 'api/oparl/v1/', 'modelNamespace' => 'OParl\\Server\\Model\\', 'transformers' => [ 'serializer' => OParl\Server\API\Serializer::class, 'namespace' => 'OParl\\Server\\API\\Transformers', 'classPattern' => '[:modelName]Transformer', 'formatHelpers' => [ 'email' => 'EFrane\Transfugio\Transformers\Formatter\EMailURI', 'date' => 'EFrane\Transfugio\Transformers\Formatter\DateISO8601', 'datetime' => 'EFrane\Transfugio\Transformers\Formatter\DateTimeISO8601', 'url' => 'EFrane\Transfugio\Transformers\Formatter\HttpURI', ], 'recursionLimit' => 2, ], 'http' => [ 'format' => 'json_accept', 'enableCORS' => true, ], 'web' => [ 'documentationEnabled' => true, // Toggle the auto-documentation feature 'documentationType' => 'JSONSchema', 'documentationRoot' => '/storage/app/schema/1.0', ], ];
<?php return [ 'itemsPerPage' => 100, 'rootURL' => 'api/oparl/v1/', 'modelNamespace' => 'OParl\\Server\\Model\\', 'transformers' => [ 'serializer' => OParl\Server\API\Serializer::class, 'namespace' => 'OParl\\Server\\API\\Transformers', 'classPattern' => '[:modelName]Transformer', 'formatHelpers' => [ 'email' => 'EFrane\Transfugio\Transformers\Formatter\EMailURI', 'date' => 'EFrane\Transfugio\Transformers\Formatter\DateISO8601', 'datetime' => 'EFrane\Transfugio\Transformers\Formatter\DateTimeISO8601', 'url' => 'EFrane\Transfugio\Transformers\Formatter\HttpURI', ], 'recursionLimit' => 2, ], 'http' => [ 'format' => 'json_accept', 'enableCORS' => true, ], 'web' => [ 'documentationEnabled' => true, // Toggle the auto-documentation feature 'documentationType' => 'JSONSchema', 'documentationRoot' => '/storage/app/hub_sync/oparl_spec/schema/', ], ];
Remove a comment that wasn't needed anymore.
$(function () { $(".boundBoxSize").on("click", function () { var currentValue = $(this).val(); var grnsightContainerClass = "grnsight-container " + currentValue; if (!$(".grnsight-container").hasClass(currentValue)) { $(".grnsight-container").attr("class", grnsightContainerClass); $("#reload").trigger("click"); }; }); $("#enableScroll").on("click", function () { if ($(this).prop("checked")) { $(".grnTest").css("overflow", "auto"); $(".grnTest").css("height", ""); $(".grnTest").css("width", ""); } else { $(".grnTest").css("overflow", "visible"); $(".grnTest").css("height", $(".grnsight-container").height()); $(".grnTest").css("width", $(".grnsight-container").width()); } }); })
$(function () { $(".boundBoxSize").on("click", function () { var currentValue = $(this).val(); var grnsightContainerClass = "grnsight-container " + currentValue; if (!$(".grnsight-container").hasClass(currentValue)) { $(".grnsight-container").attr("class", grnsightContainerClass); $("#reload").trigger("click"); }; }); $("#enableScroll").on("click", function () { if ($(this).prop("checked")) { $(".grnTest").css("overflow", "auto"); $(".grnTest").css("height", ""); $(".grnTest").css("width", ""); } else { $(".grnTest").css("overflow", "visible"); $(".grnTest").css("height", $(".grnsight-container").height()); $(".grnTest").css("width", $(".grnsight-container").width()); } }); /*$("#enableScroll").on("click", function () { $(".grnsight-container").toggleClass("containerScroll"); });*/ })
Change project factory default values
import factory from django.contrib.auth.models import User from accounts.tests.factories import UserFactory from .. import models class OrganizationFactory(factory.DjangoModelFactory): """Organization factory""" FACTORY_FOR = models.Organization name = factory.Sequence(lambda n: 'organization {}'.format(n)) @factory.post_generation def users(self, create, extracted, **kwargs): if not create: return if extracted: for user in extracted: self.users.add(user) else: self.users = UserFactory.create_batch(10) class ProjectFactory(factory.DjangoModelFactory): """Project factory""" FACTORY_FOR = models.Project name = factory.Sequence(lambda n: 'project{}'.format(n)) url = factory.Sequence(lambda n: 'http://test{}.com'.format(n)) organization = factory.SubFactory(OrganizationFactory) run_here = False @factory.sequence def owner(n): return User.objects.create_user('user{}'.format(n))
import factory from django.contrib.auth.models import User from accounts.tests.factories import UserFactory from .. import models class OrganizationFactory(factory.DjangoModelFactory): """Organization factory""" FACTORY_FOR = models.Organization name = factory.Sequence(lambda n: 'organization {}'.format(n)) @factory.post_generation def users(self, create, extracted, **kwargs): if not create: return if extracted: for user in extracted: self.users.add(user) else: self.users = UserFactory.create_batch(10) class ProjectFactory(factory.DjangoModelFactory): """Project factory""" FACTORY_FOR = models.Project name = factory.Sequence(lambda n: 'project{}'.format(n)) url = factory.Sequence(lambda n: 'http://test{}.com'.format(n)) organization = factory.SubFactory(OrganizationFactory) @factory.sequence def owner(n): return User.objects.create_user('user{}'.format(n))
Revert to returning the exportUrl as String since a relative href is not a valid Java URL.
/** * Copyright (C) 2009-2016 Simonsoft Nordic AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.simonsoft.cms.item.export; import java.nio.file.Path; public interface CmsExportWriter { void prepare(CmsExportJob job); boolean isReady(); void write(); public interface LocalFileSystem extends CmsExportWriter { Path getExportPath(); } public interface ResultUrl extends CmsExportWriter { /** * @return an href to the exported file, must be String to support a server-relative reference. */ String getExportUrl(); } }
/** * Copyright (C) 2009-2016 Simonsoft Nordic AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.simonsoft.cms.item.export; import java.net.URL; import java.nio.file.Path; public interface CmsExportWriter { void prepare(CmsExportJob job); boolean isReady(); void write(); public interface LocalFileSystem extends CmsExportWriter { Path getExportPath(); } public interface ResultUrl extends CmsExportWriter { URL getExportUrl(); } }
FIX visibility of forecast button Default value for cutoff date is end date of previous fiscal year
# Copyright 2016-2019 Akretion France # Copyright 2018-2019 Camptocamp # @author: Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Invoice Start End Dates", "version": "13.0.1.0.0", "category": "Accounting & Finance", "license": "AGPL-3", "summary": "Adds start/end dates on invoice/move lines", "author": "Akretion,Odoo Community Association (OCA)", "maintainers": ["alexis-via"], "website": "https://github.com/OCA/account-closing", "depends": ["account",], "data": ["views/account_move.xml", "views/product.xml",], "demo": ["demo/product_demo.xml"], "installable": True, }
# Copyright 2016-2019 Akretion France # Copyright 2018-2019 Camptocamp # @author: Alexis de Lattre <alexis.delattre@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { "name": "Account Invoice Start End Dates", "version": "13.0.1.0.0", "category": "Accounting & Finance", "license": "AGPL-3", "summary": "Adds start/end dates on invoice/move lines", "author": "Akretion,Odoo Community Association (OCA)", "website": "https://github.com/OCA/account-closing", "depends": ["account",], "data": ["views/account_move.xml", "views/product.xml",], "demo": ["demo/product_demo.xml"], "installable": True, }
Add maxlength to argument form title and abstract
from colander import Length from deform import Form from deform.widget import TextAreaWidget, TextInputWidget from ekklesia_portal.helper.contract import Schema, string_property from ekklesia_portal.helper.translation import _ TITLE_MAXLENGTH = 80 ABSTRACT_MAXLENGTH = 160 class ArgumentSchema(Schema): title = string_property(title=_('title'), validator=Length(min=5, max=TITLE_MAXLENGTH)) abstract = string_property(title=_('abstract'), validator=Length(min=5, max=ABSTRACT_MAXLENGTH)) details = string_property(title=_('details'), validator=Length(min=10, max=4096), missing='') argument_widgets = { 'title': TextInputWidget(attributes={'maxlength': TITLE_MAXLENGTH}), 'abstract': TextAreaWidget(rows=2, attributes={'maxlength': ABSTRACT_MAXLENGTH}), 'details': TextAreaWidget(rows=4) } class ArgumentForm(Form): def __init__(self, request, action): super().__init__(ArgumentSchema(), request, action, buttons=("submit", )) self.set_widgets(argument_widgets)
from colander import Length from deform import Form from deform.widget import TextAreaWidget from ekklesia_portal.helper.contract import Schema, string_property from ekklesia_portal.helper.translation import _ class ArgumentSchema(Schema): title = string_property(title=_('title'), validator=Length(min=5, max=80)) abstract = string_property(title=_('abstract'), validator=Length(min=5, max=140)) details = string_property(title=_('details'), validator=Length(min=10, max=4096), missing='') argument_widgets = { 'abstract': TextAreaWidget(rows=2), 'details': TextAreaWidget(rows=4) } class ArgumentForm(Form): def __init__(self, request, action): super().__init__(ArgumentSchema(), request, action, buttons=("submit", )) self.set_widgets(argument_widgets)
Add solution to problem 20
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.app.problem20; /** * Given two integers passed as parameter, can you write a method to multiply it and return the * result without use "*" operator? * * @author Pedro Vicente Gómez Sánchez. */ public class MultiplicationWithoutMultiply { /** * Iterative solution to this problem. This algorithm is based on the multiplication definition * as * a consecutive sum. The complexity order of this algorithm in time terms is O(N) where N is * equals to n1 parameter. In space terms the complexity order of this algorithm is O(1) because * we are not using any additional data structure related to the input size. */ public int calculate(int n1, int n2) { int result = 0; boolean negative = n1 < 0; n1 = Math.abs(n1); for (int i = 0; i < n1; i++) { result += n2; } if (negative) { result *= -1; } return result; } }
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * 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.github.pedrovgs.app.problem20; /** * Given two integers passed as parameter, can you write a method to multiply it and return the * result without use "*" operator? * * @author Pedro Vicente Gómez Sánchez. */ public class MultiplicationWithoutMultiply { public int calculate(int n1, int n2) { return 0; } }
Change to keys and values functions from map for labels and visits and countries
'use strict'; dataDashboard.controller('MainCtrl', ['$scope', 'Traffic', function ($scope, Traffic) { var getAllTraffic = function() { Traffic.getTraffic() .then(function(data) { if (data) { $scope.trafficList = data; // console.log($scope.trafficList); $scope.countryCount = _.countBy($scope.trafficList, 'country'); // console.log($scope.countryCount); $scope.countries = _.keys($scope.countryCount); $scope.visits = _.values($scope.countryCount); } }, function(error) { console.log(error); }); }(); }]);
'use strict'; dataDashboard.controller('MainCtrl', ['$scope', 'Traffic', function ($scope, Traffic) { var getAllTraffic = function() { Traffic.getTraffic() .then(function(data) { if (data) { $scope.trafficList = data; // console.log($scope.trafficList); $scope.countryCount = _.countBy($scope.trafficList, 'country'); // console.log($scope.countryCount); $scope.countries = _.map($scope.countryCount, function(a, b) {return b ? b : "Unknown";}); $scope.visits = _.map($scope.countryCount, function(a, b) {return a;}); } }, function(error) { console.log(error); }); }(); }]);
Bump to 2.0 to get past old django-compress
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-compress', version='2.0.0', description='A Django app for compressing CSS and JS', author='Michael Crute', author_email='mike@finiteloopsoftware.com', url='http://github.com/finiteloopsoftware/django-compress/', long_description=open('README.rst', 'r').read(), packages=[ 'compress', 'compress.templatetags', ], package_data={ 'compress': ['templates/compress/*'], }, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-compress', version='1.0.0', description='A Django app for compressing CSS and JS', author='Michael Crute', author_email='mike@finiteloopsoftware.com', url='http://github.com/finiteloopsoftware/django-compress/', long_description=open('README.rst', 'r').read(), packages=[ 'compress', 'compress.templatetags', ], package_data={ 'compress': ['templates/compress/*'], }, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
Increase size of `password` column
# -*- coding: utf-8 -*- import sys from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base SQLALCHEMY_DATABASE_URI = 'sqlite:///accounts.db' Base = declarative_base() def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(SQLALCHEMY_DATABASE_URI) class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True) username = Column(String(30), unique=True) password = Column(String(512)) email = Column(String(50)) def __repr__(self): return '<User %r>' % self.username engine = db_connect() # Connect to database Base.metadata.create_all(engine) # Create models
# -*- coding: utf-8 -*- import sys from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base SQLALCHEMY_DATABASE_URI = 'sqlite:///accounts.db' Base = declarative_base() def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(SQLALCHEMY_DATABASE_URI) class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True) username = Column(String(30), unique=True) password = Column(String(30)) email = Column(String(50)) def __repr__(self): return '<User %r>' % self.username engine = db_connect() # Connect to database Base.metadata.create_all(engine) # Create models
Change cucumber test tag to not run by default
/** * Copyright Microsoft Corporation * * 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.microsoft.windowsazure; import cucumber.api.junit.Cucumber; import cucumber.api.CucumberOptions; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions( format = {"html:target/cucumber-html-report", "json:target/cucumber-json-report.json"}, tags = {"@livetest"}) public class RunCukesTest { }
/** * Copyright Microsoft Corporation * * 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.microsoft.windowsazure; import cucumber.api.junit.Cucumber; import cucumber.api.CucumberOptions; import org.junit.runner.RunWith; @RunWith(Cucumber.class) @CucumberOptions( format = {"html:target/cucumber-html-report", "json:target/cucumber-json-report.json"}, tags = {"~@ignore"}) public class RunCukesTest { }
Add comments explaining prediction data structure
# Based on modeprediction.py import emission.core.wrapper.wrapperbase as ecwb # The "prediction" data structure is a list of label possibilities, each one consisting of a set of labels and a probability: # [ # {"labels": {"labeltype1": "labelvalue1", "labeltype2": "labelvalue2"}, "p": 0.61}, # {"labels": {"labeltype1": "labelvalue3", "labeltype2": "labelvalue4"}, "p": 0.27}, # ... # ] class Labelprediction(ecwb.WrapperBase): props = {"trip_id": ecwb.WrapperBase.Access.WORM, # the trip that this is part of "prediction": ecwb.WrapperBase.Access.WORM, # What we predict -- see above "start_ts": ecwb.WrapperBase.Access.WORM, # start time for the prediction, so that it can be captured in time-based queries, e.g. to reset the pipeline "end_ts": ecwb.WrapperBase.Access.WORM, # end time for the prediction, so that it can be captured in time-based queries, e.g. to reset the pipeline } enums = {} geojson = {} local_dates = {} def _populateDependencies(self): pass
# Based on modeprediction.py import emission.core.wrapper.wrapperbase as ecwb class Labelprediction(ecwb.WrapperBase): props = {"trip_id": ecwb.WrapperBase.Access.WORM, # the trip that this is part of "prediction": ecwb.WrapperBase.Access.WORM, # What we predict "start_ts": ecwb.WrapperBase.Access.WORM, # start time for the prediction, so that it can be captured in time-based queries, e.g. to reset the pipeline "end_ts": ecwb.WrapperBase.Access.WORM, # end time for the prediction, so that it can be captured in time-based queries, e.g. to reset the pipeline } enums = {} geojson = {} local_dates = {} def _populateDependencies(self): pass
Fix indent, PEP-8 style and remove dup import.
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if (not self.request.user.is_authenticated() and not hasattr(self.request.user, 'organisation_id')): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions')
from django.views.generic import RedirectView from django.views.generic.detail import SingleObjectMixin from django.contrib.auth import login, authenticate, login from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse class BaseAuthView(SingleObjectMixin, RedirectView): def get_redirect_url(self, *args, **kwargs): if not self.request.user.is_authenticated() \ and not hasattr(self.request.user, 'organisation_id'): auth_user = authenticate(auth_token=self.kwargs['token']) if not auth_user: raise PermissionDenied() login(self.request, auth_user) return reverse('organisation_questions')
Add plt to rio_insp locals.
import code import collections import logging import sys import matplotlib.pyplot as plt import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) def main(banner, dataset): def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read_band(source[1]) else: arr = source plt.imshow(arr, cmap=cmap) plt.show() def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read_band(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) code.interact( banner, local=dict( locals(), src=dataset, np=numpy, rio=rasterio, plt=plt)) return 0
import code import collections import logging import sys import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) def main(banner, dataset): def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ import matplotlib.pyplot as plt if isinstance(source, tuple): arr = source[0].read_band(source[1]) else: arr = source plt.imshow(arr, cmap=cmap) plt.show() def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read_band(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) code.interact( banner, local=dict(locals(), src=dataset, np=numpy, rio=rasterio)) return 0
Replace YAML parse function to parseFile
<?php namespace Misantron\Silex\Provider\Adapter; use Misantron\Silex\Provider\ConfigAdapter; use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Parser; /** * Class YamlConfigAdapter * @package Misantron\Silex\Provider\Adapter */ class YamlConfigAdapter extends ConfigAdapter { /** * @param \SplFileInfo $file * @return array */ protected function parse(\SplFileInfo $file): array { $this->assertLibraryInstalled(); try { $config = (new Parser())->parseFile($file->getRealPath()); } catch (ParseException $e) { throw new \RuntimeException('Unable to parse config file: ' . $e->getMessage()); } return $config; } /** * @return array */ protected function configFileExtensions(): array { return ['yml', 'yaml']; } /** * @throws \RuntimeException */ private function assertLibraryInstalled() { // @codeCoverageIgnoreStart if (!class_exists('Symfony\\Component\\Yaml\\Yaml')) { throw new \RuntimeException('Yaml parser component is not installed'); } // @codeCoverageIgnoreEnd } }
<?php namespace Misantron\Silex\Provider\Adapter; use Misantron\Silex\Provider\ConfigAdapter; use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Parser; /** * Class YamlConfigAdapter * @package Misantron\Silex\Provider\Adapter */ class YamlConfigAdapter extends ConfigAdapter { /** * @param \SplFileInfo $file * @return array */ protected function parse(\SplFileInfo $file): array { $this->assertLibraryInstalled(); try { $config = (new Parser())->parse(file_get_contents($file->getRealPath())); } catch (ParseException $e) { throw new \RuntimeException('Unable to parse config file: ' . $e->getMessage()); } return $config; } /** * @return array */ protected function configFileExtensions(): array { return ['yml', 'yaml']; } /** * @throws \RuntimeException */ private function assertLibraryInstalled() { // @codeCoverageIgnoreStart if (!class_exists('Symfony\\Component\\Yaml\\Yaml')) { throw new \RuntimeException('Yaml parser component is not installed'); } // @codeCoverageIgnoreEnd } }
Update graphic settings before renderer is created
import { isWebGLSupported } from './core/utils'; import CanvasRenderer from './core/renderers/canvas/CanvasRenderer'; import WebGLRenderer from './core/renderers/webgl/WebGLRenderer'; import settings from './core/settings'; import { SCALE_MODES } from './core/const'; export default class VisualServer { constructor() { this.is_initialized = false; this.renderer = null; } init(config) { if (this.is_initialized) { return; } this.is_initialized = true; if (config.scale_mode === 'linear') { settings.SCALE_MODE = SCALE_MODES.LINEAR; } else { settings.SCALE_MODE = SCALE_MODES.NEAREST; } if (!config.force_canvas && isWebGLSupported()) { this.renderer = new WebGLRenderer(config); } else { this.renderer = new CanvasRenderer(config); } } render(viewport) { this.renderer.render(viewport, undefined, true, undefined, true); } }
import { isWebGLSupported } from './core/utils'; import CanvasRenderer from './core/renderers/canvas/CanvasRenderer'; import WebGLRenderer from './core/renderers/webgl/WebGLRenderer'; import settings from './core/settings'; import { SCALE_MODES } from './core/const'; export default class VisualServer { constructor() { this.is_initialized = false; this.renderer = null; } init(config) { if (this.is_initialized) { return; } this.is_initialized = true; if (!config.force_canvas && isWebGLSupported()) { this.renderer = new WebGLRenderer(config); } else { this.renderer = new CanvasRenderer(config); } if (config.scale_mode === 'linear') { settings.SCALE_MODE = SCALE_MODES.LINEAR; } else { settings.SCALE_MODE = SCALE_MODES.NEAREST; } } render(viewport) { this.renderer.render(viewport, undefined, true, undefined, true); } }
Make committing with case-insensitive username possible
<?php /* Libre.fm -- a free network service for sharing your music listening habits Copyright (C) 2009 Libre.fm Project This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once('database.php'); function check_web_auth($username, $token, $timestamp, $api_key, $sk) { // Validates authentication using a web services token global $mdb2; } function check_standard_auth($username, $token, $timestamp) { // Validates authentication using a standard authentication token global $mdb2; $result = $mdb2->query("SELECT password FROM Users WHERE username ILIKE " . $mdb2->quote($username, 'text')); if (PEAR::isError($result) || !$result->numRows()) { // TODO: Log failures somewhere return false; } $pass = $result->fetchOne(0); $check_token = md5($pass . $timestamp); return $check_token == $token; } ?>
<?php /* Libre.fm -- a free network service for sharing your music listening habits Copyright (C) 2009 Libre.fm Project This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ require_once('database.php'); function check_web_auth($username, $token, $timestamp, $api_key, $sk) { // Validates authentication using a web services token global $mdb2; } function check_standard_auth($username, $token, $timestamp) { // Validates authentication using a standard authentication token global $mdb2; $result = $mdb2->query("SELECT password FROM Users WHERE username=" . $mdb2->quote($username, 'text')); if (PEAR::isError($result) || !$result->numRows()) { // TODO: Log failures somewhere return false; } $pass = $result->fetchOne(0); $check_token = md5($pass . $timestamp); return $check_token == $token; } ?>
Fix a floating point issue
var exports = {}; exports.simplePrint = function(video) { return `**${video.title}**`; }; exports.prettyPrint = function(video) { viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ','); return `**${video.title}** by **${video.author}** *(${viewCount} views)*`; }; exports.prettyPrintWithUser = function(video) { return exports.prettyPrint(video) + `, added by <@${video.userId}>`; }; exports.simplify = function(video) { return { vid: video.vid, title: video.title, author: video.author, view_count: video.view_count, }; }; exports.prettyTime = function(ms) { var seconds = ms / 1000; var actualSeconds = Math.ceil(seconds % 60); var minutes = Math.round((seconds - actualSeconds) / 60); return `${minutes}:${actualSeconds}`; }; module.exports = exports;
var exports = {}; exports.simplePrint = function(video) { return `**${video.title}**`; }; exports.prettyPrint = function(video) { viewCount = video.view_count.replace(/\B(?=(\d{3})+(?!\d))/g, ','); return `**${video.title}** by **${video.author}** *(${viewCount} views)*`; }; exports.prettyPrintWithUser = function(video) { return exports.prettyPrint(video) + `, added by <@${video.userId}>`; }; exports.simplify = function(video) { return { vid: video.vid, title: video.title, author: video.author, view_count: video.view_count, }; }; exports.prettyTime = function(ms) { var seconds = ms / 1000; var actualSeconds = Math.ceil(seconds % 60); var minutes = (seconds - actualSeconds) / 60; return `${minutes}:${actualSeconds}`; }; module.exports = exports;
Test that framebuffer can't be bound after deletion.
from nose.tools import * from scikits.gpu.fbo import * from pyglet.gl import * class TestFramebuffer(object): def create(self, x, y, colours, dtype): fbo = Framebuffer(x, y, bands=colours, dtype=dtype) fbo.bind() fbo.unbind() fbo.delete() def test_creation(self): fbo = Framebuffer(64, 64) for dtype in [gl.GL_UNSIGNED_BYTE, gl.GL_BYTE, gl.GL_INT, gl.GL_UNSIGNED_INT, gl.GL_FLOAT]: for bands in [1, 2, 3, 4]: yield self.create, 16, 16, bands, dtype def test_bind_deleted(self): fbo = Framebuffer(32, 32) fbo.delete() assert_raises(RuntimeError, fbo.bind)
from nose.tools import * from scikits.gpu.fbo import * from pyglet.gl import * class TestFramebuffer(object): def create(self, x, y, colours, dtype): fbo = Framebuffer(x, y, bands=colours, dtype=dtype) fbo.bind() fbo.unbind() fbo.delete() def test_creation(self): fbo = Framebuffer(64, 64) for dtype in [gl.GL_UNSIGNED_BYTE, gl.GL_BYTE, gl.GL_INT, gl.GL_UNSIGNED_INT, gl.GL_FLOAT]: for bands in [1, 2, 3, 4]: yield self.create, 16, 16, bands, dtype
Check for existence before removal
var mongoose = require('mongoose'); var Table = require('./Table'); var TableSchema = Table.schema; var Schema = mongoose.Schema; var handleError = function(err){ if (err){ console.log(err); return; } } var TableQueueSchema = new Schema({ queue : {type: [TableSchema], default: []} }); TableQueueSchema.methods.addTable = function(tableID, status) { var queue = this.queue; var query = Table.findOne({'id': tableID, 'status':status}, 'index', function(err, result){ if (err){ console.log(err); return; } if(!result){ var table = new Table({id:tableID, index: queue.length, status: status}) table.save(handleError); queue.push(table); } }); } TableQueueSchema.methods.removeTable = function(tableID) { var index; var query = Table.findOne({'id': tableID}, 'index', function(err, table){ if (err){ console.log(err); return; } if(table){ index = table.index; table.remove(); } }); this.queue.splice(index, 1); } module.exports = mongoose.model('TableQueue', TableQueueSchema);
var mongoose = require('mongoose'); var Table = require('./Table'); var TableSchema = Table.schema; var Schema = mongoose.Schema; var handleError = function(err){ if (err){ console.log(err); return; } } var TableQueueSchema = new Schema({ queue : {type: [TableSchema], default: []} }); TableQueueSchema.methods.addTable = function(tableID, status) { var queue = this.queue; var query = Table.findOne({'id': tableID, 'status':status}, 'index', function(err, result){ if (err){ console.log(err); return; } if(!result){ var table = new Table({id:tableID, index: queue.length, status: status}) table.save(handleError); queue.push(table); } }); } TableQueueSchema.methods.removeTable = function(tableID) { var index; var query = Table.findOne({'id': tableID}, 'index', function(err, table){ if (err){ console.log(err); return; } index = table.index; table.remove(); }); this.queue.splice(index, 1); } module.exports = mongoose.model('TableQueue', TableQueueSchema);
Update URL for bel2rdf service
import requests import json import time ndex_base_url = 'http://bel2rdf.bigmech.ndexbio.org' #ndex_base_url = 'http://52.37.175.128' def send_request(url_suffix, params): res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params)) res_json = get_result(res) return res_json def get_result(res): status = res.status_code # If response is immediate, we get 200 if status == 200: return res.text # If there is a continuation of the message # we get status 300, handled below. # Otherwise we return None. elif status != 300: return None task_id = res.json()['task_id'] print 'NDEx task submitted...' time_used = 0 try: while status != 200: res = requests.get(ndex_base_url + '/task/' + task_id) status = res.status_code if status != 200: time.sleep(5) time_used += 5 except KeyError: next return None print 'NDEx task complete.' return res.text
import requests import json import time ndex_base_url = 'http://general.bigmech.ndexbio.org:8082' #ndex_base_url = 'http://52.37.175.128' def send_request(url_suffix, params): res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params)) res_json = get_result(res) return res_json def get_result(res): status = res.status_code # If response is immediate, we get 200 if status == 200: return res.text # If there is a continuation of the message # we get status 300, handled below. # Otherwise we return None. elif status != 300: return None task_id = res.json()['task_id'] print 'NDEx task submitted...' time_used = 0 try: while status != 200: res = requests.get(ndex_base_url + '/task/' + task_id) status = res.status_code if status != 200: time.sleep(5) time_used += 5 except KeyError: next return None print 'NDEx task complete.' return res.text
Add method to reset the LogMonitor i.e. forget any previously logged messages.
/** ================================================================================ Project: Procter and Gamble - Skelmersdale. $HeadURL$ $Author$ $Revision$ $Date$ $Log$ ============================== (c) Swisslog(UK) Ltd, 2005 ====================== */ package io.cloudracer; import static org.junit.Assert.assertNull; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.core.Appender; public abstract class AbstractTestTools { /** * Asserts that the "TEST" {@link Appender log4j Appender} did not log any messages. * * Adjust the log4j.xml Appenders to match on only the messages that should cause this method to raise {@link AssertionError}. */ protected final void checkLogMonitorForUnexpectedMessages() { try { final int delayDuration = 1; // Pause to allow messages to be flushed to the disk (and, hence, through the appenders). TimeUnit.SECONDS.sleep(delayDuration); } catch (InterruptedException e) { // Do nothing } assertNull(String.format("An unexpected message was logged to the file \"%s\".", LogMonitor.getFileName()), LogMonitor.getLastEventLogged()); } protected void resetLogMonitor() { LogMonitor.setLastEventLogged(null); } }
/** ================================================================================ Project: Procter and Gamble - Skelmersdale. $HeadURL$ $Author$ $Revision$ $Date$ $Log$ ============================== (c) Swisslog(UK) Ltd, 2005 ====================== */ package io.cloudracer; import static org.junit.Assert.assertNull; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.core.Appender; public abstract class AbstractTestTools { /** * Asserts that the "TEST" {@link Appender log4j Appender} did not log any messages. * * Adjust the log4j.xml Appenders to match on only the messages that should cause this method to raise {@link AssertionError}. */ public final void checkForUnexpectedLogMessages() { try { final int delayDuration = 1; // Pause to allow messages to be flushed to the disk (and, hence, through the appenders). TimeUnit.SECONDS.sleep(delayDuration); } catch (InterruptedException e) { // Do nothing } assertNull(String.format("An unexpected message was logged to the file \"%s\".", LogMonitor.getFileName()), LogMonitor.getLastEventLogged()); } }
Add support for a setup phase which is not recorded.
package net.openhft.chronicle.wire; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; /** * Created by peter on 17/05/2017. */ public class TextMethodTesterTest { @Test public void run() throws IOException { TextMethodTester test = new TextMethodTester<>( "methods-in.yaml", MockMethodsImpl::new, MockMethods.class, "methods-in.yaml") .setup("methods-in.yaml") // calls made here are not validated in the output. .run(); assertEquals(test.expected(), test.actual()); } } class MockMethodsImpl implements MockMethods { private final MockMethods out; public MockMethodsImpl(MockMethods out) { this.out = out; } @Override public void method1(MockDto dto) { out.method1(dto); } @Override public void method2(MockDto dto) { out.method2(dto); } }
package net.openhft.chronicle.wire; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; /** * Created by peter on 17/05/2017. */ public class TextMethodTesterTest { @Test public void run() throws IOException { TextMethodTester test = new TextMethodTester<>( "methods-in.yaml", MockMethodsImpl::new, MockMethods.class, "methods-in.yaml") .setup("methods-in.yaml") // calls made here are ignored. .run(); assertEquals(test.expected(), test.actual()); } } class MockMethodsImpl implements MockMethods { private final MockMethods out; public MockMethodsImpl(MockMethods out) { this.out = out; } @Override public void method1(MockDto dto) { out.method1(dto); } @Override public void method2(MockDto dto) { out.method2(dto); } }
Add identifiers function and create an array of identifiers and their number of times they appear
const esprima = require('esprima'); var source = 'answer = 42; hola = 5; isCold = "Si"; answer = 50;'; const tokens = esprima.tokenize(source); //console.log(tokens); var identificadores = tokens.filter(function (el) { return (el.type === "Identifier"); }); console.log("El código es: "); console.log(source); //console.log("Los identificadores son: "); //console.log(identificadores); var armarArray = []; identificadores.forEach(function (element) { var indice = arrayObjectIndexOf(armarArray,element.value, "id"); if(indice == -1){ // No encontró el identificador, lo agrega. armarArray.push(new Identifier(element.value,1)); } else { // Encontró el identificador, suma uno. armarArray[indice].quantity++; } }); console.log("El array de Identificadores es: "); console.log(armarArray); function arrayObjectIndexOf(myArray, searchTerm, property) { for(var i = 0, len = myArray.length; i < len; i++) { if (myArray[i][property] === searchTerm) return i; } return -1; } function Identifier(id, quantity) { this.id = id; this.quantity = quantity; }
const esprima = require('esprima'); var source = 'answer = 42; hola = 5; isCold = "Si"; answer = 50;'; const tokens = esprima.tokenize(source); //console.log(tokens); var identificadores = tokens.filter(function (el) { return (el.type === "Identifier"); }); console.log("El código es: "); console.log(source); //console.log("Los identificadores son: "); //console.log(identificadores); function arrayObjectIndexOf(myArray, searchTerm, property) { for(var i = 0, len = myArray.length; i < len; i++) { if (myArray[i][property] === searchTerm) return i; } return -1; } var armarArray = []; console.log("El array de Identificadores es: "); identificadores.forEach(function (element) { var indice = arrayObjectIndexOf(armarArray,element.value, "id"); if(indice == -1){ // No encontró el identificador, lo agrega. armarArray.push(new Identifier(element.value,1)); } else { // Encontró el identificador, suma uno. armarArray[indice].quantity++; } }); console.log(armarArray); function Identifier(id, quantity) { this.id = id; this.quantity = quantity; }
Fix logging so it doesn't erase the file
from threading import Thread from Queue import Queue from twisted.python import log import time import Mailbox, Web import sys import argparse parser = argparse.ArgumentParser() parser.add_argument("--verbose", "-v", help="output logs to std out, not the file", action="store_true") args = parser.parse_args() queue = Queue() MailboxThread = Thread(target=Mailbox.MailboxHandler, args=(queue,)) WebThread = Thread(target=Web.WebHandler, args=(queue,)) MailboxThread.setDaemon(True) WebThread.setDaemon(True) if args.verbose: log.startLogging(sys.stdout) else: log.startLogging(open('mockbox.log', 'a')) MailboxThread.start() WebThread.start() while True: try: time.sleep(1) except KeyboardInterrupt: print "Shutting down..." raise
from threading import Thread from Queue import Queue from twisted.python import log import time import Mailbox, Web import sys import argparse parser = argparse.ArgumentParser() parser.add_argument("--verbose", "-v", help="output logs to std out, not the file", action="store_true") args = parser.parse_args() queue = Queue() MailboxThread = Thread(target=Mailbox.MailboxHandler, args=(queue,)) WebThread = Thread(target=Web.WebHandler, args=(queue,)) MailboxThread.setDaemon(True) WebThread.setDaemon(True) if args.verbose: log.startLogging(sys.stdout) else: log.startLogging(open('mockbox.log', 'w')) MailboxThread.start() WebThread.start() while True: try: time.sleep(1) except KeyboardInterrupt: print "Shutting down..." raise
Fix the location path of OpenIPSL
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
Fix arguments to diff method
# -*- coding: utf-8 -*- from sqlalchemy import MetaData, create_engine from sqlalchemy.orm import Session from sqlalchemy.ext.automap import automap_base class DB(object): """Facade for the low level DB operations""" def __init__(self, dsn, schema=None): self.engine = create_engine(dsn) self.meta = MetaData() self.meta.reflect(bind=self.engine, schema=schema) self.base = automap_base(metadata=self.meta) self.base.prepare() def get_classes(self): return self.base.classes def get_session(self): return Session(self.engine) def get_rows(self, session, cls, modified=None): return session.query(cls).all() class Mirror(object): """API for cli mirroring operations""" def __init__(self, source, target, source_schema=None, target_schema=None): self.source = DB(source, source_schema) self.target = DB(target, target_schema) def diff(self, tables, modified): pass def create(self, tables): pass def recreate(self, tables): pass def mirror(self, tables): pass
# -*- coding: utf-8 -*- from sqlalchemy import MetaData, create_engine from sqlalchemy.orm import Session from sqlalchemy.ext.automap import automap_base class DB(object): """Facade for the low level DB operations""" def __init__(self, dsn, schema=None): self.engine = create_engine(dsn) self.meta = MetaData() self.meta.reflect(bind=self.engine, schema=schema) self.base = automap_base(metadata=self.meta) self.base.prepare() def get_classes(self): return self.base.classes def get_session(self): return Session(self.engine) def get_rows(self, session, cls, modified=None): return session.query(cls).all() class Mirror(object): """API for cli mirroring operations""" def __init__(self, source, target, source_schema=None, target_schema=None): self.source = DB(source, source_schema) self.target = DB(target, target_schema) def diff(self, tables): pass def create(self, tables): pass def recreate(self, tables): pass def mirror(self, tables): pass
Update the PyPI version to 0.2.7
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.7', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.6', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Change visibility from protected to public
<?php declare (strict_types = 1); namespace GrottoPress\Jentil\Setups\Customizer\Layout\Settings; use GrottoPress\Jentil\Setups\Customizer\Layout\Layout; use GrottoPress\Jentil\utilities\ThemeMods\Layout as LayoutMod; use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting; abstract class AbstractSetting extends Setting { /** * @var LayoutMod */ protected $mod; public function __construct(Layout $layout) { parent::__construct($layout); $this->args['sanitize_callback'] = 'sanitize_title'; $this->control['section'] = $this->section->id; $this->control['label'] = \esc_html__('Select layout', 'jentil'); $this->control['type'] = 'select'; $this->control['choices'] = $this->section->customizer->app ->utilities->page->layouts->IDs(); } protected function themeMod(array $args): LayoutMod { return $this->section->customizer->app->utilities->themeMods->layout( $args ); } }
<?php declare (strict_types = 1); namespace GrottoPress\Jentil\Setups\Customizer\Layout\Settings; use GrottoPress\Jentil\Setups\Customizer\Layout\Layout; use GrottoPress\Jentil\utilities\ThemeMods\Layout as LayoutMod; use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting; abstract class AbstractSetting extends Setting { /** * @var LayoutMod */ protected $mod; protected function __construct(Layout $layout) { parent::__construct($layout); $this->args['sanitize_callback'] = 'sanitize_title'; $this->control['section'] = $this->section->id; $this->control['label'] = \esc_html__('Select layout', 'jentil'); $this->control['type'] = 'select'; $this->control['choices'] = $this->section->customizer->app ->utilities->page->layouts->IDs(); } protected function themeMod(array $args): LayoutMod { return $this->section->customizer->app->utilities->themeMods->layout( $args ); } }
Remove extraneous currency field from transfer schedules.
package co.omise.models.schedules; import com.fasterxml.jackson.annotation.JsonProperty; public class TransferScheduling { private String recipient; private long amount; @JsonProperty("percentage_of_balance") private float percentageOfBalance; public String getRecipient() { return recipient; } public void setRecipient(String recipient) { this.recipient = recipient; } public long getAmount() { return amount; } public void setAmount(long amount) { this.amount = amount; } public float getPercentageOfBalance() { return percentageOfBalance; } public void setPercentageOfBalance(float percentageOfBalance) { this.percentageOfBalance = percentageOfBalance; } }
package co.omise.models.schedules; import com.fasterxml.jackson.annotation.JsonProperty; public class TransferScheduling { private String recipient; private long amount; private String currency; @JsonProperty("percentage_of_balance") private float percentageOfBalance; public String getRecipient() { return recipient; } public void setRecipient(String recipient) { this.recipient = recipient; } public long getAmount() { return amount; } public void setAmount(long amount) { this.amount = amount; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public float getPercentageOfBalance() { return percentageOfBalance; } public void setPercentageOfBalance(float percentageOfBalance) { this.percentageOfBalance = percentageOfBalance; } }
Update user details API call
from social.backends.oauth import BaseOAuth2 class HastexoOAuth2(BaseOAuth2): """Hastexo OAuth2 authentication backend""" name = 'hastexo' AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/' ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ' ' def get_user_details(self, response): """Return user details from hastexo account""" return { 'username': response.get('username'), 'email': response.get('email', ''), 'first_name': response.get('first_name', ''), 'last_name': response.get('last_name', '') } def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" return self.get_json('https://store.hastexo.com/api/login/', params={ 'access_token': access_token })
from social.backends.oauth import BaseOAuth2 class HastexoOAuth2(BaseOAuth2): """Hastexo OAuth2 authentication backend""" name = 'hastexo' AUTHORIZATION_URL = 'https://store.hastexo.com/o/authorize/' ACCESS_TOKEN_URL = 'https://store.hastexo.com/o/token/' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ' ' def get_user_details(self, response): """Return user details from hastexo account""" return { 'username': response['username'], 'email': response.get('email', ''), 'first_name': '', 'last_name': '', } def user_data(self, access_token, *args, **kwargs): """Loads user data from service""" return self.get_json('https://store.hastexo.com/api/users/', params={ 'access_token': access_token })
Fix python debugging on Windows.
from __future__ import print_function import sys import os import time import socket import argparse import subprocess parser = argparse.ArgumentParser() parser.add_argument('--launch-adapter') parser.add_argument('--lldb') parser.add_argument('--wait-port') args = parser.parse_args() if args.launch_adapter: lldb = args.lldb or 'lldb' cmd = [lldb, '-b', '-O', 'command script import %s' % args.launch_adapter, '-O', 'script sys.argv=["lldb"]; import ptvsd; ptvsd.enable_attach(address=("0.0.0.0", 3000)); ptvsd.wait_for_attach()', '-O', 'script adapter.run_tcp_session(4711)', ] print('Launching', cmd) if sys.platform != 'win32': subprocess.Popen(cmd, preexec_fn=lambda: os.setsid()) else: subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_CONSOLE) if args.wait_port: port = int(args.wait_port) print('Waiting for port %d' % port) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: result = sock.connect_ex(('127.0.0.1', port)) if result == 0: break time.sleep(0.5) print('Port opened') sock.shutdown(socket.SHUT_WR) sock.close()
from __future__ import print_function import sys import os import time import socket import argparse import subprocess parser = argparse.ArgumentParser() parser.add_argument('--launch-adapter') parser.add_argument('--lldb') parser.add_argument('--wait-port') args = parser.parse_args() if args.launch_adapter: lldb = args.lldb or 'lldb' cmd = [lldb, '-b', '-O', 'command script import %s' % args.launch_adapter, '-O', 'script import ptvsd; ptvsd.enable_attach(address=("0.0.0.0", 3000)); ptvsd.wait_for_attach(); adapter.run_tcp_session(4711)', ] print('Launching', cmd) subprocess.Popen(cmd, preexec_fn=lambda: os.setsid()) if args.wait_port: port = int(args.wait_port) print('Waiting for port %d' % port) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: result = sock.connect_ex(('127.0.0.1', port)) if result == 0: break time.sleep(0.5) print('Port opened') sock.shutdown(socket.SHUT_WR) sock.close()
Reset term state and change default search term.
import React, {Component} from 'react'; import {connect} from 'react-redux'; import {searchVideos} from '../actions/index'; import {bindActionCreators} from 'redux'; class SearchBar extends Component{ constructor(props){ super(props); this.state = { term: ''}; } handleOnChange(term){ this.setState({term}); this.props.searchVideos(term); this.props.handleOnChange(); } render(){ return ( <div className="search-bar"> <input placeholder="Search videos here..." value={this.state.term} onChange={ (event) => { this.handleOnChange(event.target.value); } } /> </div> ); } componentWillMount(){ this.props.searchVideos('Dota 2'); } } function mapDispatchToProps(dispatch){ return bindActionCreators({searchVideos: searchVideos}, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar);
import React, {Component} from 'react'; import {connect} from 'react-redux'; import {searchVideos} from '../actions/index'; import {bindActionCreators} from 'redux'; class SearchBar extends Component{ constructor(props){ super(props); this.state = { term: 'Basketball'}; } handleOnChange(term){ this.setState({term}); this.props.searchVideos(term); this.props.handleOnChange(); } render(){ return ( <div className="search-bar"> <input value={this.state.term} onChange={ (event) => { this.handleOnChange(event.target.value); } } /> </div> ); } componentWillMount(){ this.props.searchVideos(this.state.term); } } function mapDispatchToProps(dispatch){ return bindActionCreators({searchVideos: searchVideos}, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar);
Enable consistent-hashing policy for Collector Change-Id: I7ed6747b6c3ef95d8fed0c62e786c7039fb510a6 Fixes-Bug: #1600368
import string template = string.Template(""" [DEFAULTS] zk_server_ip=$__contrail_zk_server_ip__ zk_server_port=$__contrail_zk_server_port__ listen_ip_addr=$__contrail_listen_ip_addr__ listen_port=$__contrail_listen_port__ log_local=$__contrail_log_local__ log_file=$__contrail_log_file__ cassandra_server_list=$__contrail_cassandra_server_list__ log_level=SYS_NOTICE # minimim time to allow client to cache service information (seconds) ttl_min=300 # maximum time to allow client to cache service information (seconds) ttl_max=1800 # health check ping interval <=0 for disabling hc_interval=$__contrail_healthcheck_interval__ # maximum hearbeats to miss before server will declare publisher out of # service. hc_max_miss=3 # use short TTL for agressive rescheduling if all services are not up ttl_short=1 # for DNS service, we use fixed policy # even when the cluster has more than two control nodes, only two of these # should provide the DNS service [DNS-SERVER] policy = fixed # Use consistent hashing for Collector for better handling of HA events [Collector] policy = chash ###################################################################### # Other service specific knobs ... # use short TTL for agressive rescheduling if all services are not up # ttl_short=1 # specify policy to use when assigning services # policy = [load-balance | round-robin | fixed | chash] ###################################################################### """)
import string template = string.Template(""" [DEFAULTS] zk_server_ip=$__contrail_zk_server_ip__ zk_server_port=$__contrail_zk_server_port__ listen_ip_addr=$__contrail_listen_ip_addr__ listen_port=$__contrail_listen_port__ log_local=$__contrail_log_local__ log_file=$__contrail_log_file__ cassandra_server_list=$__contrail_cassandra_server_list__ log_level=SYS_NOTICE # minimim time to allow client to cache service information (seconds) ttl_min=300 # maximum time to allow client to cache service information (seconds) ttl_max=1800 # health check ping interval <=0 for disabling hc_interval=$__contrail_healthcheck_interval__ # maximum hearbeats to miss before server will declare publisher out of # service. hc_max_miss=3 # use short TTL for agressive rescheduling if all services are not up ttl_short=1 # for DNS service, we use fixed policy # even when the cluster has more than two control nodes, only two of these # should provide the DNS service [DNS-SERVER] policy = fixed ###################################################################### # Other service specific knobs ... # use short TTL for agressive rescheduling if all services are not up # ttl_short=1 # specify policy to use when assigning services # policy = [load-balance | round-robin | fixed] ###################################################################### """)
Return Status 422 on bad JSON content
import json import os import webapp2 from webapp2_extras import jinja2 class BaseHandler(webapp2.RequestHandler): @webapp2.cached_property def jinja2(self): return jinja2.get_jinja2(app=self.app) def render_template(self, filename, **template_args): self.response.write(self.jinja2.render_template(filename, **template_args)) class IndexHandler(BaseHandler): def get(self): self.render_template('index.html', name=self.request.get('name')) class RegistrationHandler(webapp2.RequestHandler): def post(self): json_object = json.loads(self.request.body) if not 'username' in json_object: webapp2.abort(422, detail='Field "username" is required') else: self.response.write('Registration Received {}'.format(json_object)) class GamesHandler(webapp2.RequestHandler): def post(self): self.response.write('Game Received') app = webapp2.WSGIApplication([ webapp2.Route('/', handler=IndexHandler, name='home', methods=['GET']), webapp2.Route('/register', handler=RegistrationHandler, name='registration', methods=['POST']), webapp2.Route('/games', handler=GamesHandler, name='games', methods=['POST']), ], debug=True)
import json import os import webapp2 from webapp2_extras import jinja2 class BaseHandler(webapp2.RequestHandler): @webapp2.cached_property def jinja2(self): return jinja2.get_jinja2(app=self.app) def render_template(self, filename, **template_args): self.response.write(self.jinja2.render_template(filename, **template_args)) class IndexHandler(BaseHandler): def get(self): self.render_template('index.html', name=self.request.get('name')) class RegistrationHandler(webapp2.RequestHandler): def post(self): json_object = json.loads(self.request.body) self.response.write('Registration Received {}'.format(json_object)) class GamesHandler(webapp2.RequestHandler): def post(self): self.response.write('Game Received') app = webapp2.WSGIApplication([ webapp2.Route('/', handler=IndexHandler, name='home', methods=['GET']), webapp2.Route('/register', handler=RegistrationHandler, name='registration', methods=['POST']), webapp2.Route('/games', handler=GamesHandler, name='games', methods=['POST']), ], debug=True)
BAP-9940: Create controller DELETE list action - fix cs
<?php namespace Oro\Bundle\ApiBundle\Processor; use Oro\Component\ChainProcessor\ProcessorBag; use Oro\Bundle\ApiBundle\Provider\ConfigProvider; use Oro\Bundle\ApiBundle\Processor\DeleteList\DeleteListContext; use Oro\Bundle\ApiBundle\Provider\MetadataProvider; class DeleteListProcessor extends RequestActionProcessor { /** @var ConfigProvider */ protected $configProvider; /** @var MetadataProvider */ protected $metadataProvider; /** * @param ProcessorBag $processorBag * @param string $action * @param ConfigProvider $configProvider * @param MetadataProvider $metadataProvider */ public function __construct( ProcessorBag $processorBag, $action, ConfigProvider $configProvider, MetadataProvider $metadataProvider ) { parent::__construct($processorBag, $action); $this->configProvider = $configProvider; $this->metadataProvider = $metadataProvider; } /** * {@inheritdoc} */ protected function createContextObject() { return new DeleteListContext($this->configProvider, $this->metadataProvider); } }
<?php namespace Oro\Bundle\ApiBundle\Processor; use Oro\Bundle\ApiBundle\Provider\ConfigProvider; use Oro\Bundle\ApiBundle\Processor\DeleteList\DeleteListContext; use Oro\Bundle\ApiBundle\Provider\MetadataProvider; use Oro\Component\ChainProcessor\ProcessorBag; class DeleteListProcessor extends RequestActionProcessor { /** @var ConfigProvider */ protected $configProvider; /** @var MetadataProvider */ protected $metadataProvider; /** * @param ProcessorBag $processorBag * @param string $action * @param ConfigProvider $configProvider * @param MetadataProvider $metadataProvider */ public function __construct( ProcessorBag $processorBag, $action, ConfigProvider $configProvider, MetadataProvider $metadataProvider ) { parent::__construct($processorBag, $action); $this->configProvider = $configProvider; $this->metadataProvider = $metadataProvider; } /** * {@inheritdoc} */ protected function createContextObject() { return new DeleteListContext($this->configProvider, $this->metadataProvider); } }
Set the relation name for the list of greetings.
package hello.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.hateoas.core.Relation; @Entity @Relation(collectionRelation = "greetings") public class Greeting { @Id @GeneratedValue private long id; @NotEmpty(message = "The greeting cannot be empty.") @Size(max = 30, message = "The greeting must have 30 characters or less.") @Pattern(regexp = ".*%s.*", message = "The greeting must include the %s placeholder.") private String template; public Greeting() { } public Greeting(String template) { this.template = template; } public long getId() { return this.id; } public String getTemplate() { return this.template; } public void setTemplate(String template) { this.template = template; } public String getGreeting(String name) { return String.format(this.template, name); } @Override public String toString() { return String.format("Greeting [id = %d, template = %s]", this.id, this.template); } }
package hello.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; @Entity public class Greeting { @Id @GeneratedValue private long id; @NotEmpty(message = "The greeting cannot be empty.") @Size(max = 30, message = "The greeting must have 30 characters or less.") @Pattern(regexp = ".*%s.*", message = "The greeting must include the %s placeholder.") private String template; public Greeting() { } public Greeting(String template) { this.template = template; } public long getId() { return this.id; } public String getTemplate() { return this.template; } public void setTemplate(String template) { this.template = template; } public String getGreeting(String name) { return String.format(this.template, name); } @Override public String toString() { return String.format("Greeting [id = %d, template = %s]", this.id, this.template); } }
Order planets by distance form their star.
from django.views.generic import ListView, DetailView from .models import Planet, SolarSystem class SystemMixin(object): model = SolarSystem def get_queryset(self): return super(SystemMixin, self).get_queryset().filter(radius__isnull=False) class PlanetMixin(object): model = Planet def get_queryset(self): return super(PlanetMixin, self).get_queryset().filter( solar_system__radius__isnull=False, radius__isnull=False) class SystemList(SystemMixin, ListView): pass class SystemDetail(SystemMixin, DetailView): def get_context_data(self, **kwargs): data = super(SystemDetail, self).get_context_data(**kwargs) data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False).order_by('semi_major_axis')}) return data class PlanetList(PlanetMixin, ListView): pass class PlanetDetail(PlanetMixin, DetailView): pass
from django.views.generic import ListView, DetailView from .models import Planet, SolarSystem class SystemMixin(object): model = SolarSystem def get_queryset(self): return super(SystemMixin, self).get_queryset().filter(radius__isnull=False) class PlanetMixin(object): model = Planet def get_queryset(self): return super(PlanetMixin, self).get_queryset().filter( solar_system__radius__isnull=False, radius__isnull=False) class SystemList(SystemMixin, ListView): pass class SystemDetail(SystemMixin, DetailView): def get_context_data(self, **kwargs): data = super(SystemDetail, self).get_context_data(**kwargs) data.update({'planets': Planet.objects.filter(solar_system=self.object, radius__isnull=False)}) return data class PlanetList(PlanetMixin, ListView): pass class PlanetDetail(PlanetMixin, DetailView): pass
Change the cursor over cast list items.
// @flow import React from 'react'; import PropTypes from 'prop-types'; import { red500 } from 'material-ui/styles/colors'; import { ListItem } from 'material-ui/List'; import Avatar from 'material-ui/Avatar'; class CastListItem extends React.Component { static propTypes = { role: PropTypes.string.isRequired, displayRole: PropTypes.bool.isRequired, person: PropTypes.object.isRequired, }; renderAvatar() { const { person } = this.props; const initial = (person.name[0] || '?').toUpperCase(); return ( <Avatar backgroundColor={red500}> {initial} </Avatar> ); }; render() { const { role, displayRole, person } = this.props; return ( <ListItem style={{ cursor: 'default' }} disabled={true} primaryText={person.name} secondaryText={displayRole ? role : null} leftAvatar={this.renderAvatar(person)} /> ); }; } export default CastListItem;
// @flow import React from 'react'; import PropTypes from 'prop-types'; import { red500 } from 'material-ui/styles/colors'; import { ListItem } from 'material-ui/List'; import Avatar from 'material-ui/Avatar'; class CastListItem extends React.Component { static propTypes = { role: PropTypes.string.isRequired, displayRole: PropTypes.bool.isRequired, person: PropTypes.object.isRequired, }; renderAvatar() { const { person } = this.props; const initial = (person.name[0] || '?').toUpperCase(); return ( <Avatar backgroundColor={red500}> {initial} </Avatar> ); }; render() { const { role, displayRole, person } = this.props; return ( <ListItem disabled={true} primaryText={person.name} secondaryText={displayRole ? role : null} leftAvatar={this.renderAvatar(person)} /> ); }; } export default CastListItem;
Refactor minor details for editCommand
package seedu.jimi.logic.commands; import seedu.jimi.model.task.FloatingTask; /** * * @author zexuan * * Edits an existing task/event in Jimi. */ public class EditCommand extends Command{ public static final String COMMAND_WORD = "edit"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits an existing task/event in Jimi. " + "Example: " + COMMAND_WORD + "2 by 10th July at 12 pm"; public static final String MESSAGE_SUCCESS = "New task added: %1$s"; public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in Jimi"; private final FloatingTask toEdit; @Override public CommandResult execute() { // TODO Auto-generated method stub return null; } }
package seedu.jimi.logic.commands; import seedu.jimi.model.task.FloatingTask; /** * * @author zexuan * * Edits an existing task/event in Jimi. */ public class EditCommand extends Command{ public static final String COMMAND_WORD = "add"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits an existing task/event in Jimi. " + "Parameters: NAME p/PHONE e/EMAIL a/ADDRESS [t/TAG]...\n" + "Example: " + COMMAND_WORD + " edit 2 by 10th july at 12 pm"; public static final String MESSAGE_SUCCESS = "New task added: %1$s"; public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in Jimi"; private final FloatingTask toAdd; @Override public CommandResult execute() { // TODO Auto-generated method stub return null; } }
Add email field to login status.
package com.google.sps.servlets; import com.google.appengine.api.users.UserServiceFactory; import com.google.sps.utilities.CommonUtils; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet that returns whether user is logged in and email of the user. */ @WebServlet("/login-status") public class LoginStatusServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json;"); LoginStatus status; if (UserServiceFactory.getUserService().isUserLoggedIn()) { status = new LoginStatus(true, UserServiceFactory.getUserService().getCurrentUser().getEmail()); } else { status = new LoginStatus(false, ""); } response.getWriter().println(CommonUtils.convertToJson(status)); } private class LoginStatus { private boolean isLoggedIn; private String userEmail; public LoginStatus(boolean isLoggedIn, String userEmail) { this.isLoggedIn = isLoggedIn; this.userEmail = userEmail; } } }
package com.google.sps.servlets; import com.google.appengine.api.users.UserServiceFactory; import com.google.sps.utilities.CommonUtils; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet that returns the login status of the user. */ @WebServlet("/login-status") public class LoginStatusServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json;"); // Get the current login status. LoginStatus status; if (UserServiceFactory.getUserService().isUserLoggedIn()) { status = LoginStatus.getLoggedInInstance(); } else { status = LoginStatus.getNotLoggedInInstance(); } response.getWriter().println(CommonUtils.convertToJson(status)); } private static class LoginStatus { private static final LoginStatus STATUS_LOGGED_IN = new LoginStatus(true); private static final LoginStatus STATUS_NOT_LOGGED_IN = new LoginStatus(false); private boolean isLoggedIn; private LoginStatus(boolean isLoggedIn) { this.isLoggedIn = isLoggedIn; } public static LoginStatus getLoggedInInstance() { return STATUS_LOGGED_IN; } public static LoginStatus getNotLoggedInInstance() { return STATUS_NOT_LOGGED_IN; } } }
Comment out block to make linter happy
import assert from 'assert' const TYPE_TO_PREFIXES = { municipality: 'K', borough: 'B', county: 'F', commerceRegion: 'N' } // we might need this reverse mapping at some point later //const PREFIX_TO_TYPE = Object.keys(TYPE_TO_PREFIXES).reduce((acc, key) => { // acc[TYPE_TO_PREFIXES[key]] = key // return acc //}, {}) const REGION_TYPE_TO_ID_FIELD_MAPPING = { municipality: 'kommuneNr', county: 'fylkeNr', commerceRegion: 'naringsregionNr' } export function split(region) { return [ region.substring(0, 1).toUpperCase(), region.substring(1) ] } export function prefixify(region) { assert(TYPE_TO_PREFIXES[region.type], `No prefix registered for region type ${region.type}`) return TYPE_TO_PREFIXES[region.type] + region.code } export function getHeaderKey(region) { assert(REGION_TYPE_TO_ID_FIELD_MAPPING[region.type], `No mapping from region type ${region.type} to header key found`) return REGION_TYPE_TO_ID_FIELD_MAPPING[region.type] }
import assert from 'assert' const TYPE_TO_PREFIXES = { municipality: 'K', borough: 'B', county: 'F', commerceRegion: 'N' } const PREFIX_TO_TYPE = Object.keys(TYPE_TO_PREFIXES).reduce((acc, key) => { acc[TYPE_TO_PREFIXES[key]] = key return acc }, {}) const REGION_TYPE_TO_ID_FIELD_MAPPING = { municipality: 'kommuneNr', county: 'fylkeNr', commerceRegion: 'naringsregionNr' } export function split(region) { return [ region.substring(0, 1).toUpperCase(), region.substring(1) ] } export function prefixify(region) { assert(TYPE_TO_PREFIXES[region.type], `No prefix registered for region type ${region.type}`) return TYPE_TO_PREFIXES[region.type] + region.code } export function getHeaderKey(region) { assert(REGION_TYPE_TO_ID_FIELD_MAPPING[region.type], `No mapping from region type ${region.type} to header key found`) return REGION_TYPE_TO_ID_FIELD_MAPPING[region.type] }
Add stub for pulling player_stats including a new base_url for MySportsFeed
import json import csv import requests import secret base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/ def main(): division_standings() playoff_standings() playoff_standings() player_stats() points_for() tiebreaker() player_score() # Get Division Standings for each team def division_standings(): pass # Get Playoff Standings for each team (need number 5 & 6 in each conference) def playoff_standings(): pass # Get individual statistics for each category def player_stats(): response = requests.get('base_url/cumulative_player_stats.json', auth=HTTPBasicAuth(secret.msf_username, secret.msf_pw)) all_stats = response.json() stats = all_stats["cumulativeplayerstats"]["playerstatsentry"] # Get points for for the number one team in each conference: def points_for(): pass # Get the tiebreaker information def tiebreaker(): pass # Calculate the player scores def player_score(): pass if __name__ == '__main__': main()
import json import csv from collections import namedtuple from player_class import Players def main(): filename = get_data_file() data = load_file(filename) division_standings() playoff_standings() playoff_standings() player_stats() points_for() tiebreaker() player_score() # Import player picks into a Class def get_data_file(): base_folder = os.path.dirname(__file__) return os.path.join(base_folder, 'data', '2016_playerpicks.csv') def load_file(filename): with open(filename, 'r', encoding='utf-8') as fin: reader = csv.DictReader(fin) player_picks = [] for row in reader: p = Players.create_from_dict(row) player_picks.append(p) return player_picks # Get Division Standings for each team def division_standings(): pass # Get Playoff Standings for each team (need number 5 & 6 in each conference) def playoff_standings(): pass # Get individual statistics for each category def player_stats(): pass # Get points for for the number one team in each conference: def points_for(): pass # Get the tiebreaker information def tiebreaker(): pass # Calculate the player scores def player_score(): pass if __name__ == '__main__': main()
Use lastSeen instead of clients in list
#! /usr/bin/env node 'use strict'; const unifi = require('./lib/unifi'); const domoticz = require('./lib/domoticz'); const config = require('./lib/config'); let configArgIndex = process.argv.findIndex(arg => { return arg === '-c'; }); if (configArgIndex) { config.init(process.argv[configArgIndex + 1]); } domoticz.init(config.domoticz.url); unifi.init(config.unifi); unifi.getDevices(config.unifi.url, config.unifi.host, config.unifi.user, config.unifi.password) .then(devices => { config.domoticz.deviceMappings.forEach(deviceMapping => { let device = devices.find(device => { return device.mac === deviceMapping.mac; }); if (device && device.lastSeen.getTime() > (Date.now() - 1000 * 60 * 2)) { domoticz.turnOnSwitch(deviceMapping.switchId); } else { domoticz.turnOffSwitch(deviceMapping.switchId); } }); });
#! /usr/bin/env node 'use strict'; const unifi = require('./lib/unifi'); const domoticz = require('./lib/domoticz'); const config = require('./lib/config'); let configArgIndex = process.argv.findIndex(arg => { return arg === '-c'; }); if (configArgIndex) { config.init(process.argv[configArgIndex + 1]); } domoticz.init(config.domoticz.url); unifi.init(config.unifi); unifi.getDevices(config.unifi.url, config.unifi.host, config.unifi.user, config.unifi.password) .then(devices => { config.domoticz.deviceMappings.forEach(deviceMapping => { let device = devices.find(device => { return device.mac === deviceMapping.mac; }); if (device) { domoticz.turnOnSwitch(deviceMapping.switchId); } else { domoticz.turnOffSwitch(deviceMapping.switchId); } }); });
Remove String annotations, use Field instead
<?php namespace Saxulum\Tests\DoctrineMongoDbOdm\Document; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; /** * @ODM\Document */ class Page { /** * @var string * @ODM\Id */ protected $id; /** * @var string * @ODM\Field(type="string") */ protected $title; /** * @var string * @ODM\Field(type="string") */ protected $body; /** * @return string */ public function getId() { return $this->id; } /** * @param $title * @return $this */ public function setTitle($title) { $this->title = $title; return $this; } /** * @return string */ public function getTitle() { return $this->title; } /** * @param $body * @return $this */ public function setBody($body) { $this->body = $body; return $this; } /** * @return string */ public function getBody() { return $this->body; } }
<?php namespace Saxulum\Tests\DoctrineMongoDbOdm\Document; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; /** * @ODM\Document */ class Page { /** * @var string * @ODM\Id */ protected $id; /** * @var string * @ODM\String */ protected $title; /** * @var string * @ODM\String */ protected $body; /** * @return string */ public function getId() { return $this->id; } /** * @param $title * @return $this */ public function setTitle($title) { $this->title = $title; return $this; } /** * @return string */ public function getTitle() { return $this->title; } /** * @param $body * @return $this */ public function setBody($body) { $this->body = $body; return $this; } /** * @return string */ public function getBody() { return $this->body; } }
Change `type` prop to `theme`
const React = require('react'); const classNames = require('classnames'); class Button extends React.Component { render() { const { className, children, theme, ...props } = this.props; const buttonClassNames = classNames({ btn: true, 'btn-sm': this.props.size === 'small', 'btn-xs': this.props.size === 'extra-small', 'btn-lg': this.props.size === 'large', [`btn-${this.props.theme}`]: true, }, className); return ( <button {...props} className={buttonClassNames}> {children} </button> ); } } Button.propTypes = { size: React.PropTypes.oneOf([ 'small', 'extra-small', 'large', ]), type: React.PropTypes.oneOf([ 'button', 'submit', ]), theme: React.PropTypes.oneOf([ 'default', 'danger', 'success', 'info' ]), className: React.PropTypes.string, children: React.PropTypes.node, }; Button.defaultProps = { type: 'button', theme: 'default' }; module.exports = Button;
const React = require('react'); const classNames = require('classnames'); class Button extends React.Component { render() { const { className, children, type, ...props } = this.props; const buttonClassNames = classNames({ btn: true, 'btn-sm': this.props.size === 'small', 'btn-xs': this.props.size === 'extra-small', 'btn-lg': this.props.size === 'large', [`btn-${this.props.type}`]: true, }, className); return <button type="button" {...props} className={buttonClassNames} > {children} </button>; } } Button.propTypes = { size: React.PropTypes.oneOf([ 'small', 'extra-small', 'large', ]), type: React.PropTypes.oneOf([ 'default', 'danger', 'success', 'info' ]), className: React.PropTypes.string, children: React.PropTypes.node, }; Button.defaultProps = { type: 'default' }; module.exports = Button;
Add blank line between HexFormat chunks.
package uk.ac.cam.gpe21.droidssl.mitm; import uk.ac.cam.gpe21.droidssl.mitm.util.HexFormat; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public final class IoCopyRunnable implements Runnable { private final InputStream in; private final OutputStream out; public IoCopyRunnable(InputStream in, OutputStream out) { this.in = in; this.out = out; } @Override public void run() { try { byte[] buf = new byte[4096]; int n; while ((n = in.read(buf, 0, buf.length)) != -1) { System.out.println(HexFormat.format(buf, n) + "\n"); out.write(buf, 0, n); } } catch (IOException ex) { // TODO deal with properly (print warning, close socket?) } } }
package uk.ac.cam.gpe21.droidssl.mitm; import uk.ac.cam.gpe21.droidssl.mitm.util.HexFormat; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public final class IoCopyRunnable implements Runnable { private final InputStream in; private final OutputStream out; public IoCopyRunnable(InputStream in, OutputStream out) { this.in = in; this.out = out; } @Override public void run() { try { byte[] buf = new byte[4096]; int n; while ((n = in.read(buf, 0, buf.length)) != -1) { System.out.println(HexFormat.format(buf, n)); out.write(buf, 0, n); } } catch (IOException ex) { // TODO deal with properly (print warning, close socket?) } } }
[Telemetry] Increase Kraken timeout to allow it to pass on Android. BUG=163680 TEST=tools/perf/run_multipage_benchmarks --browser=android-content-shell kraken tools/perf/page_sets/kraken.json Review URL: https://chromiumcodereview.appspot.com/11519015 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@172374 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2012 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. from telemetry import multi_page_benchmark from telemetry import util def _Mean(l): return float(sum(l)) / len(l) if len(l) > 0 else 0.0 class Kraken(multi_page_benchmark.MultiPageBenchmark): def MeasurePage(self, _, tab, results): js_is_done = """ document.title.indexOf("Results") != -1 && document.readyState == "complete" """ def _IsDone(): return bool(tab.runtime.Evaluate(js_is_done)) util.WaitFor(_IsDone, 500, poll_interval=5) js_get_results = """ var formElement = document.getElementsByTagName("input")[0]; decodeURIComponent(formElement.value.split("?")[1]); """ result_dict = eval(tab.runtime.Evaluate(js_get_results)) total = 0 for key in result_dict: if key == 'v': continue results.Add(key, 'ms', result_dict[key], data_type='unimportant') total += _Mean(result_dict[key]) results.Add('Total', 'ms', total)
# Copyright (c) 2012 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. from telemetry import multi_page_benchmark from telemetry import util def _Mean(l): return float(sum(l)) / len(l) if len(l) > 0 else 0.0 class Kraken(multi_page_benchmark.MultiPageBenchmark): def MeasurePage(self, _, tab, results): js_is_done = """ document.title.indexOf("Results") != -1 && document.readyState == "complete" """ def _IsDone(): return bool(tab.runtime.Evaluate(js_is_done)) util.WaitFor(_IsDone, 300) js_get_results = """ var formElement = document.getElementsByTagName("input")[0]; decodeURIComponent(formElement.value.split("?")[1]); """ result_dict = eval(tab.runtime.Evaluate(js_get_results)) total = 0 for key in result_dict: if key == 'v': continue results.Add(key, 'ms', result_dict[key], data_type='unimportant') total += _Mean(result_dict[key]) results.Add('Total', 'ms', total)
Fix typo in name of variable
#!/usr/bin/env python3 import os from datetime import timedelta _BAYESIAN_JOBS_DIR = os.path.dirname(os.path.realpath(__file__)) DEFAULT_SERVICE_PORT = 34000 SWAGGER_YAML_PATH = os.path.join(_BAYESIAN_JOBS_DIR, 'swagger.yaml') DEFAULT_JOB_DIR = os.path.join(_BAYESIAN_JOBS_DIR, 'default_jobs') TOKEN_VALID_TIME = timedelta(days=14) AUTH_ORGANIZATION = 'fabric8-analytics' DISABLE_AUTHENTICATION = bool(os.environ.get('DISABLE_AUTHENTICATION', False)) GITHUB_CONSUMER_KEY = os.environ.get('GITHUB_CONSUMER_KEY', '96d6ad4971dfec52cd7c') GITHUB_CONSUMER_SECRET = os.environ.get('GITHUB_CONSUMER_SECRET', '97a65e9066a9e4468a9a024a25073ea6e10e8ab6') GITHUB_ACCESS_TOKEN = os.environ.get('GITHUB_ACCESS_TOKEN', '2ba44d20f2da859184b8ab11460952d49cbde32a') APP_SECRET_KEY = os.environ.get('APP_SECRET_KEY', 'euYu3Ma6AhV7ieshOen4neigluL9aith')
#!/usr/bin/env python3 import os from datetime import timedelta _BAYESIAN_JOBS_DIR = os.path.dirname(os.path.realpath(__file__)) DEFAULT_SERVICE_PORT = 34000 SWAGGER_YAML_PATH = os.path.join(_BAYESIAN_JOBS_DIR, 'swagger.yaml') DEFAULT_JOB_DIR = os.path.join(_BAYESIAN_JOBS_DIR, 'default_jobs') TOKEN_VALID_TIME = timedelta(days=14) AUTH_ORGANIZATION = 'fabric8-analytics' DISABLE_AUTHENTICATION = bool(os.environ.get('DISABLE_AUTHENTICATION', False)) GITHUB_CONSUMER_KEY = os.environ.get('GITHUB_CONSUMENR_KEY', '96d6ad4971dfec52cd7c') GITHUB_CONSUMER_SECRET = os.environ.get('GITHUB_CONSUMER_SECRET', '97a65e9066a9e4468a9a024a25073ea6e10e8ab6') GITHUB_ACCESS_TOKEN = os.environ.get('GITHUB_ACCESS_TOKEN', '2ba44d20f2da859184b8ab11460952d49cbde32a') APP_SECRET_KEY = os.environ.get('APP_SECRET_KEY', 'euYu3Ma6AhV7ieshOen4neigluL9aith')
Set config contained a bug after refactoring
import argparse import logging.config from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-port', help='Change the port') args = parser.parse_args() if args.host is not None: settings.set_config('SERVER', 'host', args.host) logging.INFO("Host changed to %s", args.host) if args.port is not None: settings.set_config('SERVER', 'port', args.port) logging.INFO("Port changed to %s", args.port) if not settings.all_files_exist(): raise RuntimeError("Some necessary files were missing. Please consult the log.") server = Server(host=settings.get_config('SERVER', 'host'), port=settings.get_config('SERVER', 'port')) server.start() if __name__ == '__main__': main()
import argparse import logging.config import os from intexration import settings from intexration.server import Server # Logger logging.config.fileConfig(settings.LOGGING_FILE) def main(): parser = argparse.ArgumentParser() parser.add_argument('-host', help='Change the hostname') parser.add_argument('-port', help='Change the port') args = parser.parse_args() if args.host is not None: settings.set_config('host', args.host) logging.INFO("Host changed to %s", args.host) if args.port is not None: settings.set_config('port', args.port) logging.INFO("Port changed to %s", args.port) if not settings.all_files_exist(): raise RuntimeError("Some necessary files were missing. Please consult the log.") server = Server(host=settings.get_config('SERVER', 'host'), port=settings.get_config('SERVER', 'port')) server.start() if __name__ == '__main__': main()
[FIX] Return Ayah's pk instead of number
from django.urls import reverse from rest_framework import serializers from .models import Tafseer, TafseerText class TafseerSerializer(serializers.ModelSerializer): class Meta: model = Tafseer fields = ['id', 'name'] class TafseerTextSerializer(serializers.ModelSerializer): tafseer_id = serializers.IntegerField(source='tafseer.id') tafseer_name = serializers.CharField(source='tafseer.name') ayah_url = serializers.SerializerMethodField() ayah_number = serializers.IntegerField(source='ayah.number') def get_ayah_url(self, obj): return reverse('ayah-detail', kwargs={'number': obj.ayah.number, 'sura_num': obj.ayah.sura.pk}) class Meta: model = TafseerText fields = ['tafseer_id', 'tafseer_name', 'ayah_url', 'ayah_number', 'text']
from django.urls import reverse from rest_framework import serializers from .models import Tafseer, TafseerText class TafseerSerializer(serializers.ModelSerializer): class Meta: model = Tafseer fields = ['id', 'name'] class TafseerTextSerializer(serializers.ModelSerializer): tafseer_id = serializers.IntegerField(source='tafseer.id') tafseer_name = serializers.CharField(source='tafseer.name') ayah_url = serializers.SerializerMethodField() ayah_number = serializers.IntegerField(source='ayah.pk') def get_ayah_url(self, obj): return reverse('ayah-detail', kwargs={'number': obj.ayah.number, 'sura_num': obj.ayah.sura.pk}) class Meta: model = TafseerText fields = ['tafseer_id', 'tafseer_name', 'ayah_url', 'ayah_number', 'text']
Add delete old sessions command
from datetime import datetime from django.core.management.base import BaseCommand from django.contrib.sessions.models import Session """ >>> def clean(count): ... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]): ... s.delete() ... if str(idx).endswith('000'): print idx ... print "{0} records left".format(Session.objects.filter(expire_date__lt=now).count()) ... """ class Command(NoArgsCommand): args = '<count count ...>' help = "Delete old sessions" def handle(self, *args, **options): old_sessions = Session.objects.filter(expire_date__lt=datetime.now()) self.stdout.write("Deleting {0} expired sessions".format( old_sessions.count() ) ) for index, session in enumerate(old_sessions): session.delete() if str(idx).endswith('000'): self.stdout.write("{0} records deleted".format(index)) self.stdout.write("{0} expired sessions remaining".format( Session.objects.filter(expire_date__lt=datetime.now()) ) )
from datetime import datetime from django.core.management.base import BaseCommand from django.contrib.sessions.models import Session """ >>> def clean(count): ... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]): ... s.delete() ... if str(idx).endswith('000'): print idx ... print "{0} records left".format(Session.objects.filter(expire_date__lt=now).count()) ... """ class Command(NoArgsCommand): args = '<count count ...>' help = "Delete old sessions" def handle(self, *args, **options): old_sessions = Session.objects.filter(expire_date__lt=datetime.now()) self.stdout.write("Deleting {0} expired sessions".format( old_sessions.count() ) ) for index, session in enumerate(old_sessions): session.delete() if str(idx).endswith('000'): self.stdout.write("{0} records deleted".format(index) self.stdout.write("{0} expired sessions remaining".format( Session.objects.filter(expire_date__lt=datetime.now()) ) )
Update expected value on test
import markdown from mdx_embedly import EmbedlyExtension def test_embedly(): s = "[https://github.com/yymm:embed]" expected = """ <p> <a class="embedly-card" href="https://github.com/yymm">embed.ly</a> <script async src="//cdn.embedly.com/widgets/platform.js" charset="UTF-8"></script> </p> """.strip() html = markdown.markdown(s, extensions=[EmbedlyExtension()]) assert html == expected def test_gist(): s = "[https://gist.github.com/yymm/726df7f0e4ed48e54a06:embed]" expected = """ <p> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gist-embed/2.4/gist-embed.min.js"></script> <code data-gist-id="726df7f0e4ed48e54a06"></code> </p> """.strip() html = markdown.markdown(s, extensions=[EmbedlyExtension()]) assert html == expected
import markdown from mdx_embedly import EmbedlyExtension def test_embedly(): s = "[https://github.com/yymm:embed]" expected = """ <p> <a class="embedly-card" href="https://github.com/yymm">embed.ly</a> <script async src="//cdn.embedly.com/widgets/platform.js"charset="UTF-8"></script> </p> """.strip() html = markdown.markdown(s, extensions=[EmbedlyExtension()]) assert html == expected def test_gist(): s = "[https://gist.github.com/yymm/726df7f0e4ed48e54a06:embed]" expected = """ <p> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gist-embed/2.4/gist-embed.min.js"></script> <code data-gist-id="726df7f0e4ed48e54a06"></code> </p> """.strip() html = markdown.markdown(s, extensions=[EmbedlyExtension()]) assert html == expected
Delete auto generated comments. Comment out the entire file.
package com.biotronisis.pettplant.type; //public enum EntrainmentMode { // oldMEDITATE(0), // oldSLEEP(1), // oldSTAY_AWAKE(2); // Run/Stop button values // public static final String RUN = "Run"; // public static final String STOP = "Stop"; // Pause/Resume button values // public static final String PAUSE = "Pause"; // public static final String RESUME = "Resume"; // Loop checkbox values // public static final String LOOP_OFF = "Off"; // public static final String LOOP_ON = "On"; // // public static final boolean LOOP_CHECKBOX_DEFAULT = false; // private int id; // EntrainmentMode(int id) { // this.id = id; // } // public int getValue() { // return id; // } // // public int getId() { // return id; // } // // public static EntrainmentMode getEntrainmentMode(int id) { // return EntrainmentMode.values()[id]; // } //}
package com.biotronisis.pettplant.type; /** * Created by john on 6/16/15. */ public enum EntrainmentMode { oldMEDITATE(0), oldSLEEP(1), oldSTAY_AWAKE(2); // Run/Stop button values // public static final String RUN = "Run"; // public static final String STOP = "Stop"; // Pause/Resume button values // public static final String PAUSE = "Pause"; // public static final String RESUME = "Resume"; // Loop checkbox values // public static final String LOOP_OFF = "Off"; // public static final String LOOP_ON = "On"; // // public static final boolean LOOP_CHECKBOX_DEFAULT = false; private int id; EntrainmentMode(int id) { this.id = id; } // public int getValue() { // return id; // } // // public int getId() { // return id; // } // // public static EntrainmentMode getEntrainmentMode(int id) { // return EntrainmentMode.values()[id]; // } }
Fix shell script reference - note to self add to other hooks
<?php include 'config.php'; list($algo, $hash) = explode('=', $_SERVER["HTTP_X_HUB_SIGNATURE"], 2); $payload = file_get_contents('php://input'); $payloadHash = hash_hmac($algo, $payload, $secret); if ($hash !== $payloadHash) { http_response_code(401); echo "Bad secret"; exit; } $data = json_decode($payload, true); echo "Authenticated properly\nDelivery ID: ".$_SERVER["HTTP_X_GITHUB_DELIVERY"]."\nRepository to deploy: ".$data["repository"]["full_name"]."\n"; echo passthru("/bin/bash ".__DIR__."/pullsimple.sh ".$data["repository"]["name"]." ".$data["repository"]["full_name"]." ".$auth." 2>&1"); if (isset($email_from, $email_to)) { mail($email_to, "[".$data["repository"]["full_name"]."] New ".$_SERVER["HTTP_X_GITHUB_EVENT"]." triggered a deployment", ob_get_contents(), "From: ".$email_from); } if (file_exists('/var/www/'.$data["repository"]["name"].'/post-deploy-hook.php')) { include('/var/www/'.$data["repository"]["name"].'/post-deploy-hook.php'); }
<?php include 'config.php'; list($algo, $hash) = explode('=', $_SERVER["HTTP_X_HUB_SIGNATURE"], 2); $payload = file_get_contents('php://input'); $payloadHash = hash_hmac($algo, $payload, $secret); if ($hash !== $payloadHash) { http_response_code(401); echo "Bad secret"; exit; } $data = json_decode($payload, true); echo "Authenticated properly\nDelivery ID: ".$_SERVER["HTTP_X_GITHUB_DELIVERY"]."\nRepository to deploy: ".$data["repository"]["full_name"]."\n"; echo passthru("/bin/bash ".$_SERVER['DOCUMENT_ROOT']."/pullsimple.sh ".$data["repository"]["name"]." ".$data["repository"]["full_name"]." ".$auth." 2>&1"); if (isset($email_from, $email_to)) { mail($email_to, "[".$data["repository"]["full_name"]."] New ".$_SERVER["HTTP_X_GITHUB_EVENT"]." triggered a deployment", ob_get_contents(), "From: ".$email_from); } if (file_exists('/var/www/'.$data["repository"]["name"].'/post-deploy-hook.php')) { include('/var/www/'.$data["repository"]["name"].'/post-deploy-hook.php'); }
Use AttachUser middleware before verifyAdmin.
const userController = require('../controllers/user'); const authenticationMiddleware = require('../middleware/authentication'); const express = require('express'); const router = express.Router(); // GET all users router.get( '/', // route authenticationMiddleware.validateAuthentication, // isAuthenticated middleware userController.getUsers // the controller ); // GET a specific user router.get( '/:id', authenticationMiddleware.validateAuthentication, // isAuthenticated middleware userController.getUserById ); // CREATE a new user router.post('/', userController.registerNewUser); // DELETE a user router.delete( '/:id', authenticationMiddleware.validateAuthentication, // isAuthenticated middleware userController.deleteUserById ); router.patch( '/:id/roles', authenticationMiddleware.validateAuthenticationAttachUser, // verify token and attach user to res authenticationMiddleware.verifyAdministrator, // verifyAdministrator middleware userController.setRoles ); module.exports = router;
const userController = require('../controllers/user'); const authenticationMiddleware = require('../middleware/authentication'); const express = require('express'); const router = express.Router(); // GET all users router.get( '/', // route authenticationMiddleware.validateAuthentication, // isAuthenticated middleware userController.getUsers // the controller ); // GET a specific user router.get( '/:id', authenticationMiddleware.validateAuthentication, // isAuthenticated middleware userController.getUserById ); // CREATE a new user router.post('/', userController.registerNewUser); // DELETE a user router.delete( '/:id', authenticationMiddleware.validateAuthentication, // isAuthenticated middleware userController.deleteUserById ); router.patch( '/:id/roles', authenticationMiddleware.validateAuthentication, // isAuthenticated middleware authenticationMiddleware.verifyAdministrator, // verifyAdministrator middleware userController.setRoles ); module.exports = router;