text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Replace file_io usage with open
from Crypto.Cipher import AES import os from settings import * def get_cipher(iv, text): try: with open(KEY_FILE, 'rt') as f: key = f.read().strip() except IOError: key = input(text) return AES.new(key, AES.MODE_CBC, iv) def encrypt(bytes): iv = os.urandom(16) c = get_cipher(iv, "Please enter an encryption key: ") return (iv, c.encrypt(bytes)) def decrypt(): with open(ENCRYPTED_FILE, 'rb') as f: bytes = f.read() c = get_cipher(bytes[:16], "Please enter the decryption key: ") return c.decrypt(bytes[16:]).strip(b'\x04') def multiple_of(bytes, length): if len(bytes) % length == 0: return bytes else: return bytes + (EOT_CHAR * (length - (len(bytes) % length)))
from Crypto.Cipher import AES import os from file_io import * from settings import * def get_cipher(iv, text): try: key = read_file(KEY_FILE, 'rt').strip() except IOError: key = input(text) return AES.new(key, AES.MODE_CBC, iv) def encrypt(bytes): iv = os.urandom(16) c = get_cipher(iv, "Please enter an encryption key: ") return (iv, c.encrypt(bytes)) def decrypt(): bytes = read_file(ENCRYPTED_FILE, 'rb') c = get_cipher(bytes[:16], "Please enter the decryption key: ") return c.decrypt(bytes[16:]).strip(b'\x04') def multiple_of(bytes, length): if len(bytes) % length == 0: return bytes else: return bytes + (EOT_CHAR * (length - (len(bytes) % length)))
Make IRC message delay configurable
""" byceps.util.irc ~~~~~~~~~~~~~~~ Send IRC messages to a bot via HTTP. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_ENABLED = False DEFAULT_DELAY_IN_SECONDS = 2 DEFAULT_TEXT_PREFIX = '[BYCEPS] ' def send_message(channels: List[str], text: str) -> None: """Write the text to the channels by sending it to the bot via HTTP.""" enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED) if not enabled: current_app.logger.warning('Announcements on IRC are disabled.') return text_prefix = current_app.config.get( 'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX ) text = text_prefix + text url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL) data = {'channels': channels, 'text': text} # Delay a bit as an attempt to avoid getting kicked from server # because of flooding. delay = int( current_app.config.get('ANNOUNCE_IRC_DELAY', DEFAULT_DELAY_IN_SECONDS) ) sleep(delay) requests.post(url, json=data) # Ignore response code for now.
""" byceps.util.irc ~~~~~~~~~~~~~~~ Send IRC messages to a bot via HTTP. :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from time import sleep from typing import List from flask import current_app import requests DEFAULT_BOT_URL = 'http://127.0.0.1:12345/' DEFAULT_ENABLED = False DELAY_IN_SECONDS = 2 DEFAULT_TEXT_PREFIX = '[BYCEPS] ' def send_message(channels: List[str], text: str) -> None: """Write the text to the channels by sending it to the bot via HTTP.""" enabled = current_app.config.get('ANNOUNCE_IRC_ENABLED', DEFAULT_ENABLED) if not enabled: current_app.logger.warning('Announcements on IRC are disabled.') return text_prefix = current_app.config.get( 'ANNOUNCE_IRC_TEXT_PREFIX', DEFAULT_TEXT_PREFIX ) text = text_prefix + text url = current_app.config.get('IRC_BOT_URL', DEFAULT_BOT_URL) data = {'channels': channels, 'text': text} # Delay a bit as an attempt to avoid getting kicked from server # because of flooding. sleep(DELAY_IN_SECONDS) requests.post(url, json=data) # Ignore response code for now.
Fix typos in EmployeeE projection
import DS from 'ember-data'; import ProjectedModel from './projected-model'; import Proj from '../utils/projection-attributes'; var Model = ProjectedModel.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), birthDate: DS.attr('date'), employee1: DS.belongsTo('employee', { inverse: null, async: false }), orders: DS.hasMany('order', { inverse: null, async: false }), // Validation rules. validations: { firstName: { presence: true, length: { minimum: 5 } }, lastName: { presence: true, length: { minimum: 5 } } } }); Model.defineProjection('EmployeeE', 'employee', { firstName: Proj.attr('First Name'), lastName: Proj.attr('Last Name'), birthDate: Proj.attr('Birth Date'), employee1: Proj.belongsTo('employee', { firstName: Proj.attr('Reports To - First Name'), lastName: Proj.attr('Reports To - Last Name', { hidden: true }) }), orders: Proj.hasMany('order', { shipName: Proj.attr('Ship Name'), shipCountry: Proj.attr('Ship Country'), orderDate: Proj.attr('Order Date') }) }); Model.defineProjection('EmployeeL', 'employee', { firstName: Proj.attr('First Name'), lastName: Proj.attr('Last Name') }); export default Model;
import DS from 'ember-data'; import ProjectedModel from './projected-model'; import Proj from '../utils/projection-attributes'; var Model = ProjectedModel.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), birthDate: DS.attr('date'), employee1: DS.belongsTo('employee', { inverse: null, async: false }), orders: DS.hasMany('order', { inverse: null, async: false }), // Validation rules. validations: { firstName: { presence: true, length: { minimum: 5 } }, lastName: { presence: true, length: { minimum: 5 } } } }); Model.defineProjection('EmployeeE', 'employee', { firstName: Proj.attr('First Name'), lastName: Proj.attr('Last Name'), birthDate: Proj.attr('Birth Date'), employee1: Proj.belongsTo('employee', { firstName: Proj.attr('Reports To - First Name'), lastName: Proj.attr('Reports To - Last Name', { hidden: true }) }), orders: Proj.hasMany('order', { shipName: Proj.attr('Ship Name'), ShipCountry: Proj.attr('Ship Country'), OrderDate: Proj.attr('Order Date') }) }); Model.defineProjection('EmployeeL', 'employee', { firstName: Proj.attr('First Name'), lastName: Proj.attr('Last Name') }); export default Model;
Fix broken spec, add new for CoreBundle state machine callbacks Some additional CS fixes
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Payment\Model; use Doctrine\Common\Collections\Collection; interface PaymentsSubjectInterface { /** * Get all payments associated with the payment subject. * * @return Collection|PaymentInterface[] */ public function getPayments(); /** * Check if order has any payments * * @return bool */ public function hasPayments(); /** * Add a payment. * * @param PaymentInterface $payment */ public function addPayment(PaymentInterface $payment); /** * Remove a payment. * * @param PaymentInterface $payment */ public function removePayment(PaymentInterface $payment); /** * Check if the payment subject has certain payment. * * @param PaymentInterface $payment * * @return bool */ public function hasPayment(PaymentInterface $payment); }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Payment\Model; use Doctrine\Common\Collections\Collection; interface PaymentsSubjectInterface { /** * Get all payments associated with the payment subject. * * @return Collection|PaymentInterface[] */ public function getPayments(); /** * Check if order has any payments * * @return bool */ public function hasPayments(); /** * Add a payment. * * @param PaymentInterface $payment */ public function addPayment(PaymentInterface $payment); /** * Remove a payment. * * @param PaymentInterface $payment */ public function removePayment(PaymentInterface $payment); /** * Check if the payment subject has certain payment. * * @param PaymentInterface $payment * * @return bool */ public function hasPayment(PaymentInterface $payment); }
Make sure wrappedObject is not null before making a method call on it
<?php namespace PhpSpec\Wrapper\Subject\Expectation; use Exception; use PhpSpec\Exception\Example\ErrorException; use PhpSpec\Util\Instantiator; use PhpSpec\Wrapper\Subject\WrappedObject; class ConstructorDecorator extends Decorator implements ExpectationInterface { public function __construct(ExpectationInterface $expectation) { $this->setExpectation($expectation); } public function match($alias, $subject, array $arguments = array(), WrappedObject $wrappedObject = null) { try { $wrapped = $subject->getWrappedObject(); } catch (ErrorException $e) { throw $e; } catch (Exception $e) { if (null !== $wrappedObject && $wrappedObject->getClassName()) { $instantiator = new Instantiator(); $wrapped = $instantiator->instantiate($wrappedObject->getClassName()); } } return $this->getExpectation()->match($alias, $wrapped, $arguments); } }
<?php namespace PhpSpec\Wrapper\Subject\Expectation; use Exception; use PhpSpec\Exception\Example\ErrorException; use PhpSpec\Util\Instantiator; use PhpSpec\Wrapper\Subject\WrappedObject; class ConstructorDecorator extends Decorator implements ExpectationInterface { public function __construct(ExpectationInterface $expectation) { $this->setExpectation($expectation); } public function match($alias, $subject, array $arguments = array(), WrappedObject $wrappedObject = null) { try { $wrapped = $subject->getWrappedObject(); } catch (ErrorException $e) { throw $e; } catch (Exception $e) { if ($wrappedObject->getClassName()) { $instantiator = new Instantiator(); $wrapped = $instantiator->instantiate($wrappedObject->getClassName()); } } return $this->getExpectation()->match($alias, $wrapped, $arguments); } }
Add @since to class Javadoc
package com.github.ferstl.jarscan; import org.adoptopenjdk.jitwatch.jarscan.IJarScanOperation; import org.adoptopenjdk.jitwatch.jarscan.freqinlinesize.FreqInlineSizeOperation; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; /** * List every method with bytecode larger than specified limit. * * @since 1.1 */ @Mojo( name = "maxMethodSize", aggregator = false, defaultPhase = LifecyclePhase.VERIFY, requiresDependencyCollection = ResolutionScope.TEST, requiresDependencyResolution = ResolutionScope.TEST, requiresDirectInvocation = false, threadSafe = true) public class MaxMethodSizeMojo extends AbstractJarScanMojo { /** * Report methods larger than the specified bytes. The default for {@code -XX:MaxInlineSize} is 35. The default for * {@code -XX:FreqInlineSize} is 325. * * @since 1.1 */ @Parameter(property = "limit", defaultValue = "0") private int limit; @Override protected IJarScanOperation createOperation() { return new FreqInlineSizeOperation(this.limit); } }
package com.github.ferstl.jarscan; import org.adoptopenjdk.jitwatch.jarscan.IJarScanOperation; import org.adoptopenjdk.jitwatch.jarscan.freqinlinesize.FreqInlineSizeOperation; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; /** * List every method with bytecode larger than specified limit. */ @Mojo( name = "maxMethodSize", aggregator = false, defaultPhase = LifecyclePhase.VERIFY, requiresDependencyCollection = ResolutionScope.TEST, requiresDependencyResolution = ResolutionScope.TEST, requiresDirectInvocation = false, threadSafe = true) public class MaxMethodSizeMojo extends AbstractJarScanMojo { /** * Report methods larger than the specified bytes. The default for {@code -XX:MaxInlineSize} is 35. The default for * {@code -XX:FreqInlineSize} is 325. * * @since 1.1.0 */ @Parameter(property = "limit", defaultValue = "0") private int limit; @Override protected IJarScanOperation createOperation() { return new FreqInlineSizeOperation(this.limit); } }
Break the build upon Sass compilation errors if running in a CI environment.
var gulp = require("gulp"); var CFG = require("./utils/config.js"); var $ = require("gulp-load-plugins")(); var path = require("path"); var pkg = require(path.join("..", CFG.FILE.config.pkg)); var exec = require("child_process").exec; var notify = require("./utils/notify-style-compile"); /** * style:compile * @see compass-style.org * @see compass-style.org/help/tutorials/configuration-reference */ gulp.task("style:compile", ["style:lint"], function(callback) { var compassProcess = exec([ "bundle", "exec", "compass", "compile", "--config", path.join(CFG.FILE.config.compass) ].join(" "), function(err, stdout, stderr) { $.util.log("[style:compile] stdout:", stdout); $.util.log("[style:compile] stderr: ", stderr); notify({ message: "Compilation complete!" }); if("undefined" !== typeof(process.env.<%= _.snakeCase(props.appname).toUpperCase() %>_CI)) { // Break the build, if running inside a CI environment. throw new $.util.PluginError("compass", err); } callback(); }); });
var gulp = require("gulp"); var CFG = require("./utils/config.js"); var $ = require("gulp-load-plugins")(); var path = require("path"); var pkg = require(path.join("..", CFG.FILE.config.pkg)); var exec = require("child_process").exec; var notify = require("./utils/notify-style-compile"); /** * style:compile * @see compass-style.org * @see compass-style.org/help/tutorials/configuration-reference */ gulp.task("style:compile", ["style:lint"], function(callback) { var compassProcess = exec([ "bundle", "exec", "compass", "compile", "--config", path.join(CFG.FILE.config.compass) ].join(" "), function(err, stdout, stderr) { $.util.log("[style:compile] stdout:", stdout); $.util.log("[style:compile] stderr: ", stderr); notify({ message: "Compilation complete!" }); if(null !== err) { $.util.log("[style:compile] err: ", err); throw new $.util.PluginError("compass", err); } callback(); }); });
Use node instead of element array for prop validation
import React from 'react'; function getViewportData() { let viewport = 'xs'; if (window.innerWidth >= 544) viewport = 'sm'; if (window.innerWidth >= 768) viewport = 'md'; if (window.innerWidth >= 992) viewport = 'lg'; if (window.innerWidth >= 1200) viewport = 'xl'; return viewport; } function renderThemedChildren(props) { return React.Children.map(props.children, (child) => { if (!child) return null; return React.cloneElement(child, { theme: props.theme, viewport: getViewportData() }); }); } const ContextPropagator = (props) => { return ( <div style={props.wrapperStyle}> { renderThemedChildren(props) } </div> ); } ContextPropagator.propTypes = { wrapperStyle: React.PropTypes.object, children: React.PropTypes.node }; export default ContextPropagator;
import React from 'react'; function getViewportData() { let viewport = 'xs'; if (window.innerWidth >= 544) viewport = 'sm'; if (window.innerWidth >= 768) viewport = 'md'; if (window.innerWidth >= 992) viewport = 'lg'; if (window.innerWidth >= 1200) viewport = 'xl'; return viewport; } function renderThemedChildren(props) { return React.Children.map(props.children, (child) => { if (!child) return null; return React.cloneElement(child, { theme: props.theme, viewport: getViewportData() }); }); } const ContextPropagator = (props) => { return ( <div style={props.wrapperStyle}> { renderThemedChildren(props) } </div> ); } ContextPropagator.propTypes = { wrapperStyle: React.PropTypes.object, children: React.PropTypes.arrayOf(React.PropTypes.element) }; export default ContextPropagator;
Put LPD status as first in pre-campaign dashboard
export default { 'id': -9, 'title': 'EOC Pre Campaign', 'dashboardType': 'EocCampaign', 'builtin': true, 'charts': [ { 'title': 'tableData', 'type': 'TableChart', 'indicators': [28, 1, 2, 5, 6, 11, 12, 18, 22, 24, 25, 26], 'groupBy': 'indicator', 'timeRange': { months: 0 } // 'yFormat': ',.0f', // 'xFormat': ',.0f' }, { 'title': 'trendData', 'type': 'LineChart', 'indicators': [21], 'timeRange': { months: 12 } }, { 'title': 'mapData', 'type': 'ChoroplethMap', 'locations': 'sublocations', 'timeRange': 0, 'indicators': [21] } ] }
export default { 'id': -9, 'title': 'EOC Pre Campaign', 'dashboardType': 'EocCampaign', 'builtin': true, 'charts': [ { 'title': 'tableData', 'type': 'TableChart', 'indicators': [2, 5, 6, 11, 12, 18, 22, 24, 25, 26, 28, 1], 'groupBy': 'indicator', 'timeRange': { months: 0 } // 'yFormat': ',.0f', // 'xFormat': ',.0f' }, { 'title': 'trendData', 'type': 'LineChart', 'indicators': [21], 'timeRange': { months: 12 } }, { 'title': 'mapData', 'type': 'ChoroplethMap', 'locations': 'sublocations', 'timeRange': 0, 'indicators': [21] } ] }
Use environment variable for system32 Windows can be installed on a different drive than `c:\`
'use babel'; import { CompositeDisposable } from 'atom'; export default { subscriptions: null, config: { "path": { "win32": "%SYSTEM%/drivers/etc/hosts", "darwin": "/private/etc/hosts", "linux": "/etc/hosts", } }, activate(state) { // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable this.subscriptions = new CompositeDisposable(); // Register command that toggles this view this.subscriptions.add(atom.commands.add('atom-workspace', { 'hosts-edit:toggle': () => this.toggle() })); }, deactivate() { this.subscriptions.dispose(); }, toggle() { return atom.workspace.open(this.config.path[process.platform]); } };
'use babel'; import { CompositeDisposable } from 'atom'; export default { subscriptions: null, config: { "path": { "win32": "C:/Windows/System32/drivers/etc/hosts", "darwin": "/private/etc/hosts", "linux": "/etc/hosts", } }, activate(state) { // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable this.subscriptions = new CompositeDisposable(); // Register command that toggles this view this.subscriptions.add(atom.commands.add('atom-workspace', { 'hosts-edit:toggle': () => this.toggle() })); }, deactivate() { this.subscriptions.dispose(); }, toggle() { return atom.workspace.open(this.config.path[process.platform]); } };
Make command executable without any parameters
package main import ( "log" "net/http" "github.com/codegangsta/cli" "os" ) func main() { app := cli.NewApp() app.Name = "go-http-server" app.Usage = "Start web server and public your current directory." app.Version = "0.0.2" app.Authors = append(app.Authors, cli.Author{Name: "Kohei Kawasaki", Email: "mynameiskawasaq@gmail.com"}) app.Commands = []cli.Command{ { Name: "start", Aliases: []string{"s"}, Usage: "Start the web server", Action: start, Flags: []cli.Flag { cli.StringFlag { Name: "port, p", Value: "8000", Usage: "Port number to listen to", EnvVar: "PORT", }, }, }, } app.Action = start app.Run(os.Args) } func start(c *cli.Context) { port := c.String("port") if port == "" { port = "8000" } log.Fatal(http.ListenAndServe(":"+port, http.FileServer(http.Dir(".")))) }
package main import ( "log" "net/http" "github.com/codegangsta/cli" "os" ) func main() { app := cli.NewApp() app.Name = "go-http-server" app.Usage = "Start web server and public your current directory." app.Version = "0.0.1" app.Authors = append(app.Authors, cli.Author{Name: "Kohei Kawasaki", Email: "mynameiskawasaq@gmail.com"}) app.Commands = []cli.Command{ { Name: "start", Aliases: []string{"s"}, Usage: "Start the web server", Action: start, Flags: []cli.Flag { cli.StringFlag { Name: "port, p", Value: "8000", Usage: "Port number to listen to", EnvVar: "PORT", }, }, }, } app.Run(os.Args) } func start(c *cli.Context) { port := c.String("port") log.Fatal(http.ListenAndServe(":"+port, http.FileServer(http.Dir(".")))) }
Remove a debug console error statement
function replace_t_co_links() { $('.twitter-timeline-link').each(function(){ if (!$(this).attr('data-url-expanded')) { data_expanded_url = $(this).attr('data-expanded-url'); if (data_expanded_url) { $(this).attr('href', data_expanded_url); $(this).attr('data-url-expanded', '1'); $('> .js-display-url', this).html(data_expanded_url); }} }); } $(document).ready(function(){ replace_t_co_links(); var observer = new MutationObserver(function(mutations){ replace_t_co_links(); }); var config = { attributes: true, childList: true, characterData: true, subtree: true }; observer.observe(document.body, config); });
function replace_t_co_links() { $('.twitter-timeline-link').each(function(){ if (!$(this).attr('data-url-expanded')) { data_expanded_url = $(this).attr('data-expanded-url'); if (data_expanded_url) { $(this).attr('href', data_expanded_url); $(this).attr('data-url-expanded', '1'); $('> .js-display-url', this).html(data_expanded_url); }} }); } $(document).ready(function(){ replace_t_co_links(); console.error("Voila"); var observer = new MutationObserver(function(mutations){ replace_t_co_links(); }); var config = { attributes: true, childList: true, characterData: true, subtree: true }; observer.observe(document.body, config); });
Sort on last updated first
'use strict'; // @ngInject var ParameterSearchController = function($scope, $location, $controller, npdcAppConfig, Parameter) { // Extend NpolarApiBaseController $controller("NpolarBaseController", { $scope: $scope }); $scope.resource = Parameter; npdcAppConfig.cardTitle = 'Environmental monitoring parameters'; let query = function() { let defaults = { start: 0, limit: 50, "size-facet": 5, format: "json", variant: "atom", sort: "-updated", facets: "systems,collection,species,themes,dataseries,label,warn,variable,unit,locations.placename,links.rel" }; return Object.assign({}, defaults, $location.search()); }; let detail = function(p) { let subtitle = ''; if (p.timeseries && p.timeseries.length > 0) { subtitle = `Timeseries: ${p.timeseries.length}`; } //subtitle += `. Updates: ${ $filter('date')(t.updated)}`; return subtitle; }; npdcAppConfig.search.local.results.subtitle = function(p) { return p.species || ''; }; npdcAppConfig.search.local.results.detail = detail; $scope.search(query()); $scope.$on('$locationChangeSuccess', (event, data) => { $scope.search(query()); }); }; module.exports = ParameterSearchController;
'use strict'; // @ngInject var ParameterSearchController = function($scope, $location, $controller, npdcAppConfig, Parameter) { // Extend NpolarApiBaseController $controller("NpolarBaseController", { $scope: $scope }); $scope.resource = Parameter; npdcAppConfig.cardTitle = 'Environmental monitoring parameters'; let query = function() { let defaults = { start: 0, limit: 50, "size-facet": 5, format: "json", variant: "atom", facets: "systems,collection,species,themes,dataseries,label,warn,variable,unit,locations.placename,links.rel" }; return Object.assign({}, defaults, $location.search()); }; let detail = function(p) { let subtitle = ''; if (p.timeseries && p.timeseries.length > 0) { subtitle = `Timeseries: ${p.timeseries.length}`; } //subtitle += `. Updates: ${ $filter('date')(t.updated)}`; return subtitle; }; npdcAppConfig.search.local.results.subtitle = function(p) { return p.species || ''; }; npdcAppConfig.search.local.results.detail = detail; $scope.search(query()); $scope.$on('$locationChangeSuccess', (event, data) => { $scope.search(query()); }); }; module.exports = ParameterSearchController;
Fix for page links in comments
<?php /* ==================== [BEGIN_COT_EXT] Hooks=news.loop Tags=news.tpl:{PAGE_ROW_COMMENTS} [END_COT_EXT] ==================== */ /** * Comments system for Cotonti * * @package comments * @version 0.7.0 * @author Cotonti Team * @copyright Copyright (c) Cotonti Team 2008-2011 * @license BSD */ defined('COT_CODE') or die('Wrong URL'); require_once cot_incfile('comments', 'plug'); $page_urlp = empty($pag['page_alias']) ? 'c='.$pag['page_cat'].'&id='.$pag['page_id'] : 'c='.$pag['page_cat'].'&al='.$pag['page_alias']; $news->assign(array( 'PAGE_ROW_COMMENTS' => cot_comments_link('page', $page_urlp, 'page', $pag['page_id'], $pag['page_cat']), 'PAGE_ROW_COMMENTS_COUNT' => cot_comments_count('page', $pag['page_id']) )); ?>
<?php /* ==================== [BEGIN_COT_EXT] Hooks=news.loop Tags=news.tpl:{PAGE_ROW_COMMENTS} [END_COT_EXT] ==================== */ /** * Comments system for Cotonti * * @package comments * @version 0.7.0 * @author Cotonti Team * @copyright Copyright (c) Cotonti Team 2008-2011 * @license BSD */ defined('COT_CODE') or die('Wrong URL'); require_once cot_incfile('comments', 'plug'); $page_urlp = empty($pag['page_alias']) ? 'id='.$pag['page_id'] : 'al='.$pag['page_alias']; $news->assign(array( 'PAGE_ROW_COMMENTS' => cot_comments_link('page', $page_urlp, 'page', $pag['page_id'], $pag['page_cat']), 'PAGE_ROW_COMMENTS_COUNT' => cot_comments_count('page', $pag['page_id']) )); ?>
fix: Remove attribute instead of raise it when bindings parser is used on HTML5 form elements This change fixes a bug which appears when bindings parser is used on 'checked' attribute of a checkbox and bound property is undefined
import getBindingKey from './_getbindingkey'; import bindNode from '../../bindnode'; import lookForBinder from '../../lookforbinder'; // a binder for instance of Attr const attributeBinder = { setValue(value) { this.value = value; } }; // adds binding for an attribute // its logic is much harder than for text node // check out imported modules for more info export default function processAttribute({ node, attribute, object, eventOptions }) { const { name, value } = attribute; const { type } = node; // get a key which will be actually bound to an attribute // getBindingKey analyzes given value, creates computable property and returns its key const key = getBindingKey({ object, text: value }); const probablyValueInput = name === 'value' && type !== 'checkbox' && type !== 'radio'; const probablyCheckableInput = name === 'checked' && (type === 'checkbox' || type === 'radio'); let defaultBinder; if (probablyValueInput || probablyCheckableInput) { defaultBinder = lookForBinder(node); } if (defaultBinder) { // if deault binder is found then this is default HTML5 form element // remove the attribute and use found binder node.removeAttribute(name); bindNode(object, key, node, defaultBinder, eventOptions); } else { // simply bind an attribute bindNode(object, key, attribute, attributeBinder, eventOptions); } }
import getBindingKey from './_getbindingkey'; import bindNode from '../../bindnode'; import lookForBinder from '../../lookforbinder'; // a binder for instance of Attr const attributeBinder = { setValue(value) { this.value = value; } }; // adds binding for an attribute // its logic is much harder than for text node // check out imported modules for more info export default function processAttribute({ node, attribute, object, eventOptions }) { const { name, value } = attribute; const { type } = node; // get a key which will be actually bound to an attribute // getBindingKey analyzes given value, creates computable property and returns its key const key = getBindingKey({ object, text: value }); const probablyValueInput = name === 'value' && type !== 'checkbox' && type !== 'radio'; const probablyCheckableInput = name === 'checked' && (type === 'checkbox' || type === 'radio'); let defaultBinder; if (probablyValueInput || probablyCheckableInput) { defaultBinder = lookForBinder(node); } if (defaultBinder) { // if deault binder is found then this is default HTML5 form element // remove the attribute and use found binder node.setAttribute(name, ''); bindNode(object, key, node, defaultBinder, eventOptions); } else { // simply bind an attribute bindNode(object, key, attribute, attributeBinder, eventOptions); } }
Fix for unicode characters support
<?php return [ 'default' => 'ufuzzy', 'fieldName' => 'relevance', 'drivers' => [ 'fuzzy' => [ 'class' => 'TomLingham\Searchy\SearchDrivers\FuzzySearchDriver', ], 'ufuzzy' => [ 'class' => 'TomLingham\Searchy\SearchDrivers\FuzzySearchUnicodeDriver', ], 'simple' => [ 'class' => 'TomLingham\Searchy\SearchDrivers\SimpleSearchDriver', ], 'levenshtein' => [ 'class' => 'TomLingham\Searchy\SearchDrivers\LevenshteinSearchDriver', ], ], ];
<?php return [ 'default' => 'fuzzy', 'fieldName' => 'relevance', 'drivers' => [ 'fuzzy' => [ 'class' => 'TomLingham\Searchy\SearchDrivers\FuzzySearchDriver', ], 'ufuzzy' => [ 'class' => 'TomLingham\Searchy\SearchDrivers\FuzzySearchUnicodeDriver', ], 'simple' => [ 'class' => 'TomLingham\Searchy\SearchDrivers\SimpleSearchDriver', ], 'levenshtein' => [ 'class' => 'TomLingham\Searchy\SearchDrivers\LevenshteinSearchDriver', ], ], ];
Verify `use` statements work inside generics See issue #144 - myth busted, I'd say
<?php namespace net\xp_framework\unittest\core\generics; use lang\Object; /** * Nullable value * */ #[@generic(self= 'T')] class Nullable extends Object { protected $value; /** * Constructor * * @param T value */ #[@generic(params= 'T')] public function __construct($value= null) { $this->value= $value; } /** * Returns whether a value exists * * @return bool */ public function hasValue() { return $this->value !== null; } /** * Sets value * * @param T value * @return self this instance */ #[@generic(params= 'T')] public function set($value= null) { $this->value= $value; return $this; } /** * Returns value * * @return T value */ #[@generic(return= 'T')] public function get() { return $this->value; } }
<?php namespace net\xp_framework\unittest\core\generics; /** * Nullable value * */ #[@generic(self= 'T')] class Nullable extends \lang\Object { protected $value; /** * Constructor * * @param T value */ #[@generic(params= 'T')] public function __construct($value= null) { $this->value= $value; } /** * Returns whether a value exists * * @return bool */ public function hasValue() { return $this->value !== null; } /** * Sets value * * @param T value * @return self this instance */ #[@generic(params= 'T')] public function set($value= null) { $this->value= $value; return $this; } /** * Returns value * * @return T value */ #[@generic(return= 'T')] public function get() { return $this->value; } }
Add setTimeout property to delay ufo before starting over again
var virus = document.querySelector("div"); var x = 1; var y = 0; var vy = 0; var ay = 0; var vx = 0.1; // px per millisecond var startTime = Date.now(); var clickTime; timer = setInterval(function animate() { var t = Date.now() - startTime; x = vx * t; y = vy * t + 400; virus.style.left = x + "px"; virus.style.top = y + "px"; if ( x > document.body.clientWidth) { startTime = Date.now(); } if (ay >= 0.001) { t = Date.now() - clickTime; vy = ay * t; } if (y > screen.height){ console.log("hello"); startTime = setTimeout(function() { vy = 0; ay = 0; }, 10000); } },20); // ms | 1000/20 = 50 frames per second (50 fps) virus.addEventListener("click", function onclick(event) { ay = 0.001; clickTime = Date.now(); });
var virus = document.querySelector("div"); var x = 1; var y = 0; var vy = 0; var ay = 0; var vx = .1; // px per millisecond var startTime = Date.now(); var clickTime; timer = setInterval(function animate() { var t = Date.now() - startTime; x = vx * t; y = vy * t + 400; virus.style.left = x + "px"; virus.style.top = y + "px"; if ( x > document.body.clientWidth) { startTime = Date.now(); } if (ay >= .001) { var t = Date.now() - clickTime; vy = ay * t; } //if ( y > document.body.clientHeight && x > document.body.clientWidth) { // console.log("hello"); // startTime = Date.now(); //} if (y > screen.height){ console.log("hello"); startTime = Date.now(); vy = 0; ay = 0; } //if ( y > document.body.clientHeight && x > document.body.clientWidth) { // console.log("second if"); // vy = 0; // ay = 0; //} },20); // ms | 1000/20 = 50 frames per second (50 fps) virus.addEventListener("click", function onclick(event) { ay = .001; clickTime = Date.now(); });
Change info log to debug
package ua.anironglass.template.ui.activities.main; import android.os.Bundle; import javax.inject.Inject; import timber.log.Timber; import ua.anironglass.template.R; import ua.anironglass.template.ui.activities.base.BaseActivity; public class MainActivity extends BaseActivity implements MainMvpView { @Inject MainPresenter mainPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Timber.d("Create MainActivity"); getComponent().inject(this); setContentView(R.layout.activity_main); initializeView(); } @Override public void onResume() { Timber.d("Resume MainActivity"); super.onResume(); } @Override protected void onPause() { Timber.d("Pause MainActivity"); super.onPause(); } @Override protected void onDestroy() { Timber.d("Destroy MainActivity"); super.onDestroy(); mainPresenter.detachView(); } private void initializeView() { mainPresenter.attachView(this); } }
package ua.anironglass.template.ui.activities.main; import android.os.Bundle; import javax.inject.Inject; import timber.log.Timber; import ua.anironglass.template.R; import ua.anironglass.template.ui.activities.base.BaseActivity; public class MainActivity extends BaseActivity implements MainMvpView { @Inject MainPresenter mainPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Timber.d("Create MainActivity"); getComponent().inject(this); setContentView(R.layout.activity_main); initializeView(); } @Override public void onResume() { Timber.i("Resume MainActivity"); super.onResume(); } @Override protected void onPause() { Timber.i("Pause MainActivity"); super.onPause(); } @Override protected void onDestroy() { Timber.i("Destroy MainActivity"); super.onDestroy(); mainPresenter.detachView(); } private void initializeView() { mainPresenter.attachView(this); } }
Enable HTTPS between Hadoop proxy and H2O Node SSL certificates are not validated, it is assumed the Hadoop environment is secured and man-in-the-middle attack is not possible.
package water.webserver.jetty9; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpExchange; import org.eclipse.jetty.proxy.ProxyServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.util.ssl.SslContextFactory; /** * Transparent proxy that automatically adds authentication to each request */ public class TransparentProxyServlet extends ProxyServlet.Transparent { private String _basicAuth; @Override public void init(ServletConfig config) throws ServletException { super.init(config); _basicAuth = config.getInitParameter("BasicAuth"); } @Override protected HttpClient newHttpClient() { final SslContextFactory sslContextFactory = new SslContextFactory(true); return new HttpClient(sslContextFactory); } @Override protected void addProxyHeaders(HttpServletRequest clientRequest, Request proxyRequest) { proxyRequest.getHeaders().remove("Authorization"); proxyRequest.header("Authorization", _basicAuth); } }
package water.webserver.jetty9; import org.eclipse.jetty.client.HttpExchange; import org.eclipse.jetty.proxy.ProxyServlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.api.Request; /** * Transparent proxy that automatically adds authentication to each request */ public class TransparentProxyServlet extends ProxyServlet.Transparent { private String _basicAuth; @Override public void init(ServletConfig config) throws ServletException { super.init(config); _basicAuth = config.getInitParameter("BasicAuth"); } @Override protected void addProxyHeaders(HttpServletRequest clientRequest, Request proxyRequest) { proxyRequest.getHeaders().remove("Authorization"); proxyRequest.header("Authorization", _basicAuth); } }
Rewrite getRoot to use recursion
/* eslint-disable no-unused-vars */ import 'babel-polyfill' import postcss from 'postcss' import path from 'path' import fs from 'fs' import nesting from 'postcss-nesting' const getRoot = atRule => { return atRule.parent ? getRoot(atRule.parent) : atRule } export default postcss .plugin('postcss-extract', (options = {}) => { const instance = postcss() // atRules = Object where key is atRule and value is path where save file const atRules = options.extract // do nothing if no extract if (!atRules) return instance // bubble atRules for (const atRule of Object.keys(atRules)) { instance.use(nesting({ bubble: atRule })) } const plugin = (css, result) => { Object.keys(atRules).forEach(atRule => { const extracted = postcss.root() css.walkAtRules(atRule, rule => { extracted.append(getRoot(rule)) rule.remove() }) // clean all rules except rules inside our at-rule extracted.walkRules(rule => { if (rule.parent.name === atRule) return rule.remove() }) // remove at-rule wrapper extracted.walkAtRules(atRule, rule => { rule.replaceWith(rule.nodes) }) fs.writeFileSync(`${atRules[atRule]}`, extracted.toResult().css) }) } return instance.use(plugin) })
/* eslint-disable no-unused-vars */ import 'babel-polyfill' import postcss from 'postcss' import path from 'path' import fs from 'fs' import nesting from 'postcss-nesting' const getRoot = atRule => { let rule = atRule while (rule.parent) { rule = rule.parent } return rule } export default postcss .plugin('postcss-extract', (options = {}) => { const instance = postcss() // atRules = Object where key is atRule and value is path where save file const atRules = options.extract // do nothing if no extract if (!atRules) return instance // bubble atRules for (const atRule of Object.keys(atRules)) { instance.use(nesting({ bubble: atRule })) } const plugin = (css, result) => { Object.keys(atRules).forEach(atRule => { const extracted = postcss.root() css.walkAtRules(atRule, rule => { extracted.append(getRoot(rule)) rule.remove() }) // clean all rules except rules inside our at-rule extracted.walkRules(rule => { if (rule.parent.name === atRule) return rule.remove() }) // remove at-rule wrapper extracted.walkAtRules(atRule, rule => { rule.replaceWith(rule.nodes) }) fs.writeFileSync(`${atRules[atRule]}`, extracted.toResult().css) }) } return instance.use(plugin) })
Set up library search paths for tests. When running tests, exclusively use the libraries that are either built-in, or are provided with the test suite.
import os from skidl import * files_at_start = set([]) def setup_function(f): global files_at_start files_at_start = set(os.listdir('.')) default_circuit.mini_reset() lib_search_paths.clear() lib_search_paths.update({ KICAD: [".", get_filename(".")], SKIDL: [".", get_filename("../skidl/libs")] }) def teardown_function(f): files_at_end = set(os.listdir('.')) for file in files_at_end - files_at_start: try: os.remove(file) except Exception: pass def get_filename(fn): """ Resolves a filename relative to the "tests" directory. """ abs_fn = \ fn if os.path.isabs(fn) else \ os.path.join( os.path.dirname(os.path.abspath(__file__)), fn) return os.path.realpath(abs_fn) if __name__ == '__main__': setup_function(None) with open('test.txt','wb') as f: f.write('test') teardown_function(None)
import os from skidl import * files_at_start = set([]) def setup_function(f): global files_at_start files_at_start = set(os.listdir('.')) # Make this test directory the library search paths for all ECAD tools for tool_lib_path in lib_search_paths: tool_lib_path = [os.path.dirname(os.path.abspath(__file__))] default_circuit.mini_reset() def teardown_function(f): files_at_end = set(os.listdir('.')) for file in files_at_end - files_at_start: try: os.remove(file) except Exception: pass def get_filename(fn): """ Resolves a filename relative to the "tests" directory. """ abs_fn = \ fn if os.path.isabs(fn) else \ os.path.join( os.path.dirname(os.path.abspath(__file__)), fn) return os.path.realpath(abs_fn) if __name__ == '__main__': setup_function(None) with open('test.txt','wb') as f: f.write('test') teardown_function(None)
Make request.POST be only json content when using expect_json
from functools import wraps import copy import json def expect_json(view_function): """ View decorator for simplifying handing of requests that expect json. If the request's CONTENT_TYPE is application/json, parses the json dict from request.body, and updates request.POST with the contents. """ @wraps(view_function) def expect_json_with_cloned_request(request, *args, **kwargs): # cdodge: fix postback errors in CMS. The POST 'content-type' header can include additional information # e.g. 'charset', so we can't do a direct string compare if request.META.get('CONTENT_TYPE', '').lower().startswith("application/json"): cloned_request = copy.copy(request) cloned_request.POST = json.loads(request.body) return view_function(cloned_request, *args, **kwargs) else: return view_function(request, *args, **kwargs) return expect_json_with_cloned_request
from functools import wraps import copy import json def expect_json(view_function): """ View decorator for simplifying handing of requests that expect json. If the request's CONTENT_TYPE is application/json, parses the json dict from request.body, and updates request.POST with the contents. """ @wraps(view_function) def expect_json_with_cloned_request(request, *args, **kwargs): # cdodge: fix postback errors in CMS. The POST 'content-type' header can include additional information # e.g. 'charset', so we can't do a direct string compare if request.META.get('CONTENT_TYPE', '').lower().startswith("application/json"): cloned_request = copy.copy(request) cloned_request.POST = cloned_request.POST.copy() cloned_request.POST.update(json.loads(request.body)) return view_function(cloned_request, *args, **kwargs) else: return view_function(request, *args, **kwargs) return expect_json_with_cloned_request
Fix stupid bug. Shame on me!
var SassPlotter = require('sass-plotter'); var through = require('through'); var path = require('path'); var fs = require('fs'); var plotter = new SassPlotter(); var options = {}; function write (file) { var dependentFile, fileExt, _this; _this = this; fileExt = path.extname(file.path); if (fileExt !== '.scss' && fileExt !== '.sass') return this.queue(file); if (file.event === 'unlink') { plotter.unset(file.path); } else { plotter.set(file.path, file.contents.toString(), options); } this.queue(file); plotter.dependents(file.path).forEach(function (item) { fs.readFile(item, {encoding : 'utf8'}, function (err, str) { if (err) throw new Error(err); dependentFile = file.clone(); dependentFile.path = item; dependentFile.contents = new Buffer(str); _this.queue(dependentFile); }); }, this); } module.exports = function (setting) { options = setting || options; return through(write); }
var SassPlotter = require('sass-plotter'); var through = require('through'); var path = require('path'); var fs = require('fs'); var plotter = new SassPlotter(); var options = {}; function write (file) { var dependentFile, _this; _this = this; if (path.extname(file.path) !== '.scss' || path.extname(file.path) !== '.sass') return this.queue(file); if (file.event === 'unlink') { plotter.unset(file.path); } else { plotter.set(file.path, file.contents.toString(), options); } this.queue(file); plotter.dependents(file.path).forEach(function (item) { fs.readFile(item, {encoding : 'utf8'}, function (err, str) { if (err) throw new Error(err); dependentFile = file.clone(); dependentFile.path = item; dependentFile.contents = new Buffer(str); _this.queue(dependentFile); }); }, this); } module.exports = function (setting) { options = setting || options; return through(write); }
Add Laravel Shopify API wrapper.
// Opt-in repos (case sensitive) // These repositories are loaded this way as a convenience, not because Disco has any special priority in this list. // Opting these repositories in here reduces the number of Javascript calls we need to make to load external repos. var optInRepos = [ 'cartjs', 'django-shopify-auth', 'grunt-shopify-theme-settings', 'shopify-theme-scaffold', 'shopify-dev-frame' ]; // Add custom repos by full_name. Take the org/user and repo name // - e.g. luciddesign/bootstrapify from https://github.com/luciddesign/bootstrapify var customRepos = [ 'joshrps/laravel-shopify-API-wrapper' ]; // Custom repo language, different than that defined by GitHub var customRepoLanguage = { 'cartjs': 'JavaScript', 'shopify-theme-scaffold': 'Liquid' }; // Specify how each repository should be classified. // Currently, repositories can be classified as "Themes" or "Apps". // "Themes" is the default so currently only repositories that should be classified under "Apps" should be in here. var customRepoCategory = { 'django-shopify-auth': 'Apps', 'shopify-dev-frame': 'Apps', 'laravel-shopify-API-wrapper': 'Apps' }; // Custom repo avatars. Dimensions should be 40x40 // - Be sure a custom repo doesn't have the same name as a Shopify one, or a one will be overridden var customRepoAvatar = {};
// Opt-in repos (case sensitive) // These repositories are loaded this way as a convenience, not because Disco has any special priority in this list. // Opting these repositories in here reduces the number of Javascript calls we need to make to load external repos. var optInRepos = [ 'cartjs', 'django-shopify-auth', 'grunt-shopify-theme-settings', 'shopify-theme-scaffold', 'shopify-dev-frame' ]; // Add custom repos by full_name. Take the org/user and repo name // - e.g. luciddesign/bootstrapify from https://github.com/luciddesign/bootstrapify var customRepos = [ ]; // Custom repo language, different than that defined by GitHub var customRepoLanguage = { 'cartjs': 'JavaScript', 'shopify-theme-scaffold': 'Liquid' }; // Specify how each repository should be classified. // Currently, repositories can be classified as "Themes" or "Apps". // "Themes" is the default so currently only repositories that should be classified under "Apps" should be in here. var customRepoCategory = { 'django-shopify-auth': 'Apps', 'shopify-dev-frame': 'Apps' }; // Custom repo avatars. Dimensions should be 40x40 // - Be sure a custom repo doesn't have the same name as a Shopify one, or a one will be overridden var customRepoAvatar = {};
Rename route function to getActions, now also pass the decodedPath
/* global Promise */ export default (routesFetchersMap, path, query, options, store) => { const { ignoredPathsRegex, log } = options const decodedPath = decodeURI(path) if (ignoredPathsRegex && ignoredPathsRegex.test(decodedPath)) { return Promise.resolve(true) } log( `Pre-fetcher --> Decoded path: ${decodedPath}, query: ${JSON.stringify( query )}` ) const promises = [] for (let i = 0; i < routesFetchersMap.length; i++) { const { regex, name, getActions } = routesFetchersMap[i] const m = regex.exec(decodedPath) if (m !== null) { log(`Pre-fetcher --> Matched ${name}`) let actions = getActions(m, query, decodedPath) actions = actions instanceof Array ? actions : [actions] actions.forEach((action) => { promises.push(store.dispatch(action)) }) } } if (promises.length > 0) { return Promise.all(promises) } log(`Pre-fetcher --> No route matched, nothing to prefetch`) return Promise.resolve(true) }
/* global Promise */ export default (routesFetchersMap, path, query, options, store) => { const { ignoredPathsRegex, log } = options const decodedPath = decodeURI(path) if (ignoredPathsRegex && ignoredPathsRegex.test(decodedPath)) { return Promise.resolve(true) } log( `Pre-fetcher --> Decoded path: ${decodedPath}, query: ${JSON.stringify( query )}` ) const promises = [] for (let i = 0; i < routesFetchersMap.length; i++) { const { regex, name, func } = routesFetchersMap[i] const m = regex.exec(decodedPath) if (m !== null) { log(`Pre-fetcher --> Matched ${name}`) let actions = func(m, query) actions = actions instanceof Array ? actions : [actions] actions.forEach((action) => { promises.push(store.dispatch(action)) }) } } if (promises.length > 0) { return Promise.all(promises) } log(`Pre-fetcher --> No route matched, nothing to prefetch`) return Promise.resolve(true) }
Fix whitespace in file_glob and attempt coverage modification
import glob import shutil import os if os.name == "nt": # pragma: no branch from .ntcommonpath import commonpath else: # pragma: no branch from .posixcommonpath import commonpath # def move_glob(src,dst): # """Moves files from src to dest. # src may be any glob to recognize files. dst must be a folder. # """ # for obj in glob.iglob(src): # shutil.move(obj,dst) def copy_glob(src, dst): """Copies files from src to dest. src may be any glob to recognize files. dst must be a folder. """ for obj in glob.iglob(src): if os.path.isdir(obj): start_part = commonpath([src, obj]) end_part = os.path.relpath(obj, start_part) ctree_dst = os.path.join(dst, end_part) if not os.path.isdir(ctree_dst): shutil.copytree(obj, ctree_dst) else: copy_glob(os.path.join(obj, "*"), ctree_dst) else: shutil.copy2(obj, dst)
import glob import shutil import os if os.name == "nt": # pragma: no branch from .ntcommonpath import commonpath else: from .posixcommonpath import commonpath # def move_glob(src,dst): # """Moves files from src to dest. # src may be any glob to recognize files. dst must be a folder. # """ # for obj in glob.iglob(src): # shutil.move(obj,dst) def copy_glob(src,dst): """Copies files from src to dest. src may be any glob to recognize files. dst must be a folder. """ for obj in glob.iglob(src): if os.path.isdir(obj): start_part=commonpath([src,obj]) end_part=os.path.relpath(obj,start_part) ctree_dst=os.path.join(dst,end_part) if not os.path.isdir(ctree_dst): shutil.copytree(obj,ctree_dst) else: copy_glob(os.path.join(obj,"*"),ctree_dst) else: shutil.copy2(obj,dst)
monitoring: Change monitoring interval to 10mins This patch changes the cluster monitoring interval to 10 mins. Change-Id: If8d4914e1b30478959bef57616cd9aba1dd8034d Signed-off-by: anmolbabu <3d38fb1e9c5ff2662fc415254efcdfedb95b84d5@gmail.com>
package monitoring func GetDefaultThresholdValues() (plugins []Plugin) { return []Plugin{ { Name: "df", Enable: true, Configs: []PluginConfig{ {Category: THRESHOLD, Type: CRITICAL, Value: "90"}, {Category: THRESHOLD, Type: WARNING, Value: "80"}, }, }, { Name: "memory", Enable: true, Configs: []PluginConfig{ {Category: THRESHOLD, Type: CRITICAL, Value: "90"}, {Category: THRESHOLD, Type: WARNING, Value: "80"}, }, }, { Name: "cpu", Enable: true, Configs: []PluginConfig{ {Category: THRESHOLD, Type: CRITICAL, Value: "90"}, {Category: THRESHOLD, Type: WARNING, Value: "80"}, }, }, { Name: "swap", Enable: true, Configs: []PluginConfig{ {Category: THRESHOLD, Type: CRITICAL, Value: "70"}, {Category: THRESHOLD, Type: WARNING, Value: "50"}, }, }, } } var DefaultClusterMonitoringInterval = 600
package monitoring func GetDefaultThresholdValues() (plugins []Plugin) { return []Plugin{ { Name: "df", Enable: true, Configs: []PluginConfig{ {Category: THRESHOLD, Type: CRITICAL, Value: "90"}, {Category: THRESHOLD, Type: WARNING, Value: "80"}, }, }, { Name: "memory", Enable: true, Configs: []PluginConfig{ {Category: THRESHOLD, Type: CRITICAL, Value: "90"}, {Category: THRESHOLD, Type: WARNING, Value: "80"}, }, }, { Name: "cpu", Enable: true, Configs: []PluginConfig{ {Category: THRESHOLD, Type: CRITICAL, Value: "90"}, {Category: THRESHOLD, Type: WARNING, Value: "80"}, }, }, { Name: "swap", Enable: true, Configs: []PluginConfig{ {Category: THRESHOLD, Type: CRITICAL, Value: "70"}, {Category: THRESHOLD, Type: WARNING, Value: "50"}, }, }, } } var DefaultClusterMonitoringInterval = 10
Update LeftOffset to current parent left offset
openerp.web_list_view_sticky = function (instance) { var _t = instance.web._t, _lt = instance.web._lt; var QWeb = instance.web.qweb; //Sticky Table Header instance.web.ListView.include({ load_list: function () { var self = this; self._super.apply(this, arguments); var scrollArea = self.$el.parents('.oe_view_manager.oe_view_manager_current').find('.oe_view_manager_wrapper .oe_view_manager_body')[0]; if(scrollArea){ self.$el.find('table.oe_list_content').each(function(){ $(this).stickyTableHeaders({scrollableArea: scrollArea, leftOffset: scrollArea}) }); } }, }); };
openerp.web_list_view_sticky = function (instance) { var _t = instance.web._t, _lt = instance.web._lt; var QWeb = instance.web.qweb; //Sticky Table Header instance.web.ListView.include({ load_list: function () { var self = this; self._super.apply(this, arguments); var offset = self.$el.parents('.oe_view_manager.oe_view_manager_current').find('.oe_view_manager_header').offset().top; var scrollArea = self.$el.parents('.oe_view_manager.oe_view_manager_current').find('.oe_view_manager_wrapper .oe_view_manager_body')[0]; self.$el.find('table.oe_list_content').each(function(){ $(this).stickyTableHeaders({scrollableArea: scrollArea}) }); }, }); };
Add popup intro for task
// Define the tour! var tour = { id: "hello-hopscotch", steps: [ { title: "Pick Your Level", content: "These are the different lessons you can choose from. Every time you complete a lesson, it will turn green", target: "navbar_popup", placement: "bottom" }, { title: "Information", content: "Here is information about each topic you will be learning", target: "instruction-template", placement: "bottom" }, { title: "Task", content: "Complete each task specified here", target: "popup_task", placement: "bottom" }, { title: "Terminal", content: "Type your responses here and press enter to move on to the next level", target: "terminal_popup", placement: "top" }, { title: "Finder", content: "This is your finder that will update when you type commands in the terminal.", target: "popup-folder", placement: "bottom" //maybe change } ] }; // Start the tour! if (localStorage.lessons == ""){ hopscotch.startTour(tour); }
// Define the tour! var tour = { id: "hello-hopscotch", steps: [ { title: "Pick Your Level", content: "These are the different lessons you can choose from. Every time you complete a lesson, it will turn green", target: "navbar_popup", placement: "bottom" }, { title: "Information", content: "Here is information about each topic you will be learning", target: "instruction-template", placement: "bottom" }, { title: "Terminal", content: "Type your responses here and press enter to move on to the next level", target: "terminal_popup", placement: "top" }, { title: "Finder", content: "This is your finder that will update when you type commands in the terminal.", target: "popup-folder", placement: "bottom" //maybe change } ] }; // Start the tour! if (localStorage.lessons == ""){ hopscotch.startTour(tour); }
Remove requirement for IP addresses
<?php namespace Aegir\Hostmaster\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ServerType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('hostname', 'text', array( 'description' => 'The hostname of the server. Must resolve to the IP addresses.', )); $builder->add('ip_addresses', 'textarea', array( 'description' => 'A list of IP addresses this server is publicly available under, one per line. If none is specified, a DNS lookup will be performed based on the server hostname above. <br /><strong>This should point to the public network, if you have such a separation.</strong>', 'required' => FALSE, )); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Aegir\Provision\Model\Server', 'intention' => 'server', 'translation_domain' => 'AegirHostmaster' )); } public function getName() { return 'server'; } }
<?php namespace Aegir\Hostmaster\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ServerType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('hostname', 'text', array( 'description' => 'The hostname of the server. Must resolve to the IP addresses.', )); $builder->add('ip_addresses', 'textarea', array( 'description' => 'A list of IP addresses this server is publicly available under, one per line. If none is specified, a DNS lookup will be performed based on the server hostname above. <br /><strong>This should point to the public network, if you have such a separation.</strong>', )); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Aegir\Provision\Model\Server', 'intention' => 'server', 'translation_domain' => 'AegirHostmaster' )); } public function getName() { return 'server'; } }
Sort indices/aliases and types alphabetically Closes #18
function DropdownCtrl($scope, $http, Data) { $scope.data = Data; $scope.indices = []; $scope.types = []; var path = $scope.data.host + "/_mapping"; $http.get(path).then(function(response){ $scope.data.mapping = response.data; for (i in response.data){ $scope.indices.push(i); $scope.types[i] = []; for (j in response.data[i]){ $scope.types[i].push(j); } } path = $scope.data.host + "/_aliases"; $http.get(path).then(function(response){ for (i in response.data){ for (j in response.data[i].aliases) { $scope.indices.push(j); $scope.types[j] = $scope.types[i]; $scope.data.mapping[j] = $scope.data.mapping[i]; } } $scope.indices.sort(); $scope.types.sort(); }); }); }
function DropdownCtrl($scope, $http, Data) { $scope.data = Data; $scope.indices = []; $scope.types = []; var path = $scope.data.host + "/_mapping"; $http.get(path).then(function(response){ $scope.data.mapping = response.data; for (i in response.data){ $scope.indices.push(i) $scope.types[i] = []; for (j in response.data[i]){ $scope.types[i].push(j); } } path = $scope.data.host + "/_aliases"; $http.get(path).then(function(response){ for (i in response.data){ for (j in response.data[i].aliases) { $scope.indices.push(j); $scope.types[j] = $scope.types[i]; $scope.data.mapping[j] = $scope.data.mapping[i]; } } }); }); }
Add DATE_FORMAT for parsing any datetime strings Poloniex seems to use a fixed output format for datetime strings
""" Constant values for the Poloniex API """ PUBLIC_API = 'https://poloniex.com/public' PRIVATE_API = 'https://poloniex.com/tradingApi' PUBLIC_COMMANDS = [ 'returnTicker', 'return24hVolume', 'returnOrderBook', 'returnTradeHistory', 'returnChartData', 'returnCurrencies', 'returnLoanOrders', ] PRIVATE_COMMANDS = [ 'returnBalances', 'returnCompleteBalances', 'returnDepositAddresses', 'generateNewAddress', 'returnDepositsWithdrawals', 'returnOpenOrders', 'returnTradeHistory', 'returnAvailableAccountBalances', 'returnTradableBalances', 'returnOpenLoanOffers', 'returnOrderTrades', 'returnActiveLoans', 'returnLendingHistory', 'createLoanOffer', 'cancelLoanOffer', 'toggleAutoRenew', 'buy', 'sell', 'cancelOrder', 'moveOrder', 'withdraw', 'returnFeeInfo', 'transferBalance', 'returnMarginAccountSummary', 'marginBuy', 'marginSell', 'getMarginPosition', 'closeMarginPosition', ] DATE_FORMAT='%Y-%m-%d %H:%M:%S'
""" Constant values for the Poloniex API """ PUBLIC_API = 'https://poloniex.com/public' PRIVATE_API = 'https://poloniex.com/tradingApi' PUBLIC_COMMANDS = [ 'returnTicker', 'return24hVolume', 'returnOrderBook', 'returnTradeHistory', 'returnChartData', 'returnCurrencies', 'returnLoanOrders', ] PRIVATE_COMMANDS = [ 'returnBalances', 'returnCompleteBalances', 'returnDepositAddresses', 'generateNewAddress', 'returnDepositsWithdrawals', 'returnOpenOrders', 'returnTradeHistory', 'returnAvailableAccountBalances', 'returnTradableBalances', 'returnOpenLoanOffers', 'returnOrderTrades', 'returnActiveLoans', 'returnLendingHistory', 'createLoanOffer', 'cancelLoanOffer', 'toggleAutoRenew', 'buy', 'sell', 'cancelOrder', 'moveOrder', 'withdraw', 'returnFeeInfo', 'transferBalance', 'returnMarginAccountSummary', 'marginBuy', 'marginSell', 'getMarginPosition', 'closeMarginPosition', ]
TODO: FIX FUNCTIONS. CHANGE USAGE FUNCTION TO BANNER. ADD ACTUAL USAGE FILE. FIX 'main' FUNCTION
#!/usr/bin/env python #SSH with Paramiko pg 27 import threading, paramiko, subprocess def usage(): #Provide description of program print "Black Hat Python SSH with Paramiko pg 27" print "" print "Enter Syntax or information for how program works" print "" sys.exit(0) def main() if not len(sys.argv[1:]): usage() def ssh_command(ip, user, passwd, command): client = paramiko.SSHClient() #client.load_host_keys('/home/justin/.ssh/known_hosts') client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(ip, username= user, password= passwd) ssh_session = client.get_transport().open_session() if ssh_session.active: ssh_session.exec_command(command) print ssh_session.recv(1024) #read banner while True: command = ssh_session.recv(1024) #get the command from the SSH server try: cmd_output = subprocess.check_output(command, shell=True) ssh_session.send(cmd_output) except Exception,e: ssh_session.send(str(e)) client.close() return ssh_command('192.168.1.59', 'justin', 'lovesthepython','ClientConnected') main()
#!/usr/bin/env python #SSH with Paramiko pg 27 import threading, paramiko, subprocess def usage(): #Provide description of program print "Black Hat Python SSH with Paramiko pg 27" print "" print "Enter Syntax or information for how program works" print "" sys.exit(0) def main() if not len(sys.argv[1:]): usage() def ssh_command(ip, user, passwd, command): client = paramiko.SSHClient() #client.load_host_keys('/home/justin/.ssh/known_hosts') client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(ip, username= user, password= passwd) ssh_session = client.get_transport().open_session() if ssh_session.active: ssh_session.exec_command(command) print ssh_session.recv(1024) #read banner while True: command = ssh_session.recv(1024) #get the command from the SSH server try: cmd_output = subprocess.check_output(command, shell=True) ssh_session.send(cmd_output) except Exception,e: ssh_session.send(str(e)) client.close() return ssh_command('192.168.1.59', 'justin', 'lovesthepython','ClientConnected') main()
Add note in docu about Shapely
""" This module provides utility functions for integrating with Shapely. .. note:: As GeoAlchemy 2 itself has no dependency on `Shapely`, applications using functions of this module have to ensure that `Shapely` is available. """ import shapely.wkb import shapely.wkt from .elements import WKBElement, WKTElement from .compat import buffer, bytes def to_shape(element): """ Function to convert a :class:`geoalchemy2.types.SpatialElement` to a Shapely geometry. Example:: lake = Session.query(Lake).get(1) polygon = to_shape(lake.geom) """ assert isinstance(element, (WKBElement, WKTElement)) if isinstance(element, WKBElement): return shapely.wkb.loads(bytes(element.data)) elif isinstance(element, WKTElement): return shapely.wkt.loads(element.data) def from_shape(shape, srid=-1): """ Function to convert a Shapely geometry to a :class:`geoalchemy2.types.WKBElement`. Additional arguments: ``srid`` An integer representing the spatial reference system. E.g. 4326. Default value is -1, which means no/unknown reference system. Example:: from shapely.geometry import Point wkb_element = from_shape(Point(5, 45), srid=4326) """ return WKBElement(buffer(shape.wkb), srid=srid)
""" This module provides utility functions for integrating with Shapely. """ import shapely.wkb import shapely.wkt from .elements import WKBElement, WKTElement from .compat import buffer, bytes def to_shape(element): """ Function to convert a :class:`geoalchemy2.types.SpatialElement` to a Shapely geometry. Example:: lake = Session.query(Lake).get(1) polygon = to_shape(lake.geom) """ assert isinstance(element, (WKBElement, WKTElement)) if isinstance(element, WKBElement): return shapely.wkb.loads(bytes(element.data)) elif isinstance(element, WKTElement): return shapely.wkt.loads(element.data) def from_shape(shape, srid=-1): """ Function to convert a Shapely geometry to a :class:`geoalchemy2.types.WKBElement`. Additional arguments: ``srid`` An integer representing the spatial reference system. E.g. 4326. Default value is -1, which means no/unknown reference system. Example:: from shapely.geometry import Point wkb_element = from_shape(Point(5, 45), srid=4326) """ return WKBElement(buffer(shape.wkb), srid=srid)
Update stable channel to 1.1 Review URL: https://codereview.chromium.org/138273002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@244706 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 3), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.1', 2, '-stable', 1), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 3), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.0', 2, '-stable', 1), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
Add monkey patch for mercurial trac
import logging from pylons import config, tmpl_context as c from pylons.controllers.util import abort # Monkey patch the lazywriter, since mercurial needs that on the stdout import paste.script.serve as serve serve.LazyWriter.closed = False # Conditionally import the trac components in case things trac isn't installed try: import os os.environ['TRAC_ENV_PARENT_DIR'] = '/usr/local/www' os.environ['PYTHON_EGG_CACHE'] = os.path.join(config['pylons.paths']['root'], 'egg_cache') import trac.web.main trac_app = trac.web.main.dispatch_request except: pass from kai.lib.base import BaseController log = logging.getLogger(__name__) class TracsController(BaseController): def run_app(self, environ, start_response): if not trac_app: abort(404) if c.user: environ['REMOTE_USER'] = c.user.displayname return trac_app(environ, start_response)
import logging from pylons import config, tmpl_context as c from pylons.controllers.util import abort # Conditionally import the trac components in case things trac isn't installed try: import os os.environ['TRAC_ENV_PARENT_DIR'] = '/usr/local/www' os.environ['PYTHON_EGG_CACHE'] = os.path.join(config['pylons.paths']['root'], 'egg_cache') import trac.web.main trac_app = trac.web.main.dispatch_request except: pass from kai.lib.base import BaseController log = logging.getLogger(__name__) class TracsController(BaseController): def run_app(self, environ, start_response): if not trac_app: abort(404) if c.user: environ['REMOTE_USER'] = c.user.displayname return trac_app(environ, start_response)
Use geoip helper instead of facade
<?php /** * Created by PhpStorm. * User: Bram * Date: 29-4-2017 * Time: 06:21 */ namespace Stormyy\B3\Helper; use GeoIP; abstract class PermissionHelper { public static function ip($ip){ if(\Auth::user() == null) { return preg_replace('/\.\d+\.\d+$/', '.***.***', $ip); } else { return $ip; } } public static function ipToFlag($ip){ $countryinfo = geoip()->getLocation($ip); return "<span class='flag-icon flag-icon-".strtolower($countryinfo['iso_code'])."' title='".$countryinfo['country']."'></span>"; } }
<?php /** * Created by PhpStorm. * User: Bram * Date: 29-4-2017 * Time: 06:21 */ namespace Stormyy\B3\Helper; use GeoIP; abstract class PermissionHelper { public static function ip($ip){ if(\Auth::user() == null) { return preg_replace('/\.\d+\.\d+$/', '.***.***', $ip); } else { return $ip; } } public static function ipToFlag($ip){ $countryinfo = GeoIp::getLocation($ip); return "<span class='flag-icon flag-icon-".strtolower($countryinfo['iso_code'])."' title='".$countryinfo['country']."'></span>"; } }
Set migration for compare_readings/group_compare_readings sql functions
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const database = require('../../models/database'); const sqlFile = database.sqlFile; module.exports = { fromVersion: '0.3.0', toVersion: '0.4.0', up: async db => { try { await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/create_language_types_enum.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/add_language_column.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/logemail/create_log_table.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_baseline_table.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_function_get_average_reading.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/compareReadings/create_function_get_compare_readings.sql')); } catch (err) { throw new Error('Error while migrating each sql file'); } } };
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const database = require('../../models/database'); const sqlFile = database.sqlFile; module.exports = { fromVersion: '0.3.0', toVersion: '0.4.0', up: async db => { try { await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/create_language_types_enum.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/preferences/add_language_column.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/logemail/create_log_table.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_baseline_table.sql')); await db.none(sqlFile('../migrations/0.3.0-0.4.0/sql/baseline/create_function_get_average_reading.sql')); } catch (err) { throw new Error('Error while migrating each sql file'); } } };
Fix code style and change repo_id as unique field.
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('bookmarks', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, repo_id: { type: Sequelize.INTEGER, unique: true, }, created_at: { allowNull: false, type: Sequelize.DATE, }, updated_at: { allowNull: false, type: Sequelize.DATE, } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('bookmarks'); } };
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('bookmarks', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, repo_id: { type: Sequelize.INTEGER }, created_at: { allowNull: false, type: Sequelize.DATE }, updated_at: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('bookmarks'); } };
Complete removal of reversion usage
# # Copyright (c) 2009 Brad Taylor <brad@getcoded.net> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from snowy.accounts.models import UserProfile from snowy.notes.models import Note, NoteTag #from reversion.admin import VersionAdmin from django.contrib import admin #class NoteAdmin(VersionAdmin): class NoteAdmin(admin.ModelAdmin): list_display = ('created', 'author', 'title') search_fields = ['content', 'title'] prepopulated_fields = {'slug': ('title',)} admin.site.register(Note, NoteAdmin) admin.site.register(NoteTag) admin.site.register(UserProfile)
# # Copyright (c) 2009 Brad Taylor <brad@getcoded.net> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from snowy.accounts.models import UserProfile from snowy.notes.models import Note, NoteTag from reversion.admin import VersionAdmin from django.contrib import admin class NoteAdmin(VersionAdmin): list_display = ('created', 'author', 'title') search_fields = ['content', 'title'] prepopulated_fields = {'slug': ('title',)} admin.site.register(Note, NoteAdmin) admin.site.register(NoteTag) admin.site.register(UserProfile)
Increase timeouts for idling extended test
package idling import ( "time" "github.com/openshift/origin/pkg/util/errors" exutil "github.com/openshift/origin/test/extended/util" kapi "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/util/wait" ) func waitForEndpointsAvailable(oc *exutil.CLI, serviceName string) error { return wait.Poll(200*time.Millisecond, 3*time.Minute, func() (bool, error) { ep, err := oc.KubeClient().Core().Endpoints(oc.Namespace()).Get(serviceName) // Tolerate NotFound b/c it could take a moment for the endpoints to be created if errors.TolerateNotFoundError(err) != nil { return false, err } return (len(ep.Subsets) > 0) && (len(ep.Subsets[0].Addresses) > 0), nil }) } func waitForNoPodsAvailable(oc *exutil.CLI) error { return wait.Poll(200*time.Millisecond, 3*time.Minute, func() (bool, error) { //ep, err := oc.KubeClient().Core().Endpoints(oc.Namespace()).Get(serviceName) pods, err := oc.KubeClient().Core().Pods(oc.Namespace()).List(kapi.ListOptions{}) if err != nil { return false, err } return len(pods.Items) == 0, nil }) }
package idling import ( "time" "github.com/openshift/origin/pkg/util/errors" exutil "github.com/openshift/origin/test/extended/util" kapi "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/util/wait" ) func waitForEndpointsAvailable(oc *exutil.CLI, serviceName string) error { return wait.Poll(200*time.Millisecond, 2*time.Minute, func() (bool, error) { ep, err := oc.KubeClient().Core().Endpoints(oc.Namespace()).Get(serviceName) // Tolerate NotFound b/c it could take a moment for the endpoints to be created if errors.TolerateNotFoundError(err) != nil { return false, err } return (len(ep.Subsets) > 0) && (len(ep.Subsets[0].Addresses) > 0), nil }) } func waitForNoPodsAvailable(oc *exutil.CLI) error { return wait.Poll(200*time.Millisecond, 2*time.Minute, func() (bool, error) { //ep, err := oc.KubeClient().Core().Endpoints(oc.Namespace()).Get(serviceName) pods, err := oc.KubeClient().Core().Pods(oc.Namespace()).List(kapi.ListOptions{}) if err != nil { return false, err } return len(pods.Items) == 0, nil }) }
Improve debugging, fix an error on /usage
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { IndexLink } from 'react-router'; import { usage, todo } from './styles'; import { example, p, link } from '../homepage/styles'; import { setConfig } from '../../actions'; class Usage extends Component { /*eslint-disable */ static onEnter({store, nextState, replaceState, callback}) { fetch('/api/v1/conf').then((r) => { return r.json(); }).then((conf) => { store.dispatch(setConfig(conf)); console.warn('TODO are you sure this info should be exposed?'); callback(); }); } /*eslint-enable */ render() { return <div className={usage}> <Helmet title='Usage' /> <h2 className={example}>Usage:</h2> <div className={p}> <span className={todo}>// TODO: write an article</span> <pre className={todo}>config: {JSON.stringify(this.props.config, null, 2)}</pre> </div> <br /> go <IndexLink to='/' className={link}>home</IndexLink> </div>; } } export default connect(store => ({ config: store.config }))(Usage);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { IndexLink } from 'react-router'; import { usage, todo } from './styles'; import { example, p, link } from '../homepage/styles'; import { setConfig } from '../../actions'; class Usage extends Component { /*eslint-disable */ static onEnter({store, nextState, replaceState, callback}) { fetch('/api/v1/conf').then((r) => { return r.json(); }).then((conf) => { store.dispatch(setConfig(conf)); console.warn('Faked connection latency! Please, take a look ---> `server/api.go:22`'); callback(); }); } /*eslint-enable */ render() { return <div className={usage}> <Helmet title='Usage' /> <h2 className={example}>Usage:</h2> <div className={p}> <span className={todo}>// TODO: write an article</span> <pre className={todo}>config: {JSON.stringify(this.props.config, null, 2)}</pre> </div> <br /> go <IndexLink to='/' className={link}>home</IndexLink> </div>; } } export default connect(store => ({ config: store.config }))(Usage);
Use input text for numbers
import React from 'react'; import PropTypes from 'prop-types'; import Text from './text'; import Radio from './radio'; import Select from './select'; import Date from './date'; import Blob from './blob'; // TODO: fix numbers input in iOS as we can't accept the value // import Number from './number'; // REDUX-FORM custom inputs // http://redux-form.com/6.5.0/docs/api/Field.md/ export default function getInputForm(props) { switch (props.question.type) { case 'text': return <Text {...props} />; case 'number': return <Text {...props} />; // Use the number component here case 'radio': return <Radio {...props} />; case 'select': return <Select {...props} />; case 'date': return <Date {...props} />; case 'point': return <Text {...props} />; case 'blob': return <Blob {...props} />; default: return null; } } getInputForm.propTypes = { question: PropTypes.shape({ value: PropTypes.number, type: PropTypes.string.isRequired, defaultValue: PropTypes.oneOfType([ PropTypes.number.isRequired, PropTypes.string.isRequired ]) }).isRequired };
import React from 'react'; import PropTypes from 'prop-types'; import Text from './text'; import Radio from './radio'; import Select from './select'; import Date from './date'; import Blob from './blob'; import Number from './number'; // REDUX-FORM custom inputs // http://redux-form.com/6.5.0/docs/api/Field.md/ export default function getInputForm(props) { switch (props.question.type) { case 'text': return <Text {...props} />; case 'number': return <Number {...props} />; case 'radio': return <Radio {...props} />; case 'select': return <Select {...props} />; case 'date': return <Date {...props} />; case 'point': return <Text {...props} />; case 'blob': return <Blob {...props} />; default: return null; } } getInputForm.propTypes = { question: PropTypes.shape({ value: PropTypes.number, type: PropTypes.string.isRequired, defaultValue: PropTypes.oneOfType([ PropTypes.number.isRequired, PropTypes.string.isRequired ]) }).isRequired };
Split __init__.py into separate files.
import os from setuptools import setup setup( name = "prometheus_client", version = "0.0.9", author = "Brian Brazil", author_email = "brian.brazil@gmail.com", description = ("Python client for the Prometheus monitoring system."), long_description = ("See https://github.com/prometheus/client_python/blob/master/README.md for documentation."), license = "Apache Software License 2.0", keywords = "prometheus monitoring instrumentation client", url = "https://github.com/prometheus/client_python", packages=['prometheus_client', 'prometheus_client.bridge'], test_suite="tests", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "Topic :: System :: Monitoring", "License :: OSI Approved :: Apache Software License", ], )
import os from setuptools import setup setup( name = "prometheus_client", version = "0.0.9", author = "Brian Brazil", author_email = "brian.brazil@gmail.com", description = ("Python client for the Prometheus monitoring system."), long_description = ("See https://github.com/prometheus/client_python/blob/master/README.md for documentation."), license = "Apache Software License 2.0", keywords = "prometheus monitoring instrumentation client", url = "https://github.com/prometheus/client_python", packages=['prometheus_client'], test_suite="tests", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "Topic :: System :: Monitoring", "License :: OSI Approved :: Apache Software License", ], )
Use the same FileSystem as the outputDir. Otherwise `java.nio.file.ProviderMismatchException` can be thrown if it differs from `FileSystems.getDefault()` (which was implicitly used by `Paths.get()`).
// Copyright © 2013-2015 Esko Luontola <www.orfjackal.net> // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 package net.orfjackal.retrolambda.files; import org.objectweb.asm.ClassReader; import java.io.IOException; import java.nio.file.*; public class OutputDirectory { private final Path outputDir; public OutputDirectory(Path outputDir) { this.outputDir = outputDir; } public void writeClass(byte[] bytecode) throws IOException { if (bytecode == null) { return; } ClassReader cr = new ClassReader(bytecode); Path relativePath = outputDir.getFileSystem().getPath(cr.getClassName() + ".class"); writeFile(relativePath, bytecode); } public void writeFile(Path relativePath, byte[] content) throws IOException { Path outputFile = outputDir.resolve(relativePath); Files.createDirectories(outputFile.getParent()); Files.write(outputFile, content); } }
// Copyright © 2013-2015 Esko Luontola <www.orfjackal.net> // This software is released under the Apache License 2.0. // The license text is at http://www.apache.org/licenses/LICENSE-2.0 package net.orfjackal.retrolambda.files; import org.objectweb.asm.ClassReader; import java.io.IOException; import java.nio.file.*; public class OutputDirectory { private final Path outputDir; public OutputDirectory(Path outputDir) { this.outputDir = outputDir; } public void writeClass(byte[] bytecode) throws IOException { if (bytecode == null) { return; } ClassReader cr = new ClassReader(bytecode); Path relativePath = Paths.get(cr.getClassName() + ".class"); writeFile(relativePath, bytecode); } public void writeFile(Path relativePath, byte[] content) throws IOException { Path outputFile = outputDir.resolve(relativePath); Files.createDirectories(outputFile.getParent()); Files.write(outputFile, content); } }
Use a class decorator to add enum values to classes
from __future__ import unicode_literals import os from cffi import FFI __version__ = '2.0.0a1' header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h') header = open(header_file).read() header += '#define SPOTIFY_API_VERSION ...\n' ffi = FFI() ffi.cdef(header) lib = ffi.verify('#include "libspotify/api.h"', libraries=[str('spotify')]) def _to_text(chars): return ffi.string(chars).decode('utf-8') def enum(prefix): def wrapper(obj): for attr in dir(lib): if attr.startswith(prefix): setattr(obj, attr.replace(prefix, ''), getattr(lib, attr)) return obj return wrapper @enum('SP_ERROR_') class Error(Exception): def __init__(self, error_code): self.error_code = error_code message = _to_text(lib.sp_error_message(error_code)) super(Error, self).__init__(message)
from __future__ import unicode_literals import os from cffi import FFI __version__ = '2.0.0a1' header_file = os.path.join(os.path.dirname(__file__), 'api.processed.h') header = open(header_file).read() header += '#define SPOTIFY_API_VERSION ...\n' ffi = FFI() ffi.cdef(header) lib = ffi.verify('#include "libspotify/api.h"', libraries=[str('spotify')]) def _to_text(chars): return ffi.string(chars).decode('utf-8') def _add_enum(obj, prefix): for attr in dir(lib): if attr.startswith(prefix): setattr(obj, attr.replace(prefix, ''), getattr(lib, attr)) class Error(Exception): def __init__(self, error_code): self.error_code = error_code message = _to_text(lib.sp_error_message(error_code)) super(Error, self).__init__(message) _add_enum(Error, 'SP_ERROR_')
Enable errors in the right place.
<?php require __DIR__ . '/../vendor/autoload.php'; session_save_path('.\sessions'); session_start(); define('BASEPATH', $_SERVER['DOCUMENT_ROOT']); $connections = array(); include('config.php'); if ($debug) { error_reporting(E_ALL); ini_set('display_errors', 'On'); } function makeConnection($connection_name = ''){ global $connections; if($connection_name == '') { return "No connection type given"; exit; } unset($db); $driver=$connections[$connection_name]['driver']; $dbhost=$connections[$connection_name]['dbhost']; $dbname=$connections[$connection_name]['dbname']; $dbuser=$connections[$connection_name]['dbuser']; $dbpassword=$connections[$connection_name]['dbpassword']; if (strlen($dbhost) > 0) { try { if($driver=="mysql"){ $db = new PDO("$driver:host=$dbhost;dbname=$dbname", $dbuser, $dbpassword); }else{ $db = new PDO("$driver:SERVER=$dbhost;DATABASE=$dbname", $dbuser, $dbpassword); } $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } catch (PDOException $e) { echo $e->getMessage(); } } return $db; }
<?php require __DIR__ . '/../vendor/autoload.php'; session_save_path('.\sessions'); session_start(); if ($debug) { error_reporting(E_ALL); ini_set('display_errors', 'On'); } define('BASEPATH', $_SERVER['DOCUMENT_ROOT']); $connections = array(); include('config.php'); function makeConnection($connection_name = ''){ global $connections; if($connection_name == '') { return "No connection type given"; exit; } unset($db); $driver=$connections[$connection_name]['driver']; $dbhost=$connections[$connection_name]['dbhost']; $dbname=$connections[$connection_name]['dbname']; $dbuser=$connections[$connection_name]['dbuser']; $dbpassword=$connections[$connection_name]['dbpassword']; if (strlen($dbhost) > 0) { try { if($driver=="mysql"){ $db = new PDO("$driver:host=$dbhost;dbname=$dbname", $dbuser, $dbpassword); }else{ $db = new PDO("$driver:SERVER=$dbhost;DATABASE=$dbname", $dbuser, $dbpassword); } $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } catch (PDOException $e) { echo $e->getMessage(); } } return $db; }
Improve exception message when fronted not found
<?php namespace Ilios\WebBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Ilios\CliBundle\Command\UpdateFrontendCommand; use Ilios\WebBundle\Service\WebIndexFromJson; class IndexController extends Controller { public function indexAction() { $fs = $this->get('ilioscore.symfonyfilesystem'); $path = $this->getParameter('kernel.cache_dir') . '/' . UpdateFrontendCommand::CACHE_FILE_NAME; if (!$fs->exists($path)) { throw new \Exception( "Unable to load the index file at {$path}. Run ilios:maintenance:update-frontend to create it." ); } $contents = $fs->readFile($path); $response = new Response($contents); $response->headers->set('Content-Type', 'text/html'); $response->setPublic(); $response->setMaxAge(60); return $response; } }
<?php namespace Ilios\WebBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; use Ilios\CliBundle\Command\UpdateFrontendCommand; use Ilios\WebBundle\Service\WebIndexFromJson; class IndexController extends Controller { public function indexAction() { $fs = $this->get('ilioscore.symfonyfilesystem'); $path = $this->getParameter('kernel.cache_dir') . '/' . UpdateFrontendCommand::CACHE_FILE_NAME; if (!$fs->exists($path)) { throw new \Exception( 'Unable to load the index file. Run ilios:maintenance:update-frontend to create it.' ); } $contents = $fs->readFile($path); $response = new Response($contents); $response->headers->set('Content-Type', 'text/html'); $response->setPublic(); $response->setMaxAge(60); return $response; } }
Make functions public for unit test
package io.luna.game.model; import io.luna.game.model.mob.Player; import org.junit.Test; /** * A test that ensures that functions within {@link Position} are functioning correctly. * * @author lare96 <http://github.com/lare96> */ public final class AreaTest { /** * Ensures the north east {@code x} coordinate is larger than the south west {@code x} coordinate. */ @Test(expected = IllegalArgumentException.class) public void testNorthEastX() { newArea(0, 0, -1, 0); } /** * Ensures the north east {@code y} coordinate is larger than the south west {@code y} coordinate. */ @Test(expected = IllegalArgumentException.class) public void testNorthEastY() { newArea(0, 0, 0, -1); } /** * Constructs a new {@link Area} for this test. */ private void newArea(int swX, int swY, int neX, int neY) { new Area(swX, swY, neX, neY) { @Override public void enter(Player player) { } @Override public void exit(Player player) { } }; } }
package io.luna.game.model; import io.luna.game.model.mob.Player; import org.junit.Test; /** * A test that ensures that functions within {@link Position} are functioning correctly. * * @author lare96 <http://github.com/lare96> */ final class AreaTest { /** * Ensures the north east {@code x} coordinate is larger than the south west {@code x} coordinate. */ @Test(expected = IllegalArgumentException.class) void testNorthEastX() { newArea(0, 0, -1, 0); } /** * Ensures the north east {@code y} coordinate is larger than the south west {@code y} coordinate. */ @Test(expected = IllegalArgumentException.class) void testNorthEastY() { newArea(0, 0, 0, -1); } /** * Constructs a new {@link Area} for this test. */ private void newArea(int swX, int swY, int neX, int neY) { new Area(swX, swY, neX, neY) { @Override public void enter(Player player) { } @Override public void exit(Player player) { } }; } }
Fix .remove method not removing values.
'use strict'; /* property.js * Object to represent CSS properties. */ const Value = require('./value'); module.exports = exports = Property; function Property(sel, values) { if (!(this instanceof Property)) return new Property(sel, values); // Type checking if (typeof sel !== 'string') throw new TypeError('sel must be a string'); if (Array.isArray(values)) values.forEach((x) => { if (!(x instanceof Value)) throw new TypeError('values must only contain Value objects'); }); else if (typeof values === 'undefined'); else throw new TypeError('values must be an array of Value objects'); // Set values this.sel = sel; this.values = Array.isArray(values) ? values : []; } Property.prototype.add = function(value){ if (!(value instanceof Value)) throw new TypeError('value must be a Value object'); this.values.push(value); }; Property.prototype.set = function(index, value){ if (typeof index !== 'number') throw new TypeError('index must be a number'); if (!(value instanceof Value)) throw new TypeError('value must be a Value object'); this.values[index] = value; }; Property.prototype.remove = function(index){ this.values.splice(index, 1); };
'use strict'; /* property.js * Object to represent CSS properties. */ const Value = require('./value'); module.exports = exports = Property; function Property(sel, values) { if (!(this instanceof Property)) return new Property(sel, values); // Type checking if (typeof sel !== 'string') throw new TypeError('sel must be a string'); if (Array.isArray(values)) values.forEach((x) => { if (!(x instanceof Value)) throw new TypeError('values must only contain Value objects'); }); else if (typeof values === 'undefined'); else throw new TypeError('values must be an array of Value objects'); // Set values this.sel = sel; this.values = Array.isArray(values) ? values : []; } Property.prototype.add = function(value){ if (!(value instanceof Value)) throw new TypeError('value must be a Value object'); this.values.push(value); }; Property.prototype.set = function(index, value){ if (typeof index !== 'number') throw new TypeError('index must be a number'); if (!(value instanceof Value)) throw new TypeError('value must be a Value object'); this.values[index] = value; }; Property.prototype.remove = function(index){ this.values.slice(index, index + 1); };
Allow passing multiple gaurds to the auth middleware
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class Authenticate { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string ...$guards * @return mixed */ public function handle($request, Closure $next, ...$guards) { if ($this->check($guards)) { return $next($request); } if ($request->ajax() || $request->wantsJson()) { return response('Unauthorized.', 401); } else { return redirect()->guest('login'); } } /** * Determine if the user is logged in to any of the given guards. * * @param array $guards * @return bool */ protected function check(array $guards) { if (empty($guards)) { return Auth::check(); } foreach ($guards as $guard) { if (Auth::guard($guard)->check()) { return true; } } return false; } }
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class Authenticate { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->guest()) { if ($request->ajax() || $request->wantsJson()) { return response('Unauthorized.', 401); } else { return redirect()->guest('login'); } } return $next($request); } }
Use 4 as minToWrap prop
const React = require('react'); const Changes = require('./Changes'); /** * Render an entire diff from a state. * @type {React} */ const RichDiff = React.createClass({ propTypes: { className: React.PropTypes.string, state: React.PropTypes.object.isRequired, minToWrap: React.PropTypes.number }, getDefaultProps() { return { className: '', minToWrap: 4 }; }, render() { const { state, className, minToWrap } = this.props; return ( <Changes Wrapper={props => <div className={'RichDiff ' + className}>{props.children}</div>} changes={state.changes} minToWrap={minToWrap} /> ); } }); module.exports = RichDiff;
const React = require('react'); const Changes = require('./Changes'); /** * Render an entire diff from a state. * @type {React} */ const RichDiff = React.createClass({ propTypes: { className: React.PropTypes.string, state: React.PropTypes.object.isRequired, minToWrap: React.PropTypes.number }, getDefaultProps() { return { className: '', minToWrap: 2 }; }, render() { const { state, className, minToWrap } = this.props; return ( <Changes Wrapper={props => <div className={'RichDiff ' + className}>{props.children}</div>} changes={state.changes} minToWrap={minToWrap} /> ); } }); module.exports = RichDiff;
Remove real database during testing
import pytest import vcr try: from unittest import mock except ImportError: import mock from k2catalogue.models import EPIC, create_session from k2catalogue.simbad import Simbad @pytest.fixture def session(): return create_session() @pytest.fixture def epic(session): return mock.Mock(ra=123.456, dec=-56.789) @pytest.fixture def simbad(epic): return Simbad(epic) @pytest.fixture def form_data(simbad): return simbad.form_data(radius=5.) @vcr.use_cassette('.cassettes/response.yml') @pytest.fixture def response(simbad): return simbad.send_request() def test_form_data(form_data): assert form_data['Coord'] == '123.46 -56.79' def test_response(response): assert response.status_code == 200 def test_open(simbad): with mock.patch('k2catalogue.simbad.webbrowser.open') as mock_open: simbad.open(radius=10) url, = mock_open.call_args[0] assert 'file://' in url and 'html' in url
import pytest import vcr try: from unittest import mock except ImportError: import mock from k2catalogue.models import EPIC, create_session from k2catalogue.simbad import Simbad @pytest.fixture def session(): return create_session() @pytest.fixture def epic(session): return session.query(EPIC).filter(EPIC.epic_id == 201763507).first() @pytest.fixture def simbad(epic): return Simbad(epic) @pytest.fixture def form_data(simbad): return simbad.form_data(radius=5.) @vcr.use_cassette('.cassettes/response.yml') @pytest.fixture def response(simbad): return simbad.send_request() def test_form_data(form_data): assert form_data['Coord'] == '169.18 4.72' def test_response(response): assert response.status_code == 200 def test_open(simbad): with mock.patch('k2catalogue.simbad.webbrowser.open') as mock_open: simbad.open(radius=10) url, = mock_open.call_args[0] assert 'file://' in url and 'html' in url
Fix unexpected success on sum(bytearray())
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): def test_sum_list(self): self.assertCodeExecution(""" print(sum([1, 2, 3, 4, 5, 6, 7])) """) def test_sum_tuple(self): self.assertCodeExecution(""" print(sum((1, 2, 3, 4, 5, 6, 7))) """) def test_sum_iterator(self): self.assertCodeExecution(""" i = iter([1, 2]) print(sum(i)) print(sum(i)) """) def test_sum_mix_floats_and_ints(self): self.assertCodeExecution(""" print(sum([1, 1.414, 2, 3.14159])) """) class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_frozenzet', ]
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): def test_sum_list(self): self.assertCodeExecution(""" print(sum([1, 2, 3, 4, 5, 6, 7])) """) def test_sum_tuple(self): self.assertCodeExecution(""" print(sum((1, 2, 3, 4, 5, 6, 7))) """) def test_sum_iterator(self): self.assertCodeExecution(""" i = iter([1, 2]) print(sum(i)) print(sum(i)) """) def test_sum_mix_floats_and_ints(self): self.assertCodeExecution(""" print(sum([1, 1.414, 2, 3.14159])) """) class BuiltinSumFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = ["sum"] not_implemented = [ 'test_bytearray', 'test_frozenzet', ]
Add comment explaining extension boot process
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Extension; use Flarum\Foundation\AbstractServiceProvider; use Illuminate\Contracts\Container\Container; class ExtensionServiceProvider extends AbstractServiceProvider { /** * {@inheritdoc} */ public function register() { $this->app->singleton(ExtensionManager::class); $this->app->alias(ExtensionManager::class, 'flarum.extensions'); // Boot extensions when the app is booting. This must be done as a boot // listener on the app rather than in the service provider's boot method // below, so that extensions have a chance to register things on the // container before the core boot code runs. $this->app->booting(function (Container $app) { $app->make('flarum.extensions')->extend($app); }); } /** * {@inheritdoc} */ public function boot() { $events = $this->app->make('events'); $events->subscribe(DefaultLanguagePackGuard::class); } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Extension; use Flarum\Foundation\AbstractServiceProvider; use Illuminate\Contracts\Container\Container; class ExtensionServiceProvider extends AbstractServiceProvider { /** * {@inheritdoc} */ public function register() { $this->app->singleton(ExtensionManager::class); $this->app->alias(ExtensionManager::class, 'flarum.extensions'); $this->app->booting(function (Container $app) { $app->make('flarum.extensions')->extend($app); }); } /** * {@inheritdoc} */ public function boot() { $events = $this->app->make('events'); $events->subscribe(DefaultLanguagePackGuard::class); } }
Remove the visually hidden so it doesn't read Home twice
{{-- $breadcrumbs => array // [['display_name', 'relative_url']] --}} <nav class="mt-6 mb-2" aria-label="Breadcrumbs"> <ul class="list-reset text-sm"> @foreach($breadcrumbs as $key=>$crumb) @if($key == 0) <li class="inline"> <a href="/"><span class="text-black align-middle">@svg('home', 'w-4 h-4')</span></a> <span class="icon-right-open px-2"></span> @elseif($key == (count($breadcrumbs) - 1)) <li class="font-bold text-green inline"> {{ $crumb['display_name'] }} @else <li class="inline"> <a href="{{ $crumb['relative_url'] }}" class="text-green hover:underline">{{ $crumb['display_name'] }}</a> <span class="icon-right-open px-2"></span> @endif </li> @endforeach </ul> </nav>
{{-- $breadcrumbs => array // [['display_name', 'relative_url']] --}} <nav class="mt-6 mb-2" aria-label="Breadcrumbs"> <ul class="list-reset text-sm"> @foreach($breadcrumbs as $key=>$crumb) @if($key == 0) <li class="inline"> <a href="/"><span class="text-black align-middle">@svg('home', 'w-4 h-4')</span><span class="visually-hidden">{{ strip_tags($crumb['display_name']) }}</span></a> <span class="icon-right-open px-2"></span> @elseif($key == (count($breadcrumbs) - 1)) <li class="font-bold text-green inline"> {{ $crumb['display_name'] }} @else <li class="inline"> <a href="{{ $crumb['relative_url'] }}" class="text-green hover:underline">{{ $crumb['display_name'] }}</a> <span class="icon-right-open px-2"></span> @endif </li> @endforeach </ul> </nav>
Use click instead of argparse
#! /usr/bin/env python from __future__ import print_function import click import json from collections import OrderedDict def json_loader(sortkeys): def _loader(line): if sortkeys: return json.loads(line) else: # if --no-sortkeys, let's preserve file order return json.JSONDecoder(object_pairs_hook=OrderedDict).decode(line) return _loader @click.command() @click.option('indent', '-i', '--indent', default=2, help='indentation for pretty-printing') @click.option('--sortkeys/--no-sortkeys', default=False, help='sort object keys') @click.argument('infile', type=click.File()) def cli(indent, sortkeys, infile): """Pretty-print LDJSON.""" loader = json_loader(sortkeys) for line in infile: record = loader(line) print(json.dumps(record, indent=indent, sort_keys=sortkeys)) if __name__ == '__main__': cli()
#! /usr/bin/env python from __future__ import print_function import argparse import json parser = argparse.ArgumentParser(description='Pretty-print LDJSON.') parser.add_argument('--indent', metavar='N', type=int, default=2, dest='indent', help='indentation for pretty-printing') parser.add_argument('--file', metavar='FILE', required=True, dest='file', type=argparse.FileType('r'), help='input LDJSON file') parser.add_argument('--sort', action='store_true', dest='sortkeys', help='sort object keys') args = parser.parse_args() for line in args.file: record = json.loads(line) print(json.dumps(record, indent=args.indent, sort_keys=args.sortkeys))
Change the LD search path
from cffi import FFI ffi = FFI() ffi.cdef(""" typedef struct _fluid_hashtable_t fluid_settings_t; typedef struct _fluid_synth_t fluid_synth_t; typedef struct _fluid_audio_driver_t fluid_audio_driver_t; fluid_settings_t* new_fluid_settings(void); fluid_synth_t* new_fluid_synth(fluid_settings_t* settings); fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth); int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets); int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel); int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key); void delete_fluid_audio_driver(fluid_audio_driver_t* driver); int delete_fluid_synth(fluid_synth_t* synth); void delete_fluid_settings(fluid_settings_t* settings); """) C = ffi.dlopen("libfluidsynth.so.1")
from cffi import FFI ffi = FFI() ffi.cdef(""" typedef struct _fluid_hashtable_t fluid_settings_t; typedef struct _fluid_synth_t fluid_synth_t; typedef struct _fluid_audio_driver_t fluid_audio_driver_t; fluid_settings_t* new_fluid_settings(void); fluid_synth_t* new_fluid_synth(fluid_settings_t* settings); fluid_audio_driver_t* new_fluid_audio_driver(fluid_settings_t* settings, fluid_synth_t* synth); int fluid_synth_sfload(fluid_synth_t* synth, const char* filename, int reset_presets); int fluid_synth_noteon(fluid_synth_t* synth, int chan, int key, int vel); int fluid_synth_noteoff(fluid_synth_t* synth, int chan, int key); void delete_fluid_audio_driver(fluid_audio_driver_t* driver); int delete_fluid_synth(fluid_synth_t* synth); void delete_fluid_settings(fluid_settings_t* settings); """) C = ffi.dlopen("/usr/lib/x86_64-linux-gnu/libfluidsynth.so.1") # Testing
Remove unused variable and fix typo
package com.mgaetan89.showsrage.fragment; import com.mgaetan89.showsrage.R; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class ShowsSectionFragment_GetAdapterLayoutResourceTest { @Parameterized.Parameter(1) public int layoutId; @Parameterized.Parameter(0) public String preferredShowLayout; @Test public void getAdapterLayoutResource() { assertThat(ShowsSectionFragment.getAdapterLayoutResource(this.preferredShowLayout)).isEqualTo(this.layoutId); } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {null, R.layout.adapter_shows_list_content_poster}, {"", R.layout.adapter_shows_list_content_poster}, {"banner", R.layout.adapter_shows_list_content_banner}, {"fan_art", R.layout.adapter_shows_list_content_poster}, {"poster", R.layout.adapter_shows_list_content_poster}, }); } }
package com.mgaetan89.showsrage.fragment; import com.google.gson.Gson; import com.mgaetan89.showsrage.R; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class ShowsSectionFragment_GetAdapterLayoutResourceTest { @Parameterized.Parameter(1) public int layoutId; @Parameterized.Parameter(0) public String preferedShowLayout; @Test public void getAdapterLayoutResource() { assertThat(ShowsSectionFragment.getAdapterLayoutResource(this.preferedShowLayout)).isEqualTo(this.layoutId); } @Parameterized.Parameters public static Collection<Object[]> data() { Gson gson = new Gson(); return Arrays.asList(new Object[][]{ {null, R.layout.adapter_shows_list_content_poster}, {"", R.layout.adapter_shows_list_content_poster}, {"banner", R.layout.adapter_shows_list_content_banner}, {"fan_art", R.layout.adapter_shows_list_content_poster}, {"poster", R.layout.adapter_shows_list_content_poster}, }); } }
Fix bad recurse method name.
/** * Utility to determine is an argument value corresponds * to a known command name (alias). * * @param cmd The argument string. * @param commands The list of known commands. */ module.exports = function getCommandByName(cmd, commands, opts) { opts = opts || {}; var z, arg, k, v; for(z in commands) { arg = commands[z]; if(~arg.names().indexOf(cmd)) { return arg; } } // recurse after testing top-level if(opts.recurse) { for(z in commands) { arg = commands[z]; if(Object.keys(arg.commands()).length) { v = getCommandByName(cmd, arg.commands(), opts); if(v) { return v; } } } } }
/** * Utility to determine is an argument value corresponds * to a known command name (alias). * * @param cmd The argument string. * @param commands The list of known commands. */ module.exports = function getCommandByName(cmd, commands, opts) { opts = opts || {}; var z, arg, k, v; for(z in commands) { arg = commands[z]; if(~arg.names().indexOf(cmd)) { return arg; } } // recurse after testing top-level if(opts.recurse) { for(z in commands) { arg = commands[z]; if(Object.keys(arg.commands()).length) { v = alias(cmd, arg.commands(), opts); if(v) { return v; } } } } }
Copy main module descriptor 1:1
/* * Bach - Java Shell Builder * Copyright (C) 2019 Christian Stein * * 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. */ // --main-class de.sormuras.bach.Bach open /*test*/ module de.sormuras.bach /*extends "main" module*/ { // "test" requires org.junit.jupiter; // "main" requires java.compiler; requires java.net.http; exports de.sormuras.bach; exports de.sormuras.bach.project; uses java.util.spi.ToolProvider; }
/* * Bach - Java Shell Builder * Copyright (C) 2019 Christian Stein * * 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. */ // --main-class de.sormuras.bach.Bach open /*test*/ module de.sormuras.bach /*extends "main" module*/ { requires org.junit.jupiter; // --- requires java.compiler; requires java.net.http; // exports de.sormuras.bach; // exports de.sormuras.bach.project; // exports de.sormuras.bach.project; uses java.util.spi.ToolProvider; }
Use createTableIfNotExists over plain createTable
exports.up = function(knex, Promise) { return Promise.all([ knex.schema.createTableIfNotExists('users', function(table) { table.increments(); table.string('name'); table.string('email').unique(); table.string('password'); table.string('passwordResetToken'); table.dateTime('passwordResetExpires'); table.string('gender'); table.string('phone'); table.string('location'); table.string('website'); table.string('picture'); table.string('facebook'); table.string('twitter'); table.string('google'); table.timestamps(); }) ]); }; exports.down = function(knex, Promise) { return Promise.all([ knex.schema.dropTable('users') ]) };
exports.up = function(knex, Promise) { return Promise.all([ knex.schema.createTable('users', function(table) { table.increments(); table.string('name'); table.string('email').unique(); table.string('password'); table.string('passwordResetToken'); table.dateTime('passwordResetExpires'); table.string('gender'); table.string('phone'); table.string('location'); table.string('website'); table.string('picture'); table.string('facebook'); table.string('twitter'); table.string('google'); table.timestamps(); }) ]); }; exports.down = function(knex, Promise) { return Promise.all([ knex.schema.dropTable('users') ]) };
Fix regression in test due to vert.x update
package com.gentics.mesh.etc; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Test; import io.vertx.core.http.CaseInsensitiveHeaders; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerRequest; import io.vertx.ext.web.ParsedHeaderValues; import io.vertx.ext.web.Route; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.impl.RouteImpl; public class RouterStorageTest { private RouterStorage storage = new RouterStorage(null, null, null, null); @Test public void testFailureHandler() throws Exception { RoutingContext rc = mock(RoutingContext.class); Route currentRoute = mock(RouteImpl.class); when(currentRoute.getPath()).thenReturn("/blub"); when(rc.currentRoute()).thenReturn(currentRoute); ParsedHeaderValues headerValues = mock(ParsedHeaderValues.class); when(rc.parsedHeaders()).thenReturn(headerValues); HttpServerRequest request = mock(HttpServerRequest.class); when(request.query()).thenReturn("?blub"); when(request.method()).thenReturn(HttpMethod.GET); when(request.uri()).thenReturn(""); when(rc.request()).thenReturn(request); when(rc.normalisedPath()).thenReturn("/blub"); when(rc.queryParams()).thenReturn(new CaseInsensitiveHeaders()); storage.getRootRouter().handleFailure(rc); } }
package com.gentics.mesh.etc; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Test; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerRequest; import io.vertx.ext.web.ParsedHeaderValues; import io.vertx.ext.web.Route; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.impl.RouteImpl; public class RouterStorageTest { private RouterStorage storage = new RouterStorage(null, null, null, null); @Test public void testFailureHandler() throws Exception { RoutingContext rc = mock(RoutingContext.class); Route currentRoute = mock(RouteImpl.class); when(currentRoute.getPath()).thenReturn("/blub"); when(rc.currentRoute()).thenReturn(currentRoute); ParsedHeaderValues headerValues = mock(ParsedHeaderValues.class); when(rc.parsedHeaders()).thenReturn(headerValues); HttpServerRequest request = mock(HttpServerRequest.class); when(request.query()).thenReturn("?blub"); when(request.method()).thenReturn(HttpMethod.GET); when(rc.request()).thenReturn(request); when(rc.normalisedPath()).thenReturn("/blub"); storage.getRootRouter().handleFailure(rc); } }
Fix IndexError bug in _hydrate
import requests API_URL = 'http://data.police.uk/api/' class APIError(Exception): pass def api_request(method): r = requests.get(API_URL + method) if r.status_code != 200: raise APIError(r.status_code) return r.json() class Resource(object): _requested = False api_method = None fields = [] def __getattr__(self, attr): if not self._requested and attr in self.fields: self._make_api_request() return self.__getattribute__(attr) def _make_api_request(self): self._response_data = api_request(self._get_api_method()) self._hydrate() self._requested = True def _get_api_method(self): if self.api_method is None: raise RuntimeError('You must set the api_method attribute') return self.api_method def _hydrate(self): for field in self.fields: hydrate_field = getattr(self, '_hydrate_%s' % field, lambda x: x) setattr(self, field, hydrate_field(self._response_data.get(field)))
import requests API_URL = 'http://data.police.uk/api/' class APIError(Exception): pass def api_request(method): r = requests.get(API_URL + method) if r.status_code != 200: raise APIError(r.status_code) return r.json() class Resource(object): _requested = False api_method = None fields = [] def __getattr__(self, attr): if not self._requested and attr in self.fields: self._make_api_request() return self.__getattribute__(attr) def _make_api_request(self): self._response_data = api_request(self._get_api_method()) self._hydrate() self._requested = True def _get_api_method(self): if self.api_method is None: raise RuntimeError('You must set the api_method attribute') return self.api_method def _hydrate(self): for field in self.fields: hydrate_field = getattr(self, '_hydrate_%s' % field, lambda x: x) setattr(self, field, hydrate_field(self._response_data[field]))
Change the vote up/down buttons into thumbs up/down.
// ------------------------------ Dynamic Icons ------------------------------ // /** * Take an icon name (such as "open") and return the HTML code to display the icon * @param {string} iconName - the name of the icon * @param {string} [iconClass] - an optional class to assign to the icon */ Telescope.utils.getIcon = function (iconName, iconClass) { var icons = Telescope.utils.icons; var iconCode = !!icons[iconName] ? icons[iconName] : iconName; var iconClass = (typeof iconClass === 'string') ? ' '+iconClass : ''; return '<i class="icon fa fa-' + iconCode + ' icon-' + iconName + iconClass+ '" aria-hidden="true"></i>'; }; /** * A directory of icon keys and icon codes */ Telescope.utils.icons = { open: "plus", close: "minus", upvote: "thumbs-o-up", voted: "check", downvote: "thumbs-o-down", facebook: "facebook-square", twitter: "twitter", googleplus: "google-plus", linkedin: "linkedin-square", comment: "comment-o", share: "share-square-o", more: "ellipsis-h", menu: "bars", subscribe: "envelope-o", delete: "trash-o", edit: "pencil", popularity: "fire", time: "clock-o", best: "star", search: "search" };
// ------------------------------ Dynamic Icons ------------------------------ // /** * Take an icon name (such as "open") and return the HTML code to display the icon * @param {string} iconName - the name of the icon * @param {string} [iconClass] - an optional class to assign to the icon */ Telescope.utils.getIcon = function (iconName, iconClass) { var icons = Telescope.utils.icons; var iconCode = !!icons[iconName] ? icons[iconName] : iconName; var iconClass = (typeof iconClass === 'string') ? ' '+iconClass : ''; return '<i class="icon fa fa-' + iconCode + ' icon-' + iconName + iconClass+ '" aria-hidden="true"></i>'; }; /** * A directory of icon keys and icon codes */ Telescope.utils.icons = { open: "plus", close: "minus", upvote: "chevron-up", voted: "check", downvote: "chevron-down", facebook: "facebook-square", twitter: "twitter", googleplus: "google-plus", linkedin: "linkedin-square", comment: "comment-o", share: "share-square-o", more: "ellipsis-h", menu: "bars", subscribe: "envelope-o", delete: "trash-o", edit: "pencil", popularity: "fire", time: "clock-o", best: "star", search: "search" };
Check to see if there is actually metadata to add.
$(document).ready(function(){ /** * Serialize metadata to json for submission */ $("#edit-form").submit(function(){ var metadata = {}; $("#other-metadata").find(".metadata-entry").each(function(){ var entry = $(this); var key = entry.find(".metadata-key").val(); var value = entry.find(".metadata-value").val(); metadata[key] = value; }); // paste the json into a hidden text field for submission if (Object.keys(metadata).length > 0) { $("#metadata").val(JSON.stringify(metadata)); } }); /** * Remove a metadata term */ $(".delete-metadata").on("click", function(){ $(this).closest(".metadata-entry").remove(); }); /** * Add a metadata term from the template */ $("#add-metadata").on("click", function(){ var newMetadata = $("#metadata-template").clone(true); newMetadata.removeAttr("id"); $("#metadata-fields").append(newMetadata); }); });
$(document).ready(function(){ /** * Serialize metadata to json for submission */ $("#edit-form").submit(function(){ var metadata = {}; $("#other-metadata").find(".metadata-entry").each(function(){ var entry = $(this); var key = entry.find(".metadata-key").val(); var value = entry.find(".metadata-value").val(); metadata[key] = value; }); // paste the json into a hidden text field for submission $("#metadata").val(JSON.stringify(metadata)); }); /** * Remove a metadata term */ $(".delete-metadata").on("click", function(){ $(this).closest(".metadata-entry").remove(); }); /** * Add a metadata term from the template */ $("#add-metadata").on("click", function(){ var newMetadata = $("#metadata-template").clone(true); newMetadata.removeAttr("id"); $("#metadata-fields").append(newMetadata); }); });
Improve formatting of ModelValidationError toString()
var inherits = require('inherits'); var self = module.exports = { FieldValidationError: FieldValidationError, ModelValidationError: ModelValidationError, messages: { "en-us": { "generic": "Failed to validate field", "required": "The field is required", "wrong_type": "Field value is not of type {type}" } }, getMessage: function(type, params, lang) { lang = lang || "en-us"; return self.messages[lang][type].replace(/\${([\w:]+)}/g, function(match, varname) { return params[varname]; }); } }; function FieldValidationError(type, params) { this.type = type || 'generic'; this.params = params; this.message = self.getMessage(type, params); this.stack = new Error(this.message).stack; } inherits(FieldValidationError, Error); function ModelValidationError(errors) { this.errors = errors; var message = "Error validating the model \n"; Object.keys(errors).forEach(function(field) { message += field + ": " + errors[field].message + "\n"; }); this.message = message; this.stack = new Error(this.message).stack; } inherits(ModelValidationError, Error);
var inherits = require('inherits'); var self = module.exports = { FieldValidationError: FieldValidationError, ModelValidationError: ModelValidationError, messages: { "en-us": { "generic": "Failed to validate field", "required": "The field is required", "wrong_type": "Field value is not of type {type}" } }, getMessage: function(type, params, lang) { lang = lang || "en-us"; return self.messages[lang][type].replace(/\${([\w:]+)}/g, function(match, varname) { return params[varname]; }); } }; function FieldValidationError(type, params) { this.type = type || 'generic'; this.params = params; this.message = self.getMessage(type, params); this.stack = new Error(this.message).stack; } inherits(FieldValidationError, Error); function ModelValidationError(errors) { this.errors = errors; this.message = "Error validating the model \n"+JSON.stringify(errors); this.stack = new Error(this.message).stack; } inherits(ModelValidationError, Error);
Use Promisify and add ability to get String/Array of globs in api
'use strict'; /* global -Promise */ var Promise = require('bluebird'); var _ = require('underscore'); var glob = Promise.promisify(require("glob"));; var getFileList = function getFileList (files) { if (_.isString(files)) { return glob(files); } else if (_.isArray(files)) { var fileSubLists = _.map(files, function (fileSubList) { return glob(fileSubList); }); return Promise.reduce(fileSubLists, function(fileList, subList) { return fileList.concat(subList); }, []); } throw new Error('You can only provide a String or an Array of filenames'); }; var getSupportedBrowserList = function getUnsupportedBrowserList (browsers) { return { ie: ['6'] }; }; module.exports = { getFileList: getFileList, getSupportedBrowserList: getSupportedBrowserList };
'use strict'; /* global -Promise */ var Promise = require('bluebird'); var _ = require('underscore'); var glob = require('glob'); var getFileList = function getFileList (files) { var fileList = []; return new Promise(function (resolve, reject) { if (_.isString(files)) { glob(files, function (err, files) { if (err) { reject(err); } fileList = files; resolve(fileList); }); } else if (_.isArray(files)) { // TODO } else { throw new Error('You can only provide a String or an Array of filenames'); } }); }; var getSupportedBrowserList = function getUnsupportedBrowserList (browsers) { return { ie: ['6'] }; }; module.exports = { getFileList: getFileList, getSupportedBrowserList: getSupportedBrowserList };
Remove unused comments related to Python 2 compatibility. PiperOrigin-RevId: 440310765 Change-Id: I7afdea122cd2565b06f387509de2476106d46d8c
# Copyright 2018 DeepMind Technologies Limited. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Acme is a framework for reinforcement learning.""" # Internal import. # Expose specs and types modules. from acme import specs from acme import types # Make __version__ accessible. from acme._metadata import __version__ # Expose core interfaces. from acme.core import Actor from acme.core import Learner from acme.core import Saveable from acme.core import VariableSource from acme.core import Worker # Expose the environment loop. from acme.environment_loop import EnvironmentLoop from acme.specs import make_environment_spec # Acme loves you.
# python3 # Copyright 2018 DeepMind Technologies Limited. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Acme is a framework for reinforcement learning.""" # Internal import. # Expose specs and types modules. from acme import specs from acme import types # Make __version__ accessible. from acme._metadata import __version__ # Expose core interfaces. from acme.core import Actor from acme.core import Learner from acme.core import Saveable from acme.core import VariableSource from acme.core import Worker # Expose the environment loop. from acme.environment_loop import EnvironmentLoop from acme.specs import make_environment_spec # Acme loves you.
Update to generalize the flash message text.
<?php use Scholarship\Forms\NominationForm; class NominationController extends \BaseController { /** * @var nominationForm */ protected $nominationForm; function __construct(NominationForm $nominationForm) { $this->nominationForm = $nominationForm; } public function store() { $input = Input::all(); $this->nominationForm->validate($input); $nom = new Nomination; $nom->fill($input)->save(); $this->sendNomEmail($nom); return Redirect::route('home')->with('flash_message', ['text' => 'Thanks for taking the time to nominate someone! If you know other outstanding individuals for the program, we’d love to hear about them.', 'class' => '-info']); } public function sendNomEmail($nom) { $email = new Email; $data = array( 'nom_name' => $nom->nom_name, 'rec_name' => $nom->rec_name, 'application' => link_to_route('home', 'Application'), ); $email->sendEmail('nomination', 'applicant', $nom->nom_email, $data); } }
<?php use Scholarship\Forms\NominationForm; class NominationController extends \BaseController { /** * @var nominationForm */ protected $nominationForm; function __construct(NominationForm $nominationForm) { $this->nominationForm = $nominationForm; } public function store() { $input = Input::all(); $this->nominationForm->validate($input); $nom = new Nomination; $nom->fill($input)->save(); $this->sendNomEmail($nom); return Redirect::route('home')->with('flash_message', ['text' => 'Thanks for taking the time to nominate someone for the Foot Locker Scholar Athletes program! If you know other outstanding individuals for the program, we’d love to hear about them.', 'class' => '-info']); } public function sendNomEmail($nom) { $email = new Email; $data = array( 'nom_name' => $nom->nom_name, 'rec_name' => $nom->rec_name, 'application' => link_to_route('home', 'Application'), ); $email->sendEmail('nomination', 'applicant', $nom->nom_email, $data); } }
Make exchange rates look a bit nicer
// A comma separated list of currencies to display. var ticker_currencies = "USD,BTC,ETH,JPY,CNY" ticker = function(currencies) { $.ajax({ type: "GET", url: "https://min-api.cryptocompare.com/data/price?fsym=BCC&tsyms=" + currencies, contentType: "application/json; charset=utf-8", timeout: 6000, error: function (x, t, m) { $('#ticker').html("N/A") }, success: function (currencyRates) { var output = []; $.each(currencyRates, function (currency, price) { output.push(currency + "&nbsp;-&nbsp;" + price); }); $('#ticker_value').html(output.join(" &bull; ")); } }).done(function () { setTimeout(function(){ ticker(ticker_currencies); }, 10000); }); } ticker(ticker_currencies);
// A comma separated list of currencies to display. var ticker_currencies = "USD,BTC,ETH,JPY,CNY" ticker = function(currencies) { $.ajax({ type: "GET", url: "https://min-api.cryptocompare.com/data/price?fsym=BCC&tsyms=" + currencies, contentType: "application/json; charset=utf-8", timeout: 6000, error: function (x, t, m) { $('#ticker').html("N/A") }, success: function (currencyRates) { var output = ""; $.each(currencyRates, function (currency, price) { output += currency + " - " + price + " "; }); $('#ticker_value').html(output) } }).done(function () { setTimeout(function(){ ticker(ticker_currencies); }, 10000); }); } ticker(ticker_currencies);
Allow custom version commands as well 👯
var buildFile = require('./build-file') var runGitCommand = require('./helpers/run-git-command') var commithashCommand = 'rev-parse HEAD' var versionCommand = 'describe --always' function GitRevisionPlugin (options) { this.gitWorkTree = options && options.gitWorkTree this.lightweightTags = options && options.lightweightTags || false this.commithashCommand = options && options.commithashCommand || commithashCommand this.versionCommand = options && options.versionCommand || versionCommand } GitRevisionPlugin.prototype.apply = function (compiler) { buildFile(compiler, this.gitWorkTree, this.commithashCommand, /\[git-revision-hash\]/gi, 'COMMITHASH') buildFile(compiler, this.gitWorkTree, this.versionCommand + (this.lightweightTags ? ' --tags' : ''), /\[git-revision-version\]/gi, 'VERSION') } GitRevisionPlugin.prototype.commithash = function (callback) { return runGitCommand(this.gitWorkTree, this.commithashCommand) } GitRevisionPlugin.prototype.version = function (callback) { return runGitCommand(this.gitWorkTree, this.versionCommand + (this.lightweightTags ? ' --tags' : '')) } module.exports = GitRevisionPlugin
var buildFile = require('./build-file') var runGitCommand = require('./helpers/run-git-command') var commithashCommand = 'rev-parse HEAD' var versionCommand = 'describe --always' function GitRevisionPlugin (options) { this.gitWorkTree = options && options.gitWorkTree this.lightweightTags = options && options.lightweightTags || false this.commithashCommand = options && options.commithashCommand || commithashCommand } GitRevisionPlugin.prototype.apply = function (compiler) { buildFile(compiler, this.gitWorkTree, this.commithashCommand, /\[git-revision-hash\]/gi, 'COMMITHASH') buildFile(compiler, this.gitWorkTree, versionCommand + (this.lightweightTags ? ' --tags' : ''), /\[git-revision-version\]/gi, 'VERSION') } GitRevisionPlugin.prototype.commithash = function (callback) { return runGitCommand(this.gitWorkTree, this.commithashCommand) } GitRevisionPlugin.prototype.version = function (callback) { return runGitCommand(this.gitWorkTree, versionCommand + (this.lightweightTags ? ' --tags' : '')) } module.exports = GitRevisionPlugin
Use chrome.runtime.id instead of name to select Analytics property.
/** * @constructor */ function Analytics() { this.service_ = null; } Analytics.prototype.start = function(settings) { if (this.service_) { throw 'Analytics should be started only once per session.'; } this.service_ = analytics.getService('text_app'); var propertyId = 'UA-48886257-2'; if (chrome.runtime.id === 'mmfbcljfglbokpmkimbfghdkjmjhdgbg') { propertyId = 'UA-48886257-1'; } this.tracker_ = this.service_.getTracker(propertyId); this.reportSettings_(settings); this.tracker_.sendAppView('main'); }; Analytics.prototype.reportSettings_ = function(settings) { this.tracker_.set('dimension1', settings.get('spacestab').toString()); this.tracker_.set('dimension2', settings.get('tabsize').toString()); this.tracker_.set('dimension3', Math.round(settings.get('fontsize')).toString()); this.tracker_.set('dimension4', settings.get('sidebaropen').toString()); this.tracker_.set('dimension5', settings.get('theme')); };
/** * @constructor */ function Analytics() { this.service_ = null; } Analytics.prototype.start = function(settings) { if (this.service_) { throw 'Analytics should be started only once per session.'; } this.service_ = analytics.getService('text_app'); var propertyId = 'UA-48886257-1'; if (chrome.runtime.getManifest()['name'].indexOf('Dev') >= 0) { propertyId = 'UA-48886257-2'; } this.tracker_ = this.service_.getTracker(propertyId); this.reportSettings_(settings); this.tracker_.sendAppView('main'); }; Analytics.prototype.reportSettings_ = function(settings) { this.tracker_.set('dimension1', settings.get('spacestab').toString()); this.tracker_.set('dimension2', settings.get('tabsize').toString()); this.tracker_.set('dimension3', Math.round(settings.get('fontsize')).toString()); this.tracker_.set('dimension4', settings.get('sidebaropen').toString()); this.tracker_.set('dimension5', settings.get('theme')); };
Throw an exception when SQLiteJDBC initialization fails Summary: When sqlite-jdbc can't unpack its .so (e.g., if the disk is full), it sometimes returns an error code instead of throwing. Notice this and throw our own error, rather than continuing until we hit a mysterious UnsatisfiedLinkError Test Plan: create a tiny disk image to house buck-out and try some builds Reviewed By: dinhviethoa fbshipit-source-id: b8258a4
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.sqlite; import org.sqlite.SQLiteJDBCLoader; public class SQLiteUtils { private SQLiteUtils() { // This class cannot be instantiated } /** * Initializes the JDBC loader statically to avoid sqlite-jdbc loading its JNI library in a * thread-unsafe manner. This method should be called statically from any class that uses * SQLiteJDBC. */ public static void initialize() { try { if (!SQLiteJDBCLoader.initialize()) { throw new RuntimeException("sqlite-jdbc initialization failed"); } } catch (Exception e) { throw new RuntimeException(e); } } }
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.sqlite; import org.sqlite.SQLiteJDBCLoader; public class SQLiteUtils { private SQLiteUtils() { // This class cannot be instantiated } /** * Initializes the JDBC loader statically to avoid sqlite-jdbc loading its JNI library in a * thread-unsafe manner. This method should be called statically from any class that uses * SQLiteJDBC. */ public static void initialize() { try { SQLiteJDBCLoader.initialize(); } catch (Exception e) { throw new RuntimeException(e); } } }
Use deep equal over array join
/* global QUnit */ import Em from 'ember'; import ArrayOffset from 'array-offset'; QUnit.module('ArrayOffset'); QUnit.test('constructor exists', function (assert) { assert.ok(ArrayOffset, 'ArrayOffset is not null or undefined'); assert.equal(typeof ArrayOffset, 'function', 'ArrayOffset is function'); }); QUnit.test('can be initialized without content', function (assert) { assert.ok(ArrayOffset.create(), 'ArrayOffset is created without content'); }); QUnit.test('content is initialized', function (assert) { var arr = Em.A(['a', 'b', 'c']); var proxy = ArrayOffset.create({ content: arr }); assert.equal(proxy.get('arrangedContent.length'), 3); assert.equal(proxy.get('content.length'), 3); assert.equal(proxy.get('length'), 3); assert.deepEqual(proxy.toArray(), ['a', 'b', 'c']); }); QUnit.test('default offset', function (assert) { var proxy = ArrayOffset.create(); assert.equal(proxy.get('offset'), 0, 'Default offset is zero'); });
/* global QUnit */ import Em from 'ember'; import ArrayOffset from 'array-offset'; QUnit.module('ArrayOffset'); QUnit.test('constructor exists', function (assert) { assert.ok(ArrayOffset, 'ArrayOffset is not null or undefined'); assert.equal(typeof ArrayOffset, 'function', 'ArrayOffset is function'); }); QUnit.test('can be initialized without content', function (assert) { assert.ok(ArrayOffset.create(), 'ArrayOffset is created without content'); }); QUnit.test('content is initialized', function (assert) { var arr = Em.A(['a', 'b', 'c']); var proxy = ArrayOffset.create({ content: arr }); assert.equal(proxy.get('arrangedContent.length'), 3); assert.equal(proxy.get('content.length'), 3); assert.equal(proxy.get('length'), 3); assert.equal(proxy.get('arrangedContent').join(''), 'abc'); }); QUnit.test('default offset', function (assert) { var proxy = ArrayOffset.create(); assert.equal(proxy.get('offset'), 0, 'Default offset is zero'); });
Add JWT as an attribute, so we can return it with the db response
'use strict'; var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); var jwt = require('jwt-simple'); var moment = require('moment'); /** * Define basic schema for a new user: for now, email, password, and domain to track */ var UserSchema = mongoose.Schema({ id: String, sites: Array, jwt: String, basic: { email: String, password: String } }); /** * Run an incoming password through a one-way hash */ UserSchema.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); // 8: larger = more secure, but exponentially slower }; /** * Check incoming password against db's hashed password */ UserSchema.methods.matchingPassword = function(password) { return bcrypt.compareSync(password, this.basic.password); }; /** * After a user is succesfully authenticated, create a new JWT */ UserSchema.methods.createToken = function(app) { var expires = moment().add(7, 'days').valueOf(); var self = this; var token = jwt.encode({ iss: self._id, // basically == id expires: expires }, app.get('jwtTokenSecret')); // The token we config in server.js return token; }; module.exports = mongoose.model('UserModel', UserSchema);
'use strict'; var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); var jwt = require('jwt-simple'); var moment = require('moment'); /** * Define basic schema for a new user: for now, email, password, and domain to track */ var UserSchema = mongoose.Schema({ id: String, sites: Array, basic: { email: String, password: String } }); /** * Run an incoming password through a one-way hash */ UserSchema.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); // 8: larger = more secure, but exponentially slower }; /** * Check incoming password against db's hashed password */ UserSchema.methods.matchingPassword = function(password) { return bcrypt.compareSync(password, this.basic.password); }; /** * After a user is succesfully authenticated, create a new JWT */ UserSchema.methods.createToken = function(app) { var expires = moment().add(7, 'days').valueOf(); var self = this; var token = jwt.encode({ iss: self._id, // basically == id expires: expires }, app.get('jwtTokenSecret')); // The token we config in server.js return token; }; module.exports = mongoose.model('UserModel', UserSchema);
Make owner of directory be able to access its content See https://github.com/cloudfoundry/cf-networking-release/issues/65 for the context.
package bindmount import ( "fmt" "os" "path/filepath" "syscall" "golang.org/x/sys/unix" ) type Mounter struct{} func (m *Mounter) IdempotentlyMount(source, target string) error { err := os.MkdirAll(filepath.Dir(target), 0700) if err != nil { return fmt.Errorf("os.MkdirAll failed: %s", err) } fd, err := os.Create(target) if err != nil { return fmt.Errorf("os.Create failed: %s", err) } defer fd.Close() err = unix.Mount(source, target, "none", unix.MS_BIND, "") if err != nil { return fmt.Errorf("mount failed: %s", err) } return nil } func (m *Mounter) RemoveMount(target string) error { err := unix.Unmount(target, unix.MNT_DETACH) if err != nil && err != syscall.ENOENT { return fmt.Errorf("unmount failed: %s", err) } err = os.RemoveAll(target) if err != nil { return fmt.Errorf("removeall failed: %s", err) // not tested } return nil }
package bindmount import ( "fmt" "os" "path/filepath" "syscall" "golang.org/x/sys/unix" ) type Mounter struct{} func (m *Mounter) IdempotentlyMount(source, target string) error { err := os.MkdirAll(filepath.Dir(target), 0600) if err != nil { return fmt.Errorf("os.MkdirAll failed: %s", err) } fd, err := os.Create(target) if err != nil { return fmt.Errorf("os.Create failed: %s", err) } defer fd.Close() err = unix.Mount(source, target, "none", unix.MS_BIND, "") if err != nil { return fmt.Errorf("mount failed: %s", err) } return nil } func (m *Mounter) RemoveMount(target string) error { err := unix.Unmount(target, unix.MNT_DETACH) if err != nil && err != syscall.ENOENT { return fmt.Errorf("unmount failed: %s", err) } err = os.RemoveAll(target) if err != nil { return fmt.Errorf("removeall failed: %s", err) // not tested } return nil }
Use appropriate model types - continued
// Example model var mongoose = require('mongoose'), Schema = mongoose.Schema; // Authenticate Schema var Account = new Schema ({ //conflict with node so changed from domain domainProvider: { type: String, default: ''}, uid: { type: String, default: ''}, // Could this be better? //user: { type: Schema.Types.ObjectId, ref: 'User' }, // Is email duplicated with User? email: { type: String, default: ''}, tokens: { kind : {type: String, default: ''}, token : {type: String, default: ''}, tokenSecret:{type: String, default: ''} }, streams: [{ screen_name: { type: String, default: ''}, maxid: { type: Number, default: 0}, // Used by twitter count: { type: Number, default: 200}, // Entry Limit content: { type: String, default: ''}, dateRequested: { type: Date, default: Date.now() }, }] }) mongoose.model('Account', Account);
// Example model var mongoose = require('mongoose'), Schema = mongoose.Schema; // Authenticate Schema var Account = new Schema ({ //conflict with node so changed from domain domainProvider: { type: String, default: ''}, uid: { type: String, default: ''}, // Could this be better? //user: { type: Schema.Types.ObjectId, ref: 'User' }, // Is email duplicated with User? email: { type: String, default: ''}, tokens: { kind : {type: String, default: ''}, token : {type: String, default: ''}, tokenSecret:{type: String, default: ''} }, streams: [{ screen_name: { type: String, default: ''}, maxid: { type: Integer, default: 0}, // Used by twitter count: { type: Integer, default: 200}, // Entry Limit content: { type: String, default: ''}, dateRequested: { type: Date, default: Date.now() }, }] }) mongoose.model('Account', Account);
[ROUTE] Add redirect for login/logout and implement route auth
if (Meteor.isClient) { Accounts.onLogin(function() { FlowRouter.go('cases'); }); Accounts.onLogout(function() { FlowRouter.go('home'); }); } FlowRouter.triggers.enter([function() { if (!Meteor.userId()) { FlowRouter.go('home'); } }]); FlowRouter.route('/', { name: 'home', action() { if (Meteor.userId()) { FlowRouter.go('cases'); } GAnalytics.pageview(); BlazeLayout.render('HomeLayout') } }); FlowRouter.route('/cases', { name: 'cases', action() { GAnalytics.pageview(); BlazeLayout.render('MainLayout', { main: 'Cases' }); } }); FlowRouter.route('/cases/create', { name: 'create-case', action() { GAnalytics.pageview(); BlazeLayout.render('MainLayout', { main: 'NewCase' }); } }); FlowRouter.route('/cases/:id', { name: 'single-case', action() { GAnalytics.pageview(); BlazeLayout.render('MainLayout', { main: 'Case' }); } });
FlowRouter.route('/', { name: 'home', action() { GAnalytics.pageview(); BlazeLayout.render('MainLayout') } }); FlowRouter.route('/cases', { name: 'cases', action() { GAnalytics.pageview(); BlazeLayout.render('MainLayout', { main: 'Cases' }); } }); FlowRouter.route('/cases/create', { name: 'create-case', action() { GAnalytics.pageview(); BlazeLayout.render('MainLayout', { main: 'NewCase' }); } }); FlowRouter.route('/cases/:id', { name: 'single-case', action() { GAnalytics.pageview(); BlazeLayout.render('MainLayout', { main: 'Case' }); } });
Generalize list version of EuclideanDistance to any type of solution. The implementation already allows that, but the generics unnecessarily constrain it.
package org.uma.jmetal.util.distance.impl; import org.uma.jmetal.solution.Solution; import org.uma.jmetal.util.distance.Distance; import java.util.List; /** * Class for calculating the Euclidean distance between a {@link Solution} object a list of {@link Solution} * objects in objective space. * * @author <antonio@lcc.uma.es> */ public class EuclideanDistanceBetweenSolutionAndASolutionListInObjectiveSpace <S extends Solution<?>, L extends List<S>> implements Distance<S, L> { private EuclideanDistanceBetweenSolutionsInObjectiveSpace<S> distance ; public EuclideanDistanceBetweenSolutionAndASolutionListInObjectiveSpace() { distance = new EuclideanDistanceBetweenSolutionsInObjectiveSpace<S>() ; } @Override public double getDistance(S solution, L solutionList) { double bestDistance = Double.MAX_VALUE; for (int i = 0; i < solutionList.size();i++){ double aux = distance.getDistance(solution, solutionList.get(i)); if (aux < bestDistance) bestDistance = aux; } return bestDistance; } }
package org.uma.jmetal.util.distance.impl; import org.uma.jmetal.solution.Solution; import org.uma.jmetal.util.distance.Distance; import java.util.List; /** * Class for calculating the Euclidean distance between a {@link Solution} object a list of {@link Solution} * objects in objective space. * * @author <antonio@lcc.uma.es> */ public class EuclideanDistanceBetweenSolutionAndASolutionListInObjectiveSpace <S extends Solution<Double>, L extends List<S>> implements Distance<S, L> { private EuclideanDistanceBetweenSolutionsInObjectiveSpace<S> distance ; public EuclideanDistanceBetweenSolutionAndASolutionListInObjectiveSpace() { distance = new EuclideanDistanceBetweenSolutionsInObjectiveSpace<S>() ; } @Override public double getDistance(S solution, L solutionList) { double bestDistance = Double.MAX_VALUE; for (int i = 0; i < solutionList.size();i++){ double aux = distance.getDistance(solution, solutionList.get(i)); if (aux < bestDistance) bestDistance = aux; } return bestDistance; } }
Use global.WATCH instead of global.watch global.WATCH is defined in start.js `global.WATCH = true;`. global.watch is undefined.
/** * React Starter Kit (http://www.reactstarterkit.com/) * * Copyright © 2014-2015 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import webpack from 'webpack'; import config from './config'; /** * Bundles JavaScript, CSS and images into one or more packages * ready to be used in a browser. */ export default async () => new Promise((resolve, reject) => { console.log('bundle'); const bundler = webpack(config); let bundlerRunCount = 0; function bundle(err, stats) { if (err) { return reject(err); } console.log(stats.toString(config[0].stats)); if (++bundlerRunCount === (global.watch ? config.length : 1)) { return resolve(); } } if (global.WATCH) { bundler.watch(200, bundle); } else { bundler.run(bundle); } });
/** * React Starter Kit (http://www.reactstarterkit.com/) * * Copyright © 2014-2015 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import webpack from 'webpack'; import config from './config'; /** * Bundles JavaScript, CSS and images into one or more packages * ready to be used in a browser. */ export default async () => new Promise((resolve, reject) => { console.log('bundle'); const bundler = webpack(config); let bundlerRunCount = 0; function bundle(err, stats) { if (err) { return reject(err); } console.log(stats.toString(config[0].stats)); if (++bundlerRunCount === (global.watch ? config.length : 1)) { return resolve(); } } if (global.watch) { bundler.watch(200, bundle); } else { bundler.run(bundle); } });
Set name of executor to 'taskExecutor' (@EnableAsync default)
/* * Copyright 2015-2016 EuregJUG. * * 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 eu.euregjug.site; import java.util.concurrent.Executor; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; /** * @author Michael J. Simons, 2015-12-26 */ @SpringBootApplication @EnableCaching @EnableAsync @PropertySource("classpath:build.properties") public class Application { @Bean public Executor taskExecutor() { return new ThreadPoolTaskExecutor(); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
/* * Copyright 2015-2016 EuregJUG. * * 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 eu.euregjug.site; import java.util.concurrent.Executor; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; /** * @author Michael J. Simons, 2015-12-26 */ @SpringBootApplication @EnableCaching @EnableAsync @PropertySource("classpath:build.properties") public class Application { @Bean public Executor threadPoolTaskExecutor() { return new ThreadPoolTaskExecutor(); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
Adjust Setup: using Python 3.4, not Python 2 supported (currently).
# -*- coding: utf-8 -*- from setuptools import setup, find_packages version = '0.6.1' REQUIREMENTS = ['requests'] CLASSIFIERS = [ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Application Frameworks', "Programming Language :: Python :: 3.4", #"Programming Language :: Python :: 2", #"Programming Language :: Python :: 2.6", #"Programming Language :: Python :: 2.7", ] setup( name="python-amazon-mws", version=version, description="A python interface for Amazon MWS", author="Paulo Alvarado", author_email="commonzenpython@gmail.com", url="http://github.com/czpython/python-amazon-mws", packages=find_packages(), platforms=['OS Independent'], license='LICENSE.txt', install_requires=REQUIREMENTS, classifiers=CLASSIFIERS, include_package_data=True, zip_safe=False )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages version = '0.6' REQUIREMENTS = ['requests'] CLASSIFIERS = [ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Application Frameworks', "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ] setup( name="python-amazon-mws", version=version, description="A python interface for Amazon MWS", author="Paulo Alvarado", author_email="commonzenpython@gmail.com", url="http://github.com/czpython/python-amazon-mws", packages=find_packages(), platforms=['OS Independent'], license='LICENSE.txt', install_requires=REQUIREMENTS, classifiers=CLASSIFIERS, include_package_data=True, zip_safe=False )
Switch frametype to int32 to bring in line with proto
package domain import "time" // Trace represents a full trace of a request // comprised of a number of frames type Trace []Frame // FrameType represents an Enum of types of Frames which Phosphor can record type FrameType int32 const ( // Calls Req = FrameType(1) // Client Request dispatch Rsp = FrameType(2) // Client Response received In = FrameType(3) // Server Request received Out = FrameType(4) // Server Response dispatched Timeout = FrameType(5) // Client timed out waiting // Developer initiated annotations Annotation = FrameType(6) ) // A Frame represents the smallest individually fired component of a trace // These can be assembled into spans, and entire traces of a request to our systems type Frame struct { TraceId string // Global Trace Identifier SpanId string // Identifier for this span, non unique - eg. RPC calls would have 4 frames with this id ParentSpanId string // Parent span - eg. nested RPC calls Timestamp time.Time // Timestamp the event occured, can only be compared on the same machine Duration time.Duration // Optional: duration of the event, eg. RPC call Hostname string // Hostname this event originated from Origin string // Fully qualified name of the message origin Destination string // Optional: Fully qualified name of the message destination EventType EventType // The type of Event Payload string // The payload, eg. RPC body, or Annotation PayloadSize int32 // Bytes of payload KeyValue map[string]string // Key value debug information }
package domain import "time" // Trace represents a full trace of a request // comprised of a number of frames type Trace []Frame // FrameType represents an Enum of types of Events which Phosphor can record type FrameType int const ( // Calls Req = FrameType(1) // Client Request dispatch Rsp = FrameType(2) // Client Response received In = FrameType(3) // Server Request received Out = FrameType(4) // Server Response dispatched Timeout = FrameType(5) // Client timed out waiting // Developer initiated annotations Annotation = FrameType(6) ) // A Frame represents the smallest individually fired component of a trace // These can be assembled into spans, and entire traces of a request to our systems type Frame struct { TraceId string // Global Trace Identifier SpanId string // Identifier for this span, non unique - eg. RPC calls would have 4 frames with this id ParentSpanId string // Parent span - eg. nested RPC calls Timestamp time.Time // Timestamp the event occured, can only be compared on the same machine Duration time.Duration // Optional: duration of the event, eg. RPC call Hostname string // Hostname this event originated from Origin string // Fully qualified name of the message origin Destination string // Optional: Fully qualified name of the message destination EventType EventType // The type of Event Payload string // The payload, eg. RPC body, or Annotation PayloadSize int32 // Bytes of payload KeyValue map[string]string // Key value debug information }
Add mongo dependency back to template tests
Package.describe({ summary: "Additional tests for Spacebars", internal: true }); // These tests are in a separate package to avoid a circular dependency // between the `spacebars` and `templating` packages. Package.on_test(function (api) { api.use('underscore'); api.use('spacebars'); api.use('tinytest'); api.use('jquery'); api.use('test-helpers'); api.use('showdown'); api.use('minimongo'); api.use('templating', 'client'); api.add_files([ 'template_tests.html', 'template_tests.js', 'templating_tests.html', 'templating_tests.js' ], 'client'); api.add_files('template_tests_server.js', 'server'); api.add_files([ 'assets/markdown_basic.html', 'assets/markdown_if1.html', 'assets/markdown_if2.html', 'assets/markdown_each1.html', 'assets/markdown_each2.html' ], 'server', { isAsset: true }); });
Package.describe({ summary: "Additional tests for Spacebars", internal: true }); // These tests are in a separate package to avoid a circular dependency // between the `spacebars` and `templating` packages. Package.on_test(function (api) { api.use('underscore'); api.use('spacebars'); api.use('tinytest'); api.use('jquery'); api.use('test-helpers'); api.use('showdown'); api.use('templating', 'client'); api.add_files([ 'template_tests.html', 'template_tests.js', 'templating_tests.html', 'templating_tests.js' ], 'client'); api.add_files('template_tests_server.js', 'server'); api.add_files([ 'assets/markdown_basic.html', 'assets/markdown_if1.html', 'assets/markdown_if2.html', 'assets/markdown_each1.html', 'assets/markdown_each2.html' ], 'server', { isAsset: true }); });
Use Stripes object from context, not from prop Part of STRIPES-395.
// We have to remove node_modules/react to avoid having multiple copies loaded. // eslint-disable-next-line import/no-unresolved import React, { PropTypes } from 'react'; import { modules } from 'stripes-loader'; // eslint-disable-line const Pluggable = (props, context) => { const plugins = modules.plugin || []; let best; for (name of Object.keys(plugins)) { const m = plugins[name]; if (m.pluginType === props.type) { best = m; if (m.module === context.stripes.plugins[props.type]) break; } } if (best) { const Child = context.stripes.connect(best.getModule()); return <Child {...props} /> } return props.children; }; Pluggable.contextTypes = { stripes: PropTypes.shape({ hasPerm: PropTypes.func.isRequired, }).isRequired, }; Pluggable.propTypes = { type: PropTypes.string.isRequired, }; export default Pluggable;
// We have to remove node_modules/react to avoid having multiple copies loaded. // eslint-disable-next-line import/no-unresolved import React, { PropTypes } from 'react'; import { modules } from 'stripes-loader'; // eslint-disable-line const Pluggable = props => { const plugins = modules.plugin || []; let best; for (name of Object.keys(plugins)) { const m = plugins[name]; if (m.pluginType === props.type) { best = m; if (m.module === props.stripes.plugins[props.type]) break; } } if (best) { const Child = props.stripes.connect(best.getModule()); return <Child {...props} /> } return props.children; }; Pluggable.propTypes = { type: PropTypes.string.isRequired, }; export default Pluggable;
Refresh after all files are uploaded Closes #52
window.addEventListener("load", () => { const SUPPORTED_TYPES = ["Files", "application/x-moz-file"]; let body = document.getElementsByTagName("body")[0]; body.addEventListener("dragover", (ev) => { if(SUPPORTED_TYPES.find(el => (ev.dataTransfer.types.contains || ev.dataTransfer.types.includes).call(ev.dataTransfer.types, el))) ev.preventDefault(); }); body.addEventListener("drop", (ev) => { if(SUPPORTED_TYPES.find(el => (ev.dataTransfer.types.contains || ev.dataTransfer.types.includes).call(ev.dataTransfer.types, el))) { ev.preventDefault(); let remaining_files = ev.dataTransfer.files.length; let url = document.URL; if(url[url.length - 1] != "/") url += "/"; for(let i = ev.dataTransfer.files.length - 1; i >= 0; --i) { let file = ev.dataTransfer.files[i]; let request = new XMLHttpRequest(); request.addEventListener("loadend", (e) => { if(--remaining_files === 0) window.location.reload(); }); request.open("PUT", url + file.name); request.send(file); } } }); });
window.addEventListener("load", () => { const SUPPORTED_TYPES = ["Files", "application/x-moz-file"]; let body = document.getElementsByTagName("body")[0]; body.addEventListener("dragover", (ev) => { if(SUPPORTED_TYPES.find(el => ev.dataTransfer.types.contains(el))) ev.preventDefault(); }); body.addEventListener("drop", (ev) => { if(SUPPORTED_TYPES.find(el => ev.dataTransfer.types.contains(el))) { ev.preventDefault(); let url = document.URL; if(url[url.length - 1] != "/") url += "/"; for(let i = ev.dataTransfer.files.length - 1; i >= 0; --i) { let file = ev.dataTransfer.files[i]; let request = new XMLHttpRequest(); request.open('PUT', url + file.name); request.send(file); } } }); });
Add NumericLiteralNode to ast constructors
function KIFNode(kifExpressions) { this.type = 'KIFNode'; this.expressions = this.expressions || []; this.expressions = this.expressions.concat(kifExpressions); } function WordNode(identifier) { this.type = 'WordNode'; this.word = identifier; } function VariableNode(identifier, variableType) { this.type = 'VariableNode'; this.variableType = variableType || 'IND'; this.variableName = identifier; } function FunctionTermNode(funcName, argsList) { this.type = 'FunctionTermNode'; this.functionName = funcName; this.functionArgumentList = this.functionArgumentList || []; this.functionArgumentList = this.functionArgumentList.concat(argsList); } function EquationNode(firstTerm, secondTerm) { this.type = 'EquationNode'; this.terms = this.terms || []; this.terms = this.terms.concat(firstTerm, secondTerm); } function StringLiteralNode(rawString) { this.type = 'StringLiteralNode'; this.rawString = rawString; this.chars = rawString.substring(1, rawString.length - 1); } function NumericLiteralNode(rawNumber) { this.type = 'NumericLiteralNode'; this.number = +rawNumber; } module.exports = { KIFNode: KIFNode, WordNode: WordNode, VariableNode: VariableNode, StringLiteralNode: StringLiteralNode, NumericLiteralNode: NumericLiteralNode, FunctionTermNode: FunctionTermNode, EquationNode: EquationNode };
function KIFNode(kifExpressions) { this.type = 'KIFNode'; this.expressions = this.expressions || []; this.expressions = this.expressions.concat(kifExpressions); } function WordNode(identifier) { this.type = 'WordNode'; this.word = identifier; } function VariableNode(identifier, variableType) { this.type = 'VariableNode'; this.variableType = variableType || 'IND'; this.variableName = identifier; } function FunctionTermNode(funcName, argsList) { this.type = 'FunctionTermNode'; this.functionName = funcName; this.functionArgumentList = this.functionArgumentList || []; this.functionArgumentList = this.functionArgumentList.concat(argsList); } function EquationNode(firstTerm, secondTerm) { this.type = 'EquationNode'; this.terms = this.terms || []; this.terms = this.terms.concat(firstTerm, secondTerm); } function StringLiteralNode(rawString) { this.type = 'StringLiteralNode'; this.rawString = rawString; this.chars = rawString.substring(1, rawString.length - 1); } module.exports = { KIFNode: KIFNode, WordNode: WordNode, VariableNode: VariableNode, StringLiteralNode: StringLiteralNode, FunctionTermNode: FunctionTermNode, EquationNode: EquationNode };
Remove an unused import preventing compile with OpenJDK. Import can't be resolved if using OpenJDK, but turns out it was unused anyhow.
package liquibase.integration.cdi; import liquibase.resource.ResourceAccessor; import java.util.Map; /** * Holds the configuration for Liquibase * * @author Aaron Walker (http://github.com/aaronwalker) */ public class CDILiquibaseConfig { private String contexts; private String changeLog; private Map<String,String> parameters; private boolean dropFirst = false; private String defaultSchema; public String getContexts() { return contexts; } public void setContexts(String contexts) { this.contexts = contexts; } public String getChangeLog() { return changeLog; } public void setChangeLog(String changeLog) { this.changeLog = changeLog; } public Map<String, String> getParameters() { return parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } public boolean isDropFirst() { return dropFirst; } public void setDropFirst(boolean dropFirst) { this.dropFirst = dropFirst; } public String getDefaultSchema() { return defaultSchema; } public void setDefaultSchema(String defaultSchema) { this.defaultSchema = defaultSchema; } }
package liquibase.integration.cdi; import com.sun.xml.internal.ws.util.QNameMap; import liquibase.resource.ResourceAccessor; import java.util.Map; /** * Holds the configuration for Liquibase * * @author Aaron Walker (http://github.com/aaronwalker) */ public class CDILiquibaseConfig { private String contexts; private String changeLog; private Map<String,String> parameters; private boolean dropFirst = false; private String defaultSchema; public String getContexts() { return contexts; } public void setContexts(String contexts) { this.contexts = contexts; } public String getChangeLog() { return changeLog; } public void setChangeLog(String changeLog) { this.changeLog = changeLog; } public Map<String, String> getParameters() { return parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } public boolean isDropFirst() { return dropFirst; } public void setDropFirst(boolean dropFirst) { this.dropFirst = dropFirst; } public String getDefaultSchema() { return defaultSchema; } public void setDefaultSchema(String defaultSchema) { this.defaultSchema = defaultSchema; } }
Check arguments of methods for null safety for ClassSupport #1670
/* * Copyright 2015-2018 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v20.html */ package org.junit.platform.commons.support; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.platform.commons.support.PreconditionViolationChecker.assertPreconditionViolationException; import java.util.List; import java.util.function.Function; import org.junit.jupiter.api.Test; import org.junit.platform.commons.util.ClassUtils; /** * @since 1.1 */ class ClassSupportTests { @Test void nullSafeToString_argument1IsValidated() { Function<? super Class<?>, ? extends String> mapper = null; assertPreconditionViolationException("Mapping function", () -> ClassSupport.nullSafeToString(mapper, String.class, List.class)); } @Test void nullSafeToStringDelegates() { assertEquals(ClassUtils.nullSafeToString(String.class, List.class), ClassSupport.nullSafeToString(String.class, List.class)); Function<Class<?>, String> classToStringMapper = aClass -> aClass.getSimpleName() + "-Test"; assertEquals(ClassUtils.nullSafeToString(classToStringMapper, String.class, List.class), ClassSupport.nullSafeToString(classToStringMapper, String.class, List.class)); } }
/* * Copyright 2015-2018 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v2.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v20.html */ package org.junit.platform.commons.support; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.function.Function; import org.junit.jupiter.api.Test; import org.junit.platform.commons.util.ClassUtils; /** * @since 1.1 */ class ClassSupportTests { @Test void nullSafeToStringDelegates() { assertEquals(ClassUtils.nullSafeToString(String.class, List.class), ClassSupport.nullSafeToString(String.class, List.class)); Function<Class<?>, String> classToStringMapper = aClass -> aClass.getSimpleName() + "-Test"; assertEquals(ClassUtils.nullSafeToString(classToStringMapper, String.class, List.class), ClassSupport.nullSafeToString(classToStringMapper, String.class, List.class)); } }
Revert "Fix no data error on cde dashboard"
var saikuWidgetComponent = BaseComponent.extend({ update : function() { var myself=this; var htmlId = "#" + myself.htmlObject; if (myself.saikuFilePath.substr(0,1) == "/") { myself.saikuFilePath = myself.saikuFilePath.substr(1,myself.saikuFilePath.length - 1 ); } var parameters = {}; if (myself.parameters) { _.each(myself.parameters, function(parameter) { var k = parameter[0]; var v = parameter[1]; if (window.hasOwnProperty(v)) { v = window[v]; } parameters[k] = v; }); } if (myself.width) { $(htmlId).width(myself.width); } if (myself.width) { $(htmlId).height(myself.height); } if ("table" == myself.renderMode) { $(htmlId).addClass('workspace_results'); var t = $("<div></div>"); $(htmlId).html(t); htmlId = t; } var myClient = new SaikuClient({ server: "../../../plugin/saiku/api", path: "/cde-component" }); myClient.execute({ file: myself.saikuFilePath, htmlObject: htmlId, render: myself.renderMode, mode: myself.renderType, zoom: true, params: parameters }); } });
var saikuWidgetComponent = BaseComponent.extend({ update : function() { var myself=this; var htmlId = "#" + myself.htmlObject; if (myself.saikuFilePath.substr(0,1) == "/") { myself.saikuFilePath = myself.saikuFilePath.substr(1,myself.saikuFilePath.length - 1 ); } var parameters = {}; if (myself.parameters) { _.each(myself.parameters, function(parameter) { var k = parameter[0]; var v = parameter[1]; if (window.hasOwnProperty(v)) { v = window[v]; } parameters[k] = v; }); } if (myself.width) { $(htmlId).width(myself.width); } if (myself.width) { $(htmlId).height(myself.height); } if ("table" == myself.renderMode) { $(htmlId).addClass('workspace_results'); var t = $("<div></div>"); $(htmlId).html(t); htmlId = t; } var myClient = new SaikuClient({ server: "../../../../plugin/saiku/api", path: "/cde-component" }); myClient.execute({ file: myself.saikuFilePath, htmlObject: htmlId, render: myself.renderMode, mode: myself.renderType, zoom: true, params: parameters }); } });
Add an empty line for style
import functools, threading def compose_events(events, condition=all): """Compose a sequence of events into one event. Arguments: events: a sequence of objects looking like threading.Event condition: a function taking a sequence of bools and returning a bool. """ events = list(events) master_event = threading.Event() def changed(): if condition(e.is_set() for e in events): master_event.set() else: master_event.clear() def add_changed(f): @functools.wraps(f) def wrapped(): f() changed() return wrapped for e in events: e.set = add_changed(e.set) e.clear = add_changed(e.clear) changed() return master_event
import functools, threading def compose_events(events, condition=all): """Compose a sequence of events into one event. Arguments: events: a sequence of objects looking like threading.Event condition: a function taking a sequence of bools and returning a bool. """ events = list(events) master_event = threading.Event() def changed(): if condition(e.is_set() for e in events): master_event.set() else: master_event.clear() def add_changed(f): @functools.wraps(f) def wrapped(): f() changed() return wrapped for e in events: e.set = add_changed(e.set) e.clear = add_changed(e.clear) changed() return master_event
Include existing env vars in Build Signed-off-by: Max Brunsfeld <8ee73e75b50cc292b5052b11f2ca25336d3e974e@pivotallabs.com>
package cmdtest import ( "io/ioutil" "os" "os/exec" "path/filepath" ) func Build(mainPath string, args ...string) (string, error) { return BuildIn(os.Getenv("GOPATH"), mainPath, args...) } func BuildIn(gopath string, mainPath string, args ...string) (string, error) { if len(gopath) == 0 { panic("$GOPATH not provided when building " + mainPath) } tmpdir, err := ioutil.TempDir("", "test_cmd_main") if err != nil { return "", err } executable := filepath.Join(tmpdir, filepath.Base(mainPath)) cmdArgs := append([]string{"build"}, args...) cmdArgs = append(cmdArgs, "-o", executable, mainPath) build := exec.Command("go", cmdArgs...) build.Stdout = os.Stdout build.Stderr = os.Stderr build.Stdin = os.Stdin build.Env = append(os.Environ(), "GOPATH="+gopath) err = build.Run() if err != nil { return "", err } return executable, nil }
package cmdtest import ( "io/ioutil" "os" "os/exec" "path/filepath" ) func Build(mainPath string, args ...string) (string, error) { return BuildIn(os.Getenv("GOPATH"), mainPath, args...) } func BuildIn(gopath string, mainPath string, args ...string) (string, error) { if len(gopath) == 0 { panic("$GOPATH not provided when building " + mainPath) } tmpdir, err := ioutil.TempDir("", "test_cmd_main") if err != nil { return "", err } executable := filepath.Join(tmpdir, filepath.Base(mainPath)) cmdArgs := append([]string{"build"}, args...) cmdArgs = append(cmdArgs, "-o", executable, mainPath) build := exec.Command("go", cmdArgs...) build.Stdout = os.Stdout build.Stderr = os.Stderr build.Stdin = os.Stdin build.Env = []string{"GOPATH=" + gopath} err = build.Run() if err != nil { return "", err } return executable, nil }
Make sure arity mismatch affects provability
package golog import "testing" func TestFacts (t *testing.T) { db := NewDatabase(). Asserta(NewTerm("father", NewTerm("michael"))). Asserta(NewTerm("father", NewTerm("marc"))) t.Logf("%s\n", db.String()) // these should be provably true if !IsTrue(db, NewTerm("father", NewTerm("michael"))) { t.Errorf("Couldn't prove father(michael)") } if !IsTrue(db, NewTerm("father", NewTerm("marc"))) { t.Errorf("Couldn't prove father(marc)") } // these should not be provable if IsTrue(db, NewTerm("father", NewTerm("sue"))) { t.Errorf("Proved father(sue)") } if IsTrue(db, NewTerm("father", NewTerm("michael"), NewTerm("marc"))) { t.Errorf("Proved father(michael, marc)") } if IsTrue(db, NewTerm("mother", NewTerm("michael"))) { t.Errorf("Proved mother(michael)") } }
package golog import "testing" func TestFacts (t *testing.T) { db := NewDatabase(). Asserta(NewTerm("father", NewTerm("michael"))). Asserta(NewTerm("father", NewTerm("marc"))) t.Logf("%s\n", db.String()) // these should be provably true if !IsTrue(db, NewTerm("father", NewTerm("michael"))) { t.Errorf("Couldn't prove father(michael)") } if !IsTrue(db, NewTerm("father", NewTerm("marc"))) { t.Errorf("Couldn't prove father(marc)") } // these should not be provable if IsTrue(db, NewTerm("father", NewTerm("sue"))) { t.Errorf("Proved father(sue)") } if IsTrue(db, NewTerm("mother", NewTerm("michael"))) { t.Errorf("Proved mother(michael)") } }
XWIKI-2054: Add Utility API to remove all non alpha numeric chartacters from some text * No need to repeat the same chars git-svn-id: cfa2b40e478804c47c05d0f328c574ec5aa2b82e@7258 f329d543-caf0-0310-9063-dda96c69346f
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.util; import junit.framework.TestCase; /** * Unit tests for {@link com.xpn.xwiki.util.Util}. * * @version $Id: $ */ public class UtilTest extends TestCase { public void testConvertToAlphaNumeric() { assertEquals("Search", Util.convertToAlphaNumeric("Search")); assertEquals("Search", Util.convertToAlphaNumeric("S.earch")); assertEquals("e", Util.convertToAlphaNumeric("$%#^()")); } }
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.util; import junit.framework.TestCase; /** * Unit tests for {@link com.xpn.xwiki.util.Util}. * * @version $Id: $ */ public class UtilTest extends TestCase { public void testConvertToAlphaNumeric() { assertEquals("Search", Util.convertToAlphaNumeric("Search")); assertEquals("Search", Util.convertToAlphaNumeric("S.earch")); assertEquals("e", Util.convertToAlphaNumeric("$%#^^^()")); } }
TAP5-1836: Add 0:0:0:0:0:0:0:1 as another recognized value for remoteHost meaning local git-svn-id: d9b8539636d91aff9cd33ed5cd52a0cf73394897@1293000 13f79535-47bb-0310-9956-ffa450edef68
// Copyright 2011, 2012 The Apache Software Foundation // // 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.apache.tapestry5.internal.services.security; import org.apache.tapestry5.services.Request; import org.apache.tapestry5.services.security.WhitelistAnalyzer; /** * Standard analyzer that places requests from the "localhost", "127.0.0.1", "0:0:0:0:0:0:0:1%0", or :"0:0:0:0:0:0:0:1" onto the white list. * * @since 5.3 */ public class LocalhostOnly implements WhitelistAnalyzer { public boolean isRequestOnWhitelist(Request request) { String remoteHost = request.getRemoteHost(); return remoteHost.equals("localhost") || remoteHost.equals("127.0.0.1") || remoteHost.equals("0:0:0:0:0:0:0:1%0") || remoteHost.equals("0:0:0:0:0:0:0:1"); } }
// Copyright 2011 The Apache Software Foundation // // 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.apache.tapestry5.internal.services.security; import org.apache.tapestry5.services.Request; import org.apache.tapestry5.services.security.WhitelistAnalyzer; /** * Standard analyzer that places requests from the "localhost", "127.0.0.1", or "0:0:0:0:0:0:0:1%0" onto the white list. * * @since 5.3 */ public class LocalhostOnly implements WhitelistAnalyzer { public boolean isRequestOnWhitelist(Request request) { String remoteHost = request.getRemoteHost(); return remoteHost.equals("localhost") || remoteHost.equals("127.0.0.1") || remoteHost.equals("0:0:0:0:0:0:0:1%0"); } }
Add tests to package list. Missed this earlier. Oops.
import os from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-portfolio', version='0.8.0', description='Web Worker\'s Portfolio for Django.', url='http://github.com/benspaulding/django-portfolio/', author='Ben Spaulding', author_email='ben@benspaulding.com', license='BSD', download_url='http://github.com/benspaulding/django-portfolio/tarball/v0.8.0', long_description = read('README.rst'), packages = ['portfolio', 'portfolio.tests'], package_data = {'portfolio': ['locale/*/LC_MESSAGES/*', 'templates/portfolio/*']}, classifiers=['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management'], )
import os from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-portfolio', version='0.8.0', description='Web Worker\'s Portfolio for Django.', url='http://github.com/benspaulding/django-portfolio/', author='Ben Spaulding', author_email='ben@benspaulding.com', license='BSD', download_url='http://github.com/benspaulding/django-portfolio/tarball/v0.8.0', long_description = read('README.rst'), packages = ['portfolio'], package_data = {'portfolio': ['locale/*/LC_MESSAGES/*', 'templates/portfolio/*']}, classifiers=['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Site Management'], )
Fix: Move line-height property to correct location
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { regular } from './icon-definitions'; const StyledIcon = styled.i` display: inline-block; font-family: ${props => props.fontFamily} !important; font-size: ${props => props.fontSize}; font-style: normal; font-weight: inherit; font-variant: normal; line-height: 1; speak: none; text-decoration: none; text-transform: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; vertical-align: text-bottom; &:before { content: "\\e${props => props.content}"; } `; function Icon({ name, size, ...other }) { const iconName = `im-icon-${name}`; const styledIconProps = { content: regular[iconName], fontFamily: 'indv-mkt-icons', fontSize: size !== undefined ? `${size}px` : 'inherit' }; return <StyledIcon aria-hidden {...styledIconProps} {...other} />; } Icon.propTypes = { /** Name of the icon to display */ name: PropTypes.string.isRequired, /** Specify icon size in pixels */ size: PropTypes.number }; Icon.defaultProps = { size: undefined }; export default Icon;
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { regular } from './icon-definitions'; const StyledIcon = styled.i` display: inline-block; font-family: ${props => props.fontFamily} !important; font-size: ${props => props.fontSize}; font-style: normal; font-weight: inherit; font-variant: normal; speak: none; text-decoration: none; text-transform: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; vertical-align: text-bottom; line-height: 1; &:before { content: "\\e${props => props.content}"; } `; function Icon({ name, size, ...other }) { const iconName = `im-icon-${name}`; const styledIconProps = { content: regular[iconName], fontFamily: 'indv-mkt-icons', fontSize: size !== undefined ? `${size}px` : 'inherit' }; return <StyledIcon aria-hidden {...styledIconProps} {...other} />; } Icon.propTypes = { /** Name of the icon to display */ name: PropTypes.string.isRequired, /** Specify icon size in pixels */ size: PropTypes.number }; Icon.defaultProps = { size: undefined }; export default Icon;
Update signals for latest django git-svn-id: 80df2eab91b5a6f595a6fdab3c86ff0105eb9aae@1867 2d143e24-0a30-0410-89d7-a2e95868dc81
""" Copied over from django.contrib.auth.management """ from django.dispatch import dispatcher from django.db.models import get_models, signals def _get_permission_codename(action, opts): return u'%s_%s' % (action, opts.object_name.lower()) def _get_all_permissions(opts): "Returns (codename, name) for all permissions in the given opts." return [ (_get_permission_codename('view', opts), u'Can view %s' % (opts.verbose_name_raw)), ] def create_permissions(app, created_models, verbosity, **kwargs): from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission app_models = get_models(app) if not app_models: return for klass in app_models: ctype = ContentType.objects.get_for_model(klass) for codename, name in _get_all_permissions(klass._meta): p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id, defaults={'name': name, 'content_type': ctype}) if created and verbosity >= 2: print "Adding permission '%s'" % p # TODO: check functionality - its new signals in django 1.0.x signals.post_syncdb.connect(create_permissions)
""" Copied over from django.contrib.auth.management """ from django.dispatch import dispatcher from django.db.models import get_models, signals def _get_permission_codename(action, opts): return u'%s_%s' % (action, opts.object_name.lower()) def _get_all_permissions(opts): "Returns (codename, name) for all permissions in the given opts." return [ (_get_permission_codename('view', opts), u'Can view %s' % (opts.verbose_name_raw)), ] def create_permissions(app, created_models, verbosity): from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission app_models = get_models(app) if not app_models: return for klass in app_models: ctype = ContentType.objects.get_for_model(klass) for codename, name in _get_all_permissions(klass._meta): p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id, defaults={'name': name, 'content_type': ctype}) if created and verbosity >= 2: print "Adding permission '%s'" % p dispatcher.connect(create_permissions, signal=signals.post_syncdb)