text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix for finding Beyond Compare 4 on Windows (don't unconditionally overwrite with BC3 path)
var autils = require('../../AUtils'); var osTool = require('../../osTools'); var shelljs = require('shelljs'); var GenericDiffReporterBase = require('../GenericDiffReporterBase'); module.exports = GenericDiffReporterBase.create(function () { this.name = "BeyondCompare"; var app = null; if (osTool.platform.isMac) { try { app = shelljs.ls('/Applications/Beyond Compare.app/Contents/MacOS/bcomp')[0]; } catch (err) { console.error(err); } app = app || autils.searchForExecutable("bcomp"); } else if (osTool.platform.isWindows) { app = autils.searchForExecutable("Beyond Compare 4", "BCompare.exe") || autils.searchForExecutable("Beyond Compare 3", "BCompare.exe"); } app = app || autils.searchForExecutable("bcomp"); this.exePath = app; });
var autils = require('../../AUtils'); var osTool = require('../../osTools'); var shelljs = require('shelljs'); var GenericDiffReporterBase = require('../GenericDiffReporterBase'); module.exports = GenericDiffReporterBase.create(function () { this.name = "BeyondCompare"; var app = null; if (osTool.platform.isMac) { try { app = shelljs.ls('/Applications/Beyond Compare.app/Contents/MacOS/bcomp')[0]; } catch (err) { console.error(err); } app = app || autils.searchForExecutable("bcomp"); } else if (osTool.platform.isWindows) { app = autils.searchForExecutable("Beyond Compare 4", "BCompare.exe"); app = autils.searchForExecutable("Beyond Compare 3", "BCompare.exe"); } app = app || autils.searchForExecutable("bcomp"); this.exePath = app; });
Change assertInstanceOf to assertTrue for PHP5.4
<?php namespace IVIR3aM\GraphicEditor\Tests\Colors; use IVIR3aM\GraphicEditor\ColorInterface; use IVIR3aM\GraphicEditor\Colors\FlyweightFactory; use PHPUnit\Framework\TestCase; class FlyweightFactoryTest extends TestCase { /** * @var FlyweightFactory */ private $factory; public function setUp() { $this->factory = new FlyweightFactory(); } public function testFactory() { $color = $this->factory->getColor(255, 512, 120); $this->assertTrue($color instanceof ColorInterface); $this->assertSame($color, $this->factory->getColor(255, 255, 120)); $this->assertSame($color->getRed(), 255); $this->assertSame($color->getGreen(), 255); $this->assertSame($color->getBlue(), 120); } }
<?php namespace IVIR3aM\GraphicEditor\Tests\Colors; use IVIR3aM\GraphicEditor\ColorInterface; use IVIR3aM\GraphicEditor\Colors\FlyweightFactory; use PHPUnit\Framework\TestCase; class FlyweightFactoryTest extends TestCase { /** * @var FlyweightFactory */ private $factory; public function setUp() { $this->factory = new FlyweightFactory(); } public function testFactory() { $color = $this->factory->getColor(255, 512, 120); $this->assertInstanceOf(ColorInterface::class, $color); $this->assertSame($color, $this->factory->getColor(255, 255, 120)); $this->assertSame($color->getRed(), 255); $this->assertSame($color->getGreen(), 255); $this->assertSame($color->getBlue(), 120); } }
Remove delay from loop for testing
import capture from picamera import PiCamera import time import delay def image_cap_loop(camera, status=None): """Set image parameters, capture image, set wait time, repeat""" resolution = (1640, 1232) # wait = delay.next_capture() # Delay time in seconds from delay.py wait = 60 waithours = wait / 60 / 60 # Convert seconds to hours print('Next capture begins in {} hours.'.format(waithours)) time.sleep(wait) images = 18 for i in range(images): latest = capture.cap(camera, resolution, status) status = latest[0] capture.copy_latest(latest[1]) time.sleep(300) status = camera.shutdown(camera) image_cap_loop(camera, status) return latest def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
import capture from picamera import PiCamera import time import delay def image_cap_loop(camera, status=None): """Set image parameters, capture image, set wait time, repeat""" resolution = (1640, 1232) wait = delay.next_capture() # Delay time in seconds from delay.py waithours = wait / 60 / 60 # Convert seconds to hours print('Next capture begins in {} hours.'.format(waithours)) time.sleep(wait) images = 18 for i in range(images): latest = capture.cap(camera, resolution, status) status = latest[0] capture.copy_latest(latest[1]) time.sleep(300) status = camera.shutdown(camera) image_cap_loop(camera, status) return latest def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
Add clint package to datacats requirements
#!/usr/bin/env python # Copyright 2014-2015 Boxkite Inc. # This file is part of the DataCats package and is released under # the terms of the GNU Affero General Public License version 3.0. # See LICENSE.txt or http://www.fsf.org/licensing/licenses/agpl-3.0.html from setuptools import setup import sys install_requires = [ 'setuptools', 'docopt', 'docker-py>=1.1.0', 'clint', # to output colored text to terminal 'requests>=2.5.2', # help with docker-py requirement ] exec(open("datacats/version.py").read()) setup( name='datacats', version=__version__, description='CKAN Data Catalog Developer Tools built on Docker', license='AGPL3', author='Boxkite', author_email='contact@boxkite.ca', url='https://github.com/datacats/datacats', packages=[ 'datacats', 'datacats.tests', 'datacats.cli', ], install_requires=install_requires, include_package_data=True, test_suite='datacats.tests', zip_safe=False, entry_points=""" [console_scripts] datacats=datacats.cli.main:main """, )
#!/usr/bin/env python # Copyright 2014-2015 Boxkite Inc. # This file is part of the DataCats package and is released under # the terms of the GNU Affero General Public License version 3.0. # See LICENSE.txt or http://www.fsf.org/licensing/licenses/agpl-3.0.html from setuptools import setup import sys install_requires=[ 'setuptools', 'docopt', 'docker-py>=1.1.0', 'requests>=2.5.2', # help with docker-py requirement ] exec(open("datacats/version.py").read()) setup( name='datacats', version=__version__, description='CKAN Data Catalog Developer Tools built on Docker', license='AGPL3', author='Boxkite', author_email='contact@boxkite.ca', url='https://github.com/datacats/datacats', packages=[ 'datacats', 'datacats.tests', 'datacats.cli', ], install_requires=install_requires, include_package_data=True, test_suite='datacats.tests', zip_safe=False, entry_points = """ [console_scripts] datacats=datacats.cli.main:main """, )
Split function declarations into multiple lines.
<?php namespace BFITech\ZapAdmin; /** * AdminRoute class. * * This is a thin layer than glues router and storage together. * Subclassess extend this instead of abstract AdminStore. * * @see AdminRouteDefault for limited example. */ class AdminRoute extends AdminStore { /** * Standard wrapper for Router::route. * * @param string $path Router path. * @param callable $callback Router callback. * @param string|array $method Router request method. * @param bool $is_raw If true, accept raw data instead of parsed */ public function route( $path, $callback, $method='GET', $is_raw=null ) { $this->core->route($path, function($args) use($callback){ # set token if available if (isset($args['cookie'][$this->token_name])) { # via cookie $this->adm_set_user_token( $args['cookie'][$this->token_name]); } elseif (isset($args['header']['authorization'])) { # via request header $auth = explode(' ', $args['header']['authorization']); if ($auth[0] == $this->token_name) { $this->adm_set_user_token($auth[1]); } } # execute calback $callback($args); }, $method, $is_raw); } }
<?php namespace BFITech\ZapAdmin; /** * AdminRoute class. * * This is a thin layer than glues router and storage together. * Subclassess extend this instead of abstract AdminStore. * * @see AdminRouteDefault for limited example. */ class AdminRoute extends AdminStore { /** * Standard wrapper for Router::route. * * @param string $path Router path. * @param callable $callback Router callback. * @param string|array $method Router request method. * @param bool $is_raw If true, accept raw data instead of parsed */ public function route($path, $callback, $method='GET', $is_raw=null) { $this->core->route($path, function($args) use($callback){ # set token if available if (isset($args['cookie'][$this->token_name])) { # via cookie $this->adm_set_user_token( $args['cookie'][$this->token_name]); } elseif (isset($args['header']['authorization'])) { # via request header $auth = explode(' ', $args['header']['authorization']); if ($auth[0] == $this->token_name) { $this->adm_set_user_token($auth[1]); } } # execute calback $callback($args); }, $method, $is_raw); } }
Add test_videos to the main test suite
# -*- coding: utf-8 -*- # Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com> # # This file is part of subliminal. # # subliminal is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # subliminal is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with subliminal. If not, see <http://www.gnu.org/licenses/>. from . import test_language, test_services, test_subliminal, test_videos import unittest suite = unittest.TestSuite([test_language.suite(), test_services.suite(), test_subliminal.suite(), test_videos.suite()]) if __name__ == '__main__': unittest.TextTestRunner().run(suite)
# -*- coding: utf-8 -*- # Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com> # # This file is part of subliminal. # # subliminal is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # subliminal is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with subliminal. If not, see <http://www.gnu.org/licenses/>. from . import test_language, test_services, test_subliminal import unittest suite = unittest.TestSuite([test_language.suite(), test_services.suite(), test_subliminal.suite()]) if __name__ == '__main__': unittest.TextTestRunner().run(suite)
Convert double quotes to single quotes
from setuptools import setup, find_packages import os ROOT = os.path.dirname(os.path.realpath(__file__)) setup( name='grab', version='0.6.30', description='Web Scraping Framework', long_description=open(os.path.join(ROOT, 'README.rst')).read(), url='http://grablib.org', author='Gregory Petukhov', author_email='lorien@lorien.name', packages=find_packages(exclude=['test', 'test.files']), install_requires=['lxml', 'pycurl', 'selection', 'weblib>=0.1.10', 'six', 'user_agent'], license='MIT', keywords='pycurl multicurl curl network parsing grabbing scraping' ' lxml xpath data mining', classifiers=( 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'License :: OSI Approved :: MIT License', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Internet :: WWW/HTTP', ), )
from setuptools import setup, find_packages import os ROOT = os.path.dirname(os.path.realpath(__file__)) setup( name='grab', version='0.6.30', description='Web Scraping Framework', long_description=open(os.path.join(ROOT, 'README.rst')).read(), url='http://grablib.org', author='Gregory Petukhov', author_email='lorien@lorien.name', packages=find_packages(exclude=['test', 'test.files']), install_requires=['lxml', 'pycurl', 'selection', 'weblib>=0.1.10', 'six', 'user_agent'], license="MIT", keywords="pycurl multicurl curl network parsing grabbing scraping" " lxml xpath data mining", classifiers=( 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'License :: OSI Approved :: MIT License', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Internet :: WWW/HTTP', ), )
Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Camtpcaomp # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Project closing", "version": "1.1", "author": "Camptocamp,Odoo Community Association (OCA)", "website": "http://www.camptocamp.com", "category": "project Management", "depends": ["project"], "description": """ Automatic account analytic closing when related project is closed. and If a projet is open, the related analytic account will be re-open. """, "data": [], 'installable': True, }
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Camtpcaomp # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Project closing", "version": "1.1", "author": "Camptocamp", "website": "http://www.camptocamp.com", "category": "project Management", "depends": ["project"], "description": """ Automatic account analytic closing when related project is closed. and If a projet is open, the related analytic account will be re-open. """, "data": [], 'installable': True, }
Enable debug mode for tests
<?php require_once __DIR__ . '/../vendor/autoload.php'; Tester\Environment::setup(); define('TEMP_DIR', __DIR__ . '/tmp/' . getmypid()); @mkdir(TEMP_DIR); @mkdir(TEMP_DIR . '/sessions'); $params = array('testingsqlitedb' => TEMP_DIR . '/db.sqlite'); $configurator = new Nette\Configurator; $configurator->setDebugMode(true); $configurator->setTempDirectory(TEMP_DIR); $configurator->addParameters($params); $configurator->createRobotLoader() ->addDirectory(__DIR__ . '/../app') ->register(); $configurator->addConfig(__DIR__ . '/../app/config/config.neon'); $configurator->addConfig(__DIR__ . '/config/db.neon'); $container = $configurator->createContainer(); $source = __DIR__ . '/db-image.sqlite'; $target = $params['testingsqlitedb']; Nette\Utils\FileSystem::copy($source, $target); return $container;
<?php require_once __DIR__ . '/../vendor/autoload.php'; Tester\Environment::setup(); define('TEMP_DIR', __DIR__ . '/tmp/' . getmypid()); @mkdir(TEMP_DIR); @mkdir(TEMP_DIR . '/sessions'); $params = array('testingsqlitedb' => TEMP_DIR . '/db.sqlite'); $configurator = new Nette\Configurator; $configurator->setDebugMode(false); $configurator->setTempDirectory(TEMP_DIR); $configurator->addParameters($params); $configurator->createRobotLoader() ->addDirectory(__DIR__ . '/../app') ->register(); $configurator->addConfig(__DIR__ . '/../app/config/config.neon'); $configurator->addConfig(__DIR__ . '/config/db.neon'); $container = $configurator->createContainer(); $source = __DIR__ . '/db-image.sqlite'; $target = $params['testingsqlitedb']; Nette\Utils\FileSystem::copy($source, $target); return $container;
Make sure to skip flags that are not available when testing constants Signed-off-by: Krzysztof Wilczyński <5f1c0be89013f8fde969a8dcb2fa1d522e94ee00@linux.com>
package magic import ( "testing" ) func TestConstants(t *testing.T) { var constantTests = []struct { given int expected []int }{ { MIME, []int{ MIME_TYPE, MIME_ENCODING, }, }, { NO_CHECK_ASCII, []int{ NO_CHECK_TEXT, }, }, { NO_CHECK_BUILTIN, []int{ NO_CHECK_COMPRESS, NO_CHECK_TAR, NO_CHECK_APPTYPE, NO_CHECK_ELF, NO_CHECK_TEXT, NO_CHECK_CSV, NO_CHECK_CDF, NO_CHECK_TOKENS, NO_CHECK_ENCODING, NO_CHECK_JSON, }, }, } for _, tt := range constantTests { expected := 0 for _, flag := range tt.expected { if flag > -1 { expected |= flag } } if tt.given != expected { t.Errorf("value given 0x%x, want 0x%x", tt.given, expected) } } } func TestParameters(t *testing.T) { }
package magic import ( "testing" ) func TestConstants(t *testing.T) { var constantTests = []struct { given int expected []int }{ { MIME, []int{ MIME_TYPE, MIME_ENCODING, }, }, { NO_CHECK_ASCII, []int{ NO_CHECK_TEXT, }, }, { NO_CHECK_BUILTIN, []int{ NO_CHECK_COMPRESS, NO_CHECK_TAR, NO_CHECK_APPTYPE, NO_CHECK_ELF, NO_CHECK_TEXT, NO_CHECK_CSV, NO_CHECK_CDF, NO_CHECK_TOKENS, NO_CHECK_ENCODING, NO_CHECK_JSON, }, }, } for _, tt := range constantTests { expected := 0 for _, flag := range tt.expected { expected |= flag } if tt.given != expected { t.Errorf("value given 0x%x, want 0x%x", tt.given, expected) } } } func TestParameters(t *testing.T) { }
Support class injection of elasticsearch
<?php namespace Cviebrock\LaravelElasticsearch; use Illuminate\Support\ServiceProvider as BaseServiceProvider; /** * Class ServiceProvider * * @package Cviebrock\LaravelElasticsearch */ class LumenServiceProvider extends BaseServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. * * @return void */ public function register() { $app = $this->app; $app->singleton('elasticsearch.factory', function($app) { return new Factory(); }); $app->singleton('elasticsearch', function($app) { return new LumenManager($app, $app['elasticsearch.factory']); }); $app->alias('elasticsearch', LumenManager::class); $this->withFacades(); } protected function withFacades() { class_alias('\Cviebrock\LaravelElasticsearch\Facade', 'Elasticsearch'); } }
<?php namespace Cviebrock\LaravelElasticsearch; use Illuminate\Support\ServiceProvider as BaseServiceProvider; /** * Class ServiceProvider * * @package Cviebrock\LaravelElasticsearch */ class LumenServiceProvider extends BaseServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. * * @return void */ public function register() { $app = $this->app; $app->singleton('elasticsearch.factory', function($app) { return new Factory(); }); $app->singleton('elasticsearch', function($app) { return new LumenManager($app, $app['elasticsearch.factory']); }); $this->withFacades(); } protected function withFacades() { class_alias('\Cviebrock\LaravelElasticsearch\Facade', 'Elasticsearch'); } }
Remove version check in favor of import error check
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT']
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse if django.VERSION >= (1, 10): from django.utils.deprecation import MiddlewareMixin else: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT']
Fix test to support NoFeatureFlagFound.
from __future__ import with_statement import unittest from flask import Flask import flask_featureflags as feature_flags class TestOutsideRequestContext(unittest.TestCase): def test_checking_is_active_outside_request_context_returns_false(self): self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG")) def test_default_handler_returns_false_outside_request_context(self): self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG")) class TestBadlyConfiguredApplication(unittest.TestCase): def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self): # This simulates somebody calling is_active on a Flask app that was never # set up with this extension. Since this is somebody likely trying to install it, # make sure they get a nice, helpful error message test_app = Flask(__name__) with test_app.test_request_context("/"): self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG") def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self): # This case should only happen if somebody's being especially creative, but # I want to make sure it's well-behaved anyways. test_app = Flask(__name__) with test_app.test_request_context("/"): self.assertRaises(feature_flags.NoFeatureFlagFound, feature_flags.AppConfigFlagHandler, "BOGUS_FEATURE_FLAG")
from __future__ import with_statement import unittest from flask import Flask import flask_featureflags as feature_flags class TestOutsideRequestContext(unittest.TestCase): def test_checking_is_active_outside_request_context_returns_false(self): self.assertFalse(feature_flags.is_active("BOGUS_FEATURE_FLAG")) def test_default_handler_returns_false_outside_request_context(self): self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG")) class TestBadlyConfiguredApplication(unittest.TestCase): def test_checking_is_active_on_an_app_that_was_never_set_up_raises_assertion(self): # This simulates somebody calling is_active on a Flask app that was never # set up with this extension. Since this is somebody likely trying to install it, # make sure they get a nice, helpful error message test_app = Flask(__name__) with test_app.test_request_context("/"): self.assertRaises(AssertionError, feature_flags.is_active, "BOGUS_FEATURE_FLAG") def test_running_default_handler_on_app_that_was_never_set_up_returns_false(self): # This case should only happen if somebody's being especially creative, but # I want to make sure it's well-behaved anyways. test_app = Flask(__name__) with test_app.test_request_context("/"): self.assertFalse(feature_flags.AppConfigFlagHandler("BOGUS_FEATURE_FLAG"))
Update labelPrefix to include correct period. Not sure if we need to add a new test for this file, since this is so minor?
define([ 'stache!common/templates/visualisations/completion_numbers', 'extensions/views/view', 'common/views/visualisations/volumetrics/number', 'common/views/visualisations/volumetrics/submissions-graph' ], function (template, View, VolumetricsNumberView, SubmissionGraphView) { var CompletionNumbersView = View.extend({ template: template, views: function() { var period = this.collection.options.period || 'week'; return { '#volumetrics-submissions-selected': { view: VolumetricsNumberView, options: { valueAttr: 'mean', selectionValueAttr: 'uniqueEvents', labelPrefix: 'mean per ' + period + ' over the' } }, '#volumetrics-submissions': { view: SubmissionGraphView, options: { valueAttr:'uniqueEvents' } } }; } }); return CompletionNumbersView; });
define([ 'stache!common/templates/visualisations/completion_numbers', 'extensions/views/view', 'common/views/visualisations/volumetrics/number', 'common/views/visualisations/volumetrics/submissions-graph' ], function (template, View, VolumetricsNumberView, SubmissionGraphView) { var CompletionNumbersView = View.extend({ template: template, views: { '#volumetrics-submissions-selected': { view: VolumetricsNumberView, options: { valueAttr: 'mean', selectionValueAttr: 'uniqueEvents', labelPrefix: 'mean per week over the' } }, '#volumetrics-submissions': { view: SubmissionGraphView, options: { valueAttr:'uniqueEvents' } } } }); return CompletionNumbersView; });
Create an Angular Constant for vendor libraries' global variables. Item Y240 from John Papa style guide.
// The app /* global proj4:false, ol:false, THREE:false, POCLoader:false, Potree:false */ (function() { 'use strict'; /** * @ngdoc overview * @name pattyApp * @description * # pattyApp * * Main module of the application. */ angular .module('pattyApp', [ 'ngAnimate', 'ngSanitize', 'ngTouch', 'ui.bootstrap', 'pattyApp.searchbox', 'pattyApp.minimap', 'pattyApp.pointcloud' ]) .config(function() { }).run(function(SitesService, DrivemapService) { DrivemapService.load(); SitesService.load(); }); angular.module('pattyApp.templates', []); angular.module('pattyApp.utils', ['pattyApp.templates']); angular.module('pattyApp.core', ['pattyApp.utils']) .constant('proj4', proj4); angular.module('pattyApp.minimap', ['pattyApp.core']) .constant('ol', ol); angular.module('pattyApp.pointcloud', ['pattyApp.core']) .constant('THREE', THREE) .constant('POCLoader', POCLoader) .constant('Potree', Potree); angular.module('pattyApp.searchbox', ['pattyApp.core', 'pattyApp.pointcloud']); })();
'use strict'; /** * @ngdoc overview * @name pattyApp * @description * # pattyApp * * Main module of the application. */ angular .module('pattyApp', [ 'ngAnimate', 'ngSanitize', 'ngTouch', 'ui.bootstrap', 'pattyApp.searchbox', 'pattyApp.minimap', 'pattyApp.pointcloud' ]) .config(function() { }).run(function(SitesService, DrivemapService) { DrivemapService.load(); SitesService.load(); }); angular.module('pattyApp.templates', []); angular.module('pattyApp.utils', ['pattyApp.templates']); angular.module('pattyApp.core', ['pattyApp.utils']) .factory('proj4', function($window) { return $window.proj4; }); angular.module('pattyApp.minimap', ['pattyApp.core']) .factory('ol', function($window) { return $window.ol; }); angular.module('pattyApp.pointcloud', ['pattyApp.core']) .factory('THREE', function($window) { return $window.THREE; }) .factory('POCLoader', function($window) { return $window.POCLoader; }) .factory('Potree', function($window) { return $window.Potree; }); angular.module('pattyApp.searchbox', ['pattyApp.core', 'pattyApp.pointcloud']);
[input-date] Add the options from the doamin.
var jQuery = require('jquery'); //Dependencies. ////http://www.daterangepicker.com/#ex2 var builder = require('focus').component.builder; var React = require('react'); var inputTextMixin = require('../text').mixin; let assign = require('object-assign'); /** * Input text mixin. * @type {Object} */ var inputDateMixin = { /** @inheritdoc */ mixins: [inputTextMixin], /** @inheritdoc */ componentDidMount: function inputDateDidMount(){ if(!jQuery.fn.daterangepicker){ console.warn('The jquery daterangepicker plugin should be loaded: see https://github.com/dangrossman/bootstrap-daterangepicker.'); } var component = this; //If the domains set options. let propsOptions = this.props.options && this.props.options.dateRangePicker ? this.props.options.dateRangePicker : {}; console.log('parentEL............', `div [data-reactid="${React.findDOMNode(this).getAttribute('data-reactid')}"]`); let dateRangeOptions = assign( propsOptions, { parentEl: `div [data-reactid="${React.findDOMNode(this).getAttribute('data-reactid')}"]`, singleDatePicker: true, showDropdowns: true }); jQuery(React.findDOMNode(this)).daterangepicker(dateRangeOptions, function(start){ ///*, end, label*/ component.setState({value: component.props.formatter(start.toDate())}); }); } }; module.exports = builder(inputDateMixin);
var jQuery = require('jquery'); //Dependencies. ////http://www.daterangepicker.com/#ex2 var builder = require('focus').component.builder; var React = require('react'); var inputTextMixin = require('../text').mixin; /** * Input text mixin. * @type {Object} */ var inputDateMixin = { /** @inheritdoc */ mixins: [inputTextMixin], /** @inheritdoc */ componentDidMount: function inputDateDidMount(){ if(!jQuery.fn.daterangepicker){ console.warn('The jquery daterangepicker plugin should be loaded: see https://github.com/dangrossman/bootstrap-daterangepicker.'); } var component = this; jQuery(React.findDOMNode(this)).daterangepicker({ singleDatePicker: true, showDropdowns: true }, function(start){ ///*, end, label*/ component.setState({value: component.props.formatter(start.toDate())}); }); } }; module.exports = builder(inputDateMixin);
Update expected results of generated liting
// Package main is used for testing of generated 'views' listing. // There is no way to include a new import dynamically, thus // we are running this test from generate_test.go // as a new command using exec package. package main import ( "../assets/views" "github.com/anonx/sunplate/log" ) func main() { if l := len(views.Context); l != 2 { log.Error.Fatalf("Length of views.Context expected to be equal to 2, it is %d instead.", l) } // // Make sure templates are presented in the format we expect. // for k, v := range expectedValues { if views.Context[k] != v { log.Error.Fatalf("'%s' wasn't found in %#v.", k, views.Context) } } } var expectedValues = map[string]string{ "test1.template": "testdata/views/test1.template", "test2.template": "testdata/views/test2.template", }
// Package main is used for testing of generated 'views' listing. // There is no way to include a new import dynamically, thus // we are running this test from generate_test.go // as a new command using exec package. package main import ( "../assets/views" "github.com/anonx/sunplate/log" ) func main() { if l := len(views.Context); l != 2 { log.Error.Fatalf("Length of views.Context expected to be equal to 2, it is %d instead.", l) } // // Make sure templates are presented in the format we expect. // for k, v := range expectedValues { if views.Context[k] != v { log.Error.Fatalf("'%s' wasn't found in %#v.", k, views.Context) } } } var expectedValues = map[string]string{ "testdata/views/test1.template": "testdata/views/test1.template", "testdata/views/test2.template": "testdata/views/test2.template", }
Add InstanceId, also added to EnvironProvider while we were implementing.
package maas import ( "launchpad.net/juju-core/environs" "launchpad.net/juju-core/environs/config" "launchpad.net/juju-core/log" ) type maasEnvironProvider struct{} var _ environs.EnvironProvider = (*maasEnvironProvider)(nil) var providerInstance maasEnvironProvider func init() { environs.RegisterProvider("maas", &providerInstance) } func (*maasEnvironProvider) Open(cfg *config.Config) (environs.Environ, error) { log.Printf("environs/maas: opening environment %q.", cfg.Name()) return NewEnviron(cfg) } // BoilerplateConfig is specified in the EnvironProvider interface. func (*maasEnvironProvider) BoilerplateConfig() string { panic("Not implemented.") } // SecretAttrs is specified in the EnvironProvider interface. func (*maasEnvironProvider) SecretAttrs(*config.Config) (map[string]interface{}, error) { panic("Not implemented.") } // PublicAddress is specified in the EnvironProvider interface. func (*maasEnvironProvider) PublicAddress() (string, error) { panic("Not implemented.") } // PrivateAddress is specified in the EnvironProvider interface. func (*maasEnvironProvider) PrivateAddress() (string, error) { panic("Not implemented.") } // InstanceId is specified in the EnvironProvider interface. func (*maasEnvironProvider) InstanceId() (state.InstanceId, error) { panic("Not implemented.") }
package maas import ( "launchpad.net/juju-core/environs" "launchpad.net/juju-core/environs/config" "launchpad.net/juju-core/log" ) type maasEnvironProvider struct{} var _ environs.EnvironProvider = (*maasEnvironProvider)(nil) var providerInstance maasEnvironProvider func init() { environs.RegisterProvider("maas", &providerInstance) } func (*maasEnvironProvider) Open(cfg *config.Config) (environs.Environ, error) { log.Printf("environs/maas: opening environment %q.", cfg.Name()) return NewEnviron(cfg) } // BoilerplateConfig is specified in the EnvironProvider interface. func (*maasEnvironProvider) BoilerplateConfig() string { panic("Not implemented.") } // SecretAttrs is specified in the EnvironProvider interface. func (*maasEnvironProvider) SecretAttrs(*config.Config) (map[string]interface{}, error) { panic("Not implemented.") } // PublicAddress is specified in the EnvironProvider interface. func (*maasEnvironProvider) PublicAddress() (string, error) { panic("Not implemented.") } // PrivateAddress is specified in the EnvironProvider interface. func (*maasEnvironProvider) PrivateAddress() (string, error) { panic("Not implemented.") }
Use github repo as package url.
import codecs from os.path import join, dirname from setuptools import setup, find_packages version = '1.0dev' read = lambda *rnames: unicode(codecs.open(join(dirname(__file__), *rnames), encoding='utf-8').read()).strip() setup( name='sourcebuilder', version=version, description='Generate (python) code using python', long_description='\n\n'.join((read('README.rst'), read('CHANGES.rst'),)), author='Jaap Roes', author_email='jaap.roes@gmail.com', url='https://github.com/jaap3/sourcebuilder', packages=find_packages(), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], tests_require=['unittest2==0.5.1'], test_suite='unittest2.collector', zip_safe=False, )
import codecs from os.path import join, dirname from setuptools import setup, find_packages version = '1.0dev' read = lambda *rnames: unicode(codecs.open(join(dirname(__file__), *rnames), encoding='utf-8').read()).strip() setup( name='sourcebuilder', version=version, description='Generate (python) code using python', long_description='\n\n'.join((read('README.rst'), read('CHANGES.rst'),)), author='Jaap Roes', author_email='jaap.roes@gmail.com', url='', packages=find_packages(), license='MIT', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], tests_require=['unittest2==0.5.1'], test_suite='unittest2.collector', zip_safe=False, )
Make sure integration tests call super.
# -*- coding: utf-8 -*- # # OpenCraft -- tools to aid developing and hosting free software projects # Copyright (C) 2015 OpenCraft <xavier@opencraft.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Tests - Integration - Base """ # Imports ##################################################################### from huey import djhuey from instance.models.server import OpenStackServer from instance.tests.base import TestCase # Tests ####################################################################### class IntegrationTestCase(TestCase): """ Base class for API tests """ def setUp(self): super().setUp() # Override the environment setting - always run task in the same process djhuey.HUEY.always_eager = True def tearDown(self): OpenStackServer.objects.terminate() super().tearDown()
# -*- coding: utf-8 -*- # # OpenCraft -- tools to aid developing and hosting free software projects # Copyright (C) 2015 OpenCraft <xavier@opencraft.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Tests - Integration - Base """ # Imports ##################################################################### from huey import djhuey from instance.models.server import OpenStackServer from instance.tests.base import TestCase # Tests ####################################################################### class IntegrationTestCase(TestCase): """ Base class for API tests """ def setUp(self): # Override the environment setting - always run task in the same process djhuey.HUEY.always_eager = True def tearDown(self): # Ensure we don't leave any VM running OpenStackServer.objects.terminate()
Make makemigrations verbose in ./runtests.py -v
#!/usr/bin/env python import os, sys, re, shutil os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' import django from django.core.management import call_command names_prefix = 'tests.tests' if django.VERSION >= (1, 6) else 'tests' names = next((a for a in sys.argv[1:] if not a.startswith('-')), None) if names and re.search(r'^\d+$', names): names = names_prefix + '.IssueTests.test_' + names elif names and not names.startswith('tests.'): names = names_prefix + '.' + names else: names = names_prefix if hasattr(django, 'setup'): django.setup() # NOTE: we create migrations each time since they depend on type of database, # python and django versions try: if django.VERSION >= (1, 7): shutil.rmtree('tests/migrations', True) call_command('makemigrations', 'tests', verbosity=2 if '-v' in sys.argv else 0) call_command('test', names, failfast='-x' in sys.argv, verbosity=2 if '-v' in sys.argv else 1) finally: shutil.rmtree('tests/migrations')
#!/usr/bin/env python import os, sys, re, shutil os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' import django from django.core.management import call_command names_prefix = 'tests.tests' if django.VERSION >= (1, 6) else 'tests' names = next((a for a in sys.argv[1:] if not a.startswith('-')), None) if names and re.search(r'^\d+$', names): names = names_prefix + '.IssueTests.test_' + names elif names and not names.startswith('tests.'): names = names_prefix + '.' + names else: names = names_prefix if hasattr(django, 'setup'): django.setup() # NOTE: we create migrations each time since they depend on type of database, # python and django versions try: if django.VERSION >= (1, 7): shutil.rmtree('tests/migrations', True) call_command('makemigrations', 'tests', verbosity=0) call_command('test', names, failfast='-x' in sys.argv, verbosity=2 if '-v' in sys.argv else 1) finally: shutil.rmtree('tests/migrations')
Use 1.0 branch for stable channel builders TBR=ricow Review URL: https://codereview.chromium.org/69023002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@234222 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 3), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.0', 2, '-stable', 1), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 3), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/0.8', 2, '-stable', 1), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
Fix bug in email confirmation scripts.
''' Send an email to users who haven't confirmed their passwords asking them to confirm. ''' import logging from community_share.models.user import User from community_share.models.share import Event from community_share.models.conversation import Conversation from community_share import mail_actions, config, store def send_reminders(): users = store.session.query(User).filter_by( active=True, email_confirmed=False).all() for user in users: template = mail_actions.CONFIRM_EMAIL_REMINDER_TEMPLATE subject = 'Please confirm email address.' mail_actions.request_signup_email_confirmation( user, template=template, subject=subject) if __name__ == '__main__': config.load_from_environment() logger = logging.getLogger(__name__) send_reminders()
''' Send an email to users who haven't confirmed their passwords asking them to confirm. ''' import logging from community_share.models.user import User from community_share.models.share import Event from community_share.models.conversation import Conversation from community_share import mail_actions, config, store def send_reminders(): users = store.session.query(User).filter_by( active=True, email_confirmed=True).all() for user in users: template = mail_actions.CONFIRM_EMAIL_REMINDER_TEMPLATE subject = 'Please confirm email address.' mail_actions.request_signup_email_confirmation( user, template=template, subject=subject) if __name__ == '__main__': config.load_from_environment() logger = logging.getLogger(__name__) send_reminders()
[tests] Use mdptoolbox.example.small in the tests
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small, R_small = mdptoolbox.example.small() P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix(P_small[0]) P_sparse[1] = sp.sparse.csr_matrix(P_small[1]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True)
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 14:44:07 2013 @author: steve """ import numpy as np import scipy as sp import mdptoolbox.example STATES = 10 ACTIONS = 3 SMALLNUM = 10e-12 # np.arrays P_small = np.array([[[0.5, 0.5],[0.8, 0.2]],[[0, 1],[0.1, 0.9]]]) R_small = np.array([[5, 10], [-1, 2]]) P_sparse = np.empty(2, dtype=object) P_sparse[0] = sp.sparse.csr_matrix([[0.5, 0.5],[0.8, 0.2]]) P_sparse[1] = sp.sparse.csr_matrix([[0, 1],[0.1, 0.9]]) P_forest, R_forest = mdptoolbox.example.forest() P_forest_sparse, R_forest_sparse = mdptoolbox.example.forest(S=STATES, is_sparse=True) np.random.seed(0) P_rand, R_rand = mdptoolbox.example.rand(STATES, ACTIONS) np.random.seed(0) P_rand_sparse, R_rand_sparse = mdptoolbox.example.rand(STATES, ACTIONS, is_sparse=True)
Comment out what can't be checked
import pytest from gitlabform.gitlabform import GitLabForm from gitlabform.gitlabform.test import create_group, create_project_in_group, get_gitlab, GROUP_NAME PROJECT_NAME = 'project_settings_project' GROUP_AND_PROJECT_NAME = GROUP_NAME + '/' + PROJECT_NAME @pytest.fixture(scope="module") def gitlab(request): create_group(GROUP_NAME) create_project_in_group(GROUP_NAME, PROJECT_NAME) gl = get_gitlab() def fin(): gl.delete_project(GROUP_AND_PROJECT_NAME) request.addfinalizer(fin) return gl # provide fixture value config_builds_for_private_projects = """ gitlab: api_version: 4 project_settings: project_settings: builds_access_level: private visibility: private """ class TestProjectSettings: def test__builds_for_private_projects(self, gitlab): gf = GitLabForm(config_string=config_builds_for_private_projects, project_or_group=GROUP_AND_PROJECT_NAME) gf.main() settings = gitlab.get_project_settings(GROUP_AND_PROJECT_NAME) assert settings['visibility'] is 'private' # there is no such field in the "Get single project" API :/ #assert settings['builds_access_level'] is 'private'
import pytest from gitlabform.gitlabform import GitLabForm from gitlabform.gitlabform.test import create_group, create_project_in_group, get_gitlab, GROUP_NAME PROJECT_NAME = 'project_settings_project' GROUP_AND_PROJECT_NAME = GROUP_NAME + '/' + PROJECT_NAME @pytest.fixture(scope="module") def gitlab(request): create_group(GROUP_NAME) create_project_in_group(GROUP_NAME, PROJECT_NAME) gl = get_gitlab() def fin(): gl.delete_project(GROUP_AND_PROJECT_NAME) request.addfinalizer(fin) return gl # provide fixture value config_builds_for_private_projects = """ gitlab: api_version: 4 project_settings: project_settings: builds_access_level: private visibility: private """ class TestProjectSettings: def test__builds_for_private_projects(self, gitlab): gf = GitLabForm(config_string=config_builds_for_private_projects, project_or_group=GROUP_AND_PROJECT_NAME) gf.main() settings = gitlab.get_project_settings(GROUP_AND_PROJECT_NAME) assert settings['builds_access_level'] is 'private' assert settings['visibility'] is 'private'
Make math method wrapping nicer
from functools import wraps import operator def math_method(name, right=False): math_func = getattr(operator, name) @wraps(math_func) def wrapper(self, other): value = self.value if right: value, other = other, value result = math_func(value, other) return type(self)(result, units=self.units) return wrapper class MimicFloat(type): math_methods = ('__add__', '__sub__', '__mul__', '__truediv__') math_rmethods = ('__radd__', '__rsub__', '__rmul__', '__rtruediv__') def __new__(cls, name, bases, namespace): for method in cls.math_methods: namespace[method] = math_method(method) for rmethod in cls.math_rmethods: method = rmethod.replace('__r', '__') namespace[rmethod] = math_method(method, right=True) return super(MimicFloat, cls).__new__(cls, name, bases, namespace)
import operator def math_method(name, right=False): def wrapper(self, other): value = self.value math_func = getattr(operator, name) if right: value, other = other, value result = math_func(value, other) return type(self)(result, units=self.units) return wrapper class MimicFloat(type): overrride_methods = ('__add__', '__sub__', '__mul__', '__truediv__') overrride_rmethods = ('__radd__', '__rsub__', '__rmul__', '__rtruediv__') def __new__(cls, name, bases, namespace): for method in cls.overrride_methods: namespace[method] = math_method(method) for rmethod in cls.overrride_rmethods: method = rmethod.replace('__r', '__') namespace[rmethod] = math_method(method, right=True) return super(MimicFloat, cls).__new__(cls, name, bases, namespace)
Fix tool bug using old interface
/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.commons.tools; import org.apache.commons.cli.CommandLine; /** * * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> */ public interface Tool { /** * Get the command of the tool. */ Command getCommand(); /** * Run the tool. * * @param line the command line arguments * @param context tool execution context * @throws Exception if the command fails */ default void run(CommandLine line, ToolRunningContext context) throws Exception { run(line); } @Deprecated default void run(CommandLine line) throws Exception { } }
/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.commons.tools; import org.apache.commons.cli.CommandLine; /** * * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> */ public interface Tool { /** * Get the command of the tool. */ Command getCommand(); /** * Run the tool. * * @param line the command line arguments * @param context tool execution context * @throws Exception if the command fails */ default void run(CommandLine line, ToolRunningContext context) throws Exception { } @Deprecated default void run(CommandLine line) throws Exception { run(line, new ToolRunningContext()); } }
Revert "Use NetSimple source bits path" This reverts commit 5d8cf1b3039723bb8de903b6dcfb82482d5dbac1.
package smoke import ( "time" "github.com/cloudfoundry-incubator/cf-test-helpers/cf" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" ) const ( SimpleBinaryAppBitsPath = "../../assets/binary" SimpleDotnetAppBitsPath = "../../assets/dotnet_simple/Published" ) func SkipIfNotWindows(testConfig *Config) { if !testConfig.EnableWindowsTests { Skip("Windows tests are disabled") } } func AppReport(appName string, timeout time.Duration) { Eventually(cf.Cf("app", appName, "--guid"), timeout).Should(Exit()) Eventually(cf.Cf("logs", appName, "--recent"), timeout).Should(Exit()) } func Logs(useLogCache bool, appName string) *Session { if useLogCache { return cf.Cf("tail", appName, "--lines", "125") } return cf.Cf("logs", "--recent", appName) }
package smoke import ( "time" "github.com/cloudfoundry-incubator/cf-test-helpers/cf" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gexec" ) const ( SimpleBinaryAppBitsPath = "../../assets/binary" SimpleDotnetAppBitsPath = "../../assets/dotnet_simple/NetSimple" ) func SkipIfNotWindows(testConfig *Config) { if !testConfig.EnableWindowsTests { Skip("Windows tests are disabled") } } func AppReport(appName string, timeout time.Duration) { Eventually(cf.Cf("app", appName, "--guid"), timeout).Should(Exit()) Eventually(cf.Cf("logs", appName, "--recent"), timeout).Should(Exit()) } func Logs(useLogCache bool, appName string) *Session { if useLogCache { return cf.Cf("tail", appName, "--lines", "125") } return cf.Cf("logs", "--recent", appName) }
Fix bug with negative counts
#!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the freqQuery function below. def freqQuery(queries): output = [] array = [] occurences = Counter() frequencies = Counter() for operation, value in queries: if (operation == 1): frequencies[occurences[value]] -= 1 occurences[value] += 1 frequencies[occurences[value]] += 1 elif (operation == 2): if (occurences[value] > 0): frequencies[occurences[value]] -= 1 occurences[value] -= 1 frequencies[occurences[value]] += 1 elif (operation == 3): if frequencies[value] > 0: output.append(1) else: output.append(0) # print(occurences) # print(frequencies) return output if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input().strip()) queries = [] for _ in range(q): queries.append(list(map(int, input().rstrip().split()))) ans = freqQuery(queries) fptr.write('\n'.join(map(str, ans))) fptr.write('\n') fptr.close()
#!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the freqQuery function below. def freqQuery(queries): output = [] occurences = Counter() frequencies = Counter() for operation, value in queries: if (operation == 1): frequencies[occurences[value]] -= 1 occurences[value] += 1 frequencies[occurences[value]] += 1 elif (operation == 2): frequencies[occurences[value]] -= 1 occurences[value] -= 1 frequencies[occurences[value]] += 1 elif (operation == 3): if frequencies[value] > 0: output.append(1) else: output.append(0) print(occurences) print(frequencies) return output if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input().strip()) queries = [] for _ in range(q): queries.append(list(map(int, input().rstrip().split()))) ans = freqQuery(queries) fptr.write('\n'.join(map(str, ans))) fptr.write('\n') fptr.close()
Add comments for clarity. [rev: trivial]
define([ 'jquery' ], function() { return function selectElement(selector) { var el = $(selector); if (!el.length) { return false; } // real browsers if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); var range = document.createRange(); range.selectNodeContents(el[0]); sel.addRange(range); return true; } else if (document.selection) { // IE < 9 var textRange = document.body.createTextRange(); textRange.moveToElementText(el[0]); textRange.select(); return true; } return false; }; });
define([ 'jquery' ], function() { return function selectElement(selector) { var el = $(selector); if (!el.length) { return false; } if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); var range = document.createRange(); range.selectNodeContents(el[0]); sel.addRange(range); return true; } else if (document.selection) { var textRange = document.body.createTextRange(); textRange.moveToElementText(el[0]); textRange.select(); return true; } return false; }; });
Check for promise.then instead of using instanceof When using polyfills for Promise, different polyfills have different implementations of Promise. An `instanceof` check can lead to unexpected results.
const isFunction = require('lodash.isfunction'); const invariant = require('invariant'); let oldJasmineFns = {it, fit, xit, beforeEach, afterEach, beforeAll, afterAll}; function withAsync(fns) { return Object.keys(fns).reduce((memo, name) => { memo[name] = fns[name]; memo[name].async = function(...args) { const callback = args.pop(); invariant(isFunction(callback), `${name} must be provided a function!`); return (fns[name])(...args, done => { const promise = this::callback(); invariant(promise && isFunction(promise.then), `${name} must return a promise!`); promise.then(done, done.fail); }); }; return memo; }, {}); } module.exports = { install() { Object.assign(global, {...withAsync(oldJasmineFns)}); }, uninstall() { Object.assign(global, oldJasmineFns); } };
const isFunction = require('lodash.isfunction'); const invariant = require('invariant'); let oldJasmineFns = {it, fit, xit, beforeEach, afterEach, beforeAll, afterAll}; function withAsync(fns) { return Object.keys(fns).reduce((memo, name) => { memo[name] = fns[name]; memo[name].async = function(...args) { const callback = args.pop(); invariant(isFunction(callback), `${name} must be provided a function!`); return (fns[name])(...args, done => { const promise = this::callback(); invariant(promise instanceof Promise, `${name} must return a promise!`); promise.then(done, done.fail); }); }; return memo; }, {}); } module.exports = { install() { Object.assign(global, {...withAsync(oldJasmineFns)}); }, uninstall() { Object.assign(global, oldJasmineFns); } };
Internal: Add lambda-match to plugins macros.
const gulp = require('gulp'); const sweetjs = require("gulp-sweetjs"); const sourcemaps = require('gulp-sourcemaps'); const concat = require('gulp-concat-util'); // Macro packages. const match = "sparkler/macros"; const lambda = "lambda-chop/macros"; const bdd = "sweet-bdd"; gulp.task('default', function() { console.log("Use either the 'build' or 'test' tasks"); }); gulp.task("build", function () { function pipeline (from, to, macros) { gulp.src("src/" + from + "/**/*.sjs") .pipe(sourcemaps.init()) .pipe(sweetjs({ modules: macros, readableNames: true })) .pipe(sourcemaps.write("../sourcemaps/" + from)) .pipe(gulp.dest(to)) } pipeline("lib", "lib", [match, lambda]); pipeline("plugin", "tennu_plugins", [match, lambda]); pipeline("test", "test", [bdd]); gulp.src("src/bin/**/*.sjs") .pipe(sourcemaps.init()) .pipe(sweetjs({ modules: [], readableNames: true })) .pipe(concat.header("#! /usr/bin/env node\n\n")) .pipe(sourcemaps.write("../sourcemaps/bin")) .pipe(gulp.dest("bin")) });
const gulp = require('gulp'); const sweetjs = require("gulp-sweetjs"); const sourcemaps = require('gulp-sourcemaps'); const concat = require('gulp-concat-util'); // Macro packages. const match = "sparkler/macros"; const lambda = "lambda-chop/macros"; const bdd = "sweet-bdd"; gulp.task('default', function() { console.log("Use either the 'build' or 'test' tasks"); }); gulp.task("build", function () { function pipeline (from, to, macros) { gulp.src("src/" + from + "/**/*.sjs") .pipe(sourcemaps.init()) .pipe(sweetjs({ modules: macros, readableNames: true })) .pipe(sourcemaps.write("../sourcemaps/" + from)) .pipe(gulp.dest(to)) } pipeline("lib", "lib", [match, lambda]); pipeline("plugin", "tennu_plugins", [match]); pipeline("test", "test", [bdd]); gulp.src("src/bin/**/*.sjs") .pipe(sourcemaps.init()) .pipe(sweetjs({ modules: [], readableNames: true })) .pipe(concat.header("#! /usr/bin/env node\n\n")) .pipe(sourcemaps.write("../sourcemaps/bin")) .pipe(gulp.dest("bin")) });
Fix "Model loaded" messages appearing when animating
package de.prob2.ui.consoles.b; import java.io.File; import java.util.ResourceBundle; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.consoles.Console; import de.prob2.ui.prob2fx.CurrentTrace; @Singleton public final class BConsole extends Console { @Inject private BConsole(BInterpreter bInterpreter, ResourceBundle bundle, CurrentTrace currentTrace) { super(bundle, bundle.getString("consoles.b.header"), bundle.getString("consoles.b.prompt.classicalB"), bInterpreter); currentTrace.stateSpaceProperty().addListener((o, from, to) -> { final String message; if (to == null) { message = bundle.getString("consoles.b.message.modelUnloaded"); } else { final File modelFile = to.getModel().getModelFile(); final String name = modelFile == null ? to.getMainComponent().toString() : modelFile.getName(); message = String.format(bundle.getString("consoles.b.message.modelLoaded"), name); } this.insertText(this.getLineNumber(), 0, message + '\n'); this.requestFollowCaret(); }); } }
package de.prob2.ui.consoles.b; import java.io.File; import java.util.ResourceBundle; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.consoles.Console; import de.prob2.ui.prob2fx.CurrentTrace; @Singleton public final class BConsole extends Console { @Inject private BConsole(BInterpreter bInterpreter, ResourceBundle bundle, CurrentTrace currentTrace) { super(bundle, bundle.getString("consoles.b.header"), bundle.getString("consoles.b.prompt.classicalB"), bInterpreter); currentTrace.addListener((o, from, to) -> { final String message; if (to == null) { message = bundle.getString("consoles.b.message.modelUnloaded"); } else { final File modelFile = to.getStateSpace().getModel().getModelFile(); final String name = modelFile == null ? to.getStateSpace().getMainComponent().toString() : modelFile.getName(); message = String.format(bundle.getString("consoles.b.message.modelLoaded"), name); } this.insertText(this.getLineNumber(), 0, message + '\n'); this.requestFollowCaret(); }); } }
Fix erroneous PropTypes access warning
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUMDEntry */ 'use strict'; var React = require('React'); // `version` will be added here by the React module. var ReactUMDEntry = Object.assign(React, { __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { ReactCurrentOwner: require('ReactCurrentOwner'), }, }); if (__DEV__) { Object.assign( ReactUMDEntry.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, { // ReactComponentTreeHook should not be included in production. ReactComponentTreeHook: require('ReactComponentTreeHook'), getNextDebugID: require('getNextDebugID'), } ); } module.exports = ReactUMDEntry;
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUMDEntry */ 'use strict'; var React = require('React'); // `version` will be added here by the React module. var ReactUMDEntry = Object.assign({ __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: { ReactCurrentOwner: require('ReactCurrentOwner'), }, }, React); if (__DEV__) { Object.assign( ReactUMDEntry.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, { // ReactComponentTreeHook should not be included in production. ReactComponentTreeHook: require('ReactComponentTreeHook'), getNextDebugID: require('getNextDebugID'), } ); } module.exports = ReactUMDEntry;
Make the response body available via readBody git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6660 e27351fd-9f3e-4f54-a53b-843176b1656c
## # Copyright (c) 2010 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## from StringIO import StringIO from zope.interface import implements from twisted.internet.protocol import Protocol from twisted.internet.defer import Deferred, succeed from twisted.web.iweb import IBodyProducer class _BufferReader(Protocol): def __init__(self, finished): self.finished = finished self.received = StringIO() def dataReceived(self, bytes): self.received.write(bytes) def connectionLost(self, reason): self.finished.callback(self.received.getvalue()) def readBody(response): if response.length == 0: return succeed(None) finished = Deferred() response.deliverBody(_BufferReader(finished)) return finished class StringProducer(object): implements(IBodyProducer) def __init__(self, body): self._body = body self.length = len(self._body) def startProducing(self, consumer): consumer.write(self._body) return succeed(None)
## # Copyright (c) 2010 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## from zope.interface import implements from twisted.internet.protocol import Protocol from twisted.internet.defer import Deferred, succeed from twisted.web.iweb import IBodyProducer class _DiscardReader(Protocol): def __init__(self, finished): self.finished = finished def dataReceived(self, bytes): pass def connectionLost(self, reason): self.finished.callback(None) def readBody(response): if response.length == 0: return succeed(None) finished = Deferred() response.deliverBody(_DiscardReader(finished)) return finished class StringProducer(object): implements(IBodyProducer) def __init__(self, body): self._body = body self.length = len(self._body) def startProducing(self, consumer): consumer.write(self._body) return succeed(None)
Remove destructuring to stay compatible with Node 4.x.
const path = require('path'); const fs = require('fs'); const processor = require('../lib/processors/nativeFunction'); function getFixturePath(file) { return path.join(__dirname, 'fixtures', file); } function format(file) { const text = fs.readFileSync(getFixturePath(file), { encoding: 'utf-8' }); return processor.preprocess(text); } test('Replaces all occurrences of native functions with empty functions', () => { const transformed = format('nativeDecl.js')[0]; expect(transformed).not.toContain('native function'); expect(transformed).toContain('function() {}'); }); test('Leaves source code untouched if it has no native function declarations', () => { const fixture = 'standardDecl.js'; const transformed = format(fixture)[0]; expect(transformed).not.toContain('native function'); const original = fs.readFileSync(getFixturePath(fixture), { encoding: 'utf-8' }); expect(transformed).toEqual(original); }); // TODO: Write a test for postprocess().
const path = require('path'); const fs = require('fs'); const processor = require('../lib/processors/nativeFunction'); function getFixturePath(file) { return path.join(__dirname, 'fixtures', file); } function format(file) { const text = fs.readFileSync(getFixturePath(file), { encoding: 'utf-8' }); return processor.preprocess(text); } test('Replaces all occurrences of native functions with empty functions', () => { const [transformed] = format('nativeDecl.js'); expect(transformed).not.toContain('native function'); expect(transformed).toContain('function() {}'); }); test('Leaves source code untouched if it has no native function declarations', () => { const fixture = 'standardDecl.js'; const [transformed] = format(fixture); expect(transformed).not.toContain('native function'); const original = fs.readFileSync(getFixturePath(fixture), { encoding: 'utf-8' }); expect(transformed).toEqual(original); }); // TODO: Write a test for postprocess().
Refactor for changes in retext
'use strict'; /** * Dependencies. */ var phonetics; phonetics = require('double-metaphone'); /** * Change handler. * * @this {WordNode} */ function onchange() { var data, value; data = this.data; value = this.toString(); data.phonetics = value ? phonetics(value) : null; if ('stem' in data) { data.stemmedPhonetics = value ? phonetics(data.stem) : null; } } /** * Define `doubleMetaphone`. * * @param {Retext} retext */ function doubleMetaphone(retext) { var WordNode = retext.TextOM.WordNode; WordNode.on('changetextinside', onchange); WordNode.on('removeinside', onchange); WordNode.on('insertinside', onchange); } /** * Expose `doubleMetaphone`. */ module.exports = doubleMetaphone;
'use strict'; /** * Dependencies. */ var phonetics; phonetics = require('double-metaphone'); /** * Define `doubleMetaphone`. */ function doubleMetaphone() {} /** * Change handler. * * @this {WordNode} */ function onchange() { var data, value; data = this.data; value = this.toString(); data.phonetics = value ? phonetics(value) : null; if ('stem' in data) { data.stemmedPhonetics = value ? phonetics(data.stem) : null; } } /** * Define `attach`. * * @param {Retext} retext */ function attach(retext) { var WordNode = retext.TextOM.WordNode; WordNode.on('changetextinside', onchange); WordNode.on('removeinside', onchange); WordNode.on('insertinside', onchange); } /** * Expose `attach`. */ doubleMetaphone.attach = attach; /** * Expose `doubleMetaphone`. */ module.exports = doubleMetaphone;
Use sys.executable instead of harcoded python path Fixes issue when running in a virtualenv and in non-standard python installations.
#!/usr/bin/env python # -*- coding: utf-8 -*- import twitter_rss import time import subprocess import config import sys # Launch web server p = subprocess.Popen([sys.executable, config.INSTALL_DIR + 'server.py']) # Update the feeds try: while 1: print 'Updating ALL THE FEEDS!' try: with open(config.XML_DIR + 'user/user.txt', 'r') as usernames: for user in usernames: twitter_rss.UserTweetGetter(user) usernames.close() with open(config.XML_DIR + 'htag/htag.txt', 'r') as hashtags: for htag in hashtags: twitter_rss.HashtagTweetGetter(user) hashtags.close() except IOError: print 'File could not be read' time.sleep(config.TIMER) except (KeyboardInterrupt, SystemExit): p.kill() # kill the subprocess print '\nKeyboardInterrupt catched -- Finishing program.'
#!/usr/bin/env python # -*- coding: utf-8 -*- import twitter_rss import time import subprocess import config # Launch web server p = subprocess.Popen(['/usr/bin/python2', config.INSTALL_DIR + 'server.py']) # Update the feeds try: while 1: print 'Updating ALL THE FEEDS!' try: with open(config.XML_DIR + 'user/user.txt', 'r') as usernames: for user in usernames: twitter_rss.UserTweetGetter(user) usernames.close() with open(config.XML_DIR + 'htag/htag.txt', 'r') as hashtags: for htag in hashtags: twitter_rss.HashtagTweetGetter(user) hashtags.close() except IOError: print 'File could not be read' time.sleep(config.TIMER) except (KeyboardInterrupt, SystemExit): p.kill() # kill the subprocess print '\nKeyboardInterrupt catched -- Finishing program.'
Fix bug with python plugin and pyside
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pyqode.python PLUGINS_TYPES = {'QPythonCodeEdit': pyqode.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pyqode.python.QPythonCodeEdit def createWidget(self, parent): return pyqode.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4")
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyQode - Python/Qt Code Editor widget # Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com> # # This software is released under the LGPLv3 license. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ This file contains all the PCEF QtDesigner plugins. Installation: ================== run designer.pyw (Qt Designer must be installed on your system and must be in your path on Windows) """ # This only works with PyQt, PySide does not support the QtDesigner module import os if not 'QT_API' in os.environ: os.environ.setdefault("QT_API", "PyQt") import pcef.python PLUGINS_TYPES = {'QPythonCodeEdit': pcef.python.QPythonCodeEdit} try: from pyqode.core.plugins.pcef_core_plugin import QCodeEditPlugin class QPythonCodeEditPlugin(QCodeEditPlugin): _module = 'pcef.python' # path to the widget's module _class = 'QPythonCodeEdit' # name of the widget class _name = "QPythonCodeEdit" _icon = None _type = pcef.python.QPythonCodeEdit def createWidget(self, parent): return pcef.python.QPythonCodeEdit(parent) except ImportError: print("Cannot use pcef plugins without PyQt4")
Handle not found error in win32 auto launcher
import manifest from '../../../../package.json'; import filePaths from '../../utils/file-paths'; import Winreg from 'winreg'; import BaseAutoLauncher from './base'; class Win32AutoLauncher extends BaseAutoLauncher { static REG_KEY = new Winreg({ hive: Winreg.HKCU, key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' }); enable(callback) { const updateExePath = filePaths.getSquirrelUpdateExe(); const cmd = `"${updateExePath}" --processStart ` + `"${manifest.productName}.exe" --process-start-args "--os-startup"`; log('setting registry key for', manifest.productName, 'value', cmd); Win32AutoLauncher.REG_KEY.set(manifest.productName, Winreg.REG_SZ, cmd, callback); } disable(callback) { log('removing registry key for', manifest.productName); Win32AutoLauncher.REG_KEY.remove(manifest.productName, (err) => { const notFound = err.message == 'The system was unable to find the specified registry key or value.'; if (notFound) { callback(); } else { callback(err); } }); } isEnabled(callback) { log('querying registry key for', manifest.productName); Win32AutoLauncher.REG_KEY.get(manifest.productName, function(err, item) { const enabled = !!item; log('registry value for', manifest.productName, 'is', enabled); callback(err, enabled); }); } } export default Win32AutoLauncher;
import manifest from '../../../../package.json'; import filePaths from '../../utils/file-paths'; import Winreg from 'winreg'; import BaseAutoLauncher from './base'; class Win32AutoLauncher extends BaseAutoLauncher { static REG_KEY = new Winreg({ hive: Winreg.HKCU, key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' }); enable(callback) { const updateExePath = filePaths.getSquirrelUpdateExe(); const cmd = `"${updateExePath}" --processStart ` + `"${manifest.productName}.exe" --process-start-args "--os-startup"`; log('setting registry key for', manifest.productName, 'value', cmd); Win32AutoLauncher.REG_KEY.set(manifest.productName, Winreg.REG_SZ, cmd, callback); } disable(callback) { log('removing registry key for', manifest.productName); Win32AutoLauncher.REG_KEY.remove(manifest.productName, callback); } isEnabled(callback) { log('querying registry key for', manifest.productName); Win32AutoLauncher.REG_KEY.get(manifest.productName, function(err, item) { const enabled = !!item; log('registry value for', manifest.productName, 'is', enabled); callback(err, enabled); }); } } export default Win32AutoLauncher;
Fix xlrd issue Column headers must be strings
import xlrd from ..exceptions import TableTooBigException, EmptyTableException from ..configuration import config from ..utilities import header_population from ..compat import range def xlsx_xlrd(fp): """Read and convert a xlsx file to JSON format using the xlrd library :param fp: File pointer object :return: tuple of table headers and data """ max_size = config['max_size'] wb = xlrd.open_workbook(fp.name) # Currently only displays the first sheet if there are more than one. sheet = wb.sheets()[0] if sheet.ncols > max_size or sheet.nrows > max_size: raise TableTooBigException("Table is too large to render.") if sheet.ncols < 1 or sheet.nrows < 1: raise EmptyTableException("Table is empty or corrupt.") fields = sheet.row_values(0) if sheet.nrows else [] fields = [str(value) or 'Unnamed: {0}'.format(index+1) for index, value in enumerate(fields)] data = [dict(zip(fields, sheet.row_values(row_index))) for row_index in range(1, sheet.nrows)] header = header_population(fields) return header, data
import xlrd from ..exceptions import TableTooBigException, EmptyTableException from ..configuration import config from ..utilities import header_population from ..compat import range def xlsx_xlrd(fp): """Read and convert a xlsx file to JSON format using the xlrd library :param fp: File pointer object :return: tuple of table headers and data """ max_size = config['max_size'] wb = xlrd.open_workbook(fp.name) # Currently only displays the first sheet if there are more than one. sheet = wb.sheets()[0] if sheet.ncols > max_size or sheet.nrows > max_size: raise TableTooBigException("Table is too large to render.") if sheet.ncols < 1 or sheet.nrows < 1: raise EmptyTableException("Table is empty or corrupt.") fields = sheet.row_values(0) if sheet.nrows else [] fields = [value or 'Unnamed: {0}'.format(index+1) for index, value in enumerate(fields)] data = [dict(zip(fields, sheet.row_values(row_index))) for row_index in range(1, sheet.nrows)] header = header_population(fields) return header, data
Restructure things to handle all-ok cases
'use strict'; var fs = require('fs'); function reset() { exports.out = []; exports.xmlEmitter = null; exports.opts = {}; } reset(); /** * Load a formatter * @param {String} formatterPath * @return */ function loadFormatter(formatterPath) { return require('./lib/' + formatterPath + '_emitter'); } /** * Write out a XML file for the encountered results * @param {Array} results * @param {Array} data * @param {Object} opts */ exports.reporter = function (results) { exports.out.push(results); }; exports.writeFile = function (opts) { opts = opts || {}; opts.filePath = opts.filePath || 'jshint.xml'; opts.format = opts.format || 'checkstyle'; exports.xmlEmitter = loadFormatter(opts.format); return function () { if (!exports.out.length) { reset(); return; } var outStream = fs.createWriteStream(opts.filePath); outStream.write(exports.xmlEmitter.getHeader()); exports.out.forEach(function (item) { outStream.write(exports.xmlEmitter.formatContent(item)); }); outStream.write(exports.out.join('\n')); outStream.write(exports.xmlEmitter.getFooter()); reset(); }; };
'use strict'; var fs = require('fs'); function reset() { exports.out = []; exports.xmlEmitter = null; exports.opts = {}; } reset(); /** * Load a formatter * @param {String} formatterPath * @return */ function loadFormatter(formatterPath) { return require('./lib/' + formatterPath + '_emitter'); } /** * Write out a XML file for the encountered results */ exports.reporter = function (results, data, opts) { console.log(arguments); console.log('\n\n\n\n'); opts = opts || {}; opts.format = opts.format || 'checkstyle'; opts.filePath = opts.filePath || 'jshint.xml'; exports.opts = opts; exports.xmlEmitter = loadFormatter(opts.format); exports.out.push(exports.xmlEmitter.formatContent(results)); }; exports.writeFile = function () { var outStream = fs.createWriteStream(exports.opts.filePath); outStream.write(exports.xmlEmitter.getHeader()); outStream.write(exports.out.join('\n')); outStream.write(exports.xmlEmitter.getFooter()); reset(); };
Fix change initiative section - Override GH section with DB specific one CTCTOWALTZ-706
// extensions initialisation import _ from "lodash"; import {registerComponents} from '../common/module-utils'; import {dynamicSections, dynamicSectionsByKind} from "../dynamic-section/dynamic-section-definitions"; import dbChangeInitiativeBrowser from './components/change-initiative/change-initiative-browser/db-change-initiative-browser'; import dbChangeInitiativeSection from './components/change-initiative/change-initiative-section/db-change-initiative-section'; export const init = (module) => { registerComponents(module, [ dbChangeInitiativeBrowser, dbChangeInitiativeSection ]); overrideChangeInitiativeSection(); }; function overrideChangeInitiativeSection() { dynamicSections.dbChangeInitiativesSection = { componentId: 'db-change-initiative-section', name: 'Change Initiatives', icon: 'paper-plane-o', id: 10000 }; _.forIn(dynamicSectionsByKind, (v, k) => dynamicSectionsByKind[k] = _.map( v, ds => ds.id === dynamicSections.changeInitiativeSection.id ? dynamicSections.dbChangeInitiativesSection : ds )); }
// extensions initialisation import _ from "lodash"; import {registerComponents} from '../common/module-utils'; import {dynamicSections, dynamicSectionsByKind} from "../dynamic-section/dynamic-section-definitions"; import dbChangeInitiativeBrowser from './components/change-initiative/change-initiative-browser/db-change-initiative-browser'; import dbChangeInitiativeSection from './components/change-initiative/change-initiative-section/db-change-initiative-section'; export const init = (module) => { registerComponents(module, [ dbChangeInitiativeBrowser, dbChangeInitiativeSection ]); overrideApplicationDynamicSections(); }; function overrideApplicationDynamicSections() { dynamicSections.dbChangeInitiativesSection = { componentId: 'db-change-initiative-section', name: 'Change Initiatives', icon: 'paper-plane-o', id: 10000 }; dynamicSectionsByKind["APPLICATION"] = _.map( dynamicSectionsByKind["APPLICATION"], ds => ds.id === dynamicSections.changeInitiativeSection.id ? dynamicSections.dbChangeInitiativesSection : ds ); }
Truncate a long log message.
import os import logging import envoy from .ants_error import ANTSError def create_template(metric, files): """ Builds a template from the given image files. :param metric: the similarity metric :param files: the image files :return: the template file name """ CMD = "buildtemplateparallel.sh -d 2 -c 2 -j 4 -d 2 -s {metric} -o {output} {files}" PREFIX = 'reg_' SUFFIX = 'template.nii.gz' tmpl = PREFIX + SUFFIX if os.path.exists(tmpl): logging.info("Registration template already exists: %s" % tmpl) return tmpl cmd = CMD.format(metric=metric.name, output=PREFIX, files=' '.join(files)) logging.info("Building the %s registration template with the following command:" % tmpl) logging.info(cmd[:80]) r = envoy.run(cmd) if r.status_code: logging.error("Build registration template failed with error code %d" % r.status_code) logging.error(r.std_err) raise ANTSError("Build registration template unsuccessful; see the log for details") if not os.path.exists(tmpl): logging.error("Build registration template was not created.") raise ANTSError("Build registration template unsuccessful; see the log for details") logging.info("Built the registration template %s." % tmpl) return tmpl
import os import logging import envoy from .ants_error import ANTSError def create_template(metric, files): """ Builds a template from the given image files. :param metric: the similarity metric :param files: the image files :return: the template file name """ CMD = "buildtemplateparallel.sh -d 2 -c 2 -j 4 -d 2 -s {metric} -o {output} {files}" PREFIX = 'reg_' SUFFIX = 'template.nii.gz' tmpl = PREFIX + SUFFIX if os.path.exists(tmpl): logging.info("Registration template already exists: %s" % tmpl) return tmpl cmd = CMD.format(metric=metric.name, output=PREFIX, files=' '.join(files)) logging.info("Building the %s registration template with the following command:" % tmpl) logging.info(cmd) r = envoy.run(cmd) if r.status_code: logging.error("Build registration template failed with error code %d" % r.status_code) logging.error(r.std_err) raise ANTSError("Build registration template unsuccessful; see the log for details") if not os.path.exists(tmpl): logging.error("Build registration template was not created.") raise ANTSError("Build registration template unsuccessful; see the log for details") logging.info("Built the registration template %s." % tmpl) return tmpl
Add extra space between cat emoji and text
"""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(get_cat() + ' ' + project_output) print(current_ref_output + ' ' + path_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(get_cat() + ' ' + project_output) print(current_ref_output + ' ' + path_output) def get_cat(): """Return a cat emoji""" return emoji.emojize(':cat:', use_aliases=True)
Set size on wishlist line quantity form field This doesn't actually work since there is an overriding CSS style. When issue #851 is resolved, this should start working.
# -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory, fields_for_model WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) class WishListLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(WishListLineForm, self).__init__(*args, **kwargs) self.fields['quantity'].widget.attrs['size'] = 2 LineFormset = inlineformset_factory( WishList, Line, fields=('quantity', ), form=WishListLineForm, extra=0, can_delete=False)
# -*- coding: utf-8 -*- from django import forms from django.db.models import get_model from django.forms.models import inlineformset_factory WishList = get_model('wishlists', 'WishList') Line = get_model('wishlists', 'Line') class WishListForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(WishListForm, self).__init__(*args, **kwargs) self.instance.owner = user class Meta: model = WishList fields = ('name', ) LineFormset = inlineformset_factory(WishList, Line, fields=('quantity', ), extra=0, can_delete=False)
Remove line creating false 403
<?php /** * @package Zoop * @license MIT */ namespace Zoop\GatewayModule; use Zoop\GatewayModule\Exception; use Zend\Authentication\Adapter\Http as ZendHttpAdapter; use Zend\Authentication\Result; class HttpAdapter extends ZendHttpAdapter { /** * Authenticate * * @throws Exception\RuntimeException * @return Authentication\Result */ public function authenticate() { if (empty($this->request)) { throw new Exception\RuntimeException( 'Request and Response objects must be set before calling authenticate()' ); } if ($this->request->getUri()->getScheme() != 'https') { return new Result( Result::FAILURE_UNCATEGORIZED, array(), array('Http authentication must be over https') ); } return parent::authenticate(); } }
<?php /** * @package Zoop * @license MIT */ namespace Zoop\GatewayModule; use Zoop\GatewayModule\Exception; use Zend\Authentication\Adapter\Http as ZendHttpAdapter; use Zend\Authentication\Result; class HttpAdapter extends ZendHttpAdapter { /** * Authenticate * * @throws Exception\RuntimeException * @return Authentication\Result */ public function authenticate() { if (empty($this->request)) { throw new Exception\RuntimeException( 'Request and Response objects must be set before calling authenticate()' ); } if ($this->request->getUri()->getScheme() != 'https') { $this->response->setStatusCode(403); return new Result( Result::FAILURE_UNCATEGORIZED, array(), array('Http authentication must be over https') ); } return parent::authenticate(); } }
Add the :8080 part of the url to the socketurl
// Filename: main.js // Require.js allows us to configure mappings to paths require.config({ paths: { jquery: 'libs/jquery/jquery-min', underscore: 'libs/underscore/underscore-min', backbone: 'libs/backbone/backbone-optamd3-min', } }); require([ 'jquery', 'underscore', 'backbone', 'texchat', 'util/router', 'models/room', 'views/app', 'protocols/texchat' ], function($, _, Backbone, TeXchat, Router, RoomModel, AppView, TeXchatProtocol) { TeXchat.initialize({ // config socketurl: 'http://' + window.location.hostname + ':8080/chat' }); TeXchat.room = new RoomModel({name: ''}); TeXchat.publicRooms = new RoomModel.collection(); TeXchat.view = new AppView(); TeXchat.view.render(); TeXchat.router = new Router(); TeXchat.protocol = new TeXchatProtocol(TeXchat.config.socketurl, { room: TeXchat.room }); TeXchat.protocol.setName(); if (!Backbone.history.start({pushState: true})) { // TeXchat.router.navigate(window.location.pathname.substr(1)); } });
// Filename: main.js // Require.js allows us to configure mappings to paths require.config({ paths: { jquery: 'libs/jquery/jquery-min', underscore: 'libs/underscore/underscore-min', backbone: 'libs/backbone/backbone-optamd3-min', } }); require([ 'jquery', 'underscore', 'backbone', 'texchat', 'util/router', 'models/room', 'views/app', 'protocols/texchat' ], function($, _, Backbone, TeXchat, Router, RoomModel, AppView, TeXchatProtocol) { TeXchat.initialize({ // config socketurl: window.location.origin + '/chat' }); TeXchat.room = new RoomModel({name: ''}); TeXchat.publicRooms = new RoomModel.collection(); TeXchat.view = new AppView(); TeXchat.view.render(); TeXchat.router = new Router(); TeXchat.protocol = new TeXchatProtocol(TeXchat.config.socketurl, { room: TeXchat.room }); TeXchat.protocol.setName(); if (!Backbone.history.start({pushState: true})) { // TeXchat.router.navigate(window.location.pathname.substr(1)); } });
Send TokenError when we need a refresh
'use strict'; var async = require('async'); var TokenError = require('anyfetch-provider').TokenError; var retrieve = require('./helpers/retrieve.js'); var retrieveCards = retrieve.retrieveCards; var retrieveDeletedCards = retrieve.retrieveDeletedCards; var defaultCursor = retrieve.defaultCursor; module.exports = function updateAccount(serviceData, cursor, queues, cb) { // Retrieve all contacts since last call async.parallel({ newCards: function RetrieveNewCards(cb) { retrieveCards(serviceData.accessToken, cursor || defaultCursor, cb); }, deletedCards: function RetrieveDeletedCards(cb) { retrieveDeletedCards(serviceData.accessToken, cursor || defaultCursor, cb); }, }, function handleCards(err, cardsAndDates) { if(err) { if(err.toString().match(/token/i)) { return cb(new TokenError()); } return cb(err); } var newCursor = new Date(Math.max(cardsAndDates.newCards[1], cardsAndDates.deletedCards[1]) + 1000); cardsAndDates.newCards[0].forEach(function(card) { queues.addition.push(card); }); cardsAndDates.deletedCards[0].forEach(function(card) { queues.deletion.push(card); }); cb(null, newCursor); }); };
'use strict'; var async = require('async'); var retrieve = require('./helpers/retrieve.js'); var retrieveCards = retrieve.retrieveCards; var retrieveDeletedCards = retrieve.retrieveDeletedCards; var defaultCursor = retrieve.defaultCursor; module.exports = function updateAccount(serviceData, cursor, queues, cb) { // Retrieve all contacts since last call async.parallel({ newCards: function RetrieveNewCards(cb) { retrieveCards(serviceData.accessToken, cursor || defaultCursor, cb); }, deletedCards: function RetrieveDeletedCards(cb) { retrieveDeletedCards(serviceData.accessToken, cursor || defaultCursor, cb); }, }, function handleCards(err, cardsAndDates) { if(err) { return cb(err); } var newCursor = new Date(Math.max(cardsAndDates.newCards[1], cardsAndDates.deletedCards[1]) + 1000); cardsAndDates.newCards[0].forEach(function(card) { queues.addition.push(card); }); cardsAndDates.deletedCards[0].forEach(function(card) { queues.deletion.push(card); }); cb(null, newCursor); }); };
Include regenerator-runtime in web app
import 'regenerator-runtime'; import React from 'react'; import ReactDOM from 'react-dom'; import { MemoryRouter } from 'react-router-dom'; import { Provider } from 'react-redux'; import { AppContainer } from 'react-hot-loader'; import { I18nextProvider } from 'react-i18next'; import i18n, { setupI18n } from './i18n'; import App from './App'; import configureStore from './store/configureStore'; const store = configureStore(); // Sentry process.env.NODE_ENV === 'production' && Raven.config('https://2fb5587831994721a8b5f77bf6010679@sentry.io/1256142').install(); const render = async Component => { await setupI18n(); ReactDOM.render( <AppContainer> <I18nextProvider i18n={i18n}> <Provider store={store}> <MemoryRouter> <Component /> </MemoryRouter> </Provider> </I18nextProvider> </AppContainer>, document.getElementById('react_root') ); }; render(App); if (module.hot) { module.hot.accept(() => { render(App); }); }
import React from 'react'; import ReactDOM from 'react-dom'; import { MemoryRouter } from 'react-router-dom'; import { Provider } from 'react-redux'; import { AppContainer } from 'react-hot-loader'; import { I18nextProvider } from 'react-i18next'; import i18n, { setupI18n } from './i18n'; import App from './App'; import configureStore from './store/configureStore'; const store = configureStore(); // Sentry process.env.NODE_ENV === 'production' && Raven.config('https://2fb5587831994721a8b5f77bf6010679@sentry.io/1256142').install(); const render = async Component => { await setupI18n(); ReactDOM.render( <AppContainer> <I18nextProvider i18n={i18n}> <Provider store={store}> <MemoryRouter> <Component /> </MemoryRouter> </Provider> </I18nextProvider> </AppContainer>, document.getElementById('react_root') ); }; render(App); if (module.hot) { module.hot.accept(() => { render(App); }); }
Fix plugin injection on Windows
const path = require('path'); const babelLoaderMatcher = function(rule) { return rule.loader && rule.loader.indexOf(`babel-loader${path.sep}`) != -1; } const getLoader = function(rules, matcher) { var loader; rules.some(rule => { return loader = matcher(rule) ? rule : getLoader(rule.use || rule.oneOf || [], matcher); }); return loader; }; const getBabelLoader = function(rules) { return getLoader(rules, babelLoaderMatcher); } const injectBabelPlugin = function(pluginName, config) { const loader = getBabelLoader(config.module.rules); if (!loader) { console.log("babel-loader not found"); return config; } loader.options.plugins = [pluginName].concat(loader.options.plugins || []); return config; }; module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
const babelLoaderMatcher = function(rule) { return rule.loader && rule.loader.indexOf("babel-loader/") != -1; } const getLoader = function(rules, matcher) { var loader; rules.some(rule => { return loader = matcher(rule) ? rule : getLoader(rule.use || rule.oneOf || [], matcher); }); return loader; }; const getBabelLoader = function(rules) { return getLoader(rules, babelLoaderMatcher); } const injectBabelPlugin = function(pluginName, config) { const loader = getBabelLoader(config.module.rules); if (!loader) { console.log("babel-loader not found"); return config; } loader.options.plugins = [pluginName].concat(loader.options.plugins || []); return config; }; module.exports = { getLoader, getBabelLoader, injectBabelPlugin };
Check hosting Fragment for callback The Support Library now allows a Fragment to request its hosting Fragment, if any. Update FragmentUtil.getCallback() to check the host's instance after checking for an explicitly set target Fragment. Change-Id: I582b3fc0e975d426c4ced494d8551a77f12b372f
package org.wikipedia.activity; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import org.wikipedia.activity.CallbackFragment.Callback; public final class FragmentUtil { @Nullable public static Callback getCallback(@NonNull Fragment fragment) { return getCallback(fragment, Callback.class); } @Nullable public static <T extends Callback> T getCallback(@NonNull Fragment fragment, @NonNull Class<T> callback) { if (callback.isInstance(fragment.getTargetFragment())) { //noinspection unchecked return (T) fragment.getTargetFragment(); } if (callback.isInstance(fragment.getParentFragment())) { //noinspection unchecked return (T) fragment.getParentFragment(); } if (callback.isInstance(fragment.getActivity())) { //noinspection unchecked return (T) fragment.getActivity(); } return null; } private FragmentUtil() { } }
package org.wikipedia.activity; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import org.wikipedia.activity.CallbackFragment.Callback; public final class FragmentUtil { @Nullable public static Callback getCallback(@NonNull Fragment fragment) { return getCallback(fragment, Callback.class); } @Nullable public static <T extends Callback> T getCallback(@NonNull Fragment fragment, @NonNull Class<T> callback) { if (callback.isInstance(fragment.getTargetFragment())) { //noinspection unchecked return (T) fragment.getTargetFragment(); } else if (callback.isInstance(fragment.getActivity())) { //noinspection unchecked return (T) fragment.getActivity(); } else { return null; } } private FragmentUtil() { } }
Add a max width to 100vw component to avoid horizontal scroll.
import React from 'react' import PropTypes from 'prop-types' import CircularProgress from 'material-ui/CircularProgress' class FullScreenProgress extends React.Component { render () { const {containerStyle, progressStyle} = this.props return ( <div style={containerStyle}> <CircularProgress {...progressStyle} /> </div>) } } FullScreenProgress.propTypes = { containerStyle: PropTypes.object, progressStyle: PropTypes.object } FullScreenProgress.defaultProps = { containerStyle: { width: '100vw', height: '100vh', maxWidth: '100%', boxSizing: 'border-box', display: 'flex', justifyContent: 'center', alignItems: 'center' }, progressStyle: { size: 60, thickness: 7 } } export default FullScreenProgress
import React from 'react' import PropTypes from 'prop-types' import CircularProgress from 'material-ui/CircularProgress' class FullScreenProgress extends React.Component { render () { const {containerStyle, progressStyle} = this.props return ( <div style={containerStyle}> <CircularProgress {...progressStyle} /> </div>) } } FullScreenProgress.propTypes = { containerStyle: PropTypes.object, progressStyle: PropTypes.object } FullScreenProgress.defaultProps = { containerStyle: { width: '100vw', height: '100vh', boxSizing: 'border-box', display: 'flex', justifyContent: 'center', alignItems: 'center' }, progressStyle: { size: 60, thickness: 7 } } export default FullScreenProgress
Fix TypeError exception when parsing json This change fixes the TypeError exception that is raised when it should not while parsing json File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/lib64/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer Change-Id: I1b9670adcc505084fecb54a45ce11029dc8a4d93
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Red Hat, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import click import json import six def flatten(d, prefix=''): ret = [] for k, v in d.items(): p = k if not prefix else prefix + '.' + k if isinstance(v, dict): ret += flatten(v, prefix=p) else: ret.append("%s=%s" % (p, v)) return ret def print_json(result_json): formatted_result = json.dumps(result_json, indent=4) click.echo(formatted_result) def sanitize_kwargs(**kwargs): kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v) try: kwargs['data'] = json.loads(kwargs['data']) except KeyError: pass except TypeError: pass return kwargs
# -*- coding: utf-8 -*- # # Copyright (C) 2015 Red Hat, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import click import json import six def flatten(d, prefix=''): ret = [] for k, v in d.items(): p = k if not prefix else prefix + '.' + k if isinstance(v, dict): ret += flatten(v, prefix=p) else: ret.append("%s=%s" % (p, v)) return ret def print_json(result_json): formatted_result = json.dumps(result_json, indent=4) click.echo(formatted_result) def sanitize_kwargs(**kwargs): kwargs = dict((k, v) for k, v in six.iteritems(kwargs) if v) try: kwargs['data'] = json.loads(kwargs['data']) except KeyError: pass return kwargs
Remove tests from built package
from setuptools import setup, find_packages long_description = '''\ pyimagediet is a Python wrapper around image optimisations tools used to reduce images size without loss of visual quality. It provides a uniform interface to tools, easy configuration and integration. It works on images in JPEG, GIF and PNG formats and will leave others unchanged.''' setup( author="Marko Samastur", author_email="markos@gaivo.net", name='pyimagediet', version='0.5', description='Python wrapper around image optimisations tools', long_description=long_description, url='https://github.com/samastur/pyimagediet/', platforms=['OS Independent'], license='MIT License', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Multimedia :: Graphics', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], install_requires=[ 'PyYAML>=3.11', 'python-magic>=0.4.10', ], include_package_data=True, packages=['pyimagediet'], zip_safe=False )
from setuptools import setup, find_packages long_description = '''\ pyimagediet is a Python wrapper around image optimisations tools used to reduce images size without loss of visual quality. It provides a uniform interface to tools, easy configuration and integration. It works on images in JPEG, GIF and PNG formats and will leave others unchanged.''' setup( author="Marko Samastur", author_email="markos@gaivo.net", name='pyimagediet', version='0.5', description='Python wrapper around image optimisations tools', long_description=long_description, url='https://github.com/samastur/pyimagediet/', platforms=['OS Independent'], license='MIT License', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Multimedia :: Graphics', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], install_requires=[ 'PyYAML>=3.11', 'python-magic>=0.4.10', ], include_package_data=True, packages=find_packages(), zip_safe=False )
Fix test module for changed dependency filter API
package com.vaadin.test.dependencyrewrite; import java.util.ArrayList; import java.util.List; import com.vaadin.server.DependencyFilter; import com.vaadin.server.DeploymentConfiguration; import com.vaadin.server.ServiceException; import com.vaadin.server.VaadinServlet; import com.vaadin.server.VaadinServletService; public class MyService extends VaadinServletService { public MyService(VaadinServlet servlet, DeploymentConfiguration deploymentConfiguration) throws ServiceException { super(servlet, deploymentConfiguration); } @Override protected List<DependencyFilter> initDependencyFilters( List<DependencyFilter> sessionInitFilters) throws ServiceException { List<DependencyFilter> list = new ArrayList<>( super.initDependencyFilters(sessionInitFilters)); list.add(new ApplicationDependencyFilter()); return list; } }
package com.vaadin.test.dependencyrewrite; import java.util.List; import com.vaadin.server.DependencyFilter; import com.vaadin.server.DeploymentConfiguration; import com.vaadin.server.ServiceException; import com.vaadin.server.VaadinServlet; import com.vaadin.server.VaadinServletService; public class MyService extends VaadinServletService { public MyService(VaadinServlet servlet, DeploymentConfiguration deploymentConfiguration) throws ServiceException { super(servlet, deploymentConfiguration); } @Override protected List<DependencyFilter> createDependencyFilters() throws ServiceException { List<DependencyFilter> list = super.createDependencyFilters(); list.add(new ApplicationDependencyFilter()); return list; } }
Make inserts in mongo safe
<?php namespace MASchoolManagement\Persistence; use MASchoolManagement\Subscriptions\SubscriptionFactory; use MASchoolManagement\Subscriptions\UserSubscriptions; use \MASchoolManagement\Student; class StudentPersistor { /** @var \MongoDB */ private $dbConnection; public function __construct(\MongoDB $dbConnection) { $this->dbConnection = $dbConnection; } public function create(Student $student) { $options = array( 'safe' => true ); $collection = $this->dbConnection->selectCollection('student'); $collection->insert(array('_id' => $student->getStudentId(), 'FirstName' => $student->getFirstName(), 'LastName' => $student->getLastName()), $options); } public function load($studentId) { $collection = $this->dbConnection->selectCollection('student'); $info = $collection->findOne(array('_id' => $studentId)); if (isset($info)) { return new Student($info['_id'], $info['LastName'], $info['FirstName'], new UserSubscriptions(new SubscriptionFactory())); } return null; } }
<?php namespace MASchoolManagement\Persistence; use MASchoolManagement\Subscriptions\SubscriptionFactory; use MASchoolManagement\Subscriptions\UserSubscriptions; use \MASchoolManagement\Student; class StudentPersistor { /** @var \MongoDB */ private $dbConnection; public function __construct(\MongoDB $dbConnection) { $this->dbConnection = $dbConnection; } public function create(Student $student) { $collection = $this->dbConnection->selectCollection('student'); $collection->insert(array('_id' => $student->getStudentId(), 'FirstName' => $student->getFirstName(), 'LastName' => $student->getLastName())); } public function load($studentId) { $collection = $this->dbConnection->selectCollection('student'); $info = $collection->findOne(array('_id' => $studentId)); if (isset($info)) { return new Student($info['_id'], $info['LastName'], $info['FirstName'], new UserSubscriptions(new SubscriptionFactory())); } return null; } }
Use tape for asserts to better detect callbacks not being fired
var test = require("tape") var crypto = require('crypto') var cryptoB = require('../') function assertSame (fn) { test(fn.name, function (t) { t.plan(1) fn(crypto, function (err, expected) { fn(cryptoB, function (err, actual) { t.equal(actual, expected) t.end() }) }) }) } assertSame(function sha1 (crypto, cb) { cb(null, crypto.createHash('sha1').update('hello', 'utf-8').digest('hex')) }) assertSame(function md5(crypto, cb) { cb(null, crypto.createHash('md5').update('hello', 'utf-8').digest('hex')) }) test('randomBytes', function (t) { t.plan(3 + 10) t.equal(cryptoB.randomBytes(10).length, 10) cryptoB.randomBytes(10, function(ex, bytes) { t.error(ex) t.equal(bytes.length, 10) bytes.forEach(function(bite) { t.equal(typeof bite, 'number') }) t.end() }) })
var test = require("tape") var crypto = require('crypto') var cryptoB = require('../') var assert = require('assert') function assertSame (fn) { test(fn.name, function (t) { fn(crypto, function (err, expected) { fn(cryptoB, function (err, actual) { t.equal(actual, expected) t.end() }) }) }) } assertSame(function sha1 (crypto, cb) { cb(null, crypto.createHash('sha1').update('hello', 'utf-8').digest('hex')) }) assertSame(function md5(crypto, cb) { cb(null, crypto.createHash('md5').update('hello', 'utf-8').digest('hex')) }) assert.equal(cryptoB.randomBytes(10).length, 10) test('randomBytes', function (t) { cryptoB.randomBytes(10, function(ex, bytes) { assert.ifError(ex) bytes.forEach(function(bite) { assert.equal(typeof bite, 'number') }) t.end() }) })
Fix status code in documentation Fix a mismatch between the documented status code (408) and the one set by the middleware
/*! * Connect - timeout * Ported from https://github.com/LearnBoost/connect-timeout * MIT Licensed */ /** * Module dependencies. */ var debug = require('debug')('connect:timeout'); /** * Timeout: * * Times out the request in `ms`, defaulting to `5000`. The * method `req.clearTimeout()` is added to revert this behaviour * programmatically within your application's middleware, routes, etc. * * The timeout error is passed to `next()` so that you may customize * the response behaviour. This error has the `.timeout` property as * well as `.status == 503`. * * @param {Number} ms * @return {Function} * @api public */ module.exports = function timeout(ms) { ms = ms || 5000; return function(req, res, next) { var id = setTimeout(function(){ req.emit('timeout', ms); }, ms); req.on('timeout', function(){ if (res.headerSent) return debug('response started, cannot timeout'); var err = new Error('Response timeout'); err.timeout = ms; err.status = 503; next(err); }); req.clearTimeout = function(){ clearTimeout(id); }; res.on('header', function(){ clearTimeout(id); }); next(); }; };
/*! * Connect - timeout * Ported from https://github.com/LearnBoost/connect-timeout * MIT Licensed */ /** * Module dependencies. */ var debug = require('debug')('connect:timeout'); /** * Timeout: * * Times out the request in `ms`, defaulting to `5000`. The * method `req.clearTimeout()` is added to revert this behaviour * programmatically within your application's middleware, routes, etc. * * The timeout error is passed to `next()` so that you may customize * the response behaviour. This error has the `.timeout` property as * well as `.status == 408`. * * @param {Number} ms * @return {Function} * @api public */ module.exports = function timeout(ms) { ms = ms || 5000; return function(req, res, next) { var id = setTimeout(function(){ req.emit('timeout', ms); }, ms); req.on('timeout', function(){ if (res.headerSent) return debug('response started, cannot timeout'); var err = new Error('Response timeout'); err.timeout = ms; err.status = 503; next(err); }); req.clearTimeout = function(){ clearTimeout(id); }; res.on('header', function(){ clearTimeout(id); }); next(); }; };
Fix 'float is required' when key has no exp date No expiration date was defaulting to "", which was throwing an error when creating the expire date timestamp.
from django.conf import settings from django.utils import timezone from datetime import datetime def key_state(key): results = settings.GPG_OBJ.import_keys(key).results keys = settings.GPG_OBJ.list_keys() if not results or not results[0]["fingerprint"]: return None, "invalid" else: state = "valid" result = results[0] for key in keys: if key["fingerprint"] == result["fingerprint"]: exp_timestamp = int(key["expires"]) if key["expires"] else 0 expires = datetime.fromtimestamp(exp_timestamp, timezone.utc) if key["trust"] == "r": state = "revoked" elif exp_timestamp and expires < timezone.now(): state = "expired" break return result["fingerprint"], state
from django.conf import settings from django.utils import timezone from datetime import datetime def key_state(key): results = settings.GPG_OBJ.import_keys(key).results keys = settings.GPG_OBJ.list_keys() if not results or not results[0]["fingerprint"]: return None, "invalid" else: state = "valid" result = results[0] for key in keys: if key["fingerprint"] == result["fingerprint"]: exp_timestamp = int(key["expires"]) if key["expires"] else "" expires = datetime.fromtimestamp(exp_timestamp, timezone.utc) if key["trust"] == "r": state = "revoked" elif exp_timestamp and expires < timezone.now(): state = "expired" break return result["fingerprint"], state
Fix console_script out of date after branch reconstruction.
from setuptools import setup packages = [ 'cortex', 'cortex._lib', 'cortex.built_ins', 'cortex._lib.data', 'cortex.built_ins.datasets', 'cortex.built_ins.models', 'cortex.built_ins.networks', 'cortex.built_ins.transforms'] setup(name='cortex', version='0.1', description='A library for wrapping your pytorch code', author='R Devon Hjelm', author_email='erroneus@gmail.com', packages=packages, install_requires=[ 'imageio', 'matplotlib', 'progressbar2', 'scipy', 'sklearn', 'torchvision', 'visdom', 'pyyaml'], entry_points={ 'console_scripts': [ 'cortex=cortex.main:run'] }, zip_safe=False)
from setuptools import setup packages = [ 'cortex', 'cortex._lib', 'cortex.built_ins', 'cortex._lib.data', 'cortex.built_ins.datasets', 'cortex.built_ins.models', 'cortex.built_ins.networks', 'cortex.built_ins.transforms' ] install_requirements = [ 'imageio', 'torch', 'imageio', 'matplotlib', 'progressbar2', 'scipy', 'sklearn', 'torchvision', 'visdom', 'pyyaml', 'pathlib' ] setup( name='cortex', version='0.1', description='A library for wrapping your pytorch code', author='R Devon Hjelm', author_email='erroneus@gmail.com', packages=packages, install_requires=install_requirements, entry_points={'console_scripts': ['cortex=cortex.main:main']}, zip_safe=False)
Allow flip between local remote server. Improved error report.
/** * Copyright (C) 2016 Joshua Auerbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function preProcessSQL(sql, useLocal) { var url = useLocal ? "http://localhost:9879" : "http://35.164.159.76:9879"; // console.log("URL: " + url); // console.log("local flag: " + useLocal); var request = new XMLHttpRequest(); request.open("POST", url, false); request.setRequestHeader("Content-Type", "text/plain"); request.send(sql); // console.log("Returning encoded form:"); // console.log(request.responseText); return request.responseText; } function preMain(input, useLocal) { if (input.source == "sql") { try { input.query = preProcessSQL(input.query, useLocal); } catch (e) { return { "result": e.message}; } input.sourcesexp = true; } // console.log("Input to main:"); // console.log(input); return main(input); }
/** * Copyright (C) 2016 Joshua Auerbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function preProcessSQL(sql) { var url = "http://localhost:9879"; /* TODO: how to parameterize this */ var request = new XMLHttpRequest(); request.open("POST", url, false); request.setRequestHeader("Content-Type", "text/plain"); request.send(sql); // console.log("Returning encoded form:"); // console.log(request.responseText); return request.responseText; } function preMain(input) { if (input.source == "sql") { input.query = preProcessSQL(input.query); input.sourcesexp = true; } // console.log("Input to main:"); // console.log(input); return main(input); }
Allow a list of static values.
package org.myrobotlab.document.transformer; import org.myrobotlab.document.transformer.StageConfiguration; import java.util.List; import org.myrobotlab.document.Document; /** * This will set a field on a document with a value * * @author kwatters * */ public class SetStaticFieldValue extends AbstractStage { private String fieldName = null; private String value = null; private List<String> values = null; @Override public void startStage(StageConfiguration config) { if (config != null) { fieldName = config.getStringParam("fieldName"); value = config.getStringParam("value"); values = config.getListParam("values"); } } @Override public List<Document> processDocument(Document doc) { if (values != null) { for (String value : values) { doc.addToField(fieldName, value); } } else { doc.addToField(fieldName, value); } return null; } @Override public void stopStage() { // TODO Auto-generated method stub } @Override public void flush() { // Only required if this stage does any batching. NO-OP here. } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
package org.myrobotlab.document.transformer; import org.myrobotlab.document.transformer.StageConfiguration; import java.util.List; import org.myrobotlab.document.Document; /** * This will set a field on a document with a value * * @author kwatters * */ public class SetStaticFieldValue extends AbstractStage { private String fieldName = null; private String value = null; @Override public void startStage(StageConfiguration config) { if (config != null) { fieldName = config.getStringParam("fieldName"); value = config.getStringParam("value"); } } @Override public List<Document> processDocument(Document doc) { doc.addToField(fieldName, value); return null; } @Override public void stopStage() { // TODO Auto-generated method stub } @Override public void flush() { // Only required if this stage does any batching. NO-OP here. } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
Add local-routes to config to allow the toggle of routes
<?php namespace Kregel\Identicon; use Illuminate\Support\ServiceProvider; class IdenticonServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. */ public function register() { $loader = \Illuminate\Foundation\AliasLoader::getInstance(); // Register the alias. $loader->alias('Identicon', \Identicon\Identicon::class); } /** * Bootstrap any application services. */ public function boot() { $this->app->booted(function () { if (!$this->app->routesAreCached() && !config('kregel.identicon.local-routes')) { require __DIR__.'/Http/routes.php'; } }); $this->publishes([ __DIR__.'/../config/config.php' => config_path('kregel/identicon.php'), ], 'config'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
<?php namespace Kregel\Identicon; use Illuminate\Support\ServiceProvider; class IdenticonServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. */ public function register() { $loader = \Illuminate\Foundation\AliasLoader::getInstance(); // Register the alias. $loader->alias('Identicon', \Identicon\Identicon::class); } /** * Bootstrap any application services. */ public function boot() { $this->app->booted(function () { if (!$this->app->routesAreCached()) { require __DIR__.'/Http/routes.php'; } }); $this->publishes([ __DIR__.'/../config/config.php' => config_path('kregel/identicon.php'), ], 'config'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
Add some debugging for the worker generation
from bitHopper.Website import app, flask import btcnet_info import bitHopper.Configuration.Workers @app.route("/worker", methods=['POST', 'GET']) def worker(): #Check if this is a form submission handle_worker_post(flask.request.form) #Get a list of currently configured workers pools_workers = {} for pool in btcnet_info.get_pools(): if pool.name is None: logging.debug('Ignoring %s', pool) continue pools_workers[pool.name] = bitHopper.Configuration.Workers.get_worker_from(pool.name) return flask.render_template('worker.html', pools = pools_workers) def handle_worker_post(post): for item in ['method','username','password', 'pool']: if item not in post: return if post['method'] == 'remove': bitHopper.Configuration.Workers.remove( post['pool'], post['username'], post['password']) elif post['method'] == 'add': bitHopper.Configuration.Workers.add( post['pool'], post['username'], post['password'])
from bitHopper.Website import app, flask import btcnet_info import bitHopper.Configuration.Workers @app.route("/worker", methods=['POST', 'GET']) def worker(): #Check if this is a form submission handle_worker_post(flask.request.form) #Get a list of currently configured workers pools_workers = {} for pool in btcnet_info.get_pools(): if not pool.name: continue pools_workers[pool.name] = bitHopper.Configuration.Workers.get_worker_from(pool.name) return flask.render_template('worker.html', pools = pools_workers) def handle_worker_post(post): for item in ['method','username','password', 'pool']: if item not in post: return if post['method'] == 'remove': bitHopper.Configuration.Workers.remove( post['pool'], post['username'], post['password']) elif post['method'] == 'add': bitHopper.Configuration.Workers.add( post['pool'], post['username'], post['password'])
Use instance methods in contract Signed-off-by: Sebastian Hoß <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@shoss.de>
/* * Copyright © 2012 Sebastian Hoß <mail@shoss.de> * This work is free. You can redistribute it and/or modify it under the * terms of the Do What The Fuck You Want To Public License, Version 2, * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. */ package com.github.sebhoss.contract.example; import com.github.sebhoss.contract.annotation.Clause; import com.github.sebhoss.contract.annotation.Contract; import com.github.sebhoss.contract.annotation.OGNL; import com.github.sebhoss.contract.annotation.SpEL; @OGNL @SpEL class OgnlSpELBasedInsuranceCompany extends AbstractInsuranceCompany { @Contract(preconditions = { @Clause(value = "#damage > 0", message = "Reported damage must be positive!", exception = IllegalStateException.class), @Clause(value = "#damage <= maximumReportableDamage", message = "We won't pay that!") }, postconditions = { @Clause(value = "#return >= 0", message = "We won't take any more!"), @Clause(value = "#return <= remainingMoney", message = "We can't pay that much!") }) @Override public double calculateCover(final double damage) { return damage * 0.5; } }
/* * Copyright © 2012 Sebastian Hoß <mail@shoss.de> * This work is free. You can redistribute it and/or modify it under the * terms of the Do What The Fuck You Want To Public License, Version 2, * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. */ package com.github.sebhoss.contract.example; import com.github.sebhoss.contract.annotation.Clause; import com.github.sebhoss.contract.annotation.Contract; import com.github.sebhoss.contract.annotation.OGNL; import com.github.sebhoss.contract.annotation.SpEL; @OGNL @SpEL class OgnlSpELBasedInsuranceCompany extends AbstractInsuranceCompany { @Contract(preconditions = { @Clause(value = "#damage > 0", message = "Reported damage must be positive!", exception = IllegalStateException.class), @Clause(value = "#damage <= 5000", message = "We won't pay that!") }, postconditions = { @Clause(value = "#return >= 0", message = "We won't take any more!"), @Clause(value = "#return <= 2000", message = "We can't pay that much!") }) @Override public double calculateCover(final double damage) { return damage * 0.5; } }
[FIX] css: Allow url etc in custom css and js prefs (thanks luci) git-svn-id: 84b83dd0f57d36a02bb8202710824ee41d1b7ca0@41591 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ function prefs_header_list() { return array( 'header_shadow_start' => array( 'name' => tra('Header shadow start'), 'type' => 'textarea', 'size' => '2', 'default' => '', ), 'header_shadow_end' => array( 'name' => tra('Header shadow end'), 'type' => 'textarea', 'size' => '2', 'default' => '', ), 'header_custom_css' => array( 'name' => tra('Custom CSS'), 'description' => tra('Includes a custom block of CSS inline in all pages.'), 'type' => 'textarea', 'size' => 5, 'default' => '', 'filter' => 'none', ), 'header_custom_js' => array( 'name' => tra('Custom JavaScript'), 'description' => tra('Includes a custom block of inline JavaScript in all pages.'), 'type' => 'textarea', 'size' => 5, 'default' => '', 'hint' => tra('Do not include the <script> and </script> tags.'), 'filter' => 'none', ), ); }
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ function prefs_header_list() { return array( 'header_shadow_start' => array( 'name' => tra('Header shadow start'), 'type' => 'textarea', 'size' => '2', 'default' => '', ), 'header_shadow_end' => array( 'name' => tra('Header shadow end'), 'type' => 'textarea', 'size' => '2', 'default' => '', ), 'header_custom_css' => array( 'name' => tra('Custom CSS'), 'description' => tra('Includes a custom block of CSS inline in all pages.'), 'type' => 'textarea', 'size' => 5, 'default' => '', ), 'header_custom_js' => array( 'name' => tra('Custom JavaScript'), 'description' => tra('Includes a custom block of inline JavaScript in all pages.'), 'type' => 'textarea', 'size' => 5, 'default' => '', 'hint' => tra('Do not include the <script> and </script> tags.'), ), ); }
Fix float datatype for gps course
'use strict'; module.exports = function(sequelize, DataTypes) { var Location = sequelize.define('Location', { latitude: DataTypes.FLOAT(4, 6), longitude: DataTypes.FLOAT(4, 6), timestamp: DataTypes.DATE, speed: DataTypes.FLOAT(4, 2), course: DataTypes.FLOAT(4, 2), altitude: DataTypes.FLOAT(4, 2), satellites: DataTypes.INTEGER, hdop: DataTypes.FLOAT(4, 2), age: DataTypes.INTEGER, charge: DataTypes.INTEGER, voltage: DataTypes.FLOAT(2, 3), signal: DataTypes.INTEGER }, { classMethods: { associate: function(models) { Location.belongsTo(models.Device, { onDelete: 'CASCADE', foreignKey: { allowNull: false } }); } } }); return Location; };
'use strict'; module.exports = function(sequelize, DataTypes) { var Location = sequelize.define('Location', { latitude: DataTypes.FLOAT(4, 6), longitude: DataTypes.FLOAT(4, 6), timestamp: DataTypes.DATE, speed: DataTypes.FLOAT(4, 2), course: DataTypes.INTEGER, altitude: DataTypes.FLOAT(4, 2), satellites: DataTypes.INTEGER, hdop: DataTypes.FLOAT(4, 2), age: DataTypes.INTEGER, charge: DataTypes.INTEGER, voltage: DataTypes.FLOAT(2, 3), signal: DataTypes.INTEGER }, { classMethods: { associate: function(models) { Location.belongsTo(models.Device, { onDelete: 'CASCADE', foreignKey: { allowNull: false } }); } } }); return Location; };
FIX - write concerns not added to collection
package com.mongodb.memphis.config; import org.bson.BsonDocument; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Collection { private String name; private WriteConcern writeConcern; private ReadConcern readConcern; private ReadPreference readPreference; public final String getName() { return name; } public final WriteConcern getWriteConcern() { return writeConcern; } public final ReadConcern getReadConcern() { return readConcern; } public final ReadPreference getReadPreference() { return readPreference; } public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) { MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class); if (writeConcern != null) { collection = collection.withWriteConcern(writeConcern); } if (readConcern != null) { collection = collection.withReadConcern(readConcern); } if (readPreference != null) { collection = collection.withReadPreference(readPreference); } return collection; } }
package com.mongodb.memphis.config; import org.bson.BsonDocument; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class Collection { private String name; private WriteConcern writeConcern; private ReadConcern readConcern; private ReadPreference readPreference; public final String getName() { return name; } public final WriteConcern getWriteConcern() { return writeConcern; } public final ReadConcern getReadConcern() { return readConcern; } public final ReadPreference getReadPreference() { return readPreference; } public MongoCollection<BsonDocument> getMongoCollection(MongoDatabase mongoDatabase) { MongoCollection<BsonDocument> collection = mongoDatabase.getCollection(name, BsonDocument.class); if (writeConcern != null) { collection.withWriteConcern(writeConcern); } if (readConcern != null) { collection.withReadConcern(readConcern); } if (readPreference != null) { collection.withReadPreference(readPreference); } return collection; } }
Add docblock about when this event was introduced
<?php namespace Concrete\Core\Page; /** * @since 8.5.0 */ class DisplayOrderUpdateEvent extends Event { /** * Get the old display order * * This is the order *before* the page was moved. * * @return int */ public function getOldDisplayOrder() { return (int) $this->getArgument('oldDisplayOrder'); } /** * Get the new display order * * This is the order *after* the page was moved. * * @return int */ public function getNewDisplayOrder() { return (int) $this->getArgument('newDisplayOrder'); } /** * @param int $displayOrder */ public function setOldDisplayOrder($displayOrder) { $this->setArgument('oldDisplayOrder', (int) $displayOrder); } /** * @param int $displayOrder */ public function setNewDisplayOrder($displayOrder) { $this->setArgument('newDisplayOrder', (int) $displayOrder); } }
<?php namespace Concrete\Core\Page; class DisplayOrderUpdateEvent extends Event { /** * Get the old display order * * This is the order *before* the page was moved. * * @return int */ public function getOldDisplayOrder() { return (int) $this->getArgument('oldDisplayOrder'); } /** * Get the new display order * * This is the order *after* the page was moved. * * @return int */ public function getNewDisplayOrder() { return (int) $this->getArgument('newDisplayOrder'); } /** * @param int $displayOrder */ public function setOldDisplayOrder($displayOrder) { $this->setArgument('oldDisplayOrder', (int) $displayOrder); } /** * @param int $displayOrder */ public function setNewDisplayOrder($displayOrder) { $this->setArgument('newDisplayOrder', (int) $displayOrder); } }
Fix improper grab of the pusher controller in unwire
var global = (typeof window !== 'undefined') ? window : {}, Ember = global.Ember; var Bindings = Ember.Mixin.create({ needs: 'pusher', init: function() { var pusherController, target; this._super(); if(!this.PUSHER_SUBSCRIPTIONS) { return; } pusherController = this.get('controllers.pusher'); target = this; Object.keys(target.PUSHER_SUBSCRIPTIONS).forEach(function (channelName) { var events = target.PUSHER_SUBSCRIPTIONS[channelName]; pusherController.wire(target, channelName, events); }); }, willDestroy: function() { var pusherController, target; if(!this.PUSHER_SUBSCRIPTIONS) { return; } pusherController = this.get('controllers.pusher'); target = this; Object.keys(target.PUSHER_SUBSCRIPTIONS).forEach(function (channelName) { pusherController.unwire(target, channelName); }); this._super(); }, _pusherEventsId: function() { return this.toString(); } }); export { Bindings };
var global = (typeof window !== 'undefined') ? window : {}, Ember = global.Ember; var Bindings = Ember.Mixin.create({ needs: 'pusher', init: function() { var pusherController, target; this._super(); if(!this.PUSHER_SUBSCRIPTIONS) { return; } pusherController = this.get('controllers.pusher'); target = this; Object.keys(target.PUSHER_SUBSCRIPTIONS).forEach(function (channelName) { var events = target.PUSHER_SUBSCRIPTIONS[channelName]; pusherController.wire(target, channelName, events); }); }, willDestroy: function() { var pusherController, target; if(!this.PUSHER_SUBSCRIPTIONS) { return; } pusherController = this.controllerFor('pusher'); target = this; Object.keys(target.PUSHER_SUBSCRIPTIONS).forEach(function (channelName) { pusherController.unwire(target, channelName); }); }, _pusherEventsId: function() { return this.toString(); } }); export { Bindings };
Add a test that verifies the cache has a clear method.
# coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') # Verify that the cache has a valid clear method. cache.cache.clear() self.assertEqual(len(self.panel.calls), 5) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2)
# coding: utf-8 from __future__ import absolute_import, unicode_literals import django from django.core import cache from django.utils.unittest import skipIf from ..base import BaseTestCase class CachePanelTestCase(BaseTestCase): def setUp(self): super(CachePanelTestCase, self).setUp() self.panel = self.toolbar.get_panel_by_id('CachePanel') self.panel.enable_instrumentation() def tearDown(self): self.panel.disable_instrumentation() super(CachePanelTestCase, self).tearDown() def test_recording(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.cache.get('foo') cache.cache.delete('foo') self.assertEqual(len(self.panel.calls), 3) @skipIf(django.VERSION < (1, 7), "Caches was added in Django 1.7") def test_recording_caches(self): self.assertEqual(len(self.panel.calls), 0) cache.cache.set('foo', 'bar') cache.caches[cache.DEFAULT_CACHE_ALIAS].get('foo') self.assertEqual(len(self.panel.calls), 2)
Fix error in test suite startup with dotted import names. Detected first on ubuntu 12.04, but the bug is generic, we just hadn't seen it before. Will push straight to master as this will begin causing problems as more people upgrade.
# encoding: utf-8 """ A simple utility to import something by its string name. Authors: * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Functions and classes #----------------------------------------------------------------------------- def import_item(name): """Import and return bar given the string foo.bar.""" package = '.'.join(name.split('.')[0:-1]) obj = name.split('.')[-1] # Note: the original code for this was the following. We've left it # visible for now in case the new implementation shows any problems down # the road, to make it easier on anyone looking for a problem. This code # should be removed once we're comfortable we didn't break anything. ## execString = 'from %s import %s' % (package, obj) ## try: ## exec execString ## except SyntaxError: ## raise ImportError("Invalid class specification: %s" % name) ## exec 'temp = %s' % obj ## return temp if package: module = __import__(package,fromlist=[obj]) try: pak = module.__dict__[obj] except KeyError: raise ImportError('No module named %s' % obj) return pak else: return __import__(obj)
# encoding: utf-8 """ A simple utility to import something by its string name. Authors: * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Functions and classes #----------------------------------------------------------------------------- def import_item(name): """Import and return bar given the string foo.bar.""" package = '.'.join(name.split('.')[0:-1]) obj = name.split('.')[-1] # Note: the original code for this was the following. We've left it # visible for now in case the new implementation shows any problems down # the road, to make it easier on anyone looking for a problem. This code # should be removed once we're comfortable we didn't break anything. ## execString = 'from %s import %s' % (package, obj) ## try: ## exec execString ## except SyntaxError: ## raise ImportError("Invalid class specification: %s" % name) ## exec 'temp = %s' % obj ## return temp if package: module = __import__(package,fromlist=[obj]) return module.__dict__[obj] else: return __import__(obj)
Document what the new option does
<?php namespace Backend\Form\Type; use Backend\Core\Engine\Model; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class DeleteType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->setAction( Model::createUrlForAction( $options['action'], $options['module'], null, $options['get_parameters'] ) ); $builder->add($options['id_field_name'], HiddenType::class); } public function configureOptions(OptionsResolver $resolver): void { $resolver->setRequired([ 'module', 'action', 'id_field_name', ]); $resolver->setDefaults([ 'action' => 'Delete', 'id_field_name' => 'id', 'get_parameters' => [], // Get parameters to be added to the generated action url ]); } }
<?php namespace Backend\Form\Type; use Backend\Core\Engine\Model; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class DeleteType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder->setAction( Model::createUrlForAction( $options['action'], $options['module'], null, $options['get_parameters'] ) ); $builder->add($options['id_field_name'], HiddenType::class); } public function configureOptions(OptionsResolver $resolver): void { $resolver->setRequired([ 'module', 'action', 'id_field_name', ]); $resolver->setDefaults([ 'action' => 'Delete', 'id_field_name' => 'id', 'get_parameters' => [], ]); } }
Prepare release notes for v1.6.0-rc.3 Signed-off-by: Derek McGowan <e1c79a582b6629e6b39e9679f4bb964d25db4aa8@mcg.dev>
/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package version import "runtime" var ( // Package is filled at linking time Package = "github.com/containerd/containerd" // Version holds the complete version number. Filled in at linking time. Version = "1.6.0-rc.3+unknown" // Revision is filled with the VCS (e.g. git) revision being used to build // the program at linking time. Revision = "" // GoVersion is Go tree's version. GoVersion = runtime.Version() )
/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package version import "runtime" var ( // Package is filled at linking time Package = "github.com/containerd/containerd" // Version holds the complete version number. Filled in at linking time. Version = "1.6.0-rc.2+unknown" // Revision is filled with the VCS (e.g. git) revision being used to build // the program at linking time. Revision = "" // GoVersion is Go tree's version. GoVersion = runtime.Version() )
Remove One Off option on page load for recurring tasks.
$('document').ready(function () { addOrRemoveOneOffOption(); showOrHideRecurrenceFields(); }); $('#IsRecurring').on('click', function () { addOrRemoveOneOffOption(); showOrHideRecurrenceFields(); }); function addOrRemoveOneOffOption() { if ($('#IsRecurring')[0].checked) { $('#Recurrence option[value="1"]').remove(); } else { if (!recurrenceDropdownContainsOneOffOption()) { $('#Recurrence').append('<option value="1">OneOff</option>'); } } } function showOrHideRecurrenceFields() { if ($('#IsRecurring')[0].checked) { $('#recurrence-fields').show(); } else { $('#recurrence-fields').hide(); $('#Recurrence').val("1").change(); } } function recurrenceDropdownContainsOneOffOption() { var containsOneOff = false; $('#Recurrence option').each(function () { if (this.value === '1') { containsOneOff = true; } }); return containsOneOff; }
$('document').ready(function () { showOrHideRecurrenceFields(); }); $('#IsRecurring').on('click', function () { addOrRemoveOneOffOption(); showOrHideRecurrenceFields(); }); function addOrRemoveOneOffOption() { if ($('#IsRecurring')[0].checked) { $('#Recurrence option[value="1"]').remove(); } else { $('#Recurrence').append('<option value="1">OneOff</option>'); } } function showOrHideRecurrenceFields() { if ($('#IsRecurring')[0].checked) { $('#recurrence-fields').show(); } else { $('#recurrence-fields').hide(); $('#Recurrence').val("1").change(); } }
Use Ember 1.12 computed + Ember.meta
import Ember from 'ember'; var get = Ember.get; var set = Ember.set; export default function indirect(pathProperty) { return Ember.computed(pathProperty, { get: function getIndirectPropertyValue(key) { var metaSourceKey = 'source.' + key; var metaObserverKey = 'observer.' + key; // Use a Ember.meta instead of storing meta info on the object itself var _meta = Ember.meta(this, true); _meta = _meta.__indirect__ || (_meta.__indirect__ = {}); var metaObserver = _meta[metaObserverKey]; if (!metaObserver) { _meta[metaObserverKey] = metaObserver = function() { this.notifyPropertyChange(key); }; } var currentKey = get(this, pathProperty); if (currentKey !== _meta[metaSourceKey]) { if (_meta[metaSourceKey]) { Ember.removeObserver(this, _meta[metaSourceKey], this, metaObserver); } if (currentKey) { Ember.addObserver(this, currentKey, this, metaObserver); } _meta[metaSourceKey] = currentKey; } return currentKey && get(this, currentKey); }, set: function setIndirectPropertyValue(key, value) { return set(this, get(this, pathProperty), value); } }); }
export default function indirect(middlePropertyName) { return function(key, value) { // TODO: I don't like using `key`. Can we do better? var lastSourcePropertyName = '__indirect_lastSourceProperty:' + key; var sourcePropertyObserverName = '__indirect_sourcePropertyObserver:' + key; var sourceProperty = this.get(middlePropertyName); var lastSourceProperty = this[lastSourcePropertyName]; var sourcePropertyObserver = this[sourcePropertyObserverName]; if (lastSourceProperty !== sourceProperty) { if (lastSourceProperty && sourcePropertyObserver) { this.removeObserver(lastSourceProperty, this, sourcePropertyObserver); } this[sourcePropertyObserverName] = function() { this.notifyPropertyChange(key); }; this.addObserver(sourceProperty, this, this[sourcePropertyObserverName]); this[lastSourcePropertyName] = sourceProperty; } if (arguments.length > 1) { this.set(sourceProperty, value); } return this.get(sourceProperty); }.property(middlePropertyName); }
Use virtualenv python & look for config file in new instance directory.
#!/usr/bin/env python import psycopg2 import sys import os def parse_connection_uri(): here, _ = os.path.split(__file__) with open(os.path.join(here, '../instance/application.cfg'), 'r') as fh: conn_strings = [l for l in fh.readlines() if l.startswith('SQLALCHEMY_DATABASE_URI')] if len(conn_strings) != 1: raise ValueError("can't find connection string in application.cfg") conn_uri = conn_strings[0].split('=')[1] return conn_uri.strip()[1:-1] # strip quotes, newlines connection_uri = parse_connection_uri() print "Connecting to database\n ->{}".format(connection_uri) try: conn = psycopg2.connect(connection_uri) cursor = conn.cursor() print "Connected!\n" except: exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() sys.exit("Database connection failed!\n ->%s" % (exceptionValue))
#!/usr/bin/python import psycopg2 import sys import os def parse_connection_uri(): here, _ = os.path.split(__file__) with open(os.path.join(here, '../portal/application.cfg'), 'r') as fh: conn_strings = [l for l in fh.readlines() if l.startswith('SQLALCHEMY_DATABASE_URI')] if len(conn_strings) != 1: raise ValueError("can't find connection string in application.cfg") conn_uri = conn_strings[0].split('=')[1] return conn_uri.strip()[1:-1] # strip quotes, newlines connection_uri = parse_connection_uri() print "Connecting to database\n ->{}".format(connection_uri) try: conn = psycopg2.connect(connection_uri) cursor = conn.cursor() print "Connected!\n" except: exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() sys.exit("Database connection failed!\n ->%s" % (exceptionValue))
Use the GWT date/time formatter.
package edu.pdx.cs410J.whitlock.client; import com.google.gwt.i18n.client.DateTimeFormat; import edu.pdx.cs410J.AbstractAppointment; import java.util.Date; public class Appointment extends AbstractAppointment { @Override public String getBeginTimeString() { return "START " + getBeginTime(); } @Override public String getEndTimeString() { return "END + " + formatDate(getEndTime()); } private String formatDate(Date date) { String pattern = "yyyy/MM/dd hh:mm a"; return DateTimeFormat.getFormat(pattern).format(date); } @Override public Date getEndTime() { return new Date(); } @Override public String getDescription() { return "My description"; } @Override public Date getBeginTime() { return new Date(); } }
package edu.pdx.cs410J.whitlock.client; import edu.pdx.cs410J.AbstractAppointment; import java.util.Date; public class Appointment extends AbstractAppointment { @Override public String getBeginTimeString() { return "START " + getBeginTime(); } @Override public String getEndTimeString() { return "END + " + getEndTime(); } @Override public Date getEndTime() { return new Date(); } @Override public String getDescription() { return "My description"; } @Override public Date getBeginTime() { return new Date(); } }
Change filter logger to instance field
package io.github.jordao76.quotes.filters; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.slf4j.*; import org.springframework.stereotype.*; import org.springframework.web.filter.*; @Component public class RequestLoggingFilter extends OncePerRequestFilter { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { filterChain.doFilter(request, response); if (logger.isDebugEnabled()) { logger.debug("HTTP {} for {} {}", value("status", response.getStatus()), value("method", request.getMethod()), value("endpoint", request.getRequestURI())); } } // note: later to be replaced, // see https://github.com/logstash/logstash-logback-encoder/tree/logstash-logback-encoder-4.7#loggingevent_custom_event private Object value(String key, Object value) { return value; } }
package io.github.jordao76.quotes.filters; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.slf4j.*; import org.springframework.stereotype.*; import org.springframework.web.filter.*; @Component public class RequestLoggingFilter extends OncePerRequestFilter { private static final Logger LOGGER = LoggerFactory.getLogger(RequestLoggingFilter.class); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { filterChain.doFilter(request, response); if (LOGGER.isDebugEnabled()) { LOGGER.debug("HTTP {} for {} {}", value("status", response.getStatus()), value("method", request.getMethod()), value("endpoint", request.getRequestURI())); } } // note: later to be replaced, // see https://github.com/logstash/logstash-logback-encoder/tree/logstash-logback-encoder-4.7#loggingevent_custom_event private Object value(String key, Object value) { return value; } }
Add null url on close
package com.freshplanet.ane.AirAACPlayer.functions; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; import com.adobe.fre.FREObject; import com.freshplanet.ane.AirAACPlayer.Extension; import com.freshplanet.ane.AirAACPlayer.ExtensionContext; public class CloseFunction implements FREFunction { @Override public FREObject call(FREContext context, FREObject[] arg1) { try { ExtensionContext extensionContext = (ExtensionContext) context; extensionContext.getPlayer().stop(); extensionContext.getPlayer().release(); extensionContext.setMediaUrl(null); extensionContext.setPlayer(null); } catch (Exception e) { Extension.context.dispatchStatusEventAsync("LOGGING", "[Error] Error on close"); e.printStackTrace(); } return null; } }
package com.freshplanet.ane.AirAACPlayer.functions; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; import com.adobe.fre.FREObject; import com.freshplanet.ane.AirAACPlayer.Extension; import com.freshplanet.ane.AirAACPlayer.ExtensionContext; public class CloseFunction implements FREFunction { @Override public FREObject call(FREContext context, FREObject[] arg1) { try { ExtensionContext extensionContext = (ExtensionContext) context; extensionContext.getPlayer().stop(); extensionContext.getPlayer().release(); extensionContext.setPlayer(null); } catch (Exception e) { Extension.context.dispatchStatusEventAsync("LOGGING", "[Error] Error on close"); e.printStackTrace(); } return null; } }
Remove unused NHS database mockup
import os _basedir = os.path.abspath(os.path.dirname(__file__)) # Plugin settings DATABASE_NAMES = ['atc', 'sms'] # Using sqlite for local development, will be SQL on production. SQLALCHEMY_BINDS = { 'atc': 'sqlite:///' + os.path.join(_basedir, 'db/atc.db'), 'sms': 'sqlite:///' + os.path.join(_basedir, 'db/sms.db') } # TxtLocal SMS settings SENDER = '447786202240' INBOX_ID = '498863' API_KEY = 'Sap3A0EaE2k-xL6d4nLJuQdZriNxBByUjRhOCHM5X0' API_URI = 'https://api.txtlocal.com/' API_SEND_URI = API_URI + 'send/?' API_RECEIVE_URI = API_URI + 'get_messages/?' TEST_MODE = 1 # 1 (True) to enable test mode & 0 to disable.
import os _basedir = os.path.abspath(os.path.dirname(__file__)) # Plugin settings DATABASE_NAMES = ['atc', 'nhs', 'sms'] # Using sqlite for local development, will be SQL on production. SQLALCHEMY_BINDS = { 'atc': 'sqlite:///' + os.path.join(_basedir, 'db/atc.db'), 'nhs': 'sqlite:///' + os.path.join(_basedir, 'db/nhs.db'), 'sms': 'sqlite:///' + os.path.join(_basedir, 'db/sms.db') } # TxtLocal SMS settings SENDER = '447786202240' INBOX_ID = '498863' API_KEY = 'Sap3A0EaE2k-xL6d4nLJuQdZriNxBByUjRhOCHM5X0' API_URI = 'https://api.txtlocal.com/' API_SEND_URI = API_URI + 'send/?' API_RECEIVE_URI = API_URI + 'get_messages/?' TEST_MODE = 1 # 1 (True) to enable test mode & 0 to disable.
Revert "Delay IntervalLiveData refresh to allow the previous result to be dispatched on active even when it's already expired" This reverts commit 2f166836
package be.digitalia.fosdem.livedata; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import java.util.concurrent.TimeUnit; public class LiveDataFactory { static final Handler handler = new Handler(Looper.getMainLooper()); private LiveDataFactory() { } private static class IntervalLiveData extends LiveData<Long> implements Runnable { private final long periodInMillis; private long updateTime = 0L; private long version = 0L; IntervalLiveData(long periodInMillis) { this.periodInMillis = periodInMillis; } @Override protected void onActive() { final long now = SystemClock.elapsedRealtime(); if (now >= updateTime) { update(now); } else { handler.postDelayed(this, updateTime - now); } } @Override protected void onInactive() { handler.removeCallbacks(this); } private void update(long now) { setValue(version++); updateTime = now + periodInMillis; handler.postDelayed(this, periodInMillis); } @Override public void run() { update(SystemClock.elapsedRealtime()); } } public static LiveData<Long> interval(long period, @NonNull TimeUnit unit) { return new IntervalLiveData(unit.toMillis(period)); } }
package be.digitalia.fosdem.livedata; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import java.util.concurrent.TimeUnit; public class LiveDataFactory { static final Handler handler = new Handler(Looper.getMainLooper()); private LiveDataFactory() { } private static class IntervalLiveData extends LiveData<Long> implements Runnable { private final long periodInMillis; private long updateTime = 0L; private long version = 0L; IntervalLiveData(long periodInMillis) { this.periodInMillis = periodInMillis; } @Override protected void onActive() { if (version == 0L) { run(); } else { final long now = SystemClock.elapsedRealtime(); if (now >= updateTime) { handler.post(this); } else { handler.postDelayed(this, updateTime - now); } } } @Override protected void onInactive() { handler.removeCallbacks(this); } @Override public void run() { setValue(version++); updateTime = SystemClock.elapsedRealtime() + periodInMillis; handler.postDelayed(this, periodInMillis); } } public static LiveData<Long> interval(long period, @NonNull TimeUnit unit) { return new IntervalLiveData(unit.toMillis(period)); } }
Fix test name, cover speed getter Signed-off-by: pkulev <661f9993ccc93424ad20871d2ea98bc2860e5968@gmail.com>
"""Test xoinvader.level module.""" from xoinvader.level import Level # pylint: disable=invalid-name,protected-access,missing-docstring def test_level(): e = Level() # pylint: disable=too-few-public-methods class MockObject(object): def __init__(self): self.value = 0 def add(self): self.value += 10 a = MockObject() b = MockObject() e.add_event(10, a.add) e.add_event(20, b.add) e.speed = 10 assert e.speed == 10 e.update() assert a.value == 0 assert b.value == 0 e.start() e.update() assert a.value == 10 assert b.value == 0 e.update() assert a.value == 10 assert b.value == 10 assert not e.running
"""Test xoinvader.level module.""" from xoinvader.level import Level # pylint: disable=invalid-name,protected-access,missing-docstring def test_wave(): e = Level() # pylint: disable=too-few-public-methods class MockObject(object): def __init__(self): self.value = 0 def add(self): self.value += 10 a = MockObject() b = MockObject() e.add_event(10, a.add) e.add_event(20, b.add) e.speed = 10 e.update() assert a.value == 0 assert b.value == 0 e.start() e.update() assert a.value == 10 assert b.value == 0 e.update() assert a.value == 10 assert b.value == 10 assert not e.running
Improve the js pages loading function
function loadDashboard(page, dashboard, destination) { var url = "/dashboards/page/"+dashboard+"/"+page+"/"; console.log("Getting", url); var spinner = '<div class="text-center" style="width:100%;margin-top:5em;opacity:0.6">'; spinner = spinner + '<i class="fa fa-spinner fa-spin fa-5x fa-fw"></i>\n</div>'; if ( destination === undefined) { destination = "#content" } $(destination).html(spinner); axios.get(url).then(function (response) { $(destination).html(response.data); }).catch(function (error) { console.log(error); }); $(".sparkline-embeded").each(function () { //console.log("LOAD"); var $this = $(this); $this.sparkline('html', $this.data()); console.log($this.data()) }); } $(document).ready(function () { loadDashboard("index", "{{ dashboard }}"); $(".sparkline").each(function () { //console.log("INIT"); var $this = $(this); $this.sparkline('html', $this.data()); console.log($this.data()) }); });
function loadDashboard(page, dashboard) { var url = "/dashboards/page/"+dashboard+"/"+page+"/"; console.log("Getting", url); var spinner = '<div class="text-center" style="width:100%;margin-top:5em;opacity:0.6">'; spinner = spinner + '<i class="fa fa-spinner fa-spin fa-5x fa-fw"></i>\n</div>'; $("#content").html(spinner); axios.get(url).then(function (response) { $('#content').html(response.data); }).catch(function (error) { console.log(error); }); $(".sparkline-embeded").each(function () { var $this = $(this); $this.sparkline('html', $this.data()); }); } $(document).ready(function () { loadDashboard("index", "{{ dashboard }}"); $(".sparkline").each(function () { var $this = $(this); $this.sparkline('html', $this.data()); }); });
Add named constant to explain why { } default
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. import json from .data import HathiData EMPTY_JSON_DATA = { } def load_json (json_data): try: return json.loads(json_data) except: return EMPTY_JSON_DATA def get_None_if_empty (container): return container if container else None def title_lists_in_data (data): return (x.get("titles", ()) for x in data.get("records", {}).values()) def get_titles_from_data (data): result = [ ] for title_list in title_lists_in_data(data): result.extend(title_list) return get_None_if_empty(result) def htids_in_data (data): return [x["htid"] for x in data.get("items", []) if "htid" in x] def get_htids_from_data (data): return get_None_if_empty(htids_in_data(data)) def get_hathi_data_from_json (json_data = ""): data = load_json(json_data) return HathiData(titles=get_titles_from_data(data), htids=get_htids_from_data(data))
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. import json from .data import HathiData def load_json (json_data): try: return json.loads(json_data) except: return { } def get_None_if_empty (container): return container if container else None def title_lists_in_data (data): return (x.get("titles", ()) for x in data.get("records", {}).values()) def get_titles_from_data (data): result = [ ] for title_list in title_lists_in_data(data): result.extend(title_list) return get_None_if_empty(result) def htids_in_data (data): return [x["htid"] for x in data.get("items", []) if "htid" in x] def get_htids_from_data (data): return get_None_if_empty(htids_in_data(data)) def get_hathi_data_from_json (json_data = ""): data = load_json(json_data) return HathiData(titles=get_titles_from_data(data), htids=get_htids_from_data(data))
Fix the hard-coded Elasticsearch index
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Config; use App\Providers\ElasticSearch; use Illuminate\Support\Facades\Input; Use Utils; use Request; class StudyController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } public function index() { return view('study.index'); } public function view($type, $id) { $study = ElasticSearch::get($id, env('ES_STUDY_UNIT_INDEX'), $type); //dd($study); return view('study.view') ->with('study', $study); } }
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Config; use App\Providers\ElasticSearch; use Illuminate\Support\Facades\Input; Use Utils; use Request; class StudyController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } public function index() { return view('study.index'); } public function view($type, $id) { $study = ElasticSearch::get($id, 'study', $type); //dd($study); return view('study.view') ->with('study', $study); } }
Use model namespace from config in ManyToMany model stub
/** * {{str_singular($model)}}. * * @return \Illuminate\Support\Collection; */ public function {{str_plural($model)}}() { return $this->belongsToMany('{{ config('amranidev.config.modelNameSpace') }}\{{ucfirst(str_singular($model))}}'); } /** * Assign a {{str_singular($model)}}. * * @param ${{str_singular($model)}} * @return mixed */ public function assign{{ucfirst(str_singular($model))}}(${{str_singular($model)}}) { return $this->{{str_plural($model)}}()->attach(${{str_singular($model)}}); } /** * Remove a {{str_singular($model)}}. * * @param ${{str_singular($model)}} * @return mixed */ public function remove{{ucfirst(str_singular($model))}}(${{str_singular($model)}}) { return $this->{{str_plural($model)}}()->detach(${{str_singular($model)}}); }
/** * {{str_singular($model)}}. * * @return \Illuminate\Support\Collection; */ public function {{str_plural($model)}}() { return $this->belongsToMany('App\{{ucfirst(str_singular($model))}}'); } /** * Assign a {{str_singular($model)}}. * * @param ${{str_singular($model)}} * @return mixed */ public function assign{{ucfirst(str_singular($model))}}(${{str_singular($model)}}) { return $this->{{str_plural($model)}}()->attach(${{str_singular($model)}}); } /** * Remove a {{str_singular($model)}}. * * @param ${{str_singular($model)}} * @return mixed */ public function remove{{ucfirst(str_singular($model))}}(${{str_singular($model)}}) { return $this->{{str_plural($model)}}()->detach(${{str_singular($model)}}); }
Fix creating a new index Fix when a index.collected file is not already present
const Crypto = require('crypto') const R = require('ramda') const readIndex = require('./readIndex') const hashDirectory = require('./hashDirectory') //const groupByHash = R.reduceBy((acc, item) => acc.concat(item.name), [], R.prop('sha256')) const createIndex = R.converge( (...promises) => ( Promise.all(promises) .then(R.mergeAll) .then(index => { const jsonString = JSON.stringify(index, null, 2) const bytes = Buffer.byteLength(jsonString) const hash = Crypto.createHash('sha256') hash.update(jsonString) const sha256 = hash.digest('hex') return { index, jsonString, sha256, bytes } }) ), [ R.pipe( readIndex, (promise) => promise.catch((error) => { if (error.code === 'ENOENT') { return {}; } else { console.error(error) throw error; } }) ), R.pipeP( hashDirectory, (items) => ({ items }) ) ] ) module.exports = createIndex
const Crypto = require('crypto') const R = require('ramda') const readIndex = require('./readIndex') const hashDirectory = require('./hashDirectory') //const groupByHash = R.reduceBy((acc, item) => acc.concat(item.name), [], R.prop('sha256')) const createIndex = R.converge( (...promises) => ( Promise.all(promises) .then(R.mergeAll) .then(index => { const jsonString = JSON.stringify(index, null, 2) const bytes = Buffer.byteLength(jsonString) const hash = Crypto.createHash('sha256') hash.update(jsonString) const sha256 = hash.digest('hex') return { index, jsonString, sha256, bytes } }) ), [ R.pipeP( readIndex ), R.pipeP( hashDirectory, (items) => ({ items }) ) ] ) module.exports = createIndex
Fix recount relations when using collection.
<?php namespace Websanova\EasyCache; class EasyCacheCollection extends \Illuminate\Database\Eloquent\Collection { public function recount($field, $relation = null) { foreach ($this->items as $item) { $item->recount($field, $relation); } return $this; } public function reset() { foreach ($this->items as $item) { $item->reset(); } return $this; } public function flush() { foreach ($this->items as $item) { $item->flush(); } return $this; } }
<?php namespace Websanova\EasyCache; class EasyCacheCollection extends \Illuminate\Database\Eloquent\Collection { public function recount($field) { foreach ($this->items as $item) { $item->recount($field); } return $this; } public function reset() { foreach ($this->items as $item) { $item->reset(); } return $this; } public function flush() { foreach ($this->items as $item) { $item->flush(); } return $this; } }
Prepare version number for upcoming release (2nd try)
package cgeo.geocaching.utils; import cgeo.geocaching.BuildConfig; public class BranchDetectionHelper { // should contain the version name of the last feature release public static final String FEATURE_VERSION_NAME = "2022.10.17"; // should contain version names of active bugfix releases since last feature release, oldest first // empty the part within curly brackets when creating a new release branch from master public static final String[] BUGFIX_VERSION_NAME = new String[]{ }; private BranchDetectionHelper() { // utility class } /** * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy) */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isProductionBuild() { return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly")); } /** * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build! */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isDeveloperBuild() { return BuildConfig.BUILD_TYPE.equals("debug"); } }
package cgeo.geocaching.utils; import cgeo.geocaching.BuildConfig; public class BranchDetectionHelper { // should contain the version name of the last feature release public static final String FEATURE_VERSION_NAME = "2022.10.16"; // should contain version names of active bugfix releases since last feature release, oldest first // empty the part within curly brackets when creating a new release branch from master public static final String[] BUGFIX_VERSION_NAME = new String[]{ }; private BranchDetectionHelper() { // utility class } /** * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy) */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isProductionBuild() { return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly")); } /** * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build! */ // BUILD_TYPE is detected as constant but can change depending on the build configuration @SuppressWarnings("ConstantConditions") public static boolean isDeveloperBuild() { return BuildConfig.BUILD_TYPE.equals("debug"); } }
Split host port only if collon present
package request import ( "fmt" "net" "net/http" "strings" ) // IpAddress returns client ip address from request // Will check X-Real-IP and X-Forwarded-For header. // Unless you have a trusted reverse proxy, you shouldn't use this function, the client can set headers to any arbitrary value it wants func IpAddress(r *http.Request) (net.IP, error) { addr := r.RemoteAddr if xReal := r.Header.Get("X-Real-Ip"); xReal != "" { addr = xReal } else if xForwarded := r.Header.Get("X-Forwarded-For"); xForwarded != "" { addr = xForwarded } var ip string if strings.Contains(addr, ":") { var err error ip, _, err = net.SplitHostPort(addr) if err != nil { return nil, fmt.Errorf("addr: %q is not ip:port %w", addr, err) } } userIP := net.ParseIP(ip) if userIP == nil { return nil, fmt.Errorf("ip: %q is not a valid IP address", ip) } return userIP, nil }
package request import ( "fmt" "net" "net/http" ) // IpAddress returns client ip address from request // Will check X-Real-IP and X-Forwarded-For header. // Unless you have a trusted reverse proxy, you shouldn't use this function, the client can set headers to any arbitrary value it wants func IpAddress(r *http.Request) (net.IP, error) { addr := r.RemoteAddr if xReal := r.Header.Get("X-Real-Ip"); xReal != "" { addr = xReal } else if xForwarded := r.Header.Get("X-Forwarded-For"); xForwarded != "" { addr = xForwarded } ip, _, err := net.SplitHostPort(addr) if err != nil { return nil, fmt.Errorf("addr: %q is not IP:port", addr) } userIP := net.ParseIP(ip) if userIP == nil { return nil, fmt.Errorf("ip: %q is not a valid IP address", ip) } return userIP, nil }
Fix to getShopifyApi() so it correctly returns different instances when dealing with different shops
<?php namespace RocketCode\Shopify; /** * This trait should be used to implement the interface ShopifyApiUser */ trait UsesShopifyApi { protected $api; /** * Get the Shopify API object to query Shopify * * @return \RocketCode\Shopify\API */ public function getShopifyApi() { if (!($this->api instanceof API)) { $this->api = new API([ 'API_KEY' => env('SHOPIFY_APP_ID'), 'API_SECRET' => env('SHOPIFY_APP_SECRET'), 'SHOP_DOMAIN' => $this->getDomain(), 'ACCESS_TOKEN' => $this->getAccessToken(), ]); } return $this->api; } /** * Returns the domain for the shop queried by the API * * @return string */ abstract protected function getDomain(); /** * Returns the access token for the shop queried by the API * * @return string */ abstract protected function getAccessToken(); }
<?php namespace RocketCode\Shopify; /** * This trait should be used to implement the interface ShopifyApiUser */ trait UsesShopifyApi { /** * Get the Shopify API object to query Shopify * * @return \RocketCode\Shopify\API */ public function getShopifyApi() { static $api; if (!($api instanceof API)) { $api = new API([ 'API_KEY' => env('SHOPIFY_APP_ID'), 'API_SECRET' => env('SHOPIFY_APP_SECRET'), 'SHOP_DOMAIN' => $this->getDomain(), 'ACCESS_TOKEN' => $this->getAccessToken(), ]); } return $api; } /** * Returns the domain for the shop queried by the API * * @return string */ abstract protected function getDomain(); /** * Returns the access token for the shop queried by the API * * @return string */ abstract protected function getAccessToken(); }
Add paddle inertia to calculations
#!/usr/bin/env python """ Processing routines for the waveFlapper case. """ import foampy import numpy as np import matplotlib.pyplot as plt width_2d = 0.1 width_3d = 3.66 m_paddle = 1270.0 # Paddle mass in kg, from OMB manual h_piston = 3.3147 I_paddle = 1/3*m_paddle*h_piston**2 def plot_force(): """Plots the streamwise force on the paddle over time.""" def plot_moment(): data = foampy.load_forces_moments() i = 10 t = data["time"][i:] m = data["moment"]["pressure"]["z"] + data["moment"]["viscous"]["z"] m = m[i:]*width_3d/width_2d period = 2.2 omega = 2*np.pi/period theta = 0.048*np.sin(omega*t) theta_doubledot = -0.048*omega**2*np.sin(omega*t) m_inertial = I_paddle*theta_doubledot m += m_inertial plt.figure() plt.plot(t, m) plt.xlabel("t (s)") plt.ylabel("Flapper moment (Nm)") print("Max moment from CFD =", m.max(), "Nm") print("Theoretical max moment (including inertia) =", 5500*3.3, "Nm") plt.show() if __name__ == "__main__": plot_moment()
#!/usr/bin/env python """ Processing routines for the waveFlapper case. """ import foampy import numpy as np import matplotlib.pyplot as plt width_2d = 0.1 width_3d = 3.66 def plot_force(): """Plots the streamwise force on the paddle over time.""" def plot_moment(): data = foampy.load_forces_moments() i = 10 t = data["time"][i:] m = data["moment"]["pressure"]["z"] + data["moment"]["viscous"]["z"] m = m[i:]*width_3d/width_2d plt.figure() plt.plot(t, m) plt.xlabel("t (s)") plt.ylabel("Flapper moment (Nm)") print("Max moment from CFD =", m.max(), "Nm") print("Theoretical max moment (including inertia) =", 5500*3.3, "Nm") plt.show() if __name__ == "__main__": plot_moment()
Revert "hashes are apparently not working, going to test md5 again" This reverts commit f6667a6a1c85a316caa1691b75f4aa412aa66072.
package net.thechunk.playpen.utils; import net.thechunk.playpen.protocol.Protocol; import org.apache.commons.codec.binary.Hex; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class AuthUtils { public static String createHash(String key, String message) { return createHash(key, message.getBytes(StandardCharsets.UTF_8)); } public static String createHash(String key, byte[] message) { MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } String mpk = new String(message) + key; digest.update(mpk.getBytes()); return Hex.encodeHexString(digest.digest()); } public static boolean validateHash(String hash, String key, String message) { return validateHash(hash, key, message.getBytes(StandardCharsets.UTF_8)); } public static boolean validateHash(String hash, String key, byte[] message) { return hash.equals(createHash(key, message)); } public static boolean validateHash(Protocol.AuthenticatedMessage payload, String key) { return validateHash(payload.getHash(), key, payload.getPayload().toByteArray()); } private AuthUtils() {} }
package net.thechunk.playpen.utils; import net.thechunk.playpen.protocol.Protocol; import org.apache.commons.codec.binary.Hex; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class AuthUtils { public static String createHash(String key, String message) { return createHash(key, message.getBytes(StandardCharsets.UTF_8)); } public static String createHash(String key, byte[] message) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new AssertionError(e); } String mpk = new String(message) + key; digest.update(mpk.getBytes()); return Hex.encodeHexString(digest.digest()); } public static boolean validateHash(String hash, String key, String message) { return validateHash(hash, key, message.getBytes(StandardCharsets.UTF_8)); } public static boolean validateHash(String hash, String key, byte[] message) { return hash.equals(createHash(key, message)); } public static boolean validateHash(Protocol.AuthenticatedMessage payload, String key) { return validateHash(payload.getHash(), key, payload.getPayload().toByteArray()); } private AuthUtils() {} }
Correct comparison to find out if default pairing
<?php class Userbin_SessionToken { protected $jwt; public function __construct($token) { $this->jwt = new Userbin_JWT($token); } public function __toString() { return $this->serialize(); } public function getId() { return $this->jwt->getHeader('sub'); } public function getUser() { return new Userbin_User('$current'); } public function hasDefaultPairing() { return $this->jwt->getBody('dpr') > 0; } public function hasExpired() { return $this->jwt->hasExpired(); } public function isDeviceTrusted() { return $this->jwt->getBody('tru') == 1; } public function isMFAEnabled() { return $this->jwt->getBody('mfa') == 1; } public function isMFAInProgress() { return $this->jwt->getBody('chg') == 1; } public function isMFARequired() { return $this->jwt->getBody('vfy') > 0; } public function serialize() { return $this->jwt->toString(); } }
<?php class Userbin_SessionToken { protected $jwt; public function __construct($token) { $this->jwt = new Userbin_JWT($token); } public function __toString() { return $this->serialize(); } public function getId() { return $this->jwt->getHeader('sub'); } public function getUser() { return new Userbin_User('$current'); } public function hasDefaultPairing() { return $this->jwt->getBody('dpr') == 1; } public function hasExpired() { return $this->jwt->hasExpired(); } public function isDeviceTrusted() { return $this->jwt->getBody('tru') == 1; } public function isMFAEnabled() { return $this->jwt->getBody('mfa') == 1; } public function isMFAInProgress() { return $this->jwt->getBody('chg') == 1; } public function isMFARequired() { return $this->jwt->getBody('vfy') > 0; } public function serialize() { return $this->jwt->toString(); } }
Allow case insensitive artist search
'use strict'; function escapeRegExp(string){ return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); } /** * Module dependencies. */ var mongoose = require('mongoose'), JamendoArtist = mongoose.model('JamendoArtist'), MagnatuneArtist = mongoose.model('MagnatuneArtist'), async = require('async'), _ = require('lodash'); /** * Search for artist by name */ exports.search = function(req, res) { var query = new RegExp(escapeRegExp(req.query.q), 'i'); async.parallel([ async.apply(_.bindKey(MagnatuneArtist, 'find'), {artist: query}), async.apply(_.bindKey(JamendoArtist, 'find'), {name: query}), ], function (err, results) { if (err) { res.send(400, { message: 'error', // FIXME }); } else { res.jsonp(_.flatten(results, true)); } }); };
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), JamendoArtist = mongoose.model('JamendoArtist'), MagnatuneArtist = mongoose.model('MagnatuneArtist'), async = require('async'), _ = require('lodash'); /** * Search for artist by name */ exports.search = function(req, res) { var query = req.query.q; async.parallel([ async.apply(_.bindKey(MagnatuneArtist, 'find'), {artist: query}), async.apply(_.bindKey(JamendoArtist, 'find'), {name: query}), ], function (err, results) { if (err) { res.send(400, { message: 'error', // FIXME }); } else { res.jsonp(_.flatten(results, true)); } }); };
Fix typo that causes auth error
<?php namespace Customerio; class Api { protected $siteId; protected $apiSecret; protected $request; public function __construct($siteId, $apiSecret, Request $request) { $this->siteId = $siteId; $this->apiSecret = $apiSecret; $this->request = $request; } public function createCustomer($id, $email, $attributes=array()) { return $this->request->authenticate($this->siteId, $this->apiSecret)->customer($id, $email, $attributes); } public function updateCustomer($id, $email, $attributes=array()) { return $this->createCustomer($id, $email, $attributes); } public function deleteCustomer($id) { return $this->request->authenticate($this->siteId, $this->apiSecret)->deleteCustomer($id); } public function fireEvent($id, $name, $data=array()) { return $this->request->authenticate($this->siteId, $this->apiSecret)->event($id, $name, $data); } }
<?php namespace Customerio; class Api { protected $siteId; protected $apiSecret; protected $request; public function __construct($siteId, $apiSecret, Request $request) { $this->siteId = $siteId; $this->apiSecrete = $apiSecret; $this->request = $request; } public function createCustomer($id, $email, $attributes=array()) { return $this->request->authenticate($this->siteId, $this->apiSecret)->customer($id, $email, $attributes); } public function updateCustomer($id, $email, $attributes=array()) { return $this->createCustomer($id, $email, $attributes); } public function deleteCustomer($id) { return $this->request->authenticate($this->siteId, $this->apiSecret)->deleteCustomer($id); } public function fireEvent($id, $name, $data=array()) { return $this->request->authenticate($this->siteId, $this->apiSecret)->event($id, $name, $data); } }
Refactor current user method inside Session service
import 'babel-polyfill'; import $ from 'jquery'; import Backbone from 'backbone'; import AppConfig from 'config'; import User from 'models/user'; import Storage from 'services/storage'; const SESSION_KEY = AppConfig.sessionKey; const STORAGE_KEY = AppConfig.storageKey; const EMAIL_KEY = 'email'; let currentUser = null; class Session { static currentUser() { return currentUser || (currentUser = new User(Storage.get(STORAGE_KEY))); } static create() { const deferred = $.Deferred(); if (!this.isLoggedIn()) { this.currentUser().signIn().done(() => { this.currentUser().unsetPrivateFields(); this.save(); this.trigger('create'); deferred.resolve(); }).fail(deferred.reject); } return deferred.promise(); } static destroy() { Storage.remove(STORAGE_KEY); this.currentUser().clear(); this.trigger('destroy'); } static save() { Storage.set(STORAGE_KEY, this.currentUser().toJSON()); } static isLoggedIn() { return !this.currentUser().isNew(); } static get token() { return this.currentUser().get(SESSION_KEY); } static get email() { return this.currentUser().get(EMAIL_KEY); } } Object.assign(Session, Backbone.Events); export default Session;
import 'babel-polyfill'; import $ from 'jquery'; import Backbone from 'backbone'; import AppConfig from 'config'; import User from 'models/user'; import Storage from 'services/storage'; const SESSION_KEY = AppConfig.sessionKey; const STORAGE_KEY = AppConfig.storageKey; const EMAIL_KEY = 'email'; const currentUser = new User(Storage.get(STORAGE_KEY)); class Session { static currentUser() { return currentUser; } static create() { const deferred = $.Deferred(); if (!this.isLoggedIn()) { this.currentUser().signIn().done(() => { this.currentUser().unsetPrivateFields(); this.save(); this.trigger('create'); deferred.resolve(); }).fail(deferred.reject); } return deferred.promise(); } static destroy() { Storage.remove(STORAGE_KEY); this.currentUser().clear(); this.trigger('destroy'); } static save() { Storage.set(STORAGE_KEY, this.currentUser().toJSON()); } static isLoggedIn() { return !this.currentUser().isNew(); } static get token() { return this.currentUser().get(SESSION_KEY); } static get email() { return this.currentUser().get(EMAIL_KEY); } } Object.assign(Session, Backbone.Events); export default Session;
Change Long check for Number
package org.apache.diana.api.reader; import org.apache.diana.api.ReaderField; import java.util.Date; /** * Class to reads and converts Date type * * @author Daniel Cunha - danielsoro@apache.org */ public final class DateReader implements ReaderField { @Override public boolean isCompatible(Class clazz) { return Date.class.equals(clazz); } @Override public <T> T read(Class<T> clazz, Object value) { if (Date.class.isInstance(value)) { return (T) value; } if (Number.class.isInstance(value)) { return (T) new Date(((Number) value).longValue()); } return (T) new Date(value.toString()); } }
package org.apache.diana.api.reader; import org.apache.diana.api.ReaderField; import java.util.Date; /** * Class to reads and converts Date type * * @author Daniel Cunha danielsoro@apache.org */ public final class DateReader implements ReaderField { @Override public boolean isCompatible(Class clazz) { return Date.class.equals(clazz); } @Override public <T> T read(Class<T> clazz, Object value) { if (Date.class.isInstance(value)) { return (T) value; } if (Long.class.isInstance(value)) { return (T) new Date((Long) value); } return (T) new Date(value.toString()); } }