text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Add freezegun requirement for tests.
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215) import multiprocessing assert multiprocessing import re from setuptools import setup, find_packages def get_version(): """ Extracts the version number from the version.py file. """ VERSION_FILE = 'entity_emailer/version.py' mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) if mo: return mo.group(1) else: raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE)) setup( name='', version=get_version(), description='', long_description=open('README.md').read(), url='', author='', author_email='[email protected]', keywords='', packages=find_packages(), classifiers=[ 'Programming Language :: Python', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Framework :: Django', ], license='MIT', install_requires=[ 'django>=1.6', 'django-entity>=0.4.1', 'celery>=3.1', ], tests_require=[ 'django-dynamic-fixture', 'django-nose', 'freezegun', 'mock', 'south', ], test_suite='run_tests.run_tests', include_package_data=True, )
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215) import multiprocessing assert multiprocessing import re from setuptools import setup, find_packages def get_version(): """ Extracts the version number from the version.py file. """ VERSION_FILE = 'entity_emailer/version.py' mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) if mo: return mo.group(1) else: raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE)) setup( name='', version=get_version(), description='', long_description=open('README.md').read(), url='', author='', author_email='[email protected]', keywords='', packages=find_packages(), classifiers=[ 'Programming Language :: Python', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Framework :: Django', ], license='MIT', install_requires=[ 'django>=1.6', 'django-entity>=0.4.1', 'celery>=3.1', ], tests_require=[ 'django-nose', 'south', 'mock', 'django-dynamic-fixture' ], test_suite='run_tests.run_tests', include_package_data=True, )
Add support for stopBit encoded small decimal.
package net.openhft.chronicle.bytes; import net.openhft.chronicle.core.Maths; import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.Random; import static junit.framework.TestCase.assertEquals; public class StopBitDecimalTest { @Test public void testDecimals() { Bytes<ByteBuffer> bytes = Bytes.elasticHeapByteBuffer(16); Random rand = new Random(); for (int i = 0; i < 10_000; i++) { rand.setSeed(i); bytes.clear(); int scale = rand.nextInt(10); double d = (rand.nextLong() % 1e14) / Maths.tens(scale); bytes.writeStopBitDecimal(d); BigDecimal bd = BigDecimal.valueOf(d); long v = bytes.readStopBit(); BigDecimal ebd = new BigDecimal(BigInteger.valueOf(v / 10), (int) (Math.abs(v) % 10)); assertEquals("i: " + i + ", d: " + d + ", v: " + v, ebd.doubleValue(), bd.doubleValue(), 0.0); bytes.readPosition(0); double d2 = bytes.readStopBitDecimal(); assertEquals("i: " + i + ", d: " + d + ", v: " + v, d, d2, 0.0); } } }
package net.openhft.chronicle.bytes; import net.openhft.chronicle.core.Maths; import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.Random; import static junit.framework.TestCase.assertEquals; public class StopBitDecimalTest { @Test public void testDecimals() { Bytes<ByteBuffer> bytes = Bytes.elasticHeapByteBuffer(16); Random rand = new Random(); for (int i = 0; i < 10000; i++) { rand.setSeed(i); bytes.clear(); int scale = rand.nextInt(10); double d = (rand.nextLong() % 1e14) / Maths.tens(scale); bytes.writeStopBitDecimal(d); BigDecimal bd = BigDecimal.valueOf(d); long v = bytes.readStopBit(); BigDecimal ebd = new BigDecimal(BigInteger.valueOf(v / 10), (int) (Math.abs(v) % 10)); assertEquals("i: " + i + ", d: " + d + ", v: " + v, ebd.doubleValue(), bd.doubleValue(), 0.0); bytes.readPosition(0); double d2 = bytes.readStopBitDecimal(); assertEquals("i: " + i + ", d: " + d + ", v: " + v, d, d2, 0.0); } } }
Use shorter timestamps for log messages
<?php class CbLogger { const PRIORITY_DEBUG = 1; const PRIORITY_INFO = 2; const PRIORITY_WARN = 3; const PRIORITY_ERROR = 4; const PRIORITY_DEFAULT = 99; protected static $priorities = array( self::PRIORITY_DEBUG => 'DEBUG', self::PRIORITY_INFO => 'INFO', self::PRIORITY_WARN => 'WARN', self::PRIORITY_ERROR => 'ERROR', self::PRIORITY_DEFAULT => 'DEFAULT' ); protected static $logLevel = -1; protected static $logFile; public static function setLogFile($filename) { self::$logFile = fopen($filename, 'w+'); } public static function setLogLevel($priority) { self::$logLevel = $priority; } public static function log($message, $priority = CbLogger::PRIORITY_INFO) { if ($priority < self::$logLevel) { return; } $message = sprintf( '%s - %s: %s', date('Y-m-d h:i:s'), self::$priorities[$priority], $message ); echo $message.PHP_EOL; if (self::$logFile) { fwrite(self::$logFile, $message.PHP_EOL); } } public function __destruct() { if (self::$logFile) { fclose(self::$logFile); } } }
<?php class CbLogger { const PRIORITY_DEBUG = 1; const PRIORITY_INFO = 2; const PRIORITY_WARN = 3; const PRIORITY_ERROR = 4; const PRIORITY_DEFAULT = 99; protected static $priorities = array( self::PRIORITY_DEBUG => 'DEBUG', self::PRIORITY_INFO => 'INFO', self::PRIORITY_WARN => 'WARN', self::PRIORITY_ERROR => 'ERROR', self::PRIORITY_DEFAULT => 'DEFAULT' ); protected static $logLevel = -1; protected static $logFile; public static function setLogFile($filename) { self::$logFile = fopen($filename, 'w+'); } public static function setLogLevel($priority) { self::$logLevel = $priority; } public static function log($message, $priority = CbLogger::PRIORITY_INFO) { if ($priority < self::$logLevel) { return; } $message = sprintf( '%s - %s: %s', date('c'), self::$priorities[$priority], $message ); echo $message.PHP_EOL; if (self::$logFile) { fwrite(self::$logFile, $message.PHP_EOL); } } public function __destruct() { if (self::$logFile) { fclose(self::$logFile); } } }
Fix broken NSG create command (duplicate --name parameter)
# pylint: disable=no-self-use,too-many-arguments from azure.mgmt.network.models import Subnet, SecurityRule from ._factory import _network_client_factory def create_update_subnet(resource_group_name, subnet_name, virtual_network_name, address_prefix): '''Create or update a virtual network (VNet) subnet''' subnet_settings = Subnet(name=subnet_name, address_prefix=address_prefix) ncf = _network_client_factory() return ncf.subnets.create_or_update( resource_group_name, virtual_network_name, subnet_name, subnet_settings) def create_update_nsg_rule(resource_group_name, network_security_group_name, security_rule_name, protocol, source_address_prefix, destination_address_prefix, access, direction, source_port_range, destination_port_range, description=None, priority=None): settings = SecurityRule(protocol=protocol, source_address_prefix=source_address_prefix, destination_address_prefix=destination_address_prefix, access=access, direction=direction, description=description, source_port_range=source_port_range, destination_port_range=destination_port_range, priority=priority, name=security_rule_name) ncf = _network_client_factory() return ncf.security_rules.create_or_update( resource_group_name, network_security_group_name, security_rule_name, settings) create_update_nsg_rule.__doc__ = SecurityRule.__doc__
# pylint: disable=no-self-use,too-many-arguments from azure.mgmt.network.models import Subnet, SecurityRule from ._factory import _network_client_factory def create_update_subnet(resource_group_name, subnet_name, virtual_network_name, address_prefix): '''Create or update a virtual network (VNet) subnet''' subnet_settings = Subnet(name=subnet_name, address_prefix=address_prefix) ncf = _network_client_factory() return ncf.subnets.create_or_update( resource_group_name, virtual_network_name, subnet_name, subnet_settings) def create_update_nsg_rule(resource_group_name, network_security_group_name, security_rule_name, protocol, source_address_prefix, destination_address_prefix, access, direction, source_port_range, destination_port_range, description=None, priority=None, name=None): settings = SecurityRule(protocol=protocol, source_address_prefix=source_address_prefix, destination_address_prefix=destination_address_prefix, access=access, direction=direction, description=description, source_port_range=source_port_range, destination_port_range=destination_port_range, priority=priority, name=name) ncf = _network_client_factory() return ncf.security_rules.create_or_update( resource_group_name, network_security_group_name, security_rule_name, settings) create_update_nsg_rule.__doc__ = SecurityRule.__doc__
Fix api call: pagesize is now limit
'use strict'; var RecentLocationsDirective = function (apiService, assetPath, configuration) { return { restrict: 'A', scope: { region: '=', pageSize: '=' }, templateUrl: assetPath + 'partials/_recent_locations.html', link: function (scope, elem, attrs) { scope.urlbase = configuration.urlbase || '/'; scope.$watch(attrs.region, function () { var region = scope.$eval(attrs.region); if (region) { apiService('regions/' + scope.region.uuid + '/locations?sort=-created&limit=' + (parseInt(scope.pageSize) || 10)).actions.all(function (err, locations) { scope.$applyAsync(function () { scope.locations = locations.results || locations; }); }); } }); } }; }; RecentLocationsDirective.$inject = ['apiService', 'assetPath','configuration']; module.exports = RecentLocationsDirective;
'use strict'; var RecentLocationsDirective = function (apiService, assetPath, configuration) { return { restrict: 'A', scope: { region: '=', pageSize: '=' }, templateUrl: assetPath + 'partials/_recent_locations.html', link: function (scope, elem, attrs) { scope.urlbase = configuration.urlbase || '/'; scope.$watch(attrs.region, function () { var region = scope.$eval(attrs.region); if (region) { apiService('regions/' + scope.region.uuid + '/locations?sort=-created&pagesize=' + (parseInt(scope.pageSize) || 10)).actions.all(function (err, locations) { scope.$applyAsync(function () { scope.locations = locations.results || locations; }); }); } }); } }; }; RecentLocationsDirective.$inject = ['apiService', 'assetPath','configuration']; module.exports = RecentLocationsDirective;
Add end-to-end integration testing for all compression types
import pytest from kafka import KafkaConsumer, KafkaProducer from test.conftest import version from test.testutil import random_string @pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set") @pytest.mark.parametrize("compression", [None, 'gzip', 'snappy', 'lz4']) def test_end_to_end(kafka_broker, compression): # LZ4 requires 0.8.2 if compression == 'lz4' and version() < (0, 8, 2): return connect_str = 'localhost:' + str(kafka_broker.port) producer = KafkaProducer(bootstrap_servers=connect_str, max_block_ms=10000, compression_type=compression, value_serializer=str.encode) consumer = KafkaConsumer(bootstrap_servers=connect_str, group_id=None, consumer_timeout_ms=10000, auto_offset_reset='earliest', value_deserializer=bytes.decode) topic = random_string(5) for i in range(1000): producer.send(topic, 'msg %d' % i) producer.flush() producer.close() consumer.subscribe([topic]) msgs = set() for i in range(1000): try: msgs.add(next(consumer).value) except StopIteration: break assert msgs == set(['msg %d' % i for i in range(1000)])
import pytest from kafka import KafkaConsumer, KafkaProducer from test.conftest import version from test.testutil import random_string @pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set") def test_end_to_end(kafka_broker): connect_str = 'localhost:' + str(kafka_broker.port) producer = KafkaProducer(bootstrap_servers=connect_str, max_block_ms=10000, value_serializer=str.encode) consumer = KafkaConsumer(bootstrap_servers=connect_str, group_id=None, consumer_timeout_ms=10000, auto_offset_reset='earliest', value_deserializer=bytes.decode) topic = random_string(5) for i in range(1000): producer.send(topic, 'msg %d' % i) producer.flush() producer.close() consumer.subscribe([topic]) msgs = set() for i in range(1000): try: msgs.add(next(consumer).value) except StopIteration: break assert msgs == set(['msg %d' % i for i in range(1000)])
Add version number to parameter meta data
from xml.dom.minidom import getDOMImplementation import codecs class XMLOutput(): def __init__(self, groups): impl = getDOMImplementation() xml_document = impl.createDocument(None, "parameters", None) xml_parameters = xml_document.documentElement xml_version = xml_document.createElement("version") xml_parameters.appendChild(xml_version) xml_version_value = xml_document.createTextNode("1") xml_version.appendChild(xml_version_value) for group in groups: xml_group = xml_document.createElement("group") xml_group.setAttribute("name", group.GetName()) xml_parameters.appendChild(xml_group) for param in group.GetParams(): xml_param = xml_document.createElement("parameter") xml_group.appendChild(xml_param) for code in param.GetFieldCodes(): value = param.GetFieldValue(code) xml_field = xml_document.createElement(code) xml_param.appendChild(xml_field) xml_value = xml_document.createTextNode(value) xml_field.appendChild(xml_value) self.xml_document = xml_document def Save(self, filename): with codecs.open(filename, 'w', 'utf-8') as f: self.xml_document.writexml(f, indent=" ", addindent=" ", newl="\n")
from xml.dom.minidom import getDOMImplementation import codecs class XMLOutput(): def __init__(self, groups): impl = getDOMImplementation() xml_document = impl.createDocument(None, "parameters", None) xml_parameters = xml_document.documentElement for group in groups: xml_group = xml_document.createElement("group") xml_group.setAttribute("name", group.GetName()) xml_parameters.appendChild(xml_group) for param in group.GetParams(): xml_param = xml_document.createElement("parameter") xml_group.appendChild(xml_param) for code in param.GetFieldCodes(): value = param.GetFieldValue(code) xml_field = xml_document.createElement(code) xml_param.appendChild(xml_field) xml_value = xml_document.createTextNode(value) xml_field.appendChild(xml_value) self.xml_document = xml_document def Save(self, filename): with codecs.open(filename, 'w', 'utf-8') as f: self.xml_document.writexml(f, indent=" ", addindent=" ", newl="\n")
Revert "Progressing dots to show test is running" Breaks tests; https://travis-ci.org/wikimedia/pywikibot-core/builds/26752150 This reverts commit 93379dbf499c58438917728b74862f282c15dba4. Change-Id: Iacb4cc9e6999d265b46c558ed3999c1198f87de0
# -*- coding: utf-8 -*- # # (C) Pywikibot team, 2014 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def testMapEntry(self): """Test the validity of the pywikibot.date format maps.""" for formatName in date.formats: step = 1 if formatName in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatName] for code, convFunc in date.formats[formatName].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatName)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatName)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) if __name__ == '__main__': try: unittest.main() except SystemExit: pass
# -*- coding: utf-8 -*- # # (C) Pywikibot team, 2014 # # Distributed under the terms of the MIT license. # __version__ = '$Id$' from tests.utils import unittest from pywikibot import date class TestDate(unittest.TestCase): """Test cases for date library""" def __init__(self, formatname): super(TestDate, self).__init__() self.formatname = formatname def testMapEntry(self, formatname): """The test ported from date.py""" step = 1 if formatname in date.decadeFormats: step = 10 predicate, start, stop = date.formatLimits[formatname] for code, convFunc in date.formats[formatname].items(): for value in range(start, stop, step): self.assertTrue( predicate(value), "date.formats['%(formatname)s']['%(code)s']:\n" "invalid value %(value)d" % locals()) newValue = convFunc(convFunc(value)) self.assertEqual( newValue, value, "date.formats['%(formatname)s']['%(code)s']:\n" "value %(newValue)d does not match %(value)s" % locals()) def runTest(self): """method called by unittest""" self.testMapEntry(self.formatname) def suite(): """Setup the test suite and register all test to different instances""" suite = unittest.TestSuite() suite.addTests(TestDate(formatname) for formatname in date.formats) return suite if __name__ == '__main__': try: unittest.TextTestRunner().run(suite()) except SystemExit: pass
Fix error - rm test dir command is not executed in correct branch.
#!/usr/bin/env python3 from passwd_change import passwd_change, shadow_change, mails_delete from unittest import TestCase, TestLoader, TextTestRunner import os import subprocess class PasswdChange_Test(TestCase): def setUp(self): """ Preconditions """ subprocess.call(['mkdir', 'test']) subprocess.call(['touch', 'test/rvv', 'test/max', 'test/bdv' ,'test/mail']) #TODO create passwd test file #TODO create shadow test file #TODO create keys.txt file def tearDown(self): try: if os.path.exists('test/rvv'): raise Exception('test/rvv must not exist') if not (os.path.exists('test/max') and os.path.exists('test/bdv') and os.path.exists('test/mail')): raise Exception('File max, bdv or mail must exist!') except: raise else: subprocess.call(['rm', '-r', 'test/']) def test_passwd_change(self): shadow_change(*passwd_change()) mails_delete(maildir_path='test') def test_passwd_change_2(self): shadow_change(*passwd_change()) mails_delete(maildir_path='test/') suite = TestLoader().loadTestsFromTestCase(PasswdChange_Test) TextTestRunner(verbosity=2).run(suite)
#!/usr/bin/env python3 from passwd_change import passwd_change, shadow_change, mails_delete from unittest import TestCase, TestLoader, TextTestRunner import os import subprocess class PasswdChange_Test(TestCase): def setUp(self): """ Preconditions """ subprocess.call(['mkdir', 'test']) subprocess.call(['touch', 'test/rvv', 'test/max', 'test/bdv' ,'test/mail']) #TODO create passwd test file #TODO create shadow test file #TODO create keys.txt file def tearDown(self): try: if os.path.exists('test/rvv'): raise Exception('test/rvv must not exist') if not (os.path.exists('test/max') and os.path.exists('test/bdv') and os.path.exists('test/mail')): raise Exception('File max, bdv or mail must exist!') except: subprocess.call(['rm', '-r', 'test/']) raise def test_passwd_change(self): shadow_change(*passwd_change()) mails_delete(maildir_path='test') def test_passwd_change_2(self): shadow_change(*passwd_change()) mails_delete(maildir_path='test/') suite = TestLoader().loadTestsFromTestCase(PasswdChange_Test) TextTestRunner(verbosity=2).run(suite)
Update the default application name
/*global angular: true, appInsights: true */ (function () { "use strict"; angular.module('angular-appinsights', []) .provider('insights', function () { var _appId, _appName; this.start = function (appId, appName) { _appId = appId; _appName = appName || '(Application Root)'; if (appInsights && appId) { appInsights.start(appId); } }; function Insights () { var _logEvent = function (event, properties, property) { if (appInsights && _appId) { appInsights.logEvent(event, properties, property); } }, _logPageView = function (page) { if (appInsights && _appId) { appInsights.logPageView(page); } }; return { 'logEvent': _logEvent, 'logPageView': _logPageView, 'appName': _appName }; } this.$get = function() { return new Insights(); }; }) .run(function($rootScope, $route, $location, insights) { $rootScope.$on('$locationChangeSuccess', function() { var pagePath; try { pagePath = $location.path().substr(1); pagePath = insights.appName + '/' + pagePath; } finally { insights.logPageView(pagePath); } }); }); }());
/*global angular: true, appInsights: true */ (function () { "use strict"; angular.module('angular-appinsights', []) .provider('insights', function () { var _appId, _appName; this.start = function (appId, appName) { _appId = appId; _appName = appName || '(Root)'; if (appInsights && appId) { appInsights.start(appId); } }; function Insights () { var _logEvent = function (event, properties, property) { if (appInsights && _appId) { appInsights.logEvent(event, properties, property); } }, _logPageView = function (page) { if (appInsights && _appId) { appInsights.logPageView(page); } }; return { 'logEvent': _logEvent, 'logPageView': _logPageView, 'appName': _appName }; } this.$get = function() { return new Insights(); }; }) .run(function($rootScope, $route, $location, insights) { $rootScope.$on('$locationChangeSuccess', function() { var pagePath; try { pagePath = $location.path().substr(1); pagePath = insights.appName + '/' + pagePath; } finally { insights.logPageView(pagePath); } }); }); }());
Undo change that makes client-side issue. Will need another way to get sub-items
package net.machinemuse.numina.recipe; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import java.util.HashMap; import java.util.Map; /** * Author: MachineMuse (Claire Semple) * Created: 5:06 PM, 11/4/13 */ public class ItemNameMappings { private static Map<String, ItemStack> itemMap; private static Map<String, ItemStack> getItemMap() { if (itemMap == null) { itemMap = new HashMap<String, ItemStack>(); for (Object obj : Block.blockRegistry) { Block block = (Block)obj; if (block != null && block.getUnlocalizedName() != null) { itemMap.put(block.getUnlocalizedName(), new ItemStack(block)); } } for (Object obj : Item.itemRegistry) { Item item = (Item)obj; if (item != null && item.getUnlocalizedName() != null) { itemMap.put(item.getUnlocalizedName(), new ItemStack(item)); } } } return itemMap; } public static ItemStack getItem(String name) { if (getItemMap().containsKey(name)) return getItemMap().get(name); else return null; } }
package net.machinemuse.numina.recipe; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Author: MachineMuse (Claire Semple) * Created: 5:06 PM, 11/4/13 */ public class ItemNameMappings { private static Map<String, ItemStack> itemMap; private static Map<String, ItemStack> getItemMap() { if (itemMap == null) { itemMap = new HashMap<String, ItemStack>(); for (Object obj : Block.blockRegistry) { Block block = (Block)obj; if (block != null && block.getUnlocalizedName() != null) { itemMap.put(block.getUnlocalizedName(), new ItemStack(block)); } } for (Object obj : Item.itemRegistry) { Item item = (Item)obj; if (item != null) { if(item.getHasSubtypes()) { List<ItemStack> stacklist = new ArrayList<ItemStack>(); for(CreativeTabs tab : item.getCreativeTabs()) { item.getSubItems(item, tab, stacklist); } for(ItemStack stack : stacklist) { itemMap.put(stack.getUnlocalizedName(), stack.copy()); } } else { itemMap.put(item.getUnlocalizedName(), new ItemStack(item)); } } } } return itemMap; } public static ItemStack getItem(String name) { if (getItemMap().containsKey(name)) return getItemMap().get(name); else return null; } }
Disable every single test that uses clustering.
package com.codingchili.core.protocol; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import static com.codingchili.core.configuration.CoreStrings.ERROR_CLUSTERING_REQUIRED; /** * @author Robin Duda * * Tests the clusternode class to require clustering. */ @RunWith(VertxUnitRunner.class) public class ClusterNodeIT { private Vertx vertx; @After public void tearDown(TestContext test) { vertx.close(test.asyncAssertSuccess()); } @Test public void testVertxNotClusteredError(TestContext test) { try { vertx = Vertx.vertx(); vertx.deployVerticle(new ClusterNode() {}); } catch (RuntimeException e) { test.assertEquals(ERROR_CLUSTERING_REQUIRED, e.getMessage()); } } @Ignore("Disable while memory constraint in travis are being figured out.") @Test public void testVertxClusteredOk(TestContext test) { Async async = test.async(); Vertx.clusteredVertx(new VertxOptions(), handler -> { vertx = handler.result(); handler.result().deployVerticle(new ClusterNode() {}); async.complete(); }); } }
package com.codingchili.core.protocol; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import static com.codingchili.core.configuration.CoreStrings.ERROR_CLUSTERING_REQUIRED; /** * @author Robin Duda * * Tests the clusternode class to require clustering. */ @RunWith(VertxUnitRunner.class) public class ClusterNodeIT { private Vertx vertx; @After public void tearDown(TestContext test) { vertx.close(test.asyncAssertSuccess()); } @Test public void testVertxNotClusteredError(TestContext test) { try { vertx = Vertx.vertx(); vertx.deployVerticle(new ClusterNode() {}); } catch (RuntimeException e) { test.assertEquals(ERROR_CLUSTERING_REQUIRED, e.getMessage()); } } @Test public void testVertxClusteredOk(TestContext test) { Async async = test.async(); Vertx.clusteredVertx(new VertxOptions(), handler -> { vertx = handler.result(); handler.result().deployVerticle(new ClusterNode() {}); async.complete(); }); } }
Add help message comment to env command
<?php namespace PhpBrew\Command; use PhpBrew\Config; use PhpBrew\Utils; class EnvCommand extends \CLIFramework\Command { public function brief() { return 'Export environment variables'; } public function execute($buildName = NULL) { // get current version if (!$buildName) { $buildName = getenv('PHPBREW_PHP'); } // $currentVersion; $root = Config::getPhpbrewRoot(); $home = Config::getPhpbrewHome(); $lookup = getenv('PHPBREW_LOOKUP_PREFIX'); $this->logger->writeln("export PHPBREW_ROOT=$root"); $this->logger->writeln("export PHPBREW_HOME=$home"); $this->logger->writeln("export PHPBREW_LOOKUP_PREFIX=$lookup"); if ($buildName !== false) { // checking php version existence $targetPhpBinPath = Config::getVersionBinPath($buildName); if (is_dir($targetPhpBinPath)) { echo 'export PHPBREW_PHP=' . $buildName . "\n"; echo 'export PHPBREW_PATH=' . ($buildName ? Config::getVersionBinPath($buildName) : '') . "\n"; } } $this->logger->writeln('# Run this command to configure your shell:'); $this->logger->writeln('# # eval "$(phpbrew env)"'); } }
<?php namespace PhpBrew\Command; use PhpBrew\Config; use PhpBrew\Utils; class EnvCommand extends \CLIFramework\Command { public function brief() { return 'Export environment variables'; } public function execute($buildName = NULL) { // get current version if (!$buildName) { $buildName = getenv('PHPBREW_PHP'); } // $currentVersion; $root = Config::getPhpbrewRoot(); $home = Config::getPhpbrewHome(); $lookup = getenv('PHPBREW_LOOKUP_PREFIX'); $this->logger->writeln("export PHPBREW_ROOT=$root"); $this->logger->writeln("export PHPBREW_HOME=$home"); $this->logger->writeln("export PHPBREW_LOOKUP_PREFIX=$lookup"); if ($buildName !== false) { // checking php version existence $targetPhpBinPath = Config::getVersionBinPath($buildName); if (is_dir($targetPhpBinPath)) { echo 'export PHPBREW_PHP=' . $buildName . "\n"; echo 'export PHPBREW_PATH=' . ($buildName ? Config::getVersionBinPath($buildName) : '') . "\n"; } } } }
Switch to Request filled() method Behaviour of Request has() method changed in Laravel 5.5. filled() now has the old behaviour. https://laravel.com/docs/5.5/requests#retrieving-input
<?php namespace RadDB\Http\Requests; use Illuminate\Http\Request; use Illuminate\Foundation\Http\FormRequest; class StoreRecommendationRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules(Request $request) { // Build the validation rules $rules = [ 'surveyId' => 'required|exists:testdates,id|integer', 'recommendation' => 'required|string|max:500', 'resolved' => 'integer', 'WONum' => 'string|nullable|max:20', 'ServiceReport' => 'file|mimes:pdf', ]; // If 'resolved' was checked, then add validation rules for // 'RecResolveDate' and 'ResolvedBy'. if ($request->filled('resolved')) { $rules['RecResolveDate'] = 'required|date_format:Y-m-d'; $rules['ResolvedBy'] = 'required|string|max:10'; } return $rules; } }
<?php namespace RadDB\Http\Requests; use Illuminate\Http\Request; use Illuminate\Foundation\Http\FormRequest; class StoreRecommendationRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules(Request $request) { // Build the validation rules $rules = [ 'surveyId' => 'required|exists:testdates,id|integer', 'recommendation' => 'required|string|max:500', 'resolved' => 'integer', 'WONum' => 'string|nullable|max:20', 'ServiceReport' => 'file|mimes:pdf', ]; // If 'resolved' was checked, then add validation rules for // 'RecResolveDate' and 'ResolvedBy'. if ($request->has('resolved')) { $rules['RecResolveDate'] = 'required|date_format:Y-m-d'; $rules['ResolvedBy'] = 'required|string|max:10'; } return $rules; } }
Add simple test for config builder Signed-off-by: Michal Kuffa <[email protected]>
import io import os from textwrap import dedent from pg_bawler import bawlerd class TestBawlerdConfig: def test_build_config_location_list(self): assert not bawlerd.conf.build_config_location_list(locations=()) user_conf = os.path.join( os.path.expanduser('~'), bawlerd.conf.DEFAULT_CONFIG_FILENAME) system_conf = os.path.join( '/etc/pg_bawler', bawlerd.conf.DEFAULT_CONFIG_FILENAME) assert user_conf in bawlerd.conf.build_config_location_list() assert system_conf in bawlerd.conf.build_config_location_list() def test__load_file(self): config = bawlerd.conf._load_file(io.StringIO(dedent("""\ logging: formatters: standard: format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\" handlers: default: level: "INFO" formatter: standard class: logging.StreamHandler loggers: "": handlers: ["default"] level: INFO propagate: True """))) assert 'logging' in config def test_read_config_files(self): config_base = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'configs') locations = [ os.path.join(config_base, 'etc'), os.path.join(config_base, 'home'), ] config = bawlerd.conf.read_config_files( bawlerd.conf.build_config_location_list(locations=locations)) assert config['common']['listen_timeout'] == 40 assert 'logging' in config
import io import os from textwrap import dedent from pg_bawler import bawlerd class TestBawlerdConfig: def test_build_config_location_list(self): assert not bawlerd.conf.build_config_location_list(locations=()) user_conf = os.path.join( os.path.expanduser('~'), bawlerd.conf.DEFAULT_CONFIG_FILENAME) system_conf = os.path.join( '/etc/pg_bawler', bawlerd.conf.DEFAULT_CONFIG_FILENAME) assert user_conf in bawlerd.conf.build_config_location_list() assert system_conf in bawlerd.conf.build_config_location_list() def test__load_file(self): config = bawlerd.conf._load_file(io.StringIO(dedent("""\ logging: formatters: standard: format: \"%(asctime)s %(levelname)s] %(name)s: %(message)s\" handlers: default: level: "INFO" formatter: standard class: logging.StreamHandler loggers: "": handlers: ["default"] level: INFO propagate: True """))) assert 'logging' in config
Store the Etherpad API key as a secret. Currently, the Etherpad API key were public, with the rationale the installation is a public one, everybody can anonymously or with a name make edits, destroy pads, create new pads, etc. Nasqueron is interested to get the potential to integrate other applications with Etherpad, using groups, sessions and users objects to make pads spawned by 3rd party application private. A private API key has so been regenerated, and we now store it as a secret.
<?php require '../_includes/SecurityData.php'; /** * Gets the pads * * @return Array the pads list */ function get_pads () { $key = SecurityData::getSecret('etherpad.api.key'); $url = "http://pad.wolfplex.be/api/1.2.1/listAllPads?apikey=" . $key; $api_reply = json_decode(file_get_contents($url)); if ($api_reply->code == 0) { return $api_reply->data->padIDs; } throw new Exception("API fatal error: $api_reply->message"); } $format = array_key_exists('format', $_GET) ? $_GET['format'] : ''; switch ($format) { case "": case "json": echo json_encode(get_pads()); break; case "raw": echo implode("\n", get_pads()); break; case "txt": header("Content-Type: text/plain"); foreach (get_pads() as $pad) { echo "* $pad\n"; } break; default: die("Unknown format: $format"); } ?>
<?php /** * Gets the pads * * @return Array the pads list */ function get_pads () { //TODO: move API key in config $url = "http://pad.wolfplex.be/api/1.2.1/listAllPads?apikey=U67yKTUDzz19fEHyrAuNN4zUnKxbOJZu"; $api_reply = json_decode(file_get_contents($url)); if ($api_reply->code == 0) { return $api_reply->data->padIDs; } throw new Exception("API fatal error: $api_reply->message"); } $format = array_key_exists('format', $_GET) ? $_GET['format'] : ''; switch ($format) { case "": case "json": echo json_encode(get_pads()); break; case "raw": echo implode("\n", get_pads()); break; case "txt": header("Content-Type: text/plain"); foreach (get_pads() as $pad) { echo "* $pad\n"; } break; default: die("Unknown format: $format"); } ?>
Drop support for wordpress forum
<?php if (!defined('ABSPATH')) { exit('restricted access'); } ?> <h3 ><span><?php _e('Need Help ?', 'woo-poly-integration'); ?></span> </h3> <div class="inside"> <p> <?php _e('Need help , Want to ask for new feature ? please contact using one of the following methods', 'woo-poly-integration' ) ?> </p> <ol> <li> <a href="https://github.com/hyyan/woo-poly-integration/issues" target="_blank"> <?php _e('On Github', 'woo-poly-integration'); ?> </a> </li> <!-- <li> <a href="https://wordpress.org/support/plugin/woo-poly-integration" target="_blank"> <?php //_e('On Wordpress Support Froum', 'woo-poly-integration'); ?> </a> </li>--> <li> <a href="mailto:[email protected]" target="_blank"> <?php _e('On Email', 'woo-poly-integration'); ?> </a> </li> </ol> </div>
<?php if (!defined('ABSPATH')) { exit('restricted access'); } ?> <h3 ><span><?php _e('Need Help ?', 'woo-poly-integration'); ?></span> </h3> <div class="inside"> <p> <?php _e('Need help , Want to ask for new feature ? please contact using one of the following methods', 'woo-poly-integration' ) ?> </p> <ol> <li> <a href="https://github.com/hyyan/woo-poly-integration/issues" target="_blank"> <?php _e('On Github', 'woo-poly-integration'); ?> </a> </li> <li> <a href="https://wordpress.org/support/plugin/woo-poly-integration" target="_blank"> <?php _e('On Wordpress Support Froum', 'woo-poly-integration'); ?> </a> </li> <li> <a href="mailto:[email protected]" target="_blank"> <?php _e('On Email', 'woo-poly-integration'); ?> </a> </li> </ol> </div>
Fix lint issues with Login component
import React from 'react'; export default class Login extends React.Component { static get displayName() { return 'Login'; } render() { return ( <form> <div className="form-group" > <label htmlFor="username" >{'Name'}</label> <input className="form-control" placeholder="Please, provide a User." type="text" /> </div> <div className="form-group" > <label htmlFor="password" >{'Secret'}</label> <input className="form-control" placeholder="Also, don't forget the secret password." type="password" /> </div> <button className="btn btn-default" type="submit" >{'Submit'}</button> </form> ); } }
import React from 'react'; export default class Login extends React.Component { render() { return ( <form> <div className="form-group"> <label htmlFor="username">{'Name'}</label> <input className="form-control" placeholder="Please, provide a User." type="text" /> </div> <div className="form-group"> <label htmlFor="password">{'Secret'}</label> <input className="form-control" placeholder="Also, don't forget the secret password." type="password" /> </div> <button type="submit" className="btn btn-default">{'Submit'}</button> </form> ); } }
[client] Fix error: notifications didn't show
// npm packages import React, {PropTypes} from 'react'; import {connect} from 'react-redux'; import {push} from 'react-router-redux'; // our components import {Navbar} from '../../components'; import Footer from '../../components/footer'; const mapStateToProps = state => ({ actualPath: state.routing.locationBeforeTransitions && state.routing.locationBeforeTransitions.pathname, user: state.auth.user, token: state.auth.token, }); const mapDispatchToProps = dispatch => ({ navTo: path => dispatch(push(path)), }); class App extends React.Component { static propTypes = { token: PropTypes.string, user: PropTypes.shape({ email: PropTypes.string.isRequired, id: PropTypes.string.isRequired, login: PropTypes.string.isRequired, name: PropTypes.string.isRequired, registrationDate: PropTypes.string.isRequired, surname: PropTypes.string.isRequired, }), navTo: PropTypes.func.isRequired, }; componentWillReceiveProps(nextProps) { if (this.props.token !== nextProps.token) { if (nextProps.token) { return this.props.navTo('/'); } return this.props.navTo('/home'); } } render() { const {children, user, token} = this.props; return ( <div> <Navbar {...this.props} /> <div className="container"> {children} <Footer /> </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(App);
// npm packages import React, {PropTypes} from 'react'; import {connect} from 'react-redux'; import {push} from 'react-router-redux'; // our components import {Navbar} from '../../components'; const mapStateToProps = state => ({ actualPath: state.routing.locationBeforeTransitions && state.routing.locationBeforeTransitions.pathname, user: state.auth.user, token: state.auth.token, }); const mapDispatchToProps = dispatch => ({ navTo: path => dispatch(push(path)), }); class App extends React.Component { static propTypes = { token: PropTypes.string, user: PropTypes.shape({ email: PropTypes.string.isRequired, id: PropTypes.string.isRequired, login: PropTypes.string.isRequired, name: PropTypes.string.isRequired, registrationDate: PropTypes.string.isRequired, surname: PropTypes.string.isRequired, }), navTo: PropTypes.func.isRequired, }; componentWillReceiveProps(nextProps) { if (this.props.token !== nextProps.token) { if (nextProps.token) { return this.props.navTo('/'); } return this.props.navTo('/home'); } } render() { const {children, user, token} = this.props; return ( <div> <Navbar {...this.props} /> <div className="container"> {children} </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(App);
CRM-442: Add imap related fields to User view and edit pages - remove not needed id field
<?php namespace Oro\Bundle\ImapBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ConfigurationType extends AbstractType { const NAME = 'oro_imap_configuration'; /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('host', 'text', array('required' => true)) ->add('port', 'text', array('required' => true)) ->add( 'ssl', 'choice', array( 'choices' => array('ssl', 'tsl'), 'empty_data' => null, 'empty_value' => '', 'required' => false ) ) ->add('user', 'text', array('required' => true)) ->add('password', 'password', array('required' => true)); } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( array( 'data_class' => 'Oro\\Bundle\\ImapBundle\\Entity\\ImapEmailOrigin' ) ); } /** * {@inheritdoc} */ public function getName() { return self::NAME; } }
<?php namespace Oro\Bundle\ImapBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ConfigurationType extends AbstractType { const NAME = 'oro_imap_configuration'; /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('id', 'hidden') ->add('host', 'text', array('required' => true)) ->add('port', 'text', array('required' => true)) ->add( 'ssl', 'choice', array( 'choices' => array('ssl', 'tsl'), 'empty_data' => null, 'empty_value' => '', 'required' => false ) ) ->add('user', 'text', array('required' => true)) ->add('password', 'password', array('required' => true)); } /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults( array( 'data_class' => 'Oro\\Bundle\\ImapBundle\\Entity\\ImapEmailOrigin' ) ); } /** * {@inheritdoc} */ public function getName() { return self::NAME; } }
Include brand name when finding product
<? include '../scat.php'; $term= $_REQUEST['term']; $products= array(); if (!$term) { die_jsonp([ 'error' => "Need to supply some search terms.", 'results' => [] ]); } $products= Model::factory('Product') ->select("product.*") ->select("department.name", "department_name") ->select("department.slug", "department_slug") ->select("brand.name", "brand_name") ->select_expr('(SELECT slug FROM department AS parent WHERE department.parent_id = parent.id)', 'parent_slug') ->join('brand', array('product.brand_id', '=', 'brand.id')) ->join('department', array('product.department_id', '=', 'department.id')) ->where_raw('MATCH(product.name, product.description) AGAINST (? IN NATURAL LANGUAGE MODE)', array($term)) ->where('active', 1) ->find_array(); /* Select2 */ if ($_REQUEST['_type'] == 'query') { $data= [ 'results' => [], 'pagination' => [ 'more' => false ]]; foreach ($products as $product) { $data['results'][]= [ 'id' => $product['id'], 'text' => $product['name'] . ' / ' . $product['brand_name'] ]; } echo jsonp($data); exit; } /* Other queries */ echo jsonp($products);
<? include '../scat.php'; $term= $_REQUEST['term']; $products= array(); if (!$term) { die_jsonp([ 'error' => "Need to supply some search terms.", 'results' => [] ]); } $products= Model::factory('Product') ->select("product.*") ->select("department.name", "department_name") ->select("department.slug", "department_slug") ->select("brand.name", "brand_name") ->select_expr('(SELECT slug FROM department AS parent WHERE department.parent_id = parent.id)', 'parent_slug') ->join('brand', array('product.brand_id', '=', 'brand.id')) ->join('department', array('product.department_id', '=', 'department.id')) ->where_raw('MATCH(product.name, product.description) AGAINST (? IN NATURAL LANGUAGE MODE)', array($term)) ->where('active', 1) ->find_array(); /* Select2 */ if ($_REQUEST['_type'] == 'query') { $data= [ 'results' => [], 'pagination' => [ 'more' => false ]]; foreach ($products as $product) { $data['results'][]= [ 'id' => $product['id'], 'text' => $product['name'] ]; } echo jsonp($data); exit; } /* Other queries */ echo jsonp($products);
Create new object with default mutator
import { loop, isLoop, getEffect, getModel } from './loop'; import { batch, none } from './effects'; function optimizeBatch(effects) { switch(effects.length) { case 0: return none(); case 1: return effects[0]; default: return batch(effects); } } const defaultAccessor = (state, key) => { return state[key]; }; const defaultMutator = (state, key, value) => { return { ...state, [key]: value }; }; export function combineReducers( reducerMap, rootState = {}, accessor = defaultAccessor, mutator = defaultMutator ) { return function finalReducer(state = rootState, action) { let hasChanged = false; let effects = []; const model = Object.keys(reducerMap).reduce((model, key) => { const reducer = reducerMap[key]; const previousStateForKey = accessor(state, key); let nextStateForKey = reducer(previousStateForKey, action); if (isLoop(nextStateForKey)) { effects.push(getEffect(nextStateForKey)); nextStateForKey = getModel(nextStateForKey); } hasChanged = hasChanged || nextStateForKey !== previousStateForKey; return mutator(model, key, nextStateForKey); }, rootState); return loop( hasChanged ? model : state, optimizeBatch(effects) ); }; }
import { loop, isLoop, getEffect, getModel } from './loop'; import { batch, none } from './effects'; function optimizeBatch(effects) { switch(effects.length) { case 0: return none(); case 1: return effects[0]; default: return batch(effects); } } const defaultAccessor = (state, key) => { return state[key]; }; const defaultMutator = (state, key, value) => { state[key] = value; return state; }; export function combineReducers( reducerMap, rootState = {}, accessor = defaultAccessor, mutator = defaultMutator ) { return function finalReducer(state = rootState, action) { let hasChanged = false; let effects = []; const model = Object.keys(reducerMap).reduce((model, key) => { const reducer = reducerMap[key]; const previousStateForKey = accessor(state, key); let nextStateForKey = reducer(previousStateForKey, action); if (isLoop(nextStateForKey)) { effects.push(getEffect(nextStateForKey)); nextStateForKey = getModel(nextStateForKey); } hasChanged = hasChanged || nextStateForKey !== previousStateForKey; return mutator(model, key, nextStateForKey); }, rootState); return loop( hasChanged ? model : state, optimizeBatch(effects) ); }; }
Fix inline phone number form
# from wtforms import Form from flask.ext.babel import gettext as _ from flask.ext.wtf import Form from wtforms import SubmitField, RadioField, StringField from wtforms.ext.sqlalchemy.orm import model_form from wtforms.validators import AnyOf, Required from .constants import PHONE_NUMBER_TYPE from .models import PhoneNumber, Gateway from ..extensions import db PhoneNumberFormBase = model_form(PhoneNumber, db_session=db.session, base_class=Form, exclude=[ 'areacode', 'created_at', 'updated_at', 'person', 'station_cloud', 'station_transmitter', 'stations', ]) class PhoneNumberForm(PhoneNumberFormBase): number = StringField(_('Phone Number'), [Required()], default=" ") number_type = RadioField(_("Type"), [AnyOf([str(val) for val in PHONE_NUMBER_TYPE.keys()])], choices=[(str(val), label) for val, label in PHONE_NUMBER_TYPE.items()]) submit = SubmitField(_('Save')) GatewayFormBase = model_form(Gateway, db_session=db.session, base_class=Form, exclude=[ 'created_at', 'updated_at', ]) class GatewayForm(GatewayFormBase): name = StringField() number_top = db.Column(db.Integer) number_bottom = db.Column(db.Integer) sofia_string = StringField() extra_string = StringField() submit = SubmitField(_('Save'))
# from wtforms import Form from flask.ext.babel import gettext as _ from flask.ext.wtf import Form from wtforms import SubmitField, RadioField, StringField from wtforms.ext.sqlalchemy.orm import model_form from wtforms.validators import AnyOf, Required from .constants import PHONE_NUMBER_TYPE from .models import PhoneNumber, Gateway from ..extensions import db PhoneNumberFormBase = model_form(PhoneNumber, db_session=db.session, base_class=Form, exclude=[ 'areacode', 'created_at', 'updated_at', 'person', 'station_cloud', 'station_transmitter', 'stations', ]) class PhoneNumberForm(PhoneNumberFormBase): number = StringField(_('Phone Number'), [Required], default=" ") number_type = RadioField(_("Type"), [AnyOf([str(val) for val in PHONE_NUMBER_TYPE.keys()])], choices=[(str(val), label) for val, label in PHONE_NUMBER_TYPE.items()]) submit = SubmitField(_('Save')) GatewayFormBase = model_form(Gateway, db_session=db.session, base_class=Form, exclude=[ 'created_at', 'updated_at', ]) class GatewayForm(GatewayFormBase): name = StringField() number_top = db.Column(db.Integer) number_bottom = db.Column(db.Integer) sofia_string = StringField() extra_string = StringField() submit = SubmitField(_('Save'))
Add version check for importing django.contrib.postgres.fields.ArrayField
from __future__ import unicode_literals from django import VERSION from django.db import migrations, models if VERSION >= (1, 8): from django.contrib.postgres.fields import ArrayField chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None) else: chapters_field = models.Field() # Dummy field class PostgresOnlyCreateModel(migrations.CreateModel): def database_forwards(self, app_label, schema_editor, from_state, to_state): if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"): super(PostgresOnlyCreateModel, self).database_forwards(app_label, schema_editor, from_state, to_state) def database_backwards(self, app_label, schema_editor, from_state, to_state): if VERSION >= (1, 8) and schema_editor.connection.vendor.startswith("postgres"): super(PostgresOnlyCreateModel, self).database_backwards(app_label, schema_editor, from_state, to_state) class Migration(migrations.Migration): dependencies = [ ('core', '0003_withfloatfield'), ] operations = [ PostgresOnlyCreateModel( name='BookWithChapters', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100, verbose_name='Book name')), ('chapters', chapters_field) ], ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-06-09 10:26 from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class PostgresOnlyCreateModel(migrations.CreateModel): def database_forwards(self, app_label, schema_editor, from_state, to_state): if schema_editor.connection.vendor.startswith("postgres"): super(PostgresOnlyCreateModel, self).database_forwards(app_label, schema_editor, from_state, to_state) def database_backwards(self, app_label, schema_editor, from_state, to_state): if schema_editor.connection.vendor.startswith("postgres"): super(PostgresOnlyCreateModel, self).database_backwards(app_label, schema_editor, from_state, to_state) class Migration(migrations.Migration): dependencies = [ ('core', '0003_withfloatfield'), ] operations = [ PostgresOnlyCreateModel( name='BookWithChapters', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100, verbose_name='Book name')), ('chapters', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=100), default=list, size=None)), ], ), ]
Modify CSS Exclusions to CSS Shapes, since we split up the specification. Update references.
/*! { "name": "CSS Shapes", "property": "shapes", "tags": ["css"], "notes": [{ "name": "CSS Shapes W3C specification", "href": "http://www.w3.org/TR/css-shapes" },{ "name": "Examples from Adobe", "href": "http://html.adobe.com/webplatform/layout/shapes" }, { "name": "Samples showcasing uses of Shapes", "href": "http://codepen.io/collection/qFesk" }] } !*/ define(['Modernizr', 'createElement', 'docElement', 'prefixed', 'testStyles'], function( Modernizr, createElement, docElement, prefixed, testStyles ) { // Separate test for CSS shapes as WebKit has just implemented this alone Modernizr.addTest('shapes', function () { var prefixedProperty = prefixed('shapeInside'); if (!prefixedProperty) return false; var shapeInsideProperty = prefixedProperty.replace(/([A-Z])/g, function (str, m1) { return '-' + m1.toLowerCase(); }).replace(/^ms-/, '-ms-'); return testStyles('#modernizr { ' + shapeInsideProperty + ':rectangle(0,0,0,0) }', function (elem) { // Check against computed value var styleObj = window.getComputedStyle ? getComputedStyle(elem, null) : elem.currentStyle; return styleObj[prefixed('shapeInside', docElement.style, false)] == 'rectangle(0px, 0px, 0px, 0px)'; }); }); });
/*! { "name": "CSS Shapes", "property": "shapes", "tags": ["css"], "notes": [{ "name": "CSS Shapes W3C specification", "href": "http://www.w3.org/TR/css-shapes" },{ "name": "Examples from Adobe", "href": "http://html.adobe.com/webplatform/layout/shapes" }, { "name": "Samples showcasing uses of Exclusions and Shapes", "href": "http://codepen.io/collection/qFesk" }] } !*/ define(['Modernizr', 'createElement', 'docElement', 'prefixed', 'testStyles'], function( Modernizr, createElement, docElement, prefixed, testStyles ) { // Separate test for CSS shapes as WebKit has just implemented this alone Modernizr.addTest('shapes', function () { var prefixedProperty = prefixed('shapeInside'); if (!prefixedProperty) return false; var shapeInsideProperty = prefixedProperty.replace(/([A-Z])/g, function (str, m1) { return '-' + m1.toLowerCase(); }).replace(/^ms-/, '-ms-'); return testStyles('#modernizr { ' + shapeInsideProperty + ':rectangle(0,0,0,0) }', function (elem) { // Check against computed value var styleObj = window.getComputedStyle ? getComputedStyle(elem, null) : elem.currentStyle; return styleObj[prefixed('shapeInside', docElement.style, false)] == 'rectangle(0px, 0px, 0px, 0px)'; }); }); });
Add trailing slash to forward and reverse url resolutions
# coding: utf-8 from django.utils.module_loading import import_string def _load(module): return import_string(module) if isinstance(module, str) else module class view(): def __init__(self, model, view, slug_field): self.model = _load(model) self.view = _load(view) self.slug_field = slug_field # define 'get_path' method for model self.model.get_path = lambda instance: '/'.join([getattr(item, slug_field) for item in instance.get_ancestors(include_self=True)]) + '/' def __call__(self, *args, **kwargs): if 'path' not in kwargs: raise ValueError('Path was not captured! Please capture it in your urlconf. Example: url(r\'^gallery/(?P<path>.*)\', mptt_urls.view(...), ...)') instance = None # actual instance the path is pointing to (None by default) path = kwargs['path'] instance_slug = path.split('/')[-2] # slug of the instance if instance_slug: candidates = self.model.objects.filter(**{self.slug_field: instance_slug}) # candidates to be the instance for candidate in candidates: # here we compare each candidate's path to the path passed to this view if candidate.get_path() == path: instance = candidate break kwargs['instance'] = instance return self.view(*args, **kwargs)
# coding: utf-8 from django.utils.module_loading import import_string def _load(module): return import_string(module) if isinstance(module, str) else module class view(): def __init__(self, model, view, slug_field): self.model = _load(model) self.view = _load(view) self.slug_field = slug_field # define 'get_path' method for model self.model.get_path = lambda instance: '/'.join([getattr(item, slug_field) for item in instance.get_ancestors(include_self=True)]) def __call__(self, *args, **kwargs): if 'path' not in kwargs: raise ValueError('Path was not captured! Please capture it in your urlconf. Example: url(r\'^gallery/(?P<path>.*)\', mptt_urls.view(...), ...)') instance = None # actual instance the path is pointing to (None by default) path = kwargs['path'] instance_slug = path.split('/')[-1] # slug of the instance if instance_slug: candidates = self.model.objects.filter(**{self.slug_field: instance_slug}) # candidates to be the instance for candidate in candidates: # here we compare each candidate's path to the path passed to this view if candidate.get_path() == path: instance = candidate break kwargs['instance'] = instance return self.view(*args, **kwargs)
Load docopt lazily (so that setup.py works)
"""Dispatch from command-line arguments to functions.""" import re from collections import OrderedDict __all__ = ('dispatch', 'DispatchError') __author__ = 'Vladimir Keleshev <[email protected]>' __version__ = '0.0.0' __license__ = 'MIT' __keywords__ = 'docopt dispatch function adapter kwargs' __url__ = 'https://github.com/halst/docopt-dispatch' class DispatchError(Exception): pass class Dispatch(object): def __init__(self): self._functions = OrderedDict() def on(self, argument): def decorator(function): self._functions[argument] = function return function return decorator def __call__(self, *args, **kwargs): from docopt import docopt arguments = docopt(*args, **kwargs) for argument, function in self._functions.items(): if arguments[argument]: function(**self._kwargify(arguments)) return raise DispatchError('None of dispatch conditions (%s) is triggered' % ', '.join(self._functions.keys())) @staticmethod def _kwargify(arguments): kwargify = lambda string: re.sub('\W', '_', string).strip('_') return dict((kwargify(key), value) for key, value in arguments.items()) dispatch = Dispatch()
"""Dispatch from command-line arguments to functions.""" import re from collections import OrderedDict from docopt import docopt __all__ = ('dispatch', 'DispatchError') __author__ = 'Vladimir Keleshev <[email protected]>' __version__ = '0.0.0' __license__ = 'MIT' __keywords__ = 'docopt dispatch function adapter kwargs' __url__ = 'https://github.com/halst/docopt-dispatch' class DispatchError(Exception): pass class Dispatch(object): def __init__(self): self._functions = OrderedDict() def on(self, argument): def decorator(function): self._functions[argument] = function return function return decorator def __call__(self, *args, **kwargs): arguments = docopt(*args, **kwargs) for argument, function in self._functions.items(): if arguments[argument]: function(**self._kwargify(arguments)) return raise DispatchError('None of dispatch conditions (%s) is triggered' % ', '.join(self._functions.keys())) @staticmethod def _kwargify(arguments): kwargify = lambda string: re.sub('\W', '_', string).strip('_') return dict((kwargify(key), value) for key, value in arguments.items()) dispatch = Dispatch()
Add shutdown callback support to Action
from bot.api.api import Api from bot.multithreading.scheduler import SchedulerApi from bot.storage import Config, State, Cache class Action: def __init__(self): pass def get_name(self): return self.__class__.__name__ def setup(self, api: Api, config: Config, state: State, cache: Cache, scheduler: SchedulerApi): self.api = api self.config = config self.state = state self.cache = cache self.scheduler = scheduler self.post_setup() def post_setup(self): pass def process(self, event): pass def pre_shutdown(self): pass def shutdown(self): self.pre_shutdown() class ActionGroup(Action): def __init__(self, *actions): super().__init__() self.actions = list(actions) def add(self, *actions): self.actions.extend(actions) def setup(self, *args): super().setup(*args) self.for_each(lambda action: action.setup(*args)) def process(self, event): self.for_each(lambda action: action.process(event._copy())) def shutdown(self): self.for_each(lambda action: action.shutdown()) super().shutdown() def for_each(self, func): for action in self.actions: func(action) class IntermediateAction(ActionGroup): def __init__(self): super().__init__() def then(self, *next_actions): self.add(*next_actions) return self def _continue(self, event): super().process(event)
from bot.api.api import Api from bot.multithreading.scheduler import SchedulerApi from bot.storage import Config, State, Cache class Action: def __init__(self): pass def get_name(self): return self.__class__.__name__ def setup(self, api: Api, config: Config, state: State, cache: Cache, scheduler: SchedulerApi): self.api = api self.config = config self.state = state self.cache = cache self.scheduler = scheduler self.post_setup() def post_setup(self): pass def process(self, event): pass class ActionGroup(Action): def __init__(self, *actions): super().__init__() self.actions = list(actions) def add(self, *actions): self.actions.extend(actions) def setup(self, *args): super().setup(*args) self.for_each(lambda action: action.setup(*args)) def process(self, event): self.for_each(lambda action: action.process(event._copy())) def for_each(self, func): for action in self.actions: func(action) class IntermediateAction(ActionGroup): def __init__(self): super().__init__() def then(self, *next_actions): self.add(*next_actions) return self def _continue(self, event): super().process(event)
Update the docs on twimport and imwiki to indicate that imwiki is deprecated.
""" TiddlyWebWiki-specific twanager commands """ from tiddlyweb.store import Store from tiddlyweb.manage import make_command, usage from tiddlywebwiki.tiddlywiki import import_wiki_file from tiddlywebwiki.importer import import_list def init(config): @make_command() def update(args): """Update all instance_tiddlers in the current instance.""" from tiddlywebplugins.instancer import Instance instance = Instance('.', config) instance.update_store() @make_command() def twimport(args): """Import one or more plugins, tiddlers or recipes in Cook format or a wiki: <bag> <URI>""" bag = args[0] urls = args[1:] if not bag or not urls: raise IndexError('missing args') import_list(bag, urls, config) @make_command() def imwiki(args): """Import tiddlers from a Tiddlywiki document into a bag, deprecated in favor of twimport: <bag> <filename>""" # XXX to be removed soon, deprecated. store = _store() try: bag_name, filename = args[0:2] import_wiki_file(store, filename, bag_name) except IndexError, exc: usage("index error: %s" % exc) except ValueError, exc: usage("value error: %s" % exc) def _store(): """Get our Store from config.""" return Store(config['server_store'][0], config['server_store'][1], environ={'tiddlyweb.config': config})
""" TiddlyWebWiki-specific twanager commands """ from tiddlyweb.store import Store from tiddlyweb.manage import make_command, usage from tiddlywebwiki.tiddlywiki import import_wiki_file from tiddlywebwiki.importer import import_list def init(config): @make_command() def update(args): """Update all instance_tiddlers in the current instance.""" from tiddlywebplugins.instancer import Instance instance = Instance('.', config) instance.update_store() @make_command() def twimport(args): """Import one or more plugins, tiddlers or recipes in Cook format: <bag> <URI>""" bag = args[0] urls = args[1:] if not bag or not urls: raise IndexError('missing args') import_list(bag, urls, config) @make_command() def imwiki(args): """Import tiddlers from a Tiddlywiki document into a bag: <bag> <filename>""" store = _store() try: bag_name, filename = args[0:2] import_wiki_file(store, filename, bag_name) except IndexError, exc: usage("index error: %s" % exc) except ValueError, exc: usage("value error: %s" % exc) def _store(): """Get our Store from config.""" return Store(config['server_store'][0], config['server_store'][1], environ={'tiddlyweb.config': config})
Use token and not data
////////////////////////////////////// // User buys one ticket for himself // ////////////////////////////////////// 'use strict'; var Promise = require('bluebird'); module.exports = function (db, config) { var logger = require('../../lib/log')(config); var rest = require('../../lib/rest')(config, logger); return function (req, res, next) { db.Token.find({ sherlocksToken: req.body.token }).then(function (token) { return new Promise(function (resolve, reject) { if (!token) { return reject('no token to ticket'); } token.destroy(); resolve(token.ticket); }); }).then(function (ticketId) { return db.Ticket.find(ticketId); }).then(function (ticket) { ticket.paid = true; ticket.paid_at = new Date(); // Save ticket id for later req.ticketId = ticket.id; req.sherlocksToken = req.body.token; return ticket.save(); }).then(function (ticket) { logger.info('Paid with sherlocks'); if (ticket.username !== 0) { res.locals.forcedUsername = ticket.username; res.locals.shouldNotCheckPassword = true; return next(); } res.redirect('/#/ticketBought'); }).catch(function (err) { Error.emit(res, 500, '500 - Server error', err); logger.error(err); }); }; };
////////////////////////////////////// // User buys one ticket for himself // ////////////////////////////////////// 'use strict'; var Promise = require('bluebird'); module.exports = function (db, config) { var logger = require('../../lib/log')(config); var rest = require('../../lib/rest')(config, logger); return function (req, res, next) { db.Token.find({ sherlocksToken: req.body.data }).then(function (token) { return new Promise(function (resolve, reject) { if (!token) { return reject('no token to ticket'); } token.destroy(); resolve(token.ticket); }); }).then(function (ticketId) { return db.Ticket.find(ticketId); }).then(function (ticket) { ticket.paid = true; ticket.paid_at = new Date(); return ticket.save(); }).then(function (ticket) { logger.info('Paid with sherlocks'); if (ticket.username !== 0) { res.locals.forcedUsername = ticket.username; res.locals.shouldNotCheckPassword = true; return next(); } res.redirect('/#/ticketBought'); }).catch(function (err) { Error.emit(res, 500, '500 - Server error', err); logger.error(err); }); }; };
Use grunt.util.spawn to execute the grunt task. This makes sure grunt configuration set via grunt.option is properly read again
var grunt = require('grunt'); var makeOptions = function (options) { var baseOptions = { base: null, prefix: 'grunt-', verbose: false }; if (options) { for (var key in options) { if (options.hasOwnProperty(key)) { baseOptions[key] = options[key]; } } } return baseOptions; }; module.exports = function (gulp, options) { var tasks = getTasks(options); for (var name in tasks) { if (tasks.hasOwnProperty(name)) { var fn = tasks[name]; gulp.task(name, fn); } } }; var getTasks = module.exports.tasks = function (options) { var opt = makeOptions(options); if (opt.base) { grunt.file.setBase(opt.base); } grunt.task.init([]); var gruntTasks = grunt.task._tasks, finalTasks = {}; for (var name in gruntTasks) { if (gruntTasks.hasOwnProperty(name)) { (function (name) { finalTasks[opt.prefix + name] = function (cb) { if (opt.verbose) { console.log('[grunt-gulp] Running Grunt "' + name + '" task...'); } grunt.util.spawn({ cmd: 'grunt', args: [name, '--force'] }, function() { if (opt.verbose) { grunt.log.ok('[grunt-gulp] Done running Grunt "' + name + '" task.'); } cb(); }); }; })(name); } } return finalTasks; };
var grunt = require('grunt'); var makeOptions = function (options) { var baseOptions = { base: null, prefix: 'grunt-', verbose: false }; if (options) { for (var key in options) { if (options.hasOwnProperty(key)) { baseOptions[key] = options[key]; } } } return baseOptions; }; module.exports = function (gulp, options) { var tasks = getTasks(options); for (var name in tasks) { if (tasks.hasOwnProperty(name)) { var fn = tasks[name]; gulp.task(name, fn); } } }; var getTasks = module.exports.tasks = function (options) { var opt = makeOptions(options); if (opt.base) { grunt.file.setBase(opt.base); } grunt.task.init([]); var gruntTasks = grunt.task._tasks, finalTasks = {}; for (var name in gruntTasks) { if (gruntTasks.hasOwnProperty(name)) { (function (name) { finalTasks[opt.prefix + name] = function (cb) { if (opt.verbose) { console.log('[grunt-gulp] Running Grunt "' + name + '" task...'); } grunt.tasks([name], { force: true }, function () { if (opt.verbose) { grunt.log.ok('[grunt-gulp] Done running Grunt "' + name + '" task.'); } cb(); }); }; })(name); } } return finalTasks; };
Fix new user command password hashing
<?php namespace Suitcoda\Console\Commands; use Illuminate\Console\Command; class NewUserCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'user:new-superuser {username} {name} {email} {password}'; /** * The console command description. * * @var string */ protected $description = 'Create New User.'; /** * Create a new command instance. */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $username = $this->argument('username'); $name = $this->argument('name'); $email = $this->argument('email'); $password = $this->argument('password'); $adminClass = \Config::get('auth.model'); $admin = new $adminClass(); $admin->username = $username; $admin->name = $name; $admin->email = $email; $admin->password = bcrypt($password); $admin->is_admin = true; $admin->is_active = true; if ($admin->save()) { $this->info('New Admin has been successfully created!!'); } } }
<?php namespace Suitcoda\Console\Commands; use Illuminate\Console\Command; class NewUserCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'user:new-superuser {username} {name} {email} {password}'; /** * The console command description. * * @var string */ protected $description = 'Create New User.'; /** * Create a new command instance. */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $username = $this->argument('username'); $name = $this->argument('name'); $email = $this->argument('email'); $password = $this->argument('password'); $adminClass = \Config::get('auth.model'); $admin = new $adminClass(); $admin->username = $username; $admin->name = $name; $admin->email = $email; $admin->password = $password; $admin->is_admin = true; $admin->is_active = true; if ($admin->save()) { $this->info('New Admin has been successfully created!!'); } } }
Remove expected file override in test
package com.box.l10n.mojito.cli.command; import com.box.l10n.mojito.cli.CLITestBase; import org.junit.Test; public class SimpleFileEditorCommandTest extends CLITestBase { @Test public void jsonIndent() { getL10nJCommander().run("simple-file-editor", "-i", getInputResourcesTestDir().getAbsolutePath(), "-o", getTargetTestDir().getAbsolutePath(), "--json-indent"); checkExpectedGeneratedResources(); } @Test public void poRemoveUsages() { getL10nJCommander().run("simple-file-editor", "-i", getInputResourcesTestDir().getAbsolutePath(), "-o", getTargetTestDir().getAbsolutePath(), "--po-remove-usages" ); checkExpectedGeneratedResources(); } @Test public void macStringsRemoveUsages() { getL10nJCommander().run("simple-file-editor", "-i", getInputResourcesTestDir().getAbsolutePath(), "-o", getTargetTestDir().getAbsolutePath(), "--macstrings-remove-usages" ); checkExpectedGeneratedResources(); } }
package com.box.l10n.mojito.cli.command; import com.box.l10n.mojito.cli.CLITestBase; import org.junit.Test; public class SimpleFileEditorCommandTest extends CLITestBase { @Test public void jsonIndent() { getL10nJCommander().run("simple-file-editor", "-i", getInputResourcesTestDir().getAbsolutePath(), "-o", getTargetTestDir().getAbsolutePath(), "--json-indent"); checkExpectedGeneratedResources(); } @Test public void poRemoveUsages() { getL10nJCommander().run("simple-file-editor", "-i", getInputResourcesTestDir().getAbsolutePath(), "-o", getTargetTestDir().getAbsolutePath(), "--po-remove-usages" ); checkExpectedGeneratedResources(); } @Test public void macStringsRemoveUsages() { System.setProperty("overrideExpectedTestFiles", "true"); getL10nJCommander().run("simple-file-editor", "-i", getInputResourcesTestDir().getAbsolutePath(), "-o", getTargetTestDir().getAbsolutePath(), "--macstrings-remove-usages" ); checkExpectedGeneratedResources(); } }
Fix link headers on the example
'use strict'; const url = require('url'); module.exports = (fragmentName, fragmentUrl) => (request, response) => { const pathname = url.parse(request.url).pathname; switch (pathname) { case '/fragment.js': // serve fragment's JavaScript response.writeHead(200, {'Content-Type': 'application/javascript'}); response.end(` define (['word'], function (word) { return function initFragment (element) { element.className += ' fragment-${fragmentName}-initialised'; element.innerHTML += word; }; }); `); break; case '/fragment.css': // serve fragment's CSS response.writeHead(200, {'Content-Type': 'text/css'}); response.end(` .fragment-${fragmentName} { padding: 30px; margin: 10px; text-align: center; } .fragment-${fragmentName}-initialised { background-color: lightgrey; } `); default: // serve fragment's body response.writeHead(200, { 'Link': `<${fragmentUrl}/fragment.css>; rel="stylesheet",` + `<${fragmentUrl}/fragment.js>; rel="fragment-script"`, 'Content-Type': 'text/html' }); response.end(` <div class="fragment-${fragmentName}"> Fragment ${fragmentName} </div> `); } };
'use strict'; const url = require('url'); module.exports = (fragmentName, fragmentUrl) => (request, response) => { const pathname = url.parse(request.url).pathname; switch (pathname) { case '/fragment.js': // serve fragment's JavaScript response.writeHead(200, {'Content-Type': 'application/javascript'}); response.end(` define (['word'], function (word) { return function initFragment (element) { element.className += ' fragment-${fragmentName}-initialised'; element.innerHTML += word; }; }); `); break; case '/fragment.css': // serve fragment's CSS response.writeHead(200, {'Content-Type': 'text/css'}); response.end(` .fragment-${fragmentName} { padding: 30px; margin: 10px; text-align: center; } .fragment-${fragmentName}-initialised { background-color: lightgrey; } `); default: // serve fragment's body response.writeHead(200, { 'Link': `<${fragmentUrl}/fragment.css>; rel="stylesheet", <${fragmentUrl}/fragment.js>; rel="fragment-script"`, 'Content-Type': 'text/html' }); response.end(` <div class="fragment-${fragmentName}"> Fragment ${fragmentName} </div> `); } };
Fix gemm calls in Softmax
from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'softmax' @check.arg(1, has_shape(('nB', 'nI'))) def predict(self, input__BI): output__BO = self.ops.affine(self.W, self.b, input__BI) output__BO = self.ops.softmax(output__BO, inplace=False) return output__BO @check.arg(1, has_shape(('nB', 'nI'))) def begin_update(self, input__BI, drop=0.): output__BO = self.predict(input__BI) @check.arg(0, has_shape(('nB', 'nO'))) def finish_update(grad__BO, sgd=None): self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True) self.d_b += grad__BO.sum(axis=0) grad__BI = self.ops.gemm(grad__BO, self.W) if sgd is not None: sgd(self._mem.weights, self._mem.gradient, key=self.id) return grad__BI return output__BO, finish_update
from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'softmax' @check.arg(1, has_shape(('nB', 'nI'))) def predict(self, input__BI): output__BO = self.ops.affine(self.W, self.b, input__BI) output__BO = self.ops.softmax(output__BO, inplace=False) return output__BO @check.arg(1, has_shape(('nB', 'nI'))) def begin_update(self, input__BI, drop=0.): output__BO = self.predict(input__BI) @check.arg(0, has_shape(('nB', 'nO'))) def finish_update(grad__BO, sgd=None): self.d_W += self.ops.batch_outer(grad__BO, input__BI) self.d_b += grad__BO.sum(axis=0) grad__BI = self.ops.dot(grad__BO, self.W) if sgd is not None: sgd(self._mem.weights, self._mem.gradient, key=self.id) return grad__BI return output__BO, finish_update
Add logic to install for all installers
<?php namespace BudgeIt\ComposerBuilder; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; class Runner { /** * @var Composer */ private $composer; /** * @var IOInterface */ private $io; /** * @var InstallerInterface[] */ private $installers = []; /** * @var BuildToolInterface[] */ private $buildTools = []; /** * Runner constructor. */ public function __construct(Composer $composer, IOInterface $io) { $this->composer = $composer; $this->io = $io; } /** * Register a new installer object * * @param InstallerInterface $installer */ public function registerInstaller(InstallerInterface $installer) { $this->installers[$installer->getName()] = $installer; } /** * Register a new build tool object * * @param BuildToolInterface $buildTool */ public function registerBuildTool(BuildToolInterface $buildTool) { $this->buildTools[$buildTool->getName()] = $buildTool; } /** * Run the installers for a package * * @param PackageInterface $package */ public function runInstallers(PackageInterface $package) { foreach ($this->installers as $installer) { if ($installer->supports($package)) { $installer->install($package); } } } /** * Run the build tools for a package * * @param PackageInterface $package */ public function runBuildTools(PackageInterface $package) { } }
<?php namespace BudgeIt\ComposerBuilder; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; class Runner { /** * @var Composer */ private $composer; /** * @var IOInterface */ private $io; /** * @var InstallerInterface[] */ private $installers = []; /** * @var BuildToolInterface[] */ private $buildTools = []; /** * Runner constructor. */ public function __construct(Composer $composer, IOInterface $io) { $this->composer = $composer; $this->io = $io; } /** * Register a new installer object * * @param InstallerInterface $installer */ public function registerInstaller(InstallerInterface $installer) { $this->installers[$installer->getName()] = $installer; } /** * Register a new build tool object * * @param BuildToolInterface $buildTool */ public function registerBuildTool(BuildToolInterface $buildTool) { $this->buildTools[$buildTool->getName()] = $buildTool; } /** * Run the installers for a package * * @param PackageInterface $package */ public function runInstallers(PackageInterface $package) { } /** * Run the build tools for a package * * @param PackageInterface $package */ public function runBuildTools(PackageInterface $package) { } }
Remove tagName and class from PillChoiceView
// qgr-cntrl-pills define(function (require) { var $ = require('jquery'); var _ = require('underscore'); var Backbone = require('backbone'); var Handlebars = require('handlebars'); var pills_tmpl = require('text!tmpl/pills.html'); var PillChoice = Backbone.Model.extend({ // Has attr choice_val initialize: function() { this.col = options.col; }, get_subtree: function() { return { eq: [ this.col, c.get('choice_val'); ] }; } }); var PillChoiceView = Backbone.View.extend({ // Represent an individual checkbox with a view. tmpl: Handlebars.compile(pills_tmpl), events: { 'click li': 'set_choice', 'click': 'clicked', }, initialize: function(options) { // Initialize with a choice model in the options hash. _.bindAll(this, 'render', 'set_choice') this.choices = this.options.choices; }, render: function() { var render_content = this.tmpl({ choice: this.choices }) this.$el.html(render_content); return this }, set_choice: function(e) { console.log(e); }, clicked: function(e) { e.stopImmediatePropagation(); } }); // Return exports. return { PillChoice: PillChoice, PillChoiceView: PillChoiceView, }; });
// qgr-cntrl-pills define(function (require) { var $ = require('jquery'); var _ = require('underscore'); var Backbone = require('backbone'); var Handlebars = require('handlebars'); var pills_tmpl = require('text!tmpl/pills.html'); var PillChoice = Backbone.Model.extend({ // Has attr choice_val initialize: function() { this.col = options.col; } get_subtree: function() { return { eq: [ this.col, c.get('choice_val'); ] }; } }); var PillChoiceView = Backbone.View.extend({ // Represent an individual checkbox with a view. tagName: 'label', class: 'checkbox', tmpl: Handlebars.compile(pills_tmpl), events: { 'click li': 'set_choice', 'click': 'clicked', }, initialize: function(options) { // Initialize with a choice model in the options hash. _.bindAll(this, 'render', 'set_choice') this.choices = this.options.choices; }, render: function() { var render_content = this.tmpl({ choice: this.choices }) this.$el.html(render_content); return this }, set_choice: function(e) { console.log(e); }, clicked: function(e) { e.stopImmediatePropagation(); } }); // Return exports. return { PillChoice: PillChoice, PillChoiceView: PillChoiceView, }; });
Rewrite Navigation bar as a stateless function
import React from 'react'; import { Link } from 'react-router'; import { Nav, Navbar, NavItem } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; const MENU_ITEMS = [ { link: '/home', title: 'Home' }, { link: '/current', title: 'Current' }, { link: '/recent', title: 'Recent' }, { link: '/history', title: 'History' }, { link: '/info', title: 'Info' }, ]; const Navigation = function (props) { return ( <Navbar staticTop componentClass="header" role="banner"> <Navbar.Header> <Navbar.Brand> <Link to="/" className="navbar-brand">Υπερίων</Link> </Navbar.Brand> </Navbar.Header> <Nav> { MENU_ITEMS.map((item) => ( <LinkContainer to={ { pathname: item.link } } key={ item.title } > <NavItem className={ props.activePage === item.link ? 'active' : '' } > { item.title } </NavItem> </LinkContainer>)) } </Nav> </Navbar> ); }; Navigation.propTypes = { activePage: React.PropTypes.string.isRequired, }; export default Navigation;
import React from 'react'; import { Link } from 'react-router'; import { Nav, Navbar, NavItem } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; const NAV_LINKS = { home: { link: '/home', title: 'Home' }, current: { link: '/current', title: 'Current' }, recent: { link: '/recent', title: 'Recent' }, history: { link: '/history', title: 'History' }, info: { link: '/info', title: 'Info' }, }; class Navigation extends React.Component { renderNavItem(linkName) { const link = NAV_LINKS[linkName]; return ( <LinkContainer to={ { pathname: link.link } } key={ linkName }> <NavItem className={ this.props.activePage === linkName ? 'active' : '' } > { link.title } </NavItem> </LinkContainer> ); } render() { const brand = <Link to="/" className="navbar-brand">Υπερίων</Link>; const links = Object.keys(NAV_LINKS).map((i) => this.renderNavItem(i)); return ( <Navbar staticTop componentClass="header" role="banner"> <Navbar.Header> <Navbar.Brand>{ brand }</Navbar.Brand> </Navbar.Header> <Nav> { links } </Nav> </Navbar> ); } } Navigation.propTypes = { activePage: React.PropTypes.string.isRequired, }; export default Navigation;
Modules(rooms): Remove unique constraint on configurations subdocuments
'use strict'; /** * Module dependencies */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Room Schema */ var RoomSchema = new Schema({ code: { type: String, required: 'Please fill in the code of the room.', trim: true, unique: true }, name: { type: String, trim: true }, nbseats: { type: Number, required: 'Please fill in the number of seats of the room.' }, pictures: { type: Boolean, default: false }, map: { type: Schema.Types.Mixed, default: null }, configurations: { type: [new Schema({ name: { type: String, default: 'Default configuration' }, nbseries: { type: Number, default: 1 }, seats: { type: [new Schema({ seat: { type: Number, default: 0 }, serie: { type: Number, default: 0 } }, { id: false, _id: false })], default: [] } }, { id: false, _id: false })], default: [] }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Room', RoomSchema);
'use strict'; /** * Module dependencies */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Room Schema */ var RoomSchema = new Schema({ code: { type: String, required: 'Please fill in the code of the room.', trim: true, unique: true }, name: { type: String, trim: true }, nbseats: { type: Number, required: 'Please fill in the number of seats of the room.' }, pictures: { type: Boolean, default: false }, map: { type: Schema.Types.Mixed, default: null }, configurations: { type: [new Schema({ name: { type: String, unique: true }, nbseries: { type: Number, default: 1 }, seats: { type: [new Schema({ seat: { type: Number, default: 0 }, serie: { type: Number, default: 0 } }, { id: false, _id: false })], default: [] } }, { id: false, _id: false })], default: [] }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Room', RoomSchema);
Fix typo in package description
import os import shutil from setuptools import setup, find_packages, Command import oscrypto class CleanCommand(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): folder = os.path.dirname(os.path.abspath(__file__)) for sub_folder in ['build', 'dist', 'oscrypto.egg-info']: full_path = os.path.join(folder, sub_folder) if os.path.exists(full_path): shutil.rmtree(full_path) setup( name='oscrypto', version=oscrypto.__version__, description='Cryptographic services provided by the operating system, including key generation, encryption, decryption, signing, verifying and key derivation', long_description='Docs for this project are maintained at https://github.com/wbond/oscrypto#readme.', url='https://github.com/wbond/oscrypto', author='wbond', author_email='[email protected]', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='crypto', install_requires=['asn1crypto'], packages=find_packages(exclude=['tests*', 'dev*']), cmdclass={ 'clean': CleanCommand, } )
import os import shutil from setuptools import setup, find_packages, Command import oscrypto class CleanCommand(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): folder = os.path.dirname(os.path.abspath(__file__)) for sub_folder in ['build', 'dist', 'oscrypto.egg-info']: full_path = os.path.join(folder, sub_folder) if os.path.exists(full_path): shutil.rmtree(full_path) setup( name='oscrypto', version=oscrypto.__version__, description='Crytographic services provided by the operating system, including key generation, encryption, decryption, signing, verifying and key derivation', long_description='Docs for this project are maintained at https://github.com/wbond/oscrypto#readme.', url='https://github.com/wbond/oscrypto', author='wbond', author_email='[email protected]', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='crypto', install_requires=['asn1crypto'], packages=find_packages(exclude=['tests*', 'dev*']), cmdclass={ 'clean': CleanCommand, } )
Enable deleting the search query from the box to clear it
/** * * SearchInput * */ import React from 'react'; import FontAwesome from 'react-fontawesome'; import { Button, Form, FormGroup, FormControl } from 'react-bootstrap'; import { withClientState } from '../../components/Apollo/LocalStateDecorator' class SearchInput extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.onSearchChange = this.onSearchChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } onSearchChange(e) { this.query = e.target.value; } onSubmit(e) { e.preventDefault(); let searchQuery = this.query if (searchQuery == null && searchQuery == undefined) { searchQuery = this.props.clientState.searchQuery } this.props.updateClientState({ searchQuery }) } render() { return ( <Form inline onSubmit={this.onSubmit} className="searchInput"> <FormGroup controlId="formInlineEmail"> <FormControl style={{ width: '80%' }} type="text" defaultValue={this.props.clientState && this.props.clientState.searchQuery} placeholder={(this.props.clientState && this.props.clientState.searchQuery) || 'search...'} onChange={this.onSearchChange} /> <Button type="submit"> <FontAwesome name="search" /> </Button> </FormGroup> </Form> ) } } export default withClientState(SearchInput);
/** * * SearchInput * */ import React from 'react'; import FontAwesome from 'react-fontawesome'; import { Button, Form, FormGroup, FormControl } from 'react-bootstrap'; import { withClientState } from '../../components/Apollo/LocalStateDecorator' class SearchInput extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.onSearchChange = this.onSearchChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } onSearchChange(e) { this.query = e.target.value; } onSubmit(e) { e.preventDefault(); this.props.updateClientState({ searchQuery: this.query || this.props.clientState.searchQuery }) } render() { return ( <Form inline onSubmit={this.onSubmit} className="searchInput"> <FormGroup controlId="formInlineEmail"> <FormControl style={{ width: '80%' }} type="text" defaultValue={this.props.clientState && this.props.clientState.searchQuery} placeholder={(this.props.clientState && this.props.clientState.searchQuery) || 'search...'} onChange={this.onSearchChange} /> <Button type="submit"> <FontAwesome name="search" /> </Button> </FormGroup> </Form> ) } } export default withClientState(SearchInput);
Fix for some error messages that were split into several messages The exception handler expects the error to be a list on line 33. In my case they were a string, which lead to the split of the string into multiple errors containing one character
from django.utils import encoding from django.utils.translation import ugettext_lazy as _ from rest_framework import status from rest_framework.exceptions import APIException from rest_framework.views import exception_handler as drf_exception_handler from rest_framework_json_api.utils import format_value def exception_handler(exc, context): response = drf_exception_handler(exc, context) errors = [] # handle generic errors. ValidationError('test') in a view for example if isinstance(response.data, list): for message in response.data: errors.append({ 'detail': message, 'source': { 'pointer': '/data', }, 'status': encoding.force_text(response.status_code), }) # handle all errors thrown from serializers else: for field, error in response.data.items(): field = format_value(field) pointer = '/data/attributes/{}'.format(field) # see if they passed a dictionary to ValidationError manually if isinstance(error, dict): errors.append(error) else: if isinstance(error, list): for message in error: errors.append({ 'detail': message, 'source': { 'pointer': pointer, }, 'status': encoding.force_text(response.status_code), }) else: errors.append({ 'detail': message, 'source': { 'pointer': pointer, }, 'status': encoding.force_text(response.status_code), }) context['view'].resource_name = 'errors' response.data = errors return response class Conflict(APIException): status_code = status.HTTP_409_CONFLICT default_detail = _('Conflict.')
from django.utils import encoding from django.utils.translation import ugettext_lazy as _ from rest_framework import status from rest_framework.exceptions import APIException from rest_framework.views import exception_handler as drf_exception_handler from rest_framework_json_api.utils import format_value def exception_handler(exc, context): response = drf_exception_handler(exc, context) errors = [] # handle generic errors. ValidationError('test') in a view for example if isinstance(response.data, list): for message in response.data: errors.append({ 'detail': message, 'source': { 'pointer': '/data', }, 'status': encoding.force_text(response.status_code), }) # handle all errors thrown from serializers else: for field, error in response.data.items(): field = format_value(field) pointer = '/data/attributes/{}'.format(field) # see if they passed a dictionary to ValidationError manually if isinstance(error, dict): errors.append(error) else: for message in error: errors.append({ 'detail': message, 'source': { 'pointer': pointer, }, 'status': encoding.force_text(response.status_code), }) context['view'].resource_name = 'errors' response.data = errors return response class Conflict(APIException): status_code = status.HTTP_409_CONFLICT default_detail = _('Conflict.')
Make $notification available in routeNotificationForFcm
<?php namespace Benwilkins\FCM; use GuzzleHttp\Client; use Illuminate\Notifications\Notification; /** * Class FcmChannel. */ class FcmChannel { /** * @const The API URL for Firebase */ const API_URI = 'https://fcm.googleapis.com/fcm/send'; /** * @var Client */ private $client; /** * @var string */ private $apikey; /** * @param Client $client */ public function __construct(Client $client, $apiKey) { $this->client = $client; $this->apiKey = $apiKey; } /** * @param mixed $notifiable * @param Notification $notification */ public function send($notifiable, Notification $notification) { /** @var FcmMessage $message */ $message = $notification->toFcm($notifiable); if (is_null($message->getTo()) && is_null($message->getCondition())) { if (! $to = $notifiable->routeNotificationFor('fcm', $notification)) { return; } $message->to($to); } $response = $this->client->post(self::API_URI, [ 'headers' => [ 'Authorization' => 'key='.$this->apiKey, 'Content-Type' => 'application/json', ], 'body' => $message->formatData(), ]); return \GuzzleHttp\json_decode($response->getBody(), true); } }
<?php namespace Benwilkins\FCM; use GuzzleHttp\Client; use Illuminate\Notifications\Notification; /** * Class FcmChannel. */ class FcmChannel { /** * @const The API URL for Firebase */ const API_URI = 'https://fcm.googleapis.com/fcm/send'; /** * @var Client */ private $client; /** * @var string */ private $apikey; /** * @param Client $client */ public function __construct(Client $client, $apiKey) { $this->client = $client; $this->apiKey = $apiKey; } /** * @param mixed $notifiable * @param Notification $notification */ public function send($notifiable, Notification $notification) { /** @var FcmMessage $message */ $message = $notification->toFcm($notifiable); if (is_null($message->getTo()) && is_null($message->getCondition())) { if (! $to = $notifiable->routeNotificationFor('fcm')) { return; } $message->to($to); } $response = $this->client->post(self::API_URI, [ 'headers' => [ 'Authorization' => 'key='.$this->apiKey, 'Content-Type' => 'application/json', ], 'body' => $message->formatData(), ]); return \GuzzleHttp\json_decode($response->getBody(), true); } }
Use BUILD_STATE_SCHEDULED and BUILD_STATE_RUNNING enums
import React from 'react'; import Relay from 'react-relay'; import Navigation from './layout/Navigation'; import Footer from './layout/Footer'; class Main extends React.Component { static propTypes = { children: React.PropTypes.node.isRequired, viewer: React.PropTypes.object.isRequired, organization: React.PropTypes.object }; render() { return ( <div> <Navigation organization={this.props.organization} viewer={this.props.viewer} /> {this.props.children} <Footer viewer={this.props.viewer} /> </div> ); } } export default Relay.createContainer(Main, { fragments: { viewer: () => Relay.QL` fragment on Viewer { user { name avatar { url } } organizations(first: 100) { edges { node { name slug } } } runningBuilds: builds(state: BUILD_STATE_RUNNING) { count } scheduledBuilds: builds(state: BUILD_STATE_SCHEDULED) { count } unreadChangelogs: changelogs(read: false) { count } } `, organization: () => Relay.QL` fragment on Organization { id name slug agents { count } permissions { organizationUpdate { allowed } organizationMemberCreate { allowed } notificationServiceUpdate { allowed } organizationBillingUpdate { allowed } teamAdmin { allowed } } } ` } });
import React from 'react'; import Relay from 'react-relay'; import Navigation from './layout/Navigation'; import Footer from './layout/Footer'; class Main extends React.Component { static propTypes = { children: React.PropTypes.node.isRequired, viewer: React.PropTypes.object.isRequired, organization: React.PropTypes.object }; render() { return ( <div> <Navigation organization={this.props.organization} viewer={this.props.viewer} /> {this.props.children} <Footer viewer={this.props.viewer} /> </div> ); } } export default Relay.createContainer(Main, { fragments: { viewer: () => Relay.QL` fragment on Viewer { user { name avatar { url } } organizations(first: 100) { edges { node { name slug } } } runningBuilds: builds(state: "running") { count } scheduledBuilds: builds(state: "scheduled") { count } unreadChangelogs: builds(read: false) { count } } `, organization: () => Relay.QL` fragment on Organization { id name slug agents { count } permissions { organizationUpdate { allowed } organizationMemberCreate { allowed } notificationServiceUpdate { allowed } organizationBillingUpdate { allowed } teamAdmin { allowed } } } ` } });
Update dependency to work on conda requests_oauthlib dependency name will only install from pip, requests-oauthlib works on both conda and pip
#!/usr/bin/env python # encoding=utf-8 from __future__ import print_function import os import sys from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.md')).read() needs_pytest = set(['pytest', 'test', 'ptr']).intersection(sys.argv) pytest_runner = ['pytest-runner'] if needs_pytest else [] setup(name='mwclient', version='0.9.3', # Use bumpversion to update description='MediaWiki API client', long_description=README, long_description_content_type='text/markdown', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], keywords='mediawiki wikipedia', author='Bryan Tong Minh', author_email='[email protected]', url='https://github.com/btongminh/mwclient', license='MIT', packages=['mwclient'], install_requires=['requests-oauthlib', 'six'], setup_requires=pytest_runner, tests_require=['pytest', 'pytest-cov', 'flake8', 'responses>=0.3.0', 'responses!=0.6.0', 'mock'], zip_safe=True )
#!/usr/bin/env python # encoding=utf-8 from __future__ import print_function import os import sys from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.md')).read() needs_pytest = set(['pytest', 'test', 'ptr']).intersection(sys.argv) pytest_runner = ['pytest-runner'] if needs_pytest else [] setup(name='mwclient', version='0.9.3', # Use bumpversion to update description='MediaWiki API client', long_description=README, long_description_content_type='text/markdown', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], keywords='mediawiki wikipedia', author='Bryan Tong Minh', author_email='[email protected]', url='https://github.com/btongminh/mwclient', license='MIT', packages=['mwclient'], install_requires=['requests_oauthlib', 'six'], setup_requires=pytest_runner, tests_require=['pytest', 'pytest-cov', 'flake8', 'responses>=0.3.0', 'responses!=0.6.0', 'mock'], zip_safe=True )
Remove Q in the question number.
/** * @module Question * question text **/ // CSS import styles from './style.css'; import React, { PropTypes } from 'react'; import PureComponent from 'react-pure-render/component'; import I18Next from 'i18next'; import classNames from 'classnames'; class Question extends PureComponent { render() { const { id, text, required } = this.props; return ( <div ref="root"> <div className={classNames({ [`${styles.question}`]: true, 'ut-question': true })} > {`${id}. ${text}`} </div> {required ? <span className={classNames({ [`${styles.required}`]: true, 'ut-required': true })} > {I18Next.t('basic.required')} </span> : ''} </div> ); } } Question.PropTypes = { id: PropTypes.number.isRequired, text: PropTypes.string, required: PropTypes.bool }; Question.defaultProps = {}; export default Question;
/** * @module Question * question text **/ // CSS import styles from './style.css'; import React, { PropTypes } from 'react'; import PureComponent from 'react-pure-render/component'; import I18Next from 'i18next'; import classNames from 'classnames'; class Question extends PureComponent { render() { const { id, text, required } = this.props; return ( <div ref="root"> <div className={classNames({ [`${styles.question}`]: true, 'ut-question': true })} > {`Q${id}. ${text}`} </div> {required ? <span className={classNames({ [`${styles.required}`]: true, 'ut-required': true })} > {I18Next.t('basic.required')} </span> : ''} </div> ); } } Question.PropTypes = { id: PropTypes.number.isRequired, text: PropTypes.string, required: PropTypes.bool }; Question.defaultProps = {}; export default Question;
Enable multi-element selectors for hideOtherLinks
/*global $ */ /*jslint white: true, vars: true, indent: 2 */ (function($) { "use strict"; $.fn.hideOtherLinks = function() { $(this).each(function(i, elm){ var $el = $(elm), showHide = $('<span class="other-content" />'), shownElements = [], hiddenElements = [], currentlyAppending = shownElements; $($el.contents()).each(function(i, el) { if (el.nodeValue && el.nodeValue === ".") { return; } currentlyAppending.push(el); if ($(el).is('a')) { currentlyAppending = hiddenElements; } }); if (hiddenElements.length) { $el.empty(); $(shownElements).each(function(i, el) { $el[0].appendChild(el); }); $(hiddenElements).each(function(i, el) { showHide[0].appendChild(el); }); $el.append(showHide); $el.append("."); showHide.hide(); var toggle = $('<a href="#" class="show-other-content" title="Show additional links">+ others</a>'); toggle.on('click', function(e) { e.preventDefault(); $(this).remove(); showHide.show().focus(); }); showHide.before(toggle); $el.attr('aria-live', 'polite'); } }); return this; }; })(jQuery);
/*global $ */ /*jslint white: true, vars: true, indent: 2 */ (function($) { "use strict"; $.fn.hideOtherLinks = function() { var $el = $(this), showHide = $('<span class="other-content" />'), shownElements = [], hiddenElements = [], currentlyAppending = shownElements; $($el.contents()).each(function(i, el) { if (el.nodeValue && el.nodeValue === ".") { return; } currentlyAppending.push(el); if ($(el).is('a')) { currentlyAppending = hiddenElements; } }); if (hiddenElements.length) { $el.empty(); $(shownElements).each(function(i, el) { $el[0].appendChild(el); }); $(hiddenElements).each(function(i, el) { showHide[0].appendChild(el); }); $el.append(showHide); $el.append("."); showHide.hide(); var toggle = $('<a href="#" class="show-other-content" title="Show additional links">+ others</a>'); toggle.on('click', function(e) { e.preventDefault(); $(this).remove(); showHide.show().focus(); }); showHide.before(toggle); $el.attr('aria-live', 'polite'); } return $el; }; })(jQuery);
Add cachetools to install reqs.
#!/usr/bin/env python import os try: import setuptools except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup NAME = 'chash' VERSION = '0.1.0' AUTHOR = 'Lev Givon' AUTHOR_EMAIL = '[email protected]' URL = 'https://github.com/lebedov/chash' MAINTAINER = AUTHOR MAINTAINER_EMAIL = AUTHOR_EMAIL DESCRIPTION = 'Content-based hash' LONG_DESCRIPTION = DESCRIPTION DOWNLOAD_URL = URL LICENSE = 'BSD' CLASSIFIERS = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Software Development'] if __name__ == '__main__': if os.path.exists('MANIFEST'): os.remove('MANIFEST') setup(name=NAME, version=VERSION, author=AUTHOR, author_email = AUTHOR_EMAIL, url = URL, maintainer = MAINTAINER, maintainer_email = MAINTAINER_EMAIL, description = DESCRIPTION, license = LICENSE, classifiers = CLASSIFIERS, packages = ['chash'], test_suite = 'tests', install_requires = [ 'cachetools', 'numpy', 'pandas', 'xxh'])
#!/usr/bin/env python import os try: import setuptools except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup NAME = 'chash' VERSION = '0.1.0' AUTHOR = 'Lev Givon' AUTHOR_EMAIL = '[email protected]' URL = 'https://github.com/lebedov/chash' MAINTAINER = AUTHOR MAINTAINER_EMAIL = AUTHOR_EMAIL DESCRIPTION = 'Content-based hash' LONG_DESCRIPTION = DESCRIPTION DOWNLOAD_URL = URL LICENSE = 'BSD' CLASSIFIERS = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Software Development'] if __name__ == '__main__': if os.path.exists('MANIFEST'): os.remove('MANIFEST') setup(name=NAME, version=VERSION, author=AUTHOR, author_email = AUTHOR_EMAIL, url = URL, maintainer = MAINTAINER, maintainer_email = MAINTAINER_EMAIL, description = DESCRIPTION, license = LICENSE, classifiers = CLASSIFIERS, packages = ['chash'], test_suite = 'tests', install_requires = [ 'numpy', 'pandas', 'xxh'])
Remove theme specific code from inlaylist template
<?php global $post; $items = get_field('items', $module->ID); ?> <div class="grid"> <div class="grid-lg-12"> <div class="box box-panel"> <h4 class="box-title"><?php echo $module->post_title; ?></h4> <ul> <?php foreach ($items as $item) : ?> <?php if ($item['type'] == 'external') : ?> <li> <a class="link-item link-item-outbound" href="<?php echo $item['link_external']; ?>" target="_blank"><?php echo $item['title'] ?></a> </li> <?php elseif ($item['type'] == 'internal') : ?> <li> <a class="link-item" href="<?php echo get_permalink($item['link_internal']->ID); ?>"><?php echo (!empty($item['title'])) ? $item['title'] : $item['link_internal']->post_title; ?> <?php if ($item['date'] === true) : ?> <span class="date pull-right text-sm text-dark-gray"><?php echo date('Y-m-d', strtotime($item['link_internal']->post_date)); ?></span> <?php endif; ?> </a> </li> <?php endif; ?> <?php endforeach; ?> </ul> </div> </div> </div>
<?php global $post; $items = get_field('items', $module->ID); $class = ''; switch ($args['id']) { case 'content-area': $class = 'box-panel-secondary'; break; default: $class = 'box-panel-primary'; break; } ?> <div class="grid"> <div class="grid-lg-12"> <div class="box box-panel <?php echo $class; ?>"> <h4 class="box-title"><?php echo $module->post_title; ?></h4> <ul> <?php foreach ($items as $item) : ?> <?php if ($item['type'] == 'external') : ?> <li> <a class="link-item link-item-outbound" href="<?php echo $item['link_external']; ?>" target="_blank"><?php echo $item['title'] ?></a> </li> <?php elseif ($item['type'] == 'internal') : ?> <li> <a class="link-item" href="<?php echo get_permalink($item['link_internal']->ID); ?>"><?php echo (!empty($item['title'])) ? $item['title'] : $item['link_internal']->post_title; ?> <?php if ($item['date'] === true) : ?> <span class="date pull-right text-sm text-dark-gray"><?php echo date('Y-m-d', strtotime($item['link_internal']->post_date)); ?></span> <?php endif; ?> </a> </li> <?php endif; ?> <?php endforeach; ?> </ul> </div> </div> </div>
Fix false positive user helper test
const expect = require('chai').expect; const config = require('getconfig'); const UserHelper = require('../../app/util/user-helper'); describe('User Helper', () => { const userHelper = new UserHelper(config.MC_SERVER_PATH); describe('Details', () => { it('should return expected values', () => { const expectedResult = [ { uuid: '879e207a-39a5-48df-ba7e-eb6089fe970c', name: 'MajorSlackmore' }, { uuid: '6eb35f96-c2c7-4332-b0b9-3d1981edae78', name: 'MiniSlackmore' } ]; return userHelper.getDetails() .then(detailsResult => expect(detailsResult).to.deep.equal(expectedResult)); }); }); describe('Achievements', () => { it('should return user achievements with score', () => { const expectedResult = { achievements: ['buildPickaxe', 'openInventory', 'buildWorkBench', 'mineWood', 'exploreAllBiomes'], score: 50 }; return userHelper.getAchievements('879e207a-39a5-48df-ba7e-eb6089fe970c') .then(achievementsResult => expect(achievementsResult).to.deep.equal(expectedResult)); }); }); });
const expect = require('chai').expect; const config = require('getconfig'); const UserHelper = require('../../app/util/user-helper'); describe('User Helper', () => { const userHelper = new UserHelper(config.MC_SERVER_PATH); describe('Details', () => { it('should return expected values', () => { const expectedResult = [ { uuid: '879e207a-39a5-48df-ba7e-eb6089fe970c', name: 'MajorSlackmore' }, { uuid: '6eb35f96-c2c7-4332-b0b9-3d1981edae78', name: 'MiniSlackmore' } ]; userHelper.getDetails().then((detailsResult) => { expect(detailsResult).to.equal(expectedResult); }); }); }); describe('Achievements', () => { it('should return user achievements with score', () => { const expectedResult = { achievements: ['buildPickaxe', 'openInventory', 'buildWorkBench', 'mineWood', 'exploreAllBiomes'], score: 50 }; userHelper.getAchievements('879e207a-39a5-48df-ba7e-eb6089fe970c').then((achievementsResult) => { expect(achievementsResult).to.equal(expectedResult); }); }); }); });
Fix a tab reset issue in Menu
var Menu = { refresh: function() { var items = document.querySelectorAll('ul#menu_wrapper li, #post_widget ul.card li'); var i = 0; while(i < items.length) { if(items[i].id != 'history') { items[i].onclick = function(e) { if(this.dataset.id) { MovimTpl.showPanel(); Post_ajaxGetPost(this.dataset.id); //Menu_ajaxGetNode(this.dataset.server, this.dataset.node); Menu.reset(items); movim_add_class(this, 'active'); } } } i++; } }, reset: function(list) { for(i = 0; i < list.length; i++) { movim_remove_class(list[i], 'active'); } } } MovimWebsocket.attach(function() { Notification_ajaxClear('news'); Notification.current('news'); Menu.refresh(); });
var Menu = { refresh: function() { var items = document.querySelectorAll('#menu_widget ul li, #post_widget ul.card li'); var i = 0; while(i < items.length) { if(items[i].id != 'history') { items[i].onclick = function(e) { if(this.dataset.id) { MovimTpl.showPanel(); Post_ajaxGetPost(this.dataset.id); //Menu_ajaxGetNode(this.dataset.server, this.dataset.node); Menu.reset(items); movim_add_class(this, 'active'); } } } i++; } }, reset: function(list) { for(i = 0; i < list.length; i++) { movim_remove_class(list[i], 'active'); } } } MovimWebsocket.attach(function() { Notification_ajaxClear('news'); Notification.current('news'); Menu.refresh(); });
Add ability to get calibre db
from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import NoArgsCommand from django.conf import settings from django_dropbox.storage import DropboxStorage from dropbox.rest import ErrorResponse from calibre_books.calibre.models import Book, Data class Command(NoArgsCommand): def get_url(self, path): try: return self.client.media(path).get('url') except ErrorResponse: pass def handle_noargs(self, **options): self.client = DropboxStorage().client calibre_db = self.client.get_file('/%s/metadata.db' % settings.DROPBOX_CALIBRE_DIR) local_db = open(settings.DATABASES['calibre']['NAME'], 'wb') local_db.write(calibre_db.read()) local_db.close() for book in Book.objects.all(): print book.title, url = self.get_url('/%s/%s/cover.jpg' % (settings.DROPBOX_CALIBRE_DIR, book.path)) if url: book.set_data('cover_url', url) try: data = book.data.get(format=Data.MOBI) except ObjectDoesNotExist: pass else: url = self.get_url('/%s/%s/%s.mobi' % (settings.DROPBOX_CALIBRE_DIR, book.path, data.name)) if url: book.set_data('download_url', url) print 'done'
from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import NoArgsCommand from django.conf import settings from django_dropbox.storage import DropboxStorage from dropbox.rest import ErrorResponse from calibre_books.calibre.models import Book, Data class Command(NoArgsCommand): def get_url(self, path): try: return self.client.media(path).get('url') except ErrorResponse: pass def handle_noargs(self, **options): self.client = DropboxStorage().client for book in Book.objects.all(): print book.title, url = self.get_url('/%s/%s/cover.jpg' % (settings.DROPBOX_CALIBRE_DIR, book.path)) if url: book.set_data('cover_url', url) try: data = book.data.get(format=Data.MOBI) except ObjectDoesNotExist: pass else: url = self.get_url('/%s/%s/%s.mobi' % (settings.DROPBOX_CALIBRE_DIR, book.path, data.name)) if url: book.set_data('download_url', url) print 'done'
Remove unused LOG in websocket Change-Id: Ic45e5e4353dd816fd5416b880aa47df8542b2e02
# Copyright 2017 Linaro Limited # # 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 socket import websocket from zun.common import exception class WebSocketClient(object): def __init__(self, host_url, escape='~', close_wait=0.5): self.escape = escape self.close_wait = close_wait self.host_url = host_url self.cs = None def connect(self): url = self.host_url try: self.ws = websocket.create_connection(url, skip_utf8_validation=True) except socket.error as e: raise exception.ConnectionFailed(e) except websocket.WebSocketConnectionClosedException as e: raise exception.ConnectionFailed(e) except websocket.WebSocketBadStatusException as e: raise exception.ConnectionFailed(e)
# Copyright 2017 Linaro Limited # # 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 logging import socket import websocket from zun.common import exception LOG = logging.getLogger(__name__) class WebSocketClient(object): def __init__(self, host_url, escape='~', close_wait=0.5): self.escape = escape self.close_wait = close_wait self.host_url = host_url self.cs = None def connect(self): url = self.host_url try: self.ws = websocket.create_connection(url, skip_utf8_validation=True) except socket.error as e: raise exception.ConnectionFailed(e) except websocket.WebSocketConnectionClosedException as e: raise exception.ConnectionFailed(e) except websocket.WebSocketBadStatusException as e: raise exception.ConnectionFailed(e)
Fix to check match object for null and to set a recurring alarm.
function printError(e) { chrome.alarms.clearAll(); webkitNotifications.createNotification('', e, '').show(); } function setCheckAlarm() { chrome.alarms.create({'periodInMinutes': 1, 'delayInMinutes': 1}); } function checkMail() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState != 4) { return; } if (xhr.responseText) { var matches = xhr.responseText.match(/Message: Unread/g); if (matches != null) { var count = matches.length; if (count > 0) { chrome.alarms.clearAll(); var notification = webkitNotifications.createNotification( '', 'New mail message', 'You have ' + count + ' new message(s)' ); notification.onclose = setCheckAlarm; notification.show(); } else { printError('Could not get message count from URL'); } } } else { printError('Fetching failed'); } }; xhr.open("GET", localStorage["url"], true); xhr.send(null); } if (localStorage["url"] != ""){ chrome.alarms.onAlarm.addListener(checkMail); setCheckAlarm(); checkMail(); } else { printError('owa-notification-chrome not configured'); }
function printError(e) { chrome.alarms.clearAll(); webkitNotifications.createNotification('', e, '').show(); } function checkMail() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState != 4) { return; } if (xhr.responseText) { var count = xhr.responseText.match(/Message: Unread/g).length; if (count > 0) { chrome.alarms.clearAll(); var notification = webkitNotifications.createNotification( '', 'New mail message', 'You have ' + count + ' new message(s)' ); notification.onclose = function() { chrome.alarms.create({'delayInMinutes': 1}); }; notification.show(); } else { printError('Could not get message count from URL'); } } else { printError('Fetching failed'); } }; xhr.open("GET", localStorage["url"], true); xhr.send(null); } if (localStorage["url"] != ""){ chrome.alarms.onAlarm.addListener(checkMail); chrome.alarms.create({'delayInMinutes': 1}); checkMail(); } else { printError('owa-notification-chrome not configured'); }
Write new page parent select box bug fixed
$.jlm.component('WriteNew', 'wild_posts.wf_index, wild_posts.wf_edit, wild_pages.wf_index, wild_pages.wf_edit', function() { $('#sidebar .add').click(function() { var buttonEl = $(this); var formAction = buttonEl.attr('href'); var templatePath = 'posts/new_post'; var parentPageOptions = null; if ($.jlm.params.controller == 'wild_pages') { templatePath = 'pages/new_page'; parentPageOptions = $('.all-page-parents').html(); parentPageOptions = parentPageOptions.replace('[Page]', '[WildPage]'); parentPageOptions = parentPageOptions.replace('[parent_id_options]', '[parent_id]'); } var dialogEl = $($.jlm.template(templatePath, { action: formAction, parentPageOptions: parentPageOptions })); var contentEl = $('#content-pad'); contentEl.append(dialogEl); var toHeight = 230; var hiddenContentEls = contentEl.animate({ height: toHeight }, 600).children().not(dialogEl).hide(); $('.input input', dialogEl).focus(); // Bind cancel link $('.cancel-edit a', dialogEl).click(function() { dialogEl.remove(); hiddenContentEls.show(); contentEl.height('auto'); return false; }); // Create link $('.submit input', dialogEl).click(function() { $(this).attr('disabled', 'disabled').attr('value', '<l18n>Saving...</l18n>'); return true; }); return false; }); });
$.jlm.component('WriteNew', 'wild_posts.wf_index, wild_posts.wf_edit, wild_pages.wf_index, wild_pages.wf_edit', function() { $('#sidebar .add').click(function() { var buttonEl = $(this); var formAction = buttonEl.attr('href'); var templatePath = 'posts/new_post'; var parentPageOptions = null; if ($.jlm.params.controller == 'wild_pages') { templatePath = 'pages/new_page'; parentPageOptions = $('.all-page-parents').html(); parentPageOptions = parentPageOptions.replace('[parent_id_options]', '[parent_id]'); } var dialogEl = $($.jlm.template(templatePath, { action: formAction, parentPageOptions: parentPageOptions })); var contentEl = $('#content-pad'); contentEl.append(dialogEl); var toHeight = 230; var hiddenContentEls = contentEl.animate({ height: toHeight }, 600).children().not(dialogEl).hide(); $('.input input', dialogEl).focus(); // Bind cancel link $('.cancel-edit a', dialogEl).click(function() { dialogEl.remove(); hiddenContentEls.show(); contentEl.height('auto'); return false; }); // Create link $('.submit input', dialogEl).click(function() { $(this).attr('disabled', 'disabled').attr('value', '<l18n>Saving...</l18n>'); return true; }); return false; }); });
Use source maps in developer mode.
var path = require('path'); var CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: [ './js/index.js' ], output: { path: path.join(__dirname, 'dist'), filename: 'app.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.css$/, loaders: [ 'style-loader', 'css-loader?importLoaders=1', 'postcss-loader' ] }, { test: /\.less$/, loader: 'style!css!less!' }, { test: /\.json$/, loader: "json-loader" }, { test: /\.(png|jpg|gif)$/, // inline base64 URLs for <=8k images, direct URLs for the rest loader: 'url-loader?limit=8192' }, { // Support ?123 suffix, e.g. ../fonts/m4d-icons.eot?3179539#iefix in react-responsive-carousel.less test: /\.(eot|ttf|woff|woff2|svg)((\?|\#).*)?$/, loader: 'url-loader?limit=8192' } ] }, devtool: "source-map", plugins: [ new CopyWebpackPlugin([ {from: 'public'} ]) ] };
var path = require('path'); var CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: [ './js/index.js' ], output: { path: path.join(__dirname, 'dist'), filename: 'app.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.css$/, loaders: [ 'style-loader', 'css-loader?importLoaders=1', 'postcss-loader' ] }, { test: /\.less$/, loader: 'style!css!less!' }, { test: /\.json$/, loader: "json-loader" }, { test: /\.(png|jpg|gif)$/, // inline base64 URLs for <=8k images, direct URLs for the rest loader: 'url-loader?limit=8192' }, { // Support ?123 suffix, e.g. ../fonts/m4d-icons.eot?3179539#iefix in react-responsive-carousel.less test: /\.(eot|ttf|woff|woff2|svg)((\?|\#).*)?$/, loader: 'url-loader?limit=8192' } ] }, plugins: [ new CopyWebpackPlugin([ {from: 'public'} ]) ] };
Hide the links that aren't selectable yet so you can't tab to them
var Flickity = require('flickity'); (function(Flickity) { "use strict"; if(document.querySelector('.rotate') !== null) { new Flickity('.rotate', { on: { ready: function() { // Get the height of the first image that loaded and dynamically set the height if(document.querySelector('.flickity-enabled .is-selected img') != null) { document.querySelector('.flickity-viewport').style.height = document.querySelector('.flickity-enabled .is-selected img').offsetHeight + 'px'; } // Visually hide the dots for accessibility if(document.querySelector('.flickity-page-dots') != null) { document.querySelector('.flickity-page-dots').classList.add('visually-hidden'); } } }, accessibility: true, prevNextButtons: true, pageDots: true, resize: true, setGallerySize: true, wrapAround: true, }); document.querySelector('.rotate').removeAttribute('tabindex'); let EnableTabbableItems = function () { // Don't allow tabbing to items that aren't selected document.querySelectorAll('.rotate .content a').forEach(function (item) { item.classList.add('hidden'); }); // Allow tabbing to the selected item document.querySelectorAll('.rotate .is-selected .content a').forEach(function (item) { item.classList.remove('hidden'); }); } EnableTabbableItems(); document.querySelectorAll('.flickity-button').forEach(function (item) { item.addEventListener('click', EnableTabbableItems); }); } })(Flickity);
var Flickity = require('flickity'); (function(Flickity) { "use strict"; if(document.querySelector('.rotate') !== null) { new Flickity('.rotate', { on: { ready: function() { // Get the height of the first image that loaded and dynamically set the height if(document.querySelector('.flickity-enabled .is-selected img') != null) { document.querySelector('.flickity-viewport').style.height = document.querySelector('.flickity-enabled .is-selected img').offsetHeight + 'px'; } // Visually hide the dots for accessibility if(document.querySelector('.flickity-page-dots') != null) { document.querySelector('.flickity-page-dots').classList.add('visually-hidden'); } } }, accessibility: true, prevNextButtons: true, pageDots: true, resize: true, setGallerySize: true, wrapAround: true, }); document.querySelector('.rotate').removeAttribute('tabindex'); } })(Flickity);
Revert per user API rate limit It was changed from per user to per application in ced3e50bca279f5a499a6d513fcdfd2a020c28ce
<?php namespace App\Providers; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Route; class RouteServiceProvider extends ServiceProvider { /** * The path to the "home" route for your application. * * This is used by Laravel authentication to redirect users after login. * * @var string */ public const HOME = '/home'; /** * The controller namespace for the application. * * When present, controller route declarations will automatically be prefixed with this namespace. * * @var string|null */ // protected $namespace = 'App\\Http\\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @return void */ public function boot() { $this->configureRateLimiting(); $this->routes(function () { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); }); } /** * Configure the rate limiters for the application. * * @return void */ protected function configureRateLimiting() { RateLimiter::for('api', function (Request $request) { return Limit::perMinute(60)->by($request->ip()); }); } }
<?php namespace App\Providers; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Route; class RouteServiceProvider extends ServiceProvider { /** * The path to the "home" route for your application. * * This is used by Laravel authentication to redirect users after login. * * @var string */ public const HOME = '/home'; /** * The controller namespace for the application. * * When present, controller route declarations will automatically be prefixed with this namespace. * * @var string|null */ // protected $namespace = 'App\\Http\\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @return void */ public function boot() { $this->configureRateLimiting(); $this->routes(function () { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); }); } /** * Configure the rate limiters for the application. * * @return void */ protected function configureRateLimiting() { RateLimiter::for('api', function (Request $request) { return Limit::perMinute(60); }); } }
Use defaultValue for section name as we're only taking it onBlur
require('./Section.css') var React = require('react') var Button = require('./Button') var MarkdownArea = require('./MarkdownArea') var IdeasStore = require('../store') var Section = React.createClass({ handleBlur(e) { var {name, value} = e.target if (value !== this.props[name]) { IdeasStore.editSection({[name]: value}, this.props.index) } }, handleRemove(e) { if (window.confirm(`Delete ${this.props.section || '[section]'}?`)) { IdeasStore.removeSection(this.props.index) } }, render() { return <div className="Section"> <h2> <Button className="Section__remove" onClick={this.handleRemove} title="Remove section"> &ndash; </Button> <input autoFocus={this.props.isNew} className="Section__name" defaultValue={this.props.section} name="section" onBlur={this.handleBlur} placeholder="[section]" spellCheck="false" type="text"/> </h2> <MarkdownArea name="ideas" value={this.props.ideas} onBlur={this.handleBlur} placeholder="[ideas]"/> </div> } }) module.exports = Section
require('./Section.css') var React = require('react') var Button = require('./Button') var MarkdownArea = require('./MarkdownArea') var IdeasStore = require('../store') var Section = React.createClass({ handleBlur(e) { var {name, value} = e.target if (value !== this.props[name]) { IdeasStore.editSection({[name]: value}, this.props.index) } }, handleRemove(e) { if (window.confirm(`Delete ${this.props.section || '[section]'}?`)) { IdeasStore.removeSection(this.props.index) } }, render() { return <div className="Section"> <h2> <Button className="Section__remove" onClick={this.handleRemove} title="Remove section"> &ndash; </Button> <input autoFocus={this.props.isNew} className="Section__name" value={this.props.section} name="section" onBlur={this.handleBlur} placeholder="[section]" spellCheck="false" type="text"/> </h2> <MarkdownArea name="ideas" value={this.props.ideas} onBlur={this.handleBlur} placeholder="[ideas]"/> </div> } }) module.exports = Section
Add note about Windows icon format
''' Notification =========== The :class:`Notification` provides access to public methods to create notifications. Simple Examples --------------- To send notification:: >>> from plyer import notification >>> title = 'plyer' >>> message = 'This is an example.' >>> notification.notify(title=title, message=message) ''' class Notification(object): ''' Notification facade. ''' def notify(self, title='', message='', app_name='', app_icon='', timeout=10, ticker=''): ''' Send a notification. :param title: Title of the notification :param message: Message of the notification :param app_name: Name of the app launching this notification :param app_icon: Icon to be displayed along with the message :param timeout: time to display the message for, defaults to 10 :param ticker: text to display on status bar as the notification arrives :type title: str :type message: str :type app_name: str :type app_icon: str :type timeout: int :type ticker: str .. note:: When called on Windows, ``app_icon`` has to be a path to a file in .ICO format. ''' self._notify(title=title, message=message, app_icon=app_icon, app_name=app_name, timeout=timeout, ticker=ticker) # private def _notify(self, **kwargs): raise NotImplementedError("No usable implementation found!")
''' Notification =========== The :class:`Notification` provides access to public methods to create notifications. Simple Examples --------------- To send notification:: >>> from plyer import notification >>> title = 'plyer' >>> message = 'This is an example.' >>> notification.notify(title=title, message=message) ''' class Notification(object): ''' Notification facade. ''' def notify(self, title='', message='', app_name='', app_icon='', timeout=10, ticker=''): ''' Send a notification. :param title: Title of the notification :param message: Message of the notification :param app_name: Name of the app launching this notification :param app_icon: Icon to be displayed along with the message :param timeout: time to display the message for, defaults to 10 :param ticker: text to display on status bar as the notification arrives :type title: str :type message: str :type app_name: str :type app_icon: str :type timeout: int :type ticker: str ''' self._notify(title=title, message=message, app_icon=app_icon, app_name=app_name, timeout=timeout, ticker=ticker) # private def _notify(self, **kwargs): raise NotImplementedError("No usable implementation found!")
Make "every" the default aggregate option
define('app/models/rule', ['ember'], // // Rule Model // // @returns Class /// function () { 'use strict'; return Ember.Object.extend({ // // // Properties // // id: null, unit: null, value: null, metric: null, cycles: null, command: null, machine: null, operator: null, maxValue: null, aggregate: null, timeWindow: null, machineKey: null, machineName: null, machineSize: null, actionToTake: null, machineImage: null, machineScript: null, pendingAction: false, machineBackend: null, machineLocation: null, init: function () { this._super(); // TODO: delete. This is temp for debugging only this.set('aggregate', 'every'); this.set('timeWindow', 1); }, }); } );
define('app/models/rule', ['ember'], // // Rule Model // // @returns Class /// function () { 'use strict'; return Ember.Object.extend({ // // // Properties // // id: null, unit: null, value: null, metric: null, cycles: null, command: null, machine: null, operator: null, maxValue: null, aggregate: null, timeWindow: null, machineKey: null, machineName: null, machineSize: null, actionToTake: null, machineImage: null, machineScript: null, pendingAction: false, machineBackend: null, machineLocation: null, init: function () { this._super(); // TODO: delete. This is temp for debugging only this.set('aggregate', 'any'); this.set('timeWindow', 1); }, }); } );
Fix 6547 php file instructions
<?php header("Set-Cookie: issue6547=Hello Firebug user!; Max-Age=0"); ?> <!DOCTYPE html> <html> <head> <title>Issue 6547: Show cookie Max-Age when attribute is <= 0</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link href="https://getfirebug.com/tests/head/_common/testcase.css" type="text/css" rel="stylesheet"/> </head> <body> <header> <h1><a href="http://code.google.com/p/fbug/issues/detail?id=6547">Issue 6547</a>: Show cookie Max-Age when attribute is <= 0</h1> </header> <div> <section id="description"> <h3>Steps to reproduce</h3> <ol> <li>Open Firebug</li> <li>Enable and switch to the <em>Net</em> panel</li> <li>Reload the page</li> <li>Expand the request to <em>issue6547.php</em><br/></li> <li>Switch to the <em>Cookies</em> info tab</li> <li> There should be a <em>Max. Age</em> column showing the value <code>0ms</code> </li> </ul> </section> <footer>Awad Mackie, [email protected]</footer> </div> </body> </html>
<?php header("Set-Cookie: issue6547=Hello Firebug user!; Max-Age=0"); ?> <!DOCTYPE html> <html> <head> <title>Issue 6547: Show cookie Max-Age when attribute is <= 0</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link href="https://getfirebug.com/tests/head/_common/testcase.css" type="text/css" rel="stylesheet"/> </head> <body> <header> <h1><a href="http://code.google.com/p/fbug/issues/detail?id=6547">Issue 6547</a>: Show cookie Max-Age when attribute is <= 0</h1> </header> <div> <section id="description"> <h3>Steps to reproduce</h3> <ol> <li>Open Firebug</li> <li>Enable and switch to the <em>Net</em> panel</li> <li>Reload the page</li> <li>Expand the request to <em>issue6547.php</em><br/></li> <li>Switch to the <em>Cookies</em> info tab</li> <li> There should be a <em>Max. Age</em> column showing the value <code>0</code> </li> </ul> </section> <footer>Awad Mackie, [email protected]</footer> </div> </body> </html>
Store colgroup in ui hash
define(['underscore', 'backbone.marionette', './LessonView'], function(_, Marionette, LessonView) { 'use strict'; return Marionette.CollectionView.extend({ el: $('#timetable'), childView: LessonView, childViewOptions: function () { return { parentView: this, timetable: this.collection }; }, events: { 'mousemove': 'mouseMove', 'mouseleave': 'mouseLeave' }, ui: { colgroups: 'colgroup' }, initialize: function() { }, mouseMove: function(evt) { if (!this.colX) { this.colX = this.$('#mon > tr:last-child > td') .filter(':even') .map(function() { return $(this).offset().left; }) .get(); } var currCol = this.ui.colgroups.eq(_.sortedIndex(this.colX, evt.pageX)); if (!currCol.is(this.prevCol)) { if (this.prevCol) { this.prevCol.removeAttr('class'); } currCol.addClass('hover'); this.prevCol = currCol; } }, mouseLeave: function() { if (this.prevCol) { this.prevCol.removeAttr('class'); this.prevCol = false; } }, attachBuffer: function () { }, attachHtml: function () { } }); });
define(['underscore', 'backbone.marionette', './LessonView'], function(_, Marionette, LessonView) { 'use strict'; return Marionette.CollectionView.extend({ el: $('#timetable'), childView: LessonView, childViewOptions: function () { return { parentView: this, timetable: this.collection }; }, events: { 'mousemove': 'mouseMove', 'mouseleave': 'mouseLeave' }, initialize: function() { this.$colgroups = this.$('colgroup'); }, mouseMove: function(evt) { if (!this.colX) { this.colX = this.$('#mon > tr:last-child > td') .filter(':even') .map(function() { return $(this).offset().left; }) .get(); } var currCol = this.$colgroups.eq(_.sortedIndex(this.colX, evt.pageX)); if (!currCol.is(this.prevCol)) { if (this.prevCol) { this.prevCol.removeAttr('class'); } currCol.addClass('hover'); this.prevCol = currCol; } }, mouseLeave: function() { if (this.prevCol) { this.prevCol.removeAttr('class'); this.prevCol = false; } }, attachBuffer: function () { }, attachHtml: function () { } }); });
Return commonness instead of raw counts
from collections import defaultdict import operator import six from semanticizest._util import ngrams_with_pos, tosequence class Semanticizer(object): def __init__(self, link_count, N=7): commonness = defaultdict(list) for (target, anchor), count in six.iteritems(link_count): commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): # targets.sort(key=operator.itemgetter(1), reverse=True) # Turn counts into probabilities. # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) commonness[anchor] = [(t, count / total) for t, count in targets] self.commonness = commonness self.N = N def all_candidates(self, s): """Retrieve all candidate entities. Parameters ---------- s : {string, iterable over string} Tokens. If a string, it will be tokenized using a naive heuristic. Returns ------- candidates : iterable over (int, int, string, float) Candidate entities: 4-tuples of start index, end index (both in tokenized input), target entity and probability (commonness). """ if isinstance(s, six.string_types): # XXX need a smarter tokenizer! s = s.split() else: s = tosequence(s) for i, j, s in ngrams_with_pos(s, self.N): if s in self.commonness: for target, prob in self.commonness[s]: yield i, j, target, prob
from collections import defaultdict import operator import six from semanticizest._util import ngrams_with_pos, tosequence class Semanticizer(object): def __init__(self, link_count, N=7): commonness = defaultdict(list) for (target, anchor), count in six.iteritems(link_count): commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): targets.sort(key=operator.itemgetter(1)) # Turn counts into probabilities. # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) targets = ((t, count / total) for t, count in targets) self.commonness = commonness self.N = N def all_candidates(self, s): """Retrieve all candidate entities. Parameters ---------- s : {string, iterable over string} Tokens. If a string, it will be tokenized using a naive heuristic. Returns ------- candidates : iterable over (int, int, string, float) Candidate entities: 4-tuples of start index, end index (both in tokenized input), target entity and probability (commonness). """ if isinstance(s, six.string_types): # XXX need a smarter tokenizer! s = s.split() else: s = tosequence(s) for i, j, s in ngrams_with_pos(s, self.N): if s in self.commonness: for target, prob in self.commonness[s]: yield i, j, target, prob
Fix typo inside of LANGUAGES_SUPPORTED.
# -*- encoding: utf-8 -*- # # In here we shall keep track of all variables and objects that should be # instantiated only once and be common to pieces of GLBackend code. __version__ = '2.24.16' DATABASE_VERSION = 6 # Add here by hand the languages supported! # copy paste format from 'grunt makeTranslations' LANGUAGES_SUPPORTED = [ { "code": "en", "name": "English"}, { "code": "fr", "name": "French"}, { "code": "hu_HU", "name": "Hungarian (Hungary)"}, { "code": "it", "name": "Italian"}, { "code": "nl", "name": "Dutch"}, { "code": "pt_BR", "name": "Portuguese (Brazil)"}, { "code": "ru", "name": "Russian" }, { "code": "tr", "name": "Turkish"}, { "code": "vi", "name": "Vietnamese"}, ] LANGUAGES_SUPPORTED_CODES = [ "en", "fr", "hu_HU", "it", "nl", "pt_BR", "ru", "tr", "vi" ]
# -*- encoding: utf-8 -*- # # In here we shall keep track of all variables and objects that should be # instantiated only once and be common to pieces of GLBackend code. __version__ = '2.24.16' DATABASE_VERSION = 6 # Add here by hand the languages supported! # copy paste format from 'grunt makeTranslations' LANGUAGES_SUPPORTED = [ { "code": "en", "name": "English"}, { "code": "fr", "name": "French"}, { "code": "hu_HU", "name": "Hungarian (Hungary)"}, { "code": "it", "name": "Italian"}, { "code": "nl", "name": "Dutch"}, { "code": "pt_BR", "name": "Portuguese (Brazil)"}, { "code": "ru", "name": "Russian" }, { "code": "tr", "name": "Turkish"}, { "code": "vi", "name": "Vietnamese"}, ] LANGUAGES_SUPPORTED_CODES = [ "en", "fr", "hu_HU", "it", "nl" "pt_BR", "ru", "tr", "vi" ]
Use relative path instead of only filename
import pytest import inspect import os.path def pytest_namespace(): def assume(expr, msg=''): if not expr: # get filename, line, and context (filename, line, funcname, contextlist) = inspect.stack()[1][1:5] filename = os.path.relpath(filename) context = contextlist[0] # format entry msg = '%s\n' % msg if msg else '' entry = '>%s%s%s:%s\n--------' % (context, msg, filename, line) # add entry pytest._failed_assumptions.append(entry) return {'_failed_assumptions': [], 'assume': assume} def pytest_runtest_setup(item): del pytest._failed_assumptions[:] @pytest.mark.hookwrapper def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result() if call.when == "call" and pytest._failed_assumptions: summary = 'Failed Assumptions:%s' % len(pytest._failed_assumptions) pytest._failed_assumptions.append(summary) if report.longrepr: report.longrepr = str(report.longrepr) + \ '\n--------\n' + ('\n'.join(pytest._failed_assumptions)) else: report.longrepr = '\n'.join(pytest._failed_assumptions) report.outcome = "failed"
import pytest import inspect import os.path def pytest_namespace(): def assume(expr, msg=''): if not expr: # get filename, line, and context (filename, line, funcname, contextlist) = inspect.stack()[1][1:5] filename = os.path.basename(filename) context = contextlist[0] # format entry msg = '%s\n' % msg if msg else '' entry = '>%s%s%s:%s\n--------' % (context, msg, filename, line) # add entry pytest._failed_assumptions.append(entry) return {'_failed_assumptions': [], 'assume': assume} def pytest_runtest_setup(item): del pytest._failed_assumptions[:] @pytest.mark.hookwrapper def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result() if call.when == "call" and pytest._failed_assumptions: summary = 'Failed Assumptions:%s' % len(pytest._failed_assumptions) pytest._failed_assumptions.append(summary) if report.longrepr: report.longrepr = str(report.longrepr) + \ '\n--------\n' + ('\n'.join(pytest._failed_assumptions)) else: report.longrepr = '\n'.join(pytest._failed_assumptions) report.outcome = "failed"
Update Date for 2017 Festival
$(function() { var riverbendStart = moment('2016-06-10T17:00:00-04:00'); var riverbendEnd = moment('2016-06-18T23:30:00-04:00'); var futureEventStart = moment('2017-06-10T17:00:00-04:00'); function formatDateDiff(start, end, opts) { opts = opts || {}; opts.long = opts.long || false; var duration = moment.duration(end.diff(start)); var diffStr = ""; if (opts.long) { if (duration.years() > 0) { diffStr += duration.years() + ' years '; } diffStr += duration.months() + ' months '; } diffStr += duration.days() + ' days ' + duration.hours() + ' hrs ' + duration.minutes() + ' mins ' + duration.seconds() + ' secs'; return diffStr; } function updatePage() { var now = moment(); if (now.isBetween(riverbendStart, riverbendEnd)) { $('.yep').hide(); $('.nope').show(); $('.countdown').html(formatDateDiff(now, riverbendEnd)); } else { $('.yep').show(); $('.nope').hide(); $('.countdown').html(formatDateDiff(now, futureEventStart, {long: true})); } } updatePage(); window.setInterval(updatePage, 1000); });
$(function() { var riverbendStart = moment('2016-06-10T17:00:00-04:00'); var riverbendEnd = moment('2016-06-18T23:30:00-04:00'); var futureEventStart = moment('2016-06-10T17:00:00-04:00'); function formatDateDiff(start, end, opts) { opts = opts || {}; opts.long = opts.long || false; var duration = moment.duration(end.diff(start)); var diffStr = ""; if (opts.long) { if (duration.years() > 0) { diffStr += duration.years() + ' years '; } diffStr += duration.months() + ' months '; } diffStr += duration.days() + ' days ' + duration.hours() + ' hrs ' + duration.minutes() + ' mins ' + duration.seconds() + ' secs'; return diffStr; } function updatePage() { var now = moment(); if (now.isBetween(riverbendStart, riverbendEnd)) { $('.yep').hide(); $('.nope').show(); $('.countdown').html(formatDateDiff(now, riverbendEnd)); } else { $('.yep').show(); $('.nope').hide(); $('.countdown').html(formatDateDiff(now, futureEventStart, {long: true})); } } updatePage(); window.setInterval(updatePage, 1000); });
Fix hide model on clicking
import React, { Component } from 'react' import { Modal } from '../../components' import { Button } from 'react-bootstrap' class TestModal extends Component { constructor () { super() this.state = { show: false } } hideModal () { this.setState({show: false}) } showModal () { this.setState({show: true}) } /* eslint-disable react/jsx-no-bind */ render () { console.info(this) return ( <div> <Button bsStyle='default' onClick={() => this.showModal()}>Launch Modal</Button> <Modal show={this.state.show} onHide={() => this.hideModal()}> <Modal.Header> <Modal.Title>Example Modal</Modal.Title> </Modal.Header> <Modal.Body>Hi There</Modal.Body> <Modal.Footer> <Button bsStyle='link' onClick={() => this.hideModal()}>Cancel</Button> <Button bsStyle='primary' onClick={() => this.hideModal()}> Submit </Button> </Modal.Footer> </Modal> </div>) } /* eslint-enable react/jsx-no-bind */ } export default TestModal
import React, { Component } from 'react' import { Modal } from '../../components' import { Button } from 'react-bootstrap' class TestModal extends Component { constructor () { super() this.state = { show: false } } hideModal () { console.info('test') this.setState({show: false}) } showModal () { this.setState({show: true}) } /* eslint-disable react/jsx-no-bind */ render () { return ( <div> <Button bsStyle='default' onClick={() => this.showModal()}>Launch Modal</Button> <Modal show={this.state.show} onHide={this.hideModal}> <Modal.Header> <Modal.Title>Example Modal</Modal.Title> </Modal.Header> <Modal.Body>Hi There</Modal.Body> <Modal.Footer> <Button bsStyle='link' onClick={() => this.hideModal()}>Cancel</Button> <Button bsStyle='primary' onClick={() => this.hideModal()}> Submit </Button> </Modal.Footer> </Modal> </div>) } /* eslint-enable react/jsx-no-bind */ } export default TestModal
Make Amazon keys non required
import os from functools import partial import boto3 from decouple import config from serenata_toolbox import log from serenata_toolbox.datasets.contextmanager import status_message class RemoteDatasets: def __init__(self): self.client = None self.credentials = { 'aws_access_key_id': config('AMAZON_ACCESS_KEY', default=None), 'aws_secret_access_key': config('AMAZON_SECRET_KEY', default=None), 'region_name': config('AMAZON_REGION'), } @property def bucket(self): return config('AMAZON_BUCKET') @property def s3(self): if not self.client: self.client = boto3.client('s3', **self.credentials) return self.client @property def all(self): response = self.s3.list_objects(Bucket=self.bucket) yield from (obj.get('Key') for obj in response.get('Contents', [])) def upload(self, file_path): _, file_name = os.path.split(file_path) with status_message('Uploading {}…'.format(file_name)): self.s3.upload_file(file_path, self.bucket, file_name) def delete(self, file_name): with status_message('Deleting {}…'.format(file_name)): self.s3.delete_object(Bucket=self.bucket, Key=file_name)
import os from functools import partial import boto3 from decouple import config from serenata_toolbox import log from serenata_toolbox.datasets.contextmanager import status_message class RemoteDatasets: def __init__(self): self.client = None self.credentials = { 'aws_access_key_id': config('AMAZON_ACCESS_KEY'), 'aws_secret_access_key': config('AMAZON_SECRET_KEY'), 'region_name': config('AMAZON_REGION'), } @property def bucket(self): return config('AMAZON_BUCKET') @property def s3(self): if not self.client: self.client = boto3.client('s3', **self.credentials) return self.client @property def all(self): response = self.s3.list_objects(Bucket=self.bucket) yield from (obj.get('Key') for obj in response.get('Contents', [])) def upload(self, file_path): _, file_name = os.path.split(file_path) with status_message('Uploading {}…'.format(file_name)): self.s3.upload_file(file_path, self.bucket, file_name) def delete(self, file_name): with status_message('Deleting {}…'.format(file_name)): self.s3.delete_object(Bucket=self.bucket, Key=file_name)
Add a loader while loading repositories
import React, { Component, PropTypes } from 'react'; import Progress from 'material-ui/CircularProgress'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow } from 'material-ui/Table'; import { getRepositories } from '../../installer/github'; import Repository from './Repository'; import Pagination from './Pagination'; const accessToken = window.localStorage.accessToken; const user = JSON.parse(window.localStorage.user); class RepositoryList extends Component { constructor(props) { super(props); this.state = { page: 1, hasNext: false, loading: true, repositories: [], }; } fetchRepositories = page => getRepositories(accessToken, user, page); componentWillMount() { this.fetchRepositories(this.state.page) .then(repositories => this.setState({ repositories, loading: false })); } onPageChange = page => () => { this.fetchRepositories(page) .then(repositories => this.setState({ page, repositories, })); }; render() { return ( <div> {this.state.loading && <div style={{ textAlign: 'center' }}> <Progress size={60} thickness={5} /> </div>} <Table> <TableBody> {this.state.repositories.map(repository => ( <Repository key={repository.id} repository={repository} /> ))} </TableBody> </Table> {/* to be implemented <Pagination hasNext={true} page={2} onChange={this.onPageChange} />*/} </div> ); }; } export default RepositoryList;
import React, { Component, PropTypes } from 'react'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow } from 'material-ui/Table'; import { getRepositories } from '../../installer/github'; import Repository from './Repository'; import Pagination from './Pagination'; const accessToken = window.localStorage.accessToken; const user = JSON.parse(window.localStorage.user); class RepositoryList extends Component { constructor(props) { super(props); this.state = { page: 1, hasNext: false, loading: true, repositories: [], }; } fetchRepositories = page => getRepositories(accessToken, user, page); componentWillMount() { this.fetchRepositories(this.state.page) .then(repositories => this.setState({ repositories })); } onPageChange = page => () => { this.fetchRepositories(page) .then(repositories => this.setState({ page, repositories, })); }; render() { return ( <div> <Table> <TableBody> {this.state.repositories.map(repository => ( <Repository key={repository.id} repository={repository} /> ))} </TableBody> </Table> {/* to be implemented <Pagination hasNext={true} page={2} onChange={this.onPageChange} />*/} </div> ); }; } export default RepositoryList;
Add removeInstance API for tests
package jfdi.storage; import java.nio.file.InvalidPathException; import jfdi.storage.exceptions.ExistingFilesFoundException; /** * This class serves as the facade of the Storage component. * * @author Thng Kai Yuan */ public class FileStorage implements IStorage { // The singleton instance of FileStorage private static FileStorage instance = null; // Boolean indicating if storage has been initialized private boolean isInitialized = false; /** * This private constructor prevents itself from being called by other * components. An instance of FileStorage should be initialized using the * getInstance method. */ private FileStorage() { } /** * @return the singleton instance of FileStorage */ public static FileStorage getInstance() { if (instance == null) { instance = new FileStorage(); } return instance; } @Override public void load(String storageFolderPath) throws InvalidPathException, ExistingFilesFoundException { FileManager.prepareDirectory(storageFolderPath); RecordManager.setAllFilePaths(storageFolderPath); RecordManager.loadAllRecords(); isInitialized = true; } @Override public void changeDirectory(String newStorageFolderPath) throws InvalidPathException, ExistingFilesFoundException, IllegalAccessException { if (!isInitialized) { throw new IllegalAccessException(Constants.MESSAGE_UNINITIALIZED_STORAGE); } FileManager.prepareDirectory(newStorageFolderPath); FileManager.moveFilesToDirectory(newStorageFolderPath); RecordManager.setAllFilePaths(newStorageFolderPath); RecordManager.loadAllRecords(); } /** * This method sets the existing instance to null. It should only be used * for testing/debugging purposes only. */ public void removeInstance() { instance = null; } }
package jfdi.storage; import java.nio.file.InvalidPathException; import jfdi.storage.exceptions.ExistingFilesFoundException; /** * This class serves as the facade of the Storage component. * * @author Thng Kai Yuan */ public class FileStorage implements IStorage { // The singleton instance of FileStorage private static FileStorage instance = null; // Boolean indicating if storage has been initialized private boolean isInitialized = false; /** * This private constructor prevents itself from being called by other * components. An instance of FileStorage should be initialized using the * getInstance method. */ private FileStorage() { } /** * @return the singleton instance of FileStorage */ public static FileStorage getInstance() { if (instance == null) { instance = new FileStorage(); } return instance; } @Override public void load(String storageFolderPath) throws InvalidPathException, ExistingFilesFoundException { FileManager.prepareDirectory(storageFolderPath); RecordManager.setAllFilePaths(storageFolderPath); RecordManager.loadAllRecords(); isInitialized = true; } @Override public void changeDirectory(String newStorageFolderPath) throws InvalidPathException, ExistingFilesFoundException, IllegalAccessException { if (!isInitialized) { throw new IllegalAccessException(Constants.MESSAGE_UNINITIALIZED_STORAGE); } FileManager.prepareDirectory(newStorageFolderPath); FileManager.moveFilesToDirectory(newStorageFolderPath); RecordManager.setAllFilePaths(newStorageFolderPath); RecordManager.loadAllRecords(); } }
Use loader to load driver
<?php include (SYSTEM_PATH . 'db/IDriver.php'); class DB { private $dbDriver; public function __construct() { $config =& loadClass('Config', 'Core'); $cfg = $config->load('DB'); if ($cfg !== false) { $this->driver($cfg['driver']); $this->connect($cfg['host'], $cfg['user'], $cfg['password']); $this->database($cfg['database'], false); } } public function driver($name) { $loader =& loadClass('Loader', 'Core'); $this->dbDriver = $loader->dbDriver($name); } public function connect($host, $user, $password='') { $this->dbDriver->connect($host, $user, $password); } public function database($name, $create=false) { $this->dbDriver->database($name); } public function query($sql, $data=[]) { } } ?>
<?php include (SYSTEM_PATH . 'db/IDriver.php'); class DB { private $dbDriver; public function __construct() { $config =& loadClass('Config', 'Core'); $cfg = $config->load('DB'); if ($cfg !== false) { $this->driver($cfg['driver']); $this->connect($cfg['host'], $cfg['user'], $cfg['password']); $this->database($cfg['database'], false); } } public function driver($name) { $vendor =& loadClass('Vendor', 'Core'); if (file_exists(SYSTEM_PATH.'db/driver/'.$name.'.php')) { include (SYSTEM_PATH.'db/driver/'.$name.'.php'); } } public function connect($host, $user, $password='') { $this->dbDriver->connect($host, $user, $password); } public function database($name, $create=false) { $this->dbDriver->database($name); } public function query($sql, $data=[]) { } } ?>
Update for api change with linter_configs.
from imhotep.tools import Tool from collections import defaultdict import re class JSL(Tool): regex = re.compile( r'^(?P<type>[WE]) ' r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$') def invoke(self, dirname, filenames=set(), linter_configs=set()): retval = defaultdict(lambda: defaultdict(list)) if len(filenames) == 0: cmd = 'find %s -name "*.js" | xargs jsl' % dirname else: js_files = [] for filename in filenames: if '.js' in filename: js_files.append("%s/%s" % (dirname, filename)) cmd = 'jsl %s' % ' '.join(js_files) output = self.executor(cmd) for line in output.split('\n'): match = self.regex.search(line) if match is None: continue message = '%s: %s' % (match.group('type'), match.group('message')) filename = match.group('filename')[len(dirname) + 1:] retval[filename][match.group('line_number')].append(message) return retval
from imhotep.tools import Tool from collections import defaultdict import re class JSL(Tool): regex = re.compile( r'^(?P<type>[WE]) ' r'(?P<filename>.*?) L(?P<line_number>\d+): (?P<message>.*)$') def invoke(self, dirname, filenames=set()): retval = defaultdict(lambda: defaultdict(list)) if len(filenames) == 0: cmd = 'find %s -name "*.js" | xargs jsl' % dirname else: js_files = [] for filename in filenames: if '.js' in filename: js_files.append("%s/%s" % (dirname, filename)) cmd = 'jsl %s' % ' '.join(js_files) output = self.executor(cmd) for line in output.split('\n'): match = self.regex.search(line) if match is None: continue message = '%s: %s' % (match.group('type'), match.group('message')) filename = match.group('filename')[len(dirname) + 1:] retval[filename][match.group('line_number')].append(message) return retval
Allow Django 1.6 install while preventing 1.3.X
#!/usr/bin/env python from setuptools import setup, find_packages from mutant import __version__ github_url = 'https://github.com/charettes/django-mutant' long_desc = open('README.md').read() setup( name='django-mutant', version='.'.join(str(v) for v in __version__), description='Dynamic model definition and alteration (evolving schemas)', long_description=open('README.md').read(), url=github_url, author='Simon Charette', author_email='[email protected]', install_requires=( 'django>=1.4,<=1.6', 'south>=0.7.6', 'django-orderable==1.2.1', 'django-picklefield==0.2.0', 'django-polymodels==1.0.1', ), dependency_links=( 'https://github.com/tkaemming/django-orderable/tarball/master#egg=django-orderable-1.2.1', ), packages=find_packages(exclude=['tests']), include_package_data=True, license='MIT License', classifiers=[ 'Development Status :: 1 - Planning', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ], )
#!/usr/bin/env python from setuptools import setup, find_packages from mutant import __version__ github_url = 'https://github.com/charettes/django-mutant' long_desc = open('README.md').read() setup( name='django-mutant', version='.'.join(str(v) for v in __version__), description='Dynamic model definition and alteration (evolving schemas)', long_description=open('README.md').read(), url=github_url, author='Simon Charette', author_email='[email protected]', install_requires=( 'django>=1.3,<=1.5', 'south>=0.7.6', 'django-orderable==1.2.1', 'django-picklefield==0.2.0', 'django-polymodels==1.0.1', ), dependency_links=( 'https://github.com/tkaemming/django-orderable/tarball/master#egg=django-orderable-1.2.1', ), packages=find_packages(exclude=['tests']), include_package_data=True, license='MIT License', classifiers=[ 'Development Status :: 1 - Planning', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ], )
Fix String endsWith prototype shadowing
// ================================================================================================= // Core.js | String Functions // (c) 2014 Mathigon / Philipp Legner // ================================================================================================= (function() { M.extend(String.prototype, { strip: function() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); }, collapse: function() { return this.trim().replace(/\s+/g, ' '); }, toTitleCase: function() { return this.replace(/\S+/g, function(a){ return a.charAt(0).toUpperCase() + a.slice(1); }); }, words: function() { return this.strip().split(/\s+/); } }, true); if (!String.prototype.endsWith) { M.extend(String.prototype, { endsWith: function(search) { var end = this.length; var start = end - search.length; return (this.substring(start, end) === search); } }, true); } if (!String.prototype.contains) { M.extend(String.prototype, { contains: function() { return String.prototype.indexOf.apply( this, arguments ) !== -1; } }, true); } })();
// ================================================================================================= // Core.js | String Functions // (c) 2014 Mathigon / Philipp Legner // ================================================================================================= (function() { M.extend(String.prototype, { endsWith: function(search) { var end = this.length; var start = end - search.length; return (this.substring(start, end) === search); }, strip: function() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); }, collapse: function() { return this.trim().replace(/\s+/g, ' '); }, toTitleCase: function() { return this.replace(/\S+/g, function(a){ return a.charAt(0).toUpperCase() + a.slice(1); }); }, words: function() { return this.strip().split(/\s+/); } }, true); if ( !String.prototype.contains ) { M.extend(String.prototype, { contains: function() { return String.prototype.indexOf.apply( this, arguments ) !== -1; } }, true); } })();
Fix namespace on solid ajax.
<?php namespace Solid\Ajax; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { /** * Execute an action on the controller. * * @param string $method * @param array $parameters * @return \Symfony\Component\HttpFoundation\Response */ public function callAction($method, $parameters) { $result = parent::callAction($method, $parameters); if (app('ajax.helper')->isFrameworkAjax()) { $result = $this->prepareAjaxActionResponse($result); } return $result; } /** * Prepare response to make it compatible with * front end Ajax Framework * * @param mixed $result * * @return JsonResponse */ protected function prepareAjaxActionResponse($result) { if ($result instanceof \Illuminate\View\View) { return $this->ajaxResponse(['result' => $result->render()]); } if (is_array($result)) { foreach ($result as $key => $value) { if ($value instanceof \Illuminate\View\View) { $result[$key] = $value->render(); } } } return $this->ajaxResponse($result); } /** * Convert given result to format expected by front end framework * * @param mixed $result * * @return JsonResponse */ protected function ajaxResponse($result) { return response()->json($result); } }
<?php namespace Solid\Ajax\Controllers; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { /** * Execute an action on the controller. * * @param string $method * @param array $parameters * @return \Symfony\Component\HttpFoundation\Response */ public function callAction($method, $parameters) { $result = parent::callAction($method, $parameters); if (app('ajax.helper')->isFrameworkAjax()) { $result = $this->prepareAjaxActionResponse($result); } return $result; } /** * Prepare response to make it compatible with * front end Ajax Framework * * @param mixed $result * * @return JsonResponse */ protected function prepareAjaxActionResponse($result) { if ($result instanceof \Illuminate\View\View) { return $this->ajaxResponse(['result' => $result->render()]); } if (is_array($result)) { foreach ($result as $key => $value) { if ($value instanceof \Illuminate\View\View) { $result[$key] = $value->render(); } } } return $this->ajaxResponse($result); } /** * Convert given result to format expected by front end framework * * @param mixed $result * * @return JsonResponse */ protected function ajaxResponse($result) { return response()->json($result); } }
Add additinonalFields support to GetServices
'use strict'; angular.module('adagios.live') .constant('filterSuffixes', { contains: '__contains', has_fields: '__has_field', startswith: '__startswith', endswith: '__endswith', exists: '__exists', in: '__in', isnot: '__isnot', regex: '__regex' }) .factory('getServices', ['$http', 'filterSuffixes', function ($http, filterSuffixes) { return function (columns, filters, apiName, additionnalFields) { var filtersQuery = '', additionnalQuery = ''; function createFiltersQuery(filters) { var builtQuery = ''; angular.forEach(filters, function (value, key) { var filterType = filterSuffixes[key]; angular.forEach(value, function (fieldValues, fieldName) { var filter = fieldName + filterType; angular.forEach(fieldValues, function (_value) { var filterQuery = '&' + filter + '=' + _value; builtQuery += filterQuery; }); }); }); return builtQuery; } function createAdditionnalQuery(additionnalFields) { var query = ''; angular.forEach(additionnalFields, function (value, key) { query += '&' + key + '=' + value; }); return query; } filtersQuery = createFiltersQuery(filters); additionnalQuery = createAdditionnalQuery(additionnalFields); return $http.get('/rest/status/json/' + apiName + '/?fields=' + columns + filtersQuery + additionnalQuery) .error(function () { throw new Error('getServices : GET Request failed'); }); }; }]);
'use strict'; angular.module('adagios.live') .constant('filterSuffixes', { contains: '__contains', has_fields: '__has_field', startswith: '__startswith', endswith: '__endswith', exists: '__exists', in: '__in', isnot: '__isnot', regex: '__regex' }) .factory('getServices', ['$http', 'filterSuffixes', function ($http, filterSuffixes) { return function (columns, filters, apiName) { var filtersQuery = ''; function createFiltersQuery(filters) { var builtQuery = ''; angular.forEach(filters, function (value, key) { var filterType = filterSuffixes[key]; angular.forEach(value, function (fieldValues, fieldName) { var filter = fieldName + filterType; angular.forEach(fieldValues, function (_value) { var filterQuery = '&' + filter + '=' + _value; builtQuery += filterQuery; }); }); }); return builtQuery; } filtersQuery = createFiltersQuery(filters); return $http.get('/rest/status/json/' + apiName + '/?fields=' + columns + filtersQuery) .error(function () { throw new Error('getServices : GET Request failed'); }); }; }]);
Fix watchify by enabling poll option https://github.com/substack/watchify/issues/216#issuecomment-104284044
var browserify = require('browserify'); var watchify = require('watchify'); var gulp = require('gulp'); var gutil = require('gulp-util'); var source = require('vinyl-source-stream'); var reactify = require('reactify'); function bundle(b) { gutil.log('Retranspiling source code'); return b.bundle() .pipe(source('main.js')) .pipe(gulp.dest('./dist')); } function act(watch) { var b = browserify({ debug: true, cache: {}, packageCache: {}, fullPaths: true }); if (watch) { b = watchify(b, { poll: true }); } b.transform(function(file) { return reactify(file, { harmony: true }); }); if (watch) { b.on('update', function(ids) { gutil.log('Updated files:'); gutil.log(ids.join(',')); bundle(b); }); b.on('log', function(msg) { gutil.log(msg); }); b.on('time', function(time) { gutil.log('Finished in ' + time + 'ms'); }); } b.add('./main.js'); bundle(b); } gulp.task('watchify', function() { act(true); }); gulp.task('browserify', function() { act(false); });
var browserify = require('browserify'); var watchify = require('watchify'); var gulp = require('gulp'); var gutil = require('gulp-util'); var source = require('vinyl-source-stream'); var reactify = require('reactify'); function bundle(b) { gutil.log('Retranspiling source code'); return b.bundle() .pipe(source('main.js')) .pipe(gulp.dest('./dist')); } function act(watch) { var b = browserify({ debug: true, cache: {}, packageCache: {}, fullPaths: true }); if (watch) { b = watchify(b); } b.transform(function(file) { return reactify(file, { harmony: true }); }); if (watch) { b.on('update', function(ids) { gutil.log('Updated files:'); gutil.log(ids.join(',')); bundle(b); }); b.on('log', function(msg) { gutil.log(msg); }); b.on('time', function(time) { gutil.log('Finished in ' + time + 'ms'); }); } b.add('./main.js'); bundle(b); } gulp.task('watchify', function() { act(true); }); gulp.task('browserify', function() { act(false); });
Check for input to be array
/** * Created by sandeshkumar on 4/5/16. */ function flattenArray(arr) { if(Array.isArray(arr)) { //return flatIterative(arr); //return flatRecursive(arr, []); return flatFunctional(arr); } return false; } function flatRecursive(arr, arr2) { var flattenedArr = arr2; for( var i = 0; i < arr.length; i++) { var el = arr[i]; var items = Array.isArray(el) ? flatRecursive(el, flattenedArr): el; if(!Array.isArray(el)) { flattenedArr.push(el); } } return flattenedArr; } function flatIterative(arr) { var flat = []; for (var i = 0; i < arr.length; i++) { var el = arr[i]; if(Array.isArray(el)) { for(var j = 0; j < el.length; j++) { var elm = el[j]; flat.push(elm); } } else { flat.push(el); } } return flat; } function flatFunctional(arr) { var flattened = arr.reduce(function(memo, el) { return memo.concat(el); }, []); return flattened; }
/** * Created by sandeshkumar on 4/5/16. */ function flattenArray(arr) { if(Array.isArray(arr)) { //return flatIterative(arr); //return flatRecursive(arr, []); return flatFunctional(arr); } return []; } function flatRecursive(arr, arr2) { var flattenedArr = arr2; for( var i = 0; i < arr.length; i++) { var el = arr[i]; var items = Array.isArray(el) ? flatRecursive(el, flattenedArr): el; if(!Array.isArray(el)) { flattenedArr.push(el); } } return flattenedArr; } function flatIterative(arr) { var flat = []; for (var i = 0; i < arr.length; i++) { var el = arr[i]; if(Array.isArray(el)) { for(var j = 0; j < el.length; j++) { var elm = el[j]; flat.push(elm); } } else { flat.push(el); } } return flat; } function flatFunctional(arr) { var flattened = arr.reduce(function(memo, el) { return memo.concat(el); }, []); return flattened; }
Make sure we don't expose translator as global
import six from autotranslate.compat import importlib from django.conf import settings def perform_import(val, setting_name): """ If the given setting is a string import notation, then perform the necessary import or imports. Credits: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/settings.py#L138 """ if val is None: return None elif isinstance(val, six.string_types): return import_from_string(val, setting_name) elif isinstance(val, (list, tuple)): return [import_from_string(item, setting_name) for item in val] return val def import_from_string(val, setting_name): """ Attempt to import a class from a string representation. """ try: parts = val.split('.') module_path, class_name = '.'.join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) as e: raise ImportError('Could not import {} for API setting {}. {}: {}.' .format(val, setting_name, e.__class__.__name__, e)) def get_translator(): """ Returns the default translator. """ TranslatorService = getattr(settings, 'AUTOTRANSLATE_TRANSLATOR_SERVICE', 'autotranslate.services.GoSlateTranslatorService') translator = perform_import(TranslatorService, 'AUTOTRANSLATE_TRANSLATOR_SERVICE')() return translator
import six from autotranslate.compat import importlib from django.conf import settings def perform_import(val, setting_name): """ If the given setting is a string import notation, then perform the necessary import or imports. Credits: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/settings.py#L138 """ if val is None: return None elif isinstance(val, six.string_types): return import_from_string(val, setting_name) elif isinstance(val, (list, tuple)): return [import_from_string(item, setting_name) for item in val] return val def import_from_string(val, setting_name): """ Attempt to import a class from a string representation. """ try: parts = val.split('.') module_path, class_name = '.'.join(parts[:-1]), parts[-1] module = importlib.import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) as e: raise ImportError('Could not import {} for API setting {}. {}: {}.' .format(val, setting_name, e.__class__.__name__, e)) TranslatorService = getattr(settings, 'AUTOTRANSLATE_TRANSLATOR_SERVICE', 'autotranslate.services.GoSlateTranslatorService') translator = perform_import(TranslatorService, 'AUTOTRANSLATE_TRANSLATOR_SERVICE')() translate_string = translator.translate_string translate_strings = translator.translate_strings
Change display from updatedAt.toDateString to pushedAt.toTimeString
import React from 'react'; import GithubAPI from '../../api/githubAPI'; class HomePage extends React.Component { constructor(props, context) { super(props, context); this.state = { showResult: "l" }; this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this); } invokeGitHubAPI(){ GithubAPI.testOctokat().then(testResult => { let parsedTestResult = testResult.pushedAt.toTimeString(); console.log(testResult); console.log(parsedTestResult); this.setState({showResult: parsedTestResult}); }).catch(error => { throw(error); }); } render() { return ( <div> <h1>GitHub Status API GUI</h1> <h3>Open browser console to see JSON data returned from GitHub API</h3> <div className="row"> <div className="col-sm-3"> <button type="button" className="btn btn-primary" onClick={this.invokeGitHubAPI}>Test GitHub API Call</button> </div> </div> <div className="row"> <div className="col-sm-6"> <span>{this.state.showResult}</span> </div> </div> </div> ); } } export default HomePage;
import React from 'react'; import GithubAPI from '../../api/githubAPI'; class HomePage extends React.Component { constructor(props, context) { super(props, context); this.state = { showResult: "l" }; this.invokeGitHubAPI = this.invokeGitHubAPI.bind(this); } invokeGitHubAPI(){ GithubAPI.testOctokat().then(testResult => { let parsedTestResult = testResult.updatedAt.toDateString(); console.log(testResult); console.log(parsedTestResult); this.setState({showResult: parsedTestResult}); }).catch(error => { throw(error); }); } render() { return ( <div> <h1>GitHub Status API GUI</h1> <h3>Open browser console to see JSON data returned from GitHub API</h3> <div className="row"> <div className="col-sm-3"> <button type="button" className="btn btn-primary" onClick={this.invokeGitHubAPI}>Test GitHub API Call</button> </div> </div> <div className="row"> <div className="col-sm-6"> <span>{this.state.showResult}</span> </div> </div> </div> ); } } export default HomePage;
Comment the code that duplicates the files
'use strict'; var pkg = require('./package'); var gutil = require('gulp-util'); var through = require('through2'); var path = require('path'); var File = require('vinyl'); // consts module.exports = function(out, options) { options = options || {}; var files = []; var fileList = []; return through.obj(function(file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new gutil.PluginError(pkg.name, 'Streams not supported')); return; } files.push(file); var filePath; if (options.absolute) { filePath = path.normalize(file.path); } else if (options.flatten) { filePath = path.basename(file.path); } else { filePath = path.relative(process.cwd(), file.path); } if (options.removeExtensions) { var extension = path.extname(filePath); if (extension.length) { filePath = filePath.slice(0, -extension.length); } } filePath = filePath.replace(/\\/g, '/'); fileList.push(filePath); // this.push(file); cb(); }, function(cb) { var fileListFile = new File({ path: out, contents: new Buffer(JSON.stringify(fileList, null, ' ')) }); this.push(fileListFile); cb(); }); };
'use strict'; var pkg = require('./package'); var gutil = require('gulp-util'); var through = require('through2'); var path = require('path'); var File = require('vinyl'); // consts module.exports = function(out, options) { options = options || {}; var files = []; var fileList = []; return through.obj(function(file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new gutil.PluginError(pkg.name, 'Streams not supported')); return; } files.push(file); var filePath; if (options.absolute) { filePath = path.normalize(file.path); } else if (options.flatten) { filePath = path.basename(file.path); } else { filePath = path.relative(process.cwd(), file.path); } if (options.removeExtensions) { var extension = path.extname(filePath); if (extension.length) { filePath = filePath.slice(0, -extension.length); } } filePath = filePath.replace(/\\/g, '/'); fileList.push(filePath); this.push(file); cb(); }, function(cb) { var fileListFile = new File({ path: out, contents: new Buffer(JSON.stringify(fileList, null, ' ')) }); this.push(fileListFile); cb(); }); };
Make sure the paradrop.pdlog retry when the log file does not exist
import sys import argparse import json import urllib import subprocess from time import sleep LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log" def parseLine(line): try: data = json.loads(line) msg = urllib.unquote(data['message']) print(msg) except: pass def runTail(logFile): cmd = ['tail', '-n', '100', '-f', LOG_FILE] while (True): try: proc = subprocess.Popen(cmd, \ stdout=subprocess.PIPE, \ universal_newlines=True) for line in iter(proc.stdout.readline, ''): yield line proc.stdout.close() proc.wait() except subprocess.CalledProcessError: print 'Failed to open the log file, will try again...' sleep(2) continue def main(): p = argparse.ArgumentParser(description='Paradrop log tool') p.add_argument('-f', help='Wait for additional data to be appended to the log file when end of file is reached', action='store_true', dest='f') args = p.parse_args() try: if args.f: for line in runTail(LOG_FILE): parseLine(line) else: with open(LOG_FILE, "r") as inputFile: for line in inputFile: parseLine(line) except KeyboardInterrupt: sys.exit(0) if __name__ == "__main__": main()
import sys import argparse import json import urllib import subprocess LOG_FILE = "/var/snap/paradrop-daemon/common/logs/log" def parseLine(line): try: data = json.loads(line) msg = urllib.unquote(data['message']) print(msg) except: pass def runTail(logFile): cmd = ['tail', '-n', '100', '-f', LOG_FILE] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True) for line in iter(proc.stdout.readline, ''): yield line proc.stdout.close() return_code = proc.wait() if return_code: raise subprocess.CalledProcessError(return_code, cmd) def main(): p = argparse.ArgumentParser(description='Paradrop log tool') p.add_argument('-f', help='Wait for additional data to be appended to the log file when end of file is reached', action='store_true', dest='f') args = p.parse_args() try: if args.f: for line in runTail(LOG_FILE): parseLine(line) else: with open(LOG_FILE, "r") as inputFile: for line in inputFile: parseLine(line) except KeyboardInterrupt: sys.exit(0) if __name__ == "__main__": main()
[master] Add a grunt dev task for css only, without js
'use strict()'; var config= { port: 3000 }; module.exports = function(grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); var options = { config: { src: './grunt/*.js' }, pkg: grunt.file.readJSON('package.json') }; var configs = require('load-grunt-configs')(grunt, options); // Project configuration. grunt.initConfig(configs); // load jshint grunt.registerTask('lint', [ 'jshint' ]); grunt.registerTask('devcss', [ 'compass:dev', 'postcss' ]); grunt.registerTask('devfull', [ 'compass:dev', 'postcss', 'copy:modernizr', 'copy:jqueryDev', 'copy:revolutionSliderStyle', 'copy:revolutionSliderAssets', 'copy:allDev', 'uglify:revolutionSlider' ]); grunt.registerTask('prod', [ 'compass:prod', 'postcss', 'copy:jqueryProd', 'copy:revolutionSliderStyle', 'copy:revolutionSliderAssets', 'uglify:revolutionSlider', 'uglify:prod' ]); // default option to connect server grunt.registerTask('serve', [ 'jshint', 'concurrent:dev' ]); grunt.registerTask('server', function () { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run(['serve:' + target]); }); };
'use strict()'; var config= { port: 3000 }; module.exports = function(grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); var options = { config: { src: './grunt/*.js' }, pkg: grunt.file.readJSON('package.json') }; var configs = require('load-grunt-configs')(grunt, options); // Project configuration. grunt.initConfig(configs); // load jshint grunt.registerTask('lint', [ 'jshint' ]); grunt.registerTask('dev', [ 'compass:dev', 'postcss', 'copy:modernizr', 'copy:jqueryDev', 'copy:revolutionSliderStyle', 'copy:revolutionSliderAssets', 'copy:allDev', 'uglify:revolutionSlider' ]); grunt.registerTask('prod', [ 'compass:prod', 'postcss', 'copy:jqueryProd', 'copy:revolutionSliderStyle', 'copy:revolutionSliderAssets', 'uglify:revolutionSlider', 'uglify:prod' ]); // default option to connect server grunt.registerTask('serve', [ 'jshint', 'concurrent:dev' ]); grunt.registerTask('server', function () { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run(['serve:' + target]); }); };
Change task name (plato -> analyze)
var gulp = require('gulp'); var ts = require('gulp-typescript'); var tslint = require('gulp-tslint'); var jade = require('gulp-jade'); var plato = require('gulp-plato'); var espower = require('gulp-espower'); var karma = require('karma').server; gulp.task('jade', function () { return gulp.src('./src/views/*.jade') .pipe(jade()) .pipe(gulp.dest('./dist/')); }); gulp.task('typescript', function () { return gulp.src('./src/scripts/**/*.ts') .pipe(tslint()) .pipe(tslint.report('verbose')) .pipe(ts({ declarationFiles: true, target: 'es5' }) .pipe(gulp.dest('./dist/scripts/'))); }); // Generate complexity analysis reports gulp.task('analyze', function () { return gulp.src('./dist/scripts/*.js') .pipe(plato('./report', { jshint: { options: { strict: true } }, complexity: { trycatch: true } })); }); gulp.task('test', function (done) { gulp.src('./test/scripts/*.js') .pipe(espower()) .pipe(gulp.dest('./test/scripts/espower')); return karma.start({ configFile: __dirname + '/karma.conf.js', singleRun: true }, done); }); gulp.task('default', function () { });
var gulp = require('gulp'); var ts = require('gulp-typescript'); var tslint = require('gulp-tslint'); var jade = require('gulp-jade'); var plato = require('gulp-plato'); var espower = require('gulp-espower'); var karma = require('karma').server; gulp.task('jade', function () { return gulp.src('./src/views/*.jade') .pipe(jade()) .pipe(gulp.dest('./dist/')); }); gulp.task('typescript', function () { return gulp.src('./src/scripts/**/*.ts') .pipe(tslint()) .pipe(tslint.report('verbose')) .pipe(ts({ declarationFiles: true, target: 'es5' }) .pipe(gulp.dest('./dist/scripts/'))); }); gulp.task('plato', function () { return gulp.src('./dist/scripts/*.js') .pipe(plato('./report', { jshint: { options: { strict: true } }, complexity: { trycatch: true } })); }); gulp.task('test', function (done) { gulp.src('./test/scripts/*.js') .pipe(espower()) .pipe(gulp.dest('./test/scripts/espower')); return karma.start({ configFile: __dirname + '/karma.conf.js', singleRun: true }, done); }); gulp.task('default', function () { });
Allow Django Evolution to install along with Django >= 1.7. As we're working toward some degree of compatibility with newer versions of Django, we need to ease up on the version restriction. Now's a good time to do so. Django Evolution no longer has an upper bounds on the version range.
#!/usr/bin/env python # # Setup script for Django Evolution from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test from django_evolution import get_package_version, VERSION def run_tests(*args): import os os.system('tests/runtests.py') test.run_tests = run_tests PACKAGE_NAME = 'django_evolution' download_url = ( 'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' % (VERSION[0], VERSION[1])) # Build the package setup( name=PACKAGE_NAME, version=get_package_version(), description='A database schema evolution tool for the Django web framework.', url='http://code.google.com/p/django-evolution/', author='Ben Khoo', author_email='[email protected]', maintainer='Christian Hammond', maintainer_email='[email protected]', download_url=download_url, packages=find_packages(exclude=['tests']), install_requires=[ 'Django>=1.4.10', ], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
#!/usr/bin/env python # # Setup script for Django Evolution from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages from setuptools.command.test import test from django_evolution import get_package_version, VERSION def run_tests(*args): import os os.system('tests/runtests.py') test.run_tests = run_tests PACKAGE_NAME = 'django_evolution' download_url = ( 'http://downloads.reviewboard.org/releases/django-evolution/%s.%s/' % (VERSION[0], VERSION[1])) # Build the package setup( name=PACKAGE_NAME, version=get_package_version(), description='A database schema evolution tool for the Django web framework.', url='http://code.google.com/p/django-evolution/', author='Ben Khoo', author_email='[email protected]', maintainer='Christian Hammond', maintainer_email='[email protected]', download_url=download_url, packages=find_packages(exclude=['tests']), install_requires=[ 'Django>=1.4.10,<1.7.0', ], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Python Modules', ] )
Make dependency check more stringent
from setuptools import setup from subprocess import check_output, CalledProcessError try: num_gpus = len(check_output(['nvidia-smi', '--query-gpu=gpu_name', '--format=csv']).decode().strip().split('\n')) tf = 'tensorflow-gpu' if num_gpus > 1 else 'tensorflow' except CalledProcessError: tf = 'tensorflow>=1.0.0' except FileNotFoundError: tf = 'tensorflow>=1.0.0' setup( name='autoencoder', version='0.1', description='An autoencoder implementation', author='Gokcen Eraslan', author_email="[email protected]", packages=['autoencoder'], install_requires=[tf, 'numpy>=1.7', 'keras>=1.2.2', 'six>=1.10.0', 'scikit-learn', 'pandas' #for preprocessing ], url='https://github.com/gokceneraslan/autoencoder', entry_points={ 'console_scripts': [ 'autoencoder = autoencoder.__main__:main' ]}, license='Apache License 2.0', classifiers=['License :: OSI Approved :: Apache Software License', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5'], )
from setuptools import setup from subprocess import check_output, CalledProcessError try: num_gpus = len(check_output(['nvidia-smi', '--query-gpu=gpu_name', '--format=csv']).decode().strip().split('\n')) tf = 'tensorflow-gpu' if num_gpus > 1 else 'tensorflow' except CalledProcessError: tf = 'tensorflow' except FileNotFoundError: tf = 'tensorflow' setup( name='autoencoder', version='0.1', description='An autoencoder implementation', author='Gokcen Eraslan', author_email="[email protected]", packages=['autoencoder'], install_requires=[tf, 'numpy>=1.7', 'keras>=1.2', 'six>=1.10.0', 'scikit-learn', 'pandas' #for preprocessing ], url='https://github.com/gokceneraslan/autoencoder', entry_points={ 'console_scripts': [ 'autoencoder = autoencoder.__main__:main' ]}, license='Apache License 2.0', classifiers=['License :: OSI Approved :: Apache Software License', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5'], )
Convert Eloquent models to entities when performing an action
<?php namespace Nwidart\Modules\Repositories; use Nwidart\Modules\Exceptions\Repositories\ActionFailed; use Nwidart\Modules\Exceptions\Repositories\NoRecordsFound; trait PerformsActions { /** * Validate a database action such as create, update, or delete. * * @param string $action * @param mixed $result */ protected function validateAction(string $action, $result) { if (! is_array($result)) { return; } // Action result instance is invalid if (count($result) > 1 && is_null($result[1])) { throw NoRecordsFound::emptyResult(); } // Action itself failed to make any changes if ($result[0] === false) { throw ActionFailed::create($action); } } /** * Get the actual record from the action result. * * @param mixed $result * @param string|null $action * * @return mixed */ protected function extractActionResult($result, $action = null) { if ($action == 'delete') { return $result[0]; } return $result[1]; } /** * Perform a database action. * * @param string $action * @param array $parameters * * @return mixed */ protected function performAction(string $action, ...$parameters) { $result = parent::$action(...$parameters); $this->validateAction($action, $result); $result = $this->extractActionResult($result, $action); return $this->convertToEntityResult($result); } }
<?php namespace Nwidart\Modules\Repositories; use Nwidart\Modules\Exceptions\Repositories\ActionFailed; use Nwidart\Modules\Exceptions\Repositories\NoRecordsFound; trait PerformsActions { /** * Validate a database action such as create, update, or delete. * * @param string $action * @param mixed $result */ protected function validateAction(string $action, $result) { if (! is_array($result)) { return; } // Action result instance is invalid if (count($result) > 1 && is_null($result[1])) { throw NoRecordsFound::emptyResult(); } // Action itself failed to make any changes if ($result[0] === false) { throw ActionFailed::create($action); } } /** * Get the actual record from the action result. * * @param mixed $result * @param string|null $action * * @return mixed */ protected function extractActionResult($result, $action = null) { if ($action == 'delete') { return $result[0]; } return $result[1]; } /** * Perform a database action. * * @param string $action * @param array $parameters * * @return mixed */ protected function performAction(string $action, ...$parameters) { $result = parent::$action(...$parameters); $this->validateAction($action, $result); return $this->extractActionResult($result, $action); } }
Fix being able to put bank item in bank
package me.eddiep.minecraft.ls.game.shop.impl; import me.eddiep.minecraft.ls.Lavasurvival; import me.eddiep.minecraft.ls.game.shop.Shop; import me.eddiep.minecraft.ls.game.shop.ShopManager; import me.eddiep.minecraft.ls.ranks.UserInfo; import me.eddiep.minecraft.ls.ranks.UserManager; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; public class BankShopManager implements ShopManager { @Override public void shopClicked(Player owner, Shop shop) { UserManager um = Lavasurvival.INSTANCE.getUserManager(); UserInfo user = um.getUser(owner.getUniqueId()); Inventory bankInventory = user.createBankInventory(); owner.openInventory(bankInventory); } @Override public boolean isShopInventory(Inventory inventory, Player owner) { return inventory.getTitle().equals("Bank"); } @Override public void shopClosed(Player owner, Inventory inventory, Shop shop) { if (inventory.contains(shop.getOpener())) { inventory.remove(shop.getOpener()); inventory.setItem(owner.getInventory().firstEmpty(), shop.getOpener()); } UserManager um = Lavasurvival.INSTANCE.getUserManager(); UserInfo user = um.getUser(owner.getUniqueId()); user.saveBank(inventory); } }
package me.eddiep.minecraft.ls.game.shop.impl; import me.eddiep.minecraft.ls.Lavasurvival; import me.eddiep.minecraft.ls.game.shop.Shop; import me.eddiep.minecraft.ls.game.shop.ShopManager; import me.eddiep.minecraft.ls.ranks.UserInfo; import me.eddiep.minecraft.ls.ranks.UserManager; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; public class BankShopManager implements ShopManager { @Override public void shopClicked(Player owner, Shop shop) { UserManager um = Lavasurvival.INSTANCE.getUserManager(); UserInfo user = um.getUser(owner.getUniqueId()); Inventory bankInventory = user.createBankInventory(); owner.openInventory(bankInventory); } @Override public boolean isShopInventory(Inventory inventory, Player owner) { return inventory.getTitle().equals("Bank"); } @Override public void shopClosed(Player owner, Inventory inventory, Shop shop) { if (inventory.contains(shop.getOpener())) { inventory.remove(shop.getOpener()); inventory.setItem(inventory.firstEmpty(), shop.getOpener()); } UserManager um = Lavasurvival.INSTANCE.getUserManager(); UserInfo user = um.getUser(owner.getUniqueId()); user.saveBank(inventory); } }
Remove old thing in gtu search map
<?php echo '<?xml version="1.0" encoding="UTF-8"?>';?> <kml xmlns="http://earth.google.com/kml/2.0"> <Document> <?php foreach($items as $item):?> <Placemark> <name><?php echo $item->getCode();?></name> <description><![CDATA[ <div class="map_result_id_<?php echo $item->getId();?>"> <div class="item_name hidden"><?php echo $item->getTagsWithCode(ESC_RAW);?></div> <div class=""><?php echo $item->getName(ESC_RAW);?></div> <?php if(! $is_choose):?> <?php echo link_to(image_tag('edit.png',array('title' => 'Edit')),'gtu/edit?id='.$item->getId());?> <?php echo link_to(image_tag('duplicate.png',array('title' => 'Duplicate')),'gtu/new?duplicate_id='.$item->getId());?> <?php else:?> <div class="result_choose" onclick="chooseGtuInMap(<?php echo $item->getId();?>);"><?php echo __('Choose');?></div> <?php endif;?> </div> ]]></description> <?php echo $item->getKml(ESC_RAW);?> </Placemark> <?php endforeach;?> </Document> </kml>
<?php echo '<?xml version="1.0" encoding="UTF-8"?>';?> <kml xmlns="http://earth.google.com/kml/2.0"> <Document> <?php foreach($items as $item):?> <Placemark> <name><?php echo count( $items);?>-<?php echo $item->getCode();?></name> <description><![CDATA[ <div class="map_result_id_<?php echo $item->getId();?>"> <div class="item_name hidden"><?php echo $item->getTagsWithCode(ESC_RAW);?></div> <div class=""><?php echo $item->getName(ESC_RAW);?></div> <?php if(! $is_choose):?> <?php echo link_to(image_tag('edit.png',array('title' => 'Edit')),'gtu/edit?id='.$item->getId());?> <?php echo link_to(image_tag('duplicate.png',array('title' => 'Duplicate')),'gtu/new?duplicate_id='.$item->getId());?> <?php else:?> <div class="result_choose" onclick="chooseGtuInMap(<?php echo $item->getId();?>);"><?php echo __('Choose');?></div> <?php endif;?> </div> ]]></description> <?php echo $item->getKml(ESC_RAW);?> </Placemark> <?php endforeach;?> </Document> </kml>
Add parent ID validation rule.
<?php namespace common\models\comments; use yii\base\Exception; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; use yii\behaviors\BlameableBehavior; abstract class Comment extends ActiveRecord { public static function commentClassName() { return AdjacencyListComment::className(); } public static function instantiate($row) { $className = static::commentClassName(); return new $className(); } /** * @param mixed[] $config * @return Comment */ public static function create($config = []) { $className = static::commentClassName(); return new $className($config); } /** * @inheritdoc */ public function behaviors() { return [ TimestampBehavior::className(), ['class' => BlameableBehavior::className(), 'createdByAttribute' => 'author_id', 'updatedByAttribute' => false], ]; } public function rules() { return [ ['text', 'filter', 'filter' => 'trim'], ['text', 'required'], ['text', 'string', 'min' => 5, 'max' => 10000], ['parent_id', 'required'], ['parent_id', 'exist', 'targetAttribute' => 'id'], ]; } public static function findByPostInternal($postId) { throw new Exception('Method is not implemented'); } public static function findByPost($postId) { return call_user_func([static::commentClassName(), 'findByPostInternal'], $postId); } }
<?php namespace common\models\comments; use yii\base\Exception; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; use yii\behaviors\BlameableBehavior; abstract class Comment extends ActiveRecord { public static function commentClassName() { return AdjacencyListComment::className(); } public static function instantiate($row) { $className = static::commentClassName(); return new $className(); } /** * @param mixed[] $config * @return Comment */ public static function create($config = []) { $className = static::commentClassName(); return new $className($config); } /** * @inheritdoc */ public function behaviors() { return [ TimestampBehavior::className(), ['class' => BlameableBehavior::className(), 'createdByAttribute' => 'author_id', 'updatedByAttribute' => false], ]; } public function rules() { return [ ['text', 'filter', 'filter' => 'trim'], ['text', 'required'], ['text', 'string', 'min' => 5, 'max' => 10000], ]; } public static function findByPostInternal($postId) { throw new Exception('Method is not implemented'); } public static function findByPost($postId) { return call_user_func([static::commentClassName(), 'findByPostInternal'], $postId); } }
Use correct Provider interface for global components
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.rpc.security; import com.google.inject.Inject; import com.yahoo.cloud.config.ConfigserverConfig; import com.yahoo.config.provision.security.NodeIdentifier; import com.yahoo.container.di.componentgraph.Provider; import com.yahoo.security.tls.TransportSecurityUtils; import com.yahoo.vespa.config.server.host.HostRegistries; import com.yahoo.vespa.config.server.rpc.RequestHandlerProvider; /** * A provider for {@link RpcAuthorizer}. The instance provided is dependent on the configuration of the configserver. * * @author bjorncs */ public class DefaultRpcAuthorizerProvider implements Provider<RpcAuthorizer> { private final RpcAuthorizer rpcAuthorizer; @Inject public DefaultRpcAuthorizerProvider(ConfigserverConfig config, NodeIdentifier nodeIdentifier, HostRegistries hostRegistries, RequestHandlerProvider handlerProvider) { this.rpcAuthorizer = TransportSecurityUtils.isTransportSecurityEnabled() && config.multitenant() ? new MultiTenantRpcAuthorizer(nodeIdentifier, hostRegistries, handlerProvider) : new NoopRpcAuthorizer(); } @Override public RpcAuthorizer get() { return rpcAuthorizer; } @Override public void deconstruct() {} }
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server.rpc.security; import com.google.inject.Inject; import com.google.inject.Provider; import com.yahoo.cloud.config.ConfigserverConfig; import com.yahoo.config.provision.security.NodeIdentifier; import com.yahoo.security.tls.TransportSecurityUtils; import com.yahoo.vespa.config.server.host.HostRegistries; import com.yahoo.vespa.config.server.rpc.RequestHandlerProvider; /** * A provider for {@link RpcAuthorizer}. The instance provided is dependent on the configuration of the configserver. * * @author bjorncs */ public class DefaultRpcAuthorizerProvider implements Provider<RpcAuthorizer> { private final RpcAuthorizer rpcAuthorizer; @Inject public DefaultRpcAuthorizerProvider(ConfigserverConfig config, NodeIdentifier nodeIdentifier, HostRegistries hostRegistries, RequestHandlerProvider handlerProvider) { this.rpcAuthorizer = TransportSecurityUtils.isTransportSecurityEnabled() && config.multitenant() ? new MultiTenantRpcAuthorizer(nodeIdentifier, hostRegistries, handlerProvider) : new NoopRpcAuthorizer(); } @Override public RpcAuthorizer get() { return rpcAuthorizer; } }
Add Jake's name to top of file
import pygame #WRITEN BY JACOB PANIKULAM class Text_Box(object): '''Text_Box() You never have to initialize this! Just call Text_Box.draw(display, pos, color, text) It draws the same way a pygame primitive would. ''' pygame.font.init() font = pygame.font.SysFont("monospace", 15) @classmethod def draw(self, display, pos=(0, 0), color=(255, 255, 255), text="Empty!"): ''' draw(display, pos=(0, 0), color=(255, 255, 255), text="Empty!"): pos: In pygame coordinates color: [0, 255] text: Can by multiline, of arbitrary length To change text during operation, use the "set_text method" Ex: >>> tb = Text_Box() >>> tb.draw(display, text='hello') or in a draw loop, >>> tb.draw(display, pos, color, text) ''' lines = text.splitlines() width = height = 0 for l in lines: width = max(width, self.font.size(l)[0]) height += self.font.get_linesize() height = 0 for l in lines: t = self.font.render(l, 0, color) display.blit( t, (pos[0], pos[1] + height) ) height += self.font.get_linesize()
import pygame class Text_Box(object): '''Text_Box() You never have to initialize this! Just call Text_Box.draw(display, pos, color, text) It draws the same way a pygame primitive would. ''' pygame.font.init() font = pygame.font.SysFont("monospace", 15) @classmethod def draw(self, display, pos=(0, 0), color=(255, 255, 255), text="Empty!"): ''' draw(display, pos=(0, 0), color=(255, 255, 255), text="Empty!"): pos: In pygame coordinates color: [0, 255] text: Can by multiline, of arbitrary length To change text during operation, use the "set_text method" Ex: >>> tb = Text_Box() >>> tb.draw(display, text='hello') or in a draw loop, >>> tb.draw(display, pos, color, text) ''' lines = text.splitlines() width = height = 0 for l in lines: width = max(width, self.font.size(l)[0]) height += self.font.get_linesize() height = 0 for l in lines: t = self.font.render(l, 0, color) display.blit( t, (pos[0], pos[1] + height) ) height += self.font.get_linesize()
Remove @package & restart travis
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Form\TestAsset; use DomainException; use Zend\Stdlib\ArraySerializableInterface; /** * @category Zend * @package Zend_Form * @subpackage UnitTest */ class Model implements ArraySerializableInterface { protected $foo; protected $bar; protected $foobar; public function __set($name, $value) { throw new DomainException('Overloading to set values is not allowed'); } public function __get($name) { if (property_exists($this, $name)) { return $this->$name; } throw new DomainException('Unknown attribute'); } public function exchangeArray(array $array) { foreach ($array as $key => $value) { if (!property_exists($this, $key)) { continue; } $this->$key = $value; } } public function getArrayCopy() { return array( 'foo' => $this->foo, 'bar' => $this->bar, 'foobar' => $this->foobar, ); } }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @package Zend_Form */ namespace ZendTest\Form\TestAsset; use DomainException; use Zend\Stdlib\ArraySerializableInterface; /** * @category Zend * @package Zend_Form * @subpackage UnitTest */ class Model implements ArraySerializableInterface { protected $foo; protected $bar; protected $foobar; public function __set($name, $value) { throw new DomainException('Overloading to set values is not allowed'); } public function __get($name) { if (property_exists($this, $name)) { return $this->$name; } throw new DomainException('Unknown attribute'); } public function exchangeArray(array $array) { foreach ($array as $key => $value) { if (!property_exists($this, $key)) { continue; } $this->$key = $value; } } public function getArrayCopy() { return array( 'foo' => $this->foo, 'bar' => $this->bar, 'foobar' => $this->foobar, ); } }
Add refresh to trades view.
"use strict"; (function () { angular .module("argo") .factory("streamService", streamService); streamService.$inject = ["ngSocket", "quotesService", "activityService", "tradesService"]; function streamService(ngSocket, quotesService, activityService, tradesService) { var service = { getStream: getStream }; return service; function getStream() { var ws = ngSocket("ws://localhost:8000/stream"); ws.onMessage(function (event) { var data, tick, transaction; try { data = angular.fromJson(event.data); tick = data.tick; transaction = data.transaction; if (tick) { quotesService.updateTick(tick); tradesService.updateTrades(tick); } if (transaction) { activityService.addActivity(transaction); tradesService.refresh(); } } catch (e) { // Discard "incomplete" json } }); } } }());
"use strict"; (function () { angular .module("argo") .factory("tradesService", tradesService); tradesService.$inject = ["$http", "$q", "sessionService"]; function tradesService($http, $q, sessionService) { var trades = [], service = { getTrades: getTrades, closeTrade: closeTrade, updateTrades: updateTrades }; return service; function getTrades() { sessionService.isLogged().then(function (credentials) { $http.post("/api/trades", { environment: credentials.environment, token: credentials.token, accountId: credentials.accountId }).then(function (res) { trades.length = 0; angular.extend(trades, res.data); }); }); return trades; } function closeTrade(id) { var deferred = $q.defer(); sessionService.isLogged().then(function (credentials) { $http.post("/api/closetrade", { environment: credentials.environment, token: credentials.token, accountId: credentials.accountId, id: id }).then(function (order) { deferred.resolve(order.data); }); }); return deferred.promise; } function updateTrades(tick) { trades.forEach(function (trade, index) { var current; if (trade.instrument === tick.instrument) { if (trade.side === "buy") { current = tick.bid; trades[index].profitPips = ((current - trade.price) / getPips(trade.price)); } if (trade.side === "sell") { current = tick.ask; trades[index].profitPips = ((trade.price - current) / getPips(trade.price)); } trades[index].current = current; } }); } function getPips(n) { var decimals = n.toString().split("."), nDecimals = decimals[1].length, pips = 1 / Math.pow(10, nDecimals - 1); return pips; } } }());
Check UUID column is empty If the UUID column has already been populated when creating the model, the package should not attempt to overwrite it. This takes into consideration JSON API-compatible APIs, which allows for client-generated IDs.
<?php namespace Emadadly\LaravelUuid; use Ramsey\Uuid\Uuid; use Illuminate\Database\Eloquent\ModelNotFoundException; trait Uuids { /** * Boot function from laravel. */ protected static function boot() { parent::boot(); static::creating(function ($model) { if (!$model->{config('uuid.default_uuid_column')}) { $model->{config('uuid.default_uuid_column')} = strtoupper(Uuid::uuid4()->toString()); } }); static::saving(function ($model) { $original_uuid = $model->getOriginal(config('uuid.default_uuid_column')); if ($original_uuid !== $model->{config('uuid.default_uuid_column')}) { $model->{config('uuid.default_uuid_column')} = $original_uuid; } }); } /** * Scope by uuid * @param string uuid of the model. * */ public function scopeUuid($query, $uuid, $first = true) { $match = preg_match('/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/', $uuid); if (!is_string($uuid) || $match !== 1) { throw (new ModelNotFoundException)->setModel(get_class($this)); } $results = $query->where(config('uuid.default_uuid_column'), $uuid); return $first ? $results->firstOrFail() : $results; } }
<?php namespace Emadadly\LaravelUuid; use Ramsey\Uuid\Uuid; use Illuminate\Database\Eloquent\ModelNotFoundException; trait Uuids { /** * Boot function from laravel. */ protected static function boot() { parent::boot(); static::creating(function ($model) { $model->{config('uuid.default_uuid_column')} = strtoupper(Uuid::uuid4()->toString()); }); static::saving(function ($model) { $original_uuid = $model->getOriginal(config('uuid.default_uuid_column')); if ($original_uuid !== $model->{config('uuid.default_uuid_column')}) { $model->{config('uuid.default_uuid_column')} = $original_uuid; } }); } /** * Scope by uuid * @param string uuid of the model. * */ public function scopeUuid($query, $uuid, $first = true) { $match = preg_match('/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/', $uuid); if (!is_string($uuid) || $match !== 1) { throw (new ModelNotFoundException)->setModel(get_class($this)); } $results = $query->where(config('uuid.default_uuid_column'), $uuid); return $first ? $results->firstOrFail() : $results; } }
Add journal watcher unit to pod rules
from pathlib import Path import shipyard2.rules.pods OPS_DB_PATH = Path('/srv/operations/database/v1') shipyard2.rules.pods.define_pod( name='database', apps=[ shipyard2.rules.pods.App( name='database', exec=[ 'python3', *('-m', 'g1.operations.databases.servers'), *( '--parameter', 'g1.operations.databases.servers:database.db_url', 'sqlite:///%s' % (OPS_DB_PATH / 'ops.db'), ), ], ), ], images=[ '//operations:database', ], mounts=[ shipyard2.rules.pods.Mount( source=str(OPS_DB_PATH), target=str(OPS_DB_PATH), read_only=False, ), ], systemd_unit_groups=[ shipyard2.rules.pods.SystemdUnitGroup( units=[ shipyard2.rules.pods.SystemdUnitGroup.Unit( name='database.service', content=shipyard2.rules.pods.make_pod_service_content( description='Operations Database Server', ), ), shipyard2.rules.pods.SystemdUnitGroup.Unit( name='watcher.service', content=shipyard2.rules.pods\ .make_pod_journal_watcher_content( description='Operations Database Server Watcher', ), auto_stop=False, ), ], ), ], )
from pathlib import Path import shipyard2.rules.pods OPS_DB_PATH = Path('/srv/operations/database/v1') shipyard2.rules.pods.define_pod( name='database', apps=[ shipyard2.rules.pods.App( name='database', exec=[ 'python3', *('-m', 'g1.operations.databases.servers'), *( '--parameter', 'g1.operations.databases.servers:database.db_url', 'sqlite:///%s' % (OPS_DB_PATH / 'ops.db'), ), ], ), ], images=[ '//operations:database', ], mounts=[ shipyard2.rules.pods.Mount( source=str(OPS_DB_PATH), target=str(OPS_DB_PATH), read_only=False, ), ], systemd_unit_groups=[ shipyard2.rules.pods.SystemdUnitGroup( units=[ shipyard2.rules.pods.SystemdUnitGroup.Unit( name='database.service', content=shipyard2.rules.pods.make_pod_service_content( description='Operations Database Server', ), ), ], ), ], )
Update the 'send' parameter to work with the actual API spec
package com.tozny.sdk.realm.methods.email_challenge; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.tozny.sdk.ToznyApiRequest; import javax.annotation.Nullable; /** * Constructs a Request for invoking the "realm.email_challenge" method. */ @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) public class EmailChallengeRequest implements ToznyApiRequest { @JsonProperty(required=true) private String method = "realm.email_challenge"; @JsonProperty(required=true) private String destination; @JsonProperty private String callback; @JsonProperty private String hostname; @JsonProperty private String send; public EmailChallengeRequest(String destination, @Nullable String callback, @Nullable String hostname, @Nullable Boolean send) { this.destination = destination; this.callback = callback; this.hostname = hostname; if (send == null) { this.send = "yes"; } else { this.send = "no"; } } public String getMethod() { return method; } public String getDestination() { return destination; } @Nullable public String getCallback() { return callback; } @Nullable public String getHostname() { return hostname; } @Nullable public Boolean getSend() { return send.equals("yes"); } }
package com.tozny.sdk.realm.methods.email_challenge; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; import com.tozny.sdk.ToznyApiRequest; import javax.annotation.Nullable; /** * Constructs a Request for invoking the "realm.email_challenge" method. */ @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) public class EmailChallengeRequest implements ToznyApiRequest { @JsonProperty(required=true) private String method = "realm.email_challenge"; @JsonProperty(required=true) private String destination; @JsonProperty private String callback; @JsonProperty private String hostname; @JsonProperty private Boolean send; public EmailChallengeRequest(String destination, @Nullable String callback, @Nullable String hostname, @Nullable Boolean send) { this.destination = destination; this.callback = callback; this.hostname = hostname; if (send == null) { this.send = true; } else { this.send = send; } } public String getMethod() { return method; } public String getDestination() { return destination; } @Nullable public String getCallback() { return callback; } @Nullable public String getHostname() { return hostname; } @Nullable public Boolean getSend() { return send; } }
Fix license header getting removed
/* * Copyright 2012, Board of Regents of the University of * Wisconsin System. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Board of Regents of the University of Wisconsin * System 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. */ define(['angular'], function(angular) { var config = angular.module('app-config', []); config .constant('SERVICE_LOC', { 'sessionInfo' : 'json/sessionsample.json', 'sidebarInfo' : 'samples/sidebar.json', 'notificationsURL' : 'samples/notifications.json', 'groupURL' : null }) .constant('NAMES', { 'title' : 'MyTools', 'crest' : 'img/uwcrest_web_sm.png', 'crestalt' : 'UW Crest', 'sublogo' : 'beta' }) .constant('SEARCH',{ 'isWeb' : false, 'searchURL' : 'https://my.wisc.edu/web/apps/search/' }) .constant('NOTIFICATION', { 'groupFiltering' : false, 'notificationFullURL' : 'notifications' }) .constant('MISC_URLS',{ 'feedbackURL' : 'https://my.wisc.edu/portal/p/feedback', 'back2ClassicURL' : null, 'whatsNewURL' : null }); return config; });
define(['angular'], function(angular) { var config = angular.module('app-config', []); config .constant('SERVICE_LOC', { 'sessionInfo' : 'json/sessionsample.json', 'sidebarInfo' : 'samples/sidebar.json', 'notificationsURL' : 'samples/notifications.json', 'groupURL' : null }) .constant('NAMES', { 'title' : 'MyTools', 'crest' : 'img/uwcrest_web_sm.png', 'crestalt' : 'UW Crest', 'sublogo' : 'beta' }) .constant('SEARCH',{ 'isWeb' : false, 'searchURL' : 'https://my.wisc.edu/web/apps/search/' }) .constant('NOTIFICATION', { 'groupFiltering' : false, 'notificationFullURL' : 'notifications' }) .constant('MISC_URLS',{ 'feedbackURL' : 'https://my.wisc.edu/portal/p/feedback', 'back2ClassicURL' : null, 'whatsNewURL' : null }); return config; });
Remove call to realPath for output file
/** * Main styleguide grunt task */ module.exports = function(grunt) { 'use strict'; var fs = require('fs'), nunjucks = require('nunjucks'); grunt.registerMultiTask('styleguide', 'Generate a static HTML style guide', function() { var context = this.data, partials = fs.realpathSync(context.partials), html, template; context.template = context.template || (__dirname + "/../guide.html"); context.template = fs.realpathSync(context.template); context.snippets = (function() { var filenames = fs.readdirSync(partials), snippets = {}, i = 0, name; grunt.log.writeln("Loading partials..."); for (i = 0; i < filenames.length; i++) { name = filenames[i]; grunt.log.writeln(" " + name); snippets[name.replace('.', '-')] = (context.partials + "/" + name); } return snippets; }()); template = fs.readFileSync(context.template, {encoding: 'utf-8'}); html = nunjucks.renderString(template, context); fs.writeFileSync(context.output, html); grunt.log.writeln("Finished exporting styleguide:" + this.target + " to " + context.output); }); };
/** * Main styleguide grunt task */ module.exports = function(grunt) { 'use strict'; var fs = require('fs'), nunjucks = require('nunjucks'); grunt.registerMultiTask('styleguide', 'Generate a static HTML style guide', function() { var context = this.data, output = fs.realpathSync(context.output), partials = fs.realpathSync(context.partials), html, template; context.template = context.template || (__dirname + "/../guide.html"); context.template = fs.realpathSync(context.template); context.snippets = (function() { var filenames = fs.readdirSync(partials), snippets = {}, i = 0, name; grunt.log.writeln("Loading partials..."); for (i = 0; i < filenames.length; i++) { name = filenames[i]; grunt.log.writeln(" " + name); snippets[name.replace('.', '-')] = (context.partials + "/" + name); } return snippets; }()); template = fs.readFileSync(context.template, {encoding: 'utf-8'}); html = nunjucks.renderString(template, context); fs.writeFileSync(output, html); grunt.log.writeln("Finished exporting styleguide:" + this.target + " to " + output); }); };