text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Add another property to the model.
var mongoose = require("mongoose"); var ArtworkSchema = new mongoose.Schema({ "P43_has_dimension": [ { "@type": String, "P90_has_value": String, "P91_has_unit": { "@id": String } } ], "P70i_is_documented_in": { "P3_has_note": String }, "P108i_was_produced_by": { "@type": String, "P9_consists_of": [ { "@type": String, "P2_has_type": { "@id": String }, "P7_took_place_at": { "@id": String }, "P14_carried_out_by": { "@id": String }, "P32_used_general_technique": { "@id": String }, "P4_has_time-span": { "@type": String, "http://www.w3.org/2000/01/rdf-schema#label": String, "P82b_end_of_the_end": String, "P82a_begin_of_the_begin": String, "P3_has_note": String } } ] }, "P128_carries": [ { "@type": String, "P129_is_about": { "@id": String } } ] }); mongoose.model("Artwork", ArtworkSchema)
var mongoose = require("mongoose"); var ArtworkSchema = new mongoose.Schema({ "P43_has_dimension": [ { "@type": String, "P90_has_value": String, "P91_has_unit": { "@id": String } } ], "P108i_was_produced_by": { "@type": String, "P9_consists_of": [ { "@type": String, "P2_has_type": { "@id": String }, "P7_took_place_at": { "@id": String }, "P14_carried_out_by": { "@id": String }, "P32_used_general_technique": { "@id": String }, "P4_has_time-span": { "@type": String, "http://www.w3.org/2000/01/rdf-schema#label": String, "P82b_end_of_the_end": String, "P82a_begin_of_the_begin": String, "P3_has_note": String } } ] }, "P70i_is_documented_in": { "P3_has_note": String } }); mongoose.model("Artwork", ArtworkSchema)
Use mask 0xff for the joypad.
package eu.rekawek.coffeegb.controller; import eu.rekawek.coffeegb.AddressSpace; import eu.rekawek.coffeegb.cpu.InterruptManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.Set; public class Joypad implements AddressSpace { private static final Logger LOG = LoggerFactory.getLogger(Joypad.class); private Set<ButtonListener.Button> buttons = new HashSet<>(); private int p1; public Joypad(InterruptManager interruptManager, Controller controller) { controller.setButtonListener(new ButtonListener() { @Override public void onButtonPress(Button button) { interruptManager.requestInterrupt(InterruptManager.InterruptType.P10_13); buttons.add(button); } @Override public void onButtonRelease(Button button) { buttons.remove(button); } }); } @Override public boolean accepts(int address) { return address == 0xff00; } @Override public void setByte(int address, int value) { p1 = value & 0b00110000; } @Override public int getByte(int address) { int result = p1 | 0b11111111; for (ButtonListener.Button b : buttons) { if ((b.getLine() & p1) == 0) { result &= 0xff & ~b.getMask(); } } return result; } }
package eu.rekawek.coffeegb.controller; import eu.rekawek.coffeegb.AddressSpace; import eu.rekawek.coffeegb.cpu.InterruptManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.Set; public class Joypad implements AddressSpace { private static final Logger LOG = LoggerFactory.getLogger(Joypad.class); private Set<ButtonListener.Button> buttons = new HashSet<>(); private int p1; public Joypad(InterruptManager interruptManager, Controller controller) { controller.setButtonListener(new ButtonListener() { @Override public void onButtonPress(Button button) { interruptManager.requestInterrupt(InterruptManager.InterruptType.P10_13); buttons.add(button); } @Override public void onButtonRelease(Button button) { buttons.remove(button); } }); } @Override public boolean accepts(int address) { return address == 0xff00; } @Override public void setByte(int address, int value) { p1 = value & 0b00110000; } @Override public int getByte(int address) { int result = p1 | 0b00001111; for (ButtonListener.Button b : buttons) { if ((b.getLine() & p1) == 0) { result &= 0xff & ~b.getMask(); } } return result; } }
Add unit test to verify javacc dependency configuration
package ca.coglinc.gradle.plugins.javacc; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.artifacts.Configuration; import org.gradle.testfixtures.ProjectBuilder; import org.junit.Before; import org.junit.Test; public class JavaccPluginTest { private JavaccPlugin plugin; private Project project; @Before public void applyJavaccPluginToProject() { plugin = new JavaccPlugin(); project = ProjectBuilder.builder().build(); plugin.apply(project); } @Test public void pluginAddsCompileJavaccTaskToProject() { final Task compileJavaccTask = project.getTasks().getByName("compileJavacc"); assertNotNull(compileJavaccTask); assertTrue(compileJavaccTask instanceof CompileJavaccTask); } @Test public void pluginAddsCompileJJTreeTaskToProject() { final Task compileJJTreeTask = project.getTasks().getByName("compileJjtree"); assertNotNull(compileJJTreeTask); assertTrue(compileJJTreeTask instanceof CompileJjTreeTask); } @Test public void pluginAddsCompileJjdocTaskToProject() { final Task compileJjdocTask = project.getTasks().getByName("jjdoc"); assertNotNull(compileJjdocTask); assertTrue(compileJjdocTask instanceof CompileJjdocTask); } @Test public void pluginDefinesDefaultDependencyOnJavacc() { Configuration javaccDependencyConfiguration = project.getConfigurations().getByName("javacc"); assertNotNull(javaccDependencyConfiguration); } }
package ca.coglinc.gradle.plugins.javacc; import java.util.HashMap; import java.util.Map; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.testfixtures.ProjectBuilder; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class JavaccPluginTest { private Project project; @Before public void applyJavaccPluginToProject() { project = ProjectBuilder.builder().build(); Map<String, String> pluginNames = new HashMap<String, String>(1); pluginNames.put("plugin", "ca.coglinc.javacc"); project.apply(pluginNames); } @Test public void pluginAddsCompileJavaccTaskToProject() { final Task compileJavaccTask = project.getTasks().getByName("compileJavacc"); Assert.assertNotNull(compileJavaccTask); Assert.assertTrue(compileJavaccTask instanceof CompileJavaccTask); } @Test public void pluginAddsCompileJJTreeTaskToProject() { final Task compileJJTreeTask = project.getTasks().getByName("compileJjtree"); Assert.assertNotNull(compileJJTreeTask); Assert.assertTrue(compileJJTreeTask instanceof CompileJjTreeTask); } @Test public void pluginAddsCompileJjdocTaskToProject() { final Task compileJjdocTask = project.getTasks().getByName("jjdoc"); Assert.assertNotNull(compileJjdocTask); Assert.assertTrue(compileJjdocTask instanceof CompileJjdocTask); } }
Unify promiseThrottler. Add 'key' to options.
/* * Author: CM */ (function(global) { /** * @param {PromiseThrottled} fn * @param {Object|null} [options] * @param {Boolean} options.cancel Whether to cancel the previous promise if it is still running. * @returns {PromiseThrottled} */ function promiseThrottler(fn, options) { options = _.defaults(options || {}, {cancel: false}); if (options.key) { return namespaceThrottler(options.key, fn, options); } else { return nonameThrottler(fn, options); } } /** * @see promiseThrottler */ function nonameThrottler(fn, options) { var promise; return function() { if (options.cancel && promise && promise.isPending() && promise.isCancellable()) { promise.cancel(); promise = null; } if (!promise || !promise.isPending()) { promise = fn.apply(null, arguments); } return promise; }; } var storage = {}; /** * @param {String} namespace * @param {PromiseThrottled} fn * @param {Object|null} options * @param {Boolean} options.cancel Whether to cancel the previous promise if it is still running * @returns {Promise} */ function namespaceThrottler(namespace, fn, options) { if (!storage[namespace]) { storage[namespace] = nonameThrottler(fn, options); } return storage[namespace]; } global.promiseThrottler = promiseThrottler; })(window);
/* * Author: CM */ (function(global) { /** * @callback PromiseThrottled * @param {...Object|String|Number} any number of optional params * @return {Promise} */ /** * @param {PromiseThrottled} fn * @param {Object|null} options * @param {Boolean} options.cancel Whether to cancel the previous promise if it is still running. * @returns {PromiseThrottled} */ function promiseThrottler(fn, options) { options = _.defaults(options || {}, {cancel: false}); var promise; return function() { if (options.cancel && promise && promise.isPending() && promise.isCancellable()) { promise.cancel(); promise = null; } if (!promise || !promise.isPending()) { promise = fn.apply(null, arguments); } return promise; }; } var throttlersStorage = {}; /** * @param {String} namespace * @param {PromiseThrottled} fn * @param {Object|null} options * @param {Boolean} options.cancel Whether to cancel the previous promise if it is still running * @returns {Promise} */ function throttle(namespace, fn, options) { if (!throttlersStorage[namespace]) { throttlersStorage[namespace] = throttleFunction(fn, options); } return throttlersStorage[namespace](); } global.throttleFunction = throttleFunction; global.throttle = throttle; // temporary backward compatibility global.promiseThrottler = throttleFunction; })(window);
Change soundcloud sync to happen every 20 minutes
import logging import newrelic.agent log = logging.getLogger(__name__) def send_saved_search_alerts(): from pmg import app from pmg.models import SavedSearch application = newrelic.agent.application() with newrelic.agent.BackgroundTask(application, name='send_saved_search_alerts', group='Task'): with app.app_context(): SavedSearch.send_all_alerts() def sync_soundcloud(): from pmg import app from pmg.models.soundcloud_track import SoundcloudTrack application = newrelic.agent.application() with newrelic.agent.BackgroundTask(application, name='sync_soundcloud', group='Task'): with app.app_context(): SoundcloudTrack.sync() def schedule(): from pmg import scheduler # Schedule background task for sending saved search alerts every # day at 3am (UTC) jobs = [ scheduler.add_job('pmg.tasks:send_saved_search_alerts', 'cron', id='send-saved-search-alerts', replace_existing=True, coalesce=True, hour=3), scheduler.add_job(sync_soundcloud, 'cron', id='sync-soundcloud', replace_existing=True, coalesce=True, minute='*/20'), ] for job in jobs: log.info("Scheduled task: %s" % job)
import logging import newrelic.agent log = logging.getLogger(__name__) def send_saved_search_alerts(): from pmg import app from pmg.models import SavedSearch application = newrelic.agent.application() with newrelic.agent.BackgroundTask(application, name='send_saved_search_alerts', group='Task'): with app.app_context(): SavedSearch.send_all_alerts() def sync_soundcloud(): from pmg import app from pmg.models.soundcloud_track import SoundcloudTrack application = newrelic.agent.application() with newrelic.agent.BackgroundTask(application, name='sync_soundcloud', group='Task'): with app.app_context(): SoundcloudTrack.sync() def schedule(): from pmg import scheduler # Schedule background task for sending saved search alerts every # day at 3am (UTC) jobs = [ scheduler.add_job('pmg.tasks:send_saved_search_alerts', 'cron', id='send-saved-search-alerts', replace_existing=True, coalesce=True, hour=3), scheduler.add_job(sync_soundcloud, 'cron', id='sync-soundcloud', replace_existing=True, coalesce=True, minute='*/1'), ] for job in jobs: log.info("Scheduled task: %s" % job)
Enable auto creating translation category
<?php namespace papalapa\yiistart\models; use papalapa\yiistart\modules\i18n\models\SourceMessage; use papalapa\yiistart\modules\i18n\models\SourceMessageCategories; use yii\i18n\MissingTranslationEvent; /** * Class TranslationEventHandler * @package papalapa\yiistart\models */ class TranslationEventHandler { /** * @param MissingTranslationEvent $event */ public static function handleMissingTranslation(MissingTranslationEvent $event) { $sourceMessage = SourceMessage::find()->where(['[[category]]' => $event->category, '[[message]]' => $event->message])->one(); if (!$sourceMessage) { $sourceMessage = new SourceMessage(); $sourceMessage->setAttributes(['category' => $event->category, 'message' => $event->message]); $sourceMessage->save(); if (!$sourceMessage->categoryDescription) { $sourceMessageCategory = new SourceMessageCategories([ 'category' => $event->category, ]); $sourceMessageCategory->save(); } \Yii::warning(sprintf('Translation (%s|%s) created as "%s"', $event->category, $event->language, $event->message)); } $sourceMessage->initMessages(); $sourceMessage->saveMessages(); } }
<?php namespace papalapa\yiistart\models; use papalapa\yiistart\modules\i18n\models\SourceMessage; use papalapa\yiistart\modules\i18n\models\SourceMessageCategories; use yii\i18n\MissingTranslationEvent; /** * Class TranslationEventHandler * @package papalapa\yiistart\models */ class TranslationEventHandler { /** * @param MissingTranslationEvent $event */ public static function handleMissingTranslation(MissingTranslationEvent $event) { $sourceMessage = SourceMessage::find()->where(['[[category]]' => $event->category, '[[message]]' => $event->message])->one(); if (!$sourceMessage) { $sourceMessage = new SourceMessage(); $sourceMessage->setAttributes(['category' => $event->category, 'message' => $event->message]); $sourceMessage->save(); if (!$sourceMessage->category) { $sourceMessageCategory = new SourceMessageCategories([ 'category' => $event->category, ]); $sourceMessageCategory->save(); } \Yii::warning(sprintf('Translation (%s|%s) created as "%s"', $event->category, $event->language, $event->message)); } $sourceMessage->initMessages(); $sourceMessage->saveMessages(); } }
Use a real email in contactUs email from-field
Meteor.methods({ addContactUsMessage: function(message) { try { // synchronous (to the server) insert ContactUsMessages.insert({ name: message.name, email: message.email, zipcode: message.zipcode, text: message.text, createdAt: new Date(), authorId: Meteor.userId(), // can be null, meaning a message from someone not logged in }); // send an email to ourselves containing the message var text = 'name: ' + message.name + '\nemail: ' + message.email + '\nzipcode: ' + message.zipcode + '\ntext: ' + message.text; var email = { to: "GrowSocial Pilot Coordinator <[email protected]>", from: "GrowSocial Pilot Website <[email protected]>", subject: "GrowSocial pilot message - Contact Us", text: text, }; // no need to do anything with email errors here, so pass empty callback Meteor.call('sendEmail', email, function() {}); return; // undefined, i.e. a positive response to client/caller } catch (err) { console.log('caught err from insert, will add to error log, then rethrow to server & client'); Meteor.call('addErrorLog', { tag: 'ContactUsMessages.insert', message: err.message + ', message: ' + EJSON.stringify(message).substring(1,300), }); throw(err); } }, });
Meteor.methods({ addContactUsMessage: function(message) { try { // synchronous (to the server) insert ContactUsMessages.insert({ name: message.name, email: message.email, zipcode: message.zipcode, text: message.text, createdAt: new Date(), authorId: Meteor.userId(), // can be null, meaning a message from someone not logged in }); // send an email to ourselves containing the message var text = 'name: ' + message.name + '\nemail: ' + message.email + '\nzipcode: ' + message.zipcode + '\ntext: ' + message.text; var email = { to: "GrowSocial Pilot Coordinator <[email protected]>", from: "GrowSocial Pilot Website <[email protected]>", subject: "GrowSocial pilot message - Contact Us", text: text, }; // no need to do anything with email errors here, so pass empty callback Meteor.call('sendEmail', email, function() {}); return; // undefined, i.e. a positive response to client/caller } catch (err) { console.log('caught err from insert, will add to error log, then rethrow to server & client'); Meteor.call('addErrorLog', { tag: 'ContactUsMessages.insert', message: err.message + ', message: ' + EJSON.stringify(message).substring(1,300), }); throw(err); } }, });
Prepend base URL to assets
<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>{{ $title }}</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1"> <meta name="theme-color" content="{{ $forum->attributes->themePrimaryColor }}"> @foreach ($styles as $file) <link rel="stylesheet" href="{{ $forum->attributes->baseUrl . str_replace(public_path(), '', $file) }}"> @endforeach {!! $head !!} </head> <body> {!! $layout !!} <div id="modal"></div> <div id="alerts"></div> @if (! $noJs) @foreach ($scripts as $file) <script src="{{ $forum->attributes->baseUrl . str_replace(public_path(), '', $file) }}"></script> @endforeach <script> try { var app = System.get('flarum/app').default; babelHelpers._extends(app, {!! json_encode($app) !!}); @foreach ($bootstrappers as $bootstrapper) System.get('{{ $bootstrapper }}'); @endforeach app.boot(); } catch (e) { window.location = window.location + '?nojs=1'; throw e; } </script> @endif {!! $foot !!} </body> </html>
<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>{{ $title }}</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1"> <meta name="theme-color" content="{{ $forum->attributes->themePrimaryColor }}"> @foreach ($styles as $file) <link rel="stylesheet" href="{{ str_replace(public_path(), '', $file) }}"> @endforeach {!! $head !!} </head> <body> {!! $layout !!} <div id="modal"></div> <div id="alerts"></div> @if (! $noJs) @foreach ($scripts as $file) <script src="{{ str_replace(public_path(), '', $file) }}"></script> @endforeach <script> try { var app = System.get('flarum/app').default; babelHelpers._extends(app, {!! json_encode($app) !!}); @foreach ($bootstrappers as $bootstrapper) System.get('{{ $bootstrapper }}'); @endforeach app.boot(); } catch (e) { window.location = window.location + '?nojs=1'; throw e; } </script> @endif {!! $foot !!} </body> </html>
[logicmind] Allow more representations when parsing
from tokens.andd import And from tokens.expression import Expression from tokens.iff import Iff from tokens.nop import Not from tokens.orr import Or from tokens.then import Then from tokens.variable import Variable class TokenParser: """This parser only works with atomic expressions, so parenthesis are needed everywhere to group items""" @staticmethod def parse_expression(string): # Separate parenthesis so they're new tokens # Also convert [ or { to the same parenthesis ( for s in '([{': string = string.replace(s, ' ( ') for s in ')]}': string = string.replace(s, ' ) ') # Get all operators so we can iterate over them operators = [Not, Then, Iff, Or, And] # Get all the tokens words = string.split() # Store the found nested expressions on the stack expressions_stack = [Expression()] for w in words: done = False for operator in operators: if w in operator.representations: expressions_stack[-1].add_token(operator()) done = True break if done: pass elif w == '(': expressions_stack.append(Expression()) elif w == ')': e = expressions_stack.pop() expressions_stack[-1].add_token(e) else: expressions_stack[-1].add_token(Variable(w)) return expressions_stack[0]
from tokens.andd import And from tokens.expression import Expression from tokens.iff import Iff from tokens.nop import Not from tokens.orr import Or from tokens.then import Then from tokens.variable import Variable class TokenParser: """This parser only works with atomic expressions, so parenthesis are needed everywhere to group items""" @staticmethod def parse_expression(string): # Separate parenthesis so they're new tokens # Also convert [ or { to the same parenthesis ( for s in '([{': string = string.replace(s, ' ( ') for s in ')]}': string = string.replace(s, ' ) ') # Get all the tokens words = string.split() expressions_stack = [Expression()] for w in words: if w == '(': expressions_stack.append(Expression()) elif w == ')': e = expressions_stack.pop() expressions_stack[-1].add_token(e) elif w == '¬': expressions_stack[-1].add_token(Not()) elif w == '->': expressions_stack[-1].add_token(Then()) elif w == '<->': expressions_stack[-1].add_token(Iff()) elif w == 'v': expressions_stack[-1].add_token(Or()) elif w == '^': expressions_stack[-1].add_token(And()) else: expressions_stack[-1].add_token(Variable(w)) return expressions_stack[0]
Make sure events are working correctly on front page
define([ 'zepto', 'Underscore', 'Backbone', 'models/expenses', 'text!../../tpl/home.html' ], function ($, _, Backbone, Expenses, template) { var HomeView = Backbone.View.extend({ events:{ "click #get":"refresh", "click tr": "navigate_row" }, navigate_row: function (event){ $(event.currentTarget).find('a')[0].click(); }, initialize: function(){ this.bind(); this.refresh(); }, render: function () { this.$el.html(_.template(template,{'models':this.model.toJSON()})); this.slot.html(this.el); return this; }, refresh: function(){ this.model.fetch(); }, bind: function(){ this.model.on('reset',this.render,this); this.model.on('add', this.render,this); this.model.on('remove',this.render, this); } }); return new HomeView({model:new Expenses()}); });
define([ 'zepto', 'Underscore', 'Backbone', 'models/expenses', 'text!../../tpl/home.html' ], function ($, _, Backbone, Expenses, template) { var HomeView = Backbone.View.extend({ events:{ "click #get":"refresh" }, initialize: function(){ this.bind(); this.refresh(); }, render: function () { this.el=_.template(template,{'models':this.model.toJSON()}); this.slot.html(this.el); return this; }, refresh: function(){ this.model.fetch(); }, bind: function(){ this.model.on('reset',this.render,this); this.model.on('add', this.render,this); this.model.on('remove',this.render, this); } }); return new HomeView({model:new Expenses()}); });
Revert "rm for readd alter" This reverts commit 0a0a873bb6a66a9be52dfd3f13fc1f1d0d8af226.
<?php class Pagination extends Schema { function __construct($config){ parent::__construct($config); $max = isset($config['size'])? $config['size'] : 100; $this->_schema = array( "type"=> "object", "description"=> "Request a slice of the final data set.", "properties"=> array( "limit"=> array( "type"=> "number", "description"=> "The number of items to fetch.", "default"=> 20, "minimum"=> 1, "maximum"=> $max ), "offset"=> array( "type"=> "number", "description"=> "Start with this item. 0-based.", "default"=> 0, "minimum"=> 0 ), "pageNumber"=> array( "type"=>"number", "description"=> "The page", "default"=> 1, "minimum"=> 1, ), "pageSize"=> array( "description"=> "The number of items to fetch per page.", "default"=> $max, "minimum"=> 1, ), ) ); } }
<?php class Pagination extends Schema { function __construct($config){ parent::__construct($config); $this->_schema = array( "type"=> "object", "description"=> "Request a slice of the final data set.", "properties"=> array( "limit"=> array( "type"=> "number", "description"=> "The number of items to fetch.", "default"=> 20, "minimum"=> 1, "maximum"=> 100 ), "offset"=> array( "type"=> "number", "description"=> "Start with this item. 0-based.", "default"=> 0, "minimum"=> 0 ), "page"=> array( "type"=> "object", "description"=> "Get items based on a page and pagesize, more natural for browsing.", "properties"=> array( "number"=> array( "description"=> "The page", "default"=> 1, "minimum"=> 1, ), "size"=> array( "description"=> "The number of items to fetch per page.", "default"=> 25, "minimum"=> 1, ), ), "required"=>array("number","size"), ), "required"=>array("limit","offset"), ) ); } }
Add 3.5 to PyPI info
# -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as f: readme = f.read() setup( name='whatthepatch', version='0.0.3', description='A patch parsing library.', long_description=readme, author='Christopher S. Corley', author_email='[email protected]', url='https://github.com/cscorley/whatthepatch', license='MIT', packages=['whatthepatch'], include_package_data=True, keywords=[ "patch", "diff", "parser", ], classifiers=[ "Operating System :: OS Independent", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "Topic :: Software Development", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Development :: Version Control", "Topic :: Text Processing", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ], )
# -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as f: readme = f.read() setup( name='whatthepatch', version='0.0.3', description='A patch parsing library.', long_description=readme, author='Christopher S. Corley', author_email='[email protected]', url='https://github.com/cscorley/whatthepatch', license='MIT', packages=['whatthepatch'], include_package_data=True, keywords=[ "patch", "diff", "parser", ], classifiers=[ "Operating System :: OS Independent", "License :: OSI Approved :: MIT License", "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "Topic :: Software Development", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Development :: Version Control", "Topic :: Text Processing", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], )
Undo redundant embedded URI check. git-svn-id: 25f448894bd6eb0cddf10ded73b4f5a7ea3203f3@1782 48356398-32a2-884e-a903-53898d9a118a
<?php class HTMLPurifier_URIFilter_SecureMunge extends HTMLPurifier_URIFilter { public $name = 'SecureMunge'; public $post = true; private $target, $secretKey, $parser; public function prepare($config) { $this->target = $config->get('URI', 'SecureMunge'); $this->secretKey = $config->get('URI', 'SecureMungeSecretKey'); $this->parser = new HTMLPurifier_URIParser(); if (!$this->secretKey) { trigger_error('URI.SecureMunge is being ignored due to lack of value for URI.SecureMungeSecretKey', E_USER_WARNING); return false; } return true; } public function filter(&$uri, $config, $context) { if (!$this->target || !$this->secretKey) return true; if ($context->get('EmbeddedURI', true)) return true; // abort for embedded URIs $scheme_obj = $uri->getSchemeObj($config, $context); if (!$scheme_obj) return true; // ignore unknown schemes, maybe another postfilter did it if (is_null($uri->host) || empty($scheme_obj->browsable)) { return true; } $string = $uri->toString(); $checksum = sha1($this->secretKey . ':' . $string); $new_uri = str_replace('%s', rawurlencode($string), $this->target); $new_uri = str_replace('%t', $checksum, $new_uri); $uri = $this->parser->parse($new_uri); // overwrite return true; } }
<?php class HTMLPurifier_URIFilter_SecureMunge extends HTMLPurifier_URIFilter { public $name = 'SecureMunge'; public $post = true; private $target, $secretKey, $parser; public function prepare($config) { $this->target = $config->get('URI', 'SecureMunge'); $this->secretKey = $config->get('URI', 'SecureMungeSecretKey'); $this->parser = new HTMLPurifier_URIParser(); if (!$this->secretKey) { trigger_error('URI.SecureMunge is being ignored due to lack of value for URI.SecureMungeSecretKey', E_USER_WARNING); return false; } return true; } public function filter(&$uri, $config, $context) { if (!$this->target || !$this->secretKey) return true; if ($context->get('EmbeddedURI', true)) return true; // abort for embedded URIs $scheme_obj = $uri->getSchemeObj($config, $context); if (!$scheme_obj) return true; // ignore unknown schemes, maybe another postfilter did it if (is_null($uri->host) || empty($scheme_obj->browsable) || $context->get('EmbeddedURI', true)) { return true; } $string = $uri->toString(); $checksum = sha1($this->secretKey . ':' . $string); $new_uri = str_replace('%s', rawurlencode($string), $this->target); $new_uri = str_replace('%t', $checksum, $new_uri); $uri = $this->parser->parse($new_uri); // overwrite return true; } }
Fix component defaults was shared
import pluck from './pluck'; import { ref, refs, noop, mixin, insertCss, emptyTemplate, computedAll, pureComputedAll } from '../util/'; const modulePolyfill = { constructor: noop, defaults: {}, template: emptyTemplate }; // Transform transiton component module to native component module // // @param {Object} module Transiton component module // @return {Object} Native component module function transform(module) { const { name, constructor, defaults, mixins, methods, computed, pureComputed, style, template } = Object.assign({}, modulePolyfill, module); insertCss(module.style); Object.assign(constructor.prototype, { ref, refs, ready: noop }, methods); return { viewModel: { createViewModel(params, componentInfo) { componentInfo.name = name; const opts = Object.assign( {}, defaults, ko.toJS(params), pluck(componentInfo.element) ); const vm = new constructor(opts, componentInfo); mixins && mixin(vm, opts, mixins) computed && computedAll(vm, computed); pureComputed && pureComputedAll(vm, pureComputed); vm.$opts = opts; vm.$defaults = defaults; vm.$info = vm.componentInfo = componentInfo; delete vm.$opts['$raw']; delete vm.$defaults['$raw']; return vm; } }, synchronous: true, template }; } export default transform;
import pluck from './pluck'; import { ref, refs, noop, mixin, insertCss, emptyTemplate, computedAll, pureComputedAll } from '../util/'; const modulePolyfill = { constructor: noop, defaults: {}, template: emptyTemplate }; // Transform transiton component module to native component module // // @param {Object} module Transiton component module // @return {Object} Native component module function transform(module) { const { name, constructor, defaults, mixins, methods, computed, pureComputed, style, template } = Object.assign({}, modulePolyfill, module); insertCss(module.style); Object.assign(constructor.prototype, { ref, refs, ready: noop }, methods); return { viewModel: { createViewModel(params, componentInfo) { componentInfo.name = name; const opts = Object.assign( defaults, ko.toJS(params), pluck(componentInfo.element) ); const vm = new constructor(opts, componentInfo); mixins && mixin(vm, opts, mixins) computed && computedAll(vm, computed); pureComputed && pureComputedAll(vm, pureComputed); vm.$opts = opts; vm.$defaults = defaults; vm.$info = vm.componentInfo = componentInfo; delete vm.$opts['$raw']; delete vm.$defaults['$raw']; return vm; } }, synchronous: true, template }; } export default transform;
Fix errors in integration pkg
package com.raoulvdberge.refinedstorage.integration.forgeenergy; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraftforge.energy.EnergyStorage; public class ItemEnergyForge extends EnergyStorage { private static final String NBT_ENERGY = "Energy"; private ItemStack stack; public ItemEnergyForge(ItemStack stack, int capacity) { super(capacity, Integer.MAX_VALUE, Integer.MAX_VALUE); this.stack = stack; this.energy = stack.hasTag() && stack.getTag().contains(NBT_ENERGY) ? stack.getTag().getInt(NBT_ENERGY) : 0; } @Override public int receiveEnergy(int maxReceive, boolean simulate) { int received = super.receiveEnergy(maxReceive, simulate); if (received > 0 && !simulate) { if (!stack.hasTag()) { stack.setTag(new CompoundNBT()); } stack.getTag().putInt(NBT_ENERGY, getEnergyStored()); } return received; } @Override public int extractEnergy(int maxExtract, boolean simulate) { int extracted = super.extractEnergy(maxExtract, simulate); if (extracted > 0 && !simulate) { if (!stack.hasTag()) { stack.setTag(new CompoundNBT()); } stack.getTag().putInt(NBT_ENERGY, getEnergyStored()); } return extracted; } }
package com.raoulvdberge.refinedstorage.integration.forgeenergy; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.energy.EnergyStorage; public class ItemEnergyForge extends EnergyStorage { private static final String NBT_ENERGY = "Energy"; private ItemStack stack; public ItemEnergyForge(ItemStack stack, int capacity) { super(capacity, Integer.MAX_VALUE, Integer.MAX_VALUE); this.stack = stack; this.energy = stack.hasTagCompound() && stack.getTagCompound().hasKey(NBT_ENERGY) ? stack.getTagCompound().getInteger(NBT_ENERGY) : 0; } @Override public int receiveEnergy(int maxReceive, boolean simulate) { int received = super.receiveEnergy(maxReceive, simulate); if (received > 0 && !simulate) { if (!stack.hasTagCompound()) { stack.setTagCompound(new NBTTagCompound()); } stack.getTagCompound().setInteger(NBT_ENERGY, getEnergyStored()); } return received; } @Override public int extractEnergy(int maxExtract, boolean simulate) { int extracted = super.extractEnergy(maxExtract, simulate); if (extracted > 0 && !simulate) { if (!stack.hasTagCompound()) { stack.setTagCompound(new NBTTagCompound()); } stack.getTagCompound().setInteger(NBT_ENERGY, getEnergyStored()); } return extracted; } }
Fix update_permission command for legacy content types
import logging from django.conf import settings from django.utils.importlib import import_module from django.db.models import get_apps from django.contrib.auth.management import create_permissions from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand from mapentity import registry from mapentity.registry import create_mapentity_model_permissions from geotrek.common.mixins import BasePublishableMixin logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Create models permissions" def execute(self, *args, **options): logger.info("Synchronize django permissions") for app in get_apps(): create_permissions(app, [], int(options.get('verbosity', 1))) logger.info("Done.") logger.info("Synchronize mapentity permissions") # Make sure apps are registered at this point import_module(settings.ROOT_URLCONF) # For all models registered, add missing bits for model in registry.registry.keys(): create_mapentity_model_permissions(model) logger.info("Done.") logger.info("Synchronize geotrek permissions") for content_type in ContentType.objects.all(): model = content_type.model_class() if model and issubclass(model, BasePublishableMixin): Permission.objects.get_or_create( codename='publish_%s' % content_type.model, name='Can publish %s' % content_type.name, content_type=content_type) logger.info("Done.")
import logging from django.conf import settings from django.utils.importlib import import_module from django.db.models import get_apps from django.contrib.auth.management import create_permissions from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.core.management.base import BaseCommand from mapentity import registry from mapentity.registry import create_mapentity_model_permissions from geotrek.common.mixins import BasePublishableMixin logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Create models permissions" def execute(self, *args, **options): logger.info("Synchronize django permissions") for app in get_apps(): create_permissions(app, [], int(options.get('verbosity', 1))) logger.info("Done.") logger.info("Synchronize mapentity permissions") # Make sure apps are registered at this point import_module(settings.ROOT_URLCONF) # For all models registered, add missing bits for model in registry.registry.keys(): create_mapentity_model_permissions(model) logger.info("Done.") logger.info("Synchronize geotrek permissions") for content_type in ContentType.objects.all(): if issubclass(content_type.model_class(), BasePublishableMixin): Permission.objects.get_or_create( codename='publish_%s' % content_type.model, name='Can publish %s' % content_type.name, content_type=content_type) logger.info("Done.")
Test the actual test result.
/* eslint-disable no-console, no-duplicate-imports, import/no-duplicates */ import _ from 'lodash'; import proxyquire from 'proxyquire'; import describe from '../src'; import { specStream } from '../src'; describe('RxT', (it) => { it('should run a simple passing and failing given/when/then test', test => test .given('givenWhenThen') .whenObserving((testFile) => { const spec = proxyquire(`./samples/${testFile}`, { '../../src': { default: specStream, }, }); return spec; }) .then( (result) => { const expected = [ { 'should capitalize just hello': 'pass', }, { 'should capitalize just hello': 'pass', 'should fail to assert the proper hello': 'fail', }, ]; result.results.should.have.keys(..._.keys(expected[result.step])); _.forIn(expected[result.step], (val, key) => { result.results[key].result.should.equal(val); }); }, ) ); });
/* eslint-disable no-console, no-duplicate-imports, import/no-duplicates */ import proxyquire from 'proxyquire'; import describe from '../src'; import { specStream } from '../src'; describe('RxT', (it) => { it('should run a simple passing and failing given/when/then test', test => test .given('givenWhenThen') .whenObserving((testFile) => { const spec = proxyquire(`./samples/${testFile}`, { '../../src': { default: specStream, }, }); return spec; }) .then( (result) => { const expected = [ ['should capitalize just hello'], [ 'should capitalize just hello', 'should fail to assert the proper hello', ], ]; result.results.should.have.keys(...expected[result.step]); }, ) ); });
Stop processing when language is deselected.
import axios from 'axios'; import { CHANGE_LANGUAGE, FETCH_NODES, FILTER_CONTENT_KIND, FILTER_TOPIC, FILTER_VISIBIITY, } from './types'; const API_TRANSLATE_NOW = 'https://www.khanacademy.org/api/internal/translate_now?'; /** * Activated by the user. Triggers other actions, does nothing by itself. * @param {Object} language structure containing language name and code. * @return {undefined} */ export const chooseLanguage = (language) => (dispatch) => { // change the chosen language in the state dispatch({ type: CHANGE_LANGUAGE, payload: language, }); // if language was deselected, there is nothing more to do if (!language) { return; } // get translation data from Khan Academy API and set in state dispatch({ type: FETCH_NODES, payload: axios.get(`${API_TRANSLATE_NOW}lang=${language.code}`), }); }; export const filterContentKind = (contentKind) => (dispatch) => { // change the chosen content type in the store dispatch({ type: FILTER_CONTENT_KIND, payload: contentKind, }); }; export const filterTopic = (topic) => (dispatch) => { // change the chosen topic in the store dispatch({ type: FILTER_TOPIC, payload: topic, }); }; export const filterVisibility = (key) => (dispatch) => { // change the chosen visibility in the store dispatch({ type: FILTER_VISIBIITY, payload: key, }); };
import axios from 'axios'; import { CHANGE_LANGUAGE, FETCH_NODES, FILTER_CONTENT_KIND, FILTER_TOPIC, FILTER_VISIBIITY, } from './types'; const API_TRANSLATE_NOW = 'https://www.khanacademy.org/api/internal/translate_now?'; /** * Activated by the user. Triggers other actions, does nothing by itself. * @param {Object} language structure containing language name and code. * @return {undefined} */ export const chooseLanguage = (language) => (dispatch) => { // change the chosen language in the state dispatch({ type: CHANGE_LANGUAGE, payload: language, }); // get translation data from Khan Academy API and set in state dispatch({ type: FETCH_NODES, payload: axios.get(`${API_TRANSLATE_NOW}lang=${language.code}`), }); }; export const filterContentKind = (contentKind) => (dispatch) => { // change the chosen content type in the store dispatch({ type: FILTER_CONTENT_KIND, payload: contentKind, }); }; export const filterTopic = (topic) => (dispatch) => { // change the chosen topic in the store dispatch({ type: FILTER_TOPIC, payload: topic, }); }; export const filterVisibility = (key) => (dispatch) => { // change the chosen visibility in the store dispatch({ type: FILTER_VISIBIITY, payload: key, }); };
Include config files in the pip install
#!/usr/bin/env python from setuptools import setup, find_packages from dreambeam import __version__ setup(name='dreamBeam', version=__version__, description='Measurement equation framework for radio interferometry.', author='Tobia D. Carozzi', author_email='[email protected]', packages=find_packages(), package_data={'dreambeam.telescopes.LOFAR': ['share/*.cc', 'share/simmos/*.cfg', 'share/alignment/*.txt', 'data/*teldat.p'], 'dreambeam': ['configs/*.txt']}, include_package_data=True, license='ISC', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: ISC License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Visualization' ], install_requires=[ 'numpy>=1.10', 'python-casacore', 'matplotlib>2.0', 'antpat>=0.4' ], entry_points={ 'console_scripts': [ 'pointing_jones = scripts.pointing_jones:cli_main', 'FoV_jones = scripts.FoV_jones:main' ] } )
#!/usr/bin/env python from setuptools import setup, find_packages from dreambeam import __version__ setup(name='dreamBeam', version=__version__, description='Measurement equation framework for radio interferometry.', author='Tobia D. Carozzi', author_email='[email protected]', packages=find_packages(), package_data={'dreambeam.telescopes.LOFAR': ['share/*.cc', 'share/simmos/*.cfg', 'share/alignment/*.txt', 'data/*teldat.p']}, license='ISC', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: ISC License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Visualization' ], install_requires=[ 'numpy>=1.10', 'python-casacore', 'matplotlib>2.0', 'antpat>=0.4' ], entry_points={ 'console_scripts': [ 'pointing_jones = scripts.pointing_jones:cli_main', 'FoV_jones = scripts.FoV_jones:main' ] } )
Support to request null string
import ast def isEmpty(value): if value: return False else: return True def isNotEmpty(value): if not value: return False else: return True def stringToDict(param): if isNotEmpty(param) or param != '': return ast.literal_eval(param) def stringToDictList(list): dic_list = [] if list is not None: for r in list: dic_list.append(stringToDict(r)) return dic_list def deleteNullDict(dic): if dic is not None: diccopy = dic.copy() if 'csrfmiddlewaretoken' in diccopy: del diccopy['csrfmiddlewaretoken'] for key, value in dic.items(): if value == 'None': del diccopy[key] dic = diccopy return dic def putKeyVlue(param): param = stringToDict(param) if param is not None: param = ast.literal_eval(param) return param def list_to_record(list): if isEmpty(list): return None record = None for param in list: record = param break return record def isNone(*value): for v in value: if v is None: return True return False
import ast def isEmpty(value): if value: return False else: return True def isNotEmpty(value): if not value: return False else: return True def stringToDict(param): if isNotEmpty(param) or param != '': return ast.literal_eval(param) def stringToDictList(list): dic_list = [] if list is not None: for r in list: dic_list.append(stringToDict(r)) return dic_list def deleteNullDict(dic): if dic is not None: diccopy = dic.copy() if 'csrfmiddlewaretoken' in diccopy: del diccopy['csrfmiddlewaretoken'] for key, value in dic.items(): if isEmpty(value) or value == 'None' or value == '': del diccopy[key] dic = diccopy return dic def putKeyVlue(param): param = stringToDict(param) if param is not None: param = ast.literal_eval(param) return param def list_to_record(list): if isEmpty(list): return None record = None for param in list: record = param break return record def isNone(*value): for v in value: if v is None: return True return False
Check if build number exists (so we won't create a package with 'None' in it's name)
from glob import glob import imp import logging import os import subprocess import mock from setuptools import setup as _setup from vdt.versionplugin.wheel.shared import parse_version_extra_args from vdt.versionplugin.wheel.utils import WheelRunningDistribution logger = logging.getLogger(__name__) def build_package(version): """ In here should go code that runs you package building scripts. """ def fixed_version_setup(*args, **kwargs): old_version = kwargs.pop('version') base_version = ".".join(map(str, version.version)) python_version = base_version if version.build_number is not None: python_version = "%src%s" % (base_version, version.build_number) logging.info( "Version in file is %s, using %s" % ( old_version, python_version)) _setup( version=python_version, distclass=WheelRunningDistribution, *args, **kwargs) args, extra_args = parse_version_extra_args(version.extra_args) with version.checkout_tag: with mock.patch('setuptools.setup', fixed_version_setup): imp.load_source('packagesetup', 'setup.py') if args.build_dependencies: build_dir = "%s/dist/" % os.getcwd() wheels = glob("%s/*.whl" % build_dir) cmd = ['pip', 'wheel'] + wheels logger.debug("Running command {0}".format(" ".join(cmd))) logger.debug(subprocess.check_output(cmd, cwd=build_dir)) return 0
from glob import glob import imp import logging import os import subprocess import mock from setuptools import setup as _setup from vdt.versionplugin.wheel.shared import parse_version_extra_args from vdt.versionplugin.wheel.utils import WheelRunningDistribution logger = logging.getLogger(__name__) def build_package(version): """ In here should go code that runs you package building scripts. """ def fixed_version_setup(*args, **kwargs): old_version = kwargs.pop('version') base_version = ".".join(map(str, version.version)) python_version = "%src%s" % (base_version, version.build_number) logging.info( "Version in file is %s, using %s" % ( old_version, python_version)) _setup( version=python_version, distclass=WheelRunningDistribution, *args, **kwargs) args, extra_args = parse_version_extra_args(version.extra_args) with version.checkout_tag: with mock.patch('setuptools.setup', fixed_version_setup): imp.load_source('packagesetup', 'setup.py') if args.build_dependencies: build_dir = "%s/dist/" % os.getcwd() wheels = glob("%s/*.whl" % build_dir) cmd = ['pip', 'wheel'] + wheels logger.debug("Running command {0}".format(" ".join(cmd))) logger.debug(subprocess.check_output(cmd, cwd=build_dir)) return 0
Stop closing the connection. Rely on the pool
var mssql = require("mssql"); var database = { query: function(connection, query, callback) { mssql.connect(connection, function(connectionError) { if(connectionError) { mssql.close(); callback(connectionError, []); } else { var request = new mssql.Request(); // Attach the input params to the request var values = query.values || []; for(var i = 0; i !== values.length; i++) { request.input((i + 1).toString(), query.values[i]); } request.query(query.text, function(queryError, rows) { callback(queryError, rows || []); }); } }); }, execute: function(connection, name, parameters, callback) { mssql.connect(connection, function(connectionError) { if(connectionError) { mssql.close(); callback(connectionError, []); } else { var request = new mssql.Request(); // Attach input params to the request var params = parameters || {}; var keys = Object.keys(params); for(var i = 0; i !== keys.length; i++) { var key = keys[i]; request.input(key, params[key]); } request.execute(name, function(error, recordsets) { callback(error, recordsets || []); }); } }); } }; module.exports = database;
var mssql = require("mssql"); var database = { query: function(connection, query, callback) { mssql.connect(connection, function(connectionError) { if(connectionError) { mssql.close(); callback(connectionError, []); } else { var request = new mssql.Request(); // Attach the input params to the request var values = query.values || []; for(var i = 0; i !== values.length; i++) { request.input((i + 1).toString(), query.values[i]); } request.query(query.text, function(queryError, rows) { mssql.close(); callback(queryError, rows || []); }); } }); }, execute: function(connection, name, parameters, callback) { mssql.connect(connection, function(connectionError) { if(connectionError) { mssql.close(); callback(connectionError, []); } else { var request = new mssql.Request(); // Attach input params to the request var params = parameters || {}; var keys = Object.keys(params); for(var i = 0; i !== keys.length; i++) { var key = keys[i]; request.input(key, params[key]); } request.execute(name, function(error, recordsets) { mssql.close(); callback(error, recordsets || []); }); } }); } }; module.exports = database;
Make twine check happy [ci skip]
"""colorise module setup script for distribution.""" from setuptools import setup import os def get_version(filename): with open(filename) as fh: for line in fh: if line.startswith('__version__'): return line.split('=')[-1].strip()[1:-1] setup( name='colorise', version=get_version(os.path.join('colorise', '__init__.py')), author='Alexander Asp Bock', author_email='[email protected]', platforms='Platform independent', description=('Easily print colored text to the console'), license='BSD 3-Clause License', keywords='text, color, colorise, colorize, console, terminal', packages=['colorise', 'colorise.win', 'colorise.nix'], package_data={'colorise': ['tests', 'examples']}, url='https://github.com/MisanthropicBit/colorise', long_description=open('README.md').read(), long_description_content_type='text/markdown', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Utilities', 'Topic :: Terminals', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: PyPy' ] )
"""colorise module setup script for distribution.""" from setuptools import setup import os def get_version(filename): with open(filename) as fh: for line in fh: if line.startswith('__version__'): return line.split('=')[-1].strip()[1:-1] setup( name='colorise', version=get_version(os.path.join('colorise', '__init__.py')), author='Alexander Asp Bock', author_email='[email protected]', platforms='Platform independent', description=('Easily print colored text to the console'), license='BSD 3-Clause License', keywords='text, color, colorise, colorize, console, terminal', packages=['colorise', 'colorise.win', 'colorise.nix'], package_data={'colorise': ['tests', 'examples']}, url='https://github.com/MisanthropicBit/colorise', long_description=open('README.md').read(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Utilities', 'Topic :: Terminals', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: PyPy' ] )
Correct the usage of decorator.decorator Correct the usage of decorator.decorator as described in [1]. [1]http://pythonhosted.org/decorator/documentation.html#decorator-decorator Change-Id: Ia71b751f364e09541faecf6a43f252e0b856558e Closes-Bug: #1483464
# Copyright 2015 Huawei Technologies Co.,LTD. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import decorator import pecan from magnum.common import exception from magnum import objects def enforce_bay_types(*bay_types): @decorator.decorator def wrapper(func, *args, **kwargs): obj = args[1] bay = objects.Bay.get_by_uuid(pecan.request.context, obj.bay_uuid) baymodel = objects.BayModel.get_by_uuid(pecan.request.context, bay.baymodel_id) if baymodel.coe not in bay_types: raise exception.InvalidParameterValue( 'Cannot fulfill request with a %(bay_type)s bay, ' 'expecting a %(supported_bay_types)s bay.' % {'bay_type': baymodel.coe, 'supported_bay_types': '/'.join(bay_types)}) return func(*args, **kwargs) return wrapper
# Copyright 2015 Huawei Technologies Co.,LTD. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import decorator import pecan from magnum.common import exception from magnum import objects def enforce_bay_types(*bay_types): def decorate(func): @decorator.decorator def handler(func, *args, **kwargs): obj = args[1] bay = objects.Bay.get_by_uuid(pecan.request.context, obj.bay_uuid) baymodel = objects.BayModel.get_by_uuid(pecan.request.context, bay.baymodel_id) if baymodel.coe not in bay_types: raise exception.InvalidParameterValue( 'Cannot fulfill request with a %(bay_type)s bay, ' 'expecting a %(supported_bay_types)s bay.' % {'bay_type': baymodel.coe, 'supported_bay_types': '/'.join(bay_types)}) return func(*args, **kwargs) return handler(func) return decorate
Update package description to specify OpenGL 3.3+
from setuptools import setup setup( name="demosys-py", version="0.3.10", description="Modern OpenGL 3.3+ Framework inspired by Django", long_description=open('README.rst').read(), url="https://github.com/Contraz/demosys-py", author="Einar Forselv", author_email="[email protected]", maintainer="Einar Forselv", maintainer_email="[email protected]", packages=['demosys'], include_package_data=True, keywords = ['opengl', 'framework', 'demoscene'], classifiers=[ 'Programming Language :: Python', 'Environment :: MacOS X', 'Environment :: X11 Applications', 'Intended Audience :: Developers', 'Topic :: Multimedia :: Graphics', 'License :: OSI Approved :: ISC License (ISCL)', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Application Frameworks', ], install_requires=[ 'PyOpenGL==3.1.0', 'glfw==1.4.0', 'pyrr==0.8.2', 'Pillow==4.0.0', 'pyrocket==0.2.5', # 'pygame==1.9.3', ], entry_points={'console_scripts': [ 'demosys-admin = demosys.core.management:execute_from_command_line', ]}, )
from setuptools import setup setup( name="demosys-py", version="0.3.10", description="Modern OpenGL 4.1+ Framework inspired by Django", long_description=open('README.rst').read(), url="https://github.com/Contraz/demosys-py", author="Einar Forselv", author_email="[email protected]", maintainer="Einar Forselv", maintainer_email="[email protected]", packages=['demosys'], include_package_data=True, keywords = ['opengl', 'framework', 'demoscene'], classifiers=[ 'Programming Language :: Python', 'Environment :: MacOS X', 'Environment :: X11 Applications', 'Intended Audience :: Developers', 'Topic :: Multimedia :: Graphics', 'License :: OSI Approved :: ISC License (ISCL)', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Libraries :: Application Frameworks', ], install_requires=[ 'PyOpenGL==3.1.0', 'glfw==1.4.0', 'pyrr==0.8.2', 'Pillow==4.0.0', 'pyrocket==0.2.5', # 'pygame==1.9.3', ], entry_points={'console_scripts': [ 'demosys-admin = demosys.core.management:execute_from_command_line', ]}, )
Test multiple slashes in Path::combine
<?php namespace nochso\Omni\Test; use nochso\Omni\Path; class PathTest extends \PHPUnit_Framework_TestCase { public function combineProvider() { return [ ['', ['', '']], ['/', ['', '/']], ['/', ['/', '']], ['/a', ['/', 'a']], ['foo/bar', ['foo', 'bar']], ['/foo/bar', ['/foo', 'bar']], ['/foo/bar', ['/foo', '/bar']], ['/foo/bar', ['/foo/', '/bar']], ['1/2/3/4/5.zip', ['1', '2', '3', '4', '5.zip']], ['1/2', [['1', '2']], 'Array as single parameter'], ['1/2/3.zip', [['1', '2'], '3.zip'], 'Array and string as parameter'], ['1/2/3', [['1/2/', '/3']], 'Multiple slashes should be simplified'], ['./1/2/3/', [['.//1//2//', '3//']], 'Multiple slashes should be simplified'], ]; } /** * @dataProvider combineProvider */ public function testCombine($expected, $params, $message = '') { $this->assertEquals($expected, Path::combine(...$params), $message); } public function testLocalize() { $this->assertSame('a/b', Path::localize('a\\b')); $this->assertSame('a/b', Path::localize('a\\b', '/')); $this->assertSame('a\\b', Path::localize('a/b', '\\')); $this->assertSame('a\\b', Path::localize('a\\b', '\\')); } }
<?php namespace nochso\Omni\Test; use nochso\Omni\Path; class PathTest extends \PHPUnit_Framework_TestCase { public function combineProvider() { return [ ['', ['', '']], ['/', ['', '/']], ['/', ['/', '']], ['/a', ['/', 'a']], ['foo/bar', ['foo', 'bar']], ['/foo/bar', ['/foo', 'bar']], ['/foo/bar', ['/foo', '/bar']], ['/foo/bar', ['/foo/', '/bar']], ['1/2/3/4/5.zip', ['1', '2', '3', '4', '5.zip']], ['1/2', [['1', '2']], 'Array as single parameter'], ['1/2/3.zip', [['1', '2'], '3.zip'], 'Array and string as parameter'], ]; } /** * @dataProvider combineProvider */ public function testCombine($expected, $params, $message = '') { $this->assertEquals($expected, Path::combine(...$params), $message); } public function testLocalize() { $this->assertSame('a/b', Path::localize('a\\b')); $this->assertSame('a/b', Path::localize('a\\b', '/')); $this->assertSame('a\\b', Path::localize('a/b', '\\')); $this->assertSame('a\\b', Path::localize('a\\b', '\\')); } }
Fix name/value pairing for Google Font List
<?php /** * Gets a list of cgGroup objects. */ class cgGoogleFontListGetListProcessor extends modObjectGetListProcessor { public $languageTopics = array('clientconfig:default'); /** * {@inheritDoc} * @return mixed */ public function process() { $apiKey = $this->modx->getOption('clientconfig.google_fonts_api_key', null, ''); if (empty($apiKey)) { return $this->outputArray(array(), 0); } $apiEndpoint = "https://www.googleapis.com/webfonts/v1/webfonts?key={$apiKey}&sort=alpha"; $fonts = array(); $json = $this->modx->fromJson($this->curlGet($apiEndpoint)); $fonts = $json['items']; $total = count($fonts); $list = array(); foreach ($fonts as $font) { $item = array(); $item['family'] = str_replace(' ','+',$font['family']); $item['name'] = $font['family']; $list[] = $item; } return $this->outputArray($list,$total); } protected function curlGet($url) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $results = curl_exec($curl); curl_close($curl); return $results; } } return 'cgGoogleFontListGetListProcessor';
<?php /** * Gets a list of cgGroup objects. */ class cgGoogleFontListGetListProcessor extends modObjectGetListProcessor { public $languageTopics = array('clientconfig:default'); /** * {@inheritDoc} * @return mixed */ public function process() { $apiKey = $this->modx->getOption('clientconfig.google_fonts_api_key', null, ''); if (empty($apiKey)) { return $this->outputArray(array(), 0); } $apiEndpoint = "https://www.googleapis.com/webfonts/v1/webfonts?key={$apiKey}&sort=alpha"; $fonts = array(); $json = $this->modx->fromJson($this->curlGet($apiEndpoint)); $fonts = $json['items']; $total = count($fonts); $list = array(); foreach ($fonts as $font) { $item = array(); $item['family'] = $font['family']; $item['name'] = str_replace(' ','+',$font['family']); $list[] = $item; } return $this->outputArray($list,$total); } protected function curlGet($url) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $results = curl_exec($curl); curl_close($curl); return $results; } } return 'cgGoogleFontListGetListProcessor';
Fix certificate regenerating each startup
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from jupyter_core.paths import jupyter_data_dir import subprocess import os import os.path import errno import stat c = get_config() c.NotebookApp.ip = '*' c.NotebookApp.port = 8888 c.NotebookApp.open_browser = False # Generate a self-signed certificate if 'GEN_CERT' in os.environ: dir_name = jupyter_data_dir() pem_file = os.path.join(dir_name, 'notebook.pem') if not os.path.isfile(pem_file): try: os.makedirs(dir_name) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(dir_name): pass else: raise # Generate a certificate if one doesn't exist on disk subprocess.check_call(['openssl', 'req', '-new', '-newkey', 'rsa:2048', '-days', '365', '-nodes', '-x509', '-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated', '-keyout', pem_file, '-out', pem_file]) # Restrict access to the file os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR) c.NotebookApp.certfile = pem_file
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from jupyter_core.paths import jupyter_data_dir import subprocess import os import errno import stat c = get_config() c.NotebookApp.ip = '*' c.NotebookApp.port = 8888 c.NotebookApp.open_browser = False # Generate a self-signed certificate if 'GEN_CERT' in os.environ: dir_name = jupyter_data_dir() pem_file = os.path.join(dir_name, 'notebook.pem') try: os.makedirs(dir_name) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(dir_name): pass else: raise # Generate a certificate if one doesn't exist on disk subprocess.check_call(['openssl', 'req', '-new', '-newkey', 'rsa:2048', '-days', '365', '-nodes', '-x509', '-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated', '-keyout', pem_file, '-out', pem_file]) # Restrict access to the file os.chmod(pem_file, stat.S_IRUSR | stat.S_IWUSR) c.NotebookApp.certfile = pem_file
Implement getName() in twig extension
<?php namespace IAkumaI\SphinxsearchBundle\Twig; use IAkumaI\SphinxsearchBundle\Search\Sphinxsearch; /** * Twig extension for Sphinxsearch bundle */ class SphinxsearchExtension extends \Twig_Extension { /** * @var Sphinxsearch */ protected $searchd; /** * Constructor * @param Sphinxsearch $searchd */ public function __construct(Sphinxsearch $searchd) { $this->searchd = $searchd; } /** * Highlight $text for the $query using $index * @param string $text Text content * @param string $index Sphinx index name * @param string $query Query to search * @param integer[optional] $trim If set to integer will return trimmed string of this length * * @return string */ public function sphinx_highlight($text, $index, $query, $trim = false) { $result = $this->searchd->getClient()->BuildExcerpts(array($text), $index, $query); if (!empty($result[0])) { return $result[0]; } else { return ''; } } /** * Filters list * @return array */ public function getFilters() { return array( 'sphinx_highlight' => new \Twig_Filter_Function(array($this, 'sphinx_highlight')), ); } /** * Implement getName() method * @return string */ public function getName() { return 'iakumai_sphinxsearch_extension_0'; } }
<?php namespace IAkumaI\SphinxsearchBundle\Twig; use IAkumaI\SphinxsearchBundle\Search\Sphinxsearch; /** * Twig extension for Sphinxsearch bundle */ class SphinxsearchExtension extends \Twig_Extension { /** * @var Sphinxsearch */ protected $searchd; /** * Constructor * @param Sphinxsearch $searchd */ public function __construct(Sphinxsearch $searchd) { $this->searchd = $searchd; } /** * Highlight $text for the $query using $index * @param string $text Text content * @param string $index Sphinx index name * @param string $query Query to search * @param integer[optional] $trim If set to integer will return trimmed string of this length * * @return string */ public function sphinx_highlight($text, $index, $query, $trim = false) { $result = $this->searchd->getClient()->BuildExcerpts(array($text), $index, $query); if (!empty($result[0])) { return $result[0]; } else { return ''; } } /** * Filters list * @return array */ public function getFilters() { return array( 'sphinx_highlight' => new \Twig_Filter_Function(array($this, 'sphinx_highlight')), ); } }
Fix typo in demo gulp file
var gulp = require('gulp'), styleguide = require('./lib/styleguide'), source = 'lib/app/**/*.scss', outputPath = 'demo-output'; gulp.task('styleguide', ['static'], function() { return gulp.src(source) .pipe(styleguide({ title: 'SC5 Styleguide', server: true, rootPath: outputPath, overviewPath: 'README.md', styleVariables: 'lib/app/sass/_styleguide_variables.scss', sass: { src: 'lib/app/sass/app.scss', includePaths: [ 'node_modules/node-bourbon/assets/stylesheets', 'node_modules/node-neat/assets/stylesheets' ] }, filesConfig: [ { name: 'sgAppTest', files: [ 'demo/testDirective.js' ], template: 'demo/testDirective.html' } ] })) .pipe(gulp.dest(outputPath)); }); gulp.task('static', function() { gulp.src(['lib/demo/**']) .pipe(gulp.dest(outputPath + '/demo')); }); gulp.task('watch', ['styleguide'], function() { // Start watching changes and update styleguide whenever changes are detected gulp.watch(source, ['styleguide']); });
var gulp = require('gulp'), styleguide = require('./lib/styleguide'), source = 'lib/app/**/*.scss', ouputPath = 'demo-output'; gulp.task('styleguide', ['static'], function() { return gulp.src(source) .pipe(styleguide({ title: 'SC5 Styleguide', server: true, rootPath: ouputPath, overviewPath: 'README.md', styleVariables: 'lib/app/sass/_styleguide_variables.scss', sass: { src: 'lib/app/sass/app.scss', includePaths: [ 'node_modules/node-bourbon/assets/stylesheets', 'node_modules/node-neat/assets/stylesheets' ] }, filesConfig: [ { name: 'sgAppTest', files: [ 'demo/testDirective.js' ], template: 'demo/testDirective.html' } ] })) .pipe(gulp.dest(ouputPath)); }); gulp.task('static', function() { gulp.src(['lib/demo/**']) .pipe(gulp.dest(ouputPath + '/demo')); }); gulp.task('watch', ['styleguide'], function() { // Start watching changes and update styleguide whenever changes are detected gulp.watch(source, ['styleguide']); });
Fix a remaining reference to 'swingtime' in a comment
#!/usr/bin/env python import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit(0) with open('README.rst', 'r') as f: long_description = f.read() # Dynamically calculate the version based on fullcalendar.VERSION. VERSION = __import__('fullcalendar').get_version() setup( name='mezzanine-fullcalendar', version=VERSION, url='https://github.com/jonge-democraten/mezzanine-fullcalendar', author_email='[email protected]', description='A Mezzanine calendaring application using the fullcalendar.io ' 'widget.', long_description=long_description, author='David A Krauth, Jonge Democraten', platforms=['any'], license='MIT License', classifiers=( 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ), packages=[ 'fullcalendar', 'fullcalendar.migrations', 'fullcalendar.templatetags' ], install_requires=['python-dateutil', 'django>=1.6', 'mezzanine>=3.1'] )
#!/usr/bin/env python import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit(0) with open('README.rst', 'r') as f: long_description = f.read() # Dynamically calculate the version based on swingtime.VERSION. VERSION = __import__('fullcalendar').get_version() setup( name='mezzanine-fullcalendar', version=VERSION, url='https://github.com/jonge-democraten/mezzanine-fullcalendar', author_email='[email protected]', description='A Mezzanine calendaring application using the fullcalendar.io ' 'widget.', long_description=long_description, author='David A Krauth, Jonge Democraten', platforms=['any'], license='MIT License', classifiers=( 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', ), packages=[ 'fullcalendar', 'fullcalendar.migrations', 'fullcalendar.templatetags' ], install_requires=['python-dateutil', 'django>=1.6', 'mezzanine>=3.1'] )
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) name = org.name display_name = data.get('display_name', name) contact_name = data.get('contact_name', None) contact_email = data.get('email', None) if contact_email is None: contact_email = data.get('contact_email', None) contact_phone = data.get('phone', None) if contact_phone is None: contact_phone = data.get('contact_phone', None) migrated_org = Organization.objects.create( name=name, display_name=display_name, contact_name=contact_name, contact_email=contact_email, contact_phone=contact_phone ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group)
import json from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from api_manager.models import GroupProfile, Organization class Command(BaseCommand): """ Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model """ def handle(self, *args, **options): org_groups = GroupProfile.objects.filter(group_type='organization') for org in org_groups: data = json.loads(org.data) migrated_org = Organization.objects.create( name=data['name'], display_name=data['display_name'], contact_name=data['contact_name'], contact_email=data['contact_email'], contact_phone=data['contact_phone'] ) group = Group.objects.get(groupprofile=org.id) users = group.user_set.all() for user in users: migrated_org.users.add(user) linked_groups = group.grouprelationship.get_linked_group_relationships() for linked_group in linked_groups: if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component actual_group = Group.objects.get(id=linked_group.to_group_relationship_id) migrated_org.groups.add(actual_group)
Use hdurl prop from NASA API response `hd` param appears to be obsolete, however there is an hdurl prop in the response
const { nasaApiKey } = require('./nasa-api-key'); exports.decorateConfig = (config) => { return Object.assign({}, config, { backgroundColor: 'transparent' });; } exports.decorateHyper = (Hyper, { React }) => { return class extends React.Component { constructor (props, context) { super(props, context); this._fetchImage = this._fetchImage.bind(this); this._fetchImage(); } _fetchImage () { const potdImageUrl= `https://api.nasa.gov/planetary/apod?api_key=${nasaApiKey}`; fetch(potdImageUrl).then((response) => { response.json().then((data) => { this.setState({image: data.hdurl || data.url}); }); }); } render () { let css = `${config.css || ''} .hyper_main { background-color: #000; }`; if (this.state && this.state.image) { css = `${config.css || ''} .hyper_main { background-image: url(${this.state.image}); background-size: cover; background-color: #000; }`; } return React.createElement(Hyper, Object.assign({}, this.props, { customCSS: css })); } } };
const { nasaApiKey } = require('./nasa-api-key'); exports.decorateConfig = (config) => { return Object.assign({}, config, { backgroundColor: 'transparent' });; } exports.decorateHyper = (Hyper, { React }) => { return class extends React.Component { constructor (props, context) { super(props, context); this._fetchImage = this._fetchImage.bind(this); this._fetchImage(); } _fetchImage () { const potdImageUrl= `https://api.nasa.gov/planetary/apod?api_key=${nasaApiKey}&hd=true`; fetch(potdImageUrl).then((response) => { response.json().then((data) => { this.setState({image: data.url}); }); }); } render () { let css = `${config.css || ''} .hyper_main { background-color: #000; }`; if (this.state && this.state.image) { css = `${config.css || ''} .hyper_main { background-image: url(${this.state.image}); background-size: cover; background-color: #000; }`; } return React.createElement(Hyper, Object.assign({}, this.props, { customCSS: css })); } } };
Add badge to Model Collector
<?php namespace Barryvdh\Debugbar\DataCollector; use DebugBar\DataCollector\DataCollector; use DebugBar\DataCollector\DataCollectorInterface; use DebugBar\DataCollector\Renderable; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Support\Str; /** * Collector for Models. */ class ModelsCollector extends DataCollector implements DataCollectorInterface, Renderable { public $models = []; public $count = 0; /** * @param Dispatcher $events */ public function __construct(Dispatcher $events) { $events->listen('eloquent.*', function ($event, $models) { if (Str::contains($event, 'eloquent.retrieved')) { foreach (array_filter($models) as $model) { $class = get_class($model); $this->models[$class] = ($this->models[$class] ?? 0) + 1; $this->count++; } } }); } public function collect() { ksort($this->models, SORT_NUMERIC); return ['data' => array_reverse($this->models), 'count' => $this->count]; } /** * {@inheritDoc} */ public function getName() { return 'models'; } /** * {@inheritDoc} */ public function getWidgets() { return [ "models" => [ "icon" => "cubes", "widget" => "PhpDebugBar.Widgets.HtmlVariableListWidget", "map" => "models.data", "default" => "{}" ], 'models:badge' => [ 'map' => 'models.count', 'default' => 0 ] ]; } }
<?php namespace Barryvdh\Debugbar\DataCollector; use DebugBar\DataCollector\DataCollector; use DebugBar\DataCollector\DataCollectorInterface; use DebugBar\DataCollector\Renderable; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Support\Str; /** * Collector for Models. */ class ModelsCollector extends DataCollector implements DataCollectorInterface, Renderable { public $models = []; /** * @param Dispatcher $events */ public function __construct(Dispatcher $events) { $events->listen('eloquent.*', function ($event, $models) { if (Str::contains($event, 'eloquent.retrieved')) { foreach (array_filter($models) as $model) { $class = get_class($model); $this->models[$class] = ($this->models[$class] ?? 0) + 1; } } }); } public function collect() { ksort($this->models, SORT_NUMERIC); return array_reverse($this->models); } /** * {@inheritDoc} */ public function getName() { return 'models'; } /** * {@inheritDoc} */ public function getWidgets() { return [ "models" => [ "icon" => "cubes", "widget" => "PhpDebugBar.Widgets.HtmlVariableListWidget", "map" => "models", "default" => "{}" ] ]; } }
Add new line to bottom of file
if (Meteor.isServer) { Meteor.methods({ // send user an email when they get a notifcation createNotification: function ( giblet, url, notificationKeys ) { Notifications.insert({ createdAt: new Date(), owner: giblet.owner, gibletID: giblet._id, keywords: notificationKeys, url: url }); if (giblet.email) { Meteor.call('sendEmail', giblet, url, notificationKeys); } if (giblet.SMS) { //Meteor.call('sendSMS', giblet, url, notificationKeys); } }, sendEmail: function( giblet, url, notificationKeys ) { var user = Meteor.users.findOne({_id: giblet.owner}); var subject = 'Gobbler alert: Found keywords from ' + giblet.taskname; var text = 'Found keywords ' + notificationKeys.join(', ') + ' at ' + url; var email; if (user.services.facebook) { email = user.services.facebook.email; } if (user.services.google) { email = user.services.google.email; } if (user.chosenEmail) { email = user.chosenEmail; } Email.send({ to: email, from: '[email protected]', subject: subject, text: text }); } }); }
if (Meteor.isServer) { Meteor.methods({ // send user an email when they get a notifcation createNotification: function ( giblet, url, notificationKeys ) { Notifications.insert({ createdAt: new Date(), owner: giblet.owner, gibletID: giblet._id, keywords: notificationKeys, url: url }); if (giblet.email) { Meteor.call('sendEmail', giblet, url, notificationKeys); } if (giblet.SMS) { //Meteor.call('sendSMS', giblet, url, notificationKeys); } }, sendEmail: function( giblet, url, notificationKeys ) { var user = Meteor.users.findOne({_id: giblet.owner}); var subject = 'Gobbler alert: Found keywords from ' + giblet.taskname; var text = 'Found keywords ' + notificationKeys.join(', ') + ' at ' + url; var email; if (user.services.facebook) { email = user.services.facebook.email; } if (user.services.google) { email = user.services.google.email; } if (user.chosenEmail) { email = user.chosenEmail; } Email.send({ to: email, from: '[email protected]', subject: subject, text: text }); } }); }
Remove unused class that caused the error
<?php /* * This file is part of the Doctrine\OrientDB package. * * (c) Alessandro Nadalin <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Class Updates * * @package Doctrine\OrientDB * @subpackage Formatter * @author Alessandro Nadalin <[email protected]> */ namespace Doctrine\OrientDB\Query\Formatter\Query; use Doctrine\OrientDB\Query\Formatter\Query; class Updates extends Query implements TokenInterface { public static function format(array $values) { $string = ""; foreach ($values as $key => $value) { if ($key = self::stripNonSQLCharacters($key)) { if ($value === null) { $value = 'NULL'; } else if (is_int($value) || is_float($value)) { // Preserve content of $value as is } else if (is_bool($value)) { $value = $value ? 'TRUE' : 'FALSE'; } elseif(is_array($value)) { $value = '[' . implode(',', $value) . ']'; } else { $value = '"' . addslashes($value) . '"'; } $string .= " $key = $value,"; } } return substr($string, 0, strlen($string) - 1); } }
<?php /* * This file is part of the Doctrine\OrientDB package. * * (c) Alessandro Nadalin <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Class Updates * * @package Doctrine\OrientDB * @subpackage Formatter * @author Alessandro Nadalin <[email protected]> */ namespace Doctrine\OrientDB\Query\Formatter\Query; use Doctrine\OrientDB\Query\Formatter\Query; use Doctrine\OrientDB\Query\Formatter\String; class Updates extends Query implements TokenInterface { public static function format(array $values) { $string = ""; foreach ($values as $key => $value) { if ($key = self::stripNonSQLCharacters($key)) { if ($value === null) { $value = 'NULL'; } else if (is_int($value) || is_float($value)) { // Preserve content of $value as is } else if (is_bool($value)) { $value = $value ? 'TRUE' : 'FALSE'; } elseif(is_array($value)) { $value = '[' . implode(',', $value) . ']'; } else { $value = '"' . addslashes($value) . '"'; } $string .= " $key = $value,"; } } return substr($string, 0, strlen($string) - 1); } }
Make plain repl work again.
import sys import getopt from ctl import HavenCtl def print_version(): import pkg_resources # part of setuptools version = pkg_resources.require("havenctl")[0].version print(version) def print_usage(): print """ Usage: havenctl [-a <remote_address> | --address=<remote_address>] [-p <remote_port> | --port=<remote_port>] [-hv] cmd """ def execute_from_command_line(): address = None port = 7854 try: opts, args = getopt.getopt(sys.argv[1:], "a:p:hv", \ ["address=", "port=", "version", "help"]) except getopt.GetoptError, err: print str(err) usage() sys.exit(2) for o, a in opts: if o in ("-h", "--help"): print_usage() sys.exit() elif o in ("-v", "--version"): print_version() sys.exit() elif o in ("-a", "--address"): address = a elif o in ("-p", "--port"): port = a else: usage() assert False, "unhandled option" sys.exit(2) remaining = " ".join(args) handle_user_args(address, port, remaining) def handle_user_args(address, port, cmd): repl = HavenCtl() if(address): repl.onecmd("connect " + str(address) + " " + str(port)) if(cmd): repl.onecmd(cmd) else: repl.cmdloop()
import sys import getopt from ctl import HavenCtl def print_version(): import pkg_resources # part of setuptools version = pkg_resources.require("havenctl")[0].version print(version) def print_usage(): print """ Usage: havenctl [-a <remote_address> | --address=<remote_address>] [-p <remote_port> | --port=<remote_port>] [-hv] cmd """ def execute_from_command_line(): try: opts, args = getopt.getopt(sys.argv[1:], "a:p:hv", \ ["address=", "port=", "version", "help"]) except getopt.GetoptError, err: print str(err) usage() sys.exit(2) for o, a in opts: if o in ("-h", "--help"): print_usage() sys.exit() elif o in ("-v", "--version"): print_version() sys.exit() elif o in ("-a", "--address"): address = a elif o in ("-p", "--port"): port = a else: usage() assert False, "unhandled option" sys.exit(2) handle_user_args(address, port, " ".join(args)) def handle_user_args(address, port, cmd): repl = HavenCtl() if(address): repl.onecmd("connect " + str(address) + " " + str(port)) if(cmd): repl.onecmd(cmd) else: repl.cmdloop()
Support Django 1.7 in test runner.
#!/usr/bin/env python from os.path import dirname, abspath import sys import django from django.conf import settings if not settings.configured: settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'localeurl.tests', 'django.contrib.sites', # for sitemap test 'django.contrib.sessions', # for USE_SESSION ), ROOT_URLCONF='localeurl.tests.test_urls', SITE_ID=1, ) if django.VERSION >= (1, 2): settings_dict["DATABASES"] = { "default": { "ENGINE": "django.db.backends.sqlite3" }} else: settings_dict["DATABASE_ENGINE"] = "sqlite3" settings.configure(**settings_dict) if django.VERSION >= (1, 7): django.setup() def runtests(*test_args): if not test_args: test_args = ['tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) try: from django.test.simple import DjangoTestSuiteRunner def run_tests(test_args, verbosity, interactive): runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive, failfast=False) return runner.run_tests(test_args) except ImportError: # for Django versions that don't have DjangoTestSuiteRunner from django.test.simple import run_tests failures = run_tests( test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'localeurl.tests', 'django.contrib.sites', # for sitemap test 'django.contrib.sessions', # for USE_SESSION ), ROOT_URLCONF='localeurl.tests.test_urls', SITE_ID=1, ) if VERSION >= (1, 2): settings_dict["DATABASES"] = { "default": { "ENGINE": "django.db.backends.sqlite3" }} else: settings_dict["DATABASE_ENGINE"] = "sqlite3" settings.configure(**settings_dict) def runtests(*test_args): if not test_args: test_args = ['tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) try: from django.test.simple import DjangoTestSuiteRunner def run_tests(test_args, verbosity, interactive): runner = DjangoTestSuiteRunner( verbosity=verbosity, interactive=interactive, failfast=False) return runner.run_tests(test_args) except ImportError: # for Django versions that don't have DjangoTestSuiteRunner from django.test.simple import run_tests failures = run_tests( test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
Fix back links in intro
module.exports = { '/': { backLink: '/../priority_service_170315/filter/uncancelled', next: '/what-you-need' }, '/before-you-continue-overseas': { backLink: '/../priority_service_170315/overseas/uncancelled', next: '/what-you-need-overseas' }, '/what-you-need': { backLink: './', next: '/you-need-a-photo' }, '/what-you-need-overseas': { backLink: '/../priority_service_170315/overseas/try-service', next: '/you-need-a-photo-overseas' }, '/you-need-a-photo': { backLink: '../book-appointment/confirmation-scenario-1', next: '/choose-photo-method' }, '/you-need-a-photo-overseas': { backLink: './what-you-need-overseas', next: '/choose-photo-method' }, '/you-need-a-photo-v3': { backLink: './what-you-need', next: '/choose-photo-method' }, '/choose-photo-method': { fields: ['choose-photo'], next: '/../upload' }, '/choose-photo-method-overseas': { fields: ['choose-photo-overseas'], next: '/../upload' } };
module.exports = { '/': { backLink: '/../priority_service_170301/filter/uncancelled', next: '/what-you-need' }, '/before-you-continue-overseas': { backLink: '/../priority_service_170301/overseas/uncancelled', next: '/what-you-need-overseas' }, '/what-you-need': { backLink: './', next: '/you-need-a-photo' }, '/what-you-need-overseas': { backLink: '/../priority_service_170301/overseas/try-service', next: '/you-need-a-photo-overseas' }, '/you-need-a-photo': { backLink: '../book-appointment/confirmation-scenario-1', next: '/choose-photo-method' }, '/you-need-a-photo-overseas': { backLink: './what-you-need-overseas', next: '/choose-photo-method' }, '/you-need-a-photo-v3': { backLink: './what-you-need', next: '/choose-photo-method' }, '/choose-photo-method': { fields: ['choose-photo'], next: '/../upload' }, '/choose-photo-method-overseas': { fields: ['choose-photo-overseas'], next: '/../upload' } };
Update requests to fix security issue
from setuptools import setup, find_packages from pypandoc import convert def convert_markdown_to_rst(file): return convert(file, 'rst') setup(name='gitlabform', version='1.0.2', description='Easy configuration as code tool for GitLab using config in plain YAML', long_description=convert_markdown_to_rst('README.md'), url='https://github.com/egnyte/gitlabform', author='Egnyte', keywords=['gitlab', 'configuration-as-code'], classifiers=[ "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Development Status :: 4 - Beta", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Version Control :: Git", ], packages=find_packages(), install_requires=[ 'requests>=2.20.0', 'pyyaml==3.13', ], tests_requires=[ 'pytest', ], setup_requires=[ 'pypandoc', ], scripts=[ 'bin/gitlabform', ], )
from setuptools import setup, find_packages from pypandoc import convert def convert_markdown_to_rst(file): return convert(file, 'rst') setup(name='gitlabform', version='1.0.1', description='Easy configuration as code tool for GitLab using config in plain YAML', long_description=convert_markdown_to_rst('README.md'), url='https://github.com/egnyte/gitlabform', author='Egnyte', keywords=['gitlab', 'configuration-as-code'], classifiers=[ "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Development Status :: 4 - Beta", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Version Control :: Git", ], packages=find_packages(), install_requires=[ 'requests==2.18.4', 'pyyaml==3.13', ], tests_requires=[ 'pytest', ], setup_requires=[ 'pypandoc', ], scripts=[ 'bin/gitlabform', ], )
Add useHistoryState-plugin to plugins. (not only create)
Ext.namespace('Kwc.List.Switch'); Kwc.List.Switch.Component = Ext.extend(Kwf.EyeCandy.List, { //transition: {}, showArrows: true, defaultState: 'normal', childSelector: '> div > .listSwitchItem', _init: function() { this.states = [ 'normal' ]; if (!this.plugins) this.plugins = []; this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveListener.LargeContentAjax({ largeContainerSelector: '.listSwitchLargeContent', transition: this.transition.type, transitionConfig: this.transition })); this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.Click({})); this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.DefaultActiveClass({})); if (this.showArrows) { this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.NextPreviousLinks({ })); } if (this.showPlayPause) { this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.PlayPauseLink({ autoPlay: this.autoPlay })); } if (this.useHistoryState) { this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.HistoryState({ })); } Kwc.List.Switch.Component.superclass._init.call(this); } });
Ext.namespace('Kwc.List.Switch'); Kwc.List.Switch.Component = Ext.extend(Kwf.EyeCandy.List, { //transition: {}, showArrows: true, defaultState: 'normal', childSelector: '> div > .listSwitchItem', _init: function() { this.states = [ 'normal' ]; if (!this.plugins) this.plugins = []; this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveListener.LargeContentAjax({ largeContainerSelector: '.listSwitchLargeContent', transition: this.transition.type, transitionConfig: this.transition })); this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.Click({})); this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.DefaultActiveClass({})); if (this.showArrows) { this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.NextPreviousLinks({ })); } if (this.showPlayPause) { this.plugins.push(new Kwf.EyeCandy.List.Plugins.ActiveChanger.PlayPauseLink({ autoPlay: this.autoPlay })); } if (this.useHistoryState) { new Kwf.EyeCandy.List.Plugins.ActiveChanger.HistoryState({ }); } Kwc.List.Switch.Component.superclass._init.call(this); } });
Use all of content in redirect from oauth callback
"""Main codrspace views""" from django.shortcuts import render, redirect from settings import GITHUB_CLIENT_ID import requests def index(request, slug=None, template_name="base.html"): return render(request, template_name) def edit(request, slug=None, template_name="edit.html"): """Edit Your Post""" return render(request, template_name, {}) def signin_start(request, slug=None, template_name="signin.html"): """Start of OAuth signin""" return redirect('https://github.com/login/oauth/authorize?client_id=%s' % ( GITHUB_CLIENT_ID)) def signin_callback(request, slug=None, template_name="base.html"): """Callback from Github OAuth""" code = request.GET['code'] resp = requests.post(url='https://github.com/login/oauth/access_token', params={ 'client_id': GITHUB_CLIENT_ID, 'client_secret': '2b40ac4251871e09441eb4147cbd5575be48bde9', 'code': code}) # FIXME: Handle error if resp.status_code != 200 or 'error' in resp.content: raise Exception('code: %u content: %s' % (resp.status_code, resp.content)) token = resp.content return redirect('http://www.codrspace.com/%s' % (token))
"""Main codrspace views""" from django.shortcuts import render, redirect from settings import GITHUB_CLIENT_ID import requests def index(request, slug=None, template_name="base.html"): return render(request, template_name) def edit(request, slug=None, template_name="edit.html"): """Edit Your Post""" return render(request, template_name, {}) def signin_start(request, slug=None, template_name="signin.html"): """Start of OAuth signin""" return redirect('https://github.com/login/oauth/authorize?client_id=%s' % ( GITHUB_CLIENT_ID)) def signin_callback(request, slug=None, template_name="base.html"): """Callback from Github OAuth""" code = request.GET['code'] resp = requests.post(url='https://github.com/login/oauth/access_token', params={ 'client_id': GITHUB_CLIENT_ID, 'client_secret': '2b40ac4251871e09441eb4147cbd5575be48bde9', 'code': code}) # FIXME: Handle error if resp.status_code != 200 or 'error' in resp.content: raise Exception('code: %u content: %s' % (resp.status_code, resp.content)) token = resp.content['access_token'] return redirect('http://www.codrspace.com/%s' % (token))
MongoDB: Fix pagination for last page
var utils = require('../../utils'); module.exports = function(mongoose) { /** * Paginates and executes a query */ mongoose.Query.prototype.paginate = function paginate(page, limit, callback) { // The number of pages to show page = parseInt(page, 10) || 1; limit = parseInt(limit, 10) || 20; if(page < 1) page = 1; if(limit < 1) limit = 1; var skip = (page * limit) - limit; var query = this.skip(skip).limit(limit); if(!callback) return query; query.exec(function(fErr, result) { if(fErr) return callback(fErr, null, null); query.model.count(query._conditions).exec(function(cErr, count) { if(cErr) return callback(cErr, null, null); var totalPages = Math.ceil(count / limit); var info = { enabled: count > limit, items: { total: count, remaining: limit < count ? count - limit : 0, limit: limit }, pages: { current: page, total: totalPages || 1, prev: page > 1 && page <= totalPages ? page - 1 : null, next: page < totalPages ? page + 1 : null, first: 1, last: totalPages || 1 } }; return callback(null, result, info); }); }); }; };
var utils = require('../../utils'); module.exports = function(mongoose) { /** * Paginates and executes a query */ mongoose.Query.prototype.paginate = function paginate(page, limit, callback) { // The number of pages to show page = parseInt(page, 10) || 1; limit = parseInt(limit, 10) || 20; if(page < 1) page = 1; if(limit < 1) limit = 1; var skip = (page * limit) - limit; var query = this.skip(skip).limit(limit); if(!callback) return query; query.exec(function(fErr, result) { if(fErr) return callback(fErr, null, null); query.model.count(query._conditions).exec(function(cErr, count) { if(cErr) return callback(cErr, null, null); var totalPages = Math.ceil(count / limit); var info = { enabled: count > limit, items: { total: count, remaining: limit < count ? count - limit : 0, limit: limit }, pages: { current: page, total: totalPages || 1, prev: page > 1 && page <= totalPages ? page - 1 : null, next: page < totalPages ? page + 1 : null, first: 1, last: totalPages } }; return callback(null, result, info); }); }); }; };
Update requirements. Add bat file
from distutils.core import setup setup( name='lcinvestor', version=open('lcinvestor/VERSION').read(), author='Jeremy Gillick', author_email='[email protected]', packages=['lcinvestor', 'lcinvestor.tests', 'lcinvestor.settings'], package_data={ 'lcinvestor': ['VERSION'], 'lcinvestor.settings': ['settings.yaml'] }, scripts=['bin/lcinvestor', 'bin/lcinvestor.bat'], url='https://github.com/jgillick/LendingClubAutoInvestor', license=open('LICENSE.txt').read(), description='A simple tool that will watch your LendingClub account and automatically invest cash as it becomes available.', long_description=open('README.rst').read(), install_requires=[ "lendingclub >= 0.1.3", # "python-daemon >= 1.6", "argparse >= 1.2.1", "pyyaml >= 3.09", "pause >= 0.1.2" ], platforms='osx, posix, linux, windows', classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Environment :: Console', 'Environment :: No Input/Output (Daemon)', 'Topic :: Office/Business :: Financial' ], keywords='lendingclub investing daemon' )
from distutils.core import setup setup( name='lcinvestor', version=open('lcinvestor/VERSION').read(), author='Jeremy Gillick', author_email='[email protected]', packages=['lcinvestor', 'lcinvestor.tests', 'lcinvestor.settings'], package_data={ 'lcinvestor': ['VERSION'], 'lcinvestor.settings': ['settings.yaml'] }, scripts=['bin/lcinvestor'], url='https://github.com/jgillick/LendingClubAutoInvestor', license=open('LICENSE.txt').read(), description='A simple tool that will watch your LendingClub account and automatically invest cash as it becomes available.', long_description=open('README.rst').read(), install_requires=[ "lendingclub >= 0.1.2", # "python-daemon >= 1.6", "argparse >= 1.2.1", "pybars >= 0.0.4", "pyyaml >= 3.09", "pause >= 0.1.2" ], platforms='osx, posix, linux, windows', classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Environment :: Console', 'Environment :: No Input/Output (Daemon)', 'Topic :: Office/Business :: Financial' ], keywords='lendingclub investing daemon' )
Clear undo buffer when terminal cleared.
import threading import wx from styled_text_ctrl import StyledTextCtrl class ThreadOutputCtrl(StyledTextCtrl): def __init__(self, parent, env, auto_scroll=False): StyledTextCtrl.__init__(self, parent, env) self.auto_scroll = auto_scroll self.__lock = threading.Lock() self.__queue = [] self.__timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) def __OnTimer(self, evt): self.flush() def flush(self): with self.__lock: queue, self.__queue = self.__queue, [] lines = "".join(queue) if lines: with self.ModifyReadOnly(): self.AppendText(lines) self.EmptyUndoBuffer() if self.auto_scroll: self.ScrollToLine(self.GetLineCount() - 1) def start(self, interval=100): self.SetReadOnly(True) self.__timer.Start(interval) def stop(self): self.__timer.Stop() self.flush() self.SetReadOnly(False) def write(self, s): with self.__lock: self.__queue.append(s) def ClearAll(self): with self.ModifyReadOnly(): StyledTextCtrl.ClearAll(self) self.EmptyUndoBuffer()
import threading import wx from styled_text_ctrl import StyledTextCtrl class ThreadOutputCtrl(StyledTextCtrl): def __init__(self, parent, env, auto_scroll=False): StyledTextCtrl.__init__(self, parent, env) self.auto_scroll = auto_scroll self.__lock = threading.Lock() self.__queue = [] self.__timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) def __OnTimer(self, evt): self.flush() def flush(self): with self.__lock: queue, self.__queue = self.__queue, [] lines = "".join(queue) if lines: with self.ModifyReadOnly(): self.AppendText(lines) self.EmptyUndoBuffer() if self.auto_scroll: self.ScrollToLine(self.GetLineCount() - 1) def start(self, interval=100): self.SetReadOnly(True) self.__timer.Start(interval) def stop(self): self.__timer.Stop() self.flush() self.SetReadOnly(False) def write(self, s): with self.__lock: self.__queue.append(s) def ClearAll(self): with self.ModifyReadOnly(): StyledTextCtrl.ClearAll(self)
Change an option for a grunt task
module.exports = function(grunt) { // Load tasks grunt.loadNpmTasks('grunt-nodemon'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-concurrent'); grunt.loadNpmTasks('grunt-browserify'); grunt.initConfig({ less: { development: { options: { paths: ["assets/css"] }, files: { "client/css/app.css": "client/css/app.less" } } }, browserify: { development: { files: { 'client/js/game.bundle.js': ['game/game.js'] } } }, watch: { styles: { // Which files to watch (all .less files recursively in the less directory) files: ['client/css/**/*.less'], tasks: ['less'], options: { spawn: false } }, scripts: { files: ['game/**/*.js'], tasks: ['browserify'], options: { spawn: false } } }, concurrent: { dev: ['nodemon:dev', 'watch'], options: { logConcurrentOutput: true } }, nodemon: { dev: { script: './server/main.js' }, options: { nodeArgs: ['--debug'] } }, clean: ["node_modules", "client/components"] }); grunt.registerTask('dev', ['less', 'browserify', 'concurrent:dev']); };
module.exports = function(grunt) { // Load tasks grunt.loadNpmTasks('grunt-nodemon'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-concurrent'); grunt.loadNpmTasks('grunt-browserify'); grunt.initConfig({ less: { development: { options: { paths: ["assets/css"] }, files: { "client/css/app.css": "client/css/app.less" } } }, browserify: { development: { files: { 'client/js/game.bundle.js': ['game/game.js'] } } }, watch: { styles: { // Which files to watch (all .less files recursively in the less directory) files: ['client/css/**/*.less'], tasks: ['less'], options: { nospawn: true } }, scripts: { files: ['game/**/*.js'], tasks: ['browserify'] } }, concurrent: { dev: ['nodemon:dev', 'watch'], options: { logConcurrentOutput: true } }, nodemon: { dev: { script: './server/main.js' }, options: { nodeArgs: ['--debug'] } }, clean: ["node_modules", "client/components"] }); grunt.registerTask('dev', ['less', 'browserify', 'concurrent:dev']); };
Use just "jsonDecode" instead of "decode"
<?php class CM_Clockwork_Storage_FileSystem extends CM_Clockwork_Storage_Abstract implements CM_Service_ManagerAwareInterface { use CM_Service_ManagerAwareTrait; protected function _load() { $data = []; $file = $this->_getStorageFile(); if ($file->exists()) { $values = CM_Params::jsonDecode($file->read(), true); $data = \Functional\map($values, function ($timeStamp) { return new DateTime('@' . $timeStamp); }); } return $data; } protected function _save(array $data) { $values = \Functional\map($data, function (DateTime $dateTime) { return $dateTime->getTimestamp(); }); $content = CM_Params::jsonEncode($values, true); $file = $this->_getStorageFile(); if (!$file->exists()) { $file->ensureParentDirectory(); } $file->write($content); } /** * @return CM_File */ private function _getStorageFile() { $filename = md5($this->_context); return new CM_File("clockwork/{$filename}.json", $this->getServiceManager()->getFilesystems()->getData()); } }
<?php class CM_Clockwork_Storage_FileSystem extends CM_Clockwork_Storage_Abstract implements CM_Service_ManagerAwareInterface { use CM_Service_ManagerAwareTrait; protected function _load() { $data = []; $file = $this->_getStorageFile(); if ($file->exists()) { $values = CM_Params::decode($file->read(), true); $data = \Functional\map($values, function ($timeStamp) { return new DateTime('@' . $timeStamp); }); } return $data; } protected function _save(array $data) { $values = \Functional\map($data, function (DateTime $dateTime) { return $dateTime->getTimestamp(); }); $content = CM_Params::jsonEncode($values, true); $file = $this->_getStorageFile(); if (!$file->exists()) { $file->ensureParentDirectory(); } $file->write($content); } /** * @return CM_File */ private function _getStorageFile() { $filename = md5($this->_context); return new CM_File("clockwork/{$filename}.json", $this->getServiceManager()->getFilesystems()->getData()); } }
Remove empty properties from object
import path from 'path'; import HtmlWebpackPlugin from 'webpack-html-plugin'; import webpack from 'webpack'; /** removes empty items from array */ const array = (target) => target.filter((item) => item); /** removes empty properties from object */ const object = (target) => Object.keys(target).filter((key) => target[key]).reduce((result, key) => Object.assign({[key]: target[key]}, result), {}); export default ({dev, prod}) => ({ entry: array([ dev && 'react-hot-loader/patch', 'babel-polyfill', './src/', ]), output: { path: path.resolve(__dirname, 'dist'), publicPath: '/', filename: 'bundle.js', }, plugins: array([ new HtmlWebpackPlugin({ template: 'src/index.html', inject: true, }), dev && new webpack.NoErrorsPlugin(), ]), module: { rules: [ { test: /\.js$/, use: 'babel-loader', exclude: '/node_modules/', options: { presets: ['es2015', 'react'], modules: false, }, }, { test: /\.less$/, use: [ {loader: 'style-loader'}, {loader: 'css-loader'}, {loader: 'less-loader'}, ], }, ], }, });
import path from 'path'; import HtmlWebpackPlugin from 'webpack-html-plugin'; import webpack from 'webpack'; const array = (target) => target.filter((item) => item); export default ({dev, prod}) => ({ entry: array([ dev && 'react-hot-loader/patch', 'babel-polyfill', './src/', ]), output: { path: path.resolve(__dirname, 'dist'), publicPath: '/', filename: 'bundle.js', }, plugins: array([ new HtmlWebpackPlugin({ template: 'src/index.html', inject: true, }), dev && new webpack.NoErrorsPlugin(), ]), module: { rules: [ { test: /\.js$/, use: 'babel-loader', exclude: '/node_modules/', options: { presets: ['es2015', 'react'], modules: false, }, }, { test: /\.less$/, use: [ {loader: 'style-loader'}, {loader: 'css-loader'}, {loader: 'less-loader'}, ], }, ], }, });
Add GitLab CI commit env variable
(function (logger, exec, Promise) { 'use strict'; module.exports = { getCommitId: function (commitId) { return new Promise(function (resolve, reject) { if (commitId) { logger.debug('Provided Commit Id: ' + commitId); return resolve(commitId); } var gitCommit = process.env.CODACY_GIT_COMMIT || process.env.TRAVIS_COMMIT || process.env.DRONE_COMMIT || process.env.GIT_COMMIT || process.env.CIRCLE_SHA1 || process.env.CI_COMMIT_ID || process.env.WERCKER_GIT_COMMIT || process.env.BUILDKITE_COMMIT || process.env.CI_COMMIT_SHA; if (gitCommit) { logger.debug('Received Commit Id: ' + gitCommit); return resolve(gitCommit); } exec('git rev-parse HEAD', function (err, commitId) { if (err) { return reject(err); } commitId = commitId.trim(); logger.debug('Got Commit Id: ' + commitId); resolve(commitId); }); }); } }; }(require('./logger')(), require('child_process').exec, require('bluebird')));
(function (logger, exec, Promise) { 'use strict'; module.exports = { getCommitId: function (commitId) { return new Promise(function (resolve, reject) { if (commitId) { logger.debug('Provided Commit Id: ' + commitId); return resolve(commitId); } var gitCommit = process.env.CODACY_GIT_COMMIT || process.env.TRAVIS_COMMIT || process.env.DRONE_COMMIT || process.env.GIT_COMMIT || process.env.CIRCLE_SHA1 || process.env.CI_COMMIT_ID || process.env.WERCKER_GIT_COMMIT || process.env.BUILDKITE_COMMIT; if (gitCommit) { logger.debug('Received Commit Id: ' + gitCommit); return resolve(gitCommit); } exec('git rev-parse HEAD', function (err, commitId) { if (err) { return reject(err); } commitId = commitId.trim(); logger.debug('Got Commit Id: ' + commitId); resolve(commitId); }); }); } }; }(require('./logger')(), require('child_process').exec, require('bluebird')));
Fix interaction test: use newer interaction. - Does tvtag remove older interactions?
package com.uwetrottmann.getglue.services; import com.uwetrottmann.getglue.BaseTestCase; import com.uwetrottmann.getglue.entities.GetGlueInteraction; import com.uwetrottmann.getglue.entities.GetGlueInteractionResource; import java.util.List; import static org.fest.assertions.api.Assertions.assertThat; public class InteractionServiceTest extends BaseTestCase { public static final String SAMPLE_INTERACTION = "getgluejava/2014-04-22T17:08:08Z"; public void test_get() { InteractionService service = getManager().interactionService(); GetGlueInteractionResource resource = service.get(SAMPLE_INTERACTION); assertThat(resource).isNotNull(); assertThat(resource.interaction).isNotNull(); assertThat(resource.interaction._object).isNotNull(); assertThat(resource.interaction._object.id).isEqualTo("tv_shows/how_i_met_your_mother"); assertThat(resource.interaction._object.title).isEqualTo("How I Met Your Mother"); assertThat(resource.interaction.comment).isEqualTo("Testing getglue-java."); } public void test_votes() { InteractionService service = getManager().interactionService(); List<GetGlueInteraction> resource = service.votes(SAMPLE_INTERACTION); assertThat(resource).isNotNull(); } public void test_replies() { InteractionService service = getManager().interactionService(); List<GetGlueInteraction> resource = service.replies(SAMPLE_INTERACTION); assertThat(resource).isNotNull(); } }
package com.uwetrottmann.getglue.services; import com.uwetrottmann.getglue.BaseTestCase; import com.uwetrottmann.getglue.entities.GetGlueInteraction; import com.uwetrottmann.getglue.entities.GetGlueInteractionResource; import java.util.List; import static org.fest.assertions.api.Assertions.assertThat; public class InteractionServiceTest extends BaseTestCase { public static final String SAMPLE_INTERACTION = "getgluejava/2013-10-24T18:30:38Z"; public void test_get() { InteractionService service = getManager().interactionService(); GetGlueInteractionResource resource = service.get(SAMPLE_INTERACTION); assertThat(resource).isNotNull(); assertThat(resource.interaction).isNotNull(); assertThat(resource.interaction._object).isNotNull(); assertThat(resource.interaction._object.id).isEqualTo("tv_shows/how_i_met_your_mother"); assertThat(resource.interaction._object.title).isEqualTo("How I Met Your Mother"); assertThat(resource.interaction.comment).isEqualTo("Testing getglue-java."); } public void test_votes() { InteractionService service = getManager().interactionService(); List<GetGlueInteraction> resource = service.votes(SAMPLE_INTERACTION); assertThat(resource).isNotNull(); } public void test_replies() { InteractionService service = getManager().interactionService(); List<GetGlueInteraction> resource = service.replies(SAMPLE_INTERACTION); assertThat(resource).isNotNull(); } }
Call function when options is a function
'use strict'; (function (root, factory) { if (typeof define === 'function' && define.amd) { define([ 'marionette', 'underscore', 'bootstrapValidator' ], factory); } else if (typeof exports === 'object') { module.exports = factory( require('backbone.marionette'), require('underscore'), require('bootstrapValidator') ); } })(this, function (Marionette, _, BootstrapValidator) { return Marionette.Behavior.extend({ onShow: function () { _(this.options.targets).forEach(function (target) { var globalOptions = this.options.options; if (_.isFunction(globalOptions)) { globalOptions = globalOptions.call(this); } if (_.isString(target)) { if (target === '@') { this.$el.bootstrapValidator(globalOptions); } else { var selector = Marionette.normalizeUIString(target, Object.getPrototypeOf(this.view).ui); this.$(selector).bootstrapValidator(globalOptions); } } else { var localOptions = target.options; if (_.isFunction(localOptions)) { localOptions = localOptions.call(this); } var options = _.extend({}, globalOptions, localOptions); var selector = Marionette.normalizeUIString(target.selector, Object.getPrototypeOf(this.view).ui); this.$(selector).bootstrapValidator(options); } }, this); } }); });
'use strict'; (function(root, factory) { if (typeof define === 'function' && define.amd) { define([ 'marionette', 'underscore', 'bootstrapValidator' ], factory); } else if (typeof exports === 'object') { module.exports = factory( require('backbone.marionette'), require('underscore'), require('bootstrapValidator') ); } })(this, function(Marionette, _, BootstrapValidator) { return Marionette.Behavior.extend({ onShow: function() { _(this.options.targets).forEach(function(target) { var globalOptions = this.options.options; if(_.isString(target)) { if(target === '@') { this.$el.bootstrapValidator(globalOptions); } else { var selector = Marionette.normalizeUIString(target, Object.getPrototypeOf(this.view).ui); this.$(selector).bootstrapValidator(globalOptions); } } else { var localOptions = target.options; var options = _.extend({}, globalOptions, localOptions); var selector = Marionette.normalizeUIString(target.selector, Object.getPrototypeOf(this.view).ui); this.$(selector).bootstrapValidator(options); } }, this); } }); });
Revert "Activity was imported twice" This reverts commit a0600929774c1e90c7dc43043ff87b5ea84213b4.
import android import android.activity from os import unlink from jnius import autoclass, cast from plyer.facades import Camera from plyer.platforms.android import activity Intent = autoclass('android.content.Intent') PythonActivity = autoclass('org.renpy.android.PythonActivity') MediaStore = autoclass('android.provider.MediaStore') Uri = autoclass('android.net.Uri') class AndroidCamera(Camera): def _take_picture(self, on_complete, filename=None): assert(on_complete is not None) self.on_complete = on_complete self.filename = filename android.activity.unbind(on_activity_result=self._on_activity_result) android.activity.bind(on_activity_result=self._on_activity_result) intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) uri = Uri.parse('file://' + filename) parcelable = cast('android.os.Parcelable', uri) intent.putExtra(MediaStore.EXTRA_OUTPUT, parcelable) activity.startActivityForResult(intent, 0x123) def _on_activity_result(self, requestCode, resultCode, intent): if requestCode != 0x123: return android.activity.unbind(on_activity_result=self._on_activity_result) if self.on_complete(self.filename): self._unlink(self.filename) def _unlink(self, fn): try: unlink(fn) except: pass def instance(): return AndroidCamera()
from os import unlink from jnius import autoclass, cast from plyer.facades import Camera from plyer.platforms.android import activity Intent = autoclass('android.content.Intent') PythonActivity = autoclass('org.renpy.android.PythonActivity') MediaStore = autoclass('android.provider.MediaStore') Uri = autoclass('android.net.Uri') class AndroidCamera(Camera): def _take_picture(self, on_complete, filename=None): assert(on_complete is not None) self.on_complete = on_complete self.filename = filename activity.unbind(on_activity_result=self._on_activity_result) activity.bind(on_activity_result=self._on_activity_result) intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) uri = Uri.parse('file://' + filename) parcelable = cast('android.os.Parcelable', uri) intent.putExtra(MediaStore.EXTRA_OUTPUT, parcelable) activity.startActivityForResult(intent, 0x123) def _on_activity_result(self, requestCode, resultCode, intent): if requestCode != 0x123: return activity.unbind(on_activity_result=self._on_activity_result) if self.on_complete(self.filename): self._unlink(self.filename) def _unlink(self, fn): try: unlink(fn) except: pass def instance(): return AndroidCamera()
Fix problem with image not updating.
'use strict'; /** * @file * Delivers a component representing one single category in the autocomplete * parent autocomplete component. */ import React from 'react'; import {isArray, includes} from 'lodash'; import AutoCompleteRow from './AutoCompleteRow.component'; var AutoCompleteCategory = React.createClass({ displayName: 'AutoCompleteCategory', propTypes: { data: React.PropTypes.array, label: React.PropTypes.object }, getLabel(label) { return ( <div className='autocomplete--category--label-container' > <span className='autocomplete--category--label' >{label}</span> </div> ); }, render() { let data = this.props.data || []; if (!isArray(data)) { data = new Array(data); } const label = this.props.label || null; const labelToRender = (label) ? this.getLabel(label) : ''; const showImage = label && !includes(['Forfatter', 'Emne'], label.props.children); const rows = data.map((value) => { return ( <AutoCompleteRow href={value.href} image={value.image} imageComp={value.imageComp} key={value.text + value.href} showImage={showImage} text={value.text} /> ); }); return ( <div className='autocomplete--category-container' > {labelToRender} <div className='autocomplete--category--rows-container' > {rows} </div> </div> ); } }); export default AutoCompleteCategory;
'use strict'; /** * @file * Delivers a component representing one single category in the autocomplete * parent autocomplete component. */ import React from 'react'; import {isArray, includes} from 'lodash'; import AutoCompleteRow from './AutoCompleteRow.component'; var AutoCompleteCategory = React.createClass({ displayName: 'AutoCompleteCategory', propTypes: { data: React.PropTypes.array, label: React.PropTypes.object }, getLabel(label) { return ( <div className='autocomplete--category--label-container' > <span className='autocomplete--category--label' >{label}</span> </div> ); }, render() { let data = this.props.data || []; if (!isArray(data)) { data = new Array(data); } const label = this.props.label || null; const labelToRender = (label) ? this.getLabel(label) : ''; const showImage = label && !includes(['Forfatter', 'Emne'], label.props.children); const rows = data.map((value, key) => { return ( <AutoCompleteRow href={value.href} image={value.image} imageComp={value.imageComp} key={key} showImage={showImage} text={value.text} /> ); }); return ( <div className='autocomplete--category-container' > {labelToRender} <div className='autocomplete--category--rows-container' > {rows} </div> </div> ); } }); export default AutoCompleteCategory;
BB-562: Add possibility to inject code into forms and view templates - CR fixes
<?php namespace Oro\Bundle\UIBundle\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\Form\FormView; use Twig_Environment; class BeforeListRenderEvent extends Event { /** * @var \Twig_Environment */ protected $environment; /** * @var array */ protected $data; /** * @var FormView|null */ protected $formView; /** * @param \Twig_Environment $environment * @param array $data * @param FormView|null $formView */ public function __construct(Twig_Environment $environment, array $data, FormView $formView = null) { $this->formView = $formView; $this->data = $data; $this->environment = $environment; } /** * @return \Twig_Environment */ public function getEnvironment() { return $this->environment; } /** * @return FormView|null */ public function getFormView() { return $this->formView; } /** * @return array */ public function getData() { return $this->data; } /** * @param array $data * @return BeforeListRenderEvent */ public function setData(array $data) { $this->data = $data; return $this; } }
<?php namespace Oro\Bundle\UIBundle\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\Form\FormView; use Twig_Environment; class BeforeListRenderEvent extends Event { /** * @var \Twig_Environment */ protected $environment; /** * @var array */ protected $data; /** * @var FormView|null */ protected $formView; /** * @param \Twig_Environment $environment * @param array $data * @param FormView $formView */ public function __construct(Twig_Environment $environment, array $data, FormView $formView = null) { $this->formView = $formView; $this->data = $data; $this->environment = $environment; } /** * @return \Twig_Environment */ public function getEnvironment() { return $this->environment; } /** * @return FormView */ public function getFormView() { return $this->formView; } /** * @return array */ public function getData() { return $this->data; } /** * @param array $data * @return BeforeListRenderEvent */ public function setData(array $data) { $this->data = $data; return $this; } }
Adjust to ts2dart change of filename handling.
var chalk = require('chalk'); var gutil = require('gulp-util'); var spawn = require('gulp-spawn'); var through = require('through2'); var ts2dart = require('ts2dart'); var which = require('which'); exports.transpile = function() { var hadErrors = false; return through.obj( function(file, enc, done) { try { var transpiler = new ts2dart.Transpiler(/* failFast */ false, /* generateLibrary */ true); var src = transpiler.translateFile(file.path, file.relative); file.contents = new Buffer(src); file.path = file.path.replace(/.[tj]s$/, '.dart'); done(null, file); } catch (e) { hadErrors = true; if (e.name === 'TS2DartError') { // Sort of expected, log only the message. gutil.log(chalk.red(e.message)); } else { // Log the entire stack trace. gutil.log(chalk.red(e.stack)); } done(null, null); } }, function finished(done) { if (hadErrors) { gutil.log(chalk.red('ts2dart transpilation failed.')); throw new Error('ts2dart transpilation failed.'); } else { gutil.log(chalk.green('ts2dart transpilation succeeded.')); } done(); }); }; exports.format = function() { return spawn({cmd: which.sync('dartfmt')}); };
var chalk = require('chalk'); var gutil = require('gulp-util'); var spawn = require('gulp-spawn'); var through = require('through2'); var ts2dart = require('ts2dart'); var which = require('which'); exports.transpile = function() { var hadErrors = false; return through.obj( function(file, enc, done) { try { var src = ts2dart.translateFile(file.path); file.contents = new Buffer(src); file.path = file.path.replace(/.[tj]s$/, '.dart'); done(null, file); } catch (e) { hadErrors = true; if (e.name === 'TS2DartError') { // Sort of expected, log only the message. gutil.log(chalk.red(e.message)); } else { // Log the entire stack trace. gutil.log(chalk.red(e.stack)); } done(null, null); } }, function finished(done) { if (hadErrors) { gutil.log(chalk.red('ts2dart transpilation failed.')); throw new Error('ts2dart transpilation failed.'); } else { gutil.log(chalk.green('ts2dart transpilation succeeded.')); } done(); }); }; exports.format = function() { return spawn({cmd: which.sync('dartfmt')}); };
Replace incorrect JS_MIMETYPES with CSS_MIMETYPES
from django.conf import settings from mediasync import CSS_MIMETYPES, JS_MIMETYPES import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.realpath(os.path.expanduser(path)) return path def css_minifier(filedata, content_type, remote_path, is_active): is_css = (content_type in CSS_MIMETYPES or remote_path.lower().endswith('.css')) yui_path = _yui_path(settings) if is_css and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'css'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout) def js_minifier(filedata, content_type, remote_path, is_active): is_js = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.js')) yui_path = _yui_path(settings) if is_js and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'js'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout)
from django.conf import settings from mediasync import JS_MIMETYPES import os from subprocess import Popen, PIPE def _yui_path(settings): if not hasattr(settings, 'MEDIASYNC'): return None path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) if path: path = os.path.realpath(os.path.expanduser(path)) return path def css_minifier(filedata, content_type, remote_path, is_active): is_css = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.css')) yui_path = _yui_path(settings) if is_css and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'css'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout) def js_minifier(filedata, content_type, remote_path, is_active): is_js = (content_type in JS_MIMETYPES or remote_path.lower().endswith('.js')) yui_path = _yui_path(settings) if is_js and yui_path and is_active: proc = Popen(['java', '-jar', yui_path, '--type', 'js'], stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = proc.communicate(input=filedata) return str(stdout)
Use getResourceAsStream as getResource won't work
package com.github.atomfrede.jadenticon; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.io.File; import java.io.InputStream; public class JdenticonWrapper { private Object jdenticon; private Invocable invocable; public JdenticonWrapper() { try { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn"); invocable = (Invocable) nashorn; InputStream scriptStream = getClass().getResourceAsStream("/jdenticon.js"); String script = IOUtils.toString(scriptStream); nashorn.eval(script); jdenticon = nashorn.eval("jdenticon"); } catch (Exception e) { throw new RuntimeException("Unable to setup nashorn and jdenticon script.", e); } } public String getSvg(Jadenticon jadenticon) { try { return (String) invocable.invokeMethod(jdenticon, "toSvg", jadenticon.hash, jadenticon.size, jadenticon.padding); } catch (ScriptException | NoSuchMethodException e) { throw new RuntimeException("Unable to create jdenticon svg.", e); } } }
package com.github.atomfrede.jadenticon; import org.apache.commons.io.FileUtils; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.io.File; public class JdenticonWrapper { private Object jdenticon; private Invocable invocable; public JdenticonWrapper() { try { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn"); invocable = (Invocable) nashorn; String script = FileUtils.readFileToString(new File(getClass().getResource("/jdenticon.js").toURI())); nashorn.eval(script); jdenticon = nashorn.eval("jdenticon"); } catch (Exception e) { throw new RuntimeException("Unable to setup nashorn and jdenticon script.", e); } } public String getSvg(Jadenticon jadenticon) { try { return (String) invocable.invokeMethod(jdenticon, "toSvg", jadenticon.hash, jadenticon.size, jadenticon.padding); } catch (ScriptException | NoSuchMethodException e) { throw new RuntimeException("Unable to create jdenticon svg.", e); } } }
Remove use of "unsure" from TrainingData type The "unsure" key isn't used anywhere else
import numpy import sys from typing import (Iterator, Tuple, Mapping, Union, Iterable, List, Any) if sys.version_info >= (3, 8): from typing import TypedDict, Protocol, Literal else: from typing_extensions import TypedDict, Protocol, Literal RecordDict = Mapping[str, Any] RecordID = Union[int, str] Record = Tuple[RecordID, RecordDict] RecordPair = Tuple[Record, Record] RecordPairs = Iterator[RecordPair] Blocks = Iterator[List[RecordPair]] Cluster = Tuple[Tuple[RecordID, ...], Union[numpy.ndarray, Tuple]] Clusters = Iterable[Cluster] Data = Mapping[RecordID, RecordDict] TrainingExample = Tuple[RecordDict, RecordDict] Links = Iterable[Union[numpy.ndarray, Tuple[Tuple[RecordID, RecordID], float]]] LookupResults = Iterable[Tuple[RecordID, Tuple[Tuple[RecordID, float], ...]]] JoinConstraint = Literal['one-to-one', 'many-to-one', 'many-to-many'] class TrainingData(TypedDict): match: List[TrainingExample] distinct: List[TrainingExample] class Classifier(Protocol): def fit(self, X: object, y: object) -> None: ... def predict_proba(self, X: object) -> Any: ...
import numpy import sys from typing import (Iterator, Tuple, Mapping, Union, Iterable, List, Any) if sys.version_info >= (3, 8): from typing import TypedDict, Protocol, Literal else: from typing_extensions import TypedDict, Protocol, Literal RecordDict = Mapping[str, Any] RecordID = Union[int, str] Record = Tuple[RecordID, RecordDict] RecordPair = Tuple[Record, Record] RecordPairs = Iterator[RecordPair] Blocks = Iterator[List[RecordPair]] Cluster = Tuple[Tuple[RecordID, ...], Union[numpy.ndarray, Tuple]] Clusters = Iterable[Cluster] Data = Mapping[RecordID, RecordDict] TrainingExample = Tuple[RecordDict, RecordDict] Links = Iterable[Union[numpy.ndarray, Tuple[Tuple[RecordID, RecordID], float]]] LookupResults = Iterable[Tuple[RecordID, Tuple[Tuple[RecordID, float], ...]]] JoinConstraint = Literal['one-to-one', 'many-to-one', 'many-to-many'] class _TrainingData(TypedDict): match: List[TrainingExample] distinct: List[TrainingExample] class TrainingData(_TrainingData, total=False): uncertain: List[TrainingExample] # optional key class Classifier(Protocol): def fit(self, X: object, y: object) -> None: ... def predict_proba(self, X: object) -> Any: ...
Fix for os.path.join with model_id, was breaking on non-string model_id values.
import os import requests class LumidatumClient(object): def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'): self.authentication_token = authentication_token self.model_id = str(model_id) self.host_address = host_address def getRecommendations(self, parameters, model_id=None): """ Get recommendations for a model specified by model_id. Returns a list of id/score pairs in descending order from the highest score. """ selected_model_id = str(model_id) if model_id else self.model_id if selected_model_id is None: raise ValueError('model_id must be specified either at initialization of LumidatumClient or in client method call.') headers = { 'Authorization': self.authentication_token, 'content-type': 'application/json', } response = requests.post( os.path.join(self.host_address, 'api/predict', selected_model_id), parameters, headers=headers ) return response.json() def getRecommendationDescriptions(self, parameters, model_id=None): """ Get human readable recommendations. """ parameters['human_readable'] = True return self.getRecommendations(self, parameters, model_id)
import os import requests class LumidatumClient(object): def __init__(self, authentication_token, model_id=None, host_address='https://www.lumidatum.com'): self.authentication_token = authentication_token self.model_id = str(model_id) self.host_address = host_address def getRecommendations(self, parameters, model_id=None): """ Get recommendations for a model specified by model_id. Returns a list of id/score pairs in descending order from the highest score. """ selected_model_id = str(model_if) if model_id else self.model_id if selected_model_id is None: raise ValueError('model_id must be specified either at initialization of LumidatumClient or in client method call.') headers = { 'Authorization': self.authentication_token, 'content-type': 'application/json', } response = requests.post( os.path.join(self.host_address, 'api/predict', selected_model_id), parameters, headers=headers ) return response.json() def getRecommendationDescriptions(self, parameters, model_id=None): """ Get human readable recommendations. """ parameters['human_readable'] = True return self.getRecommendations(self, parameters, model_id)
Remove some thrash from library.
// ---------------------------- Imports. --------------------------------- const fs = require('fs'), cp = require('child_process'), request = require('request') // --------------------------- Main class. ------------------------------- class Pizdos { // Public. /** * Starts attack on url using options. * @param {string} url * @param {Object} options */ static attack(url, options) { fs.readFile(__dirname + '/../config/standart-options.json', 'utf8', (err, data) => { if (err) throw err const o = Object.assign(JSON.parse(data), options) this.startAttack(url, o.attackDuration, o.requestsFrequency) }) } // Private. /** * Starts attack on url. * @param {string} url * @param {number} processesCount * @param {number} duration * @param {number} frequency */ static startAttack(url, duration, frequency) { console.log('Attack is started.') setInterval(() => { request(url, (error) => { if (error) { console.log('Attack ended with an error.') process.abort() } }) }, frequency) setTimeout(() => { console.log('Attack is complete.') process.abort() }, duration) } } // ---------------------------- Exports. --------------------------------- module.exports = Pizdos
// ---------------------------- Imports. --------------------------------- const fs = require('fs'), cp = require('child_process'), request = require('request') // --------------------------- Main class. ------------------------------- class Pizdos { // Public. /** * Starts attack on url using options. * @param {string} url * @param {Object} options */ static attack(url, options) { fs.readFile(__dirname + '/../config/standart-options.json', 'utf8', (err, data) => { if (err) throw err const o = Object.assign(JSON.parse(data), options) this.startAttack(url, o.attackDuration, o.requestsFrequency) }) } // Private. /** * Starts attack on url. * @param {string} url * @param {number} processesCount * @param {number} duration * @param {number} frequency */ static startAttack(url, duration, frequency) { console.log('Attack is started.') setInterval(() => { request(url, (error, r, b) => { if (!!error) { console.log('Attack ended with an error.') process.abort() } }) }, frequency) setTimeout(() => { console.log('Attack is complete.') process.abort() }, duration) } } // ---------------------------- Exports. --------------------------------- module.exports = Pizdos
Define template path inside share callback
<?php namespace Apitude\Core\Template; use Apitude\Core\Provider\AbstractServiceProvider; use Apitude\Core\Utility\Arr; use Handlebars\Handlebars; use Handlebars\Loader\FilesystemLoader; use Silex\Application; class TemplateServiceProvider extends AbstractServiceProvider { public function register(Application $app) { parent::register($app); $config = $app['config']; $app['handlebars'] = $app->share(function ($app) { $templatePathConfigPath = 'template.handlebars.path'; if (! Arr::path($config, $templatePathConfigPath)) { Arr::setPath( $config, $templatePathConfigPath, APP_PATH . '/templates' ); } return new Handlebars([ 'loader' => new FilesystemLoader( Arr::path($config, $templatePathConfigPath), [ 'extension' => '.hbs', ] ), 'partials_loader' => new FilesystemLoader( Arr::path($config, $templatePathConfigPath), [ 'prefix' => '_', ] ) ]); }); $app['config'] = $config; } }
<?php namespace Apitude\Core\Template; use Apitude\Core\Provider\AbstractServiceProvider; use Apitude\Core\Utility\Arr; use Handlebars\Handlebars; use Handlebars\Loader\FilesystemLoader; use Silex\Application; class TemplateServiceProvider extends AbstractServiceProvider { public function register(Application $app) { parent::register($app); $config = $app['config']; $templatePathConfigPath = 'template.handlebars.path'; if (! Arr::path($config, $templatePathConfigPath)) { Arr::setPath( $config, $templatePathConfigPath, APP_PATH . '/templates' ); } $app['handlebars'] = $app->share(function ($app) { return new Handlebars([ 'loader' => new FilesystemLoader( Arr::path($config, $templatePathConfigPath), [ 'extension' => '.hbs', ] ), 'partials_loader' => new FilesystemLoader( Arr::path($config, $templatePathConfigPath), [ 'prefix' => '_', ] ) ]); }); $app['config'] = $config; } }
Make building_number and state optional
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAddressesTable extends Migration { public function up() { Schema::create('addresses', function (Blueprint $table) { $table->increments('id'); $table->morphs('addressable'); $table->integer('country_id')->unsigned()->index(); $table->string('organization')->nullable(); $table->string('name_prefix'); $table->string('name_suffix')->nullable(); $table->string('first_name'); $table->string('last_name'); $table->string('street'); $table->string('building_number')->nullable(); $table->string('building_flat')->nullable(); $table->string('city'); $table->string('city_prefix')->nullable(); $table->string('city_suffix')->nullable(); $table->string('state')->nullable(); $table->string('state_code')->nullable(); $table->string('postcode'); $table->string('phone')->nullable(); $table->float('lat')->nullable(); $table->float('lng')->nullable(); foreach (config('addressable.flags', []) as $flag) { $table->boolean('is_'.$flag)->default(false)->index(); } $table->timestamps(); }); } public function down() { Schema::dropIfExists('addresses'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAddressesTable extends Migration { public function up() { Schema::create('addresses', function (Blueprint $table) { $table->increments('id'); $table->morphs('addressable'); $table->integer('country_id')->unsigned()->index(); $table->string('organization')->nullable(); $table->string('name_prefix'); $table->string('name_suffix')->nullable(); $table->string('first_name'); $table->string('last_name'); $table->string('street'); $table->string('building_number'); $table->string('building_flat')->nullable(); $table->string('city'); $table->string('city_prefix')->nullable(); $table->string('city_suffix')->nullable(); $table->string('state'); $table->string('state_code')->nullable(); $table->string('postcode'); $table->string('phone')->nullable(); $table->float('lat')->nullable(); $table->float('lng')->nullable(); foreach (config('addressable.flags', []) as $flag) { $table->boolean('is_'.$flag)->default(false)->index(); } $table->timestamps(); }); } public function down() { Schema::dropIfExists('addresses'); } }
Add padding to the basket input.
import { Util } from "../../util.js"; export class BasketTemplate { static update(render, state, events) { const headerClasses = "fw6 bb b--black-20 tl pb1 pr1 bg-black-10"; const trClasses = "pv1 pr1 bb b--black-20"; const trClassesLink = `${trClasses} pointer dim`; /* eslint-disable indent */ render` <h2>Basket</h2> <div class="pa2"> <input id="assetsSearch" class="pa2" size="32" oninput="${events}" placeholder="What assets to be added?"> </div> <table style="${Util.show(state.assetsSearch.length)}" class="f7 mw8 pa2"> <thead> <th class="${headerClasses}">Symbol</th> <th class="${headerClasses}">Description</th> <th class="${headerClasses}">Type</th> <th class="${headerClasses}">Market</th> </thead> <tbody>${state.assetsSearch.map(asset => hyperHTML.wire()`<tr> <td id="${`assetSearch-${asset.symbol}`}" onclick=${e => events(e, asset)} class="${trClassesLink}" title="Click to add the asset">${asset.symbol}</td> <td class="${trClasses}">${asset.name}</td> <td class="${trClasses}">${asset.type}</td> <td class="${trClasses}">${asset.exchDisp}</td> </tr>`) }</tbody> </table> `; /* eslint-enable indent */ } }
import { Util } from "../../util.js"; export class BasketTemplate { static update(render, state, events) { const headerClasses = "fw6 bb b--black-20 tl pb1 pr1 bg-black-10"; const trClasses = "pv1 pr1 bb b--black-20"; const trClassesLink = `${trClasses} pointer dim`; /* eslint-disable indent */ render` <h2>Basket</h2> <input id="assetsSearch" size="32" oninput="${events}" placeholder="What assets to be added?"> <table style="${Util.show(state.assetsSearch.length)}" class="f7 mw8 pa2"> <thead> <th class="${headerClasses}">Symbol</th> <th class="${headerClasses}">Description</th> <th class="${headerClasses}">Type</th> <th class="${headerClasses}">Market</th> </thead> <tbody>${state.assetsSearch.map(asset => hyperHTML.wire()`<tr> <td id="${`assetSearch-${asset.symbol}`}" onclick=${e => events(e, asset)} class="${trClassesLink}" title="Click to add the asset">${asset.symbol}</td> <td class="${trClasses}">${asset.name}</td> <td class="${trClasses}">${asset.type}</td> <td class="${trClasses}">${asset.exchDisp}</td> </tr>`) }</tbody> </table> `; /* eslint-enable indent */ } }
Rename markdown_div to jquery variable with $
$(function () { var before_value = '', $markdown_div = $('#id_markdown'), $preview = $('.preview'), $html_div = $('#id_html'), $create_form = $('#create_html'), markdown_event, markdown_content = '', markdown_slides = []; $create_form.submit(function () { $html_div.val(marked($markdown_div.val())); }); // onFocus 이벤트 발생 시 setInterval을 통해 _onWatch를 실행 $markdown_div.focus(function (e) { markdown_event = setInterval($.proxy(function () { _onWatch(); }), 200); }); $markdown_div.blur(function (e) { if ($markdown_div) { clearInterval(markdown_event); } }); function _onWatch() { // 이전 값과 현재 값이 다르면 필요한 액션 수행 var currentValue = $markdown_div.val(); if (before_value !== currentValue) { before_value = currentValue; // 현재 값 저장 markdown_content = $markdown_div.val(); markdown_slides = markdown_content.split(/={5,}/); $preview.html(''); markdown_slides.forEach(function (v, i) { $preview.append('<div class="callout secondary">' + marked(v) + '</div>'); }); } } });
$(function () { var before_value = '', markdown_div = $('#id_markdown'), $preview = $('.preview'), $html_div = $('#id_html'), $create_form = $('#create_html'), markdown_event, markdown_content = '', markdown_slides = []; $create_form.submit(function () { $html_div.val(marked(markdown_div.val())); }); // onFocus 이벤트 발생 시 setInterval을 통해 _onWatch를 실행 markdown_div.focus(function (e) { markdown_event = setInterval($.proxy(function () { _onWatch(); }), 200); }); markdown_div.blur(function (e) { if (markdown_div) { clearInterval(markdown_event); } }); function _onWatch() { // 이전 값과 현재 값이 다르면 필요한 액션 수행 var currentValue = markdown_div.val(); if (before_value !== currentValue) { before_value = currentValue; // 현재 값 저장 markdown_content = markdown_div.val(); markdown_slides = markdown_content.split(/={5,}/); $preview.html(''); markdown_slides.forEach(function (v, i) { $preview.append('<div class="callout secondary">' + marked(v) + '</div>'); }); } } });
Support Django < 1.5 with a simplified version of `get_url()`
from django.core.management import call_command try: from django.shortcuts import resolve_url except ImportError: import warnings warnings.warn("URL path supported only in get_url() with Django < 1.5") resolve_url = lambda to, *args, **kwargs: to from behave_django.testcase import BehaveDjangoTestCase def before_scenario(context, scenario): # This is probably a hacky method of setting up the test case # outside of a test runner. Suggestions are welcome. :) context.test = BehaveDjangoTestCase() context.test.setUpClass() context.test() # Load fixtures if getattr(context, 'fixtures', None): call_command('loaddata', *context.fixtures, verbosity=0) context.base_url = context.test.live_server_url def get_url(to=None, *args, **kwargs): """ URL helper attached to context with built-in reverse resolution as a handy shortcut. Takes an absolute path, a view name, or a model instance as an argument (as django.shortcuts.resolve_url). Examples:: context.get_url() context.get_url('/absolute/url/here') context.get_url('view-name') context.get_url('view-name', 'with args', and='kwargs') context.get_url(model_instance) """ return context.base_url + ( resolve_url(to, *args, **kwargs) if to else '') context.get_url = get_url def after_scenario(context, scenario): context.test.tearDownClass() del context.test
from django.core.management import call_command from django.shortcuts import resolve_url from behave_django.testcase import BehaveDjangoTestCase def before_scenario(context, scenario): # This is probably a hacky method of setting up the test case # outside of a test runner. Suggestions are welcome. :) context.test = BehaveDjangoTestCase() context.test.setUpClass() context.test() # Load fixtures if getattr(context, 'fixtures', None): call_command('loaddata', *context.fixtures, verbosity=0) context.base_url = context.test.live_server_url def get_url(to=None, *args, **kwargs): """ URL helper attached to context with built-in reverse resolution as a handy shortcut. Takes an absolute path, a view name, or a model instance as an argument (as django.shortcuts.resolve_url). Examples:: context.get_url() context.get_url('/absolute/url/here') context.get_url('view-name') context.get_url('view-name', 'with args', and='kwargs') context.get_url(model_instance) """ return context.base_url + ( resolve_url(to, *args, **kwargs) if to else '') context.get_url = get_url def after_scenario(context, scenario): context.test.tearDownClass() del context.test
Fix resolved file paths and exclude node_modules Since I’m no longer using beartime-core, nothing in node_modules/ needs to be compiled.
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'build.js' }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /\.vue$/, loader: 'vue' }, { test: /\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg|ttf)$/, loader: 'url' }, { test: /\.json$/, loader: 'json' } ] }, babel: { presets: ['es2015'] }, devServer: { historyApiFallback: true, noInfo: false }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]) }
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/', filename: 'build.js' }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /\.vue$/, loader: 'vue' }, { test: /\.js$/, loader: 'babel' }, { test: /\.(png|jpg|gif|svg|ttf)$/, loader: 'url' }, { test: /\.json$/, loader: 'json' } ] }, babel: { presets: ['es2015'] }, devServer: { historyApiFallback: true, noInfo: false }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]) }
CAMEL-14671: Make PropertiesFunction part of the PropertiesComponent SPI
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.test.blueprint; import org.apache.camel.spi.PropertiesFunction; import org.junit.Test; public class PropertiesComponentFunctionTest extends CamelBlueprintTestSupport { public static final class MyFunction implements PropertiesFunction { @Override public String getName() { return "beer"; } @Override public String apply(String remainder) { return "mock:" + remainder.toLowerCase(); } } @Override protected String getBlueprintDescriptor() { return "org/apache/camel/test/blueprint/PropertiesComponentFunctionTest.xml"; } @Test public void testFunction() throws Exception { getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:bar").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.test.blueprint; import org.apache.camel.component.properties.PropertiesFunction; import org.junit.Test; public class PropertiesComponentFunctionTest extends CamelBlueprintTestSupport { public static final class MyFunction implements PropertiesFunction { @Override public String getName() { return "beer"; } @Override public String apply(String remainder) { return "mock:" + remainder.toLowerCase(); } } @Override protected String getBlueprintDescriptor() { return "org/apache/camel/test/blueprint/PropertiesComponentFunctionTest.xml"; } @Test public void testFunction() throws Exception { getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:bar").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } }
Replace slashes with backslash in namespace Fixes #70.
<?php namespace Studio\Parts\Composer; use Studio\Filesystem\Directory; use Studio\Parts\AbstractPart; class Part extends AbstractPart { public function setupPackage($composer, Directory $target) { // Ask for package name $composer->name = $this->input->ask( 'Please name this package', '/[[:alnum:]]+\/[[:alnum:]]+/', 'Please enter a valid package name in the format "vendor/name".' ); // Ask for the root namespace $namespace = $this->input->ask( 'Please provide a default namespace (PSR-4)', '/([[:alnum:]]+\\\\?)+/', 'Please enter a valid PHP namespace', $this->makeDefaultNamespace($composer->name) ); // Normalize and store the namespace $namespace = str_replace('/', '\\', $namespace); $namespace = rtrim($namespace, '\\'); @$composer->autoload->{'psr-4'}->{"$namespace\\"} = 'src/'; // Create an example file $this->copyTo( __DIR__ . '/stubs/src/Example.php', $target, 'src/Example.php', function ($content) use ($namespace) { return preg_replace('/namespace[^;]+;/', "namespace $namespace;", $content); } ); } protected function makeDefaultNamespace($package) { list($vendor, $name) = explode('/', $package); return ucfirst($vendor) . '\\' . ucfirst($name); } }
<?php namespace Studio\Parts\Composer; use Studio\Filesystem\Directory; use Studio\Parts\AbstractPart; class Part extends AbstractPart { public function setupPackage($composer, Directory $target) { // Ask for package name $composer->name = $this->input->ask( 'Please name this package', '/[[:alnum:]]+\/[[:alnum:]]+/', 'Please enter a valid package name in the format "vendor/name".' ); // Ask for the root namespace $namespace = $this->input->ask( 'Please provide a default namespace (PSR-4)', '/([[:alnum:]]+\\\\?)+/', 'Please enter a valid PHP namespace', $this->makeDefaultNamespace($composer->name) ); // Normalize and store the namespace $namespace = rtrim($namespace, '\\'); @$composer->autoload->{'psr-4'}->{"$namespace\\"} = 'src/'; // Create an example file $this->copyTo( __DIR__ . '/stubs/src/Example.php', $target, 'src/Example.php', function ($content) use ($namespace) { return preg_replace('/namespace[^;]+;/', "namespace $namespace;", $content); } ); } protected function makeDefaultNamespace($package) { list($vendor, $name) = explode('/', $package); return ucfirst($vendor) . '\\' . ucfirst($name); } }
Add a couple more cursor helpers
<?php namespace League\CLImate\Util; class Cursor { /** * Move the cursor up in the terminal x number of lines. * * @param int $lines * * @return string */ public function up($lines = 1) { return "\e[{$lines}A"; } /** * Move the cursor down in the terminal x number of lines. * * @param int $lines * * @return string */ public function down($lines = 1) { return "\e[{$lines}B"; } /** * Move the cursor right in the terminal x number of columns. * * @param int $cols * * @return string */ public function right($columns = 1) { return "\e[{$columns}C"; } /** * Move the cursor left in the terminal x number of columns. * * @param int $cols * * @return string */ public function left($cols = 1) { return "\e[{$cols}D"; } /** * Move cursor to the beginning of the current line. * * @return string */ public function startOfCurrentLine() { return "\r"; } /** * Delete the current line to the end. * * @return string */ public function deleteCurrentLine() { return "\e[K"; } /** * Get the style for hiding the cursor * * @return string */ public function hide() { return "\e[?25l"; } /** * Get the style for returning the cursor to its default * * @return string */ public function defaultStyle() { return "\e[?25h"; } }
<?php namespace League\CLImate\Util; class Cursor { /** * Move the cursor up in the terminal x number of lines. * * @param int $lines * * @return string */ public function up($lines = 1) { return "\e[{$lines}A"; } /** * Move the cursor left in the terminal x number of columns. * * @param int $cols * * @return string */ public function left($cols = 1) { return "\e[{$cols}D"; } /** * Move cursor to the beginning of the current line. * * @return string */ public function startOfCurrentLine() { return "\r"; } /** * Delete the current line to the end. * * @return string */ public function deleteCurrentLine() { return "\e[K"; } /** * Get the style for hiding the cursor * * @return string */ public function hide() { return "\e[?25l"; } /** * Get the style for returning the cursor to its default * * @return string */ public function defaultStyle() { return "\e[?25h"; } }
Split Protocol class in Protocol and ProtocolElement
''' Created on 11 jan. 2013 @author: sander ''' from abc import abstractmethod, ABCMeta class ProtocolElement(object): __metaclass__ = ABCMeta @abstractmethod def __init__(self): ''' Constructor ''' def __repr__(self): # This works as long as we accept all properties as paramters in the # constructor params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(params)) def __str__(self): return str(self.to_bytes()) def __bytes__(self): return self.to_bytes() @abstractmethod def sanitize(self): ''' Check and optionally fix properties ''' @classmethod @abstractmethod def from_bytes(cls, bitstream): ''' Parse the given packet and update properties accordingly ''' @abstractmethod def to_bytes(self): ''' Create bytes from properties ''' class Protocol(ProtocolElement): __metaclass__ = ABCMeta header_type = None @abstractmethod def __init__(self, next_header=None, payload=''): ''' Constructor ''' super(Protocol, self).__init__() self.next_header = next_header self.payload = payload
''' Created on 11 jan. 2013 @author: sander ''' from abc import abstractmethod, ABCMeta class Protocol(object): __metaclass__ = ABCMeta header_type = None @abstractmethod def __init__(self, next_header=None, payload=''): ''' Constructor ''' self.next_header = next_header self.payload = payload def __repr__(self): # This works as long as we accept all properties as paramters in the # constructor params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(params)) @abstractmethod def sanitize(self): ''' Check and optionally fix properties ''' @classmethod @abstractmethod def from_bytes(cls, bitstream): ''' Parse the given packet and update properties accordingly ''' @abstractmethod def to_bytes(self): ''' Create bytes from properties ''' def __str__(self): return str(self.to_bytes()) def __bytes__(self): return bytes(self.to_bytes())
Add debug code to list how many object entities there are for each type, along with number of fields
var ObjectEditor = { Data: { Units: require('../WEdata/data/Units.json'), Items: require('../WEdata/data/Items.json'), Destructables: require('../WEdata/data/Destructables.json') }, Fields: { Units: require('../WEdata/fields/UnitMetaData.json'), Items: require('../WEdata/fields/ItemMetaData.json'), Destructables: require('../WEdata/fields/DestructableMetaData.json') }, Find: { UnitFieldIdByLongName: function(longName) { // e.g. bountydice -> ubdi // TODO: time this function -- it may take too long for lookups for(var fieldKey in ObjectEditor.Fields.Units) { if( ObjectEditor.Fields.Units[fieldKey] && ObjectEditor.Fields.Units[fieldKey].field.toLowerCase() === longName.toLowerCase()) { return fieldKey; } } // console.error('Unable to lookup unit field by long name:', longName); return null; // Unable to find by long name }, FieldLongNameById: function(objEditorType, id) { // e.g. ubdi -> bountydice var objEditorFieldName = objEditorType[0].toUpperCase() + objEditorType.substr(1) + 's'; return ObjectEditor.Fields[objEditorFieldName][id].field; } } } Object.keys(ObjectEditor.Data).forEach((data) => { console.log(data, Object.keys(ObjectEditor.Data[data]).length, Object.keys(ObjectEditor.Fields[data]).length); }) module.exports = ObjectEditor;
var ObjectEditor = { Data: { Units: require('../WEdata/data/Units.json'), Items: require('../WEdata/data/Items.json'), Destructables: require('../WEdata/data/Destructables.json') }, Fields: { Units: require('../WEdata/fields/UnitMetaData.json'), Items: require('../WEdata/fields/ItemMetaData.json'), Destructables: require('../WEdata/fields/DestructableMetaData.json') }, Find: { UnitFieldIdByLongName: function(longName) { // e.g. bountydice -> ubdi // TODO: time this function -- it may take too long for lookups for(var fieldKey in ObjectEditor.Fields.Units) { if( ObjectEditor.Fields.Units[fieldKey] && ObjectEditor.Fields.Units[fieldKey].field.toLowerCase() === longName.toLowerCase()) { return fieldKey; } } // console.error('Unable to lookup unit field by long name:', longName); return null; // Unable to find by long name }, FieldLongNameById: function(objEditorType, id) { // e.g. ubdi -> bountydice var objEditorFieldName = objEditorType[0].toUpperCase() + objEditorType.substr(1) + 's'; return ObjectEditor.Fields[objEditorFieldName][id].field; } } } module.exports = ObjectEditor;
Maintain current protocol, hostname and port when navigating
/*global window, document, Faye */ /*jslint vars: true, indent: 2 */ (function () { 'use strict'; var begin = function (beginControlling, beginMirroring) { var faye = new Faye.Client('/faye'); if (window.location.hostname.indexOf('mirror') === 0) { beginMirroring(faye); } else { beginControlling(faye); } }; var navigateTo = function (url) { var a = document.createElement('a'); a.href = url; a.protocol = window.location.protocol; a.host = window.location.host; if (window.location.href !== a.href) { window.location.href = a.href; } }; var beginControlling = function (faye) { window.addEventListener('scroll', function () { faye.publish('/scroll', { x: window.scrollX, y: window.scrollY }); }); window.addEventListener('click', function (event) { var element = event.target; while (element) { if (element.localName === 'a') { event.preventDefault(); faye.publish('/navigate', { url: element.href }); navigateTo(element.href); break; } element = element.parentNode; } }); }; var beginMirroring = function (faye) { faye.subscribe('/scroll', function (message) { window.scrollTo(message.x, message.y); }); faye.subscribe('/navigate', function (message) { navigateTo(message.url); }); }; begin(beginControlling, beginMirroring); }());
/*global window, document, Faye */ /*jslint vars: true, indent: 2 */ (function () { 'use strict'; var begin = function (beginControlling, beginMirroring) { var faye = new Faye.Client('/faye'); if (window.location.hostname.indexOf('mirror') === 0) { beginMirroring(faye); } else { beginControlling(faye); } }; var navigateTo = function (url) { if (window.location.href !== url) { window.location.href = url; } }; var beginControlling = function (faye) { window.addEventListener('scroll', function () { faye.publish('/scroll', { x: window.scrollX, y: window.scrollY }); }); window.addEventListener('click', function (event) { var element = event.target; while (element) { if (element.localName === 'a') { event.preventDefault(); faye.publish('/navigate', { url: element.href }); navigateTo(element.href); break; } element = element.parentNode; } }); }; var beginMirroring = function (faye) { faye.subscribe('/scroll', function (message) { window.scrollTo(message.x, message.y); }); faye.subscribe('/navigate', function (message) { navigateTo(message.url); }); }; begin(beginControlling, beginMirroring); }());
Add exit command to the help text
/* * 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 io.trino.cli; public final class Help { private Help() {} public static String getHelpText() { return "" + "Supported commands:\n" + "QUIT\n" + "EXIT\n" + "CLEAR\n" + "EXPLAIN [ ( option [, ...] ) ] <query>\n" + " options: FORMAT { TEXT | GRAPHVIZ | JSON }\n" + " TYPE { LOGICAL | DISTRIBUTED | VALIDATE | IO }\n" + "DESCRIBE <table>\n" + "SHOW COLUMNS FROM <table>\n" + "SHOW FUNCTIONS\n" + "SHOW CATALOGS [LIKE <pattern>]\n" + "SHOW SCHEMAS [FROM <catalog>] [LIKE <pattern>]\n" + "SHOW TABLES [FROM <schema>] [LIKE <pattern>]\n" + "USE [<catalog>.]<schema>\n" + ""; } }
/* * 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 io.trino.cli; public final class Help { private Help() {} public static String getHelpText() { return "" + "Supported commands:\n" + "QUIT\n" + "CLEAR\n" + "EXPLAIN [ ( option [, ...] ) ] <query>\n" + " options: FORMAT { TEXT | GRAPHVIZ | JSON }\n" + " TYPE { LOGICAL | DISTRIBUTED | VALIDATE | IO }\n" + "DESCRIBE <table>\n" + "SHOW COLUMNS FROM <table>\n" + "SHOW FUNCTIONS\n" + "SHOW CATALOGS [LIKE <pattern>]\n" + "SHOW SCHEMAS [FROM <catalog>] [LIKE <pattern>]\n" + "SHOW TABLES [FROM <schema>] [LIKE <pattern>]\n" + "USE [<catalog>.]<schema>\n" + ""; } }
Improve error message when prophet.yml not found.
<?php /** * * * @author Sam Schmidt * @date 2015-04-22 * @company Linus Shops */ namespace LinusShops\Prophet; use LinusShops\Prophet\Exceptions\InvalidConfigException; use Symfony\Component\Yaml\Parser; class Config { private $modules; public function __construct($parsedConfigFile, $prefix = '') { if (!is_array($parsedConfigFile)) { throw new InvalidConfigException('Invalid config: parsed config must be an array.'); } if (isset($parsedConfigFile['modules'])) { $this->loadModules($parsedConfigFile['modules']); } } /** * @param string $path * @return Config * @throws InvalidConfigException */ public static function getConfigFromFile($path = '.') { $path .= '/prophet.yml'; if (!is_file($path)) { throw new InvalidConfigException("prophet.yml not found in path {$path}"); } $yaml = new Parser(); return new Config($yaml->parse(file_get_contents($path))); } private function loadModules($modules) { foreach ($modules as $definition) { $module = new Module( $definition['name'], $definition['path'] ); $this->modules[$module->getName()] = $module; } } public function getModules() { return $this->modules; } public function hasModules() { return count($this->modules) > 0; } }
<?php /** * * * @author Sam Schmidt * @date 2015-04-22 * @company Linus Shops */ namespace LinusShops\Prophet; use LinusShops\Prophet\Exceptions\InvalidConfigException; use Symfony\Component\Yaml\Parser; class Config { private $modules; public function __construct($parsedConfigFile, $prefix = '') { if (!is_array($parsedConfigFile)) { throw new InvalidConfigException('Invalid config: parsed config must be an array.'); } if (isset($parsedConfigFile['modules'])) { $this->loadModules($parsedConfigFile['modules']); } } /** * @param string $path * @return Config * @throws InvalidConfigException */ public static function getConfigFromFile($path = '.') { $path .= '/prophet.yml'; if (!is_file($path)) { throw new InvalidConfigException('Invalid config path given.'); } $yaml = new Parser(); return new Config($yaml->parse(file_get_contents($path))); } private function loadModules($modules) { foreach ($modules as $definition) { $module = new Module( $definition['name'], $definition['path'] ); $this->modules[$module->getName()] = $module; } } public function getModules() { return $this->modules; } public function hasModules() { return count($this->modules) > 0; } }
Change assertIn to assert_ for python 2.6 support
import unittest import fiona from shapely.geometry import Point import geopandas as gpd from geopandas.geocode import geocode, _prepare_geocode_result class TestGeocode(unittest.TestCase): def test_prepare_result(self): # Calls _prepare_result with sample results from the geocoder call # loop p0 = Point(12.3, -45.6) # Treat these as lat/lon p1 = Point(-23.4, 56.7) d = {'a': ('address0', p0.coords[0]), 'b': ('address1', p1.coords[0])} df = _prepare_geocode_result(d) assert type(df) is gpd.GeoDataFrame self.assertEqual(fiona.crs.from_epsg(4326), df.crs) self.assertEqual(len(df), 2) self.assert_('address' in df) coords = df.loc['a']['geometry'].coords[0] test = p0.coords[0] # Output from the df should be lon/lat self.assertAlmostEqual(coords[0], test[1]) self.assertAlmostEqual(coords[1], test[0]) coords = df.loc['b']['geometry'].coords[0] test = p1.coords[0] self.assertAlmostEqual(coords[0], test[1]) self.assertAlmostEqual(coords[1], test[0]) def test_bad_provider(self): self.assertRaises(ValueError, geocode, ['cambridge, ma'], 'badprovider')
import unittest import fiona from shapely.geometry import Point import geopandas as gpd from geopandas.geocode import geocode, _prepare_geocode_result class TestGeocode(unittest.TestCase): def test_prepare_result(self): # Calls _prepare_result with sample results from the geocoder call # loop p0 = Point(12.3, -45.6) # Treat these as lat/lon p1 = Point(-23.4, 56.7) d = {'a': ('address0', p0.coords[0]), 'b': ('address1', p1.coords[0])} df = _prepare_geocode_result(d) assert type(df) is gpd.GeoDataFrame self.assertEqual(fiona.crs.from_epsg(4326), df.crs) self.assertEqual(len(df), 2) self.assertIn('address', df) coords = df.loc['a']['geometry'].coords[0] test = p0.coords[0] # Output from the df should be lon/lat self.assertAlmostEqual(coords[0], test[1]) self.assertAlmostEqual(coords[1], test[0]) coords = df.loc['b']['geometry'].coords[0] test = p1.coords[0] self.assertAlmostEqual(coords[0], test[1]) self.assertAlmostEqual(coords[1], test[0]) def test_bad_provider(self): self.assertRaises(ValueError, geocode, ['cambridge, ma'], 'badprovider')
Add files on the command line, cleanup
// Copyright 2013 SteelSeries ApS. All rights reserved. // No license is given for the use of this source code. // This package impliments a basic LISP interpretor for embedding in a go program for scripting. // This file provides a repl package main import ( "bufio" "flag" "fmt" "github.com/steelseries/golisp" "os" "strings" ) func main() { flag.Parse() fmt.Printf("%d", flag.NArg()) for i := 0; i < flag.NArg(); i = i + 1 { fmt.Printf("Loading %s\n", flag.Arg(i)) _, err := golisp.ProcessFile(flag.Arg(i)) if err != nil { fmt.Printf("Error: %s\n", err) } } for true { in := bufio.NewReader(os.Stdin) for true { fmt.Printf(">") input, err := in.ReadString('\n') if err != nil { panic(err) } input = strings.TrimRight(input, "\r\n") if input != "" { code, err := golisp.Parse(input) println(golisp.String(code)) if err != nil { fmt.Printf("Error: %s\n", err) } else { d, err := golisp.Eval(code) if err != nil { fmt.Printf("Error in evaluation: %s\n", err) } else { fmt.Printf("==> %s\n", golisp.String(d)) } } } } } }
// Copyright 2013 SteelSeries ApS. All rights reserved. // No license is given for the use of this source code. // This package impliments a basic LISP interpretor for embedding in a go program for scripting. // This file provides a repl package main import ( "bufio" "fmt" "github.com/steelseries/golisp" "os" "strings" ) func main() { for true { in := bufio.NewReader(os.Stdin) for true { fmt.Printf(">") input, err := in.ReadString('\n') if err != nil { panic(err) } input = strings.TrimRight(input, "\r\n") code, err := golisp.Parse(input) println(golisp.String(code)) if err != nil { fmt.Printf("Error: %s\n", err) } else { d, err := golisp.Eval(code) if err != nil { fmt.Printf("Error in evaluation: %s\n", err) } else { fmt.Printf("==> %s\n", golisp.String(d)) } } } } }
Fix affiliated institutions multiplying at every render
import Ember from 'ember'; import loadAll from 'ember-osf/utils/load-relationship'; export default Ember.Component.extend({ users: Ember.A(), bibliographicUsers: Ember.A(), institutions: Ember.A(), getAuthors: function() { // Cannot be called until node has loaded! const node = this.get('node'); if (!node) { return }; if(this.get('users').length > 0 || this.get('bibliographicUsers').length > 0) { return; } const contributors = Ember.A(); loadAll(node, 'contributors', contributors).then(() => { contributors.forEach((item) => { this.get('users').pushObject(item.get('users')); if(item.get('bibliographic')){ this.get('bibliographicUsers').pushObject(item.get('users')); } }) }); }, getAffiliatedInst: function (){ const node = this.get('node'); if (!node) { return }; if(this.get('institutions').length > 0) { return; } const institutions = Ember.A(); loadAll(node, 'affiliatedInstitutions', institutions).then(() => { institutions.forEach((item) => { this.get('institutions').pushObject(item); }) }); }, didReceiveAttrs() { this._super(...arguments); this.getAuthors(); this.getAffiliatedInst(); } });
import Ember from 'ember'; import loadAll from 'ember-osf/utils/load-relationship'; export default Ember.Component.extend({ users: Ember.A(), bibliographicUsers: Ember.A(), institutions: Ember.A(), getAuthors: function() { // Cannot be called until node has loaded! const node = this.get('node'); if (!node) { return }; if(this.get('users').length > 0 || this.get('bibliographicUsers').length > 0) { return; } const contributors = Ember.A(); loadAll(node, 'contributors', contributors).then(() => { contributors.forEach((item) => { this.get('users').pushObject(item.get('users')); if(item.get('bibliographic')){ this.get('bibliographicUsers').pushObject(item.get('users')); } }) }); }, getAffiliatedInst: function (){ const node = this.get('node'); if (!node) { return }; const institutions = Ember.A(); loadAll(node, 'affiliatedInstitutions', institutions).then(() => { institutions.forEach((item) => { this.get('institutions').pushObject(item); }) }); }, didReceiveAttrs() { this._super(...arguments); this.getAuthors(); this.getAffiliatedInst(); } });
Make methods names more representative
var cdb = require('cartodb.js'); var RowsView = require('./rows_view'); var ChooseGeometryView = require('./choose_geometry_view'); var ViewFactory = require('../../view_factory'); /** * View for the georeference types that requires the two-steps flow. * First select columns values, and then the geometry type to use. */ module.exports = cdb.core.View.extend({ initialize: function() { this._initBinds(); }, render: function() { this.clearSubViews(); if (this.model.get('step') === 1) { this._renderChooseGeometry(); } else { this._renderHeader(); this._renderRows(); } return this; }, _renderHeader: function() { this._appendView( ViewFactory.createByTemplate('common/dialogs/georeference/default_content_header', { title: this.options.title, desc: this.options.desc }) ); }, _renderRows: function() { this._appendView( new RowsView({ model: this.model }) ); }, _renderChooseGeometry: function() { this._appendView( new ChooseGeometryView({ model: this.model }) ); }, _appendView: function(view) { this.addView(view); this.$el.append(view.render().$el); }, _initBinds: function() { this.model.bind('change:step', this.render, this); } });
var cdb = require('cartodb.js'); var RowsView = require('./rows_view'); var ChooseGeometryView = require('./choose_geometry_view'); var ViewFactory = require('../../view_factory'); /** * View for the georeference types that requires the two-steps flow. * First select columns values, and then the geometry type to use. */ module.exports = cdb.core.View.extend({ initialize: function() { this._initBinds(); }, render: function() { this.clearSubViews(); if (this.model.get('step') === 1) { this._createChooseGeometryView(); } else { this._createHeaderView(); this._createRowsView(); } return this; }, _createHeaderView: function() { this._appendView( ViewFactory.createByTemplate('common/dialogs/georeference/default_content_header', { title: this.options.title, desc: this.options.desc }) ); }, _createRowsView: function() { this._appendView( new RowsView({ model: this.model }) ); }, _createChooseGeometryView: function() { this._appendView( new ChooseGeometryView({ model: this.model }) ); }, _appendView: function(view) { this.addView(view); this.$el.append(view.render().$el); }, _initBinds: function() { this.model.bind('change:step', this.render, this); } });
Update invalid URI to correctly throw exception
/* * $Id: AltRepTest.java [23-Apr-2004] * * Copyright (c) 2004, Ben Fortuna All rights reserved. */ package net.fortuna.ical4j.model.parameter; import java.net.URI; import java.net.URISyntaxException; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.ParameterFactoryImpl; import junit.framework.TestCase; /** * Test case for AltRep. * @author benfortuna */ public class AltRepTest extends TestCase { /* * Class to test for void AltRep(String) */ public void testAltRepString() throws URISyntaxException { try { new AltRep("<mailto:../:...invalid...>"); fail("URISyntaxException not thrown!"); } catch (URISyntaxException use) { // test success. } AltRep ar = (AltRep) ParameterFactoryImpl.getInstance().createParameter(Parameter.ALTREP, "mailto:[email protected]"); assertNotNull(ar.getUri()); } /* * Class to test for void AltRep(URI) */ public void testAltRepURI() throws URISyntaxException { AltRep ar = new AltRep(new URI("mailto:[email protected]")); assertNotNull(ar.getUri()); } }
/* * $Id: AltRepTest.java [23-Apr-2004] * * Copyright (c) 2004, Ben Fortuna All rights reserved. */ package net.fortuna.ical4j.model.parameter; import java.net.URI; import java.net.URISyntaxException; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.ParameterFactoryImpl; import junit.framework.TestCase; /** * Test case for AltRep. * @author benfortuna */ public class AltRepTest extends TestCase { /* * Class to test for void AltRep(String) */ public void testAltRepString() throws URISyntaxException { try { new AltRep("::...invalid..."); fail("URISyntaxException not thrown!"); } catch (URISyntaxException use) { // test success. } AltRep ar = (AltRep) ParameterFactoryImpl.getInstance().createParameter(Parameter.ALTREP, "mailto:[email protected]"); assertNotNull(ar.getUri()); } /* * Class to test for void AltRep(URI) */ public void testAltRepURI() throws URISyntaxException { AltRep ar = new AltRep(new URI("mailto:[email protected]")); assertNotNull(ar.getUri()); } }
Add test for no HTTP_AUTHORIZATION header at all
from utils.testcase import EndpointTestCase from rest_framework import status from rest_framework.test import APIClient from django.utils.translation import ugettext_lazy as _ import sure class TestUtils(EndpointTestCase): def test_fail_authentication(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='Bearer ' + 'wrongToken') response = client.get('/room') response.status_code.should.eql(status.HTTP_401_UNAUTHORIZED) response.data.should.eql({'detail': _('Invalid token.')}) def test_bad_formatted_authentication(self): client = APIClient() response = client.get('/room') response.status_code.should.eql(status.HTTP_401_UNAUTHORIZED) response.data.should.eql({'detail': _('Invalid token header. No credentials provided.')}) client.credentials(HTTP_AUTHORIZATION='Bearer') response = client.get('/room') response.status_code.should.eql(status.HTTP_401_UNAUTHORIZED) response.data.should.eql({'detail': _('Invalid token header. No credentials provided.')}) client.credentials(HTTP_AUTHORIZATION='Bearer token1 token2') response = client.get('/room') response.status_code.should.eql(status.HTTP_401_UNAUTHORIZED) response.data.should.eql({'detail': _('Invalid token header. Token string should not contain spaces.')}) client.credentials(HTTP_AUTHORIZATION='token') response = client.get('/room') response.status_code.should.eql(status.HTTP_401_UNAUTHORIZED) response.data.should.eql({'detail': _('Invalid token header. No credentials provided.')})
from utils.testcase import EndpointTestCase from rest_framework import status from rest_framework.test import APIClient from django.utils.translation import ugettext_lazy as _ import sure class TestUtils(EndpointTestCase): def test_fail_authentication(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='Bearer ' + 'wrongToken') response = client.get('/room') response.status_code.should.eql(status.HTTP_401_UNAUTHORIZED) response.data.should.eql({'detail': _('Invalid token.')}) def test_bad_formatted_authentication(self): client = APIClient() client.credentials(HTTP_AUTHORIZATION='Bearer') response = client.get('/room') response.status_code.should.eql(status.HTTP_401_UNAUTHORIZED) response.data.should.eql({'detail': _('Invalid token header. No credentials provided.')}) client.credentials(HTTP_AUTHORIZATION='Bearer token1 token2') response = client.get('/room') response.status_code.should.eql(status.HTTP_401_UNAUTHORIZED) response.data.should.eql({'detail': _('Invalid token header. Token string should not contain spaces.')}) client.credentials(HTTP_AUTHORIZATION='token') response = client.get('/room') response.status_code.should.eql(status.HTTP_401_UNAUTHORIZED) response.data.should.eql({'detail': _('Invalid token header. No credentials provided.')})
Fix transparent issue of search input
module.exports = { inputStyle: { "backgroundColor": "white", "border": `1px solid transparent`, "borderRadius": `1px`, "boxShadow": `0 2px 6px rgba(0, 0, 0, 0.3)`, "boxSizing": `border-box`, "MozBoxSizing": `border-box`, "fontSize": `14px`, "height": `32px`, "marginTop": `27px`, "outline": `none`, "padding": `0 12px`, "textOverflow": `ellipses`, "width": `400px`, }, divStatusStyle: { position: 'absolute', top: '15px', right: '15px', }, divAppbaseStyle: { position: 'absolute', width: '200px', bottom: '15px', left: '0px', right: '0px', marginLeft: 'auto', marginRight: 'auto', textAlign: 'center', }, divContainer: { padding: "1em" }, divListTag: { backgroundColor: "#ddd", margin: "5px", padding: "5px" }, divListItem: { margin: "5px", padding: "3px" }, divScroll: { overflow: "auto", height: "400px", width: "100%", margin: "5px", }, };
module.exports = { inputStyle: { "border": `1px solid transparent`, "borderRadius": `1px`, "boxShadow": `0 2px 6px rgba(0, 0, 0, 0.3)`, "boxSizing": `border-box`, "MozBoxSizing": `border-box`, "fontSize": `14px`, "height": `32px`, "marginTop": `27px`, "outline": `none`, "padding": `0 12px`, "textOverflow": `ellipses`, "width": `400px`, }, divStatusStyle: { position: 'absolute', top: '15px', right: '15px', }, divAppbaseStyle: { position: 'absolute', width: '200px', bottom: '15px', left: '0px', right: '0px', marginLeft: 'auto', marginRight: 'auto', textAlign: 'center', }, divContainer: { padding: "1em" }, divListTag: { backgroundColor: "#ddd", margin: "5px", padding: "5px" }, divListItem: { margin: "5px", padding: "3px" }, divScroll: { overflow: "auto", height: "400px", width: "100%", margin: "5px", }, };
Replace pre-commit test patch decorators with setUp/tearDown patching.
import unittest from mock import Mock, patch from captainhook import pre_commit class TestMain(unittest.TestCase): def setUp(self): self.get_files_patch = patch('captainhook.pre_commit.get_files') get_files = self.get_files_patch.start() get_files.return_value = ['file_one'] self.hook_config_patch = patch('captainhook.pre_commit.HookConfig') self.HookConfig = self.hook_config_patch.start() self.HookConfig().is_enabled.return_value = True self.HookConfig().arguments.return_value = '' self.testmod = Mock() self.testmod.run.return_value = None self.checks_patch = patch('captainhook.pre_commit.checks') checks = self.checks_patch.start() checks.return_value = [("testmod", self.testmod)] def tearDown(self): self.checks_patch.stop() self.hook_config_patch.stop() self.get_files_patch.stop() def test_calling_run_without_args(self): result = pre_commit.main() self.assertEquals(result, 0) self.testmod.run.assert_called_with(['file_one']) def test_calling_run_with_args(self): self.HookConfig().arguments.return_value = 'yep' result = pre_commit.main() self.assertEquals(result, 0) self.testmod.run.assert_called_with(['file_one'], 'yep')
import unittest from mock import Mock, patch from captainhook import pre_commit class TestMain(unittest.TestCase): @patch('captainhook.pre_commit.get_files') @patch('captainhook.pre_commit.HookConfig') @patch('captainhook.pre_commit.checks') def test_calling_run_without_args(self, checks, HookConfig, get_files): get_files.return_value = ['file_one'] HookConfig().is_enabled.return_value = True HookConfig().arguments.return_value = '' testmod = Mock() testmod.run.return_value = None checks.return_value = [("testmod", testmod)] result = pre_commit.main() self.assertEquals(result, 0) testmod.run.assert_called_with(['file_one']) @patch('captainhook.pre_commit.get_files') @patch('captainhook.pre_commit.HookConfig') @patch('captainhook.pre_commit.checks') def test_calling_run_with_args(self, checks, HookConfig, get_files): get_files.return_value = ['file_one'] HookConfig().is_enabled.return_value = True HookConfig().arguments.return_value = 'yep' testmod = Mock() testmod.run.return_value = None checks.return_value = [("testmod", testmod)] result = pre_commit.main() self.assertEquals(result, 0) testmod.run.assert_called_with(['file_one'], 'yep')
Fix Trove classifiers to allow PyPI upload
from distutils.core import setup from pexpect import __version__ setup (name='pexpect', version=__version__, py_modules=['pxssh', 'fdpexpect', 'FSM', 'screen', 'ANSI'], packages=['pexpect'], description='Pexpect allows easy control of interactive console applications.', author='Noah Spurrier; Thomas Kluyver; Jeff Quast', author_email='[email protected]; [email protected]; [email protected]', url='http://pexpect.readthedocs.org/', license='ISC license', platforms='UNIX', classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: POSIX', 'Operating System :: MacOS :: MacOS X', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', 'Topic :: System', 'Topic :: System :: Archiving :: Packaging', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Shells', 'Topic :: System :: Software Distribution', 'Topic :: Terminals', ], )
from distutils.core import setup from pexpect import __version__ setup (name='pexpect', version=__version__, py_modules=['pxssh', 'fdpexpect', 'FSM', 'screen', 'ANSI'], packages=['pexpect'], description='Pexpect allows easy control of interactive console applications.', author='Noah Spurrier; Thomas Kluyver; Jeff Quast', author_email='[email protected]; [email protected]; [email protected]', url='http://pexpect.readthedocs.org/', license='ISC license', platforms='UNIX', classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Quality Engineers', 'License :: OSI Approved :: ISC License (ISCL)', 'Operating System :: POSIX', 'Operating System :: MacOS :: MacOS X', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', 'Topic :: System, System :: Archiving :: Packaging, System :: Installation/Setup', 'Topic :: System :: Shells', 'Topic :: System :: Software Distribution', 'Topic :: Terminals', ], )
Validate language input for settings page
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Image; use Storage; class SettingsController extends Controller { public function index() { $user = Auth::user(); return view('settings', [ 'languages' => config('app.locales'), 'tags' => $user->tags ]); } public function store(Request $request) { $request->validate([ 'avatar' => 'nullable|mimes:jpeg,jpg,png,gif', // TODO VALIDATE OTHER FIELDS 'language' => 'required|in:' . implode(',', array_keys(config('app.locales'))) ]); $user = Auth::user(); if ($request->hasFile('avatar')) { $file = $request->file('avatar'); $fileName = $file->hashName(); $image = Image::make($file) ->fit(500); Storage::put('public/avatars/' . $fileName, (string) $image->encode()); $user->avatar = $fileName; } $user->name = $request->input('name'); $user->email = $request->input('email'); $user->language = $request->input('language'); $user->save(); return redirect()->route('settings'); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Image; use Storage; class SettingsController extends Controller { public function index() { $user = Auth::user(); return view('settings', [ 'languages' => config('app.locales'), 'tags' => $user->tags ]); } public function store(Request $request) { $request->validate([ 'avatar' => 'nullable|mimes:jpeg,jpg,png,gif' // TODO VALIDATE OTHER FIELDS ]); $user = Auth::user(); if ($request->hasFile('avatar')) { $file = $request->file('avatar'); $fileName = $file->hashName(); $image = Image::make($file) ->fit(500); Storage::put('public/avatars/' . $fileName, (string) $image->encode()); $user->avatar = $fileName; } $user->name = $request->input('name'); $user->email = $request->input('email'); $user->language = $request->input('language'); $user->save(); return redirect()->route('settings'); } }
Fix direct assignment to the forward side of a many-to-many
from django.db import migrations PERM_INITIAL = {'wsparcie': ('can_add_record', 'can_change_own_record', 'can_view', 'can_view_all' ), 'obserwator': ( 'can_view', 'can_view_all'), 'klient': ('can_add_record', 'can_send_to_client', 'can_view'), 'admin': '__all__', } def get_perm(p, codenames=None): qs = p.objects.filter(**{'content_type__app_label': 'cases', 'content_type__model': 'case'}) if codenames is not '__all__': qs = qs.filter(codename__in=codenames) return qs.all() def add_groups(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. PermissionGroup = apps.get_model("cases", "PermissionGroup") Permission = apps.get_model('auth', 'Permission') for name, codenames in PERM_INITIAL.items(): p, _ = PermissionGroup.objects.get_or_create(name=name) p.permissions.set(get_perm(Permission, codenames)) p.save() class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('cases', '0020_permissiongroup'), ] operations = [ migrations.RunPython(add_groups), ]
from django.db import migrations PERM_INITIAL = {'wsparcie': ('can_add_record', 'can_change_own_record', 'can_view', 'can_view_all' ), 'obserwator': ( 'can_view', 'can_view_all'), 'klient': ('can_add_record', 'can_send_to_client', 'can_view'), 'admin': '__all__', } def get_perm(p, codenames=None): qs = p.objects.filter(**{'content_type__app_label': 'cases', 'content_type__model': 'case'}) if codenames is not '__all__': qs = qs.filter(codename__in=codenames) return qs.all() def add_groups(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. PermissionGroup = apps.get_model("cases", "PermissionGroup") Permission = apps.get_model('auth', 'Permission') for name, codenames in PERM_INITIAL.items(): p, _ = PermissionGroup.objects.get_or_create(name=name) p.permissions = get_perm(Permission, codenames) p.save() class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('cases', '0020_permissiongroup'), ] operations = [ migrations.RunPython(add_groups), ]
Fix extra output in tests
<?php namespace Rocketeer\Abstracts\Strategies; use Mockery\MockInterface; use Rocketeer\TestCases\RocketeerTestCase; class AbstractStrategyTest extends RocketeerTestCase { public function testCanCheckForManifestWithoutServer() { $this->app['path.base'] = realpath(__DIR__.'/../../..'); $this->swapConfig(array( 'paths.app' => realpath(__DIR__.'/../../..'), )); $this->usesComposer(false); $strategy = $this->builder->buildStrategy('Dependencies', 'Composer'); $this->assertTrue($strategy->isExecutable()); } public function testCanDisplayStatus() { $this->expectOutputRegex('#<fg=cyan>\w+</fg=cyan> \| <info>Deploy/Clone</info> <comment>\(.+\)</comment>#'); $this->mock('rocketeer.command', 'Command', function (MockInterface $mock) { return $mock->shouldReceive('line')->andReturnUsing(function ($input) { echo $input; }); }); $strategy = $this->builder->buildStrategy('Deploy', 'Clone'); $strategy->displayStatus(); } public function testCanGetIdentifier() { $strategy = $this->builder->buildStrategy('Dependencies'); $this->assertEquals('strategies.dependencies.polyglot', $strategy->getIdentifier()); } public function testCanFireEvents() { $this->pretend(); $this->expectFiredEvent('strategies.dependencies.composer.before'); $composer = $this->builder->buildStrategy('Dependencies', 'Composer'); $composer->install(); } }
<?php namespace Rocketeer\Abstracts\Strategies; use Mockery\MockInterface; use Rocketeer\TestCases\RocketeerTestCase; class AbstractStrategyTest extends RocketeerTestCase { public function testCanCheckForManifestWithoutServer() { $this->app['path.base'] = realpath(__DIR__.'/../../..'); $this->swapConfig(array( 'paths.app' => realpath(__DIR__.'/../../..'), )); $this->usesComposer(false); $strategy = $this->builder->buildStrategy('Dependencies', 'Composer'); $this->assertTrue($strategy->isExecutable()); } public function testCanDisplayStatus() { $this->expectOutputRegex('#<fg=cyan>\w+</fg=cyan> \| <info>Deploy/Clone</info> <comment>\(.+\)</comment>#'); $this->mock('rocketeer.command', 'Command', function (MockInterface $mock) { return $mock->shouldReceive('line')->andReturnUsing(function ($input) { echo $input; }); }); $strategy = $this->builder->buildStrategy('Deploy', 'Clone'); $strategy->displayStatus(); } public function testCanGetIdentifier() { $strategy = $this->builder->buildStrategy('Dependencies'); $this->assertEquals('strategies.dependencies.polyglot', $strategy->getIdentifier()); } public function testCanFireEvents() { $this->expectFiredEvent('strategies.dependencies.composer.before'); $composer = $this->builder->buildStrategy('Dependencies', 'Composer'); $composer->install(); } }
Use Object.entries instead of Object.keys
import * as path from 'path'; import {fs} from 'node-promise-es6'; import * as fse from 'fs-extra-promise-es6'; export default class { constructor(basePath) { this.basePath = path.resolve(basePath); } async create() { await fse.mkdirs(this.basePath); } path(...components) { return path.resolve(this.basePath, ...components); } async remove() { await fse.remove(this.path()); } async write(files) { for (const [filePath, fileContents] of Object.entries(files)) { const absoluteFilePath = this.path(filePath); await fse.ensureFile(absoluteFilePath); if (typeof fileContents === 'object') { await fse.writeJson(absoluteFilePath, fileContents); } else { const reindentedFileContents = fileContents .split('\n') .filter((line, index, array) => index !== 0 && index !== array.length - 1 || line.trim() !== '') .reduce(({indentation, contents}, line) => { const whitespaceToRemove = Number.isInteger(indentation) ? indentation : line.match(/^\s*/)[0].length; return { indentation: whitespaceToRemove, contents: `${contents}${line.slice(whitespaceToRemove)}\n` }; }, {contents: ''}).contents; await fs.writeFile(absoluteFilePath, reindentedFileContents); } } } }
import * as path from 'path'; import {fs} from 'node-promise-es6'; import * as fse from 'fs-extra-promise-es6'; export default class { constructor(basePath) { this.basePath = path.resolve(basePath); } async create() { await fse.mkdirs(this.basePath); } path(...components) { return path.resolve(this.basePath, ...components); } async remove() { await fse.remove(this.path()); } async write(files) { for (const file of Object.keys(files)) { const filePath = this.path(file); const fileContents = files[file]; await fse.ensureFile(filePath); if (typeof fileContents === 'object') { await fse.writeJson(filePath, fileContents); } else { const reindentedFileContents = fileContents .split('\n') .filter((line, index, array) => index !== 0 && index !== array.length - 1 || line.trim() !== '') .reduce(({indentation, contents}, line) => { const whitespaceToRemove = Number.isInteger(indentation) ? indentation : line.match(/^\s*/)[0].length; return { indentation: whitespaceToRemove, contents: `${contents}${line.slice(whitespaceToRemove)}\n` }; }, {contents: ''}).contents; await fs.writeFile(filePath, reindentedFileContents); } } } }
Declare variables in bezzier.js for loops
define(['../math.js', '../../app/directives/graph_sketcher/GraphUtils.js'], function(m, graphUtils) { return { numOfPts: 100, lineStyle: function(pts) { let n = pts.length - 1; let comb = []; let r; for (let r = 0; r <= n; r += 1) { // from the other math library!!!! not the same as Math!!!! comb.push(m.combinations(n, r)); } let step = 1 / this.numOfPts; let bezier = []; let u; let i; let tmp1; let tmp2; let tmp3; for (let i = 0; i < this.numOfPts; i += 1) { u = i * step; let sx = 0; let sy = 0; for (r = 0; r <= n; r += 1) { tmp1 = Math.pow(u, r); tmp2 = Math.pow(1 - u, n - r); tmp3 = comb[r] * tmp1 * tmp2; sx += tmp3 * pts[r].x; sy += tmp3 * pts[r].y; } bezier.push(graphUtils.createPoint(sx, sy, i)); } bezier.push(pts[pts.length - 1]); return bezier; } } });
define(['../math.js', '../../app/directives/graph_sketcher/GraphUtils.js'], function(m, graphUtils) { return { numOfPts: 100, lineStyle: function(pts) { let n = pts.length - 1; let comb = []; let r; for (r = 0; r <= n; r += 1) { // from the other math library!!!! not the same as Math!!!! comb.push(m.combinations(n, r)); } let step = 1 / this.numOfPts; let bezier = []; let u; let i; let tmp1; let tmp2; let tmp3; for (i = 0; i < this.numOfPts; i += 1) { u = i * step; let sx = 0; let sy = 0; for (r = 0; r <= n; r += 1) { tmp1 = Math.pow(u, r); tmp2 = Math.pow(1 - u, n - r); tmp3 = comb[r] * tmp1 * tmp2; sx += tmp3 * pts[r].x; sy += tmp3 * pts[r].y; } bezier.push(graphUtils.createPoint(sx, sy, i)); } bezier.push(pts[pts.length - 1]); return bezier; } } });
Add the wasm-unsafe-eval keyword for CSP
<?php /* * This file is part of the Nelmio SecurityBundle. * * (c) Nelmio <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Nelmio\SecurityBundle\ContentSecurityPolicy; class ContentSecurityPolicyParser { protected $keywords = array( 'self', 'unsafe-inline', 'unsafe-eval', 'wasm-unsafe-eval', 'strict-dynamic', 'unsafe-hashes', 'report-sample', 'unsafe-allow-redirects', 'none', ); /** * @param array $sourceList * * @return string */ public function parseSourceList($sourceList) { if (!is_array($sourceList)) { return $sourceList; } $sourceList = $this->quoteKeywords($sourceList); return implode(' ', $sourceList); } /** * @param array $sourceList * * @return array */ protected function quoteKeywords(array $sourceList) { $keywords = $this->keywords; return array_map( function ($source) use ($keywords) { if (in_array($source, $keywords, true)) { return sprintf("'%s'", $source); } return $source; }, $sourceList ); } }
<?php /* * This file is part of the Nelmio SecurityBundle. * * (c) Nelmio <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Nelmio\SecurityBundle\ContentSecurityPolicy; class ContentSecurityPolicyParser { protected $keywords = array( 'self', 'unsafe-inline', 'unsafe-eval', 'strict-dynamic', 'unsafe-hashes', 'report-sample', 'unsafe-allow-redirects', 'none', ); /** * @param array $sourceList * * @return string */ public function parseSourceList($sourceList) { if (!is_array($sourceList)) { return $sourceList; } $sourceList = $this->quoteKeywords($sourceList); return implode(' ', $sourceList); } /** * @param array $sourceList * * @return array */ protected function quoteKeywords(array $sourceList) { $keywords = $this->keywords; return array_map( function ($source) use ($keywords) { if (in_array($source, $keywords, true)) { return sprintf("'%s'", $source); } return $source; }, $sourceList ); } }
Create unit watcher grunt task
/*jshint camelcase:false */ module.exports = function (grunt) { // Load all grunt tasks require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ release: { options: { bump: true, //default: true file: 'package.json', //default: package.json add: true, //default: true commit: true, //default: true tag: true, //default: true push: true, //default: true pushTags: true, //default: true npm: true, //default: true tagName: 'v<%= version %>', //default: '<%= version %>' commitMessage: 'releasing v<%= version %>', //default: 'release <%= version %>' tagMessage: 'v<%= version %>' //default: 'Version <%= version %>' } }, jshint: { options: { jshintrc: true, }, lib: ['lib/**/*.js'], }, watch: { spec: { files: [ 'lib/**/*.js', 'test/**/*.js', ], tasks: ['mochaTest:spec'], }, unit: { files: [ 'lib/**/*.js', 'test/**/*.js', ], tasks: ['mochaTest:unit'], }, }, mochaTest: { options: { reporter: 'spec', }, spec: { src: ['test/spec/*.js'] }, unit: { src: ['test/unit/*.js'] } }, }); // Default task. grunt.registerTask('default', []); };
/*jshint camelcase:false */ module.exports = function (grunt) { // Load all grunt tasks require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ release: { options: { bump: true, //default: true file: 'package.json', //default: package.json add: true, //default: true commit: true, //default: true tag: true, //default: true push: true, //default: true pushTags: true, //default: true npm: true, //default: true tagName: 'v<%= version %>', //default: '<%= version %>' commitMessage: 'releasing v<%= version %>', //default: 'release <%= version %>' tagMessage: 'v<%= version %>' //default: 'Version <%= version %>' } }, jshint: { options: { jshintrc: true, }, lib: ['lib/**/*.js'], }, watch: { spec: { files: [ 'lib/**/*.js', 'test/**/*.js', ], tasks: ['mochaTest:spec'], }, }, mochaTest: { options: { reporter: 'spec', }, spec: { src: ['test/spec/*.js'] } }, }); // Default task. grunt.registerTask('default', []); };
Allow to do app->make with parameters to pass to the constructor of guzzle client
<?php namespace GuzzleHttp\Subscriber\Log\Support; use DebugBar\DataCollector\ExceptionsCollector; use DebugBar\DebugBar; use GuzzleHttp\Client; use GuzzleHttp\Subscriber\Log\LogSubscriber; use GuzzleHttp\Subscriber\Log\DebugbarSubscriber; use Psr\Log\LoggerInterface; use Illuminate\Support\ServiceProvider as BaseServiceProvider; use DebugBar\DataCollector\TimeDataCollector; class ServiceProvider extends BaseServiceProvider { /** * Register method */ public function register() { $this->registerGuzzleSubscriber(); } /** * Register a log subscriber on every Guzzle client. */ private function registerGuzzleSubscriber() { // Register a log subscriber with every Guzzle client. $this->app->bind('GuzzleHttp\Client', function ($app, $params) { // Create new client. $client = new Client(array_shift($params) ?: []); /** @var DebugBar $debugBar */ $debugBar = $this->app->make('debugbar'); /** @var LoggerInterface $logger */ $logger = $debugBar->getCollector('messages'); /** @var TimeDataCollector $timeline */ $timeline = $debugBar->getCollector('time'); /** @var ExceptionsCollector $exceptions */ $exceptions = $debugBar->getCollector('exceptions'); // Attach event subscribers. $client->getEmitter()->attach(new LogSubscriber($logger)); $client->getEmitter()->attach(new DebugbarSubscriber($timeline, $exceptions)); // Return configured client. return $client; }); } }
<?php namespace GuzzleHttp\Subscriber\Log\Support; use DebugBar\DataCollector\ExceptionsCollector; use DebugBar\DebugBar; use GuzzleHttp\Client; use GuzzleHttp\Subscriber\Log\LogSubscriber; use GuzzleHttp\Subscriber\Log\DebugbarSubscriber; use Psr\Log\LoggerInterface; use Illuminate\Support\ServiceProvider as BaseServiceProvider; use DebugBar\DataCollector\TimeDataCollector; class ServiceProvider extends BaseServiceProvider { /** * Register method */ public function register() { $this->registerGuzzleSubscriber(); } /** * Register a log subscriber on every Guzzle client. */ private function registerGuzzleSubscriber() { // Register a log subscriber with every Guzzle client. $this->app->bind('GuzzleHttp\Client', function () { // Create new client. $client = new Client; /** @var DebugBar $debugBar */ $debugBar = $this->app->make('debugbar'); /** @var LoggerInterface $logger */ $logger = $debugBar->getCollector('messages'); /** @var TimeDataCollector $timeline */ $timeline = $debugBar->getCollector('time'); /** @var ExceptionsCollector $exceptions */ $exceptions = $debugBar->getCollector('exceptions'); // Attach event subscribers. $client->getEmitter()->attach(new LogSubscriber($logger)); $client->getEmitter()->attach(new DebugbarSubscriber($timeline, $exceptions)); // Return configured client. return $client; }); } }
Fix: Remove visibility check, use the hide category functionality instead
<div class="panel panel-default qanda-panel"> <div class="panel-heading"> <?php echo $group; ?> </div> <div class="list-group"> <?php foreach($categories as $category) { ?> <a href="<?php echo $category['link']; ?>" class="list-group-item"> <b class="list-group-item-heading"><?php echo $category['name']; ?></b> <p class="list-group-item-text"><?php echo $category['description']; ?></p> </a> <small> <ul> <?php $questions = \humhub\modules\questionanswer\models\Question::find() ->contentContainer($category['space']) ->andFilterWhere(['post_type' => 'question']) ->orderBy('created_at DESC') ->limit(3) ->all(); foreach($questions as $q) { echo "<li>"; echo \yii\helpers\Html::a(\yii\helpers\Html::encode($q['post_title']), \humhub\modules\questionanswer\helpers\Url::createUrl('view', [ 'id'=> $q['id'], 'sguid' => $category['space']->guid ])); echo "</li>"; } ?> </ul> </small> <?php } ?> </div> </div>
<div class="panel panel-default qanda-panel"> <div class="panel-heading"> <?php echo $group; ?> </div> <div class="list-group"> <?php foreach($categories as $category) { ?> <?php if($category['space']->visibility > 0) { ?> <a href="<?php echo $category['link']; ?>" class="list-group-item"> <b class="list-group-item-heading"><?php echo $category['name']; ?></b> <p class="list-group-item-text"><?php echo $category['description']; ?></p> </a> <small> <ul> <?php $questions = \humhub\modules\questionanswer\models\Question::find() ->contentContainer($category['space']) ->andFilterWhere(['post_type' => 'question']) ->orderBy('created_at DESC') ->limit(3) ->all(); foreach($questions as $q) { echo "<li>"; echo \yii\helpers\Html::a(\yii\helpers\Html::encode($q['post_title']), \humhub\modules\questionanswer\helpers\Url::createUrl('view', [ 'id'=> $q['id'], 'sguid' => $category['space']->guid ])); echo "</li>"; } ?> </ul> </small> <?php } ?> <?php } ?> </div> </div>
Make press-tip work on hover
import Tooltip from 'tooltip.js'; import './press-tip.scss'; export function PressTip() { 'ngInject'; return { restrict: 'A', link($scope, $element, $attrs) { let tooltip = null; let timer = null; function showTip() { if (!tooltip) { let title = $attrs.pressTip; if ($attrs.pressTipTitle) { title = `<h2>${$attrs.pressTipTitle}</h2>${title}`; } tooltip = new Tooltip($element[0], { placement: 'top', // or bottom, left, right, and variations title, html: true, trigger: 'manual', container: 'body' }); } tooltip.show(); } $element.on('mouseenter', (e) => { timer = setTimeout(() => { showTip(); }, 300); }); $element.on('mousedown touchstart', (e) => { e.preventDefault(); showTip(); }); $element.on('mouseup mouseleave touchend', (e) => { e.preventDefault(); if (tooltip) { tooltip.hide(); } clearTimeout(timer); }); $scope.$on('$destroy', () => { if (tooltip) { tooltip.dispose(); tooltip = null; } }); } }; }
import Tooltip from 'tooltip.js'; import './press-tip.scss'; export function PressTip() { 'ngInject'; return { restrict: 'A', link($scope, $element, $attrs) { let tooltip = null; function showTip() { if (!tooltip) { let title = $attrs.pressTip; if ($attrs.pressTipTitle) { title = `<h2>${$attrs.pressTipTitle}</h2>${title}`; } tooltip = new Tooltip($element[0], { placement: 'top', // or bottom, left, right, and variations title, html: true, trigger: 'manual', container: 'body' }); } tooltip.show(); } $element.on('mousedown touchstart', (e) => { e.preventDefault(); showTip(); }); $element.on('mouseup mouseleave touchend', (e) => { e.preventDefault(); if (tooltip) { tooltip.hide(); } }); $scope.$on('$destroy', () => { if (tooltip) { tooltip.dispose(); tooltip = null; } }); } }; }
Return $this after adding a tag
<?php namespace SlmMail\Mail\Message\Provider; use SlmMail\Mail\Message\ProvidesOptions; use SlmMail\Mail\Message\ProvidesTags; use Zend\Mail\Message; class Mailgun extends Message { use ProvidesOptions; const TAG_LIMIT = 3; /** * @var array */ protected $tags = array(); /** * Get all tags for this message * * @return array */ public function getTags() { return $this->tags; } /** * Set all tags for this message * * @param array $tags * @return self */ public function setTags(array $tags) { if (count($tags) > self::TAG_LIMIT) { throw new Exception\InvalidArgumentException(sprintf( 'Mailgun only allows up to %s tags', self::TAG_LIMIT )); } $this->tags = $tags; return $this; } /** * Add a tag to this message * * @param string $tag * @return self */ public function addTag($tag) { if (count($this->tags)+1 > self::TAG_LIMIT) { throw new Exception\InvalidArgumentException(sprintf( 'Mailgun only allows up to %s tags', self::TAG_LIMIT )); } $this->tags[] = (string) $tag; return $this; } }
<?php namespace SlmMail\Mail\Message\Provider; use SlmMail\Mail\Message\ProvidesOptions; use SlmMail\Mail\Message\ProvidesTags; use Zend\Mail\Message; class Mailgun extends Message { use ProvidesOptions; const TAG_LIMIT = 3; /** * @var array */ protected $tags = array(); /** * Get all tags for this message * * @return array */ public function getTags() { return $this->tags; } /** * Set all tags for this message * * @param array $tags * @return self */ public function setTags(array $tags) { if (count($tags) > self::TAG_LIMIT) { throw new Exception\InvalidArgumentException(sprintf( 'Mailgun only allows up to %s tags', self::TAG_LIMIT )); } $this->tags = $tags; return $this; } /** * Add a tag to this message * * @param string $tag */ public function addTag($tag) { if (count($this->tags)+1 > self::TAG_LIMIT) { throw new Exception\InvalidArgumentException(sprintf( 'Mailgun only allows up to %s tags', self::TAG_LIMIT )); } $this->tags[] = (string) $tag; } }
Add space before each elseif opening parenthesis.
<?php namespace Sil\PhpEnv; class Env { /** * Retrieve the value of the specified environment variable, translating * values of 'true', 'false', and 'null' to their actual non-string values. * * PHP's built-in "getenv()" function returns a string (or false, if the * environment variable is not set). If the value is 'false', then it will * be returned as the string "false", which evaluates to true. This function * is to check for that kind of string value and return the actual value * that it refers to. * * NOTE: If the specified environment variable is not set and no default * value was provided, this function returns null (rather returning false * the way getenv() does). * * @param string $name The name of the desired environment variable. * @param mixed $default The default value to return if no such environment * variable exists. * @return mixed The resulting value (if set), or the given default value * (if any, otherwise null). */ public static function get($name, $default = null) { $value = \getenv($name); if ($value === false) { return $default; } elseif ($value == 'false') { return false; } elseif ($value == 'true') { return true; } elseif ($value == 'null') { return null; } else { return $value; } } }
<?php namespace Sil\PhpEnv; class Env { /** * Retrieve the value of the specified environment variable, translating * values of 'true', 'false', and 'null' to their actual non-string values. * * PHP's built-in "getenv()" function returns a string (or false, if the * environment variable is not set). If the value is 'false', then it will * be returned as the string "false", which evaluates to true. This function * is to check for that kind of string value and return the actual value * that it refers to. * * NOTE: If the specified environment variable is not set and no default * value was provided, this function returns null (rather returning false * the way getenv() does). * * @param string $name The name of the desired environment variable. * @param mixed $default The default value to return if no such environment * variable exists. * @return mixed The resulting value (if set), or the given default value * (if any, otherwise null). */ public static function get($name, $default = null) { $value = \getenv($name); if ($value === false) { return $default; } elseif($value == 'false') { return false; } elseif($value == 'true') { return true; } elseif($value == 'null') { return null; } else { return $value; } } }
Check for null input; there is no input on page load
import Component from '@ember/component'; import { empty, or } from '@ember/object/computed'; export default Component.extend({ emptyName: empty('api_token.name'), disableCreate: or('api_token.isSaving', 'emptyName'), serverError: null, didInsertElement() { let input = this.element.querySelector('input'); if (input && input.focus) { input.focus(); } }, actions: { async saveToken() { try { await this.api_token.save(); this.set('serverError', null); } catch (err) { let msg; if (err.errors && err.errors[0] && err.errors[0].detail) { msg = `An error occurred while saving this token, ${err.errors[0].detail}`; } else { msg = 'An unknown error occurred while saving this token'; } this.set('serverError', msg); } }, async revokeToken() { try { await this.api_token.destroyRecord(); } catch (err) { let msg; if (err.errors && err.errors[0] && err.errors[0].detail) { msg = `An error occurred while revoking this token, ${err.errors[0].detail}`; } else { msg = 'An unknown error occurred while revoking this token'; } this.set('serverError', msg); } }, }, });
import Component from '@ember/component'; import { empty, or } from '@ember/object/computed'; export default Component.extend({ emptyName: empty('api_token.name'), disableCreate: or('api_token.isSaving', 'emptyName'), serverError: null, didInsertElement() { let input = this.element.querySelector('input'); if (input.focus) { input.focus(); } }, actions: { async saveToken() { try { await this.api_token.save(); this.set('serverError', null); } catch (err) { let msg; if (err.errors && err.errors[0] && err.errors[0].detail) { msg = `An error occurred while saving this token, ${err.errors[0].detail}`; } else { msg = 'An unknown error occurred while saving this token'; } this.set('serverError', msg); } }, async revokeToken() { try { await this.api_token.destroyRecord(); } catch (err) { let msg; if (err.errors && err.errors[0] && err.errors[0].detail) { msg = `An error occurred while revoking this token, ${err.errors[0].detail}`; } else { msg = 'An unknown error occurred while revoking this token'; } this.set('serverError', msg); } }, }, });
Change case of type hint.
<?php namespace Math\Functions; /** * Arithmetic of functions. These functions return functions themselves. */ class Arithmetic { /** * Adds any number of single variable (callback) functions {f(x)}. Returns * the sum as a callback function. * * @param callable ... $args Two or more single-variable callback functions * * @return callable Sum of the input functions */ public static function add(callable ...$args) { $sum = function ($x, ... $args) { $function = 0; foreach ($args as $arg) { $function += $arg($x); } return $function; }; return function ($x) use ($args, $sum) { return call_user_func_array($sum, array_merge([$x], $args)); }; } /** * Multiplies any number of single variable (callback) functions {f(x)}. * Returns the product as a callback function. * * @param callable ... $args Two or more single-variable callback functions * * @return callable Product of the input functions */ public static function multiply(callable ...$args) { $product = function ($x, ... $args) { $function = 1; foreach ($args as $arg) { $function *= $arg($x); } return $function; }; return function ($x) use ($args, $product) { return call_user_func_array($product, array_merge([$x], $args)); }; } }
<?php namespace Math\Functions; /** * Arithmetic of functions. These functions return functions themselves. */ class Arithmetic { /** * Adds any number of single variable (callback) functions {f(x)}. Returns * the sum as a callback function. * * @param callable ... $args Two or more single-variable callback functions * * @return callable Sum of the input functions */ public static function add(Callable ...$args) { $sum = function ($x, ... $args) { $function = 0; foreach ($args as $arg) { $function += $arg($x); } return $function; }; return function ($x) use ($args, $sum) { return call_user_func_array($sum, array_merge([$x], $args)); }; } /** * Multiplies any number of single variable (callback) functions {f(x)}. * Returns the product as a callback function. * * @param callable ... $args Two or more single-variable callback functions * * @return callable Product of the input functions */ public static function multiply(Callable ...$args) { $product = function ($x, ... $args) { $function = 1; foreach ($args as $arg) { $function *= $arg($x); } return $function; }; return function ($x) use ($args, $product) { return call_user_func_array($product, array_merge([$x], $args)); }; } }
Allow YQL module to be embedded in a loop
# pipeyql.py # import urllib import urllib2 from xml.etree import cElementTree as ElementTree from pipe2py import util def pipe_yql(context, _INPUT, conf, **kwargs): """This source issues YQL queries. Keyword arguments: context -- pipeline context _INPUT -- not used conf: yqlquery -- YQL query #todo handle envURL Yields (_OUTPUT): query results """ url = "http://query.yahooapis.com/v1/public/yql" #todo get from a config/env file for item in _INPUT: if "subkey" in conf['yqlquery']: yql = item[conf['yqlquery']['subkey']] else: yql = util.get_value(conf['yqlquery'], kwargs) query = urllib.urlencode({'q':yql, #note: we use the default format of xml since json loses some structure #todo diagnostics=true e.g. if context.test #todo consider paging for large result sets }) req = urllib2.Request(url, query) response = urllib2.urlopen(req) #Parse the response ft = ElementTree.parse(response) if context.verbose: print "pipe_yql loading xml:", yql root = ft.getroot() #note: query also has row count results = root.find('results') #Convert xml into generation of dicts for element in results.getchildren(): i = util.xml_to_dict(element) yield i if item == True: #i.e. this is being fed forever, i.e. not in a loop, so we just yield our item once break
# pipeyql.py # import urllib import urllib2 from xml.etree import cElementTree as ElementTree from pipe2py import util def pipe_yql(context, _INPUT, conf, **kwargs): """This source issues YQL queries. Keyword arguments: context -- pipeline context _INPUT -- not used conf: yqlquery -- YQL query #todo handle envURL Yields (_OUTPUT): query results """ url = "http://query.yahooapis.com/v1/public/yql" #todo get from a config/env file yql = util.get_value(conf['yqlquery'], kwargs) query = urllib.urlencode({'q':yql, #note: we use the default format of xml since json loses some structure #todo diagnostics=true e.g. if context.test #todo consider paging for large result sets }) req = urllib2.Request(url, query) response = urllib2.urlopen(req) #Parse the response ft = ElementTree.parse(response) if context.verbose: print "pipe_yql loading xml:", yql root = ft.getroot() #note: query also has row count results = root.find('results') #Convert xml into generation of dicts for element in results.getchildren(): i = util.xml_to_dict(element) yield i
Update support for passing in filenames. This shit is gross
from imhotep.tools import Tool from collections import defaultdict import json import os import logging log = logging.getLogger(__name__) class FoodCritic(Tool): def invoke(self, dirname, filenames=set(), config_file=None): retval = defaultdict(lambda: defaultdict(list)) if len(filenames) == 0: cmd = "find %s/cookbooks -type d -maxdepth 1 ! -path %s/cookbooks | xargs foodcritic" % (dirname, dirname) else: filenames = ["%s/%s" % (dirname, "/".join(filename.split('/')[:2])) for filename in filenames] cmd = "foodcritic %s" % (" ".join(filenames)) log.debug("Command: %s", cmd) try: output = self.executor(cmd) for line in output.split('\n'): rule, message, file_name, line_number = line.split(':') file_name = file_name.lstrip() file_name = file_name.replace(dirname, "")[1:] message = "[%s](http://acrmp.github.io/foodcritic/#%s): %s" % (rule, rule, message) retval[file_name][line_number].append(message) except: pass return retval
from imhotep.tools import Tool from collections import defaultdict import json import os import logging log = logging.getLogger(__name__) class FoodCritic(Tool): def invoke(self, dirname, filenames=set(), config_file=None, file_list=None): retval = defaultdict(lambda: defaultdict(list)) if file_list is None: cmd = "find %s/cookbooks -type d -maxdepth 1 ! -path %s/cookbooks | xargs foodcritic" % (dirname, dirname) else: cmd = "foodcritic %s" % (" ".join(file_list)) log.debug("Command: %s", cmd) try: output = self.executor(cmd) for line in output.split('\n'): rule, message, file_name, line_number = line.split(':') file_name = file_name.lstrip() file_name = file_name.replace(dirname, "")[1:] message = "[%s](http://acrmp.github.io/foodcritic/#%s): %s" % (rule, rule, message) retval[file_name][line_number].append(message) except: pass return retval
Use idx as key for similar player avatars
import React from 'react'; import PlayerAvatar from './PlayerAvatar.js' import '../style/components/SimilarPlayersCard.css'; export default function SimilarPlayersCard(props) { const similarPlayersList = [ { 'firstName': props.firstName0, 'lastName': props.lastName0, 'img': props.img0, 'ppg': props.ppg0, 'apg': props.apg0, 'rpg': props.rpg0 }, { 'firstName': props.firstName1, 'lastName': props.lastName1, 'img': props.img1, 'ppg': props.ppg1, 'apg': props.apg1, 'rpg': props.rpg1 }, { 'firstName': props.firstName2, 'lastName': props.lastName2, 'img': props.img2, 'ppg': props.ppg2, 'apg': props.apg2, 'rpg': props.rpg2 } ]; const playerAvatarList = similarPlayersList.map((player, idx) => <PlayerAvatar key={idx} playerName={player.firstName + ' ' + player.lastName} img={player.img} ppg={player.ppg} apg={player.apg} rpg={player.rpg} /> ); return ( <div className='SimilarPlayersCard card'> <div className='card-title'> Similar Players </div> {playerAvatarList} </div> ); }
import React from 'react'; import PlayerAvatar from './PlayerAvatar.js' import '../style/components/SimilarPlayersCard.css'; export default function SimilarPlayersCard(props) { const similarPlayersList = [ { 'firstName': props.firstName0, 'lastName': props.lastName0, 'img': props.img0, 'ppg': props.ppg0, 'apg': props.apg0, 'rpg': props.rpg0 }, { 'firstName': props.firstName1, 'lastName': props.lastName1, 'img': props.img1, 'ppg': props.ppg1, 'apg': props.apg1, 'rpg': props.rpg1 }, { 'firstName': props.firstName2, 'lastName': props.lastName2, 'img': props.img2, 'ppg': props.ppg2, 'apg': props.apg2, 'rpg': props.rpg2 } ]; const playerAvatarList = similarPlayersList.map((player) => <PlayerAvatar key={player.firstName + '_' + player.lastName} playerName={player.firstName + ' ' + player.lastName} img={player.img} ppg={player.ppg} apg={player.apg} rpg={player.rpg} /> ); return ( <div className='SimilarPlayersCard card'> <div className='card-title'> Similar Players </div> {playerAvatarList} </div> ); }