text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add button that navigate to login 3 from login 2
import React from 'react'; import {View, Text, StyleSheet} from "react-native"; import Button from "react-native-button"; import {Actions} from "react-native-router-flux"; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "#F5FCFF", }, }); export default class extends React.Component { render(){ return ( <View style={styles.container}> <Text>Login2 page: {this.props.data}</Text> <Button onPress={Actions.pop}>Back</Button> <Button onPress={Actions.loginModal3}>Login 3</Button> </View> ); } }
import React from 'react'; import {View, Text, StyleSheet} from "react-native"; import Button from "react-native-button"; import {Actions} from "react-native-router-flux"; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "#F5FCFF", }, }); export default class extends React.Component { render(){ return ( <View style={styles.container}> <Text>Login2 page: {this.props.data}</Text> <Button onPress={Actions.pop}>Back</Button> </View> ); } }
Edit to the regular expression pattern used to identify meta-mapped references.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ''' Constant mapping appropriate quantipy types to pandas dtypes ''' DTYPE_MAP = { "float": ["float64", "float32", "float16"], "int": ["int64", "int32", "int16", "int8", "int0", "float64", "float32", "float16"], "string": ["object"], "date": ["datetime64"], "time": ["timedelta64"], "bool": ["bool"], "single": ["int64", "int32", "int16", "int8", "int0", "float64", "float32", "float16"], "dichotomous set": [], "categorical set": [], "delimited set": ["object"], "grid": [] } MAPPED_PATTERN = "^[^@].*[@].*[^@]$"
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ''' Constant mapping appropriate quantipy types to pandas dtypes ''' DTYPE_MAP = { "float": ["float64", "float32", "float16"], "int": ["int64", "int32", "int16", "int8", "int0", "float64", "float32", "float16"], "string": ["object"], "date": ["datetime64"], "time": ["timedelta64"], "bool": ["bool"], "single": ["int64", "int32", "int16", "int8", "int0", "float64", "float32", "float16"], "dichotomous set": [], "categorical set": [], "delimited set": ["object"], "grid": [] } MAPPED_PATTERN = "^[^@].+[@].+[^@]$"
Drop `author_email` - oops, excessive copy-paste
import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], )
import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', author_email='django12factor@doismellburning.co.uk', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], )
Make tensorflow be optional to allow using tensorflow-gpu
from setuptools import setup, find_packages exec(open('keras_vggface/version.py').read()) setup( name='keras_vggface', version=__version__, description='VGGFace implementation with Keras framework', url='https://github.com/rcmalli/keras-vggface', author='Refik Can MALLI', author_email="mallir@itu.edu.tr", license='MIT', keywords=['keras', 'vggface', 'deeplearning'], packages=find_packages(exclude=["temp", "test", "data", "visualize"]), zip_safe=False, install_requires=[ 'numpy>=1.9.1', 'scipy>=0.14', 'h5py', 'pillow', 'keras', 'six>=1.9.0', 'pyyaml' ], extras_require={ "tf": ["tensorflow"], "tf_gpu": ["tensorflow-gpu"], })
from setuptools import setup, find_packages exec(open('keras_vggface/version.py').read()) setup(name='keras_vggface', version=__version__, description='VGGFace implementation with Keras framework', url='https://github.com/rcmalli/keras-vggface', author='Refik Can MALLI', author_email = "mallir@itu.edu.tr", license='MIT', keywords = ['keras', 'vggface', 'deeplearning'], packages=find_packages(exclude=["temp", "test", "data", "visualize"]), zip_safe=False, install_requires=['numpy>=1.9.1', 'scipy>=0.14', 'h5py', 'pillow', 'tensorflow', 'keras', 'six>=1.9.0', 'pyyaml'])
Refresh global addresses when joining
'use strict'; angular.module('copayApp.controllers').controller('CopayersController', function($scope, $rootScope, $location, backupService, walletFactory, controllerUtils) { $scope.backup = function() { var w = $rootScope.wallet; w.setBackupReady(); backupService.download(w); }; $scope.downloadBackup = function() { var w = $rootScope.wallet; backupService.download(w); } $scope.goToWallet = function() { controllerUtils.updateGlobalAddresses(); $location.path('/receive'); }; $scope.deleteWallet = function() { var w = $rootScope.wallet; w.disconnect(); walletFactory.delete(w.id, function() { controllerUtils.logout(); }); }; // Cached list of copayers $scope.copayers = $rootScope.wallet.getRegisteredPeerIds(); $scope.copayersList = function() { return $rootScope.wallet.getRegisteredPeerIds(); } $scope.isBackupReady = function(copayer) { return $rootScope.wallet.publicKeyRing.isBackupReady(copayer.copayerId); } });
'use strict'; angular.module('copayApp.controllers').controller('CopayersController', function($scope, $rootScope, $location, backupService, walletFactory, controllerUtils) { $scope.backup = function() { var w = $rootScope.wallet; w.setBackupReady(); backupService.download(w); }; $scope.downloadBackup = function() { var w = $rootScope.wallet; backupService.download(w); } $scope.goToWallet = function() { $location.path('/receive'); }; $scope.deleteWallet = function() { var w = $rootScope.wallet; w.disconnect(); walletFactory.delete(w.id, function() { controllerUtils.logout(); }); }; // Cached list of copayers $scope.copayers = $rootScope.wallet.getRegisteredPeerIds(); $scope.copayersList = function() { return $rootScope.wallet.getRegisteredPeerIds(); } $scope.isBackupReady = function(copayer) { return $rootScope.wallet.publicKeyRing.isBackupReady(copayer.copayerId); } });
Change because of duplication issue
<?php use Interop\Container\ContainerInterface; use DI\Factory\RequestedEntry; return [ 'ActionListener' => DI\object(Sarcofag\SPI\EventManager\GenericListener::class), 'DataFilterListener' => DI\object(Sarcofag\SPI\EventManager\GenericListener::class), 'DefaultStaticPostController' => DI\object(Sarcofag\Theme\Controller\StaticPostController::class), 'DefaultStaticPageController' => DI\object(Sarcofag\Theme\Controller\StaticPostController::class), 'GenericMenu' => DI\object(Sarcofag\SPI\Menu\Menu::class), 'GenericSidebar' => DI\object(Sarcofag\SPI\Sidebar\SidebarEntry::class), 'MenuRegistry' => DI\object(Sarcofag\SPI\Menu\Registry::class), 'SidebarRegistry' => DI\object(Sarcofag\SPI\Sidebar\Registry::class), 'WidgetRegistry' => DI\object(Sarcofag\SPI\Widget\Registry::class) ];
<?php use Interop\Container\ContainerInterface; use DI\Factory\RequestedEntry; return [ 'ActionListener' => DI\object(Sarcofag\SPI\EventManager\GenericListener::class), 'DataFilterListener' => DI\object(Sarcofag\SPI\EventManager\GenericListener::class), 'DefaultStaticPostController' => DI\object(Sarcofag\Theme\Controller\StaticPostController::class), 'DefaultStaticPageController' => DI\object(Sarcofag\Theme\Controller\StaticPostController::class), 'Renderer' => DI\object(Sarcofag\View\Renderer\SimpleRenderer::class), 'GenericMenu' => DI\object(Sarcofag\SPI\Menu\Menu::class), 'GenericSidebar' => DI\object(Sarcofag\SPI\Sidebar\SidebarEntry::class), 'MenuRegistry' => DI\object(Sarcofag\SPI\Menu\Registry::class), 'SidebarRegistry' => DI\object(Sarcofag\SPI\Sidebar\Registry::class), 'WidgetRegistry' => DI\object(Sarcofag\SPI\Widget\Registry::class) ];
Update iprestrict models in initial data
"""Disable iprestriction completely.""" from iprestrict.models import RangeBasedIPGroup, IPRange, Rule def load_data(**kwargs): allow_all() def allow_all(): all_group = get_or_create_all_group() Rule.objects.all().delete() Rule.objects.create( ip_group=all_group, action='A', url_pattern='ALL', rank=65536) def get_or_create_all_group(): all_group, created = RangeBasedIPGroup.objects.get_or_create(name='ALL', description='Matches ALL IP Addresses') if created: IPRange.objects.create( ip_group=all_group, first_ip='0.0.0.0', last_ip='255.255.255.255') IPRange.objects.create( ip_group=all_group, first_ip='0:0:0:0:0:0:0:0', last_ip='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff') return all_group
"""Disable iprestriction completely.""" from iprestrict.models import IPGroup, IPRange, Rule def load_data(**kwargs): allow_all() def allow_all(): all_group = get_or_create_all_group() Rule.objects.all().delete() Rule.objects.create( ip_group=all_group, action='A', url_pattern='ALL', rank=65536) def get_or_create_all_group(): all_group, created = IPGroup.objects.get_or_create(name='ALL', description='Matches ALL IP Addresses') if created: IPRange.objects.create( ip_group=all_group, first_ip='0.0.0.0', last_ip='255.255.255.255') IPRange.objects.create( ip_group=all_group, first_ip='0:0:0:0:0:0:0:0', last_ip='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff') return all_group
Fix promisifySync case of promise arguments
// Promisify synchronous function 'use strict'; var callable = require('es5-ext/lib/Object/valid-callable') , deferred = require('../../deferred') , isPromise = require('../../is-promise') , processArguments = require('../_process-arguments') , apply = Function.prototype.apply , applyFn; applyFn = function (fn, args, resolve) { var value; try { value = apply.call(fn, this, args); } catch (e) { value = e; } resolve(value); }; module.exports = function (length) { var fn, result; fn = callable(this); if (fn.returnsPromise) { return fn; } if (length != null) { length = length >>> 0; } result = function () { var args, def; args = processArguments(arguments, length); if (isPromise(args)) { if (args.failed) { return args; } def = deferred(); args.end(function (args) { applyFn.call(this, fn, args, def.resolve); }.bind(this), def.resolve); } else { def = deferred(); applyFn.call(this, fn, args, def.resolve); } return def.promise; }; result.returnsPromise = true; return result; };
// Promisify synchronous function 'use strict'; var callable = require('es5-ext/lib/Object/valid-callable') , deferred = require('../../deferred') , isPromise = require('../../is-promise') , processArguments = require('../_process-arguments') , apply = Function.prototype.apply , applyFn; applyFn = function (fn, args, resolve) { var value; try { value = apply.call(fn, this, args); } catch (e) { value = e; } resolve(value); }; module.exports = function (length) { var fn, result; fn = callable(this); if (fn.returnsPromise) { return fn; } if (length != null) { length = length >>> 0; } result = function () { var args, def; args = processArguments(arguments, length); if (isPromise(args)) { if (args.failed) { return args; } def = deferred(); args.end(function (args) { apply.call(this, fn, args, def.resolve); }.bind(this), def.resolve); } else { def = deferred(); applyFn.call(this, fn, args, def.resolve); } return def.promise; }; result.returnsPromise = true; return result; };
Use relative imports again to support python 3
# inbuild python imports # inbuilt django imports from django.test import LiveServerTestCase # third party imports # inter-app imports # local imports from . import mixins from .mixins import SimpleTestCase class MongoTestCase(mixins.MongoTestMixin, SimpleTestCase): """ TestCase that creates a mongo collection and clears it after each test """ pass class MongoLiveServerTestCase(mixins.MongoTestMixin, LiveServerTestCase): """ TestCase that runs liveserver using mongodb instead of relational database """ pass class Neo4jTestCase(mixins.Neo4jTestMixin, SimpleTestCase): pass class MongoNeo4jTestCase(mixins.MongoNeo4jTestMixin, mixins.SimpleTestCase): pass class RedisTestCase(mixins.RedisTestMixin, mixins.SimpleTestCase): pass class MongoRedisTestCase(mixins.MongoRedisTestMixin, mixins.SimpleTestCase): pass class RedisMongoNeo4jTestCase(mixins.RedisMongoNeo4jTestMixin, mixins.SimpleTestCase): pass class APIRedisTestCase(mixins.ApiTestMixin, RedisTestCase): pass class APIMongoTestCase(mixins.ApiTestMixin, MongoTestCase): pass class APINeo4jTestCase(mixins.ApiTestMixin, Neo4jTestCase): pass class APIMongoRedisTestCase(mixins.ApiTestMixin, MongoRedisTestCase): pass class APIRedisMongoNeo4jTestCase(mixins.ApiTestMixin, RedisMongoNeo4jTestCase): pass
# inbuild python imports # inbuilt django imports from django.test import LiveServerTestCase # third party imports # inter-app imports # local imports import mixins from mixins import SimpleTestCase class MongoTestCase(mixins.MongoTestMixin, SimpleTestCase): """ TestCase that creates a mongo collection and clears it after each test """ pass class MongoLiveServerTestCase(mixins.MongoTestMixin, LiveServerTestCase): """ TestCase that runs liveserver using mongodb instead of relational database """ pass class Neo4jTestCase(mixins.Neo4jTestMixin, SimpleTestCase): pass class MongoNeo4jTestCase(mixins.MongoNeo4jTestMixin, mixins.SimpleTestCase): pass class RedisTestCase(mixins.RedisTestMixin, mixins.SimpleTestCase): pass class MongoRedisTestCase(mixins.MongoRedisTestMixin, mixins.SimpleTestCase): pass class RedisMongoNeo4jTestCase(mixins.RedisMongoNeo4jTestMixin, mixins.SimpleTestCase): pass class APIRedisTestCase(mixins.ApiTestMixin, RedisTestCase): pass class APIMongoTestCase(mixins.ApiTestMixin, MongoTestCase): pass class APINeo4jTestCase(mixins.ApiTestMixin, Neo4jTestCase): pass class APIMongoRedisTestCase(mixins.ApiTestMixin, MongoRedisTestCase): pass class APIRedisMongoNeo4jTestCase(mixins.ApiTestMixin, RedisMongoNeo4jTestCase): pass
Front: Remove reference to nonexistent file
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from shuup.front.views.product import ProductDetailView class ProductPreviewView(ProductDetailView): template_name = "shuup/front/product/product_preview.jinja" def get_context_data(self, **kwargs): # By default the template rendering the basket add form # uses the `request.path` as its' `next` value. # This is fine if you are on product page but here in # preview, we cannot redirect back to `/xtheme/product_preview`. context = super(ProductPreviewView, self).get_context_data(**kwargs) # Add `return_url` to context to avoid usage of `request.path` context["return_url"] = "/xtheme/products" return context def product_preview(request): return ProductPreviewView.as_view()(request, pk=request.GET["id"])
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from shuup.front.views.product import ProductDetailView class ProductPreviewView(ProductDetailView): template_name = "shuup/front/product/product_preview.jinja" def get_context_data(self, **kwargs): # By default the template rendering the basket add form # uses the `request.path` as its' `next` value. # This is fine if you are on product page but here in # preview, we cannot redirect back to `/xtheme/product_preview`. context = super(ProductPreviewView, self).get_context_data(**kwargs) # Add `return_url` to context to avoid usage of `request.path` in # `classic_gray/shuup/front/product/_detail_order_section.jinja` context["return_url"] = "/xtheme/products" return context def product_preview(request): return ProductPreviewView.as_view()(request, pk=request.GET["id"])
fix(exception-mapper): Return 500 errors for all unmapped exceptions
/** * Copyright (C) 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.redhat.ipaas.rest.v1.handler.exception; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component @Provider public class IPaasServerExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Exception> { private static final Logger LOG = LoggerFactory.getLogger(IPaasServerExceptionMapper.class); @Override public Response toResponse(Exception e) { LOG.error(e.getMessage(),e); RestError error = new RestError("Internal Server Exception. " + e.getMessage(), "Please contact the administrator and file a bug report", 500); return Response.status(error.errorCode).entity(error).build(); } }
/** * Copyright (C) 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.redhat.ipaas.rest.v1.handler.exception; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component @Provider public class IPaasServerExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<ClassNotFoundException> { private static final Logger LOG = LoggerFactory.getLogger(IPaasServerExceptionMapper.class); @Override public Response toResponse(ClassNotFoundException e) { LOG.error(e.getMessage(),e); RestError error = new RestError("Internal Server Exception. " + e.getMessage(), "Please contact the administrator and file a bug report", 500); return Response.status(error.errorCode).entity(error).build(); } }
Save draft button tweak on homepage
<div class="card"> <div class="card-header"> <h2>Quick Draft <small>Save a quick draft post:</small> </h2> <br> @include('canvas::shared.errors') @include('canvas::shared.success') <form class="keyboard-save" role="form" method="POST" id="postCreate" action="{{ route('canvas.admin.post.store') }}"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> @include('canvas::backend.home.partials.form') <br> <div class="form-group"> <button type="submit" class="btn btn-primary btn-icon-text"><i class="zmdi zmdi-floppy"></i> Save Draft</button> </div> </form> </div> </div>
<div class="card"> <div class="card-header"> <h2>Quick Draft <small>Save a quick draft post:</small> </h2> <br> @include('canvas::shared.errors') @include('canvas::shared.success') <form class="keyboard-save" role="form" method="POST" id="postCreate" action="{{ route('canvas.admin.post.store') }}"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> @include('canvas::backend.home.partials.form') <br> <div class="form-group"> <button type="submit" class="btn btn-primary btn-icon-text"><i class="zmdi zmdi-floppy"></i> Save</button> </div> </form> </div> </div>
Add utility function to write pvs to file
# Function to return a list of pvs from a given file import pkg_resources pkg_resources.require('aphla') import aphla as ap def get_pv_names(mode): ''' Given a certain ring mode as a string, return all available pvs ''' ap.machines.load(mode) result = set() elements = ap.getElements('*') for element in elements: pvs = element.pv() if(len(pvs) > 0): pv_name = pvs[0].split(':')[0] result.add(pv_name) return result def get_pvs_from_file(filepath): ''' Return a list of pvs from a given file ''' with open(filepath) as f: contents = f.read().splitlines() return contents def write_pvs_to_file(filename, data): ''' Write given pvs to file ''' f = open(filename, 'w') for element in data: f.write(element, '\n') f.close()
# Function to return a list of pvs from a given file import pkg_resources pkg_resources.require('aphla') import aphla as ap def get_pv_names(mode): ''' Given a certain ring mode as a string, return all available pvs ''' ap.machines.load(mode) result = set() elements = ap.getElements('*') for element in elements: pvs = element.pv() if(len(pvs) > 0): pv_name = pvs[0].split(':')[0] result.add(pv_name) return result def get_pvs_from_file(filepath): ''' Return a list of pvs from a given file ''' with open(filepath) as f: contents = f.read().splitlines() return contents
FIX deprecation warning for using assertEquals
""" Test utilities. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * import json from unittest import TestCase def parent_module(module_name): # type: (AnyStr) -> AnyStr """Return the parent module name for a module. :param module_name: module nam :type module_name: str :return: module's parent name :rtype: str >>> parent_module('zsl.application.module') 'zsl.application' """ return '.'.join(module_name.split('.')[:-1]) def json_loads(str_): # type: (AnyStr) -> Dict[str, str] """Parse json from flask response which could be in bytes in Py3.""" if isinstance(str_, bytes): str_ = str_.decode() return json.loads(str_) class HttpTestCase(TestCase): """Extends TestCase with methods for easier testing of HTTP requests.""" def assertHTTPStatus(self, status, test_value, msg): # type: (Union[int, HTTPStatus], int, AnyStr) -> None """Assert http status :param status: http status :param test_value: flask respond status :param msg: test message """ if hasattr(status, 'value'): # py2/3 status = status.value self.assertEqual(status, test_value, msg)
""" Test utilities. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from builtins import * import json from unittest import TestCase def parent_module(module_name): # type: (AnyStr) -> AnyStr """Return the parent module name for a module. :param module_name: module nam :type module_name: str :return: module's parent name :rtype: str >>> parent_module('zsl.application.module') 'zsl.application' """ return '.'.join(module_name.split('.')[:-1]) def json_loads(str_): # type: (AnyStr) -> Dict[str, str] """Parse json from flask response which could be in bytes in Py3.""" if isinstance(str_, bytes): str_ = str_.decode() return json.loads(str_) class HttpTestCase(TestCase): """Extends TestCase with methods for easier testing of HTTP requests.""" def assertHTTPStatus(self, status, test_value, msg): # type: (Union[int, HTTPStatus], int, AnyStr) -> None """Assert http status :param status: http status :param test_value: flask respond status :param msg: test message """ if hasattr(status, 'value'): # py2/3 status = status.value self.assertEquals(status, test_value, msg)
Fix extension loading functional test Call the agent _report_state() before checking the report state itself Change-Id: Idbf552d5ca5968bc95b0a3c395499c3f2d215729 Closes-Bug: 1658089
# Copyright (c) 2016 Red Hat, 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 neutron.tests.functional.agent.l2 import base class TestOVSAgentSfcExtension(base.OVSAgentTestFramework): def setUp(self): super(TestOVSAgentSfcExtension, self).setUp() self.config.set_override('extensions', ['sfc'], 'agent') self.agent = self.create_agent() def test_run(self): self.agent._report_state() agent_state = self.agent.state_rpc.report_state.call_args[0][1] self.assertEqual(['sfc'], agent_state['configurations']['extensions'])
# Copyright (c) 2016 Red Hat, 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 neutron.tests.functional.agent.l2 import base class TestOVSAgentSfcExtension(base.OVSAgentTestFramework): def setUp(self): super(TestOVSAgentSfcExtension, self).setUp() self.config.set_override('extensions', ['sfc'], 'agent') def test_run(self): agent = self.create_agent() self.start_agent(agent) agent_state = agent.state_rpc.report_state.call_args[0][1] self.assertEqual(['sfc'], agent_state['configurations']['extensions'])
Fix production build broken by tracking
import ua from 'universal-analytics' import { machineIdSync } from 'node-machine-id' import { version as appVersion } from '../package.json' import config from './config' const DEFAULT_CATEGORY = 'Cerebro App' const isTrackingEnabled = () => ( process.env.NODE_ENV === 'production' && config.get('trackingEnabled') ) let visitorCache = null const visitor = () => { if (visitorCache) { return visitorCache } if (isTrackingEnabled()) { try { visitorCache = ua('UA-87361302-1', machineIdSync(), { strictCidFormat: false }) } catch (err) { console.log('[machine-id error]', err) visitorCache = ua('UA-87361302-1') } } return visitorCache } export const screenView = (screenName) => { if (isTrackingEnabled()) { visitor().screenview(screenName, 'Cerebro', appVersion, process.platform) } } export const trackEvent = ({ category, event, label, value }) => { if (isTrackingEnabled()) { visitor().event(category || DEFAULT_CATEGORY, event, label, value).send() } }
import ua from 'universal-analytics' import { machineIdSync } from 'node-machine-id' import { version as appVersion } from '../package.json' import config from './config' const DEFAULT_CATEGORY = 'Cerebro App' const trackingEnabled = process.env.NODE_ENV === 'production' && config.get('trackingEnabled') let visitor if (trackingEnabled) { try { visitor = ua('UA-87361302-1', machineIdSync(), { strictCidFormat: false }) } catch (err) { console.log('[machine-id error]', err) visitor = ua('UA-87361302-1') } } export const screenView = (screenName) => { if (trackingEnabled) { visitor.screenview(screenName, 'Cerebro', appVersion, process.platform) } } export const trackEvent = ({ category, event, label, value }) => { if (trackingEnabled) { visitor.event(category || DEFAULT_CATEGORY, event, label, value).send() } }
Add watch task to gulp
'use strict'; const gulp = require('gulp'); const babel = require('gulp-babel'); const uglify = require('gulp-uglify'); const browserify = require('browserify'); const source = require('vinyl-source-stream'); const buffer = require('vinyl-buffer'); const del = require('del'); gulp.task('clean', () => { return del(['compiled', 'dist']); }); gulp.task('compile', ['clean'], () => { return gulp.src('src/**/*.js') .pipe(babel()) .pipe(gulp.dest('compiled')); }); gulp.task('browserify', ['compile'], () => { return browserify('compiled/astraloids.js') .transform('browserify-shader') .bundle() .pipe(source('astraloids.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('dist')); }); gulp.task('watch', () => { gulp.watch('src/**/*.js', ['browserify']); }); gulp.task('default', ['watch', 'browserify']);
'use strict'; const gulp = require('gulp'); const babel = require('gulp-babel'); const uglify = require('gulp-uglify'); const browserify = require('browserify'); const source = require('vinyl-source-stream'); const buffer = require('vinyl-buffer'); const del = require('del'); gulp.task('clean', () => { return del(['compiled', 'dist']); }); gulp.task('compile', ['clean'], () => { return gulp.src('src/**/*.js') .pipe(babel()) .pipe(gulp.dest('compiled')); }); gulp.task('browserify', ['compile'], () => { return browserify('compiled/astraloids.js') .transform('browserify-shader') .bundle() .pipe(source('astraloids.js')) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest('dist')); }); gulp.task('default', ['browserify']);
Set class on page load.
/* Leaflet.ZoomCSS Adding a css class on the map div element, so other elements, such as markers can be automatically styled based on the zoom level using css instead of javascript Copyright (c) 2014, Dag Jomar Mersland, dagjomar@gmail.com, @dagjomar https://github.com/dagjomar/Leaflet.ZoomCSS */ L.Map.mergeOptions({ zoomCss: true }); L.Map.ZoomCSS = L.Handler.extend({ addHooks: function () { this._zoomCSS(); this._map.on('zoomend', this._zoomCSS, this); }, removeHooks: function () { this._map.off('zoomend', this._zoomCSS, this); }, _zoomCSS: function (e) { var map = this._map, zoom = map.getZoom(), container = map.getContainer(); container.className = container.className.replace( /z[0-9]{1,2}/g, '' ) + ' z' + zoom; } }); L.Map.addInitHook('addHandler', 'zoomCss', L.Map.ZoomCSS);
/* Leaflet.ZoomCSS Adding a css class on the map div element, so other elements, such as markers can be automatically styled based on the zoom level using css instead of javascript Copyright (c) 2014, Dag Jomar Mersland, dagjomar@gmail.com, @dagjomar https://github.com/dagjomar/Leaflet.ZoomCSS */ L.Map.mergeOptions({ zoomCss: true }); L.Map.ZoomCSS = L.Handler.extend({ addHooks: function () { this._map.on('zoomend', this._zoomCSS, this); }, removeHooks: function () { this._map.off('zoomend', this._zoomCSS, this); }, _zoomCSS: function (e) { var map = this._map, zoom = map.getZoom(), container = map.getContainer(); container.className = container.className.replace( /z[0-9]{1,2}/g, '' ) + ' z' + zoom; } }); L.Map.addInitHook('addHandler', 'zoomCss', L.Map.ZoomCSS);
Use a choices for specifiying type of reporter
# -*- coding: utf-8 -*- import sys import argparse from mamba import application_factory, __version__ from mamba.infrastructure import is_python3 def main(): arguments = _parse_arguments() if arguments.version: print(__version__) return factory = application_factory.ApplicationFactory(arguments) runner = factory.create_runner() runner.run() if runner.has_failed_examples: sys.exit(1) def _parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('--version', '-v', default=False, action='store_true', help='Display the version.') parser.add_argument('--slow', '-s', default=0.075, type=float, help='Slow test threshold in seconds (default: %(default)s)') parser.add_argument('--enable-coverage', default=False, action='store_true', help='Enable code coverage measurement (default: %(default)s)') parser.add_argument('--format', '-f', default='documentation', action='store', choices=['documentation', 'progress'], help='Output format (default: %(default)s)') parser.add_argument('specs', default=['spec'], nargs='*', help='Specs or directories with specs to run (default: %(default)s)') if not is_python3(): parser.add_argument('--watch', '-w', default=False, action='store_true', help='Enable file watching support - not available with python3 (default: %(default)s)') return parser.parse_args() if __name__ == '__main__': main()
# -*- coding: utf-8 -*- import sys import argparse from mamba import application_factory, __version__ from mamba.infrastructure import is_python3 def main(): arguments = _parse_arguments() if arguments.version: print(__version__) return factory = application_factory.ApplicationFactory(arguments) runner = factory.create_runner() runner.run() if runner.has_failed_examples: sys.exit(1) def _parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument('--version', '-v', default=False, action='store_true', help='Display the version.') parser.add_argument('--slow', '-s', default=0.075, type=float, help='Slow test threshold in seconds (default: %(default)s)') parser.add_argument('--enable-coverage', default=False, action='store_true', help='Enable code coverage measurement (default: %(default)s)') parser.add_argument('--format', '-f', default='documentation', action='store', help='Output format (default: %(default)s)') parser.add_argument('specs', default=['spec'], nargs='*', help='Specs or directories with specs to run (default: %(default)s)') if not is_python3(): parser.add_argument('--watch', '-w', default=False, action='store_true', help='Enable file watching support - not available with python3 (default: %(default)s)') return parser.parse_args() if __name__ == '__main__': main()
Use numeric value for day of week in CRON expression.
export default (app) => { app.jobs.schedule('send audit email', '0 16 * * 6', async () => { app.info('CRON: sending audit email - starting') const mailerConfig = app.get('mailer') const recipients = mailerConfig.auditRecipients && mailerConfig.auditRecipients.split(',') app.info(`recipients: ${JSON.stringify(recipients)}`) if (recipients) { await Promise.all( recipients.map(async (recipient) => { await app.service('admin/audit').find({ query: { email: 'true', recipient }, }) }) ) } else { app.info('CRON: no audit recipients specified, no audit email sent') } app.info('CRON: sending audit email - done') }) }
export default (app) => { app.jobs.schedule('send audit email', '0 16 * * FRI', async () => { app.info('CRON: sending audit email - starting') const mailerConfig = app.get('mailer') const recipients = mailerConfig.auditRecipients && mailerConfig.auditRecipients.split(',') if (recipients) { await Promise.all( recipients.map(async (recipient) => { await app.service('admin/audit').find({ query: { email: 'true', recipient }, }) }) ) } else { app.info('CRON: no audit recipients specified, no audit email sent') } app.info('CRON: sending audit email - done') }) }
Update ver 0.1 Beta (Build 7) plg_system examples
<?php require("bin/fw.php"); define('N', "\n"); define('BR', "<br />"); define('BRN', "<br />\n"); # plg_visitor echo "You are using ".browserName." ver ".browserVer." on ".platformFamily." ".(is64bit ? "64 bit" : "32 bit")." from ".getIP().BRN; # plg_dump $arr = array("Defined Variables"=>get_defined_vars(), "Defined Constants"=>get_defined_constants()); echo dump($arr, TRUE, TRUE).BRN; # plg_system echo 'echo clean_number(\'4f32k91025\'); <span style="color: orange; font-style: italic"># will output '.clean_number('4f32k91025').'</span>'.BRN; echo 'echo decimal_to_fraction(\'.125\'); <span style="color: orange; font-style: italic"># will output </span>'.decimal_to_fraction ('.125').'</span>'.BRN;
<?php require("bin/fw.php"); define('N', "\n"); define('BR', "<br />"); define('BRN', "<br />\n"); # plg_visitor echo "You are using ".browserName." ver ".browserVer." on ".platformFamily." ".(is64bit ? "64 bit" : "32 bit")." from ".getIP().BRN; # plg_dump $arr = array("Defined Variables"=>get_defined_vars(), "Defined Constants"=>get_defined_constants()); echo dump($arr, TRUE, TRUE).BRN; # plg_system echo 'echo clean_number(\'4f32k91025\'); <span style="color: orange; font-style: italic"># will output '.clean_number('4f32k91025').'</span>'.BRN; echo 'echo decimal_to_fraction(\'.675\'); <span style="color: orange; font-style: italic"># will output </span>'.decimal_to_fraction ('.675').'</span>'.BRN;
Move these to macros, the exact type of these functions changes by deifne
# 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. INCLUDES = """ #include <openssl/pkcs12.h> """ TYPES = """ typedef ... PKCS12; """ FUNCTIONS = """ void PKCS12_free(PKCS12 *); PKCS12 *d2i_PKCS12_bio(BIO *, PKCS12 **); int i2d_PKCS12_bio(BIO *, PKCS12 *); """ MACROS = """ int PKCS12_parse(PKCS12 *, const char *, EVP_PKEY **, X509 **, struct stack_st_X509 **); PKCS12 *PKCS12_create(char *, char *, EVP_PKEY *, X509 *, struct stack_st_X509 *, int, int, int, int, int); """
# 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. INCLUDES = """ #include <openssl/pkcs12.h> """ TYPES = """ typedef ... PKCS12; """ FUNCTIONS = """ int PKCS12_parse(PKCS12 *, const char *, EVP_PKEY **, X509 **, struct stack_st_X509 **); PKCS12 *PKCS12_create(char *, char *, EVP_PKEY *, X509 *, struct stack_st_X509 *, int, int, int, int, int); void PKCS12_free(PKCS12 *); PKCS12 *d2i_PKCS12_bio(BIO *, PKCS12 **); int i2d_PKCS12_bio(BIO *, PKCS12 *); """ MACROS = """ """
Implement navigation to engine class.
package net.bitpot.railways.models.routes; import com.intellij.openapi.module.Module; import net.bitpot.railways.gui.RailwaysIcons; import net.bitpot.railways.models.Route; import net.bitpot.railways.models.requestMethods.RequestMethod; import net.bitpot.railways.utils.RailwaysPsiUtils; import net.bitpot.railways.utils.RailwaysUtils; import org.jetbrains.plugins.ruby.ruby.lang.psi.holders.RContainer; import javax.swing.*; /** * @author Basil Gren * on 14.12.2014. */ public class EngineRoute extends Route { private String engineClass; public EngineRoute(Module myModule, RequestMethod requestMethod, String routePath, String routeName, String engineClass) { super(myModule, requestMethod, routePath, routeName); this.engineClass = engineClass; } @Override public String getQualifiedActionTitle() { return engineClass; } @Override public Icon getActionIcon() { return RailwaysIcons.NODE_MOUNTED_ENGINE; } @Override public void navigate(boolean requestFocus) { RContainer container = RailwaysPsiUtils. findClassOrModule(engineClass, getModule().getProject()); if (container != null) container.navigate(requestFocus); } }
package net.bitpot.railways.models.routes; import com.intellij.openapi.module.Module; import net.bitpot.railways.gui.RailwaysIcons; import net.bitpot.railways.models.Route; import net.bitpot.railways.models.requestMethods.RequestMethod; import javax.swing.*; /** * @author Basil Gren * on 14.12.2014. */ public class EngineRoute extends Route { private String engineClass; public EngineRoute(Module myModule, RequestMethod requestMethod, String routePath, String routeName, String engineClass) { super(myModule, requestMethod, routePath, routeName); this.engineClass = engineClass; } @Override public String getQualifiedActionTitle() { return engineClass; } @Override public Icon getActionIcon() { return RailwaysIcons.NODE_MOUNTED_ENGINE; } }
Fix error reported by jshint
/** * Run script for Grunt, task runner * * The MIT License (MIT) * Copyright (c) 2015 GochoMugo <mugo@forfuture.co.ke> */ "use strict"; exports = module.exports = function(grunt) { grunt.initConfig({ benchmark: { all: { src: ["benchmark/*.js"], dest: "benchmark/results.csv" } }, jshint: { all: [ "Gruntfile.js", "lib/**/*.js", "test/**/*.js", "benchmark/**/*.js" ], options: { jshintrc: true } }, mochaTest: { test: { options: { reporter: "spec", quiet: false, clearRequireCache: false }, src: ["test/test.*.js"] } } }); grunt.loadNpmTasks("grunt-benchmark"); grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-mocha-test"); grunt.registerTask("test", ["jshint", "mochaTest", "benchmark"]); };
/** * Run script for Grunt, task runner * * The MIT License (MIT) * Copyright (c) 2015 GochoMugo <mugo@forfuture.co.ke> */ exports = module.exports = function(grunt) { "use strict"; grunt.initConfig({ benchmark: { all: { src: ["benchmark/*.js"], dest: "benchmark/results.csv" } }, jshint: { all: [ "Gruntfile.js", "lib/**/*.js", "test/**/*.js", "benchmark/**/*.js" ], options: { jshintrc: true } }, mochaTest: { test: { options: { reporter: "spec", quiet: false, clearRequireCache: false }, src: ["test/test.*.js"] } } }); grunt.loadNpmTasks("grunt-benchmark"); grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-mocha-test"); grunt.registerTask("test", ["jshint", "mochaTest", "benchmark"]); };
Fix count() method that might not return a relevant result
<?php namespace BenTools\ETL\Tests\Iterator; use BenTools\ETL\Iterator\CsvFileIterator; use BenTools\ETL\Tests\TestSuite; use PHPUnit\Framework\TestCase; class CsvFileIteratorTest extends TestCase { public function testIterator() { $file = new \SplFileObject(TestSuite::getDataFile('dictators.csv')); $iterator = new CsvFileIterator($file); $this->assertCount(3, $iterator); $this->assertEquals([ [ 'country', 'name', ], [ 'USA', 'Donald Trump', ], [ 'Russia', 'Vladimir Poutine', ], ], array_values(iterator_to_array($iterator))); } }
<?php namespace BenTools\ETL\Tests\Iterator; use BenTools\ETL\Iterator\CsvFileIterator; use BenTools\ETL\Tests\TestSuite; use PHPUnit\Framework\TestCase; class CsvFileIteratorTest extends TestCase { public function testIterator() { $file = new \SplFileObject(TestSuite::getDataFile('dictators.csv')); $iterator = new CsvFileIterator($file); $this->assertEquals([ [ 'country', 'name', ], [ 'USA', 'Donald Trump', ], [ 'Russia', 'Vladimir Poutine', ], ], array_values(iterator_to_array($iterator))); } }
Fix sending of empty string
'use strict'; const debug = require('debug')('sockjs:connection'); const stream = require('stream'); const uuid = require('uuid/v4'); class SockJSConnection extends stream.Duplex { constructor(session) { super({ decodeStrings: false, encoding: 'utf8', readableObjectMode: true }); this._session = session; this.id = uuid(); this.headers = {}; this.prefix = this._session.prefix; debug('new connection', this.id, this.prefix); } toString() { return `<SockJSConnection ${this.id}>`; } _write(chunk, encoding, callback) { if (Buffer.isBuffer(chunk)) { chunk = chunk.toString(); } this._session.send(chunk); callback(); } _read() { } end(chunk, encoding, callback) { super.end(chunk, encoding, callback); this.close(); } close(code, reason) { debug('close', code, reason); return this._session.close(code, reason); } get readyState() { return this._session.readyState; } } module.exports = SockJSConnection;
'use strict'; const debug = require('debug')('sockjs:connection'); const stream = require('stream'); const uuid = require('uuid/v4'); class SockJSConnection extends stream.Duplex { constructor(session) { super({ decodeStrings: false, encoding: 'utf8' }); this._session = session; this.id = uuid(); this.headers = {}; this.prefix = this._session.prefix; debug('new connection', this.id, this.prefix); } toString() { return `<SockJSConnection ${this.id}>`; } _write(chunk, encoding, callback) { if (Buffer.isBuffer(chunk)) { chunk = chunk.toString(); } this._session.send(chunk); callback(); } _read() { } end(chunk, encoding, callback) { super.end(chunk, encoding, callback); this.close(); } close(code, reason) { debug('close', code, reason); return this._session.close(code, reason); } get readyState() { return this._session.readyState; } } module.exports = SockJSConnection;
Revert "Tests default to MySQL strict" This reverts commit 53d1ba7fcfa1e238b8e24e8071436ced8f45ec58.
<?php namespace Pheasant\Tests; class MysqlTestCase extends \PHPUnit_Framework_TestCase { public function setUp() { // initialize a new pheasant $this->pheasant = \Pheasant::setup( 'mysql://root@localhost/pheasanttest?charset=utf8&strict=false' ); // wipe sequence pool $this->pheasant->connection() ->sequencePool() ->initialize() ->clear() ; } // Helper to return a connection public function connection() { return $this->pheasant->connection(); } // Helper to drop and re-create a table public function table($name, $columns) { $table = $this->pheasant->connection()->table($name); if($table->exists()) $table->drop(); $table->create($columns); $this->assertTableExists($name); return $table; } public function assertConnectionExists() { $this->assertTrue($this->pheasant->connection()); } public function assertTableExists($table) { $this->assertTrue($this->pheasant->connection()->table($table)->exists()); } public function assertRowCount($sql, $count) { $result = $this->connection()->execute($sql); $this->assertEquals($result->count(), $count); } }
<?php namespace Pheasant\Tests; class MysqlTestCase extends \PHPUnit_Framework_TestCase { public function setUp() { // initialize a new pheasant $this->pheasant = \Pheasant::setup( 'mysql://root@localhost/pheasanttest?charset=utf8&strict=true' ); // wipe sequence pool $this->pheasant->connection() ->sequencePool() ->initialize() ->clear() ; } // Helper to return a connection public function connection() { return $this->pheasant->connection(); } // Helper to drop and re-create a table public function table($name, $columns) { $table = $this->pheasant->connection()->table($name); if($table->exists()) $table->drop(); $table->create($columns); $this->assertTableExists($name); return $table; } public function assertConnectionExists() { $this->assertTrue($this->pheasant->connection()); } public function assertTableExists($table) { $this->assertTrue($this->pheasant->connection()->table($table)->exists()); } public function assertRowCount($sql, $count) { $result = $this->connection()->execute($sql); $this->assertEquals($result->count(), $count); } }
Fix test: use sortable because builtin does not accept third parameter.
<?php namespace Mimic\Test; use PHPUnit_Framework_TestCase; use Mimic\Functional as F; /** * Unit Test for sort Mimic library function. * * @since 0.1.0 */ class SortFuncTest extends PHPUnit_Framework_TestCase { public function dataProvider() { return array( array(false, F\sortable(), array(4, 2, 1, 3), array(1, 2, 3, 4)), array(true, F\sortable(), array(4, 2, 1, 3), array(2 => 1, 1 => 2, 3 => 3, 0 => 4)), array(false, F\sortable(), array('2', '1', 'world', 'hello'), array('1', '2', 'hello', 'world') ), array(true, F\sortable(), array('2', '1', 'world', 'hello'), array(2 => '1', 0 => '2', 4 => 'hello', 3 => 'world') ), ); } /** * @dataProvider dataProvider * @covers ::Mimic\Functional\sort */ public function testResults($preserveKeys, $callback, $collection, $expected) { $this->assertEquals($expected, F\sort($collection, $callback, $preserveKeys)); } }
<?php namespace Mimic\Test; use PHPUnit_Framework_TestCase; use Mimic\Functional as F; /** * Unit Test for sort Mimic library function. * * @since 0.1.0 */ class SortFuncTest extends PHPUnit_Framework_TestCase { public function dataProvider() { return array( array(false, F\sortable(), array(4, 2, 1, 3), array(1, 2, 3, 4)), array(true, F\sortable(), array(4, 2, 1, 3), array(2 => 1, 1 => 2, 3 => 3, 0 => 4)), array(false, 'strcasecmp', array('2', '1', 'world', 'hello'), array('1', '2', 'hello', 'world') ), array(true, 'strcasecmp', array('2', '1', 'world', 'hello'), array(2 => '1', 0 => '2', 4 => 'hello', 3 => 'world') ), ); } /** * @dataProvider dataProvider * @covers ::Mimic\Functional\sort */ public function testResults($preserveKeys, $callback, $collection, $expected) { $this->assertEquals($expected, F\sort($collection, $callback, $preserveKeys)); } }
Fix package version and remove django from list of required packages.
from distutils.core import setup LONG_DESC = """ Unicode URLS in django.""" setup( name='unicode_urls', packages=['unicode_urls', 'unicode_urls.django', 'unicode_urls.cms'], version='0.2.1', long_description=LONG_DESC, description='Unicode urls.', author='Alex Gavrisco', author_email='alexandr@gavrisco.com', url='', download_url='', keywords=['django', 'urls', 'unicode', 'cms', 'djangocms', 'django-cms'], license='MIT', classifiers=[ 'Programming Language :: Python', 'Operating System :: OS Independent', 'Natural Language :: English', 'Development Status :: Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', ] )
from distutils.core import setup LONG_DESC = """ Unicode URLS in django.""" setup( name='unicode_urls', packages=['unicode_urls', 'unicode_urls.django', 'unicode_urls.cms'], version='0.0.1', long_description=LONG_DESC, description='Unicode urls.', author='Alex Gavrisco', author_email='alexandr@gavrisco.com', url='', download_url='', keywords=['django', 'urls', 'unicode', 'cms', 'djangocms', 'django-cms'], license='MIT', classifiers=[ 'Programming Language :: Python', 'Operating System :: OS Independent', 'Natural Language :: English', 'Development Status :: Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', ], install_requires=[ 'django>=1.7', ] )
Fix eclipse error message on mod_wsgi import Signed-off-by: Jonathan Dieter <ddc8e8b9809278692339ab749e05e6020a8d4c9a@lesbg.com>
# lesson/main.py # # This file is part of LESSON. LESSON is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2 or later. # # 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 General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright (C) 2012 Jonathan Dieter <jdieter@lesbg.com> import sys, os abspath = os.path.dirname(__file__) if abspath not in sys.path: sys.path.append(abspath) os.chdir(abspath) import render mode = "debug" try: from mod_wsgi import version #@UnresolvedImport print "Detected mod_wgi version %i.%i" % version mode = "wsgi" except: pass application = render.start(mode)
# lesson/main.py # # This file is part of LESSON. LESSON is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2 or later. # # 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 General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright (C) 2012 Jonathan Dieter <jdieter@lesbg.com> import sys, os abspath = os.path.dirname(__file__) if abspath not in sys.path: sys.path.append(abspath) os.chdir(abspath) import render mode = "debug" try: from mod_wsgi import version print "Detected mod_wgi version %i.%i" % version mode = "wsgi" except: pass application = render.start(mode)
Increase max password size so it works with the default Heroku-generated password of 64 characters
package io.github.jhipster.registry.web.rest.dto; import javax.validation.constraints.*; /** * A DTO representing a user's credentials */ public class LoginDTO { @NotNull @Size(min = 1, max = 50) private String username; @NotNull @Size(min = 5, max = 64) private String password; private Boolean rememberMe; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Boolean isRememberMe() { return rememberMe; } public void setRememberMe(Boolean rememberMe) { this.rememberMe = rememberMe; } @Override public String toString() { return "LoginDTO{" + "password='" + password + '\'' + ", username='" + username + '\'' + ", rememberMe=" + rememberMe + '}'; } }
package io.github.jhipster.registry.web.rest.dto; import javax.validation.constraints.*; /** * A DTO representing a user's credentials */ public class LoginDTO { @NotNull @Size(min = 1, max = 50) private String username; @NotNull @Size(min = 5, max = 50) private String password; private Boolean rememberMe; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Boolean isRememberMe() { return rememberMe; } public void setRememberMe(Boolean rememberMe) { this.rememberMe = rememberMe; } @Override public String toString() { return "LoginDTO{" + "password='" + password + '\'' + ", username='" + username + '\'' + ", rememberMe=" + rememberMe + '}'; } }
Remove + / - buttons
const h = require('virtual-dom/h'); module.exports = function (data) { const {gameID, game} = data; return h('div', {className: 'room'}, [ game.playing ? null : h('form', {method: 'post', action: `/${gameID}`}, [ h('input', {type: 'number', name: 'max-score', min: '1', value: game.maxScore}), h('button', {type: 'submit'}, 'Start') ]), h('a', {href: '/new-player/' + gameID}, 'Wanna play along?'), h('div', {id: 'players'}, [ h('ul', Object.keys(game.players).map(playerID => { const player = game.players[playerID]; return h('li', { style: { backgroundColor: `rgb(${player.color[1]}, ${player.color[0]}, ${player.color[2]})` }, dataPlayerId: playerID }, 'Score: ' + player.score) })) ]) ]); };
const h = require('virtual-dom/h'); module.exports = function (data) { const {gameID, game} = data; return h('div', {className: 'room'}, [ game.playing ? null : h('form', {method: 'post', action: `/${gameID}`}, [ h('button', {type: 'button', id: 'min'}, '-'), h('input', {type: 'number', name: 'max-score', min: '1', value: game.maxScore}), h('button', {type: 'button', id: 'max'}, '+'), h('button', {type: 'submit'}, 'Start') ]), h('a', {href: '/new-player/' + gameID}, 'Wanna play along?'), h('div', {id: 'players'}, [ h('ul', Object.keys(game.players).map(playerID => { const player = game.players[playerID]; return h('li', { style: { backgroundColor: `rgb(${player.color[1]}, ${player.color[0]}, ${player.color[2]})` }, dataPlayerId: playerID }, 'Score: ' + player.score) })) ]) ]); };
Fix unit test by adding new namespace
<?php /** * @author Jaisen Mathai <jaisen@jmathai.com> * @copyright Copyright 2015, Jaisen Mathai */ namespace JMathai\S3BucketStreamZipTest; use JMathai\S3BucketStreamZip\S3BucketStreamZip; use PHPUnit_Framework_TestCase; class S3BucketStreamZipTest extends PHPUnit_Framework_TestCase { /** * @expectedException \JMathai\S3BucketStreamZip\Exception\InvalidParameterException */ public function testInvalidParamsToConstructorKey() { $client = new S3BucketStreamZip(array(), array()); } /** * @expectedException \JMathai\S3BucketStreamZip\Exception\InvalidParameterException */ public function testInvalidParamsToConstructorSecret() { $client = new S3BucketStreamZip(array('key' => 'foo'), array()); } /** * @expectedException \JMathai\S3BucketStreamZip\Exception\InvalidParameterException */ public function testInvalidParamsToConstructorBucket() { $client = new S3BucketStreamZip(array('key' => 'foo', 'secret' => 'bar'), array()); } public function testValidParamsToConstructor() { $client = new S3BucketStreamZip(array('key' => 'foo', 'secret' => 'bar'), array('Bucket' => 'foobar')); } }
<?php /** * @author Jaisen Mathai <jaisen@jmathai.com> * @copyright Copyright 2015, Jaisen Mathai */ namespace S3BucketStreamZipTest; use S3BucketStreamZip\S3BucketStreamZip; use PHPUnit_Framework_TestCase; class S3BucketStreamZipTest extends PHPUnit_Framework_TestCase { /** * @expectedException \S3BucketStreamZip\Exception\InvalidParameterException */ public function testInvalidParamsToConstructorKey() { $client = new S3BucketStreamZip(array(), array()); } /** * @expectedException \S3BucketStreamZip\Exception\InvalidParameterException */ public function testInvalidParamsToConstructorSecret() { $client = new S3BucketStreamZip(array('key' => 'foo'), array()); } /** * @expectedException \S3BucketStreamZip\Exception\InvalidParameterException */ public function testInvalidParamsToConstructorBucket() { $client = new S3BucketStreamZip(array('key' => 'foo', 'secret' => 'bar'), array()); } public function testValidParamsToConstructor() { $client = new S3BucketStreamZip(array('key' => 'foo', 'secret' => 'bar'), array('Bucket' => 'foobar')); } }
Make lyra export work thanks to @RussellSprouts and @arvind.
'use strict'; angular.module('vleApp') .directive('lyraExport', function () { return { template: '<a href="#" ng-click="export()">export to lyra...</a>', restrict: 'E', controller: function ($scope, $timeout, Vegalite, Alerts) { $scope.export = function() { var vegaSpec = Vegalite.vegaSpec; if (!vegaSpec) { Alerts.add('No vega spec present.'); } // Hack needed. See https://github.com/uwdata/lyra/issues/214 vegaSpec.marks[0]['lyra.groupType'] = 'layer'; console.log(vegaSpec) var lyraURL = 'http://idl.cs.washington.edu/projects/lyra/app/'; var lyraWindow = window.open(lyraURL, '_blank'); // HACK // lyraWindow.onload doesn't work across domains $timeout(function() { Alerts.add('Please check whether lyra loaded the vega spec correctly. This feature is experimental and may not work.', 5000); lyraWindow.postMessage({spec: vegaSpec}, lyraURL); }, 5000); } } }; });
'use strict'; angular.module('vleApp') .directive('lyraExport', function () { return { template: '<a href="#" ng-click="export()">export to lyra...</a>', restrict: 'E', controller: function ($scope, $timeout, Vegalite, Alerts) { $scope.export = function() { var vegaSpec = Vegalite.vegaSpec; if (!vegaSpec) { Alerts.add('No vega spec present.'); } var lyraURL = 'http://idl.cs.washington.edu/projects/lyra/app/'; var lyraWindow = window.open(lyraURL, '_blank'); // HACK // lyraWindow.onload doesn't work across domains $timeout(function() { Alerts.add('Please check whether lyra loaded the vega spec correctly. This feature is experimental and may not work.', 5000); lyraWindow.postMessage({spec: vegaSpec}, lyraURL); }, 5000); } } }; });
Remove CfP, add Committee page
<?php /******************************************************************************* * Copyright (c) 2015 Eclipse Foundation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Christopher Guindon (Eclipse Foundation) - Initial implementation *******************************************************************************/ if (!defined('ABSPATH')) exit; ?> <ul class="nav navbar-nav navbar-right"> <!--<li><a href="./cfp.php">Call For Proposals</a></li>--> <li><a href="./index.php#registration">Register</a></li> <li><a href="./Committee.php">Our Committee</a></li> <li><a href="./terms.php">Terms</a></li> <li><a href="./conduct.php">Code of Conduct</a></li> <li><a href="./index.php#schedule">Schedule</a></li> <li><a href="./index.php#sponsorship">Sponsorship</a></li> </ul>
<?php /******************************************************************************* * Copyright (c) 2015 Eclipse Foundation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Christopher Guindon (Eclipse Foundation) - Initial implementation *******************************************************************************/ if (!defined('ABSPATH')) exit; ?> <ul class="nav navbar-nav navbar-right"> <li><a href="./cfp.php">Call For Proposals</a></li> <li><a href="./index.php#registration">Register</a></li> <li><a href="./terms.php">Terms</a></li> <li><a href="./conduct.php">Code of Conduct</a></li> <li><a href="./index.php#schedule">Schedule</a></li> <li><a href="./index.php#sponsorship">Sponsorship</a></li> </ul>
Change the search path to look locally In order to use tools/build.py, we need to search locally for imports. Closes-bug: #1592030 Change-Id: Idfa651c1268f93366de9f4e3fa80c33be42c71c3
#!/usr/bin/env python # 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 os import sys PROJECT_ROOT = os.path.abspath(os.path.join( os.path.dirname(os.path.realpath(__file__)), '../..')) if PROJECT_ROOT not in sys.path: sys.path.insert(0, PROJECT_ROOT) from kolla.image import build def main(): statuses = build.run_build() if statuses: bad_results, good_results, unmatched_results = statuses if bad_results: return 1 return 0 if __name__ == '__main__': main()
#!/usr/bin/env python # 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 kolla.image import build def main(): statuses = build.run_build() if statuses: bad_results, good_results, unmatched_results = statuses if bad_results: return 1 return 0 if __name__ == '__main__': main()
Use next to get the zone
import os import types from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase): def setUp(self): configure_services('cloudflare', ['cloudflare'], conf.common) self.cloudflare = CloudFlareService() def test_iter_zones(self): zone = next(self.cloudflare.iter_zones()) self.assertIsInstance(zone, dict) def test_get_zone(self): zone_id = next(self.cloudflare.iter_zones())['id'] zone = self.cloudflare.get_zone(zone_id) self.assertIsInstance(zone, dict)
import os import types from unittest import TestCase from yoconfigurator.base import read_config from yoconfig import configure_services from pycloudflare.services import CloudFlareService app_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) conf = read_config(app_dir) class ZonesTest(TestCase): def setUp(self): configure_services('cloudflare', ['cloudflare'], conf.common) self.cloudflare = CloudFlareService() def test_iter_zones(self): zone = next(self.cloudflare.iter_zones()) self.assertIsInstance(zone, dict) def test_get_zone(self): zone_id = self.cloudflare.get_zones()[0]['id'] zone = self.cloudflare.get_zone(zone_id) self.assertIsInstance(zone, dict)
Fix undefined `$items` variable in `devtoolsProjectList.tpl` By simply extending the `MultipleLinkPage` class, the `$items` variable is automatically set. See #2354
<?php namespace wcf\acp\page; use wcf\data\devtools\project\DevtoolsProjectList; use wcf\page\MultipleLinkPage; /** * Shows a list of devtools projects. * * @author Alexander Ebert * @copyright 2001-2017 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Acp\Page * @since 3.1 */ class DevtoolsProjectListPage extends MultipleLinkPage { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.devtools.project.list'; /** * @inheritDoc */ public $itemsPerPage = PHP_INT_MAX; /** * @inheritDoc */ public $objectListClassName = DevtoolsProjectList::class; /** * @inheritDoc */ public $neededModules = ['ENABLE_DEVELOPER_TOOLS']; /** * @inheritDoc */ public $neededPermissions = ['admin.configuration.package.canInstallPackage']; /** * @var DevtoolsProjectList */ public $objectList; }
<?php namespace wcf\acp\page; use wcf\data\devtools\project\DevtoolsProjectList; use wcf\page\AbstractPage; use wcf\system\WCF; /** * Shows a list of devtools projects. * * @author Alexander Ebert * @copyright 2001-2017 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\Acp\Page * @since 3.1 */ class DevtoolsProjectListPage extends AbstractPage { /** * @inheritDoc */ public $activeMenuItem = 'wcf.acp.menu.link.devtools.project.list'; /** * @inheritDoc */ public $neededModules = ['ENABLE_DEVELOPER_TOOLS']; /** * @inheritDoc */ public $neededPermissions = ['admin.configuration.package.canInstallPackage']; /** * @var DevtoolsProjectList */ public $objectList; /** * @inheritDoc */ public function readData() { parent::readData(); $this->objectList = new DevtoolsProjectList(); $this->objectList->readObjects(); } /** * @inheritDoc */ public function assignVariables() { parent::assignVariables(); WCF::getTPL()->assign([ 'objects' => $this->objectList ]); } }
Update factory. Reset migrations & add fake data again
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ /** @var \Illuminate\Database\Eloquent\Factory $factory */ $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'username' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), '2fa_token' => null, 'last_ip' => $faker->ipv4, 'active' => $faker->boolean, 'rank' => $faker->boolean ? 'member' : 'admin', 'remember_token' => str_random(10), ]; });
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ /** @var \Illuminate\Database\Eloquent\Factory $factory */ $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'username' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), '2fa_token' => null, 'last_ip' => $faker->ipv4, 'active' => $faker->boolean, 'remember_token' => str_random(10), ]; });
Remove deprecated methods encoding in lib/x509util.GetPermittedMethods().
package x509util import ( "crypto/x509" "encoding/asn1" "fmt" "github.com/Symantec/Dominator/lib/constants" "strings" ) func getPermittedMethods(cert *x509.Certificate) (map[string]struct{}, error) { methodList := make(map[string]struct{}) for _, extension := range cert.Extensions { if extension.Id.String() != constants.PermittedMethodListOID { continue } var lines []string rest, err := asn1.Unmarshal(extension.Value, &lines) if err != nil { return nil, err } if len(rest) > 0 { return nil, fmt.Errorf("%d extra bytes in method extension", len(rest)) } for _, sm := range lines { if strings.Count(sm, ".") == 1 { methodList[sm] = struct{}{} } else { return nil, fmt.Errorf("bad line: \"%s\"", sm) } } return methodList, nil } return methodList, nil }
package x509util import ( "crypto/x509" "encoding/asn1" "fmt" "github.com/Symantec/Dominator/lib/constants" "strings" ) func getPermittedMethods(cert *x509.Certificate) (map[string]struct{}, error) { methodList := make(map[string]struct{}) for _, extension := range cert.Extensions { if extension.Id.String() != constants.PermittedMethodListOID { continue } var lines []string rest, err := asn1.Unmarshal(extension.Value, &lines) if err != nil { return nil, err } if len(rest) > 0 { return nil, fmt.Errorf("%d extra bytes in method extension", len(rest)) } for _, sm := range lines { if strings.Count(sm, ".") == 1 { methodList[sm] = struct{}{} } else { return nil, fmt.Errorf("bad line: \"%s\"", sm) } } return methodList, nil } // Fallback to deprecated location. for _, sm := range strings.Split(cert.Subject.CommonName, ",") { if strings.Count(sm, ".") == 1 { methodList[sm] = struct{}{} } } return methodList, nil }
Add missing type hint for field_schema parameter
from typing import Any, Callable, Dict, Iterable, Optional, Type from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile from pydantic.fields import ModelField __all__ = ["UploadedFile"] class UploadedFile(DjangoUploadedFile): @classmethod def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]: yield cls._validate @classmethod def _validate(cls: Type["UploadedFile"], v: Any) -> Any: if not isinstance(v, DjangoUploadedFile): raise ValueError(f"Expected UploadFile, received: {type(v)}") return v @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any], field: Optional[ModelField]): field_schema.update(type="string", format="binary")
from typing import Any, Callable, Iterable, Optional, Type from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile from pydantic.fields import ModelField __all__ = ["UploadedFile"] class UploadedFile(DjangoUploadedFile): @classmethod def __get_validators__(cls: Type["UploadedFile"]) -> Iterable[Callable[..., Any]]: yield cls._validate @classmethod def _validate(cls: Type["UploadedFile"], v: Any) -> Any: if not isinstance(v, DjangoUploadedFile): raise ValueError(f"Expected UploadFile, received: {type(v)}") return v @classmethod def __modify_schema__(cls, field_schema, field: Optional[ModelField]): field_schema.update(type="string", format="binary")
Use app storage sub path
<?php return array( /* |-------------------------------------------------------------------------- | Service |-------------------------------------------------------------------------- | | Current only supports 'maxmind'. | */ 'service' => 'maxmind', /* |-------------------------------------------------------------------------- | Services settings |-------------------------------------------------------------------------- | | Service specific settings. | */ 'maxmind' => array( 'type' => env('GEOIP_DRIVER', 'database'), // database or web_service 'user_id' => env('GEOIP_USER_ID'), 'license_key' => env('GEOIP_LICENSE_KEY'), 'database_path' => storage_path('app/geoip.mmdb'), ), /* |-------------------------------------------------------------------------- | Default Location |-------------------------------------------------------------------------- | | Return when a location is not found. | */ 'default_location' => array ( "ip" => "127.0.0.0", "isoCode" => "US", "country" => "United States", "city" => "New Haven", "state" => "CT", "postal_code" => "06510", "lat" => 41.31, "lon" => -72.92, "timezone" => "America/New_York", "continent" => "NA", ), );
<?php return array( /* |-------------------------------------------------------------------------- | Service |-------------------------------------------------------------------------- | | Current only supports 'maxmind'. | */ 'service' => 'maxmind', /* |-------------------------------------------------------------------------- | Services settings |-------------------------------------------------------------------------- | | Service specific settings. | */ 'maxmind' => array( 'type' => env('GEOIP_DRIVER', 'database'), // database or web_service 'user_id' => env('GEOIP_USER_ID'), 'license_key' => env('GEOIP_LICENSE_KEY'), 'database_path' => storage_path('geoip.mmdb'), ), /* |-------------------------------------------------------------------------- | Default Location |-------------------------------------------------------------------------- | | Return when a location is not found. | */ 'default_location' => array ( "ip" => "127.0.0.0", "isoCode" => "US", "country" => "United States", "city" => "New Haven", "state" => "CT", "postal_code" => "06510", "lat" => 41.31, "lon" => -72.92, "timezone" => "America/New_York", "continent" => "NA", ), );
Add data to log for spec map
<?php /** * Humbug * * @category Humbug * @package Humbug * @copyright Copyright (c) 2015 Pádraic Brady (http://blog.astrumfutura.com) * @license https://github.com/padraic/humbug/blob/master/LICENSE New BSD License */ namespace Humbug\PhpSpec\Listener; use Humbug\PhpSpec\Logger\JsonSpecMapLogger; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use PhpSpec\Event\ExampleEvent; use PhpSpec\Event\SpecificationEvent; use PhpSpec\Event\SuiteEvent; class SpecMapperListener implements EventSubscriberInterface { public function __construct(JsonSpecMapLogger $logger) { $this->logger = $logger; } public static function getSubscribedEvents() { return [ 'afterSpecification' => ['afterSpecification', -10], ]; } public function afterSpecification(SpecificationEvent $event) { $this->logger->logSpecification( $event->getClass()->getFile(), $event->getTitle(), $event->getClass()->name, ); } public function afterSuite(SuiteEvent $event) { $this->logger->write(); } }
<?php /** * Humbug * * @category Humbug * @package Humbug * @copyright Copyright (c) 2015 Pádraic Brady (http://blog.astrumfutura.com) * @license https://github.com/padraic/humbug/blob/master/LICENSE New BSD License */ namespace Humbug\PhpSpec\Listener; use Humbug\PhpSpec\Logger\JsonSpecMapLogger; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use PhpSpec\Event\ExampleEvent; use PhpSpec\Event\SpecificationEvent; use PhpSpec\Event\SuiteEvent; class SpecMapperListener implements EventSubscriberInterface { public function __construct(JsonSpecMapLogger $logger) { $this->logger = $logger; } public static function getSubscribedEvents() { return [ 'afterSpecification' => ['afterSpecification', -10], ]; } public function afterSpecification(SpecificationEvent $event) { $this->logger->logSpecification( $event->getTitle(), $event->getTime() ); } public function afterSuite(SuiteEvent $event) { $this->logger->write(); } }
Update SWFError with a formatted type
# -*- coding: utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. class SWFError(Exception): def __init__(self, message, raw_error, *args): Exception.__init__(self, message, *args) self.kind, self.details = raw_error.split(':') self.type_ = self.kind.lower().strip().replace(' ', '_') if self.kind else None def __repr__(self): msg = self.message if self.kind and self.details: msg += '\nReason: {}, {}'.format(self.kind, self.details) return msg def __str__(self): msg = self.message if self.kind and self.details: msg += '\nReason: {}, {}'.format(self.kind, self.details) return msg class PollTimeout(SWFError): pass class InvalidCredentialsError(SWFError): pass class ResponseError(SWFError): pass class DoesNotExistError(SWFError): pass class AlreadyExistsError(SWFError): pass class InvalidKeywordArgumentError(SWFError): pass
# -*- coding: utf-8 -*- # Copyright (c) 2013, Theo Crevon # Copyright (c) 2013, Greg Leclercq # # See the file LICENSE for copying permission. class SWFError(Exception): def __init__(self, message, raw_error, *args): Exception.__init__(self, message, *args) self.kind, self.details = raw_error.split(':') def __repr__(self): msg = self.message if self.kind and self.details: msg += '\nReason: {}, {}'.format(self.kind, self.details) return msg def __str__(self): msg = self.message if self.kind and self.details: msg += '\nReason: {}, {}'.format(self.kind, self.details) return msg class PollTimeout(SWFError): pass class InvalidCredentialsError(SWFError): pass class ResponseError(SWFError): pass class DoesNotExistError(SWFError): pass class AlreadyExistsError(SWFError): pass class InvalidKeywordArgumentError(SWFError): pass
Change to removed widget namespace in views
/* ************************************************************************ ${Name} Copyright: 2010 Deutsche Telekom AG, Germany, http://telekom.com ************************************************************************ */ /* ************************************************************************ #asset(${NamespacePath}/*) ************************************************************************ */ /** * Unify application class */ qx.Class.define("${Namespace}.Application", { extend : unify.Application, members : { // overridden main : function() { // Call super class this.base(arguments); // Set theme qx.theme.manager.Meta.getInstance().setTheme(unify.theme.Dark); // Configure application document.title = "${Name}"; // Create view managers var MasterViewManager = new unify.view.ViewManager("master"); // Register your view classes... MasterViewManager.add(${Namespace}.view.Start, true); // Add TabViews or SplitViews... var TabView = new unify.view.TabViewManager(MasterViewManager); TabView.add(${Namespace}.view.Start); // Add view manager (or SplitView or TabView) to the root this.add(TabView); // Add at least one view manager to the navigation managment var Navigation = unify.view.Navigation.getInstance(); Navigation.add(MasterViewManager); Navigation.init(); } } });
/* ************************************************************************ ${Name} Copyright: 2010 Deutsche Telekom AG, Germany, http://telekom.com ************************************************************************ */ /* ************************************************************************ #asset(${NamespacePath}/*) ************************************************************************ */ /** * Unify application class */ qx.Class.define("${Namespace}.Application", { extend : unify.Application, members : { // overridden main : function() { // Call super class this.base(arguments); // Set theme qx.theme.manager.Meta.getInstance().setTheme(unify.theme.Dark); // Configure application document.title = "${Name}"; // Create view managers var MasterViewManager = new unify.view.widget.ViewManager("master"); // Register your view classes... MasterViewManager.add(${Namespace}.view.Start, true); // Add TabViews or SplitViews... var TabView = new unify.view.widget.TabViewManager(MasterViewManager); TabView.add(${Namespace}.view.Start); // Add view manager (or SplitView or TabView) to the root this.add(TabView); // Add at least one view manager to the navigation managment var Navigation = unify.view.Navigation.getInstance(); Navigation.add(MasterViewManager); Navigation.init(); } } });
Add Manage App Store link
<?php define('COOKIE_SESSION', true); require_once("../config.php"); session_start(); require_once("gate.php"); if ( $REDIRECTED === true || ! isset($_SESSION["admin"]) ) return; setcookie("adminmenu","true", 0, "/"); \Tsugi\Core\LTIX::getConnection(); $OUTPUT->header(); $OUTPUT->bodyStart(); $OUTPUT->topNav(); ?> <h1>Welcome Adminstrator</h1> <ul> <li><a href="upgrade.php" target="_new">Upgrade Database</a></li> <li><a href="nonce.php" target="_new">Check Nonces</a></li> <li><a href="context/index.php">View Contexts</a></li> <?php if ( $CFG->providekeys ) { ?> <li><a href="key/index.php">Manage Access Keys</a></li> <?php } ?> <li><a href="install/index.php">Manage Installed Modules</a></li> </ul> <?php $OUTPUT->footer();
<?php define('COOKIE_SESSION', true); require_once("../config.php"); session_start(); require_once("gate.php"); if ( $REDIRECTED === true || ! isset($_SESSION["admin"]) ) return; setcookie("adminmenu","true", 0, "/"); \Tsugi\Core\LTIX::getConnection(); $OUTPUT->header(); $OUTPUT->bodyStart(); $OUTPUT->topNav(); ?> <h1>Welcome Adminstrator</h1> <ul> <li><a href="upgrade.php" target="_new">Upgrade Database</a></li> <li><a href="nonce.php" target="_new">Check Nonces</a></li> <li><a href="context/index.php">View Contexts</a></li> <?php if ( $CFG->providekeys ) { ?> <li><a href="key/index.php">Manage Access Keys</a></li> <?php } ?> </ul> <?php $OUTPUT->footer();
Fix problem introduced during recent refactor
/* * Copyright 2020 Crown Copyright * * 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 stroom.event.logging.rs.impl; import javax.annotation.Nullable; public class MockRequestEventLog implements RequestEventLog { @Override public void log(final RequestInfo info, @Nullable final Object responseEntity) { } @Override public void log(final RequestInfo info, @Nullable final Object responseEntity, final Throwable error) { } }
/* * Copyright 2020 Crown Copyright * * 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 stroom.event.logging.rs.impl; import stroom.rs.logging.impl.RequestInfo; import javax.annotation.Nullable; public class MockRequestEventLog implements RequestEventLog { @Override public void log(final RequestInfo info, @Nullable final Object responseEntity) { } @Override public void log(final RequestInfo info, @Nullable final Object responseEntity, final Throwable error) { } }
Change merge order for default data
<?php namespace StickyNotes; /** * Sticky Notes * * An open source lightweight pastebin application * * @package StickyNotes * @author Sayak Banerjee * @copyright (c) 2013 Sayak Banerjee <mail@sayakbanerjee.com> * @license http://www.opensource.org/licenses/bsd-license.php * @link http://sayakbanerjee.com/sticky-notes * @since Version 1.0 * @filesource */ /** * Response class * * Abstraction over \Illuminate\Support\Facades\Response to enable skin support * * @package StickyNotes * @subpackage Libraries * @author Sayak Banerjee */ class Response extends \Illuminate\Support\Facades\Response { /** * This abstraction over the base method injects the skin name * and default view data. * * @param string $view * @param array $data * @param int $status * @param array $headers * @return \Illuminate\View\View */ public static function view($view, $data = array(), $status = 200, array $headers = array()) { $data = array_merge(View::defaults(), $data); return parent::view(View::skin($view), $data, $status, $headers); } }
<?php namespace StickyNotes; /** * Sticky Notes * * An open source lightweight pastebin application * * @package StickyNotes * @author Sayak Banerjee * @copyright (c) 2013 Sayak Banerjee <mail@sayakbanerjee.com> * @license http://www.opensource.org/licenses/bsd-license.php * @link http://sayakbanerjee.com/sticky-notes * @since Version 1.0 * @filesource */ /** * Response class * * Abstraction over \Illuminate\Support\Facades\Response to enable skin support * * @package StickyNotes * @subpackage Libraries * @author Sayak Banerjee */ class Response extends \Illuminate\Support\Facades\Response { /** * This abstraction over the base method injects the skin name * and default view data. * * @param string $view * @param array $data * @param int $status * @param array $headers * @return \Illuminate\View\View */ public static function view($view, $data = array(), $status = 200, array $headers = array()) { $data = array_merge($data, View::defaults()); return parent::view(View::skin($view), $data, $status, $headers); } }
Update composite section to handle notifications
package ca.antonious.viewcelladapter.sections; import java.util.ArrayList; import java.util.List; import ca.antonious.viewcelladapter.internal.SectionObserver; import ca.antonious.viewcelladapter.viewcells.AbstractViewCell; import ca.antonious.viewcelladapter.utils.ViewCellUtils; /** * Created by George on 2016-12-17. */ public class CompositeSection extends AbstractSection implements SectionObserver { private List<AbstractSection> sections; public CompositeSection() { this.sections = new ArrayList<>(); } @Override public AbstractViewCell get(int position) { return ViewCellUtils.getViewCell(sections, position); } @Override public void remove(int position) { int sectionIndex = ViewCellUtils.getSectionIndex(sections, position); int viewCellIndex = ViewCellUtils.getViewCellIndex(sections, position); sections.get(sectionIndex).remove(viewCellIndex); } @Override public int getItemCount() { return ViewCellUtils.getTotalCount(sections); } public CompositeSection addSection(AbstractSection section) { section.addObserver(this); sections.add(section); return this; } public CompositeSection removeSection(AbstractSection section) { section.removeObserver(this); sections.remove(section); return this; } @Override public void onDataChanged() { notifyDataChanged(); } }
package ca.antonious.viewcelladapter.sections; import java.util.ArrayList; import java.util.List; import ca.antonious.viewcelladapter.viewcells.AbstractViewCell; import ca.antonious.viewcelladapter.utils.ViewCellUtils; /** * Created by George on 2016-12-17. */ public class CompositeSection extends AbstractSection { private List<AbstractSection> sections; public CompositeSection() { this.sections = new ArrayList<>(); } @Override public AbstractViewCell get(int position) { return ViewCellUtils.getViewCell(sections, position); } @Override public void remove(int position) { int sectionIndex = ViewCellUtils.getSectionIndex(sections, position); int viewCellIndex = ViewCellUtils.getViewCellIndex(sections, position); sections.get(sectionIndex).remove(viewCellIndex); } @Override public int getItemCount() { return ViewCellUtils.getTotalCount(sections); } public CompositeSection addSection(AbstractSection section) { sections.add(section); return this; } public CompositeSection removeSection(AbstractSection section) { sections.remove(section); return this; } }
Delete init code (mount App)
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import './index.css'; import App from './App'; import { CoursesListPage } from './pages/courses-list/couses-list'; import { CoursesItemPage } from './pages/courses-item/courses-item'; import { CoursesNewPage } from './pages/courses-new/courses-new'; ReactDOM.render(( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={CoursesListPage}/> <Route path="/courses" component={CoursesListPage} /> <Route path="/courses/new" component={CoursesNewPage}/> <Route path="/courses/:id" component={CoursesItemPage}/> </Route> </Router> ), document.getElementById('root') );
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import './index.css'; import App from './App'; import { CoursesListPage } from './pages/courses-list/couses-list'; import { CoursesItemPage } from './pages/courses-item/courses-item'; import { CoursesNewPage } from './pages/courses-new/courses-new'; ReactDOM.render( <App />, document.getElementById('root') ); ReactDOM.render(( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={CoursesListPage}/> <Route path="/courses" component={CoursesListPage} /> <Route path="/courses/new" component={CoursesNewPage}/> <Route path="/courses/:id" component={CoursesItemPage}/> </Route> </Router> ), document.getElementById('root') );
Fix is ajax change in custom actions
import client from './client' import superagent from 'superagent' export default { getCustomActions (callback) { client.get('/api/data/custom-actions', callback) }, newCustomAction (customAction, callback) { const data = { name: customAction.name, url: customAction.url } client.post('/api/data/custom-actions/', data, callback) }, updateCustomAction (customAction, callback) { const data = { name: customAction.name, url: customAction.url, entity_type: customAction.entityType, is_ajax: customAction.isAjax === 'true' } client.put(`/api/data/custom-actions/${customAction.id}`, data, callback) }, deleteCustomAction (customAction, callback) { client.del(`/api/data/custom-actions/${customAction.id}`, callback) }, postCustomAction (url, data) { return new Promise((resolve, reject) => { superagent .post(url) .withCredentials() .send(data) .end((err, res) => { if (err) reject(err) else resolve() }) }) } }
import client from './client' import superagent from 'superagent' export default { getCustomActions (callback) { client.get('/api/data/custom-actions', callback) }, newCustomAction (customAction, callback) { const data = { name: customAction.name, url: customAction.url } client.post('/api/data/custom-actions/', data, callback) }, updateCustomAction (customAction, callback) { const data = { name: customAction.name, url: customAction.url, entity_type: customAction.entityType, is_ajax: Boolean(customAction.isAjax) } client.put(`/api/data/custom-actions/${customAction.id}`, data, callback) }, deleteCustomAction (customAction, callback) { client.del(`/api/data/custom-actions/${customAction.id}`, callback) }, postCustomAction (url, data) { return new Promise((resolve, reject) => { superagent .post(url) .withCredentials() .send(data) .end((err, res) => { if (err) reject(err) else resolve() }) }) } }
Use class methods for unittests
import unittest from app import create_app, db from app.utils import get_or_create from app.models import User class TestUtils(unittest.TestCase): def setUp(self): self.app = create_app("testing") self.app_ctx = self.app.app_context() self.app_ctx.push() db.create_all() def tearDown(self): db.session.remove() db.drop_all() self.app_ctx.pop() def test_get_or_create(self): user1, created1 = get_or_create(User, name="foo", social_id="bar") db.session.add(user1) db.session.commit() user2, created2 = get_or_create(User, name="foo", social_id="bar") self.assertTrue(created1) self.assertFalse(created2) self.assertEquals(user1, user2)
import unittest from app import create_app, db from app.utils import get_or_create from app.models import User class TestUtils(unittest.TestCase): def setUp(self): self.app = create_app("testing") self.app_ctx = self.app.app_context() self.app_ctx.push() db.create_all() def tearDown(self): db.session.remove() db.drop_all() self.app_ctx.pop() def test_get_or_create(self): user1, created1 = get_or_create(User, name="foo", social_id="bar") db.session.add(user1) db.session.commit() user2, created2 = get_or_create(User, name="foo", social_id="bar") assert created1 assert not created2 assert user1 == user2
Use GuiUtils instead of extending Gui
package mezz.jei.gui; import cpw.mods.fml.client.config.GuiUtils; import mezz.jei.api.gui.IDrawable; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; import javax.annotation.Nonnull; public class DrawableResource implements IDrawable { @Nonnull private final ResourceLocation resourceLocation; private final int u; private final int v; private final int width; private final int height; public DrawableResource(@Nonnull ResourceLocation resourceLocation, int u, int v, int width, int height) { this.resourceLocation = resourceLocation; this.u = u; this.v = v; this.width = width; this.height = height; } @Override public int getWidth() { return width; } @Override public int getHeight() { return height; } public void draw(@Nonnull Minecraft minecraft) { minecraft.getTextureManager().bindTexture(resourceLocation); GuiUtils.drawTexturedModalRect(0, 0, u, v, width, height, 0); } }
package mezz.jei.gui; import mezz.jei.api.gui.IDrawable; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.util.ResourceLocation; import javax.annotation.Nonnull; public class DrawableResource extends Gui implements IDrawable { @Nonnull private final ResourceLocation resourceLocation; private final int u; private final int v; private final int width; private final int height; public DrawableResource(@Nonnull ResourceLocation resourceLocation, int u, int v, int width, int height) { this.resourceLocation = resourceLocation; this.u = u; this.v = v; this.width = width; this.height = height; } @Override public int getWidth() { return width; } @Override public int getHeight() { return height; } public void draw(@Nonnull Minecraft minecraft) { minecraft.getTextureManager().bindTexture(resourceLocation); this.drawTexturedModalRect(0, 0, u, v, width, height); } }
Update the playground to support custom services
/*global Playground*/ (function() { "use strict"; Playground.VideoService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.videoPort = port; } }); Playground.SurveyService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.surveyPort = port; } }); Playground.SlotMachine = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.slotMachinePort = port; } }); Playground.AdPlaylistService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.adPlaylistPort = port; }, events: { surveyTaken: function (data) { this.sandbox.slotMachinePort.send('addCoin'); } } }); $.extend(Playground, { initializeServices: function () { this.conductor.addDefaultCapability('video', Playground.VideoService); this.conductor.addDefaultCapability('survey', Playground.SurveyService); this.conductor.addDefaultCapability('slotMachine', Playground.SlotMachine); } }); })();
/*global Playground*/ (function() { "use strict"; Playground.VideoService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.videoPort = port; } }); Playground.SurveyService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.surveyPort = port; } }); Playground.SlotMachine = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.slotMachinePort = port; } }); Playground.AdPlaylistService = Conductor.Oasis.Service.extend({ initialize: function (port) { this.sandbox.adPlaylistPort = port; }, events: { surveyTaken: function (data) { this.sandbox.slotMachinePort.send('addCoin'); } } }); $.extend(Playground, { initializeServices: function () { Conductor.services.video = Playground.VideoService; Conductor.services.survey = Playground.SurveyService; Conductor.services.slotMachine = Playground.SlotMachine; } }); })();
Use str type instead of bytes in Python 2
""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (str, bytearray, buffer) else: # Python 2.7 BYTES_TYPES = (str, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return str(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data
""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (3, 4) if PY3: BYTES_TYPES = (bytes, bytearray, memoryview) elif PY26: BYTES_TYPES = (bytes, bytearray, buffer) else: BYTES_TYPES = (bytes, bytearray, memoryview, buffer) def flatten_bytes(data): """ Convert bytes-like objects (bytes, bytearray, memoryview, buffer) to a bytes string. """ if not isinstance(data, BYTES_TYPES): raise TypeError('data argument must be byte-ish (%r)', type(data)) if PY34: # In Python 3.4, socket.send() and bytes.join() accept memoryview # and bytearray return data if not data: return b'' if not PY3 and isinstance(data, (buffer, bytearray)): return bytes(data) elif not PY26 and isinstance(data, memoryview): return data.tobytes() else: return data
Use docblock tag instead of a plain php comment. This prevents accidentally exporting the ::build() method on the XML-RPC server. svn commit r1712
<?php require_once 'Swat/SwatPage.php'; require_once 'XML/RPC2/Server.php'; /** * Base class for an XML-RPC Server * * The XML-RPC server acts as a regular page in an application . This means * all the regular page security features work for XML-RPC servers. * * Swat XML-RPC server pages use the PEAR::XML_RPC2 package to service * requests. * * @package Swat * @copyright 2005 silverorange * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 */ abstract class SwatXMLRPCServer extends SwatPage { /** * Process the request * * This method is called by site code to process the page request. It creates * an XML-RPC server and handles a request. The XML-RPC response from the * server is output here as well. * * @xmlrpc.hidden */ public function process() { $server = XML_RPC2_Server::create($this); ob_start(); $server->handleCall(); // TODO: remove workaround when php-5.0.5 is commonplace $x = ob_get_clean(); $this->layout->response = $x; } /** * @xmlrpc.hidden */ public function build() { } protected function createLayout() { return new SwatLayout('Swat/layouts/xmlrpcserver.php'); } } ?>
<?php require_once 'Swat/SwatPage.php'; require_once 'XML/RPC2/Server.php'; /** * Base class for an XML-RPC Server * * The XML-RPC server acts as a regular page in an application . This means * all the regular page security features work for XML-RPC servers. * * Swat XML-RPC server pages use the PEAR::XML_RPC2 package to service * requests. * * @package Swat * @copyright 2005 silverorange * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 */ abstract class SwatXMLRPCServer extends SwatPage { /** * Process the request * * This method is called by site code to process the page request. It creates * an XML-RPC server and handles a request. The XML-RPC response from the * server is output here as well. * * @xmlrpc.hidden */ public function process() { $server = XML_RPC2_Server::create($this); ob_start(); $server->handleCall(); // TODO: remove workaround when php-5.0.5 is commonplace $x = ob_get_clean(); $this->layout->response = $x; } /* * @xmlrpc.hidden */ public function build() { } protected function createLayout() { return new SwatLayout('Swat/layouts/xmlrpcserver.php'); } } ?>
Load scripts in debug mode Bug: T124633 Change-Id: I82d1366428e529c541297e6848fa0e71678c270c
<?php /** * ResourceLoader module providing extra data to the client-side. * * @file * @ingroup Extensions */ namespace Kartographer; use ResourceLoader; use ResourceLoaderContext; use ResourceLoaderModule; class DataModule extends ResourceLoaderModule { protected $origin = self::ORIGIN_USER_SITEWIDE; protected $targets = array( 'desktop', 'mobile' ); public function getScript( ResourceLoaderContext $context ) { $config = $context->getResourceLoader()->getConfig(); return ResourceLoader::makeConfigSetScript( array( 'wgKartographerMapServer' => $config->get( 'KartographerMapServer' ), 'wgKartographerIconServer' => $config->get( 'KartographerIconServer' ), 'wgKartographerSrcsetScales' => $config->get( 'KartographerSrcsetScales' ), 'wgKartographerStyles' => $config->get( 'KartographerStyles' ), 'wgKartographerDfltStyle' => $config->get( 'KartographerDfltStyle' ), ) ); } public function enableModuleContentVersion() { return true; } /** * @see ResourceLoaderModule::supportsURLLoading * * @return bool */ public function supportsURLLoading() { return false; // always use getScript() to acquire JavaScript (even in debug mode) } }
<?php /** * ResourceLoader module providing extra data to the client-side. * * @file * @ingroup Extensions */ namespace Kartographer; use ResourceLoader; use ResourceLoaderContext; use ResourceLoaderModule; class DataModule extends ResourceLoaderModule { protected $origin = self::ORIGIN_USER_SITEWIDE; protected $targets = array( 'desktop', 'mobile' ); public function getScript( ResourceLoaderContext $context ) { $config = $context->getResourceLoader()->getConfig(); return ResourceLoader::makeConfigSetScript( array( 'wgKartographerMapServer' => $config->get( 'KartographerMapServer' ), 'wgKartographerIconServer' => $config->get( 'KartographerIconServer' ), 'wgKartographerSrcsetScales' => $config->get( 'KartographerSrcsetScales' ), 'wgKartographerStyles' => $config->get( 'KartographerStyles' ), 'wgKartographerDfltStyle' => $config->get( 'KartographerDfltStyle' ), ) ); } public function enableModuleContentVersion() { return true; } }
Remove south from test requirements
from setuptools import setup, find_packages setup( name = "django-report-builder", version = "2.0.2", author = "David Burke", author_email = "david@burkesoftware.com", description = ("Query and Report builder for Django ORM"), license = "BSD", keywords = "django report", url = "https://github.com/burke-software/django-report-builder", packages=find_packages(), include_package_data=True, test_suite='setuptest.setuptest.SetupTestSuite', tests_require=( 'django-setuptest', 'argparse', ), classifiers=[ "Development Status :: 5 - Production/Stable", 'Environment :: Web Environment', 'Framework :: Django', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', "License :: OSI Approved :: BSD License", ], install_requires=[ 'django>=1.4', 'openpyxl', 'python-dateutil', 'django-report-utils>=0.2.3', ] )
from setuptools import setup, find_packages setup( name = "django-report-builder", version = "2.0.2", author = "David Burke", author_email = "david@burkesoftware.com", description = ("Query and Report builder for Django ORM"), license = "BSD", keywords = "django report", url = "https://github.com/burke-software/django-report-builder", packages=find_packages(), include_package_data=True, test_suite='setuptest.setuptest.SetupTestSuite', tests_require=( 'django-setuptest', 'south', 'argparse', ), classifiers=[ "Development Status :: 5 - Production/Stable", 'Environment :: Web Environment', 'Framework :: Django', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', "License :: OSI Approved :: BSD License", ], install_requires=[ 'django>=1.4', 'openpyxl', 'python-dateutil', 'django-report-utils>=0.2.3', ] )
Test XHR throw ex on mailformed URL. On branch rc1 modified: firefox/content/prototype.js
var Q = require("events"); var HTTP = require("http"); var P; window.addEventListener("load", function (e) { var r = HTTP.create(); var p = r.send("GET", "htt://www.foodoes_not_exist/"); dump("call to r.send() returned\n"); p.then( function (res) { dump("RESPONSE status:\n"+ res.status +"\n"); res.headers = 44; }, function (e) {dump("Got exception. \n"+ e +"\n");}). then( function (res) { dump("RESPONSE HEADERS:\n"+ res.headers +"\n"); res.headers = 7; }, function (e) {dump("Got exception. \n"+ e +"\n");} ); dump("call to r.then() returned\n"); P = p; }, false);
var Q = require("events"); var HTTP = require("http"); var P; window.addEventListener("load", function (e) { var r = HTTP.create(); var p = r.send("GET", "http://www.foodoes_not_exist/"); dump("call to r.send() returned\n"); p.then( function (res) { dump("RESPONSE status:\n"+ res.status +"\n"); res.headers = 44; }, function (e) {dump("Got exception. \n"+ e +"\n");}). then( function (res) { dump("RESPONSE HEADERS:\n"+ res.headers +"\n"); res.headers = 7; }, function (e) {dump("Got exception. \n"+ e +"\n");} ); dump("call to r.then() returned\n"); P = p; }, false);
Fix bug: KeyError: 'HOME' in Windows.
#!/usr/bin/env python """ Utility to copy ROUGE script. It has to be run before `setup.py` """ import os import shutil from files2rouge import settings from six.moves import input def copy_rouge(): if 'HOME' not in os.environ: home = os.environ['HOMEPATH'] else: home = os.environ['HOME'] src_rouge_root = "./files2rouge/RELEASE-1.5.5/" default_root = os.path.join(home, '.files2rouge/') print("files2rouge uses scripts and tools that will not be stored with " "the python package") path = input( "where do you want to save it? [default: %s]" % default_root) if path == "": path = default_root rouge_data = os.path.join(path, "data") rouge_path = os.path.join(path, "ROUGE-1.5.5.pl") print("Copying '%s' to '%s'" % (src_rouge_root, path)) shutil.copytree(src_rouge_root, path) return {"ROUGE_path": rouge_path, "ROUGE_data": rouge_data} conf_path = "./files2rouge/settings.json" s = settings.Settings(path=conf_path) data = copy_rouge() s._generate(data)
#!/usr/bin/env python """ Utility to copy ROUGE script. It has to be run before `setup.py` """ import os import shutil from files2rouge import settings from six.moves import input def copy_rouge(): home = os.environ['HOME'] src_rouge_root = "./files2rouge/RELEASE-1.5.5/" default_root = os.path.join(home, '.files2rouge/') print("files2rouge uses scripts and tools that will not be stored with " "the python package") path = input( "where do you want to save it? [default: %s]" % default_root) if path == "": path = default_root rouge_data = os.path.join(path, "data") rouge_path = os.path.join(path, "ROUGE-1.5.5.pl") print("Copying '%s' to '%s'" % (src_rouge_root, path)) shutil.copytree(src_rouge_root, path) return {"ROUGE_path": rouge_path, "ROUGE_data": rouge_data} conf_path = "./files2rouge/settings.json" s = settings.Settings(path=conf_path) data = copy_rouge() s._generate(data)
Update to version 0.1.1 (already in pypi). PiperOrigin-RevId: 391948484 Change-Id: Idf5c7f00dbba8ffe2ca292961d4e0e0e26bcd1cb
# Copyright 2021 Google LLC. # # 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. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '1' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
# Copyright 2021 Google LLC. # # 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. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '0' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
Correct regex in unit test Summary: Correct regex used in unit tests. Test Plan: Unit test Reviewed By: @alikhtarov Differential Revision: D1804582
# Copyright (c) 2015, 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. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import re from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1'] def setUp(self): self.add_mcrouter(self.config) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) stats = mcr.stats("suspect_servers") self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:(tko|down)", stats.values()[0]))
# Copyright (c) 2015, 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. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import re from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCase): config = './mcrouter/test/test_mcrouter_to_mcrouter_tko.json' extra_args = ['--timeouts-until-tko', '1'] def setUp(self): self.add_mcrouter(self.config) def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_underlying_tko(self): mcr = self.get_mcrouter() self.assertFalse(mcr.delete("key")) stats = mcr.stats("suspect_servers") self.assertEqual(1, len(stats)) self.assertTrue(re.match("status:[tko|down]", stats.values()[0]))
Make non-browserfiable interested in non-javascript resources.
var allJavascript = /\.js$/; var json = /package\.json$/; var coffeeOrJs = /\.(?:js)|(?:coffee)$/; var nonModule = /scripts/; var minified = /-min\.js$/; var generated = /generated/; var stub = /\.stub\.js/; exports.allJavascript = function (f) { return allJavascript.test(f) && !stub.test(f); }; exports.handwrittenJavascript = function (f) { return exports.allJavascript(f) && !generated.test(f) && !minified.test(f); }; var browserfiable = function (f) { return (coffeeOrJs.test(f) || json.test(f)) && !generated.test(f) && !nonModule.test(f) && !minified.test(f) && !stub.test(f); }; exports.browserfiable = browserfiable; exports.nonBrowserfiableJavascript = function (f) { return exports.allJavascript(f) && !browserfiable(f); }; exports.nonBrowserfiable = function (f) { return !browserfiable(f); }; exports.nonCode = function (f) { return !coffeeOrJs.test(f); };
var allJavascript = /\.js$/; var json = /package\.json$/; var coffeeOrJs = /\.(?:js)|(?:coffee)$/; var nonModule = /scripts/; var minified = /-min\.js$/; var generated = /generated/; var stub = /\.stub\.js/; exports.allJavascript = function (f) { return allJavascript.test(f) && !stub.test(f); }; exports.handwrittenJavascript = function (f) { return exports.allJavascript(f) && !generated.test(f) && !minified.test(f); }; var browserfiable = function (f) { return (coffeeOrJs.test(f) || json.test(f)) && !generated.test(f) && !nonModule.test(f) && !minified.test(f) && !stub.test(f); }; exports.browserfiable = browserfiable; exports.nonBrowserfiable = function (f) { return exports.allJavascript(f) && !browserfiable(f); }; exports.nonCode = function (f) { return !coffeeOrJs.test(f); };
Deploy to GitHub pages [ci skip]
export Tuttolino404 from "./tuttolino-404.png" export TuttolinoCompetitor from "./tuttolino-competitor.svg" export TuttolinoErrorMobile from "./tuttolino-error-mobile.png" export TuttolinoError from "./tuttolino-error.svg" export TuttolinoFamilySofa from "./tuttolino-family-sofa.svg" export TuttolinoFamily from "./tuttolino-family.svg" export TuttolinoGay from "./tuttolino-gay.svg" export TuttolinoGlasses from "./tuttolino-glasses.svg" export TuttolinoHey from "./tuttolino-hey.svg" export TuttolinoHolmesNoCircle from "./tuttolino-holmes-no_circle.svg" export TuttolinoHolmes from "./tuttolino-holmes.svg" export TuttolinoIntroScreens from "./tuttolino-intro-screens.svg" export TuttolinoSergi from "./tuttolino-sergi.svg" export TuttolinoSuccess from "./tuttolino-success.svg" export TuttolinoTablet from "./tuttolino-tablet.svg" export TuttolinoTuttiFan from "./tuttolino-tutti_fan.svg"
export Tuttolino404 from "./tuttolino-404.png" export TuttolinoCompetitor from "./tuttolino-competitor.svg" export TuttolinoErrorMobile from "./tuttolino-error-mobile.png" export TuttolinoError from "./tuttolino-error.svg" export TuttolinoFamilySofa from "./tuttolino-family-sofa.svg" export TuttolinoFamily from "./tuttolino-family.svg" export TuttolinoGay from "./tuttolino-gay.svg" export TuttolinoGlasses from "./tuttolino-glasses.svg" export TuttolinoHey from "./tuttolino-hey.svg" export TuttolinoHolmesNoCircle from "./tuttolino-holmes-no_circle.svg" export TuttolinoHolmes from "./tuttolino-holmes.svg" export TuttolinoHolmes from "./tuttolino-holmes-no_circle.svg" export TuttolinoIntroScreens from "./tuttolino-intro-screens.svg" export TuttolinoSergi from "./tuttolino-sergi.svg" export TuttolinoSuccess from "./tuttolino-success.svg" export TuttolinoTablet from "./tuttolino-tablet.svg" export TuttolinoTuttiFan from "./tuttolino-tutti_fan.svg"
Enable source maps in production
const config = require('./webpack.config.js'); const webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); config.devtool = 'cheap-module-source-map'; // Set environment to production config.plugins.push(new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, })); // Extract css to file // Replace less loader Object.keys(config.module.loaders).forEach((key) => { const loader = config.module.loaders[key]; if (loader.test.match(/\.less$/)) { loader.loader = ExtractTextPlugin.extract( 'css-loader?sourceMap!' + 'less-loader?sourceMap', ); } }); // Add extract text plugin config.plugins.push(new ExtractTextPlugin('[name]-[hash].css')); // Uglify js config.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, screw_ie8: true, }, comments: false, })); module.exports = config;
const config = require('./webpack.config.js'); const webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); config.devtool = 'cheap-module-source-map'; // Set environment to production config.plugins.push(new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, })); // Extract css to file // Replace less loader Object.keys(config.module.loaders).forEach((key) => { const loader = config.module.loaders[key]; if (loader.test.match(/\.less$/)) { loader.loader = ExtractTextPlugin.extract( 'css-loader?sourceMap!' + 'less-loader?sourceMap', ); } }); // Add extract text plugin config.plugins.push(new ExtractTextPlugin('[name]-[hash].css')); // Uglify js config.plugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, screw_ie8: true, }, comments: false, sourceMap: false, })); module.exports = config;
Fix the 'base' attribute for ng-apps
<!doctype html> <html class="no-js" <?php language_attributes(); ?>> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="alternate" type="application/rss+xml" title="<?= get_bloginfo('name'); ?> Feed" href="<?= esc_url(get_feed_link()); ?>"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700' rel='stylesheet' type='text/css'> <link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/dae2ada1-fb62-4216-ab20-8072b137a586.css"/> <link type="text/css" rel="stylesheet" href="<?php echo get_template_directory_uri() ?>/dist/styles/icons.svg.css"/> <?php wp_head(); ?> <?php if (is_page_template('template-timeline.php') || is_page_template('template-stories.php')) { $parts = explode('/', rtrim($_SERVER['REQUEST_URI'], '/')); $base = $parts[1]; ?> <base href="/<?php echo $base; ?>/"></base> <?php } ?> </head>
<!doctype html> <html class="no-js" <?php language_attributes(); ?>> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="alternate" type="application/rss+xml" title="<?= get_bloginfo('name'); ?> Feed" href="<?= esc_url(get_feed_link()); ?>"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700' rel='stylesheet' type='text/css'> <link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/dae2ada1-fb62-4216-ab20-8072b137a586.css"/> <link type="text/css" rel="stylesheet" href="<?php echo get_template_directory_uri() ?>/dist/styles/icons.svg.css"/> <?php wp_head(); ?> <base href="/history/"></base> </head>
Swap word API out with Chuck Norris joke API
/* * We are using jQuery functions as they are pretty easy to use. * You can do all of this stuff using vanilla javascript though */ // $(...) will run the function you give it when the page is loaded & ready $(function() { // console.log will log a message or object to the browser developer console console.log("page loaded..."); $("selector-goes-here").click(/* function for when the button is clicked goes here */); /* * TODO: You will need to use a css selector to get jQuery to find the button element in the page * Then you will need to make a new javascript function to do stuff for when the button * is clicked and pass it into the click function above... */ }); // Gets a random chuck norris joke from an API, then passes it to the callback function function fetchRandomChuckNorrisJoke(callback) { // this api picks a random chuck norris joke and returns it as plain text // limited to the dev category // WARNING: I do not control the content of the jokes! Some might be a bit rude! var promise = $.get("https://api.chucknorris.io/jokes/random?category=dev"); // $.get is asynchronous, so we need to define a // handler for when the request is complete promise.done(function(data) { // The data returned is a json object console.log(data); // if you want to do something with the word do it here callback(data.value); }) }
/* * We are using jQuery functions as they are pretty easy to use. * You can do all of this stuff using vanilla javascript though */ // $(...) will run the function you give it when the page is loaded & ready $(function() { // console.log will log a message or object to the browser developer console console.log("page loaded..."); $("selector-goes-here").click(/* function for when the button is clicked goes here */); /* * TODO: You will need to use a css selector to get jQuery to find the button element in the page * Then you will need to make a new javascript function to do stuff for when the button * is clicked and pass it into the click function above... */ }); // Gets a random word from an API, then passes it to the callback function function fetchRandomWord(callback) { // this api picks a random word and returns it as plain text var promise = $.get("http://setgetgo.com/randomword/get.php"); // $.get is asynchronous, so we need to define a // handler for when the request is complete promise.done(function(data) { console.log(data); // if you want to do something with the word do it here callback(data); }) }
Use a protocol relative URL so the package can be used other HTTPS as well
module.exports = asString module.exports.add = append function asString(fonts) { var href = getHref(fonts) return '<link href="' + href + '" rel="stylesheet" type="text/css">' } function asElement(fonts) { var href = getHref(fonts) var link = document.createElement('link') link.setAttribute('href', href) link.setAttribute('rel', 'stylesheet') link.setAttribute('type', 'text/css') return link } function getHref(fonts) { var family = Object.keys(fonts).map(function(name) { var details = fonts[name] name = name.replace(/\s+/, '+') return typeof details === 'boolean' ? name : name + ':' + makeArray(details).join(',') }).join('|') return '//fonts.googleapis.com/css?family=' + family } function append(fonts) { var link = asElement(fonts) document.head.appendChild(link) return link } function makeArray(arr) { return Array.isArray(arr) ? arr : [arr] }
module.exports = asString module.exports.add = append function asString(fonts) { var href = getHref(fonts) return '<link href="' + href + '" rel="stylesheet" type="text/css">' } function asElement(fonts) { var href = getHref(fonts) var link = document.createElement('link') link.setAttribute('href', href) link.setAttribute('rel', 'stylesheet') link.setAttribute('type', 'text/css') return link } function getHref(fonts) { var family = Object.keys(fonts).map(function(name) { var details = fonts[name] name = name.replace(/\s+/, '+') return typeof details === 'boolean' ? name : name + ':' + makeArray(details).join(',') }).join('|') return 'http://fonts.googleapis.com/css?family=' + family } function append(fonts) { var link = asElement(fonts) document.head.appendChild(link) return link } function makeArray(arr) { return Array.isArray(arr) ? arr : [arr] }
Add colour to execution status.
#!/usr/bin/env node const fs = require('fs') colours = require('colors') program = require('commander'); program .version('0.0.1') .description('A command line script to minify files.') .option('-f, --file <file>', 'Specify the file to minify: minify -f thisFile.js') .parse(process.argv); if (program.file) { /* Read the file into a string */ var filePath = program.file , fileContent = fs.readFileSync(filePath, 'utf8') , minFileContent = minifyString(fileContent) , minFileName = addMinExtension(filePath); var minifiedFile = fs.writeFile(minFileName, minFileContent, function(err) { if (err) { console.log(filePath.blue.underline + ' minify unsuccessful'.red); throw err; }; console.log(filePath.blue.underline + ' minified successfully to '.green + minFileName.blue.underline); }); }; /***************************************/ // Helper Functions // /***************************************/ /* Remove all white space from str. */ function minifyString(str) { return str.replace(/\s/g, ''); }; /* Insert .min extension to FileName. */ function addMinExtension(fileName) { var fileExtIndex = fileName.indexOf('.') , filePrefix = fileName.slice(0, fileExtIndex) , fileExten = fileName.slice(fileExtIndex, fileName.length) , minFileName = filePrefix + '.min' + fileExten; return minFileName; };
#!/usr/bin/env node const fs = require('fs') program = require('commander'); program .version('0.0.1') .description('A command line script to minify files.') .option('-f, --file <file>', 'Specify the file to minify: minify -f thisFile.js') .parse(process.argv); if (program.file) { /* Read the file into a string */ var filePath = program.file , fileContent = fs.readFileSync(filePath, 'utf8') , minFileContent = minifyString(fileContent) , minFileName = addMinExtension(filePath); var minifiedFile = fs.writeFile(minFileName, minFileContent, function(err) { if (err) { throw err; }; console.log('-- ' + filePath + ' minified to ' + minFileName + ' --'); }); }; /***************************************/ // Helper Functions // /***************************************/ /* Remove all white space from str. */ function minifyString(str) { return str.replace(/\s/g, ''); }; /* Insert .min extension to FileName. */ function addMinExtension(FileName) { var fileExtIndex = FileName.indexOf('.') , filePrefix = FileName.slice(0, fileExtIndex) , fileExten = FileName.slice(fileExtIndex, FileName.length) , minFileName = filePrefix + '.min' + fileExten; return minFileName; };
Call os.Exit() with m.Run()'s return value This closes #149. This closes #151.
package main import ( "flag" "fmt" "log" "math/rand" "os" "testing" "time" "github.com/keybase/client/go/libkb" bserver "github.com/keybase/kbfs/bserver" ) var ( BServerRemote = flag.Bool("kbfs.bserverRemote", false, "which bserver to use, local or remote") ) func init() { flag.Parse() } func TestMain(m *testing.M) { log.SetFlags(log.LstdFlags | log.Lshortfile) libkb.G.Init() libkb.G.ConfigureConfig() libkb.G.ConfigureLogging() libkb.G.ConfigureSocketInfo() rand.Seed(time.Now().UnixNano()) if *BServerRemote == true { fmt.Printf("Testing Using Remote Backend: %s\n", bserver.Config.BServerAddr) bserver.InitConfig("../bserver/testconfig.json") bserver.Config.TestNoSession = true bserver.StartBServer() } os.Exit(m.Run()) }
package main import ( "flag" "fmt" "github.com/keybase/client/go/libkb" bserver "github.com/keybase/kbfs/bserver" "log" "math/rand" "testing" "time" ) var ( BServerRemote = flag.Bool("kbfs.bserverRemote", false, "which bserver to use, local or remote") ) func init() { flag.Parse() } func TestMain(m *testing.M) { log.SetFlags(log.LstdFlags | log.Lshortfile) libkb.G.Init() libkb.G.ConfigureConfig() libkb.G.ConfigureLogging() libkb.G.ConfigureSocketInfo() rand.Seed(time.Now().UnixNano()) if *BServerRemote == true { fmt.Printf("Testing Using Remote Backend: %s\n", bserver.Config.BServerAddr) bserver.InitConfig("../bserver/testconfig.json") bserver.Config.TestNoSession = true bserver.StartBServer() } m.Run() }
Change app-level error handler to use api_client.error exceptions
# coding=utf-8 from flask import render_template from . import main from ..api_client.error import APIError @main.app_errorhandler(APIError) def api_error_handler(e): return _render_error_page(e.status_code) @main.app_errorhandler(404) def page_not_found(e): return _render_error_page(404) @main.app_errorhandler(500) def internal_server_error(e): return _render_error_page(500) @main.app_errorhandler(503) def service_unavailable(e): return _render_error_page(503, e.response) def _render_error_page(status_code, error_message=None): templates = { 404: "errors/404.html", 500: "errors/500.html", 503: "errors/500.html", } if status_code not in templates: status_code = 500 return render_template( templates[status_code], error_message=error_message ), status_code
# coding=utf-8 from flask import render_template from . import main from dmapiclient import APIError @main.app_errorhandler(APIError) def api_error_handler(e): return _render_error_page(e.status_code) @main.app_errorhandler(404) def page_not_found(e): return _render_error_page(404) @main.app_errorhandler(500) def internal_server_error(e): return _render_error_page(500) @main.app_errorhandler(503) def service_unavailable(e): return _render_error_page(503, e.response) def _render_error_page(status_code, error_message=None): templates = { 404: "errors/404.html", 500: "errors/500.html", 503: "errors/500.html", } if status_code not in templates: status_code = 500 return render_template( templates[status_code], error_message=error_message ), status_code
Fix tests for visit_Attribute on 2.5/PyPy
from attest import Tests, assert_hook from attest.hook import ExpressionEvaluator suite = Tests() @suite.test def eval(): value = 1 + 1 valgen = (v for v in [value]) samples = { 'isinstance(value, int)': 'True', 'value == int("2")': "(2 == 2)", 'type(value).__name__': "'int'", 'value == 5 - 3': '(2 == 2)', '{"value": value}': "{'value': 2}", '[valgen.next() for _ in [value]] == [v for v in [value]]': '([2] == [2])', } for expr, result in samples.iteritems(): ev = repr(ExpressionEvaluator(expr, globals(), locals())) assert ev == result assert bool(ev) is True
from attest import Tests, assert_hook from attest.hook import ExpressionEvaluator suite = Tests() @suite.test def eval(): value = 1 + 1 valgen = (v for v in [value]) samples = { 'isinstance(value, int)': 'True', 'value == int("2")': "(2 == 2)", 'value.denominator': '1', 'value == 5 - 3': '(2 == 2)', '{"value": value}': "{'value': 2}", '[valgen.next() for _ in [value]] == [v for v in [value]]': '([2] == [2])', } for expr, result in samples.iteritems(): ev = repr(ExpressionEvaluator(expr, globals(), locals())) assert ev == result assert bool(ev) is True
Update the path to the methods
// Define DrupalAjaxRequest var DrupalAjaxRequest = (function () { var fetchNode = function(node_id, callback) { Zepto.ajax( { url: Kiosk.util.contentUrl('node'), dataType: 'jsonp', data: {nid: node_id}, type: 'GET', cache: false, success: function (result) { callback(result); } } ); } var fetchCollections = function(callback) { Zepto.ajax( { url: Kiosk.util.contentUrl('collections'), dataType: 'jsonp', type: 'GET', cache: false, success: function (result) { callback(result); } } ); } return { fetchNode : fetchNode, fetchCollections: fetchCollections } })();
// Define DrupalAjaxRequest var DrupalAjaxRequest = (function () { var fetchNode = function(node_id, callback) { Zepto.ajax( { url: Kiosk.contentUrl('node'), dataType: 'jsonp', data: {nid: node_id}, type: 'GET', cache: false, success: function (result) { callback(result); } } ); } var fetchCollections = function(callback) { Zepto.ajax( { url: Kiosk.contentUrl('collections'), dataType: 'jsonp', type: 'GET', cache: false, success: function (result) { callback(result); } } ); } return { fetchNode : fetchNode, fetchCollections: fetchCollections } })();
Change database init script for daemon tests
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from time import sleep import unittest import os import cairis.bin.cairisd __author__ = 'Robin Quetin' class CairisDaemonTestCase(unittest.TestCase): srcRoot = os.environ['CAIRIS_SRC'] createDbSql = srcRoot + '/test/createdb.sql' sqlDir = srcRoot + '/sql' initSql = sqlDir + '/init.sql' procsSql = sqlDir + '/procs.sql' cmd = "/usr/bin/mysql --user=root --password='' < " + createDbSql os.system(cmd) cmd = "/usr/bin/mysql --user=irisuser --password='' --database=arm < " + initSql os.system(cmd) cmd = "/usr/bin/mysql --user=irisuser --password='' --database=arm < " + procsSql os.system(cmd) app = cairis.bin.cairisd.main(['-d', '--unit-test']) sleep(1)
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from time import sleep import unittest import os import cairis.bin.cairisd __author__ = 'Robin Quetin' class CairisDaemonTestCase(unittest.TestCase): cmd = os.environ['CAIRIS_SRC'] + "/test/initdb.sh" os.system(cmd) app = cairis.bin.cairisd.main(['-d', '--unit-test']) sleep(1)
Fix evil eval warning in lint
/** * Main controller for the Huna JS app. Shows the main (index) page */ app.controller('ErrorController', function($scope, $interval){ var stop; $scope.timeout = ""; $scope.busy = false; $scope.parseError = function(){ countDown(); var a = ""; a.asdf = asdf; }; $scope.syntaxError = function(){ countDown(); eval("var a = b;"); // jshint ignore:line }; $scope.uncaughtException = function(){ countDown(); throw new Error("Uncaught Exception..."); }; $scope.stop = function(){ if (angular.isDefined(stop)){ $interval.cancel(stop); stop = undefined; $scope.timeout = ""; $scope.busy = false; } }; function countDown(){ $scope.busy = true; $scope.timeout = 8; stop = $interval(function(){ $scope.timeout--; if ($scope.timeout <= 0){ $scope.stop(); } }, 1000); } $scope.$on('$destroy', function() { $scope.stop(); }); });
/** * Main controller for the Huna JS app. Shows the main (index) page */ app.controller('ErrorController', function($scope, $interval){ var stop; $scope.timeout = ""; $scope.busy = false; $scope.parseError = function(){ countDown(); var a = ""; a.asdf = asdf; }; $scope.syntaxError = function(){ countDown(); eval("var a = b;"); }; $scope.uncaughtException = function(){ countDown(); throw new Error("Uncaught Exception..."); }; $scope.stop = function(){ if (angular.isDefined(stop)){ $interval.cancel(stop); stop = undefined; $scope.timeout = ""; $scope.busy = false; } }; function countDown(){ $scope.busy = true; $scope.timeout = 8; stop = $interval(function(){ $scope.timeout--; if ($scope.timeout <= 0){ $scope.stop(); } }, 1000); } $scope.$on('$destroy', function() { $scope.stop(); }); });
Call $scope.$apply after running the logic of the function/updating the property
angular.module('apps', ['angular-loading-bar', 'apis']) .controller('mailserversetting', ['$window', '$timeout', 'systemApi', function ($window, $timeout, $api) { var self = this; self.Initialize = function () { self.JsonModel = $window['MailServerSettingJson']; self.AlertSuccess = false; self.AlertError = false; }; self.SaveMailServer = function () { $api.SaveMailServer({ data: self.Config, success: function (response) { if (response.Success) { self.AlertSuccess = true; var parentscope = parent.angular.element('[ng-controller^="index"]').scope(); $timeout(parentscope.self.CloseIframe, 2000); $timeout(parentscope.$apply, 2500); } else { self.AlertError = true; } } }); } self.Initialize(); }]);
angular.module('apps', ['angular-loading-bar', 'apis']) .controller('mailserversetting', ['$window', '$timeout', 'systemApi', function ($window, $timeout, $api) { var self = this; self.Initialize = function () { self.JsonModel = $window['MailServerSettingJson']; self.AlertSuccess = false; self.AlertError = false; }; self.SaveMailServer = function () { $api.SaveMailServer({ data: self.Config, success: function (response) { if (response.Success) { self.AlertSuccess = true; var parentscope = parent.angular.element('[ng-controller^="index"]').scope(); $timeout(parentscope.self.CloseIframe, 2500); } else { self.AlertError = true; } } }); } self.Initialize(); }]);
Convert DiscordSync route to POST
<?php /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::prefix('bans')->group(function() { Route::post('list', 'BanController@getBanList'); Route::middleware('auth.token.server')->group(function() { Route::post('store/ban', 'BanController@storeBan'); Route::post('store/unban', 'BanController@storeUnban'); Route::post('status', 'BanController@getUserStatus'); Route::post('history', 'BanController@getUserBanHistory'); }); }); Route::prefix('servers')->group(function() { Route::get('all', 'ServerController@getAllServers'); }); Route::post('discord/sync', 'DiscordSyncController@getRank'); Route::post('minecraft/authenticate', 'TempMinecraftController@authenticate');
<?php /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::prefix('bans')->group(function() { Route::post('list', 'BanController@getBanList'); Route::middleware('auth.token.server')->group(function() { Route::post('store/ban', 'BanController@storeBan'); Route::post('store/unban', 'BanController@storeUnban'); Route::post('status', 'BanController@getUserStatus'); Route::post('history', 'BanController@getUserBanHistory'); }); }); Route::prefix('servers')->group(function() { Route::get('all', 'ServerController@getAllServers'); }); Route::get('discord/sync', 'DiscordSyncController@getRank'); Route::post('minecraft/authenticate', 'TempMinecraftController@authenticate');
Fix ini_set('error_log', ...) with HHVM https://github.com/facebook/hhvm/issues/3558
<?php /** * * This file is part of the Apix Project. * * (c) Franck Cassedanne <franck at ouarz.net> * * @license http://opensource.org/licenses/BSD-3-Clause New BSD License * */ namespace Apix\Log\tests\Logger; use Apix\Log\Logger; class ErrorLogTest extends TestCase { protected $dest = './apix-unit-test-logger.log'; // protected $dest = '/dev/stdout'; protected function setUp() { // HHVM support // @see: https://github.com/facebook/hhvm/issues/3558 if (defined('HHVM_VERSION')) { ini_set('log_errors', 'On'); ini_set('error_log', $this->dest); } ini_set('error_log', $this->dest); } protected function tearDown() { if (file_exists($this->dest)) { unlink($this->dest); } } /** * {@inheritDoc} */ public function getLogger() { return new Logger\ErrorLog(); } }
<?php /** * * This file is part of the Apix Project. * * (c) Franck Cassedanne <franck at ouarz.net> * * @license http://opensource.org/licenses/BSD-3-Clause New BSD License * */ namespace Apix\Log\tests\Logger; use Apix\Log\Logger; class ErrorLogTest extends TestCase { protected $dest = './apix-unit-test-logger.log'; // protected $dest = '/dev/stdout'; protected function setUp() { ini_set('error_log', $this->dest); } protected function tearDown() { if (file_exists($this->dest)) { unlink($this->dest); } } /** * {@inheritDoc} */ public function getLogger() { return new Logger\ErrorLog(); } }
Set update job timeout back to a more reasonable value
import sys import time import logging logging.basicConfig(level=logging.DEBUG) from redis import StrictRedis from rq import Queue from apscheduler.schedulers.blocking import BlockingScheduler from d1lod import jobs conn = StrictRedis(host='redis', port='6379') q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def queue_update_job(): q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout @sched.scheduled_job('interval', minutes=1) def queue_stats_job(): q.enqueue(jobs.calculate_stats) @sched.scheduled_job('interval', minutes=1) def queue_export_job(): q.enqueue(jobs.export_graph) @sched.scheduled_job('interval', minutes=1) def print_jobs_job(): sched.print_jobs() # Wait a bit for Sesame to start time.sleep(10) # Queue the stats job first. This creates the repository before any other # jobs are run. q.enqueue(jobs.calculate_stats) # Start the scheduler sched.start()
import sys import time import logging logging.basicConfig(level=logging.DEBUG) from redis import StrictRedis from rq import Queue from apscheduler.schedulers.blocking import BlockingScheduler from d1lod import jobs conn = StrictRedis(host='redis', port='6379') q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def queue_update_job(): q.enqueue(jobs.update_graph, timeout=604800) # 7 day timeout @sched.scheduled_job('interval', minutes=1) def queue_stats_job(): q.enqueue(jobs.calculate_stats) @sched.scheduled_job('interval', minutes=1) def queue_export_job(): q.enqueue(jobs.export_graph) @sched.scheduled_job('interval', minutes=1) def print_jobs_job(): sched.print_jobs() # Wait a bit for Sesame to start time.sleep(10) # Queue the stats job first. This creates the repository before any other # jobs are run. q.enqueue(jobs.calculate_stats) # Start the scheduler sched.start()
Verify key type instead of value This is to make the code cleaner and easier to understand
var extend = require('extend'); var Plom = function(options) { this.options = options || {}; this.data = this.options.data || {}; } Plom.extend = function(object) { var NewPlom = function(options) { this.options = options || {}; this.data = this.options.data || {}; if(this.initialize) { this.initialize(options); } }; object = object || null; NewPlom.prototype = extend({}, this.prototype, object); NewPlom.extend = this.extend.bind(this); return NewPlom; }; Plom.prototype.set = function(key, val) { if (typeof key === 'object') { this.data = key; return this; } this.data[key] = val; return this; }; Plom.prototype.get = function(key) { if(key) { return this.data[key]; } return this.data; }; module.exports = Plom;
var extend = require('extend'); var Plom = function(options) { this.options = options || {}; this.data = this.options.data || {}; } Plom.extend = function(object) { var NewPlom = function(options) { this.options = options || {}; this.data = this.options.data || {}; if(this.initialize) { this.initialize(options); } }; object = object || null; NewPlom.prototype = extend({}, this.prototype, object); NewPlom.extend = this.extend.bind(this); return NewPlom; }; Plom.prototype.set = function(key, val) { var argsLength = Array.prototype.slice.call(arguments).length; if (argsLength === 2) { this.data[key] = val; return this; } this.data = key; return this; }; Plom.prototype.get = function(key) { if(key) { return this.data[key]; } return this.data; }; module.exports = Plom;
Stop using `exposed` prefix for remote attributes, per rpyc v4
import sys import rpyc from rpyc.utils.server import OneShotServer class GhcompService(rpyc.ClassicService): def on_connect(self, conn): print('Incoming connection.') super(GhcompService, self).on_connect(conn) import ghpythonlib.components as ghcomp self.ghcomp = ghcomp def on_disconnect(self, conn): print('Disconnected.') def get_component(self, component_name, is_cluster_component=False): component = getattr(self.ghcomp, component_name) if is_cluster_component: component = getattr(component, component_name) # TODO: improve ghcomp to get clusters the same way we get compiled components, thus removing the need for a custom getter return component if __name__ == '__main__': import rhinoscriptsyntax as rs port = rs.GetInteger("Server bind port", 18871, 1023, 65535) server = OneShotServer(GhcompService, hostname='localhost', port=port, listener_timeout=None) server.start()
import sys import rpyc from rpyc.utils.server import OneShotServer class GhcompService(rpyc.ClassicService): def on_connect(self, conn): print('Incoming connection.') super(GhcompService, self).on_connect(conn) import ghpythonlib.components as ghcomp self.ghcomp = ghcomp def on_disconnect(self, conn): print('Disconnected.') def exposed_get_component(self, component_name, is_cluster_component=False): component = getattr(self.ghcomp, component_name) if is_cluster_component: component = getattr(component, component_name) # TODO: improve ghcomp to get clusters the same way we get compiled components, thus removing the need for a custom getter return component if __name__ == '__main__': import rhinoscriptsyntax as rs port = rs.GetInteger("Server bind port", 18871, 1023, 65535) server = OneShotServer(GhcompService, hostname='localhost', port=port, listener_timeout=None) server.start()
Fix Attempting to Display Blank Errors Fix attempting to display blank errors in single pages - This is particularly apparent with the newer `Controller::$error` property.
<?php defined('C5_EXECUTE') or die(_("Access Denied.")); if (isset($error) && $error != '') { if ($error instanceof Exception) { $_error[] = $error->getMessage(); } else if ($error instanceof ValidationErrorHelper) { $_error = $error->getList(); } else if (is_array($error)) { $_error = $error; } else if (is_string($error)) { $_error[] = $error; } ?> <? if($_error) { ?> <? if ($format == 'block') { ?> <div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">×</button> <?php foreach($_error as $e): ?> <?php echo $e?><br/> <?php endforeach; ?> </div> <? } else { ?> <ul class="ccm-error"> <?php foreach($_error as $e): ?> <li><?php echo $e?></li> <?php endforeach; ?> </ul> <? } ?> <? } ?> <?php } ?>
<?php defined('C5_EXECUTE') or die(_("Access Denied.")); if (isset($error) && $error != '') { if ($error instanceof Exception) { $_error[] = $error->getMessage(); } else if ($error instanceof ValidationErrorHelper) { $_error = $error->getList(); } else if (is_array($error)) { $_error = $error; } else if (is_string($error)) { $_error[] = $error; } ?> <? if ($format == 'block') { ?> <div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">×</button> <?php foreach($_error as $e): ?> <?php echo $e?><br/> <?php endforeach; ?> </div> <? } else { ?> <ul class="ccm-error"> <?php foreach($_error as $e): ?> <li><?php echo $e?></li> <?php endforeach; ?> </ul> <? } ?> <?php } ?>
Hide the sidebar by default.
import {Experiment, ExperimentStep} from './experiment.model'; angular.module('materialscommons').component('mcExperiment', { templateUrl: 'app/project/experiments/experiment/mc-experiment.html', controller: MCExperimentComponentController }); /*@ngInject*/ function MCExperimentComponentController($scope, moveStep) { let ctrl = this; ctrl.currentStep = null; ctrl.currentNode = null; ctrl.showSidebar = false; // Create the initial hard coded experiment ctrl.experiment = new Experiment('test experiment'); let s = new ExperimentStep('', ''); s.id = "simple0"; ctrl.experiment.steps.push(s); ctrl.currentStep = s; ctrl.moveLeft = () => moveStep.left(ctrl.currentNode, ctrl.currentStep, ctrl.experiment); ctrl.moveRight = () => moveStep.right(ctrl.currentNode, ctrl.currentStep); ctrl.moveUp = () => moveStep.up(ctrl.currentNode, ctrl.currentStep); ctrl.moveDown = () => moveStep.down(ctrl.currentNode, ctrl.currentStep, ctrl.experiment); ctrl.expandAll = () => $scope.$broadcast('angular-ui-tree:expand-all'); ctrl.collapseAll = () => $scope.$broadcast('angular-ui-tree:collapse-all'); ctrl.showStepMaximized = () => ctrl.currentStep && ctrl.currentStep.displayState.maximize; }
import {Experiment, ExperimentStep} from './experiment.model'; angular.module('materialscommons').component('mcExperiment', { templateUrl: 'app/project/experiments/experiment/mc-experiment.html', controller: MCExperimentComponentController }); /*@ngInject*/ function MCExperimentComponentController($scope, moveStep) { let ctrl = this; ctrl.currentStep = null; ctrl.currentNode = null; ctrl.showSidebar = true; // Create the initial hard coded experiment ctrl.experiment = new Experiment('test experiment'); let s = new ExperimentStep('', ''); s.id = "simple0"; ctrl.experiment.steps.push(s); ctrl.currentStep = s; ctrl.moveLeft = () => moveStep.left(ctrl.currentNode, ctrl.currentStep, ctrl.experiment); ctrl.moveRight = () => moveStep.right(ctrl.currentNode, ctrl.currentStep); ctrl.moveUp = () => moveStep.up(ctrl.currentNode, ctrl.currentStep); ctrl.moveDown = () => moveStep.down(ctrl.currentNode, ctrl.currentStep, ctrl.experiment); ctrl.expandAll = () => $scope.$broadcast('angular-ui-tree:expand-all'); ctrl.collapseAll = () => $scope.$broadcast('angular-ui-tree:collapse-all'); ctrl.showStepMaximized = () => ctrl.currentStep && ctrl.currentStep.displayState.maximize; }
Refactor to avoid duplicate code
from ..constants import FORMAT_CHECKS from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES from ..postprocessor import KnowledgePostProcessor class FormatChecks(KnowledgePostProcessor): _registry_keys = [FORMAT_CHECKS] def process(self, kp): headers = kp.headers for field, typ, _ in HEADER_REQUIRED_FIELD_TYPES: assert field in headers, \ "Required field `{field}` missing from headers." for field, typ, _ in \ HEADER_REQUIRED_FIELD_TYPES + HEADER_OPTIONAL_FIELD_TYPES: if field in headers: header_field = headers[field] assert isinstance(header_field, typ), \ f"Value for field `{field}` is of type " + \ f"{type(header_field)}, and needs to be of type {typ}."
from ..constants import FORMAT_CHECKS from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES from ..postprocessor import KnowledgePostProcessor class FormatChecks(KnowledgePostProcessor): _registry_keys = [FORMAT_CHECKS] def process(self, kp): headers = kp.headers for field, typ, input in HEADER_REQUIRED_FIELD_TYPES: assert field in headers, \ "Required field `{field}` missing from headers." assert isinstance(headers[field], typ), \ f"Value for field `{field}` is of type " + \ f"{type(headers[field])}, and needs to be of type {typ}." for field, typ, input in HEADER_OPTIONAL_FIELD_TYPES: if field in headers: assert isinstance(headers[field], typ), \ f"Value for field `{field}` is of type " + \ f"{type(headers[field])}, and needs to be of type {typ}."
Fix location factory field name
# coding: utf-8 import factory import random from .models import Location, Region class RegionFactory(factory.Factory): FACTORY_FOR = Region name = factory.Sequence(lambda n: "Region_%s" % n) slug = factory.LazyAttribute(lambda a: a.name.lower()) latitude = random.uniform(-90.0, 90.0) longitude = random.uniform(-180.0, 180.0) zoom = random.randint(1, 10) order = factory.Sequence(lambda n: n) class LocationFactory(factory.Factory): FACTORY_FOR = Location latitude = random.uniform(-90.0, 90.0) longitude = random.uniform(-180.0, 180.0) description = factory.Sequence(lambda n: "Location_%s" % n) region = factory.SubFactory(RegionFactory)
# coding: utf-8 import factory import random from .models import Location, Region class RegionFactory(factory.Factory): FACTORY_FOR = Region name = factory.Sequence(lambda n: "Region_%s" % n) slug = factory.LazyAttribute(lambda a: a.name.lower()) latitude = random.uniform(-90.0, 90.0) longitude = random.uniform(-180.0, 180.0) zoom = random.randint(1, 10) order = factory.Sequence(lambda n: n) class LocationFactory(factory.Factory): FACTORY_FOR = Location latitude = random.uniform(-90.0, 90.0) longitude = random.uniform(-180.0, 180.0) name = factory.Sequence(lambda n: "Location_%s" % n) regionId = factory.SubFactory(RegionFactory)
Use an older raven until our Sentry is upgraded to 5.1
from setuptools import setup, find_packages setup( name='jmbo-skeleton', version='0.6', description='Create a Jmbo project environment quickly. Includes a Jmbo demo application.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='dev@praekelt.com', license='BSD', url='', packages = find_packages(), install_requires = [ 'jmbo-foundry>=1.1.1', 'raven<3.0.0', ], include_package_data=True, tests_require=[ 'django-setuptest>=0.1.2', ], test_suite="setuptest.setuptest.SetupTestSuite", classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
from setuptools import setup, find_packages setup( name='jmbo-skeleton', version='0.6', description='Create a Jmbo project environment quickly. Includes a Jmbo demo application.', long_description = open('README.rst', 'r').read() + open('AUTHORS.rst', 'r').read() + open('CHANGELOG.rst', 'r').read(), author='Praekelt Foundation', author_email='dev@praekelt.com', license='BSD', url='', packages = find_packages(), install_requires = [ 'jmbo-foundry>=1.1.1', 'raven', ], include_package_data=True, tests_require=[ 'django-setuptest>=0.1.2', ], test_suite="setuptest.setuptest.SetupTestSuite", classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
Print status at the extension's badge
var MoochSentinel = { render: function(status) { if (status.okay) { var msg = "Okay"; var color = [255, 0, 0, 0]; } else { var msg = "Blocked"; var color = [0, 255, 0, 0]; } document.getElementById("status").innerText = msg; chrome.browserAction.setBadgeText({text: msg}); chrome.browserAction.setBadgeColor({color: color}); }, requestStatus: function() { var user = localStorage['moochLogin']; if (!user) { document.getElementById("status").innerText = "Please, set user login on options page"; return; } var xhr = new XMLHttpRequest(); xhr.open("GET", "http://mooch.co.vu:5000/status/" + user, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var status = JSON.parse(xhr.responseText); MoochSentinel.render(status); } } xhr.send(); } } document.addEventListener("DOMContentLoaded", function() { MoochSentinel.requestStatus(); });
var MoochSentinel = { render: function(status) { document.getElementById("status").innerText = status.okay? "Okay!" : "Blocked"; }, requestStatus: function() { var user = localStorage['moochLogin']; if (!user) { document.getElementById("status").innerText = "Please, set user login on options page"; return; } var xhr = new XMLHttpRequest(); xhr.open("GET", "http://mooch.co.vu:5000/status/" + user, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var status = JSON.parse(xhr.responseText); MoochSentinel.render(status); } } xhr.send(); } } document.addEventListener("DOMContentLoaded", function() { MoochSentinel.requestStatus(); });
Add utility to retrieve all extension type bases
"Simple utilities related to extension types" #------------------------------------------------------------------------ # Read state from extension types #------------------------------------------------------------------------ def get_attributes_type(py_class): "Return the attribute struct type of the numba extension type" return py_class.__numba_struct_type def get_vtab_type(py_class): "Return the type of the virtual method table of the numba extension type" return py_class.__numba_vtab_type def get_method_pointers(py_class): "Return [(method_name, method_pointer)] given a numba extension type" return getattr(py_class, '__numba_method_pointers', None) #------------------------------------------------------------------------ # Type checking #------------------------------------------------------------------------ def is_numba_class(py_class): return hasattr(py_class, '__numba_struct_type') def get_all_numba_bases(py_class): seen = set() bases = [] for base in py_class.__mro__[::-1]: if is_numba_class(base) and base.exttype not in seen: seen.add(base.exttype) bases.append(base) return bases[::-1] def get_numba_bases(py_class): for base in py_class.__bases__: if is_numba_class(base): yield base
"Simple utilities related to extension types" #------------------------------------------------------------------------ # Read state from extension types #------------------------------------------------------------------------ def get_attributes_type(py_class): "Return the attribute struct type of the numba extension type" return py_class.__numba_struct_type def get_vtab_type(py_class): "Return the type of the virtual method table of the numba extension type" return py_class.__numba_vtab_type def get_method_pointers(py_class): "Return [(method_name, method_pointer)] given a numba extension type" return getattr(py_class, '__numba_method_pointers', None) #------------------------------------------------------------------------ # Type checking #------------------------------------------------------------------------ def is_numba_class(py_class): return hasattr(py_class, '__numba_struct_type') def get_numba_bases(py_class): for base in py_class.__mro__: if is_numba_class(base): yield base
Update the reply count display
<div class="data-list"> @foreach ($discussions as $discussion) <div class="d-flex align-items-start align-items-md-center justify-content-start mb-2 p-2"> <div class="d-flex align-items-start align-items-md-center mr-auto"> <div class="mr-3"> <div class="hidden-sm-down">{!! avatar($discussion->author)->link() !!}</div> <div class="hidden-md-up pt-2">{!! avatar($discussion->author)->link()->small() !!}</div> </div> <div> {!! $discussion->present()->titleAsLink !!} {!! $discussion->present()->topic !!} <span class="small text-muted pl-2"> {!! $discussion->present()->updatedAt !!} {!! $discussion->present()->updatedBy !!} </span> </div> </div> <div class="text-center text-subtle font-special mb-0 px-2 h5 font-weight-3"> {{ $discussion->present()->replyCount }} </div> </div> @endforeach </div>
<div class="data-list"> @foreach ($discussions as $discussion) <div class="d-flex align-items-start align-items-md-center justify-content-start mb-2 p-2"> <div class="d-flex align-items-start align-items-md-center mr-auto"> <div class="mr-3"> <div class="hidden-sm-down">{!! avatar($discussion->author)->link() !!}</div> <div class="hidden-md-up pt-2">{!! avatar($discussion->author)->link()->small() !!}</div> </div> <div> {!! $discussion->present()->titleAsLink !!} {!! $discussion->present()->topic !!} <span class="small text-muted pl-2"> {!! $discussion->present()->updatedAt !!} {!! $discussion->present()->updatedBy !!} </span> </div> </div> <div class="text-center text-subtle font-mono mb-0 px-2 h4 font-weight-4"> {{ $discussion->present()->replyCount }} </div> </div> @endforeach </div>
Add longDescription and exampleStringValue to sleep
package org.cytoscape.commandDialog.internal.tasks; import org.cytoscape.work.AbstractTask; import org.cytoscape.work.ProvidesTitle; import org.cytoscape.work.TaskMonitor; import org.cytoscape.work.Tunable; public class SleepCommandTask extends AbstractEmptyObservableTask { @ProvidesTitle public String getTitle() { return "Sleeping..."; } @Tunable(description="Duration of sleep in seconds", longDescription="Enter the time in seconds to sleep", exampleStringValue="5") public double duration; public SleepCommandTask() { super(); } @Override public void run(TaskMonitor arg0) throws Exception { if (duration != 0d) { arg0.showMessage(TaskMonitor.Level.INFO, "Sleeping for "+duration+" seconds"); Thread.sleep((long)duration*1000); arg0.showMessage(TaskMonitor.Level.INFO, "Slept for "+duration+" seconds"); } } }
package org.cytoscape.commandDialog.internal.tasks; import org.cytoscape.work.AbstractTask; import org.cytoscape.work.ProvidesTitle; import org.cytoscape.work.TaskMonitor; import org.cytoscape.work.Tunable; public class SleepCommandTask extends AbstractEmptyObservableTask { @ProvidesTitle public String getTitle() { return "Sleeping..."; } @Tunable(description="Duration of sleep in seconds") public double duration; public SleepCommandTask() { super(); } @Override public void run(TaskMonitor arg0) throws Exception { if (duration != 0d) { arg0.showMessage(TaskMonitor.Level.INFO, "Sleeping for "+duration+" seconds"); Thread.sleep((long)duration*1000); arg0.showMessage(TaskMonitor.Level.INFO, "Slept for "+duration+" seconds"); } } }
Add the google analytics traking
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-104380197-1', 'auto'); ga('send', 'pageview'); </script> <!-- jQuery --> <script src="<?php echo base_url('assets/js/libs/jquery.js')?>"></script> <!-- Plugins --> <script src="<?php echo base_url('assets/js/plugins.js')?>"></script> <!-- Main --> <script src="<?php echo base_url('assets/js/main.js')?>"></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> </body> </html>
<!-- jQuery --> <script src="<?php echo base_url('assets/js/libs/jquery.js')?>"></script> <!-- Plugins --> <script src="<?php echo base_url('assets/js/plugins.js')?>"></script> <!-- Main --> <script src="<?php echo base_url('assets/js/main.js')?>"></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <script> (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]= function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date; e=o.createElement(i);r=o.getElementsByTagName(i)[0]; e.src='//www.google-analytics.com/analytics.js'; r.parentNode.insertBefore(e,r)}(window,document,'script','ga')); ga('create','UA-XXXXX-X','auto');ga('send','pageview'); </script> </body> </html>
Use 24-hour format for German translations
// German jQuery.extend( jQuery.fn.pickadate.defaults, { monthsFull: [ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ], monthsShort: [ 'Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez' ], weekdaysFull: [ 'Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag' ], weekdaysShort: [ 'So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa' ], today: 'Heute', clear: 'Löschen', close: 'Schließen', firstDay: 1, format: 'dddd, dd. mmmm yyyy', formatSubmit: 'yyyy/mm/dd' }); jQuery.extend( jQuery.fn.pickatime.defaults, { clear: 'Löschen', format: 'H:i' });
// German jQuery.extend( jQuery.fn.pickadate.defaults, { monthsFull: [ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ], monthsShort: [ 'Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez' ], weekdaysFull: [ 'Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag' ], weekdaysShort: [ 'So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa' ], today: 'Heute', clear: 'Löschen', close: 'Schließen', firstDay: 1, format: 'dddd, dd. mmmm yyyy', formatSubmit: 'yyyy/mm/dd' }); jQuery.extend( jQuery.fn.pickatime.defaults, { clear: 'Löschen' });
Fix DI container when using console controller
<?php namespace haqqi\storm; use yii\base\Application; use yii\base\BootstrapInterface; use yii\base\Event; use yii\console\Controller; use yii\web\View; class Bootstrap implements BootstrapInterface { public function bootstrap($app) { $app->on(Application::EVENT_BEFORE_REQUEST, function ($event) { /** * @var $event Event */ \Yii::$container->set('yii\web\JqueryAsset', [ 'js' => ['jquery.min.js'], 'jsOptions' => ['position' => View::POS_HEAD] ]); \Yii::$container->set('yii\bootstrap\BootstrapAsset', [ 'css' => ['css/bootstrap.min.css'] ]); \Yii::$container->set('yii\bootstrap\BootstrapPluginAsset', [ 'js' => ['js/bootstrap.min.js'], 'jsOptions' => ['position' => View::POS_HEAD] ]); \Yii::$container->set('mimicreative\assets\MetisMenuAsset', [ 'css' => [] ]); }); } }
<?php namespace haqqi\storm; use yii\base\Application; use yii\base\BootstrapInterface; use yii\base\Event; use yii\console\Controller; use yii\web\View; class Bootstrap implements BootstrapInterface { public function bootstrap($app) { $app->on(Application::EVENT_BEFORE_REQUEST, function ($event) { /** * @var $event Event */ /* * Setup the config of asset bundles */ if(!$event->action->controller instanceof Controller) { $bundles =& $event->sender->assetManager->bundles; $bundles['yii\web\JqueryAsset']['js'] = ['jquery.min.js']; $bundles['yii\web\JqueryAsset']['jsOptions'] = ['position' => View::POS_HEAD]; $bundles['yii\bootstrap\BootstrapAsset']['css'] = ['css/bootstrap.min.css']; $bundles['yii\bootstrap\BootstrapPluginAsset']['js'] = ['js/bootstrap.min.js']; $bundles['yii\bootstrap\BootstrapPluginAsset']['jsOptions'] = ['position' => View::POS_HEAD]; $bundles['mimicreative\assets\MetisMenuAsset']['css'] = []; // \FB::log($event->sender->assetManager->bundles); } }); } }
Update to universal Google Analytics
<!-- footer --> <footer class="footer" role="contentinfo"> <!-- copyright --> <p class="copyright"> &copy; <?php echo date("Y"); ?> Copyright <?php bloginfo('name'); ?>. <?php _e('Powered by', 'html5blank'); ?> <a href="//wordpress.org" title="WordPress">WordPress</a> &amp; <a href="//html5blank.com" title="HTML5 Blank">HTML5 Blank</a>. </p> <!-- /copyright --> </footer> <!-- /footer --> </div> <!-- /wrapper --> <?php wp_footer(); ?> <!-- analytics --> <script> (function(f,i,r,e,s,h,l){i['GoogleAnalyticsObject']=s;f[s]=f[s]||function(){ (f[s].q=f[s].q||[]).push(arguments)},f[s].l=1*new Date();h=i.createElement(r), l=i.getElementsByTagName(r)[0];h.async=1;h.src=e;l.parentNode.insertBefore(h,l) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXX-XX', 'yourdomain.com'); ga('send', 'pageview'); </script> </body> </html>
<!-- footer --> <footer class="footer" role="contentinfo"> <!-- copyright --> <p class="copyright"> &copy; <?php echo date("Y"); ?> Copyright <?php bloginfo('name'); ?>. <?php _e('Powered by', 'html5blank'); ?> <a href="//wordpress.org" title="WordPress">WordPress</a> &amp; <a href="//html5blank.com" title="HTML5 Blank">HTML5 Blank</a>. </p> <!-- /copyright --> </footer> <!-- /footer --> </div> <!-- /wrapper --> <?php wp_footer(); ?> <!-- analytics --> <script> var _gaq=[['_setAccount','UA-XXXXXXXX-XX'],['_trackPageview']]; (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0]; g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js'; s.parentNode.insertBefore(g,s)})(document,'script'); </script> </body> </html>
Add environment variable for exported views
"use strict"; const Promise = require('bluebird'); const Task = require('../Task'); const path = require('path'); const ProjectType = require('../../ProjectType'); const fs = require('fs'); class ViewImportTask extends Task { constructor(buildManager, taskRunner) { super(buildManager, taskRunner); this.availableTo = [ProjectType.FRONTEND]; } action() { var _ = require('lodash'); var views = require('../../RequireViews')({ dirname: path.join(process.cwd(), this._buildManager.options.views), filter: /(.+)\.tsx$/, map: function (name) { return _.capitalize(name); } }); const exportFolder = path.join(process.cwd(), this._buildManager.options.views, 'export.js'); process.env.EXPORT_VIEWS_PATH = exportFolder; fs.writeFileSync(exportFolder, 'module.exports = ' + JSON.stringify(views).replace(/"/gmi, '')); return Promise.resolve(); } } module.exports = ViewImportTask;
"use strict"; const Promise = require('bluebird'); const Task = require('../Task'); const path = require('path'); const ProjectType = require('../../ProjectType'); const fs = require('fs'); class ViewImportTask extends Task { constructor(buildManager, taskRunner) { super(buildManager, taskRunner); this.availableTo = [ProjectType.FRONTEND]; } action() { var _ = require('lodash'); var views = require('../../RequireViews')({ dirname: path.join(process.cwd(), this._buildManager.options.views), filter: /(.+)\.tsx$/, map: function (name) { return _.capitalize(name); } }); const exportFolder = path.join(process.cwd(), this._buildManager.options.views, 'export.js'); fs.writeFileSync(exportFolder, 'module.exports = ' + JSON.stringify(views).replace(/"/gmi, '')); return Promise.resolve(); } } module.exports = ViewImportTask;
Unify bokeh's text properties' values with bokehjs
"""Classes that can be mixed-in to HasProps classes to get them the corresponding attributes. """ from .properties import HasProps, ColorSpec, DataSpec, Enum, DashPattern, Int, String from .enums import LineJoin, LineCap, FontStyle, TextAlign, TextBaseline class FillProps(HasProps): """ Mirrors the BokehJS properties.fill_properties class """ fill_color = ColorSpec("gray") fill_alpha = DataSpec(1.0) class LineProps(HasProps): """ Mirrors the BokehJS properties.line_properties class """ line_color = ColorSpec("black") line_width = DataSpec line_alpha = DataSpec(1.0) line_join = Enum(LineJoin) line_cap = Enum(LineCap) line_dash = DashPattern line_dash_offset = Int(0) class TextProps(HasProps): """ Mirrors the BokehJS properties.text_properties class """ text_font = String("Helvetica") text_font_size = String("12pt") text_font_style = Enum(FontStyle) text_color = ColorSpec("#444444") text_alpha = DataSpec(1.0) text_align = Enum(TextAlign) text_baseline = Enum(TextBaseline, default="bottom")
"""Classes that can be mixed-in to HasProps classes to get them the corresponding attributes. """ from .properties import HasProps, ColorSpec, DataSpec, Enum, DashPattern, Int, String from .enums import LineJoin, LineCap, FontStyle, TextAlign, TextBaseline class FillProps(HasProps): """ Mirrors the BokehJS properties.fill_properties class """ fill_color = ColorSpec("gray") fill_alpha = DataSpec(1.0) class LineProps(HasProps): """ Mirrors the BokehJS properties.line_properties class """ line_color = ColorSpec("black") line_width = DataSpec line_alpha = DataSpec(1.0) line_join = Enum(LineJoin) line_cap = Enum(LineCap) line_dash = DashPattern line_dash_offset = Int(0) class TextProps(HasProps): """ Mirrors the BokehJS properties.text_properties class """ text_font = String("Helvetica") text_font_size = String("10pt") text_font_style = Enum(FontStyle) text_color = ColorSpec("black") text_alpha = DataSpec(1.0) text_align = Enum(TextAlign) text_baseline = Enum(TextBaseline)
Fix missing parameter in docs of setChannel function
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Channel\Model; use Sylius\Component\Resource\Model\CodeAwareInterface; use Sylius\Component\Resource\Model\ResourceInterface; use Sylius\Component\Resource\Model\TimestampableInterface; use Sylius\Component\Resource\Model\ToggleableInterface; /** * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface ChannelInterface extends CodeAwareInterface, TimestampableInterface, ToggleableInterface, ResourceInterface { /** * @return string */ public function getName(); /** * @param string $name */ public function setName($name); /** * @return string */ public function getDescription(); /** * @param string $description */ public function setDescription($description); /** * @return string */ public function getHostname(); /** * @param string $hostname */ public function setHostname($hostname); /** * @return string */ public function getColor(); /** * @param string $color */ public function setColor($color); }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Channel\Model; use Sylius\Component\Resource\Model\CodeAwareInterface; use Sylius\Component\Resource\Model\ResourceInterface; use Sylius\Component\Resource\Model\TimestampableInterface; use Sylius\Component\Resource\Model\ToggleableInterface; /** * @author Paweł Jędrzejewski <pawel@sylius.org> */ interface ChannelInterface extends CodeAwareInterface, TimestampableInterface, ToggleableInterface, ResourceInterface { /** * @return string */ public function getName(); /** * @param string $name */ public function setName($name); /** * @return string */ public function getDescription(); /** * @param string $description */ public function setDescription($description); /** * @return string */ public function getHostname(); /** * @param string $url */ public function setHostname($hostname); /** * @return string */ public function getColor(); /** * @param string $color */ public function setColor($color); }
Update params to send object literal with `digits` property
import chai, { expect } from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; chai.use(sinonChai); import ResourceTestHelper from './ResourceTestHelper'; import DtmfResource from '../lib/DtmfResource'; import HttpClient from '../lib/HttpClient'; import Credentials from '../lib/Credentials'; var creds = Credentials.parse({ applicationId: 'some-id', privateKey: __dirname + '/private-test.key' }); var emptyCallback = () => {}; describe('DtmfResource', () => { var httpClientStub = null; var dtmf = null; beforeEach(() => { httpClientStub = sinon.createStubInstance(HttpClient); var options = { httpClient: httpClientStub }; dtmf = new DtmfResource(creds, options); }) it('should be able to send DTMF to a call', () => { const callId = '2342342-lkjhlkjh-32423'; var params = {digits: [1,2,3,4]}; dtmf.send(callId, params, emptyCallback); var expectedRequestArgs = ResourceTestHelper.requestArgsMatch(params, { path: DtmfResource.PATH.replace('{call_uuid}', callId), method: 'PUT' }); expect(httpClientStub.request) .to.have.been.calledWith( sinon.match(expectedRequestArgs), emptyCallback ); }); });
import chai, { expect } from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; chai.use(sinonChai); import ResourceTestHelper from './ResourceTestHelper'; import DtmfResource from '../lib/DtmfResource'; import HttpClient from '../lib/HttpClient'; import Credentials from '../lib/Credentials'; var creds = Credentials.parse({ applicationId: 'some-id', privateKey: __dirname + '/private-test.key' }); var emptyCallback = () => {}; describe('DtmfResource', () => { var httpClientStub = null; var dtmf = null; beforeEach(() => { httpClientStub = sinon.createStubInstance(HttpClient); var options = { httpClient: httpClientStub }; dtmf = new DtmfResource(creds, options); }) it('should be able to send DTMF to a call', () => { const callId = '2342342-lkjhlkjh-32423'; var params = [1,2,3,4]; dtmf.send(callId, params, emptyCallback); var expectedRequestArgs = ResourceTestHelper.requestArgsMatch(params, { path: DtmfResource.PATH.replace('{call_uuid}', callId), method: 'PUT' }); expect(httpClientStub.request) .to.have.been.calledWith( sinon.match(expectedRequestArgs), emptyCallback ); }); });
Revert "Change DATE_FORMAT to be equivalent to datetime.isoformat()" This reverts commit 2085cf0c103df44c500bae9bccdc2ce16cd8710f. See discussion of the original commit https://github.com/amiv-eth/amivapi/commit/2085cf0c103df44c500bae9bccdc2ce16cd8710f
"""Default settings for all environments. These settings will be extended by additional config files in ROOT/config. Run `python manage.py create_config` to create such a config file. """ from os.path import abspath, dirname, join # Custom ROOT_DIR = abspath(join(dirname(__file__), "..")) EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' # Flask DEBUG = False TESTING = False # Flask-SQLALchemy # Eve ID_FIELD = "id" AUTH_FIELD = "_author" DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ" BANDWIDTH_SAVER = False RESOURCE_METHODS = ['GET', 'POST'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] PUBLIC_METHODS = ['GET'] # This is the only way to make / public XML = False # Eve, file storage options RETURN_MEDIA_AS_BASE64_STRING = False EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url'] STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump' STORAGE_URL = r'/storage'
"""Default settings for all environments. These settings will be extended by additional config files in ROOT/config. Run `python manage.py create_config` to create such a config file. """ from os.path import abspath, dirname, join # Custom ROOT_DIR = abspath(join(dirname(__file__), "..")) EMAIL_REGEX = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' # Flask DEBUG = False TESTING = False # Flask-SQLALchemy # Eve ID_FIELD = "id" AUTH_FIELD = "_author" DATE_FORMAT = "%Y-%m-%dT%H:%M:%S" BANDWIDTH_SAVER = False RESOURCE_METHODS = ['GET', 'POST'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] PUBLIC_METHODS = ['GET'] # This is the only way to make / public XML = False # Eve, file storage options RETURN_MEDIA_AS_BASE64_STRING = False EXTENDED_MEDIA_INFO = ['filename', 'size', 'content_url'] STORAGE_DIR = r'D:\Programmieren\amivapi\src\filedump' STORAGE_URL = r'/storage'
Add type declartions and docstrings
import flask from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id: int) -> User: """Returns a user from the database based on their id :param user_id: a users unique id :return: User object with corresponding id, or none if user does not exist """ return User.query.filter_by(id=user_id).first() def handle_basic_auth(request: flask.Request) -> User: """Verifies a request using BASIC auth :param request: flask request object :return: User object corresponding to login information, or none if user does not exist """ auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request: flask.Request) -> flask.Response: """Handle a login request from a user :param request: incoming request object :return: flask response object """ user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return flask.Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
from flask import Response from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id): """Returns a user from the database based on their id""" return User.query.filter_by(id=user_id).first() def handle_basic_auth(request): auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request): """Handle a login request from a user.""" user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})