text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
fix(date): Set the default date format
/** * This is the default configuration file for the Superdesk application. By default, * the app will use the file with the name "superdesk.config.js" found in the current * working directory, but other files may also be specified using relative paths with * the SUPERDESK_CONFIG environment variable or the grunt --config flag. */ module.exports = function(grunt) { return { apps: [ 'superdesk.analytics' ], importApps: [ 'superdesk-analytics', 'superdesk-publisher' ], defaultRoute: '/workspace/personal', validatorMediaMetadata: { headline: { required: true }, alt_text: { required: true }, description_text: { required: true }, copyrightholder: { required: false }, byline: { required: false }, usageterms: { required: false }, copyrightnotice: { required: false } }, publisher: { protocol: 'https', tenant: process.env.PUBLISHER_API_SUBDOMAIN || '', domain: process.env.PUBLISHER_API_DOMAIN || 'localhost', base: 'api/v1' }, langOverride: { 'en': { 'ANPA Category': 'Category', 'ANPA CATEGORY': 'CATEGORY' } }, view: { timeformat: 'HH:mm', dateformat: 'DD.MM.YYYY', }, features: { preview: 1, swimlane: {columnsLimit: 4}, editor3: true, editorHighlights: true }, workspace: { analytics: true } }; };
/** * This is the default configuration file for the Superdesk application. By default, * the app will use the file with the name "superdesk.config.js" found in the current * working directory, but other files may also be specified using relative paths with * the SUPERDESK_CONFIG environment variable or the grunt --config flag. */ module.exports = function(grunt) { return { apps: [ 'superdesk.analytics' ], importApps: [ 'superdesk-analytics', 'superdesk-publisher' ], defaultRoute: '/workspace/personal', validatorMediaMetadata: { headline: { required: true }, alt_text: { required: true }, description_text: { required: true }, copyrightholder: { required: false }, byline: { required: false }, usageterms: { required: false }, copyrightnotice: { required: false } }, publisher: { protocol: 'https', tenant: process.env.PUBLISHER_API_SUBDOMAIN || '', domain: process.env.PUBLISHER_API_DOMAIN || 'localhost', base: 'api/v1' }, langOverride: { 'en': { 'ANPA Category': 'Category', 'ANPA CATEGORY': 'CATEGORY' } }, features: { preview: 1, swimlane: {columnsLimit: 4}, editor3: true, editorHighlights: true }, workspace: { analytics: true } }; };
Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'django.contrib.sites', # for sitemap test ), ROOT_URLCONF='localeurl.tests.test_urls', ) if VERSION >= (1, 2): settings_dict["DATABASES"] = { "default": { "ENGINE": "django.db.backends.sqlite3" }} else: settings_dict["DATABASE_ENGINE"] = "sqlite3" settings.configure(**settings_dict) def runtests(*test_args): if not test_args: test_args = ['localeurl'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) try: from django.test.simple import DjangoTestSuiteRunner def run_tests(test_args, verbosity, interactive): runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive) return runner.run_tests(test_args) except ImportError: # for Django versions that don't have DjangoTestSuiteRunner from django.test.simple import run_tests failures = run_tests(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', ), ROOT_URLCONF='localeurl.tests.test_urls', ) if VERSION >= (1, 2): settings_dict["DATABASES"] = { "default": { "ENGINE": "django.db.backends.sqlite3" }} else: settings_dict["DATABASE_ENGINE"] = "sqlite3" settings.configure(**settings_dict) def runtests(*test_args): if not test_args: test_args = ['localeurl'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) try: from django.test.simple import DjangoTestSuiteRunner def run_tests(test_args, verbosity, interactive): runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive) return runner.run_tests(test_args) except ImportError: # for Django versions that don't have DjangoTestSuiteRunner from django.test.simple import run_tests failures = run_tests(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
Add utf-8 in autopost example
import glob import os import sys import time from io import open sys.path.append(os.path.join(sys.path[0], '../../')) from instabot import Bot posted_pic_list = [] try: with open('pics.txt', 'r', encoding='utf8') as f: posted_pic_list = f.read().splitlines() except Exception: posted_pic_list = [] timeout = 24 * 60 * 60 # pics will be posted every 24 hours bot = Bot() bot.login() while True: pics = glob.glob("./pics/*.jpg") pics = sorted(pics) try: for pic in pics: if pic in posted_pic_list: continue caption = pic[:-4].split(" ") caption = " ".join(caption[1:]) print("upload: " + caption) bot.uploadPhoto(pic, caption=caption) if bot.LastResponse.status_code != 200: print(bot.LastResponse) # snd msg break if pic not in posted_pic_list: posted_pic_list.append(pic) with open('pics.txt', 'a', encoding='utf8') as f: f.write(pic + "\n") time.sleep(timeout) except Exception as e: print(str(e)) time.sleep(60)
import time import sys import os import glob sys.path.append(os.path.join(sys.path[0], '../../')) from instabot import Bot posted_pic_list = [] try: with open('pics.txt', 'r') as f: posted_pic_list = f.read().splitlines() except Exception: posted_pic_list = [] timeout = 24 * 60 * 60 # pics will be posted every 24 hours bot = Bot() bot.login() while True: pics = glob.glob("./pics/*.jpg") pics = sorted(pics) try: for pic in pics: if pic in posted_pic_list: continue caption = pic[:-4].split(" ") caption = " ".join(caption[1:]) print("upload: " + caption) bot.uploadPhoto(pic, caption=caption) if bot.LastResponse.status_code != 200: print(bot.LastResponse) # snd msg break if pic not in posted_pic_list: posted_pic_list.append(pic) with open('pics.txt', 'a') as f: f.write(pic + "\n") time.sleep(timeout) except Exception as e: print(str(e)) time.sleep(60)
Add preconditions, cope with exception during file read.
package uk.ac.ebi.quickgo.ontology.metadata; import uk.ac.ebi.quickgo.common.loader.GZIPFiles; import uk.ac.ebi.quickgo.rest.metadata.MetaData; import uk.ac.ebi.quickgo.rest.service.ServiceConfigException; import com.google.common.base.Preconditions; import java.nio.file.Path; import java.util.List; import static java.util.stream.Collectors.toList; /** * Populate a MetaData instance with information about the data provided by this service * * @author Tony Wardell * Date: 07/03/2017 * Time: 10:51 * Created with IntelliJ IDEA. */ public class MetaDataProvider { private final Path ontologyPath; public MetaDataProvider(Path ontologyPath) { Preconditions.checkArgument(ontologyPath != null, "The path to the source of the Ontology metadata cannot " + "be null."); this.ontologyPath = ontologyPath; } /** * Lookup the MetaData for the Ontology service * @return MetaData instance */ public MetaData lookupMetaData() { try { List<MetaData> goLines = GZIPFiles.lines(ontologyPath) .skip(1) .filter(s -> s.startsWith("GO")) .map(s -> { String[] a = s.split("\t"); return new MetaData(a[2], a[1]); }) .collect(toList()); Preconditions.checkState(goLines.size() == 1, "Unable to read the correct number of lines for Ontology " + "metadata"); return goLines.get(0); } catch (Exception e) { throw new ServiceConfigException(e); } } }
package uk.ac.ebi.quickgo.ontology.metadata; import uk.ac.ebi.quickgo.common.loader.GZIPFiles; import uk.ac.ebi.quickgo.rest.metadata.MetaData; import java.nio.file.Path; import java.util.List; import static java.util.stream.Collectors.toList; /** * Populate a MetaData instance with information about the data provided by this service * * @author Tony Wardell * Date: 07/03/2017 * Time: 10:51 * Created with IntelliJ IDEA. */ public class MetaDataProvider { private final Path ontologyPath; public MetaDataProvider(Path ontologyPath) { this.ontologyPath = ontologyPath; } public MetaData lookupMetaData() { List<MetaData> goLines = GZIPFiles.lines(ontologyPath) .skip(1) .filter(s -> s.startsWith("GO")) .limit(1) .map(s -> { String[] a = s.split("\t"); return new MetaData(a[2], a[1]); }) .collect(toList()); return (goLines.size() == 1) ? goLines.get(0) : null; } }
Add validator to initial user migration
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.core.validators from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('contact_number', models.CharField( max_length=16, null=True, blank=True)), ('bio', models.TextField(null=True, blank=True)), ('homepage', models.CharField( max_length=256, null=True, blank=True)), ('twitter_handle', models.CharField( max_length=15, null=True, blank=True, validators=[ django.core.validators.RegexValidator( '^[A-Za-z0-9_]{1,15}$', 'Incorrectly formatted twitter handle') ])), ('github_username', models.CharField( max_length=32, null=True, blank=True)), ('user', models.OneToOneField( to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], options={ }, bases=(models.Model,), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('contact_number', models.CharField( max_length=16, null=True, blank=True)), ('bio', models.TextField(null=True, blank=True)), ('homepage', models.CharField( max_length=256, null=True, blank=True)), ('twitter_handle', models.CharField( max_length=15, null=True, blank=True)), ('github_username', models.CharField( max_length=32, null=True, blank=True)), ('user', models.OneToOneField( to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)), ], options={ }, bases=(models.Model,), ), ]
INSERT IGONRE `last insert id` after success insert
<?php namespace Tests\AppBundle\Native; class InsertTest extends ConnectionTestCase { public function testIgnore() { $connection = $this->getConnection(); try { $connection->exec(' CREATE TABLE `users` ( `id` INT PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(255), UNIQUE KEY (`name`) ); '); $response = $connection->executeUpdate(" INSERT INTO `users` (`name`) VALUE ('Alex'); "); $this->assertSame(1, $response); $this->assertSame('1', $connection->lastInsertId()); $response = $connection->executeUpdate(" INSERT INTO `users` (`name`) VALUE ('Reen'); "); $this->assertSame(1, $response); $this->assertSame('2', $connection->lastInsertId()); $response = $connection->executeUpdate(" INSERT IGNORE INTO `users` (`name`) VALUE ('Sky'); "); $this->assertSame(1, $response); $this->assertSame('3', $connection->lastInsertId()); $response = $connection->executeUpdate(" INSERT IGNORE INTO `users` (`name`) VALUE ('Alex'); "); $this->assertSame(0, $response); $this->assertSame('0', $connection->lastInsertId()); } finally { $this->clear(['users']); } } }
<?php namespace Tests\AppBundle\Native; class InsertTest extends ConnectionTestCase { public function testIgnore() { $connection = $this->getConnection(); try { $connection->exec(' CREATE TABLE `users` ( `id` INT PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(255), UNIQUE KEY (`name`) ); '); $response = $connection->executeUpdate(" INSERT INTO `users` (`name`) VALUE ('Alex'); "); $this->assertSame(1, $response); $this->assertSame('1', $connection->lastInsertId()); $response = $connection->executeUpdate(" INSERT INTO `users` (`name`) VALUE ('Reen'); "); $this->assertSame(1, $response); $this->assertSame('2', $connection->lastInsertId()); $response = $connection->executeUpdate(" INSERT IGNORE INTO `users` (`name`) VALUE ('Alex'); "); $this->assertSame(0, $response); $this->assertSame('0', $connection->lastInsertId()); } finally { $this->clear(['users']); } } }
Fix view count cutoff for YT
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery from django.utils.encoding import smart_str import re class YoutubeMusic: def __init__(self): self.service = YouTubeService() def search(self, artist): query = YouTubeVideoQuery() query.vq = artist query.orderby = 'relevance' query.racy = 'exclude' query.format = '5' query.max_results = 50 query.categories.append("/Music") feed = self.service.YouTubeQuery(query) results = [] for entry in feed.entry: if not self.is_valid_entry(artist, entry): continue results.append({ 'url': entry.media.player.url, 'title': smart_str(entry.media.title.text), 'duration': int(entry.media.duration.seconds), }) return {'artist': artist, 'results': results} def is_valid_entry(self, artist, entry): duration = int(entry.media.duration.seconds) title = smart_str(entry.media.title.text).lower() if entry.rating is not None and float(entry.rating.average) < 3.5: return False if entry.statistics is None or int(entry.statistics.view_count) < 1000: return False if duration < (2 * 60) or duration > (9 * 60): return False if artist.lower() not in title: return False if re.search(r"\b(perform|performance|concert|cover)\b", title): return False return True
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery from django.utils.encoding import smart_str import re class YoutubeMusic: def __init__(self): self.service = YouTubeService() def search(self, artist): query = YouTubeVideoQuery() query.vq = artist query.orderby = 'relevance' query.racy = 'exclude' query.format = '5' query.max_results = 50 query.categories.append("/Music") feed = self.service.YouTubeQuery(query) results = [] for entry in feed.entry: if not self.is_valid_entry(artist, entry): continue results.append({ 'url': entry.media.player.url, 'title': smart_str(entry.media.title.text), 'duration': int(entry.media.duration.seconds), }) return {'artist': artist, 'results': results} def is_valid_entry(self, artist, entry): duration = int(entry.media.duration.seconds) title = smart_str(entry.media.title.text).lower() if entry.rating is not None and float(entry.rating.average) < 3.5: return False if entry.statistics is None or entry.statistics.view_count < 1000: return False if duration < (2 * 60) or duration > (9 * 60): return False if artist.lower() not in title: return False if re.search(r"\b(perform|performance|concert|cover)\b", title): return False return True
FIX package in include command.
<?php if (!defined("CMS_VERSION")) { header("HTTP/1.0 404 Not Found"); die(""); } if (!class_exists("commandIncDualListbox")) { class commandIncDualListbox extends driverCommand { public static function runMe(&$params, $debug = true) { $path = driverCommand::run('modGetPath', array('name' => 'pharinix_mod_bootstrap_duallistbox')); echo '<link rel="stylesheet" href="'.CMS_DEFAULT_URL_BASE.$path['path'].'bootstrap-duallistbox.css"/>'; echo '<script src="'.CMS_DEFAULT_URL_BASE.$path['path'].'jquery.bootstrap-duallistbox.js"></script>'; } public static function getHelp() { return array( "package" => "pharinix_mod_bootstrap_duallistbox", "description" => __("Print HTML includes to duallistbox."), "parameters" => array(), "response" => array(), "type" => array( "parameters" => array(), "response" => array(), ), "echo" => true ); } public static function getAccess($ignore = "") { $me = __FILE__; return parent::getAccess($me); } public static function getAccessFlags() { return driverUser::PERMISSION_FILE_ALL_EXECUTE; } } } return new commandIncDualListbox();
<?php if (!defined("CMS_VERSION")) { header("HTTP/1.0 404 Not Found"); die(""); } if (!class_exists("commandIncDualListbox")) { class commandIncDualListbox extends driverCommand { public static function runMe(&$params, $debug = true) { $path = driverCommand::run('modGetPath', array('name' => 'pharinix_mod_bootstrap_duallistbox')); echo '<link rel="stylesheet" href="'.CMS_DEFAULT_URL_BASE.$path['path'].'bootstrap-duallistbox.css"/>'; echo '<script src="'.CMS_DEFAULT_URL_BASE.$path['path'].'jquery.bootstrap-duallistbox.js"></script>'; } public static function getHelp() { return array( "description" => __("Print HTML includes to duallistbox."), "parameters" => array(), "response" => array(), "type" => array( "parameters" => array(), "response" => array(), ), "echo" => true ); } public static function getAccess($ignore = "") { $me = __FILE__; return parent::getAccess($me); } public static function getAccessFlags() { return driverUser::PERMISSION_FILE_ALL_EXECUTE; } } } return new commandIncDualListbox();
Bump version due to failed markdown/rST conversion in README
from setuptools import setup setup( name = "django-safe-project", version = "0.0.4", author = "Matthew Reid", author_email = "[email protected]", description = ("Start Django projects with sensitive data outside of the " "global settings module"), url='https://github.com/nocarryr/django-safe-project', license='MIT', keywords = "django", packages=['django_safe_project'], include_package_data=True, scripts=['startproject.py'], entry_points={ 'console_scripts':[ 'django-safe-project = startproject:main', ], }, setup_requires=['setuptools-markdown'], long_description_markdown_filename='README.md', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Security', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], )
from setuptools import setup setup( name = "django-safe-project", version = "0.0.3", author = "Matthew Reid", author_email = "[email protected]", description = ("Start Django projects with sensitive data outside of the " "global settings module"), url='https://github.com/nocarryr/django-safe-project', license='MIT', keywords = "django", packages=['django_safe_project'], include_package_data=True, scripts=['startproject.py'], entry_points={ 'console_scripts':[ 'django-safe-project = startproject:main', ], }, setup_requires=['setuptools-markdown'], long_description_markdown_filename='README.md', classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Security', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', ], )
Convert data to unsigned 8-bit when displaying
import gtk, gobject import numpy as N class CameraImage(gtk.Image): __gproperties__ = { 'data' : (gobject.TYPE_PYOBJECT, 'Image data', 'NumPy ndarray containing the data', gobject.PARAM_READWRITE) } def __init__(self): gtk.Image.__gobject_init__(self) self._data = N.zeros((200, 320, 3), dtype=N.uint8) self._display_data() def do_get_property(self, property): if property.name == 'data': return self._data else: raise AttributeError, 'unknown property %s' % property.name def do_set_property(self, property, value): if property.name == 'data': # Convert to 8-bit RGB data if value.dtype is not N.uint8: value = N.array(value, dtype=N.uint8) if len(value.shape) != 3: value = N.dstack((value, value, value)) self._data = value self._display_data() else: raise AttributeError, 'unknown property %s' % property.name def _display_data(self): # OpenCV returns the camera data transposed pixbuf = gtk.gdk.pixbuf_new_from_data(self._data, gtk.gdk.COLORSPACE_RGB, # only allowed value has_alpha=False, bits_per_sample=8, # only allowed value width=self._data.shape[1], height=self._data.shape[0], rowstride=self._data.strides[0]) self.set_from_pixbuf(pixbuf) gobject.type_register(CameraImage)
import gtk, gobject import numpy as N class CameraImage(gtk.Image): __gproperties__ = { 'data' : (gobject.TYPE_PYOBJECT, 'Image data', 'NumPy ndarray containing the data', gobject.PARAM_READWRITE) } def __init__(self): gtk.Image.__gobject_init__(self) self._data = N.zeros((200, 320, 3), dtype=N.uint8) self._display_data() def do_get_property(self, property): if property.name == 'data': return self._data else: raise AttributeError, 'unknown property %s' % property.name def do_set_property(self, property, value): if property.name == 'data': self._data = value self._display_data() else: raise AttributeError, 'unknown property %s' % property.name def _display_data(self): # OpenCV returns the camera data transposed pixbuf = gtk.gdk.pixbuf_new_from_data(self._data, gtk.gdk.COLORSPACE_RGB, has_alpha=False, bits_per_sample=8, width=self._data.shape[1], height=self._data.shape[0], rowstride=self._data.strides[0]) self.set_from_pixbuf(pixbuf) gobject.type_register(CameraImage)
Add warning about custom logout redirection
<?php return [ 'layout' => 'ui::layouts.public.full', 'captcha' => false, 'identifier' => 'email', 'login' => [ 'implementation' => \Laravolt\Auth\DefaultLogin::class, ], 'registration' => [ 'enable' => true, 'status' => 'ACTIVE', 'implementation' => \Laravolt\Auth\DefaultUserRegistrar::class, ], 'activation' => [ 'enable' => false, 'status_before' => 'PENDING', 'status_after' => 'ACTIVE', ], 'cas' => [ 'enable' => false, ], 'ldap' => [ 'enable' => false, 'resolver' => [ 'ldap_user' => \Laravolt\Auth\Services\Resolvers\LdapUserResolver::class, 'eloquent_user' => \Laravolt\Auth\Services\Resolvers\EloquentUserResolver::class, ], ], 'router' => [ 'middleware' => ['web'], 'prefix' => 'auth', ], 'redirect' => [ 'after_login' => '/', 'after_register' => '/', 'after_reset_password' => '/', // WARNING: after_logout redirection only valid for Laravel >= 5.7 'after_logout' => '/', ], ];
<?php return [ 'layout' => 'ui::layouts.public.full', 'captcha' => false, 'identifier' => 'email', 'login' => [ 'implementation' => \Laravolt\Auth\DefaultLogin::class, ], 'registration' => [ 'enable' => true, 'status' => 'ACTIVE', 'implementation' => \Laravolt\Auth\DefaultUserRegistrar::class, ], 'activation' => [ 'enable' => false, 'status_before' => 'PENDING', 'status_after' => 'ACTIVE', ], 'cas' => [ 'enable' => false, ], 'ldap' => [ 'enable' => false, 'resolver' => [ 'ldap_user' => \Laravolt\Auth\Services\Resolvers\LdapUserResolver::class, 'eloquent_user' => \Laravolt\Auth\Services\Resolvers\EloquentUserResolver::class, ], ], 'router' => [ 'middleware' => ['web'], 'prefix' => 'auth', ], 'redirect' => [ 'after_login' => '/', 'after_register' => '/', 'after_reset_password' => '/', 'after_logout' => '/', ], ];
Add test to find a setting by name
<?php namespace Modules\Setting\Tests; class EloquentSettingRepositoryTest extends BaseSettingTest { public function setUp() { parent::setUp(); } /** @test */ public function it_creates_translated_setting() { // Prepare $data = [ 'core::site-name' => [ 'en' => 'AsgardCMS_en', 'fr' => 'AsgardCMS_fr', ] ]; // Run $this->settingRepository->createOrUpdate($data); // Assert $setting = $this->settingRepository->find(1); $this->assertEquals('core::site-name', $setting->name); $this->assertEquals('AsgardCMS_en', $setting->translate('en')->value); $this->assertEquals('AsgardCMS_fr', $setting->translate('fr')->value); } /** @test */ public function it_creates_plain_setting() { // Prepare $data = [ 'core::template' => 'asgard' ]; // Run $this->settingRepository->createOrUpdate($data); // Assert $setting = $this->settingRepository->find(1); $this->assertEquals('core::template', $setting->name); $this->assertEquals('asgard', $setting->plainValue); } /** @test */ public function it_finds_setting_by_name() { // Prepare $data = [ 'core::site-name' => [ 'en' => 'AsgardCMS_en', 'fr' => 'AsgardCMS_fr', ] ]; // Run $this->settingRepository->createOrUpdate($data); // Assert $setting = $this->settingRepository->findByName('core::site-name'); $this->assertEquals('core::site-name', $setting->name); $this->assertEquals('AsgardCMS_en', $setting->translate('en')->value); $this->assertEquals('AsgardCMS_fr', $setting->translate('fr')->value); } }
<?php namespace Modules\Setting\Tests; class EloquentSettingRepositoryTest extends BaseSettingTest { public function setUp() { parent::setUp(); } /** @test */ public function it_creates_translated_setting() { // Prepare $data = [ 'core::site-name' => [ 'en' => 'AsgardCMS_en', 'fr' => 'AsgardCMS_fr', ] ]; // Run $this->settingRepository->createOrUpdate($data); // Assert $setting = $this->settingRepository->find(1); $this->assertEquals('core::site-name', $setting->name); $this->assertEquals('AsgardCMS_en', $setting->translate('en')->value); $this->assertEquals('AsgardCMS_fr', $setting->translate('fr')->value); } /** @test */ public function it_creates_plain_setting() { // Prepare $data = [ 'core::template' => 'asgard' ]; // Run $this->settingRepository->createOrUpdate($data); // Assert $setting = $this->settingRepository->find(1); $this->assertEquals('core::template', $setting->name); $this->assertEquals('asgard', $setting->plainValue); } }
[FIX] website_field_autocomplete: Use search_read * Use search_read in controller data getter, instead of custom implementation
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import json from openerp import http from openerp.http import request from openerp.addons.website.controllers.main import Website class Website(Website): @http.route( '/website/field_autocomplete/<string:model>', type='http', auth='public', methods=['GET'], website=True, ) def _get_field_autocomplete(self, model, **kwargs): """ Return json autocomplete data """ domain = json.loads(kwargs.get('domain', "[]")) fields = json.loads(kwargs.get('fields', "[]")) limit = kwargs.get('limit', None) res = self._get_autocomplete_data(model, domain, fields, limit) return json.dumps(res.values()) def _get_autocomplete_data(self, model, domain, fields, limit=None): """ Gets and returns raw record data Params: model: Model name to query on domain: Search domain fields: List of fields to get limit: Limit results to Returns: Dict of record dicts, keyed by ID """ if limit: limit = int(limit) res = request.env[model].search_read( domain, fields, limit=limit ) return {r['id']: r for r in res}
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import json from openerp import http from openerp.http import request from openerp.addons.website.controllers.main import Website class Website(Website): @http.route( '/website/field_autocomplete/<string:model>', type='http', auth='public', methods=['GET'], website=True, ) def _get_field_autocomplete(self, model, **kwargs): """ Return json autocomplete data """ domain = json.loads(kwargs.get('domain', "[]")) fields = json.loads(kwargs.get('fields', "[]")) limit = kwargs.get('limit', None) res = self._get_autocomplete_data(model, domain, fields, limit) return json.dumps(res.values()) def _get_autocomplete_data(self, model, domain, fields, limit=None): """ Gets and returns raw record data Params: model: Model name to query on domain: Search domain fields: List of fields to get limit: Limit results to Returns: Dict of record dicts, keyed by ID """ res = {} if limit: limit = int(limit) self.record_ids = request.env[model].search(domain, limit=limit) for rec_id in self.record_ids: res[rec_id.id] = { k: getattr(rec_id, k, None) for k in fields } return res
Fix code format with php-cs-fixer
<?php namespace Cassowary\Adapter; class RedisAdapter implements AdapterInterface { const BLACKLIST_KEY = 'blacklist'; /** * @var \Redis */ private static $redis; /** * @var string */ private static $prefix; /** * @var int */ private static $duration; public static function init(array $params) { $redis = new \Redis(); if (array_key_exists('socket', $params)) { $redis->connect($params['socket']); } else { $redis->connect($params['host'], $params['port']); } $redis->select($params['index']); self::$redis = $redis; self::$prefix = $params['prefix']; self::$duration = $params['duration']; } public static function getCount($host) { return self::$redis->get(self::$prefix. $host); } public static function increment($host) { $count = self::$redis->incrBy(self::$prefix. $host, 1); if (self::$redis->get(self::$prefix. $host) == 1) { self::$redis->setTimeout(self::$prefix. $host, self::$duration); } return $count; } public static function addToBlacklist($host) { self::$redis->sAdd(self::$prefix. self::BLACKLIST_KEY, $host); } public static function getBlacklist() { return self::$redis->sMembers(self::$prefix. self::BLACKLIST_KEY); } }
<?php namespace Cassowary\Adapter; class RedisAdapter implements AdapterInterface { const BLACKLIST_KEY = 'blacklist'; /** * @var \Redis */ private static $redis; /** * @var string */ private static $prefix; /** * @var int */ private static $duration; public static function init(array $params) { $redis = new \Redis(); $redis->connect($params['host'], $params['port']); $redis->select($params['index']); self::$redis = $redis; self::$prefix = $params['prefix']; self::$duration = $params['duration']; } public static function getCount($host) { return self::$redis->get(self::$prefix.$host); } public static function increment($host) { $count = self::$redis->incrBy(self::$prefix.$host, 1); if (self::$redis->get(self::$prefix.$host) == 1) { self::$redis->setTimeout(self::$prefix.$host, self::$duration); } return $count; } public static function addToBlacklist($host) { self::$redis->sAdd(self::$prefix. self::BLACKLIST_KEY, $host); } public static function getBlacklist() { return self::$redis->sMembers(self::$prefix. self::BLACKLIST_KEY); } }
Fix Null Id, on create user Postgresql
<?php namespace ZfcUser\Mapper; use Zend\Stdlib\Hydrator\ClassMethods; use ZfcUser\Entity\UserInterface as UserEntityInterface; class UserHydrator extends ClassMethods { /** * Extract values from an object * * @param object $object * @return array * @throws Exception\InvalidArgumentException */ public function extract($object) { if (!$object instanceof UserEntityInterface) { throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface'); } /* @var $object UserInterface */ $data = parent::extract($object); if ($data['id'] !== null) { $data = $this->mapField('id', 'user_id', $data); } else { unset($data['id']); } return $data; } /** * Hydrate $object with the provided $data. * * @param array $data * @param object $object * @return UserInterface * @throws Exception\InvalidArgumentException */ public function hydrate(array $data, $object) { if (!$object instanceof UserEntityInterface) { throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface'); } $data = $this->mapField('user_id', 'id', $data); return parent::hydrate($data, $object); } protected function mapField($keyFrom, $keyTo, array $array) { $array[$keyTo] = $array[$keyFrom]; unset($array[$keyFrom]); return $array; } }
<?php namespace ZfcUser\Mapper; use Zend\Stdlib\Hydrator\ClassMethods; use ZfcUser\Entity\UserInterface as UserEntityInterface; class UserHydrator extends ClassMethods { /** * Extract values from an object * * @param object $object * @return array * @throws Exception\InvalidArgumentException */ public function extract($object) { if (!$object instanceof UserEntityInterface) { throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface'); } /* @var $object UserInterface*/ $data = parent::extract($object); $data = $this->mapField('id', 'user_id', $data); return $data; } /** * Hydrate $object with the provided $data. * * @param array $data * @param object $object * @return UserInterface * @throws Exception\InvalidArgumentException */ public function hydrate(array $data, $object) { if (!$object instanceof UserEntityInterface) { throw new Exception\InvalidArgumentException('$object must be an instance of ZfcUser\Entity\UserInterface'); } $data = $this->mapField('user_id', 'id', $data); return parent::hydrate($data, $object); } protected function mapField($keyFrom, $keyTo, array $array) { $array[$keyTo] = $array[$keyFrom]; unset($array[$keyFrom]); return $array; } }
:art: Fix mixins-before-declaration rule to work with latest gonzales
'use strict'; var helpers = require('../helpers'); module.exports = { 'name': 'mixins-before-declarations', 'defaults': { 'exclude': [ 'breakpoint', 'mq' ] }, 'detect': function (ast, parser) { var result = [], error; ast.traverseByType('include', function (node, i, parent) { var depth = 0, declarationCount = [depth]; parent.forEach(function (item) { if (item.is('ruleset')) { depth++; declarationCount[depth] = 0; } else if (item.is('declaration')) { if (item.first().is('property')) { var prop = item.first(); if (prop.first().is('ident')) { declarationCount[depth]++; } } } else if (item.is('include')) { item.forEach('ident', function (name) { if (parser.options.exclude.indexOf(name.content) === -1 && declarationCount[depth] > 0) { error = { 'ruleId': parser.rule.name, 'line': item.start.line, 'column': item.start.column, 'message': 'Mixins should come before declarations', 'severity': parser.severity }; result = helpers.addUnique(result, error); } }); } }); }); return result; } };
'use strict'; var helpers = require('../helpers'); module.exports = { 'name': 'mixins-before-declarations', 'defaults': { 'exclude': [ 'breakpoint', 'mq' ] }, 'detect': function (ast, parser) { var result = [], error; ast.traverseByType('include', function (node, i, parent) { var depth = 0, declarationCount = [depth]; parent.forEach( function (item) { if (item.type === 'ruleset') { depth++; declarationCount[depth] = 0; } else if (item.type === 'declaration') { if (item.first().is('property')) { var prop = item.first(); if (prop.first().is('ident')) { declarationCount[depth]++; } } } else if (item.type === 'include') { item.forEach('simpleSelector', function (name) { if (parser.options.exclude.indexOf(name.content[0].content) === -1 && declarationCount[depth] > 0) { error = { 'ruleId': parser.rule.name, 'line': item.start.line, 'column': item.start.column, 'message': 'Mixins should come before declarations', 'severity': parser.severity }; result = helpers.addUnique(result, error); } }); } }); }); return result; } };
Simplify how we determine if asset is already showing.
CMS.Views.Assets = Backbone.View.extend({ // takes CMS.Models.AssetCollection as model initialize : function() { this.listenTo(this.collection, 'destroy', this.handleDestroy); this.render(); }, render: function() { this.$el.empty(); var self = this; _.each(this.collection.models, function(asset) { var view = new CMS.Views.Asset({model: asset}); self.$el.append(view.render().el); }); return this; }, handleDestroy: function(model, collection, options) { var index = options.index; this.$el.children().eq(index).remove(); analytics.track('Deleted Asset', { 'course': course_location_analytics, 'id': model.get('url') }); }, addAsset: function (model) { // If asset is not already being shown, add it. if (this.collection.findWhere({'url': model.get('url')}) === undefined) { this.collection.add(model, {at: 0}); var view = new CMS.Views.Asset({model: model}); this.$el.prepend(view.render().el); analytics.track('Uploaded a File', { 'course': course_location_analytics, 'asset_url': model.get('url') }); } } });
CMS.Views.Assets = Backbone.View.extend({ // takes CMS.Models.AssetCollection as model initialize : function() { this.listenTo(this.collection, 'destroy', this.handleDestroy); this.render(); }, render: function() { this.$el.empty(); var self = this; _.each(this.collection.models, function(asset) { var view = new CMS.Views.Asset({model: asset}); self.$el.append(view.render().el); }); return this; }, handleDestroy: function(model, collection, options) { var index = options.index; this.$el.children().eq(index).remove(); analytics.track('Deleted Asset', { 'course': course_location_analytics, 'id': model.get('url') }); }, addAsset: function (model) { // If asset is not already being shown, add it. if (_.all( this.collection.models, function (asset) { return asset.get('url') !== model.get('url'); })) { this.collection.add(model, {at: 0}); var view = new CMS.Views.Asset({model: model}); this.$el.prepend(view.render().el); analytics.track('Uploaded a File', { 'course': course_location_analytics, 'asset_url': model.get('url') }); } } });
Save user role when signing up
<?php namespace app\models; use yii\base\Model; /** * Signup form */ class SignupForm extends Model { public $email; public $signup_token; public $password; /** * @inheritdoc */ public function rules() { return [ ['signup_token', 'trim'], ['email', 'trim'], ['email', 'required'], ['email', 'email'], ['email', 'string', 'max' => 255], ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'You are already an existing user. Proceed to login'], ['password', 'required'], ['password', 'string', 'min' => 6], ]; } /** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function signup() { if (!$this->validate()) { return null; } $user = new User(); $user->email = $this->email; $user->role = SignupLinks::findByEmail($this->email)->role; $user->setPassword($this->password); $user->generateAuthKey(); return $user->save() ? $user : null; } }
<?php namespace app\models; use yii\base\Model; /** * Signup form */ class SignupForm extends Model { public $email; public $signup_token; public $password; /** * @inheritdoc */ public function rules() { return [ ['signup_token', 'trim'], ['email', 'trim'], ['email', 'required'], ['email', 'email'], ['email', 'string', 'max' => 255], ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'You are already an existing user. Proceed to login'], ['password', 'required'], ['password', 'string', 'min' => 6], ]; } /** * Signs user up. * * @return User|null the saved model or null if saving fails */ public function signup() { if (!$this->validate()) { return null; } $user = new User(); $user->email = $this->email; $user->setPassword($this->password); $user->generateAuthKey(); return $user->save() ? $user : null; } }
Add buy card button to account page
import React, { Component } from 'react'; class AccountPage extends Component { constructor () { super(); } render () { const { account } = this.props; return ( <div class="AccountPage"> <div class="header col-sm-12 centered"> <h1>{account.name}</h1> <h3>Last worked: {account.lastCredit}</h3> <h3>Last purchase: {account.lastMeal}</h3> </div> <div id="credits" class="centered"> Barter Credits: ${(account.currentCredit / 100).toFixed(2)} </div> <div class="buttons row center-block"> <button class="btn btn-info col-sm-offset-1" onClick={() => this.props.switchView('buycardpage', account)}> Buy Card </button> <button class="btn btn-info col-sm-offset-1" onClick={() => this.props.switchView('buymealpage', account)}> Buy Meal </button> <button class="btn btn-success col-sm-offset-1" onClick={() => this.props.switchView('addcreditpage', account)}> Add Credit </button> </div> <div class="text-center row" onClick={() => this.props.switchView('searchpage')}> <button class="btn btn-lg btn-danger col-sm-offset-5 center-block">Back to Search</button> </div> </div> ); } } export default AccountPage;
import React, { Component } from 'react'; class AccountPage extends Component { constructor () { super(); } render () { const { account } = this.props; return ( <div class="AccountPage"> <div class="header col-sm-12 centered"> <h1>{account.name}</h1> <h3>Last worked: {account.lastCredit}</h3> <h3>Last purchase: {account.lastMeal}</h3> </div> <div id="credits" class="centered"> Barter Credits: ${(account.currentCredit / 100).toFixed(2)} </div> <div class="buttons row center-block"> <button class="btn btn-info col-sm-offset-1" onClick={() => this.props.switchView('buymealpage', account)}> Buy Meal </button> <button class="btn btn-success col-sm-offset-1" onClick={() => this.props.switchView('addcreditpage', account)}> Add Credit </button> </div> <div class="text-center row" onClick={() => this.props.switchView('searchpage')}> <button class="btn btn-lg btn-danger col-sm-offset-5 center-block">Back to Search</button> </div> </div> ); } } export default AccountPage;
Clean up node_modules after updating them
"use strict"; module.exports = function (grunt) { grunt.initConfig({ bump: { options: { files: ["package.json"], commit: true, commitMessage: "Release %VERSION%", commitFiles: ["-a"], createTag: true, tagName: "%VERSION%", tagMessage: "Version %VERSION%", push: false, } }, shell: { options: { stdout: true, stderr: true, failOnError: true }, push: { command: "git push -u -f --tags origin master" }, publish: { command: "npm publish" }, update: { command: "npm-check-updates -u" }, modules: { command: "rm -rf node_modules && npm install" } } }); grunt.registerTask("update", ["shell:update", "shell:modules"]); grunt.registerTask("release", ["bump", "shell:push", "shell:publish"]); grunt.registerTask("minor", ["bump:minor", "shell:push", "shell:publish"]); grunt.registerTask("major", ["bump:major", "shell:push", "shell:publish"]); grunt.loadNpmTasks("grunt-bump"); grunt.loadNpmTasks("grunt-shell"); };
"use strict"; module.exports = function (grunt) { grunt.initConfig({ bump: { options: { files: ["package.json"], commit: true, commitMessage: "Release %VERSION%", commitFiles: ["-a"], createTag: true, tagName: "%VERSION%", tagMessage: "Version %VERSION%", push: false, } }, shell: { options: { stdout: true, stderr: true, failOnError: true }, push: { command: "git push -u -f --tags origin master" }, publish: { command: "npm publish" }, update: { command: "npm-check-updates -u" } } }); grunt.registerTask("update", "shell:update"); grunt.registerTask("release", ["bump", "shell:push", "shell:publish"]); grunt.registerTask("minor", ["bump:minor", "shell:push", "shell:publish"]); grunt.registerTask("major", ["bump:major", "shell:push", "shell:publish"]); grunt.loadNpmTasks("grunt-bump"); grunt.loadNpmTasks("grunt-shell"); };
Fix : Drawer menu items are not centered
import React, { Component, PropTypes, View, Text, TouchableHighlight } from 'react-native'; import Icon from '../Icon'; import { TYPO } from '../config'; export default class Item extends Component { static propTypes = { icon: PropTypes.string, value: PropTypes.string.isRequired, onPress: PropTypes.func, active: PropTypes.bool, disabled: PropTypes.bool }; static defaultProps = { active: false, disabled: false }; render() { const { icon, value, onPress } = this.props; return ( <TouchableHighlight onPress={onPress} underlayColor={'#e8e8e8'} style={styles.touchable} > <View style={styles.item}> <Icon name={icon} color={'rgba(0,0,0,.54)'} size={22} style={styles.icon} /> <View style={styles.value}> <Text style={[TYPO.paperFontBody2, { color: 'rgba(0,0,0,.87)' }]}> {value} </Text> </View> </View> </TouchableHighlight> ); } } const styles = { touchable: { paddingHorizontal: 16, marginVertical: 8, height: 48 }, item: { flex: 1, flexDirection: 'row', alignItems: 'center', }, icon: { position: 'relative', top: -1 }, value: { flex: 1, paddingLeft: 34, top: 1 } };
import React, { Component, PropTypes, View, Text, TouchableHighlight } from 'react-native'; import Icon from '../Icon'; import { TYPO } from '../config'; export default class Item extends Component { static propTypes = { icon: PropTypes.string, value: PropTypes.string.isRequired, onPress: PropTypes.func, active: PropTypes.bool, disabled: PropTypes.bool }; static defaultProps = { active: false, disabled: false }; render() { const { icon, value, onPress } = this.props; return ( <TouchableHighlight onPress={onPress} underlayColor={'#e8e8e8'} style={styles.touchable} > <View style={styles.item}> <Icon name={icon} color={'rgba(0,0,0,.54)'} size={22} style={styles.icon} /> <View style={styles.value}> <Text style={[TYPO.paperFontBody2, { color: 'rgba(0,0,0,.87)' }]}> {value} </Text> </View> </View> </TouchableHighlight> ); } } const styles = { touchable: { paddingHorizontal: 16, marginVertical: 8, height: 48 }, item: { flex: 1, flexDirection: 'row', alignItems: 'center', }, icon: { position: 'relative', top: -2 }, value: { flex: 1, paddingLeft: 34 } };
Move to spec inspired test names (truth always wins.)
package com.github.mttkay.memento; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; import com.google.testing.compile.CompilationFailureException; import com.google.testing.compile.JavaFileObjects; import com.sun.tools.internal.xjc.util.NullStream; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.truth0.Truth; import java.io.PrintStream; @RunWith(JUnit4.class) public class MementoProcessorTest { @Before public void dontPrintExceptions() { // get rid of the stack trace prints for expected exceptions System.setErr(new PrintStream(new NullStream())); } @Test public void itGeneratesMementoFragmentClass() { Truth.ASSERT.about(javaSource()) .that(JavaFileObjects.forResource("RetainedActivity.java")) .processedWith(new MementoProcessor()) .compilesWithoutError() .and().generatesSources(JavaFileObjects.forResource("RetainedActivity$Memento.java")); } @Test(expected = CompilationFailureException.class) public void itThrowsExceptionWhenRetainedFieldIsPrivate() { Truth.ASSERT.about(javaSource()) .that(JavaFileObjects.forResource("RetainedActivityWithPrivateFields.java")) .processedWith(new MementoProcessor()) .failsToCompile(); } }
package com.github.mttkay.memento; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; import com.google.testing.compile.CompilationFailureException; import com.google.testing.compile.JavaFileObjects; import com.sun.tools.internal.xjc.util.NullStream; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.truth0.Truth; import java.io.PrintStream; @RunWith(JUnit4.class) public class MementoProcessorTest { @Before public void dontPrintExceptions() { // get rid of the stack trace prints for expected exceptions System.setErr(new PrintStream(new NullStream())); } @Test public void generateMementoClass() { Truth.ASSERT.about(javaSource()) .that(JavaFileObjects.forResource("RetainedActivity.java")) .processedWith(new MementoProcessor()) .compilesWithoutError() .and().generatesSources(JavaFileObjects.forResource("RetainedActivity$Memento.java")); } @Test(expected = CompilationFailureException.class) public void throwsIllegalStateIfRetainedFieldIsPrivate() { Truth.ASSERT.about(javaSource()) .that(JavaFileObjects.forResource("RetainedActivityWithPrivateFields.java")) .processedWith(new MementoProcessor()) .failsToCompile(); } }
Add tests for adding default and installed level packs
describe('Game Manager', function() { it('is an object', function() { expect(Flown.GameManager).toBeDefined(); expect(typeof Flown.GameManager).toBe('object'); }); describe('creating a game manager', function() { it('has a create function', function() { expect(Flown.GameManager.create).toBeDefined(); expect(typeof Flown.GameManager.create).toBe('function'); }); it('creates a new game manager object', function() { var gameManager = Flown.GameManager.create(); expect(gameManager).toBeDefined(); expect(gameManager._levelManager).toBeDefined(); expect(gameManager._gameBoard).toBeDefined(); }); }); describe('initialising a game manager', function() { var gameManager; beforeEach(function() { Flown.DefaultLevels = exampleLevelPacks1; window.localStorage.setItem('flown.extrapacks', JSON.stringify(exampleLevelPacks2)); gameManager = Flown.GameManager.create(); }); afterEach(function() { window.localStorage.clear('flown.extrapacks'); }); it('has an init function', function() { expect(Flown.GameManager.init).toBeDefined(); expect(typeof Flown.GameManager.init).toBe('function'); }); it('sets the initial values of the game manager object', function() { expect(gameManager._levelManager).toBeDefined(); expect(gameManager._gameBoard).toBeDefined(); expect(gameManager._levelManager._packs.length).toBe(exampleLevelPacks1.length + exampleLevelPacks2.length); }); }); });
describe('Game Manager', function() { it('is an object', function() { expect(Flown.GameManager).toBeDefined(); expect(typeof Flown.GameManager).toBe('object'); }); describe('creating a game manager', function() { it('has a create function', function() { expect(Flown.GameManager.create).toBeDefined(); expect(typeof Flown.GameManager.create).toBe('function'); }); it('creates a new game manager object', function() { var gameManager = Flown.GameManager.create(); expect(gameManager).toBeDefined(); expect(gameManager._levelManager).toBeDefined(); expect(gameManager._gameBoard).toBeDefined(); }); }); describe('initialising a game manager', function() { var gameManager; beforeEach(function() { gameManager = Flown.GameManager.create(); }); it('has an init function', function() { expect(Flown.GameManager.init).toBeDefined(); expect(typeof Flown.GameManager.init).toBe('function'); }); it('sets the initial values of the game manager object', function() { var gameManager = Flown.GameManager.create(); expect(gameManager._levelManager).toBeDefined(); expect(gameManager._gameBoard).toBeDefined(); }); }); });
Use modify with the orderbook
from order import Order from orderbook import OrderBook from client import FinanceClient from ordermanager import OrderManager from strategy import Vanilla, Strawberry import sys # local server for finance data host_ip, server_port = "localhost", 9995 def main(): """ Turn on the FinanceServer - fetch data from the FinanceServer - parse out each order as an Order object - add these Orders to the OrderBook using the values in Action - for each added order, decide to trade indicated by signal """ strategy_choice = sys.argv[1] books = {} client = FinanceClient(host_ip, server_port) ordermanager = OrderManager() if strategy_choice == 'Vanilla': strategy = Vanilla() elif strategy_choice == 'Strawberry': strategy = Strawberry() else: print('strategies available: Vanilla or Strawberry') print(strategy.name, strategy.description) for line in client.fetch(): try: order = Order(line) book = books.get(order.symbol) if book is None: book = books[order.symbol] = OrderBook(order.symbol) if order.action == 'A': book.add(order) elif order.side == 'M': book.modify(order) bid, offer = book.display_book(output=True) ordermanager.signal(bid, offer, strategy.execute) except Exception as e: print(e) pass if __name__ == '__main__': main()
from order import Order from orderbook import OrderBook from client import FinanceClient from ordermanager import OrderManager from strategy import Vanilla, Strawberry import sys # local server for finance data host_ip, server_port = "localhost", 9995 def main(): """ Turn on the FinanceServer - fetch data from the FinanceServer - parse out each order as an Order object - add these Orders to the OrderBook using the values in Action - for each added order, decide to trade indicated by signal """ strategy_choice = sys.argv[1] books = {} client = FinanceClient(host_ip, server_port) ordermanager = OrderManager() if strategy_choice == 'Vanilla': strategy = Vanilla() elif strategy_choice == 'Strawberry': strategy = Strawberry() else: print('strategies available: Vanilla or Strawberry') print(strategy.name, strategy.description) for line in client.fetch(): try: order = Order(line) book = books.get(order.symbol) if book is None: book = books[order.symbol] = OrderBook(order.symbol) book.add(order) bid, offer = book.display_book(output=True) ordermanager.signal(bid, offer, strategy.execute) except Exception as e: print(e) pass if __name__ == '__main__': main()
Correct spelling of Django in requirements It seems that using 'django' instead of 'Django' has the consequence that "pip install django_debug_toolbar" has the consequence of installing the latest version of Django, even if you already have Django installed.
from setuptools import setup, find_packages from io import open setup( name='django-debug-toolbar', version='1.3.2', description='A configurable set of panels that display various debug ' 'information about the current request/response.', long_description=open('README.rst', encoding='utf-8').read(), author='Rob Hudson', author_email='[email protected]', url='https://github.com/django-debug-toolbar/django-debug-toolbar', download_url='https://pypi.python.org/pypi/django-debug-toolbar', license='BSD', packages=find_packages(exclude=('tests.*', 'tests', 'example')), install_requires=[ 'Django>=1.4.2', 'sqlparse', ], include_package_data=True, zip_safe=False, # because we're including static files classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
from setuptools import setup, find_packages from io import open setup( name='django-debug-toolbar', version='1.3.2', description='A configurable set of panels that display various debug ' 'information about the current request/response.', long_description=open('README.rst', encoding='utf-8').read(), author='Rob Hudson', author_email='[email protected]', url='https://github.com/django-debug-toolbar/django-debug-toolbar', download_url='https://pypi.python.org/pypi/django-debug-toolbar', license='BSD', packages=find_packages(exclude=('tests.*', 'tests', 'example')), install_requires=[ 'django>=1.4.2', 'sqlparse', ], include_package_data=True, zip_safe=False, # because we're including static files classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Adjust unit test for new props webpage
import DomMock from '../../helpers/dom-mock'; import jsdom from 'mocha-jsdom'; import expect from 'expect'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import { Portal } from '../../../portal/src/containers/Portal'; import FBLogin from '../../../portal/src/components/FBLogin'; import Subject from '../../../portal/src/components/Popup/Subject'; DomMock('<html><body></body></html>'); describe('[Portal] Testing Portal Component', () => { jsdom({ skipWindowCheck: true }); const props = { loading: false, token: 'xxxx', account: {}, subject: '', surveyID: '', editSubject: false, preview: '', previewID: '', webpage: 'index', routing: {}, editSubjectActions: () => {}, subjectActions: () => {}, questionsActions: () => {}, previewActions: () => {}, accountActions: () => {} }; it('Portal: FB Login', () => { const content = TestUtils.renderIntoDocument(<Portal {...props} />); const fb = TestUtils.scryRenderedComponentsWithType(content, FBLogin); expect(fb.length).toEqual(1); }); it('Portal: edit subject popup', () => { const editProps = Object.assign({}, props, { editSubject: true }); const content = TestUtils.renderIntoDocument(<Portal {...editProps} />); const subject = TestUtils.findRenderedComponentWithType(content, Subject); expect(subject).toExist(); }); });
import DomMock from '../../helpers/dom-mock'; import jsdom from 'mocha-jsdom'; import expect from 'expect'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import { Portal } from '../../../portal/src/containers/Portal'; import FBLogin from '../../../portal/src/components/FBLogin'; import Subject from '../../../portal/src/components/Popup/Subject'; DomMock('<html><body></body></html>'); describe('[Portal] Testing Portal Component', () => { jsdom({ skipWindowCheck: true }); const props = { loading: false, token: 'xxxx', account: {}, subject: '', surveyID: '', editSubject: false, preview: '', previewID: '', routing: {}, editSubjectActions: () => {}, subjectActions: () => {}, questionsActions: () => {}, previewActions: () => {}, accountActions: () => {} }; it('Portal: FB Login', () => { const content = TestUtils.renderIntoDocument(<Portal {...props} />); const fb = TestUtils.scryRenderedComponentsWithType(content, FBLogin); expect(fb.length).toEqual(1); }); it('Portal: edit subject popup', () => { const editProps = Object.assign({}, props, { editSubject: true }); const content = TestUtils.renderIntoDocument(<Portal {...editProps} />); const subject = TestUtils.findRenderedComponentWithType(content, Subject); expect(subject).toExist(); }); });
Use instanceof to include subclasses
<?php /** * @package elemental */ class ElementalGridFieldDeleteAction extends GridFieldDeleteAction { public function getColumnContent($gridField, $record, $columnName) { if(!$record->canEdit()) return; $field = new CompositeField(); if(!$record instanceof ElementVirtualLinked) { $field->push(GridField_FormAction::create($gridField, 'UnlinkRelation'.$record->ID, false, "unlinkrelation", array('RecordID' => $record->ID)) ->addExtraClass('gridfield-button-unlink') ->setAttribute('title', _t('GridAction.UnlinkRelation', "Unlink")) ->setAttribute('data-icon', 'chain--minus') ); } if($record->canDelete() && $record->VirtualClones()->count() == 0) { $field->push(GridField_FormAction::create($gridField, 'DeleteRecord'.$record->ID, false, "deleterecord", array('RecordID' => $record->ID)) ->addExtraClass('gridfield-button-delete') ->setAttribute('title', _t('GridAction.Delete', "Delete")) ->setAttribute('data-icon', 'cross-circle') ->setDescription(_t('GridAction.DELETE_DESCRIPTION','Delete')) ); } return $field->Field(); } }
<?php /** * @package elemental */ class ElementalGridFieldDeleteAction extends GridFieldDeleteAction { public function getColumnContent($gridField, $record, $columnName) { if(!$record->canEdit()) return; $field = new CompositeField(); if($record->getClassName() != "ElementVirtualLinked") { $field->push(GridField_FormAction::create($gridField, 'UnlinkRelation'.$record->ID, false, "unlinkrelation", array('RecordID' => $record->ID)) ->addExtraClass('gridfield-button-unlink') ->setAttribute('title', _t('GridAction.UnlinkRelation', "Unlink")) ->setAttribute('data-icon', 'chain--minus') ); } if($record->canDelete() && $record->VirtualClones()->count() == 0) { $field->push(GridField_FormAction::create($gridField, 'DeleteRecord'.$record->ID, false, "deleterecord", array('RecordID' => $record->ID)) ->addExtraClass('gridfield-button-delete') ->setAttribute('title', _t('GridAction.Delete', "Delete")) ->setAttribute('data-icon', 'cross-circle') ->setDescription(_t('GridAction.DELETE_DESCRIPTION','Delete')) ); } return $field->Field(); } }
Fix wrong CLI argument type
from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=str) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py")
from django.core.management.base import BaseCommand from submission.models import Article from core.models import File class Command(BaseCommand): """Dumps the text of files to the database using FileText Model""" help = """ Dumps the text of galley files into the database, which populates the full-text searching indexes """ def add_arguments(self, parser): parser.add_argument('--journal-code', type=int) parser.add_argument('--article-id', type=int) parser.add_argument('--file-id', type=int) parser.add_argument('--all', action="store_true", default=False) def handle(self, *args, **options): if options["file_id"]: file_ = File.objects.get(id=options["file_id"]) file_.index_full_text() elif options["article_id"] or options["journal_code"] or options["all"]: articles = Article.objects.all() if options["journal_code"]: articles = articles.filter(journal__code=options["journal_code"]) if options["article_id"]: articles = articles.filter(id=options["article_id"]) for article in articles: print(f"Processing Article {article.pk}") article.index_full_text() else: self.stderr.write("At least one filtering flag must be provided") self.print_help("manage.py", "dump_file_text_to_db.py")
Add 'tomorrow' to date range filter As requested by CITA.
/* global moment */ (function($) { 'use strict'; var dateRangePicker = { init: function() { this.$picker = $('.js-date-range-picker'); this.$picker.daterangepicker({ ranges: { 'Today': [moment(), moment()], 'Tomorrow': [moment().add(1, 'days'), moment().add(1, 'days')], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] }, locale: { format: 'DD/MM/YYYY', cancelLabel: 'Clear' }, autoUpdateInput: false }); this.$picker.on('apply.daterangepicker', function(ev, picker) { $(this).val(picker.startDate.format('DD/MM/YYYY') + ' - ' + picker.endDate.format('DD/MM/YYYY')); }); this.$picker.on('cancel.daterangepicker', function() { $(this).val(''); }); } }; window.PWPlanner = window.PWPlanner || {}; window.PWPlanner.dateRangePicker = dateRangePicker; })(jQuery);
/* global moment */ (function($) { 'use strict'; var dateRangePicker = { init: function() { this.$picker = $('.js-date-range-picker'); this.$picker.daterangepicker({ ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] }, locale: { format: 'DD/MM/YYYY', cancelLabel: 'Clear' }, autoUpdateInput: false }); this.$picker.on('apply.daterangepicker', function(ev, picker) { $(this).val(picker.startDate.format('DD/MM/YYYY') + ' - ' + picker.endDate.format('DD/MM/YYYY')); }); this.$picker.on('cancel.daterangepicker', function() { $(this).val(''); }); } }; window.PWPlanner = window.PWPlanner || {}; window.PWPlanner.dateRangePicker = dateRangePicker; })(jQuery);
Rename caught previous exception variable
<?php declare(strict_types = 1); namespace EPS\PhpUri\Validator; use EPS\PhpUri\Exception\ValidatorException; final class AggregatedValidator implements Validator { /** * @var Validator[] */ private $validators; public function __construct(array $validators) { $this->validators = []; foreach ($validators as $validator) { $this->addValidator($validator); } } public function addValidator(Validator $validator): void { $this->validators[] = $validator; } /** * {@inheritdoc} */ public function validate(string $uriCandidate): bool { $results = array_map( function (Validator $validator) use ($uriCandidate) { return $this->processValidator($validator, $uriCandidate); }, $this->validators ); $failedValidations = array_filter($results, function (bool $result) { return $result === false; }); if (empty($failedValidations)) { return true; } throw ValidatorException::validationFailed($uriCandidate); } private function processValidator(Validator $validator, string $uriCandidate) { try { return $validator->validate($uriCandidate); } catch (\Throwable $previousException) { throw ValidatorException::validationFailed($uriCandidate, $previousException); } } }
<?php declare(strict_types = 1); namespace EPS\PhpUri\Validator; use EPS\PhpUri\Exception\ValidatorException; final class AggregatedValidator implements Validator { /** * @var Validator[] */ private $validators; public function __construct(array $validators) { $this->validators = []; foreach ($validators as $validator) { $this->addValidator($validator); } } public function addValidator(Validator $validator): void { $this->validators[] = $validator; } /** * {@inheritdoc} */ public function validate(string $uriCandidate): bool { $results = array_map( function (Validator $validator) use ($uriCandidate) { return $this->processValidator($validator, $uriCandidate); }, $this->validators ); $failedValidations = array_filter($results, function (bool $result) { return $result === false; }); if (empty($failedValidations)) { return true; } throw ValidatorException::validationFailed($uriCandidate); } private function processValidator(Validator $validator, string $uriCandidate) { try { return $validator->validate($uriCandidate); } catch (\Throwable $exception) { throw ValidatorException::validationFailed($uriCandidate, $exception); } } }
Make parameterized assertion error extend assertion error
package org.junit.experimental.theories.internal; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; public class ParameterizedAssertionError extends AssertionError { private static final long serialVersionUID = 1L; public ParameterizedAssertionError(Throwable targetException, String methodName, Object... params) { super(String.format("%s(%s)", methodName, join(", ", params))); this.initCause(targetException); } @Override public boolean equals(Object obj) { return toString().equals(obj.toString()); } public static String join(String delimiter, Object... params) { return join(delimiter, Arrays.asList(params)); } public static String join(String delimiter, Collection<Object> values) { StringBuffer buffer = new StringBuffer(); Iterator<Object> iter = values.iterator(); while (iter.hasNext()) { Object next = iter.next(); buffer.append(stringValueOf(next)); if (iter.hasNext()) { buffer.append(delimiter); } } return buffer.toString(); } private static String stringValueOf(Object next) { try { return String.valueOf(next); } catch (Throwable e) { return "[toString failed]"; } } }
package org.junit.experimental.theories.internal; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; public class ParameterizedAssertionError extends RuntimeException { private static final long serialVersionUID = 1L; public ParameterizedAssertionError(Throwable targetException, String methodName, Object... params) { super(String.format("%s(%s)", methodName, join(", ", params)), targetException); } @Override public boolean equals(Object obj) { return toString().equals(obj.toString()); } public static String join(String delimiter, Object... params) { return join(delimiter, Arrays.asList(params)); } public static String join(String delimiter, Collection<Object> values) { StringBuffer buffer = new StringBuffer(); Iterator<Object> iter = values.iterator(); while (iter.hasNext()) { Object next = iter.next(); buffer.append(stringValueOf(next)); if (iter.hasNext()) { buffer.append(delimiter); } } return buffer.toString(); } private static String stringValueOf(Object next) { try { return String.valueOf(next); } catch (Throwable e) { return "[toString failed]"; } } }
Fix build wheels with Pandoc 2.
import os from subprocess import call, check_output import sys from shutil import copy2 platform = sys.platform def checkAndInstall(): try: check_output('pandoc -v'.split()) except OSError: def getFile(): from requests import get with open(pandocFile, "wb") as file: response = get(source) file.write(response.content) if platform == 'win32': pandocFile = 'pandoc-2.1.3-windows.msi' source = 'https://github.com/jgm/pandoc/releases/download/2.1.3/' + pandocFile getFile() call('msiexec.exe /i "{}" /norestart'.format(pandocFile)) else: pandocFile = 'pandoc-2.1.3-linux.tar.gz' source = 'https://github.com/jgm/pandoc/releases/download/2.1.3/' + pandocFile getFile() call("tar -xvzf {}".format(pandocFile).split()) copy2('./pandoc-2.1.3/bin/pandoc', '/usr/local/bin') copy2('./pandoc-2.1.3/bin/pandoc-citeproc', '/usr/local/bin') if __name__ == '__main__': checkAndInstall()
import os from subprocess import call, check_output import sys from shutil import copy2 platform = sys.platform def checkAndInstall(): try: check_output('pandoc -v'.split()) except OSError: cudir = os.path.abspath(os.curdir) os.chdir(os.path.abspath(os.path.join(os.path.pardir, 'downloads'))) def getFile(): from requests import get with open(pandocFile, "wb") as file: response = get(source) file.write(response.content) if platform == 'win32': pandocFile = 'pandoc-2.1.3-windows.msi' source = 'https://github.com/jgm/pandoc/releases/download/2.1.3/' + pandocFile getFile() call('msiexec.exe /i "{}" /norestart'.format(pandocFile)) else: pandocFile = 'pandoc-2.1.3-linux.tar.gz' source = 'https://github.com/jgm/pandoc/releases/download/2.1.3/' + pandocFile getFile() call("tar -xvzf {}".format(pandocFile).split()) copy2('./pandoc-2.1.3/bin/pandoc', '/usr/local/bin') copy2('./pandoc-2.1.3/bin/pandoc-citeproc', '/usr/local/bin') os.chdir(cudir) if __name__ == '__main__': checkAndInstall()
Set fileParameterName for flow to the route used by the upload service.
Application.Services.factory("mcFlow", mcFlowService); function mcFlowService() { var self = this; self.flow = new Flow( { target: "/api/upload/chunk", testChunks: false, fileParameterName: "chunkData" } ); function each(obj, callback, context) { if (!obj) { return ; } var key; // Is Array? if (typeof(obj.length) !== 'undefined') { for (key = 0; key < obj.length; key++) { if (callback.call(context, obj[key], key) === false) { return ; } } } else { for (key in obj) { if (obj.hasOwnProperty(key) && callback.call(context, obj[key], key) === false) { return ; } } } } function extend(dst, src) { each(arguments, function(obj) { if (obj !== dst) { each(obj, function(value, key){ dst[key] = value; }); } }); return dst; } self.service = { get: function() { return self.flow; } }; return self.service; }
Application.Services.factory("mcFlow", mcFlowService); function mcFlowService() { var self = this; self.flow = new Flow( { target: "/api/upload/chunk", testChunks: false } ); function each(obj, callback, context) { if (!obj) { return ; } var key; // Is Array? if (typeof(obj.length) !== 'undefined') { for (key = 0; key < obj.length; key++) { if (callback.call(context, obj[key], key) === false) { return ; } } } else { for (key in obj) { if (obj.hasOwnProperty(key) && callback.call(context, obj[key], key) === false) { return ; } } } } function extend(dst, src) { each(arguments, function(obj) { if (obj !== dst) { each(obj, function(value, key){ dst[key] = value; }); } }); return dst; } self.service = { get: function() { return self.flow; } }; return self.service; }
Return empty array instead of null
<?php /** * PostRenderer.php * * Created By: jonathan * Date: 24/09/2017 * Time: 22:17 */ namespace Stati\Reader; use Stati\Entity\Page; use Stati\Entity\Sass; use Symfony\Component\Finder\Finder; use Stati\Reader\Reader; use Symfony\Component\Yaml\Yaml; /** * Copies files and folders that do not start with _ and do not have frontmatter * Class FilesRenderer * @package Stati\Renderer */ class DataReader extends Reader { public function read() { $config = $this->site->getConfig(); $dataDir = $config['data_dir']; if (!is_dir($dataDir)) { return []; } // Get top level files and parse $finder = new Finder(); $finder ->in('./_data/') ->files() ->notName('/^_/') ->name('/(.yml|.yaml)$/') ; foreach ($config['exclude'] as $exclude) { $finder->notName($exclude); $finder->notPath($exclude); } $data = []; foreach ($finder as $file) { $name = pathinfo($file->getFilename(), PATHINFO_FILENAME); $data[$name] = Yaml::parse($file->getContents()); } return $data; } }
<?php /** * PostRenderer.php * * Created By: jonathan * Date: 24/09/2017 * Time: 22:17 */ namespace Stati\Reader; use Stati\Entity\Page; use Stati\Entity\Sass; use Symfony\Component\Finder\Finder; use Stati\Reader\Reader; use Symfony\Component\Yaml\Yaml; /** * Copies files and folders that do not start with _ and do not have frontmatter * Class FilesRenderer * @package Stati\Renderer */ class DataReader extends Reader { public function read() { $config = $this->site->getConfig(); $dataDir = $config['data_dir']; if (!is_dir($dataDir)) { return; } // Get top level files and parse $finder = new Finder(); $finder ->in('./_data/') ->files() ->notName('/^_/') ->name('/(.yml|.yaml)$/') ; foreach ($config['exclude'] as $exclude) { $finder->notName($exclude); $finder->notPath($exclude); } $data = []; foreach ($finder as $file) { $name = pathinfo($file->getFilename(), PATHINFO_FILENAME); $data[$name] = Yaml::parse($file->getContents()); } return $data; } }
Fix type in contrib.sites.migrations for Django 2.x compatibility
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.contrib.sites.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Site', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)), ('domain', models.CharField(verbose_name='domain name', max_length=100, validators=[django.contrib.sites.models._simple_domain_name_validator])), ('name', models.CharField(verbose_name='display name', max_length=50)), ], options={ 'verbose_name_plural': 'sites', 'verbose_name': 'site', 'db_table': 'django_site', 'ordering': ('domain',), }, managers=[ ('objects', django.contrib.sites.models.SiteManager()), ], ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.contrib.sites.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Site', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)), ('domain', models.CharField(verbose_name='domain name', max_length=100, validators=[django.contrib.sites.models._simple_domain_name_validator])), ('name', models.CharField(verbose_name='display name', max_length=50)), ], options={ 'verbose_name_plural': 'sites', 'verbose_name': 'site', 'db_table': 'django_site', 'ordering': ('domain',), }, managers=[ (b'objects', django.contrib.sites.models.SiteManager()), ], ), ]
Trim repository URL when copied/pasted from a repo hoster (google code) the URL may include trailing spaces that make the clone command fail
package hudson.plugins.git; import java.io.Serializable; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.util.FormValidation; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; @ExportedBean public class UserRemoteConfig extends AbstractDescribableImpl<UserRemoteConfig> implements Serializable { private String name; private String refspec; private String url; @DataBoundConstructor public UserRemoteConfig(String url, String name, String refspec) { this.url = StringUtils.trim(url); this.name = name; this.refspec = refspec; } @Exported public String getName() { return name; } @Exported public String getRefspec() { return refspec; } @Exported public String getUrl() { return url; } @Extension public static class DescriptorImpl extends Descriptor<UserRemoteConfig> { public FormValidation doCheckUrl(@QueryParameter String value) { if (value == null || value.isEmpty()) { return FormValidation.error("Please enter Git repository."); } else { return FormValidation.ok(); } } @Override public String getDisplayName() { return ""; } } }
package hudson.plugins.git; import java.io.Serializable; import hudson.Extension; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.util.FormValidation; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; @ExportedBean public class UserRemoteConfig extends AbstractDescribableImpl<UserRemoteConfig> implements Serializable { private String name; private String refspec; private String url; @DataBoundConstructor public UserRemoteConfig(String url, String name, String refspec) { this.url = url; this.name = name; this.refspec = refspec; } @Exported public String getName() { return name; } @Exported public String getRefspec() { return refspec; } @Exported public String getUrl() { return url; } @Extension public static class DescriptorImpl extends Descriptor<UserRemoteConfig> { public FormValidation doCheckUrl(@QueryParameter String value) { if (value == null || value.isEmpty()) { return FormValidation.error("Please enter Git repository."); } else { return FormValidation.ok(); } } @Override public String getDisplayName() { return ""; } } }
Remove serializer 0.0->0 todo. Functionality is correct. My JSON Firefox plugin hid the .0, making me think this was a Jackson problem. However, Jackson is correctly outputting floats.
package com.indeed.proctor.service; import com.fasterxml.jackson.annotation.JsonInclude; import com.indeed.proctor.common.model.Payload; import com.indeed.proctor.common.model.TestBucket; /** * Representation of TestBucket intended for serialization into JSON. * * Mostly a rewriting of TestBucket with a few extras like skipping nulls and included test version for caching. */ @JsonInclude(JsonInclude.Include.NON_NULL) public class JsonTestBucket { final private String name; final private int value; final private Object payload; final private int version; /** * Serializes the object using an existing bucket and a separate version. * * Version needs to be obtained outside of the bucket through ProctorResult.getTestVersions() */ public JsonTestBucket(final TestBucket bucket, final int version) { name = bucket.getName(); value = bucket.getValue(); this.version = version; // The json serializer will automatically make this into whatever json type it should be. // So we don't have to worry about figuring out the type of the payload. final Payload bucketPayload = bucket.getPayload(); if (bucketPayload != null) { payload = bucket.getPayload().fetchAValue(); } else { payload = null; } } public String getName() { return name; } public int getValue() { return value; } public Object getPayload() { return payload; } public int getVersion() { return version; } }
package com.indeed.proctor.service; import com.fasterxml.jackson.annotation.JsonInclude; import com.indeed.proctor.common.model.Payload; import com.indeed.proctor.common.model.TestBucket; /** * Representation of TestBucket intended for serialization into JSON. * * Mostly a rewriting of TestBucket with a few extras like skipping nulls and included test version for caching. */ @JsonInclude(JsonInclude.Include.NON_NULL) public class JsonTestBucket { final private String name; final private int value; final private Object payload; final private int version; /** * Serializes the object using an existing bucket and a separate version. * * Version needs to be obtained outside of the bucket through ProctorResult.getTestVersions() */ public JsonTestBucket(final TestBucket bucket, final int version) { name = bucket.getName(); value = bucket.getValue(); this.version = version; // The json serializer will automatically make this into whatever json type it should be. // So we don't have to worry about figuring out the type of the payload. // TODO: The serializer converts 0.0 to 0. Is this a problem? final Payload bucketPayload = bucket.getPayload(); if (bucketPayload != null) { payload = bucket.getPayload().fetchAValue(); } else { payload = null; } } public String getName() { return name; } public int getValue() { return value; } public Object getPayload() { return payload; } public int getVersion() { return version; } }
Fix styling on flights form
import React from 'react' export function FlightsForm({ homeFloor, value, onChange }) { function onFlightsChanged(event) { const flights = parseFloat(event.target.value) onChange(flights) } function addFlights(flights) { onChange(value + flights) } function onAddDefaultFlights() { addFlights(homeFloor) } function addFlight() { addFlights(1) } function subtractFlight() { addFlights(-1) } return ( <div> <div className="input-group"> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={subtractFlight} type="button">-</button> </span> <input type="number" className="form-control" value={value} onChange={onFlightsChanged} /> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={addFlight} type="button">+</button> </span> </div> <button className="btn btn-block btn-primary" onClick={onAddDefaultFlights}> Add {homeFloor} flights </button> <p>{value * 13} ft</p> </div> ) } FlightsForm.propTypes = { homeFloor: React.PropTypes.number, value: React.PropTypes.number, onChange: React.PropTypes.func.isRequired, } FlightsForm.defaultProps = { homeFloor: 1, value: 0, onChange() {}, }
import React from 'react' export function FlightsForm({ homeFloor, value, onChange }) { function onFlightsChanged(event) { const flights = parseFloat(event.target.value) onChange(flights) } function addFlights(flights) { onChange(value + flights) } function onAddDefaultFlights() { addFlights(homeFloor) } function addFlight() { addFlights(1) } function subtractFlight() { addFlights(-1) } return ( <div> <fieldset className="input-group"> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={subtractFlight} type="button">-</button> </span> <input type="number" className="form-control" value={value} onChange={onFlightsChanged} /> <span className="input-group-btn"> <button className="btn btn-secondary" onClick={addFlight} type="button">+</button> </span> </fieldset> <button className="btn btn-block btn-primary" onClick={onAddDefaultFlights}> Add {homeFloor} flights </button> <p>{value * 13} ft</p> </div> ) } FlightsForm.propTypes = { homeFloor: React.PropTypes.number, value: React.PropTypes.number, onChange: React.PropTypes.func.isRequired, } FlightsForm.defaultProps = { homeFloor: 1, value: 0, onChange() {}, }
Fix code standards on callback
<?php /* * This file is part of Respect/Validation. * * (c) Alexandre Gomes Gaigalas <[email protected]> * * For the full copyright and license information, please view the "LICENSE.md" * file that was distributed with this source code. */ namespace Respect\Validation\Rules; use stdClass; /** * @group rule * @covers \Respect\Validation\Rules\StringVal */ class StringValTest extends RuleTestCase { public function providerForValidInput() { $rule = new StringVal(); return [ [$rule, '6'], [$rule, 'String'], [$rule, 1.0], [$rule, 42], [$rule, false], [$rule, true], [$rule, new ClassWithToString()], ]; } public function providerForInvalidInput() { $rule = new StringVal(); return [ [$rule, []], [$rule, function () { }], [$rule, new stdClass()], [$rule, null], [$rule, tmpfile()], ]; } } class ClassWithToString { public function __toString() { return self::class; } }
<?php /* * This file is part of Respect/Validation. * * (c) Alexandre Gomes Gaigalas <[email protected]> * * For the full copyright and license information, please view the "LICENSE.md" * file that was distributed with this source code. */ namespace Respect\Validation\Rules; use stdClass; /** * @group rule * @covers \Respect\Validation\Rules\StringVal */ class StringValTest extends RuleTestCase { public function providerForValidInput() { $rule = new StringVal(); return [ [$rule, '6'], [$rule, 'String'], [$rule, 1.0], [$rule, 42], [$rule, false], [$rule, true], [$rule, new ClassWithToString()], ]; } public function providerForInvalidInput() { $rule = new StringVal(); return [ [$rule, []], [$rule, function () { }], [$rule, new stdClass()], [$rule, null], [$rule, tmpfile()], ]; } } class ClassWithToString { public function __toString() { return self::class; } }
Create users when they log in
import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): u = User().current() user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if not oa: oa = OldAuth() oa.site = site oa.put() user_name = user.nickname() user_key = hashlib.md5(user.nickname() + date.today().strftime('%Y-%m-%d') + oa.salt).hexdigest() key = base64.b64encode(user_key + user_name) if oa.loginurl: self.redirect(oa.loginurl % key) class Logout(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if oa: self.redirect(users.create_logout_url(oa.logouturl)) def main(): Route([ ('/oldauth', Login), ('/oldauth_exit', Logout), ]) if __name__ == '__main__': main()
import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if not oa: oa = OldAuth() oa.site = site oa.put() user_name = user.nickname() user_key = hashlib.md5(user.nickname() + date.today().strftime('%Y-%m-%d') + oa.salt).hexdigest() key = base64.b64encode(user_key + user_name) if oa.loginurl: self.redirect(oa.loginurl % key) class Logout(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if oa: self.redirect(users.create_logout_url(oa.logouturl)) def main(): Route([ ('/oldauth', Login), ('/oldauth_exit', Logout), ]) if __name__ == '__main__': main()
Fix crash with empty array
package handlers import ( "io" "encoding/json" "strings" "strconv" "math/rand" "time" "github.com/nelsonleduc/calmanbot/handlers/models" ) func ParseJSON(bytes []byte, path string) string { var stuff interface{} json.Unmarshal(bytes, &stuff) elements := strings.Split(path, ".") for _, el := range elements { converted := ConvertedComponent(el, stuff) num, err := strconv.ParseInt(converted, 10, 64) if err == nil { if num < 0 { stuff = "" break } arr := stuff.([]interface{}) stuff = arr[num] } else { switch t := stuff.(type) { case map[string]interface{}: stuff = t[converted] default: stuff = "" break } } } return stuff.(string) } func ParseMessageJSON(reader io.Reader) models.Message { message := new(models.Message) json.NewDecoder(reader).Decode(message) return *message } func ConvertedComponent(s string, stuff interface{}) string { if s == "{_randomInt_}" { switch t := stuff.(type) { case []interface{}: length := len(t) var num int if length > 0 { rand.Seed(time.Now().UnixNano()) num = rand.Intn(length) } else { num = -1 } return strconv.Itoa(num) default: return s } } return s }
package handlers import ( "io" "encoding/json" "strings" "strconv" "math/rand" "time" "github.com/nelsonleduc/calmanbot/handlers/models" ) func ParseJSON(bytes []byte, path string) string { var stuff interface{} json.Unmarshal(bytes, &stuff) elements := strings.Split(path, ".") for _, el := range elements { converted := ConvertedComponent(el, stuff) num, err := strconv.ParseInt(converted, 10, 64) if err == nil { arr := stuff.([]interface{}) stuff = arr[num] } else { switch t := stuff.(type) { case map[string]interface{}: stuff = t[converted] default: stuff = "" break } } } return stuff.(string) } func ParseMessageJSON(reader io.Reader) models.Message { message := new(models.Message) json.NewDecoder(reader).Decode(message) return *message } func ConvertedComponent(s string, stuff interface{}) string { if s == "{_randomInt_}" { switch t := stuff.(type) { case []interface{}: rand.Seed(time.Now().UnixNano()) num := rand.Intn(len(t)) return strconv.Itoa(num) default: return s } } return s }
Fix small style issue w/ assertEqual vs assertEquals
""" SoftLayer.tests.managers.object_storage_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ import SoftLayer from SoftLayer import fixtures from SoftLayer import testing class ObjectStorageTests(testing.TestCase): def set_up(self): self.object_storage = SoftLayer.ObjectStorageManager(self.client) def test_list_accounts(self): accounts = self.object_storage.list_accounts() self.assertEqual(accounts, fixtures.SoftLayer_Account.getHubNetworkStorage) def test_list_endpoints(self): accounts = self.set_mock('SoftLayer_Account', 'getHubNetworkStorage') accounts.return_value = { 'storageNodes': [{ 'datacenter': {'name': 'dal05'}, 'frontendIpAddress': 'https://dal05/auth/v1.0/', 'backendIpAddress': 'https://dal05/auth/v1.0/'} ], } endpoints = self.object_storage.list_endpoints() self.assertEqual(endpoints, [{'datacenter': {'name': 'dal05'}, 'private': 'https://dal05/auth/v1.0/', 'public': 'https://dal05/auth/v1.0/'}])
""" SoftLayer.tests.managers.object_storage_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ import SoftLayer from SoftLayer import fixtures from SoftLayer import testing class ObjectStorageTests(testing.TestCase): def set_up(self): self.object_storage = SoftLayer.ObjectStorageManager(self.client) def test_list_accounts(self): accounts = self.object_storage.list_accounts() self.assertEquals(accounts, fixtures.SoftLayer_Account.getHubNetworkStorage) def test_list_endpoints(self): accounts = self.set_mock('SoftLayer_Account', 'getHubNetworkStorage') accounts.return_value = { 'storageNodes': [{ 'datacenter': {'name': 'dal05'}, 'frontendIpAddress': 'https://dal05/auth/v1.0/', 'backendIpAddress': 'https://dal05/auth/v1.0/'} ], } endpoints = self.object_storage.list_endpoints() self.assertEquals(endpoints, [{'datacenter': {'name': 'dal05'}, 'private': 'https://dal05/auth/v1.0/', 'public': 'https://dal05/auth/v1.0/'}])
Remove broken reference to the 'add-module-exports' Babel plugin.
var path = require('path'); module.exports = { entry: path.resolve('./src/script/index.js'), devtool: 'eval', resolve: { extensions: ['.js', '.jsx', '.less', '.json'], alias: { 'react': path.resolve('./node_modules/react'), 'eth-lightwallet': path.resolve('./node_modules/eth-lightwallet/dist/lightwallet.min.js'), }, }, watchOptions: { poll: 5000, ignored: /node_modules/, }, module : { loaders : [ { test : /\.(js|jsx)$/, loader : 'babel', exclude: /node_modules/, query: { presets : ['es2015', 'react'], }, }, { test: /\.less$/, loader: 'style!css!less', }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.(ttf|eot|svg|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9]|\?[0-9a-z#]+)?$/, loader: 'file-loader', }, ], }, output: { path: path.resolve('./public/build'), publicPath: '/build/', filename: 'app.js', }, }
var path = require('path'); module.exports = { entry: path.resolve('./src/script/index.js'), devtool: 'eval', resolve: { extensions: ['.js', '.jsx', '.less', '.json'], alias: { 'react': path.resolve('./node_modules/react'), 'eth-lightwallet': path.resolve('./node_modules/eth-lightwallet/dist/lightwallet.min.js'), }, }, watchOptions: { poll: 5000, ignored: /node_modules/, }, module : { loaders : [ { test : /\.(js|jsx)$/, loader : 'babel', exclude: /node_modules/, query: { presets : ['es2015', 'react'], plugins: ['add-module-exports'], }, }, { test: /\.less$/, loader: 'style!css!less', }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.(ttf|eot|svg|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9]|\?[0-9a-z#]+)?$/, loader: 'file-loader', }, ], }, output: { path: path.resolve('./public/build'), publicPath: '/build/', filename: 'app.js', }, }
Fix url for default user image
define('app/views/user_menu', ['app/views/templated', 'md5'], /** * User Menu View * * @returns Class */ function (TemplatedView) { 'user strict'; return TemplatedView.extend({ /** * Properties */ isNotCore: !IS_CORE, accountUrl: URL_PREFIX + '/account', gravatarURL: EMAIL && ('https://www.gravatar.com/avatar/' + md5(EMAIL) + '?d=' + encodeURIComponent('https://mist.io/resources/images/sprite-images/user.png') +'&s=36'), /** * * Actions * */ actions: { meClicked: function(){ $('#user-menu-popup').popup('open'); }, loginClicked: function() { $('#user-menu-popup').popup('close'); Ember.run.later(function() { Mist.loginController.open(); }, 300); }, logoutClicked: function() { Mist.loginController.logout(); } } }); } );
define('app/views/user_menu', ['app/views/templated', 'md5'], /** * User Menu View * * @returns Class */ function (TemplatedView) { 'user strict'; return TemplatedView.extend({ /** * Properties */ isNotCore: !IS_CORE, accountUrl: URL_PREFIX + '/account', //TODO: change the logo_splash.png to user.png gravatarURL: EMAIL && ('https://www.gravatar.com/avatar/' + md5(EMAIL) + '?d=' + encodeURIComponent('https://mist.io/resources/images/user.png') +'&s=36'), /** * * Actions * */ actions: { meClicked: function(){ $('#user-menu-popup').popup('open'); }, loginClicked: function() { $('#user-menu-popup').popup('close'); Ember.run.later(function() { Mist.loginController.open(); }, 300); }, logoutClicked: function() { Mist.loginController.logout(); } } }); } );
Remove imgur duplicates based on ID.
#!/usr/bin/env python3 """ "imgur-album-downloader" is great, but it seems to download albums twice, and appends their stupid ID to the end. This script fixes both. """ import re import os import sys IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)-(\w+)\.([A-Za-z0-9]+)') if __name__ == '__main__': if len(sys.argv) >= 2: os.chdir(sys.argv[1]) ids = {} for fn in os.listdir('.'): match = IMGUR_FILENAME_REGEX.match(fn) if match is None: continue new_fn = f'{match[1]}.{match[3]}' if fn == new_fn: continue print(f"Renaming '{fn}' to '{new_fn}'") os.rename(fn, new_fn) id = match[2] files = ids.get(id, []) files.append(new_fn) ids[id] = files for _, files in ids.items(): if len(files) > 1: files_quoted = ', '.join(f"'{fn}'" for fn in files) print(f"Found duplicates: {files_quoted}") files.sort() for fn in files[1:]: print(f"Removing {fn}") os.remove(fn)
#!/usr/bin/env python3 """ "imgur-album-downloader" is great, but it seems to download albums twice, and appends their stupid ID to the end. This script fixes both. """ import hashlib import re import os import sys IMGUR_FILENAME_REGEX = re.compile(r'([0-9]+)(?:-\w+)?\.([A-Za-z0-9]+)') def get_hash(fn): with open(fn, 'rb') as fh: hashsum = hashlib.md5(fh.read()).digest() return hashsum if __name__ == '__main__': if len(sys.argv) >= 2: os.chdir(sys.argv[1]) sums = {} for fn in os.listdir('.'): match = IMGUR_FILENAME_REGEX.match(fn) if match is None: continue new_fn = f'{match.group(1)}.{match.group(2)}' if fn == new_fn: continue print(f"Renaming '{fn}' to '{new_fn}'") os.rename(fn, new_fn) hashsum = get_hash(new_fn) files = sums.get(hashsum, []) files.append(new_fn) sums[hashsum] = files for hashsum, files in sums.items(): if len(files) > 1: files_quoted = [f"'{x}'" for x in files] print(f"Found duplicates: {', '.join(files_quoted)}") files.sort() for fn in files[1:]: os.remove(fn)
Move getting the event loop out of try/except
import logging from argparse import ArgumentParser import asyncio from .protocol import connect_inotify logger = logging.getLogger(__name__) def main(): parser = ArgumentParser() parser.add_argument( '-ll', '--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], default='WARNING') parser.add_argument('paths', nargs='+', help='File path(s) to watch for file system events') args = parser.parse_args() logging.basicConfig(level=getattr(logging, args.log_level)) loop = asyncio.get_event_loop() try: _, inotify = loop.run_until_complete(connect_inotify()) @asyncio.coroutine def run(inotify): @asyncio.coroutine def callback(event): print(event) for path in args.paths: watch = yield from inotify.watch(callback, path, all_events=True) logger.debug('Added watch %s for all events in %s', watch.watch_descriptor, path) yield from inotify.close_event.wait() try: loop.run_until_complete(run(inotify)) except KeyboardInterrupt: inotify.close() loop.run_until_complete(inotify.close_event.wait()) finally: loop.close() if __name__ == '__main__': main()
import logging from argparse import ArgumentParser import asyncio from .protocol import connect_inotify logger = logging.getLogger(__name__) def main(): parser = ArgumentParser() parser.add_argument( '-ll', '--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], default='WARNING') parser.add_argument('paths', nargs='+', help='File path(s) to watch for file system events') args = parser.parse_args() logging.basicConfig(level=getattr(logging, args.log_level)) try: loop = asyncio.get_event_loop() _, inotify = loop.run_until_complete(connect_inotify()) @asyncio.coroutine def run(inotify): @asyncio.coroutine def callback(event): print(event) for path in args.paths: watch = yield from inotify.watch(callback, path, all_events=True) logger.debug('Added watch %s for all events in %s', watch.watch_descriptor, path) yield from inotify.close_event.wait() try: loop.run_until_complete(run(inotify)) except KeyboardInterrupt: inotify.close() loop.run_until_complete(inotify.close_event.wait()) finally: loop.close() if __name__ == '__main__': main()
Allow variables at root level for yaml definitions. git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1062 3942dd89-8c5d-46d7-aeed-044bccf3e60c
import logging from flexget.manager import Session from flexget.plugin import * log = logging.getLogger('change') class ChangeWarn: """ Gives warning if user has deprecated / changed configuration in the root level. Will be replaced by root level validation in the future! """ def old_database(self, feed, reason=''): log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason) feed.manager.disable_feeds() feed.abort() def on_process_start(self, feed): config = feed.manager.config # prevent useless keywords in root level allow = ['feeds', 'presets', 'variables'] for key in config.iterkeys(): if key not in allow: log.critical('Keyword \'%s\' is not allowed in the root level!' % key) session = Session() # database changes from flexget.utils.sqlalchemy_utils import table_columns, table_exists columns = table_columns('imdb_movies', session) if not 'photo' in columns: self.old_database(feed, '(photo missing from imdb_movies table)') columns = table_columns('make_rss', session) if not 'rsslink' in columns: self.old_database(feed, '(rsslink missing from make_rss table)') if table_exists('episode_qualities', session): self.old_database(feed, '(old series format)') session.close() register_plugin(ChangeWarn, 'change_warn', builtin=True)
import logging from flexget.manager import Session from flexget.plugin import * log = logging.getLogger('change') class ChangeWarn: """ Gives warning if user has deprecated / changed configuration in the root level. Will be replaced by root level validation in the future! """ def old_database(self, feed, reason=''): log.critical('You\'re running old database! Please see bleeding edge news for necessary actions! %s' % reason) feed.manager.disable_feeds() feed.abort() def on_process_start(self, feed): config = feed.manager.config # prevent useless keywords in root level allow = ['feeds', 'presets'] for key in config.iterkeys(): if key not in allow: log.critical('Keyword \'%s\' is not allowed in the root level!' % key) session = Session() # database changes from flexget.utils.sqlalchemy_utils import table_columns, table_exists columns = table_columns('imdb_movies', session) if not 'photo' in columns: self.old_database(feed, '(photo missing from imdb_movies table)') columns = table_columns('make_rss', session) if not 'rsslink' in columns: self.old_database(feed, '(rsslink missing from make_rss table)') if table_exists('episode_qualities', session): self.old_database(feed, '(old series format)') session.close() register_plugin(ChangeWarn, 'change_warn', builtin=True)
Use a hamburger icon instead of back icon
/* @flow */ "use strict"; import ViewController from "$LIB/ViewController"; import {createMenuView} from "$VIEWS/MenuView"; import navigationBar from "$WIDGETS/bars/navigation"; import widgetGroup from "$WIDGETS/group"; import glyph from "$WIDGETS/glyph"; import GCS from "$LIB/grandCentralStation"; import L from "$APP/localization/localization"; import h from "yasmf-h"; export default class MenuViewController extends ViewController { constructor({model} = {}) { super({title: "Menu", model, view: createMenuView()}); } get TARGET_SELECTORS() { return [ {selector: "tap:.menu-icon", emit: "menuTapped"} ]; } onMenuTapped() { GCS.emit("APP:DO:menu"); } template() { return h.el("main.MenuViewController y-container?is=menu-view-controller", [ navigationBar({contents:[ widgetGroup({contents:[ glyph({icon:"menu", contents: L.T("icon:menu"), title: L.T("general:tap-to-hide-the-sidebar")}) ]}), widgetGroup({contents:[ h.el("h1?is=y-title", L.T("app:menu-title")) ], flex: true}) ]}), this.renderSubviews() ]); } } export function createMenuViewController(options={}) { return new MenuViewController(options); }
/* @flow */ "use strict"; import ViewController from "$LIB/ViewController"; import {createMenuView} from "$VIEWS/MenuView"; import navigationBar from "$WIDGETS/bars/navigation"; import widgetGroup from "$WIDGETS/group"; import glyph from "$WIDGETS/glyph"; import GCS from "$LIB/grandCentralStation"; import L from "$APP/localization/localization"; import h from "yasmf-h"; export default class MenuViewController extends ViewController { constructor({model} = {}) { super({title: "Menu", model, view: createMenuView()}); } get TARGET_SELECTORS() { return [ {selector: "tap:.back-icon", emit: "menuTapped"} ]; } onMenuTapped() { GCS.emit("APP:DO:menu"); } template() { return h.el("main.MenuViewController y-container?is=menu-view-controller", [ navigationBar({contents:[ widgetGroup({contents:[ glyph({icon:"back", contents: L.T("icon:back"), title: L.T("general:tap-to-hide-the-sidebar")}) ]}), widgetGroup({contents:[ h.el("h1?is=y-title", L.T("app:menu-title")) ], flex: true}) ]}), this.renderSubviews() ]); } } export function createMenuViewController(...args) { return new MenuViewController(...args); }
Use promise chaining during registration
(function (angular) { 'use strict'; angular .module('movieClub.auth') .factory('authApi', authApi); function authApi($firebaseAuth, usersApi, firebaseRef) { var factory = { login: login, logout: logout, onAuth: onAuth, register: register }, authRef = $firebaseAuth(firebaseRef); return factory; function login(email, password) { return authRef.$authWithPassword({email: email, password: password}); } function logout() { authRef.$unauth(); } function register(username, email, password) { return authRef.$createUser({email: email, password: password}) .then(_.partial(login, email, password)) .then(_.partialRight(addUsername, username)); } function onAuth(func) { return authRef.$onAuth(func); } function addUsername(auth, username) { var user = usersApi.getById(auth.uid); user.username = username; user.$save(); return user.$loaded(); } } }(window.angular));
(function (angular) { 'use strict'; angular .module('movieClub.auth') .factory('authApi', authApi); function authApi($firebaseAuth, usersApi, firebaseRef) { var factory = { login: login, logout: logout, onAuth: onAuth, register: register }, authRef = $firebaseAuth(firebaseRef); return factory; function login(email, password) { var credentials = { email: email, password: password }; return authRef.$authWithPassword(credentials); } function logout() { authRef.$unauth(); } function onAuth(func) { return authRef.$onAuth(func); } function register(username, email, password) { var credentials = { email: email, password: password }; return authRef.$createUser(credentials) .then(function () { return login(email, password) .then(function (auth) { var user = usersApi.getById(auth.uid); user.username = username; user.$save(); return user.$loaded(); }); }); } } }(window.angular));
Fix outer script access to request, response property
<?php namespace Karen; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; class Controller { public $request; public $response; protected $queue = []; public function __construct(Request $request, Response $response) { $this->request = $request; $this->response = $response; } public function render(string $output) { $this->response->getBody()->write($output); return $this->response; } public static function sendResponse(Response $response) { header(sprintf( 'HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase() )); foreach ($response->getHeaders() as $name => $values) { foreach ($values as $value) { header(sprintf('%s: %s', $name, $value), false); } } if (!in_array($response->getStatusCode(), [204, 205, 304])) { echo $response->getBody(); } } public function addQueue(string $name, callable $queue) { $this->queue[$name] = $queue; } public function getQueue() { return $this->queue; } /** * get routing action queue of Middleware interface */ public function actionQueue(callable $callable, array $args) { return function (Request $request, Response $response) use ($callable, $args){ return call_user_func($callable, $args, $this); }; } }
<?php namespace Karen; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; class Controller { protected $request; protected $response; protected $queue = []; public function __construct(Request $request, Response $response) { $this->request = $request; $this->response = $response; } public function render(string $output) { $this->response->getBody()->write($output); return $this->response; } public static function sendResponse(Response $response) { header(sprintf( 'HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase() )); foreach ($response->getHeaders() as $name => $values) { foreach ($values as $value) { header(sprintf('%s: %s', $name, $value), false); } } if (!in_array($response->getStatusCode(), [204, 205, 304])) { echo $response->getBody(); } } public function addQueue(string $name, callable $queue) { $this->queue[$name] = $queue; } public function getQueue() { return $this->queue; } /** * get routing action queue of Middleware interface */ public function actionQueue(callable $callable, array $args) { return function (Request $request, Response $response) use ($callable, $args){ return call_user_func($callable, $args, $this); }; } }
Fix infinite loop for filter
<?php namespace Romans\Filter; use Romans\Grammar\Grammar; use Romans\Grammar\GrammarAwareTrait; /** * Int to Roman */ class IntToRoman { use GrammarAwareTrait; /** * Default Constructor * * @param Grammar $grammar Grammar Object */ public function __construct(Grammar $grammar = null) { if (! isset($grammar)) { $grammar = new Grammar(); } $this->setGrammar($grammar); } /** * Filter Integer to Roman Number * * @param int Integer * @return string Roman Number Result */ public function filter(int $value) : string { if ($value <= 0) { throw new Exception(sprintf('Invalid integer: %d', $value)); } $tokens = $this->getGrammar()->getTokens(); $values = array_reverse($this->getGrammar()->getValues()); $result = ''; foreach ($values as $token => $current) { while ($current > 0 && $value >= $current) { $value = $value - $current; $result = $result . $tokens[$token]; } } return $result; } }
<?php namespace Romans\Filter; use Romans\Grammar\Grammar; use Romans\Grammar\GrammarAwareTrait; /** * Int to Roman */ class IntToRoman { use GrammarAwareTrait; /** * Default Constructor * * @param Grammar $grammar Grammar Object */ public function __construct(Grammar $grammar = null) { if (! isset($grammar)) { $grammar = new Grammar(); } $this->setGrammar($grammar); } /** * Filter Integer to Roman Number * * @param int Integer * @return string Roman Number Result */ public function filter(int $value) : string { if ($value <= 0) { throw new Exception(sprintf('Invalid integer: %d', $value)); } $tokens = $this->getGrammar()->getTokens(); $values = array_reverse($this->getGrammar()->getValues()); $result = ''; foreach ($values as $token => $current) { while ($value >= $current) { $value = $value - $current; $result = $result . $tokens[$token]; } } return $result; } }
Add option for source maps, and pass to ng-annotate.
var ngAnnotate = require('ng-annotate'), SourceMapSource = require('webpack-core/lib/SourceMapSource'); function ngAnnotatePlugin(options) { this.options = options || { add: true, sourceMap: false }; } ngAnnotatePlugin.prototype.apply = function apply(compiler) { var options = this.options; compiler.plugin('compilation', function(compilation) { compilation.plugin('optimize-chunk-assets', function(chunks, callback) { var files = []; function getFilesFromChunk(chunk) { files = files.concat(chunk.files); } function annotateFile(file) { if (options.sourceMap) { options.map = { inFile: file, sourceRoot: "" }; } var value = ngAnnotate(compilation.assets[file].source(), options); var asset = compilation.assets[file]; if (options.sourceMap && asset.sourceAndMap) { var sourceAndMap = asset.sourceAndMap(); var map = sourceAndMap.map; var input = sourceAndMap.source; } else { map = asset.map(); } if (!value.errors) { if (options.sourceMap) { compilation.assets[file] = new SourceMapSource(value.src, file, JSON.parse(value.map), input, map); } else { compilation.assets[file] = new SourceMapSource(value.src, file, map); } } } chunks.forEach(getFilesFromChunk); files = files.concat(compilation.additionalChunkAssets); files.forEach(annotateFile); callback(); }); }); }; module.exports = ngAnnotatePlugin;
var ngAnnotate = require('ng-annotate'), SourceMapSource = require('webpack-core/lib/SourceMapSource'); function ngAnnotatePlugin(options) { this.options = options || { add: true }; } ngAnnotatePlugin.prototype.apply = function apply(compiler) { var options = this.options; compiler.plugin('compilation', function(compilation) { compilation.plugin('optimize-chunk-assets', function(chunks, callback) { var files = []; function getFilesFromChunk(chunk) { files = files.concat(chunk.files); } function annotateFile(file) { var map = compilation.assets[file].map(), value = ngAnnotate(compilation.assets[file].source(), options); if (!value.errors) { compilation.assets[file] = new SourceMapSource(value.src, file, map); } } chunks.forEach(getFilesFromChunk); files = files.concat(compilation.additionalChunkAssets); files.forEach(annotateFile); callback(); }); }); }; module.exports = ngAnnotatePlugin;
Add control for number of spaces in JSON output.
function Category(name) { this.category = name; this.features = []; } Category.prototype.addFeature = function(name) { this.features.push({"name": name, "support": []}); } if (process.argv.length < 3) { console.log('Generate JSON representation of the SVG 2 new features Markdown file.'); console.log(`usage: ${process.argv[0]} <inputfile> <json_spaces=4>`); process.exit(1); } else { const fs = require('fs'); const readline = require('readline'); const input_md = process.argv[2]; const json_spaces = process.argv[3] === undefined ? 4 : process.argv[3]|0; const categories = []; let current_category = null; readline.createInterface( {input: fs.createReadStream(input_md, {encoding: 'utf-8'})} ) .on('line', (line) => { // By convention, categories are level 3 headings, and // features are items in a list. Ignore anything else. if (line.startsWith('###')) { const name = /^###\s*(.+?):??\s*$/.exec(line); current_category = new Category(name[1]); categories.push(current_category); } else if ((line.startsWith('*') || line.startsWith('-')) && current_category) { const name = /[*-]\s*(.*)/.exec(line); current_category.addFeature(name[1]); } }) .on('close', () => { console.log(JSON.stringify(categories, null, json_spaces)); }); }
function Category(name) { this.category = name; this.features = []; } Category.prototype.addFeature = function(name) { this.features.push({"name": name, "support": []}); } if (process.argv.length != 3) { console.log('Generate JSON representation of the SVG 2 new features Markdown file.'); console.log(`usage: ${process.argv[0]} <inputfile>`); process.exit(1); } else { const fs = require('fs'); const readline = require('readline'); const input_md = process.argv[2]; const categories = []; let current_category = null; readline.createInterface( {input: fs.createReadStream(input_md, {encoding: 'utf-8'})} ) .on('line', (line) => { // By convention, categories are level 3 headings, and // features are items in a list. Ignore anything else. if (line.startsWith('###')) { const name = /^###\s*(.+?):??\s*$/.exec(line); current_category = new Category(name[1]); categories.push(current_category); } else if ((line.startsWith('*') || line.startsWith('-')) && current_category) { const name = /[*-]\s*(.*)/.exec(line); current_category.addFeature(name[1]); } }) .on('close', () => { console.log(JSON.stringify(categories, null, 4)); }); }
Make doctrine executor do left-joins by default
<?php namespace RulerZ\Executor\DoctrineORM; use RulerZ\Context\ExecutionContext; use RulerZ\Result\IteratorTools; trait FilterTrait { abstract protected function execute($target, array $operators, array $parameters); /** * {@inheritDoc} */ public function applyFilter($target, array $parameters, array $operators, ExecutionContext $context) { /** @var \Doctrine\ORM\QueryBuilder $target */ foreach ($this->detectedJoins as $join) { $target->leftJoin(sprintf('%s.%s', $join['root'], $join['column']), $join['as']); } // this will return DQL code $dql = $this->execute($target, $operators, $parameters); // so we apply it to the query builder $target->andWhere($dql); // now we define the parameters foreach ($parameters as $name => $value) { $target->setParameter($name, $value); } return $target; } /** * {@inheritDoc} */ public function filter($target, array $parameters, array $operators, ExecutionContext $context) { /** @var \Doctrine\ORM\QueryBuilder $target */ $this->applyFilter($target, $parameters, $operators, $context); // execute the query $result = $target->getQuery()->getResult(); // and return the appropriate result type if ($result instanceof \Traversable) { return $result; } else if (is_array($result)) { return IteratorTools::fromArray($result); } throw new \RuntimeException(sprintf('Unhandled result type: "%s"', get_class($result))); } }
<?php namespace RulerZ\Executor\DoctrineORM; use RulerZ\Context\ExecutionContext; use RulerZ\Result\IteratorTools; trait FilterTrait { abstract protected function execute($target, array $operators, array $parameters); /** * {@inheritDoc} */ public function applyFilter($target, array $parameters, array $operators, ExecutionContext $context) { /** @var \Doctrine\ORM\QueryBuilder $target */ foreach ($this->detectedJoins as $join) { $target->join(sprintf('%s.%s', $join['root'], $join['column']), $join['as']); } // this will return DQL code $dql = $this->execute($target, $operators, $parameters); // so we apply it to the query builder $target->andWhere($dql); // now we define the parameters foreach ($parameters as $name => $value) { $target->setParameter($name, $value); } return $target; } /** * {@inheritDoc} */ public function filter($target, array $parameters, array $operators, ExecutionContext $context) { /** @var \Doctrine\ORM\QueryBuilder $target */ $this->applyFilter($target, $parameters, $operators, $context); // execute the query $result = $target->getQuery()->getResult(); // and return the appropriate result type if ($result instanceof \Traversable) { return $result; } else if (is_array($result)) { return IteratorTools::fromArray($result); } throw new \RuntimeException(sprintf('Unhandled result type: "%s"', get_class($result))); } }
Add failing test for formatting
# -*- coding: utf-8 -*- import click def test_basic_functionality(runner): @click.command() def cli(): """First paragraph. This is a very long second paragraph and not correctly wrapped but it will be rewrapped. \b This is a paragraph without rewrapping. \b 1 2 3 And this is a paragraph that will be rewrapped again. """ result = runner.invoke(cli, ['--help'], terminal_width=60) assert not result.exception assert result.output.splitlines() == [ 'Usage: cli [OPTIONS]', '', ' First paragraph.', '', ' This is a very long second paragraph and not correctly', ' wrapped but it will be rewrapped.', '', ' This is', ' a paragraph', ' without rewrapping.', '', ' 1', ' 2', ' 3', '', ' And this is a paragraph that will be rewrapped again.', '', 'Options:', ' --help Show this message and exit.', ] def test_wrapping_long_options_strings(runner): @click.group() def cli(): """Top level command """ @cli.group() def a_very_long(): """Second level """ @a_very_long.command() @click.argument('first') @click.argument('second') @click.argument('third') @click.argument('fourth') def command(): """A command. """ result = runner.invoke(cli, ['a_very_long', 'command', '--help'], terminal_width=54) assert not result.exception assert result.output.splitlines() == [ 'Usage: cli a_very_long command [OPTIONS] FIRST SECOND', ' THIRD FOURTH', '', ' A command.', '', 'Options:', ' --help Show this message and exit.', ]
# -*- coding: utf-8 -*- import click def test_basic_functionality(runner): @click.command() def cli(): """First paragraph. This is a very long second paragraph and not correctly wrapped but it will be rewrapped. \b This is a paragraph without rewrapping. \b 1 2 3 And this is a paragraph that will be rewrapped again. """ result = runner.invoke(cli, ['--help'], terminal_width=60) assert not result.exception assert result.output.splitlines() == [ 'Usage: cli [OPTIONS]', '', ' First paragraph.', '', ' This is a very long second paragraph and not correctly', ' wrapped but it will be rewrapped.', '', ' This is', ' a paragraph', ' without rewrapping.', '', ' 1', ' 2', ' 3', '', ' And this is a paragraph that will be rewrapped again.', '', 'Options:', ' --help Show this message and exit.', ]
Define The Default Grunt Task
module.exports = function(grunt) { grunt.initConfig({ jshint: { all: ['src/**/*.js', 'test/**/*.js'], options: { globals: { _: false, $: false, jasmine: false, describe: false, it: false, expect: false, beforeEach: false, afterEach: false, sinon: false }, browser: true, devel: true } }, testem: { unit: { options: { framework: 'jasmine2', launch_in_dev: ['PhantomJS'], before_tests: 'grunt jshint', serve_files: [ 'node_modules/lodash/index.js', 'node_modules/jquery/dist/jquery.js', 'node_modules/sinon/pkg/sinon.js', 'src/**/*.js', 'test/**/*.js' ], watch_files: [ 'src/**/*.js', 'test/**/*.js' ] } } }, watch: { all: { files: ['src/**/*.js', 'test/**/*.js'], tasks: ['jshint'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-testem'); grunt.registerTask('default', ['testem:run:unit']); };
module.exports = function(grunt) { grunt.initConfig({ jshint: { all: ['src/**/*.js', 'test/**/*.js'], options: { globals: { _: false, $: false, jasmine: false, describe: false, it: false, expect: false, beforeEach: false, afterEach: false, sinon: false }, browser: true, devel: true } }, testem: { unit: { options: { framework: 'jasmine2', launch_in_dev: ['PhantomJS'], before_tests: 'grunt jshint', serve_files: [ 'node_modules/lodash/index.js', 'node_modules/jquery/dist/jquery.js', 'node_modules/sinon/pkg/sinon.js', 'src/**/*.js', 'test/**/*.js' ], watch_files: [ 'src/**/*.js', 'test/**/*.js' ] } } }, watch: { all: { files: ['src/**/*.js', 'test/**/*.js'], tasks: ['jshint'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-testem'); };
Add sortkey to create table stmt
package org.bricolages.streaming.preflight; import java.util.StringJoiner; import lombok.*; class CreateTableGenerator { private StreamDefinitionEntry streamDef; CreateTableGenerator(StreamDefinitionEntry streamDef) { this.streamDef = streamDef; } String generate() { val sb = new StringBuilder(); sb.append("--dest-table: "); sb.append(streamDef.getFullTableName()); sb.append("\n\n"); sb.append("create table $dest_table \n("); generateColumnDefinitionList(sb); sb.append("\n)\n"); sb.append("sortkey(jst_time)\n"); sb.append(";\n"); return sb.toString(); } void generateColumnDefinitionList(StringBuilder sb) { val sj = new StringJoiner("\n,"); for (val columnDef: streamDef.getColumns()) { sj.add(generateColumnDefinition(columnDef)); } sb.append(sj.toString()); } String generateColumnDefinition(ColumnDefinitionEntry columnDef) { val sj = new StringJoiner(" ", " ", ""); sj.add(columnDef.getColumName()); sj.add(columnDef.getParams().getType()); sj.add("encode"); sj.add(columnDef.getParams().getEncoding().toString()); return sj.toString(); } }
package org.bricolages.streaming.preflight; import java.util.StringJoiner; import lombok.*; class CreateTableGenerator { private StreamDefinitionEntry streamDef; CreateTableGenerator(StreamDefinitionEntry streamDef) { this.streamDef = streamDef; } String generate() { val sb = new StringBuilder(); sb.append("--dest-table: "); sb.append(streamDef.getFullTableName()); sb.append("\n\n"); sb.append("create table $dest_table \n("); generateColumnDefinitionList(sb); sb.append("\n)\n;\n"); return sb.toString(); } void generateColumnDefinitionList(StringBuilder sb) { val sj = new StringJoiner("\n,"); for (val columnDef: streamDef.getColumns()) { sj.add(generateColumnDefinition(columnDef)); } sb.append(sj.toString()); } String generateColumnDefinition(ColumnDefinitionEntry columnDef) { val sj = new StringJoiner(" ", " ", ""); sj.add(columnDef.getColumName()); sj.add(columnDef.getParams().getType()); sj.add("encode"); sj.add(columnDef.getParams().getEncoding().toString()); return sj.toString(); } }
Add SessionStore to Session Facade Because of changes to the session facade. Fixes #37
<?php return array( /* |-------------------------------------------------------------------------- | Filename |-------------------------------------------------------------------------- | | The default path to the helper file | */ 'filename' => '_ide_helper.php', /* |-------------------------------------------------------------------------- | Helper files to include |-------------------------------------------------------------------------- | | Include helper files. By default not included, but can be toggled with the | -- helpers (-H) option. Extra helper files can be included. | */ 'include_helpers' => false, 'helper_files' => array( base_path().'/vendor/laravel/framework/src/Illuminate/Support/helpers.php', ), /* |-------------------------------------------------------------------------- | Extra classes |-------------------------------------------------------------------------- | | These implementations are not really extended, but called with magic functions | */ 'extra' => array( 'Eloquent' => array('Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'), 'Session' => array('Illuminate\Session\Store'), ), 'magic' => array( 'Log' => array( 'debug' => 'Monolog\Logger::addDebug', 'info' => 'Monolog\Logger::addInfo', 'notice' => 'Monolog\Logger::addNotice', 'warning' => 'Monolog\Logger::addWarning', 'error' => 'Monolog\Logger::addError', 'critical' => 'Monolog\Logger::addCritical', 'alert' => 'Monolog\Logger::addAlert', 'emergency' => 'Monolog\Logger::addEmergency', ) ) );
<?php return array( /* |-------------------------------------------------------------------------- | Filename |-------------------------------------------------------------------------- | | The default path to the helper file | */ 'filename' => '_ide_helper.php', /* |-------------------------------------------------------------------------- | Helper files to include |-------------------------------------------------------------------------- | | Include helper files. By default not included, but can be toggled with the | -- helpers (-H) option. Extra helper files can be included. | */ 'include_helpers' => false, 'helper_files' => array( base_path().'/vendor/laravel/framework/src/Illuminate/Support/helpers.php', ), /* |-------------------------------------------------------------------------- | Extra classes |-------------------------------------------------------------------------- | | These implementations are not really extended, but called with magic functions | */ 'extra' => array( 'Eloquent' => array('Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'), ), 'magic' => array( 'Log' => array( 'debug' => 'Monolog\Logger::addDebug', 'info' => 'Monolog\Logger::addInfo', 'notice' => 'Monolog\Logger::addNotice', 'warning' => 'Monolog\Logger::addWarning', 'error' => 'Monolog\Logger::addError', 'critical' => 'Monolog\Logger::addCritical', 'alert' => 'Monolog\Logger::addAlert', 'emergency' => 'Monolog\Logger::addEmergency', ) ) );
Add negative positioning to hidden file input
<?php namespace App\Form\Field; class File extends \AzuraForms\Field\File { public function configure(array $config = []): void { parent::configure($config); $this->options['button_text'] = $this->attributes['button_text'] ?? __('Select File'); $this->options['button_icon'] = $this->attributes['button_icon'] ?? null; } public function getField($form_name): ?string { list($attribute_string, $class) = $this->_attributeString(); $button_text = $this->options['button_text']; if ($this->options['button_icon'] !== null) { $button_text .= sprintf(' <i class="material-icons" aria-hidden="true">%1$s</i>', $this->options['button_icon']); } $output = '<button name="%1$s_button" id="%2$s_%1$s_button" class="file-upload btn btn-primary btn-block text-center %3$s" type="button">'; $output .= '%4$s'; $output .= '</button>'; $output .= '<small class="file-name"></small>'; $output .= '<input type="file" name="%1$s" id="%2$s_%1$s" style="visibility: hidden; position: absolute; left: -9999px;">'; return sprintf($output, $this->getFullName(), $form_name, $class, $button_text ); } }
<?php namespace App\Form\Field; class File extends \AzuraForms\Field\File { public function configure(array $config = []): void { parent::configure($config); $this->options['button_text'] = $this->attributes['button_text'] ?? __('Select File'); $this->options['button_icon'] = $this->attributes['button_icon'] ?? null; } public function getField($form_name): ?string { list($attribute_string, $class) = $this->_attributeString(); $button_text = $this->options['button_text']; if ($this->options['button_icon'] !== null) { $button_text .= sprintf(' <i class="material-icons" aria-hidden="true">%1$s</i>', $this->options['button_icon']); } $output = '<button name="%1$s_button" id="%2$s_%1$s_button" class="file-upload btn btn-primary btn-block text-center %3$s" type="button">'; $output .= '%4$s'; $output .= '</button>'; $output .= '<small class="file-name"></small>'; $output .= '<input type="file" name="%1$s" id="%2$s_%1$s" style="visibility: hidden; position: absolute;">'; return sprintf($output, $this->getFullName(), $form_name, $class, $button_text ); } }
Add done flag to experiment.
export class ExperimentStep { constructor(title, _type) { this.id = ''; this.title = title; this._type = _type; this.steps = []; this.description = ''; this.flags = { important: false, review: false, error: false, done: false }; this.displayState = { details: { showTitle: true, showStatus: true, showNotes: true, showFiles: false, showSamples: false, currentFilesTab: 0, currentSamplesTab: 0 }, editTitle: true, open: false, maximize: false }; this.node = null; } addStep(step) { this.steps.push(step); } } export class Experiment { constructor(name) { this.name = name; this.goal = ''; this.description = 'Look at grain size as it relates to hardness'; this.aim = ''; this.done = false; this.steps = []; } addStep(title, _type) { let s = new ExperimentStep(title, _type); this.steps.push(s); } }
export class ExperimentStep { constructor(title, _type) { this.id = ''; this.title = title; this._type = _type; this.steps = []; this.description = ''; this.flags = { important: false, review: false, error: false, done: false }; this.displayState = { details: { showTitle: true, showStatus: true, showNotes: true, showFiles: false, showSamples: false, currentFilesTab: 0, currentSamplesTab: 0 }, editTitle: true, open: false, maximize: false }; this.node = null; } addStep(step) { this.steps.push(step); } } export class Experiment { constructor(name) { this.name = name; this.goal = ''; this.description = 'Look at grain size as it relates to hardness'; this.aim = ''; this.steps = []; } addStep(title, _type) { let s = new ExperimentStep(title, _type); this.steps.push(s); } }
Improve metric http client to deal with missing report data list.
package io.sphere.sdk.play.metrics; import io.sphere.sdk.http.HttpClient; import io.sphere.sdk.http.HttpRequest; import io.sphere.sdk.http.HttpResponse; import play.mvc.Http; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionStage; public class MetricHttpClient implements HttpClient { private final HttpClient underlying; private MetricHttpClient(final HttpClient underlying) { this.underlying = underlying; } @Override public CompletionStage<HttpResponse> execute(final HttpRequest httpRequest) { final Optional<Http.Context> contextOptional = Optional.ofNullable(Http.Context.current.get()); final CompletionStage<HttpResponse> result = underlying.execute(httpRequest); final long startTimestamp = System.currentTimeMillis(); contextOptional.ifPresent(context -> result.thenAccept(response -> { final long stopTimestamp = System.currentTimeMillis(); report(context, httpRequest, response, startTimestamp, stopTimestamp); })); return result; } @SuppressWarnings("unchecked") private void report(final Http.Context context, final HttpRequest httpRequest, final HttpResponse response, long startTimestamp, long stopTimestamp) { final Optional<List<ReportRawData>> dataOption = Optional.ofNullable((List<ReportRawData>) context.args.get(MetricAction.KEY)); dataOption.ifPresent(data -> data.add(new ReportRawData(httpRequest, response, startTimestamp, stopTimestamp))); } @Override public void close() { underlying.close(); } public static MetricHttpClient of(final HttpClient underlying) { return new MetricHttpClient(underlying); } }
package io.sphere.sdk.play.metrics; import io.sphere.sdk.http.HttpClient; import io.sphere.sdk.http.HttpRequest; import io.sphere.sdk.http.HttpResponse; import play.mvc.Http; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionStage; public class MetricHttpClient implements HttpClient { private final HttpClient underlying; private MetricHttpClient(final HttpClient underlying) { this.underlying = underlying; } @Override public CompletionStage<HttpResponse> execute(final HttpRequest httpRequest) { final Optional<Http.Context> contextOptional = Optional.ofNullable(Http.Context.current.get()); final CompletionStage<HttpResponse> result = underlying.execute(httpRequest); final long startTimestamp = System.currentTimeMillis(); contextOptional.ifPresent(context -> result.thenAccept(response -> { final long stopTimestamp = System.currentTimeMillis(); report(context, httpRequest, response, startTimestamp, stopTimestamp); })); return result; } @SuppressWarnings("unchecked") private void report(final Http.Context context, final HttpRequest httpRequest, final HttpResponse response, long startTimestamp, long stopTimestamp) { final List<ReportRawData> data = (List<ReportRawData>) context.args.get(MetricAction.KEY); data.add(new ReportRawData(httpRequest, response, startTimestamp, stopTimestamp)); } @Override public void close() { underlying.close(); } public static MetricHttpClient of(final HttpClient underlying) { return new MetricHttpClient(underlying); } }
Allow to overwrite default Laravel parameters
<?php namespace Eusonlito\LaravelPacker; use Illuminate\Support\ServiceProvider; class PackerServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../../config/config.php' => config_path('packer.php') ]); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('packer', function($app) { return new Packer($this->config()); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['packer']; } /** * Get the base settings from config file * * @return array */ public function config() { $config = config('packer'); if (empty($config['environment'])) { $config['environment'] = app()->environment(); } if (empty($config['public_path'])) { $config['public_path'] = public_path(); } if (empty($config['asset'])) { $config['asset'] = asset(''); } return $config; } }
<?php namespace Eusonlito\LaravelPacker; use Illuminate\Support\ServiceProvider; class PackerServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../../config/config.php' => config_path('packer.php') ]); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('packer', function($app) { return new Packer($this->config()); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['packer']; } /** * Get the base settings from config file * * @return array */ public function config() { $config = config('packer'); if (empty($config['environment'])) { $config['environment'] = app()->environment(); } $config['public_path'] = public_path(); $config['asset'] = asset(''); return $config; } }
Update test to use new name of helper for dois
from scrapi.base import helpers class TestHelpers(object): def test_format_one_tag(self): single_tag = ' A single tag ' single_output = helpers.format_tags(single_tag) assert single_output == ['a single tag'] assert isinstance(single_output, list) def test_format_many_tags(self): many_tags = [' A', 'Bunch', ' oftags '] many_output = helpers.format_tags(many_tags) assert set(many_output) == set(['a', 'bunch', 'oftags']) def test_format_sep_tags(self): sep_tags = ['These, we know', 'should be many'] sep_output = helpers.format_tags(sep_tags, sep=',') assert set(sep_output) == set(['these', 'we know', 'should be many']) def test_extract_dois(self): identifiers = 'doi: THIS_IS_A_DOI!' valid_doi = helpers.oai_extract_dois(identifiers) assert valid_doi == 'THIS_IS_A_DOI!' def test_oai_extract_url(self): identifiers = 'I might be a url but rly I am naaaahhttt' extraction_attempt = helpers.oai_extract_url(identifiers) extraction_attempt def test_process_contributors(self): args = ['Stardust Rhodes', 'Golddust Rhodes', 'Dusty Rhodes'] response = helpers.oai_process_contributors(args) assert isinstance(response, list)
from scrapi.base import helpers class TestHelpers(object): def test_format_one_tag(self): single_tag = ' A single tag ' single_output = helpers.format_tags(single_tag) assert single_output == ['a single tag'] assert isinstance(single_output, list) def test_format_many_tags(self): many_tags = [' A', 'Bunch', ' oftags '] many_output = helpers.format_tags(many_tags) assert set(many_output) == set(['a', 'bunch', 'oftags']) def test_format_sep_tags(self): sep_tags = ['These, we know', 'should be many'] sep_output = helpers.format_tags(sep_tags, sep=',') assert set(sep_output) == set(['these', 'we know', 'should be many']) def test_extract_doi(self): identifiers = 'doi: THIS_IS_A_DOI!' valid_doi = helpers.oai_extract_doi(identifiers) assert valid_doi == 'THIS_IS_A_DOI!' def test_oai_extract_url(self): identifiers = 'I might be a url but rly I am naaaahhttt' extraction_attempt = helpers.oai_extract_url(identifiers) extraction_attempt def test_process_contributors(self): args = ['Stardust Rhodes', 'Golddust Rhodes', 'Dusty Rhodes'] response = helpers.oai_process_contributors(args) assert isinstance(response, list)
Remove the need for @Configuration annotation. Simplify!
package org.wildfly.swarm.swagger.runtime; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.Archive; import org.wildfly.swarm.container.JARArchive; import org.wildfly.swarm.container.runtime.AbstractServerConfiguration; import org.wildfly.swarm.jaxrs.JAXRSArchive; import org.wildfly.swarm.swagger.SwaggerFraction; import java.util.Collections; import java.util.List; /** * @author Lance Ball */ public class SwaggerConfiguration extends AbstractServerConfiguration<SwaggerFraction> { public SwaggerConfiguration() { super(SwaggerFraction.class); } @Override public SwaggerFraction defaultFraction() { return new SwaggerFraction(); } @Override public void prepareArchive(Archive<?> a) { JAXRSArchive deployment = a.as(JAXRSArchive.class); JARArchive archive = a.as(JARArchive.class); try { archive.addModule("io.swagger"); deployment.addResource(io.swagger.jaxrs.listing.ApiListingResource.class); deployment.addResource(io.swagger.jaxrs.listing.SwaggerSerializers.class); } catch (Exception e) { e.printStackTrace(); } } @Override public List<ModelNode> getList(SwaggerFraction fraction) throws Exception { return Collections.emptyList(); } }
package org.wildfly.swarm.swagger.runtime; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.Archive; import org.wildfly.swarm.container.JARArchive; import org.wildfly.swarm.container.runtime.AbstractServerConfiguration; import org.wildfly.swarm.container.runtime.Configuration; import org.wildfly.swarm.jaxrs.JAXRSArchive; import org.wildfly.swarm.swagger.SwaggerFraction; import java.util.Collections; import java.util.List; /** * @author Lance Ball */ @Configuration public class SwaggerConfiguration extends AbstractServerConfiguration<SwaggerFraction> { public SwaggerConfiguration() { super(SwaggerFraction.class); } @Override public SwaggerFraction defaultFraction() { return new SwaggerFraction(); } @Override public void prepareArchive(Archive<?> a) { JAXRSArchive deployment = a.as(JAXRSArchive.class); JARArchive archive = a.as(JARArchive.class); try { archive.addModule("io.swagger"); deployment.addResource(io.swagger.jaxrs.listing.ApiListingResource.class); deployment.addResource(io.swagger.jaxrs.listing.SwaggerSerializers.class); } catch (Exception e) { e.printStackTrace(); } } @Override public List<ModelNode> getList(SwaggerFraction fraction) throws Exception { return Collections.emptyList(); } }
Map: Move starting location a little so Wick Sports Ground is visible
(function(){ angular .module('app') .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider.configure({ // key: 'your api key', v: '3.20', //defaults to latest 3.X anyhow libraries: 'weather,geometry,visualization' }); }) .controller('MapController', [ '$state', 'uiGmapGoogleMapApi', 'sitesService', MapController ]); function MapController($state, uiGmapGoogleMapApi, sitesService) { self = this; sitesService .loadAllItems() .then(function(siteData) { self.siteData = [].concat(siteData); console.log(self.siteData); }); uiGmapGoogleMapApi.then(function(maps) { //small hack to fix issues with older lodash version. to be resolved in future if( typeof _.contains === 'undefined' ) { _.contains = _.includes; } if( typeof _.object === 'undefined' ) { _.object = _.zipObject; } self.mapParams = { center: { latitude: 51.48, longitude: -2.53 }, zoom: 12 }; }); self.goToSite = function (shortcode) { $state.go('home.site', {shortcode: shortcode}); }; } })();
(function(){ angular .module('app') .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider.configure({ // key: 'your api key', v: '3.20', //defaults to latest 3.X anyhow libraries: 'weather,geometry,visualization' }); }) .controller('MapController', [ '$state', 'uiGmapGoogleMapApi', 'sitesService', MapController ]); function MapController($state, uiGmapGoogleMapApi, sitesService) { self = this; sitesService .loadAllItems() .then(function(siteData) { self.siteData = [].concat(siteData); console.log(self.siteData); }); uiGmapGoogleMapApi.then(function(maps) { //small hack to fix issues with older lodash version. to be resolved in future if( typeof _.contains === 'undefined' ) { _.contains = _.includes; } if( typeof _.object === 'undefined' ) { _.object = _.zipObject; } self.mapParams = { center: { latitude: 51.48, longitude: -2.5879 }, zoom: 12 }; }); self.goToSite = function (shortcode) { $state.go('home.site', {shortcode: shortcode}); }; } })();
Remove capture group from URL reg exp. You get the whole match anyway. And now you can more easily use the source of the regexp as a part for constructing more complicated regular expressions. e.g. var x = new RegExp( RegExp.url.source + "|" + RegExp.email.source, 'i' );
// -------------------------------------------------------------------------- \\ // File: RegExp.js \\ // Module: Core \\ // Requires: Core.js \\ // Author: Neil Jenkins \\ // License: © 2010–2011 Opera Software ASA. All rights reserved. \\ // -------------------------------------------------------------------------- \\ "use strict"; /** Property: RegExp.email Type: RegExp A regular expression for detecting an email address. */ RegExp.email = /\b([\w\-.%+]+@(?:[\w\-]+\.)+[A-Z]{2,4})\b/i; /** Property: RegExp.url Type: RegExp A regular expression for detecting a url. Regexp by John Gruber, see <http://daringfireball.net/2010/07/improved_regex_for_matching_urls> */ RegExp.url = /\b(?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])/i;
// -------------------------------------------------------------------------- \\ // File: RegExp.js \\ // Module: Core \\ // Requires: Core.js \\ // Author: Neil Jenkins \\ // License: © 2010–2011 Opera Software ASA. All rights reserved. \\ // -------------------------------------------------------------------------- \\ "use strict"; /** Property: RegExp.email Type: RegExp A regular expression for detecting an email address. */ RegExp.email = /\b([\w\-.%+]+@(?:[\w\-]+\.)+[A-Z]{2,4})\b/i; /** Property: RegExp.url Type: RegExp A regular expression for detecting a url. Regexp by John Gruber, see <http://daringfireball.net/2010/07/improved_regex_for_matching_urls> */ RegExp.url = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]+\))+(?:\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
Fix up statsd work to support python 2.6 Format specifiers must include field specifier
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging from functools import wraps from django_statsd.clients import statsd logger = logging.getLogger(__name__) def task_timer(fn): @wraps(fn) def __wrapped__(self, *args, **kwargs): statsd.incr('tasks.{0}.{1}.count'.format( self.name.rsplit('.', 1)[-1], fn.__name__)) with statsd.timer('tasks.{0}.{1}.timer'.format( self.name.rsplit('.', 1)[-1], fn.__name__)): return fn(self, *args, **kwargs) return __wrapped__ class BaseTimer(object): def __init__(self, name, prefix=None): self.name = name.rsplit('.', 1)[-1] if prefix: self.name = '{0}.{1}'.format(prefix, self.name) def __call__(self, fn): @wraps(fn) def __wrapped__(obj, *args, **kwargs): statsd.incr('{0}.{1}.count'.format( self.name, fn.__name__ )) with statsd.timer('{0}.{1}.timer'.format( self.name, fn.__name__ )): return fn(obj, *args, **kwargs) return __wrapped__
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging from functools import wraps from django_statsd.clients import statsd logger = logging.getLogger(__name__) def task_timer(fn): @wraps(fn) def __wrapped__(self, *args, **kwargs): statsd.incr('tasks.{}.{}.count'.format( self.name.rsplit('.', 1)[-1], fn.__name__)) with statsd.timer('tasks.{}.{}.timer'.format( self.name.rsplit('.', 1)[-1], fn.__name__)): return fn(self, *args, **kwargs) return __wrapped__ class BaseTimer(object): def __init__(self, name, prefix=None): self.name = name.rsplit('.', 1)[-1] if prefix: self.name = '{}.{}'.format(prefix, self.name) def __call__(self, fn): @wraps(fn) def __wrapped__(obj, *args, **kwargs): statsd.incr('{}.{}.count'.format( self.name, fn.__name__ )) with statsd.timer('{}.{}.timer'.format( self.name, fn.__name__ )): return fn(obj, *args, **kwargs) return __wrapped__
Fix exception json_decode() expects parameter 1 to be string, array given Since Notifynder fixes Extra array is empty if you call toArray, no longer json_decode is required. https://github.com/fenos/Notifynder/issues/126
<li class="news-item"> <table cellpadding="4"> <tr> <td> @if ($notification['body']['name'] == 'user.booked') <span class="label label-warning">{!! Icon::calendar() !!}</span> @endif @if ($notification['body']['name'] == 'appointment.cancel') <span class="label label-danger">{!! Icon::calendar() !!}</span> @endif @if ($notification['body']['name'] == 'appointment.confirm') <span class="label label-success">{!! Icon::calendar() !!}</span> @endif @if ($notification['body']['name'] == 'appointment.serve') <span class="label label-info">{!! Icon::calendar() !!}</span> @endif </td> <td> @if ($notification['extra']) {{trans('notifications.'.$notification['body']['name'], ['user' => $notification['from']['name']] + $notification['extra']) }} @else {{trans('notifications.'.$notification['body']['name'], ['user' => $notification['from']['name']]) }} @endif &nbsp;<small class="text-muted" title="{{$timestamp->toDateTimeString()}}">{{$timestamp->diffForHumans() }}</small> </td> </tr> </table> </li>
<li class="news-item"> <table cellpadding="4"> <tr> <td> @if ($notification['body']['name'] == 'user.booked') <span class="label label-warning">{!! Icon::calendar() !!}</span> @endif @if ($notification['body']['name'] == 'appointment.cancel') <span class="label label-danger">{!! Icon::calendar() !!}</span> @endif @if ($notification['body']['name'] == 'appointment.confirm') <span class="label label-success">{!! Icon::calendar() !!}</span> @endif @if ($notification['body']['name'] == 'appointment.serve') <span class="label label-info">{!! Icon::calendar() !!}</span> @endif </td> <td> @if ($notification['extra']) {{trans('notifications.'.$notification['body']['name'], ['user' => $notification['from']['name']] + json_decode($notification['extra'], true)) }} @else {{trans('notifications.'.$notification['body']['name'], ['user' => $notification['from']['name']]) }} @endif &nbsp;<small class="text-muted" title="{{$timestamp->toDateTimeString()}}">{{$timestamp->diffForHumans() }}</small> </td> </tr> </table> </li>
Fix usage of wrong Nullable annotation
package de.mineformers.investiture.allomancy.tileentity; import javax.annotation.Nullable; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; /** * Stores the multi-block's master position */ public class TileMetalExtractorSlave extends TileEntity { private BlockPos master = BlockPos.ORIGIN; @Override public NBTTagCompound writeToNBT(NBTTagCompound compound) { compound = super.writeToNBT(compound); compound.setLong("MasterPosition", master.toLong()); return compound; } @Override public void readFromNBT(NBTTagCompound compound) { super.readFromNBT(compound); this.master = BlockPos.fromLong(compound.getLong("MasterPosition")); } @Override public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate) { return true; } void setMasterPosition(BlockPos master) { this.master = master.subtract(pos); } public BlockPos getMasterPosition() { return pos.add(master); } @Nullable public TileMetalExtractorMaster getMaster() { TileEntity te = world.getTileEntity(getMasterPosition()); if (te instanceof TileMetalExtractorMaster) return (TileMetalExtractorMaster) te; return null; } }
package de.mineformers.investiture.allomancy.tileentity; import com.sun.istack.internal.Nullable; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; /** * Stores the multi-block's master position */ public class TileMetalExtractorSlave extends TileEntity { private BlockPos master = BlockPos.ORIGIN; @Override public NBTTagCompound writeToNBT(NBTTagCompound compound) { compound = super.writeToNBT(compound); compound.setLong("MasterPosition", master.toLong()); return compound; } @Override public void readFromNBT(NBTTagCompound compound) { super.readFromNBT(compound); this.master = BlockPos.fromLong(compound.getLong("MasterPosition")); } @Override public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate) { return true; } void setMasterPosition(BlockPos master) { this.master = master.subtract(pos); } public BlockPos getMasterPosition() { return pos.add(master); } @Nullable public TileMetalExtractorMaster getMaster() { TileEntity te = world.getTileEntity(getMasterPosition()); if (te instanceof TileMetalExtractorMaster) return (TileMetalExtractorMaster) te; return null; } }
Fix a bug where spaces in a list element would cause an exception
package org.monospark.spongematchers.parser.element; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.monospark.spongematchers.util.PatternBuilder; import com.google.common.collect.Lists; public final class ListElementParser extends StringElementParser { ListElementParser() {} @Override Pattern createPattern() { return new PatternBuilder() .appendNonCapturingPart("\\[\\s*") .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN) .openAnonymousParantheses() .appendNonCapturingPart("\\s*,\\s*") .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN) .closeParantheses() .zeroOrMore() .appendNonCapturingPart("\\s*\\]") .build(); } @Override void parse(Matcher matcher, StringElementContext context) { createList(matcher, context); } private void createList(Matcher matcher, StringElementContext context) { List<StringElement> elements = Lists.newArrayList(); Matcher elementMatcher = StringElementParser.REPLACE_PATTERN.matcher(matcher.group()); while (elementMatcher.find()) { StringElement element = context.getElementAt(elementMatcher.start(), elementMatcher.end()); context.removeElement(element); elements.add(element); } context.addElement(new ListElement(matcher.start(), matcher.end(), elements));; } }
package org.monospark.spongematchers.parser.element; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.monospark.spongematchers.util.PatternBuilder; import com.google.common.collect.Lists; public final class ListElementParser extends StringElementParser { ListElementParser() {} @Override Pattern createPattern() { return new PatternBuilder() .appendNonCapturingPart("\\[") .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN) .openAnonymousParantheses() .appendNonCapturingPart("\\s*,\\s*") .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN) .closeParantheses() .zeroOrMore() .appendNonCapturingPart("\\]") .build(); } @Override void parse(Matcher matcher, StringElementContext context) { createList(matcher, context); } private void createList(Matcher matcher, StringElementContext context) { List<StringElement> elements = Lists.newArrayList(); Matcher elementMatcher = StringElementParser.REPLACE_PATTERN.matcher(matcher.group()); while (elementMatcher.find()) { StringElement element = context.getElementAt(elementMatcher.start(), elementMatcher.end()); context.removeElement(element); elements.add(element); } context.addElement(new ListElement(matcher.start(), matcher.end(), elements));; } }
Split off two functions from GeometryExporter.__init__
print "Loading ", __name__ import geometry, from_poser, to_lux reload(geometry) reload(from_poser) reload(to_lux) import from_poser, to_lux def get_materials(geometry, convert = None): f = convert or (lambda mat, k: ' NamedMaterial "%s/%s"' % (k, mat.Name())) return [f(mat, geometry.material_key) for mat in geometry.materials] def preprocess(geometry, options = {}): if options.get('compute_normals', True) in [True, 1, '1', 'true']: geometry.compute_normals() for i in xrange(int(options.get('subdivisionlevel', 0))): print " subdividing: pass", (i+1) geometry.subdivide() class GeometryExporter(object): def __init__(self, subject, convert_material = None, write_mesh_parameters = None, options = {}): geom = from_poser.get(subject) if geom is None or geom.is_empty: print "Mesh is empty." self.write = lambda file: None else: print "Mesh has", geom.number_of_polygons, "polygons and", print geom.number_of_points, "vertices" materials = get_materials(geom, convert_material) preprocess(geom, options) to_lux.preprocess(geom) self.write = lambda file: to_lux.write(file, geom, materials, write_mesh_parameters)
print "Loading ", __name__ import geometry, from_poser, to_lux reload(geometry) reload(from_poser) reload(to_lux) import from_poser, to_lux class GeometryExporter(object): def __init__(self, subject, convert_material = None, write_mesh_parameters = None, options = {}): geom = from_poser.get(subject) if geom is None or geom.is_empty: print "Mesh is empty." self.write = lambda file: None else: print "Mesh has", geom.number_of_polygons, "polygons and", print geom.number_of_points, "vertices" mats = geom.materials key = geom.material_key if convert_material: materials = [convert_material(mat, key) for mat in mats] else: materials = [' NamedMaterial "%s/%s"' % (key, mat.Name()) for mat in mats] if options.get('compute_normals', True) in [True, 1, '1', 'true']: geom.compute_normals() for i in xrange(int(options.get('subdivisionlevel', 0))): print " subdividing: pass", (i+1) geom.subdivide() to_lux.preprocess(geom) self.write = lambda file: to_lux.write(file, geom, materials, write_mesh_parameters)
Convert CLI output to `.csv`
#!/usr/bin/env node 'use strict'; var csv = require('to-csv'); var input = process.argv.slice(2); var pkg = require('./package.json'); var stdin = require('get-stdin'); var viewport = require('./'); /** * Help screen */ function help() { console.log(pkg.description); console.log(''); console.log('Usage'); console.log(' $ viewport [device]'); console.log(' $ cat <file> | viewport [device]'); console.log(''); console.log('Example'); console.log(' $ viewport'); console.log(' $ viewport iphone4 iphone5'); console.log(' $ cat devices.txt | viewport'); } /** * Show help */ if (input.indexOf('-h') !== -1 || input.indexOf('--help') !== -1) { help(); return; } /** * Show package version */ if (input.indexOf('-v') !== -1 || input.indexOf('--version') !== -1) { console.log(pkg.version); return; } /** * Run */ function run(input) { viewport(input, function (err, devices) { if (err) { throw err; } console.log(csv(devices)); }); } /** * Apply arguments */ if (process.stdin.isTTY) { run(input); } else { stdin(function (data) { [].push.apply(input, data.trim().split('\n')); run(input); }); }
#!/usr/bin/env node 'use strict'; var input = process.argv.slice(2); var pkg = require('./package.json'); var stdin = require('get-stdin'); var viewport = require('./'); /** * Help screen */ function help() { console.log(pkg.description); console.log(''); console.log('Usage'); console.log(' $ viewport [device]'); console.log(' $ cat <file> | viewport [device]'); console.log(''); console.log('Example'); console.log(' $ viewport'); console.log(' $ viewport iphone4 iphone5'); console.log(' $ cat devices.txt | viewport'); } /** * Show help */ if (input.indexOf('-h') !== -1 || input.indexOf('--help') !== -1) { help(); return; } /** * Show package version */ if (input.indexOf('-v') !== -1 || input.indexOf('--version') !== -1) { console.log(pkg.version); return; } /** * Run */ function run(input) { viewport(input, function (err, devices) { if (err) { throw err; } console.log(devices); }); } /** * Apply arguments */ if (process.stdin.isTTY) { run(input); } else { stdin(function (data) { [].push.apply(input, data.trim().split('\n')); run(input); }); }
Add parameter documentation to the even emitter
package im.vector; import android.os.Handler; import android.os.Looper; import org.matrix.androidsdk.util.Log; import java.util.HashSet; import java.util.Set; public class EventEmitter<T> { private static final String LOG_TAG = EventEmitter.class.getSimpleName(); private final Set<Listener<T>> mCallbacks; private final Handler mUiHandler; public EventEmitter() { mCallbacks = new HashSet<>(); mUiHandler = new Handler(Looper.getMainLooper()); } public void register(Listener<T> cb) { mCallbacks.add(cb); } public void unregister(Listener<T> cb) { mCallbacks.remove(cb); } /** * Fires all registered callbacks on the UI thread. * * @param t passed to the callback */ public void fire(final T t) { final Set<Listener<T>> callbacks = new HashSet<>(mCallbacks); mUiHandler.post(new Runnable() { @Override public void run() { for (Listener<T> cb : callbacks) { try { cb.onEventFired(EventEmitter.this, t); } catch (Exception e) { Log.e(LOG_TAG, "Callback threw: " + e.getMessage(), e); } } } } ); } public interface Listener<T> { void onEventFired(EventEmitter<T> emitter, T t); } }
package im.vector; import android.os.Handler; import android.os.Looper; import org.matrix.androidsdk.util.Log; import java.util.HashSet; import java.util.Set; public class EventEmitter<T> { private static final String LOG_TAG = EventEmitter.class.getSimpleName(); private final Set<Listener<T>> mCallbacks; private final Handler mUiHandler; public EventEmitter() { mCallbacks = new HashSet<>(); mUiHandler = new Handler(Looper.getMainLooper()); } public void register(Listener<T> cb) { mCallbacks.add(cb); } public void unregister(Listener<T> cb) { mCallbacks.remove(cb); } /** * Fires all registered callbacks on the UI thread. * * @param t */ public void fire(final T t) { final Set<Listener<T>> callbacks = new HashSet<>(mCallbacks); mUiHandler.post(new Runnable() { @Override public void run() { for (Listener<T> cb : callbacks) { try { cb.onEventFired(EventEmitter.this, t); } catch (Exception e) { Log.e(LOG_TAG, "Callback threw: " + e.getMessage(), e); } } } } ); } public interface Listener<T> { void onEventFired(EventEmitter<T> emitter, T t); } }
Refactor `react-engine` client-side mounting to use Require.js Replace event listener `DOMContentLoaded` with `requirejs` now that the scripts will run after they are loaded. Make sure to load `react` and `react-dom` before `react-router`. Also, attach the modules to `window` for it to work in production.
require('../css/style.css'); (function(window, document, requirejs, define){ 'use strict'; // config try { var config = JSON.parse( document.getElementById('data-config').getAttribute('data-config') ); var versions = config.versions; } catch (error) { // console.log(error); } /** * Require.js config. */ requirejs.config({ paths: { 'react': [ '//cdnjs.cloudflare.com/ajax/libs/react/' + versions['react'] + '/react.min' ], 'react-dom': [ '//cdnjs.cloudflare.com/ajax/libs/react/' + versions['react-dom'] + '/react-dom.min' ], 'react-router': [ '//cdnjs.cloudflare.com/ajax/libs/react-router/' + versions['react-router'] + '/ReactRouter.min' ] } }); /** * Mount on client-side. */ requirejs(['react', 'react-dom'], function(React, ReactDOM) { window.React = React; window.ReactDOM = ReactDOM; requirejs(['react-router'], function(ReactRouter) { window.ReactRouter = ReactRouter; var client = require('react-engine/lib/client'); client.boot({ routes: require('../../routes/Routes'), viewResolver: function(viewName) { return require('../../views/' + viewName); } }); }); }); })(window, document, window.requirejs, window.define);
require('../css/style.css'); (function(window, document, requirejs, define){ 'use strict'; // config try { var config = JSON.parse( document.getElementById('data-config').getAttribute('data-config') ); var versions = config.versions; } catch (error) { // console.log(error); } /** * Require.js config. */ requirejs.config({ paths: { 'react': [ '//cdnjs.cloudflare.com/ajax/libs/react/' + versions['react'] + '/react.min' ], 'react-dom': [ '//cdnjs.cloudflare.com/ajax/libs/react/' + versions['react-dom'] + '/react-dom.min' ], 'react-router': [ '//cdnjs.cloudflare.com/ajax/libs/react-router/' + versions['react-router'] + '/ReactRouter.min' ] } }); /** * Client-side mounting. */ document.addEventListener('DOMContentLoaded', function() { var client = require('react-engine/lib/client'); client.boot({ routes: require('../../routes/Routes'), viewResolver: function(viewName) { return require('../../views/' + viewName); } }); }); })(window, document, window.requirejs, window.define);
Fix blank alt fields by accepting preferred null Definitely feeling the slowdown on `/artworks`. Might need to change API to be a facade on Elasticsearch for speed, if we can figure out `include` functionality on search.
<?php namespace App; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class BelongsToManyOrOne extends BelongsToMany { /** * Whether this relation should return a collection. * * @var boolean */ protected $isMany = true; /** * Get the results of the relationship. * * @return mixed */ public function getResults() { $results = $this->get(); return $this->isMany ? $results : $results->first(); } /** * Declare that a single result should be returned. * * @return $this */ public function expectOne() { $this->isMany = false; return $this; } /** * Declare that a collection of results should be returned. * * @return $this */ public function expectMany() { $this->isMany = true; return $this; } /** * Convenience method for only getting the preferred item. * * @return $this */ public function isPreferred() { return $this->wherePivot('preferred', '=', true)->expectOne(); } /** * Convenience method for only getting the alternative items. * * @return $this */ public function isAlternative() { return $this->wherePivotIn('preferred', [false, null], 'or')->expectMany(); } }
<?php namespace App; use Illuminate\Database\Eloquent\Relations\BelongsToMany; class BelongsToManyOrOne extends BelongsToMany { /** * Whether this relation should return a collection. * * @var boolean */ protected $isMany = true; /** * Get the results of the relationship. * * @return mixed */ public function getResults() { $results = $this->get(); return $this->isMany ? $results : $results->first(); } /** * Declare that a single result should be returned. * * @return $this */ public function expectOne() { $this->isMany = false; return $this; } /** * Declare that a collection of results should be returned. * * @return $this */ public function expectMany() { $this->isMany = true; return $this; } /** * Convenience method for only getting the preferred item. * * @return $this */ public function isPreferred() { return $this->wherePivot('preferred', '=', true)->expectOne(); } /** * Convenience method for only getting the alternative items. * * @return $this */ public function isAlternative() { return $this->wherePivot('preferred', '=', false)->expectMany(); } }
Fix duplicate download url, and fix unspecified key problem
import React, {PureComponent, PropTypes} from 'react' import {connect} from 'react-redux' import {parse} from 'url' import {uniq} from 'lodash' import ButtonItem from './button-item' function mapStateToProps(state) { return { title: state.song.playing.title, artist: state.song.playing.artist, files: state.song.playing.files } } function mapDispatchToProps(dispatch) { return {} } @connect(mapStateToProps, mapDispatchToProps) export default class DownloadButton extends PureComponent { static propTypes = { title: PropTypes.string, artist: PropTypes.string, files: PropTypes.array } render() { const {title, artist, files} = this.props return ( <ButtonItem icon='download' hidden={!files}> <p>Download Song</p> {files && files.map(({urls, format, quality}) => ( <p key={urls.join('.')}> <span> {format || 'unknown'}&nbsp; {quality && quality.description}: </span> {uniq(urls).map((url, index) => ( <span key={url}> <br/>&nbsp;·&nbsp; <a href={url} target='_blank' type={`audio/${format}`} download={`${artist} - ${title}`} style={{ color: 'inherit', textDecoration: 'underline', cursor: 'pointer' }}> {parse(url).host} </a> </span> ))} </p> ))} </ButtonItem> ) } }
import React, {PureComponent, PropTypes} from 'react' import {connect} from 'react-redux' import {parse} from 'url' import ButtonItem from './button-item' function mapStateToProps(state) { return { title: state.song.playing.title, artist: state.song.playing.artist, files: state.song.playing.files } } function mapDispatchToProps(dispatch) { return {} } @connect(mapStateToProps, mapDispatchToProps) export default class DownloadButton extends PureComponent { static propTypes = { title: PropTypes.string, artist: PropTypes.string, files: PropTypes.array } render() { const {title, artist, files} = this.props return ( <ButtonItem icon='download' hidden={!files}> <p>Download Song</p> {files && files.map(({urls, format, quality}) => ( <p> <span> {format || 'unknown'}&nbsp; {quality && quality.description}: </span> {urls.map((url, index) => ( <span> <br/>&nbsp;·&nbsp; <a href={url} target='_blank' type={`audio/${format}`} download={`${artist} - ${title}`} style={{ color: 'inherit', textDecoration: 'underline', cursor: 'pointer' }}> {parse(url).host} </a> </span> ))} </p> ))} </ButtonItem> ) } }
Print project name even if it doesn't exist on disk
"""Print utilities""" import os import emoji from termcolor import colored, cprint from clowder.utility.git_utilities import ( git_current_sha, git_current_branch, git_is_detached, git_is_dirty ) def print_project_status(root_directory, path, name): """Print repo status""" repo_path = os.path.join(root_directory, path) git_path = os.path.join(repo_path, '.git') if not os.path.isdir(git_path): cprint(name, 'green') return if git_is_dirty(repo_path): color = 'red' symbol = '*' else: color = 'green' symbol = '' project_output = colored(symbol + name, color) if git_is_detached(repo_path): current_ref = git_current_sha(repo_path) current_ref_output = colored('(HEAD @ ' + current_ref + ')', 'magenta') else: current_branch = git_current_branch(repo_path) current_ref_output = colored('(' + current_branch + ')', 'magenta') path_output = colored(path, 'cyan') print(project_output + ' ' + current_ref_output + ' ' + path_output) def print_group(name): name_output = colored(name, attrs=['bold']) print(get_cat() + ' ' + name_output) def get_cat(): """Return a cat emoji""" return emoji.emojize(':cat:', use_aliases=True)
"""Print utilities""" import os import emoji from termcolor import colored from clowder.utility.git_utilities import ( git_current_sha, git_current_branch, git_is_detached, git_is_dirty ) def print_project_status(root_directory, path, name): """Print repo status""" repo_path = os.path.join(root_directory, path) git_path = os.path.join(repo_path, '.git') if not os.path.isdir(git_path): return if git_is_dirty(repo_path): color = 'red' symbol = '*' else: color = 'green' symbol = '' project_output = colored(symbol + name, color) if git_is_detached(repo_path): current_ref = git_current_sha(repo_path) current_ref_output = colored('(HEAD @ ' + current_ref + ')', 'magenta') else: current_branch = git_current_branch(repo_path) current_ref_output = colored('(' + current_branch + ')', 'magenta') path_output = colored(path, 'cyan') print(project_output + ' ' + current_ref_output + ' ' + path_output) def print_group(name): name_output = colored(name, attrs=['bold']) print(get_cat() + ' ' + name_output) def get_cat(): """Return a cat emoji""" return emoji.emojize(':cat:', use_aliases=True)
Use DOTALL flag on regex.
# The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS"basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # OS2Webscanner was developed by Magenta in collaboration with OS2 the # Danish community of open source municipalities (http://www.os2web.dk/). # # The code is currently governed by OS2 the Danish community of open # source municipalities ( http://www.os2web.dk/ ) """Regular expression-based rules.""" import regex from rule import Rule from ..items import MatchItem class RegexRule(Rule): """Represents a rule which matches using a regular expression.""" def __init__(self, name, match_string, sensitivity): """Initialize the rule. The sensitivity is used to assign a sensitivity value to matches. """ self.name = name self.regex = regex.compile(match_string, regex.DOTALL) self.sensitivity = sensitivity def execute(self, text): """Execute the rule on the text.""" matches = set() re_matches = self.regex.finditer(text) for match in re_matches: matches.add(MatchItem(matched_data=match.group(0), sensitivity=self.sensitivity)) return matches
# The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an "AS IS"basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # OS2Webscanner was developed by Magenta in collaboration with OS2 the # Danish community of open source municipalities (http://www.os2web.dk/). # # The code is currently governed by OS2 the Danish community of open # source municipalities ( http://www.os2web.dk/ ) """Regular expression-based rules.""" import regex from rule import Rule from ..items import MatchItem class RegexRule(Rule): """Represents a rule which matches using a regular expression.""" def __init__(self, name, match_string, sensitivity): """Initialize the rule. The sensitivity is used to assign a sensitivity value to matches. """ self.name = name self.regex = regex.compile(match_string) self.sensitivity = sensitivity def execute(self, text): """Execute the rule on the text.""" matches = set() re_matches = self.regex.finditer(text) for match in re_matches: matches.add(MatchItem(matched_data=match.group(0), sensitivity=self.sensitivity)) return matches
Update markup for survey link Resolves: https://trello.com/c/ZpypHwAa/526-fix-banner-styling
<?php $showBannerOnNetwork = get_site_option('banner_setting'); $showBannerBySite = get_field('show_banner', 'options'); if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) { $bannerTitle = get_site_option('banner_title'); $bannerLinkText = get_site_option('banner_link_text'); $bannerLink = get_site_option('banner_link'); ?> <aside id="user-satisfaction-survey-container" class="govuk-width-container"> <section id="user-satisfaction-survey" class="visible" aria-hidden="false"> <div class="govuk-grid-row"> <div class="govuk-grid-column-three-quarters"> <p class="govuk-heading-s"><?php echo esc_html($bannerTitle) ?></p> <p class="govuk-body"><a href="<?php echo esc_url($bannerLink)?>" id="take-survey" class="govuk-link" target="_blank" rel="noopener noreferrer nofollow"><?php echo esc_html($bannerLinkText) ?></a></p> </div> <div class="govuk-grid-column-one-quarter"> <p class="govuk-body"><a href="#survey-no-thanks" id="survey-no-thanks" class="govuk-link" role="button" aria-controls="user-satisfaction-survey">No thanks</a></p> </div> </div> </section> </aside> <?php } ?>
<?php $showBannerOnNetwork = get_site_option('banner_setting'); $showBannerBySite = get_field('show_banner', 'options'); if ($showBannerOnNetwork == true && ($showBannerBySite == true || $showBannerBySite === null)) { $bannerTitle = get_site_option('banner_title'); $bannerLinkText = get_site_option('banner_link_text'); $bannerLink = get_site_option('banner_link'); ?> <aside id="user-satisfaction-survey-container" class="govuk-width-container"> <section id="user-satisfaction-survey" class="visible" aria-hidden="false"> <div class="govuk-grid-row"> <div class="govuk-grid-column-three-quarters"> <p class="govuk-heading-s"><?php echo esc_html($bannerTitle) ?></p> <p class="govuk-body"><a href="<?php echo esc_url($bannerLink)?>" id="take-survey" target="_blank"><?php echo esc_html($bannerLinkText) ?></a></p> </div> <div class="govuk-grid-column-one-quarter"> <p class="govuk-body"><a href="#survey-no-thanks" id="survey-no-thanks" class="govuk-link" role="button" aria-controls="user-satisfaction-survey">No thanks</a></p> </div> </div> </section> </aside> <?php } ?>
Add test case for empty and missing IRCv3 tags
import pytest from pydle.features import ircv3 pytestmark = [pytest.mark.unit, pytest.mark.ircv3] @pytest.mark.parametrize( "payload, expected", [ ( rb'@empty=;missing :irc.example.com NOTICE #channel :Message', {'empty': True, 'missing': True} ), ( rb"@+example=raw+:=,escaped\:\s\\ :irc.example.com NOTICE #channel :Message", {"+example": """raw+:=,escaped; \\"""} ), ( rb"@+example=\foo\bar :irc.example.com NOTICE #channel :Message", {"+example": "foobar"} ), ( rb'@msgid=796~1602221579~51;account=user123 :user123!user123@(ip) PRIVMSG #user123 :ping', {'msgid': '796~1602221579~51', 'account': 'user123'} ), ( rb'@inspircd.org/service;inspircd.org/bot :ChanServ!services@services.(domain) MODE #user123 +qo user123 :user123', {"inspircd.org/service": True, r"inspircd.org/bot": True} ) ] ) def test_tagged_message_escape_sequences(payload, expected): message = ircv3.tags.TaggedMessage.parse(payload) assert message.tags == expected
import pytest from pydle.features import ircv3 pytestmark = [pytest.mark.unit, pytest.mark.ircv3] @pytest.mark.parametrize( "payload, expected", [ ( rb"@+example=raw+:=,escaped\:\s\\ :irc.example.com NOTICE #channel :Message", {"+example": """raw+:=,escaped; \\"""} ), ( rb"@+example=\foo\bar :irc.example.com NOTICE #channel :Message", {"+example": "foobar"} ), ( rb'@msgid=796~1602221579~51;account=user123 :user123!user123@((ip) PRIVMSG #user123 :ping', {'msgid': '796~1602221579~51', 'account': 'user123'} ), ( rb'@inspircd.org/service;inspircd.org/bot :ChanServ!services@services.(domain) MODE #user123 +qo user123 :user123', {"inspircd.org/service": True, r"inspircd.org/bot": True} ) ] ) def test_tagged_message_escape_sequences(payload, expected): message = ircv3.tags.TaggedMessage.parse(payload) assert message.tags == expected
[IMP][10.0] Add UI notification for AJAX request status
'use strict'; odoo.define('proxy_action.proxy_view', function (require) { var ActionManager = require('web.ActionManager'); var core = require('web.core') var _t = core._t ActionManager.include({ ir_actions_act_proxy: function (action, options) { var self = this; self.do_notify(_t('Proxy action executing'), _t('Your action is being executed')); action.action_list.forEach(function (task) { $.ajax({ url: task['url'], type: 'POST', data: JSON.stringify(task['params']), contentType: 'application/json', }).done(function (result) { console.log("Proxy action has been successfully sent: ", result); self.do_notify(_t('Success'), _t('Proxy action successfully sent')); self.ir_actions_act_window_close(action, options); }).fail(function (result) { console.log('Proxy action has failed: ', result); self.do_warn(_t("Failure"), _t("Proxy action failure. Please check logs.")); self.ir_actions_act_window_close(action, options); }) }) this.do_action({"type":"ir.actions.act_window_close"}); } }); });
'use strict'; odoo.define('proxy_action.proxy_view', function (require) { var ActionManager = require('web.ActionManager'); ActionManager.include({ ir_actions_act_proxy: function (action, options) { var self = this; action.action_list.forEach(function (task) { $.ajax({ url: task['url'], type: 'POST', data: JSON.stringify(task['params']), contentType: 'application/json', }).done(function (result) { console.log("Proxy action have been done with sucess", result); //TODO add an UI feedback self.ir_actions_act_window_close(action, options); }).fail(function (result) { console.log('Proxy action have failed', result); //TODO add an UI feedback self.ir_actions_act_window_close(action, options); }) }) this.do_action({"type":"ir.actions.act_window_close"}); } }); });
Fix PyPi readme. Bump to 1.4.2
import os __location__ = os.path.dirname(__file__) try: from setuptools import setup except ImportError: from distutils.core import setup # read the contents of README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='pandas-profiling', version='1.4.2', author='Jos Polfliet', author_email='[email protected]', packages=['pandas_profiling'], url='https://github.com/pandas-profiling/pandas-profiling', license='MIT', description='Generate profile report for pandas DataFrame', install_requires=[ "pandas>=0.19", "matplotlib>=1.4", "jinja2>=2.8", "six>=1.9" ], include_package_data = True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Operating System :: OS Independent', 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering', 'Framework :: IPython', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7' ], keywords='pandas data-science data-analysis python jupyter ipython', long_description=long_description, long_description_content_type='text/markdown' )
import os __location__ = os.path.dirname(__file__) try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='pandas-profiling', version='1.4.1', author='Jos Polfliet', author_email='[email protected]', packages=['pandas_profiling'], url='http://github.com/jospolfliet/pandas-profiling', license='MIT', description='Generate profile report for pandas DataFrame', install_requires=[ "pandas>=0.19", "matplotlib>=1.4", "jinja2>=2.8", "six>=1.9" ], include_package_data = True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Operating System :: OS Independent', 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'Topic :: Scientific/Engineering', 'Framework :: IPython', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6' ], keywords='pandas data-science data-analysis python jupyter ipython', )
Create codesandbox using the 'parcel' template The default template is `create-react-app` and this one ignores the `head` tag defined in out `index.html`
(function() { function compress(json) { return LZString.compressToBase64(JSON.stringify(json)) .replace(/\+/g, `-`) .replace(/\//g, `_`) .replace(/=+$/, ``); } var htmlClipboard = new Clipboard('#copy-html-button'); htmlClipboard.on('success', function(e) { e.clearSelection(); }); var jsClipboard = new Clipboard('#copy-js-button'); jsClipboard.on('success', function(e) { e.clearSelection(); }); var pkgClipboard = new Clipboard('#copy-pkg-button'); pkgClipboard.on('success', function(e) { e.clearSelection(); }); var codepenButton = document.getElementsByClassName('codepen-button')[0]; if (codepenButton) { codepenButton.onclick = function(event) { event.preventDefault(); var form = document.getElementById('codepen-form'); const html = document.getElementById('example-html-source').innerText; const js = document.getElementById('example-js-source').innerText; const pkgJson = document.getElementById('example-pkg-source').innerText; form.parameters.value = compress({ files: { 'index.html': { content: html }, 'index.js': { content: js }, "package.json": { content: pkgJson }, 'sandbox.config.json': { content: '{"template": "parcel"}' } } }); form.submit(); }; } })();
(function() { function compress(json) { return LZString.compressToBase64(JSON.stringify(json)) .replace(/\+/g, `-`) .replace(/\//g, `_`) .replace(/=+$/, ``); } var htmlClipboard = new Clipboard('#copy-html-button'); htmlClipboard.on('success', function(e) { e.clearSelection(); }); var jsClipboard = new Clipboard('#copy-js-button'); jsClipboard.on('success', function(e) { e.clearSelection(); }); var pkgClipboard = new Clipboard('#copy-pkg-button'); pkgClipboard.on('success', function(e) { e.clearSelection(); }); var codepenButton = document.getElementsByClassName('codepen-button')[0]; if (codepenButton) { codepenButton.onclick = function(event) { event.preventDefault(); var form = document.getElementById('codepen-form'); const html = document.getElementById('example-html-source').innerText; const js = document.getElementById('example-js-source').innerText; const pkgJson = document.getElementById('example-pkg-source').innerText; form.parameters.value = compress({ files: { 'index.html': { content: html }, 'index.js': { content: js }, "package.json": { content: pkgJson } } }); form.submit(); }; } })();
Use this instead of query
angular .module('ngSharepoint.Lists') .factory('UpdateQuery', ['$spList', 'CamlBuilder', 'WhereQuery', 'Query', function($spList, CamlBuilder, WhereQuery, Query) { var UpdateQuery = function(list) { this.__list = list; this.__values = {}; this.__where = []; return this; }; UpdateQuery.prototype = new Query(); UpdateQuery.prototype.set = function(key, value) { this.__values[key] = value; return this; }; UpdateQuery.prototype.where = function(key) { var query = new WhereQuery(this, key); this.__where.push(query); return query; }; UpdateQuery.prototype.__execute = function() { var camlBuilder = new CamlBuilder(); var camlView = camlBuilder.push('View'); var queryTag; if (this.__where.length === 1) { queryTag = camlView.push('Query'); this.__where[0].push(queryTag.push('Where')); }else if (this.__where.length > 1) { queryTag = camlView.push('Query'); var andTag = queryTag.push('Where').push('And'); this.__where.forEach(function(where) { where.push(andTag); }); } return $spList.getList(this.__list).update(camlBuilder.build(), this.__values); }; return (UpdateQuery); }]);
angular .module('ngSharepoint.Lists') .factory('UpdateQuery', ['$spList', 'CamlBuilder', 'WhereQuery', 'Query', function($spList, CamlBuilder, WhereQuery, Query) { var UpdateQuery = function(list) { this.__list = list; this.__values = {}; this.__where = []; return this; }; UpdateQuery.prototype = new Query(); UpdateQuery.prototype.set = function(key, value) { this.__values[key] = value; return this; }; UpdateQuery.prototype.where = function(key) { var query = new WhereQuery(this, key); this.__where.push(query); return query; }; UpdateQuery.prototype.__execute = function() { var camlBuilder = new CamlBuilder(); var camlView = camlBuilder.push('View'); var queryTag; if (query.__where.length === 1) { queryTag = camlView.push('Query'); query.__where[0].push(queryTag.push('Where')); }else if (query.__where.length > 1) { queryTag = camlView.push('Query'); var andTag = queryTag.push('Where').push('And'); query.__where.forEach(function(where) { where.push(andTag); }); } return $spList.getList(this.__list).update(camlBuilder.build(), this.__values); }; return (UpdateQuery); }]);
Return is_authenticated true if we got user and it is active
from django.http import HttpResponse from django.template import loader from django.utils.crypto import salted_hmac, constant_time_compare from django.contrib.auth.models import User class HMACAuth(object): def __init__(self, realm='API'): self.realm = realm def process_request(self, request): user_id = request.META.get('HTTP_X_LA_USER_ID', None) signature = request.META.get('HTTP_X_LA_HASH', None) return user_id, signature def is_authenticated(self, request): user_id, signature = self.process_request(request) if user_id and signature: check_digest = salted_hmac("linked_accounts.views.login", str(user_id)).hexdigest() if not constant_time_compare(signature, check_digest): return False try: user = User.objects.get(id=user_id) if user.is_active: request.user = user return True except User.DoesNotExist: pass return False def challenge(self): response = HttpResponse() response.status_code = 401 tmpl = loader.render_to_string('linked_accounts/api_challenge.html') response.content = tmpl return response def __repr__(self): return u'<HMACAuth: realm=%s>' % self.realm
from django.http import HttpResponse from django.template import loader from django.utils.crypto import salted_hmac, constant_time_compare from django.contrib.auth.models import User class HMACAuth(object): def __init__(self, realm='API'): self.realm = realm def process_request(self, request): user_id = request.META.get('HTTP_X_LA_USER_ID', None) signature = request.META.get('HTTP_X_LA_HASH', None) return user_id, signature def is_authenticated(self, request): user_id, signature = self.process_request(request) if user_id and signature: check_digest = salted_hmac("linked_accounts.views.login", str(user_id)).hexdigest() if not constant_time_compare(signature, check_digest): return False try: user = User.objects.get(id=user_id) if user.is_active: request.user = user except User.DoesNotExist: pass return False def challenge(self): response = HttpResponse() response.status_code = 401 tmpl = loader.render_to_string('linked_accounts/api_challenge.html') response.content = tmpl return response def __repr__(self): return u'<HMACAuth: realm=%s>' % self.realm
Change the way the configuration file is loaded
<?php namespace ProjectLint\Console\Command; use ProjectLint\Item\ItemManager; use ProjectLint\Report\Renderer\TextRenderer; use ProjectLint\Rule\RuleSet; use ProjectLint\Rule\RuleSetChecker; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Logger\ConsoleLogger; class ProjectLintCommand extends Command { protected function configure() { $this->setName('projectlint') ->setDescription('Checks project structure') ->setHelp(PHP_EOL . 'Checks project layout against a ruleset' . PHP_EOL) ->addArgument('path', InputArgument::OPTIONAL, 'Project path', 'Current directory'); } protected function execute(InputInterface $input, OutputInterface $output) { $logger = new ConsoleLogger($output); $projectPath = $input->getArgument('path'); if ('Current directory' == $projectPath) { $projectPath = getcwd(); } $ruleSet = new RuleSet($projectPath . '/projectlint.yml', $logger); $itemManager = new ItemManager($projectPath); $checker = new RuleSetChecker($itemManager); $report = $checker->check($ruleSet); $renderer = new TextRenderer($output); $renderer->render($report); // Set exit code return $report->hasViolations() ? 1 : 0; } }
<?php namespace ProjectLint\Console\Command; use ProjectLint\Item\ItemManager; use ProjectLint\Report\Renderer\TextRenderer; use ProjectLint\Rule\RuleSet; use ProjectLint\Rule\RuleSetChecker; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Logger\ConsoleLogger; class ProjectLintCommand extends Command { protected function configure() { $this->setName('projectlint') ->setDescription('Checks project structure') ->setHelp(PHP_EOL . 'Checks project layout against a ruleset' . PHP_EOL) ->addArgument('ruleset', InputArgument::OPTIONAL, 'Ruleset path', 'projectlint.yml'); } protected function execute(InputInterface $input, OutputInterface $output) { $logger = new ConsoleLogger($output); $ruleSetPath = $input->getArgument('ruleset'); $ruleSet = new RuleSet($ruleSetPath, $logger); $itemManager = new ItemManager(getcwd()); $checker = new RuleSetChecker($itemManager); $report = $checker->check($ruleSet); $renderer = new TextRenderer($output); $renderer->render($report); // Set exit code return $report->hasViolations() ? 1 : 0; } }
Set value of 'owner' to the value of the ObjectId
from . import app, mongo from alexandria.decorators import * from flask import request, jsonify, url_for, session from flask.ext.classy import FlaskView, route import json from bson import json_util class BooksView(FlaskView): route_prefix = '/api/' @authenticated def index(self): query = mongo.Books.find() books = json.loads(json_util.dumps(query, default=json_util.default)) for book in books: book['id'] = book['_id']['$oid'] book.pop('_id') book['owner'] = book['owner']['$oid'] return jsonify(books=books) @authenticated def genre(self, id): query = mongo.Books.find({'genres':id}) books = json.loads(json_util.dumps(query, default=json_util.default)) for book in books: book['id'] = book['_id']['$oid'] book.pop('_id') book['owner'] = book['owner']['$oid'] return jsonify(books=books) @authenticated def author(self, id): query = mongo.Books.find({'authors':id}) books = json.loads(json_util.dumps(query, default=json_util.default)) for book in books: book['id'] = book['_id']['$oid'] book.pop('_id') book['owner'] = book['owner']['$oid'] return jsonify(books=books) BooksView.register(app)
from . import app, mongo from alexandria.decorators import * from flask import request, jsonify, url_for, session from flask.ext.classy import FlaskView, route import json from bson import json_util class BooksView(FlaskView): route_prefix = '/api/' @authenticated def index(self): query = mongo.Books.find() books = json.loads(json_util.dumps(query, default=json_util.default)) for book in books: book['id'] = book['_id']['$oid'] book.pop('_id') return jsonify(books=books) @authenticated def genre(self, id): query = mongo.Books.find({'genres':id}) books = json.loads(json_util.dumps(query, default=json_util.default)) for book in books: book['id'] = book['_id']['$oid'] book.pop('_id') return jsonify(books=books) @authenticated def author(self, id): query = mongo.Books.find({'authors':id}) books = json.loads(json_util.dumps(query, default=json_util.default)) for book in books: book['id'] = book['_id']['$oid'] book.pop('_id') return jsonify(books=books) BooksView.register(app)
Increase update time for compliments.
var config = { lang: 'nl', time: { timeFormat: 12 }, weather: { //change weather params here: //units: metric or imperial params: { q: 'Baarn,Netherlands', units: 'metric', // if you want a different lang for the weather that what is set above, change it here lang: 'nl', APPID: 'YOUR_FREE_OPENWEATHER_API_KEY' } }, compliments: { interval: 30000, fadeInterval: 4000, morning: [ 'Good morning, handsome!', 'Enjoy your day!', 'How was your sleep?' ], afternoon: [ 'Hello, beauty!', 'You look sexy!', 'Looking good today!' ], evening: [ 'Wow, you look hot!', 'You look nice!', 'Hi, sexy!' ] }, news: { feed: 'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml' } }
var config = { lang: 'nl', time: { timeFormat: 12 }, weather: { //change weather params here: //units: metric or imperial params: { q: 'Baarn,Netherlands', units: 'metric', // if you want a different lang for the weather that what is set above, change it here lang: 'nl', APPID: 'YOUR_FREE_OPENWEATHER_API_KEY' } }, compliments: { interval: 2000, fadeInterval: 4000, morning: [ 'Good morning, handsome!', 'Enjoy your day!', 'How was your sleep?' ], afternoon: [ 'Hello, beauty!', 'You look sexy!', 'Looking good today!' ], evening: [ 'Wow, you look hot!', 'You look nice!', 'Hi, sexy!' ] }, news: { feed: 'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml' } }
Fix result loading for novel mutations
from models import Protein, Mutation from database import get_or_create class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'], created = get_or_create( Mutation, protein=state['protein'], **state['mutation_kwargs'] ) del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state)
from models import Protein, Mutation class SearchResult: def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs): self.protein = protein self.mutation = mutation self.is_mutation_novel = is_mutation_novel self.type = type self.meta_user = None self.__dict__.update(kwargs) def __getstate__(self): state = self.__dict__.copy() state['protein_refseq'] = self.protein.refseq del state['protein'] state['mutation_kwargs'] = { 'position': self.mutation.position, 'alt': self.mutation.alt } del state['mutation'] state['meta_user'].mutation = None return state def __setstate__(self, state): state['protein'] = Protein.query.filter_by( refseq=state['protein_refseq'] ).one() del state['protein_refseq'] state['mutation'] = Mutation.query.filter_by( protein=state['protein'], **state['mutation_kwargs'] ).one() del state['mutation_kwargs'] state['meta_user'].mutation = state['mutation'] state['mutation'].meta_user = state['meta_user'] self.__dict__.update(state)
Make test Callback a little more reusable
<?php namespace Respect\Validation\Rules; class CallbackTest extends \PHPUnit_Framework_TestCase { private $truthy, $falsy; function setUp() { $this->truthy = new Callback(function() { return true; }); $this->falsy = new Callback(function() { return false; }); } public function thisIsASampleCallbackUsedInsideThisTest() { return true; } public function testCallbackValidatorShouldReturnTrueIfCallbackReturnsTrue() { $this->assertTrue($this->truthy->assert('wpoiur')); } /** * @expectedException Respect\Validation\Exceptions\CallbackException */ public function testCallbackValidatorShouldReturnFalseIfCallbackReturnsFalse() { $this->assertTrue($this->falsy->assert('w poiur')); } public function testCallbackValidatorShouldAcceptArrayCallbackDefinitions() { $v = new Callback(array($this, 'thisIsASampleCallbackUsedInsideThisTest')); $this->assertTrue($v->assert('test')); } public function testCallbackValidatorShouldAcceptFunctionNamesAsString() { $v = new Callback('is_string'); $this->assertTrue($v->assert('test')); } /** * @expectedException Respect\Validation\Exceptions\ComponentException */ public function testInvalidCallbacksShouldRaiseComponentExceptionUponInstantiation() { $v = new Callback(new \stdClass); $this->assertTrue($v->assert('w poiur')); } }
<?php namespace Respect\Validation\Rules; class CallbackTest extends \PHPUnit_Framework_TestCase { public function thisIsASampleCallbackUsedInsideThisTest() { return true; } public function testCallbackValidatorShouldReturnTrueIfCallbackReturnsTrue() { $v = new Callback(function() { return true; }); $this->assertTrue($v->assert('wpoiur')); } /** * @expectedException Respect\Validation\Exceptions\CallbackException */ public function testCallbackValidatorShouldReturnFalseIfCallbackReturnsFalse() { $v = new Callback(function() { return false; }); $this->assertTrue($v->assert('w poiur')); } public function testCallbackValidatorShouldAcceptArrayCallbackDefinitions() { $v = new Callback(array($this, 'thisIsASampleCallbackUsedInsideThisTest')); $this->assertTrue($v->assert('test')); } public function testCallbackValidatorShouldAcceptFunctionNamesAsString() { $v = new Callback('is_string'); $this->assertTrue($v->assert('test')); } /** * @expectedException Respect\Validation\Exceptions\ComponentException */ public function testInvalidCallbacksShouldRaiseComponentExceptionUponInstantiation() { $v = new Callback(new \stdClass); $this->assertTrue($v->assert('w poiur')); } }
Improve password hashing store in registration
<?php namespace App\Controllers; class AuthController { public function login() { var_dump(input()); return $input; } public function register() { $inputs = input()->all(['email', 'password']); if (!$this->isValid($inputs)) { return 'form is not valid'; } if ($this->isEmailExist($inputs['email'])) { return 'email already used'; } \Builder::table('users')->insert([ 'email' => $inputs['email'], 'password' => password_hash($inputs['password'], PASSWORD_DEFAULT), 'role' => 'student' ]); return 'success'; } private function isEmailExist($email) { return !is_null(\Builder::table('users')->where('email', '=', $email)->first()); } /** * Check if array has falsy values * * @param array $inputs * @return boolean */ private function isValid($inputs) { return !in_array(false, $this->isEmpty($inputs)); } /** * Transform all values in array to (boolean) false depending * on whether its empty or not. The element will be false if * it is empty. * * @param array $arrays * @return array */ private function isEmpty($arrays) { return array_map( function ($value) { return !empty($value); }, $arrays ); } }
<?php namespace App\Controllers; class AuthController { public function login() { var_dump(input()); return $input; } public function register() { $inputs = input()->all(['email', 'password']); if (!$this->isValid($inputs)) { return 'form is not valid'; } if ($this->isEmailExist($inputs['email'])) { return 'email already used'; } \Builder::table('users')->insert([ 'email' => $inputs['email'], 'password' => sha1($inputs['email']), 'role' => 'student' ]); return 'success'; } private function isEmailExist($email) { return !is_null(\Builder::table('users')->where('email', '=', $email)->first()); } /** * Check if array has falsy values * * @param arrays $inputs * @return boolean */ private function isValid($inputs) { return !in_array(false, $this->isEmpty($inputs)); } /** * Transform all values in array to (boolean) false depending * on whether its empty or not. The element will be false if * it is empty. * * @param array $arrays * @return array */ private function isEmpty($arrays) { return array_map( function ($value) { return !empty($value); }, $arrays ); } }
Rename integration test model names for debugging in console
"""Basic scenarios, symmetric tests""" import pytest from bloop import ( BaseModel, Column, GlobalSecondaryIndex, Integer, MissingObjects, ) from .models import User def test_crud(engine): engine.bind(User) user = User(email="[email protected]", username="user", profile="first") engine.save(user) same_user = User(email=user.email, username=user.username) engine.load(same_user) assert user.profile == same_user.profile same_user.profile = "second" engine.save(same_user) engine.load(user, consistent=True) assert user.profile == same_user.profile engine.delete(user) with pytest.raises(MissingObjects) as excinfo: engine.load(same_user, consistent=True) assert [same_user] == excinfo.value.objects def test_projection_overlap(engine): class ProjectionOverlap(BaseModel): hash = Column(Integer, hash_key=True) range = Column(Integer, range_key=True) other = Column(Integer) by_other = GlobalSecondaryIndex(projection=["other", "range"], hash_key="other") # by_other's projected attributes overlap with the model and its own keys engine.bind(ProjectionOverlap) def test_stream_creation(engine): class StreamCreation(BaseModel): class Meta: stream = { "include": ["keys"] } hash = Column(Integer, hash_key=True) engine.bind(StreamCreation)
"""Basic scenarios, symmetric tests""" import pytest from bloop import ( BaseModel, Column, GlobalSecondaryIndex, Integer, MissingObjects, ) from .models import User def test_crud(engine): engine.bind(User) user = User(email="[email protected]", username="user", profile="first") engine.save(user) same_user = User(email=user.email, username=user.username) engine.load(same_user) assert user.profile == same_user.profile same_user.profile = "second" engine.save(same_user) engine.load(user, consistent=True) assert user.profile == same_user.profile engine.delete(user) with pytest.raises(MissingObjects) as excinfo: engine.load(same_user, consistent=True) assert [same_user] == excinfo.value.objects def test_projection_overlap(engine): class Model(BaseModel): hash = Column(Integer, hash_key=True) range = Column(Integer, range_key=True) other = Column(Integer) by_other = GlobalSecondaryIndex(projection=["other", "range"], hash_key="other") # by_other's projected attributes overlap with the model and its own keys engine.bind(Model) def test_stream_creation(engine): class Model(BaseModel): class Meta: stream = { "include": ["keys"] } hash = Column(Integer, hash_key=True) engine.bind(Model)
Fix up migration to have only one PK
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-27 13:23 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('roombookings', '0006_bookinga_bookingb_lock'), ] operations = [ migrations.AlterField( model_name='bookinga', name='slotid', field=models.BigIntegerField(null=True, primary_key=False), ), migrations.AlterField( model_name='bookingb', name='slotid', field=models.BigIntegerField(null=True, primary_key=False), ), migrations.AddField( model_name='bookinga', name='id', field=models.AutoField(primary_key=True, serialize=False), preserve_default=False, ), migrations.AddField( model_name='bookingb', name='id', field=models.AutoField(primary_key=True, serialize=False), preserve_default=False, ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-27 13:23 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('roombookings', '0006_bookinga_bookingb_lock'), ] operations = [ migrations.AddField( model_name='bookinga', name='id', field=models.AutoField(primary_key=True, serialize=False), preserve_default=False, ), migrations.AddField( model_name='bookingb', name='id', field=models.AutoField(primary_key=True, serialize=False), preserve_default=False, ), migrations.AlterField( model_name='bookinga', name='slotid', field=models.BigIntegerField(), ), migrations.AlterField( model_name='bookingb', name='slotid', field=models.BigIntegerField(), ), ]
Insert custom commands through the getCommands() function.
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Categories * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Categories Toolbar Class * * @author John Bell <http://nooku.assembla.com/profile/johnbell> * @category Nooku * @package Nooku_Server * @subpackage Categories */ class ComCategoriesControllerToolbarCategories extends ComDefaultControllerToolbarDefault { public function getCommands() { $this->addSeperator() ->addEnable(array('label' => 'publish')) ->addDisable(array('label' => 'unpublish')); return parent::getCommands(); } protected function _commandNew(KControllerToolbarCommand $command) { $option = $this->_identifier->package; $view = KInflector::singularize($this->_identifier->name); $section = $this->getController()->getModel()->get('section'); $command->append(array( 'attribs' => array( 'href' => JRoute::_('index.php?option=com_'.$option.'&view='.$view.'&section='.$section ) ) )); } }
<?php /** * @version $Id$ * @category Nooku * @package Nooku_Server * @subpackage Categories * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Categories Toolbar Class * * @author John Bell <http://nooku.assembla.com/profile/johnbell> * @category Nooku * @package Nooku_Server * @subpackage Categories */ class ComCategoriesControllerToolbarCategories extends ComDefaultControllerToolbarDefault { public function __construct(KConfig $config) { parent::__construct($config); $this->addSeperator() ->addEnable(array('label' => 'publish')) ->addDisable(array('label' => 'unpublish')); } protected function _commandNew(KControllerToolbarCommand $command) { $option = $this->_identifier->package; $view = KInflector::singularize($this->_identifier->name); $section = $this->getController()->getModel()->get('section'); $command->append(array( 'attribs' => array( 'href' => JRoute::_('index.php?option=com_'.$option.'&view='.$view.'&section='.$section ) ) )); } }
Remove loading indicator in case of error
'use strict'; app.controller('UserProfileController', ['userService', '$routeParams', '$scope', 'favoritePost', function (userService, $routeParams, $scope, favoritePost) { $scope.size = "sm"; $scope.user = {}; $scope.imageSrc = ''; userService.getDetails($routeParams.user) .then(function (response) { $scope.user = response.data.user; $scope.user.favs = response.data.favs; }, function (response) { console.log('error', response); }); userService.getPosts($routeParams.user) .then(function (response) { $scope.posts = response.data.posts; $scope.page.loading = false; $scope.posts.forEach(function (el) { favoritePost.checkFav(el); }); }, function (response) { $scope.page.loading = false; console.log('Error:', response.status, response.statusText); }); }]);
'use strict'; app.controller('UserProfileController', ['userService', '$routeParams', '$scope', 'favoritePost', function (userService, $routeParams, $scope, favoritePost) { $scope.size = "sm"; $scope.user = {}; $scope.imageSrc = ''; userService.getDetails($routeParams.user) .then(function (response) { $scope.user = response.data.user; $scope.user.favs = response.data.favs; }, function (response) { console.log('error', response); }); userService.getPosts($routeParams.user) .then(function (response) { $scope.posts = response.data.posts; $scope.page.loading = false; $scope.posts.forEach(function (el) { favoritePost.checkFav(el); }); }, function (response) { console.log('Error:', response.status, response.statusText); }); }]);
Test a manifest with multiple files.
import os from bmi_tester.api import check_bmi def touch_file(fname): with open(fname, "w"): pass def test_bmi_check(tmpdir): with tmpdir.as_cwd(): touch_file("input.yaml") assert ( check_bmi( "bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"] ) == 0 ) def test_bmi_check_with_manifest_as_list(tmpdir): with tmpdir.as_cwd(): touch_file("input.yaml") assert ( check_bmi( "bmi_tester.bmi:Bmi", extra_args=["-vvv"], input_file="input.yaml", manifest=["input.yaml"], ) == 0 ) def test_bmi_check_with_manifest_as_string(tmpdir): with tmpdir.as_cwd(): with open("manifest.txt", "w") as fp: fp.write(os.linesep.join(["input.yaml", "data.dat"])) touch_file("input.yaml") touch_file("data.dat") assert ( check_bmi( "bmi_tester.bmi:Bmi", extra_args=["-vvv"], input_file="input.yaml", manifest="manifest.txt", ) == 0 )
from bmi_tester.api import check_bmi def test_bmi_check(tmpdir): with tmpdir.as_cwd(): with open("input.yaml", "w"): pass assert ( check_bmi( "bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"] ) == 0 ) def test_bmi_check_with_manifest_as_list(tmpdir): with tmpdir.as_cwd(): with open("input.yaml", "w"): pass assert ( check_bmi( "bmi_tester.bmi:Bmi", extra_args=["-vvv"], input_file="input.yaml", manifest=["input.yaml"], ) == 0 ) def test_bmi_check_with_manifest_as_string(tmpdir): with tmpdir.as_cwd(): with open("manifest.txt", "w") as fp: fp.write("input.yaml") with open("input.yaml", "w"): pass assert ( check_bmi( "bmi_tester.bmi:Bmi", extra_args=["-vvv"], input_file="input.yaml", manifest="manifest.txt", ) == 0 )
Improve error handling for service retrieval
var request = require('request'); var async = require('async'); var Service = require('./service.js'); module.exports = function(uri){ this.uri = uri; this.getServices = function(callback){ request.get(this.uri + '/zosConnect/services', function(error, response, body){ if(error){ callback(error, null); } else if(response.statusCode != 200){ callback(new Error('Failed to get list of services (' + response.statusCode + ')'), null); } else { var json = JSON.parse(body); var services = []; var asyncTasks = []; json.zosConnectServices.forEach(function(service){ asyncTasks.push(function(asyncCallback){ services.push(service.ServiceName); asyncCallback(); }) }) async.parallel(asyncTasks, function(){ callback(null, services); }) } }) } this.getService = function(serviceName, callback){ request.get(this.uri + '/zosConnect/services/' + serviceName, function(error, response, body){ if(error){ callback(error, null); } else if(response.statusCode != 200){ callback(new Error('Unable to get service (' + response.statusCode + ')'), null); } else { var serviceData = JSON.parse(body); callback(null, new Service(this.uri, serviceName, serviceData.zosConnect.serviceInvokeURL)); } }) } }
var request = require('request'); var async = require('async'); var Service = require('./service.js'); module.exports = function(uri){ this.uri = uri; this.getServices = function(callback){ request.get(this.uri + '/zosConnect/services', function(error, response, body){ if(error || response.statusCode != 200){ callback(error, null); } else { var json = JSON.parse(body); var services = []; var asyncTasks = []; json.zosConnectServices.forEach(function(service){ asyncTasks.push(function(asyncCallback){ services.push(service.ServiceName); asyncCallback(); }) }) async.parallel(asyncTasks, function(){ callback(null, services); }) } }) } this.getService = function(serviceName, callback){ request.get(this.uri + '/zosConnect/services/' + serviceName, function(error, response, body){ if(error || response.statusCode != 200){ callback(error, null); } else { var serviceData = JSON.parse(body); callback(null, new Service(this.uri, serviceName, serviceData.zosConnect.serviceInvokeURL)); } }) } }
Fix test case to account for method rename
import java.io.File; import org.opensim.modeling.*; class TestXsensDataReader { public static void test_XsensDataReader() { // Test creation and population of XsensDataReaderSettings object XsensDataReaderSettings settings = new XsensDataReaderSettings(); ExperimentalSensor nextSensor = new ExperimentalSensor("000_00B421AF", "shank"); settings.append_ExperimentalSensors(nextSensor); settings.set_trial_prefix(0, "MT_012005D6_031-"); // Test costruct XsensDataReader from a XsensDataReaderSettings object XsensDataReader xsensDataReader = new XsensDataReader(settings); // Make sure types returned by the xsensDataReader are usable in Java StdMapStringAbstractDataTable tables = xsensDataReader.read(""); // Check that custom accessors are available and return usable types // Only spot check of the table is done as actual testing of contents // lives in the C++ tests TimeSeriesTableVec3 accelTableTyped = IMUDataReader.getLinearAccelerationsTable(tables); assert accelTableTyped.getNumRows() == 3369; assert accelTableTyped.getNumColumns() == 1; assert accelTableTyped. getTableMetaDataString("DataRate").equals("100.000000"); } public static void main(String[] args) { test_XsensDataReader(); } };
import java.io.File; import org.opensim.modeling.*; class TestXsensDataReader { public static void test_XsensDataReader() { // Test creation and population of XsensDataReaderSettings object XsensDataReaderSettings settings = new XsensDataReaderSettings(); ExperimentalSensor nextSensor = new ExperimentalSensor("000_00B421AF", "shank"); settings.append_ExperimentalSensors(nextSensor); settings.set_trial_prefix(0, "MT_012005D6_031-"); // Test costruct XsensDataReader from a XsensDataReaderSettings object XsensDataReader xsensDataReader = new XsensDataReader(settings); // Make sure types returned by the xsensDataReader are usable in Java StdMapStringAbstractDataTable tables = xsensDataReader.readData(""); // Check that custom accessors are available and return usable types // Only spot check of the table is done as actual testing of contents // lives in the C++ tests TimeSeriesTableVec3 accelTableTyped = IMUDataReader.getLinearAccelerationsTable(tables); assert accelTableTyped.getNumRows() == 3369; assert accelTableTyped.getNumColumns() == 1; assert accelTableTyped. getTableMetaDataString("DataRate").equals("100.000000"); } public static void main(String[] args) { test_XsensDataReader(); } };
Fix to unicode problem in 3.2
from __future__ import absolute_import, unicode_literals import datetime, json from sqlalchemy import ( Column, Integer, Text, DateTime, ForeignKey, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, relationship, backref, ) from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(Text, unique=True) created_at = Column(DateTime, default=datetime.datetime.utcnow) address = relationship("Address", uselist=False, backref="user") def __init__(self, name): self.name = name def __str__(self): return "%s" % self.name def __repr__(self): return '<%s#%s>' % (self.__class__.__name__, self.id) class Address(Base): __tablename__ = 'addresses' id = Column(Integer, primary_key=True) description = Column(Text, unique=True) user_id = Column(Integer, ForeignKey('users.id')) def __init__(self, description): self.description = description def __str__(self): return "%s" % (self.id) def __repr__(self): return '<%s#%s>' % (self.__class__.__name__, self.id)
import datetime, json from sqlalchemy import ( Column, Integer, Text, DateTime, ForeignKey, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, relationship, backref, ) from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(Text, unique=True) created_at = Column(DateTime, default=datetime.datetime.utcnow) address = relationship("Address", uselist=False, backref="user") def __init__(self, name): self.name = name def __str__(self): return u"%s" % self.name def __repr__(self): return '<%s#%s>' % (self.__class__.__name__, self.id) class Address(Base): __tablename__ = 'addresses' id = Column(Integer, primary_key=True) description = Column(Text, unique=True) user_id = Column(Integer, ForeignKey('users.id')) def __init__(self, description): self.description = description def __str__(self): return "%s" % (self.id) def __repr__(self): return '<%s#%s>' % (self.__class__.__name__, self.id)
Check returned value of non-stubbed method call
<?php namespace spec\rtens\mockster3; use rtens\mockster3\Mockster; use watoki\scrut\Specification; class CheckReturnTypeTest extends Specification { /** @var CheckReturnTypeTest_FooClass $mock */ private $mock; /** @var CheckReturnTypeTest_FooClass|Mockster $foo */ private $foo; protected function setUp() { parent::setUp(); $this->foo = new Mockster(CheckReturnTypeTest_FooClass::class); $this->mock = $this->foo->mock(); } function testAcceptAllIfNoTypeHintGiven() { Mockster::stub($this->foo->noHint())->will()->return_("foo"); Mockster::stub($this->foo->noHint())->will()->return_(42); $this->mock->noHint(); } function testFailIfPrimitiveValueDoesNotMatch() { Mockster::stub($this->foo->returnsString())->will()->return_(42); try { $this->mock->returnsString(); $this->fail("Should have thrown an exception"); } catch (\ReflectionException $e) { } $this->assertCount(1, Mockster::stub($this->foo->returnsString())->calls()); } function testFailIfNonStubbedValueDoesNotMatch() { Mockster::stub($this->foo->returnsString())->dontStub(); try { $this->mock->returnsString(); $this->fail("Should have thrown an exception"); } catch (\ReflectionException $e) { } $this->assertCount(1, Mockster::stub($this->foo->returnsString())->calls()); } } class CheckReturnTypeTest_FooClass { public function noHint() { return null; } /** * @return string */ public function returnsString() { return null; } }
<?php namespace spec\rtens\mockster3; use rtens\mockster3\Mockster; use watoki\scrut\Specification; class CheckReturnTypeTest extends Specification { /** @var CheckReturnTypeTest_FooClass $mock */ private $mock; /** @var CheckReturnTypeTest_FooClass|Mockster $foo */ private $foo; protected function setUp() { parent::setUp(); $this->foo = new Mockster(CheckReturnTypeTest_FooClass::class); $this->mock = $this->foo->mock(); } function testAcceptAllIfNoTypeHintGiven() { Mockster::stub($this->foo->noHint())->will()->return_("foo"); Mockster::stub($this->foo->noHint())->will()->return_(42); $this->mock->noHint(); } function testFailIfReturnedValuePrimitiveDoesNotMatch() { Mockster::stub($this->foo->returnsString())->will()->return_(42); try { $this->mock->returnsString(); $this->fail("Should have thrown an exception"); } catch (\ReflectionException $e) { } $this->assertCount(1, Mockster::stub($this->foo->returnsString())->calls()); } } class CheckReturnTypeTest_FooClass { public function noHint() { return null; } /** * @return string */ public function returnsString() { return null; } }