text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix import in tests build
import * as dateCompare from "../../date/compare"; import * as dateFormat from "../../date/format"; import * as domAttr from "../../dom/attr"; import * as domCSS from "../../dom/css"; import * as domEvents from "../../dom/events"; import * as domManipulate from "../../dom/manipulate"; import * as domTraverse from "../../dom/traverse"; import * as domUtils from "../../dom/utils"; import * as ioFile from "../../io/file"; import * as timing from "../../timing/timing"; import UrlSlug from "../../url/Slug"; window.mojave = { timing: timing, date: { compare: dateCompare, format: dateFormat, }, dom: { attr: domAttr, css: domCSS, events: domEvents, manipulate: domManipulate, traverse: domTraverse, utils: domUtils, }, io: { file: ioFile, }, url: { Slug: UrlSlug, }, };
import * as dateCompare from "../../date/compare"; import * as dateFormat from "../../date/format"; import * as domClasses from "../../dom/classes"; import * as domCSS from "../../dom/css"; import * as domEvents from "../../dom/events"; import * as domManipulate from "../../dom/manipulate"; import * as domTraverse from "../../dom/traverse"; import * as domUtils from "../../dom/utils"; import * as ioFile from "../../io/file"; import * as timing from "../../timing/timing"; import UrlSlug from "../../url/Slug"; window.mojave = { timing: timing, date: { compare: dateCompare, format: dateFormat, }, dom: { classes: domClasses, css: domCSS, events: domEvents, manipulate: domManipulate, traverse: domTraverse, utils: domUtils, }, io: { file: ioFile, }, url: { Slug: UrlSlug, }, };
Remove whitespace from name when checking for bye
from django.core.exceptions import ValidationError from django.template.defaultfilters import slugify import re NAME_REGULAR_EXPRESSION = re.compile(r'^[a-zA-Z0-9]+[\w\-\.: ]*$') def greater_than_zero(value): """Checks if value is greater than zero""" if value <= 0: raise ValidationError("Value must be greater than zero.") def non_negative(value): """Checks if value is greater than or equal to zero""" if value < 0: raise ValidationError("Value must be greater than or equal to zero.") def validate_name(value): """Ensures that a string matches a regular expression and that the slugified version of a string is not the empty string""" if value.lower().strip() == "bye": msg = "Name cannot be 'Bye'" raise ValidationError(msg) if NAME_REGULAR_EXPRESSION.match(value) is None: msg = "Team name doesn't start with an alphanumeric or contains " \ "invalid characters." raise ValidationError(msg) if slugify(value) == "": msg = "Name must contain some letters or numbers." raise ValidationError(msg)
from django.core.exceptions import ValidationError from django.template.defaultfilters import slugify import re NAME_REGULAR_EXPRESSION = re.compile(r'^[a-zA-Z0-9]+[\w\-\.: ]*$') def greater_than_zero(value): """Checks if value is greater than zero""" if value <= 0: raise ValidationError("Value must be greater than zero.") def non_negative(value): """Checks if value is greater than or equal to zero""" if value < 0: raise ValidationError("Value must be greater than or equal to zero.") def validate_name(value): """Ensures that a string matches a regular expression and that the slugified version of a string is not the empty string""" if value.lower() == "bye": msg = "Name cannot be 'Bye'" raise ValidationError(msg) if NAME_REGULAR_EXPRESSION.match(value) is None: msg = "Team name doesn't start with an alphanumeric or contains " \ "invalid characters." raise ValidationError(msg) if slugify(value) == "": msg = "Name must contain some letters or numbers." raise ValidationError(msg)
Change the unit of timeout
// straw-ios-service-http.js // This library depends on es6 Promise. /** * @class * @singleton */ straw.service.http = (function (straw) { 'use strict'; var exports = {}; var core = straw.core; var Promise = window.Promise; /** * @method * Perform `GET` method. * * @param {String} url The url to get. * @param {Object} opts The options. "timeout": timeout period in milliseconds, "charset": character sets, for example "utf8", "shift_jis" or "euc-jp". * @return {Promise} The promise object. */ exports.get = function (url, opts) { var promise = new Promise(function (resolve, reject) { core.serviceCall('http', 'get', {url: url, timeout: opts.timeout / 1000, charset: opts.charset}, resolve, reject); }); return promise; }; /** * @method * Perform `GET` method. * * @param {String} url */ exports.post = function (url, data, opts) { throw Error('Sorry, not implemented yet'); }; return exports; }(window.straw));
// straw-ios-service-http.js // This library depends on es6 Promise. /** * @class * @singleton */ straw.service.http = (function (straw) { 'use strict'; var exports = {}; var core = straw.core; var Promise = window.Promise; /** * @method * Perform `GET` method. * * @param {String} url The url to get. * @param {Object} opts The options. "timeout": timeout period in milliseconds, "charset": character sets, for example "utf8", "shift_jis" or "euc-jp". * @return {Promise} The promise object. */ exports.get = function (url, opts) { var promise = new Promise(function (resolve, reject) { core.serviceCall('http', 'get', {url: url, timeout: opts.timeout, charset: opts.charset}, resolve, reject); }); return promise; }; /** * @method * Perform `GET` method. * * @param {String} url */ exports.post = function (url, data, opts) { throw Error('Sorry, not implemented yet'); }; return exports; }(window.straw));
Add annoy dependency for Trimap
from setuptools import setup, find_packages setup(name='rnaseq-lib', version='1.0a27', description='Library of convenience functions related to current research', url='http://github.com/jvivian/rnaseq-lib', author='John Vivian', author_email='jtvivian@gmail.com', license='MIT', package_dir={'': 'src'}, packages=find_packages('src'), package_data={'rnaseq_lib': ['data/*']}, install_requires=['pandas', 'numpy', 'seaborn', 'holoviews', 'scipy'], extras_require={ 'web': [ 'requests', 'mygene', 'bs4', 'biopython', 'synpaseclient', 'xmltodict'], 'trimap': ['annoy']} )
from setuptools import setup, find_packages setup(name='rnaseq-lib', version='1.0a27', description='Library of convenience functions related to current research', url='http://github.com/jvivian/rnaseq-lib', author='John Vivian', author_email='jtvivian@gmail.com', license='MIT', package_dir={'': 'src'}, packages=find_packages('src'), package_data={'rnaseq_lib': ['data/*']}, install_requires=['pandas', 'numpy', 'seaborn', 'holoviews', 'scipy'], extras_require={ 'web': [ 'requests', 'mygene', 'bs4', 'biopython', 'synpaseclient', 'xmltodict']} )
Add actions argument to say function
'use strict'; const Bot = require('./bot'); class SmoochApiBot extends Bot { constructor(options) { super(options); this.name = options.name; this.avatarUrl = options.avatarUrl; } say(text, actions) { const api = this.store.getApi(); let message = Object.assign({ text, actions: actions, role: 'appMaker' }, { name: this.name, avatarUrl: this.avatarUrl }); return api.conversations.sendMessage(this.userId, message); } } module.exports = SmoochApiBot;
'use strict'; const Bot = require('./bot'); class SmoochApiBot extends Bot { constructor(options) { super(options); this.name = options.name; this.avatarUrl = options.avatarUrl; } say(text) { const api = this.store.getApi(); let message = Object.assign({ text, role: 'appMaker' }, { name: this.name, avatarUrl: this.avatarUrl }); return api.conversations.sendMessage(this.userId, message); } } module.exports = SmoochApiBot;
Change the name of the format function in the source class
<?php /* * This file is part of the DataGridBundle. * * (c) Stanislav Turza <sorien@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sorien\DataGridBundle\Grid\Mapping; /** * @Annotation */ class Source { private $columns; private $filterable; public function __construct($metadata = array()) { $this->columns = isset($metadata['columns']) ? array_map(array($this, 'formatColumnName'), explode(',', $metadata['columns'])) : array(); $this->filterable = !(isset($metadata['filterable']) && $metadata['filterable']); } private function formatColumnName($columnName) { $columnName = str_replace('.','__', $columnName); return trim($columnName); } public function getColumns() { return $this->columns; } public function hasColumns() { return !empty($this->columns); } public function isFilterable() { return $this->filterable; } }
<?php /* * This file is part of the DataGridBundle. * * (c) Stanislav Turza <sorien@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sorien\DataGridBundle\Grid\Mapping; /** * @Annotation */ class Source { private $columns; private $filterable; public function __construct($metadata = array()) { $this->columns = isset($metadata['columns']) ? array_map(array($this, 'format'), explode(',', $metadata['columns'])) : array(); $this->filterable = !(isset($metadata['filterable']) && $metadata['filterable']); } private function format($columName) { $columName = str_replace('.','__', $columName); return trim($columName); } public function getColumns() { return $this->columns; } public function hasColumns() { return !empty($this->columns); } public function isFilterable() { return $this->filterable; } }
[kucoin] Allow to specify (optional) timespan on trade history params.
package org.knowm.xchange.kucoin.service; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair; import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging; import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan; import java.util.Date; public class KucoinTradeHistoryParams implements TradeHistoryParamCurrencyPair, TradeHistoryParamPaging, TradeHistoryParamsTimeSpan { private CurrencyPair currencyPair; private Integer pageLength; private Integer pageNumber; private Date startTime; private Date endTime; @Override public Integer getPageLength() { return pageLength; } @Override public void setPageLength(Integer pageLength) { this.pageLength = pageLength; } @Override public Integer getPageNumber() { return pageNumber; } @Override public void setPageNumber(Integer pageNumber) { this.pageNumber = pageNumber; } @Override public CurrencyPair getCurrencyPair() { return currencyPair; } @Override public void setCurrencyPair(CurrencyPair pair) { this.currencyPair = pair; } @Override public Date getStartTime() { return startTime; } @Override public void setStartTime(Date startTime) { this.startTime = startTime; } @Override public Date getEndTime() { return endTime; } @Override public void setEndTime(Date endTime) { this.endTime = endTime; } }
package org.knowm.xchange.kucoin.service; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair; import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging; public class KucoinTradeHistoryParams implements TradeHistoryParamCurrencyPair, TradeHistoryParamPaging { private CurrencyPair currencyPair; private Integer pageLength; private Integer pageNumber; @Override public Integer getPageLength() { return pageLength; } @Override public void setPageLength(Integer pageLength) { this.pageLength = pageLength; } @Override public Integer getPageNumber() { return pageNumber; } @Override public void setPageNumber(Integer pageNumber) { this.pageNumber = pageNumber; } @Override public CurrencyPair getCurrencyPair() { return currencyPair; } @Override public void setCurrencyPair(CurrencyPair pair) { this.currencyPair = pair; } }
Add back correct lost file
package seedu.taskman.storage; import seedu.taskman.commons.exceptions.IllegalValueException; import seedu.taskman.model.tag.Tag; import javax.xml.bind.annotation.XmlValue; /** * JAXB-friendly adapted version of the Tag. */ public class XmlAdaptedTag { @XmlValue public String tagName; /** * No-arg constructor for JAXB use. */ public XmlAdaptedTag() { } /** * Converts a given Tag into this class for JAXB use. * * @param source future changes to this will not affect the created */ public XmlAdaptedTag(Tag source) { tagName = source.tagName; } /** * Converts this jaxb-friendly adapted tag object into the model's Tag object. * * @throws IllegalValueException if there were any data constraints violated in the adapted task */ public Tag toModelType() throws IllegalValueException { return new Tag(tagName); } }
package seedu.taskman.storage; import seedu.taskman.commons.exceptions.IllegalValueException; import seedu.taskman.model.tag.Tag; import javax.xml.bind.annotation.XmlValue; /** * JAXB-friendly adapted version of the Tag. */ public class XmlAdaptedTag { @XmlValue public String tagName; /** * No-arg constructor for JAXB use. */ public XmlAdaptedTag() { } /** * Converts a given Tag into this class for JAXB use. * * @param source future changes to this will not affect the created */ public XmlAdaptedTag(Tag source) { tagName = source.tagName; } /** * Converts this jaxb-friendly adapted tag object into the model's Tag object. * * @throws IllegalValueException if there were any data constraints violated in the adapted task */ public Tag toModelType() throws IllegalValueException { return new Tag(tagName); } }
Read sentry release from service if available
import Ember from 'ember'; import config from '../config/environment'; export function initialize(application) { if (Ember.get(config, 'sentry.development') === true) { return; } if (!config.sentry) { throw new Error('`sentry` should be configured when not in development mode.'); } const { dsn, debug = true, includePaths = [], whitelistUrls = [], serviceName = 'logger', serviceReleaseProperty = 'release' } = config.sentry; const lookupName = `service:${serviceName}`; const service = application.container.lookup(lookupName); try { window.Raven.debug = debug; window.Raven.config(dsn, { includePaths, whitelistUrls, release: service.get(serviceReleaseProperty) || config.APP.version }); } catch (e) { return; } window.Raven.install(); const { globalErrorCatching = true } = config.sentry; if (globalErrorCatching === true) { service.enableGlobalErrorCatching(); } } export default { initialize, name: 'sentry-setup' };
import Ember from 'ember'; import config from '../config/environment'; export function initialize(application) { if (Ember.get(config, 'sentry.development') === true) { return; } if (!config.sentry) { throw new Error('`sentry` should be configured when not in development mode.'); } const { dsn, debug = true, includePaths = [], whitelistUrls = [] } = config.sentry; try { window.Raven.debug = debug; window.Raven.config(dsn, { includePaths, whitelistUrls, release: config.APP.version }); } catch (e) { return; } window.Raven.install(); const { globalErrorCatching = true } = config.sentry; if (globalErrorCatching === true) { const { serviceName = 'logger' } = config.sentry; const lookupName = `service:${serviceName}`; application.container.lookup(lookupName).enableGlobalErrorCatching(); } } export default { initialize, name: 'sentry-setup' };
Add basic documentation to ModelReport
from copy import deepcopy class ModelReport(object): """ An abstraction of a model report that wraps access to various sections of the report. """ """ :param raw_report: the dict representation of model report JSON :type: dict """ def __init__(self, raw_report): self._raw_report = raw_report @property def model_name(self): """ :rtype: str """ return self._raw_report['model_name'] @property def performance(self): """ :rtype: dict """ return self._raw_report['error_metrics'] @property def feature_importances(self): """ :rtype: list of dict """ return self._raw_report['feature_importances'] @property def model_settings(self): """ :rtype: dict """ return self._raw_report['model_settings'] """ WARNING - the dict format returned is unstable and may change over time. :return: a copy of the raw report that backs the instance. :rtype: dict """ def to_json(self): return deepcopy(self._raw_report)
from copy import deepcopy class ModelReport(object): """ An abstraction of a model report that wraps access to various sections of the report. """ """ :param raw_report: the dict representation of model report JSON :type: dict """ def __init__(self, raw_report): self._raw_report = raw_report @property def model_name(self): return self._raw_report['model_name'] @property def performance(self): return self._raw_report['error_metrics'] @property def feature_importances(self): return self._raw_report['feature_importances'] @property def model_settings(self): return self._raw_report['model_settings'] """ WARNING - the dict format returned is unstable and may change over time. :return: a copy of the raw report that backs the instance. :rtype: dict """ def to_json(self): return deepcopy(self._raw_report)
Fix for tags not being cleaned up
define([ 'goo/fsmpack/statemachine/actions/Action', 'goo/entities/components/ProximityComponent' ], /** @lends */ function( Action, ProximityComponent ) { 'use strict'; function TagAction(/*id, settings*/) { Action.apply(this, arguments); } TagAction.prototype = Object.create(Action.prototype); TagAction.prototype.constructor = TagAction; TagAction.external = { name: 'Tag', type: 'collision', description: 'Sets a tag on the entity. Use tags to be able to capture collision events with the \'Collides\' action', parameters: [{ name: 'Tag', key: 'tag', type: 'dropdown', description: 'Checks for collisions with other ojects having this tag', 'default': 'red', options: ['red', 'blue', 'green', 'yellow'] }], transitions: [] }; TagAction.prototype._run = function (fsm) { var entity = fsm.getOwnerEntity(); if (entity.proximityComponent) { if (entity.proximityComponent.tag !== this.tag) { entity.clearComponent('ProximityComponent'); entity.setComponent(new ProximityComponent(this.tag)); } } else { entity.setComponent(new ProximityComponent(this.tag)); } }; TagAction.prototype.cleanup = function (fsm) { var entity = fsm.getOwnerEntity(); entity.clearComponent('ProximityComponent'); }; return TagAction; });
define([ 'goo/fsmpack/statemachine/actions/Action', 'goo/entities/components/ProximityComponent' ], /** @lends */ function( Action, ProximityComponent ) { 'use strict'; function TagAction(/*id, settings*/) { Action.apply(this, arguments); } TagAction.prototype = Object.create(Action.prototype); TagAction.prototype.constructor = TagAction; TagAction.external = { name: 'Tag', type: 'collision', description: 'Sets a tag on the entity. Use tags to be able to capture collision events with the \'Collides\' action', parameters: [{ name: 'Tag', key: 'tag', type: 'dropdown', description: 'Checks for collisions with other ojects having this tag', 'default': 'red', options: ['red', 'blue', 'green', 'yellow'] }], transitions: [] }; TagAction.prototype._run = function (fsm) { var entity = fsm.getOwnerEntity(); if (entity.proximityComponent) { if (entity.proximityComponent.tag !== this.tag) { entity.clearComponent('ProximityComponent'); entity.setComponent(new ProximityComponent(this.tag)); } } else { entity.setComponent(new ProximityComponent(this.tag)); } }; return TagAction; });
Fix templates building on OS X
#!/usr/bin/env python3 try: from setuptools import setup except ImportError: from distutils.core import setup from sys import platform import subprocess import glob import os ver = os.environ.get("PKGVER") or subprocess.run(['git', 'describe', '--tags'], stdout=subprocess.PIPE).stdout.decode().strip() setup( name = 'knightos', packages = ['knightos', 'knightos.commands'], version = ver, description = 'KnightOS SDK', author = 'Drew DeVault', author_email = 'sir@cmpwn.com', url = 'https://github.com/KnightOS/sdk', install_requires = ['requests', 'pyyaml', 'pystache', 'docopt'], license = 'AGPL-3.0', scripts=['bin/knightos'], include_package_data=True, package_data={ 'knightos': [ 'knightos/templates/\'*\'', 'knightos/templates/c/\'*\'', 'knightos/templates/assembly/\'*\'', ] }, )
#!/usr/bin/env python3 try: from setuptools import setup except ImportError: from distutils.core import setup from sys import platform import subprocess import glob import os ver = os.environ.get("PKGVER") or subprocess.run(['git', 'describe', '--tags'], stdout=subprocess.PIPE).stdout.decode().strip() setup( name = 'knightos', packages = ['knightos', 'knightos.commands'], version = ver, description = 'KnightOS SDK', author = 'Drew DeVault', author_email = 'sir@cmpwn.com', url = 'https://github.com/KnightOS/sdk', install_requires = ['requests', 'pyyaml', 'pystache', 'docopt'], license = 'AGPL-3.0', scripts=['bin/knightos'], package_data={ 'knightos': [ 'templates/\'*\'', 'templates/c/\'*\'', 'templates/assembly/\'*\'', ] }, )
Create log dir if it doesn't exist
<?php namespace Sleeti\Logging; class Logger { protected $container; protected $handler; protected $loggers; public function __construct($container) { $this->container = $container; if (!is_dir($this->container['settings']['logging']['path']) && $this->container['settings']['logging']['enabled']) { mkdir($this->container['settings']['logging']['path']); } $logfile = $this->container['settings']['logging']['path'] . 'sleeti.log'; $this->handler = new \Monolog\Handler\RotatingFileHandler($logfile, $container['settings']['logging']['maxFiles'] ?? 0); $dateFormat = 'H:i:s'; $outputFormat = "[%datetime%] [%level_name%] %channel%: %message% %context%\n"; $formatter = new \Monolog\Formatter\LineFormatter($outputFormat, $dateFormat); $this->handler->setFormatter($formatter); } private function addLogger($name) { $logger = new \Monolog\Logger($name); $logger->pushHandler($this->handler, $this->container['settings']['logging']['level'] ?? \Monolog\Logger::INFO); $this->loggers[$name] = $logger; } public function log($name, $level, $message, array $context = []) { if (!$this->container['settings']['logging']['enabled']) return; if (!isset($loggers[$name])) { $this->addLogger($name); } $this->loggers[$name]->log($level, $message, $context); } }
<?php namespace Sleeti\Logging; class Logger { protected $container; protected $handler; protected $loggers; public function __construct($container) { $this->container = $container; $logfile = $this->container['settings']['logging']['path'] . 'sleeti.log'; $this->handler = new \Monolog\Handler\RotatingFileHandler($logfile, $container['settings']['logging']['maxFiles'] ?? 0); $dateFormat = 'H:i:s'; $outputFormat = "[%datetime%] [%level_name%] %channel%: %message% %context%\n"; $formatter = new \Monolog\Formatter\LineFormatter($outputFormat, $dateFormat); $this->handler->setFormatter($formatter); } private function addLogger($name) { $logger = new \Monolog\Logger($name); $logger->pushHandler($this->handler, $this->container['settings']['logging']['level'] ?? \Monolog\Logger::INFO); $this->loggers[$name] = $logger; } public function log($name, $level, $message, array $context = []) { if (!$this->container['settings']['logging']['enabled']) return; if (!isset($loggers[$name])) { $this->addLogger($name); } $this->loggers[$name]->log($level, $message, $context); } }
Allow to call wordpress functions using WP helper
<?php namespace Ampersand; use Ampersand\Config; use Ampersand\Http\Session; use Ampersand\Helpers\URL; use Ampersand\Helpers\WP; class Render { private static $twig; public static function getTwig() { if(!self::$twig){ \Twig_Autoloader::register(); $cache = Config::get('cache') ? Config::get('cache').'/' : false; $loader = new \Twig_Loader_Filesystem(Config::get('views').'/'); $twig = new \Twig_Environment($loader, array( 'cache' => $cache, 'debug' => Config::get('debug') )); // Add globals $twig->addGlobal('session', Session::getInstance()); $twig->addGlobal('url', new URL()); $twig->addGlobal('wp', new WP()); self::$twig = $twig; } return self::$twig; } public static function view($template, $data = []) { return self::getTwig()->render(str_replace('.', '/', $template).'.html', $data); } public static function template($template, $data = []) { foreach($data as $key => $value) ${$key} = $value; ob_start(); include(locate_template($template.'.php')); return ob_get_clean(); } }
<?php namespace Ampersand; use Ampersand\Config; use Ampersand\Http\Session; use Ampersand\Helpers\URL; class Render { private static $twig; public static function getTwig() { if(!self::$twig){ \Twig_Autoloader::register(); $cache = Config::get('cache') ? Config::get('cache').'/' : false; $loader = new \Twig_Loader_Filesystem(Config::get('views').'/'); $twig = new \Twig_Environment($loader, array( 'cache' => $cache, 'debug' => Config::get('debug') )); // Add globals $twig->addGlobal('session', Session::getInstance()); $twig->addGlobal('url', new URL()); self::$twig = $twig; } return self::$twig; } public static function view($template, $data = []) { return self::getTwig()->render(str_replace('.', '/', $template).'.html', $data); } public static function template($template, $data = []) { foreach($data as $key => $value) ${$key} = $value; ob_start(); include(locate_template($template.'.php')); return ob_get_clean(); } }
Fix a breaking change due to the angular dependency update
import angular from 'angular' import 'angular-aria' import 'angular-i18n/nl-nl' import 'angular-sanitize' const moduleDependencies = [ // Main modules 'dpDetail', 'dpDataSelection', // Shared module 'dpShared', 'ngAria', ] // eslint-disable-next-line angular/di angular.module('atlas', moduleDependencies).config(['$provide', urlChangeProvider]) // Allow https://github.com/angular/angular.js/blob/master/CHANGELOG.md#breaking-changes angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement() urlChangeProvider.$inject = ['$provide'] /* istanbul ignore next */ function urlChangeProvider($provide) { $provide.decorator('$browser', [ '$delegate', function ($delegate) { $delegate.onUrlChange = function () {} $delegate.url = function () { return '' } return $delegate }, ]) }
import angular from 'angular' import 'angular-aria' import 'angular-i18n/nl-nl' import 'angular-sanitize' const moduleDependencies = [ // Main modules 'dpDetail', 'dpDataSelection', // Shared module 'dpShared', 'ngAria', ] // eslint-disable-next-line angular/di angular.module('atlas', moduleDependencies).config(['$provide', urlChangeProvider]) urlChangeProvider.$inject = ['$provide'] /* istanbul ignore next */ function urlChangeProvider($provide) { $provide.decorator('$browser', [ '$delegate', function ($delegate) { $delegate.onUrlChange = function () {} $delegate.url = function () { return '' } return $delegate }, ]) }
Modify parsing logic for last_modified in JSON
# Stdlib imports from datetime import datetime from pytz import timezone # Core Django imports from django.utils.timezone import utc # Imports from app from sync_center.models import Map, KML def get_update_id_list(model_name, req_data): db_data = None if model_name == 'map': db_data = Map.objects.all() elif model_name == 'kml': db_data = KML.objects.all() id_list = [] for data in db_data: id_str = str(data.id) if id_str not in req_data.keys(): id_list.append(data.id) else: req_last_modified = datetime.strptime(req_data[id_str]['last_modified'], '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo = utc) if data.last_modified > req_last_modified: id_list.append(data.id) return id_list
# Stdlib imports from datetime import datetime from pytz import timezone # Core Django imports from django.utils.timezone import utc # Imports from app from sync_center.models import Map, KML def get_update_id_list(model_name, req_data): db_data = None if model_name == 'map': db_data = Map.objects.all() elif model_name == 'kml': db_data = KML.objects.all() id_list = [] for data in db_data: id_str = str(data.id) if id_str not in req_data.keys(): id_list.append(data.id) else: req_last_modified = datetime.strptime(req_data[id_str]['last_modified'], '%Y-%m-%d %H:%M:%S').replace(tzinfo = utc) if data.last_modified > req_last_modified: id_list.append(data.id) return id_list
Remove sentinel from config. Travis won't pass if a sentinel is set
//Copyright 2012 Telefonica Investigación y Desarrollo, S.A.U // //This file is part of RUSH. // // RUSH is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // RUSH is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License along with RUSH // . If not, seehttp://www.gnu.org/licenses/. // //For those usages not covered by the GNU Affero General Public License please contact with::dtc_support@tid.es module.exports = require('./configBase.js'); //0..15 for 0 ->pre-production 1->test module.exports.selectedDB = 1; //Include evMonitor module.exports.consumer.evModules.push( { module: './evMonitor' } ); //Reduce bucket timers module.exports.retryBuckets = [5, 10, 15]; module.exports.probeInterval = 5 * 1000; //module.exports.sentinels = [{host:'localhost', port:26379}];
//Copyright 2012 Telefonica Investigación y Desarrollo, S.A.U // //This file is part of RUSH. // // RUSH is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // RUSH is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License along with RUSH // . If not, seehttp://www.gnu.org/licenses/. // //For those usages not covered by the GNU Affero General Public License please contact with::dtc_support@tid.es module.exports = require('./configBase.js'); //0..15 for 0 ->pre-production 1->test module.exports.selectedDB = 1; //Include evMonitor module.exports.consumer.evModules.push( { module: './evMonitor' } ); //Reduce bucket timers module.exports.retryBuckets = [5, 10, 15]; module.exports.probeInterval = 5 * 1000; module.exports.sentinels = [{host:'localhost', port:26379}];
Fix deprecation warning: DATABASE_* -> DATABASES
from os.path import dirname, join TEST_ROOT = dirname(__file__) INSTALLED_APPS = ('adminfiles', 'tests', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.auth', 'django.contrib.sessions', 'sorl.thumbnail') DATABASES = { "default": { "ENGINE": 'django.db.backends.sqlite3', } } SITE_ID = 1 MEDIA_URL = '/media/' MEDIA_ROOT = join(TEST_ROOT, 'media') STATIC_URL = '/static/' STATIC_ROOT = MEDIA_ROOT ROOT_URLCONF = 'tests.urls' TEMPLATE_DIRS = (join(TEST_ROOT, 'templates'),)
from os.path import dirname, join TEST_ROOT = dirname(__file__) INSTALLED_APPS = ('adminfiles', 'tests', 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.auth', 'django.contrib.sessions', 'sorl.thumbnail') DATABASE_ENGINE = 'sqlite3' SITE_ID = 1 MEDIA_URL = '/media/' MEDIA_ROOT = join(TEST_ROOT, 'media') STATIC_URL = '/static/' STATIC_ROOT = MEDIA_ROOT ROOT_URLCONF = 'tests.urls' TEMPLATE_DIRS = (join(TEST_ROOT, 'templates'),)
Fix functional test for policy type listing This patch fixes the funtional test for policy type listing. We have changed the names of builtin policy types. Change-Id: I9f04ab2a4245e8946db3a0255658676cc5f600ab
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from senlin.tests.functional import api as test_api from senlin.tests.functional import base class TestPolicyType(base.SenlinFunctionalTest): def test_get_policy_types(self): # Check that listing policy types works. policy_types = test_api.list_policy_types(self.client) policy_names = [p['name'] for p in policy_types] self.assertIn('senlin.policy.deletion', policy_names) self.assertIn('senlin.policy.scaling', policy_names)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from senlin.tests.functional import api as test_api from senlin.tests.functional import base class TestPolicyType(base.SenlinFunctionalTest): def test_get_policy_types(self): # Check that listing policy types works. policy_types = test_api.list_policy_types(self.client) policy_names = [p['name'] for p in policy_types] self.assertIn('DeletionPolicy', policy_names) self.assertIn('ScalingInPolicy', policy_names)
fix(this._super): Add this._super calls to avoid weird JS breaking behaviour
(function($){ $.entwine('userswitcher', function($){ $('form.userswitcher select').entwine({ onchange : function(){ this.parents('form:first').submit(); this._super(); } }); $('form.userswitcher .Actions').entwine({ onmatch : function(){ this.hide(); this._super(); } }); $('body').entwine({ onmatch : function(){ var base = $('base').prop('href'), isCMS = this.hasClass('cms') ? 1 : ''; $.get(base + 'userswitcher/UserSwitcherFormHTML/', {userswitchercms: isCMS}).done(function(data){ var body = $('body'); if(body.hasClass('cms')){ $('.cms-login-status').append(data); }else{ $('body').append(data); } }); this._super(); } }); }); })(jQuery);
(function($){ $.entwine('userswitcher', function($){ $('form.userswitcher select').entwine({ onchange : function(){ this.parents('form:first').submit(); } }); $('form.userswitcher .Actions').entwine({ onmatch : function(){ this.hide(); } }); $('body').entwine({ onmatch : function(){ var base = $('base').prop('href'), isCMS = this.hasClass('cms') ? 1 : ''; $.get(base + 'userswitcher/UserSwitcherFormHTML/', {userswitchercms: isCMS}).done(function(data){ var body = $('body'); if(body.hasClass('cms')){ $('.cms-login-status').append(data); }else{ $('body').append(data); } }); } }); }); })(jQuery);
Add an interface to change table_name
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from ..interface import TableLoaderInterface class TableLoaderManager(TableLoaderInterface): def __init__(self, loader): self.__loader = loader @property def loader(self): return self.__loader @property def format_name(self): return self.__loader.format_name @property def source_type(self): return self.__loader.source_type @property def table_name(self): return self.__loader.table_name @table_name.setter def table_name(self, value): self.__loader.table_name = value @property def encoding(self): try: return self.__loader.encoding except AttributeError: return None @encoding.setter def encoding(self, codec_name): self.__loader.encoding = codec_name def load(self): return self.__loader.load() def inc_table_count(self): self.__loader.inc_table_count()
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from ..interface import TableLoaderInterface class TableLoaderManager(TableLoaderInterface): def __init__(self, loader): self.__loader = loader @property def loader(self): return self.__loader @property def format_name(self): return self.__loader.format_name @property def source_type(self): return self.__loader.source_type @property def encoding(self): try: return self.__loader.encoding except AttributeError: return None @encoding.setter def encoding(self, codec_name): self.__loader.encoding = codec_name def load(self): return self.__loader.load() def inc_table_count(self): self.__loader.inc_table_count()
Improve JVM launch time message
/* * Copyright (c) 2015-2019 Dzikoysk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.panda_lang.panda.framework; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.ManagementFactory; public class PandaFrameworkLogger { protected static Logger PANDA_FRAMEWORK_LOGGER = LoggerFactory.getLogger("Panda Framework"); public static void setLogger(Logger logger) { PANDA_FRAMEWORK_LOGGER = logger; } public static void printJVMUptime() { PANDA_FRAMEWORK_LOGGER.debug(""); PANDA_FRAMEWORK_LOGGER.debug("JVM launch time: " + (System.currentTimeMillis() - ManagementFactory.getRuntimeMXBean().getStartTime()) + "ms (。•́︿•̀。)"); PANDA_FRAMEWORK_LOGGER.debug(""); } }
/* * Copyright (c) 2015-2019 Dzikoysk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.panda_lang.panda.framework; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.management.ManagementFactory; public class PandaFrameworkLogger { protected static Logger PANDA_FRAMEWORK_LOGGER = LoggerFactory.getLogger("Panda Framework"); public static void setLogger(Logger logger) { PANDA_FRAMEWORK_LOGGER = logger; } public static void printJVMUptime() { PANDA_FRAMEWORK_LOGGER.debug("JVM launch time: " + (System.currentTimeMillis() - ManagementFactory.getRuntimeMXBean().getStartTime()) + "ms"); } }
Use the render shortcut which defaults to RequestContext and allows passing a status code
from django.contrib.auth.decorators import login_required from django.shortcuts import render __author__ = 'Quantum' def generic_message(request, title, message, status=None): return render(request, 'generic_message.jade', { 'message': message, 'title': title }, status=status) class TitleMixin(object): title = '(untitled)' def get_context_data(self, **kwargs): context = super(TitleMixin, self).get_context_data(**kwargs) context['title'] = self.get_title() return context def get_title(self): return self.title class LoginRequiredMixin(object): @classmethod def as_view(cls, **initkwargs): view = super(LoginRequiredMixin, cls).as_view(**initkwargs) return login_required(view)
from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from django.template import RequestContext __author__ = 'Quantum' def generic_message(request, title, message): return render_to_response('generic_message.jade', { 'message': message, 'title': title }, context_instance=RequestContext(request)) class TitleMixin(object): title = '(untitled)' def get_context_data(self, **kwargs): context = super(TitleMixin, self).get_context_data(**kwargs) context['title'] = self.get_title() return context def get_title(self): return self.title class LoginRequiredMixin(object): @classmethod def as_view(cls, **initkwargs): view = super(LoginRequiredMixin, cls).as_view(**initkwargs) return login_required(view)
[API][Product] Remove custom latest products endpoint
<?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\Component\Core\Repository; use Doctrine\ORM\QueryBuilder; use Sylius\Component\Core\Model\ChannelInterface; use Sylius\Component\Core\Model\ProductInterface; use Sylius\Component\Core\Model\TaxonInterface; use Sylius\Component\Product\Repository\ProductRepositoryInterface as BaseProductRepositoryInterface; interface ProductRepositoryInterface extends BaseProductRepositoryInterface { /** * @param mixed|null $taxonId */ public function createListQueryBuilder(string $locale, $taxonId = null): QueryBuilder; public function createShopListQueryBuilder( ChannelInterface $channel, TaxonInterface $taxon, string $locale, array $sorting = [], bool $includeAllDescendants = false ): QueryBuilder; public function createListQueryBuilderByChannelAndLocaleCode(ChannelInterface $channel, string $localeCode): QueryBuilder; /** * @return array|ProductInterface[] */ public function findLatestByChannel(ChannelInterface $channel, string $locale, int $count): array; public function findOneByChannelAndSlug(ChannelInterface $channel, string $locale, string $slug): ?ProductInterface; public function findOneByCode(string $code): ?ProductInterface; }
<?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\Component\Core\Repository; use Doctrine\ORM\QueryBuilder; use Sylius\Component\Core\Model\ChannelInterface; use Sylius\Component\Core\Model\ProductInterface; use Sylius\Component\Core\Model\TaxonInterface; use Sylius\Component\Product\Repository\ProductRepositoryInterface as BaseProductRepositoryInterface; interface ProductRepositoryInterface extends BaseProductRepositoryInterface { /** * @param mixed|null $taxonId */ public function createListQueryBuilder(string $locale, $taxonId = null): QueryBuilder; public function createShopListQueryBuilder( ChannelInterface $channel, TaxonInterface $taxon, string $locale, array $sorting = [], bool $includeAllDescendants = false ): QueryBuilder; /** * @return array|ProductInterface[] */ public function findLatestByChannel(ChannelInterface $channel, string $locale, int $count): array; public function findOneByChannelAndSlug(ChannelInterface $channel, string $locale, string $slug): ?ProductInterface; public function findOneByCode(string $code): ?ProductInterface; }
Use the user-set language in twig filter
<?php namespace Grav\Plugin; use \Grav\Common\Grav; class AdminTwigExtension extends \Twig_Extension { protected $grav; public function __construct() { $this->grav = Grav::instance(); $this->lang = $this->grav['user']->language; } /** * Returns extension name. * * @return string */ public function getName() { return 'AdminTwigExtension'; } public function getFilters() { return [ new \Twig_SimpleFilter('tu', [$this, 'tuFilter']), ]; } public function tuFilter() { return $this->grav['language']->translate(func_get_args(), [$this->grav['user']->authenticated ? $this->lang : 'en']); } }
<?php namespace Grav\Plugin; use \Grav\Common\Grav; class AdminTwigExtension extends \Twig_Extension { protected $grav; public function __construct() { $this->grav = Grav::instance(); } /** * Returns extension name. * * @return string */ public function getName() { return 'AdminTwigExtension'; } public function getFilters() { return [ new \Twig_SimpleFilter('tu', [$this, 'tuFilter']), ]; } public function tuFilter() { return $this->grav['language']->translate(func_get_args()); } }
Use non-circle social icons in footer
import quotes from '../util/quotes.js'; export default { isLoggedIn: false, showMenu: false, circleIcons: false, toast: null, quote: { text: null, author: null, current: Math.floor(Math.random() * quotes.length), }, files: { cwd: '', content: [], focused: null, preview: null, uploading: false, }, links: { content: null, loading: false, }, notes: { content: null, loading: false, }, media: { movie: null, tv: null, watchlist: null, search: [], existing: [], item: null, }, pagination: { enabled: false, current: 1, total: 1, }, };
import quotes from '../util/quotes.js'; export default { isLoggedIn: false, showMenu: false, circleIcons: true, toast: null, quote: { text: null, author: null, current: Math.floor(Math.random() * quotes.length), }, files: { cwd: '', content: [], focused: null, preview: null, uploading: false, }, links: { content: null, loading: false, }, notes: { content: null, loading: false, }, media: { movie: null, tv: null, watchlist: null, search: [], existing: [], item: null, }, pagination: { enabled: false, current: 1, total: 1, }, };
fix: Make error handling use full parser list There was a bug in the error handling that made the the loop over parser return the error instead of continuing to the next parser.
const parsers = require('../parsers') const transform = require('../transform') const request = require('../request') const { ConnectionFailedError, EmptyParseOutputError } = require('../errors') async function parse(parser, text) { const parsed = await parsers[parser](text) if (!parsed) throw new EmptyParseOutputError() return transform(parsed) } module.exports = async function parseFromQuery({ url, parser }) { let content try { content = (await request(url)).text } catch (error) { if (error.code === 'ENOTFOUND') { throw new ConnectionFailedError(url) } throw error } if (parser) { return parse(parser, content) } else { for (let i = 0; i < parsers.keys.length; i++) { try { return await parse(parsers.keys[i], content) } catch (error) { if (i < parsers.keys.length - 1) { continue } throw error } } } }
const parsers = require('../parsers') const transform = require('../transform') const request = require('../request') const { ConnectionFailedError, EmptyParseOutputError } = require('../errors') async function parse(parser, text) { const parsed = await parsers[parser](text) if (!parsed) throw new EmptyParseOutputError() return transform(parsed) } module.exports = async function parseFromQuery({ url, parser }) { let content try { content = (await request(url)).text } catch (error) { if (error.code === 'ENOTFOUND') { throw new ConnectionFailedError(url) } throw error } if (parser) { return parse(parser, content) } else { for (let i = 0; i < parsers.keys.length; i++) { try { return parse(parsers.keys[i], content) } catch (error) { if (i !== parsers.keys.length - 1) { throw error } continue } } } }
Fix the order payments validation of 0 amount.
<?php namespace WickedReports\Api\Item; use Respect\Validation\Validator as v; class OrderPayment extends BaseItem { /** * @var array */ protected $dates = ['PaymentDate']; /** * @return v */ protected static function validation() { return v::arrayType() ->key('SourceSystem', v::stringType()->notEmpty()->length(0, 255)) ->key('OrderID', v::stringType()->notEmpty()->length(0, 500)) ->key('PaymentDate', v::date('Y-m-d H:i:s')) ->key('Amount', v::numeric()->min(0)) ->key('Status', v::stringType()->length(0, 500)->in(['', 'APPROVED', 'FAILED', 'REFUNDED', 'PARTIALLY REFUNDED'])) ; } }
<?php namespace WickedReports\Api\Item; use Respect\Validation\Validator as v; class OrderPayment extends BaseItem { /** * @var array */ protected $dates = ['PaymentDate']; /** * @return v */ protected static function validation() { return v::arrayType() ->key('SourceSystem', v::stringType()->notEmpty()->length(0, 255)) ->key('OrderID', v::stringType()->notEmpty()->length(0, 500)) ->key('PaymentDate', v::date('Y-m-d H:i:s')) ->key('Amount', v::numeric()->notEmpty()) ->key('Status', v::stringType()->length(0, 500)->in(['', 'APPROVED', 'FAILED', 'REFUNDED', 'PARTIALLY REFUNDED'])) ; } }
Make WordPress link open in new window
<!-- footer --> <footer class="footer" role="contentinfo"> <!-- copyright --> <p class="copyright"> &copy; <?php echo esc_html( date( 'Y' ) ); ?> Copyright <?php bloginfo( 'name' ); ?>. <?php esc_html_e( 'Powered by', 'html5blank' ); ?> <a href="//wordpress.org" target="_blank">WordPress</a> &amp; <a href="//html5blank.com" target="_blank">HTML5 Blank</a>. </p> <!-- /copyright --> </footer> <!-- /footer --> </div> <!-- /wrapper --> <?php wp_footer(); ?> <!-- analytics --> <script> (function(f,i,r,e,s,h,l){i['GoogleAnalyticsObject']=s;f[s]=f[s]||function(){ (f[s].q=f[s].q||[]).push(arguments)},f[s].l=1*new Date();h=i.createElement(r), l=i.getElementsByTagName(r)[0];h.async=1;h.src=e;l.parentNode.insertBefore(h,l) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXX-XX', 'yourdomain.com'); ga('send', 'pageview'); </script> </body> </html>
<!-- footer --> <footer class="footer" role="contentinfo"> <!-- copyright --> <p class="copyright"> &copy; <?php echo esc_html( date( 'Y' ) ); ?> Copyright <?php bloginfo( 'name' ); ?>. <?php esc_html_e( 'Powered by', 'html5blank' ); ?> <a href="//wordpress.org">WordPress</a> &amp; <a href="//html5blank.com" target="_blank">HTML5 Blank</a>. </p> <!-- /copyright --> </footer> <!-- /footer --> </div> <!-- /wrapper --> <?php wp_footer(); ?> <!-- analytics --> <script> (function(f,i,r,e,s,h,l){i['GoogleAnalyticsObject']=s;f[s]=f[s]||function(){ (f[s].q=f[s].q||[]).push(arguments)},f[s].l=1*new Date();h=i.createElement(r), l=i.getElementsByTagName(r)[0];h.async=1;h.src=e;l.parentNode.insertBefore(h,l) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXX-XX', 'yourdomain.com'); ga('send', 'pageview'); </script> </body> </html>
Fix a exception in the case that an Alert first get exposed, an exception is thrown due to the size of the Alert value elements is empty.
package com.linkedin.helix.monitoring.mbeans; import com.linkedin.helix.alerts.AlertValueAndStatus; public class ClusterAlertItem implements ClusterAlertItemMBean { String _alertItemName; double _alertValue; int _alertFired; AlertValueAndStatus _valueAndStatus; public ClusterAlertItem(String name, AlertValueAndStatus valueAndStatus) { _valueAndStatus = valueAndStatus; _alertItemName = name; refreshValues(); } @Override public String getSensorName() { return _alertItemName; } @Override public double getAlertValue() { return _alertValue; } public void setValueMap(AlertValueAndStatus valueAndStatus) { _valueAndStatus = valueAndStatus; refreshValues(); } void refreshValues() { if(_valueAndStatus.getValue().getElements().size() > 0) { _alertValue = Double.parseDouble(_valueAndStatus.getValue().getElements().get(0)); } else { _alertValue = 0; } _alertFired = _valueAndStatus.isFired() ? 1 : 0; } @Override public int getAlertFired() { return _alertFired; } }
package com.linkedin.helix.monitoring.mbeans; import com.linkedin.helix.alerts.AlertValueAndStatus; public class ClusterAlertItem implements ClusterAlertItemMBean { String _alertItemName; double _alertValue; int _alertFired; AlertValueAndStatus _valueAndStatus; public ClusterAlertItem(String name, AlertValueAndStatus valueAndStatus) { _valueAndStatus = valueAndStatus; _alertItemName = name; refreshValues(); } @Override public String getSensorName() { return _alertItemName; } @Override public double getAlertValue() { return _alertValue; } public void setValueMap(AlertValueAndStatus valueAndStatus) { _valueAndStatus = valueAndStatus; refreshValues(); } void refreshValues() { _alertValue = Double.parseDouble(_valueAndStatus.getValue().getElements().get(0)); _alertFired = _valueAndStatus.isFired() ? 1 : 0; } @Override public int getAlertFired() { return _alertFired; } }
Fix issue with null value in tables
<?php namespace Anomaly\RelationshipFieldType; use Anomaly\Streams\Platform\Addon\FieldType\FieldTypeModifier; use Anomaly\Streams\Platform\Model\EloquentModel; /** * Class RelationshipFieldTypeModifier * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> * @package Anomaly\RelationshipFieldType */ class RelationshipFieldTypeModifier extends FieldTypeModifier { /** * The field type instance. * This is for IDE support. * * @var RelationshipFieldType */ protected $fieldType; /** * Modify the value. * * @param $value * @return integer */ public function modify($value) { if ($value instanceof EloquentModel) { return $value->getId(); } return (int)$value; } /** * Restore the value from storage format. * * @param $value * @return mixed */ public function restore($value) { return $value ?: null; } }
<?php namespace Anomaly\RelationshipFieldType; use Anomaly\Streams\Platform\Addon\FieldType\FieldTypeModifier; use Anomaly\Streams\Platform\Model\EloquentModel; /** * Class RelationshipFieldTypeModifier * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> * @package Anomaly\RelationshipFieldType */ class RelationshipFieldTypeModifier extends FieldTypeModifier { /** * The field type instance. * This is for IDE support. * * @var RelationshipFieldType */ protected $fieldType; /** * Modify the value. * * @param $value * @return integer */ public function modify($value) { if ($value instanceof EloquentModel) { return $value->getId(); } return (int)$value; } }
Use test sources as the default in configuration (and improve warning message, when falling back to)
import logging from lib.config import Config from lib.sources.decklinkavsource import DeckLinkAVSource from lib.sources.imgvsource import ImgVSource from lib.sources.tcpavsource import TCPAVSource from lib.sources.testsource import TestSource from lib.sources.videoloopsource import VideoLoopSource log = logging.getLogger('AVSourceManager') sources = {} def spawn_source(name, port, has_audio=True, has_video=True, force_num_streams=None): kind = Config.getSourceKind(name) if kind == 'img': sources[name] = ImgVSource(name) elif kind == 'decklink': sources[name] = DeckLinkAVSource(name, has_audio, has_video) elif kind == 'videoloop': sources[name] = VideoLoopSource(name) elif kind == 'tcp': sources[name] = TCPAVSource(name, port, has_audio, has_video, force_num_streams) else: if kind != 'test': log.warning('Unknown value "%s" in attribute "kind" in definition of source %s (see section [source.%s] in configuration). Falling back to kind "test".', kind, name, name) sources[name] = TestSource(name, has_audio, has_video) return sources[name] def restart_source(name): assert False, "restart_source() not implemented"
import logging from lib.config import Config from lib.sources.decklinkavsource import DeckLinkAVSource from lib.sources.imgvsource import ImgVSource from lib.sources.tcpavsource import TCPAVSource from lib.sources.testsource import TestSource from lib.sources.videoloopsource import VideoLoopSource log = logging.getLogger('AVSourceManager') sources = {} def spawn_source(name, port, has_audio=True, has_video=True, force_num_streams=None): kind = Config.getSourceKind(name) if kind == 'img': sources[name] = ImgVSource(name) elif kind == 'decklink': sources[name] = DeckLinkAVSource(name, has_audio, has_video) elif kind == 'test': sources[name] = TestSource(name, has_audio, has_video) elif kind == 'videoloop': sources[name] = VideoLoopSource(name) elif kind == 'tcp': sources[name] = TCPAVSource(name, port, has_audio, has_video, force_num_streams) else: log.warning('Unknown source kind "%s", defaulting to "tcp"', kind) return sources[name] def restart_source(name): assert False, "restart_source() not implemented"
Fix payload structure for text
const request = require('request'), TOKEN = process.env.PAGE_ACCESS_TOKEN; /** * Send message to API. * * @param {object} json Data to send. * @param {function} callback Called at end. */ module.exports = (json, callback = null) => { request({ json, method: 'POST', qs: {access_token: TOKEN}, uri: 'https://graph.facebook.com/v2.6/me/messages' }, (err, res, body) => { if (!callback) return; if (err || res.statusCode != 200) { callback({ error: err, message: body && body.error, status: res && res.statusCode }); } else { callback(null, { messageId: body && body.message_id, recipientId: body && body.recipient_id }); } }); }; /** * Send text to API. * * @param {string} id User ID. * @param {string} text Message. * @param {string} [metadata] Additional. * @param {function} [callback] Called at end. */ module.exports.text = (id, text, metadata, callback) => { module.exports({ recipient: {id}, message: {text, metadata} }, callback); };
const request = require('request'), TOKEN = process.env.PAGE_ACCESS_TOKEN; /** * Send message to API. * * @param {object} json Data to send. * @param {function} callback Called at end. */ module.exports = (json, callback = null) => { request({ json, method: 'POST', qs: {access_token: TOKEN}, uri: 'https://graph.facebook.com/v2.6/me/messages' }, (err, res, body) => { if (!callback) return; if (err || res.statusCode != 200) { callback({ error: err, message: body && body.error, status: res && res.statusCode }); } else { callback(null, { messageId: body && body.message_id, recipientId: body && body.recipient_id }); } }); }; /** * Send text to API. * * @param {string} id User ID. * @param {string} text Message. * @param {string} [metadata] Additional. * @param {function} [callback] Called at end. */ module.exports.text = (id, text, metadata, callback) => { module.exports({ text, metadata, recipient: {id} }, callback); };
Add test for getAllResponseHeaders after an abort
var sys = require("util") ,assert = require("assert") ,XMLHttpRequest = require("../XMLHttpRequest").XMLHttpRequest ,xhr = new XMLHttpRequest() ,http = require("http"); // Test server var server = http.createServer(function (req, res) { // Test setRequestHeader assert.equal("Foobar", req.headers["x-test"]); var body = "Hello World"; res.writeHead(200, { "Content-Type": "text/plain", "Content-Length": Buffer.byteLength(body) }); res.write("Hello World"); res.end(); this.close(); }).listen(8000); xhr.onreadystatechange = function() { if (this.readyState == 4) { // Test getAllResponseHeaders() var headers = "content-type: text/plain\r\ncontent-length: 11\r\nconnection: close"; assert.equal(headers, this.getAllResponseHeaders()); // Test aborted getAllResponseHeaders this.abort(); assert.equal("", this.getAllResponseHeaders()); sys.puts("done"); } }; xhr.open("GET", "http://localhost:8000/"); xhr.setRequestHeader("X-Test", "Foobar"); xhr.send();
var sys = require("util") ,assert = require("assert") ,XMLHttpRequest = require("../XMLHttpRequest").XMLHttpRequest ,xhr = new XMLHttpRequest() ,http = require("http"); // Test server var server = http.createServer(function (req, res) { // Test setRequestHeader assert.equal("Foobar", req.headers["x-test"]); var body = "Hello World"; res.writeHead(200, { "Content-Type": "text/plain", "Content-Length": Buffer.byteLength(body) }); res.write("Hello World"); res.end(); this.close(); }).listen(8000); xhr.onreadystatechange = function() { if (this.readyState == 4) { // Test getAllResponseHeaders() var headers = "content-type: text/plain\r\ncontent-length: 11\r\nconnection: close"; assert.equal(headers, this.getAllResponseHeaders()); sys.puts("done"); } }; xhr.open("GET", "http://localhost:8000/"); xhr.setRequestHeader("X-Test", "Foobar"); xhr.send();
Use method instead of property
// Include needed files var fluffbot = require('../lib/fluffbot') var discord = require('discord.js') var event = require('../lib/event') // Instantiate bots var fluffbot = new fluffbot() discord = new discord.Client({autoReconnect:true}) discord.login(fluffbot.settings.bot_token) // Initiate the playing game to say the current version discord.on('ready', function(event) { this.setStatus('online', 'Alpha v2.0.4 by FluffyMatt'); }) // Event listener when bot is added to a server discord.on('serverCreated', function(server) { this.sendMessage(server.generalChannel ,'@here FluffBot has joined '+server.name+' and is here to help!'); }) // Event listener for new member joining discord.on('serverNewMember', function(server, user) { this.sendMessage(server.generalChannel ,'@here Welcome '+user.toString()+' to the Fam'); }) // Event listener registered event.bus.on('response', function(message, data) { discord.reply(message, data) }) // Event listener registered event.bus.on('message', function(message, data) { discord.sendMessage(message, data) }) // Message event listener discord.on('message', function(message) { if (message.content.indexOf('!') > -1 && message.content[0] == '!') { fluffbot._runCommand(message) } })
// Include needed files var fluffbot = require('../lib/fluffbot') var discord = require('discord.js') var event = require('../lib/event') // Instantiate bots var fluffbot = new fluffbot() discord = new discord.Client({autoReconnect:true}) discord.login(fluffbot.settings.bot_token) // Initiate the playing game to say the current version discord.on('ready', function(event) { this.status('online', 'Alpha v2.0.4 by FluffyMatt'); }) // Event listener when bot is added to a server discord.on('serverCreated', function(server) { this.sendMessage(server.generalChannel ,'@here FluffBot has joined '+server.name+' and is here to help!'); }) // Event listener for new member joining discord.on('serverNewMember', function(server, user) { this.sendMessage(server.generalChannel ,'@here Welcome '+user.toString()+' to the Fam'); }) // Event listener registered event.bus.on('response', function(message, data) { discord.reply(message, data) }) // Event listener registered event.bus.on('message', function(message, data) { discord.sendMessage(message, data) }) // Message event listener discord.on('message', function(message) { if (message.content.indexOf('!') > -1 && message.content[0] == '!') { fluffbot._runCommand(message) } })
Apply connectDropTarget to element instead of ref / domNode
import React from 'react' import { DropTarget } from 'react-dnd' import BigCalendar from 'react-big-calendar' import { updateEventTime } from './dropActions' import cn from 'classnames'; /* drop targets */ const dropTarget = { drop(props, monitor, backgroundWrapper) { const event = monitor.getItem(); const { moveEvent } = backgroundWrapper.context const updatedEvent = updateEventTime(event, backgroundWrapper.props) moveEvent(updatedEvent) } }; function collectTarget(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver() }; } class DroppableBackgroundWrapper extends React.Component { render() { const { connectDropTarget, children, isOver } = this.props; const BackgroundWrapper = BigCalendar.components.backgroundWrapper; const resultingChildren = isOver ? React.cloneElement(children, { className: cn(children.props.className, 'dnd-over') }) : children; return (<BackgroundWrapper children={connectDropTarget(resultingChildren)} />); } } DroppableBackgroundWrapper.contextTypes = { moveEvent: React.PropTypes.func } export default DropTarget(['event'], dropTarget, collectTarget)(DroppableBackgroundWrapper)
import React from 'react' import { DropTarget } from 'react-dnd' import BigCalendar from 'react-big-calendar' import { findDOMNode } from 'react-dom' import { updateEventTime } from './dropActions' import cn from 'classnames'; /* drop targets */ const dropTarget = { drop(props, monitor, backgroundWrapper) { const event = monitor.getItem(); const { moveEvent } = backgroundWrapper.context const updatedEvent = updateEventTime(event, backgroundWrapper.props) moveEvent(updatedEvent) } }; function collectTarget(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver() }; } class DroppableBackgroundWrapper extends React.Component { render() { const { connectDropTarget, children, isOver } = this.props; const BackgroundWrapper = BigCalendar.components.backgroundWrapper; const resultingChildren = isOver ? React.cloneElement(children, { className: cn(children.props.className, 'dnd-over') }) : children; return (<BackgroundWrapper children={resultingChildren} ref={instance => { const domNode = findDOMNode(instance); return connectDropTarget(domNode); }} />); } } DroppableBackgroundWrapper.contextTypes = { moveEvent: React.PropTypes.func } export default DropTarget(['event'], dropTarget, collectTarget)(DroppableBackgroundWrapper)
Use 'errors' instead of 'result'
'use strict'; var gonzales = require('gonzales-pe'); var linters = [ require('./linters/space_before_brace') ]; exports.lint = function (data, path, config) { var ast = this.parseAST(data); var errors = []; ast.map(function (node) { var i; for (i = 0; i < linters.length; i++) { errors.push(linters[i].call(null, { config: config, node: node, path: path })); } }); // Remove empty errors return errors.filter(function (error) { return error !== null && error !== true; }); }; exports.parseAST = function (input) { return gonzales.parse(input, { syntax: 'less' }); };
'use strict'; var gonzales = require('gonzales-pe'); var linters = [ require('./linters/space_before_brace') ]; exports.lint = function (data, path, config) { var ast = this.parseAST(data); var result = []; ast.map(function (node) { var i; for (i = 0; i < linters.length; i++) { result.push(linters[i].call(null, { config: config, node: node, path: path })); } }); // Remove all results for nodes that were skipped or passed return result.filter(function (item) { return item !== null && item !== true; }); }; exports.parseAST = function (input) { return gonzales.parse(input, { syntax: 'less' }); };
Update model.js for syntax error It was bothering me..
var chai = require('chai'); var should = chai.should(); var User = require('../models/User'); describe('User Model', function() { it('should create a new user', function(done) { var user = new User({ email: 'test@gmail.com', password: 'password' }); user.save(function(err) { if (err) return done(err); done(); }); }); it('should not create a user with the unique email', function(done) { var user = new User({ email: 'test@gmail.com', password: 'password' }); user.save(function(err) { if (err) err.code.should.equal(11000); done(); }); }); it('should find user by email', function(done) { User.findOne({ email: 'test@gmail.com' }, function(err, user) { if (err) return done(err); user.email.should.equal('test@gmail.com'); done(); }); }); it('should delete a user', function(done) { User.remove({ email: 'test@gmail.com' }, function(err) { if (err) return done(err); done(); }); }); });
var chai = require('chai'); var should = chai.should(); var User = require('../models/User'); describe('User Model', function() { it('should create a new user', function(done) { var user = new User({ email: 'test@gmail.com', password: 'password' }); user.save(function(err) { if (err) return done(err); done(); }) }); it('should not create a user with the unique email', function(done) { var user = new User({ email: 'test@gmail.com', password: 'password' }); user.save(function(err) { if (err) err.code.should.equal(11000); done(); }); }); it('should find user by email', function(done) { User.findOne({ email: 'test@gmail.com' }, function(err, user) { if (err) return done(err); user.email.should.equal('test@gmail.com'); done(); }); }); it('should delete a user', function(done) { User.remove({ email: 'test@gmail.com' }, function(err) { if (err) return done(err); done(); }); }); });
flake8: Fix all warnings in sets app
from django.db import models from django.utils import timezone from comics.core.models import Comic class Set(models.Model): name = models.SlugField( max_length=100, unique=True, help_text='The set identifier') add_new_comics = models.BooleanField( default=False, help_text='Automatically add new comics to the set') hide_empty_comics = models.BooleanField( default=False, help_text='Hide comics without matching releases from view') created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField() last_loaded = models.DateTimeField() comics = models.ManyToManyField(Comic) class Meta: db_table = 'comics_set' ordering = ['name'] def __unicode__(self): return self.name def get_slug(self): return self.name def set_slug(self, slug): self.name = slug slug = property(get_slug, set_slug) def set_loaded(self): self.last_loaded = timezone.now() self.save()
from django.db import models from django.utils import timezone from comics.core.models import Comic class Set(models.Model): name = models.SlugField(max_length=100, unique=True, help_text='The set identifier') add_new_comics = models.BooleanField(default=False, help_text='Automatically add new comics to the set') hide_empty_comics = models.BooleanField(default=False, help_text='Hide comics without matching releases from view') created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField() last_loaded = models.DateTimeField() comics = models.ManyToManyField(Comic) class Meta: db_table = 'comics_set' ordering = ['name'] def __unicode__(self): return self.name def get_slug(self): return self.name def set_slug(self, slug): self.name = slug slug = property(get_slug, set_slug) def set_loaded(self): self.last_loaded = timezone.now() self.save()
Fix thumbnail route when it's fetched from api
/* globals BUILDCONFIG */ export default (app) => { class ThumbnailService { constructor(authService) { 'ngInject'; this.authService = authService; } getBestFitUrl(thumbnails, size) { let url = thumbnails.reduce((thumb, next) => { if (Math.abs(size - next.widthPx) < Math.abs(size - thumb.widthPx)) { return next; } return thumb; }).url; if (url.startsWith('/')) { url = `${BUILDCONFIG.API_HOST}/api${url}?token=${this.authService.token()}`; } return url; } } app.service('thumbnailService', ThumbnailService); };
export default (app) => { class ThumbnailService { constructor(authService) { 'ngInject'; this.authService = authService; } getBestFitUrl(thumbnails, size) { let url = thumbnails.reduce((thumb, next) => { if (Math.abs(size - next.widthPx) < Math.abs(size - thumb.widthPx)) { return next; } return thumb; }).url; if (url.startsWith('/')) { return `${url}?token=${this.authService.token()}`; } return url; } } app.service('thumbnailService', ThumbnailService); };
Add missing R class to WebView resource rewriting. We weren't rewriting the resources for web_contents_delegate_android, resulting in crashes any time a resource was loaded by that component (e.g. popup bubbles for HTML form validation failures). Add it to the list and also clean up outdated comments here that refer to previous versions of this code. Add a TODO to track finding a better way to do this which is less fragile. BUG=490826 Review URL: https://codereview.chromium.org/1154853005 Cr-Commit-Position: refs/heads/master@{#331356} (cherry picked from commit f417eb24ae1c89a02b081571aeed1403cc39a1cc) Review URL: https://codereview.chromium.org/1153103002 Cr-Commit-Position: d34a0005849006230ae7ffb1a9693419810a06bc@{#98} Cr-Branched-From: 40cda19e609fd36fbf5fe489055423e611631abc@{#330231}
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.android.webview.chromium; /** * Helper class used to fix up resource ids. */ class ResourceRewriter { /** * Rewrite the R 'constants' for the WebView library apk. */ public static void rewriteRValues(final int packageId) { // This list must be kept up to date to include all R classes depended on directly or // indirectly by android_webview_java. // TODO(torne): find a better way to do this, http://crbug.com/492166. com.android.webview.chromium.R.onResourcesLoaded(packageId); org.chromium.android_webview.R.onResourcesLoaded(packageId); org.chromium.components.web_contents_delegate_android.R.onResourcesLoaded(packageId); org.chromium.content.R.onResourcesLoaded(packageId); org.chromium.ui.R.onResourcesLoaded(packageId); } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.android.webview.chromium; /** * Helper class used to fix up resource ids. * This is mostly a copy of the code in frameworks/base/core/java/android/app/LoadedApk.java. * TODO: Remove if a cleaner mechanism is provided (either public API or AAPT is changed to generate * this code). */ class ResourceRewriter { /** * Rewrite the R 'constants' for the WebView library apk. */ public static void rewriteRValues(final int packageId) { // TODO: We should use jarjar to remove the redundant R classes here, but due // to a bug in jarjar it's not possible to rename classes with '$' in their name. // See b/15684775. com.android.webview.chromium.R.onResourcesLoaded(packageId); org.chromium.android_webview.R.onResourcesLoaded(packageId); org.chromium.content.R.onResourcesLoaded(packageId); org.chromium.ui.R.onResourcesLoaded(packageId); } }
Reduce the name of a function
#!/usr/bin/env python import rospy,copy from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse from pimouse_ros.msg import LightSensorValues class WallStop(): def __init__(self): self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1) self.sensor_values = LightSensorValues() rospy.Subscriber('/lightsensors', LightSensorValues, self.callback) def callback(self,messages): self.sensor_values = messages def run(self): rate = rospy.Rate(10) data = Twist() while not rospy.is_shutdown(): data.linear.x = 0.2 if self.sensor_values.sum_all < 500 else 0.0 self.cmd_vel.publish(data) rate.sleep() if __name__ == '__main__': rospy.init_node('wall_stop') rospy.wait_for_service('/motor_on') rospy.wait_for_service('/motor_off') rospy.on_shutdown(rospy.ServiceProxy('/motor_off',Trigger).call) rospy.ServiceProxy('/motor_on',Trigger).call() WallStop().run()
#!/usr/bin/env python import rospy,copy from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse from pimouse_ros.msg import LightSensorValues class WallStop(): def __init__(self): self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1) self.sensor_values = LightSensorValues() rospy.Subscriber('/lightsensors', LightSensorValues, self.callback_lightsensors) def callback_lightsensors(self,messages): self.sensor_values = messages def run(self): rate = rospy.Rate(10) data = Twist() while not rospy.is_shutdown(): data.linear.x = 0.2 if self.sensor_values.sum_all < 500 else 0.0 self.cmd_vel.publish(data) rate.sleep() if __name__ == '__main__': rospy.init_node('wall_stop') rospy.wait_for_service('/motor_on') rospy.wait_for_service('/motor_off') rospy.on_shutdown(rospy.ServiceProxy('/motor_off',Trigger).call) rospy.ServiceProxy('/motor_on',Trigger).call() WallStop().run()
Change app name. Added getItems method
// app.shoppingListService.js (function() { "use strict"; angular.module("ShoppingListApp") .service("ShoppingListService", ShoppingListService); ShoppingListService.$inject = ["$q", "WeightLossFilterService"]; function ShoppingListService($q, WeightLossFilterService) { let service = this; // List of Shopping items let items = []; service.addItem = addItem; service.getItems = getItems; function addItem(itemName, itemQuantity) { let promise = WeightLossFilterService.checkName(itemName); promise.then(response => { let nextPromise = WeightLossFilterService.checkQuantity(itemQuantity); nextPromise.then(result => { let item = { name: itemName, quantity: itemQuantity }; items.push(item); }, errorResponse => { console.log(errorResponse.message); }); }, errorResponse => { console.log(errorResponse.message); }); } function getItems() { return items; } } })();
// app.shoppingListService.js (function() { "use strict"; angular.module("MyApp") .service("ShoppingListService", ShoppingListService); ShoppingListService.$inject = ["$q", "WeightLossFilterService"]; function ShoppingListService($q, WeightLossFilterService) { let service = this; // List of Shopping items let items = []; service.addItem = addItem; function addItem(itemName, itemQuantity) { let promise = WeightLossFilterService.checkName(itemName); promise.then(response => { let nextPromise = WeightLossFilterService.checkQuantity(itemQuantity); nextPromise.then(result => { let item = { name: itemName, quantity: itemQuantity }; items.push(item); }, errorResponse => { console.log(errorResponse.message); }); }, errorResponse => { console.log(errorResponse.message); }); } } })();
Put Sitemap link in footer
<footer> <div id="footer-newsletter"> <div class="container"> <p> Get our Newsletter: <form action="" method="post"> <input type="text" class="form-control form-footer-newsletter" placeholder="Your E-Mail adress" /> <input type="submit" value="Subscribe" name="subscribe" id="footer-newsletter-subscribe" class="btn btn-success"> </form> </p> </div> </div> <div class="container"> <p class="footer-links pull-right"> <a href="{{ url('sitemap') }}">Sitemap</a>| <a href="{{ url('privacy-policy') }}">Privacy Policy</a>| <a href="{{ url('terms-of-service') }}">Terms of service</a>| <a href="{{ url('imprint') }}">Imprint</a> </p> </div> </footer>
<footer> <div id="footer-newsletter"> <div class="container"> <p> Get our Newsletter: <form action="" method="post"> <input type="text" class="form-control form-footer-newsletter" placeholder="Your E-Mail adress" /> <input type="submit" value="Subscribe" name="subscribe" id="footer-newsletter-subscribe" class="btn btn-success"> </form> </p> </div> </div> <div class="container"> <p class="footer-links pull-right"> <a href="{{ url('privacy-policy') }}">Privacy Policy</a>| <a href="{{ url('terms-of-service') }}">Terms of service</a>| <a href="{{ url('imprint') }}">Imprint</a> </p> </div> </footer>
Add next query param to signup url
import Ember from 'ember'; import config from 'ember-get-config'; export default Ember.Service.extend({ store: Ember.inject.service(), id: config.PREPRINTS.provider, provider: Ember.computed('id', function() { const id = this.get('id'); if (!id) return; return this .get('store') .findRecord('preprint-provider', id); }), isProvider: Ember.computed('id', function() { const id = this.get('id'); return id && id !== 'osf'; }), stylesheet: Ember.computed('id', function() { const id = this.get('id'); if (!id) return; const suffix = config.ASSET_SUFFIX ? `-${config.ASSET_SUFFIX}` : ''; return `/preprints/assets/css/${id}${suffix}.css`; }), signupUrl: Ember.computed('id', function() { const query = Ember.$.param({ campaign: `${this.get('id')}-preprints`, next: window.location.href }); return `${config.OSF.url}register?${query}`; }), });
import Ember from 'ember'; import config from 'ember-get-config'; export default Ember.Service.extend({ store: Ember.inject.service(), id: config.PREPRINTS.provider, provider: Ember.computed('id', function() { const id = this.get('id'); if (!id) return; return this .get('store') .findRecord('preprint-provider', id); }), isProvider: Ember.computed('id', function() { const id = this.get('id'); return id && id !== 'osf'; }), stylesheet: Ember.computed('id', function() { const id = this.get('id'); if (!id) return; const suffix = config.ASSET_SUFFIX ? `-${config.ASSET_SUFFIX}` : ''; return `/preprints/assets/css/${id}${suffix}.css`; }), signupUrl: Ember.computed('id', function() { const query = Ember.$.param({ campaign: `${this.get('id')}-preprints` }); return `${config.OSF.url}register?${query}`; }), });
Use post data cause form values won't be here.
<?php namespace Anomaly\UsersModule\User\Validation; use Anomaly\UsersModule\User\Contract\UserInterface; use Anomaly\UsersModule\User\Login\LoginFormBuilder; use Anomaly\UsersModule\User\UserAuthenticator; use Symfony\Component\HttpFoundation\Response; /** * Class ValidateCredentials * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> */ class ValidateCredentials { /** * Handle the validation. * * @param UserAuthenticator $authenticator * @param LoginFormBuilder $builder * @return bool */ public function handle(UserAuthenticator $authenticator, LoginFormBuilder $builder) { if (!$response = $authenticator->authenticate($builder->getPostData())) { return false; } if ($response instanceof UserInterface) { $builder->setUser($response); } if ($response instanceof Response) { $builder->setFormResponse($response); } return true; } }
<?php namespace Anomaly\UsersModule\User\Validation; use Anomaly\UsersModule\User\Contract\UserInterface; use Anomaly\UsersModule\User\Contract\UserRepositoryInterface; use Anomaly\UsersModule\User\Login\LoginFormBuilder; use Anomaly\UsersModule\User\UserAuthenticator; use Symfony\Component\HttpFoundation\Response; /** * Class ValidateCredentials * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> */ class ValidateCredentials { /** * Handle the validation. * * @param UserAuthenticator $authenticator * @param LoginFormBuilder $builder * @return bool */ public function handle(UserAuthenticator $authenticator, LoginFormBuilder $builder) { $values = $builder->getFormValues(); if (!$response = $authenticator->authenticate($values->all())) { return false; } if ($response instanceof UserInterface) { $builder->setUser($response); } if ($response instanceof Response) { $builder->setFormResponse($response); } return true; } }
Add to javadoc about thread safety in a processor in a route
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel; /** * A <a href="http://camel.apache.org/processor.html">processor</a> is used to implement the * <a href="http://camel.apache.org/event-driven-consumer.html"> Event Driven Consumer</a> * and <a href="http://camel.apache.org/message-translator.html"> Message Translator</a> * patterns and to process message exchanges. * <p/> * Notice if you use a {@link Processor} in a Camel route, then make sure to write the {@link Processor} * in a thread-safe way, as the Camel routes can potentially be executed by concurrent threads, and therefore * multiple threads can call the same {@link Processor} instance. * * @version */ public interface Processor { /** * Processes the message exchange * * @param exchange the message exchange * @throws Exception if an internal processing error has occurred. */ void process(Exchange exchange) throws Exception; }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel; /** * A <a href="http://camel.apache.org/processor.html">processor</a> is used to implement the * <a href="http://camel.apache.org/event-driven-consumer.html"> Event Driven Consumer</a> * and <a href="http://camel.apache.org/message-translator.html"> Message Translator</a> * patterns and to process message exchanges. * * @version */ public interface Processor { /** * Processes the message exchange * * @param exchange the message exchange * @throws Exception if an internal processing error has occurred. */ void process(Exchange exchange) throws Exception; }
Fix ISE if the UA header is missing
/** * Module dependencies. */ var config = require('lib/config'); var jade = require('jade'); var path = require('path'); var resolve = path.resolve; var t = require('t-component'); var html = jade.renderFile(resolve(__dirname, 'index.jade'), { config: config, t: t }); var express = require('express'); var app = module.exports = express(); var bowser = require('bowser'); app.get('/browser-update', function (req, res, next) { res.send(200, html); }); app.get('*', function (req, res, next) { //Check the user agent, and if is invalid, redirect to the page // for browser update. var userAgent = bowser.browser._detect(typeof req.headers['user-agent'] !== 'undefined' ? req.headers['user-agent'] : ''); if (userAgent.msie && userAgent.version <= 9) { res.redirect(302, '/browser-update'); } else { next(); } });
/** * Module dependencies. */ var config = require('lib/config'); var jade = require('jade'); var path = require('path'); var resolve = path.resolve; var t = require('t-component'); var html = jade.renderFile(resolve(__dirname, 'index.jade'), { config: config, t: t }); var express = require('express'); var app = module.exports = express(); var bowser = require('bowser'); app.get('/browser-update', function (req, res, next) { res.send(200, html); }); app.get('*', function (req, res, next) { //Check the user agent, and if is invalid, redirect to the page // for browser update. var userAgent = bowser.browser._detect(req.headers['user-agent']); if (userAgent.msie && userAgent.version <= 9) { res.redirect(302, '/browser-update'); } else { next(); } });
Add performance budgeting to babel/postcss/extract-text e2e test
const webpack2 = require('../../index') // Need to write it like this instead of destructuring so it runs on Node 4.x w/o transpiling const addPlugins = webpack2.addPlugins const createConfig = webpack2.createConfig const entryPoint = webpack2.entryPoint const performance = webpack2.performance const setOutput = webpack2.setOutput const webpack = webpack2.webpack const babel = require('@webpack-blocks/babel6') const postcss = require('@webpack-blocks/postcss') const extractText = require('@webpack-blocks/extract-text2') const path = require('path') module.exports = createConfig([ entryPoint( path.join(__dirname, 'app.js') ), setOutput( path.join(__dirname, 'build/bundle.js') ), babel(), postcss(), extractText( path.join('styles.css') ), performance({ maxAssetSize: 100000, maxEntrypointSize: 500000, hints: 'error' }), addPlugins([ new webpack.DefinePlugin({ 'process.env': { TEST: '"This is the injected process.env.TEST!"' } }) ]) ])
const webpack2 = require('../../index') // Need to write it like this instead of destructuring so it runs on Node 4.x w/o transpiling const addPlugins = webpack2.addPlugins const createConfig = webpack2.createConfig const entryPoint = webpack2.entryPoint const setOutput = webpack2.setOutput const webpack = webpack2.webpack const babel = require('@webpack-blocks/babel6') const postcss = require('@webpack-blocks/postcss') const extractText = require('@webpack-blocks/extract-text2') const path = require('path') module.exports = createConfig([ entryPoint( path.join(__dirname, 'app.js') ), setOutput( path.join(__dirname, 'build/bundle.js') ), babel(), postcss(), extractText( path.join('styles.css') ), addPlugins([ new webpack.DefinePlugin({ 'process.env': { TEST: '"This is the injected process.env.TEST!"' } }) ]) ])
Disable duplicate check mode for merging-- this can cause events to be thrown out for MC data.
import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), duplicateCheckMode = cms.untracked.string('noDuplicateCheck') ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out)
import FWCore.ParameterSet.Config as cms from FWCore.ParameterSet.VarParsing import VarParsing import subprocess import os import sys options = VarParsing('analysis') options.register('chirp', default=None, mytype=VarParsing.varType.string) options.register('inputs', mult=VarParsing.multiplicity.list, mytype=VarParsing.varType.string) options.register('output', mytype=VarParsing.varType.string) options.parseArguments() if options.chirp: for input in options.inputs: status = subprocess.call([os.path.join(os.environ.get("PARROT_PATH", "bin"), "chirp_get"), options.chirp, input, os.path.basename(input)]) if status != 0: sys.exit(500) process = cms.Process("PickEvent") process.source = cms.Source ("PoolSource", fileNames = cms.untracked.vstring(''), ) process.out = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string(options.output) ) process.end = cms.EndPath(process.out)
Add an assert to make mypy check pass again
#!/usr/bin/env python import os.path import sys import subprocess import unittest tests_dir = os.path.dirname(__file__) sys.path.insert(0, os.path.dirname(tests_dir)) import secretstorage if __name__ == '__main__': major, minor, patch = sys.version_info[:3] print('Running with Python %d.%d.%d (SecretStorage from %s)' % (major, minor, patch, os.path.dirname(secretstorage.__file__))) mock = None if len(sys.argv) > 1 and os.path.isfile(sys.argv[1]): mock = subprocess.Popen(('/usr/bin/python3', sys.argv[1],), stdout=subprocess.PIPE, universal_newlines=True) assert mock.stdout is not None # for mypy bus_name = mock.stdout.readline().rstrip() secretstorage.util.BUS_NAME = bus_name print('Bus name set to %r' % secretstorage.util.BUS_NAME) loader = unittest.TestLoader() runner = unittest.TextTestRunner(verbosity=2) result = runner.run(loader.discover(tests_dir)) if mock is not None: mock.terminate() sys.exit(not result.wasSuccessful())
#!/usr/bin/env python import os.path import sys import subprocess import unittest tests_dir = os.path.dirname(__file__) sys.path.insert(0, os.path.dirname(tests_dir)) import secretstorage if __name__ == '__main__': major, minor, patch = sys.version_info[:3] print('Running with Python %d.%d.%d (SecretStorage from %s)' % (major, minor, patch, os.path.dirname(secretstorage.__file__))) mock = None if len(sys.argv) > 1 and os.path.isfile(sys.argv[1]): mock = subprocess.Popen(('/usr/bin/python3', sys.argv[1],), stdout=subprocess.PIPE, universal_newlines=True) bus_name = mock.stdout.readline().rstrip() secretstorage.util.BUS_NAME = bus_name print('Bus name set to %r' % secretstorage.util.BUS_NAME) loader = unittest.TestLoader() runner = unittest.TextTestRunner(verbosity=2) result = runner.run(loader.discover(tests_dir)) if mock is not None: mock.terminate() sys.exit(not result.wasSuccessful())
examples: Fix typo on pull example Signed-off-by: Theodore Keloglou <a07b7322a11cee41c8267d5dc5751e643be543a6@gmail.com>
package main import ( "fmt" "os" "gopkg.in/src-d/go-git.v4" . "gopkg.in/src-d/go-git.v4/_examples" ) // Pull changes from a remote repository func main() { CheckArgs("<path>") path := os.Args[1] // We instantiate a new repository targeting the given path (the .git folder) r, err := git.PlainOpen(path) CheckIfError(err) // Get the working directory for the repository w, err := r.Worktree() CheckIfError(err) // Pull the latest changes from the origin remote and merge into the current branch Info("git pull origin") err = w.Pull(&git.PullOptions{RemoteName: "origin"}) CheckIfError(err) // Print the latest commit that was just pulled ref, err := r.Head() CheckIfError(err) commit, err := r.CommitObject(ref.Hash()) CheckIfError(err) fmt.Println(commit) }
package main import ( "fmt" "os" "gopkg.in/src-d/go-git.v4" . "gopkg.in/src-d/go-git.v4/_examples" ) // Pull changes from a remote repository func main() { CheckArgs("<path>") path := os.Args[1] // We instance\iate a new repository targeting the given path (the .git folder) r, err := git.PlainOpen(path) CheckIfError(err) // Get the working directory for the repository w, err := r.Worktree() CheckIfError(err) // Pull the latest changes from the origin remote and merge into the current branch Info("git pull origin") err = w.Pull(&git.PullOptions{RemoteName: "origin"}) CheckIfError(err) // Print the latest commit that was just pulled ref, err := r.Head() CheckIfError(err) commit, err := r.CommitObject(ref.Hash()) CheckIfError(err) fmt.Println(commit) }
Include all of the files in test coverage report
const webpackConfig = require('./webpack.config.babel')({env: 'test'}); const testGlob = 'src/**/*.test.js'; const srcGlob = 'src/**/!(*.test|*.stub).js'; module.exports = config => { config.set({ basePath: '', frameworks: ['mocha', 'chai'], files: [ testGlob, srcGlob ], exclude: ['src/bootstrap.js'], preprocessors: { [testGlob]: ['webpack'], [srcGlob]: ['webpack'] }, webpack: webpackConfig, webpackMiddleware: {noInfo: true}, reporters: ['progress', 'coverage'], coverageReporter: { check: { global: { statements: 11, branches: 0, functions: 0, lines: 11 } }, reporters: [ {type: 'lcov', dir: 'coverage/', subdir: '.'}, {type: 'json', dir: 'coverage/', subdir: '.'}, {type: 'text-summary'} ] }, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['Chrome'], singleRun: true, concurrency: Infinity }); };
const webpackConfig = require('./webpack.config.babel')({env: 'test'}); const fileGlob = 'src/**/*.test.js'; module.exports = config => { config.set({ basePath: '', frameworks: ['mocha', 'chai'], files: [ fileGlob ], preprocessors: { [fileGlob]: ['webpack'] }, webpack: webpackConfig, reporters: ['progress', 'coverage'], coverageReporter: { reporters: [ {type: 'lcov', dir: 'coverage/', subdir: '.'}, {type: 'json', dir: 'coverage/', subdir: '.'}, {type: 'text-summary'} ] }, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['Chrome'], singleRun: true, concurrency: Infinity }); };
Write each tag from newline
<?php namespace common\widgets; use app\modules\article\models\Tag; use yii\base\Widget; use yii\bootstrap\Html; /** * Class TagsInputWidget * @package common\widgets * @property Tag[] $tags */ class TagsWidget extends Widget { public function run() { $html = ''; foreach ($this->tags as $tag) { $html .= '&#010;'.$this->renderTagItem($tag); } return $html; } /** * @param Tag|Tag[] $tags */ public function setTags($tags) { $this->tags = is_array($tags) ? $tags : [$tags]; } /** * @param Tag $tag * @return string */ private function renderTagItem(Tag $tag) { return Html::a($tag->name, $tag->getUrlView(), ['class' => 'label label-info']); } }
<?php namespace common\widgets; use app\modules\article\models\Tag; use yii\base\Widget; use yii\bootstrap\Html; /** * Class TagsInputWidget * @package common\widgets * @property Tag[] $tags */ class TagsWidget extends Widget { public function run() { $html = ''; foreach ($this->tags as $tag) { $html .= $this->renderTagItem($tag); } return $html; } /** * @param Tag|Tag[] $tags */ public function setTags($tags) { $this->tags = is_array($tags) ? $tags : [$tags]; } /** * @param Tag $tag * @return string */ private function renderTagItem(Tag $tag) { return Html::a($tag->name, $tag->getUrlView(), ['class' => 'label label-info']); } }
Correct "Doc test pane" to "Dock test pane" This PR so far only changes the string displayed in the UI. The rest of the code still refers to this option as `doccontainer`. Should all these instances also be changed to `dockcontainer`? As an aside, it seems to be called a container in one option ("Hide container") but as a test pane in another ("Doc test pane"). Should these be made consistent?
/* globals jQuery,QUnit */ QUnit.config.urlConfig.push({ id: 'nocontainer', label: 'Hide container'}); QUnit.config.urlConfig.push({ id: 'nojshint', label: 'Disable JSHint'}); QUnit.config.urlConfig.push({ id: 'doccontainer', label: 'Dock test pane'}); QUnit.config.testTimeout = 60000; //Default Test Timeout 60 Seconds if (QUnit.notifications) { QUnit.notifications({ icons: { passed: '/assets/passed.png', failed: '/assets/failed.png' } }); } jQuery(document).ready(function() { var containerVisibility = QUnit.urlParams.nocontainer ? 'hidden' : 'visible'; var containerPosition = QUnit.urlParams.doccontainer ? 'absolute' : 'relative'; document.getElementById('ember-testing-container').style.visibility = containerVisibility; document.getElementById('ember-testing-container').style.position = containerPosition; });
/* globals jQuery,QUnit */ QUnit.config.urlConfig.push({ id: 'nocontainer', label: 'Hide container'}); QUnit.config.urlConfig.push({ id: 'nojshint', label: 'Disable JSHint'}); QUnit.config.urlConfig.push({ id: 'doccontainer', label: 'Doc test pane'}); QUnit.config.testTimeout = 60000; //Default Test Timeout 60 Seconds if (QUnit.notifications) { QUnit.notifications({ icons: { passed: '/assets/passed.png', failed: '/assets/failed.png' } }); } jQuery(document).ready(function() { var containerVisibility = QUnit.urlParams.nocontainer ? 'hidden' : 'visible'; var containerPosition = QUnit.urlParams.doccontainer ? 'absolute' : 'relative'; document.getElementById('ember-testing-container').style.visibility = containerVisibility; document.getElementById('ember-testing-container').style.position = containerPosition; });
Exclude fetch errors from tracking (based on error code).
/** * Cache data. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 { trackEvent } from './'; export async function trackAPIError( method, type, identifier, datapoint, error ) { // Exclude certain errors from tracking based on error code. const excludedErrorCodes = [ 'fetch_error', // Client failed to fetch from WordPress. ]; if ( excludedErrorCodes.indexOf( error.code ) >= 0 ) { return; } await trackEvent( 'api_error', `${ method }:${ type }/${ identifier }/data/${ datapoint }`, `${ error.message } (code: ${ error.code }${ error.data?.reason ? ', reason: ' + error.data.reason : '' } ])`, error.data?.status || error.code ); }
/** * Cache data. * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 { trackEvent } from './'; export async function trackAPIError( method, type, identifier, datapoint, error ) { await trackEvent( 'api_error', `${ method }:${ type }/${ identifier }/data/${ datapoint }`, `${ error.message } (code: ${ error.code }${ error.data?.reason ? ', reason: ' + error.data.reason : '' } ])`, error.data?.status || error.code ); }
Stop claiming support for 2.6 I don't even have a Python 2.6 interpreter.
from setuptools import setup setup( name="ftfy", version='3.3.0', maintainer='Luminoso Technologies, Inc.', maintainer_email='info@luminoso.com', license="MIT", url='http://github.com/LuminosoInsight/python-ftfy', platforms=["any"], description="Fixes some problems with Unicode text after the fact", packages=['ftfy', 'ftfy.bad_codecs'], package_data={'ftfy': ['char_classes.dat']}, classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Filters", "Development Status :: 5 - Production/Stable" ], entry_points={ 'console_scripts': [ 'ftfy = ftfy.cli:main' ] } )
from setuptools import setup setup( name="ftfy", version='3.3.0', maintainer='Luminoso Technologies, Inc.', maintainer_email='info@luminoso.com', license="MIT", url='http://github.com/LuminosoInsight/python-ftfy', platforms=["any"], description="Fixes some problems with Unicode text after the fact", packages=['ftfy', 'ftfy.bad_codecs'], package_data={'ftfy': ['char_classes.dat']}, classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Filters", "Development Status :: 5 - Production/Stable" ], entry_points={ 'console_scripts': [ 'ftfy = ftfy.cli:main' ] } )
Add example of using the Load method on the Markup object
var markup = null; $(function() { var markupTools = MarkupTools('.button-bar > div'); markup = Markup('#pdf-markup', markupTools); $(markup).on('update add', function() { $('#result').text(JSON.stringify(markup.Serialize())); }); $(markupTools).on('browse', function(e, settings) { new Browser(settings); }); $('.button-bar > ul').find('a').each(function() { var pluginName = $(this).data('plugin'); var plugin = window[pluginName]; markup.AddPlugin(plugin); $(this).on('click', function(){ window[$(this).data('plugin')].New(markup); }); }); markup.Load([{"type":"text","text":"Invoice","x":94,"y":2,"color":"#00000","size":"20","bold":"1"},{"type":"image","source":"example.png","x":47,"y":50,"width":"129"}]); });
var markup = null; $(function() { var markupTools = MarkupTools('.button-bar > div'); markup = Markup('#pdf-markup', markupTools); $(markup).on('update add', function() { $('#result').text(JSON.stringify(markup.Serialize())); }); $(markupTools).on('browse', function(e, settings) { new Browser(settings); }); $('.button-bar > ul').find('a').each(function() { var pluginName = $(this).data('plugin'); var plugin = window[pluginName]; markup.AddPlugin(plugin); $(this).on('click', function(){ window[$(this).data('plugin')].New(markup); }); }); });
Fix typo in requrie that breaks on case-sensitive FS
var Game = require('./game'); var GameArtist = require('./artists/gameartist'); var EventDispatcher = require('./eventdispatcher'); var utils = require('./utils'); var EventLogger = require('./eventlogger'); var PlaybackDispatcher = require('./playbackdispatcher'); var Landmine = window.Landmine || {}; Landmine.start = function(options) { utils.requireOptions(options, 'canvas'); var eventDispatcher = options.eventDispatcher || new EventDispatcher(options.canvas); var game = new Game({ canvas: options.canvas, eventDispatcher: eventDispatcher }); //jshint unused:false var gameArtist = new GameArtist({ canvas: options.canvas, game: game }); var eventLogger = new EventLogger({ eventDispatcher: eventDispatcher }); Landmine.events = eventLogger; game.start(); }; Landmine.playback = function(options) { utils.requireOptions(options, 'canvas', 'events'); var vcr = new PlaybackDispatcher({ events: options.events }); options.eventDispatcher = vcr; Landmine.start(options); vcr.start(); }; window.Landmine = Landmine;
var Game = require('./game'); var GameArtist = require('./artists/gameartist'); var EventDispatcher = require('./eventdispatcher'); var utils = require('./utils'); var EventLogger = require('./eventLogger'); var PlaybackDispatcher = require('./playbackdispatcher'); var Landmine = window.Landmine || {}; Landmine.start = function(options) { utils.requireOptions(options, 'canvas'); var eventDispatcher = options.eventDispatcher || new EventDispatcher(options.canvas); var game = new Game({ canvas: options.canvas, eventDispatcher: eventDispatcher }); //jshint unused:false var gameArtist = new GameArtist({ canvas: options.canvas, game: game }); var eventLogger = new EventLogger({ eventDispatcher: eventDispatcher }); Landmine.events = eventLogger; game.start(); }; Landmine.playback = function(options) { utils.requireOptions(options, 'canvas', 'events'); var vcr = new PlaybackDispatcher({ events: options.events }); options.eventDispatcher = vcr; Landmine.start(options); vcr.start(); }; window.Landmine = Landmine;
Fix the bug causing all the requests getting parsed by the path code
package txtdirect import ( "fmt" "regexp" "strings" ) var dockerRegexs = map[string]string{ "_catalog": "^/v2/_catalog$", "tags": "^/v2/(.*)/tags/(.*)", "manifests": "^/v2/(.*)/manifests/(.*)", "blobs": "^/v2/(.*)/blobs/(.*)", } var DockerRegex = regexp.MustCompile("^\\/v2\\/(.*\\/(tags|manifests|blobs)\\/.*|_catalog$)") func generateDockerv2URI(path string, rec record) (string, int) { if path != "/" { regexType := DockerRegex.FindAllStringSubmatch(path, -1)[0] pathRegex, err := regexp.Compile(dockerRegexs[regexType[len(regexType)-1]]) if err != nil { panic(err) } pathSubmatches := pathRegex.FindAllStringSubmatch(path, -1) pathSlice := pathSubmatches[0][1:] uri := rec.To for i, v := range pathSlice { uri = strings.Replace(uri, fmt.Sprintf("$%d", i+1), v, -1) } return uri, rec.Code } return rec.To, rec.Code }
package txtdirect import ( "fmt" "regexp" "strings" ) var dockerRegexs = map[string]string{ "_catalog": "^/v2/_catalog$", "tags": "^/v2/(.*)/tags/(.*)", "manifests": "^/v2/(.*)/manifests/(.*)", "blobs": "^/v2/(.*)/blobs/(.*)", } var DockerRegex = regexp.MustCompile("^\\/v2\\/(.*\\/(tags|manifests|blobs)\\/.*|_catalog$)") func generateDockerv2URI(path string, rec record) (string, int) { if path != "" { regexType := DockerRegex.FindAllStringSubmatch(path, -1)[0] pathRegex, err := regexp.Compile(dockerRegexs[regexType[len(regexType)-1]]) if err != nil { panic(err) } pathSubmatches := pathRegex.FindAllStringSubmatch(path, -1) pathSlice := pathSubmatches[0][1:] uri := rec.To for i, v := range pathSlice { uri = strings.Replace(uri, fmt.Sprintf("$%d", i+1), v, -1) } return uri, rec.Code } return rec.To, rec.Code }
Reorder imports in alphabetical order
import graphqlapi.utils as utils from graphqlapi.exceptions import RequestException from graphqlapi.interceptor import ExecuteBatch, TestDataSource from graphql.parser import GraphQLParser interceptors = [ ExecuteBatch(), TestDataSource() ] def proxy_request(payload: dict): graphql_ast = parse_query(payload['query']) # Execute request on GraphQL API status, data = utils.execute_graphql_request(payload['query']) for interceptor in interceptors: if interceptor.can_handle(graphql_ast): data = interceptor.after_request(graphql_ast, status, data) return 200 if status == 200 else 500, data def parse_query(payload_query: str): try: return GraphQLParser().parse(payload_query) except Exception: raise RequestException(400, 'Invalid GraphQL query')
import graphqlapi.utils as utils from graphql.parser import GraphQLParser from graphqlapi.interceptor import ExecuteBatch, TestDataSource from graphqlapi.exceptions import RequestException interceptors = [ ExecuteBatch(), TestDataSource() ] def proxy_request(payload: dict): graphql_ast = parse_query(payload['query']) # Execute request on GraphQL API status, data = utils.execute_graphql_request(payload['query']) for interceptor in interceptors: if interceptor.can_handle(graphql_ast): data = interceptor.after_request(graphql_ast, status, data) return 200 if status == 200 else 500, data def parse_query(payload_query: str): try: return GraphQLParser().parse(payload_query) except Exception: raise RequestException(400, 'Invalid GraphQL query')
Use https for s3 links
<?php /* * This file is part of flagrow/upload. * * Copyright (c) Flagrow. * * http://flagrow.github.io * * For the full copyright and license information, please view the license.md * file that was distributed with this source code. */ namespace Flagrow\Upload\Adapters; use Flagrow\Upload\Contracts\UploadAdapter; use Flagrow\Upload\File; use Illuminate\Support\Arr; class AwsS3 extends Flysystem implements UploadAdapter { /** * @param File $file */ protected function generateUrl(File $file) { $region = $this->adapter->getClient()->getRegion(); $bucket = $this->adapter->getBucket(); $baseUrl = in_array($region, [null, 'us-east-1']) ? sprintf('https://%s.s3-website-us-east-1.amazonaws.com/', $bucket) : sprintf('https://%s.s3-website-%s.amazonaws.com/', $bucket, $region); $file->url = sprintf( $baseUrl . '%s', Arr::get($this->meta, 'path', $file->path) ); } }
<?php /* * This file is part of flagrow/upload. * * Copyright (c) Flagrow. * * http://flagrow.github.io * * For the full copyright and license information, please view the license.md * file that was distributed with this source code. */ namespace Flagrow\Upload\Adapters; use Flagrow\Upload\Contracts\UploadAdapter; use Flagrow\Upload\File; use Illuminate\Support\Arr; class AwsS3 extends Flysystem implements UploadAdapter { /** * @param File $file */ protected function generateUrl(File $file) { $region = $this->adapter->getClient()->getRegion(); $bucket = $this->adapter->getBucket(); $baseUrl = in_array($region, [null, 'us-east-1']) ? sprintf('http://%s.s3-website-us-east-1.amazonaws.com/', $bucket) : sprintf('http://%s.s3-website-%s.amazonaws.com/', $bucket, $region); $file->url = sprintf( $baseUrl . '%s', Arr::get($this->meta, 'path', $file->path) ); } }
Move promisified functions out of the actual function that uses them.
import fs from 'fs'; import path from 'path'; import promisify from 'es6-promisify'; import { InvalidFile, InvalidJsonString } from './errors'; const fileReadPromise = promisify(fs.readFile); const fileWritePromise = promisify(fs.writeFile); export function convertOneFile(fileName, destFileName) { const readFile = fileReadPromise(fileName) .catch(reason => {throw new InvalidFile(reason.path)}); const minify = fileContent => minifyJson(fileContent) .catch(() => {throw new InvalidJsonString()}); const writeFile = minifiedJson => fileWritePromise(destFileName, minifiedJson) .catch(reason => {throw new InvalidFile(reason.path)}); return readFile .then(minify) .then(writeFile); } const minifyJson = content => new Promise((resolve, reject) => { try { resolve(JSON.stringify(JSON.parse(content))); } catch (e) { reject(e); } });
import fs from 'fs'; import path from 'path'; import promisify from 'es6-promisify'; import { InvalidFile, InvalidJsonString } from './errors'; export function convertOneFile(fileName, destFileName) { const fileReadPromise = promisify(fs.readFile); const fileWritePromise = promisify(fs.writeFile); const readFile = fileReadPromise(fileName) .catch(reason => {throw new InvalidFile(reason.path)}); const minify = fileContent => minifyJson(fileContent) .catch(() => {throw new InvalidJsonString()}); const writeFile = minifiedJson => fileWritePromise(destFileName, minifiedJson) .catch(reason => {throw new InvalidFile(reason.path)}); return readFile .then(minify) .then(writeFile); } const minifyJson = content => new Promise((resolve, reject) => { try { resolve(JSON.stringify(JSON.parse(content))); } catch (e) { reject(e); } });
Use submit button in demo app capture screen, works in old browsers
/* * * Run with node examples/simple.js * * Go to http://localhost:8282 and have fun! * */ var busterServer = require("../lib/buster-server"); var http = require("http"); var fs = require("fs"); var bs = Object.create(busterServer); var sess = bs.createSession({ load: ["/test.js"], resources: { "/test.js": { content: fs.readFileSync(__dirname + "/simple-browser.js", "utf8") } } }); http.createServer(function (req, res) { if (bs.respond(req, res)) return; if (req.method == "GET" && req.url == "/") { res.writeHead(200, {"Content-Type": "text/html"}); res.write('<form method="POST" action="/capture"><input type="submit" value="Capture"></form>'); res.end(); return; } if (req.method == "POST" && req.url == "/capture") { var client = bs.createClient(); res.writeHead(302, {"Location": client.url}); res.end(); return; } res.writeHead(404); res.end(); }).listen(8282);
/* * * Run with node examples/simple.js * * Go to http://localhost:8282 and have fun! * */ var busterServer = require("../lib/buster-server"); var http = require("http"); var fs = require("fs"); var bs = Object.create(busterServer); var sess = bs.createSession({ load: ["/test.js"], resources: { "/test.js": { content: fs.readFileSync(__dirname + "/simple-browser.js", "utf8") } } }); http.createServer(function (req, res) { if (bs.respond(req, res)) return; if (req.method == "GET" && req.url == "/") { res.writeHead(200, {"Content-Type": "text/html"}); res.write('<form method="POST" action="/capture"><button>Capture</button></form>'); res.end(); return; } if (req.method == "POST" && req.url == "/capture") { var client = bs.createClient(); res.writeHead(302, {"Location": client.url}); res.end(); return; } res.writeHead(404); res.end(); }).listen(8282);
Fix the depends argument of the C Extension
from setuptools import setup, Extension, find_packages from glob import glob from os import path import sys def version(): with open('src/iteration_utilities/__init__.py') as f: for line in f: if line.startswith('__version__'): return line.split(r"'")[1] _iteration_utilities_module = Extension( 'iteration_utilities._iteration_utilities', sources=[path.join('src', 'iteration_utilities', '_iteration_utilities', '_module.c')], depends=glob(path.join('src', 'iteration_utilities', '_iteration_utilities', '*.c')) ) setup( packages=find_packages('src'), package_dir={'': 'src'}, py_modules=[path.splitext(path.basename(p))[0] for p in glob('src/*.py')], version=version(), ext_modules=[_iteration_utilities_module], )
from setuptools import setup, Extension, find_packages from glob import glob from os import path import sys def version(): with open('src/iteration_utilities/__init__.py') as f: for line in f: if line.startswith('__version__'): return line.split(r"'")[1] _iteration_utilities_module = Extension( 'iteration_utilities._iteration_utilities', sources=[path.join('src', 'iteration_utilities', '_iteration_utilities', '_module.c')], depends=glob(path.join('src', '*.c')) ) setup( packages=find_packages('src'), package_dir={'': 'src'}, py_modules=[path.splitext(path.basename(p))[0] for p in glob('src/*.py')], version=version(), ext_modules=[_iteration_utilities_module], )
Fix ini_get() for boolean values
<?php namespace Gaufrette\Functional\Adapter; use Gaufrette\Adapter\Apc; use Gaufrette\Filesystem; class ApcTest extends FunctionalTestCase { public function setUp() { if (!extension_loaded('apc')) { return $this->markTestSkipped('The APC extension is not available.'); } elseif (!filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) || !filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) { return $this->markTestSkipped('The APC extension is available, but not enabled.'); } apc_clear_cache('user'); $this->filesystem = new Filesystem(new Apc('gaufrette-test.')); } public function tearDown() { parent::tearDown(); if (extension_loaded('apc')) { apc_clear_cache('user'); } } }
<?php namespace Gaufrette\Functional\Adapter; use Gaufrette\Adapter\Apc; use Gaufrette\Filesystem; class ApcTest extends FunctionalTestCase { public function setUp() { if (!extension_loaded('apc')) { return $this->markTestSkipped('The APC extension is not available.'); } elseif (!ini_get('apc.enabled') || !ini_get('apc.enable_cli')) { return $this->markTestSkipped('The APC extension is available, but not enabled.'); } apc_clear_cache('user'); $this->filesystem = new Filesystem(new Apc('gaufrette-test.')); } public function tearDown() { parent::tearDown(); if (extension_loaded('apc')) { apc_clear_cache('user'); } } }
Add wsgi_intercept to the dependencies list
#! /usr/bin/env python from setuptools import setup, find_packages setup( name='armet', version='0.3.0-pre', description='Clean and modern framework for creating RESTful APIs.', author='Concordus Applications', author_email='support@concordusapps.com', url='http://github.com/armet/python-armet', package_dir={'armet': 'src/armet'}, packages=find_packages('src'), install_requires=( 'six', # Python 2 and 3 normalization layer 'python-mimeparse' # For parsing accept and content-type headers ), extras_require={ 'test': ( 'nose', 'yanc', 'httplib2', 'flask', 'django', 'wsgi_intercept' ) } )
#! /usr/bin/env python from setuptools import setup, find_packages setup( name='armet', version='0.3.0-pre', description='Clean and modern framework for creating RESTful APIs.', author='Concordus Applications', author_email='support@concordusapps.com', url='http://github.com/armet/python-armet', package_dir={'armet': 'src/armet'}, packages=find_packages('src'), install_requires=( 'six', # Python 2 and 3 normalization layer 'python-mimeparse' # For parsing accept and content-type headers ), extras_require={ 'test': ( 'nose', 'yanc', 'httplib2', 'flask', 'django' ) } )
Use 0.3.3 hosts mgmt plugin because 0.3.4 is borked.
from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() execfile('substance/_version.py') install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts=0.3.3', 'jinja2'] setup(name='substance', version=__version__, author='turbulent/bbeausej', author_email='b@turbulent.ca', license='MIT', long_description=readme, description='substance - local dockerized development environment', install_requires=install_requires, packages=find_packages(), package_data={ 'substance': ['support/*'] }, test_suite='tests', zip_safe=False, include_package_data=True, entry_points={ 'console_scripts': [ 'substance = substance.cli:cli', 'subenv = substance.subenv.cli:cli' ], })
from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() execfile('substance/_version.py') install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts', 'jinja2'] setup(name='substance', version=__version__, author='turbulent/bbeausej', author_email='b@turbulent.ca', license='MIT', long_description=readme, description='substance - local dockerized development environment', install_requires=install_requires, packages=find_packages(), package_data={ 'substance': ['support/*'] }, test_suite='tests', zip_safe=False, include_package_data=True, entry_points={ 'console_scripts': [ 'substance = substance.cli:cli', 'subenv = substance.subenv.cli:cli' ], })
internal: Use ErrUnknownProvider in tests as well
package main import ( "reflect" "testing" ) func TestGetMetadataProvider(t *testing.T) { tests := []struct { desc string name string err error }{ { desc: "supported provider", name: "digitalocean", err: nil, }, { desc: "unknown provider", name: "not-supported", err: ErrUnknownProvider, }, { desc: "empty provider", name: "", err: ErrUnknownProvider, }, } for _, tt := range tests { _, err := getMetadataProvider(tt.name) if !reflect.DeepEqual(err, tt.err) { t.Errorf("%s:\nwant: %v\n got: %v", tt.desc, tt.err, err) } } }
package main import ( "errors" "reflect" "testing" ) func TestGetMetadataProvider(t *testing.T) { tests := []struct { desc string name string err error }{ { desc: "supported provider", name: "digitalocean", err: nil, }, { desc: "unknown provider", name: "not-supported", err: errors.New("unknown provider"), }, { desc: "empty provider", name: "", err: errors.New("unknown provider"), }, } for _, tt := range tests { _, err := getMetadataProvider(tt.name) if !reflect.DeepEqual(err, tt.err) { t.Errorf("%s:\nwant: %v\n got: %v", tt.desc, tt.err, err) } } }
Call Filter constructor to allow for common Filter options
var Filter = require('broccoli-filter') var coffeeScript = require('coffee-script') module.exports = CoffeeScriptFilter CoffeeScriptFilter.prototype = Object.create(Filter.prototype) CoffeeScriptFilter.prototype.constructor = CoffeeScriptFilter function CoffeeScriptFilter (inputTree, options) { if (!(this instanceof CoffeeScriptFilter)) return new CoffeeScriptFilter(inputTree, options) Filter.call(this, inputTree, options) this.bare = options && options.bare } CoffeeScriptFilter.prototype.extensions = ['coffee'] CoffeeScriptFilter.prototype.targetExtension = 'js' CoffeeScriptFilter.prototype.processString = function (string) { var coffeeScriptOptions = { bare: this.bare } try { return coffeeScript.compile(string, coffeeScriptOptions) } catch (err) { err.line = err.location && err.location.first_line err.column = err.location && err.location.first_column throw err } }
var Filter = require('broccoli-filter') module.exports = CoffeeScriptFilter CoffeeScriptFilter.prototype = Object.create(Filter.prototype) CoffeeScriptFilter.prototype.constructor = CoffeeScriptFilter function CoffeeScriptFilter (inputTree, options) { if (!(this instanceof CoffeeScriptFilter)) return new CoffeeScriptFilter(inputTree, options) this.inputTree = inputTree this.options = options || {} } CoffeeScriptFilter.prototype.extensions = ['coffee'] CoffeeScriptFilter.prototype.targetExtension = 'js' CoffeeScriptFilter.prototype.processString = function (string) { // We must be careful to create a fresh options hash every time. // https://github.com/jashkenas/coffee-script/issues/1924#issuecomment-28157026 var options = { bare: this.options.bare } try { return require('coffee-script').compile(string, options) } catch (err) { err.line = err.location && err.location.first_line err.column = err.location && err.location.first_column throw err } }
Use fork of trayhost, where needed functionality will be added.
package main import ( "fmt" "io/ioutil" "runtime" "github.com/shurcooL/trayhost" ) func main() { runtime.LockOSThread() menuItems := trayhost.MenuItems{ trayhost.MenuItem{ Title: "Instant Share", Handler: func() { fmt.Println("TODO: grab content, content-type of clipboard") fmt.Println("TODO: request URL") fmt.Println("TODO: display/put URL in clipboard") fmt.Println("TODO: upload image in background") }, }, trayhost.SeparatorMenuItem(), trayhost.MenuItem{ Title: "Quit", Handler: trayhost.Exit, }, } // TODO: Create a real icon and bake it into the binary. iconData, err := ioutil.ReadFile("./icon.png") if err != nil { panic(err) } trayhost.Initialize("InstantShare", iconData, menuItems) trayhost.EnterLoop() }
package main import ( "fmt" "io/ioutil" "runtime" "github.com/overlordtm/trayhost" ) // TODO: Factor into trayhost. func trayhost_NewSeparatorMenuItem() trayhost.MenuItem { return trayhost.MenuItem{Title: ""} } func main() { runtime.LockOSThread() menuItems := trayhost.MenuItems{ trayhost.MenuItem{ Title: "Instant Share", Handler: func() { fmt.Println("TODO: grab content, content-type of clipboard") fmt.Println("TODO: request URL") fmt.Println("TODO: display/put URL in clipboard") fmt.Println("TODO: upload image in background") }, }, trayhost_NewSeparatorMenuItem(), trayhost.MenuItem{ Title: "Quit", Handler: trayhost.Exit, }, } // TODO: Create a real icon and bake it into the binary. iconData, err := ioutil.ReadFile("./icon.png") if err != nil { panic(err) } trayhost.Initialize("InstantShare", iconData, menuItems) trayhost.EnterLoop() }
Allow user to set a different database
if (Meteor.isServer) { const _resetDatabase = function (options) { if (process.env.NODE_ENV !== 'development') { throw new Error( 'resetDatabase is not allowed outside of a development mode. ' + 'Aborting.' ); } options = options || {}; var excludedCollections = ['system.indexes']; if (options.excludedCollections) { excludedCollections = excludedCollections.concat(options.excludedCollections); } var db = options.db || MongoInternals.defaultRemoteCollectionDriver().mongo.db; var getCollections = Meteor.wrapAsync(db.collections, db); var collections = getCollections(); var appCollections = _.reject(collections, function (col) { return col.collectionName.indexOf('velocity') === 0 || excludedCollections.indexOf(col.collectionName) !== -1; }); _.each(appCollections, function (appCollection) { var remove = Meteor.wrapAsync(appCollection.remove, appCollection); remove({}, {}); }); }; Meteor.methods({ 'xolvio:cleaner/resetDatabase': function (options) { _resetDatabase(options); } }); resetDatabase = function(options, callback) { _resetDatabase(options); if (typeof callback === 'function') { callback(); } } } if (Meteor.isClient) { resetDatabase = function(options, callback) { Meteor.call('xolvio:cleaner/resetDatabase', options, callback); } }
if (Meteor.isServer) { const _resetDatabase = function (options) { if (process.env.NODE_ENV !== 'development') { throw new Error( 'resetDatabase is not allowed outside of a development mode. ' + 'Aborting.' ); } options = options || {}; var excludedCollections = ['system.indexes']; if (options.excludedCollections) { excludedCollections = excludedCollections.concat(options.excludedCollections); } var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db; var getCollections = Meteor.wrapAsync(db.collections, db); var collections = getCollections(); var appCollections = _.reject(collections, function (col) { return col.collectionName.indexOf('velocity') === 0 || excludedCollections.indexOf(col.collectionName) !== -1; }); _.each(appCollections, function (appCollection) { var remove = Meteor.wrapAsync(appCollection.remove, appCollection); remove({}, {}); }); }; Meteor.methods({ 'xolvio:cleaner/resetDatabase': function (options) { _resetDatabase(options); } }); resetDatabase = function(options, callback) { _resetDatabase(options); if (typeof callback === 'function') { callback(); } } } if (Meteor.isClient) { resetDatabase = function(options, callback) { Meteor.call('xolvio:cleaner/resetDatabase', options, callback); } }
Update quickjs installer per latest upstream changes Closes #87.
// Copyright 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the “License”); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // <https://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. 'use strict'; const path = require('path'); const unzip = require('../../shared/unzip.js'); const { Installer } = require('../../shared/installer.js'); const extract = ({ filePath, binary, os }) => { return new Promise(async (resolve, reject) => { const tmpPath = path.dirname(filePath); await unzip({ from: filePath, to: tmpPath, }); const installer = new Installer({ engine: binary, path: tmpPath, }); switch (os) { case 'linux64': { installer.installBinary({ 'qjs': binary }); break; } } resolve(); }); }; module.exports = extract;
// Copyright 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the “License”); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // <https://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. 'use strict'; const path = require('path'); const unzip = require('../../shared/unzip.js'); const { Installer } = require('../../shared/installer.js'); const extract = ({ filePath, binary, os }) => { return new Promise(async (resolve, reject) => { const tmpPath = path.dirname(filePath); await unzip({ from: filePath, to: tmpPath, }); const installer = new Installer({ engine: binary, path: tmpPath, }); switch (os) { case 'linux64': { installer.installBinary({ 'qjsbn': binary }); break; } } resolve(); }); }; module.exports = extract;
Use BorderBehavior instead of the deprecated MarkupComponentBorder git-svn-id: 5a74b5304d8e7e474561603514f78b697e5d94c4@1180802 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package org.apache.wicket.examples.forminput; import org.apache.wicket.markup.html.border.BorderBehavior; /** * Simple example to show how a border works. Adding this border to e.g. a label that displays 'x' * results in '[ x ]' being displayed. * * @author jcompagner */ public class BeforeAndAfterBorder extends BorderBehavior { }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package org.apache.wicket.examples.forminput; import org.apache.wicket.markup.html.border.MarkupComponentBorder; /** * Simple example to show how a border works. Adding this border to e.g. a label that displays 'x' * results in '[ x ]' being displayed. * * @author jcompagner */ public class BeforeAndAfterBorder extends MarkupComponentBorder { }
Remove unnecessary IE check for placeholder
var app = { Profiles: null }; // Let's namespace our app's functions in here. (function($) { $().ready(function() { $('html').removeClass('no-js').addClass('js'); // Return the current locale (found in the body attribute // as a data attribute). app.locale = $('body').data('locale'); // Return a localized URL. app.localeUrl = function(url) { return '/' + app.locale + '/' + url.toString(); }; // Apply language change once another language is selected $('#language').change(function() { $('#language-switcher').submit(); }); //Main nav dropdown $('a.dropdown-toggle').click(function() { $('.dropdown-menu').toggle(); $('i.icon-reorder').toggleClass('open'); }); $('input, textarea').placeholder(); }); })(jQuery);
var app = { Profiles: null }; // Let's namespace our app's functions in here. (function($) { $().ready(function() { $('html').removeClass('no-js').addClass('js'); // Return the current locale (found in the body attribute // as a data attribute). app.locale = $('body').data('locale'); // Return a localized URL. app.localeUrl = function(url) { return '/' + app.locale + '/' + url.toString(); }; // Apply language change once another language is selected $('#language').change(function() { $('#language-switcher').submit(); }); //Main nav dropdown $('a.dropdown-toggle').click(function() { $('.dropdown-menu').toggle(); $('i.icon-reorder').toggleClass('open'); }); if ($.browser.msie) { $('input, textarea').placeholder(); } }); })(jQuery);
Check against dir when copying assets Now a declaration like ```javascript { from: './extra', to: '.' } ``` will work as expected. Previously `from` expected to find a file in this case and failed as a result. This can be possibly cleaned up further.
'use strict'; var fs = require('fs'); var path = require('path'); var async = require('async'); var cpr = require('cpr'); var cp = require('cp'); exports.copyExtraAssets = function(buildDir, assets, cb) { assets = assets || []; async.forEach(assets, function(asset, cb) { var from = asset.from; var stats = fs.statSync(from); if(from.indexOf('./') === 0 && stats.isFile()) { cp(from, path.join(buildDir, asset.to, from), cb); } else { cpr(from, path.join(buildDir, asset.to), cb); } }, cb); }; exports.copyIfExists = function(from, to, cb) { fs.exists(from, function(exists) { if(exists) { cpr(from, to, cb); } else { cb(); } }); };
'use strict'; var fs = require('fs'); var path = require('path'); var async = require('async'); var cpr = require('cpr'); var cp = require('cp'); exports.copyExtraAssets = function(buildDir, assets, cb) { assets = assets || []; async.forEach(assets, function(asset, cb) { var from = asset.from; if(from.indexOf('./') === 0) { cp(from, path.join(buildDir, asset.to, from), cb); } else { cpr(from, path.join(buildDir, asset.to), cb); } }, cb); }; exports.copyIfExists = function(from, to, cb) { fs.exists(from, function(exists) { if(exists) { cpr(from, to, cb); } else { cb(); } }); };
Add model Sync to repo.
from peewee import SqliteDatabase, OperationalError __all__ = [ 'BaseDatabase', ] class BaseDatabase: """The base database class to be used with Peewee. """ def __init__(self, url=None): self.url = url self.db = SqliteDatabase(None) def initialize(self, url=None): if url is not None: self.url = url else: raise ValueError self.db.init(url) self._post_initialization() return self.db def _post_initialization(self): from paper_to_git.models import PaperDoc, PaperFolder, Sync self.db.connect() try: self.db.create_tables([PaperDoc, PaperFolder, Sync]) except OperationalError: # The database already exists. pass
from peewee import SqliteDatabase, OperationalError __all__ = [ 'BaseDatabase', ] class BaseDatabase: """The base database class to be used with Peewee. """ def __init__(self, url=None): self.url = url self.db = SqliteDatabase(None) def initialize(self, url=None): if url is not None: self.url = url else: raise ValueError self.db.init(url) self._post_initialization() return self.db def _post_initialization(self): from paper_to_git.models import PaperDoc, PaperFolder self.db.connect() try: self.db.create_tables([PaperDoc, PaperFolder]) except OperationalError: # The database already exists. pass
Update mock requirement from <2.1,>=2.0 to >=2.0,<3.1 Updates the requirements on [mock](https://github.com/testing-cabal/mock) to permit the latest version. - [Release notes](https://github.com/testing-cabal/mock/releases) - [Changelog](https://github.com/testing-cabal/mock/blob/master/CHANGELOG.rst) - [Commits](https://github.com/testing-cabal/mock/compare/2.0.0...3.0.2) Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.1.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.22', 'future>=0.16,<0.18', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<3.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.1.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.22', 'future>=0.16,<0.18', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<2.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
Change printing format of results
var valueEnv = new EnvGlobal(); var typeEnv = new EnvGlobal(); catchEvent(window, "load", setup); function setup(event) { setupEvents(event); document.getElementById("outputArea").value = "> "; } function setupEvents(event) { catchEvent(document.getElementById("inputForm"), "submit", evalForm) } function evalForm(event) { var theEvent = event ? event : window.event; var inputArea = document.getElementById("inputArea"); var outputArea = document.getElementById("outputArea"); var inputStr = inputArea.value; outputArea.value += inputStr + "\n" + eval(inputStr) + "\n> "; inputArea.value = ""; cancelEvent(theEvent); } function eval(str) { var result = ""; var stream = new Stream(str); var lexer = new Lexer(stream); var parser = new Parser(lexer); try { while (true) { var expr = parser.parse(); if (!expr) { break; } var type = expr.infer(typeEnv); var value = expr.eval(valueEnv); result += "- : " + type + " = " + value; } } catch (e) { alert(e); } return result; }
var valueEnv = new EnvGlobal(); var typeEnv = new EnvGlobal(); catchEvent(window, "load", setup); function setup(event) { setupEvents(event); document.getElementById("outputArea").value = "> "; } function setupEvents(event) { catchEvent(document.getElementById("inputForm"), "submit", evalForm) } function evalForm(event) { var theEvent = event ? event : window.event; var inputArea = document.getElementById("inputArea"); var outputArea = document.getElementById("outputArea"); var inputStr = inputArea.value; outputArea.value += inputStr + "\n" + eval(inputStr) + "\n> "; inputArea.value = ""; cancelEvent(theEvent); } function eval(str) { var result = ""; var stream = new Stream(str); var lexer = new Lexer(stream); var parser = new Parser(lexer); try { while (true) { var expr = parser.parse(); if (!expr) { break; } var type = expr.infer(typeEnv); var value = expr.eval(valueEnv); result += value + " : " + type + " " } } catch (e) { alert(e); } return result; }
Fix typo in comment (reported on the pydotorg mailing list).
# Import smtplib for the actual sending function import smtplib # Here are the email package modules we'll need from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart COMMASPACE = ', ' # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'Our family reunion' # me == the sender's email address # family = the list of all recipients' email addresses msg['From'] = me msg['To'] = COMMASPACE.join(family) msg.preamble = 'Our family reunion' # Guarantees the message ends in a newline msg.epilogue = '' # Assume we know that the image files are all in PNG format for file in pngfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. fp = open(file, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP() s.connect() s.sendmail(me, family, msg.as_string()) s.close()
# Import smtplib for the actual sending function import smtplib # Here are the email pacakge modules we'll need from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart COMMASPACE = ', ' # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = 'Our family reunion' # me == the sender's email address # family = the list of all recipients' email addresses msg['From'] = me msg['To'] = COMMASPACE.join(family) msg.preamble = 'Our family reunion' # Guarantees the message ends in a newline msg.epilogue = '' # Assume we know that the image files are all in PNG format for file in pngfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. fp = open(file, 'rb') img = MIMEImage(fp.read()) fp.close() msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP() s.connect() s.sendmail(me, family, msg.as_string()) s.close()
Add broccoli-sass as a dependency
'use strict'; module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addPackagesToProject([ { name: 'liquid-fire', target: '0.17.1' }, { name: 'ember-rl-dropdown', target: 'git+https://git@github.com/alphasights/ember-rl-dropdown.git' }, { name: 'ember-cli-tooltipster', target: '0.0.6' } ]).then(function() { return this.addBowerPackagesToProject([ { name: 'paint', target: '0.6.10' }, { name: 'spinjs', target: '2.0.1' }, { name: 'tooltipster', target: '3.3.0' }, { name: 'broccoli-sass', target: '0.4.0' } ]).then(function() { return this.insertIntoFile('.jshintrc', ' "Spinner",', { after: '"predef": [\n' } ); }.bind(this)); }.bind(this)); } }
'use strict'; module.exports = { normalizeEntityName: function() {}, afterInstall: function() { return this.addPackagesToProject([ { name: 'liquid-fire', target: '0.17.1' }, { name: 'ember-rl-dropdown', target: 'git+https://git@github.com/alphasights/ember-rl-dropdown.git' }, { name: 'ember-cli-tooltipster', target: '0.0.6' } ]).then(function() { return this.addBowerPackagesToProject([ { name: 'paint', target: '0.6.10' }, { name: 'spinjs', target: '2.0.1' }, { name: 'tooltipster', target: '3.3.0' } ]).then(function() { return this.insertIntoFile('.jshintrc', ' "Spinner",', { after: '"predef": [\n' } ); }.bind(this)); }.bind(this)); } }
Disable spellcheck/auto correct as there are platform issues with it
/* * Copyright 2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([], function () { "use strict"; function displayPromotions() { return true; } function requestParams(queryModel, infiniteScroll) { return { text: queryModel.get('queryText'), auto_correct: false }; } function validateQuery(queryModel) { return queryModel.get('queryText'); } function waitForIndexes(queryModel) { return _.isEmpty(queryModel.get('indexes')); } return { colourboxGrouping: 'results', displayPromotions: displayPromotions, requestParams: requestParams, validateQuery: validateQuery, waitForIndexes: waitForIndexes } });
/* * Copyright 2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([], function () { "use strict"; function displayPromotions() { return true; } function requestParams(queryModel, infiniteScroll) { return { text: queryModel.get('queryText'), auto_correct: infiniteScroll ? false : queryModel.get('autoCorrect') }; } function validateQuery(queryModel) { return queryModel.get('queryText'); } function waitForIndexes(queryModel) { return _.isEmpty(queryModel.get('indexes')); } return { colourboxGrouping: 'results', displayPromotions: displayPromotions, requestParams: requestParams, validateQuery: validateQuery, waitForIndexes: waitForIndexes } });
Rewrite Vimeo to use the new scope selection system
import foauth.providers class Vimeo(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://vimeo.com/' docs_url = 'http://developer.vimeo.com/apis/advanced' category = 'Videos' # URLs to interact with the API request_token_url = 'https://vimeo.com/oauth/request_token' authorize_url = 'https://vimeo.com/oauth/authorize' access_token_url = 'https://vimeo.com/oauth/access_token' api_domain = 'vimeo.com' available_permissions = [ (None, 'access your videos'), ('write', 'access, update and like videos'), ('delete', 'access, update, like and delete videos'), ] permissions_widget = 'radio' def get_authorize_params(self, redirect_uri, scopes): params = super(Vimeo, self).get_authorize_params(redirect_uri, scopes) if any(scopes): params['permission'] = scopes[0] return params def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/rest/v2?method=vimeo.people.getInfo&format=json') return r.json[u'person'][u'id']
import foauth.providers class Vimeo(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://vimeo.com/' docs_url = 'http://developer.vimeo.com/apis/advanced' category = 'Videos' # URLs to interact with the API request_token_url = 'https://vimeo.com/oauth/request_token' authorize_url = 'https://vimeo.com/oauth/authorize?permission=delete' access_token_url = 'https://vimeo.com/oauth/access_token' api_domain = 'vimeo.com' available_permissions = [ ('read', 'access information about videos'), ('write', 'update and like videos'), ('delete', 'delete videos'), ] def get_user_id(self, key): r = self.api(key, self.api_domain, u'/api/rest/v2?method=vimeo.people.getInfo&format=json') return r.json[u'person'][u'id']
Add CLI arguments for printing AST and bytecode
package main import ( "flag" "fmt" "io/ioutil" "log" "runtime" ) func main() { runtime.GOMAXPROCS(2) // Flag initialization var printAST, printInst bool flag.BoolVar(&printAST, "ast", false, "Print abstract syntax tree structure") flag.BoolVar(&printInst, "bytecode", false, "Print comprehensive bytecode instructions") flag.Parse() if flag.NArg() != 1 { flag.Usage() log.Fatalf("FILE: the .rb file to execute") } file := flag.Args()[0] buffer, err := ioutil.ReadFile(file) if err != nil { log.Fatal(err) } p := &Leg{Buffer: string(buffer)} p.Init() if err := p.Parse(); err != nil { log.Fatal(err) } p.Execute() if printAST { Traverse(rootAST) } vm := initVM() vm.compile(rootAST) if printInst { printInstructions(vm.instList, true) } vm.executeBytecode(nil) } func printInstructions(inst []Instruction, blocks bool) { for _, v := range inst { fmt.Println(v) fmt.Print("\t") fmt.Println(v.obj) if v.inst_type == BC_PUTOBJ && v.obj.(*RObject).name == "RBlock" { printInstructions(v.obj.(*RObject).methods["def"].def, blocks) } } }
package main import ( "flag" // "fmt" "io/ioutil" "log" "runtime" ) func main() { runtime.GOMAXPROCS(2) flag.Parse() if flag.NArg() != 1 { flag.Usage() log.Fatalf("FILE: the .rb file to execute") } file := flag.Arg(0) buffer, err := ioutil.ReadFile(file) if err != nil { log.Fatal(err) } p := &Leg{Buffer: string(buffer)} p.Init() if err := p.Parse(); err != nil { log.Fatal(err) } p.Execute() // Traverse(rootAST) vm := initVM() vm.compile(rootAST) vm.executeBytecode() // fmt.Println("") // fmt.Println(len(vm.instList)) // for _, v := range vm.instList { // fmt.Println(v) // fmt.Print("\t") // fmt.Println(v.obj) // } }
Test identifier reader inside lexer test
package eparser import ( "testing" ) func TestLex(t *testing.T) { l := newLexer() res, errs := l.Lex("some_var123 **= (7 ** (3 + 4 - 2)) << 1.23 % 0.3") expected := []tokenType{ IDENT, POW_EQ, LPAREN, INT, POW, LPAREN, INT, ADD, INT, SUB, INT, RPAREN, RPAREN, LSH, FLOAT, REM, FLOAT, EOL, } if errs != nil { t.Error("lexer error(s) found") } for k, v := range res { if expected[k] != v.Type { t.Error("mismatched token") } } } func TestUTF8(t *testing.T) { if !isIdent('Å') || !isIdent('Ś') { t.Error("isIdent doesn't recognize unicode characters") } }
package eparser import ( "testing" ) func TestLex(t *testing.T) { l := newLexer() res, errs := l.Lex("a **= (7 ** (3 + 4 - 2)) << 1.23 % 0.3") expected := []tokenType{ IDENT, POW_EQ, LPAREN, INT, POW, LPAREN, INT, ADD, INT, SUB, INT, RPAREN, RPAREN, LSH, FLOAT, REM, FLOAT, EOL, } if errs != nil { t.Error("lexer error(s) found") } for k, v := range res { if expected[k] != v.Type { t.Error("mismatched token") } } } func TestUTF8(t *testing.T) { if !isIdent('Å') || !isIdent('Ś') { t.Error("isIdent doesn't recognize unicode characters") } }
Set ServiceProvider to be eagerly loaded (not deferred)
<?php namespace Felixkiss\UniqueWithValidator; use Illuminate\Support\ServiceProvider; use Illuminate\Validation\Factory; class UniqueWithValidatorServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('felixkiss/uniquewith-validator'); // Registering the validator extension with the validator factory $this->app['validator']->resolver(function($translator, $data, $rules, $messages) { // Set custom validation error messages $messages['unique_with'] = $translator->get('uniquewith-validator::validation.unique_with'); return new ValidatorExtension($translator, $data, $rules, $messages); }); } /** * Register the service provider. * * @return void */ public function register() { } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
<?php namespace Felixkiss\UniqueWithValidator; use Illuminate\Support\ServiceProvider; use Illuminate\Validation\Factory; class UniqueWithValidatorServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('felixkiss/uniquewith-validator'); // Registering the validator extension with the validator factory $this->app['validator']->resolver(function($translator, $data, $rules, $messages) { // Set custom validation error messages $messages['unique_with'] = $translator->get('uniquewith-validator::validation.unique_with'); return new ValidatorExtension($translator, $data, $rules, $messages); }); } /** * Register the service provider. * * @return void */ public function register() { } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
Remove space character from the replace function
<?php namespace Swis\LaravelFulltext; class TermBuilder { public static function terms($search){ $wildcards = config('laravel-fulltext.enable_wildcards'); // Remove every boolean operator (+, -, > <, ( ), ~, *, ", @distance) from the search query // else we will break the MySQL query. $search = preg_replace('/[+\-><\(\)~*\"@]+/', '', $search); $terms = collect(preg_split('/[\s,]+/', $search)); if($wildcards === true){ $terms->transform(function($term){ return $term. '*'; }); } return $terms; } }
<?php namespace Swis\LaravelFulltext; class TermBuilder { public static function terms($search){ $wildcards = config('laravel-fulltext.enable_wildcards'); // Remove every boolean operator (+, -, > <, ( ), ~, *, ", @distance) from the search query // else we will break the MySQL query. $search = preg_replace('/[+\-><\(\)~*\"@]+/', ' ', $search); $terms = collect(preg_split('/[\s,]+/', $search)); if($wildcards === true){ $terms->transform(function($term){ return $term. '*'; }); } return $terms; } }
Fix Trades Widget to count by isPositive rather than IRR
package name.abuchen.portfolio.ui.views.dashboard; import java.util.List; import com.ibm.icu.text.MessageFormat; import name.abuchen.portfolio.model.Dashboard.Widget; import name.abuchen.portfolio.snapshot.trades.Trade; import name.abuchen.portfolio.ui.views.trades.TradeDetailsView; import name.abuchen.portfolio.util.TextUtil; public class TradesWidget extends AbstractTradesWidget { public TradesWidget(Widget widget, DashboardData dashboardData) { super(widget, dashboardData); } @Override public void update(TradeDetailsView.Input input) { this.title.setText(TextUtil.tooltip(getWidget().getLabel())); List<Trade> trades = input.getTrades(); long positive = trades.stream().filter(t -> t.getProfitLoss().isPositive()).count(); String text = MessageFormat.format("{0} <green>↑{1}</green> <red>↓{2}</red>", //$NON-NLS-1$ trades.size(), positive, trades.size() - positive); this.indicator.setText(text); } }
package name.abuchen.portfolio.ui.views.dashboard; import java.util.List; import com.ibm.icu.text.MessageFormat; import name.abuchen.portfolio.model.Dashboard.Widget; import name.abuchen.portfolio.snapshot.trades.Trade; import name.abuchen.portfolio.ui.views.trades.TradeDetailsView; import name.abuchen.portfolio.util.TextUtil; public class TradesWidget extends AbstractTradesWidget { public TradesWidget(Widget widget, DashboardData dashboardData) { super(widget, dashboardData); } @Override public void update(TradeDetailsView.Input input) { this.title.setText(TextUtil.tooltip(getWidget().getLabel())); List<Trade> trades = input.getTrades(); long positive = trades.stream().filter(t -> t.getIRR() > 0).count(); String text = MessageFormat.format("{0} <green>↑{1}</green> <red>↓{2}</red>", //$NON-NLS-1$ trades.size(), positive, trades.size() - positive); this.indicator.setText(text); } }
Add second escape backslash to namespace strings
<?php namespace Gt\Dom; /** * Represents any web page loaded in the browser and serves as an entry point * into the web page's content, the DOM tree (including elements such as * <body> or <table>). */ class Document extends \DOMDocument { use LiveProperty, ParentNode; public function __construct($document = null) { parent::__construct("1.0", "utf-8"); $this->registerNodeClass("\\DOMNode", "\\Gt\\Dom\\Node"); $this->registerNodeClass("\\DOMElement", "\\Gt\\Dom\\Element"); $this->registerNodeClass("\\DOMAttr", "\\Gt\\Dom\\Attr"); $this->registerNodeClass("\\DOMDocumentFragment", "\\Gt\\Dom\\DocumentFragment"); $this->registerNodeClass("\\DOMDocumentType", "\\Gt\\Dom\\DocumentType"); $this->registerNodeClass("\\DOMCharacterData", "\\Gt\\Dom\\CharacterData"); $this->registerNodeClass("\\DOMText", "\\Gt\\Dom\\Text"); $this->registerNodeClass("\\DOMComment", "\\Gt\\Dom\\Comment"); if ($document instanceof \DOMDocument) { $this->appendChild($this->importNode($document->documentElement, true)); return; } } };
<?php namespace Gt\Dom; /** * Represents any web page loaded in the browser and serves as an entry point * into the web page's content, the DOM tree (including elements such as * <body> or <table>). */ class Document extends \DOMDocument { use LiveProperty, ParentNode; public function __construct($document = null) { parent::__construct("1.0", "utf-8"); $this->registerNodeClass("\DOMNode", "\Gt\Dom\Node"); $this->registerNodeClass("\DOMElement", "\Gt\Dom\Element"); $this->registerNodeClass("\DOMAttr", "\Gt\Dom\Attr"); $this->registerNodeClass("\DOMDocumentFragment", "\Gt\Dom\DocumentFragment"); $this->registerNodeClass("\DOMDocumentType", "\Gt\Dom\DocumentType"); $this->registerNodeClass("\DOMCharacterData", "\Gt\Dom\CharacterData"); $this->registerNodeClass("\DOMText", "\Gt\Dom\Text"); $this->registerNodeClass("\DOMComment", "\Gt\Dom\Comment"); if ($document instanceof \DOMDocument) { $this->appendChild($this->importNode($document->documentElement, true)); return; } } };
Allow the listener to be set to null
package com.markupartist.crimesweeper; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.MapView; import android.content.Context; import android.location.Location; import java.util.List; public class PlayerLocationOverlay extends MyLocationOverlay { private CrimeLocationHitListener listener; private List<CrimeSite> _crimeSites = null; public PlayerLocationOverlay(Context context, MapView mapView) { super(context, mapView); _crimeSites = CrimeSite.getCrimeSites(24 * 60); } public void setCrimeLocationHitListener(CrimeLocationHitListener listener) { this.listener = listener; } @Override public void onLocationChanged(Location location) { super.onLocationChanged(location); if(listener == null) { return; } for(CrimeSite crimeSite : _crimeSites) { if(crimeSite.intersectWithPlayer(location)) { listener.onCrimeLocationHit(crimeSite); } } } }
package com.markupartist.crimesweeper; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.MapView; import android.content.Context; import android.location.Location; import java.util.List; public class PlayerLocationOverlay extends MyLocationOverlay { private CrimeLocationHitListener listener; private List<CrimeSite> _crimeSites = null; public PlayerLocationOverlay(Context context, MapView mapView) { super(context, mapView); _crimeSites = CrimeSite.getCrimeSites(24 * 60); } public void setCrimeLocationHitListener(CrimeLocationHitListener listener) { this.listener = listener; } @Override public void onLocationChanged(Location location) { super.onLocationChanged(location); for(CrimeSite crimeSite : _crimeSites) { if(crimeSite.intersectWithPlayer(location)) { listener.onCrimeLocationHit(crimeSite); } } } }
Use proper description of what gets transferred Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net>
<?php namespace OCA\Deck\Command; use OCA\Deck\Service\BoardService; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; final class TransferOwnership extends Command { protected $boardService; public function __construct(BoardService $boardService) { parent::__construct(); $this->boardService = $boardService; } protected function configure() { $this ->setName('deck:transfer-ownership') ->setDescription('Change owner of deck boards') ->addArgument( 'owner', InputArgument::REQUIRED, 'Owner uid' ) ->addArgument( 'newOwner', InputArgument::REQUIRED, 'New owner uid' ); } protected function execute(InputInterface $input, OutputInterface $output) { $owner = $input->getArgument('owner'); $newOwner = $input->getArgument('newOwner'); $output->writeln("Transfer deck boards from $owner to $newOwner"); $this->boardService->transferOwnership($owner, $newOwner); $output->writeln("Transfer deck boards from $owner to $newOwner completed"); } }
<?php namespace OCA\Deck\Command; use OCA\Deck\Service\BoardService; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; final class TransferOwnership extends Command { protected $boardService; public function __construct(BoardService $boardService) { parent::__construct(); $this->boardService = $boardService; } protected function configure() { $this ->setName('deck:transfer-ownership') ->setDescription('Change owner of deck entities') ->addArgument( 'owner', InputArgument::REQUIRED, 'Owner uid' ) ->addArgument( 'newOwner', InputArgument::REQUIRED, 'New owner uid' ); } protected function execute(InputInterface $input, OutputInterface $output) { $owner = $input->getArgument('owner'); $newOwner = $input->getArgument('newOwner'); $output->writeln("Transfer deck entities from $owner to $newOwner"); $this->boardService->transferOwnership($owner, $newOwner); $output->writeln("Transfer deck entities from $owner to $newOwner completed"); } }
Make unit test more stable
package at.ac.tuwien.kr.alpha.common; import at.ac.tuwien.kr.alpha.grounder.parser.ProgramParser; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Copyright (c) 2018, the Alpha Team. */ public class RuleTest { private final ProgramParser parser = new ProgramParser(); @Test public void renameVariables() { String originalRule = "p(X,Y) :- a, f(Z) = 1, q(X,g(Y),Z), dom(A)."; Rule rule = parser.parse(originalRule).getRules().get(0); Rule renamedRule = rule.renameVariables("_13"); Rule expectedRenamedRule = parser.parse("p(X_13, Y_13) :- a, f(Z_13) = 1, q(X_13, g(Y_13), Z_13), dom(A_13).").getRules().get(0); assertEquals(expectedRenamedRule.toString(), renamedRule.toString()); // FIXME: Rule does not implement equals() } }
package at.ac.tuwien.kr.alpha.common; import at.ac.tuwien.kr.alpha.grounder.parser.ProgramParser; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Copyright (c) 2018, the Alpha Team. */ public class RuleTest { private final ProgramParser parser = new ProgramParser(); @Test public void renameVariables() { String originalRule = "p(X,Y) :- a, f(Z) = 1, q(X,g(Y),Z), dom(A)."; Rule rule = parser.parse(originalRule).getRules().get(0); Rule renamedRule = rule.renameVariables("_13"); // FIXME: below test is unstable, better check for real equality. assertEquals("p(X_13, Y_13) :- a, f(Z_13) = 1, q(X_13, g(Y_13), Z_13), dom(A_13).", renamedRule.toString()); } }
TEST use same amount of noise for frank wolfe test as for other test. Works now that C is scaled correctly :)
from numpy.testing import assert_array_equal from pystruct.models import GridCRF from pystruct.datasets import generate_blocks_multinomial from pystruct.learners import FrankWolfeSSVM def test_multinomial_blocks_frankwolfe(): X, Y = generate_blocks_multinomial(n_samples=50, noise=0.5, seed=0) crf = GridCRF(inference_method='qpbo') clf = FrankWolfeSSVM(model=crf, C=1, line_search=True, batch_mode=False, dual_check_every=500) clf.fit(X, Y) Y_pred = clf.predict(X) assert_array_equal(Y, Y_pred)
from numpy.testing import assert_array_equal from pystruct.models import GridCRF from pystruct.datasets import generate_blocks_multinomial from pystruct.learners import FrankWolfeSSVM def test_multinomial_blocks_frankwolfe(): X, Y = generate_blocks_multinomial(n_samples=50, noise=0.4, seed=0) crf = GridCRF(inference_method='qpbo') clf = FrankWolfeSSVM(model=crf, C=1, line_search=True, batch_mode=False, dual_check_every=500) clf.fit(X, Y) Y_pred = clf.predict(X) assert_array_equal(Y, Y_pred)
Fix deprecation warnings due to invalid escape sequences.
import six import sys import test_helper import unittest from authy import AuthyException from authy.api import AuthyApiClient from authy.api.resources import Tokens from authy.api.resources import Users class ApiClientTest(unittest.TestCase): def setUp(self): self.api = AuthyApiClient(test_helper.API_KEY, test_helper.API_URL) def test_tokens(self): self.assertIsInstance(self.api.tokens, Tokens) def test_users(self): self.assertIsInstance(self.api.users, Users) def test_version(self): if six.PY3: self.assertRegex(self.api.version(), r'\d.\d*') else: import re self.assertTrue(re.compile(r'\d.\d*').search(self.api.version())) if __name__ == "__main__": unittest.main()
import six import sys import test_helper import unittest from authy import AuthyException from authy.api import AuthyApiClient from authy.api.resources import Tokens from authy.api.resources import Users class ApiClientTest(unittest.TestCase): def setUp(self): self.api = AuthyApiClient(test_helper.API_KEY, test_helper.API_URL) def test_tokens(self): self.assertIsInstance(self.api.tokens, Tokens) def test_users(self): self.assertIsInstance(self.api.users, Users) def test_version(self): if six.PY3: self.assertRegex(self.api.version(), '\d.\d*') else: import re self.assertTrue(re.compile(r'\d.\d*').search(self.api.version())) if __name__ == "__main__": unittest.main()
Make the mobile menu available in "/mail/" Summary: Ref T13244. See <https://discourse.phabricator-community.org/t/left-hand-menu-not-responsive-on-mobile/2358>. Test Plan: {F6184160} Reviewers: amckinley Reviewed By: amckinley Maniphest Tasks: T13244 Differential Revision: https://secure.phabricator.com/D20093
<?php final class PhabricatorMetaMTAMailListController extends PhabricatorMetaMTAController { public function handleRequest(AphrontRequest $request) { $controller = id(new PhabricatorApplicationSearchController()) ->setQueryKey($request->getURIData('queryKey')) ->setSearchEngine(new PhabricatorMetaMTAMailSearchEngine()) ->setNavigation($this->buildSideNav()); return $this->delegateToController($controller); } public function buildSideNav() { $user = $this->getRequest()->getUser(); $nav = new AphrontSideNavFilterView(); $nav->setBaseURI(new PhutilURI($this->getApplicationURI())); id(new PhabricatorMetaMTAMailSearchEngine()) ->setViewer($user) ->addNavigationItems($nav->getMenu()); $nav->selectFilter(null); return $nav; } public function buildApplicationMenu() { return $this->buildSideNav()->getMenu(); } }
<?php final class PhabricatorMetaMTAMailListController extends PhabricatorMetaMTAController { public function handleRequest(AphrontRequest $request) { $controller = id(new PhabricatorApplicationSearchController()) ->setQueryKey($request->getURIData('queryKey')) ->setSearchEngine(new PhabricatorMetaMTAMailSearchEngine()) ->setNavigation($this->buildSideNav()); return $this->delegateToController($controller); } public function buildSideNav() { $user = $this->getRequest()->getUser(); $nav = new AphrontSideNavFilterView(); $nav->setBaseURI(new PhutilURI($this->getApplicationURI())); id(new PhabricatorMetaMTAMailSearchEngine()) ->setViewer($user) ->addNavigationItems($nav->getMenu()); $nav->selectFilter(null); return $nav; } }
Fix logic in any logic filter
package in.twizmwaz.cardinal.module.modules.filter.type.logic; import in.twizmwaz.cardinal.module.ModuleCollection; import in.twizmwaz.cardinal.module.modules.filter.FilterModule; import in.twizmwaz.cardinal.module.modules.filter.FilterState; import static in.twizmwaz.cardinal.module.modules.filter.FilterState.ALLOW; import static in.twizmwaz.cardinal.module.modules.filter.FilterState.DENY; public class AnyFilter extends FilterModule { private final ModuleCollection<FilterModule> children; public AnyFilter(final String name, final ModuleCollection<FilterModule> children) { super(name); this.children = children; } @Override public FilterState evaluate(final Object object) { for (FilterModule child : children) { if (child.evaluate(object).equals(ALLOW)) return ALLOW; } return DENY; } }
package in.twizmwaz.cardinal.module.modules.filter.type.logic; import in.twizmwaz.cardinal.module.ModuleCollection; import in.twizmwaz.cardinal.module.modules.filter.FilterModule; import in.twizmwaz.cardinal.module.modules.filter.FilterState; import static in.twizmwaz.cardinal.module.modules.filter.FilterState.ALLOW; public class AnyFilter extends FilterModule { private final ModuleCollection<FilterModule> children; public AnyFilter(final String name, final ModuleCollection<FilterModule> children) { super(name); this.children = children; } @Override public FilterState evaluate(final Object object) { for (FilterModule child : children) { if (child.evaluate(object).equals(ALLOW)) return ALLOW; } return ALLOW; } }
Define WP_ADMIN before loading WordPress ... where "loading WordPress" also includes loading plugins and themes. Also, define WP_NETWORK_ADMIN and WP_USER_ADMIN, for completeness. see #385
<?php // Can be used by plugins/themes to check if wp-cli is running or not define( 'WP_CLI', true ); define( 'WP_CLI_VERSION', '0.10.0-alpha' ); include WP_CLI_ROOT . 'utils.php'; include WP_CLI_ROOT . 'dispatcher.php'; include WP_CLI_ROOT . 'class-wp-cli.php'; include WP_CLI_ROOT . 'class-wp-cli-command.php'; include WP_CLI_ROOT . 'man.php'; \WP_CLI\Utils\load_dependencies(); WP_CLI::init(); WP_CLI::$runner->before_wp_load(); // Load wp-config.php code, in the global scope eval( WP_CLI::$runner->get_wp_config_code() ); WP_CLI::$runner->after_wp_config_load(); // Simulate a /wp-admin/ page load $_SERVER['PHP_SELF'] = '/wp-admin/index.php'; define( 'WP_ADMIN', true ); define( 'WP_NETWORK_ADMIN', false ); define( 'WP_USER_ADMIN', false ); // Load Core, mu-plugins, plugins, themes etc. require WP_CLI_ROOT . 'wp-settings-cli.php'; // Fix memory limit. See http://core.trac.wordpress.org/ticket/14889 @ini_set( 'memory_limit', -1 ); require ABSPATH . 'wp-admin/includes/admin.php'; do_action( 'admin_init' ); WP_CLI::$runner->after_wp_load();
<?php // Can be used by plugins/themes to check if wp-cli is running or not define( 'WP_CLI', true ); define( 'WP_CLI_VERSION', '0.10.0-alpha' ); include WP_CLI_ROOT . 'utils.php'; include WP_CLI_ROOT . 'dispatcher.php'; include WP_CLI_ROOT . 'class-wp-cli.php'; include WP_CLI_ROOT . 'class-wp-cli-command.php'; include WP_CLI_ROOT . 'man.php'; \WP_CLI\Utils\load_dependencies(); WP_CLI::init(); WP_CLI::$runner->before_wp_load(); // Load wp-config.php code, in the global scope eval( WP_CLI::$runner->get_wp_config_code() ); WP_CLI::$runner->after_wp_config_load(); // Load main WordPress code, in the global scope require WP_CLI_ROOT . 'wp-settings-cli.php'; // Fix memory limit. See http://core.trac.wordpress.org/ticket/14889 @ini_set( 'memory_limit', -1 ); // Simulate a /wp-admin/ page load $_SERVER['PHP_SELF'] = '/wp-admin/index.php'; define( 'WP_ADMIN', true ); require ABSPATH . 'wp-admin/includes/admin.php'; do_action( 'admin_init' ); WP_CLI::$runner->after_wp_load();
Set celery to ignore results
import os import logging from celery import Celery from temp_config.set_environment import DeployEnv runtime_env = DeployEnv() runtime_env.load_deployment_environment() redis_server = os.environ.get('REDIS_HOSTNAME') redis_port = os.environ.get('REDIS_PORT') celery_tasks = [ 'hms_flask.modules.hms_controller', 'pram_flask.tasks' ] redis = 'redis://' + redis_server + ':' + redis_port + '/0' logging.info("Celery connecting to redis server: " + redis) celery = Celery('flask_qed', broker=redis, backend=redis, include=celery_tasks) celery.conf.update( CELERY_ACCEPT_CONTENT=['json'], CELERY_TASK_SERIALIZER='json', CELERY_RESULT_SERIALIZER='json', CELERY_IGNORE_RESULT=True, CELERY_TRACK_STARTED=True, )
import os import logging from celery import Celery from temp_config.set_environment import DeployEnv runtime_env = DeployEnv() runtime_env.load_deployment_environment() redis_server = os.environ.get('REDIS_HOSTNAME') redis_port = os.environ.get('REDIS_PORT') celery_tasks = [ 'hms_flask.modules.hms_controller', 'pram_flask.tasks' ] redis = 'redis://' + redis_server + ':' + redis_port + '/0' logging.info("Celery connecting to redis server: " + redis) celery = Celery('flask_qed', broker=redis, backend=redis, include=celery_tasks) celery.conf.update( CELERY_ACCEPT_CONTENT=['json'], CELERY_TASK_SERIALIZER='json', CELERY_RESULT_SERIALIZER='json', CELERY_IGNORE_RESULT=False, CELERY_TRACK_STARTED=True, )
Return 1 in gulp when the build failed
'use strict'; var source = require('vinyl-source-stream') var streamify = require('gulp-streamify') var browserify = require('browserify') var babelify = require('babelify') var uglify = require('gulp-uglify') var rename = require('gulp-rename') var gulp = require('gulp') var del = require('del') var exitStatus = 0; process.on('exit', function () { if (exitStatus !== 0) { process.exit(exitStatus); } }); var paths = { scripts: ['src/**.js'] }; gulp.task('clean', function() { return del(['build']); }); gulp.task('default', ['clean'], function() { return browserify('./src/index.js') .transform('babelify') .bundle() .on('error', function (err) { exitStatus = 1; console.log(err.toString()); this.emit('end'); }) .pipe(source('index.js')) .pipe(rename('yaje.js')) .pipe(gulp.dest('build')) .pipe(streamify(uglify())) .pipe(rename('yaje.min.js')) .pipe(gulp.dest('build')) }); gulp.task('watch', function() { gulp.watch(paths.scripts, ['default']); });
'use strict'; var source = require('vinyl-source-stream') var streamify = require('gulp-streamify') var browserify = require('browserify') var babelify = require('babelify') var uglify = require('gulp-uglify') var rename = require('gulp-rename') var gulp = require('gulp') var del = require('del') var paths = { scripts: ['src/**.js'] }; gulp.task('clean', function() { return del(['build']); }); gulp.task('default', ['clean'], function() { return browserify('./src/index.js') .transform('babelify') .bundle() .on('error', function (err) { console.log(err.toString()); this.emit('end'); }) .pipe(source('index.js')) .pipe(rename('yaje.js')) .pipe(gulp.dest('build')) .pipe(streamify(uglify())) .pipe(rename('yaje.min.js')) .pipe(gulp.dest('build')) }); gulp.task('watch', function() { gulp.watch(paths.scripts, ['default']); });
Refactor JS To have Reusuable Functions
$(document).ready( function () { $('#signup').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#signup_modal').show(); }); $('#screen_block').click(function(event){ event.preventDefault(); clear_modals(); }); $('#login').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#login_modal').show(); }); $('.new_question_button').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#new_question_modal').show(); }); $('form#new_question').submit(function(event){ event.preventDefault(); $.ajax({ url: '/questions', type: 'POST', data: $('form#new_question').serialize(), dataType: 'JSON', }).done(function(data){ $('ol.thumb-grid').load('/ .thumb-grid') clear_modals(); }).fail(function(data){ console.log(data); }); }); }); function clear_modals(){ $('#screen_block').hide(); $('#login_modal').hide(); $('#signup_modal').hide(); $('#new_question_modal').hide(); }
$(document).ready( function () { $('#signup').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#signup_modal').show(); }); $('#screen_block').click(function(event){ event.preventDefault(); $('#screen_block').hide(); $('#login_modal').hide(); $('#signup_modal').hide(); $('#new_question_modal').hide(); }); $('#login').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#login_modal').show(); }); $('.new_question_button').click(function(event){ event.preventDefault(); $('#screen_block').show(); $('#new_question_modal').show(); }); $('form#new_question').submit(function(event){ event.preventDefault(); $.ajax({ url: '/questions', type: 'POST', data: $('form#new_question').serialize(), dataType: 'JSON', }).done(function(data){ $('ol.thumb-grid').load('/ .thumb-grid') clear_modals(); }).fail(function(data){ console.log(data); }); }); }); function clear_modals(){ $('#screen_block').hide(); $('#login_modal').hide(); $('#signup_modal').hide(); $('#new_question_modal').hide(); }