text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Use asyncio.run() to run the test client. This makes for cleaner code.
import asyncio import platform import time from zeep import AsyncClient from zeep.cache import InMemoryCache from zeep.transports import AsyncTransport # Spyne SOAP client using Zeep and async transport. Run with python -m examples.test_client # Allow CTRL+C on windows console w/ asyncio if platform.system() == "Windows": import signal signal.signal(signal.SIGINT, signal.SIG_DFL) async def do_call(client, text, number): result = await client.service.say_hello(text=text, number=number) return result == "{} {}".format(text, number) def generate_tasks(client): tasks = [] for m in range(10000): tasks.append(asyncio.ensure_future(do_call(client, "Tester", m))) return tasks async def send_messages(client): start = time.time() results = await asyncio.gather(*generate_tasks(client)) delta_time = time.time() - start print("Result: ", all(results)) print(delta_time) async def main(): client = AsyncClient( wsdl="http://localhost:8080/say_hello/?WSDL", transport=AsyncTransport(cache=InMemoryCache(timeout=None)), ) await send_messages(client) await client.transport.aclose() if __name__ == "__main__": asyncio.run(main())
import asyncio import platform import time from zeep import AsyncClient from zeep.cache import InMemoryCache from zeep.transports import AsyncTransport # Spyne SOAP client using Zeep and async transport. Run with python -m examples.test_client # Allow CTRL+C on windows console w/ asyncio if platform.system() == "Windows": import signal signal.signal(signal.SIGINT, signal.SIG_DFL) async def do_call(client, text, number): result = await client.service.say_hello(text=text, number=number) return result == "{} {}".format(text, number) def generate_tasks(client): tasks = [] for m in range(10000): tasks.append(asyncio.ensure_future(do_call(client, "Tester", m))) return tasks async def send_messages(client): start = time.time() results = await asyncio.gather(*generate_tasks(client)) delta_time = time.time() - start print("Result: ", all(results)) print(delta_time) def main(): loop = asyncio.get_event_loop() client = AsyncClient( wsdl="http://localhost:8080/say_hello/?WSDL", transport=AsyncTransport(cache=InMemoryCache(timeout=None)), ) loop.run_until_complete(send_messages(client)) loop.run_until_complete(client.transport.aclose()) if __name__ == "__main__": main()
Add a check for an array to prevent fatal error
<?php /** * Go! OOP&AOP PHP framework * * @copyright Copyright 2013, Lissachenko Alexander <lisachenko.it@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ namespace Go\Instrument\ClassLoading; use Go\Instrument\ClassLoading\UniversalClassLoader; /** * Ensures that autoloader of Go! library is first in the stack of autoloaders * * This fix problems with autoloaders that was prepended, for example, composer. * * @return void */ function ensureLibraryAutoloaderIsFirst() { $loaders = spl_autoload_functions(); if ($loaders && isset($loaders[0]) && is_array($loaders[0])) { if ($loaders[0][0] instanceof UniversalClassLoader) { return; } } $newLoaders = array(); foreach ($loaders as $loader) { spl_autoload_unregister($loader); if (is_array($loader) && ($loader[0] instanceof UniversalClassLoader)) { array_unshift($newLoaders, $loader); } else { array_push($newLoaders, $loader); } } foreach ($newLoaders as $loader) { spl_autoload_register($loader); } } ensureLibraryAutoloaderIsFirst();
<?php /** * Go! OOP&AOP PHP framework * * @copyright Copyright 2013, Lissachenko Alexander <lisachenko.it@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ namespace Go\Instrument\ClassLoading; use Go\Instrument\ClassLoading\UniversalClassLoader; /** * Ensures that autoloader of Go! library is first in the stack of autoloaders * * This fix problems with autoloaders that was prepended, for example, composer. * * @return void */ function ensureLibraryAutoloaderIsFirst() { $loaders = spl_autoload_functions(); if (isset($loaders[0]) && ($loaders[0][0] instanceof UniversalClassLoader)) { return; } $newLoaders = array(); foreach ($loaders as $loader) { spl_autoload_unregister($loader); if (is_array($loader) && ($loader[0] instanceof UniversalClassLoader)) { array_unshift($newLoaders, $loader); } else { array_push($newLoaders, $loader); } } foreach ($newLoaders as $loader) { spl_autoload_register($loader); } } ensureLibraryAutoloaderIsFirst();
Disable one more graph test
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.graphrbac; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import java.util.List; public class ServicePrincipalsTests extends GraphRbacManagementTestBase { private static final String RG_NAME = "javacsmrg350"; private static final String APP_NAME = "app-javacsm350"; @BeforeClass public static void setup() throws Exception { createClients(); } @AfterClass public static void cleanup() throws Exception { } @Test @Ignore("Doesn't work when logged as a service principal") public void getServicePrincipal() throws Exception { List<ServicePrincipal> servicePrincipals = graphRbacManager.servicePrincipals().list(); Assert.assertNotNull(servicePrincipals); } }
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.graphrbac; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.List; public class ServicePrincipalsTests extends GraphRbacManagementTestBase { private static final String RG_NAME = "javacsmrg350"; private static final String APP_NAME = "app-javacsm350"; @BeforeClass public static void setup() throws Exception { createClients(); } @AfterClass public static void cleanup() throws Exception { } @Test public void getServicePrincipal() throws Exception { List<ServicePrincipal> servicePrincipals = graphRbacManager.servicePrincipals().list(); Assert.assertNotNull(servicePrincipals); } }
Rename Legal to Data policy
import React from 'react' import './Footer.scss' export const Footer = () => ( <div className='footer'> <div className='container'> <ul className='footer-links'> <li> <a href='https://ooni.torproject.org/about/'>About OONI</a> </li> <li> <a href='https://ooni.torproject.org/about/data-policy/'>Data policy</a> </li> <li> <a href='mailto:contact@openobservatory.org'>Help</a> </li> <li> <a href='https://explorer.ooni.torproject.org/'>Explore data</a> </li> </ul> </div> </div> ) export default Footer
import React from 'react' import './Footer.scss' export const Footer = () => ( <div className='footer'> <div className='container'> <ul className='footer-links'> <li> <a href='https://ooni.torproject.org/about/'>About OONI</a> </li> <li> <a href='https://ooni.torproject.org/about/data-policy/'>Legal</a> </li> <li> <a href='mailto:contact@openobservatory.org'>Help</a> </li> <li> <a href='https://explorer.ooni.torproject.org/'>Explore data</a> </li> </ul> </div> </div> ) export default Footer
Update test to cover windows environment Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Tenanti\Tests\Unit\Migrator; use Mockery as m; use Orchestra\Tenanti\Migrator\Creator; use PHPUnit\Framework\TestCase; class CreatorTest extends TestCase { /** * Teardown the test environment. */ protected function tearDown(): void { m::close(); } /** * Test Orchestra\Tenanti\Migrator\Creator::getStubPath() * method. * * @test */ public function testGetStubPath() { $files = m::mock('Illuminate\Filesystem\Filesystem'); $stub = new Creator($files); $path = \realpath(__DIR__.'/../../../'); $this->assertStringContainsString($path.\DIRECTORY_SEPARATOR.'src/Migrator/stubs', $stub->stubPath()); } }
<?php namespace Orchestra\Tenanti\Tests\Unit\Migrator; use Mockery as m; use Orchestra\Tenanti\Migrator\Creator; use PHPUnit\Framework\TestCase; class CreatorTest extends TestCase { /** * Teardown the test environment. */ protected function tearDown(): void { m::close(); } /** * Test Orchestra\Tenanti\Migrator\Creator::getStubPath() * method. * * @test */ public function testGetStubPath() { $files = m::mock('Illuminate\Filesystem\Filesystem'); $stub = new Creator($files); $this->assertStringContainsString('src/Migrator/stubs', $stub->stubPath()); } }
Remove rogue debugger how embarassing
from rest_framework import serializers as ser from api.base.utils import absolute_reverse from api.base.serializers import JSONAPISerializer, RelationshipField, IDField, LinksField class IdentifierSerializer(JSONAPISerializer): category = ser.CharField(read_only=True) filterable_fields = frozenset(['category']) value = ser.CharField(read_only=True) referent = RelationshipField( related_view='registrations:registration-detail', related_view_kwargs={'node_id': '<referent._id>'}, ) id = IDField(source='_id', read_only=True) links = LinksField({'self': 'self_url'}) class Meta: type_ = 'identifiers' def get_absolute_url(self, obj): return obj.absolute_api_v2_url def get_id(self, obj): return obj._id def get_detail_url(self, obj): return '{}/identifiers/{}'.format(obj.absolute_api_v2_url, obj._id) def self_url(self, obj): return absolute_reverse('identifiers:identifier-detail', kwargs={ 'identifier_id': obj._id, })
from rest_framework import serializers as ser from api.base.utils import absolute_reverse from api.base.serializers import JSONAPISerializer, RelationshipField, IDField, LinksField class IdentifierSerializer(JSONAPISerializer): category = ser.CharField(read_only=True) filterable_fields = frozenset(['category']) value = ser.CharField(read_only=True) referent = RelationshipField( related_view='registrations:registration-detail', related_view_kwargs={'node_id': '<referent._id>'}, ) id = IDField(source='_id', read_only=True) links = LinksField({'self': 'self_url'}) class Meta: type_ = 'identifiers' def get_absolute_url(self, obj): return obj.absolute_api_v2_url def get_id(self, obj): return obj._id def get_detail_url(self, obj): import ipdb; ipdb.set_trace() return '{}/identifiers/{}'.format(obj.absolute_api_v2_url, obj._id) def self_url(self, obj): return absolute_reverse('identifiers:identifier-detail', kwargs={ 'identifier_id': obj._id, })
Featured-image: Stop limiting error handling for aggregated requests Several feed endpoints have graceful error handling for aggregated requests, meant to allow RESTBase to gracefully omit featured feed content where the underlying content is not found as expected. For the featured image endpoint, this is limited to 504 responses for some reason. That doesn't seem necessary or desirable, so this removes it. Also removed some unused imports. Change-Id: Id5282325b51ae2eb3514a2ee56afbb7c755c4aff
/** * To retrieve the picture of the day for a given date. */ 'use strict'; const BBPromise = require('bluebird'); const dateUtil = require('../dateUtil'); const imageinfo = require('../imageinfo'); /** * Get imageinfo data for featured image (Picture of the day) * @param {Object} req req Server request * @param {Object} siteinfo Site info object * @return {Object} featured image response */ function promise(req, siteinfo) { const aggregated = !!req.query.aggregated; if (!dateUtil.validate(dateUtil.hyphenDelimitedDateString(req))) { if (aggregated) { return BBPromise.resolve({ meta: {} }); } dateUtil.throwDateError(); } return imageinfo.requestPictureOfTheDay(req, dateUtil.getRequestedDate(req), siteinfo) .catch((err) => { if (aggregated) { return BBPromise.resolve({ meta: {} }); } throw err; }); } module.exports = { promise, };
/** * To retrieve the picture of the day for a given date. */ 'use strict'; const BBPromise = require('bluebird'); const dateUtil = require('../dateUtil'); const sUtil = require('../util'); const imageinfo = require('../imageinfo'); const HTTPError = sUtil.HTTPError; /** * Get imageinfo data for featured image (Picture of the day) * @param {Object} app App object * @param {Object} req req Server request * @param {Object} siteinfo Site info object * @return {Object} featured image response */ function promise(req, siteinfo) { const aggregated = !!req.query.aggregated; if (!dateUtil.validate(dateUtil.hyphenDelimitedDateString(req))) { if (aggregated) { return BBPromise.resolve({ meta: {} }); } dateUtil.throwDateError(); } return imageinfo.requestPictureOfTheDay(req, dateUtil.getRequestedDate(req), siteinfo) .catch((err) => { if (aggregated && err.status === 504) { return BBPromise.resolve({ meta: {} }); } throw err; }); } module.exports = { promise, };
Fix encoding issue when test lcd
# -*- coding: utf-8 -*- import unittest from ev3.ev3dev import Lcd from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main()
from ev3.ev3dev import Lcd # -*- coding: utf-8 -*- import unittest from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main()
Convert tabs to spaces in source.
/* Hover Image Replacement Plug-in for jQuery * * Authors: * Sam Moore - sam@hashtack.com * * Adds a query function to swap the 'src' attribute * of the given img tag to a desired URL on hover. * */ (function ( $ ) { swapImageSrc = function (image) { oldSrc = image.attr('src'); newSrc = image.attr('data-hover-image') image.attr('src', newSrc); image.attr('data-hover-image', oldSrc); }; hoverCallback = function(image, animated) { // TODO: add animated option swapImageSrc( $(image.delegateTarget) ); }; $.fn.hoverImg = function ( hover_src ) { this.attr('data-hover-image', hover_src); this.hover( hoverCallback, hoverCallback ); }; })( jQuery );
/* Hover Image Replacement Plug-in for jQuery * * Authors: * Sam Moore - sam@hashtack.com * * Adds a query function to swap the 'src' attribute * of the given img tag to a desired URL on hover. * */ (function ( $ ) { swapImageSrc = function (image) { oldSrc = image.attr('src'); newSrc = image.attr('data-hover-image') image.attr('src', newSrc); image.attr('data-hover-image', oldSrc); }; hoverCallback = function(image, animated) { // TODO: add animated option swapImageSrc( $(image.delegateTarget) ); }; $.fn.hoverImg = function ( hover_src ) { this.attr('data-hover-image', hover_src); this.hover( hoverCallback, hoverCallback ); }; })( jQuery );
Add missing 'use SA\CpeSDK' in SWF HAndler
<?php namespace SA\CpeSdk\Swf; use Aws\Swf\SwfClient; // SA Cpe SDK use SA\CpeSdk; /** * Create the AWS SWF connection * Check for AWS environment variables */ class CpeSwfHandler { public $swf; public function __construct() { # Check if preper env vars are setup if (!($region = getenv("AWS_DEFAULT_REGION"))) throw new CpeSdk\CpeException("Set 'AWS_DEFAULT_REGION' environment variable!"); if (!getenv('AWS_ACCESS_KEY_ID')) throw new CpeSdk\CpeException("Set 'AWS_ACCESS_KEY_ID' environment variable!"); if (!getenv('AWS_SECRET_ACCESS_KEY')) throw new CpeSdk\CpeException("Set 'AWS_SECRET_ACCESS_KEY' environment variable!"); // SWF client $this->swf = SwfClient::factory(array( 'region' => $region )); } }
<?php namespace SA\CpeSdk\Swf; use Aws\Swf\SwfClient; /** * Create the AWS SWF connection * Check for AWS environment variables */ class CpeSwfHandler { public $swf; public function __construct() { # Check if preper env vars are setup if (!($region = getenv("AWS_DEFAULT_REGION"))) throw new CpeSdk\CpeException("Set 'AWS_DEFAULT_REGION' environment variable!"); if (!getenv('AWS_ACCESS_KEY_ID')) throw new CpeSdk\CpeException("Set 'AWS_ACCESS_KEY_ID' environment variable!"); if (!getenv('AWS_SECRET_ACCESS_KEY')) throw new CpeSdk\CpeException("Set 'AWS_SECRET_ACCESS_KEY' environment variable!"); // SWF client $this->swf = SwfClient::factory(array( 'region' => $region )); } }
Support correctly weird characters in filenames when downloading This commit add support for the following: - Correctly encoded oData parameter sent to the endpoint. - Support for # and % in filenames by using a newer 365 endpoint. Summary: Current implementation was injecting an URL directly quoted to the endpoint, instead of encoding as an oData value. This was solved by using the encode_method_value method. This fixes issues when the file contains weird characters, like slashes and single quotes. The getFileServerByUrl endpoint does not support some characters in filenames, like # and %. A newer endpoint (getFileByServerRelativePath) is used instead, which allows to download files with those characters.
from office365.runtime.http.http_method import HttpMethod from office365.runtime.odata.odata_path_parser import ODataPathParser from office365.runtime.queries.service_operation_query import ServiceOperationQuery class DownloadFileQuery(ServiceOperationQuery): def __init__(self, web, file_url, file_object): """ A download file content query :type file_url: str :type web: office365.sharepoint.webs.web.Web :type file_object: typing.IO """ def _construct_download_query(request): request.method = HttpMethod.Get self.context.after_execute(_process_response) def _process_response(response): """ :type response: RequestOptions """ file_object.write(response.content) # Sharepoint Endpoint bug: https://github.com/SharePoint/sp-dev-docs/issues/2630 file_url = ODataPathParser.encode_method_value(file_url) super(DownloadFileQuery, self).__init__(web, r"getFileByServerRelativePath(decodedurl={0})/$value".format(file_url)) self.context.before_execute(_construct_download_query)
from office365.runtime.http.http_method import HttpMethod from office365.runtime.queries.service_operation_query import ServiceOperationQuery class DownloadFileQuery(ServiceOperationQuery): def __init__(self, web, file_url, file_object): """ A download file content query :type file_url: str :type web: office365.sharepoint.webs.web.Web :type file_object: typing.IO """ def _construct_download_query(request): request.method = HttpMethod.Get self.context.after_execute(_process_response) def _process_response(response): """ :type response: RequestOptions """ file_object.write(response.content) super(DownloadFileQuery, self).__init__(web, r"getFileByServerRelativeUrl('{0}')/\$value".format(file_url)) self.context.before_execute(_construct_download_query)
Update PSR-2 and remove unused use Former-commit-id: e54069691862a3c7d4249b624a720b9a536875cc
<?php namespace Concrete\Core\Form\Service\Widget; use View; class Typography { /** * Creates form fields and JavaScript includes to add a font picker widget. * <code> * $dh->output('background-color', '#f00'); * </code> * @param string $inputName * @param array $value * @param array $options */ public function output($inputName, $value = array(), $options = array()) { $view = View::getInstance(); $view->requireAsset('core/style-customizer'); $options['inputName'] = $inputName; $options = array_merge($options, $value); $strOptions = json_encode($options); print '<span class="ccm-style-customizer-display-swatch-wrapper" data-font-selector="' . $inputName . '"></span>'; print "<script type=\"text/javascript\">"; print "$(function () { $('span[data-font-selector={$inputName}]').concreteTypographySelector({$strOptions}); })"; print "</script>"; } }
<?php namespace Concrete\Core\Form\Service\Widget; use Loader; use View; use Request; class Typography { /** * Creates form fields and JavaScript includes to add a font picker widget. * <code> * $dh->output('background-color', '#f00'); * </code> * @param string $inputName * @param array $value * @param array $options */ public function output($inputName, $value = array(), $options = array()) { $view = View::getInstance(); $view->requireAsset('core/style-customizer'); $options['inputName'] = $inputName; $options = array_merge($options, $value); $strOptions = json_encode($options); print '<span class="ccm-style-customizer-display-swatch-wrapper" data-font-selector="' . $inputName . '"></span>'; print "<script type=\"text/javascript\">"; print "$(function() { $('span[data-font-selector={$inputName}]').concreteTypographySelector({$strOptions}); })"; print "</script>"; } }
Fix ConnectedSWFObject: pass default value to pop()
# -*- coding:utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. import boto.swf from . import settings SETTINGS = settings.get() class ConnectedSWFObject(object): """Authenticated object interface Provides the instance attributes: - `region`: name of the AWS region - `connection`: to the SWF endpoint (`boto.swf.layer1.Layer1` object): """ __slots__ = [ 'region', 'connection' ] def __init__(self, *args, **kwargs): settings_ = {k: v for k, v in SETTINGS.iteritems()} settings_.update(kwargs) self.region = (settings_.pop('region', None) or boto.swf.layer1.Layer1.DefaultRegionName) self.connection = boto.swf.connect_to_region(self.region, **settings_) if self.connection is None: raise ValueError('invalid region: {}'.format(self.region))
# -*- coding:utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. import boto.swf from . import settings SETTINGS = settings.get() class ConnectedSWFObject(object): """Authenticated object interface Provides the instance attributes: - `region`: name of the AWS region - `connection`: to the SWF endpoint (`boto.swf.layer1.Layer1` object): """ __slots__ = [ 'region', 'connection' ] def __init__(self, *args, **kwargs): settings_ = {k: v for k, v in SETTINGS.iteritems()} settings_.update(kwargs) self.region = (settings_.pop('region') or boto.swf.layer1.Layer1.DefaultRegionName) self.connection = boto.swf.connect_to_region(self.region, **settings_) if self.connection is None: raise ValueError('invalid region: {}'.format(self.region))
Clear create comment form after posting.
module.exports = Zeppelin.FormView.extend({ className: 'create-comment', formSelector: 'form.create-comment-form', template: require('account/templates/create-comment'), model: require('core/models/comment'), elements: { 'commentInput': 'textarea.create-comment-input' }, events: { 'click [data-action=cancel]': 'onCancel', 'focus textarea.create-comment-input': 'toggleActions' }, context: function() { return { creator: this.options.user } }, initialize: function() { this.prepareModel(); }, toggleActions: function() { this.$el.toggleClass('is-open'); this.getElement('commentInput').css({ height: '35px' }); }, prepareModel: function() { this.setModel(require('core/models/comment')); this.model.set('card', this.options.card); return this; }, onRender: function() { this.getElement('commentInput').autosize(); }, onCancel: function() { this.toggleActions(); this.reset(); }, onValidationSuccess: function() { this.broadcast('comment:created', this.model); }, onSubmit: function() { this.toggleActions(); this.prepareModel(); this.reset(); } });
module.exports = Zeppelin.FormView.extend({ className: 'create-comment', formSelector: 'form.create-comment-form', template: require('account/templates/create-comment'), model: require('core/models/comment'), elements: { 'commentInput': 'textarea.create-comment-input' }, events: { 'click [data-action=cancel]': 'onCancel', 'focus textarea.create-comment-input': 'toggleActions' }, context: function() { return { creator: this.options.user } }, initialize: function() { this.prepareModel(); }, toggleActions: function() { this.$el.toggleClass('is-open'); this.getElement('commentInput').css({ height: '35px' }); }, prepareModel: function() { this.setModel(require('core/models/comment')); this.model.set('card', this.options.card); return this; }, onRender: function() { this.getElement('commentInput').autosize(); }, onCancel: function() { this.reset(); this.toggleActions(); }, onValidationSuccess: function() { this.broadcast('comment:created', this.model); }, onSubmit: function() { this.reset(); this.toggleActions(); this.prepareModel(); } });
Fix model definition in signature form
from petition.forms import BaseSignatureForm from crispy_forms.layout import Layout from crispy_forms.bootstrap import PrependedText import swapper Signature = swapper.load_model("petition", "Signature") class SignatureForm(BaseSignatureForm): def __init__(self, *args, **kwargs): super(SignatureForm, self).__init__(*args, **kwargs) self.helper.layout = Layout( 'first_name', 'last_name', PrependedText('email', '@'), PrependedText('city', '<i class="fa fa-globe"></i>'), PrependedText('telephone', '<i class="fa fa-phone"></i>'), 'giodo', 'newsletter', ) class Meta: model = Signature
from petition.forms import BaseSignatureForm from crispy_forms.layout import Layout from crispy_forms.bootstrap import PrependedText class SignatureForm(BaseSignatureForm): def __init__(self, *args, **kwargs): super(SignatureForm, self).__init__(*args, **kwargs) self.helper.layout = Layout( 'first_name', 'last_name', PrependedText('email', '@'), PrependedText('city', '<i class="fa fa-globe"></i>'), PrependedText('telephone', '<i class="fa fa-phone"></i>'), 'giodo', 'newsletter', )
Set updatedAt field on insertion
events = {}; events.beforeInsert = function() { var doc = this; var Class = doc.constructor; // Find a class on which the behavior had been set. var behaviorData = Astro.utils.behaviors.findBehavior( Class, 'timestamp' ); // Get current date. var date = new Date(); // If the "hasCreatedField" option is set. if (behaviorData.hasCreatedField) { // Set value for created field. this.set(behaviorData.createdFieldName, date); } if (behaviorData.hasUpdatedField) { // Set value for the "updatedAt" field. this.set(behaviorData.updatedFieldName, date); } }; events.beforeUpdate = function() { var doc = this; var Class = doc.constructor; // Find a class on which the behavior had been set. var behaviorData = Astro.utils.behaviors.findBehavior( Class, 'timestamp' ); // If the "hasUpdatedField" option is set. if (behaviorData.hasUpdatedField) { // We only set the "updatedAt" field if there are any changes. if (_.size(this.getModified())) { // Set value for the "updatedAt" field. this.set(behaviorData.updatedFieldName, new Date()); } } };
events = {}; events.beforeInsert = function() { // Find a class on which the behavior had been set. var behaviorData = Astro.utils.behaviors.findBehavior(this.constructor, 'timestamp'); // If the "hasCreatedField" option is set. if (behaviorData.hasCreatedField) { // Set value for created field. this.set(behaviorData.createdFieldName, new Date()); } }; events.beforeUpdate = function() { // Find a class on which the behavior had been set. var behaviorData = Astro.utils.behaviors.findBehavior(this.constructor, 'timestamp'); // If the "hasUpdatedField" option is set. if (behaviorData.hasUpdatedField) { // We only set the "updatedAt" field if there are any changes. if (_.size(this.getModified())) { // Set value for the "updatedAt" field. this.set(behaviorData.updatedFieldName, new Date()); } } };
feat(autocomplete): Allow trieOptions to be passed into autocomplete - trieOptions to be passed into autocomplete - add properties of autocomplete to documentation - update autocomplete syntax - update event-stream dependency to from and through [#130668639] Signed-off-by: Ryan Dy <9eea7ae7eaa2d8efe5cde89ff3ed76190015ba01@pivotal.io>
const axs = require('../../node_modules/accessibility-developer-tools/dist/js/axs_testing.js'); function failureMessageForAdtResult(result) { const elements = result.elements.map((element) => element.outerHTML); return [ result.rule.heading, ...elements ].join('\n '); } module.exports = function toPassADT() { return { compare(node) { let result = {}; // // let config = new axs.AuditConfiguration(); // config.showUnsupportedRulesWarning = false; // config.scope = node; // // const adtResults = axs.Audit.run(config) // .filter((adtResult) => adtResult.result === 'FAIL'); // // result.pass = adtResults.length === 0; // // if (result.pass) { // result.message = 'Expected ADT to fail'; // } else { // const failures = adtResults // .map((result) => failureMessageForAdtResult(result)) // .join('\n '); // result.message = `Expected ADT to pass but got errors:\n ${failures}`; // } return result; } }; };
const axs = require('../../node_modules/accessibility-developer-tools/dist/js/axs_testing.js'); function failureMessageForAdtResult(result) { const elements = result.elements.map((element) => element.outerHTML); return [ result.rule.heading, ...elements ].join('\n '); } module.exports = function toPassADT() { return { compare(node) { let result = {}; let config = new axs.AuditConfiguration(); config.showUnsupportedRulesWarning = false; config.scope = node; const adtResults = axs.Audit.run(config) .filter((adtResult) => adtResult.result === 'FAIL'); result.pass = adtResults.length === 0; if (result.pass) { result.message = 'Expected ADT to fail'; } else { const failures = adtResults .map((result) => failureMessageForAdtResult(result)) .join('\n '); result.message = `Expected ADT to pass but got errors:\n ${failures}`; } return result; } }; };
Add optional "fail" action handler to Check actions
package com.elmakers.mine.bukkit.action; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.api.action.ActionHandler; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellResult; public abstract class CheckAction extends CompoundAction { protected abstract boolean isAllowed(CastContext context); @Override protected void addHandlers(Spell spell, ConfigurationSection parameters) { addHandler(spell, "actions"); addHandler(spell, "fail"); } @Override public SpellResult step(CastContext context) { boolean allowed = isAllowed(context); if (!allowed) { ActionHandler fail = getHandler("fail"); if (fail != null && fail.size() != 0) { return startActions("fail"); } } ActionHandler actions = getHandler("actions"); if (actions == null || actions.size() == 0) { return allowed ? SpellResult.CAST : SpellResult.STOP; } if (!allowed) { return SpellResult.NO_TARGET; } return startActions(); } }
package com.elmakers.mine.bukkit.action; import com.elmakers.mine.bukkit.api.action.ActionHandler; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.spell.SpellResult; public abstract class CheckAction extends CompoundAction { protected abstract boolean isAllowed(CastContext context); @Override public SpellResult step(CastContext context) { boolean allowed = isAllowed(context); ActionHandler actions = getHandler("actions"); if (actions == null || actions.size() == 0) { return allowed ? SpellResult.CAST : SpellResult.STOP; } if (!allowed) { return SpellResult.NO_TARGET; } return startActions(); } }
Fix space for the tests
module.exports = inject function inject (bot) { bot.isAlive = true bot._client.on('respawn', (packet) => { bot.isAlive = false bot.emit('respawn') }) bot._client.once('update_health', (packet) => { if (bot.isAlive && packet.health > 0) { bot.emit('spawn') } }) bot._client.on('update_health', (packet) => { bot.health = packet.health bot.food = packet.food bot.foodSaturation = packet.foodSaturation bot.emit('health') if (bot.health <= 0) { bot.isAlive = false bot.emit('death') bot._client.write('client_command', { payload: 0 }) } else if (bot.health > 0 && !bot.isAlive) { bot.isAlive = true bot.emit('spawn') } }) }
module.exports = inject function inject (bot) { bot.isAlive = true bot._client.on('respawn', (packet) => { bot.isAlive = false bot.emit('respawn') }) bot._client.once('update_health', (packet) => { if(bot.isAlive && packet.health > 0) { bot.emit('spawn') } }) bot._client.on('update_health', (packet) => { bot.health = packet.health bot.food = packet.food bot.foodSaturation = packet.foodSaturation bot.emit('health') if (bot.health <= 0) { bot.isAlive = false bot.emit('death') bot._client.write('client_command', { payload: 0 }) } else if (bot.health > 0 && !bot.isAlive) { bot.isAlive = true bot.emit('spawn') } }) }
Add test for clock_seq increase if the clock is set backwards
var uuid = require('../uuid'), assert = require('assert'); function compare(ids) { console.log(ids); for (var i = 0; i < ids.length; i++) { var id = ids[i].split('-'); id = [id[2], id[1], id[0], id[3], id[4]].join(''); ids[i] = id; } var sorted = ([].concat(ids)).sort(); assert.equal(sorted.toString(), ids.toString(), 'Warning: sorted !== ids'); console.log('everything in order!'); } var today = new Date().getTime(); var tenhoursago = new Date(today - 10*3600*1000).getTime(); var twentyeightdayslater = new Date(today + 28*24*3600*1000).getTime(); var uuidToday = uuid.v1({ timestamp: today }); var uuidTenhoursago = uuid.v1({ timestamp: tenhoursago }); var uuidTwentyeightdayslater = uuid.v1({ timestamp: twentyeightdayslater }); var uuidNow = uuid.v1(); var ids = [uuidTenhoursago, uuidToday, uuidNow, uuidTwentyeightdayslater]; console.log('Test if ids are in order:'); compare(ids); // Betwenn uuidToday and uuidTenhoursago the clock is set backwards, so we // expect the clock_seq to increase by one assert.ok(uuidToday[22] < uuidTenhoursago[22], 'clock_seq was not increased'); // Same for uuidNow since we set the clock to a future value inbetween assert.ok(uuidTwentyeightdayslater[22] < uuidNow[22], 'clock_seq was not increased');
var uuid = require('../uuid'); var today = new Date().getTime(); var tenhoursago = new Date(today - 10*3600*1000).getTime(); function compare(ids) { console.log(ids); for (var i = 0; i < ids.length; i++) { var id = ids[i].split('-'); id = [id[2], id[1], id[0], id[3], id[4]].join(''); ids[i] = id; } var sorted = ([].concat(ids)).sort(); if (sorted.toString() !== ids.toString()) { console.log('Warning: sorted !== ids'); } else { console.log('everything in order!'); } } var uuidToday = uuid.v1({ timestamp: today }); var uuidTenhoursago = uuid.v1({ timestamp: tenhoursago }); var uuidNow = uuid.v1(); var ids = [uuidTenhoursago, uuidToday, uuidNow]; console.log('Test if ids are in order:'); compare(ids);
Support Go export on windows.
package targets import "path" import "os" import "os/exec" import "runtime" import "errors" type Go struct {} func (Go) Compile(mainFile string) error { compile := exec.Command("go", "build", "-tags", "example", "-o", path.Base(mainFile[:len(mainFile)-2])+".gob") compile.Stdout = os.Stdout compile.Stderr = os.Stderr return compile.Run() } func (Go) Run(mainFile string) error { run := exec.Command("./"+path.Base(mainFile[:len(mainFile)-2])+".gob") run.Stdout = os.Stdout run.Stderr = os.Stderr return run.Run() } func (Go) Export(mainFile string) error { if runtime.GOOS == "linux" || runtime.GOOS == "darwin" { return os.Rename(path.Base(mainFile[:len(mainFile)-2])+".gob", "../"+path.Base(mainFile[:len(mainFile)-2])) } else if runtime.GOOS == "windows" { return os.Rename(path.Base(mainFile[:len(mainFile)-2])+".gob", "../"+path.Base(mainFile[:len(mainFile)-2])+".exe") } else { return errors.New("Cannot export on "+runtime.GOOS+ " systems!") } } func init() { RegisterTarget("go", Go{}) }
package targets import "path" import "os" import "os/exec" import "runtime" import "errors" type Go struct {} func (Go) Compile(mainFile string) error { compile := exec.Command("go", "build", "-tags", "example", "-o", path.Base(mainFile[:len(mainFile)-2])+".gob") compile.Stdout = os.Stdout compile.Stderr = os.Stderr return compile.Run() } func (Go) Run(mainFile string) error { run := exec.Command("./"+path.Base(mainFile[:len(mainFile)-2])+".gob") run.Stdout = os.Stdout run.Stderr = os.Stderr return run.Run() } func (Go) Export(mainFile string) error { if runtime.GOOS == "linux" || runtime.GOOS == "darwin" { return os.Rename(path.Base(mainFile[:len(mainFile)-2])+".gob", "../"+path.Base(mainFile[:len(mainFile)-2])) //TODO support exe on windows. } else { return errors.New("Cannot export on "+runtime.GOOS+ " systems!") } } func init() { RegisterTarget("go", Go{}) }
mattdrayer/WL-525: Handle for missing product attribute
import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not getattr(product.attr, 'id_verification_required', False): return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course
import hashlib from django.conf import settings from django.core.cache import cache from edx_rest_api_client.client import EdxRestApiClient from ecommerce.core.url_utils import get_lms_url def mode_for_seat(product): """ Returns the enrollment mode (aka course mode) for the specified product. If the specified product does not include a 'certificate_type' attribute it is likely the bulk purchase "enrollment code" product variant of the single-seat product, so we attempt to locate the 'seat_type' attribute in its place. """ mode = getattr(product.attr, 'certificate_type', getattr(product.attr, 'seat_type', None)) if not mode: return 'audit' if mode == 'professional' and not product.attr.id_verification_required: return 'no-id-professional' return mode def get_course_info_from_lms(course_key): """ Get course information from LMS via the course api and cache """ api = EdxRestApiClient(get_lms_url('api/courses/v1/')) cache_key = 'courses_api_detail_{}'.format(course_key) cache_hash = hashlib.md5(cache_key).hexdigest() course = cache.get(cache_hash) if not course: # pragma: no cover course = api.courses(course_key).get() cache.set(cache_hash, course, settings.COURSES_API_CACHE_TIMEOUT) return course
Fix E_NOTICE caused by unset styles
<?php abstract class SVGNode { protected $parent; protected $styles; public function __construct() { $this->styles = array(); } public function getStyle($name) { return isset($this->styles[$name]) ? $this->styles[$name] : null; } public function setStyle($name, $value) { $this->styles[$name] = $value; } public function removeStyle($name) { unset($this->styles[$name]); } public function getComputedStyle($name) { $style = null; if (isset($this->styles[$name])) $style = $this->styles[$name]; if (($style === null || $style === 'inherit') && isset($this->parent)) return $this->parent->getComputedStyle($name); // 'inherit' is not what we want. Either get the real style, or // nothing at all. return $style !== 'inherit' ? $style : null; } public abstract function toXMLString(); public abstract function draw(SVGRenderingHelper $rh, $scaleX, $scaleY, $offsetX = 0, $offsetY = 0); public function __toString() { return $this->toXMLString(); } }
<?php abstract class SVGNode { protected $parent; protected $styles; public function __construct() { $this->styles = array(); } public function getStyle($name) { return $this->styles[$name]; } public function setStyle($name, $value) { $this->styles[$name] = $value; } public function removeStyle($name) { unset($this->styles[$name]); } public function getComputedStyle($name) { $style = null; if (isset($this->styles[$name])) $style = $this->styles[$name]; if (($style === null || $style === 'inherit') && isset($this->parent)) return $this->parent->getComputedStyle($name); // 'inherit' is not what we want. Either get the real style, or // nothing at all. return $style !== 'inherit' ? $style : null; } public abstract function toXMLString(); public abstract function draw(SVGRenderingHelper $rh, $scaleX, $scaleY, $offsetX = 0, $offsetY = 0); public function __toString() { return $this->toXMLString(); } }
Use prefix parameter to set prefixPath
const FaviconsWebpackPlugin = require('favicons-webpack-plugin'); module.exports.onCreateWebpackConfig = ({ actions, stage, getConfig }, { logo, icons = {}, title, background }) => { if (stage === 'develop-html' || stage === 'build-html') { actions.setWebpackConfig({ plugins: [ new FaviconsWebpackPlugin({ logo: logo || './src/favicon.png', title, background: background || '#fff', inject: false, emitStats: true, statsFilename: '.iconstats.json', prefix: getConfig().output.publicPath + 'icons-[hash]/', icons: { android: true, appleIcon: true, appleStartup: true, coast: false, favicons: true, firefox: true, opengraph: false, twitter: false, yandex: false, windows: false, ...icons, }, }), ], }); } };
const FaviconsWebpackPlugin = require('favicons-webpack-plugin'); module.exports.onCreateWebpackConfig = ({ actions, stage, getConfig }, { logo, icons = {}, title, background }) => { if (stage === 'develop-html' || stage === 'build-html') { actions.setWebpackConfig({ plugins: [ new FaviconsWebpackPlugin({ logo: logo || './src/favicon.png', title, background: background || '#fff', inject: false, emitStats: true, statsFilename: '.iconstats.json', publicPath: getConfig().output.publicPath, icons: { android: true, appleIcon: true, appleStartup: true, coast: false, favicons: true, firefox: true, opengraph: false, twitter: false, yandex: false, windows: false, ...icons, }, }), ], }); } };
Initialize empty tiles array for Meld object
# -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles or [] self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]]
# -*- coding: utf-8 -*- from mahjong.tile import TilesConverter class Meld(object): CHI = 'chi' PON = 'pon' KAN = 'kan' CHANKAN = 'chankan' NUKI = 'nuki' who = None tiles = None type = None from_who = None called_tile = None # we need it to distinguish opened and closed kan opened = True def __init__(self, meld_type=None, tiles=None, opened=True, called_tile=None, who=None, from_who=None): self.type = meld_type self.tiles = tiles self.opened = opened self.called_tile = called_tile self.who = who self.from_who = from_who def __str__(self): return 'Type: {}, Tiles: {} {}'.format(self.type, TilesConverter.to_one_line_string(self.tiles), self.tiles) # for calls in array def __repr__(self): return self.__str__() @property def tiles_34(self): return [x // 4 for x in self.tiles[:3]]
Remove test of deprecated method
from neomodel import StructuredNode, StringProperty, CypherException class User2(StructuredNode): email = StringProperty() def test_cypher(): jim = User2(email='jim1@test.com').save() email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0] assert email == 'jim1@test.com' def test_cypher_syntax_error(): jim = User2(email='jim1@test.com').save() try: jim.cypher("START a=node({self}) RETURN xx") except CypherException as e: assert hasattr(e, 'message') assert hasattr(e, 'query') assert hasattr(e, 'query_parameters') assert hasattr(e, 'java_trace') assert hasattr(e, 'java_exception') else: assert False
from neomodel import StructuredNode, StringProperty, CypherException class User2(StructuredNode): email = StringProperty() def test_start_cypher(): jim = User2(email='jim@test.com').save() email = jim.start_cypher("RETURN a.email")[0][0][0] assert email == 'jim@test.com' def test_cypher(): jim = User2(email='jim1@test.com').save() email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0] assert email == 'jim1@test.com' def test_cypher_syntax_error(): jim = User2(email='jim1@test.com').save() try: jim.cypher("START a=node({self}) RETURN xx") except CypherException as e: assert hasattr(e, 'message') assert hasattr(e, 'query') assert hasattr(e, 'query_parameters') assert hasattr(e, 'java_trace') assert hasattr(e, 'java_exception') else: assert False
Change TSpec focus script to use windowing (now that it is supported). git-svn-id: a38512e6531051f4ba6aaa1c8358347ddeca2e1b@117751 b00c9580-4927-0410-8824-811d448ea4c7
"""Take a series of exposures at different focus positions to estimate best focus. History: 2008-03-25 ROwen First version 2008-04-03 ROwen Changed doWindow to True because the TripleSpec slitviewer can now window """ import TUI.Base.BaseFocusScript # make script reload also reload BaseFocusScript reload(TUI.Base.BaseFocusScript) SlitviewerFocusScript = TUI.Base.BaseFocusScript.SlitviewerFocusScript Debug = False # run in debug-only mode (which doesn't DO anything, it just pretends)? HelpURL = "Scripts/BuiltInScripts/InstFocus.html" class ScriptClass(SlitviewerFocusScript): def __init__(self, sr): """The setup script; run once when the script runner window is created. """ SlitviewerFocusScript.__init__(self, sr = sr, gcamActor = "tcam", instName = "TSpec", imageViewerTLName = "Guide.TSpec Slitviewer", defBoreXY = [None, -5.0], doWindow = True, helpURL = HelpURL, debug = Debug, )
"""Take a series of exposures at different focus positions to estimate best focus. """ import TUI.Base.BaseFocusScript # make script reload also reload BaseFocusScript reload(TUI.Base.BaseFocusScript) SlitviewerFocusScript = TUI.Base.BaseFocusScript.SlitviewerFocusScript Debug = False # run in debug-only mode (which doesn't DO anything, it just pretends)? HelpURL = "Scripts/BuiltInScripts/InstFocus.html" class ScriptClass(SlitviewerFocusScript): def __init__(self, sr): """The setup script; run once when the script runner window is created. """ SlitviewerFocusScript.__init__(self, sr = sr, gcamActor = "tcam", instName = "TSpec", imageViewerTLName = "Guide.TSpec Slitviewer", defBoreXY = [None, -5.0], doWindow = False, helpURL = HelpURL, debug = Debug, )
Print messagen if there is no matched test
package h2spec import ( "fmt" "time" "github.com/summerwind/h2spec/config" "github.com/summerwind/h2spec/http2" "github.com/summerwind/h2spec/log" "github.com/summerwind/h2spec/reporter" "github.com/summerwind/h2spec/spec" ) func Run(c *config.Config) error { total := 0 failed := false specs := []*spec.TestGroup{ http2.Spec(), } start := time.Now() for _, s := range specs { s.Test(c) if s.FailedCount > 0 { failed = true } total += s.FailedCount total += s.SkippedCount total += s.PassedCount } end := time.Now() d := end.Sub(start) if c.DryRun { return nil } if total == 0 { log.SetIndentLevel(0) log.Println("No matched tests found.") return nil } if failed { log.SetIndentLevel(0) reporter.FailedTests(specs) } log.SetIndentLevel(0) log.Println(fmt.Sprintf("Finished in %.4f seconds", d.Seconds())) reporter.Summary(specs) if c.JUnitReport != "" { err := reporter.JUnitReport(specs, c.JUnitReport) if err != nil { return err } } return nil }
package h2spec import ( "fmt" "time" "github.com/summerwind/h2spec/config" "github.com/summerwind/h2spec/http2" "github.com/summerwind/h2spec/log" "github.com/summerwind/h2spec/reporter" "github.com/summerwind/h2spec/spec" ) func Run(c *config.Config) error { failed := false specs := []*spec.TestGroup{ http2.Spec(), } start := time.Now() for _, s := range specs { s.Test(c) if s.FailedCount > 0 { failed = true } } end := time.Now() d := end.Sub(start) if c.DryRun { return nil } if failed { log.SetIndentLevel(0) reporter.FailedTests(specs) } log.SetIndentLevel(0) log.Println(fmt.Sprintf("Finished in %.4f seconds", d.Seconds())) reporter.Summary(specs) if c.JUnitReport != "" { err := reporter.JUnitReport(specs, c.JUnitReport) if err != nil { return err } } return nil }
Refactor to use method references
package helloworld; import static org.requirementsascode.UseCaseModelBuilder.newBuilder; import org.requirementsascode.UseCaseModel; import org.requirementsascode.UseCaseModelBuilder; import org.requirementsascode.UseCaseModelRunner; public class HelloWorld03_EnterNameExample extends AbstractHelloWorldExample{ private static final Class<EnterText> ENTER_FIRST_NAME = EnterText.class; public UseCaseModel buildWith(UseCaseModelBuilder modelBuilder) { UseCaseModel useCaseModel = modelBuilder.useCase("Get greeted") .basicFlow() .step("S1").system(this::promptUserToEnterFirstName) .step("S2").user(ENTER_FIRST_NAME).system(this::greetUserWithFirstName) .build(); return useCaseModel; } private void promptUserToEnterFirstName(UseCaseModelRunner runner) { System.out.print("Please enter your first name: "); } private void greetUserWithFirstName(EnterText enterText) { System.out.println("Hello, " + enterText.text + "."); } public static void main(String[] args){ HelloWorld03_EnterNameExample example = new HelloWorld03_EnterNameExample(); example.start(); } private void start() { UseCaseModelRunner useCaseModelRunner = new UseCaseModelRunner(); UseCaseModel useCaseModel = buildWith(newBuilder()); useCaseModelRunner.run(useCaseModel); useCaseModelRunner.reactTo(enterText()); } }
package helloworld; import static org.requirementsascode.UseCaseModelBuilder.newBuilder; import java.util.function.Consumer; import org.requirementsascode.UseCaseModel; import org.requirementsascode.UseCaseModelBuilder; import org.requirementsascode.UseCaseModelRunner; public class HelloWorld03_EnterNameExample extends AbstractHelloWorldExample{ private static final Class<EnterText> ENTER_FIRST_NAME = EnterText.class; public UseCaseModel buildWith(UseCaseModelBuilder modelBuilder) { UseCaseModel useCaseModel = modelBuilder.useCase("Get greeted") .basicFlow() .step("S1").system(promptUserToEnterFirstName()) .step("S2").user(ENTER_FIRST_NAME).system(greetUserWithFirstName()) .build(); return useCaseModel; } private Consumer<UseCaseModelRunner> promptUserToEnterFirstName() { return r -> System.out.print("Please enter your first name: "); } private Consumer<EnterText> greetUserWithFirstName() { return enterText -> System.out.println("Hello, " + enterText.text + "."); } public static void main(String[] args){ HelloWorld03_EnterNameExample example = new HelloWorld03_EnterNameExample(); example.start(); } private void start() { UseCaseModelRunner useCaseModelRunner = new UseCaseModelRunner(); UseCaseModel useCaseModel = buildWith(newBuilder()); useCaseModelRunner.run(useCaseModel); useCaseModelRunner.reactTo(enterText()); } }
Fix a bug in alembic downgrading script
"""Insert school data Revision ID: 13f089849099 Revises: 3cea1b2cfa Create Date: 2013-05-05 22:58:35.938292 """ # revision identifiers, used by Alembic. revision = '13f089849099' down_revision = '3cea1b2cfa' from os.path import abspath, dirname, join from alembic import op import sqlalchemy as sa proj_dir = dirname(dirname(dirname(abspath(__file__)))) schools_path = join(proj_dir, 'data/schools.csv') school_t = sa.sql.table( 'school', sa.sql.column('id', sa.String(length=20)), sa.sql.column('name', sa.Unicode(length=100)) ) def upgrade(): for line in list(open(schools_path, 'r'))[1:]: code, ko = map(str.strip, line.split(',')) op.execute(school_t.insert().values({ 'id': code, 'name': ko })) def downgrade(): op.execute(school_t.delete())
"""Insert school data Revision ID: 13f089849099 Revises: 3cea1b2cfa Create Date: 2013-05-05 22:58:35.938292 """ # revision identifiers, used by Alembic. revision = '13f089849099' down_revision = '3cea1b2cfa' from os.path import abspath, dirname, join from alembic import op import sqlalchemy as sa proj_dir = dirname(dirname(dirname(abspath(__file__)))) schools_path = join(proj_dir, 'data/schools.csv') school_t = sa.sql.table( 'school', sa.sql.column('id', sa.String(length=20)), sa.sql.column('name', sa.Unicode(length=100)) ) def upgrade(): for line in list(open(schools_path, 'r'))[1:]: code, ko = map(str.strip, line.split(',')) op.execute(school_t.insert().values({ 'id': code, 'name': ko })) def downgrade(): op.execute(school_t.remove())
Change the ordering of celery global options
import sys from celery.__main__ import main as celerymain from sea import create_app from sea.cli import jobm def celery(argv, app): if argv[0] == "inspect": from sea.contrib.extensions.celery import empty_celeryapp empty_celeryapp.load_config(app) sys.argv = ( ["celery"] + ["-A", "sea.contrib.extensions.celery.empty_celeryapp.capp"] + argv ) else: create_app() sys.argv = ( ["celery"] + ["-A", "app.extensions:{app}".format(app=app)] + argv ) return celerymain() @jobm.job("async_task", proxy=True, inapp=False, help="invoke celery cmds for async tasks") def async_task(argv): return celery(argv, "async_task") @jobm.job("bus", proxy=True, inapp=False, help="invoke celery cmds for bus") def bus(argv): return celery(argv, "bus")
import sys from celery.__main__ import main as celerymain from sea import create_app from sea.cli import jobm def celery(argv, app): if argv[0] == "inspect": from sea.contrib.extensions.celery import empty_celeryapp empty_celeryapp.load_config(app) sys.argv = ( ["celery"] + argv + ["-A", "sea.contrib.extensions.celery.empty_celeryapp.capp"] ) else: create_app() sys.argv = ( ["celery"] + argv + ["-A", "app.extensions:{app}".format(app=app)] ) return celerymain() @jobm.job("async_task", proxy=True, inapp=False, help="invoke celery cmds for async tasks") def async_task(argv): return celery(argv, "async_task") @jobm.job("bus", proxy=True, inapp=False, help="invoke celery cmds for bus") def bus(argv): return celery(argv, "bus")
Add test admin to retrieve a user detail
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_admin_retrieve_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdminDetail.as_view() response = view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_200_OK)
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ fixtures=['account_test.yaml'] def setUp(self): self.client = APIClient() self.factory = APIRequestFactory() self.admin = User.objects.get(pk=1) def test_admin_list_user(self): request = self.factory.get('/billjobs/users/') force_authenticate(request, user=self.admin) view = UserAdmin.as_view() response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK)
Add sleep calls for AWS loops
import boto3 import time def await_volume(client, volumeId, waitingState, finishedState): while True: volumes = client.describe_volumes(VolumeIds=[volumeId]) state = volumes['Volumes'][0]['State'] if state != waitingState: break time.sleep(1) if state != finishedState: print 'Unexpected volume state (expected {}): {}'.format(finishedState, volumes) sys.exit(1) def await_instance(client, instanceId, waitingState, finishedState): while True: instances = client.describe_instances(InstanceIds=[instanceId]) state = instances['Reservations'][0]['Instances'][0]['State']['Name'] if waitingState and state != waitingState: break if state == finishedState: break time.sleep(1) if state != finishedState: print 'Unexpected instance state (expected {}): {}'.format(finishedState, instances) sys.exit(1)
import boto3 def await_volume(client, volumeId, waitingState, finishedState): while True: volumes = client.describe_volumes(VolumeIds=[volumeId]) state = volumes['Volumes'][0]['State'] if state != waitingState: break if state != finishedState: print 'Unexpected volume state (expected {}): {}'.format(finishedState, volumes) sys.exit(1) def await_instance(client, instanceId, waitingState, finishedState): while True: instances = client.describe_instances(InstanceIds=[instanceId]) state = instances['Reservations'][0]['Instances'][0]['State']['Name'] if waitingState and state != waitingState: break if state == finishedState: break if state != finishedState: print 'Unexpected instance state (expected {}): {}'.format(finishedState, instances) sys.exit(1)
[hints] Check url safety before redirecting. Safety first!
from zenaida.contrib.hints.models import Dismissed from zenaida.contrib.hints.forms import DismissHintForm from django.core.exceptions import SuspiciousOperation from django.http import (HttpResponse, HttpResponseNotAllowed, HttpResponseBadRequest, HttpResponseRedirect) from django.utils.http import is_safe_url def dismiss(request): if not request.POST: return HttpResponseNotAllowed(['POST']) else: form = DismissHintForm(request.POST) dismissed = form.save(commit=False) dismissed.user = request.user dismissed.save() if 'next' in request.GET: next_url = request.GET['next'] else: next_url = request.META['HTTP_REFERER'] if not is_safe_url(next_url, host=request.get_host()): raise SuspiciousOperation("Url {} is not safe to redirect to.".format(next_url)) return HttpResponseRedirect(next_url)
from zenaida.contrib.hints.models import Dismissed from zenaida.contrib.hints.forms import DismissHintForm from django.http import (HttpResponse, HttpResponseNotAllowed, HttpResponseBadRequest, HttpResponseRedirect) def dismiss(request): if not request.POST: return HttpResponseNotAllowed(['POST']) else: form = DismissHintForm(request.POST) dismissed = form.save(commit=False) dismissed.user = request.user dismissed.save() if 'next' in request.GET: next_url = request.GET['next'] else: next_url = request.META['HTTP_REFERER'] return HttpResponseRedirect(next_url)
Use central definition of property.
package org.eobjects.build; import java.io.File; import java.util.Map; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugins.annotations.Parameter; public abstract class AbstractDotnetMojo extends AbstractMojo { @Parameter(defaultValue = PluginHelper.PROPERTY_BASEDIR, readonly = true) private File basedir; @Parameter(property = "environment", required = false) private Map<String, String> environment; @Parameter(required = false, defaultValue = "false") private boolean skip; @Parameter(property = "dotnet.pack.output", required = false) private File packOutput; @Parameter(property = "dotnet.configuration", required = false, defaultValue = "Release") private String buildConfiguration; @Parameter(property = PluginHelper.PROPERTY_TARGET_FRAMEWORK, required = false, defaultValue = "") private String buildTargetFramework; public PluginHelper getPluginHelper() { return PluginHelper.get(getLog(), basedir, environment, packOutput, buildConfiguration, buildTargetFramework, skip); } }
package org.eobjects.build; import java.io.File; import java.util.Map; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugins.annotations.Parameter; public abstract class AbstractDotnetMojo extends AbstractMojo { @Parameter(defaultValue = PluginHelper.PROPERTY_BASEDIR, readonly = true) private File basedir; @Parameter(property = "environment", required = false) private Map<String, String> environment; @Parameter(required = false, defaultValue = "false") private boolean skip; @Parameter(property = "dotnet.pack.output", required = false) private File packOutput; @Parameter(property = "dotnet.configuration", required = false, defaultValue = "Release") private String buildConfiguration; @Parameter(property = "dotnet.build.framework", required = false, defaultValue = "") private String buildTargetFramework; public PluginHelper getPluginHelper() { return PluginHelper.get(getLog(), basedir, environment, packOutput, buildConfiguration, buildTargetFramework, skip); } }
Exit fragment-ready event handler when it's from a non-applicable fragment
(function ($) { var FIELDS = { 'centerpage': 'referenced_cp', 'channel': 'query', 'query': 'raw_query' }; var show_matching_field = function(container, current_type) { $(['referenced_cp', 'query', 'raw_query']).each(function(i, field) { var method = field == FIELDS[current_type] ? 'show' : 'hide'; var target = $('.fieldname-' + field, container).closest('fieldset'); target[method](); }); }; $(document).bind('fragment-ready', function(event) { var type_select = $('.fieldname-automatic_type select', event.__target); if (! type_select.length) { return; } show_matching_field(event.__target, type_select.val()); type_select.on( 'change', function() { show_matching_field(event.__target, $(this).val()); }); }); }(jQuery));
(function ($) { var FIELDS = { 'centerpage': 'referenced_cp', 'channel': 'query', 'query': 'raw_query' }; var show_matching_field = function(container, current_type) { $(['referenced_cp', 'query', 'raw_query']).each(function(i, field) { var method = field == FIELDS[current_type] ? 'show' : 'hide'; var target = $('.fieldname-' + field, container).closest('fieldset'); target[method](); }); }; $(document).bind('fragment-ready', function(event) { var type_select = $('.fieldname-automatic_type select', event.__target); show_matching_field(event.__target, type_select.val()); type_select.on( 'change', function() { show_matching_field(event.__target, $(this).val()); }); }); }(jQuery));
Update PowerShell alias to handle no history If history is cleared (or the shell is new and there is no history), invoking thefuck results in an error because the alias attempts to execute the usage string. The fix is to check if Get-History returns anything before invoking thefuck.
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' {\n' \ ' $history = (Get-History -Count 1).CommandLine;\n' \ ' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \ ' $fuck = $(thefuck $history);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', }
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' { \n' \ ' $fuck = $(thefuck (Get-History -Count 1).CommandLine);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', }
Add pop method on Stack class
#!/usr/bin/env python '''Implementation of a simple stack data structure. The stack has push, pop, and peek methods. Items in the stack have a value, and next_item attribute. The stack has a top attribute. ''' class Item(object): def __init__(self, value, next_item=None): self.value = value self.next_item = next_item def __str__(self): return self.value class Stack(object): def __init__(self, top=None): self.top = top def push(self, value): item = Item(value) item.next_item = self.top self.top = item def pop(self): try: pop_item = self.top self.top = pop_item.next_item return pop_item.value except AttributeError: raise ValueError('No items in stack') def peek(self): return self.top.value
#!/usr/bin/env python '''Implementation of a simple stack data structure. The stack has push, pop, and peek methods. Items in the stack have a value, and next_item attribute. The stack has a top attribute. ''' class Item(object): def __init__(self, value, next_item=None): self.value = value self.next_item = next_item def __str__(self): return self.value class Stack(object): def __init__(self, top=None): self.top = top def push(self, value): item = Item(value) item.next_item = self.top self.top = item def pop(self): pass def peek(self): return self.top.value
Change extend from Content to Widget as additional level not needed
/* *********************************************************************************************** Unify Project Homepage: unify-project.org License: MIT + Apache (V2) Copyright: 2010, Sebastian Fastner, Mainz, Germany, http://unify-training.com *********************************************************************************************** */ /** * Generic composite container widget */ qx.Class.define("unify.ui.widget.container.Scroll", { extend : unify.ui.widget.core.Widget, include : [ qx.ui.core.MChildrenHandling ], construct : function() { this.base(arguments, new qx.ui.layout.Basic()); }, members: { __scrollView : null, _createElement : function() { var scrollView = this.__scrollView = new unify.ui.ScrollView(); return scrollView.getElement(); }, getContentElement : function() { var scrollView = this.__scrollView; var contentElement; if (!scrollView) { this.getElement(); scrollView = this.__scrollView; contentElement = scrollView.getContentElement(); qx.bom.element2.Style.set(contentElement, "position", "absolute"); } else { contentElement = scrollView.getContentElement() } return contentElement; } }, destruct : function() { this.__scrollView = null; } });
/* *********************************************************************************************** Unify Project Homepage: unify-project.org License: MIT + Apache (V2) Copyright: 2010, Sebastian Fastner, Mainz, Germany, http://unify-training.com *********************************************************************************************** */ /** * Generic composite container widget */ qx.Class.define("unify.ui.widget.container.Scroll", { extend : unify.ui.widget.basic.Content, include : [ qx.ui.core.MChildrenHandling ], construct : function() { this.base(arguments, new qx.ui.layout.Basic()); }, members: { __scrollView : null, _createElement : function() { var scrollView = this.__scrollView = new unify.ui.ScrollView(); return scrollView.getElement(); }, getContentElement : function() { var scrollView = this.__scrollView; var contentElement; if (!scrollView) { this.getElement(); scrollView = this.__scrollView; contentElement = scrollView.getContentElement(); qx.bom.element2.Style.set(contentElement, "position", "absolute"); } else { contentElement = scrollView.getContentElement() } return contentElement; } }, destruct : function() { this.__scrollView = null; } });
Use Livequery on default input action.
$(document).ready(function() { $('a[rel*=facebox]').facebox(); $('input[type=text][default]').livequery(function(){ $(this).addClass('defaulted'); $(this).attr('value', $(this).attr('default')); $(this).focus(function(){ if($(this).attr('value') == $(this).attr('default')){ $(this).removeClass('defaulted'); $(this).attr('value', ''); } }); $(this).blur(function(){ if($(this).attr('value') == ''){ $(this).addClass('defaulted'); $(this).attr('value', $(this).attr('default')); } }); }); $('form').livequery('submit', function(){ $(this).find('input[type=text][default]').each(function(){ if($(this).attr('value') == $(this).attr('default')){ $(this).attr('value', ''); } }); return true; }); });
$(document).ready(function() { $('a[rel*=facebox]').facebox(); $('input[type=text][default]').each(function(){ $(this).addClass('defaulted'); $(this).attr('value', $(this).attr('default')); $(this).focus(function(){ if($(this).attr('value') == $(this).attr('default')){ $(this).removeClass('defaulted'); $(this).attr('value', ''); } }); $(this).blur(function(){ if($(this).attr('value') == ''){ $(this).addClass('defaulted'); $(this).attr('value', $(this).attr('default')); } }); }); $('form').submit(function(){ $(this).find('input[type=text][default]').each(function(){ if($(this).attr('value') == $(this).attr('default')){ $(this).attr('value', ''); } }); return true; }); });
Remove StringIO in favor of BytesIO.
""" Test the virtual IO system. """ from io import BytesIO import sys import os from mock import call from mock import patch import pytest sys.path.append(os.path.join('..', '..', 'snake')) from snake.vm import System @pytest.fixture() def system(): """ Fixture to load a new VM. """ return System() def test_io_load_file(system): """ Test loading a file. """ test_file = BytesIO("hello world") system.load_file(test_file) assert system.get_input() == 'hello world' def test_io_stdout(system): """ Test IO output. """ with patch('__builtin__.print') as mock_print: system.stdout('hello world') mock_print.assert_has_calls([ call('hello world') ])
""" Test the virtual IO system. """ from StringIO import StringIO import sys import os from mock import call from mock import patch import pytest sys.path.append(os.path.join('..', '..', 'snake')) from snake.vm import System @pytest.fixture() def system(): """ Fixture to load a new VM. """ return System() def test_io_load_file(system): """ Test loading a file. """ test_file = StringIO("hello world") system.load_file(test_file) assert system.get_input() == 'hello world' def test_io_stdout(system): """ Test IO output. """ with patch('__builtin__.print') as mock_print: system.stdout('hello world') mock_print.assert_has_calls([ call('hello world') ])
Add callbacks to the unimplemented functions
/* * Copyright (c) 2012, Joyent, Inc. All rights reserved. * * A brief overview of this source file: what is its purpose. */ module.exports = { add: add, modify: modify, del: del }; function add(replicator, entry, callback) { var log = replicator.log; var ufds = replicator.localUfds; // TODO: targetdn needs to take replication suffix into account var targetdn = entry.object.targetdn; var theEntry = entry.parsedChanges; ufds.add(targetdn, theEntry, function (err, res) { // Ignore existing entries? if (err && err.name != 'EntryAlreadyExistsError') { log.fatal('Could not add entry %s', targetdn, theEntry); return callback(err); } log.debug('Entry replicatead %s', targetdn, theEntry); return callback(); }); } function modify(replicator, entry, callback) { return callback(); } function del(replicator, entry, callback) { return callback(); }
/* * Copyright (c) 2012, Joyent, Inc. All rights reserved. * * A brief overview of this source file: what is its purpose. */ module.exports = { add: add, modify: modify, del: del }; function add(replicator, entry, callback) { var log = replicator.log; var ufds = replicator.localUfds; // TODO: targetdn needs to take replication suffix into account var targetdn = entry.object.targetdn; var theEntry = entry.parsedChanges; ufds.add(targetdn, theEntry, function (err, res) { // Ignore existing entries? if (err && err.name != 'EntryAlreadyExistsError') { log.fatal('Could not add entry %s', targetdn, theEntry); return callback(err); } log.debug('Entry replicatead %s', targetdn, theEntry); return callback(); }); } function modify(replicator, entry) { return callback(); } function del(replicator, entry) { return callback(); }
Add CDN origin domain to allowed hosts.
import os import socket from .base import * # noqa SERVER_ENV = os.getenv('DJANGO_SERVER_ENV') SECRET_KEY = os.getenv('SECRET_KEY') STATIC_URL = os.getenv('STATIC_URL', STATIC_URL) DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = [ 'webwewant.mozilla.org', 'webwewant.allizom.org', 'glow.cdn.mozilla.net', 'glow-origin.cdn.mozilla.net', # the server's IP (for monitors) socket.gethostbyname(socket.gethostname()), ] CACHES = { 'default': { 'BACKEND': 'redis_cache.cache.RedisCache', 'LOCATION': 'unix:/var/run/redis/redis.sock:1', 'OPTIONS': { 'PARSER_CLASS': 'redis.connection.HiredisParser', } }, 'smithers': { 'BACKEND': 'redis_cache.cache.RedisCache', 'LOCATION': 'unix:/var/run/redis/redis.sock:0', 'OPTIONS': { 'PARSER_CLASS': 'redis.connection.HiredisParser', } } } DJANGO_REDIS_IGNORE_EXCEPTIONS = False ENABLE_REDIS = True
import os import socket from .base import * # noqa SERVER_ENV = os.getenv('DJANGO_SERVER_ENV') SECRET_KEY = os.getenv('SECRET_KEY') STATIC_URL = os.getenv('STATIC_URL', STATIC_URL) DEBUG = TEMPLATE_DEBUG = False ALLOWED_HOSTS = [ 'webwewant.mozilla.org', 'webwewant.allizom.org', 'glow.cdn.mozilla.net', # the server's IP (for monitors) socket.gethostbyname(socket.gethostname()), ] CACHES = { 'default': { 'BACKEND': 'redis_cache.cache.RedisCache', 'LOCATION': 'unix:/var/run/redis/redis.sock:1', 'OPTIONS': { 'PARSER_CLASS': 'redis.connection.HiredisParser', } }, 'smithers': { 'BACKEND': 'redis_cache.cache.RedisCache', 'LOCATION': 'unix:/var/run/redis/redis.sock:0', 'OPTIONS': { 'PARSER_CLASS': 'redis.connection.HiredisParser', } } } DJANGO_REDIS_IGNORE_EXCEPTIONS = False ENABLE_REDIS = True
Change return value of getResults
define(["underscore", "jquery"], function(_, $) { return function (averageCartype) { var public = {}; var private = {}; private.createObject = function (averageCartype) { var queryObject = { c: [], sc: null, p: null, ecol: [] }; for (var carclass in averageCartype.carclass) queryObject.c.push(carclass); for (var color in averageCartype.colors) queryObject.ecol.push(color); var seatsRange = averageCartype.min_seats + ":" + averageCartype.max_seats; queryObject.sc = seatsRange; var priceRange = averageCartype.min_price + ":" + averageCartype.max_price; queryObject.p = priceRange; return queryObject; }; private.createURL = function (queryObject) { var url = "http://m.mobile.de/svc/s/?"; var params = $.param(queryObject); url = url.concat(params); return url; }; public.getResults = function (averageCartype) { var queryObject = private.createObject(averageCartype); var url = private.createURL(queryObject); var results = $.getJSON(url, function(json) { return json; }); return results; }; return public; }; });
define(["underscore", "jquery"], function(_, $) { return function (averageCartype) { var public = {}; var private = {}; private.createObject = function (averageCartype) { var queryObject = { c: [], sc: null, p: null, ecol: [] }; for (var carclass in averageCartype.carclass) queryObject.c.push(carclass); for (var color in averageCartype.colors) queryObject.ecol.push(color); var seatsRange = averageCartype.min_seats + ":" + averageCartype.max_seats; queryObject.sc = seatsRange; var priceRange = averageCartype.min_price + ":" + averageCartype.max_price; queryObject.p = priceRange; return queryObject; }; private.createURL = function (queryObject) { var url = "http://m.mobile.de/svc/s/?"; var params = $.param(queryObject); url = url.concat(params); return url; }; public.getResults = function (averageCartype) { var queryObject = private.createObject(averageCartype); var url = private.createURL(queryObject); $.getJSON(url, function(json) { console.log(json); }); }; return public; }; });
Change signed in to true (just for testing)
import React from "react"; import {render} from "react-dom"; //import my components import CalendarContainer from "../containers/CalendarContainer"; import SourceViewButton from "../components/SourceViewButton"; import SignIn from "../components/SignIn"; export function renderComponents(){ var signedIn = true; if(signedIn){ render( // the data fetching is done INSIDE CalendarContainer. <CalendarContainer />, document.getElementById("root") ); }else{ render( <SignIn />, document.getElementById("root") ); } } export function changeCellData(day, period, newVal){ console.debug("Changing cell data. Day: " + day + ", period: " + period + ", new value: " + newVal); } export function changeDayData(day, name){ console.debug("Changing day data. Day: " + day + ", New name: " + name); } export function changePeriodData(period, name, start, end){ console.debug("Changing period data. Period: " + period + ", name: " + name + ", time: " + start + "-" + end + "."); } export function deletePeriod(period){ console.debug("Deleting period " + period); } export function deleteDay(day){ console.debug("Deleting Day " + day); } export function addDay(){ console.debug("Adding a new day!"); } export function addPeriod(){ console.debug("Adding a new period!"); }
import React from "react"; import {render} from "react-dom"; //import my components import CalendarContainer from "../containers/CalendarContainer"; import SourceViewButton from "../components/SourceViewButton"; import SignIn from "../components/SignIn"; export function renderComponents(){ var signedIn = false; if(signedIn){ render( // the data fetching is done INSIDE CalendarContainer. <CalendarContainer />, document.getElementById("root") ); }else{ render( <SignIn />, document.getElementById("root") ); } } export function changeCellData(day, period, newVal){ console.debug("Changing cell data. Day: " + day + ", period: " + period + ", new value: " + newVal); } export function changeDayData(day, name){ console.debug("Changing day data. Day: " + day + ", New name: " + name); } export function changePeriodData(period, name, start, end){ console.debug("Changing period data. Period: " + period + ", name: " + name + ", time: " + start + "-" + end + "."); } export function deletePeriod(period){ console.debug("Deleting period " + period); } export function deleteDay(day){ console.debug("Deleting Day " + day); } export function addDay(){ console.debug("Adding a new day!"); } export function addPeriod(){ console.debug("Adding a new period!"); }
Add fkey constraints at the same time
from sqlalchemy import * from migrate import * import annotateit from annotateit import db from annotateit.model import Consumer, User meta = MetaData() consumer = Table('consumer', meta, Column('id', Integer, primary_key=True, nullable=False), Column('key', String), Column('secret', String), Column('ttl', Integer), Column('created_at', DateTime), Column('updated_at', DateTime), Column('user_id', Integer, ForeignKey('user.id')), ) user = Table('user', meta, Column('id', Integer, primary_key=True, nullable=False), Column('username', String), Column('email', String), Column('password_hash', String), Column('created_at', DateTime), Column('updated_at', DateTime), ) def upgrade(migrate_engine): meta.bind = migrate_engine user.create() consumer.create() def downgrade(migrate_engine): meta.bind = migrate_engine consumer.drop() user.drop()
from __future__ import print_function from getpass import getpass import readline import sys from sqlalchemy import * from migrate import * from migrate.changeset.constraint import ForeignKeyConstraint import annotateit from annotateit import db from annotateit.model import Consumer, User meta = MetaData() consumer = Table('consumer', meta, Column('id', Integer, primary_key=True, nullable=False), Column('key', String), Column('secret', String), Column('ttl', Integer), Column('created_at', DateTime), Column('updated_at', DateTime), Column('user_id', Integer), ) user = Table('user', meta, Column('id', Integer, primary_key=True, nullable=False), Column('username', String), Column('email', String), Column('password_hash', String), Column('created_at', DateTime), Column('updated_at', DateTime), ) consumer_user_id_fkey = ForeignKeyConstraint([consumer.c.user_id], [user.c.id]) def upgrade(migrate_engine): meta.bind = migrate_engine consumer.create() user.create() consumer_user_id_fkey.create() def downgrade(migrate_engine): meta.bind = migrate_engine consumer_user_id_fkey.create() user.drop() consumer.drop()
Remove unnecessary call for modules
<?php namespace Amazon\Pay\Test\Mftf\Helper; use Magento\FunctionalTestingFramework\Helper\Helper; class WaitForPopup extends Helper { public function waitForPopup() { /** @var \Magento\FunctionalTestingFramework\Module\MagentoWebDriver $webDriver */ $webDriver = $this->getModule('\Magento\FunctionalTestingFramework\Module\MagentoWebDriver'); try { $webDriver->executeInSelenium(function(\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) { // Allow popup to appear before switching tabs $handles = $webdriver->getWindowHandles(); while(count($handles) < 2) { $handles = $webdriver->getWindowHandles(); } }); } catch(\Exception $e) { print($e); } } }
<?php namespace Amazon\Pay\Test\Mftf\Helper; use Magento\FunctionalTestingFramework\Helper\Helper; class WaitForPopup extends Helper { public function waitForPopup() { /** @var \Magento\FunctionalTestingFramework\Module\MagentoWebDriver $webDriver */ $webDriver = $this->getModule('\Magento\FunctionalTestingFramework\Module\MagentoWebDriver'); $allMods = $this->getModules(); try { $webDriver->executeInSelenium(function(\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) { // Allow popup to appear before switching tabs $handles = $webdriver->getWindowHandles(); while(count($handles) < 2) { $handles = $webdriver->getWindowHandles(); } }); } catch(\Exception $e) { print($e); } } }
Fix use of deprecated api
package de.christinecoenen.code.zapp.utils.video; import android.view.View; import com.google.android.exoplayer2.Player; import java.lang.ref.WeakReference; /** * Allows the screen to turn off as soon as video playback finishes * or pauses. */ class ScreenDimmingVideoEventListener implements Player.EventListener { private final WeakReference<View> viewToKeepScreenOn; ScreenDimmingVideoEventListener(View viewToKeepScreenOn) { this.viewToKeepScreenOn = new WeakReference<>(viewToKeepScreenOn); } @Override public void onPlaybackStateChanged(int playbackState) { View view = viewToKeepScreenOn.get(); if (view == null) { return; } if (playbackState == Player.STATE_IDLE || playbackState == Player.STATE_ENDED) { view.setKeepScreenOn(false); } else { // This prevents the screen from getting dim/lock view.setKeepScreenOn(true); } } }
package de.christinecoenen.code.zapp.utils.video; import android.view.View; import com.google.android.exoplayer2.Player; import java.lang.ref.WeakReference; /** * Allows the screen to turn off as soon as video playback finishes * or pauses. */ class ScreenDimmingVideoEventListener implements Player.EventListener { private final WeakReference<View> viewToKeepScreenOn; ScreenDimmingVideoEventListener(View viewToKeepScreenOn) { this.viewToKeepScreenOn = new WeakReference<>(viewToKeepScreenOn); } @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { View view = viewToKeepScreenOn.get(); if (view == null) { return; } if (playbackState == Player.STATE_IDLE || playbackState == Player.STATE_ENDED || !playWhenReady) { view.setKeepScreenOn(false); } else { // This prevents the screen from getting dim/lock view.setKeepScreenOn(true); } } }
Update missed file to UTF-8 encoding.
package com.emilsjolander.components.StickyListHeaders; import android.content.Context; import android.view.View; import android.widget.LinearLayout; /** * * @author Emil Sj�lander * * Copyright 2012 Emil Sj�lander 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. * */ public class WrapperView { private LinearLayout v; public WrapperView(Context c) { v = new LinearLayout(c); v.setId(R.id.__stickylistheaders_wrapper_view); v.setOrientation(LinearLayout.VERTICAL); } public WrapperView(View v) { this.v = (LinearLayout) v; } public View wrapViews(View... views){ v.removeAllViews(); for(View child : views){ v.addView(child); } return v; } }
package com.emilsjolander.components.StickyListHeaders; import android.content.Context; import android.view.View; import android.widget.LinearLayout; /** * * @author Emil Sjlander * * Copyright 2012 Emil Sjlander 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. * */ public class WrapperView { private LinearLayout v; public WrapperView(Context c) { v = new LinearLayout(c); v.setId(R.id.__stickylistheaders_wrapper_view); v.setOrientation(LinearLayout.VERTICAL); } public WrapperView(View v) { this.v = (LinearLayout) v; } public View wrapViews(View... views){ v.removeAllViews(); for(View child : views){ v.addView(child); } return v; } }
Refactor IconView to simplify placeholder behaviour
var $ = require('jquery'); var CoreView = require('backbone/core-view'); var iconTemplates = {}; var importAllIconTemplates = function () { var templates = require.context('./templates', false, /\.tpl$/); templates.keys().forEach(function (template) { iconTemplates[template] = templates(template); }); }; importAllIconTemplates(); module.exports = CoreView.extend({ constructor: function (opts) { this.placeholder = this._preinitializeWithPlaceholder(opts && opts.placeholder); CoreView.prototype.constructor.call(this, opts); }, initialize: function (opts) { if (!opts || !opts.icon) throw new Error('An icon is required to render IconView'); this.icon = opts.icon; this.iconTemplate = this._getIconTemplate(this.icon); if (!this.iconTemplate) { throw new Error('The selected icon does not have any available template'); } }, render: function () { this.$el.html(this.iconTemplate); if (this.placeholder) { this.placeholder.replaceWith(this.$el); } return this; }, _getIconTemplate: function (icon) { var iconTemplate = './' + this.icon + '.tpl'; return iconTemplates[iconTemplate]; }, _preinitializeWithPlaceholder: function (placeholderNode) { if (!placeholderNode) { return; } var placeholder = $(placeholderNode); this.tagName = placeholder.prop('tagName'); this.className = placeholder.attr('class'); return placeholder; } });
var $ = require('jquery'); var CoreView = require('backbone/core-view'); var iconTemplates = {}; var importAllIconTemplates = function () { var templates = require.context('./templates', false, /\.tpl$/); templates.keys().forEach(function (template) { iconTemplates[template] = templates(template); }); }; importAllIconTemplates(); module.exports = CoreView.extend({ initialize: function (opts) { if (!opts || !opts.icon) throw new Error('An icon is required to render IconView'); this.icon = opts.icon; this.iconTemplate = this._getIconTemplate(this.icon); if (!this.iconTemplate) { throw new Error('The selected icon does not have any available template'); } this.placeholder = opts && opts.placeholder; }, render: function () { this.$el.html(this.iconTemplate); if (this.placeholder) { var placeholder = $(this.placeholder); this.$el.removeClass().addClass(placeholder.attr('class')); placeholder.replaceWith(this.$el); } return this; }, _getIconTemplate: function (icon) { var iconTemplate = './' + this.icon + '.tpl'; return iconTemplates[iconTemplate]; } });
Define the default policy file This change ensures that the default policy file for Manila API access is defined by default, so that operators can deploy their own policy more easily. Change-Id: Ie890766ea2a274791393304cdfe532e024171195
# Copyright 2016 Red Hat Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.conf import settings settings.POLICY_FILES.update({ 'share': 'manila_policy.json', }) # The OPENSTACK_MANILA_FEATURES settings can be used to enable or disable # the UI for the various services provided by Manila. OPENSTACK_MANILA_FEATURES = { 'enable_share_groups': True, 'enable_replication': True, 'enable_migration': True, 'enable_public_share_type_creation': True, 'enable_public_share_group_type_creation': True, 'enable_public_shares': True, 'enabled_share_protocols': ['NFS', 'CIFS', 'GlusterFS', 'HDFS', 'CephFS', 'MapRFS'], }
# Copyright 2016 Red Hat Inc. # # 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. # The OPENSTACK_MANILA_FEATURES settings can be used to enable or disable # the UI for the various services provided by Manila. OPENSTACK_MANILA_FEATURES = { 'enable_share_groups': True, 'enable_replication': True, 'enable_migration': True, 'enable_public_share_type_creation': True, 'enable_public_share_group_type_creation': True, 'enable_public_shares': True, 'enabled_share_protocols': ['NFS', 'CIFS', 'GlusterFS', 'HDFS', 'CephFS', 'MapRFS'], }
Update sass block to use new API
/** * SASS webpack block. * * @see https://github.com/jtangelder/sass-loader */ module.exports = sass /** * @param {object} [options] See https://github.com/sass/node-sass#options * @param {string[]} [options.includePaths] * @param {bool} [options.indentedSyntax] * @param {string} [options.outputStyle] * @param {bool} [options.sourceMap] * @return {Function} */ function sass (options) { options = options || {} const hasOptions = Object.keys(options).length > 0 return (context, helpers) => helpers.addLoader({ test: context.fileType('text/x-sass'), loaders: [ 'style-loader', options.sourceMap ? 'css-loader?sourceMap' : 'css-loader', hasOptions ? 'sass-loader?' + JSON.stringify(options) : 'sass-loader' ] }) }
/** * SASS webpack block. * * @see https://github.com/jtangelder/sass-loader */ module.exports = sass /** * @param {object} [options] See https://github.com/sass/node-sass#options * @param {string[]} [options.includePaths] * @param {bool} [options.indentedSyntax] * @param {string} [options.outputStyle] * @param {bool} [options.sourceMap] * @return {Function} */ function sass (options) { options = options || {} const hasOptions = Object.keys(options).length > 0 return (context) => ({ module: { loaders: [ { test: context.fileType('text/x-sass'), loaders: [ 'style-loader', options.sourceMap ? 'css-loader?sourceMap' : 'css-loader', hasOptions ? 'sass-loader?' + JSON.stringify(options) : 'sass-loader' ] } ] } }) }
Use identity instead of global id.
/** * DashboardController * * @description :: Server-side logic for managing Dashboards * @help :: See http://links.sailsjs.org/docs/controllers */ module.exports = { index: function (req, res) { if(!req.user.hasPermission('system.dashboard.view')) { res.forbidden(req.__('Error.Authorization.NoRights')); } else { var widgetContents = []; sails.app.customWidgets.forEach(function(widget) { var controller = widget.controller.toLowerCase(); var action = widget.action; var result = sails.controllers[controller][action](req); if(result) { result.owner = widget; widgetContents.push(result); } }); res.view({ widgets: widgetContents }); } } };
/** * DashboardController * * @description :: Server-side logic for managing Dashboards * @help :: See http://links.sailsjs.org/docs/controllers */ module.exports = { index: function (req, res) { if(!req.user.hasPermission('system.dashboard.view')) { res.forbidden(req.__('Error.Authorization.NoRights')); } else { var widgetContents = []; sails.app.customWidgets.forEach(function(widget) { var controller = widget.controller; var action = widget.action; var result = sails.controllers[controller][action](req); if(result) { result.owner = widget; widgetContents.push(result); } }); res.view({ widgets: widgetContents }); } } };
Replace all '.' by '\.' in the names
function subscribe(link) { $.ajax(link, { success: function(json, stat, xhr) { var name, sel; name = json.repo.name; name = name.replace(/\./g, '\\.'); sel = $("#"+json.github_username+'-'+name); sel.toggleClass('btn-success'); sel.toggleClass('btn-default'); if (json.repo.enabled) { sel.html("On"); } else { sel.html("Off"); } }, error: function(json, stat, xhr) { console.log('error'); console.log(json); }, }); }
function subscribe(link) { $.ajax(link, { success: function(json, stat, xhr) { var name, sel; name = json.repo.name; name = name.replace('.', '\\.'); sel = $("#"+json.github_username+'-'+name); sel.toggleClass('btn-success'); sel.toggleClass('btn-default'); if (json.repo.enabled) { sel.html("On"); } else { sel.html("Off"); } }, error: function(json, stat, xhr) { console.log('error'); console.log(json); }, }); }
Sort package list in required installs
#!/usr/bin/python # -*- coding: utf-8 -*- from setuptools import find_packages from setuptools import setup __version__ = "0.13.0" setup( name='pyramid_zipkin', version=__version__, provides=["pyramid_zipkin"], author='Yelp, Inc.', author_email='opensource+pyramid-zipkin@yelp.com', license='Copyright Yelp 2016', url="https://github.com/Yelp/pyramid_zipkin", description='Zipkin instrumentation for the Pyramid framework.', packages=find_packages(exclude=('tests*',)), package_data={'': ['*.thrift']}, install_requires=[ 'py_zipkin', 'pyramid', 'six', ], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ], )
#!/usr/bin/python # -*- coding: utf-8 -*- from setuptools import find_packages from setuptools import setup __version__ = "0.13.0" setup( name='pyramid_zipkin', version=__version__, provides=["pyramid_zipkin"], author='Yelp, Inc.', author_email='opensource+pyramid-zipkin@yelp.com', license='Copyright Yelp 2016', url="https://github.com/Yelp/pyramid_zipkin", description='Zipkin instrumentation for the Pyramid framework.', packages=find_packages(exclude=('tests*',)), package_data={'': ['*.thrift']}, install_requires=[ 'pyramid', 'six', 'py_zipkin', ], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ], )
Add examples/* to linted files.
/*jslint node: true */ "use strict"; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { options: { laxcomma: true , strict: true , globals: { 'require': false , 'describe': false , 'it': false , 'exports': false , 'before': false } } , all: [ '*.js', 'src/*.js', 'test/*.js', 'examples/*.js'] } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-jshint'); // Default task(s). grunt.registerTask('default', ['jshint']); };
/*jslint node: true */ "use strict"; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { options: { laxcomma: true , strict: true , globals: { 'require': false , 'describe': false , 'it': false , 'exports': false , 'before': false } } , all: [ '*.js', 'src/*.js', 'test/*.js'] } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-jshint'); // Default task(s). grunt.registerTask('default', ['jshint']); };
FIX query class for Member MDL
<?php namespace frontend\modules\bbii\models\_query; use yii\db\ActiveQuery; /** * Created to replace Yii1's scope concept. Yii2 uses query classes * * @since 0.0.5 */ class BbiiMemberQuery extends ActiveQuery { public function find() { return $this; } public function findAll() { return $this; } // custom query methods public function present() { return $this->andWhere( 'last_visit > \''.date('Y-m-d H:i:s', time() - 900).'\'' )->orderBy('last_visit DESC'); } public function show() { return $this->andWhere(['show_online' => 1]); } public function newest() { return $this->orderBy('first_visit DESC')->limit(1); } public function moderator() { return $this->andWhere(['moderator' => 1]); } public function hidden() { return true; } }
<?php namespace frontend\modules\bbii\models\_query; use yii\db\ActiveQuery; /** * Created to replace Yii1's scope concept. Yii2 uses query classes * * @since 0.0.5 */ class BbiiMemberQuery extends ActiveQuery { public function find() { return $this; } public function findAll() { return $this; } // custom query methods public function present() { return $this->andWhere([ 'last_visit > \''.date('Y-m-d H:i:s', time() - 900).'\'' ])->orderBy('last_visit DESC'); } public function show() { return $this->andWhere(['show_online' => 1]); } public function newest() { return $this->orderBy('first_visit DESC')->limit(1); } public function moderator() { return $this->andWhere(['moderator' => 1]); } }
Add url assignment to each crawled dataset item
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from dataset import DatasetItem class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']), 'parse_dataset')] def parse_dataset(self, response): sel = Selector(response) dataset = DatasetItem() dataset['url'] = response.url
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from dataset import DatasetItem class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']), 'parse_dataset')] def parse_dataset(self, response): sel = Selector(response) dataset = DatasetItem()
Add a convex hull operation to really close this up.
import scipy.ndimage as ndim from skimage.filters import gaussian from skimage.morphology import convex_hull_image def patch_up_roi(roi, sigma=0.5, truncate=2): """ After being non-linearly transformed, ROIs tend to have holes in them. We perform a couple of computational geometry operations on the ROI to fix that up. Parameters ---------- roi : 3D binary array The ROI after it has been transformed. sigma : float The sigma for initial Gaussian smoothing. truncate : float The truncation for the Gaussian Returns ------- ROI after dilation and hole-filling """ return convex_hull_image(gaussian(ndim.binary_fill_holes(roi), sigma=sigma, truncate=truncate) > 0.1)
import scipy.ndimage as ndim from skimage.filters import gaussian def patch_up_roi(roi, sigma=0.5, truncate=2): """ After being non-linearly transformed, ROIs tend to have holes in them. We perform a couple of computational geometry operations on the ROI to fix that up. Parameters ---------- roi : 3D binary array The ROI after it has been transformed. sigma : float The sigma for initial Gaussian smoothing. truncate : float The truncation for the Gaussian Returns ------- ROI after dilation and hole-filling """ return (ndim.binary_fill_holes( gaussian(roi, sigma=sigma, truncate=truncate)).astype(float) > 0.1)
Use brighter colors in contextual Graphite graphs
// TODO: This is not a real model or controller App.Graphs = Ember.Controller.extend({ graph: function(emberId, entityName, entityType, numSeries) { entityName = entityName.replace(/\./g, '-'); var url = ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityType + '&entityName=' + entityName '&graphVars={"colorList":"yellow,green,orange,red,blue,pink"}'; if (numSeries) url += '&numSeries=' + numSeries; return Ember.$.ajax({ url: url, type: 'GET', dataType: 'json' }).then(function (data) { if (entityType == 'node') { App.store.getById('node', emberId).set('graphs', App.associativeToNumericArray(data)); } else if (entityType == 'vm') { App.store.getById('vm', emberId).set('graphs', App.associativeToNumericArray(data)); } }); } }); App.graphs = App.Graphs.create();
// TODO: This is not a real model or controller App.Graphs = Ember.Controller.extend({ graph: function(emberId, entityName, entityType, numSeries) { entityName = entityName.replace(/\./g, '-'); var url = ((!localStorage.apiDomain) ? '' : '//' + localStorage.apiDomain) + '/api/v1/graphs?entityType=' + entityType + '&entityName=' + entityName; if (numSeries) url += '&numSeries=' + numSeries; return Ember.$.ajax({ url: url, type: 'GET', dataType: 'json' }).then(function (data) { if (entityType == 'node') { App.store.getById('node', emberId).set('graphs', App.associativeToNumericArray(data)); } else if (entityType == 'vm') { App.store.getById('vm', emberId).set('graphs', App.associativeToNumericArray(data)); } }); } }); App.graphs = App.Graphs.create();
Add safer function call for CLI
#!/usr/bin/env node import yargs from 'yargs'; import path from 'path'; import fs from 'fs'; import * as pose from '.'; const opts = yargs .usage('$ pose <action> [options]') .help('help') .options({ name: { alias: ['n'], default: path.basename(process.cwd()), desc: 'Name of template', }, entry: { alias: ['e'], default: process.cwd(), defaultDesc: 'cwd', desc: 'Entry of template', }, help: { alias: ['h'], }, }).argv; const action = opts._[0]; if (!action) { console.log('Type "pose help" to get started.'); process.exit(); } [ opts._pose = path.join(process.env.HOME, '.pose'), opts._templates = path.join(opts._pose, 'templates'), ].forEach(dir => { fs.mkdir(dir, () => null); }); if (typeof pose[action] !== 'function') { pose[action](); } else { console.error(`Unknown action "${action}"`); } export { action, opts };
#!/usr/bin/env node import yargs from 'yargs'; import path from 'path'; import fs from 'fs'; import * as pose from '.'; const opts = yargs .usage('$ pose <action> [options]') .help('help') .options({ name: { alias: ['n'], default: path.basename(process.cwd()), desc: 'Name of template', }, entry: { alias: ['e'], default: process.cwd(), defaultDesc: 'cwd', desc: 'Entry of template', }, help: { alias: ['h'], }, }).argv; const action = opts._[0]; if (!action) { console.log('Type "pose help" to get started.'); process.exit(); } [ opts._pose = path.join(process.env.HOME, '.pose'), opts._templates = path.join(opts._pose, 'templates'), ].forEach(dir => { fs.mkdir(dir, () => null); }); pose[action](opts); export { action, opts };
Resolve a couple of compiler warnings that crept into the code.
// Copyright (C) 2009 Google Inc. // // 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.google.enterprise.connector.pusher; /** * Interface for a factory that creates {@link Pusher} instances for use by a * {@link com.google.enterprise.connector.traversal.Traverser Traverser}. */ public interface PusherFactory { /** * Create a new {@link Pusher} instance appropriate for the supplied * dataSource. * * @param dataSource a data source for a {@code Feed}, typically the name * of a connector instance. * @return a {@link Pusher} * @throws PushException if no {@link Pusher} is assigned to the * {@code dataSource}. */ public Pusher newPusher(String dataSource) throws PushException; }
// Copyright (C) 2009 Google Inc. // // 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.google.enterprise.connector.pusher; /** * Interface for a factory that creates {@link Pusher} instances for use by a * {@link com.google.enterprise.connector.traverser.Traverser Traverser}. */ public interface PusherFactory { /** * Create a new {@link Pusher} instance appropriate for the supplied * dataSource. * * @param dataSource a data source for a {@code Feed}, typically the name * of a connector instance. * @return a {@link Pusher} * @throws {@link PushException} if no {@link Pusher} is assigned to the * {@code dataSource}. */ public Pusher newPusher(String dataSource) throws PushException; }
Fix pre-commit issues in the cli_parse tests.
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for the 'parse' CLI command.""" import tempfile import pytest from click.testing import CliRunner import tbmodels from tbmodels._cli import cli @pytest.mark.parametrize('pos_kind', ['wannier', 'nearest_atom']) @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix, sample, pos_kind): """Test the 'parse' command with different 'prefix' and 'pos_kind'.""" runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, ['parse', '-o', out_file.name, '-f', sample(''), '-p', prefix, '--pos-kind', pos_kind], catch_exceptions=False ) print(run.output) model_res = tbmodels.Model.from_hdf5_file(out_file.name) model_reference = tbmodels.Model.from_wannier_folder(folder=sample(''), prefix=prefix, pos_kind=pos_kind) models_equal(model_res, model_reference)
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> import pytest import tempfile from click.testing import CliRunner import tbmodels from tbmodels._cli import cli @pytest.mark.parametrize('pos_kind', ['wannier', 'nearest_atom']) @pytest.mark.parametrize('prefix', ['silicon', 'bi']) def test_cli_parse(models_equal, prefix, sample, pos_kind): runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, ['parse', '-o', out_file.name, '-f', sample(''), '-p', prefix, '--pos-kind', pos_kind], catch_exceptions=False ) print(run.output) model_res = tbmodels.Model.from_hdf5_file(out_file.name) model_reference = tbmodels.Model.from_wannier_folder(folder=sample(''), prefix=prefix, pos_kind=pos_kind) models_equal(model_res, model_reference)
Mark as commented explicitly all encrypted types by default
<?php /** * LICENSE: This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. * * @copyright 2016 Copyright(c) - All rights reserved. */ namespace Rafrsr\DoctrineExtraBundle\DBAL\Types; use Doctrine\DBAL\Platforms\AbstractPlatform; /** * EncryptedTrait */ trait EncryptedTrait { /** * {@inheritdoc} */ public function convertToPHPValue($value, AbstractPlatform $platform) { if ($value !== null) { $value = Encryptor::get()->decrypt($value); } return parent::convertToPHPValue($value, $platform); } /** * {@inheritdoc} */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { if ($value !== null) { $value = parent::convertToDatabaseValue($value, $platform); } return Encryptor::get()->encrypt($value); } /** * {@inheritdoc} */ public function requiresSQLCommentHint(AbstractPlatform $platform) { return true; } }
<?php /** * LICENSE: This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. * * @copyright 2016 Copyright(c) - All rights reserved. */ namespace Rafrsr\DoctrineExtraBundle\DBAL\Types; use Doctrine\DBAL\Platforms\AbstractPlatform; /** * EncryptedTrait */ trait EncryptedTrait { /** * @inheritdoc */ public function convertToPHPValue($value, AbstractPlatform $platform) { if ($value !== null) { $value = Encryptor::get()->decrypt($value); } return parent::convertToPHPValue($value, $platform); } /** * @inheritdoc */ public function convertToDatabaseValue($value, AbstractPlatform $platform) { if ($value !== null) { $value = parent::convertToDatabaseValue($value, $platform); } return Encryptor::get()->encrypt($value); } }
Send messages more than once
if (process.argv.length < 7) { throw new Error("Need at least 7 command line arguments. In order, must be:\n" + "consumer_key\n" + "consumer_secret\n" + "access_token\n" + "access_token_secret\n" + "target_screen_name\n" + "message_text\n", "send_frequency_in_ms"); } var twitter = require("twitter"); var client = new twitter({ consumer_key: process.argv[2], consumer_secret: process.argv[3], access_token_key: process.argv[4], access_token_secret: process.argv[5] }); var params = { screen_name: process.argv[6], text: process.argv[7] }; setInterval(function() { client.post("direct_messages/new.json", params, handle_result); }, process.argv[8]); function handle_result(error, data, response) { if (error) { console.log(error); } else { console.log("Sent at " + Date.now()); } }
if (process.argv.length < 7) { throw new Error("Need at least 5 command line arguments. In order, must be:\n" + "consumer_key\n" + "consumer_secret\n" + "access_token\n" + "access_token_secret\n" + "target_screen_name\n"); } var twitter = require("twitter"); var client = new twitter({ consumer_key: process.argv[2], consumer_secret: process.argv[3], access_token_key: process.argv[4], access_token_secret: process.argv[5] }); var params = { screen_name: process.argv[6], text: "This is a test" } client.post("direct_messages/new.json", params, handle_result); function handle_result(error, data, response) { if (error) { console.log(error); } else { console.log(data); } }
Replace moment with luxon in test
import { module, test } from 'qunit'; import { setupRenderingTest } from 'dummy/tests/helpers'; import { setupIntl } from 'ember-intl/test-support'; import { render } from '@ember/test-helpers'; import { hbs } from 'ember-cli-htmlbars'; import { setupMirage } from 'ember-cli-mirage/test-support'; import { DateTime } from 'luxon'; module('Integration | Component | sessions-grid-last-updated', function (hooks) { setupRenderingTest(hooks); setupIntl(hooks, 'en-us'); setupMirage(hooks); test('it renders', async function (assert) { assert.expect(1); const session = this.server.create('session', { updatedAt: DateTime.fromObject({ year: 2019, month: 7, day: 9, hour: 17, minute: 0, second: 0, }).toJSDate(), }); const sessionModel = await this.owner.lookup('service:store').findRecord('session', session.id); this.set('session', sessionModel); await render(hbs`<SessionsGridLastUpdated @session={{this.session}} />`); assert.dom(this.element).hasText('Last Update Last Update: 07/09/2019 5:00 PM'); }); });
import { module, test } from 'qunit'; import { setupRenderingTest } from 'dummy/tests/helpers'; import { setupIntl } from 'ember-intl/test-support'; import { render } from '@ember/test-helpers'; import { hbs } from 'ember-cli-htmlbars'; import { setupMirage } from 'ember-cli-mirage/test-support'; import moment from 'moment'; module('Integration | Component | sessions-grid-last-updated', function (hooks) { setupRenderingTest(hooks); setupIntl(hooks, 'en-us'); setupMirage(hooks); hooks.beforeEach(function () { this.owner.lookup('service:moment').setLocale('en'); }); test('it renders', async function (assert) { assert.expect(1); const session = this.server.create('session', { updatedAt: moment('2019-07-09 17:00:00').toDate(), }); const sessionModel = await this.owner.lookup('service:store').findRecord('session', session.id); this.set('session', sessionModel); await render(hbs`<SessionsGridLastUpdated @session={{this.session}} />`); assert.dom(this.element).hasText('Last Update Last Update: 07/09/2019 5:00 PM'); }); });
Revert "Revert "set opennms home for JMXDataCollectionConfigFactory"" This reverts commit c460f2203e5b22a0786c473072e4b59073bca8b9.
package org.opennms.netmgt.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /* @RunWith(OpenNMSJUnit4ClassRunner.class) @ContextConfiguration(locations={ "classpath:/emptyContext.xml" }) @TestExecutionListeners({ OpenNMSConfigurationExecutionListener.class }) */ public class JMXDataCollectionConfigFactoryTest { @Before public void setUp() { System.setProperty("opennms.home", new File("target/test-classes").getAbsolutePath()); } @Test // Tests that the JmxDataCollectionConfigFactory also supports/implements the split config feature. public void shouldSupportSplitConfig() throws FileNotFoundException { File jmxCollectionConfig = new File("src/test/resources/etc/jmx-datacollection-split.xml"); Assert.assertTrue("JMX configuration file is not readable", jmxCollectionConfig.canRead()); FileInputStream configFileStream = new FileInputStream(jmxCollectionConfig); JMXDataCollectionConfigFactory factory = new JMXDataCollectionConfigFactory(configFileStream); Assert.assertNotNull(factory.getJmxCollection("jboss")); Assert.assertNotNull(factory.getJmxCollection("jsr160")); Assert.assertEquals(8, factory.getJmxCollection("jboss").getMbeanCount()); Assert.assertEquals(4, factory.getJmxCollection("jsr160").getMbeanCount()); } }
package org.opennms.netmgt.config; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; public class JMXDataCollectionConfigFactoryTest { @Test // Tests that the JmxDataCollectionConfigFactory also supports/implements the split config feature. public void shouldSupportSplitConfig() throws FileNotFoundException { File jmxCollectionConfig = new File("src/test/resources/etc/jmx-datacollection-split.xml"); Assert.assertTrue("JMX configuration file is not readable", jmxCollectionConfig.canRead()); FileInputStream configFileStream = new FileInputStream(jmxCollectionConfig); JMXDataCollectionConfigFactory factory = new JMXDataCollectionConfigFactory(configFileStream); Assert.assertNotNull(factory.getJmxCollection("jboss")); Assert.assertNotNull(factory.getJmxCollection("jsr160")); Assert.assertEquals(8, factory.getJmxCollection("jboss").getMbeanCount()); Assert.assertEquals(4, factory.getJmxCollection("jsr160").getMbeanCount()); } }
Use the new safeRunForDist method
package info.u_team.u_team_core; import org.apache.logging.log4j.*; import info.u_team.u_team_core.api.IModProxy; import info.u_team.u_team_core.intern.proxy.*; import info.u_team.u_team_core.util.verify.JarSignVerifier; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.*; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; @Mod(UCoreMain.MODID) public class UCoreMain { public static final String MODID = "uteamcore"; public static final Logger LOGGER = LogManager.getLogger("UTeamCore"); private static final IModProxy PROXY = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new); public UCoreMain() { JarSignVerifier.checkSigned(MODID); FMLJavaModLoadingContext.get().getModEventBus().register(this); PROXY.construct(); } @SubscribeEvent public void setup(FMLCommonSetupEvent event) { PROXY.setup(); } @SubscribeEvent public void ready(FMLLoadCompleteEvent event) { PROXY.complete(); } }
package info.u_team.u_team_core; import org.apache.logging.log4j.*; import info.u_team.u_team_core.api.IModProxy; import info.u_team.u_team_core.intern.proxy.*; import info.u_team.u_team_core.util.verify.JarSignVerifier; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.*; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; @Mod(UCoreMain.MODID) public class UCoreMain { public static final String MODID = "uteamcore"; public static final Logger LOGGER = LogManager.getLogger("UTeamCore"); private static final IModProxy PROXY = DistExecutor.runForDist(() -> ClientProxy::new, () -> CommonProxy::new); public UCoreMain() { JarSignVerifier.checkSigned(MODID); FMLJavaModLoadingContext.get().getModEventBus().register(this); PROXY.construct(); } @SubscribeEvent public void setup(FMLCommonSetupEvent event) { PROXY.setup(); } @SubscribeEvent public void ready(FMLLoadCompleteEvent event) { PROXY.complete(); } }
Fix re-evaluation loop with assignment expression
package com.madisp.bad.expr; import com.madisp.bad.eval.BadConverter; import com.madisp.bad.eval.Scope; import com.madisp.bad.eval.Watcher; /** * Created with IntelliJ IDEA. * User: madis * Date: 3/27/13 * Time: 7:02 PM */ public class AssignExpression implements Expression { private final Expression expr; private final VarExpression var; public AssignExpression(VarExpression var, Expression expr) { this.var = var; this.expr = expr; } @Override public Object value(Scope scope) { Object newValue = BadConverter.object(expr.value(scope)); scope.setVar(var.getBase(scope), var.getIdentifier(), newValue); return newValue; } @Override public void addWatcher(Scope scope, Watcher w) { expr.addWatcher(scope, w); // we don't need to watch var as it will trigger re-evaluation loop when this expression is watched // var.addWatcher(scope, w); } }
package com.madisp.bad.expr; import com.madisp.bad.eval.BadConverter; import com.madisp.bad.eval.Scope; import com.madisp.bad.eval.Watcher; /** * Created with IntelliJ IDEA. * User: madis * Date: 3/27/13 * Time: 7:02 PM */ public class AssignExpression implements Expression { private final Expression expr; private final VarExpression var; public AssignExpression(VarExpression var, Expression expr) { this.var = var; this.expr = expr; } @Override public Object value(Scope scope) { Object newValue = BadConverter.object(expr.value(scope)); scope.setVar(var.getBase(scope), var.getIdentifier(), newValue); return newValue; } @Override public void addWatcher(Scope scope, Watcher w) { expr.addWatcher(scope, w); var.addWatcher(scope, w); } }
Remove global var to seek if outputs works
package fnlog_test import ( "github.com/northbright/fnlog" "log" ) /*var ( noTagLog *log.Logger ) */ func Example() { iLog := fnlog.New("i") wLog := fnlog.New("w") eLog := fnlog.New("e") iLog.Printf("print infos") wLog.Printf("print warnnings") eLog.Printf("print errors") //noTagLog.Printf("print messages without tag") // Output: // 2015/06/09 14:32:59 unit_test.go:14 fnlog_test.Example(): i: print infos // 2015/06/09 14:32:59 unit_test.go:15 fnlog_test.Example(): w: print warnnings // 2015/06/09 14:32:59 unit_test.go:16 fnlog_test.Example(): e: print errors // 2015/06/09 14:32:59 unit_test.go:17 fnlog_test.Example(): print messages without tag } func init() { //noTagLog = fnlog.New("") }
package fnlog_test import ( "github.com/northbright/fnlog" "log" ) var ( noTagLog *log.Logger ) func Example() { iLog := fnlog.New("i") wLog := fnlog.New("w") eLog := fnlog.New("e") iLog.Printf("print infos") wLog.Printf("print warnnings") eLog.Printf("print errors") noTagLog.Printf("print messages without tag") // Output: // 2015/06/09 14:32:59 unit_test.go:14 fnlog_test.Example(): i: print infos // 2015/06/09 14:32:59 unit_test.go:15 fnlog_test.Example(): w: print warnnings // 2015/06/09 14:32:59 unit_test.go:16 fnlog_test.Example(): e: print errors // 2015/06/09 14:32:59 unit_test.go:17 fnlog_test.Example(): print messages without tag } func init() { noTagLog = fnlog.New("") }
Remove unnecessary string constants from service
package com.ibm.mil.smartringer; import android.app.IntentService; import android.content.Intent; import android.media.AudioManager; import android.util.Log; public class RingerAdjusterService extends IntentService { private static final String TAG = RingerAdjusterService.class.getName(); public RingerAdjusterService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { Log.i(TAG, "Service for adjusting ringer volume has been called"); // initialize volume adjuster and mute ringer to perform proper noise level detection AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); VolumeAdjuster volumeAdjuster = new VolumeAdjuster(audioManager, AudioManager.STREAM_RING); volumeAdjuster.mute(); // detect noise level for specified sensitivity and adjust ringer volume accordingly VolumeAdjuster.SensitivityLevel sensLevel = VolumeAdjuster.getUsersSensitivityLevel(this); NoiseMeter noiseMeter = new NoiseMeter(); volumeAdjuster.adjustVolume(noiseMeter.getMaxAmplitude(), sensLevel); stopSelf(); } }
package com.ibm.mil.smartringer; import android.app.IntentService; import android.content.Intent; import android.media.AudioManager; import android.util.Log; public class RingerAdjusterService extends IntentService { private static final String TAG = RingerAdjusterService.class.getName(); private static final String PREFS_NAME = "SmartRingerPrefs"; private static final String SENS_KEY = "sensitivityLevel"; public RingerAdjusterService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { Log.i(TAG, "Service for adjusting ringer volume has been called"); // initialize volume adjuster and mute ringer to perform proper noise level detection AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); VolumeAdjuster volumeAdjuster = new VolumeAdjuster(audioManager, AudioManager.STREAM_RING); volumeAdjuster.mute(); // detect noise level for specified sensitivity and adjust ringer volume accordingly VolumeAdjuster.SensitivityLevel sensLevel = VolumeAdjuster.getUsersSensitivityLevel(this); NoiseMeter noiseMeter = new NoiseMeter(); volumeAdjuster.adjustVolume(noiseMeter.getMaxAmplitude(), sensLevel); stopSelf(); } }
Add six to the explicit dependencies
from setuptools import find_packages, setup setup( name='jupyter-notebook-gist', version='0.4.0', description='Create a gist from the Jupyter Notebook UI', author='Mozilla Firefox Data Platform', author_email='fx-data-platform@mozilla.com', packages=find_packages(where='src'), package_dir={'': 'src'}, include_package_data=True, license='MPL2', install_requires=[ 'ipython >= 4', 'notebook >= 4.2', 'jupyter', 'requests', 'six', 'widgetsnbextension', ], url='https://github.com/mozilla/jupyter-notebook-gist', zip_safe=False, )
from setuptools import find_packages, setup setup( name='jupyter-notebook-gist', version='0.4.0', description='Create a gist from the Jupyter Notebook UI', author='Mozilla Firefox Data Platform', author_email='fx-data-platform@mozilla.com', packages=find_packages(where='src'), package_dir={'': 'src'}, include_package_data=True, license='MPL2', install_requires=[ 'ipython >= 4', 'notebook >= 4.2', 'jupyter', 'requests', 'widgetsnbextension', ], url='https://github.com/mozilla/jupyter-notebook-gist', zip_safe=False, )
Add the headers to the response https://developer.forecast.io/docs/v2#response-headers
<?php namespace Forecast; class Forecast { const API_ENDPOINT = 'https://api.forecast.io/forecast/'; private $api_key; public function __construct($api_key) { $this->api_key = $api_key; } private function request($latitude, $longitude, $time = null, $options = array()) { $request_url = self::API_ENDPOINT . $this->api_key . '/' . $latitude . ',' . $longitude . ((is_null($time)) ? '' : ','. $time); if (!empty($options)) { $request_url .= '?'. http_build_query($options); } $response = json_decode(file_get_contents($request_url)); $response->headers = $http_response_header; return $response; } public function get($latitude, $longitude, $time = null, $options = array()) { return $this->request($latitude, $longitude, $time, $options); } }
<?php namespace Forecast; class Forecast { const API_ENDPOINT = 'https://api.forecast.io/forecast/'; private $api_key; public function __construct($api_key) { $this->api_key = $api_key; } private function request($latitude, $longitude, $time = null, $options = array()) { $request_url = self::API_ENDPOINT . $this->api_key . '/' . $latitude . ',' . $longitude . ((is_null($time)) ? '' : ','. $time); if (!empty($options)) { $request_url .= '?'. http_build_query($options); } return json_decode(file_get_contents($request_url)); } public function get($latitude, $longitude, $time = null, $options = array()) { return $this->request($latitude, $longitude, $time, $options); } }
Update os_version to High Sierra
module.exports = { browsers: { bs_chrome_mac: { base: 'BrowserStack', browser: 'chrome', os: 'OS X', os_version: 'High Sierra' }, bs_safari_mac: { base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'High Sierra' }, bs_firefox_win: { base: 'BrowserStack', browser: 'firefox', os: 'Windows', os_version: '8.1' }, bs_chrome_win: { base: 'BrowserStack', browser: 'chrome', os: 'Windows', os_version: '8.1' }, bs_ie_win: { base: 'BrowserStack', browser: 'ie', os: 'Windows', os_version: '8.1' }, } }
module.exports = { browsers: { bs_chrome_mac: { base: 'BrowserStack', browser: 'chrome', os: 'OS X', os_version: 'Mountain Lion' }, bs_safari_mac: { base: 'BrowserStack', browser: 'safari', os: 'OS X', os_version: 'Mountain Lion' }, bs_firefox_win: { base: 'BrowserStack', browser: 'firefox', os: 'Windows', os_version: '8.1' }, bs_chrome_win: { base: 'BrowserStack', browser: 'chrome', os: 'Windows', os_version: '8.1' }, bs_ie_win: { base: 'BrowserStack', browser: 'ie', os: 'Windows', os_version: '8.1' }, } }
Allow sending kwars to mesh shader
from pyrr import Matrix33 class MeshShader: def __init__(self, shader, **kwargs): self.shader = shader def draw(self, mesh, proj_mat, view_mat): """Minimal draw function. Should be overridden""" mesh.vao.bind(self.shader) self.shader.uniform_mat4("m_proj", proj_mat) self.shader.uniform_mat4("m_mv", view_mat) mesh.vao.draw() def apply(self, mesh): """ Determine if this MeshShader should be applied to the mesh Can return self or some MeshShader instance to support dynamic MeshShader creation """ raise NotImplementedError("apply is not implemented. Please override the MeshShader method") def create_normal_matrix(self, modelview): """ Convert to mat3 and return inverse transpose. These are normally needed when dealing with normals in shaders. :param modelview: The modelview matrix :return: Normal matrix """ normal_m = Matrix33.from_matrix44(modelview) normal_m = normal_m.inverse normal_m = normal_m.transpose() return normal_m
from pyrr import Matrix33 class MeshShader: def __init__(self, shader): self.shader = shader def draw(self, mesh, proj_mat, view_mat): """Minimal draw function. Should be overridden""" mesh.vao.bind(self.shader) self.shader.uniform_mat4("m_proj", proj_mat) self.shader.uniform_mat4("m_mv", view_mat) mesh.vao.draw() def apply(self, mesh): """ Determine if this MeshShader should be applied to the mesh Can return self or some MeshShader instance to support dynamic MeshShader creation """ raise NotImplementedError("apply is not implemented. Please override the MeshShader method") def create_normal_matrix(self, modelview): """ Convert to mat3 and return inverse transpose. These are normally needed when dealing with normals in shaders. :param modelview: The modelview matrix :return: Normal matrix """ normal_m = Matrix33.from_matrix44(modelview) normal_m = normal_m.inverse normal_m = normal_m.transpose() return normal_m
Fix - needed to provide create_task a function, not a class
# -*- coding: utf-8 -*- from aiodownload import AioDownloadBundle, AioDownload import asyncio def one(url, download=None): return [s for s in swarm([url], download=download)][0] def swarm(urls, download=None): return [e for e in each(urls, download=download)] def each(iterable, url_map=None, download=None): url_map = url_map or _url_map download = download or AioDownload() tasks = [] for i in iterable: url = url_map(i) info = None if i == url else i tasks.append( download._loop.create_task( download.main(AioDownloadBundle(url, info=info)) ) ) for task_set in download._loop.run_until_complete(asyncio.wait(tasks)): for task in task_set: yield task.result() def _url_map(x): return str(x)
# -*- coding: utf-8 -*- from aiodownload import AioDownloadBundle, AioDownload import asyncio def one(url, download=None): return [s for s in swarm([url], download=download)][0] def swarm(urls, download=None): return [e for e in each(urls, download=download)] def each(iterable, url_map=None, download=None): url_map = url_map or _url_map download = download or AioDownload() tasks = [] for i in iterable: url = url_map(i) info = None if i == url else i tasks.append( download._loop.create_task( AioDownload(url, info=info) ) ) for task_set in download._loop.run_until_complete(asyncio.wait(tasks)): for task in task_set: yield task.result() def _url_map(x): return str(x)
Send notification to the correct address
import sys print(sys.version_info) import random import time import networkzero as nw0 quotes = [ "Humpty Dumpty sat on a wall", "Hickory Dickory Dock", "Baa Baa Black Sheep", "Old King Cole was a merry old sould", ] def main(address_pattern=None): my_name = input("Name: ") my_address = nw0.advertise(my_name, address_pattern) print("Advertising %s on %s" % (my_name, my_address)) while True: services = [(name, address) for (name, address) in nw0.discover_all() if name != my_name] for name, address in services: topic, message = nw0.wait_for_notification(address, "quote", wait_for_s=0) if topic: print("%s says: %s" % (name, message)) quote = random.choice(quotes) nw0.send_notification(my_address, "quote", quote) time.sleep(1) if __name__ == '__main__': main(*sys.argv[1:])
import sys print(sys.version_info) import random import time import networkzero as nw0 quotes = [ "Humpty Dumpty sat on a wall", "Hickory Dickory Dock", "Baa Baa Black Sheep", "Old King Cole was a merry old sould", ] def main(address_pattern=None): my_name = input("Name: ") my_address = nw0.advertise(my_name, address_pattern) print("Advertising %s on %s" % (my_name, my_address)) while True: services = [(name, address) for (name, address) in nw0.discover_all() if name != my_name] for name, address in services: topic, message = nw0.wait_for_notification(address, "quote", wait_for_s=0) if topic: print("%s says: %s" % (name, message)) quote = random.choice(quotes) nw0.send_notification(address, "quote", quote) time.sleep(0.5) if __name__ == '__main__': main(*sys.argv[1:])
Use BaseDbObjectTestCase in AddressScope UT AddressScopeDbObjectTestCase class is using _BaseObjectTestCase class which doesn't contain all the unit test cases for Oslo-Versioned classes. This patch replace that class. Partially-Implements: blueprint adopt-oslo-versioned-objects-for-db Change-Id: I180046743471487a9f9a6e53ae0f2fd09afdf123
# Copyright (c) 2016 Intel 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. from neutron.objects import address_scope from neutron.tests.unit.objects import test_base as obj_test_base from neutron.tests.unit import testlib_api class AddressScopeIfaceObjectTestCase(obj_test_base.BaseObjectIfaceTestCase): _test_class = address_scope.AddressScope class AddressScopeDbObjectTestCase(obj_test_base.BaseDbObjectTestCase, testlib_api.SqlTestCase): _test_class = address_scope.AddressScope
# Copyright (c) 2016 Intel 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. from neutron.objects import address_scope from neutron.tests.unit.objects import test_base as obj_test_base from neutron.tests.unit import testlib_api class AddressScopeIfaceObjectTestCase(obj_test_base.BaseObjectIfaceTestCase): _test_class = address_scope.AddressScope class AddressScopeDbObjectTestCase(obj_test_base._BaseObjectTestCase, testlib_api.SqlTestCase): _test_class = address_scope.AddressScope
Enable service compositions command to instantiate the linked ontology
package eu.scasefp7.eclipse.core.handlers; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; /** * A command handler for exporting all service compositions to the linked ontology. * * @author themis */ public class CompileServiceCompositionsHandler extends CommandExecutorHandler { /** * This function is called when the user selects the menu item. It populates the linked ontology. * * @param event the event containing the information about which file was selected. * @return the result of the execution which must be {@code null}. */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { if (getProjectOfExecutionEvent(event) != null) { executeCommand("eu.scasefp7.eclipse.servicecomposition.commands.exportAllToOntology"); return null; } else { throw new ExecutionException("No project selected"); } } }
package eu.scasefp7.eclipse.core.handlers; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; /** * A command handler for exporting all service compositions to the linked ontology. * * @author themis */ public class CompileServiceCompositionsHandler extends CommandExecutorHandler { /** * This function is called when the user selects the menu item. It populates the linked ontology. * * @param event the event containing the information about which file was selected. * @return the result of the execution which must be {@code null}. */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { if (getProjectOfExecutionEvent(event) != null) { // executeCommand("eu.scasefp7.eclipse.servicecomposition.commands.exportAllToOntology"); return null; } else { throw new ExecutionException("No project selected"); } } }
Set default mustValidateSecret to true
<?php /** * @author Alex Bilbie <hello@alexbilbie.com> * @copyright Copyright (c) Alex Bilbie * @license http://mit-license.org/ * * @link https://github.com/thephpleague/oauth2-server */ namespace League\OAuth2\Server\Repositories; use League\OAuth2\Server\Entities\ClientEntityInterface; /** * Client storage interface. */ interface ClientRepositoryInterface extends RepositoryInterface { /** * Get a client. * * @param string $clientIdentifier The client's identifier * @param null|string $grantType The grant type used (if sent) * @param null|string $clientSecret The client's secret (if sent) * @param bool $mustValidateSecret If true the client must attempt to validate the secret if the client * is confidential * * @return ClientEntityInterface */ public function getClientEntity($clientIdentifier, $grantType = null, $clientSecret = null, $mustValidateSecret = true); }
<?php /** * @author Alex Bilbie <hello@alexbilbie.com> * @copyright Copyright (c) Alex Bilbie * @license http://mit-license.org/ * * @link https://github.com/thephpleague/oauth2-server */ namespace League\OAuth2\Server\Repositories; use League\OAuth2\Server\Entities\ClientEntityInterface; /** * Client storage interface. */ interface ClientRepositoryInterface extends RepositoryInterface { /** * Get a client. * * @param string $clientIdentifier The client's identifier * @param null|string $grantType The grant type used (if sent) * @param null|string $clientSecret The client's secret (if sent) * @param bool $mustValidateSecret If true the client must attempt to validate the secret if the client * is confidential * * @return ClientEntityInterface */ public function getClientEntity($clientIdentifier, $grantType = null, $clientSecret = null, $mustValidateSecret = false); }
Fix crash in 1.6 at Accessibility settings intent. Check SDK version & launch intent differently for 1.6. Instead of OnPreferenceClickListener, use .setIntent on preference.
package com.pilot51.voicenotify; import android.content.Intent; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; public class MainActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); Preference accessPref = (Preference)findPreference("accessibility"); int sdkVer = android.os.Build.VERSION.SDK_INT; if (sdkVer > 4) { accessPref.setIntent(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)); } else if (sdkVer == 4) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClassName("com.android.settings", "com.android.settings.AccessibilitySettings"); accessPref.setIntent(intent); } ((Preference)findPreference("appList")).setIntent(new Intent(this, AppList.class)); } }
package com.pilot51.voicenotify; import android.content.Intent; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; public class MainActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); ((Preference) findPreference("accessibility")).setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { startActivity(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS)); return true; } }); ((Preference) findPreference("appList")).setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { startActivity(new Intent(MainActivity.this, AppList.class)); return true; } }); } }
FIX AL CAMPO DEL REPORTE DE PROVEEDOR - AHORA ES TIPO HIDDEN
<div class="container"> <input type="hidden" id="tipo_reporte" value="por_proveedor"> <div class="row"> <div class="col-sm-8 col-md-8 col-lg-8"> <label for="">Seleccione proveedor</label> <select name="proveedor_id" id="proveedor_id" class="form-control"> @foreach(App\Models\compras\Proveedor::get() as $proveedor) <option value="{{ $proveedor->id }}">{{ $proveedor->razon_social }}</option> @endforeach </select> </div> </div> <div class="row"> <div class="col-sm-4 col-lg-4 col-md-4"> <label for="">Fecha desde (DD-MM-AAAA)</label> <input type="date" id="fecha_desde" class="form-control" name="fecha_desde"> </div> <div class="col-sm-4 col-lg-4 col-md-4"> <label for="">Fecha hasta (DD-MM-AAAA)</label> <input type="date" id="fecha_hasta" class="form-control" name="fecha_hasta"> </div> </div> </div>
<div class="container"> <input type="text" id="tipo_reporte" value="por_proveedor"> <div class="row"> <div class="col-sm-8 col-md-8 col-lg-8"> <label for="">Seleccione proveedor</label> <select name="proveedor_id" id="proveedor_id" class="form-control"> @foreach(App\Models\compras\Proveedor::get() as $proveedor) <option value="{{ $proveedor->id }}">{{ $proveedor->razon_social }}</option> @endforeach </select> </div> </div> <div class="row"> <div class="col-sm-4 col-lg-4 col-md-4"> <label for="">Fecha desde (DD-MM-AAAA)</label> <input type="date" id="fecha_desde" class="form-control" name="fecha_desde"> </div> <div class="col-sm-4 col-lg-4 col-md-4"> <label for="">Fecha hasta (DD-MM-AAAA)</label> <input type="date" id="fecha_hasta" class="form-control" name="fecha_hasta"> </div> </div> </div>
Change registration email sender to Phuxivator
from django.core.mail import send_mail # TODO: check whether this should be sent from Phuxivator def mailApplicantSubmission(context, sender='phuxivator@tf.fi'): name = context['name'] receiver = context['email'] subject = 'Tack för din medlemsansökan till Teknologföreningen!' message = '''Hej {name}, Tack för din medlemsansökan till Teknologföreningen! För att bli en fullständig medlem så är nästa steg att delta i ett Nationsmöte (Namö). Detta informeras mera senare. Vid frågor eller ifall du inte ansökt om medlemskap, kontakt {sender} Detta är ett automatiskt meddelande, du behöver inte svara på det. '''.format(name=name, sender=sender) return send_mail( subject, message, sender, [receiver], fail_silently=False)
from django.core.mail import send_mail # TODO: check whether this should be sent from Phuxivator def mailApplicantSubmission(context, sender='infochef@tf.fi'): name = context['name'] receiver = context['email'] subject = 'Tack för din medlemsansökan till Teknologföreningen!' message = '''Hej {name}, Tack för din medlemsansökan till Teknologföreningen! För att bli en fullständig medlem så är nästa steg att delta i ett Nationsmöte (Namö). Detta informeras mera senare. Vid frågor eller ifall du inte ansökt om medlemskap, kontakt {sender} Detta är ett automatiskt meddelande, du behöver inte svara på det. '''.format(name=name, sender=sender) return send_mail( subject, message, sender, [receiver], fail_silently=False)
Clean up the clean up Typo :(
(function () { CKEDITOR.plugins.add('structuredheadings', { icons: 'structuredheadings', init: (editor) => { // The command to add an autonumbering class editor.addCommand('autoNumberHeading', { exec: (editor) => { /* Get all header elements and assign classes * only if needed */ assignClassToList(editor.document.find('h1,h2,h3')); } }); // Adding the button to the toolbar editor.ui.addButton( 'structuredheadings', { label: 'Autonumber Heading', command: 'autoNumberHeading', toolbar: 'styles,0' }) return editor; // actually, no return is required, but this shuts eslint up } }); function assignClassToList(list) { // Iterate over the list of nodes for (var i = 0; i < list.count(); i++) { var h = list.getItem(i); // Add the class if it doesn't have it if(!h.hasClass('autonumber')) { h.addClass('autonumber'); } }; } })();
(function () { CKEDITOR.plugins.add('structuredheadings', { icons: 'structuredheadings', init: (editor) => { // The command to add an autonumbering class editor.addCommand('autoNumberHeading', { exec: (editor) => { /* Get all header elements and assign classes * only if needed */ assignClassToList(editor.document.find('h1,h2. h3')); } }); // Adding the button to the toolbar editor.ui.addButton( 'structuredheadings', { label: 'Autonumber Heading', command: 'autoNumberHeading', toolbar: 'styles,0' }) return editor; // actually, no return is required, but this shuts eslint up } }); function assignClassToList(list) { // Iterate over the list of nodes for (var i = 0; i < list.count(); i++) { var h = list.getItem(i); // Add the class if it doesn't have it if(!h.hasClass('autonumber')) { h.addClass('autonumber'); } }; } })();
Add --strict flag to raise exception on undefined variables
import sys import argparse import yaml import jinja2 def render(template_string, context_dict, strict=False): template = jinja2.Template(template_string) if strict: template.environment.undefined = jinja2.StrictUndefined return template.render(**context_dict) def main(): parser = argparse.ArgumentParser() parser.add_argument('template', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="Config file template. If not supplied, stdin is used") parser.add_argument('config', type=argparse.FileType('r'), help="YAML data file to read") parser.add_argument('--out', '-o', dest='out', type=argparse.FileType('w'), default=sys.stdout, help="Output file to write. If not supplied, stdout is used") parser.add_argument('--strict', dest='strict', action='store_true', default=False, help="Raise an exception on undefined variables") args = parser.parse_args() context_dict = yaml.load(args.config.read()) template_string = args.template.read() rendered = render(template_string, context_dict, args.strict) args.out.write(rendered) if __name__ == "__main__": main()
import sys import argparse import yaml from jinja2 import Template def render(template_string, context_dict): template = Template(template_string) return template.render(**context_dict) def main(): parser = argparse.ArgumentParser() parser.add_argument('template', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="Config file template. If not supplied, stdin is used") parser.add_argument('config', type=argparse.FileType('r'), help="YAML data file to read") parser.add_argument('--out', '-o', dest='out', type=argparse.FileType('w'), default=sys.stdout, help="Output file to write. If not supplied, stdout is used") args = parser.parse_args() context_dict = yaml.load(args.config.read()) template_string = args.template.read() rendered = render(template_string, context_dict) args.out.write(rendered) if __name__ == "__main__": main()
Enable the additional validation methods.
define([ 'require', '../../lib/jquery.validate', '../../lib/jquery-validation-1.9.0/additional-methods.min', '../logging' ], function(require) { var log = require('../logging').getLogger('validate'); var init = function($el, opts) { var rules = $el.find('[data-required-if]').toArray().reduce(function(acc, el) { var $el = $(el), id = $el.attr('id'); if (!id) { log.error('Element needs id, skipping:', $el); return acc; } acc[id] = {required: $el.data('required-if')}; return acc; }, {}); log.debug('rules:', rules); // ATTENTION: adding the debug option to validate, disables // form submission $el.validate({rules: rules}); return $el; }; var pattern = { markup_trigger: 'form.validate', register_jquery_plugin: false, init: init }; return pattern; });
define([ 'require', '../../lib/jquery.validate', '../logging' ], function(require) { var log = require('../logging').getLogger('validate'); var init = function($el, opts) { var rules = $el.find('[data-required-if]').toArray().reduce(function(acc, el) { var $el = $(el), id = $el.attr('id'); if (!id) { log.error('Element needs id, skipping:', $el); return acc; } acc[id] = {required: $el.data('required-if')}; return acc; }, {}); log.debug('rules:', rules); // ATTENTION: adding the debug option to validate, disables // form submission $el.validate({rules: rules}); return $el; }; var pattern = { markup_trigger: 'form.validate', register_jquery_plugin: false, init: init }; return pattern; });
Remove use of depracated share method in Laravel 5 service provider
<?php namespace ZackKitzmiller\Laravel5; use ZackKitzmiller\Tiny; use Illuminate\Support\ServiceProvider; class TinyServiceProvider extends ServiceProvider { public function boot() { $this->app->singleton('tiny.generate', function () { return new TinyGenerateCommand(); }); $this->commands('tiny.generate'); } public function register() { $this->app->singleton('tiny', function () { $key = getenv('LEAGUE_TINY_KEY'); return new Tiny($key); }); } public function provides() { return array('tiny'); } }
<?php namespace ZackKitzmiller\Laravel5; use ZackKitzmiller\Tiny; use Illuminate\Support\ServiceProvider; class TinyServiceProvider extends ServiceProvider { public function boot() { $this->app['tiny.generate'] = $this->app->share(function ($app) { return new TinyGenerateCommand(); }); $this->commands('tiny.generate'); } public function register() { $this->app['tiny'] = $this->app->share(function ($app) { $key = getenv('LEAGUE_TINY_KEY'); return new Tiny($key); }); } public function provides() { return array('tiny'); } }
Fix wrong java tmp dir sys property git-svn-id: 2433085265c0232ec46d186f8a8240da49417e22@32162 2c54a935-e501-0410-bc05-97a93f6bca70
package com.atlassian.sal.refimpl; import com.atlassian.sal.api.ApplicationProperties; import java.util.Date; import java.io.File; /** * Implementation of ApplicationProperties for http://localhost */ public class RefimplApplicationProperties implements ApplicationProperties { private static final Date THEN = new Date(); public String getBaseUrl() { return System.getProperty("baseurl", "http://localhost:8080/atlassian-plugins-refimpl"); } public String getDisplayName() { return "RefImpl"; } public String getVersion() { return "1.0"; } public Date getBuildDate() { return THEN; } public String getBuildNumber() { return "123"; } public File getHomeDirectory() { return new File(System.getProperty("java.io.tmpdir")); } }
package com.atlassian.sal.refimpl; import com.atlassian.sal.api.ApplicationProperties; import java.util.Date; import java.io.File; /** * Implementation of ApplicationProperties for http://localhost */ public class RefimplApplicationProperties implements ApplicationProperties { private static final Date THEN = new Date(); public String getBaseUrl() { return System.getProperty("baseurl", "http://localhost:8080/atlassian-plugins-refimpl"); } public String getDisplayName() { return "RefImpl"; } public String getVersion() { return "1.0"; } public Date getBuildDate() { return THEN; } public String getBuildNumber() { return "123"; } public File getHomeDirectory() { return new File(System.getProperty("java.tmp.dir")); } }
Fix numero secu input value
'use strict'; angular.module('impactApp').directive('numeroSecu', function() { return { require: 'ngModel', link: function(scope, elem, attr, ngModel) { const isValid = (value) => { if (!value) { return true; } const valueKey = value.slice(-2); const valueRest = value.slice(0, -2); const computedKey = 97 - valueRest % 97; return parseInt(valueKey) === computedKey; }; //For DOM -> model validation ngModel.$parsers.unshift((value) => { const valid = isValid(value); ngModel.$setValidity('numero-secu', valid); return value; }); //For model -> DOM validation ngModel.$formatters.unshift((value) => { const valid = isValid(value); ngModel.$setValidity('numero-secu', valid); return value; }); } }; });
'use strict'; angular.module('impactApp').directive('numeroSecu', function() { return { require: 'ngModel', link: function(scope, elem, attr, ngModel) { const isValid = (value) => { if (!value) { return true; } const valueKey = value.slice(-2); const valueRest = value.slice(0, -2); const computedKey = 97 - valueRest % 97; return parseInt(valueKey) === computedKey; }; //For DOM -> model validation ngModel.$parsers.unshift((value) => { const valid = isValid(value); ngModel.$setValidity('numero-secu', valid); return valid; }); //For model -> DOM validation ngModel.$formatters.unshift((value) => { const valid = isValid(value); ngModel.$setValidity('numero-secu', valid); return value; }); } }; });
[form-builder] Make latlon example use PatchEvent
import React, {PropTypes} from 'react' import PatchEvent, {set} from '../../../../src/PatchEvent' export default class MyCustomLatLonInput extends React.Component { static propTypes = { value: PropTypes.object, onChange: PropTypes.func }; static defaultProps = { onChange() {}, value: {} }; handleLatChange = event => { this.handleFieldChange('lat', event.target.value) } handleLonChange = event => { this.handleFieldChange('lon', event.target.value) } handleFieldChange(fieldName, fieldValue) { const {onChange, value} = this.props const nextValue = Object.assign({_type: 'latlon'}, value, { [fieldName]: fieldValue.trim() ? Number(fieldValue) : undefined }) onChange(PatchEvent.from(set(nextValue))) } render() { const {value} = this.props return ( <div> <h4>Custom lat lon input (e.g. a map or something)</h4> lat: <input type="number" value={value.lat || ''} onChange={this.handleLatChange} /> lon: <input type="number" value={value.lon || ''} onChange={this.handleLonChange} /> </div> ) } }
import React, {PropTypes} from 'react' export default class MyCustomLatLonInput extends React.Component { static propTypes = { value: PropTypes.object, onChange: PropTypes.func }; static defaultProps = { onChange() {}, value: {} }; static contextTypes = { resolveInputComponent: PropTypes.func, schema: PropTypes.object }; constructor(props, context) { super(props, context) this.handleLatChange = this.handleLatChange.bind(this) this.handleLonChange = this.handleLonChange.bind(this) } handleLatChange(event) { this.handleFieldChange('lat', event.target.value) } handleLonChange(event) { this.handleFieldChange('lon', event.target.value) } handleFieldChange(fieldName, fieldValue) { const {value, onChange} = this.props const nextValue = Object.assign({_type: 'latlon'}, value, { [fieldName]: fieldValue.trim() ? Number(fieldValue) : undefined }) onChange({patch: {type: 'set', value: nextValue}}) } render() { const {value} = this.props return ( <div> <h4>Custom lat lon input (e.g. a map or something)</h4> lat: <input type="number" value={value.lat || ''} onChange={this.handleLatChange} /> lon: <input type="number" value={value.lon || ''} onChange={this.handleLonChange} /> </div> ) } }
Allow users to run Step Stool as either `step-stool` or `stepstool`.
from setuptools import setup requires = ['Markdown', 'PyRSS2Gen', 'Pygments', 'PyYAML >= 3.10', 'typogrify'] packages = ['step_stool'] entry_points = { 'console_scripts': [ 'stepstool = step_stool:main', 'step-stool = step_stool:main' ] } classifiers = [ 'Environment :: Console', 'Development Status :: 1 - Planning', 'Intended Audience :: End Users/Desktop' 'License :: OSI Approved :: MIT License', 'Natural Language :: English' 'Operating System :: OS Independent' 'Programming Language :: Python', 'Programming Language :: Python :: 3.3', 'Topic :: Communications' ] try: import argparse except ImportError: requires.append('argparse') README = open('README.md').read() setup( name='step-stool', version='0.1', url='http://step-stool.io', description='A(nother) static site generator in Python', author='Chris Krycho', author_email='chris@step-stool.com', packages=packages, install_requires=requires, entry_points=entry_points, classifiers=classifiers )
from setuptools import setup requires = ['Markdown', 'PyRSS2Gen', 'Pygments', 'PyYAML >= 3.10', 'typogrify'] packages = ['step_stool'] entry_points = { 'console_scripts': [ 'step-stool = step_stool:main' ] } classifiers = [ 'Environment :: Console', 'Development Status :: 1 - Planning', 'Intended Audience :: End Users/Desktop' 'License :: OSI Approved :: MIT License', 'Natural Language :: English' 'Operating System :: OS Independent' 'Programming Language :: Python', 'Programming Language :: Python :: 3.3', 'Topic :: Communications' ] try: import argparse except ImportError: requires.append('argparse') README = open('README.md').read() setup( name='step-stool', version='0.1', url='http://step-stool.io', description='A(nother) static site generator in Python', author='Chris Krycho', author_email='chris@step-stool.com', packages=packages, install_requires=requires, entry_points=entry_points, classifiers=classifiers )
Move some fixtures into better places Move datadir into the sipsecmon plugin and testname into lab.runnerctl.
""" pytest runner control plugin """ import pytest import string def pytest_runtest_makereport(item, call): if 'setup_test' in item.keywords and call.excinfo: if not call.excinfo.errisinstance(pytest.skip.Exception): pytest.halt('A setup test has failed, aborting...') class Halt(object): def __init__(self): self.msg = None def __call__(self, msg): self.msg = msg def pytest_namespace(): return {'halt': Halt()} @pytest.hookimpl(hookwrapper=True) def pytest_runtest_protocol(item, nextitem): yield if pytest.halt.msg: item.session.shouldstop = pytest.halt.msg @pytest.fixture(scope='class') def testname(request): """Pytest test node name with all unfriendly characters transformed into underscores. The lifetime is class scoped since this name is often used to provision remote sw profiles which live for the entirety of a test suite. """ return request.node.name.translate( string.maketrans('\[', '__')).strip(']')
""" pytest runner control plugin """ import pytest def pytest_runtest_makereport(item, call): if 'setup_test' in item.keywords and call.excinfo: if not call.excinfo.errisinstance(pytest.skip.Exception): pytest.halt('A setup test has failed, aborting...') class Halt(object): def __init__(self): self.msg = None def __call__(self, msg): self.msg = msg def pytest_namespace(): return {'halt': Halt()} @pytest.hookimpl(hookwrapper=True) def pytest_runtest_protocol(item, nextitem): yield if pytest.halt.msg: item.session.shouldstop = pytest.halt.msg
Add logo and fix styling
import React from 'react' import { Link } from 'react-router-dom' import injectSheet from 'react-jss' import Spacer from '../../components/spacer' import LogoBetaWhite from '../../components/icons/icon-components/logo-beta-white' const MiniAppFooter = ({ classes }) => { return ( <div> <Spacer height="100px" /> <div className={classes.footerRoot}> <LogoBetaWhite height={25} width={160} /> <Link to="/about" className={classes.navigationLink}> About </Link> <Link to="/feedback" className={classes.navigationLink}> Feedback </Link> <div className={classes.copyrightText}>&copy; Help Assist Her 2018</div> </div> </div> ) } const styles = { footerRoot: { height: '149px', 'background-color': '#3D65F9', }, navigationLink: { 'font-family': 'hah-regular', 'font-size': '18px', color: '#FFFFFF', 'text-decoration': 'none', }, copyrightText: { 'font-family': 'hah-regular', 'font-size': '10px', color: '#ABD3F9', }, } export default injectSheet(styles)(MiniAppFooter)
import React from 'react' import { Link } from 'react-router-dom' import injectSheet from 'react-jss' import Spacer from '../../components/spacer' const MiniAppFooter = ({ classes }) => { return ( <div> <Spacer height="100px" /> <div className={classes.footerRoot}> <Link to="/about" className={classes.navigationLink}> About </Link> <Link to="/feedback" className={classes.navigationLink}> Feedback </Link> <div className={classes.copyrightText}>&copy; Help Assist Her 2018</div> </div> </div> ) } const styles = { footerRoot: { height: '188px', 'background-color': '#3d65f9', }, navigationLink: { 'font-family': 'sans-serif', 'font-size': '18px', color: '#ffffff', 'text-decoration': 'none', }, copyrightText: { 'font-family': 'sans-serif', 'font-size': '14px', color: '#ffffff', }, } export default injectSheet(styles)(MiniAppFooter)
Fix ItemEditController observer accessing model when model was destroyed
var ItemEditController = Em.ObjectController.extend({ setComplete: function () { var model = this.get('model'), complete; // this observer fires even when this controller is not part of the active route. // this is because route controllers are singletons and persist. // since changing routes destroys the temp model we used for editing, we must // avoid accessing or mutating it until we know it's fresh (on entering the route). if (model.isDestroyed) { return; } complete = this.get('canonicalModel.complete'); model.set('complete', complete); }.observes('canonicalModel.complete'), actions: { cancel: function () { this.get('model').destroy(); this.transitionToRoute('items'); }, save: function () { var self = this, item = this.get('model'); this.api.edit('items', item).then(function (data) { var id = Ember.get(data, 'id'); self.store.load('items', data); self.send('refresh'); self.transitionToRoute('item.index', self.store.find('items', id)); }).catch(function () { alert('Sorry, something went wrong saving your edited item! Please try again later.'); }); }, } }); export default ItemEditController;
var ItemEditController = Em.ObjectController.extend({ setComplete: function () { var complete = this.get('canonicalModel.complete'); this.set('model.complete', complete); }.observes('canonicalModel.complete'), actions: { cancel: function () { this.get('model').destroy(); this.transitionToRoute('items'); }, save: function () { var self = this, item = this.get('model'); this.api.edit('items', item).then(function (data) { var id = Ember.get(data, 'id'); self.store.load('items', data); self.send('refresh'); self.transitionToRoute('item.index', self.store.find('items', id)); }).catch(function () { alert('Sorry, something went wrong saving your edited item! Please try again later.'); }); }, } }); export default ItemEditController;
Fix a bug where Assertion's stack is always true even when set to false
/** * External dependencies. */ var chai = global.chai || require('chai'); /** * Chai.js plugin. * * Options: * * - styles: array/string should, expect, assert * - stack: boolean include stack * - diff: boolean show diff * * @param {Object} hydro * @api public */ module.exports = function(hydro) { var opts = hydro.get('chai') || {}; var styles = !Array.isArray(opts.styles) ? [opts.styles] : opts.styles; for (var i = 0, len = styles.length; i < len; i++) { switch (styles[i]) { case 'expect': hydro.set('globals', 'expect', chai.expect); break; case 'should': hydro.set('globals', 'should', chai.should()); break; case 'assert': hydro.set('globals', 'assert', chai.assert); break; } } if (opts.hasOwnProperty('stack')) { chai.Assertion.includeStack = opts.stack; } if (opts.hasOwnProperty('diff')) { chai.Assertion.showDiff = opts.diff; } };
/** * External dependencies. */ var chai = global.chai || require('chai'); /** * Chai.js plugin. * * Options: * * - styles: array/string should, expect, assert * - stack: boolean include stack * - diff: boolean show diff * * @param {Object} hydro * @api public */ module.exports = function(hydro) { var opts = hydro.get('chai') || {}; var styles = !Array.isArray(opts.styles) ? [opts.styles] : opts.styles; for (var i = 0, len = styles.length; i < len; i++) { switch (styles[i]) { case 'expect': hydro.set('globals', 'expect', chai.expect); break; case 'should': hydro.set('globals', 'should', chai.should()); break; case 'assert': hydro.set('globals', 'assert', chai.assert); break; } } if (opts.hasOwnProperty('stack')) { chai.Assertion.includeStack = true; } if (opts.hasOwnProperty('diff')) { chai.Assertion.showDiff = opts.diff; } };
Change to look more like a "plugin js"
var Shortcut = function() {}; Shortcut.prototype.CreateShortcut: = function (shortcut_text, successCallback, errorCallback) { cordova.exec( successCallback, errorCallback, 'ShortcutPlugin', 'addShortcut', [{ "shortcuttext": shortcut_text }] ); }; Shortcut.prototype.RemoveShortcut: function(shortcut_text, successCallback, errorCallback) { cordova.exec( successCallback, errorCallback, 'ShortcutPlugin', 'delShortcut', [{ "shortcuttext": shortcut_text }] ); }; if(!window.plugins) { window.plugins = {}; } if (!window.plugins.Shortcut) { window.plugins.Shortcut = new ShortcutPlugin(); }
var ShortcutPlugin = { CreateShortcut: function(shortcut_text, successCallback, errorCallback) { cordova.exec( successCallback, errorCallback, 'ShortcutPlugin', 'addShortcut', [{ "shortcuttext": shortcut_text }] ); } DeleteShortcut: function(shortcut_text, successCallback, errorCallback) { cordova.exec( successCallback, errorCallback, 'ShortcutPlugin', 'delShortcut', [{ "shortcuttext": shortcut_text }] ); } }
Fix wrong block entity type
package info.u_team.u_team_test.block; import info.u_team.u_team_core.block.UEntityBlock; import info.u_team.u_team_test.init.TestBlockEntityTypes; import info.u_team.u_team_test.init.TestCreativeTabs; import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.BlockHitResult; public class BasicSyncBlock extends UEntityBlock { public BasicSyncBlock() { super(TestCreativeTabs.TAB, Properties.of(Material.METAL).strength(2).requiresCorrectToolForDrops(), TestBlockEntityTypes.BASIC_SYNC); } @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { return openMenu(world, pos, player, true); } }
package info.u_team.u_team_test.block; import info.u_team.u_team_core.block.UEntityBlock; import info.u_team.u_team_test.init.TestBlockEntityTypes; import info.u_team.u_team_test.init.TestCreativeTabs; import net.minecraft.core.BlockPos; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.BlockHitResult; public class BasicSyncBlock extends UEntityBlock { public BasicSyncBlock() { super(TestCreativeTabs.TAB, Properties.of(Material.METAL).strength(2).requiresCorrectToolForDrops(), TestBlockEntityTypes.BASIC_ENERGY_CREATOR); } @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { return openMenu(world, pos, player, true); } }
Fix - ribbon doesn't open contact form
var codebrag = codebrag || {}; /** * Module for adding scripts not related with app features and Angular */ codebrag.addons = {}; codebrag.addons.betaRibbon = (function() { var ribbon = $('.ribbon'); var infoPopup = $('#early-version-popup'); var popupCloseBtn = infoPopup.find('.close-btn'); var link = infoPopup.find('a'); var openedPopupClass = 'opened'; function togglePopupPage() { [ribbon, popupCloseBtn, link].forEach(function(el) { el.on('click', function() { infoPopup.toggleClass(openedPopupClass); }); }); } return { init: togglePopupPage } }()); $(document).ready(function() { codebrag.addons.betaRibbon.init(); });
var codebrag = codebrag || {}; /** * Module for adding scripts not related with app features and Angular */ codebrag.addons = {}; codebrag.addons.betaRibbon = (function() { var ribbon = $('.ribbon'); var infoPopup = $('.popup-page'); var popupCloseBtn = infoPopup.find('.close-btn'); var link = infoPopup.find('a[data-uv-lightbox="classic_widget"]'); var openedPopupClass = 'opened'; function togglePopupPage() { [ribbon, popupCloseBtn, link].forEach(function(el) { el.on('click', function() { infoPopup.toggleClass(openedPopupClass); }); }); } return { init: togglePopupPage } }()); $(document).ready(function() { codebrag.addons.betaRibbon.init(); });
Revert to simple tokens for front-matter multiplex
import CodeMirror from "codemirror" import _ from "underscore" require("codemirror/addon/mode/multiplex") require("codemirror/addon/edit/trailingspace") // Load modes _.each([ "gfm", "javascript", "ruby", "coffeescript", "css", "sass", "stylus", "yaml" ], mode => require(`codemirror/mode/${mode}/${mode}`)) CodeMirror.defineMode("frontmatter_markdown", (config) => { return CodeMirror.multiplexingMode( CodeMirror.getMode(config, "text/x-gfm"), { open : "---", close : "---", mode : CodeMirror.getMode(config, "text/x-yaml"), delimStyle : "front-matter-delim" } ) }) export default CodeMirror
import CodeMirror from "codemirror" import _ from "underscore" require("codemirror/addon/mode/multiplex") require("codemirror/addon/edit/trailingspace") // Load modes _.each([ "gfm", "javascript", "ruby", "coffeescript", "css", "sass", "stylus", "yaml" ], mode => require(`codemirror/mode/${mode}/${mode}`)) CodeMirror.defineMode("frontmatter_markdown", (config) => { return CodeMirror.multiplexingMode( CodeMirror.getMode(config, "text/x-gfm"), { open : /^\b.+\b: .*|^---$/, close : /^---$/, mode : CodeMirror.getMode(config, "text/x-yaml"), parseDelimiters : true } ) }) export default CodeMirror
Add resolving for item queries
import Item from "./graphql/types/item" import Update from "./graphql/types/update" import { makeExecutableSchema } from "graphql-tools" const RuneScapeQuery = ` type RuneScapeQuery { items: [Item] item(id: Int!): Item updates: [Update] } ` const SchemaDefinition = ` schema { query: RuneScapeQuery } ` export default makeExecutableSchema({ typeDefs: [SchemaDefinition, RuneScapeQuery, Item, Update], resolvers: { RuneScapeQuery: { items: (root, { ids }, { models }) => models.items.find({}, { _id: false, rsbuddy: false }), item: (root, { id }, { models }) => models.items.findOne({ id }, { _id: false, rsbuddy: false }), updates: (root, args, { models }) => models.updates.find({}, { _id: false }) }, Item: { rsbuddy: (root, args, { models }) => models.items.findOne({ id: root.id }, { _id: false, rsbuddy: true }) } } })
import Item from "./graphql/types/item" import Update from "./graphql/types/update" import { makeExecutableSchema } from "graphql-tools" const RuneScapeQuery = ` type RuneScapeQuery { items: [Item] item(id: Int!): Item updates: [Update] } ` const SchemaDefinition = ` schema { query: RuneScapeQuery } ` export default makeExecutableSchema({ typeDefs: [SchemaDefinition, RuneScapeQuery, Item, Update], resolvers: { RuneScapeQuery: { items: (root, { ids }, { models }) => models.items.find({}, { _id: false, rsbuddy: false }), item: (root, { id }, { models }) => models.items.findOne({ id }, { _id: false, rsbuddy: false }), updates: (root, args, { models }) => models.updates.find({}, { _id: false }) } } })