text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Remove webpack bundle analyzer for netlify deploy
const path = require('path'); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = env => ({ context: __dirname, entry: './src/index.js', devtool: env.prod ? 'cheap-module-source-map' : 'eval', output: { path: path.join(__dirname, '/dist'), filename: 'bundle.js', publicPath: '/dist/' }, devServer: { historyApiFallback: true }, resolve: { extensions: ['.js', '.json'] }, stats: { colors: true, reasons: true, chunks: true }, module: { rules: [ { enforce: 'pre', test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }, { include: path.resolve(__dirname, 'src'), test: /\.js$/, loader: 'babel-loader' }, { test: /\.css$/, use: [ 'style-loader', { loader: 'css-loader', options: { url: false } } ] } ] } });
const path = require('path'); const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; module.exports = env => ({ context: __dirname, entry: './src/index.js', devtool: env.prod ? 'cheap-module-source-map' : 'eval', output: { path: path.join(__dirname, '/dist'), filename: 'bundle.js', publicPath: '/dist/' }, devServer: { historyApiFallback: true }, resolve: { extensions: ['.js', '.json'] }, stats: { colors: true, reasons: true, chunks: true }, module: { rules: [ { enforce: 'pre', test: /\.js$/, loader: 'eslint-loader', exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }, { include: path.resolve(__dirname, 'src'), test: /\.js$/, loader: 'babel-loader' }, { test: /\.css$/, use: [ 'style-loader', { loader: 'css-loader', options: { url: false } } ] } ] }, plugins: env.prod ? [ new BundleAnalyzerPlugin() ] : [] });
Fix the reload when adding and option Oh JavaScript. How do I hate thee? Let me count the ways. We now pas a function: $scope.notifyOptionAdded rather than a function call $scope.notifyOptionAdded() so that promises work, rather than running synchronously.
/// <reference path="../Services/VoteService.js" /> 'use strict'; (function () { angular .module('GVA.Voting') .controller('AddVoterOptionDialogController', AddVoterOptionDialogController); AddVoterOptionDialogController.$inject = ['$scope', 'VoteService']; function AddVoterOptionDialogController($scope, VoteService) { $scope.multipleAddingAllowed = false; $scope.addOption = addOption; $scope.addOptionAndClose = addOptionAndClose; function addOption(form) { add(form); dismiss(); } function add(form) { if (form.name === null) { return; } var newVoterOption = { Name: form.name, Description: form.description }; $scope.options.push(newVoterOption); VoteService.addVoterOption($scope.ngDialogData.pollId, newVoterOption) .then($scope.notifyOptionAdded); } function addOptionAndClose(form) { add(form); dismiss(); } function dismiss() { $scope.closeThisDialog(); } } })();
/// <reference path="../Services/VoteService.js" /> 'use strict'; (function () { angular .module('GVA.Voting') .controller('AddVoterOptionDialogController', AddVoterOptionDialogController); AddVoterOptionDialogController.$inject = ['$scope', 'VoteService']; function AddVoterOptionDialogController($scope, VoteService) { $scope.multipleAddingAllowed = false; $scope.addOption = addOption; $scope.addOptionAndClose = addOptionAndClose; function addOption(form) { add(form); dismiss(); } function add(form) { if (form.name === null) { return; } var newVoterOption = { Name: form.name, Description: form.description }; $scope.options.push(newVoterOption); VoteService.addVoterOption($scope.ngDialogData.pollId, newVoterOption) .then($scope.notifyOptionAdded()); } function addOptionAndClose(form) { add(form); dismiss(); } function dismiss() { $scope.closeThisDialog(); } } })();
Stop mixing extension configuration and context options
<?php namespace sablonier\carousel; use Bolt\Extension\SimpleExtension; class CarouselExtension extends SimpleExtension { /** * {@inheritdoc} */ protected function registerTwigFunctions() { return [ 'carousel' => ['carouselFunction'] ]; } /** * {@inheritdoc} */ protected function registerTwigPaths() { return [ 'templates' ]; } /** * Render and return the twig file templates/_carousel.twig * * @return carousel */ public function carouselFunction($options) { $config = $this->getConfig(); $context = [ 'options' => $options, ]; switch ($config['render']['framework']) { case 'bootstrap4': $carousel = $this->renderTemplate('_carousel_bootstrap4.twig', $context); break; /*case 'foundation6': $carousel = $this->renderTemplate('_carousel_foundation6.twig', $context); break; case 'purecss': $carousel = $this->renderTemplate('_carousel_purecss.twig', $context); break;*/ } echo $carousel; } }
<?php namespace sablonier\carousel; use Bolt\Extension\SimpleExtension; class CarouselExtension extends SimpleExtension { /** * {@inheritdoc} */ protected function registerTwigFunctions() { return [ 'carousel' => ['carouselFunction'] ]; } /** * {@inheritdoc} */ protected function registerTwigPaths() { return [ 'templates' ]; } /** * Render and return the twig file templates/_carousel.twig * * @return carousel */ public function carouselFunction($options) { $config = $this->getConfig(); $context = [ 'options' => $options, 'type' => $config['render']['type'] ]; switch ($config['render']['framework']) { case 'bootstrap4': $carousel = $this->renderTemplate('_carousel_bootstrap4.twig', $context); break; /*case 'foundation6': $carousel = $this->renderTemplate('_carousel_foundation6.twig', $context); break; case 'purecss': $carousel = $this->renderTemplate('_carousel_purecss.twig', $context); break;*/ } echo $carousel; } }
Check an extra possible data dir when installing in a venv When installing spec-cleaner in a virtual env, the data files (i.e. "excludes-bracketing.txt") are available in a different directory. Also check this directory. Fixes #128
# vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: # the .. is appended as we are in spec_cleaner sub_folder _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # try venv structure try: _file = open('{0}/../usr/share/spec-cleaner/{1}'.format( os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError as error: # try system dir try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None
# vim: set ts=4 sw=4 et: coding=UTF-8 import os from .rpmexception import RpmException class FileUtils(object): """ Class working with file operations. Read/write.. """ # file variable f = None def open_datafile(self, name): """ Function to open data files. Used all around so kept glob here for importing. """ try: _file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r') except IOError: # the .. is appended as we are in spec_cleaner sub_folder try: _file = open('/usr/share/spec-cleaner/{0}'.format(name), 'r') except IOError as error: raise RpmException(error.strerror) self.f = _file def open(self, name, mode): """ Function to open regular files with exception handling. """ try: _file = open(name, mode) except IOError as error: raise RpmException(error.strerror) self.f = _file def close(self): """ Just wrapper for closing the file """ if self.f: self.f.close() self.f = None def __del__(self): self.close() self.f = None
Add some protection against a failed load of Multiverse
package com.elmakers.mine.bukkit.protection; import com.onarandombox.MultiverseCore.MultiverseCore; import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MultiverseWorld; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class MultiverseManager implements PVPManager { private boolean enabled = false; private MultiverseCore mv = null; public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled && mv != null; } public void initialize(Plugin plugin) { if (enabled) { try { Plugin mvPlugin = plugin.getServer().getPluginManager().getPlugin("Multiverse-Core"); if (mvPlugin instanceof MultiverseCore) { mv = (MultiverseCore)mvPlugin; } } catch (Throwable ex) { } if (mv != null) { plugin.getLogger().info("Multiverse-Core found, will respect PVP settings"); } } else { mv = null; } } @Override public boolean isPVPAllowed(Player player, Location location) { if (!enabled || mv == null || location == null) return true; World world = location.getWorld(); if (world == null) return true; MVWorldManager manager = mv.getMVWorldManager(); if (manager == null) return true; MultiverseWorld mvWorld = manager.getMVWorld(world); if (mvWorld == null) return true; ; return mvWorld.isPVPEnabled(); } }
package com.elmakers.mine.bukkit.protection; import com.onarandombox.MultiverseCore.MultiverseCore; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; public class MultiverseManager implements PVPManager { private boolean enabled = false; private MultiverseCore mv = null; public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled && mv != null; } public void initialize(Plugin plugin) { if (enabled) { try { Plugin mvPlugin = plugin.getServer().getPluginManager().getPlugin("Multiverse-Core"); if (mvPlugin instanceof MultiverseCore) { mv = (MultiverseCore)mvPlugin; } } catch (Throwable ex) { } if (mv != null) { plugin.getLogger().info("Multiverse-Core found, will respect PVP settings"); } } else { mv = null; } } @Override public boolean isPVPAllowed(Player player, Location location) { if (!enabled || mv == null || location == null) return true; World world = location.getWorld(); if (world == null) return true; return mv.getMVWorldManager().getMVWorld(world).isPVPEnabled(); } }
Clone only valid react element
import React, { PureComponent, createElement, Children, cloneElement, isValidElement } from 'react'; import PropTypes from 'prop-types'; import eventManager from './../util/eventManager'; class ContextMenuProvider extends PureComponent { static propTypes = { id: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]).isRequired, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node ]).isRequired, renderTag: PropTypes.node, event: PropTypes.string, className: PropTypes.string, style: PropTypes.object }; static defaultProps = { renderTag: 'div', event: 'onContextMenu', className: '', style: {} }; handleEvent = e => { e.preventDefault(); eventManager.emit(`display::${this.props.id}`, e.nativeEvent); }; getChildren() { const { id, renderTag, event, children, className, style, ...rest } = this.props; return isValidElement(this.props.children) ? Children.map(this.props.children, child => cloneElement(child, { ...rest })) : this.props.children; } render() { const { renderTag, event, className, style } = this.props; const attributes = Object.assign({}, { [event]: this.handleEvent, className, style }); return createElement( renderTag, attributes, this.getChildren() ); } } export default ContextMenuProvider;
import React, { PureComponent, createElement, Children, cloneElement } from 'react'; import PropTypes from 'prop-types'; import eventManager from './../util/eventManager'; class ContextMenuProvider extends PureComponent { static propTypes = { id: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]).isRequired, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node ]).isRequired, renderTag: PropTypes.node, event: PropTypes.string, className: PropTypes.string, style: PropTypes.object }; static defaultProps = { renderTag: 'div', event: 'onContextMenu', className: '', style: {} }; handleEvent = e => { e.preventDefault(); eventManager.emit(`display::${this.props.id}`, e.nativeEvent); }; getChildren() { const { id, renderTag, event, children, className, style, ...rest } = this.props; return Children.map(this.props.children, child => cloneElement(child, { ...rest })); } render() { const { renderTag, event, className, style } = this.props; const attributes = Object.assign({}, { [event]: this.handleEvent, className, style }); return createElement( renderTag, attributes, this.getChildren() ); } } export default ContextMenuProvider;
Use redis pipelining when sending events
import datetime import redis import time import urlparse import beaver.transport class RedisTransport(beaver.transport.Transport): def __init__(self, beaver_config, file_config, logger=None): super(RedisTransport, self).__init__(beaver_config, file_config, logger=logger) redis_url = beaver_config.get('redis_url') redis_password = beaver_config.get('redis_password') _url = urlparse.urlparse(redis_url, scheme="redis") _, _, _db = _url.path.rpartition("/") self._redis = redis.StrictRedis(host=_url.hostname, port=_url.port, password=redis_password, db=int(_db), socket_timeout=10) self._redis_namespace = beaver_config.get('redis_namespace') wait = 0 while 1: if wait == 20: break time.sleep(0.1) wait += 1 try: self._redis.ping() break except redis.exceptions.ConnectionError: pass self._pipeline = self._redis.pipeline(transaction=False) def callback(self, filename, lines): timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ") for line in lines: self._pipeline.rpush( self._redis_namespace, self.format(filename, timestamp, line) ) self._pipeline.execute()
import datetime import redis import time import urlparse import beaver.transport class RedisTransport(beaver.transport.Transport): def __init__(self, beaver_config, file_config, logger=None): super(RedisTransport, self).__init__(beaver_config, file_config, logger=logger) redis_url = beaver_config.get('redis_url') redis_password = beaver_config.get('redis_password') _url = urlparse.urlparse(redis_url, scheme="redis") _, _, _db = _url.path.rpartition("/") self._redis = redis.StrictRedis(host=_url.hostname, port=_url.port, password=redis_password, db=int(_db), socket_timeout=10) self._redis_namespace = beaver_config.get('redis_namespace') wait = 0 while 1: if wait == 20: break time.sleep(0.1) wait += 1 try: self._redis.ping() break except redis.exceptions.ConnectionError: pass def callback(self, filename, lines): timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ") for line in lines: self._redis.rpush( self._redis_namespace, self.format(filename, timestamp, line) )
Fix the configuration property access
<?php namespace PHPYAM\extra; use PHPYAM\core\interfaces\IConfiguration; /** * TODO comment. * * @package PHPYAM\extra * @author Thierry BLIND * @since 01/04/2022 * @copyright 2014-2022 Thierry BLIND */ class Configuration implements IConfiguration { /** * * {@inheritdoc} * @see \PHPYAM\core\interfaces\IConfiguration::get() */ public function get($key, $defaultValue) { $classReflexion = new \ReflectionClass($this); $classConstants = $classReflexion->getConstants(); if (array_key_exists($key, $classConstants)) { return $classConstants[$key]; } if (property_exists($this, $key)) { return $this->{$key}; } if (defined($key)) { return constant($key); } return $defaultValue; } /** * NB: can be overridden if the log4php library should not be used. * * {@inheritdoc} * @see \PHPYAM\core\interfaces\IConfiguration::logError() */ public function logError($data) { \Logger::getLogger(__CLASS__)->error($data); } }
<?php namespace PHPYAM\extra; use PHPYAM\core\interfaces\IConfiguration; /** * TODO comment. * * @package PHPYAM\extra * @author Thierry BLIND * @since 01/04/2022 * @copyright 2014-2022 Thierry BLIND */ class Configuration implements IConfiguration { /** * * {@inheritdoc} * @see \PHPYAM\core\interfaces\IConfiguration::get() */ public function get($key, $defaultValue) { $classReflexion = new \ReflectionClass($this); $classConstants = $classReflexion->getConstants(); if (array_key_exists($key, $classConstants)) { return $classConstants[$key]; } if (property_exists($this, $key)) { return $this->${$key}; } if (defined($key)) { return constant($key); } return $defaultValue; } /** * NB: can be overridden if the log4php library should not be used. * * {@inheritdoc} * @see \PHPYAM\core\interfaces\IConfiguration::logError() */ public function logError($data) { \Logger::getLogger(__CLASS__)->error($data); } }
Fix error handling to catch if JSON is not returned
import six class APIError(Exception): "SmartFile API base Exception." pass class RequestError(APIError): """ Exception for issues regarding a request. """ def __init__(self, exc, *args, **kwargs): self.exc = exc self.detail = str(exc) super(RequestError, self).__init__(*args, **kwargs) def __str__(self): return self.detail class ResponseError(APIError): """ Exception for issues regarding a response. """ def __init__(self, response, *args, **kwargs): self.response = response self.status_code = response.status_code try: json = response.json() except ValueError: if self.status_code == 404: self.detail = six.u('Invalid URL, check your API path') else: self.detail = six.u('Server error; check response for errors') else: if self.status_code == 400 and 'field_errors' in json: self.detail = json['field_errors'] else: try: # A faulty move request returns the below response self.detail = json['src'][0] except KeyError: # A faulty delete request returns the below response try: self.detail = json['path'][0] except KeyError: self.detail = six.u('Error: %s' % response.content) super(ResponseError, self).__init__(*args, **kwargs) def __str__(self): return 'Response {0}: {1}'.format(self.status_code, self.detail)
import six class APIError(Exception): "SmartFile API base Exception." pass class RequestError(APIError): """ Exception for issues regarding a request. """ def __init__(self, exc, *args, **kwargs): self.exc = exc self.detail = str(exc) super(RequestError, self).__init__(*args, **kwargs) def __str__(self): return self.detail class ResponseError(APIError): """ Exception for issues regarding a response. """ def __init__(self, response, *args, **kwargs): self.response = response self.status_code = response.status_code try: json = response.json() except ValueError: if self.status_code == 404: self.detail = six.u('Invalid URL, check your API path') else: self.detail = six.u('Server error; check response for errors') else: if self.status_code == 400 and 'field_errors' in json: self.detail = json['field_errors'] else: try: # A faulty move request returns the below response self.detail = json['src'][0] except KeyError: # A faulty delete request returns the below response self.detail = json['path'][0] super(ResponseError, self).__init__(*args, **kwargs) def __str__(self): return 'Response {0}: {1}'.format(self.status_code, self.detail)
Add setters for limited motor
package com.thegongoliers.output.motors; import com.thegongoliers.annotations.Untested; import java.util.function.BooleanSupplier; @Untested public class LimiterMotorModule implements MotorModule { private BooleanSupplier mPositiveLimit; private BooleanSupplier mNegativeLimit; public LimiterMotorModule(BooleanSupplier positiveLimit, BooleanSupplier negativeLimit) { mPositiveLimit = positiveLimit; mNegativeLimit = negativeLimit; if (mPositiveLimit == null) { mPositiveLimit = () -> false; } if (mNegativeLimit == null) { mNegativeLimit = () -> false; } } public void setNegativeLimit(BooleanSupplier mNegativeLimit) { this.mNegativeLimit = mNegativeLimit; } public void setPositiveLimit(BooleanSupplier mPositiveLimit) { this.mPositiveLimit = mPositiveLimit; } @Override public double run(double currentSpeed, double desiredSpeed, double deltaTime) { if (shouldStop(desiredSpeed)) { return 0.0; } return desiredSpeed; } public boolean isAtPositiveLimit(){ return mPositiveLimit.getAsBoolean(); } public boolean isAtNegativeLimit(){ return mNegativeLimit.getAsBoolean(); } private boolean shouldStop(double speed) { if (speed > 0 && isAtPositiveLimit()) { return true; } if (speed < 0 && isAtNegativeLimit()) { return true; } return false; } }
package com.thegongoliers.output.motors; import com.thegongoliers.annotations.Untested; import java.util.function.BooleanSupplier; @Untested public class LimiterMotorModule implements MotorModule { private BooleanSupplier mPositiveLimit; private BooleanSupplier mNegativeLimit; public LimiterMotorModule(BooleanSupplier positiveLimit, BooleanSupplier negativeLimit) { mPositiveLimit = positiveLimit; mNegativeLimit = negativeLimit; if (mPositiveLimit == null) { mPositiveLimit = () -> false; } if (mNegativeLimit == null) { mNegativeLimit = () -> false; } } @Override public double run(double currentSpeed, double desiredSpeed, double deltaTime) { if (shouldStop(desiredSpeed)) { return 0.0; } return desiredSpeed; } public boolean isAtPositiveLimit(){ return mPositiveLimit.getAsBoolean(); } public boolean isAtNegativeLimit(){ return mNegativeLimit.getAsBoolean(); } private boolean shouldStop(double speed) { if (speed > 0 && isAtPositiveLimit()) { return true; } if (speed < 0 && isAtNegativeLimit()) { return true; } return false; } }
Add previous exception to DeleteHandlingException
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\CoreBundle\Doctrine\ORM\Handler; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\ORMException; use Sylius\Bundle\ResourceBundle\Controller\ResourceDeleteHandlerInterface; use Sylius\Component\Resource\Exception\DeleteHandlingException; use Sylius\Component\Resource\Model\ResourceInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; final class ResourceDeleteHandler implements ResourceDeleteHandlerInterface { /** @var ResourceDeleteHandlerInterface */ private $decoratedHandler; /** @var EntityManagerInterface */ private $entityManager; public function __construct(ResourceDeleteHandlerInterface $decoratedHandler, EntityManagerInterface $entityManager) { $this->decoratedHandler = $decoratedHandler; $this->entityManager = $entityManager; } /** * @throws DeleteHandlingException */ public function handle(ResourceInterface $resource, RepositoryInterface $repository): void { $this->entityManager->beginTransaction(); try { $this->decoratedHandler->handle($resource, $repository); $this->entityManager->commit(); } catch (ORMException $exception) { $this->entityManager->rollback(); throw new DeleteHandlingException( 'Ups, something went wrong during deleting a resource, please try again.', 'something_went_wrong_error', 500, 0, $exception ); } } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\CoreBundle\Doctrine\ORM\Handler; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\ORMException; use Sylius\Bundle\ResourceBundle\Controller\ResourceDeleteHandlerInterface; use Sylius\Component\Resource\Exception\DeleteHandlingException; use Sylius\Component\Resource\Model\ResourceInterface; use Sylius\Component\Resource\Repository\RepositoryInterface; final class ResourceDeleteHandler implements ResourceDeleteHandlerInterface { /** @var ResourceDeleteHandlerInterface */ private $decoratedHandler; /** @var EntityManagerInterface */ private $entityManager; public function __construct(ResourceDeleteHandlerInterface $decoratedHandler, EntityManagerInterface $entityManager) { $this->decoratedHandler = $decoratedHandler; $this->entityManager = $entityManager; } /** * @throws DeleteHandlingException */ public function handle(ResourceInterface $resource, RepositoryInterface $repository): void { $this->entityManager->beginTransaction(); try { $this->decoratedHandler->handle($resource, $repository); $this->entityManager->commit(); } catch (ORMException $exception) { $this->entityManager->rollback(); throw new DeleteHandlingException(); } } }
Add a todo in a test
package org.twig.extension; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CoreTests { @Test public void canEnsureIterableOnIterable() { Iterable<String> list = new ArrayList<>(); Iterable<String> ensuredList = (Iterable<String>)Core.ensureIterable(list); Assert.assertSame("Returned list should be the same as the provided list", list, ensuredList); } @Test public void canEnsureIterableOnNonIterable() { String notAList = null; Iterable<String> ensuredList = (Iterable<String>)Core.ensureIterable(notAList); Assert.assertTrue("Returned list should be a list even though null and another type was provided", ensuredList instanceof Iterable); } // TODO test ensureIterable(Map<?>) @Test public void canCheckInOnString() { String haystack = "bar foo baz"; Assert.assertTrue("Should find foo", Core.inFilter("foo", haystack)); Assert.assertFalse("Should not find something that's not in the string", Core.inFilter("not in string", haystack)); } @Test public void canCheckInOnList() { List<String> haystack = Arrays.asList("foo", "bar", "baz"); Assert.assertTrue("Should find object that's present in array", Core.inFilter("foo", haystack)); Assert.assertFalse("Should not find object that's not present in array", Core.inFilter("not in the list", haystack)); } }
package org.twig.extension; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CoreTests { @Test public void canEnsureIterableOnIterable() { Iterable<String> list = new ArrayList<>(); Iterable<String> ensuredList = (Iterable<String>)Core.ensureIterable(list); Assert.assertSame("Returned list should be the same as the provided list", list, ensuredList); } @Test public void canEnsureIterableOnNonIterable() { String notAList = null; Iterable<String> ensuredList = (Iterable<String>)Core.ensureIterable(notAList); Assert.assertTrue("Returned list should be a list even though null and another type was provided", ensuredList instanceof Iterable); } @Test public void canCheckInOnString() { String haystack = "bar foo baz"; Assert.assertTrue("Should find foo", Core.inFilter("foo", haystack)); Assert.assertFalse("Should not find something that's not in the string", Core.inFilter("not in string", haystack)); } @Test public void canCheckInOnList() { List<String> haystack = Arrays.asList("foo", "bar", "baz"); Assert.assertTrue("Should find object that's present in array", Core.inFilter("foo", haystack)); Assert.assertFalse("Should not find object that's not present in array", Core.inFilter("not in the list", haystack)); } }
Increase timeout for elm tests.
var expect = require('chai').expect; var count = require('count-substring'); var htmlToText = require('html-to-text'); module.exports = function (browser) { describe("The tests written in Elm", function () { it('should pass', function () { return browser .url('http://localhost:8080/elm.html') .waitUntil(function () { return this.getHTML("#results").then(function (html) { var passedCount = count(html, "All tests passed"); var failedCount = count(html, "FAILED"); if (passedCount > 0) { return true; } if (failedCount > 0) { console.log("Failed!\n"); console.log(htmlToText.fromString(html)); throw "Failed tests written in Elm"; } return false; }); }, 10000, 500); }); }); };
var expect = require('chai').expect; var count = require('count-substring'); var htmlToText = require('html-to-text'); module.exports = function (browser) { describe("The tests written in Elm", function () { it('should pass', function () { return browser .url('http://localhost:8080/elm.html') .waitUntil(function () { return this.getHTML("#results").then(function (html) { var passedCount = count(html, "All tests passed"); var failedCount = count(html, "FAILED"); if (passedCount > 0) { return true; } if (failedCount > 0) { console.log("Failed!\n"); console.log(htmlToText.fromString(html)); throw "Failed tests written in Elm"; } return false; }); }, 3000, 500); }); }); };
Augment unit test for show_hist
import openpnm as op class GenericGeometryTest: def setup_class(self): self.net = op.network.Cubic(shape=[3, 3, 3]) self.geo = op.geometry.StickAndBall(network=self.net, pores=self.net.Ps, throats=self.net.Ts) self.geo.regenerate_models() def teardown_class(self): mgr = op.Workspace() mgr.clear() def test_plot_histogram(self): # Test default args self.geo.show_hist() # Test with non-default args self.geo.show_hist(props=['pore.diameter', 'pore.volume', 'throat.length']) # Test layout when num_props = 4 => should be 2 by 2 self.geo.show_hist( props=[ 'pore.diameter', 'throat.diameter', 'pore.volume', 'throat.length' ] ) # Test layout when num_props > 4 => should be nrows by 3 self.geo.show_hist( props=[ 'pore.diameter', 'pore.volume', 'throat.length', 'throat.diameter', 'pore.seed' ] ) if __name__ == '__main__': t = GenericGeometryTest() self = t t.setup_class() for item in t.__dir__(): if item.startswith('test'): print('running test: '+item) t.__getattribute__(item)()
import openpnm as op class GenericGeometryTest: def setup_class(self): self.net = op.network.Cubic(shape=[3, 3, 3]) self.geo = op.geometry.StickAndBall(network=self.net, pores=self.net.Ps, throats=self.net.Ts) self.geo.regenerate_models() def teardown_class(self): mgr = op.Workspace() mgr.clear() def test_plot_histogram(self): self.geo.show_hist() self.geo.show_hist(props=['pore.diameter', 'pore.volume', 'throat.length']) self.geo.show_hist(props=['pore.diameter', 'pore.volume', 'throat.length', 'throat.diameter', 'pore.seed']) if __name__ == '__main__': t = GenericGeometryTest() self = t t.setup_class() for item in t.__dir__(): if item.startswith('test'): print('running test: '+item) t.__getattribute__(item)()
Create returns object as well
/** * Created by Itay Herskovits on 2/1/15. */ (function () { angular.module('mytodoApp') .service('TodoService', ['$http', 'Backand', 'AuthService', TodoService]); function TodoService($http, Backand, AuthService) { var self = this; var objectName = 'todo'; self.readAll = function () { return Backand.object.getList(objectName).then(function(response) { return response.data }); }; self.readOne = function (id) { return Backand.object.getOne(objectName, id).then(function(response) { return response.data }); }; self.create = function (description) { var object = {description: description}; return Backand.object.create(objectName, object, {returnObject: true}) .then(function(response) { return response.data; }); }; self.update = function (id, data) { return Backand.object.create(objectName, data) .then(function(response) { return response.data; }); }; self.delete = function (id) { return Backand.object.remove(objectName, id); }; } }());
/** * Created by Itay Herskovits on 2/1/15. */ (function () { angular.module('mytodoApp') .service('TodoService', ['$http', 'Backand', 'AuthService', TodoService]); function TodoService($http, Backand, AuthService) { var self = this; var objectName = 'todo'; self.readAll = function () { return Backand.object.getList(objectName).then(function(response) { return response.data }); }; self.readOne = function (id) { return Backand.object.getOne(objectName, id).then(function(response) { return response.data }); }; self.create = function (description) { var object = {description: description}; return Backand.object.create(objectName, object) .then(function(response) { return response.data; }); }; self.update = function (id, data) { return Backand.object.create(objectName, data) .then(function(response) { return response.data; }); }; self.delete = function (id) { return Backand.object.remove(objectName, id); }; } }());
Fix mismatched args in CMake.build
import os from buildtools.bt_logging import log from buildtools.os_utils import cmd, ENV class CMake(object): def __init__(self): self.flags = {} self.generator = None def setFlag(self, key, val): log.info('CMake: {} = {}'.format(key, val)) self.flags[key] = val def build(self, CMAKE, dir='.', env=None, target=None, moreflags=[]): moreflags += ['--build'] if target is not None: moreflags += ['--target', target] self.run(CMAKE, env, dir, moreflags) def run(self, CMAKE, env=None, dir='.', moreflags=[]): if env is None: env = ENV.env flags = [] if self.generator is not None: flags += ['-G', self.generator] for key, value in self.flags.items(): flags += ['-D{0}={1}'.format(key, value)] flags += moreflags with log.info('Running CMake:'): for key, value in env.items(): log.info('+{0}="{1}"'.format(key, value)) return cmd([CMAKE] + flags + [dir], env=env, critical=True, echo=True) return False
import os from buildtools.bt_logging import log from buildtools.os_utils import cmd, ENV class CMake(object): def __init__(self): self.flags = {} self.generator = None def setFlag(self, key, val): log.info('CMake: {} = {}'.format(key, val)) self.flags[key] = val def build(self, CMAKE, dir='.', env=None, target=None, moreflags=[]): moreflags += ['--build'] if target is not None: moreflags += ['--target',target] self.run(CMAKE,dir,env,moreflags) def run(self, CMAKE, env=None, dir='.', moreflags=[]): if env is None: env = ENV.env flags = [] if self.generator is not None: flags += ['-G',self.generator] for key, value in self.flags.items(): flags += ['-D{0}={1}'.format(key, value)] flags += moreflags with log.info('Running CMake:'): for key, value in env.items(): log.info('+{0}="{1}"'.format(key, value)) return cmd([CMAKE] + flags + [dir], env=env, critical=True, echo=True) return False
Handle 2 digit year DOBs
(function() { 'use strict'; angular .module('core.formData') .factory('FormDataService', FormDataService); FormDataService.$inject = ['$sessionStorage', '_']; /* @ngInject */ function FormDataService($sessionStorage, _) { var formData = $sessionStorage.formData || {}; var service = { saveData: saveData, clearData: clearData, getData: getData, getAge: getAge, validAge: validAge }; return service; //////////////// function saveData(data) { formData = $sessionStorage.formData = angular.extend(formData, data); } function clearData() { formData = {}; delete $sessionStorage.formData; } function getData(step) { if (!step) { return formData; } return formData[step] || {}; } function getAge(dobObj) { var dob = getData('steps.details').dob; var date, m; if (!dob) { return; } date = new Date(dob.year + ' ' + dob.month + ' ' + dob.day); m = moment(date); return moment().diff(m, 'years'); } function validAge () { var age = getAge(); if (typeof age === 'undefined' || (age && age >= 18 && age <= 70)) { return true; } return false; } } })();
(function() { 'use strict'; angular .module('core.formData') .factory('FormDataService', FormDataService); FormDataService.$inject = ['$sessionStorage', '_']; /* @ngInject */ function FormDataService($sessionStorage, _) { var formData = $sessionStorage.formData || {}; var service = { saveData: saveData, clearData: clearData, getData: getData, getAge: getAge, validAge: validAge }; return service; //////////////// function saveData(data) { formData = $sessionStorage.formData = angular.extend(formData, data); } function clearData() { formData = {}; delete $sessionStorage.formData; } function getData(step) { if (!step) { return formData; } return formData[step] || {}; } function getAge(dobObj) { var dob = getData('steps.details').dob; var birthDate; if (!dob) { return; } birthDate = moment({ day: dob.day, month: dob.month, year: dob.year }); return moment().diff(birthDate, 'years'); } function validAge () { var age = getAge(); // console.log(age); if (typeof age === 'undefined' || (age && age >= 18 && age <= 70)) { return true; } return false; } } })();
Add DASH to Coinbase ticker
const _ = require('lodash/fp') const axios = require('axios') const BN = require('../../../bn') function getBuyPrice (obj) { const currencyPair = obj.currencyPair return axios({ method: 'get', url: `https://api.coinbase.com/v2/prices/${currencyPair}/buy`, headers: {'CB-Version': '2017-07-10'} }) .then(r => r.data) } function getSellPrice (obj) { const currencyPair = obj.currencyPair return axios({ method: 'get', url: `https://api.coinbase.com/v2/prices/${currencyPair}/sell`, headers: {'CB-Version': '2017-07-10'} }) .then(r => r.data) } function ticker (account, fiatCode, cryptoCode) { return Promise.resolve() .then(() => { if (!_.includes(cryptoCode, ['BTC', 'ETH', 'LTC', 'BCH', 'ZEC', 'DASH'])) { throw new Error('Unsupported crypto: ' + cryptoCode) } }) .then(() => { const currencyPair = `${cryptoCode}-${fiatCode}` const promises = [ getBuyPrice({currencyPair}), getSellPrice({currencyPair}) ] return Promise.all(promises) }) .then(([buyPrice, sellPrice]) => ({ rates: { ask: BN(buyPrice.data.amount), bid: BN(sellPrice.data.amount) } })) } module.exports = { ticker }
const _ = require('lodash/fp') const axios = require('axios') const BN = require('../../../bn') function getBuyPrice (obj) { const currencyPair = obj.currencyPair return axios({ method: 'get', url: `https://api.coinbase.com/v2/prices/${currencyPair}/buy`, headers: {'CB-Version': '2017-07-10'} }) .then(r => r.data) } function getSellPrice (obj) { const currencyPair = obj.currencyPair return axios({ method: 'get', url: `https://api.coinbase.com/v2/prices/${currencyPair}/sell`, headers: {'CB-Version': '2017-07-10'} }) .then(r => r.data) } function ticker (account, fiatCode, cryptoCode) { return Promise.resolve() .then(() => { if (!_.includes(cryptoCode, ['BTC', 'ETH', 'LTC', 'BCH', 'ZEC'])) { throw new Error('Unsupported crypto: ' + cryptoCode) } }) .then(() => { const currencyPair = `${cryptoCode}-${fiatCode}` const promises = [ getBuyPrice({currencyPair}), getSellPrice({currencyPair}) ] return Promise.all(promises) }) .then(([buyPrice, sellPrice]) => ({ rates: { ask: BN(buyPrice.data.amount), bid: BN(sellPrice.data.amount) } })) } module.exports = { ticker }
Use a list for main elements
from urllib.request import Request, urlopen from .renderers import XMLRenderer class Client: def __init__(self, hostname, auth_info): self.base_url = 'http://{}/MRWEnvio.asmx'.format(hostname) self.auth_info = auth_info self.renderer = XMLRenderer() def make_http_request(self, pickup_info, service_info): data = [ {'soap:Header': self.auth_info.as_dict()}, {'soap:Body': { 'mrw:TransmEnvio': { 'mrw:request': [ pickup_info.as_dict(), service_info.as_dict(), ] }, }}, ] namespaces = [ ('soap', 'http://www.w3.org/2003/05/soap-envelope'), ('mrw', 'http://www.mrw.es/'), ] data = self.renderer.render({'soap:Envelope': data}, namespaces) headers = {'Content-type': 'application/soap+xml; charset=utf-8'} return Request(self.base_url, data, headers, method='POST') def send(self, pickup_info, service_info): req = self.make_http_request(pickup_info, service_info) with urlopen(req) as response: body = response.read() body = body.decode('utf-8') return body
from urllib.request import Request, urlopen from .renderers import XMLRenderer class Client: def __init__(self, hostname, auth_info): self.base_url = 'http://{}/MRWEnvio.asmx'.format(hostname) self.auth_info = auth_info self.renderer = XMLRenderer() def make_http_request(self, pickup_info, service_info): data = { 'soap:Header': self.auth_info.as_dict(), 'soap:Body': { 'mrw:TransmEnvio': { 'mrw:request': [ pickup_info.as_dict(), service_info.as_dict(), ] } } } namespaces = [ ('soap', 'http://www.w3.org/2003/05/soap-envelope'), ('mrw', 'http://www.mrw.es/'), ] data = self.renderer.render({'soap:Envelope': data}, namespaces) headers = {'Content-type': 'application/soap+xml; charset=utf-8'} return Request(self.base_url, data, headers, method='POST') def send(self, pickup_info, service_info): req = self.make_http_request(pickup_info, service_info) with urlopen(req) as response: body = response.read() body = body.decode('utf-8') return body
Fix prod'n webpack conf for linked deps
var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); var path = require("path"); module.exports = { context: __dirname, entry: [ './ditto/static/chat/js/base.js', ], output: { path: path.resolve('./ditto/static/dist'), publicPath: '/static/dist/', // This will override the url generated by django's staticfiles filename: "[name]-[hash].js", }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ["babel-loader?optional[]=es7.comprehensions&optional[]=es7.classProperties&optional[]=es7.objectRestSpread&optional[]=es7.decorators"], } ] }, plugins: [ new BundleTracker({filename: './webpack-stats-prod.json'}), // removes a lot of debugging code in React new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') }}), // keeps hashes consistent between compilations new webpack.optimize.OccurenceOrderPlugin(), // minifies your code new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ], resolve: { fallback: path.join(__dirname, 'node_modules'), extensions: ['', '.js', '.jsx'] } };
var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); var path = require("path"); module.exports = { context: __dirname, entry: [ './ditto/static/chat/js/base.js', ], output: { path: path.resolve('./ditto/static/dist'), publicPath: '/static/dist/', // This will override the url generated by django's staticfiles filename: "[name]-[hash].js", }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ["babel-loader?optional[]=es7.comprehensions&optional[]=es7.classProperties&optional[]=es7.objectRestSpread&optional[]=es7.decorators"], } ] }, plugins: [ new BundleTracker({filename: './webpack-stats-prod.json'}), // removes a lot of debugging code in React new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') }}), // keeps hashes consistent between compilations new webpack.optimize.OccurenceOrderPlugin(), // minifies your code new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ], resolve: { extensions: ['', '.js', '.jsx'] } };
Remove test button from dashboard
@extends('mconsole::app') @section('content') <div class="row"> <div class="col-xs-12"> <div class="portlet light"> <div class="portlet-title"> <div class="caption"> <i class="icon-bulb font-dark"></i> <span class="caption-subject font-dark bold uppercase">Мудрость</span> </div> </div> <div class="portlet-body form"> <ul class="media-list"> <li class="media"> <img width="95px" class="media-object pull-left hidden-xs" src="/massets/img/mudrec.png"> <div class="media-body"> <blockquote> <p>“ {{ $quote['text'] }} „</p> <small><cite title="Source Title">{{ $quote['author'] }}</cite></small> </blockquote> </div> </li> </ul> </div> </div> </div> </div> @endsection
@extends('mconsole::app') @section('content') <div class="btn red btn-outline">TEST</div> <div class="row"> <div class="col-xs-12"> <div class="portlet light"> <div class="portlet-title"> <div class="caption"> <i class="icon-bulb font-dark"></i> <span class="caption-subject font-dark bold uppercase">Мудрость</span> </div> </div> <div class="portlet-body form"> <ul class="media-list"> <li class="media"> <img width="95px" class="media-object pull-left hidden-xs" src="/massets/img/mudrec.png"> <div class="media-body"> <blockquote> <p>“ {{ $quote['text'] }} „</p> <small><cite title="Source Title">{{ $quote['author'] }}</cite></small> </blockquote> </div> </li> </ul> </div> </div> </div> </div> @endsection
Add a comment on HAR encoding.
#!/usr/bin/env python import datetime import json import logging import urllib2 class HarManager(object): def __init__(self, args): self._logger = logging.getLogger('kcaa.proxy_util') self.pageref = 1 proxy_root = 'http://{}/proxy/{}'.format(args.proxy_controller, args.proxy.partition(':')[2]) self.har = '{}/har'.format(proxy_root) self.har_pageref = '{}/har/pageref' def _get(self, url): try: return urllib2.urlopen(url) except urllib2.URLError as e: self._logger.error('Proxy error: {}'.format(e)) return None def get_next_page(self): start = datetime.datetime.now() data = self._get(self.har) if not data: return None end = datetime.datetime.now() content = data.read() # No Content-Length header? content_size = len(content) self._logger.debug('Poke HAR ({:.1f} KiB) in {:.2f} seconds.'.format( (1.0 / 1024) * content_size, (end - start).total_seconds())) # HAR content should always be encoded in UTF-8, according to the spec. return json.loads(content, encoding='utf8')
#!/usr/bin/env python import datetime import json import logging import urllib2 class HarManager(object): def __init__(self, args): self._logger = logging.getLogger('kcaa.proxy_util') self.pageref = 1 proxy_root = 'http://{}/proxy/{}'.format(args.proxy_controller, args.proxy.partition(':')[2]) self.har = '{}/har'.format(proxy_root) self.har_pageref = '{}/har/pageref' def _get(self, url): try: return urllib2.urlopen(url) except urllib2.URLError as e: self._logger.error('Proxy error: {}'.format(e)) return None def get_next_page(self): start = datetime.datetime.now() data = self._get(self.har) if not data: return None end = datetime.datetime.now() content = data.read() # No Content-Length header? content_size = len(content) self._logger.debug('Poke HAR ({:.1f} KiB) in {:.2f} seconds.'.format( (1.0 / 1024) * content_size, (end - start).total_seconds())) return json.loads(content)
Add stealth address to scope.
define(['./module', 'darkwallet'], function (controllers, DarkWallet) { 'use strict'; controllers.controller('ReceiveStealthCtrl', ['$scope', 'notify', function($scope, notify) { // function to receive stealth information $scope.receiveStealth = function() { notify.note("stealth", "initializing"); notify.progress.start(); var client = DarkWallet.getClient(); var stealth_fetched = function(error, results) { if (error) { console.log("error on stealth"); notify.error("stealth", error); //write_to_screen('<span style="color: red;">ERROR:</span> ' + error); return; } console.log("fetching stealth", results); var addresses; try { addresses = $scope.identity.wallet.processStealth(results); } catch (e) { notify.error("stealth", e.message); return; } if (addresses && addresses.length) { var walletService = DarkWallet.service.wallet; addresses.forEach(function(walletAddress) { // TODO: should be added to scope in response to some event $scope.addToScope(walletAddress); walletService.initAddress(walletAddress); }) notify.success("stealth ok", addresses.length + " payments detected"); } else { notify.success("stealth ok"); } } client.fetch_stealth([0,0], stealth_fetched, 0); }; }]); });
define(['./module', 'darkwallet'], function (controllers, DarkWallet) { 'use strict'; controllers.controller('ReceiveStealthCtrl', ['$scope', 'notify', function($scope, notify) { // function to receive stealth information $scope.receiveStealth = function() { notify.note("stealth", "initializing"); notify.progress.start(); var client = DarkWallet.getClient(); var stealth_fetched = function(error, results) { if (error) { console.log("error on stealth"); notify.error("stealth", error); //write_to_screen('<span style="color: red;">ERROR:</span> ' + error); return; } console.log("fetching stealth", results); var addresses; try { addresses = $scope.identity.wallet.processStealth(results); } catch (e) { notify.error("stealth", e.message); return; } if (addresses && addresses.length) { var walletService = DarkWallet.service.wallet; addresses.forEach(function(walletAddress) { walletService.initAddress(walletAddress); }) notify.success("stealth ok", addresses.length + " payments detected"); } else { notify.success("stealth ok"); } } client.fetch_stealth([0,0], stealth_fetched, 0); }; }]); });
Add tests folder to lint task
'use strict'; var path = require('path'); var argv = require('yargs').default('browser', true).argv; var pkg = require('../package.json'); var dest = 'build'; var src = 'src'; var tests = 'tests'; var ENVIRONMENT = argv.env || process.env.env || 'development'; var APP_NAME = pkg.name; module.exports = { environment: ENVIRONMENT, license: { src: '../LICENSE' }, tests: { failTask: false, forceKarmaExit: { onSuccess: true, onFailure: true } }, src: src, jsdoc: { src: src, readme: './README.md', dest: './docs', template: './node_modules/ink-docstrap/template', configFile: './gulpfile.js/doc_config.js' }, lint: { src: [ path.join(src, '**', '*.js'), path.join(tests, '**', '*.js'), ] }, browserify: { // A separate bundle will be generated for each // bundle config in the list below debug: true, // debug mode for browserify (sourcemaps) watch: false, // should we use watchify bundleConfigs: [ { entries: 'index.js', dest: dest, outputName: APP_NAME + '.js' } ] }, // @TODO what 'production' means in this context is not obvious. // I.e. why are no other environments defined? production: { jsSrc: path.join(dest, '**', '*.js'), dest: dest } };
'use strict'; var path = require('path'); var argv = require('yargs').default('browser', true).argv; var pkg = require('../package.json'); var dest = 'build'; var src = 'src'; var ENVIRONMENT = argv.env || process.env.env || 'development'; var APP_NAME = pkg.name; module.exports = { environment: ENVIRONMENT, license: { src: '../LICENSE' }, tests: { failTask: false, forceKarmaExit: { onSuccess: true, onFailure: true } }, src: src, jsdoc: { src: src, readme: './README.md', dest: './docs', template: './node_modules/ink-docstrap/template', configFile: './gulpfile.js/doc_config.js' }, lint: { src: [ path.join(src, '**', '*.js'), ] }, browserify: { // A separate bundle will be generated for each // bundle config in the list below debug: true, // debug mode for browserify (sourcemaps) watch: false, // should we use watchify bundleConfigs: [ { entries: 'index.js', dest: dest, outputName: APP_NAME + '.js' } ] }, // @TODO what 'production' means in this context is not obvious. // I.e. why are no other environments defined? production: { jsSrc: path.join(dest, '**', '*.js'), dest: dest } };
Set mongo id in database after command was consumed
<?php namespace Command; use Database\Connect; use Config\Config; use Database\Query; class setData { /** * setData constructor. * * @param \Aura\Web\Request $request * @param \Aura\Web\Response $response * @param \Aura\View\View $view */ public function __construct($request, $response, $view) { $status = 'success'; $message = 'Data updated successfully.'; $secureToken = (new Config)->getConfig()['secure_token']; $retrievedSecureToken = $request->query->get('key', ''); if ($secureToken !== $retrievedSecureToken) { $status = 'error'; $message = 'Incorrect secure token.'; } else { $post = $request->post; $commandId = $post->get('command_id', null); $consumedDate = $post->get('command_consumed_date_time', '0000-00-00 00:00:00'); $mongoId = $post->get('mongo_id', null); if ($commandId) { $query = (new Query) ->update() ->table('commands') ->cols([ 'consumed' => 1, 'command_consumed_date_time' => $consumedDate, 'mongo_id' => $mongoId, ]) ->where('command_id = ?', $commandId); (new Connect)->query($query); } } $view->setData([ 'status' => $status, 'message' => $message, ]); $response->content->set($view->__invoke()); } }
<?php namespace Command; use Database\Connect; use Config\Config; use Database\Query; class setData { /** * setData constructor. * * @param \Aura\Web\Request $request * @param \Aura\Web\Response $response * @param \Aura\View\View $view */ public function __construct($request, $response, $view) { $status = 'success'; $message = 'Data updated successfully.'; $secureToken = (new Config)->getConfig()['secure_token']; $retrievedSecureToken = $request->query->get('key', ''); if ($secureToken !== $retrievedSecureToken) { $status = 'error'; $message = 'Incorrect secure token.'; } else { $post = $request->post; $commandId = $post->get('command_id', null); $consumedDate = $post->get('command_consumed_date_time', '0000-00-00 00:00:00'); if ($commandId) { $query = (new Query) ->update() ->table('commands') ->cols([ 'consumed' => 1, 'command_consumed_date_time' => $consumedDate, ]) ->where('command_id = ?', $commandId); (new Connect)->query($query); } } $view->setData([ 'status' => $status, 'message' => $message, ]); $response->content->set($view->__invoke()); } }
Change from planning to in beta
import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info <= (2, 4): error = 'Requires Python Version 2.5 or above... exiting.' print >> sys.stderr, error sys.exit(1) requirements = [ 'requests', ] setup(name='googlemaps', version='2.0-dev', description='API Client library for Google Maps', scripts=[], url='https://github.com/googlemaps/google-maps-services-python', packages=['googlemaps'], license='Apache 2.0', platforms='Posix; MacOS X; Windows', setup_requires=requirements, install_requires=requirements, classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Topic :: Internet', ] )
import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info <= (2, 4): error = 'Requires Python Version 2.5 or above... exiting.' print >> sys.stderr, error sys.exit(1) requirements = [ 'requests', ] setup(name='googlemaps', version='2.0-dev', description='API Client library for Google Maps', scripts=[], url='https://github.com/googlemaps/google-maps-services-python', packages=['googlemaps'], license='Apache 2.0', platforms='Posix; MacOS X; Windows', setup_requires=requirements, install_requires=requirements, classifiers=['Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Topic :: Internet', ] )
Fix login with active dominion not being redirect to status screen
<?php namespace OpenDominion\Http\Controllers\Auth; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use OpenDominion\Http\Controllers\AbstractController; use OpenDominion\Models\User; use OpenDominion\Services\AnalyticsService; use OpenDominion\Services\DominionSelectorService; class LoginController extends AbstractController { use AuthenticatesUsers; protected $redirectTo = '/dashboard'; public function getLogin() { return view('pages.auth.login'); } public function postLogin(Request $request) { return $this->login($request); } protected function authenticated(Request $request, User $user) { if ($user->dominions->count() === 1) { $dominionSelectorService = app()->make(DominionSelectorService::class); $dominionSelectorService->selectUserDominion($user->dominions->first()); $this->redirectTo = '/dominion/status'; } // todo: fire laravel event $analyticsService = app()->make(AnalyticsService::class); $analyticsService->queueFlashEvent(new AnalyticsService\Event( 'user', 'login' )); } public function postLogout(Request $request) { $response = $this->logout($request); // todo: fire laravel event $analyticsService = app()->make(AnalyticsService::class); $analyticsService->queueFlashEvent(new AnalyticsService\Event( 'user', 'logout' )); session()->flash('alert-success', 'You have been logged out.'); return $response; } }
<?php namespace OpenDominion\Http\Controllers\Auth; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use OpenDominion\Http\Controllers\AbstractController; use OpenDominion\Models\User; use OpenDominion\Services\AnalyticsService; use OpenDominion\Services\DominionSelectorService; class LoginController extends AbstractController { use AuthenticatesUsers; protected $redirectTo = '/dashboard'; public function getLogin() { return view('pages.auth.login'); } public function postLogin(Request $request) { return $this->login($request); } protected function authenticated(Request $request, User $user) { if ($user->dominions->count() === 1) { $dominionSelectorService = app()->make(DominionSelectorService::class); $dominionSelectorService->selectUserDominion($user->dominions->first()); } // todo: fire laravel event $analyticsService = app()->make(AnalyticsService::class); $analyticsService->queueFlashEvent(new AnalyticsService\Event( 'user', 'login' )); } public function postLogout(Request $request) { $response = $this->logout($request); // todo: fire laravel event $analyticsService = app()->make(AnalyticsService::class); $analyticsService->queueFlashEvent(new AnalyticsService\Event( 'user', 'logout' )); session()->flash('alert-success', 'You have been logged out.'); return $response; } }
Check for known file extensions
require(['ByteSource', 'AppleVolume'], function(ByteSource, AppleVolume) { 'use strict'; function makeFileDrop(el, callback) { if (typeof el === 'string') { el = document.getElementById(el); if (!el) { console.error('filedrop element not found'); return; } el.addEventListener('dragenter', function(e) { el.classList.add('dropping'); }); el.addEventListener('dragleave', function(e) { el.classList.remove('dropping'); }); el.addEventListener('dragover', function(e) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }); el.addEventListener('drop', function(e) { e.stopPropagation(); e.preventDefault(); el.classList.remove('dropping'); if (e.dataTransfer.files[0]) { callback(e.dataTransfer.files[0]); } }); el.classList.add('drop-target'); } } makeFileDrop('drop-zone', function(droppedFile) { if (\.(iso|toast|dsk|img)$/i.test(droppedFile.name)) { var byteSource = ByteSource.from(droppedFile); var appleVolume = new AppleVolume(byteSource); appleVolume.read({ onvolumestart: function(masterDirectoryBlock) { console.log(masterDirectoryBlock); } }); } else { console.log(droppedFile.name); } }); });
require(['ByteSource', 'AppleVolume'], function(ByteSource, AppleVolume) { 'use strict'; function makeFileDrop(el, callback) { if (typeof el === 'string') { el = document.getElementById(el); if (!el) { console.error('filedrop element not found'); return; } el.addEventListener('dragenter', function(e) { el.classList.add('dropping'); }); el.addEventListener('dragleave', function(e) { el.classList.remove('dropping'); }); el.addEventListener('dragover', function(e) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }); el.addEventListener('drop', function(e) { e.stopPropagation(); e.preventDefault(); el.classList.remove('dropping'); if (e.dataTransfer.files[0]) { callback(e.dataTransfer.files[0]); } }); el.classList.add('drop-target'); } } makeFileDrop('drop-zone', function(droppedFile) { var byteSource = ByteSource.from(droppedFile); var appleVolume = new AppleVolume(byteSource); appleVolume.read({ onvolumestart: function(masterDirectoryBlock) { console.log(masterDirectoryBlock); } }); }); });
parity-client: Simplify command name length calculation
package com.paritytrading.parity.client.command; import com.paritytrading.parity.client.TerminalClient; import java.util.Scanner; class HelpCommand implements Command { @Override public void execute(TerminalClient client, Scanner arguments) throws CommandException { if (arguments.hasNext()) { Command command = Commands.find(arguments.next()); if (arguments.hasNext()) throw new CommandException(); if (command != null) displayCommandHelp(client, command); else displayGeneralHelp(client); } else { displayGeneralHelp(client); } } private void displayGeneralHelp(TerminalClient client) { client.printf("Commands:\n"); int maxCommandNameLength = calculateMaxCommandNameLength(); for (Command command : Commands.all()) client.printf(" %-" + maxCommandNameLength + "s %s\n", command.getName(), command.getDescription()); client.printf("\nType 'help <command>' for command specific help.\n"); } private void displayCommandHelp(TerminalClient client, Command command) { client.printf("Usage: %s\n\n %s\n\n", command.getUsage(), command.getDescription()); } private int calculateMaxCommandNameLength() { return Commands.names().collectInt(String::length).max(); } @Override public String getName() { return "help"; } @Override public String getDescription() { return "Display the help"; } @Override public String getUsage() { return "help [command]"; } }
package com.paritytrading.parity.client.command; import com.paritytrading.parity.client.TerminalClient; import java.util.Scanner; class HelpCommand implements Command { @Override public void execute(TerminalClient client, Scanner arguments) throws CommandException { if (arguments.hasNext()) { Command command = Commands.find(arguments.next()); if (arguments.hasNext()) throw new CommandException(); if (command != null) displayCommandHelp(client, command); else displayGeneralHelp(client); } else { displayGeneralHelp(client); } } private void displayGeneralHelp(TerminalClient client) { client.printf("Commands:\n"); int maxCommandNameLength = calculateMaxCommandNameLength(); for (Command command : Commands.all()) client.printf(" %-" + maxCommandNameLength + "s %s\n", command.getName(), command.getDescription()); client.printf("\nType 'help <command>' for command specific help.\n"); } private void displayCommandHelp(TerminalClient client, Command command) { client.printf("Usage: %s\n\n %s\n\n", command.getUsage(), command.getDescription()); } private int calculateMaxCommandNameLength() { return Commands.all().collectInt(c -> c.getName().length()).max(); } @Override public String getName() { return "help"; } @Override public String getDescription() { return "Display the help"; } @Override public String getUsage() { return "help [command]"; } }
Make sure the app menu state is set
(function () { 'use strict'; function EditorMenuDirective($injector, treeService, navigationService, umbModelMapper, appState) { function link(scope, el, attr, ctrl) { scope.dropdown = { isOpen: false }; function onInit() { getOptions(); } //adds a handler to the context menu item click, we need to handle this differently //depending on what the menu item is supposed to do. scope.executeMenuItem = function (action) { navigationService.executeMenuAction(action, scope.currentNode, scope.currentSection); scope.dropdown.isOpen = false; }; //callback method to go and get the options async function getOptions() { if (!scope.currentNode) { return; } //when the options item is selected, we need to set the current menu item in appState (since this is synonymous with a menu) //- otherwise we break any tree dialog that works with the current node (and that's pretty much all of them) appState.setMenuState("currentNode", scope.currentNode); if (!scope.actions) { treeService.getMenu({ treeNode: scope.currentNode }) .then(function (data) { scope.actions = data.menuItems; }); } }; onInit(); } var directive = { restrict: 'E', replace: true, templateUrl: 'views/components/editor/umb-editor-menu.html', link: link, scope: { currentNode: "=", currentSection: "@" } }; return directive; } angular.module('umbraco.directives').directive('umbEditorMenu', EditorMenuDirective); })();
(function () { 'use strict'; function EditorMenuDirective($injector, treeService, navigationService, umbModelMapper, appState) { function link(scope, el, attr, ctrl) { scope.dropdown = { isOpen: false }; function onInit() { getOptions(); } //adds a handler to the context menu item click, we need to handle this differently //depending on what the menu item is supposed to do. scope.executeMenuItem = function (action) { navigationService.executeMenuAction(action, scope.currentNode, scope.currentSection); scope.dropdown.isOpen = false; }; //callback method to go and get the options async function getOptions() { if (!scope.currentNode) { return; } //when the options item is selected, we need to set the current menu item in appState (since this is synonymous with a menu) // Niels: No i think we are wrong, we should not set the currentNode, cause it represents the currentNode of interaction. //appState.setMenuState("currentNode", scope.currentNode); if (!scope.actions) { treeService.getMenu({ treeNode: scope.currentNode }) .then(function (data) { scope.actions = data.menuItems; }); } }; onInit(); } var directive = { restrict: 'E', replace: true, templateUrl: 'views/components/editor/umb-editor-menu.html', link: link, scope: { currentNode: "=", currentSection: "@" } }; return directive; } angular.module('umbraco.directives').directive('umbEditorMenu', EditorMenuDirective); })();
Use more sane numbers for initial data
from orbit import satellite from django.core.management.base import BaseCommand from base.tests import ObservationFactory, StationFactory from base.models import Satellite class Command(BaseCommand): help = 'Create initial fixtures' def handle(self, *args, **options): ObservationFactory.create_batch(20) StationFactory.create_batch(20) satellites = Satellite.objects.all() for obj in satellites: try: sat = satellite(obj.norad_cat_id) except: self.stdout.write(('Satellite {} with Identifier {} does ' 'not exist [deleted]').format(obj.name, obj.norad_cat_id)) obj.delete() continue obj.name = sat.name() tle = sat.tle() obj.tle0 = tle[0] obj.tle1 = tle[1] obj.tle2 = tle[2] obj.save() self.stdout.write(('Satellite {} with Identifier {} ' 'found [updated]').format(obj.norad_cat_id, obj.name))
from orbit import satellite from django.core.management.base import BaseCommand from base.tests import ObservationFactory, StationFactory from base.models import Satellite class Command(BaseCommand): help = 'Create initial fixtures' def handle(self, *args, **options): ObservationFactory.create_batch(200) StationFactory.create_batch(200) satellites = Satellite.objects.all() for obj in satellites: try: sat = satellite(obj.norad_cat_id) except: self.stdout.write(('Satellite {} with Identifier {} does ' 'not exist [deleted]').format(obj.name, obj.norad_cat_id)) obj.delete() continue obj.name = sat.name() tle = sat.tle() obj.tle0 = tle[0] obj.tle1 = tle[1] obj.tle2 = tle[2] obj.save() self.stdout.write(('Satellite {} with Identifier {} ' 'found [updated]').format(obj.norad_cat_id, obj.name))
Fix window size before running tests To make tests as repeatable as possible.
const wd = require('wd'); const Promise = require('bluebird'); const browser = require('./browser'); const normalise = require('./normalise-logs'); function test (opts) { return function () { return Promise.using(browser(opts.browser), (session) => { return session .setWindowSize(1024, 768) .get(opts.url) .then(() => { return Promise.resolve() .then(() => { if (opts.scroll || opts.reporter === 'fps') { return session.execute('function f () { window.scrollBy(0,5); window.requestAnimationFrame(f); } window.requestAnimationFrame(f);'); } }) .then(() => { if (typeof opts.inject === 'function') { return opts.inject(session); } }) .then(() => { return session.waitFor(wd.asserters.jsCondition(`document.readyState==='complete'`), 120000) .catch(() => { console.error('Page loading timed out after 120s'); }); }) .then(() => { return session; }); }) .sleep(opts.sleep) .log('performance') .then((logs) => { return normalise(logs, opts.url); }); }); }; } module.exports = test;
const wd = require('wd'); const Promise = require('bluebird'); const browser = require('./browser'); const normalise = require('./normalise-logs'); function test (opts) { return function () { return Promise.using(browser(opts.browser), (session) => { return session .get(opts.url) .then(() => { return Promise.resolve() .then(() => { if (opts.scroll || opts.reporter === 'fps') { return session.execute('function f () { window.scrollBy(0,5); window.requestAnimationFrame(f); } window.requestAnimationFrame(f);'); } }) .then(() => { if (typeof opts.inject === 'function') { return opts.inject(session); } }) .then(() => { return session.waitFor(wd.asserters.jsCondition(`document.readyState==='complete'`), 120000) .catch(() => { console.error('Page loading timed out after 120s'); }); }) .then(() => { return session; }); }) .sleep(opts.sleep) .log('performance') .then((logs) => { return normalise(logs, opts.url); }); }); }; } module.exports = test;
Test added for retrieval under views-expired scenario.
<?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use Faker\Generator; use Rhumsaa\Uuid\Uuid; class SecretTest extends TestCase { use DatabaseTransactions; /** * Test secret creation. * * @return void */ public function testCreateSecret() { $this->visit('/create') ->type('a secret', 'secret') ->press('Submit') ->see('/show/') ->seePageIs('/store'); } /** * Test secret retrieval. * * @return void */ public function testRetrieveSecret() { $faker = Faker\Factory::create(); $secret_intermediate = $faker->word(32); $secret = Crypt::encrypt($secret_intermediate); $uuid4_intermediate = Uuid::uuid4(); $uuid4 = Hash::make($uuid4_intermediate); $secret = factory(App\Secret::class)->create([ 'uuid4' => $uuid4, 'secret' => $secret ]); $this->visit('/show/' . $uuid4_intermediate) ->see($secret_intermediate); } /** * Test views-expired secret retrieval. * * @return void */ public function testRetrieveViewsExpiredSecret() { $faker = Faker\Factory::create(); $secret_intermediate = $faker->word(32); $secret = Crypt::encrypt($secret_intermediate); $uuid4_intermediate = Uuid::uuid4(); $uuid4 = Hash::make($uuid4_intermediate); $count_views = $faker->numberBetween(5,1000); $secret = factory(App\Secret::class)->create([ 'uuid4' => $uuid4, 'secret' => $secret, 'expires_views' => $count_views, 'count_views' => $count_views ]); $this->visit('/show/' . $uuid4_intermediate) ->see('Secret not found.'); } }
<?php use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use Faker\Generator; use Rhumsaa\Uuid\Uuid; class SecretTest extends TestCase { use DatabaseTransactions; /** * Test secret creation. * * @return void */ public function testCreateSecret() { $this->visit('/create') ->type('a secret', 'secret') ->press('Submit') ->see('/show/') ->seePageIs('/store'); } /** * Test secret retrieval. * * @return void */ public function testRetrieveSecret() { $faker = Faker\Factory::create(); $secret_intermediate = $faker->word(32); $secret = Crypt::encrypt($secret_intermediate); $uuid4_intermediate = Uuid::uuid4(); $uuid4 = Hash::make($uuid4_intermediate); $secret = factory(App\Secret::class)->create([ 'uuid4' => $uuid4, 'secret' => $secret ]); $this->visit('/show/' . $uuid4_intermediate) ->see($secret_intermediate); } }
Add project run to project result.
from __future__ import absolute_import import logging import traceback from celery import shared_task from celery.utils.log import get_task_logger from datastore.models import ProjectRun logger = get_task_logger(__name__) @shared_task def execute_project_run(project_run_pk): try: project_run = ProjectRun.objects.get(pk=project_run_pk) except ProjectRun.DoesNotExist: logger.info("Received an invalid project_run_pk %s" % project_run_pk) return project_run.status = 'RUNNING' project_run.save() project = project_run.project logger.info( "Running {} meter for project {}" .format(project_run.meter_class, project.pk) ) try: project.run_meter(meter_class=project_run.meter_class, meter_settings=project_run.meter_settings, project_run=project_run) project_run.status = 'SUCCESS' logger.info( "Successfully ran {} meter for project {}" .format(project_run.meter_class, project.pk) ) except: tb = traceback.format_exc() project_run.status = 'FAILED' project_run.traceback = tb logger.info( "Failed running {} meter for project {}:\n{}" .format(project_run.meter_class, project.pk, tb) ) logging.error(traceback.print_exc()) project_run.save()
from __future__ import absolute_import import logging import traceback from celery import shared_task from celery.utils.log import get_task_logger from datastore.models import ProjectRun logger = get_task_logger(__name__) @shared_task def execute_project_run(project_run_pk): try: project_run = ProjectRun.objects.get(pk=project_run_pk) except ProjectRun.DoesNotExist: logger.info("Received an invalid project_run_pk %s" % project_run_pk) return project_run.status = 'RUNNING' project_run.save() project = project_run.project logger.info( "Running {} meter for project {}" .format(project_run.meter_class, project.pk) ) try: project.run_meter(meter_class=project_run.meter_class, meter_settings=project_run.meter_settings) project_run.status = 'SUCCESS' logger.info( "Successfully ran {} meter for project {}" .format(project_run.meter_class, project.pk) ) except: tb = traceback.format_exc() project_run.status = 'FAILED' project_run.traceback = tb logger.info( "Failed running {} meter for project {}:\n{}" .format(project_run.meter_class, project.pk, tb) ) logging.error(traceback.print_exc()) project_run.save()
Add @xstate/graph to changeset-managed packages
const { exec } = require('@actions/exec'); const getWorkspaces = require('get-workspaces').default; async function execWithOutput(command, args, options) { let myOutput = ''; let myError = ''; return { code: await exec(command, args, { listeners: { stdout: data => { myOutput += data.toString(); }, stderr: data => { myError += data.toString(); } }, ...options }), stdout: myOutput, stderr: myError }; } const publishablePackages = [ 'xstate', '@xstate/fsm', '@xstate/graph', '@xstate/test' ]; (async () => { const currentBranchName = ( await execWithOutput('git', ['rev-parse', '--abbrev-ref', 'HEAD']) ).stdout.trim(); if (!/^changeset-release\//.test(currentBranchName)) { return; } const latestCommitMessage = ( await execWithOutput('git', ['log', '-1', '--pretty=%B']) ).stdout.trim(); await exec('git', ['reset', '--mixed', 'HEAD~1']); const workspaces = await getWorkspaces(); for (let workspace of workspaces) { if (publishablePackages.includes(workspace.name)) { continue; } await exec('git', ['checkout', '--', workspace.dir]); } await exec('git', ['add', '.']); await exec('git', ['commit', '-m', latestCommitMessage]); await exec('git', ['push', 'origin', currentBranchName, '--force']); })();
const { exec } = require('@actions/exec'); const getWorkspaces = require('get-workspaces').default; async function execWithOutput(command, args, options) { let myOutput = ''; let myError = ''; return { code: await exec(command, args, { listeners: { stdout: data => { myOutput += data.toString(); }, stderr: data => { myError += data.toString(); } }, ...options }), stdout: myOutput, stderr: myError }; } const publishablePackages = ['xstate', '@xstate/fsm', '@xstate/test']; (async () => { const currentBranchName = (await execWithOutput('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ])).stdout.trim(); if (!/^changeset-release\//.test(currentBranchName)) { return; } const latestCommitMessage = (await execWithOutput('git', [ 'log', '-1', '--pretty=%B' ])).stdout.trim(); await exec('git', ['reset', '--mixed', 'HEAD~1']); const workspaces = await getWorkspaces(); for (let workspace of workspaces) { if (publishablePackages.includes(workspace.name)) { continue; } await exec('git', ['checkout', '--', workspace.dir]); } await exec('git', ['add', '.']); await exec('git', ['commit', '-m', latestCommitMessage]); await exec('git', ['push', 'origin', currentBranchName, '--force']); })();
Use __dirname when setting the root
// require Johnny's static var JohhnysStatic = require("../index") // require http , http = require('http'); // set static server: public folder JohhnysStatic.setStaticServer({root: __dirname + "/public"}); // set routes JohhnysStatic.setRoutes({ "/": { "url": "/html/index.html" } , "/test1/": { "url": "/html/test1.html" } , "/test2/": { "url": "/html/test2.html" } }); // create http server http.createServer(function(req, res) { // safe serve if (JohhnysStatic.exists(req, res)) { // serve file JohhnysStatic.serve(req, res, function (err) { // not found error if (err.code === "ENOENT") { // write head res.writeHead(404, {"Content-Type": "text/html"}); // send response res.end("404 - Not found."); // return return; } // other error res.end(JSON.stringify(err)); }); // return return; } // if the route doesn't exist, it's a 404! res.end("404 - Not found"); }).listen(8000); // output console.log("Listening on 8000.");
// require Johnny's static var JohhnysStatic = require("../index") // require http , http = require('http'); // set static server: public folder JohhnysStatic.setStaticServer({root: "./public"}); // set routes JohhnysStatic.setRoutes({ "/": { "url": __dirname + "/html/index.html" } , "/test1/": { "url": __dirname + "/html/test1.html" } , "/test2/": { "url": __dirname + "/html/test2.html" } }); // create http server http.createServer(function(req, res) { // safe serve if (JohhnysStatic.exists(req, res)) { // serve file JohhnysStatic.serve(req, res, function (err) { // not found error if (err.code === "ENOENT") { // write head res.writeHead(404, {"Content-Type": "text/html"}); // send response res.end("404 - Not found."); // return return; } // other error res.end(JSON.stringify(err)); }); // return return; } // if the route doesn't exist, it's a 404! res.end("404 - Not found"); }).listen(8000); // output console.log("Listening on 8000.");
Fix React error from missing keys
import React from "react"; import { GraphManager } from "./index"; export default class AbstractGraph extends React.Component { constructor(props) { super(props); let properties; try { // TODO: Make sure the name is not going to change in the build properties = require("./" + this.constructor.name + "/default.config.js").properties; } catch (err) { properties = {}; } this.defaults = GraphManager.getDefaultProperties(properties); } getConfiguredProperties() { return Object.assign({}, this.defaults, this.props.configuration.data); } applyColor(index) { const { colors } = this.getConfiguredProperties(); return colors[index % colors.length]; } getTooltipContent() { const { tooltip } = this.getConfiguredProperties(); const d = this.hoveredDatum; if(tooltip && d) { return ( <div> {tooltip.map(({column}) => ( <div key={column}> <strong>{column}</strong> : {d[column]} </div> ))} </div> ); } else { return null; } } }
import React from "react"; import { GraphManager } from "./index"; export default class AbstractGraph extends React.Component { constructor(props) { super(props); let properties; try { // TODO: Make sure the name is not going to change in the build properties = require("./" + this.constructor.name + "/default.config.js").properties; } catch (err) { properties = {}; } this.defaults = GraphManager.getDefaultProperties(properties); } getConfiguredProperties() { return Object.assign({}, this.defaults, this.props.configuration.data); } applyColor(index) { const { colors } = this.getConfiguredProperties(); return colors[index % colors.length]; } getTooltipContent() { const { tooltip } = this.getConfiguredProperties(); const d = this.hoveredDatum; if(tooltip && d) { return ( <div> {tooltip.map(({column}) => ( <div> <strong>{column}</strong> : {d[column]} </div> ))} </div> ); } else { return null; } } }
Change location of static files on server
from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/nkhumphreys/assets/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd)
from fabric.api import local, env, sudo env.hosts = ['nkhumphreys.co.uk'] env.user = 'root' NAME = "gobananas" def deploy(): base_cmd = "scp -r {local_path} root@{host}:{remote_path}" remote_path = "/tmp" template_path = "/var/www/templates/" static_path = "/var/www/static/" for h in env.hosts: cmd = base_cmd.format(local_path=NAME, host=h, remote_path=remote_path) local(cmd) cmd = base_cmd.format(local_path="./templates/*", host=h, remote_path=template_path) local(cmd) cmd = base_cmd.format(local_path="./static/*", host=h, remote_path=static_path) local(cmd) sudo("mv %s/%s /usr/bin" % (remote_path, NAME)) sudo("supervisorctl restart %s" % NAME) def logs(): cmd = "tail -f /var/log/supervisor/{name}-*.log" cmd = cmd.format(name=NAME) sudo(cmd)
Remove unneeded noParse build rules
'use strict'; const path = require('path'); const loaders = require('./webpack/loaders'); const plugins = require('./webpack/plugins'); module.exports = { entry: { app: './src/index.ts', // and vendor files separate vendor: [ '@angular/core', '@angular/compiler', '@angular/common', '@angular/http', '@angular/platform-browser', '@angular/platform-browser-dynamic', '@angular/router', 'core-js', 'rxjs', 'immutable', ], }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[hash].js', publicPath: '/', sourceMapFilename: '[name].[hash].js.map', chunkFilename: '[id].chunk.js', }, devtool: process.env.NODE_ENV === 'production' ? 'source-map' : 'inline-source-map', resolve: { extensions: ['.webpack.js', '.web.js', '.ts', '.js'], }, plugins: plugins, devServer: { historyApiFallback: { index: '/' }, proxy: {}, }, module: { rules: [ loaders.angular, loaders.tslint, loaders.ts, loaders.html, loaders.css, loaders.svg, loaders.eot, loaders.woff, loaders.woff2, loaders.ttf, ], }, };
'use strict'; const path = require('path'); const loaders = require('./webpack/loaders'); const plugins = require('./webpack/plugins'); module.exports = { entry: { app: './src/index.ts', // and vendor files separate vendor: [ '@angular/core', '@angular/compiler', '@angular/common', '@angular/http', '@angular/platform-browser', '@angular/platform-browser-dynamic', '@angular/router', 'core-js', 'rxjs', 'immutable', ], }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[hash].js', publicPath: '/', sourceMapFilename: '[name].[hash].js.map', chunkFilename: '[id].chunk.js', }, devtool: process.env.NODE_ENV === 'production' ? 'source-map' : 'inline-source-map', resolve: { extensions: ['.webpack.js', '.web.js', '.ts', '.js'], }, plugins: plugins, devServer: { historyApiFallback: { index: '/' }, proxy: {}, }, module: { rules: [ loaders.angular, loaders.tslint, loaders.ts, loaders.html, loaders.css, loaders.svg, loaders.eot, loaders.woff, loaders.woff2, loaders.ttf, ], noParse: [/zone\.js\/dist\/.+/, /angular2\/bundles\/.+/], }, };
Fix Direct parser's token separator The idea is to support tabs as a separator, besides spaces.
package pt.ist.rc.paragraph.loader.direct; import pt.ist.rc.paragraph.model.Graph; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.function.Function; public class DirectLoader<VV, EV> { private final Reader r; private final Function<String, VV> loadVertexDataFunction; private final Function<String, EV> loadEdgeDataFunction; public DirectLoader(Reader r, Function<String, VV> loadVertexDataFunction, Function<String, EV> loadEdgeDataFunction) { this.r = r; this.loadVertexDataFunction = loadVertexDataFunction; this.loadEdgeDataFunction = loadEdgeDataFunction; } public DirectLoader(Reader r) { this(r, x -> null, x -> null); } public Graph<VV, EV> load() throws IOException { Graph.BuilderEdges<VV, EV> partialGraph = new Graph.BuilderEdges<>(); try(BufferedReader br = new BufferedReader(r)) { for(String line = br.readLine(); line != null; line = br.readLine()) { // TODO: Check what happens when reader is empty if (line.startsWith("#")) continue; final String[] idxs = line.split("\\s"); int fromIdx = Integer.parseInt(idxs[0]); int toIdx = Integer.parseInt(idxs[1]); partialGraph.addEdge(fromIdx, toIdx); } } return partialGraph.build(); } }
package pt.ist.rc.paragraph.loader.direct; import pt.ist.rc.paragraph.model.Graph; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.function.Function; public class DirectLoader<VV, EV> { private final Reader r; private final Function<String, VV> loadVertexDataFunction; private final Function<String, EV> loadEdgeDataFunction; public DirectLoader(Reader r, Function<String, VV> loadVertexDataFunction, Function<String, EV> loadEdgeDataFunction) { this.r = r; this.loadVertexDataFunction = loadVertexDataFunction; this.loadEdgeDataFunction = loadEdgeDataFunction; } public DirectLoader(Reader r) { this(r, x -> null, x -> null); } public Graph<VV, EV> load() throws IOException { Graph.BuilderEdges<VV, EV> partialGraph = new Graph.BuilderEdges<>(); try(BufferedReader br = new BufferedReader(r)) { for(String line = br.readLine(); line != null; line = br.readLine()) { // TODO: Check what happens when reader is empty if (line.startsWith("#")) continue; final String[] idxs = line.split(" "); int fromIdx = Integer.parseInt(idxs[0]); int toIdx = Integer.parseInt(idxs[1]); partialGraph.addEdge(fromIdx, toIdx); } } return partialGraph.build(); } }
Fix form validator (lot cleaner)
//////////////////////////// // Form Validator factory // //////////////////////////// 'use strict'; pay.factory('FormValidator', [function () { return function (form, imageSelector, imageValidator) { var formValid = true; // Image validation if (typeof imageValidator !== 'undefined') { var $file = form[imageSelector]; var file = $file.files[0]; if (!file || (file.type !== 'image/png' && file.type !== 'image/jpeg')) { $($file).parent().parent().next().addClass('ng-invalid'); formValid = false; } else { $($file).parent().parent().next().removeClass('ng-invalid').addClass('ng-valid'); } } // Input validation var $invalids = $('.ng-pristine, .ng-invalid', form); var emptyForms = $invalids.filter(function () { console.log('On a un pristine ou un invalide', this) if ($(this).is(':visible') === false) { console.log('Bon ok il était pas visible le coco'); return false; } return this.value.length === 0; }); console.log('Champs problématiques : ', emptyForms); if (emptyForms.length !== 0) { emptyForms.removeClass('ng-pristine ng-valid').addClass('ng-invalid'); formValid = false; } return formValid; }; }]);
//////////////////////////// // Form Validator factory // //////////////////////////// 'use strict'; pay.factory('FormValidator', [function () { return function (form, imageSelector, imageValidator) { // If we end directly the function, all errors may be not thrown var formValid = true; // Image validation if (typeof imageValidator !== 'undefined') { var $file = form[imageSelector]; var file = $file.files[0]; if (!file || (file.type !== 'image/png' && file.type !== 'image/jpeg')) { $($file).parent().parent().next().addClass('ng-invalid'); formValid = false; } else { $($file).parent().parent().next().removeClass('ng-invalid').addClass('ng-valid'); } } // Input validation var isFormValid = $('.ng-pristine, .ng-invalid', form).filter(function () { return this.value.length === 0; }).length === 0; if (!isFormValid) { var $invalids = $('.ng-pristine, .ng-invalid', form).filter(function () { return this.value.length === 0; }); $invalids.removeClass('ng-pristine ng-valid').addClass('ng-invalid'); formValid = false; } return formValid; }; }]);
Set stage to maximized screen
package GUI; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; public class App extends Application { public static void main(String[] args) { launch(args); } public void start(Stage stageIn) throws UnsupportedEncodingException, FileNotFoundException { stage = stageIn; stage.setTitle("Programming Life"); loadScene("/FXML/Menu.fxml"); } private static Stage stage; private static AnchorPane pane; public static FXMLLoader loadScene(String path) { try { // Load the anchor pane FXMLLoader loader = new FXMLLoader(); loader.setLocation(App.class.getResource(path)); pane = loader.load(); // Set the pane onto the scene Scene scene = new Scene(pane); stage.setScene(scene); stage.setResizable(true); stage.setMaximized(true); stage.show(); System.out.println(path + " loaded on the stage"); return loader; } catch (IOException e) { e.printStackTrace(); System.out .println("Something went wrong while loading the fxml file"); } return null; } }
package GUI; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; public class App extends Application { public static void main(String[] args) { launch(args); } public void start(Stage stageIn) throws UnsupportedEncodingException, FileNotFoundException { stage = stageIn; stage.setTitle("Programming Life"); loadScene("/FXML/Menu.fxml"); } private static Stage stage; private static AnchorPane pane; public static FXMLLoader loadScene(String path) { try { // Load the anchor pane FXMLLoader loader = new FXMLLoader(); loader.setLocation(App.class.getResource(path)); pane = loader.load(); // Set the pane onto the scene Scene scene = new Scene(pane); stage.setScene(scene); stage.setResizable(true); stage.show(); System.out.println(path + " loaded on the stage"); return loader; } catch (IOException e) { e.printStackTrace(); System.out .println("Something went wrong while loading the fxml file"); } return null; } }
Stop doing an excessive amount of work in `diffusion.rawdiffquery` Ref T11665. Without `-n 1`, this logs the ENTIRE history of the repository. We actually get the right result, but this is egregiously slow. Add `-n 1` to return only one result. It appears that I wrote this wrong way back in 2011, in D953. This query is rarely used (until recently) which is likely why it has escaped notice for so long. Test Plan: Used Conduit console to execute `diffusion.rawdiffquery`. Got the same results but spent 8ms instead of 200ms executing this command, in a very small repository.
<?php final class DiffusionGitRawDiffQuery extends DiffusionRawDiffQuery { protected function newQueryFuture() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $commit = $this->getAnchorCommit(); $options = array( '-M', '-C', '--no-ext-diff', '--no-color', '--src-prefix=a/', '--dst-prefix=b/', '-U'.(int)$this->getLinesOfContext(), ); $against = $this->getAgainstCommit(); if ($against === null) { // Check if this is the root commit by seeing if it has parents, since // `git diff X^ X` does not work if "X" is the initial commit. list($parents) = $repository->execxLocalCommand( 'log -n 1 --format=%s %s --', '%P', $commit); if (strlen(trim($parents))) { $against = $commit.'^'; } else { $against = ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT; } } $path = $drequest->getPath(); if (!strlen($path)) { $path = '.'; } return $repository->getLocalCommandFuture( 'diff %Ls %s %s -- %s', $options, $against, $commit, $path); } }
<?php final class DiffusionGitRawDiffQuery extends DiffusionRawDiffQuery { protected function newQueryFuture() { $drequest = $this->getRequest(); $repository = $drequest->getRepository(); $commit = $this->getAnchorCommit(); $options = array( '-M', '-C', '--no-ext-diff', '--no-color', '--src-prefix=a/', '--dst-prefix=b/', '-U'.(int)$this->getLinesOfContext(), ); $against = $this->getAgainstCommit(); if ($against === null) { // Check if this is the root commit by seeing if it has parents, since // `git diff X^ X` does not work if "X" is the initial commit. list($parents) = $repository->execxLocalCommand( 'log --format=%s %s --', '%P', $commit); if (strlen(trim($parents))) { $against = $commit.'^'; } else { $against = ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT; } } $path = $drequest->getPath(); if (!strlen($path)) { $path = '.'; } return $repository->getLocalCommandFuture( 'diff %Ls %s %s -- %s', $options, $against, $commit, $path); } }
KiwiShell: Insert sleep when waiting user input
/* * Expand Eeadline object */ Readline.inputLine = function(){ let line = null ; while(line == null){ line = Readline.input() ; sleep(0.1) ; } console.print("\n") ; // insert newline after the input return line ; } Readline.inputInteger = function() { let result = null ; while(result == null){ let line = Readline.inputLine() ; let val = parseInt(line) ; if(!isNaN(val)){ result = val ; } } return result ; } Readline.menu = function(items){ let result = 0 ; let decided = false ; while(!decided){ for(let i=0 ; i<items.length ; i++){ console.print(`${i}: ${items[i]}\n`) ; } console.print("number> ") ; let line = Readline.inputLine() ; let num = parseInt(line) ; if(!isNaN(num)){ if(0<=num && num<items.length){ result = num ; decided = true; } else { console.error(`[Error] Unexpected value: ${num}\n`) ; } } else { console.error(`[Error] Not number value: ${line}\n`) ; } } return result ; }
/* * Expand Eeadline object */ Readline.inputLine = function(){ let line = null ; while(line == null){ line = Readline.input() ; } console.print("\n") ; // insert newline after the input return line ; } Readline.inputInteger = function() { let result = null ; while(result == null){ let line = Readline.inputLine() ; let val = parseInt(line) ; if(!isNaN(val)){ result = val ; } } return result ; } Readline.menu = function(items){ let result = 0 ; let decided = false ; while(!decided){ for(let i=0 ; i<items.length ; i++){ console.print(`${i}: ${items[i]}\n`) ; } console.print("number> ") ; let line = Readline.inputLine() ; let num = parseInt(line) ; if(!isNaN(num)){ if(0<=num && num<items.length){ result = num ; decided = true; } else { console.error(`[Error] Unexpected value: ${num}\n`) ; } } else { console.error(`[Error] Not number value: ${line}\n`) ; } } return result ; }
Fix apidoc to allow `npm install` to complete
module.exports = function(app) { /** * @apiGroup buildings * @apiName Show list of buildings * @apiVersion 3.0.0 * @api {get} buildings Show list of available buildings * @apiSuccess {[]} buildings List of buildings * @apiError InternalServerError */ app.get('/api/v3/buildings', function(request, response) { app.settings.db.Building.find({}, { _id: 0, __v: 0, rooms: 0 }, function(error, buildings) { if (error) return response.status(500).send(); response.json(buildings); }); }); /** * @apiGroup building * @apiName Get building information * @apiVersion 3.0.0 * @api {get} buildings Show list of available buildings * @apiParam {string} name Building name * @apiSuccess {string} name building name * @apiError BuildingNotFound */ app.get('/api/v3/buildings/:name', function(request, response) { var name = request.params.name; app.settings.db.Building.find( { "name" : new RegExp(name, 'i') }, { _id: 0, __v: 0 }, function(error, building) { if (error || building.length == 0) return response.status(404).send("BuildingNotFound"); response.json(building[0]); }); }); };
module.exports = function(app) { /** * @apiGroup buildings * @apiName Show list of buildings * @apiVersion 3.0.0 * @api {get} buildings Show list of available buildings * @apiSuccess {[]} buildings List of buildings * @apiError InternalServerError */ app.get('/api/v3/buildings', function(request, response) { app.settings.db.Building.find({}, { _id: 0, __v: 0, rooms: 0 }, function(error, buildings) { if (error) return response.status(500).send(); response.json(buildings); }); }); /** * @apiGroup building * @apiName Get building information * @apiVersion 3.0.0 * @api {get} buildings Show list of available buildings * @apiParam {string} name Building name * @apiSuccess {} building data * @apiError BuildingNotFound */ app.get('/api/v3/buildings/:name', function(request, response) { var name = request.params.name; app.settings.db.Building.find( { "name" : new RegExp(name, 'i') }, { _id: 0, __v: 0 }, function(error, building) { if (error || building.length == 0) return response.status(404).send("BuildingNotFound"); response.json(building[0]); }); }); };
Fix typos in record_format hash
// Main Module for searchthedocs demo define(function (require) { var _ = require('underscore'), $ = require('jquery'), SearchTheDocsView = require('searchthedocs/src/searchthedocs'); var searchthedocs_main = function() { var search_options = { default_endpoint: 'sections', endpoints: { sections: { data_type: 'json', //default_params: {format: 'jsonp'}, api_url: 'http://searchtd.dev:8000/api/v2/search/section/', record_url: 'http://{{domain}}.readthedocs.org/en/' + '{{version}}/{{path}}.html#{{page_id}}', param_map: { search: 'q', domain: 'project' }, result_format: { records_path: 'results.hits.hits', record_format: { // Fields used in sidebar display domain: 'fields.project', title: 'fields.title', // Fields used to build record_url version: 'fields.version', path: 'fields.path', page_id: 'fields.page_id' } }, } } }; window.searchtd = new SearchTheDocsView({ brand: 'searchthedocs', brand_href: '#', search_options: search_options }); $('#searchthedocs-container').append(searchtd.render().el); }; return searchthedocs_main; });
// Main Module for searchthedocs demo define(function (require) { var _ = require('underscore'), $ = require('jquery'), SearchTheDocsView = require('searchthedocs/src/searchthedocs'); var searchthedocs_main = function() { var search_options = { default_endpoint: 'sections', endpoints: { sections: { data_type: 'json', //default_params: {format: 'jsonp'}, api_url: 'http://searchtd.dev:8000/api/v2/search/section/', record_url: 'http://{{domain}}.readthedocs.org/en/' + '{{version}}/{{path}}.html#{{page_id}}', param_map: { search: 'q', domain: 'project' }, result_format: { records: 'results.hits.hits', record_format: { // Fields used in sidebar display domain: 'fields.project', title: 'fields.title', // Fields used to build record_url version: 'fields.version', path: 'fields.setup', page_id: 'fields.quick-install' } }, } } }; window.searchtd = new SearchTheDocsView({ brand: 'searchthedocs', brand_href: '#', search_options: search_options }); $('#searchthedocs-container').append(searchtd.render().el); }; return searchthedocs_main; });
Switch back to var syntax for all functions
import { select, local } from "d3-selection"; var myLocal = local(), noop = function (){}; export default function (tagName, className){ var create = noop, render = noop, destroy = noop, myCreate = function (){ var my = myLocal.set(this, { selection: select(this), state: {}, render: noop }); create(my.selection, function setState(state){ Object.assign(my.state, state); my.render(); }); my.render = function (){ render(my.selection, my.props, my.state); }; }, myRender = function (props){ var my = myLocal.get(this); my.props = props; my.render(); }, myDestroy = function (props){ destroy(myLocal.get(this).state); }, selector = className ? "." + className : tagName, component = function(selection, props){ var components = selection.selectAll(selector) .data(Array.isArray(props) ? props : [props]); components .enter().append(tagName) .attr("class", className) .each(myCreate) .merge(components) .each(myRender); components .exit() .each(myDestroy) .remove(); }; component.render = function(_) { render = _; return component; }; component.create = function(_) { create = _; return component; }; component.destroy = function(_) { destroy = _; return component; }; return component; };
import { select, local } from "d3-selection"; var myLocal = local(), noop = function (){}; export default function (tagName, className){ var create = noop, render = noop, destroy = noop, myCreate = function (){ var my = myLocal.set(this, { selection: select(this), state: {}, render: noop }); create(my.selection, function setState(state){ Object.assign(my.state, state); my.render(); }); my.render = function (){ render(my.selection, my.props, my.state); }; }, myRender = function (props){ var my = myLocal.get(this); my.props = props; my.render(); }, myDestroy = function (props){ destroy(myLocal.get(this).state); }, selector = className ? "." + className : tagName; function component(selection, props){ var components = selection.selectAll(selector) .data(Array.isArray(props) ? props : [props]); components .enter().append(tagName) .attr("class", className) .each(myCreate) .merge(components) .each(myRender); components .exit() .each(myDestroy) .remove(); } component.render = function(_) { render = _; return component; }; component.create = function(_) { create = _; return component; }; component.destroy = function(_) { destroy = _; return component; }; return component; };
[tasks] Fix wrong rendering of priority
/* * Set of functions to make data more readable. */ import { mapGetters } from 'vuex' import { formatDate, formatFullDate, formatSimpleDate } from '@/lib/time' export const formatListMixin = { created () { }, mounted () { }, beforeDestroy () { }, computed: { ...mapGetters([ 'organisation' ]) }, methods: { formatBoolean (booleanValue) { return booleanValue ? this.$t('main.yes') : this.$t('main.no') }, formatDate, formatFullDate, formatSimpleDate, formatDuration (duration) { if (duration) { return (duration / 60 / this.organisation.hours_by_day).toLocaleString( 'fullwide', { maximumFractionDigits: 2 } ) } else { return 0 } }, formatPriority (priority) { let label = priority + '' if (priority === 0) { label = 'normal' } else if (priority === 1) { label = this.$t('tasks.priority.high') } else if (priority === 2) { label = this.$t('tasks.priority.very_high') } else if (priority === 3) { label = this.$t('tasks.priority.emergency') } return label }, sanitizeInteger (value) { let val = 0 if (typeof value === 'string') { value = value.replace(/\D/g, '') if (value && value.length > 0) val = parseInt(value) || 0 } return val } } }
/* * Set of functions to make data more readable. */ import { mapGetters } from 'vuex' import { formatDate, formatFullDate, formatSimpleDate } from '@/lib/time' export const formatListMixin = { created () { }, mounted () { }, beforeDestroy () { }, computed: { ...mapGetters([ 'organisation' ]) }, methods: { formatBoolean (booleanValue) { return booleanValue ? this.$t('main.yes') : this.$t('main.no') }, formatDate, formatFullDate, formatSimpleDate, formatDuration (duration) { if (duration) { return (duration / 60 / this.organisation.hours_by_day).toLocaleString( 'fullwide', { maximumFractionDigits: 2 } ) } else { return 0 } }, formatPriority (priority) { let label = priority + '' if (priority === 0) { label = 'normal' } else if (priority === 1) { label = this.$('tasks.priority.high') } else if (priority === 2) { label = this.$('tasks.priority.very_high') } else if (priority === 3) { label = this.$('tasks.priority.emergency') } return label }, sanitizeInteger (value) { let val = 0 if (typeof value === 'string') { value = value.replace(/\D/g, '') if (value && value.length > 0) val = parseInt(value) || 0 } return val } } }
Remove Node RSS restart interval in favor of kubernetes cron job
var _ = require('lodash'), async = require('async'), checkForFiling = require('./check'), request = require('request'), models = require('../../models'), parser = require('rss-parser'); // var interval = 60000; function queueFilingsToCheck() { console.log('checking RSS'); parser.parseURL('http://efilingapps.fec.gov/rss/generate?preDefinedFilingType=ALL', function(err, parsed) { if (!err && parsed && parsed.feed && parsed.feed.entries) { var newFilings = parsed.feed.entries.map(function (filing) { return parseInt(filing.link.replace('http://docquery.fec.gov/dcdev/posted/','').replace('.fec','')); }); models.fec_filing.findAll({ attributes: ['filing_id'], where: { filing_id: { gte: _.min(newFilings) } } }) .then(function(filings) { filings = filings.map(function(filing) { return filing.filing_id; }); async.mapSeries(_.difference(newFilings,filings), checkForFiling, function () { console.log('done'); // setTimeout(queueFilingsToCheck,interval); }); }); } else { console.error(error); console.log('done'); // setTimeout(queueFilingsToCheck,interval); } }); } queueFilingsToCheck();
var _ = require('lodash'), async = require('async'), checkForFiling = require('./check'), request = require('request'), models = require('../../models'), parser = require('rss-parser'); var interval = 60000; function queueFilingsToCheck() { console.log('checking RSS'); parser.parseURL('http://efilingapps.fec.gov/rss/generate?preDefinedFilingType=ALL', function(err, parsed) { if (!err && parsed && parsed.feed && parsed.feed.entries) { var newFilings = parsed.feed.entries.map(function (filing) { return parseInt(filing.link.replace('http://docquery.fec.gov/dcdev/posted/','').replace('.fec','')); }); models.fec_filing.findAll({ attributes: ['filing_id'], where: { filing_id: { gte: _.min(newFilings) } } }) .then(function(filings) { filings = filings.map(function(filing) { return filing.filing_id; }); async.mapSeries(_.difference(newFilings,filings), checkForFiling, function () { console.log('waiting'); setTimeout(queueFilingsToCheck,interval); }); }); } else { console.error(error); console.log('waiting'); setTimeout(queueFilingsToCheck,interval); } }); } queueFilingsToCheck();
Fix require on Node.js 0.12.
// Control-flow utilities. var cadence = require('cadence') // Evented message queue. var Procession = require('./procession') // Create a splitter that will split the given queue. // function Splitter (queue, splits) { this._shifter = queue.shifter() this._map = {} this._array = [] for (var key in splits) { var queue = new Procession var split = { selector: splits[key], queue: queue, shifter: queue.shifter() } this._map[key] = split this._array.push(split) } } Splitter.prototype.dequeue = cadence(function (async, name) { var split = this._map[name] var loop = async(function () { if (split.queue.size != 0 || split.queue.endOfStream) { return [ loop.break, split.shifter.shift() ] } this._shifter.dequeue(async()) }, function (envelope) { if (envelope == null) { this._array.forEach(function (split) { split.queue.push(null) }) } else { for (var i = 0, I = this._array.length; i < I; i++) { if (this._array[i].selector(envelope)) { this._array[i].queue.push(envelope) break } } } })() }) module.exports = Splitter
// Control-flow utilities. var cadence = require('cadence') // Evented message queue. var Procession = require('.') // Create a splitter that will split the given queue. // function Splitter (queue, splits) { this._shifter = queue.shifter() this._map = {} this._array = [] for (var key in splits) { var queue = new Procession var split = { selector: splits[key], queue: queue, shifter: queue.shifter() } this._map[key] = split this._array.push(split) } } Splitter.prototype.dequeue = cadence(function (async, name) { var split = this._map[name] var loop = async(function () { if (split.queue.size != 0 || split.queue.endOfStream) { return [ loop.break, split.shifter.shift() ] } this._shifter.dequeue(async()) }, function (envelope) { if (envelope == null) { this._array.forEach(function (split) { split.queue.push(null) }) } else { for (var i = 0, I = this._array.length; i < I; i++) { if (this._array[i].selector(envelope)) { this._array[i].queue.push(envelope) break } } } })() }) module.exports = Splitter
Throw an exception when allow_url_fopen is disabled
<?php namespace Airbrake\Http; use Airbrake\Exception; use InvalidArgumentException; class Factory { /** * HTTP client generation. * * @param string|null $handler * * @throws Exception If the cURL extension or the Guzzle client aren't available (if required). * @throws InvalidArgumentException If the http client handler isn't "default", "curl" or "guzzle" * * @return ClientInterface */ public static function createHttpClient($handler = null) { if ($handler === 'guzzle') { if (!class_exists('GuzzleHttp\Client')) { throw new Exception('The Guzzle HTTP client must be included in order to use the "guzzle" handler.'); } return new GuzzleClient(); } if ($handler === 'curl') { if (!extension_loaded('curl')) { throw new Exception('The cURL extension must be loaded in order to use the "curl" handler.'); } return new CurlClient(); } if (!$handler || $handler === 'default') { if (!ini_get('allow_url_fopen')) { throw new Exception('The default HTTP client requires allow_url_fopen = true'); } return new DefaultClient(); } throw new InvalidArgumentException('The http client handler must be set to "default", "curl" or "guzzle"'); } }
<?php namespace Airbrake\Http; use Airbrake\Exception; use InvalidArgumentException; class Factory { /** * HTTP client generation. * * @param string|null $handler * * @throws Exception If the cURL extension or the Guzzle client aren't available (if required). * @throws InvalidArgumentException If the http client handler isn't "default", "curl" or "guzzle" * * @return ClientInterface */ public static function createHttpClient($handler = null) { if ($handler === 'guzzle') { if (!class_exists('GuzzleHttp\Client')) { throw new Exception('The Guzzle HTTP client must be included in order to use the "guzzle" handler.'); } return new GuzzleClient(); } if ($handler === 'curl') { if (!extension_loaded('curl')) { throw new Exception('The cURL extension must be loaded in order to use the "curl" handler.'); } return new CurlClient(); } if (!$handler || $handler === 'default') { return new DefaultClient(); } throw new InvalidArgumentException('The http client handler must be set to "default", "curl" or "guzzle"'); } }
Use the new RulesEngine configuration service for vars
angular.module('OpiferEntityPicker', ['ui.bootstrap.typeahead']) .directive('entityPicker', function() { var tpl = '<input type="text" ng-model="search" typeahead="object.name for object in getObject($viewValue)" typeahead-on-select="onSelect($item, $model, $label)" typeahead-loading="loadingLocations" class="form-control">' + '<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>'; return { restrict: 'E', transclude: true, scope: { subject: '=', configuration: '=' }, template: tpl, controller: function($scope, $http, $attrs) { // Get the object by search term $scope.getObject = function(term) { return $http.get(Routing.generate($scope.configuration.searchRoute(), [], true), { params: { term: term } }).then(function(response){ return response.data.map(function(item){ return item; }); }); }; // Select the object $scope.onSelect = function(item, model, label) { if (angular.isUndefined($scope.subject.right.value)) { $scope.subject.right.value = []; } if ($scope.subject.right.value.indexOf(item.id) == -1) { $scope.subject.right.value.push(item.id); $scope.configuration.add(item); } $scope.search = null; }; } }; }) ;
angular.module('OpiferEntityPicker', ['ui.bootstrap.typeahead']) .directive('entityPicker', function() { var tpl = '<input type="text" ng-model="search" typeahead="object.name for object in getObject($viewValue)" typeahead-on-select="onSelect($item, $model, $label)" typeahead-loading="loadingLocations" class="form-control">' + '<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>'; return { restrict: 'E', transclude: true, scope: { url: '=', subject: '=' }, template: tpl, controller: function($scope, $http, $attrs) { // Get the object by search term $scope.getObject = function(term) { return $http.get($scope.url, { params: { term: term } }).then(function(response){ return response.data.map(function(item){ return item; }); }); }; // Select the object $scope.onSelect = function(item, model, label) { if (angular.isUndefined($scope.subject.right.value)) { $scope.subject.right.value = []; } var item = {id:item.id, name:item.name}; if ($scope.subject.right.value.indexOf(item) == -1) { $scope.subject.right.value.push(item); } $scope.search = null; }; } }; }) ;
Make RequestType a normal class, not an enum. This removes the restriction of needing Python >= 3.4. RequestType is now a normal class with class variables (fixes #19).
import json from pyglab.exceptions import RequestError import requests class RequestType(object): GET = 1 POST = 2 PUT = 3 DELETE = 4 class ApiRequest: _request_creators = { RequestType.GET: requests.get, RequestType.POST: requests.post, RequestType.PUT: requests.put, RequestType.DELETE: requests.delete, } def __init__(self, request_type, url, token, params={}, sudo=None, page=None, per_page=None): # Build header header = {'PRIVATE-TOKEN': token} if sudo is not None: header['SUDO', sudo] # Build parameters if page is not None: params['page'] = page if per_page is not None: params['per_page'] = per_page r = self._request_creators[request_type](url, params=params, headers=header) content = json.loads(r.text) if RequestError.is_error(r.status_code): raise RequestError.error_class(r.status_code)(content) self._content = content @property def content(self): return self._content
import enum import json from pyglab.exceptions import RequestError import requests @enum.unique class RequestType(enum.Enum): GET = 1 POST = 2 PUT = 3 DELETE = 4 class ApiRequest: _request_creators = { RequestType.GET: requests.get, RequestType.POST: requests.post, RequestType.PUT: requests.put, RequestType.DELETE: requests.delete, } def __init__(self, request_type, url, token, params={}, sudo=None, page=None, per_page=None): # Build header header = {'PRIVATE-TOKEN': token} if sudo is not None: header['SUDO', sudo] # Build parameters if page is not None: params['page'] = page if per_page is not None: params['per_page'] = per_page r = self._request_creators[request_type](url, params=params, headers=header) content = json.loads(r.text) if RequestError.is_error(r.status_code): raise RequestError.error_class(r.status_code)(content) self._content = content @property def content(self): return self._content
Fix importing force_text tests for 1.4 compatibility use 1.4 compat code
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from django.test import TestCase try: from django.utils.encoding import force_text except ImportError: from django.utils.encoding import force_unicode as force_text from import_export.formats import base_formats class XLSTest(TestCase): def test_binary_format(self): self.assertTrue(base_formats.XLS().is_binary()) class CSVTest(TestCase): def setUp(self): self.format = base_formats.CSV() def test_import_dos(self): filename = os.path.join( os.path.dirname(__file__), os.path.pardir, 'exports', 'books-dos.csv') in_stream = open(filename, self.format.get_read_mode()).read() expected = 'id,name,author_email\n1,Some book,[email protected]\n' self.assertEqual(in_stream, expected) def test_import_unicode(self): # importing csv UnicodeEncodeError 347 filename = os.path.join( os.path.dirname(__file__), os.path.pardir, 'exports', 'books-unicode.csv') in_stream = open(filename, self.format.get_read_mode()) data = force_text(in_stream.read()) base_formats.CSV().create_dataset(data)
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from django.test import TestCase from django.utils.text import force_text from import_export.formats import base_formats class XLSTest(TestCase): def test_binary_format(self): self.assertTrue(base_formats.XLS().is_binary()) class CSVTest(TestCase): def setUp(self): self.format = base_formats.CSV() def test_import_dos(self): filename = os.path.join( os.path.dirname(__file__), os.path.pardir, 'exports', 'books-dos.csv') in_stream = open(filename, self.format.get_read_mode()).read() expected = 'id,name,author_email\n1,Some book,[email protected]\n' self.assertEqual(in_stream, expected) def test_import_unicode(self): # importing csv UnicodeEncodeError 347 filename = os.path.join( os.path.dirname(__file__), os.path.pardir, 'exports', 'books-unicode.csv') in_stream = open(filename, self.format.get_read_mode()) data = force_text(in_stream.read()) base_formats.CSV().create_dataset(data)
Correct configuration root & remove unnecessary $rootNode variable
<?php /* * This file is part of CacheToolBundle. * * (c) Samuel Gordalina <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CacheTool\Bundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $treeBuilder ->root('cache_tool') ->children() ->scalarNode('adapter') ->defaultValue('fastcgi') ->validate() ->ifNotInArray(array('cli', 'fastcgi')) ->thenInvalid('Adapter `%s` is not valid') ->end() ->end() ->scalarNode('fastcgi') ->defaultValue('127.0.0.1:9000') ->end() ->scalarNode('temp_dir') ->defaultValue(null) ->end() ->end() ; return $treeBuilder; } }
<?php /* * This file is part of CacheToolBundle. * * (c) Samuel Gordalina <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CacheTool\Bundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('cachetool'); $rootNode ->children() ->scalarNode('adapter') ->defaultValue('fastcgi') ->validate() ->ifNotInArray(array('cli', 'fastcgi')) ->thenInvalid('Adapter `%s` is not valid') ->end() ->end() ->scalarNode('fastcgi') ->defaultValue('127.0.0.1:9000') ->end() ->scalarNode('temp_dir') ->defaultValue(null) ->end() ->end() ; return $treeBuilder; } }
OEE-624: Add multi language support for Outlook layouts
<?php namespace Oro\Bundle\SoapBundle\Tests\EventListener; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\RequestContext; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Oro\Bundle\SoapBundle\EventListener\LocaleListener; class LocaleListenerTest extends \PHPUnit_Framework_TestCase { /** @var LocaleListener */ protected $listener; /** @var string */ protected $defaultLocale; protected function setUp() { $this->defaultLocale = \Locale::getDefault(); } protected function tearDown() { \Locale::setDefault($this->defaultLocale); } public function testOnKernelRequest() { $customLocale = 'fr'; $request = new Request(['locale' => $customLocale]); $request->server->set('REQUEST_URI', '/api/rest/test'); $request->setDefaultLocale($this->defaultLocale); $this->listener = new LocaleListener(); $this->listener->onKernelRequest($this->createGetResponseEvent($request)); $this->assertEquals($customLocale, $request->getLocale()); } /** * @param Request $request * @return GetResponseEvent */ protected function createGetResponseEvent(Request $request) { $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent') ->disableOriginalConstructor() ->setMethods(array('getRequest')) ->getMock(); $event->expects($this->once()) ->method('getRequest') ->will($this->returnValue($request)); return $event; } }
<?php namespace Oro\Bundle\SoapBundle\Tests\EventListener; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\RequestContext; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Oro\Bundle\SoapBundle\EventListener\LocaleListener; class LocaleListenerTest extends \PHPUnit_Framework_TestCase { /** @var LocaleListener */ protected $listener; /** @var string */ protected $defaultLocale; protected function setUp() { $this->defaultLocale = \Locale::getDefault(); } protected function tearDown() { \Locale::setDefault($this->defaultLocale); } public function testOnKernelRequest() { $customLocale = 'fr'; $request = new Request(['_locale' => $customLocale]); //$request->server->set('REQUEST_URI', '/api/rest/test'); $request->setDefaultLocale($this->defaultLocale); $this->listener = new LocaleListener(); $this->listener->onKernelRequest($this->createGetResponseEvent($request)); $this->assertEquals($customLocale, $request->getLocale()); } /** * @param Request $request * @return GetResponseEvent */ protected function createGetResponseEvent(Request $request) { $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent') ->disableOriginalConstructor() ->setMethods(array('getRequest')) ->getMock(); $event->expects($this->once()) ->method('getRequest') ->will($this->returnValue($request)); return $event; } }
Make use allow more connections per pool. Now capped at 10.
#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice [email protected] import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 10: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 10: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout)
#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice [email protected] import threading class ResourceGenerator: def __init__(self, generate = lambda:None, pool = None, timeout = None): #Pool is a list of items #Generate creates a new item self.generate = generate self.pool = pool self.timeout = timeout def __enter__(self): #Check if an item is available while len(self.pool) > 5: for lock, item in self.pool: if lock.acquire(False): self.lock = lock return item if len(self.pool) > 5: gevent.sleep(0) #Otherwise make a new item (lock, item) = (threading.Lock(), self.generate(self.timeout)) lock.acquire() self.lock = lock self.pool.add((lock,item)) return item def __exit__(self, type, value, traceback): self.lock.release() class Pool: def __init__(self, generate): self.pools = {} self.generate = generate def __call__(self, url, timeout=None): key = url+str(timeout) if url not in self.pools: self.pools[key] = set() return ResourceGenerator(self.generate, pool = self.pools[key], timeout=timeout)
Fix route parameters for a row action
<?php /* * This file is part of the DataGridBundle. * * (c) Stanislav Turza <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sorien\DataGridBundle\Grid\Column; use Sorien\DataGridBundle\Grid\Action\RowAction; class ActionsColumn extends Column { private $rowActions; public function __construct($column, $title, array $rowActions = array()) { $this->rowActions = $rowActions; parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false)); } public function getRouteParameters($row, $action) { $actionParameters = $action->getRouteParameters(); if(!empty($actionParameters)){ $routeParameters = array(); foreach ($actionParameters as $name => $parameter) { if(is_numeric($name)){ $routeParameters[$parameter] = $row->getField($parameter); } else { $routeParameters[$name] = $parameter; } } } return array_merge( array($row->getPrimaryField() => $row->getPrimaryFieldValue()), $routeParameters ); } public function getRowActions() { return $this->rowActions; } public function setRowActions(array $rowActions) { $this->rowActions = $rowActions; } public function getType() { return 'actions'; } }
<?php /* * This file is part of the DataGridBundle. * * (c) Stanislav Turza <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sorien\DataGridBundle\Grid\Column; use Sorien\DataGridBundle\Grid\Action\RowAction; class ActionsColumn extends Column { private $rowActions; public function __construct($column, $title, array $rowActions = array()) { $this->rowActions = $rowActions; parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false)); } public function getRouteParameters($row, $action) { $actionParameters = $action->getRouteParameters(); if(!empty($actionParameters)){ $routeParameters = array(); foreach ($actionParameters as $name => $parameter) { if(is_numeric($name)){ $routeParameters[$parameter] = $row->getField($parameter); } else { $routeParameters[$name] = $parameter; } } return $routeParameters; } $routeParameters = array_merge( array($row->getPrimaryField() => $row->getPrimaryFieldValue()), $action->getRouteParameters() ); return $routeParameters; } public function getRowActions() { return $this->rowActions; } public function setRowActions(array $rowActions) { $this->rowActions = $rowActions; } public function getType() { return 'actions'; } }
Modify libCategories.so path to use hdfs. git-svn-id: 41b0c0219f7416f0d477a2a4ae2b791f31fdedae@100 72e40b64-262a-4186-abad-0444e9ae7036
package es.tid.ps.dynamicprofile.dictionary; /** * Class that defines the native methods to access the comScore dictionary API * via JNI. * * @author dmicol */ public class CSDictionaryJNIInterface { /** * Initializes the dictionary wrapper using the terms in domain file. * * @param iMode * the operation mode (value should be 1) * @param szTermsInDomainFlatFileName * the terms in domain file name * @return whether the initialization succeeded */ public native boolean InitFromTermsInDomainFlatFile(int iMode, String szTermsInDomainFlatFileName); /** * Loads the comScore dictionary in memory. * * @param iMode * the operation mode (value should be 1) * @param szTermsInDomainFlatFileName * the terms in domain file name * @param szDictionaryName * the file name of the dictionary * @return whether the load of the dictionary succeeded */ public native boolean LoadCSDictionary(int iMode, String szTermsInDomainFlatFileName, String szDictionaryName); /** * Applies the dictionary to the given URL, and returns the pattern ID for * such URL. * * @param szURL * the url to apply the dictionary to * @return the pattern ID of the URL */ public native long ApplyDictionaryUsingUrl(String szURL); static { System.load("/user/hdfs/libCategories.so"); } }
package es.tid.ps.dynamicprofile.dictionary; /** * Class that defines the native methods to access the comScore dictionary API * via JNI. * * @author dmicol */ public class CSDictionaryJNIInterface { /** * Initializes the dictionary wrapper using the terms in domain file. * * @param iMode * the operation mode (value should be 1) * @param szTermsInDomainFlatFileName * the terms in domain file name * @return whether the initialization succeeded */ public native boolean InitFromTermsInDomainFlatFile(int iMode, String szTermsInDomainFlatFileName); /** * Loads the comScore dictionary in memory. * * @param iMode * the operation mode (value should be 1) * @param szTermsInDomainFlatFileName * the terms in domain file name * @param szDictionaryName * the file name of the dictionary * @return whether the load of the dictionary succeeded */ public native boolean LoadCSDictionary(int iMode, String szTermsInDomainFlatFileName, String szDictionaryName); /** * Applies the dictionary to the given URL, and returns the pattern ID for * such URL. * * @param szURL * the url to apply the dictionary to * @return the pattern ID of the URL */ public native long ApplyDictionaryUsingUrl(String szURL); static { System.load("/usr/lib64/libCategories.so"); } }
Fix on_error triggered twice issue If some error happens, the on_error will be triggered twice.
var request = require('request'); var path = require('path'); var fs = require('fs'); function on_error(err, options) { if (options.done) { return options.done(err); } throw err; } module.exports = function(options) { if (!options.url) { throw new Error('The option url is required'); } if (!options.dest) { throw new Error('The option dest is required'); } request({url: options.url, encoding: null}, function (err, res, body) { if (err) { on_error(err, options); return; } if (body && res.statusCode === 200) { if (!path.extname(options.dest)) { options.dest = path.join(options.dest, path.basename(options.url)); } fs.writeFile(options.dest, body, 'binary', function(err){ if (err) { on_error(err, options); } options.done && options.done(false, options.dest, body) }); } else { if (!body) { on_error(new Error('Image loading error - empty body. URL: ' + options.url), options); } else { on_error(new Error('Image loading error - ' + res.statusCode + '. URL: ' + options.url), options); } } }); };
var request = require('request'); var path = require('path'); var fs = require('fs'); function on_error(err, options) { if (options.done) { return options.done(err); } throw err; } module.exports = function(options) { if (!options.url) { throw new Error('The option url is required'); } if (!options.dest) { throw new Error('The option dest is required'); } request({url: options.url, encoding: null}, function (err, res, body) { if (err) { on_error(err, options); } if (body && res.statusCode === 200) { if (!path.extname(options.dest)) { options.dest = path.join(options.dest, path.basename(options.url)); } fs.writeFile(options.dest, body, 'binary', function(err){ if (err) { on_error(err, options); } options.done && options.done(false, options.dest, body) }); } else { if (!body) { on_error(new Error('Image loading error - empty body. URL: ' + options.url), options); } else { on_error(new Error('Image loading error - ' + res.statusCode + '. URL: ' + options.url), options); } } }); };
Use activity context not application context
package com.fedorvlasov.lazylist; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class LazyAdapter extends BaseAdapter { private Activity activity; private String[] data; private static LayoutInflater inflater=null; public ImageLoader imageLoader; public LazyAdapter(Activity a, String[] d) { activity = a; data=d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader=new ImageLoader(activity); } public int getCount() { return data.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.item, null); TextView text=(TextView)vi.findViewById(R.id.text);; ImageView image=(ImageView)vi.findViewById(R.id.image); text.setText("item "+position); imageLoader.DisplayImage(data[position], image); return vi; } }
package com.fedorvlasov.lazylist; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class LazyAdapter extends BaseAdapter { private Activity activity; private String[] data; private static LayoutInflater inflater=null; public ImageLoader imageLoader; public LazyAdapter(Activity a, String[] d) { activity = a; data=d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader=new ImageLoader(activity.getApplicationContext()); } public int getCount() { return data.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.item, null); TextView text=(TextView)vi.findViewById(R.id.text);; ImageView image=(ImageView)vi.findViewById(R.id.image); text.setText("item "+position); imageLoader.DisplayImage(data[position], image); return vi; } }
Add missing "devel" and "undef". Remove "indent" since it was moved to jscs.
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('bower.json'), jshint: { grunt: { src: ['Gruntfile.js'] }, main: { src: ['tock.js'], options: { 'browser': true, 'camelcase': true, 'curly': true, 'devel': true, 'eqeqeq': true, 'newcap': true, 'quotmark': 'single', 'undef': true, 'unused': true } }, }, uglify: { options: { banner: '// Tock.js (version <%= pkg.version %>) <%= pkg.homepage %>\n// License: <%= pkg.license %>\n' }, main: { src: '<%= jshint.main.src %>', dest: 'tock.min.js' } }, watch: { main: { files: '<%= jshint.main.src %>', tasks: ['jshint:main', 'uglify:main'] } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['jshint', 'uglify']); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('bower.json'), jshint: { grunt: { src: ['Gruntfile.js'] }, main: { src: ['tock.js'], options: { 'browser': true, 'camelcase': true, 'curly': true, 'eqeqeq': true, 'indent': 2, 'newcap': true, 'quotmark': 'single', 'unused': true } }, }, uglify: { options: { banner: '// Tock.js (version <%= pkg.version %>) <%= pkg.homepage %>\n// License: <%= pkg.license %>\n' }, main: { src: '<%= jshint.main.src %>', dest: 'tock.min.js' } }, watch: { main: { files: '<%= jshint.main.src %>', tasks: ['jshint:main', 'uglify:main'] } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['jshint', 'uglify']); };
Replace tab indentation with 4 spaces
#!/usr/bin/env python # Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import struct import json def sendraw(buf): sys.stdout.write(struct.pack("<q", len(buf))) sys.stdout.write(buf) sys.stdout.flush() def send(obj): sendraw(json.dumps(obj)) def mainloop(): text = '' while True: sizebuf = sys.stdin.read(8) if len(sizebuf) == 0: return (size,) = struct.unpack("<q", sizebuf) cmd, arg = json.loads(sys.stdin.read(size)) print >> sys.stderr, cmd, arg if cmd == 'key': chars = arg['chars'] if chars == u'\x7f': if len(text): text = text[:-1] else: text += chars send(['settext', text]) mainloop()
#!/usr/bin/env python # Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import struct import json def sendraw(buf): sys.stdout.write(struct.pack("<q", len(buf))) sys.stdout.write(buf) sys.stdout.flush() def send(obj): sendraw(json.dumps(obj)) def mainloop(): text = '' while True: sizebuf = sys.stdin.read(8) if len(sizebuf) == 0: return (size,) = struct.unpack("<q", sizebuf) cmd, arg = json.loads(sys.stdin.read(size)) print >> sys.stderr, cmd, arg if cmd == 'key': chars = arg['chars'] if chars == u'\x7f': if len(text): text = text[:-1] else: text += chars send(['settext', text]) mainloop()
Update chpl_task to only default to muxed when ugni comm is used. This expands upon (and fixes) #1640 and #1635. * [ ] Run printchplenv on mac and confirm it still works. * [ ] Emulate cray-x* with module and confirm comm, tasks are ugni, muxed. ```bash ( export CHPL_MODULE_HOME=$CHPL_HOME export CHPL_HOST_PLATFORM=cray-xc export CHPL_TARGET_COMPILER=cray-prgenv-gnu printchplenv ) ``` * [ ] Emulate cray-x* with module but not supported compiler and confirm comm, tasks are gasnet, default tasks. ```bash ( export CHPL_MODULE_HOME=$CHPL_HOME export CHPL_HOST_PLATFORM=cray-xc export CHPL_TARGET_COMPILER=cray-prgenv-cray printchplenv ) ``` * [ ] Emulate cray-x* without module and confirm comm, tasks settings are gasnet, default tasks. ```bash ( export CHPL_HOST_PLATFORM=cray-xc export CHPL_TARGET_COMPILER=cray-prgenv-gnu printchplenv ) ``` * [ ] Emulate cray-x* with module and intel compiler, but knc target arch and confirm comm, tasks are gasnet, default tasks. ```bash ( export CHPL_MODULE_HOME=$CHPL_HOME export CHPL_HOST_PLATFORM=cray-xc export CHPL_TARGET_COMPILER=cray-prgenv-intel export CRAY_CPU_TARGET=knc printchplenv ) ``` * [ ] Emulate cray-x* with module, supported compiler, but none ugni comm and confirm tasks are default tasks. ```bash ( export CHPL_MODULE_HOME=$CHPL_HOME export CHPL_HOST_PLATFORM=cray-xc export CHPL_TARGET_COMPILER=cray-prgenv-gnu export CHPL_COMM=none printchplenv ) ```
#!/usr/bin/env python import sys, os import chpl_arch, chpl_platform, chpl_compiler, chpl_comm from utils import memoize import utils @memoize def get(): tasks_val = os.environ.get('CHPL_TASKS') if not tasks_val: arch_val = chpl_arch.get('target', get_lcd=True) platform_val = chpl_platform.get() compiler_val = chpl_compiler.get('target') comm_val = chpl_comm.get() # use muxed on cray-x* machines using the module and supported compiler if (comm_val == 'ugni' and platform_val.startswith('cray-x') and utils.using_chapel_module() and compiler_val in ('cray-prgenv-gnu', 'cray-prgenv-intel') and arch_val != 'knc'): tasks_val = 'muxed' elif (arch_val == 'knc' or platform_val.startswith('cygwin') or platform_val.startswith('netbsd') or compiler_val == 'cray-prgenv-cray'): tasks_val = 'fifo' else: tasks_val = 'qthreads' return tasks_val def _main(): tasks_val = get() sys.stdout.write("{0}\n".format(tasks_val)) if __name__ == '__main__': _main()
#!/usr/bin/env python import sys, os import chpl_arch, chpl_platform, chpl_compiler from utils import memoize import utils @memoize def get(): tasks_val = os.environ.get('CHPL_TASKS') if not tasks_val: arch_val = chpl_arch.get('target', get_lcd=True) platform_val = chpl_platform.get() compiler_val = chpl_compiler.get('target') # use muxed on cray-x* machines using the module and supported compiler if (platform_val.startswith('cray-x') and utils.using_chapel_module() and compiler_val in ('cray-prgenv-gnu', 'cray-prgenv-intel') and arch_val != 'knc'): tasks_val = 'muxed' elif (arch_val == 'knc' or platform_val.startswith('cygwin') or platform_val.startswith('netbsd') or compiler_val == 'cray-prgenv-cray'): tasks_val = 'fifo' else: tasks_val = 'qthreads' return tasks_val def _main(): tasks_val = get() sys.stdout.write("{0}\n".format(tasks_val)) if __name__ == '__main__': _main()
Add method to check is content is in another collection
import http from '../http'; export default class collections { static get(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response; }) } static getAll() { return http.get(`/zebedee/collections`) .then(response => { return response; }) } static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } static approve(collectionID) { return http.post(`/zebedee/approve/${collectionID}`); } static delete(collectionID) { return http.delete(`/zebedee/collection/${collectionID}`); } static update(collectionID, body) { body.id = collectionID; return http.put(`/zebedee/collection/${collectionID}`, body); } static deletePage(collectionID, pageURI) { return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`); } static cancelDelete(collectionID, pageURI) { return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } static async checkContentIsInCollection(pageURI) { return http.get(`/zebedee/checkcollectionsforuri?uri=${pageURI}`) } }
import http from '../http'; export default class collections { static get(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response; }) } static getAll() { return http.get(`/zebedee/collections`) .then(response => { return response; }) } static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } static approve(collectionID) { return http.post(`/zebedee/approve/${collectionID}`); } static delete(collectionID) { return http.delete(`/zebedee/collection/${collectionID}`); } static update(collectionID, body) { body.id = collectionID; return http.put(`/zebedee/collection/${collectionID}`, body); } static deletePage(collectionID, pageURI) { return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`); } static cancelDelete(collectionID, pageURI) { return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } }
Fix tests python 2.6 support
from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON class ViewsTests(BaseAppTest): def test_validpath(self): for (path, expect) in ( ('/', 'home'), ('/index.html', 'home'), ('/level1', 'level 1'), ('/level1/', 'level 1'), ('/level1/index.html', 'level 1'), ('/level1/other.html', 'other'), ('/level1/level2', 'level 2'), ('/level1/level2/index.html', 'level 2'), ): result = self.testapp.get(path, extra_environ=AUTH_ENVIRON, status=200) self.assertTrue(expect in result.body) def test_not_validpath(self): for path in ( '/other.html', '/index', '/level1/index', '/level3/', ): self.testapp.get(path, extra_environ=AUTH_ENVIRON, status=404) class MimeTypeTests(BaseAppTest): def test_mimetypes(self): for (path, mimetype) in ( ('/', 'text/html'), ('/index.html', 'text/html'), ('/example.jpeg', 'image/jpeg'), ): result = self.testapp.get(path, extra_environ=AUTH_ENVIRON) self.assertEqual(result.content_type, mimetype)
from s3authbasic.testing import BaseAppTest, AUTH_ENVIRON class ViewsTests(BaseAppTest): def test_validpath(self): for (path, expect) in ( ('/', 'home'), ('/index.html', 'home'), ('/level1', 'level 1'), ('/level1/', 'level 1'), ('/level1/index.html', 'level 1'), ('/level1/other.html', 'other'), ('/level1/level2', 'level 2'), ('/level1/level2/index.html', 'level 2'), ): result = self.testapp.get(path, extra_environ=AUTH_ENVIRON, status=200) self.assertIn(expect, result.body) def test_not_validpath(self): for path in ( '/other.html', '/index', '/level1/index', '/level3/', ): self.testapp.get(path, extra_environ=AUTH_ENVIRON, status=404) class MimeTypeTests(BaseAppTest): def test_mimetypes(self): for (path, mimetype) in ( ('/', 'text/html'), ('/index.html', 'text/html'), ('/example.jpeg', 'image/jpeg'), ): result = self.testapp.get(path, extra_environ=AUTH_ENVIRON) self.assertEqual(result.content_type, mimetype)
Fix issue with UTCDateTime constructor.
<?php namespace Northstar\Console\Commands; use Northstar\Models\User; use MongoDB\BSON\UTCDateTime; use Illuminate\Console\Command; use Illuminate\Support\Collection; class RemoveOldBirthdates extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'northstar:olds'; /** * The console command description. * * @var string */ protected $description = 'Remove birthdates that are way too old.'; /** * Execute the console command. * * @return mixed */ public function handle() { // Get any users where 'birthdate' is before 1900. Note that strtotime gives // us a traditional UNIX timestamp (in seconds), but UTCDateTime wants a // JavaScript-style timestamp (in milliseconds). $query = User::whereRaw([ 'birthdate' => [ '$lt' => new UTCDateTime(strtotime('1900-01-01 00:00:00') * 1000), ], ]); $progressBar = $this->output->createProgressBar($query->count()); $query->chunkById(200, function (Collection $users) use ($progressBar) { foreach ($users as $user) { $birthdate = $user->birthdate; $user->birthdate = null; $user->save(); $progressBar->advance(); info('Removed invalid birthdate.', [ 'id' => $user->id, 'birthdate' => $birthdate, ]); } }); $progressBar->finish(); } }
<?php namespace Northstar\Console\Commands; use Northstar\Models\User; use MongoDB\BSON\UTCDateTime; use Illuminate\Console\Command; use Illuminate\Support\Collection; class RemoveOldBirthdates extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'northstar:olds'; /** * The console command description. * * @var string */ protected $description = 'Remove birthdates that are way too old.'; /** * Execute the console command. * * @return mixed */ public function handle() { // Get any users where 'birthdate' is before 1900... a.k.a way too old: $query = User::whereRaw([ 'birthdate' => [ '$lt' => new UTCDateTime(strtotime('1900-01-01 00:00:00')), ], ]); $progressBar = $this->output->createProgressBar($query->count()); $query->chunkById(200, function (Collection $users) use ($progressBar) { foreach ($users as $user) { $birthdate = $user->birthdate; $user->birthdate = null; $user->save(); $progressBar->advance(); info('Removed invalid birthdate.', [ 'id' => $user->id, 'birthdate' => $birthdate, ]); } }); $progressBar->finish(); } }
Add the getService shorcut method
<?php namespace A5sys\MinkContext\Context; use Behat\MinkExtension\Context\MinkContext; /** * A symfony2 context */ class SymfonyContext extends MinkContext { use \A5sys\MinkContext\Traits\MinkTrait; protected $em = null; protected $kernel = null; protected $container = null; protected $doctrine = null; /** * Initializes context. * * @param Kernel $kernel */ public function __construct($kernel) { $this->kernel = $kernel; $this->container = $kernel->getContainer(); $this->doctrine = $kernel->getContainer()->get('doctrine'); $this->em = $this->doctrine->getManager(); } /** * Get a service * * @param string $serviceName The name of the service to retrieve * * @return Service */ public function getService($serviceName) { return $this->container->get($serviceName); } /** * * @return EntityManager */ protected function getEntityManager() { return $this->em; } /** * * @return Doctrine */ protected function getDoctrine() { return $this->doctrine; } /** * * @return Container */ protected function getContainer() { return $this->container; } /** * * @return AppKernel */ protected function getKernel() { return $this->kernel; } }
<?php namespace A5sys\MinkContext\Context; use Behat\MinkExtension\Context\MinkContext; /** * A symfony2 context */ class SymfonyContext extends MinkContext { use \A5sys\MinkContext\Traits\MinkTrait; protected $em = null; protected $kernel = null; protected $container = null; protected $doctrine = null; /** * Initializes context. * * @param Kernel $kernel */ public function __construct($kernel) { $this->kernel = $kernel; $this->container = $kernel->getContainer(); $this->doctrine = $kernel->getContainer()->get('doctrine'); $this->em = $this->doctrine->getManager(); } /** * * @return EntityManager */ protected function getEntityManager() { return $this->em; } /** * * @return Doctrine */ protected function getDoctrine() { return $this->doctrine; } /** * * @return Container */ protected function getContainer() { return $this->container; } /** * * @return AppKernel */ protected function getKernel() { return $this->kernel; } }
Add Pillow to tests require
#/usr/bin/env python import os from setuptools import setup, find_packages ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) # Dynamically calculate the version based on photologue.VERSION version_tuple = __import__('photologue').VERSION if len(version_tuple) == 3: version = "%d.%d.%s" % version_tuple else: version = "%d.%d" % version_tuple[:2] setup( name = "django-photologue-praekelt", version = version, description = "Powerful image management for the Django web framework. Praekelt fork.", author = "Justin Driscoll", author_email = "[email protected]", url = "https://github.com/praekelt/django-photologue/", packages = find_packages(), package_data = { 'photologue': [ 'res/*.jpg', 'locale/*/LC_MESSAGES/*', 'templates/photologue/*.html', 'templates/photologue/tags/*.html', ] }, zip_safe = False, test_suite="setuptest.setuptest.SetupTestSuite", tests_require=[ 'django-setuptest>=0.1.4', 'Pillow', ], classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], )
#/usr/bin/env python import os from setuptools import setup, find_packages ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) # Dynamically calculate the version based on photologue.VERSION version_tuple = __import__('photologue').VERSION if len(version_tuple) == 3: version = "%d.%d.%s" % version_tuple else: version = "%d.%d" % version_tuple[:2] setup( name = "django-photologue-praekelt", version = version, description = "Powerful image management for the Django web framework. Praekelt fork.", author = "Justin Driscoll", author_email = "[email protected]", url = "https://github.com/praekelt/django-photologue/", packages = find_packages(), package_data = { 'photologue': [ 'res/*.jpg', 'locale/*/LC_MESSAGES/*', 'templates/photologue/*.html', 'templates/photologue/tags/*.html', ] }, zip_safe = False, test_suite="setuptest.setuptest.SetupTestSuite", tests_require=[ 'django-setuptest>=0.1.4', ], classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], )
OEE-1075: Update rate converter to support fixation logic - Add freeze case in unit tests - Rewrite converter for base currency amount usage instead of rate - Remove unused param from convert method
<?php namespace Oro\Bundle\CurrencyBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Oro\Bundle\DataAuditBundle\Metadata\Annotation as Oro; class MultiCurrency { use CurrencyAwareTrait; protected $value; protected $baseCurrencyValue = null; /** * @param string $value * @param string $currency * @param string | null $baseCurrencyValue * @return MultiCurrency */ public static function create($value, $currency, $baseCurrencyValue = null) { /* @var $multiCurrency self */ $multiCurrency = new static(); $multiCurrency->setValue($value) ->setCurrency($currency) ->setBaseCurrencyValue($baseCurrencyValue); return $multiCurrency; } /** * @return string */ public function getValue() { return $this->value; } /** * @param string $value * @return $this */ public function setValue($value) { $this->value = $value; return $this; } /** * @return string|null */ public function getBaseCurrencyValue() { return $this->baseCurrencyValue; } /** * @param $baseCurrencyValue * @return $this */ public function setBaseCurrencyValue($baseCurrencyValue) { $this->baseCurrencyValue = $baseCurrencyValue; return $this; } }
<?php namespace Oro\Bundle\CurrencyBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Oro\Bundle\DataAuditBundle\Metadata\Annotation as Oro; class MultiCurrency { use CurrencyAwareTrait; protected $value; protected $rate; protected $baseCurrencyValue; /** * @param string $value * @param string $currency * @param float $rate | null * @return MultiCurrency */ public static function create($value, $currency, $rate = null) { /* @var $multiCurrency self */ $multiCurrency = new static(); $multiCurrency->setValue($value) ->setCurrency($currency) ->setRate($rate); return $multiCurrency; } /** * @return string */ public function getValue() { return $this->value; } /** * @param string $value * @return $this */ public function setValue($value) { $this->value = $value; return $this; } /** * @return float */ public function getRate() { return $this->rate; } /** * @param float $rate * @return $this */ public function setRate($rate) { $this->rate = $rate; return $this; } /** * @return mixed */ public function getBaseCurrencyValue() { return $this->baseCurrencyValue; } /** * @param $baseCurrencyValue * @return $this */ public function setBaseCurrencyValue($baseCurrencyValue) { $this->baseCurrencyValue = $baseCurrencyValue; return $this; } }
Fix &h not being removed from the message properly
package net.md_5.bungee.command; import net.md_5.bungee.BungeeCord; import net.md_5.bungee.ChatColor; import net.md_5.bungee.Permission; import net.md_5.bungee.UserConnection; public class CommandAlert extends Command { @Override public void execute(CommandSender sender, String[] args) { if (getPermission(sender) != Permission.ADMIN) { sender.sendMessage(ChatColor.RED + "You do not have permission to execute this command!"); return; } if (args.length == 0) { sender.sendMessage(ChatColor.RED + "You must supply a message."); } else { StringBuilder builder = new StringBuilder(); if (!args[0].contains("&h")) //They want to hide the alert prefix { builder.append(ChatColor.DARK_PURPLE); builder.append("[Alert] "); //No space at start. } for (String s : args) { s = s.replaceAll("&h", ""); //Fix replace builder.append(ChatColor.translateAlternateColorCodes('&', s)); //Allow custom colours builder.append(" "); } String message = builder.substring(0, builder.length() - 1); for (UserConnection con : BungeeCord.instance.connections.values()) { con.sendMessage(message); } } } }
package net.md_5.bungee.command; import net.md_5.bungee.BungeeCord; import net.md_5.bungee.ChatColor; import net.md_5.bungee.Permission; import net.md_5.bungee.UserConnection; public class CommandAlert extends Command { @Override public void execute(CommandSender sender, String[] args) { if (getPermission(sender) != Permission.ADMIN) { sender.sendMessage(ChatColor.RED + "You do not have permission to execute this command!"); return; } if (args.length == 0) { sender.sendMessage(ChatColor.RED + "You must supply a message."); } else { StringBuilder builder = new StringBuilder(); if (!args[0].contains("&h")) //They want to hide the alert prefix { builder.append(ChatColor.DARK_PURPLE); builder.append("[Alert] "); //No space at start. } else { args[0].replaceAll("&h", ""); //Remove hide control code from message } for (String s : args) { builder.append(ChatColor.translateAlternateColorCodes('&', s)); //Allow custom colours builder.append(" "); } String message = builder.substring(0, builder.length() - 1); for (UserConnection con : BungeeCord.instance.connections.values()) { con.sendMessage(message); } } } }
Add check to ensure second argument is an integer
<?php namespace DMS\Bundle\TwigExtensionBundle\Twig\Date; /** * Adds support for Padding a String in Twig */ class PadStringExtension extends \Twig_Extension { /** * Name of Extension * * @return string */ public function getName() { return 'PadStringExtension'; } /** * Available filters * * @return array */ public function getFilters() { return array( 'padString' => new \Twig_Filter_Method($this, 'padStringFilter'), ); } /** * Pads string on right or left with given padCharacter until string * reaches maxLength * * @param $value * @param $padCharacter * @param $maxLength * @param bool $padLeft * @return string */ public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true) { if ( ! is_int($maxLength) ) { throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer'); } if (function_exists('mb_strlen')) { $padLength = $maxLength - mb_strlen($value); } else { $padLength = $maxLength - strlen($value); } if ($padLength <= 0) { return $value; } $padString = str_repeat($padCharacter, $padLength); if ($padLeft) { return $padString . $value; } return $value . $padString; } }
<?php namespace DMS\Bundle\TwigExtensionBundle\Twig\Date; /** * Adds support for Padding a String in Twig */ class PadStringExtension extends \Twig_Extension { /** * Name of Extension * * @return string */ public function getName() { return 'PadStringExtension'; } /** * Available filters * * @return array */ public function getFilters() { return array( 'padString' => new \Twig_Filter_Method($this, 'padStringFilter'), ); } /** * Pads string on right or left with given padCharacter until string * reaches maxLength * * @param $value * @param $padCharacter * @param $maxLength * @param bool $padLeft * @return string */ public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true) { if (function_exists('mb_strlen')) { $padLength = $maxLength - mb_strlen($value); } else { $padLength = $maxLength - strlen($value); } if ($padLength <= 0) { return $value; } $padString = str_repeat($padCharacter, $padLength); if ($padLeft) { return $padString . $value; } return $value . $padString; } }
Move return statement in _lookup_user into except/else flow
from django.contrib.auth import get_user_model from django.conf import settings from django.contrib.auth.models import check_password from django.core.validators import validate_email from django.forms import ValidationError User = get_user_model() class EmailOrUsernameAuthBackend(): """ A custom authentication backend. Allows users to log in using their email address or username. """ def _lookup_user(self, username_or_email): try: validate_email(username_or_email) except ValidationError: # not an email using_email = False else: # looks like an email! using_email = True try: if using_email: user = User.objects.get(email__iexact=username_or_email) else: user = User.objects.get(username__iexact=username_or_email) except User.DoesNotExist: return None else: return user def authenticate(self, username=None, password=None): """ Authentication method - username here is actually "username_or_email", but named as such to fit Django convention """ user = self._lookup_user(username) if user: if user.check_password(password): return user return None def get_user(self, user_id): try: user = User.objects.get(pk=user_id) if user.is_active: return user return None except User.DoesNotExist: return None
from django.contrib.auth import get_user_model from django.conf import settings from django.contrib.auth.models import check_password from django.core.validators import validate_email from django.forms import ValidationError User = get_user_model() class EmailOrUsernameAuthBackend(): """ A custom authentication backend. Allows users to log in using their email address or username. """ def _lookup_user(self, username_or_email): try: validate_email(username_or_email) except ValidationError: # not an email using_email = False else: # looks like an email! using_email = True try: if using_email: user = User.objects.get(email__iexact=username_or_email) else: user = User.objects.get(username__iexact=username_or_email) except User.DoesNotExist: return None return user def authenticate(self, username=None, password=None): """ Authentication method - username here is actually "username_or_email", but named as such to fit Django convention """ user = self._lookup_user(username) if user: if user.check_password(password): return user return None def get_user(self, user_id): try: user = User.objects.get(pk=user_id) if user.is_active: return user return None except User.DoesNotExist: return None
Add new config variables to example config
var fs = require('fs'); var splitca = require('split-ca'); module.exports = { webServerPort: 8080, /* MySQL config */ MySQL_Hostname: 'localhost', MySQL_Username: 'root', MySQL_Password: '', MySQL_Database: 'janusvr', /* Redis config */ redis: { host: "127.0.0.1", port: 6379, //password: null }, /* SSL config */ ssl: { port: 8081, options: { ca: splitca('cert/cabundle.pem'), key: fs.readFileSync('cert/server-key.pem'), cert: fs.readFileSync('cert/server-cert.pem'), } }, /* AWS config */ aws: { secretAccessKey: '', accessKeyId: '', region: '', screenshotBucket: '' }, /* API Config */ apis: { popularRooms: { enabled: true, }, addThumb: { enabled: true, masterToken: 'changethis' }, partyList: { enabled: true, }, perfLog: { enabled: true, db: "perflogs" }, screenshot: { enabled: true } } }
var fs = require('fs'); var splitca = require('split-ca'); module.exports = { webServerPort: 8080, /* MySQL config */ MySQL_Hostname: 'localhost', MySQL_Username: 'root', MySQL_Password: '', MySQL_Database: 'janusvr', /* Redis config */ redis: { host: "127.0.0.1", port: 6379, //password: null }, /* SSL config */ ssl: { port: 8081, options: { ca: splitca('cert/cabundle.pem'), key: fs.readFileSync('cert/server-key.pem'), cert: fs.readFileSync('cert/server-cert.pem'), } }, /* API Config */ apis: { popularRooms: { enabled: true, }, addThumb: { enabled: true, masterToken: 'changethis' }, partyList: { enabled: true, }, perfLog: { enabled: true, db: "perflogs" } } }
Set HOME, allow errors to pass through to stdout/stderr
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import os import shutil import subprocess import tempfile from string import Template from .artifact import Artifact LOG = logging.getLogger(__name__) class MWM(object): name = 'mwm' description = 'maps.me MWM' cmd = Template('generate_mwm.sh $input') def __init__(self, input): """ Initialize the MWM generation utility. Args: pbf: the source PBF """ self.input = input self.output = os.path.splitext(input)[0] + '.mwm' def run(self): if self.is_complete: LOG.debug("Skipping MWM, file exists") return convert_cmd = self.cmd.safe_substitute({ 'input': self.input, }) LOG.debug('Running: %s' % convert_cmd) tmpdir = tempfile.mkdtemp() env = os.environ.copy() env.update(HOME=tmpdir, MWM_WRITABLE_DIR=tmpdir, TARGET=os.path.dirname(self.output)) try: subprocess.check_call( convert_cmd, env=env, shell=True, executable='/bin/bash') LOG.debug('generate_mwm.sh complete') finally: shutil.rmtree(tmpdir) @property def results(self): return [Artifact([self.output], self.name)] @property def is_complete(self): return os.path.isfile(self.output)
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import os import shutil import subprocess import tempfile from string import Template from .artifact import Artifact LOG = logging.getLogger(__name__) class MWM(object): name = 'mwm' description = 'maps.me MWM' cmd = Template('generate_mwm.sh $input') def __init__(self, input): """ Initialize the MWM generation utility. Args: pbf: the source PBF """ self.input = input self.output = os.path.splitext(input)[0] + '.mwm' def run(self): if self.is_complete: LOG.debug("Skipping MWM, file exists") return convert_cmd = self.cmd.safe_substitute({ 'input': self.input, }) LOG.debug('Running: %s' % convert_cmd) tmpdir = tempfile.mkdtemp() env = os.environ.copy() env.update(MWM_WRITABLE_DIR=tmpdir, TARGET=os.path.dirname(self.output)) try: subprocess.check_call( convert_cmd, env=env, shell=True, executable='/bin/bash', stdout=subprocess.PIPE, stderr=subprocess.PIPE) LOG.debug('generate_mwm.sh complete') finally: shutil.rmtree(tmpdir) @property def results(self): return [Artifact([self.output], self.name)] @property def is_complete(self): return os.path.isfile(self.output)
Fix up some settings for start_zone()
import xmlrpclib from supervisor.xmlrpc import SupervisorTransport def start_zone(port=1300, zoneid="defaultzone", processgroup='zones', autorestart=False): s = xmlrpclib.ServerProxy('http://localhost:9001') import socket try: version = s.twiddler.getAPIVersion() except(socket.error), exc: raise UserWarning("Could not connect to supervisor: %s" % exc) if float(version) >= 0.3: command = '/usr/bin/python zoneserver.py --port=%d --zoneid=%s' % (int(port), zoneid) settings = {'command': command, 'autostart': str(True), 'autorestart': str(autorestart), 'redirect_stderr': str(True)} try: addtogroup = s.twiddler.addProgramToGroup(processgroup, zoneid, settings) except(xmlrpclib.Fault), exc: if "BAD_NAME" in exc.faultString: raise UserWarning("Zone already exists in process list.") else: print exc print exc.faultCode, exc.faultString raise if addtogroup: return True else: raise UserWarning("Couldn't add zone %s to process group." % zoneid) else: raise UserWarning("Twiddler version too old.") if __name__ == "__main__": if start_zone(): print "Started zone successfully."
import xmlrpclib from supervisor.xmlrpc import SupervisorTransport def start_zone(port=1300, zoneid="defaultzone", processgroup='zones', autorestart=False): s = xmlrpclib.ServerProxy('http://localhost:9001') import socket try: version = s.twiddler.getAPIVersion() except(socket.error), exc: raise UserWarning("Could not connect to supervisor: %s" % exc) if float(version) >= 0.3: command = '/usr/bin/python zoneserver.py --port=%d --zoneid=%s' % (port, zoneid) settings = {'command': command, 'autostart': str(True), 'autorestart': str(autorestart)} try: addtogroup = s.twiddler.addProgramToGroup(processgroup, zoneid, settings) except(xmlrpclib.Fault), exc: if "BAD_NAME" in exc.faultString: raise UserWarning("Zone already exists in process list.") else: print exc print exc.faultCode, exc.faultString raise if addtogroup: return True else: raise UserWarning("Couldn't add zone %s to process group." % zoneid) else: raise UserWarning("Twiddler version too old.") if __name__ == "__main__": if start_zone(): print "Started zone successfully."
Fix linting issue after updating mocha-eslint.
var stringUtil = require('ember-cli-string-utils'); var SilentError = require('silent-error'); var pathUtil = require('ember-cli-path-utils'); module.exports = { description: 'Generates an ember-data adapter.', availableOptions: [ { name: 'base-class', type: String } ], locals: function(options) { var adapterName = options.entity.name; var baseClass = 'JSONAPIAdapter'; var importStatement = 'import JSONAPIAdapter from \'ember-data/adapters/json-api\';'; var isAddon = options.inRepoAddon || options.project.isEmberCLIAddon(); var relativePath = pathUtil.getRelativePath(options.entity.name); if (options.pod && options.podPath) { relativePath = pathUtil.getRelativePath(options.podPath + options.entity.name); } if (!isAddon && !options.baseClass && adapterName !== 'application') { options.baseClass = 'application'; } if (options.baseClass === adapterName) { throw new SilentError('Adapters cannot extend from themself. To resolve this, remove the `--base-class` option or change to a different base-class.'); } if (options.baseClass) { baseClass = stringUtil.classify(options.baseClass.replace('/', '-')); baseClass = baseClass + 'Adapter'; importStatement = 'import ' + baseClass + ' from \'' + relativePath + options.baseClass + '\';'; } return { importStatement: importStatement, baseClass: baseClass }; } };
var stringUtil = require('ember-cli-string-utils'); var SilentError = require('silent-error'); var pathUtil = require('ember-cli-path-utils'); module.exports = { description: 'Generates an ember-data adapter.', availableOptions: [ { name: 'base-class', type: String } ], locals: function(options) { var adapterName = options.entity.name; var baseClass = 'JSONAPIAdapter'; var importStatement = 'import JSONAPIAdapter from \'ember-data/adapters/json-api\';'; var isAddon = options.inRepoAddon || options.project.isEmberCLIAddon(); var relativePath = pathUtil.getRelativePath(options.entity.name); if (options.pod && options.podPath) { relativePath = pathUtil.getRelativePath(options.podPath + options.entity.name); } if (!isAddon && !options.baseClass && adapterName !== 'application') { options.baseClass = 'application'; } if (options.baseClass === adapterName) { throw new SilentError('Adapters cannot extend from themself. To resolve this, remove the `--base-class` option or change to a different base-class.'); } if (options.baseClass) { baseClass = stringUtil.classify(options.baseClass.replace('\/', '-')); baseClass = baseClass + 'Adapter'; importStatement = 'import ' + baseClass + ' from \'' + relativePath + options.baseClass + '\';'; } return { importStatement: importStatement, baseClass: baseClass }; } };
Change timer test so that we can reproduce the random issue. Change timings.
package competitive.programming.timemanagement; import static org.junit.Assert.fail; import org.junit.Test; public class TimerTest { @Test public void nonStartedTimerDoesNotTimeout() { Timer timer = new Timer(); try { timer.timeCheck(); sleep(1); timer.timeCheck(); } catch (TimeoutException e) { fail(); } } @Test public void doesNotTimeOutBeforeTimeoutReached() { Timer timer = new Timer(); try { // We have a random failing test here. Try to reproduce the issue // more frequently. for (int i = 0; i < 100; i++) { timer.startTimer(20); sleep(10); timer.timeCheck(); } } catch (TimeoutException e) { fail(); } } @Test(expected = TimeoutException.class) public void timeoutReached() throws TimeoutException { Timer timer = new Timer(); timer.startTimer(1); sleep(2); timer.timeCheck(); } private void sleep(long milliseconds) { // I had some difficulties to sleep precisely a number of milliseconds. // Thread.sleep was not fine... long start = System.nanoTime(); long timeout = start + milliseconds * 1000 * 1000; while (System.nanoTime() < timeout) { // do nothing } } }
package competitive.programming.timemanagement; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import competitive.programming.timemanagement.TimeoutException; import competitive.programming.timemanagement.Timer; public class TimerTest { @Test public void nonStartedTimerDoesNotTimeout() { Timer timer = new Timer(); try { timer.timeCheck(); sleep(1); timer.timeCheck(); } catch (TimeoutException e) { fail(); } } @Test public void doesNotTimeOutBeforeTimeoutReached() { Timer timer = new Timer(); try { timer.startTimer(2); sleep(1); long currentTimeTaken = timer.currentTimeTakenInNanoSeconds(); assertTrue(currentTimeTaken>1*1000*1000); assertTrue(currentTimeTaken<2*1000*1000); timer.timeCheck(); } catch (TimeoutException e) { fail(); } } @Test(expected = TimeoutException.class) public void timeoutReached() throws TimeoutException { Timer timer = new Timer(); timer.startTimer(1); sleep(2); timer.timeCheck(); } private void sleep(long milliseconds){ //I had some difficulties to sleep precisely a number of milliseconds. //Thread.sleep was not fine... long start = System.nanoTime(); long timeout = start+milliseconds*1000*1000; while (System.nanoTime()<timeout){ //do nothing } } }
Use match instead of query string for now.
var elasticsearch = require('elasticsearch'); var client = new elasticsearch.Client({ host: process.env.ELASTICSEARCH, }); function query(q) { return client.search({ index: 'chadocs', type: 'document', body: { query: { filtered: { query: { match: { content: q } } } }, highlight: { fields: { content: {} } }, fields: [ "title", "original_source_url" ], from: 0, size: 50, sort: { _score: { order: "desc" } }, } }); } exports.query = query;
var elasticsearch = require('elasticsearch'); var client = new elasticsearch.Client({ host: process.env.ELASTICSEARCH, }); function query(q) { return client.search({ index: 'chadocs', type: 'document', body: { query: { filtered: { query: { query_string: { query: q } } } }, highlight: { fields: { content: {} } }, fields: [ "title", "original_source_url" ], from: 0, size: 50, sort: { _score: { order: "desc" } }, } }); } exports.query = query;
Add type to import method
<?php namespace CfdiUtils\Nodes; use \DOMElement; class XmlNodeImporter { /** * Local record for registered namespaces to avoid set the namespace declaration in every children * @var string[] */ private $registeredNamespaces = []; public function import(DOMElement $element): NodeInterface { $node = new Node($element->tagName); if ('' !== $element->prefix) { $this->registerNamespace($node, 'xmlns:' . $element->prefix, $element->namespaceURI); $this->registerNamespace($node, 'xmlns:xsi', 'http://www.w3.org/2001/xmlschema-instance'); } /** @var \DOMNode $attribute */ foreach ($element->attributes as $attribute) { $node[$attribute->nodeName] = $attribute->nodeValue; } /** @var DOMElement $childElement */ foreach ($element->childNodes as $childElement) { if (! $childElement instanceof DOMElement) { continue; } $childNode = $this->import($childElement); $node->children()->add($childNode); } return $node; } private function registerNamespace(Node $node, string $prefix, string $uri) { if (isset($this->registeredNamespaces[$prefix])) { return; } $this->registeredNamespaces[$prefix] = $uri; $node[$prefix] = $uri; } }
<?php namespace CfdiUtils\Nodes; use DOMElement; class XmlNodeImporter { /** * Local record for registered namespaces to avoid set the namespace declaration in every children * @var string[] */ private $registeredNamespaces = []; public function import($element): NodeInterface { $node = new Node($element->tagName); if ('' !== $element->prefix) { $this->registerNamespace($node, 'xmlns:' . $element->prefix, $element->namespaceURI); $this->registerNamespace($node, 'xmlns:xsi', 'http://www.w3.org/2001/xmlschema-instance'); } /** @var \DOMNode $attribute */ foreach ($element->attributes as $attribute) { $node[$attribute->nodeName] = $attribute->nodeValue; } /** @var DOMElement $childElement */ foreach ($element->childNodes as $childElement) { if (! $childElement instanceof DOMElement) { continue; } $childNode = $this->import($childElement); $node->children()->add($childNode); } return $node; } private function registerNamespace(Node $node, string $prefix, string $uri) { if (isset($this->registeredNamespaces[$prefix])) { return; } $this->registeredNamespaces[$prefix] = $uri; $node[$prefix] = $uri; } }
Remove simplekv requirement, mark as procution instead of beta
""" Flask-JWT-Extended ------------------- Flask-Login provides jwt endpoint protection for Flask. """ from setuptools import setup setup(name='Flask-JWT-Extended', version='2.4.1', url='https://github.com/vimalloc/flask-jwt-extended', license='MIT', author='Landon Gilbert-Bland', author_email='[email protected]', description='Extended JWT integration with Flask', long_description='Extended JWT integration with Flask', keywords = ['flask', 'jwt', 'json web token'], packages=['flask_jwt_extended'], zip_safe=False, platforms='any', install_requires=['Flask', 'PyJWT'], extras_require={ 'asymmetric_crypto': ["cryptography"] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ])
""" Flask-JWT-Extended ------------------- Flask-Login provides jwt endpoint protection for Flask. """ from setuptools import setup setup(name='Flask-JWT-Extended', version='2.4.1', url='https://github.com/vimalloc/flask-jwt-extended', license='MIT', author='Landon Gilbert-Bland', author_email='[email protected]', description='Extended JWT integration with Flask', long_description='Extended JWT integration with Flask', keywords = ['flask', 'jwt', 'json web token'], packages=['flask_jwt_extended'], zip_safe=False, platforms='any', install_requires=['Flask', 'PyJWT', 'simplekv'], extras_require={ 'asymmetric_crypto': ["cryptography"] }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ])
Revert my previous 'fix' for point projection
var cornerstoneTools = (function ($, cornerstone, cornerstoneTools) { "use strict"; if(cornerstoneTools === undefined) { cornerstoneTools = {}; } if(cornerstoneTools.referenceLines === undefined) { cornerstoneTools.referenceLines = {}; } // projects a patient point to an image point function projectPatientPointToImagePlane(patientPoint, imagePlane) { var point = patientPoint.clone().sub(imagePlane.imagePositionPatient); var x = imagePlane.rowCosines.dot(point) / imagePlane.columnPixelSpacing; var y = imagePlane.columnCosines.dot(point) / imagePlane.rowPixelSpacing; var imagePoint = {x: x, y: y}; return imagePoint; } // projects an image point to a patient point function imagePointToPatientPoint(imagePoint, imagePlane) { var x = imagePlane.rowCosines.clone().multiplyScalar(imagePoint.x); x.multiplyScalar(imagePlane.columnPixelSpacing); var y = imagePlane.columnCosines.clone().multiplyScalar(imagePoint.y); y.multiplyScalar(imagePlane.rowPixelSpacing); var patientPoint = x.add(y); patientPoint.add(imagePlane.imagePositionPatient); return patientPoint; } // module/private exports cornerstoneTools.projectPatientPointToImagePlane = projectPatientPointToImagePlane; cornerstoneTools.imagePointToPatientPoint = imagePointToPatientPoint; return cornerstoneTools; }($, cornerstone, cornerstoneTools));
var cornerstoneTools = (function ($, cornerstone, cornerstoneTools) { "use strict"; if(cornerstoneTools === undefined) { cornerstoneTools = {}; } if(cornerstoneTools.referenceLines === undefined) { cornerstoneTools.referenceLines = {}; } // projects a patient point to an image point function projectPatientPointToImagePlane(patientPoint, imagePlane) { var point = patientPoint.clone().sub(imagePlane.imagePositionPatient); var x = imagePlane.columnCosines.dot(point) / imagePlane.columnPixelSpacing; var y = imagePlane.rowCosines.dot(point) / imagePlane.rowPixelSpacing; var imagePoint = {x: x, y: y}; return imagePoint; } // projects an image point to a patient point function imagePointToPatientPoint(imagePoint, imagePlane) { var x = imagePlane.columnCosines.clone().multiplyScalar(imagePoint.x); x.multiplyScalar(imagePlane.columnPixelSpacing); var y = imagePlane.rowCosines.clone().multiplyScalar(imagePoint.y); y.multiplyScalar(imagePlane.rowPixelSpacing); var patientPoint = x.add(y); patientPoint.add(imagePlane.imagePositionPatient); return patientPoint; } // module/private exports cornerstoneTools.projectPatientPointToImagePlane = projectPatientPointToImagePlane; cornerstoneTools.imagePointToPatientPoint = imagePointToPatientPoint; return cornerstoneTools; }($, cornerstone, cornerstoneTools));
Fix rendering in show status When rendering in the show status, if the labels span multiple lines, the formatting breaks. Adding the clearfix to the fieldgroup ensures that each row of the form is correctly rendered.
@if (in_array($field->type, array('hidden','auto')) OR !$field->has_wrapper ) {!! $field->output !!} @if ($field->message!='') <span class="help-block"> <span class="glyphicon glyphicon-warning-sign"></span> {!! $field->message !!} </span> @endif @else <div class="form-group clearfix{!!$field->has_error!!}" id="fg_{!! $field->name !!}" > @if ($field->has_label) <label for="{!! $field->name !!}" class="col-sm-2 control-label{!! $field->req !!}">{!! $field->label !!}</label> <div class="col-sm-10" id="div_{!! $field->name !!}"> @else <div class="col-sm-12" id="div_{!! $field->name !!}"> @endif {!! $field->output !!} @if(count($field->messages)) @foreach ($field->messages as $message) <span class="help-block"> <span class="glyphicon glyphicon-warning-sign"></span> {!! $message !!} </span> @endforeach @endif </div> </div> @endif
@if (in_array($field->type, array('hidden','auto')) OR !$field->has_wrapper ) {!! $field->output !!} @if ($field->message!='') <span class="help-block"> <span class="glyphicon glyphicon-warning-sign"></span> {!! $field->message !!} </span> @endif @else <div class="form-group{!!$field->has_error!!}" id="fg_{!! $field->name !!}"> @if ($field->has_label) <label for="{!! $field->name !!}" class="col-sm-2 control-label{!! $field->req !!}">{!! $field->label !!}</label> <div class="col-sm-10" id="div_{!! $field->name !!}"> @else <div class="col-sm-12" id="div_{!! $field->name !!}"> @endif {!! $field->output !!} @if(count($field->messages)) @foreach ($field->messages as $message) <span class="help-block"> <span class="glyphicon glyphicon-warning-sign"></span> {!! $message !!} </span> @endforeach @endif </div> </div> @endif
Add animation for button nav on IPhone
functions = { setButtonNav : function () { var windowWidth = $(window).width(), buttonNav = $('.side-nav__button'); buttonNav.addClass('on-mobile'); } }; $(document).ready(function () { functions.setButtonNav(); $('.side-nav-container').hover(function () { $(this).addClass('is-showed'); $('.kudo').addClass('hide'); }, function() { $(this).removeClass('is-showed'); $('.kudo').removeClass('hide'); }); $(window).scroll(function () { var logotype = $('.logotype'), buttonNav = $('.side-nav__button'), buttonNavMobile = buttonNav.filter('.on-mobile'), scrollTop = $(window).scrollTop(), windowHeight = $(window).height(), kudoSide = $('.kudo'), kudoBottom = $('.instapaper'), // $('.kudo-bottom') kudoBottomPosition = false; if (kudoBottom.length > 0) { kudoBottomPosition = kudoBottom.offset().top; // instapaper for now while adding kudo-bottom elem } if ( scrollTop > 150) { logotype.addClass('is-showed'); buttonNav.addClass('no-opacity'); if ( buttonNavMobile.length > 0) { buttonNavMobile.hide(); } } else { logotype.removeClass('is-showed'); buttonNav.removeClass('no-opacity'); if ( buttonNavMobile.length > 0) { buttonNavMobile.show(); } } if (kudoBottomPosition !== false && ( scrollTop + windowHeight > kudoBottomPosition)) { kudoSide.addClass('hide'); } else { kudoSide.removeClass('hide'); } }); $(window).resize(function () { functions.setButtonNav(); }); });
$(document).ready(function () { $('.side-nav-container').hover(function () { $(this).addClass('is-showed'); $('.kudo').addClass('hide'); }, function() { $(this).removeClass('is-showed'); $('.kudo').removeClass('hide'); }); $(window).scroll(function () { var logotype = $('.logotype'), buttonNav = $('.side-nav__button'), scrollTop = $(window).scrollTop(), windowHeight = $(window).outerHeight(), kudoSide = $('.kudo'); kudoBottom = $('.instapaper'); // $('.kudo-bottom') kudoBottomPosition = kudoBottom.offset().top; // instapaper for now while adding kudo-bottom elem if ( scrollTop > 150) { logotype.addClass('is-showed'); buttonNav.addClass('no-opacity'); } else { logotype.removeClass('is-showed'); buttonNav.removeClass('no-opacity') } if ( scrollTop + windowHeight > kudoBottomPosition) { kudoSide.addClass('hide'); } else { kudoSide.removeClass('hide'); } }); });
Add missing first word to replied messages
package net.wayward_realms.waywardchat; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class ReplyCommand implements CommandExecutor { private WaywardChat plugin; public ReplyCommand(WaywardChat plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) { if (plugin.getLastPrivateMessage((Player) sender) != null) { if (args.length >= 1) { StringBuilder message = new StringBuilder(); for (String arg : args) { message.append(arg).append(" "); } plugin.sendPrivateMessage((Player) sender, plugin.getLastPrivateMessage((Player) sender), message.toString()); } else { sender.sendMessage(plugin.getPrefix() + ChatColor.RED + "You must specify a message to reply with"); } } else { sender.sendMessage(plugin.getPrefix() + ChatColor.RED + "You have not recieved a private message recently (or the last group you recieved a message from was disbanded)"); } } else { sender.sendMessage(plugin.getPrefix() + ChatColor.RED + "You must be a player to perform this command."); } return true; } }
package net.wayward_realms.waywardchat; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class ReplyCommand implements CommandExecutor { private WaywardChat plugin; public ReplyCommand(WaywardChat plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) { if (plugin.getLastPrivateMessage((Player) sender) != null) { if (args.length >= 1) { StringBuilder message = new StringBuilder(); for (int i = 1; i < args.length; i++) { message.append(args[i]).append(" "); } plugin.sendPrivateMessage((Player) sender, plugin.getLastPrivateMessage((Player) sender), message.toString()); } else { sender.sendMessage(plugin.getPrefix() + ChatColor.RED + "You must specify a message to reply with"); } } else { sender.sendMessage(plugin.getPrefix() + ChatColor.RED + "You have not recieved a private message recently (or the last group you recieved a message from was disbanded)"); } } else { sender.sendMessage(plugin.getPrefix() + ChatColor.RED + "You must be a player to perform this command."); } return true; } }
Send a message instead of posting error. Let us free up more document memory.
// ==UserScript== // @include http://youtube.com/html5 // @include http://www.youtube.com/html5 // @include https://youtube.com/html5 // @include https://www.youtube.com/html5 // ==/UserScript== (function() { window.addEventListener('DOMContentLoaded', function() { submitFormWithSessionToken(); }, false); var form = document.getElementById('html5form'); function submitFormWithSessionToken() { if (widget.preferences.continueTesting == 'true') { if (form) { if (form.querySelector("input[name='enable_html5']")) { if (!form.querySelector("input[name='session_token']")) { form.addEventListener('DOMNodeInserted', formSubmitter, false); } else formSubmitter(); } else if (form.querySelector("input[name='disable_html5']")) { continueTesting(); opera.extension.postMessage('testCandidate'); }} else opera.extension.postMessage('discontinuedTesting'); }} function formSubmitter() { form.submit(); } function continueTesting() { // keep the test subjects in the HTML5 Trial var enrichmentCentre = document.getElementById('html5-join-link'), escapeElevator = enrichmentCentre.getElementsByTagName('h3')[0]; enrichmentCentre.removeChild(escapeElevator); } // ... there is no escape ... }());
// ==UserScript== // @include http://youtube.com/html5 // @include http://www.youtube.com/html5 // @include https://youtube.com/html5 // @include https://www.youtube.com/html5 // ==/UserScript== (function() { window.addEventListener('DOMContentLoaded', function() { submitFormWithSessionToken(); }, false); var form = document.getElementById('html5form'); function submitFormWithSessionToken() { if (widget.preferences.continueTesting == 'true') { if (form) { if (form.querySelector("input[name='enable_html5']")) { if (!form.querySelector("input[name='session_token']")) { form.addEventListener('DOMNodeInserted', formSubmitter, false); } else formSubmitter(); } else if (form.querySelector("input[name='disable_html5']")) { continueTesting(); opera.extension.postMessage('testCandidate'); }} else opera.postError('HTML5 Trial Applicant form not found.'); }} function formSubmitter() { form.submit(); } function continueTesting() { // keep the test subjects in the HTML5 Trial var enrichmentCentre = document.getElementById('html5-join-link'), escapeElevator = enrichmentCentre.getElementsByTagName('h3')[0]; enrichmentCentre.removeChild(escapeElevator); } // ... there is no escape ... }());
FIX : fenêtre login ne se ferme plus sur clic en dehors popup ou esc
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ (function () { define([], function () { var appRun = function ($rootScope, $sessionStorage, $state, $uibModal, authService, editableOptions) { editableOptions.theme = 'bs3'; $rootScope.loginOngoing = false; $rootScope.$on("event:auth-forbidden", function () { $state.go("app.dashboard"); }); $rootScope.$on("event:auth-loginRequired", function () { delete $sessionStorage.oauth; var modalScope = $rootScope.$new(); if (!$rootScope.loginOngoing) { $rootScope.loginOngoing = true; modalScope.modalInstance = $uibModal.open({ animation: true, backdrop: "static", templateUrl: "login.html", controller: "loginController", controllerAs: "login", scope: modalScope, keyboard: false, size: "md" }); modalScope.modalInstance.result.then( function () { authService.loginConfirmed(); $rootScope.loginOngoing = false; } ); } }); $state.go("login"); }; appRun.$inject = ["$rootScope", "$sessionStorage", "$state", "$uibModal", "authService", "editableOptions"]; return appRun; }); })();
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ (function () { define([], function () { var appRun = function ($rootScope, $sessionStorage, $state, $uibModal, authService, editableOptions) { editableOptions.theme = 'bs3'; $rootScope.loginOngoing = false; $rootScope.$on("event:auth-forbidden", function () { $state.go("app.dashboard"); }); $rootScope.$on("event:auth-loginRequired", function () { delete $sessionStorage.oauth; var modalScope = $rootScope.$new(); if (!$rootScope.loginOngoing) { $rootScope.loginOngoing = true; modalScope.modalInstance = $uibModal.open({ animation: true, templateUrl: "login.html", controller: "loginController", controllerAs: "login", scope: modalScope, backdrop: "static", size: "md" }); modalScope.modalInstance.result.then( function () { authService.loginConfirmed(); $rootScope.loginOngoing = false; } ); } }); $state.go("login"); }; appRun.$inject = ["$rootScope", "$sessionStorage", "$state", "$uibModal", "authService", "editableOptions"]; return appRun; }); })();
Revert "Use activity context not application context" This reverts commit e5ef5b32fc6592df810815226c0297485c4a83c3.
package com.fedorvlasov.lazylist; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class LazyAdapter extends BaseAdapter { private Activity activity; private String[] data; private static LayoutInflater inflater=null; public ImageLoader imageLoader; public LazyAdapter(Activity a, String[] d) { activity = a; data=d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader=new ImageLoader(activity.getApplicationContext()); } public int getCount() { return data.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.item, null); TextView text=(TextView)vi.findViewById(R.id.text);; ImageView image=(ImageView)vi.findViewById(R.id.image); text.setText("item "+position); imageLoader.DisplayImage(data[position], image); return vi; } }
package com.fedorvlasov.lazylist; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class LazyAdapter extends BaseAdapter { private Activity activity; private String[] data; private static LayoutInflater inflater=null; public ImageLoader imageLoader; public LazyAdapter(Activity a, String[] d) { activity = a; data=d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader=new ImageLoader(activity); } public int getCount() { return data.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.item, null); TextView text=(TextView)vi.findViewById(R.id.text);; ImageView image=(ImageView)vi.findViewById(R.id.image); text.setText("item "+position); imageLoader.DisplayImage(data[position], image); return vi; } }
Add name config property to the simple config fixture
module.exports = function() { return { 'translation.af': JSON.stringify({ '' : { 'domain' : 'messages', 'lang' : 'af', 'plural_forms' : 'nplurals=2; plural=(n != 1);' }, 'yes' : [null, 'ja'], 'no' : [null, 'nee'], 'yes?' : [null, 'ja?'], 'no!' : [null, 'nee!'], 'hello': [null, 'hallo'], 'hello?': [null, 'hallo?'], 'goodbye': [null, 'totsiens'] }), 'translation.jp': JSON.stringify({ '' : { 'domain' : 'messages', 'lang' : 'af', 'plural_forms' : 'nplurals=2; plural=(n != 1);' }, 'yes' : [null, 'hai'], 'no' : [null, 'iie'] }), config: JSON.stringify({ name: 'anakin_the_app', lerp: 'larp', metric_store: 'luke_the_store' }), foo: JSON.stringify({bar: 'baz'}) }; };
module.exports = function() { return { 'translation.af': JSON.stringify({ '' : { 'domain' : 'messages', 'lang' : 'af', 'plural_forms' : 'nplurals=2; plural=(n != 1);' }, 'yes' : [null, 'ja'], 'no' : [null, 'nee'], 'yes?' : [null, 'ja?'], 'no!' : [null, 'nee!'], 'hello': [null, 'hallo'], 'hello?': [null, 'hallo?'], 'goodbye': [null, 'totsiens'] }), 'translation.jp': JSON.stringify({ '' : { 'domain' : 'messages', 'lang' : 'af', 'plural_forms' : 'nplurals=2; plural=(n != 1);' }, 'yes' : [null, 'hai'], 'no' : [null, 'iie'] }), config: JSON.stringify({ lerp: 'larp', metric_store: 'luke_the_store' }), foo: JSON.stringify({bar: 'baz'}) }; };
Update leaflet request to be over https
from django.contrib.gis.forms import widgets class LeafletPointWidget(widgets.BaseGeometryWidget): template_name = 'leaflet/leaflet.html' class Media: css = { 'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css', 'leaflet/css/location_form.css', 'leaflet/css/LeafletWidget.css') } js = ( 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.js', 'leaflet/js/LeafletWidget.js' ) def render(self, name, value, attrs=None): # add point if value: attrs.update({ 'point': { 'x': value.x, 'y': value.y, 'z': value.z, 'srid': value.srid } }) return super().render(name, value, attrs)
from django.contrib.gis.forms import widgets class LeafletPointWidget(widgets.BaseGeometryWidget): template_name = 'leaflet/leaflet.html' class Media: css = { 'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css', 'leaflet/css/location_form.css', 'leaflet/css/LeafletWidget.css') } js = ( 'https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js', 'leaflet/js/LeafletWidget.js' ) def render(self, name, value, attrs=None): # add point if value: attrs.update({ 'point': { 'x': value.x, 'y': value.y, 'z': value.z, 'srid': value.srid } }) return super().render(name, value, attrs)
Make lodash an external for real
var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { devtool: 'source-map', entry: { 'tree-chooser': './src/index.js', 'tree-chooser.min': './src/index.js' }, output: { path: './dist', filename: '[name].js', library: 'tree-chooser', libraryTarget: 'commonjs' }, externals: { angular: 'angular', lodash : { 'commonjs': 'lodash' } }, module: { preLoaders: [ { test: /\.js/, exclude: /node_modules/, loader: 'jshint-loader!jscs-loader', }, ], loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'ng-annotate?single_quotes!babel?presets[]=es2015' }, { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') }, { test: /\.html$/, loader: 'html?minimize=true' } ] }, plugins: [ new ExtractTextPlugin('tree-chooser.css'), new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js$/, minimize: true }) ], jshint: { failOnHint: true, esversion: 6, node: true, quotmark: 'single' }, jscs: { failOnHint: true } };
var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { devtool: 'source-map', entry: { 'tree-chooser': './src/index.js', 'tree-chooser.min': './src/index.js' }, output: { path: './dist', filename: '[name].js' }, externals: { angular: 'angular', lodash: '_' }, module: { preLoaders: [ { test: /\.js/, exclude: /node_modules/, loader: 'jshint-loader!jscs-loader', }, ], loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'ng-annotate?single_quotes!babel?presets[]=es2015' }, { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') }, { test: /\.html$/, loader: 'html?minimize=true' } ] }, plugins: [ new ExtractTextPlugin('tree-chooser.css'), new webpack.optimize.UglifyJsPlugin({ include: /\.min\.js$/, minimize: true }) ], jshint: { failOnHint: true, esversion: 6, node: true, quotmark: 'single' }, jscs: { failOnHint: true } };
Change SpectrometerReader a little so it can handle more data formats.
# -*- coding: utf-8 -*- """ Created on Fri Aug 7 12:04:18 2015 @author: wirkert """ import numpy as np from msi.io.reader import Reader from msi.msi import Msi class SpectrometerReader(Reader): def __init__(self): pass def read(self, file_to_read): # our spectrometer like to follow german standards in files, we need # to switch to english ones transformed="" replacements = {',': '.', '\r\n': ''} with open(file_to_read) as infile: for line in infile: for src, target in replacements.iteritems(): line = line.replace(src, target) transformed = "\n".join([transformed, line]) for num, line in enumerate(transformed.splitlines(), 1): if ">>>>>Begin" in line: break for num_end, line in enumerate(transformed.splitlines(), 1): if ">>>>>End" in line: num_end -= 1 break string_only_spectrum = "\n".join(transformed.splitlines()[num:num_end]) data_vector = np.fromstring(string_only_spectrum, sep="\t").reshape(-1, 2) msi = Msi(data_vector[:, 1], {'wavelengths': data_vector[:, 0] * 10 ** -9}) return msi
# -*- coding: utf-8 -*- """ Created on Fri Aug 7 12:04:18 2015 @author: wirkert """ import numpy as np from msi.io.reader import Reader from msi.msi import Msi class SpectrometerReader(Reader): def __init__(self): pass def read(self, file_to_read): # our spectrometer like to follow german standards in files, we need # to switch to english ones transformed="" replacements = {',': '.', '\r\n': ''} with open(file_to_read) as infile: for line in infile: for src, target in replacements.iteritems(): line = line.replace(src, target) transformed = "\n".join([transformed, line]) for num, line in enumerate(transformed.splitlines(), 1): if ">>>>>Begin Spectral Data<<<<<" in line: break string_only_spectrum = "\n".join(transformed.splitlines()[num:]) data_vector = np.fromstring(string_only_spectrum, sep="\t").reshape(-1, 2) msi = Msi(data_vector[:, 1], {'wavelengths': data_vector[:, 0] * 10 ** -9}) return msi
Add method to get all families of currently loaded elements
class Lattice(object): def __init__(self, name): self.name = name self._elements = [] def __getitem__(self, i): return self._elements[i] def __len__(self): ''' Get the number of elements in the lattice ''' return len(self._elements) def __str__(self): print(self._elements) def get_length(self): ''' Get the length of the lattice in meters ''' total_length = 0 for e in self._elements: total_length += e.get_length() return total_length def add_element(self, element): ''' Add an element to the lattice # TODO: modify method to accept a set() arg ''' self._elements.append(element) def get_elements(self, family='*'): ''' Get all elements of a lattice from a specified family. If no family is specified, return all elements ''' if family == '*': return self._elements matched_elements = list() for element in self._elements: if family in element.families: matched_elements.append(element) return matched_elements def get_all_families(self): families = set() for element in self._elements: for family in element.families: families.add(family) return families
class Lattice(object): def __init__(self, name): self.name = name self._elements = [] def __getitem__(self, i): return self._elements[i] def __len__(self): ''' Get the number of elements in the lattice ''' return len(self._elements) def __str__(self): print(self._elements) def get_length(self): ''' Get the length of the lattice in meters ''' total_length = 0 for e in self._elements: total_length += e.get_length() return total_length def add_element(self, element): ''' Add an element to the lattice # TODO: modify method to accept a set() arg ''' self._elements.append(element) def get_elements(self, family='*'): ''' Get all elements of a lattice from a specified family. If no family is specified, return all elements ''' if family == '*': return self._elements matched_elements = list() for element in self._elements: if family in element.families: matched_elements.append(element) return matched_elements
Move mcapid calls to top of api to make it easier to identify REST routes that need to be replaced
class AccountsAPIService { /*@ngInject*/ constructor(apiService, Restangular, toast) { this.apiService = apiService; this.Restangular = Restangular; this.toast = toast; } createAccount(name, email, password) { return this.Restangular.one('v3').one('createNewUser').customPOST({ email: email, fullname: name, password: password, }).then(u => u.plain().data); } resetApiKey() { return this.Restangular.one('v3').one('resetUserApikey').customPOST().then( data => data.plain().data, e => this.toast.error(e.data.error) ); } changePassword(newPassword) { return this.Restangular.one('v3').one('changeUserPassword').customPOST({ password: newPassword }).then( () => true, e => this.toast.error(e.data.error) ); } resetUserPasswordWithValidate(uuid, password) { return this.Restangular.one('v3').one('resetUserPasswordFromUuid').customPOST({ validate_uuid: uuid, password: password, }).then( () => true ); } ////////////////// createResetPasswordRequest(email) { return this.apiService('accounts').one('reset').customPOST({ email: email }); } getUserForResetPassword(uuid) { return this.apiService('users').one('rvalidate', uuid).get(); } } angular.module('materialscommons').service('accountsAPI', AccountsAPIService);
class AccountsAPIService { /*@ngInject*/ constructor(apiService, Restangular, toast) { this.apiService = apiService; this.Restangular = Restangular; this.toast = toast; } createAccount(name, email, password) { return this.Restangular.one('v3').one('createNewUser').customPOST({ email: email, fullname: name, password: password, }).then(u => u.plain().data); } resetApiKey() { return this.Restangular.one('v3').one('resetUserApikey').customPOST().then( data => data.plain().data, e => this.toast.error(e.data.error) ); } changePassword(newPassword) { return this.Restangular.one('v3').one('changeUserPassword').customPOST({ password: newPassword }).then( () => true, e => this.toast.error(e.data.error) ); } createResetPasswordRequest(email) { return this.apiService('accounts').one('reset').customPOST({ email: email }); } getUserForResetPassword(uuid) { return this.apiService('users').one('rvalidate', uuid).get(); } resetUserPasswordWithValidate(uuid, password) { return this.Restangular.one('v3').one('resetUserPasswordFromUuid').customPOST({ validate_uuid: uuid, password: password, }).then( () => true ); } } angular.module('materialscommons').service('accountsAPI', AccountsAPIService);
Fix 6547 test case to account for new formatTime return
function runTest() { FBTest.sysout("issue6547.START"); FBTest.openNewTab(basePath + "cookies/6547/issue6547.php", function(win) { FBTest.openFirebug(); FBTest.selectPanel("net"); FBTestFireCookie.enableCookiePanel(); FBTest.enableNetPanel(function(win) { var options = { tagName: "tr", classes: "netRow category-html hasHeaders loaded" }; FBTest.waitForDisplayedElement("net", options, function(row) { var panelNode = FBTest.selectPanel("net").panelNode; FBTest.click(row); FBTest.expandElements(panelNode, "netInfoCookiesTab"); var selector = ".netInfoReceivedCookies .cookieRow .cookieMaxAgeLabel"; var label = panelNode.querySelector(selector); FBTest.compare("0ms", label.textContent, "Max age must be zero"); FBTest.testDone("issue6547.DONE"); }); }); }); }
function runTest() { FBTest.sysout("issue6547.START"); FBTest.openNewTab(basePath + "cookies/6547/issue6547.php", function(win) { FBTest.openFirebug(); FBTest.selectPanel("net"); FBTestFireCookie.enableCookiePanel(); FBTest.enableNetPanel(function(win) { var options = { tagName: "tr", classes: "netRow category-html hasHeaders loaded" }; FBTest.waitForDisplayedElement("net", options, function(row) { var panelNode = FBTest.selectPanel("net").panelNode; FBTest.click(row); FBTest.expandElements(panelNode, "netInfoCookiesTab"); var selector = ".netInfoReceivedCookies .cookieRow .cookieMaxAgeLabel"; var label = panelNode.querySelector(selector); FBTest.compare("0", label.textContent, "Max age must be zero"); FBTest.testDone("issue6547.DONE"); }); }); }); }
Change source to point to which part of the request caused the error, and add the specific reason to detail
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): for reason in value: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason}) else: errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.')
from rest_framework import status from rest_framework.exceptions import APIException def json_api_exception_handler(exc, context): """ Custom exception handler that returns errors object as an array """ # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node "title" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for key, value in message.iteritems(): if key in top_level_error_keys: errors.append({key: value}) else: if isinstance(value, list): for reason in value: errors.append({'source': {key: reason}}) else: errors.append({'source': {key: value}}) elif isinstance(message, (list, tuple)): for error in message: errors.append({'detail': error}) else: errors.append({'detail': message}) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.')
Make the whole retry page tappable
import React from "react-native"; import Page from "./page"; const { StyleSheet, View, Text, Image, TouchableOpacity } = React; const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center" }, failed: { fontSize: 18 }, button: { flexDirection: "row", alignItems: "center", padding: 16 }, label: { paddingHorizontal: 8, marginHorizontal: 8 }, icon: { height: 24, width: 24, opacity: 0.5 } }); export default class PageRetry extends React.Component { render() { return ( <Page {...this.props}> <TouchableOpacity onPress={this.props.onRetry} style={styles.container}> <Text style={styles.failed}>Failed to load data</Text> {this.props.onRetry ? <View style={styles.button}> <Image style={styles.icon} source={require("image!ic_refresh_black")} /> <Text style={styles.label}>Retry</Text> </View> : null } </TouchableOpacity> </Page> ); } } PageRetry.propTypes = { onRetry: React.PropTypes.func };
import React from "react-native"; import Page from "./page"; const { StyleSheet, View, Text, Image, TouchableOpacity } = React; const styles = StyleSheet.create({ failed: { fontSize: 18 }, button: { flexDirection: "row", alignItems: "center", padding: 16 }, label: { paddingHorizontal: 8, marginLeft: 8 }, icon: { height: 24, width: 24, opacity: 0.5 } }); export default class PageRetry extends React.Component { render() { return ( <Page {...this.props}> <Text style={styles.failed}>Failed to load data</Text> {this.props.onRetry ? <TouchableOpacity onPress={this.props.onRetry}> <View style={styles.button}> <Image style={styles.icon} source={require("image!ic_refresh_black")} /> <Text style={styles.label}>Retry</Text> </View> </TouchableOpacity> : null } </Page> ); } } PageRetry.propTypes = { onRetry: React.PropTypes.func };
Add back in geolocate url name.
from django.conf.urls.defaults import patterns, url, include from django.views.generic.simple import direct_to_template import django.views.static import settings import views # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^fmsgame/', include('fmsgame.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/', include(admin.site.urls)), (r'^$', direct_to_template, { 'template': 'login.html', } ), url(r'^geolocate$', direct_to_template, { 'template': 'geolocate.html', } name='geolocate'), ( r'^find_issues', views.find_issues, ), ( r'^issue/(?P<issue_id>[\d]+)/$', views.issue ), # openid login/registration (r'^openid/', include( 'django_openid_auth.urls' )), ) if settings.SERVE_STATIC_FILES: urlpatterns += patterns('', (r'^static/(?P<path>.*)$', django.views.static.serve, {'document_root':settings.MEDIA_ROOT}), )
from django.conf.urls.defaults import patterns, url, include from django.views.generic.simple import direct_to_template import django.views.static import settings import views # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^fmsgame/', include('fmsgame.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/', include(admin.site.urls)), (r'^$', direct_to_template, { 'template': 'login.html', } ), (r'^geolocate$', direct_to_template, { 'template': 'geolocate.html', } ), ( r'^find_issues', views.find_issues, ), ( r'^issue/(?P<issue_id>[\d]+)/$', views.issue ), # openid login/registration (r'^openid/', include( 'django_openid_auth.urls' )), ) if settings.SERVE_STATIC_FILES: urlpatterns += patterns('', (r'^static/(?P<path>.*)$', django.views.static.serve, {'document_root':settings.MEDIA_ROOT}), )
Clear indices list before reload
function DropdownCtrl($scope, $http, Data, pubsub) { $scope.data = Data; $scope.pubsub = pubsub; $scope.indices = []; $scope.types = []; $scope.pubsub.subscribe('HOST_CHANGED', function(newHost){ $scope.data.host = newHost; $scope.loadMappings(); }); $scope.loadMappings = function(){ var path = $scope.data.host + "/_mapping"; $http.get(path).then(function(response){ if($scope.indices && $scope.indices.length > 0){ $scope.indicies.length = 0; } $scope.data.mapping = response.data; for (i in response.data){ $scope.indices.push(i); $scope.types[i] = []; for (j in response.data[i]){ $scope.types[i].push(j); } } path = $scope.data.host + "/_aliases"; $http.get(path).then(function(response){ for (i in response.data){ for (j in response.data[i].aliases) { $scope.indices.push(j); $scope.types[j] = $scope.types[i]; $scope.data.mapping[j] = $scope.data.mapping[i]; } } $scope.indices.sort(); $scope.types.sort(); }); }); }; $scope.loadMappings(); }
function DropdownCtrl($scope, $http, Data, pubsub) { $scope.data = Data; $scope.pubsub = pubsub; $scope.indices = []; $scope.types = []; $scope.pubsub.subscribe('HOST_CHANGED', function(newHost){ $scope.data.host = newHost; $scope.loadMappings(); }); $scope.loadMappings = function(){ var path = $scope.data.host + "/_mapping"; $http.get(path).then(function(response){ $scope.data.mapping = response.data; for (i in response.data){ $scope.indices.push(i); $scope.types[i] = []; for (j in response.data[i]){ $scope.types[i].push(j); } } path = $scope.data.host + "/_aliases"; $http.get(path).then(function(response){ for (i in response.data){ for (j in response.data[i].aliases) { $scope.indices.push(j); $scope.types[j] = $scope.types[i]; $scope.data.mapping[j] = $scope.data.mapping[i]; } } $scope.indices.sort(); $scope.types.sort(); }); }); }; $scope.loadMappings(); }
Reset the padding on the background articles
(function() { var root = this, Peeler = function() {}, articles = document.querySelectorAll("article"), viewportWidth = root.innerWidth, aspectRatio = 1200/1440, bodyHeight = 0, articleStates = []; Peeler.prototype.bind = function() { var article, i, len, height; root.onscroll = function(event) { var yOffset = window.pageYOffset, i = 0; for (len = articles.length; i < len; i++) { if (yOffset <= articleStates[i].max && yOffset >= articleStates[i].min) { articles[i].style["margin-top"] = -(yOffset-(articleStates[i].min)) + "px"; articles[i].style["z-index"] = "2"; } else { articles[i].style["margin-top"] = "0px"; articles[i].style["z-index"] = "1"; } } }; articles[0].style["z-index"] = "2"; // Set each of the articles according to the aspect ratio for (i = 0, len = articles.length; i < len; i++) { article = articles[i]; height = viewportWidth * aspectRatio; article.style.height = height + "px"; articleStates.push({min: bodyHeight, max: bodyHeight+height}); bodyHeight += height; } document.body.style.height = bodyHeight + "px"; }; Peeler.prototype.peel = function() { }; root.Peeler = Peeler; }).call(this);
(function() { var root = this, Peeler = function() {}, articles = document.querySelectorAll("article"), viewportWidth = root.innerWidth, aspectRatio = 1200/1440, bodyHeight = 0, articleStates = []; Peeler.prototype.bind = function() { var article, i, len, height; root.onscroll = function(event) { var yOffset = window.pageYOffset, i = 0; for (len = articles.length; i < len; i++) { if (yOffset <= articleStates[i].max && yOffset >= articleStates[i].min) { articles[i].style["margin-top"] = -(yOffset-(articleStates[i].min)) + "px"; articles[i].style["z-index"] = "2"; } else { articles[i].style["z-index"] = "1"; } } }; articles[0].style["z-index"] = "2"; // Set each of the articles according to the aspect ratio for (i = 0, len = articles.length; i < len; i++) { article = articles[i]; height = viewportWidth * aspectRatio; article.style.height = height + "px"; articleStates.push({min: bodyHeight, max: bodyHeight+height}); bodyHeight += height; } document.body.style.height = bodyHeight + "px"; }; Peeler.prototype.peel = function() { }; root.Peeler = Peeler; }).call(this);