text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Support more than on path when building a DirScanner
import os import zope.interface import mutagen import jukebox.song class IScanner(zope.interface.Interface): def scan(): """ Start the scanning process. It is expected to be called at startup and can block. """ def watch(): """ Starts an async watcher that can add files to the IStorage """ def stop(): """ Stops the async watcher """ class DirScanner(object): zope.interface.implements(IScanner) def __init__(self, storage, *paths): self.storage = storage self.paths = paths def _scan_path(self, path): print path for root, dirs, files in os.walk(path): for name in files: file_path = os.path.join(root, name) try: music_file = mutagen.File(file_path, easy=True) except: continue if not music_file: continue try: title = music_file['title'][0] except KeyError: title = None try: album = music_file['album'][0] except KeyError: album = None try: artist = music_file['artist'][0] except KeyError: artist = None self.storage.add_song(jukebox.song.Song( title=title, album=album, artist=artist, path=file_path, )) def scan(self): for path in self.paths: self._scan_path(path) def watch(self): pass def stop(self): pass
import os import zope.interface import mutagen import jukebox.song class IScanner(zope.interface.Interface): def scan(): """ Start the scanning process. It is expected to be called at startup and can block. """ def watch(): """ Starts an async watcher that can add files to the IStorage """ def stop(): """ Stops the async watcher """ class DirScanner(object): zope.interface.implements(IScanner) def __init__(self, storage, path): self.storage = storage self.path = path def scan(self): for root, dirs, files in os.walk(self.path): for name in files: path = os.path.join(root, name) try: music_file = mutagen.File(path, easy=True) except: continue if not music_file: continue self.storage.add_song(jukebox.song.Song( title=(music_file['title'] + [None])[0], album=(music_file['album'] + [None])[0], artist=(music_file['artist'] + [None])[0], path=path, )) def watch(self): pass def stop(self): pass
BB-4210: Add validation functionality to RuleEditorComponent - temp commit (polish of suggestion output)
define(function(require) { 'use strict'; var $ = require('jquery'); require('bootstrap'); /** * This customization allows to define own functions for Typeahead */ var Typeahead; var origTypeahead = $.fn.typeahead.Constructor; var origFnTypeahead = $.fn.typeahead; Typeahead = function(element, options) { var _this = this; var opts = $.extend({}, $.fn.typeahead.defaults, options); _.each(opts, function(value, name) { _this[name] = value || _this[name]; }); origTypeahead.apply(this, arguments); }; Typeahead.prototype = origTypeahead.prototype; Typeahead.prototype.constructor = Typeahead; $.fn.typeahead = function(option) { return this.each(function() { var $this = $(this); var data = $this.data('typeahead'); var options = typeof option === 'object' && option; if (!data) { $this.data('typeahead', (data = new Typeahead(this, options))); } if (typeof option === 'string') { data[option](); } }); }; $.fn.typeahead.defaults = origFnTypeahead.defaults; $.fn.typeahead.Constructor = Typeahead; $.fn.typeahead.noConflict = origFnTypeahead.noConflict; });
define(function(require) { 'use strict'; var $ = require('jquery'); require('bootstrap'); /** * This customization allows to define own focus, click, render, show, lookup functions for Typeahead */ var Typeahead; var origTypeahead = $.fn.typeahead.Constructor; var origFnTypeahead = $.fn.typeahead; Typeahead = function(element, options) { var opts = $.extend({}, $.fn.typeahead.defaults, options); this.focus = opts.focus || this.focus; this.render = opts.render || this.render; this.show = opts.show || this.show; this.lookup = opts.lookup || this.lookup; origTypeahead.apply(this, arguments); }; Typeahead.prototype = origTypeahead.prototype; Typeahead.prototype.constructor = Typeahead; $.fn.typeahead = function(option) { return this.each(function() { var $this = $(this); var data = $this.data('typeahead'); var options = typeof option === 'object' && option; if (!data) { $this.data('typeahead', (data = new Typeahead(this, options))); } if (typeof option === 'string') { data[option](); } }); }; $.fn.typeahead.defaults = origFnTypeahead.defaults; $.fn.typeahead.Constructor = Typeahead; $.fn.typeahead.noConflict = origFnTypeahead.noConflict; });
Use inout proxy script for log.
import neovim import os, subprocess import json @neovim.plugin class LanguageServerClient: def __init__(self, nvim): self.nvim = nvim self.server = subprocess.Popen( ["/bin/bash", "/opt/rls/wrapper.sh"], # ["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"], # ['langserver-go', '-trace', '-logfile', '/tmp/langserver-go.log'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) @neovim.command('GetDocumentation') def GetDocumentation(self): MESSAGE = { "jsonrpc": "2.0", "id": 0, "method": "initialize", "params": { "processId": os.getpid(), "rootPath": "/private/tmp/sample-rs", "capabilities":{}, "trace":"verbose" } } body = json.dumps(MESSAGE) response = ( "Content-Length: {}\r\n\r\n" "{}".format(len(body), body) ) self.server.stdin.write(response.encode('utf-8')) self.server.stdin.flush() while True: line = self.server.stdout.readline().decode('utf-8') if line: print(line) break def test_LanguageServerClient(): client = LanguageServerClient(None) client.GetDocumentation()
import neovim import os, subprocess import json @neovim.plugin class LanguageServerClient: def __init__(self, nvim): self.nvim = nvim self.server = subprocess.Popen( ["cargo", "run", "--manifest-path=/opt/rls/Cargo.toml"], # ['langserver-go', '-trace', '-logfile', '/tmp/langserver-go.log'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) @neovim.command('GetDocumentation') def GetDocumentation(self): MESSAGE = { "jsonrpc": "2.0", "id": 0, "method": "initialize", "params": { "processId": os.getpid(), "rootPath": "/private/tmp/sample-rs", "capabilities":{}, "trace":"verbose" } } body = json.dumps(MESSAGE) response = ( "Content-Length: {}\r\n\r\n" "{}".format(len(body), body) ) self.server.stdin.write(response.encode('utf-8')) self.server.stdin.flush() while True: line = self.server.stdout.readline().decode('utf-8') if line: print(line) break def test_LanguageServerClient(): client = LanguageServerClient(None) client.GetDocumentation()
Fix id for scaffolded objects
import ApolloClient, { createNetworkInterface } from 'apollo-client'; import { printRequest } from 'apollo-client/transport/networkInterface'; import qs from 'qs'; function buildApolloClient(baseUrl) { const networkInterface = createNetworkInterface({ uri: `${baseUrl}graphql/`, opts: { credentials: 'same-origin', headers: { accept: 'application/json', }, }, }); const apolloClient = new ApolloClient({ shouldBatch: true, addTypename: true, dataIdFromObject: (o) => { if ((o.id >= 0 || o.ID >= 0) && o.__typename) { return `${o.__typename}:${(o.id >= 0) ? o.id : o.ID}`; } return null; }, networkInterface, }); networkInterface.use([{ applyMiddleware(req, next) { const entries = printRequest(req.request); // eslint-disable-next-line no-param-reassign req.options.headers = Object.assign( {}, req.options.headers, { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', } ); // eslint-disable-next-line no-param-reassign req.options.body = qs.stringify(Object.assign( {}, entries, { variables: JSON.stringify(entries.variables) } )); next(); }, }]); return apolloClient; } export default buildApolloClient;
import ApolloClient, { createNetworkInterface } from 'apollo-client'; import { printRequest } from 'apollo-client/transport/networkInterface'; import qs from 'qs'; function buildApolloClient(baseUrl) { const networkInterface = createNetworkInterface({ uri: `${baseUrl}graphql/`, opts: { credentials: 'same-origin', headers: { accept: 'application/json', }, }, }); const apolloClient = new ApolloClient({ shouldBatch: true, addTypename: true, dataIdFromObject: (o) => { if (o.id >= 0 && o.__typename) { return `${o.__typename}:${o.id}`; } return null; }, networkInterface, }); networkInterface.use([{ applyMiddleware(req, next) { const entries = printRequest(req.request); // eslint-disable-next-line no-param-reassign req.options.headers = Object.assign( {}, req.options.headers, { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', } ); // eslint-disable-next-line no-param-reassign req.options.body = qs.stringify(Object.assign( {}, entries, { variables: JSON.stringify(entries.variables) } )); next(); }, }]); return apolloClient; } export default buildApolloClient;
Use relative path to mock data
function findStations(callback) { $.ajax({ type: 'GET', url: 'mockdata/veturilo.xml', dataType: 'xml', success: function (xml) { var stations = []; $(xml).find('place').each(function () { var place = $(this); var station = { name: place.attr('name'), lat: place.attr('lat'), lng: place.attr('lng'), bikes: place.attr('bikes'), racks: place.attr('bike_racks') }; stations.push(station); }); callback(stations); } }); } var distanceSquare = function (pointA, pointB) { var x = pointA.lat - pointB.lat; var y = pointA.lng - pointB.lng; return (x * x) + (y * y); }; function findNearestStation(point, stations) { var nearest = null; var smallestDistanceSquare; $.each(stations, function (i, station) { var distance = distanceSquare(point, station); if ((nearest === null) || ((smallestDistanceSquare > distance) && (stations.bikes != '0'))) { nearest = station; smallestDistanceSquare = distance; } }); return nearest; }
function findStations(callback) { $.ajax({ type: 'GET', url: 'http://localhost:8765/mockdata/veturilo.xml', dataType: 'xml', success: function (xml) { var stations = []; $(xml).find('place').each(function () { var place = $(this); var station = { name: place.attr('name'), lat: place.attr('lat'), lng: place.attr('lng'), bikes: place.attr('bikes'), racks: place.attr('bike_racks') }; stations.push(station); }); callback(stations); } }); } var distanceSquare = function (pointA, pointB) { var x = pointA.lat - pointB.lat; var y = pointA.lng - pointB.lng; return (x * x) + (y * y); }; function findNearestStation(point, stations) { var nearest = null; var smallestDistanceSquare; $.each(stations, function (i, station) { var distance = distanceSquare(point, station); if ((nearest === null) || ((smallestDistanceSquare > distance) && (stations.bikes != '0'))) { nearest = station; smallestDistanceSquare = distance; } }); return nearest; }
Add starfield to battle scene.
define(function(require){ var scene = new THREE.Object3D(); var camera = new THREE.PerspectiveCamera(75, 16 / 9, 0.1, 5000); var loader = new THREE.JSONLoader(true); var origin = new THREE.Vector3(); var StarSystem = require("component/starfield"); var starfield = StarSystem.create(33, 100); scene.add(starfield); camera.position.set(0, 3, 10); camera.lookAt(origin); var ship; loader.load("models/spaceship-five.js", function(geometry, materials){ materials[1].bumpMap.bumpScale = 0.0001; ship = new THREE.Object3D(); ship.add(new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials))); var tailLight = new THREE.PointLight(0xCCCCFF, 2, 3); tailLight.position.set(0, 0, 5.2); ship.add(tailLight); scene.add(ship); console.log(ship); }); var light = new THREE.PointLight(0xFFFFFF, 1, 100); light.position.set(10, 10, 10); scene.add(light); return { scene: scene, camera: camera, render: render, init: init }; function render(time){ ship.rotation.y += 0.01; } });
define(function(require){ var scene = new THREE.Object3D(); var camera = new THREE.PerspectiveCamera(75, 16 / 9, 0.1, 5000); var loader = new THREE.JSONLoader(true); var origin = new THREE.Vector3(); var StarSystem = require("component/starfield"); var starfield = StarSystem.create(33); scene.add(starfield); camera.position.set(0, 3, 10); camera.lookAt(origin); var ship; loader.load("models/spaceship-five.js", function(geometry, materials){ materials[1].bumpMap.bumpScale = 0.0001; ship = new THREE.Object3D(); ship.add(new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials))); var tailLight = new THREE.PointLight(0xCCCCFF, 2, 3); tailLight.position.set(0, 0, 5.2); ship.add(tailLight); scene.add(ship); console.log(ship); }); var light = new THREE.PointLight(0xFFFFFF, 1, 100); light.position.set(10, 10, 10); scene.add(light); return { scene: scene, camera: camera, render: render } function render(time){ ship.rotation.y += 0.01; } });
Add id attribute to posts wrap The same id is already added to posts wrap in other templates.
<?php declare (strict_types = 1); \Jentil()->utilities->loader->loadPartial('header'); \the_post(); ?> <div id="main-query" class="posts-wrap show-content big singular-post"> <article data-post-id="<?php \the_ID(); ?>" id="post-<?php \the_ID(); ?>" <?php \post_class(['post-wrap']); ?> itemscope itemtype="http://schema.org/Article"> <?php if ($post->post_title) { ?> <header class="page-header"> <?php } \do_action('jentil_before_title'); \the_title( '<h1 class="entry-title" itemprop="name headline mainEntityOfPage">', '</h1>' ); \do_action('jentil_after_title'); if ($post->post_title) { ?> </header> <?php } \do_action('jentil_before_content'); ?> <div class="entry-content" itemprop="articleBody"> <?php \the_content(); \wp_link_pages([ 'before' => '<nav class="page-links pagination">' . \esc_html__('Pages: ', 'jentil'), 'after' => '</nav>', ]); ?> </div><!-- .entry-content --> <?php \do_action('jentil_after_content'); ?> </article> </div> <?php \Jentil()->utilities->loader->loadPartial('footer');
<?php declare (strict_types = 1); \Jentil()->utilities->loader->loadPartial('header'); \the_post(); ?> <div class="posts-wrap show-content big singular-post"> <article data-post-id="<?php \the_ID(); ?>" id="post-<?php \the_ID(); ?>" <?php \post_class(['post-wrap']); ?> itemscope itemtype="http://schema.org/Article"> <?php if ($post->post_title) { ?> <header class="page-header"> <?php } \do_action('jentil_before_title'); \the_title( '<h1 class="entry-title" itemprop="name headline mainEntityOfPage">', '</h1>' ); \do_action('jentil_after_title'); if ($post->post_title) { ?> </header> <?php } \do_action('jentil_before_content'); ?> <div class="entry-content" itemprop="articleBody"> <?php \the_content(); \wp_link_pages([ 'before' => '<nav class="page-links pagination">' . \esc_html__('Pages: ', 'jentil'), 'after' => '</nav>', ]); ?> </div><!-- .entry-content --> <?php \do_action('jentil_after_content'); ?> </article> </div> <?php \Jentil()->utilities->loader->loadPartial('footer');
Simplify detection of keys already bound
class Bindings(object): def __init__(self): self._bindings = {} def bind(self, key, provider=None): if key in self: raise AlreadyBoundException("Cannot rebind key: %s" % key) if provider is None: return Binder(key, self) else: self._bindings[key] = provider def copy(self): copy = Bindings() copy._bindings = self._bindings.copy() return copy def update(self, bindings): for key in bindings._bindings: if key in self._bindings: raise AlreadyBoundException("Key already bound: %s" % key) self._bindings.update(bindings._bindings) def __contains__(self, key): return key in self._bindings def __getitem__(self, key): return self._bindings[key] class Binder(object): def __init__(self, key, bindings): self._key = key self._bindings = bindings def to_instance(self, instance): self.to_provider(lambda: instance) def to_key(self, key): if key is self._key: raise TypeError("Cannot bind a key to itself") self.to_provider(lambda injector: injector.get(key)) def to_type(self, key): return self.to_key(key) def to_provider(self, provider): self._bindings.bind(self._key, provider) class AlreadyBoundException(Exception): pass
class Bindings(object): def __init__(self): self._bindings = {} def bind(self, key): if key in self: raise AlreadyBoundException("Cannot rebind key: %s" % key) return Binder(key, self._bindings) def copy(self): copy = Bindings() copy._bindings = self._bindings.copy() return copy def update(self, bindings): for key in bindings._bindings: if key in self._bindings: raise AlreadyBoundException("Key already bound: %s" % key) self._bindings.update(bindings._bindings) def __contains__(self, key): return key in self._bindings def __getitem__(self, key): return self._bindings[key] class Binder(object): def __init__(self, key, bindings): self._bound = False self._key = key self._bindings = bindings def to_instance(self, instance): self.to_provider(lambda: instance) def to_key(self, key): if key is self._key: raise TypeError("Cannot bind a key to itself") self.to_provider(lambda injector: injector.get(key)) def to_type(self, key): return self.to_key(key) def to_provider(self, provider): if self._bound: raise AlreadyBoundException() self._bound = True self._bindings[self._key] = provider class AlreadyBoundException(Exception): pass
Exclude non-confirmed accounts from stats In future simple User.count() would likely contain also spambots etc. Will show up as a slight drop in numbers at [statistics page](https://www.trustroots.org/#!/statistics).
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors'), async = require('async'), git = require('git-rev'), Offer = mongoose.model('Offer'), User = mongoose.model('User'); /** * Get all statistics */ exports.get = function(req, res) { req.statistics = {}; async.waterfall([ // Total users function(done) { User .find({public:true}) .count(function(err, count) { req.statistics.total = count; done(err); }); }, // Hosting stats function(done) { Offer.count({ $or: [ { status: 'yes' }, { status: 'maybe' } ] }, function(err, count) { req.statistics.hosting = count; done(err); }); }, // Returns: 'git rev-parse HEAD' // @link https://www.npmjs.com/package/git-rev function(done) { git.long(function (hash) { req.statistics.commit = hash; done(null); }); }, // Done! function(done) { res.json(req.statistics); } ], function(err) { if (err) { res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } }); };
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors'), async = require('async'), git = require('git-rev'), Offer = mongoose.model('Offer'), User = mongoose.model('User'); /** * Get all statistics */ exports.get = function(req, res) { req.statistics = {}; async.waterfall([ // Total users function(done) { User.count(function(err, count) { req.statistics.total = count; done(err); }); }, // Hosting stats function(done) { Offer.count({ $or: [ { status: 'yes' }, { status: 'maybe' } ] }, function(err, count) { req.statistics.hosting = count; done(err); }); }, // Returns: 'git rev-parse HEAD' // @link https://www.npmjs.com/package/git-rev function(done) { git.long(function (hash) { req.statistics.commit = hash; done(null); }); }, // Done! function(done) { res.json(req.statistics); } ], function(err) { if (err) { res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } }); };
Make sure button is before all other children
HNSpecial.settings.registerModule("mark_as_read", function () { function editLinks() { var subtexts = _.toArray(document.getElementsByClassName("subtext")); subtexts.forEach(function (subtext) { if (!subtext.getAttribute("data-hnspecial-mark-as-read")) { subtext.setAttribute("data-hnspecial-mark-as-read", "true"); // Create the Mark as read "button" var button = _.createElement("span", { classes: ["hnspecial-mark-as-read-button"], content: "&#10004;" // tick symbol }); // Add the click listener button.addEventListener("click", function (e) { // Well, that escalated quickly var url = e.target.parentElement.parentElement.previousSibling.childNodes[2].children[0].href; chrome.extension.sendRequest({ module: "mark_as_read", action: "toggle", params: { url: url } }); }); // Insert the button into the page subtext.insertBefore(button, subtext.childNodes[0]); } }); } // Run it editLinks(); // Subscribe to the event emitted when new links are present HNSpecial.settings.subscribe("new links", editLinks); });
HNSpecial.settings.registerModule("mark_as_read", function () { function editLinks() { var subtexts = _.toArray(document.getElementsByClassName("subtext")); subtexts.forEach(function (subtext) { if (!subtext.getAttribute("data-hnspecial-mark-as-read")) { subtext.setAttribute("data-hnspecial-mark-as-read", "true"); // Create the Mark as read "button" var button = _.createElement("span", { classes: ["hnspecial-mark-as-read-button"], content: "&#10004;" // tick symbol }); // Add the click listener button.addEventListener("click", function (e) { // Wow, that escalated quickly var url = e.target.parentElement.parentElement.previousSibling.childNodes[2].children[0].href; chrome.extension.sendRequest({ module: "mark_as_read", action: "toggle", params: { url: url } }); }); // Insert the button into the page subtext.insertBefore(button, subtext.children[0]); } }); } // Run it editLinks(); // Subscribe to the event emitted when new links are present HNSpecial.settings.subscribe("new links", editLinks); });
Make pagination wrappers conditional for author template
<?php $pagination_wrapper_start = '<div class="row"><div class="col-md-8 col-md-offset-2">'; $pagination_wrapper_end = '</div></div>'; if (is_author()): $pagination_wrapper_start = ''; $pagination_wrapper_end = ''; endif; get_header(); if (!is_front_page()) : if (have_posts()) : ?> <div class="container"> <div id="primary" class="content-area"> <?php get_template_part(SNIPPETS_DIR . '/header/page-header'); ?> <main id="main" class="site-main" role="main"> <?php /* Start the Loop */ while (have_posts()) : the_post(); if (is_page()) : get_template_part(SNIPPETS_DIR . '/content/content-page'); else : get_template_part(SNIPPETS_DIR . '/content/content'); endif; endwhile; ?> </main> <?php else : get_template_part(SNIPPETS_DIR . '/content/content-none'); endif; echo $pagination_wrapper_start; get_template_part(SNIPPETS_DIR . '/navigation/pagination'); echo $pagination_wrapper_end; get_template_part(SNIPPETS_DIR . '/sidebars/twitter-content'); ?> </div> </div> <?php endif; get_sidebar(); get_footer();
<?php get_header(); if (!is_front_page()) : if (have_posts()) : ?> <div class="container"> <div id="primary" class="content-area"> <?php get_template_part(SNIPPETS_DIR . '/header/page-header'); ?> <main id="main" class="site-main" role="main"> <?php /* Start the Loop */ while (have_posts()) : the_post(); if (is_page()) : get_template_part(SNIPPETS_DIR . '/content/content-page'); else : get_template_part(SNIPPETS_DIR . '/content/content'); endif; endwhile; ?> </main> <?php else : get_template_part(SNIPPETS_DIR . '/content/content-none'); endif; ?> <div class="row"> <div class="col-md-8 col-md-offset-2"> <?php get_template_part(SNIPPETS_DIR . '/navigation/pagination'); ?> </div> </div> <?php get_template_part(SNIPPETS_DIR . '/sidebars/twitter-content'); ?> </div> </div> <?php endif; get_sidebar(); get_footer();
Implement clickdown and clickup to function correctly
/* * @module Clickable * @namespace component * @desc Used to make a game component perfom an action when she's clicked * @copyright (C) SpilGames * @author Jeroen Reurings * @license BSD 3-Clause License (see LICENSE file in project root) */ glue.module.create( 'glue/component/clickable', [ 'glue', 'glue/basecomponent' ], function (Glue, BaseComponent) { 'use strict'; return function (object) { var baseComponent = BaseComponent('clickable', object), isClicked = function (e) { return object.getBoundingBox().hasPosition(e.position); }, pointerDownHandler = function (e) { if (isClicked(e) && object.onClickDown) { object.onClickDown(e); } }, pointerUpHandler = function (e) { if (isClicked(e) && object.onClickUp) { object.onClickUp(e); } }; baseComponent.set({ setup: function (settings) { }, update: function (deltaT) { }, pointerDown: function (e) { pointerDownHandler(e); }, pointerUp: function (e) { pointerUpHandler(e); }, register: function () { baseComponent.register('pointerDown'); baseComponent.register('pointerUp'); }, unregister: function () { baseComponent.unregister('pointerDown'); baseComponent.unregister('pointerUp'); } }); return object; }; } );
/* * @module Clickable * @namespace component * @desc Used to make a game component perfom an action when she's clicked * @copyright (C) SpilGames * @author Jeroen Reurings * @license BSD 3-Clause License (see LICENSE file in project root) */ glue.module.create( 'glue/component/clickable', [ 'glue', 'glue/basecomponent' ], function (Glue, BaseComponent) { 'use strict'; return function (object) { var baseComponent = BaseComponent('clickable', object), isClicked = function (e) { return object.getBoundingBox().hasPosition(e.position); }, pointerDownHandler = function (e) { if (isClicked(e) && object.onClick) { object.onClick(e); } }, pointerUpHandler = function (e) { if (isClicked(e) && object.onClick) { object.onClick(e); } }; baseComponent.set({ setup: function (settings) { }, update: function (deltaT) { }, pointerDown: function (e) { pointerDownHandler(e); }, pointerUp: function (e) { pointerUpHandler(e); }, register: function () { baseComponent.register('pointerDown'); }, unregister: function () { baseComponent.unregister('pointerDown'); } }); return object; }; } );
Add support for nested lists in the excel renderer
import xlsxwriter import os from django.conf import settings from rest_framework import renderers def _write_excel_file(data): result = data.get('results') work_book_name = 'download.xlsx' workbook = xlsxwriter.Workbook(work_book_name) worksheet = workbook.add_worksheet() row = 0 col = 0 data_dict = result[0] data_keys = data_dict.keys() for key in data_keys: worksheet.write(row, col, key) col = col + 1 row = 1 col = 0 for data_dict in result: for key in data_keys: if not isinstance(data[key], list): worksheet.write(row, col, data_dict[key]) col = col + 1 else: _write_excel_file() row = row + 1 workbook.close() return work_book_name class ExcelRenderer(renderers.BaseRenderer): media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # noqa format = 'excel' def render(self, data, accepted_media_type=None, renderer_context=None): file_name = _write_excel_file(data) file_path = os.path.join(settings.BASE_DIR, file_name) with open(file_path, 'r') as excel_file: file_data = excel_file.read() return file_data
import xlsxwriter import os from django.conf import settings from rest_framework import renderers def _write_excel_file(data): result = data.get('results') work_book_name = 'human.xlsx' workbook = xlsxwriter.Workbook(work_book_name) worksheet = workbook.add_worksheet() row = 0 col = 0 data_dict = result[0] data_keys = data_dict.keys() for key in data_keys: worksheet.write(row, col, key) col = col + 1 row = 1 col = 0 for data_dict in result: for key in data_keys: worksheet.write(row, col, data_dict[key]) col = col + 1 row = row + 1 workbook.close() return work_book_name class ExcelRenderer(renderers.BaseRenderer): media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # noqa format = 'excel' def render(self, data, accepted_media_type=None, renderer_context=None): file_name = _write_excel_file(data) file_path = os.path.join(settings.BASE_DIR, file_name) with open(file_path, 'r') as excel_file: file_data = excel_file.read() return file_data
Use an arrow function to get rid of ctrl = this
let defaultSnippet = ` from player_map import playerPositions print playerPositions()`; export default class Controller { constructor($log, $rootScope, connection, $mdToast) { this.$log = $log; this.$rootScope = $rootScope; this.connection = connection; this.$mdToast = $mdToast; this.codeSnippet = defaultSnippet; var aceLoaded = (_editor) => { _editor.commands.addCommand({ name: "Execute", bindKey: { mac: "Command-Shift-Up", win: "Alt-Shift-Up" }, exec: function () { this.run(this.snippet); } }); }; function aceChanged() { //console.debug("ace was changed"); } this.aceConfig = { useWrapMode: true, mode: "python", onLoad: aceLoaded, onChange: aceChanged }; } run() { // Make sure we are still connected if (!this.connection.isConnected) { let msg = "Lost the connection"; $mdToast.show($mdToast.simple().content(msg)); } this.connection.send(this.codeSnippet); } }
let defaultSnippet = ` from player_map import playerPositions print playerPositions()`; export default class Controller { constructor($log, $rootScope, connection, $mdToast) { var ctrl = this; this.$log = $log; this.$rootScope = $rootScope; this.connection = connection; this.$mdToast = $mdToast; this.codeSnippet = defaultSnippet; function aceLoaded(_editor) { _editor.commands.addCommand({ name: "Execute", bindKey: { mac: "Command-Shift-Up", win: "Alt-Shift-Up" }, exec: function () { ctrl.run(ctrl.snippet); } }); } function aceChanged() { //console.debug("ace was changed"); } this.aceConfig = { useWrapMode: true, mode: "python", onLoad: aceLoaded, onChange: aceChanged }; } run() { // Make sure we are still connected if (!this.connection.isConnected) { let msg = "Lost the connection"; $mdToast.show($mdToast.simple().content(msg)); } this.connection.send(this.codeSnippet); } }
Add null check for scope
package com.github.ferstl.depgraph; import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.dependency.graph.DependencyNode; import com.github.ferstl.depgraph.dot.NodeRenderer; import com.google.common.base.Joiner; enum NodeRenderers implements NodeRenderer { ARTIFACT_ID_LABEL { @Override public String render(DependencyNode node) { Artifact artifact = node.getArtifact(); return toScopedString(artifact.getArtifactId(), artifact.getScope()); } }, GROUP_ID_LABEL { @Override public String render(DependencyNode node) { Artifact artifact = node.getArtifact(); return toScopedString(artifact.getGroupId(), artifact.getScope()); } }, SCOPED_GROUP_ID { @Override public String render(DependencyNode node) { Artifact artifact = node.getArtifact(); return COLON_JOINER.join(artifact.getGroupId(), artifact.getScope()); } }, VERSIONLESS_ID { @Override public String render(DependencyNode node) { Artifact artifact = node.getArtifact(); return COLON_JOINER.join( artifact.getGroupId(), artifact.getArtifactId(), artifact.getType(), artifact.getClassifier(), artifact.getScope()); } }; private static final Joiner COLON_JOINER = Joiner.on(":").useForNull(""); private static String toScopedString(String string, String scope) { if (scope != null && !"compile".equals(scope)) { return string + "\\n(" + scope + ")"; } return string; } }
package com.github.ferstl.depgraph; import org.apache.maven.artifact.Artifact; import org.apache.maven.shared.dependency.graph.DependencyNode; import com.github.ferstl.depgraph.dot.NodeRenderer; import com.google.common.base.Joiner; enum NodeRenderers implements NodeRenderer { ARTIFACT_ID_LABEL { @Override public String render(DependencyNode node) { Artifact artifact = node.getArtifact(); return toScopedString(artifact.getArtifactId(), artifact.getScope()); } }, GROUP_ID_LABEL { @Override public String render(DependencyNode node) { Artifact artifact = node.getArtifact(); return toScopedString(artifact.getGroupId(), artifact.getScope()); } }, SCOPED_GROUP_ID { @Override public String render(DependencyNode node) { Artifact artifact = node.getArtifact(); return COLON_JOINER.join(artifact.getGroupId(), artifact.getScope()); } }, VERSIONLESS_ID { @Override public String render(DependencyNode node) { Artifact artifact = node.getArtifact(); return COLON_JOINER.join( artifact.getGroupId(), artifact.getArtifactId(), artifact.getType(), artifact.getClassifier(), artifact.getScope()); } }; private static final Joiner COLON_JOINER = Joiner.on(":").useForNull(""); private static String toScopedString(String string, String scope) { if (!"compile".equals(scope)) { return string + "\\n(" + scope + ")"; } return string; } }
Refactor logging in celery router Send logging for celery router tasks to the 'rapidsms' logger rather than the 'celery' logger, and make sure celery knows the task failed by re-raising the exception.
import celery import logging from rapidsms.errors import MessageSendingError logger = logging.getLogger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") raise @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass
import celery from celery.utils.log import get_task_logger from rapidsms.errors import MessageSendingError logger = get_task_logger(__name__) @celery.task def receive_async(text, connection_id, message_id, fields): """Task used to send inbound message through router phases.""" from rapidsms.models import Connection from rapidsms.router import get_router logger.debug('receive_async: %s' % text) router = get_router() # reconstruct incoming message connection = Connection.objects.select_related().get(pk=connection_id) message = router.new_incoming_message(text=text, connections=[connection], id_=message_id, fields=fields) try: # call process_incoming directly to skip receive_incoming router.process_incoming(message) except Exception: logger.exception("Exception processing incoming message") @celery.task def send_async(backend_name, id_, text, identities, context): """Task used to send outgoing messages to backends.""" logger.debug('send_async: %s' % text) from rapidsms.router import get_router router = get_router() try: router.send_to_backend(backend_name=backend_name, id_=id_, text=text, identities=identities, context=context) except MessageSendingError: # This exception has already been logged in send_to_backend. # We'll simply pass here and not re-raise or log the exception again. pass
[Fixture] Set EUR as base currency in fixtures
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\FixturesBundle\DataFixtures\ORM; use Doctrine\Common\Persistence\ObjectManager; use Sylius\Bundle\FixturesBundle\DataFixtures\DataFixture; use Sylius\Component\Currency\Model\CurrencyInterface; /** * Default currency fixtures. * * @author Saša Stamenković <[email protected]> */ class LoadCurrencyData extends DataFixture { const BASE_CURRENCY = 'EUR'; /** * @var array */ protected $currencies = [ 'EUR' => 1.00, 'USD' => 1.30, 'GBP' => 0.85, ]; /** * {@inheritdoc} */ public function load(ObjectManager $manager) { $currencyFactory = $this->getCurrencyFactory(); foreach ($this->currencies as $code => $rate) { $currency = $currencyFactory->createNew(); $currency->setCode($code); $currency->setExchangeRate($rate); $currency->setEnabled(true); if (self::BASE_CURRENCY === $code) { $currency->setBase(true); } $this->setReference('Sylius.Currency.'.$code, $currency); $manager->persist($currency); } $manager->flush(); } /** * {@inheritdoc} */ public function getOrder() { return 10; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\FixturesBundle\DataFixtures\ORM; use Doctrine\Common\Persistence\ObjectManager; use Sylius\Bundle\FixturesBundle\DataFixtures\DataFixture; /** * Default currency fixtures. * * @author Saša Stamenković <[email protected]> */ class LoadCurrencyData extends DataFixture { protected $currencies = [ 'EUR' => 1.00, 'USD' => 1.30, 'GBP' => 0.85, ]; /** * {@inheritdoc} */ public function load(ObjectManager $manager) { $currencyFactory = $this->getCurrencyFactory(); foreach ($this->currencies as $code => $rate) { $currency = $currencyFactory->createNew(); $currency->setCode($code); $currency->setExchangeRate($rate); $currency->setEnabled(true); $this->setReference('Sylius.Currency.'.$code, $currency); $manager->persist($currency); } $manager->flush(); } /** * {@inheritdoc} */ public function getOrder() { return 10; } }
Add description attr to Change
import uuid import jsonschema import changeling.exception class Change(object): schema = { 'name': 'change', 'properties': { 'id': {'type': 'string'}, 'name': {'type': 'string'}, 'description': {'type': 'string'}, }, 'additionalProperties': False, } def __init__(self, id=None, name=None, description=None): self.id = id or str(uuid.uuid4()) self.name = name self.description = description @classmethod def from_dict(self, data): self.validate(data) return Change(**data) def to_dict(self): def _generate_set_attributes(): for k in Change.schema['properties'].keys(): val = getattr(self, k) if val is not None: yield (k, val) return dict(_generate_set_attributes()) def __str__(self): return "<Change id=%s name=%s>" % (self.id, self.name) @classmethod def validate(cls, data): try: jsonschema.validate(data, cls.schema) except jsonschema.ValidationError as exc: raise changeling.exception.ValidationError(exc) def is_valid(self): try: self.validate(self.to_dict()) except changeling.exception.ValidationError: return False else: return True
import uuid import jsonschema import changeling.exception class Change(object): schema = { 'name': 'change', 'properties': { 'id': {'type': 'string'}, 'name': {'type': 'string'}, }, 'additionalProperties': False, } def __init__(self, id=None, name=None): self.id = id or str(uuid.uuid4()) self.name = name @classmethod def from_dict(self, data): self.validate(data) return Change(**data) def to_dict(self): def _generate_set_attributes(): for k in Change.schema['properties'].keys(): val = getattr(self, k) if val is not None: yield (k, val) return dict(_generate_set_attributes()) def __str__(self): return "<Change id=%s name=%s>" % (self.id, self.name) @classmethod def validate(cls, data): try: jsonschema.validate(data, cls.schema) except jsonschema.ValidationError as exc: raise changeling.exception.ValidationError(exc) def is_valid(self): try: self.validate(self.to_dict()) except changeling.exception.ValidationError: return False else: return True
Switch test runtime widget to show runtime by classes. Not only was information overflow, also optimizing runtime by slowest class first should bring most change (instead of slowest test)
(function (widget, zoomableSunburst) { // Following http://bl.ocks.org/metmajer/5480307 var diameter = 600; var svg = widget.create("Avg test runtime by class", "Color: Job/Test Suite, Arc size: duration", "/testclasses.csv") .svg(diameter); var graph = zoomableSunburst(svg, diameter); var title = function (entry) { var runtime = entry.averageRuntime ? ' (' + entry.averageRuntime + ' ms)' : ''; return entry.name + runtime; }; var transformTestcase = function (testcase) { return { name: testcase.name, size: testcase.averageRuntime, title: title(testcase) }; }; var transformTestsuite = function (suite) { return { name: suite.name, children: suite.children.map(function (child) { if (child.children) { return transformTestsuite(child); } else { return transformTestcase(child); } }) }; }; var transformTestsuites = function (jobMap) { return Object.keys(jobMap) .map(function (jobName) { var job = jobMap[jobName]; return { name: jobName, children: job.children.map(transformTestsuite) }; }); }; d3.json('/testclasses', function (_, testsuites) { var data = { name: "Testsuites", children: transformTestsuites(testsuites) }; graph.render(data); }); }(widget, zoomableSunburst));
(function (widget, zoomableSunburst) { // Following http://bl.ocks.org/metmajer/5480307 var diameter = 600; var svg = widget.create("Avg test runtime", "Color: Job/Test Suite, Arc size: duration", "/testsuites.csv") .svg(diameter); var graph = zoomableSunburst(svg, diameter); var title = function (entry) { var runtime = entry.averageRuntime ? ' (' + entry.averageRuntime + ' ms)' : ''; return entry.name + runtime; }; var transformTestcase = function (testcase) { return { name: testcase.name, size: testcase.averageRuntime, title: title(testcase) }; }; var transformTestsuite = function (suite) { return { name: suite.name, children: suite.children.map(function (child) { if (child.children) { return transformTestsuite(child); } else { return transformTestcase(child); } }) }; }; var transformTestsuites = function (jobMap) { return Object.keys(jobMap) .map(function (jobName) { var job = jobMap[jobName]; return { name: jobName, children: job.children.map(transformTestsuite) }; }); }; d3.json('/testsuites', function (_, testsuites) { var data = { name: "Testsuites", children: transformTestsuites(testsuites) }; graph.render(data); }); }(widget, zoomableSunburst));
Update meta-info, first public package exposed
import os import shutil import sys from setuptools import setup from setuptools.command.install import install import bzt class InstallWithHook(install, object): """ Command adding post-install hook to setup """ def run(self): """ Do the command's job! """ install.run(self) self.__hook() def __hook(self): dirname = os.getenv("VIRTUAL_ENV", "") + os.path.sep + "etc" + os.path.sep + "bzt.d" sys.stdout.write("Creating %s" % dirname) if not os.path.exists(dirname): os.makedirs(dirname) src = os.path.dirname(__file__) src += os.path.sep + "bzt" + os.path.sep + "10-base.json" sys.stdout.write("Copying %s to %s" % (src, dirname)) shutil.copy(src, dirname + os.path.sep) setup( name="bzt", version=bzt.version, description='Taurus Tool for Continuous Testing', author='Andrey Pokhilko', author_email='[email protected]', url='https://github.com/Blazemeter/taurus/', install_requires=[ 'pyyaml', 'psutil', 'colorlog', 'lxml', 'cssselect', 'urwid' ], packages=['bzt', 'bzt.modules'], entry_points={ 'console_scripts': [ 'bzt=bzt.cli:main', ], }, package_data={ "bzt": [] }, cmdclass=dict(install=InstallWithHook) )
import os import shutil import sys from setuptools import setup from setuptools.command.install import install import bzt class InstallWithHook(install, object): """ Command adding post-install hook to setup """ def run(self): """ Do the command's job! """ install.run(self) self.__hook() def __hook(self): dirname = os.getenv("VIRTUAL_ENV", "") + os.path.sep + "etc" + os.path.sep + "bzt.d" sys.stdout.write("Creating %s" % dirname) if not os.path.exists(dirname): os.makedirs(dirname) src = os.path.dirname(__file__) src += os.path.sep + "bzt" + os.path.sep + "10-base.json" sys.stdout.write("Copying %s to %s" % (src, dirname)) shutil.copy(src, dirname + os.path.sep) setup( name="bzt", version=bzt.version, install_requires=[ 'pyyaml', 'psutil', 'colorlog', 'lxml', 'cssselect', 'urwid' ], packages=['bzt', 'bzt.modules'], entry_points={ 'console_scripts': [ 'bzt=bzt.cli:main', ], }, package_data={ "bzt": [] }, cmdclass=dict(install=InstallWithHook) )
Update search:reindex to populate set of indices
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Elasticsearch; use App\Console\Helpers\Indexer; class ReindexSearch extends Command { use Indexer; protected $signature = 'search:reindex {dest : The name of the index to copy documents to} {source? : The prefix of the indexes to create the alias from}'; protected $description = 'Copy documents from one set of indices to another'; public function handle() { $source = env('ELASTICSEARCH_INDEX', 'test-latest-prefix'); $dest = $this->argument('dest'); if ($this->argument('source')) { $source = $this->argument('source'); } foreach (allModelsThatUse(\App\Models\ElasticSearchable::class) as $model) { $endpoint = endpointFor($model); $index = $source .'-' .$endpoint; $params = [ 'wait_for_completion' => false, 'body' => [ 'source' => [ 'index' => $index, 'size' => 100, ], 'dest' => [ 'index' => $dest .'-' .$endpoint, ], ], ]; $return = Elasticsearch::reindex($params); $this->info('Reindex from ' .$index .'has started. You can monitor the process here: ' .$this->baseUrl() .'/_tasks/' .$return['task']); } } }
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Elasticsearch; use App\Console\Helpers\Indexer; class ReindexSearch extends Command { use Indexer; protected $signature = 'search:reindex {source : The name of the index to copy documents from} {dest? : The name of the index to copy documents to}'; protected $description = 'Copy documents from one index to another'; public function handle() { $source = $this->argument('source'); $dest = env('ELASTICSEARCH_INDEX', 'data_aggregator_test'); if ($this->argument('dest')) { $dest = $this->argument('dest'); } $params = [ 'wait_for_completion' => false, 'body' => [ 'source' => [ 'index' => $source, 'size' => 100, ], 'dest' => [ 'index' => $dest, ], ], ]; $return = Elasticsearch::reindex($params); $this->info('Reindex has started. You can monitor the process here: ' .$this->baseUrl() .'/_tasks/' .$return['task']); } }
Add method for raising not supported error
def notsupported(mode): raise NotImplementedError("Operation not supported for mode '%s'" % mode) def check_spark(): SparkContext = False try: from pyspark import SparkContext finally: return SparkContext def check_path(path, credentials=None): """ Check that specified output path does not already exist The ValueError message will suggest calling with overwrite=True; this function is expected to be called from the various output methods that accept an 'overwrite' keyword argument. """ from thunder.data.readers import get_file_reader reader = get_file_reader(path)(credentials=credentials) existing = reader.list(path, directories=True) if existing: raise ValueError("Path %s appears to already exist. Specify a new directory, " "or call " % path + "with overwrite=True to overwrite.") def connection_with_anon(credentials, anon=True): """ Connect to S3 with automatic handling for anonymous access. Parameters ---------- credentials : dict AWS access key ('access') and secret access key ('secret') anon : boolean, optional, default = True Whether to make an anonymous connection if credentials fail to authenticate """ from boto.s3.connection import S3Connection from boto.exception import NoAuthHandlerFound try: conn = S3Connection(aws_access_key_id=credentials['access'], aws_secret_access_key=credentials['secret']) return conn except NoAuthHandlerFound: if anon: conn = S3Connection(anon=True) return conn else: raise
def check_spark(): SparkContext = False try: from pyspark import SparkContext finally: return SparkContext def check_path(path, credentials=None): """ Check that specified output path does not already exist The ValueError message will suggest calling with overwrite=True; this function is expected to be called from the various output methods that accept an 'overwrite' keyword argument. """ from thunder.data.readers import get_file_reader reader = get_file_reader(path)(credentials=credentials) existing = reader.list(path, directories=True) if existing: raise ValueError("Path %s appears to already exist. Specify a new directory, " "or call " % path + "with overwrite=True to overwrite.") def connection_with_anon(credentials, anon=True): """ Connect to S3 with automatic handling for anonymous access. Parameters ---------- credentials : dict AWS access key ('access') and secret access key ('secret') anon : boolean, optional, default = True Whether to make an anonymous connection if credentials fail to authenticate """ from boto.s3.connection import S3Connection from boto.exception import NoAuthHandlerFound try: conn = S3Connection(aws_access_key_id=credentials['access'], aws_secret_access_key=credentials['secret']) return conn except NoAuthHandlerFound: if anon: conn = S3Connection(anon=True) return conn else: raise
Fix bounds element touch area incorrect issue.
package com.mocircle.cidrawing.element; import android.graphics.Matrix; import android.graphics.Path; import android.graphics.RectF; /** * A kind of element which is surrounded by the bounds. */ public abstract class BoundsElement extends DrawElement { protected transient RectF originalBoundingBox; protected transient Path boundingPath; @Override public void applyMatrixForData(Matrix matrix) { super.applyMatrixForData(matrix); boundingPath.transform(matrix); } @Override public void updateBoundingBox() { if (boundingPath != null) { RectF box = new RectF(); boundingPath.computeBounds(box, true); setBoundingBox(box); } } @Override public RectF getOuterBoundingBox() { if (boundingPath != null) { Path path = new Path(boundingPath); path.transform(getDisplayMatrix()); RectF box = new RectF(); path.computeBounds(box, true); return box; } return new RectF(); } @Override public Path getTouchableArea() { if (boundingPath != null) { return boundingPath; } else { return new Path(); } } @Override protected void cloneTo(BaseElement element) { super.cloneTo(element); if (element instanceof BoundsElement) { BoundsElement obj = (BoundsElement) element; if (originalBoundingBox != null) { obj.originalBoundingBox = new RectF(originalBoundingBox); } if (boundingPath != null) { obj.boundingPath = new Path(boundingPath); } } } protected abstract void calculateBoundingBox(); }
package com.mocircle.cidrawing.element; import android.graphics.Matrix; import android.graphics.Path; import android.graphics.RectF; /** * A kind of element which is surrounded by the bounds. */ public abstract class BoundsElement extends DrawElement { protected transient RectF originalBoundingBox; protected transient Path boundingPath; @Override public void applyMatrixForData(Matrix matrix) { super.applyMatrixForData(matrix); boundingPath.transform(matrix); } @Override public void updateBoundingBox() { if (boundingPath != null) { RectF box = new RectF(); boundingPath.computeBounds(box, true); setBoundingBox(box); } } @Override public RectF getOuterBoundingBox() { if (boundingPath != null) { Path path = new Path(boundingPath); path.transform(getDisplayMatrix()); RectF box = new RectF(); path.computeBounds(box, true); return box; } return new RectF(); } @Override protected void cloneTo(BaseElement element) { super.cloneTo(element); if (element instanceof BoundsElement) { BoundsElement obj = (BoundsElement) element; if (originalBoundingBox != null) { obj.originalBoundingBox = new RectF(originalBoundingBox); } if (boundingPath != null) { obj.boundingPath = new Path(boundingPath); } } } protected abstract void calculateBoundingBox(); }
Add the eslint-pragma for AMD to be more in context
(function (name, definition) { if (typeof define === 'function') { // AMD /* eslint-env amd */ define(definition) } else if (typeof module !== 'undefined' && module.exports) { // Node.js module.exports = definition() } else { // Browser window[name] = definition() } })('nullPrune', function () { function isObject (input) { return input && (typeof input === 'object') } function ownKeys (obj) { var key var ownKeys = [] var hasOwnProperty = Object.prototype.hasOwnProperty for (key in obj) { if (hasOwnProperty.call(obj, key)) { ownKeys.push(key) } } return ownKeys } function nullPrune (inputObject, context) { var objectKey = context.objectKey var parentObject = context.parentObject var keys = ownKeys(inputObject) var k var key var node for (k in keys) { key = keys[k] node = inputObject[key] if (isObject(node)) { nullPrune(node, { objectKey: key, parentObject: inputObject }) } else if (node == null) { delete inputObject[key] } } if (parentObject && ownKeys(inputObject).length === 0) { delete parentObject[objectKey] } } return function (inputObject) { if (!isObject(inputObject)) { return inputObject } nullPrune(inputObject, {}) return inputObject } })
/* eslint-env amd */ (function (name, definition) { if (typeof define === 'function') { // AMD define(definition) } else if (typeof module !== 'undefined' && module.exports) { // Node.js module.exports = definition() } else { // Browser window[name] = definition() } })('nullPrune', function () { function isObject (input) { return input && (typeof input === 'object') } function ownKeys (obj) { var key var ownKeys = [] var hasOwnProperty = Object.prototype.hasOwnProperty for (key in obj) { if (hasOwnProperty.call(obj, key)) { ownKeys.push(key) } } return ownKeys } function nullPrune (inputObject, context) { var objectKey = context.objectKey var parentObject = context.parentObject var keys = ownKeys(inputObject) var k var key var node for (k in keys) { key = keys[k] node = inputObject[key] if (isObject(node)) { nullPrune(node, { objectKey: key, parentObject: inputObject }) } else if (node == null) { delete inputObject[key] } } if (parentObject && ownKeys(inputObject).length === 0) { delete parentObject[objectKey] } } return function (inputObject) { if (!isObject(inputObject)) { return inputObject } nullPrune(inputObject, {}) return inputObject } })
Send the data in the functions
"use strict"; // Dependencies const readJson = require("r-json") , writeJson = require("w-json") , mapO = require("map-o") , ul = require("ul") , findValue = require("find-value") ; /** * packy * Sets the default fields in the package.json file. * * @name packy * @function * @param {String} path The path to the `package.json` file. * @param {Object} def An object containing the fields that should be merged in the package.json. * @param {Function} fn The callback function. */ module.exports = function packy(path, def, fn) { readJson(path, (err, data) => { if (err) { return fn(err); } var merged = ul.deepMerge(def, data); let merge = (current, parents) => { return mapO(current, function (v, n) { var p = parents.concat([n]) if (typeof v === "object") { return merge(v, p); } if (typeof v === "function") { return v(findValue(data, p.join(".")), data); } return v; }); }; merge(merged, []); writeJson(path, merged, fn); }); };
"use strict"; // Dependencies const readJson = require("r-json") , writeJson = require("w-json") , mapO = require("map-o") , ul = require("ul") , findValue = require("find-value") ; /** * packy * Sets the default fields in the package.json file. * * @name packy * @function * @param {String} path The path to the `package.json` file. * @param {Object} def An object containing the fields that should be merged in the package.json. * @param {Function} fn The callback function. */ module.exports = function packy(path, def, fn) { readJson(path, (err, data) => { if (err) { return fn(err); } var merged = ul.deepMerge(def, data); let merge = (current, parents) => { return mapO(current, function (v, n) { var p = parents.concat([n]) if (typeof v === "object") { return merge(v, p); } if (typeof v === "function") { return v(findValue(data, p.join("."))); } return v; }); }; merge(merged, []); writeJson(path, merged, fn); }); };
Use ENJAZACESSS when is access is provided
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY consumer_secret = settings.SOCIAL_AUTH_TWITTER_SECRET access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: consumer_key = settings.ENJAZACCOUNTS_TWITTER_KEY consumer_secret = settings.ENJAZACCOUNTS_TWITTER_SECRET access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
import twitter from django.core.management.base import BaseCommand from django.conf import settings from core.models import Tweet class Command(BaseCommand): help = "Send out tweets." def handle(self, *args, **options): for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5): if tweet.user: user_tokens = tweet.user.social_auth.all()[0].tokens access_token = user_tokens['oauth_token'] access_token_secret = user_tokens['oauth_token_secret'] elif tweet.access: access_token = tweet.access.access_token access_token_secret = tweet.access.access_token_secret api = twitter.Api(consumer_key=settings.SOCIAL_AUTH_TWITTER_KEY, consumer_secret=settings.SOCIAL_AUTH_TWITTER_SECRET, access_token_key=access_token, access_token_secret=access_token_secret,) try: if tweet.media_path: status = api.PostUpdate(tweet.text, media=tweet.media_path) else: status = api.PostUpdate(tweet.text) except twitter.TwitterError, e: print "Something went wrong with #{}: ".format(tweet.pk), e tweet.failed_trials += 1 tweet.save() continue tweet.tweet_id = status.id tweet.was_sent = True tweet.save()
Use select method to filter return data when retrieving a user's stats.
'use strict'; const Promise = require('bluebird'); const UserStats = require('../models/UserStats'); module.exports = function() { const create = function(userId) { return new Promise((resolve, reject) => { UserStats.create({ userId: userId }) .then((newUserStats) => { resolve(newUserStats.toObject()); }) .catch(reject); }); }; const getByDocOrUserId = function(docOrUserId) { return new Promise((resolve, reject) => { UserStats.findOne({ $or: [ { _id: docOrUserId }, { userId: docOrUserId }, ], }) .select('-__v -_id -userId') .exec() .then((userStats) => { resolve(userStats); }) .catch(reject); }); }; const updateByDocOrUserId = function(docOrUserId, updateOptions) { return new Promise((resolve, reject) => { UserStats.findOneAndUpdate( { $or: [ { _id: docOrUserId }, { userId: docOrUserId }, ], }, updateOptions, { new: true } ) .then(resolve) .catch(reject); }); }; return { create: create, getByDocOrUserId: getByDocOrUserId, updateByDocOrUserId: updateByDocOrUserId, }; };
'use strict'; const Promise = require('bluebird'); const UserStats = require('../models/UserStats'); module.exports = function() { const create = function(userId) { return new Promise((resolve, reject) => { UserStats.create({ userId: userId }) .then((newUserStats) => { resolve(newUserStats.toObject()); }) .catch(reject); }); }; const getByDocOrUserId = function(docOrUserId) { return new Promise((resolve, reject) => { UserStats.findOne({ $or: [ { _id: docOrUserId }, { userId: docOrUserId }, ], }) .then((userStats) => { resolve(userStats); }) .catch(reject); }); }; const updateByDocOrUserId = function(docOrUserId, updateOptions) { return new Promise((resolve, reject) => { UserStats.findOneAndUpdate( { $or: [ { _id: docOrUserId }, { userId: docOrUserId }, ], }, updateOptions, { new: true } ) .then(resolve) .catch(reject); }); }; return { create: create, getByDocOrUserId: getByDocOrUserId, updateByDocOrUserId: updateByDocOrUserId, }; };
Replace deprecated class (since Symphony 2.6)
<?php if (!defined('ENMDIR')) define('ENMDIR', EXTENSIONS . "/email_newsletter_manager"); if (!defined('ENVIEWS')) define('ENVIEWS', ENMDIR . "/content/templates"); class contentExtensionemail_newsletter_managerpublishfield extends XMLPage { public function view() { $this->addHeaderToPage('Content-Type', 'text/html'); $field_id = $this->_context[0]; $entry_id = $this->_context[1]; $this->_context['entry_id'] = $entry_id; try { $entry = EntryManager::fetch($entry_id); $entry = $entry[0]; if (!is_a($entry, 'Entry')) { $this->_status = 404; return; } $field = FieldManager::fetch($field_id); if (!is_a($field, 'Field')) { $this->_status = 404; return; } $field->set('id', $field_id); $entry_data = $entry->getData(); $data = new XMLElement('field'); $field->displayPublishPanel($data, $entry_data[$field_id]); echo $data->generate(true); exit; $this->_Result->appendChild($data); } catch (Exception $e) { } } public function addScriptToHead() { } public function addStylesheetToHead() { } }
<?php if (!defined('ENMDIR')) define('ENMDIR', EXTENSIONS . "/email_newsletter_manager"); if (!defined('ENVIEWS')) define('ENVIEWS', ENMDIR . "/content/templates"); class contentExtensionemail_newsletter_managerpublishfield extends AjaxPage { public function view() { $this->addHeaderToPage('Content-Type', 'text/html'); $field_id = $this->_context[0]; $entry_id = $this->_context[1]; $this->_context['entry_id'] = $entry_id; try { $entry = EntryManager::fetch($entry_id); $entry = $entry[0]; if (!is_a($entry, 'Entry')) { $this->_status = 404; return; } $field = FieldManager::fetch($field_id); if (!is_a($field, 'Field')) { $this->_status = 404; return; } $field->set('id', $field_id); $entry_data = $entry->getData(); $data = new XMLElement('field'); $field->displayPublishPanel($data, $entry_data[$field_id]); echo $data->generate(true); exit; $this->_Result->appendChild($data); } catch (Exception $e) { } } public function addScriptToHead() { } public function addStylesheetToHead() { } }
Unplug unit tests before moving them.
#!/usr/bin/env node "use strict"; // TODO: This script is duplicated in mlproj-core, do we want to change that? var chproc = require('child_process'); var proc = require('process'); function run(tests, callback) { if ( ! tests.length ) { // nothing else to do } else if ( tests[0].msg ) { let test = tests.shift(); console.log(test.msg); proc.chdir(test.cwd); run(tests); } else { let test = tests.shift(); // keep track of whether callback has been invoked to prevent multiple invocations var invoked = false; var process = chproc.fork(test.script); // listen for errors as they may prevent the exit event from firing process.on('error', function () { if ( invoked ) { return; } invoked = true; throw new Error(err); }); // execute the callback once the process has finished running process.on('exit', function (code) { if ( invoked ) { return; } invoked = true; if ( code ) { throw new Error('exit code ' + code); } run(tests); }); } } // first go to test dir proc.chdir('./test/'); run([ { msg: 'Run unit tests', cwd: './unit/' }, { script: './tui/parse-options.js' } ]);
#!/usr/bin/env node "use strict"; var chproc = require('child_process'); var proc = require('process'); function run(tests, callback) { if ( ! tests.length ) { // nothing else to do } else if ( tests[0].msg ) { let test = tests.shift(); console.log(test.msg); proc.chdir(test.cwd); run(tests); } else { let test = tests.shift(); // keep track of whether callback has been invoked to prevent multiple invocations var invoked = false; var process = chproc.fork(test.script); // listen for errors as they may prevent the exit event from firing process.on('error', function () { if ( invoked ) { return; } invoked = true; throw new Error(err); }); // execute the callback once the process has finished running process.on('exit', function (code) { if ( invoked ) { return; } invoked = true; if ( code ) { throw new Error('exit code ' + code); } run(tests); }); } } // first go to test dir proc.chdir('./test/'); run([ { msg: 'Run test scenarii', cwd: './scenarii/' }, { script: './run-scenario.js' }, { msg: 'Run unit tests', cwd: '../unit/' }, { script: './tui/parse-options.js' } ]);
Add required author_email to package metadata
import re from setuptools import find_packages, setup with open('netsgiro/__init__.py') as fh: metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", fh.read())) with open('README.rst') as fh: long_description = fh.read() setup( name='netsgiro', version=metadata['version'], description='File parsers for Nets AvtaleGiro and OCR Giro', long_description=long_description, url='https://github.com/otovo/python-netsgiro', author='Otovo AS', author_email='[email protected]', license='Apache License, Version 2.0', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], keywords='avtalegiro ocr giro', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=[ 'attrs', 'typing', # Needed for Python 3.4 ], extras_require={ 'dev': [ 'check-manifest', 'flake8', 'flake8-import-order', 'mypy', 'pytest', 'pytest-xdist', 'tox', ], }, )
import re from setuptools import find_packages, setup with open('netsgiro/__init__.py') as fh: metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", fh.read())) with open('README.rst') as fh: long_description = fh.read() setup( name='netsgiro', version=metadata['version'], description='File parsers for Nets AvtaleGiro and OCR Giro', long_description=long_description, url='https://github.com/otovo/python-netsgiro', author='Otovo AS', license='Apache License, Version 2.0', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], keywords='avtalegiro ocr giro', packages=find_packages(exclude=['tests', 'tests.*']), install_requires=[ 'attrs', 'typing', # Needed for Python 3.4 ], extras_require={ 'dev': [ 'check-manifest', 'flake8', 'flake8-import-order', 'mypy', 'pytest', 'pytest-xdist', 'tox', ], }, )
Disable debug output, add missing var
include('helma/webapp/response'); include('helma/engine'); include('helma/jsdoc'); require('core/array'); exports.index = function index(req, module) { var repo = new ScriptRepository(getRepositories()[1]); if (module && module != "/") { var jsdoc = []; var res = repo.getScriptResource(module); var currentDoc; parseScriptResource(res, function(node) { if (node.jsDoc) { currentDoc = extractTags(node.jsDoc) // print(currentDoc[0][1]); jsdoc.push(currentDoc); } else { // print(getTypeName(node) + " // " + getName(node)); if (isName(node) && getName(node) != "exports" && currentDoc && !currentDoc.name) { Object.defineProperty(currentDoc, 'name', {value: getName(node)}); } } return true; }); return new SkinnedResponse(getResource('./skins/module.html'), { title: "Module " + res.moduleName, jsdoc: jsdoc }); } else { var modules = repo.getScriptResources(true).sort(function(a, b) {return a.relativePath > b.relativePath}); return new SkinnedResponse(getResource('./skins/index.html'), { title: "API Documentation", modules: modules }); } }
include('helma/webapp/response'); include('helma/engine'); include('helma/jsdoc'); require('core/array'); exports.index = function index(req, module) { var repo = new ScriptRepository(getRepositories()[1]); if (module && module != "/") { var jsdoc = []; res = repo.getScriptResource(module); var currentDoc; parseScriptResource(res, function(node) { if (node.jsDoc) { currentDoc = extractTags(node.jsDoc) print(currentDoc[0][1]); jsdoc.push(currentDoc); } else { print(getTypeName(node) + " // " + getName(node)); if (isName(node) && getName(node) != "exports" && currentDoc && !currentDoc.name) { Object.defineProperty(currentDoc, 'name', {value: getName(node)}); } } return true; }); return new SkinnedResponse(getResource('./skins/module.html'), { title: "Module " + res.moduleName, jsdoc: jsdoc }); } else { var modules = repo.getScriptResources(true).sort(function(a, b) {return a.relativePath > b.relativePath}); return new SkinnedResponse(getResource('./skins/index.html'), { title: "API Documentation", modules: modules }); } }
Use the new django management commands definition (ArgumentParser)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from optparse import make_option from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy as _ class Command(BaseCommand): help = _("Collect information about all customers which accessed this shop.") def add_arguments(self, parser): parser.add_argument("--delete-expired", action='store_true', dest='delete_expired', help=_("Delete customers with expired sessions.")) def handle(self, verbosity, delete_expired, *args, **options): from shop.models.customer import CustomerModel data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0) for customer in CustomerModel.objects.iterator(): data['total'] += 1 if customer.user.is_active: data['active'] += 1 if customer.user.is_staff: data['staff'] += 1 if customer.is_registered(): data['registered'] += 1 elif customer.is_guest(): data['guests'] += 1 elif customer.is_anonymous(): data['anonymous'] += 1 if customer.is_expired(): data['expired'] += 1 if delete_expired: customer.delete() msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.") self.stdout.write(msg.format(**data))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from optparse import make_option from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy as _ class Command(BaseCommand): help = _("Collect information about all customers which accessed this shop.") option_list = BaseCommand.option_list + ( make_option("--delete-expired", action='store_true', dest='delete_expired', help=_("Delete customers with expired sessions.")), ) def handle(self, verbosity, delete_expired, *args, **options): from shop.models.customer import CustomerModel data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0) for customer in CustomerModel.objects.iterator(): data['total'] += 1 if customer.user.is_active: data['active'] += 1 if customer.user.is_staff: data['staff'] += 1 if customer.is_registered(): data['registered'] += 1 elif customer.is_guest(): data['guests'] += 1 elif customer.is_anonymous(): data['anonymous'] += 1 if customer.is_expired(): data['expired'] += 1 if delete_expired: customer.delete() msg = _("Customers in this shop: total={total}, anonymous={anonymous}, expired={expired}, active={active}, guests={guests}, registered={registered}, staff={staff}.") self.stdout.write(msg.format(**data))
Fix other tests with same regexp issue
import unittest, sys from HARK.validators import non_empty class ValidatorsTests(unittest.TestCase): ''' Tests for validator decorators which validate function arguments ''' def test_non_empty(self): @non_empty('list_a') def foo(list_a, list_b): pass try: foo([1], []) except Exception: self.fail() if sys.version[0] == '2': with self.assertRaisesRegexp( TypeError, 'Expected non-empty argument for parameter list_a', ): foo([], [1]) else: with self.assertRaisesRegex( TypeError, 'Expected non-empty argument for parameter list_a', ): foo([], [1]) @non_empty('list_a', 'list_b') def foo(list_a, list_b): pass if sys.version[0] == '2': with self.assertRaisesRegexp( TypeError, 'Expected non-empty argument for parameter list_b', ): foo([1], []) with self.assertRaisesRegexp( TypeError, 'Expected non-empty argument for parameter list_a', ): foo([], [1]) else: with self.assertRaisesRegex( TypeError, 'Expected non-empty argument for parameter list_b', ): foo([1], []) with self.assertRaisesRegex( TypeError, 'Expected non-empty argument for parameter list_a', ): foo([], [1])
import unittest, sys from HARK.validators import non_empty class ValidatorsTests(unittest.TestCase): ''' Tests for validator decorators which validate function arguments ''' def test_non_empty(self): @non_empty('list_a') def foo(list_a, list_b): pass try: foo([1], []) except Exception: self.fail() if sys.version[0] == '2': with self.assertRaisesRegexp( TypeError, 'Expected non-empty argument for parameter list_a', ): foo([], [1]) else: with self.assertRaisesRegex( TypeError, 'Expected non-empty argument for parameter list_a', ): foo([], [1]) @non_empty('list_a', 'list_b') def foo(list_a, list_b): pass with self.assertRaisesRegex( TypeError, 'Expected non-empty argument for parameter list_b', ): foo([1], []) with self.assertRaisesRegex( TypeError, 'Expected non-empty argument for parameter list_a', ): foo([], [1])
Fix vendor bundle example with polyfills
'use strict'; module.exports = { modify(defaultConfig, { target, dev }, webpack) { const config = defaultConfig; // stay immutable here // Change the name of the server output file in production if (target === 'web') { // modify filenaming to account for multiple entry files config.output.filename = dev ? 'static/js/[name].js' : 'static/js/[name].[hash:8].js'; // add another entry point called vendor config.entry.vendor = [ // now that React has moved, we need to Razzle's polyfills because // vendor.js will be loaded before our other entry. Razzle looks for // process.env.REACT_BUNDLE_PATH and will exclude the polyfill from our normal entry, // so we don't need to worry about including it twice. require.resolve('razzle/polyfills'), require.resolve('react'), require.resolve('react-dom'), // ... add any other vendor packages with require.resolve('xxx') ]; // Use Twitter Lite's vendor & manifest bundle approach // See https://medium.com/@paularmstrong/twitter-lite-and-high-performance-react-progressive-web-apps-at-scale-d28a00e780a3 config.plugins.push( new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'manifest'], minChunks: Infinity, }) ); // Extract common modules from all the chunks (requires no 'name' property) config.plugins.push( new webpack.optimize.CommonsChunkPlugin({ async: true, children: true, minChunks: 4, }) ); } return config; }, };
'use strict'; module.exports = { modify(defaultConfig, { target, dev }, webpack) { const config = defaultConfig; // stay immutable here // Change the name of the server output file in production if (target === 'web') { // modify filenaming to account for multiple entry files config.output.filename = dev ? 'static/js/[name].js' : 'static/js/[name].[hash:8].js'; // add another entry point called vendor config.entry.vendor = [ require.resolve('react'), require.resolve('react-dom'), // ... add any other vendor packages with require.resolve('xxx') ]; // Use Twitter Lite's vendor & manifest bundle approach // See https://medium.com/@paularmstrong/twitter-lite-and-high-performance-react-progressive-web-apps-at-scale-d28a00e780a3 config.plugins.push( new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'manifest'], minChunks: Infinity, }) ); // Extract common modules from all the chunks (requires no 'name' property) config.plugins.push( new webpack.optimize.CommonsChunkPlugin({ async: true, children: true, minChunks: 4, }) ); } return config; }, };
Fix problem with translation sanitation (Danish characters appear as HTML entities on the page): we don't need to sanitize our translations themselves, just the parameters substituted in.
(function() { 'use strict'; angular .module('openeApp.translations', [ 'pascalprecht.translate' ]) .factory('availableLanguages', AvailableLanguages) .config(config); var availableLanguages = { keys: ['en', 'da'], localesKeys: { 'en_US': 'en', 'en_UK': 'en', 'da_DK': 'da' } }; function AvailableLanguages(){ return availableLanguages; } config.$inject = ['$translateProvider', '$translatePartialLoaderProvider']; function config($translateProvider, $translatePartialLoaderProvider) { $translatePartialLoaderProvider.addPart('login'); $translatePartialLoaderProvider.addPart('menu'); $translatePartialLoaderProvider.addPart('common'); $translatePartialLoaderProvider.addPart('document.preview'); $translateProvider.useLoader('$translatePartialLoader', { urlTemplate: '/app/src/i18n/{lang}/{part}.json' }); $translateProvider.useSanitizeValueStrategy('sanitizeParameters'); $translateProvider .registerAvailableLanguageKeys(availableLanguages.keys, availableLanguages.localesKeys) .determinePreferredLanguage(); } })();
(function() { 'use strict'; angular .module('openeApp.translations', [ 'pascalprecht.translate' ]) .factory('availableLanguages', AvailableLanguages) .config(config); var availableLanguages = { keys: ['en', 'da'], localesKeys: { 'en_US': 'en', 'en_UK': 'en', 'da_DK': 'da' } }; function AvailableLanguages(){ return availableLanguages; } config.$inject = ['$translateProvider', '$translatePartialLoaderProvider']; function config($translateProvider, $translatePartialLoaderProvider) { $translatePartialLoaderProvider.addPart('login'); $translatePartialLoaderProvider.addPart('menu'); $translatePartialLoaderProvider.addPart('common'); $translatePartialLoaderProvider.addPart('document.preview'); $translateProvider.useLoader('$translatePartialLoader', { urlTemplate: '/app/src/i18n/{lang}/{part}.json' }); $translateProvider.useSanitizeValueStrategy('sanitize'); $translateProvider .registerAvailableLanguageKeys(availableLanguages.keys, availableLanguages.localesKeys) .determinePreferredLanguage(); } })();
Clean up access checker interface
<?php namespace Ordermind\LogicalPermissions; interface AccessCheckerInterface { /** * Sets the permission type collection. * * @param PermissionTypeCollectionInterface $permissionTypeCollection * * @return AccessCheckerInterface */ public function setPermissionTypeCollection(PermissionTypeCollectionInterface $permissionTypeCollection); /** * Gets the permission type collection. * * @return PermissionTypeCollectionInterface|null */ public function getPermissionTypeCollection(); /** * Sets the bypass access checker. * * @param BypassAccessCheckerInterface $bypassAccessChecker * * @return AccessCheckerInterface */ public function setBypassAccessChecker(BypassAccessCheckerInterface $bypassAccessChecker); /** * Gets the bypass access checker. * * @return BypassAccessCheckerInterface|null */ public function getBypassAccessChecker(); /** * Gets all keys that can be used in a permission tree. * * @return array Valid permission keys. */ public function getValidPermissionKeys(); /** * Checks access for a permission tree. * @param array|string|bool $permissions The permission tree to be evaluated. * @param array|object|null $context (optional) A context that could for example contain the evaluated user and document. Default value is NULL. * @param bool $allowBypass (optional) Determines whether bypassing access should be allowed. Default value is TRUE. * * @return bool TRUE if access is granted or FALSE if access is denied. */ public function checkAccess($permissions, $context = null, $allowBypass = true); }
<?php namespace Ordermind\LogicalPermissions; interface AccessCheckerInterface { /** * Sets the permission type collection. * * @param \Ordermind\LogicalPermissions\PermissionTypeCollectionInterface $permissionTypeCollection * * @return \Ordermind\LogicalPermissions\AccessCheckerInterface */ public function setPermissionTypeCollection(\Ordermind\LogicalPermissions\PermissionTypeCollectionInterface $permissionTypeCollection); /** * Gets the permission type collection. * * @return \Ordermind\LogicalPermissions\PermissionTypeCollectionInterface|NULL */ public function getPermissionTypeCollection(); /** * Sets the bypass access checker. * * @param \Ordermind\LogicalPermissions\BypassAccessCheckerInterface $bypassAccessChecker * * @return \Ordermind\LogicalPermissions\AccessCheckerInterface */ public function setBypassAccessChecker(BypassAccessCheckerInterface $bypassAccessChecker); /** * Gets the bypass access checker. * * @return \Ordermind\LogicalPermissions\BypassAccessCheckerInterface|NULL */ public function getBypassAccessChecker(); /** * Gets all keys that can be used in a permission tree. * * @return array Valid permission keys. */ public function getValidPermissionKeys(); /** * Checks access for a permission tree. * @param array|string|bool $permissions The permission tree to be evaluated. * @param array|object|NULL $context (optional) A context that could for example contain the evaluated user and document. Default value is NULL. * @param bool $allowBypass (optional) Determines whether bypassing access should be allowed. Default value is TRUE. * @return bool TRUE if access is granted or FALSE if access is denied. */ public function checkAccess($permissions, $context = NULL, $allowBypass = TRUE); }
Mark as requiring at least Python 3.6
#!/usr/bin/env python3 import os import re from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: long_description = readme.read() with open(os.path.join(os.path.dirname(__file__), 'pyhdfs', '__init__.py')) as py: version_match = re.search(r"__version__ = '(.+?)'", py.read()) assert version_match version = version_match.group(1) with open(os.path.join(os.path.dirname(__file__), 'dev_requirements.txt')) as dev_requirements: tests_require = dev_requirements.read().splitlines() setup( name="PyHDFS", version=version, description="Pure Python HDFS client", long_description=long_description, url='https://github.com/jingw/pyhdfs', author="Jing Wang", author_email="[email protected]", license="MIT License", packages=['pyhdfs'], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Topic :: System :: Filesystems", ], install_requires=[ 'requests', 'simplejson', ], tests_require=tests_require, package_data={ '': ['*.rst'], 'pyhdfs': ['py.typed'] }, python_requires='>=3.6', )
#!/usr/bin/env python3 import os import re from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: long_description = readme.read() with open(os.path.join(os.path.dirname(__file__), 'pyhdfs', '__init__.py')) as py: version_match = re.search(r"__version__ = '(.+?)'", py.read()) assert version_match version = version_match.group(1) with open(os.path.join(os.path.dirname(__file__), 'dev_requirements.txt')) as dev_requirements: tests_require = dev_requirements.read().splitlines() setup( name="PyHDFS", version=version, description="Pure Python HDFS client", long_description=long_description, url='https://github.com/jingw/pyhdfs', author="Jing Wang", author_email="[email protected]", license="MIT License", packages=['pyhdfs'], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Topic :: System :: Filesystems", ], install_requires=[ 'requests', 'simplejson', ], tests_require=tests_require, package_data={ '': ['*.rst'], 'pyhdfs': ['py.typed'] }, )
Add postgresql extra to sqlalchemy Was implicitly being installed with testcontainers
import re from setuptools import setup, find_packages INIT_FILE = 'pg_grant/__init__.py' init_data = open(INIT_FILE).read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_data)) VERSION = metadata['version'] LICENSE = metadata['license'] DESCRIPTION = metadata['description'] AUTHOR = metadata['author'] EMAIL = metadata['email'] requires = { 'attrs', } extras_require = { ':python_version<"3.5"': { 'typing', }, 'query': { 'sqlalchemy[postgresql]', }, 'test': { 'pytest>=3.0', 'testcontainers', }, 'docstest': { 'doc8', 'sphinx', 'sphinx_rtd_theme', }, 'pep8test': { 'flake8', 'pep8-naming', }, } setup( name='pg_grant', version=VERSION, description=DESCRIPTION, # long_description=open('README.rst').read(), author=AUTHOR, author_email=EMAIL, url='https://github.com/RazerM/pg_grant', packages=find_packages(exclude=['tests']), classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], license=LICENSE, install_requires=requires, extras_require=extras_require, tests_require=extras_require['test'])
import re from setuptools import setup, find_packages INIT_FILE = 'pg_grant/__init__.py' init_data = open(INIT_FILE).read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_data)) VERSION = metadata['version'] LICENSE = metadata['license'] DESCRIPTION = metadata['description'] AUTHOR = metadata['author'] EMAIL = metadata['email'] requires = { 'attrs', } extras_require = { ':python_version<"3.5"': { 'typing', }, 'query': { 'sqlalchemy', }, 'test': { 'pytest>=3.0', 'testcontainers', }, 'docstest': { 'doc8', 'sphinx', 'sphinx_rtd_theme', }, 'pep8test': { 'flake8', 'pep8-naming', }, } setup( name='pg_grant', version=VERSION, description=DESCRIPTION, # long_description=open('README.rst').read(), author=AUTHOR, author_email=EMAIL, url='https://github.com/RazerM/pg_grant', packages=find_packages(exclude=['tests']), classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], license=LICENSE, install_requires=requires, extras_require=extras_require, tests_require=extras_require['test'])
Solve data undefined in error event
/** * @author Marcelo G. */ (function ($) { $.viaAjaxLite = { sendForm: function(selector, callback) { var jqElement = $(selector); var self = this; $(selector + ' input[type="submit"], ' + selector + ' button[type="submit"]' ).bind('click', function(event) { event.preventDefault(); self.send({ url: jqElement.attr('action'), type: jqElement.attr('method'), data: jqElement.serialize(), target: jqElement.attr('target') || jqElement.attr('rel') }, callback ); }); }, load: function(options, callback) { this.send(options, callback); }, send: function(options, callback) { // enviar consulta options = $.extend({type: 'get', data: {}}, options); $.ajax({ url: options.url, type: options.type, data: options.data, success: function(data, textStatus, jqXHR) { // procesar respuesta $(options.target).html(data); return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]); }, beforeSend: function() { $(options.target).html('<div class="progress progress-striped active"><div style="width: 45%" class="progress-bar"></div></div>'); }, error: function(data, textStatus, jqXHR) { return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]); } }); } }; }(typeof jQuery === 'function' ? jQuery : this));
/** * @author Marcelo G. */ (function ($) { $.viaAjaxLite = { sendForm: function(selector, callback) { var jqElement = $(selector); var self = this; $(selector + ' input[type="submit"], ' + selector + ' button[type="submit"]' ).bind('click', function(event) { event.preventDefault(); self.send({ url: jqElement.attr('action'), type: jqElement.attr('method'), data: jqElement.serialize(), target: jqElement.attr('target') || jqElement.attr('rel') }, callback ); }); }, load: function(options, callback) { this.send(options, callback); }, send: function(options, callback) { // enviar consulta options = $.extend({type: 'get', data: {}}, options); $.ajax({ url: options.url, type: options.type, data: options.data, success: function(data, textStatus, jqXHR) { // procesar respuesta $(options.target).html(data); return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]); }, beforeSend: function() { $(options.target).html('<div class="progress progress-striped active"><div style="width: 45%" class="progress-bar"></div></div>'); }, error: function() { return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]); } }); } }; }(typeof jQuery === 'function' ? jQuery : this));
Add a flag on the yaml resources loader to parse custom tags
<?php namespace LAG\AdminBundle\Resource\Loader; use Exception; use Symfony\Component\Filesystem\Exception\FileNotFoundException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Symfony\Component\Yaml\Yaml; class ResourceLoader { /** * Load admins configuration in the yaml files found in the given resource path. An exception will be thrown if the * path is invalid. * * @throws Exception */ public function load(string $resourcesPath): array { $fileSystem = new Filesystem(); if (!$fileSystem->exists($resourcesPath)) { throw new FileNotFoundException(null, 0, null, $resourcesPath); } if (!is_dir($resourcesPath)) { throw new Exception(sprintf('The resources path %s should be a directory', $resourcesPath)); } $finder = new Finder(); $finder ->files() ->name('*.yaml') ->in($resourcesPath) ; $data = []; foreach ($finder as $fileInfo) { $yaml = Yaml::parse(file_get_contents($fileInfo->getRealPath()), Yaml::PARSE_CUSTOM_TAGS); if (!is_array($yaml)) { continue; } foreach ($yaml as $name => $admin) { $data[$name] = $admin; } } return $data; } }
<?php namespace LAG\AdminBundle\Resource\Loader; use Exception; use Symfony\Component\Filesystem\Exception\FileNotFoundException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Symfony\Component\Yaml\Yaml; class ResourceLoader { /** * Load admins configuration in the yaml files found in the given resource path. An exception will be thrown if the * path is invalid. * * @throws Exception */ public function load(string $resourcesPath): array { $fileSystem = new Filesystem(); if (!$fileSystem->exists($resourcesPath)) { throw new FileNotFoundException(null, 0, null, $resourcesPath); } if (!is_dir($resourcesPath)) { throw new Exception(sprintf('The resources path %s should be a directory', $resourcesPath)); } $finder = new Finder(); $finder ->files() ->name('*.yaml') ->in($resourcesPath) ; $data = []; foreach ($finder as $fileInfo) { $yaml = Yaml::parse(file_get_contents($fileInfo->getRealPath())); if (!is_array($yaml)) { continue; } foreach ($yaml as $name => $admin) { $data[$name] = $admin; } } return $data; } }
Fix possible undefined methods in inherited classes
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Stdlib\Hydrator\Filter; use InvalidArgumentException; use ReflectionException; use ReflectionMethod; use ReflectionParameter; /** * Filter that includes methods which have no parameters or only optional parameters */ class OptionalParametersFilter implements FilterInterface { /** * Map of methods already analyzed * by {@see \Zend\Stdlib\Hydrator\Filter\OptionalParametersFilter::filter()}, * cached for performance reasons * * @var bool[] */ protected static $propertiesCache = array(); /** * {@inheritDoc} */ public function filter($property) { if (isset(static::$propertiesCache[$property])) { return static::$propertiesCache[$property]; } try { $reflectionMethod = new ReflectionMethod($property); } catch (ReflectionException $exception) { throw new InvalidArgumentException(sprintf('Method %s doesn\'t exist', $property)); } $mandatoryParameters = array_filter( $reflectionMethod->getParameters(), function (ReflectionParameter $parameter) { return ! $parameter->isOptional(); } ); return static::$propertiesCache[$property] = empty($mandatoryParameters); } }
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Stdlib\Hydrator\Filter; use InvalidArgumentException; use ReflectionException; use ReflectionMethod; use ReflectionParameter; /** * Filter that includes methods which have no parameters or only optional parameters */ class OptionalParametersFilter implements FilterInterface { /** * Map of methods already analyzed * by {@see \Zend\Stdlib\Hydrator\Filter\OptionalParametersFilter::filter()}, * cached for performance reasons * * @var bool[] */ private static $propertiesCache = array(); /** * {@inheritDoc} */ public function filter($property) { if (isset(static::$propertiesCache[$property])) { return static::$propertiesCache[$property]; } try { $reflectionMethod = new ReflectionMethod($property); } catch (ReflectionException $exception) { throw new InvalidArgumentException(sprintf('Method %s doesn\'t exist', $property)); } $mandatoryParameters = array_filter( $reflectionMethod->getParameters(), function (ReflectionParameter $parameter) { return ! $parameter->isOptional(); } ); return static::$propertiesCache[$property] = empty($mandatoryParameters); } }
Make the description field much bigger
<?php namespace AppBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Form\FormMapper; class ServiceAdmin extends Admin { protected function configureFormFields(FormMapper $formMapper) { $formMapper->add('name', 'text'); $formMapper->add('description', 'textarea', ['required' => false, 'attr' => ['rows' => 15]]); $formMapper->add('dataMaintainer', 'text', ['required' => false]); $formMapper->add('endDate', 'date', ['required' => false]); $formMapper->add('providers', 'sonata_type_model', ['multiple' => true, 'required' => false]); $formMapper->add('stages', 'sonata_type_model', ['multiple' => true]); $formMapper->add('categories', 'sonata_type_model', ['multiple' => true]); $formMapper->add('serviceUsers', 'sonata_type_model', ['multiple' => true]); $formMapper->add('issues', 'sonata_type_model', ['multiple' => true, 'required' => false]); } protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('name') ->add('description') ->add('providers') ->add('stages') ->add('categories'); } protected function configureListFields(ListMapper $listMapper) { $listMapper->addIdentifier('name'); } }
<?php namespace AppBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Form\FormMapper; class ServiceAdmin extends Admin { protected function configureFormFields(FormMapper $formMapper) { $formMapper->add('name', 'text'); $formMapper->add('description', 'textarea', ['required' => false]); $formMapper->add('dataMaintainer', 'text', ['required' => false]); $formMapper->add('endDate', 'date', ['required' => false]); $formMapper->add('providers', 'sonata_type_model', ['multiple' => true, 'required' => false]); $formMapper->add('stages', 'sonata_type_model', ['multiple' => true]); $formMapper->add('categories', 'sonata_type_model', ['multiple' => true]); $formMapper->add('serviceUsers', 'sonata_type_model', ['multiple' => true]); $formMapper->add('issues', 'sonata_type_model', ['multiple' => true, 'required' => false]); } protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('name') ->add('description') ->add('providers') ->add('stages') ->add('categories'); } protected function configureListFields(ListMapper $listMapper) { $listMapper->addIdentifier('name'); } }
Update a helper class to perform a one-shot task. Add retry logic.
package org.deviceconnect.android.deviceplugin.alljoyn; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; public class OneShotSessionHandler { private static final int JOIN_RETRY_MAX = 5; private OneShotSessionHandler() { } public static void run(@NonNull final Context context, @NonNull final String busName, final short port, @NonNull final SessionJoinCallback callback) { final AllJoynDeviceApplication app = (AllJoynDeviceApplication) context.getApplicationContext(); AllJoynDeviceApplication.ResultReceiver resultReceiver = app.new ResultReceiver() { private int failedCount = 0; @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (resultCode != AllJoynDeviceApplication.RESULT_OK) { if (failedCount > JOIN_RETRY_MAX) { callback.onSessionFailed(busName, port); } else { ++failedCount; app.joinSession(busName, port, this); } return; } int sessionId = resultData.getInt(AllJoynDeviceApplication.PARAM_SESSION_ID); callback.onSessionJoined(busName, port, sessionId); app.leaveSession(sessionId, app.new ResultReceiver()); } }; app.joinSession(busName, port, resultReceiver); } public interface SessionJoinCallback { void onSessionJoined(@NonNull String busName, short port, int sessionId); void onSessionFailed(@NonNull String busName, short port); } }
package org.deviceconnect.android.deviceplugin.alljoyn; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; public class OneShotSessionHandler { private OneShotSessionHandler() { } public static void run(@NonNull final Context context, @NonNull final String busName, final short port, @NonNull final SessionJoinCallback callback) { final AllJoynDeviceApplication app = (AllJoynDeviceApplication) context.getApplicationContext(); app.joinSession(busName, port, app.new ResultReceiver() { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (resultCode != AllJoynDeviceApplication.RESULT_OK) { callback.onSessionFailed(busName, port); return; } int sessionId = resultData.getInt(AllJoynDeviceApplication.PARAM_SESSION_ID); callback.onSessionJoined(busName, port, sessionId); app.leaveSession(sessionId, app.new ResultReceiver()); } }); } public interface SessionJoinCallback { void onSessionJoined(@NonNull String busName, short port, int sessionId); void onSessionFailed(@NonNull String busName, short port); } }
Update floating sublayout to use floatDimensions
from base import SubLayout, Rect from Xlib import Xatom class TopLevelSubLayout(SubLayout): ''' This class effectively wraps a sublayout, and automatically adds a floating sublayout, ''' def __init__(self, sublayout_data, clientStack, theme): WrappedSubLayout, args = sublayout_data SubLayout.__init__(self, clientStack, theme) self.sublayouts.append(Floating(clientStack, theme, parent=self ) ) self.sublayouts.append(WrappedSubLayout(clientStack, theme, parent=self, **args ) ) class VerticalStack(SubLayout): def layout(self, rectangle, windows): SubLayout.layout(self, rectangle, windows) def configure(self, r, client): position = self.windows.index(client) cliheight = int(r.h / len(self.windows)) #inc border self.place(client, r.x, r.y + cliheight*position, r.w, cliheight, ) class Floating(SubLayout): def filter(self, client): return client.floating def request_rectangle(self, r, windows): return (Rect(0,0,0,0), r) #we want nothing def configure(self, r, client): d = client.floatDimensions self.place(client, **d)
from base import SubLayout, Rect from Xlib import Xatom class TopLevelSubLayout(SubLayout): ''' This class effectively wraps a sublayout, and automatically adds a floating sublayout, ''' def __init__(self, sublayout_data, clientStack, theme): WrappedSubLayout, args = sublayout_data SubLayout.__init__(self, clientStack, theme) self.sublayouts.append(Floating(clientStack, theme, parent=self ) ) self.sublayouts.append(WrappedSubLayout(clientStack, theme, parent=self, **args ) ) class VerticalStack(SubLayout): def layout(self, rectangle, windows): SubLayout.layout(self, rectangle, windows) def configure(self, r, client): position = self.windows.index(client) cliheight = int(r.h / len(self.windows)) #inc border self.place(client, r.x, r.y + cliheight*position, r.w, cliheight, ) class Floating(SubLayout): def filter(self, client): return client.floating def request_rectangle(self, r, windows): return (Rect(0,0,0,0), r) #we want nothing def configure(self, r, client): client.unhide() #let it be where it wants
Fix fenced code blocks rendering without language - Closes #19
<?php namespace allejo\stakx\Engines; use Highlight\Highlighter; class MarkdownEngine extends \Parsedown { protected $highlighter; public function __construct () { $this->highlighter = new Highlighter(); } protected function blockHeader($Line) { $Block = parent::blockHeader($Line); // Create our unique ids by sanitizing the header content $id = strtolower($Block['element']['text']); $id = str_replace(' ', '-', $id); $id = preg_replace('/[^0-9a-zA-Z-_]/', '', $id); $id = preg_replace('/-+/', '-', $id); $Block['element']['attributes']['id'] = $id; return $Block; } public function blockFencedCodeComplete ($block) { // The class has a `language-` prefix, remove this to get the language if (isset($block['element']['text']['attributes'])) { $language = substr($block['element']['text']['attributes']['class'], 9); try { $highlighted = $this->highlighter->highlight($language, $block['element']['text']['text']); $block['element']['text']['text'] = $highlighted->value; } catch (\DomainException $exception) {} return $block; } return parent::blockFencedCodeComplete($block); } }
<?php namespace allejo\stakx\Engines; use Highlight\Highlighter; class MarkdownEngine extends \Parsedown { protected $highlighter; public function __construct () { $this->highlighter = new Highlighter(); } protected function blockHeader($Line) { $Block = parent::blockHeader($Line); // Create our unique ids by sanitizing the header content $id = strtolower($Block['element']['text']); $id = str_replace(' ', '-', $id); $id = preg_replace('/[^0-9a-zA-Z-_]/', '', $id); $id = preg_replace('/-+/', '-', $id); $Block['element']['attributes']['id'] = $id; return $Block; } public function blockFencedCodeComplete ($block) { // The class has a `language-` prefix, remove this to get the language if (isset($block['element']['text']['attributes'])) { $language = substr($block['element']['text']['attributes']['class'], 9); try { $highlighted = $this->highlighter->highlight($language, $block['element']['text']['text']); $block['element']['text']['text'] = $highlighted->value; } catch (\DomainException $exception) {} } return $block; } }
Add Python 3 trove classifier
#-*- encoding: utf-8 -*- from setuptools import setup from setuptools.command.test import test as TestCommand import sys class Tox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import tox errno = tox.cmdline(self.test_args) sys.exit(errno) setup(name="django-money", version="0.5.0", description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as the money implementation.", url="https://github.com/jakewins/django-money", maintainer='Greg Reinbach', maintainer_email='[email protected]', packages=["djmoney", "djmoney.forms", "djmoney.models", "djmoney.templatetags", "djmoney.tests"], install_requires=['setuptools', 'Django >= 1.4, < 1.8', 'py-moneyed > 0.4', 'six'], platforms=['Any'], keywords=['django', 'py-money', 'money'], classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Framework :: Django", ], tests_require=['tox>=1.6.0'], cmdclass={'test': Tox}, )
#-*- encoding: utf-8 -*- from setuptools import setup from setuptools.command.test import test as TestCommand import sys class Tox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import tox errno = tox.cmdline(self.test_args) sys.exit(errno) setup(name="django-money", version="0.5.0", description="Adds support for using money and currency fields in django models and forms. Uses py-moneyed as the money implementation.", url="https://github.com/jakewins/django-money", maintainer='Greg Reinbach', maintainer_email='[email protected]', packages=["djmoney", "djmoney.forms", "djmoney.models", "djmoney.templatetags", "djmoney.tests"], install_requires=['setuptools', 'Django >= 1.4, < 1.8', 'py-moneyed > 0.4', 'six'], platforms=['Any'], keywords=['django', 'py-money', 'money'], classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ], tests_require=['tox>=1.6.0'], cmdclass={'test': Tox}, )
[SofaPython] FIX crash in python script when visualizing advanced timer output
import os import sys import Sofa # ploting import matplotlib.pyplot as plt # JSON deconding from collections import OrderedDict import json # argument parser: usage via the command line import argparse def measureAnimationTime(node, timerName, timerInterval, timerOutputType, resultFileName, simulationDeltaTime, iterations): # timer Sofa.timerSetInterval(timerName, timerInterval) # Set the number of steps neded to compute the timer Sofa.timerSetEnabled(timerName, True) resultFileName = resultFileName + ".log" rootNode = node.getRoot() with open(resultFileName, "w+") as outputFile : outputFile.write("{") i = 0 Sofa.timerSetOutputType(timerName, timerOutputType) while i < iterations: Sofa.timerBegin(timerName) rootNode.simulationStep(simulationDeltaTime) result = Sofa.timerEnd(timerName, rootNode) if result != None : outputFile.write(result + ",") oldResult = result i = i+1 last_pose = outputFile.tell() outputFile.seek(last_pose - 1) outputFile.write("\n}") outputFile.seek(7) firstStep = outputFile.read(1) outputFile.close() Sofa.timerSetEnabled(timerName, 0) print "[Scene info]: end of simulation." return 0
import os import sys import Sofa # ploting import matplotlib.pyplot as plt # JSON deconding from collections import OrderedDict import json # argument parser: usage via the command line import argparse def measureAnimationTime(node, timerName, timerInterval, timerOutputType, resultFileName, simulationDeltaTime, iterations): # timer Sofa.timerSetInterval(timerName, timerInterval) # Set the number of steps neded to compute the timer Sofa.timerSetEnabled(timerName, True) resultFileName = resultFileName + ".log" rootNode = node.getRoot() with open(resultFileName, "w+") as outputFile : outputFile.write("{") i = 0 Sofa.timerSetOutPutType(timerName, timerOutputType) while i < iterations: Sofa.timerBegin(timerName) rootNode.simulationStep(simulationDeltaTime) result = Sofa.timerEnd(timerName, rootNode) if result != None : outputFile.write(result + ",") oldResult = result i = i+1 last_pose = outputFile.tell() outputFile.seek(last_pose - 1) outputFile.write("\n}") outputFile.seek(7) firstStep = outputFile.read(1) outputFile.close() Sofa.timerSetEnabled(timerName, 0) print "[Scene info]: end of simulation." return 0
Put all syntax highlighting setup on the UI thread Fixes #13
package collabode.hilite; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager; import org.eclipse.jdt.internal.ui.text.JavaColorManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.IJavaPartitions; import org.eclipse.ui.PlatformUI; import collabode.JavaPadDocument; /** * Wrapper for {@link SemanticHighlightingManager} to operate on a {@link JavaPadDocument}. * Also acts as a messenger to pass along reconcile events. */ @SuppressWarnings("restriction") public class PadSemanticHighlighter { static final JavaColorManager COLORS = new JavaColorManager(false); public PadSemanticHighlighter(final JavaPadDocument doc) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { PadCompilationUnitEditor editor = new PadCompilationUnitEditor(); PadJavaSourceViewer viewer = new PadJavaSourceViewer(doc); JavaPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(doc, IJavaPartitions.JAVA_PARTITIONING); editor.config.getPresentationReconciler(viewer).install(viewer); // standard highlighting new SemanticHighlightingManager().install(editor, viewer, COLORS, PreferenceConstants.getPreferenceStore()); doc.addReconcileListener(editor); } }); } }
package collabode.hilite; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager; import org.eclipse.jdt.internal.ui.text.JavaColorManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.IJavaPartitions; import org.eclipse.ui.PlatformUI; import collabode.JavaPadDocument; /** * Wrapper for {@link SemanticHighlightingManager} to operate on a {@link JavaPadDocument}. * Also acts as a messenger to pass along reconcile events. */ @SuppressWarnings("restriction") public class PadSemanticHighlighter { static final JavaColorManager COLORS = new JavaColorManager(false); private final PadCompilationUnitEditor editor; private final PadJavaSourceViewer viewer; public PadSemanticHighlighter(final JavaPadDocument doc) { editor = new PadCompilationUnitEditor(); viewer = new PadJavaSourceViewer(doc); JavaPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(doc, IJavaPartitions.JAVA_PARTITIONING); PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { editor.config.getPresentationReconciler(viewer).install(viewer); // standard highlighting new SemanticHighlightingManager().install(editor, viewer, COLORS, PreferenceConstants.getPreferenceStore()); } }); doc.addReconcileListener(editor); } }
Use view_list icon for dashboard
export default class { constructor($scope, auth, toast) { 'ngInject'; $scope.buttons = [ { name: 'View Code', icon: 'code', show: true, href: 'https://github.com/mjhasbach/material-qna' }, { name: 'QnA', icon: 'question_answer', get show() { return $scope.user.data && $scope.view.current !== 'qna'; }, onClick: function() { $scope.view.current = 'qna'; } }, { name: 'Dashboard', icon: 'view_list', get show() { return $scope.user.data && $scope.view.current !== 'dashboard'; }, onClick: function() { $scope.view.current = 'dashboard'; } }, { name: 'Logout', icon: 'exit_to_app', get show() { return $scope.user.data; }, onClick: function() { auth.logout().then(function() { $scope.user.data = null; $scope.view.current = 'auth'; }).catch(function() { toast.show('Unable to log out'); }); } } ]; } }
export default class { constructor($scope, auth, toast) { 'ngInject'; $scope.buttons = [ { name: 'View Code', icon: 'code', show: true, href: 'https://github.com/mjhasbach/material-qna' }, { name: 'QnA', icon: 'question_answer', get show() { return $scope.user.data && $scope.view.current !== 'qna'; }, onClick: function() { $scope.view.current = 'qna'; } }, { name: 'Dashboard', icon: 'settings', get show() { return $scope.user.data && $scope.view.current !== 'dashboard'; }, onClick: function() { $scope.view.current = 'dashboard'; } }, { name: 'Logout', icon: 'exit_to_app', get show() { return $scope.user.data; }, onClick: function() { auth.logout().then(function() { $scope.user.data = null; $scope.view.current = 'auth'; }).catch(function() { toast.show('Unable to log out'); }); } } ]; } }
Use full pathname to perf_expectations in test. BUG=none TEST=none Review URL: http://codereview.chromium.org/266055 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@28770 0039d316-1c4b-4281-b951-d872f2087c98
#!/usr/bin/python # Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for perf_expectations. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit API built into gcl. """ UNIT_TESTS = [ 'tests.perf_expectations_unittest', ] PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json' def CheckChangeOnUpload(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == path: run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) return output def CheckChangeOnCommit(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == path: run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api, output_api)) return output
#!/usr/bin/python # Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for perf_expectations. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit API built into gcl. """ UNIT_TESTS = [ 'tests.perf_expectations_unittest', ] PERF_EXPECTATIONS = 'perf_expectations.json' def CheckChangeOnUpload(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == input_api.os_path.basename(path): run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) return output def CheckChangeOnCommit(input_api, output_api): run_tests = False for path in input_api.LocalPaths(): if PERF_EXPECTATIONS == input_api.os_path.basename(path): run_tests = True output = [] if run_tests: output.extend(input_api.canned_checks.RunPythonUnitTests(input_api, output_api, UNIT_TESTS)) output.extend(input_api.canned_checks.CheckDoNotSubmit(input_api, output_api)) return output
Use toFixed for bigjs filter
'use strict'; angular.module('omniFilters', []) .filter('bigjs', ['$sce', function ($sce) { return function (input, format, noZerosTrimming) { var dropFraction = false; if (input == null || format == null) return input; if (format === '') return ''; if (format.indexOf('.') < 0) { format = format.replace(/(\D*$)/, ".0$1"); dropFraction = true; } var nums = Big(input).toFixed(); if (!noZerosTrimming && nums !== '0') { nums = nums.replace(/0+(?=\D+$)|0+$/g, '').replace(/(^\D*|:)?0+/g, function(str, p1) {return p1 ? p1 + '0' : str;}); } nums = nums.split('.'); if (nums[1] !== undefined && format.indexOf('.') >= 0 && nums[1].replace(/\D/g, '') === '') { nums[1] = '0' + nums[1]; } if (nums.length > 1 && !dropFraction) { nums[0] = '<span class="numeral-left">' + nums[0] + '</span>'; nums[1] = '<span class="numeral-right">.' + nums[1] + '</span>'; } else { nums[0] = '<span class="numeral-integer">' + nums[0] + '</span>'; nums = [nums[0]]; } return $sce.trustAsHtml(nums.join('')); }; }]);
'use strict'; angular.module('omniFilters', []) .filter('bigjs', ['$sce', function ($sce) { return function (input, format, noZerosTrimming) { var dropFraction = false; if (input == null || format == null) return input; if (format === '') return ''; if (format.indexOf('.') < 0) { format = format.replace(/(\D*$)/, ".0$1"); dropFraction = true; } var nums = Big(input).valueOf(); if (!noZerosTrimming && nums !== '0') { nums = nums.replace(/0+(?=\D+$)|0+$/g, '').replace(/(^\D*|:)?0+/g, function(str, p1) {return p1 ? p1 + '0' : str;}); } nums = nums.split('.'); if (nums[1] !== undefined && format.indexOf('.') >= 0 && nums[1].replace(/\D/g, '') === '') { nums[1] = '0' + nums[1]; } if (nums.length > 1 && !dropFraction) { nums[0] = '<span class="numeral-left">' + nums[0] + '</span>'; nums[1] = '<span class="numeral-right">.' + nums[1] + '</span>'; } else { nums[0] = '<span class="numeral-integer">' + nums[0] + '</span>'; nums = [nums[0]]; } return $sce.trustAsHtml(nums.join('')); }; }]);
Use Object.getOwnPropertyNames for compatibility with native promises
'use strict'; var Promise = require('bluebird'); var sinon = require('sinon'); function thenable (promiseFactory) { return Object.getOwnPropertyNames(Promise.prototype) .filter(function (method) { return method !== 'then'; }) .reduce(function (acc, method) { acc[method] = function () { var args = arguments; var promise = this.then(); return promise[method].apply(promise, args); }; return acc; }, { then: function (resolve, reject) { return promiseFactory().then(resolve, reject); } }); } function resolves (value) { /*jshint validthis:true */ return this.returns(thenable(function () { return new Promise(function (resolve) { resolve(value); }); })); } sinon.stub.resolves = resolves; sinon.behavior.resolves = resolves; function rejects (err) { if (typeof err === 'string') { err = new Error(err); } /*jshint validthis:true */ return this.returns(thenable(function () { return new Promise(function (resolve, reject) { reject(err); }); })); } sinon.stub.rejects = rejects; sinon.behavior.rejects = rejects; module.exports = function (_Promise_) { if (typeof _Promise_ !== 'function') { throw new Error('A Promise constructor must be provided'); } else { Promise = _Promise_; } return sinon; };
'use strict'; var Promise = require('bluebird'); var sinon = require('sinon'); function thenable (promiseFactory) { return Object.keys(Promise.prototype) .filter(function (method) { return Promise.prototype.hasOwnProperty(method) && method !== 'then'; }) .reduce(function (acc, method) { acc[method] = function () { var args = arguments; var promise = this.then(); return promise[method].apply(promise, args); }; return acc; }, { then: function (resolve, reject) { return promiseFactory().then(resolve, reject); } }); } function resolves (value) { /*jshint validthis:true */ return this.returns(thenable(function () { return new Promise(function (resolve) { resolve(value); }); })); } sinon.stub.resolves = resolves; sinon.behavior.resolves = resolves; function rejects (err) { if (typeof err === 'string') { err = new Error(err); } /*jshint validthis:true */ return this.returns(thenable(function () { return new Promise(function (resolve, reject) { reject(err); }); })); } sinon.stub.rejects = rejects; sinon.behavior.rejects = rejects; module.exports = function (_Promise_) { if (typeof _Promise_ !== 'function') { throw new Error('A Promise constructor must be provided'); } else { Promise = _Promise_; } return sinon; };
Stop reactor and find files
from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor from twisted.application.internet import MulticastServer from BeautifulSoup import BeautifulSoup, SoupStrainer import requests fileserver = '' urls = [] def get_file_urls(self, url): f = requests.get("http://" + url) for link in BeautifulSoup(f, parseOnlyThese=SoupStrainer('a')): urls.append(link) def get_files(): pass class MulticastClientUDP(DatagramProtocol): def __init__(self): self.host = '224.0.0.5' def startProtocol(self): # this could be placed in a config self.transport.joinGroup(self.host) def datagramReceived(self, datagram, address): print "Received: " + repr(datagram) fileserver = repr(datagram).replace("'", "") # this will need more checking - it is killing the conn once it receives the address self.transport.loseConnection() reactor.stop() def main(): print "Listening" reactor.listenMulticast(8005, MulticastClientUDP(), listenMultiple = True) reactor.run() # reactor is closed at this point. get_file_urls(fileserver) if __name__ == '__main__': main()
from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor from twisted.application.internet import MulticastServer from BeautifulSoup import BeautifulSoup, SoupStrainer import requests fileserver = '' urls = [] def get_file_urls(self, url): f = requests.get("http://" + url) for link in BeautifulSoup(f, parseOnlyThese=SoupStrainer('a')): self.urls.append(link) print link class MulticastClientUDP(DatagramProtocol): def __init__(self): self.host = '224.0.0.5' def startProtocol(self): # this could be placed in a config self.transport.joinGroup(self.host) def datagramReceived(self, datagram, address): print "Received: " + repr(datagram) fileserver = repr(datagram).replace("'", "") # this will need more checking - it is killing the conn once it receives the address self.transport.loseConnection() reactor.stop() # once you receive the message then add it to the def main(): print "Listening" reactor.listenMulticast(8005, MulticastClientUDP(), listenMultiple = True) reactor.run() # is the reactor done? get_file_urls(fileserver) if __name__ == '__main__': main()
Make scorer accept instances of model and desc. gen.
import numpy as np from sklearn.cross_validation import cross_val_score from sklearn.externals import joblib as pickle class scorer(object): def __init__(self, model_instance, descriptor_generator_instance): self.model = model_instance self.descriptor_generator = descriptor_generator_instance def fit(self, ligands, target): self.train_descs = self.descriptor_generator.build(ligands) self.train_target = target return self.model.fit(descs,target) def predict(self, ligands): descs = self.descriptor_generator.build(ligands) return self.model.predict(descs) def score(self, ligands, target): descs = self.descriptor_generator.build(ligands) return self.model.score(descs,target) def cross_validate(n = 10, test_set = None, test_target = None): if test_set and test_target: cv_set = np.vstack((self.train_descs, test_set)) cv_target = np.vstack((self.train_target, test_target)) else: cv_set = self.train_descs cv_target = self.train_target return cross_val_score(self.model, cv_set, cv_target, cv = n) def save(filename): f = open(filename,'wb') pickle.dump(self, filename) f.close() @classmethod def load(filename): return pickle.load(open(filename,'rb'))
import numpy as np from sklearn.cross_validation import cross_val_score from sklearn.externals import joblib as pickle class scorer(object): def __init__(self, model, descriptor_generator, model_opts = {}, desc_opts = {}): self.model = model() self.descriptor_generator = descriptor_generator(**desc_opts) def fit(self, ligands, target): self.train_descs = self.descriptor_generator.build(ligands) self.train_target = target return self.model.fit(descs,target) def predict(self, ligands): descs = self.descriptor_generator.build(ligands) return self.model.predict(descs) def score(self, ligands, target): descs = self.descriptor_generator.build(ligands) return self.model.score(descs,target) def cross_validate(n = 10, test_set = None, test_target = None): if test_set and test_target: cv_set = np.vstack((self.train_descs, test_set)) cv_target = np.vstack((self.train_target, test_target)) else: cv_set = self.train_descs cv_target = self.train_target return cross_val_score(self.model, cv_set, cv_target, cv = n) def save(filename): f = open(filename,'wb') pickle.dump(self, filename) f.close() @classmethod def load(filename): return pickle.load(open(filename,'rb'))
Remove distribution bundle from the loaded bundles. We only need distribution bundle when updating dependencies. No need to load it in the kernel.
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new AppBundle\AppBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle(); } return $bundles; } public function getRootDir() { return __DIR__; } public function getCacheDir() { return dirname(__DIR__).'/var/cache/'.$this->environment; } public function getLogDir() { return dirname(__DIR__).'/var/logs'; } protected function getEnvParameters() { return $_SERVER; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load($this->getRootDir().'/config/config.yml'); } }
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new AppBundle\AppBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle(); // $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); } return $bundles; } public function getRootDir() { return __DIR__; } public function getCacheDir() { return dirname(__DIR__).'/var/cache/'.$this->environment; } public function getLogDir() { return dirname(__DIR__).'/var/logs'; } protected function getEnvParameters() { return $_SERVER; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load($this->getRootDir().'/config/config.yml'); } }
chore: Add TODO for more IAM Policy testing See also: PSOBAT-1482
"""Test IAM Policies for correctness.""" import json from foremast.iam.construct_policy import construct_policy ANSWER1 = { 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 's3:GetObject', 's3:ListObject' ], 'Resource': [ 'arn:aws:s3:::archaius-stage/forrest/unicornforrest', 'arn:aws:s3:::archaius-stage/forrest/unicornforrest/*' ] } ] } def test_main(): """Check general assemblage.""" settings = {'services': {'s3': True}} policy_json = construct_policy(app='unicornforrest', env='stage', group='forrest', pipeline_settings=settings) assert json.loads(policy_json) == ANSWER1 # TODO: Test other services besides S3 settings.update({'services': {'dynamodb': ['coreforrest', 'edgeforrest', 'attendantdevops']}}) policy_json = construct_policy(pipeline_settings=settings) policy = json.loads(policy_json)
"""Test IAM Policies for correctness.""" import json from foremast.iam.construct_policy import construct_policy ANSWER1 = { 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 's3:GetObject', 's3:ListObject' ], 'Resource': [ 'arn:aws:s3:::archaius-stage/forrest/unicornforrest', 'arn:aws:s3:::archaius-stage/forrest/unicornforrest/*' ] } ] } def test_main(): """Check general assemblage.""" settings = {'services': {'s3': True}} policy_json = construct_policy(app='unicornforrest', env='stage', group='forrest', pipeline_settings=settings) assert json.loads(policy_json) == ANSWER1 settings.update({'services': {'dynamodb': ['coreforrest', 'edgeforrest', 'attendantdevops']}}) policy_json = construct_policy(pipeline_settings=settings) policy = json.loads(policy_json)
Add comment to explain pagination handling
from future.standard_library import install_aliases install_aliases() # noqa from urllib.parse import urlparse from celery.task import Task from django.conf import settings from seed_services_client import IdentityStoreApiClient from .models import Parish class SyncLocations(Task): """ Has a look at all the identity store identities, and ensures that all of the locations assigned to identities appear in the list of locations. """ def get_identities(self, client): """ Returns an iterator over all the identities in the identity store specified by 'client'. """ identities = client.get_identities() while True: for identity in identities.get('results', []): yield identity # If there is a next page, extract the querystring and get it if identities.get('next') is not None: qs = urlparse(identities['next']).query identities = client.get_identities(params=qs) else: break def run(self, **kwargs): l = self.get_logger(**kwargs) l.info('Starting location import') imported_count = 0 client = IdentityStoreApiClient( settings.IDENTITY_STORE_TOKEN, settings.IDENTITY_STORE_URL) for identity in self.get_identities(client): parish = identity.get('details', {}).get('parish') if parish is not None: _, created = Parish.objects.get_or_create(name=parish.title()) if created: imported_count += 1 l.info('Imported {} locations'.format(imported_count)) return imported_count sync_locations = SyncLocations()
from future.standard_library import install_aliases install_aliases() # noqa from urllib.parse import urlparse from celery.task import Task from django.conf import settings from seed_services_client import IdentityStoreApiClient from .models import Parish class SyncLocations(Task): """ Has a look at all the identity store identities, and ensures that all of the locations assigned to identities appear in the list of locations. """ def get_identities(self, client): """ Returns an iterator over all the identities in the identity store specified by 'client'. """ identities = client.get_identities() while True: for identity in identities.get('results', []): yield identity if identities.get('next') is not None: qs = urlparse(identities['next']).query identities = client.get_identities(params=qs) else: break def run(self, **kwargs): l = self.get_logger(**kwargs) l.info('Starting location import') imported_count = 0 client = IdentityStoreApiClient( settings.IDENTITY_STORE_TOKEN, settings.IDENTITY_STORE_URL) for identity in self.get_identities(client): parish = identity.get('details', {}).get('parish') if parish is not None: _, created = Parish.objects.get_or_create(name=parish.title()) if created: imported_count += 1 l.info('Imported {} locations'.format(imported_count)) return imported_count sync_locations = SyncLocations()
Remove redundant case property check
from casexml.apps.case.util import get_datetime_case_property_changed from custom.enikshay.const import ENROLLED_IN_PRIVATE class PrivateNikshayNotifiedDateSetter(object): """Sets the date_private_nikshay_notification property for use in reports """ def __init__(self, domain, person, episode): self.domain = domain self.person = person self.episode = episode def update_json(self): if not self.should_update: return {} registered_datetime = get_datetime_case_property_changed( self.episode, 'private_nikshay_registered', 'true', ) if registered_datetime is not None: return { 'date_private_nikshay_notification': str(registered_datetime.date()) } else: return {} @property def should_update(self): if self.episode.get_case_property('date_private_nikshay_notification') is not None: return False if self.episode.get_case_property('private_nikshay_registered') != 'true': return False if self.episode.get_case_property(ENROLLED_IN_PRIVATE) != 'true': return False return True
from casexml.apps.case.util import get_datetime_case_property_changed from custom.enikshay.const import ( ENROLLED_IN_PRIVATE, REAL_DATASET_PROPERTY_VALUE, ) class PrivateNikshayNotifiedDateSetter(object): """Sets the date_private_nikshay_notification property for use in reports """ def __init__(self, domain, person, episode): self.domain = domain self.person = person self.episode = episode def update_json(self): if not self.should_update: return {} registered_datetime = get_datetime_case_property_changed( self.episode, 'private_nikshay_registered', 'true', ) if registered_datetime is not None: return { 'date_private_nikshay_notification': str(registered_datetime.date()) } else: return {} @property def should_update(self): if self.episode.get_case_property('date_private_nikshay_notification') is not None: return False if self.episode.get_case_property('private_nikshay_registered') != 'true': return False if self.episode.get_case_property(ENROLLED_IN_PRIVATE) != 'true': return False if self.person.get_case_property('dataset') != REAL_DATASET_PROPERTY_VALUE: return False return True
Update location of files on service provider.
<?php namespace Nobox\LazyStrings; use Illuminate\Support\ServiceProvider; use Illuminate\Filesystem\Filesystem; use Nobox\LazyStrings\Commands\LazyDeployCommand; class LazyStringsServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { $views = __DIR__ . '/../views'; $config = __DIR__ . '/../config/lazy-strings.php'; $routes = __DIR__ . '/routes.php'; $this->loadViewsFrom($views, 'lazy-strings'); $this->publishes([ $config => config_path('lazy-strings.php'), ]); include $routes; } /** * Register bindings in the container. * * @return void */ public function register() { // add LazyStrings class to app container $this->app->bind('lazy-strings', function ($app) { return new LazyStrings(new Filesystem); }); // register `lazy:deploy` command $this->app->bind('command.lazy-deploy', function ($app) { return new LazyDeployCommand(); }); $this->commands('command.lazy-deploy'); } }
<?php namespace Nobox\LazyStrings; use Illuminate\Support\ServiceProvider; use Illuminate\Filesystem\Filesystem; use Nobox\LazyStrings\Commands\LazyDeployCommand; class LazyStringsServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { $views = __DIR__ . '/../../views'; $config = __DIR__ . '/../../config/lazy-strings.php'; $routes = __DIR__ . '/../../routes.php'; $this->loadViewsFrom($views, 'lazy-strings'); $this->publishes([ $config => config_path('lazy-strings.php'), ]); include $routes; } /** * Register bindings in the container. * * @return void */ public function register() { // add LazyStrings class to app container $this->app->bind('lazy-strings', function ($app) { return new LazyStrings(new Filesystem); }); // register `lazy:deploy` command $this->app->bind('command.lazy-deploy', function ($app) { return new LazyDeployCommand(); }); $this->commands('command.lazy-deploy'); } }
Change shares to singleton in service provider
<?php namespace Coreplex\Navigator; use ReflectionClass; use Illuminate\Support\ServiceProvider; class NavigatorServiceProvider extends ServiceProvider { public function boot() { $this->publishes([ __DIR__ . '/../config/navigator.php' => config_path('navigator.php'), ]); $this->mergeConfigFrom(__DIR__ . '/../config/navigator.php', 'navigator'); } /** * Regsiter the service provider. */ public function register() { $this->registerStore(); $this->registerNavigator(); } /** * Register the data store to be used by navigator. */ protected function registerStore() { $this->app->singleton('Coreplex\Navigator\Contracts\Store', function($app) { return (new ReflectionClass($app['config']['navigator']['store']))->newInstanceArgs([$app['config']['navigator']['menus']]); }); } /** * Register the navigator instance. */ protected function registerNavigator() { $this->app->singleton('Coreplex\Navigator\Contracts\Navigator', function($app) { return new Navigator( $app['Coreplex\Core\Contracts\Renderer'], $app['Coreplex\Navigator\Contracts\Store'], $app['config']['navigator'] ); }); } }
<?php namespace Coreplex\Navigator; use ReflectionClass; use Illuminate\Support\ServiceProvider; class NavigatorServiceProvider extends ServiceProvider { public function boot() { $this->publishes([ __DIR__ . '/../config/navigator.php' => config_path('navigator.php'), ]); $this->mergeConfigFrom(__DIR__ . '/../config/navigator.php', 'navigator'); } /** * Regsiter the service provider. */ public function register() { $this->registerStore(); $this->registerNavigator(); } /** * Register the data store to be used by navigator. */ protected function registerStore() { $this->app['Coreplex\Navigator\Contracts\Store'] = $this->app->share(function ($app) { return (new ReflectionClass($app['config']['navigator']['store']))->newInstanceArgs([$app['config']['navigator']['menus']]); }); } /** * Register the navigator instance. */ protected function registerNavigator() { $this->app['Coreplex\Navigator\Contracts\Navigator'] = $this->app->share(function ($app) { return new Navigator( $app['Coreplex\Core\Contracts\Renderer'], $app['Coreplex\Navigator\Contracts\Store'], $app['config']['navigator'] ); }); } }
Make the validation query constant private
package com.github.arteam.jdbi3; import com.codahale.metrics.health.HealthCheck; import io.dropwizard.db.TimeBoundHealthCheck; import io.dropwizard.util.Duration; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.Jdbi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; /** * Health check which verifies the availability of the database */ public class JdbiHealthCheck extends HealthCheck { private static final Logger log = LoggerFactory.getLogger(JdbiHealthCheck.class); private static final String VALIDATION_QUERY_FAILED = "Validation query failed"; private final Jdbi jdbi; private final String validationQuery; private final TimeBoundHealthCheck timeBoundHealthCheck; public JdbiHealthCheck(ExecutorService executorService, Duration duration, Jdbi dbi, String validationQuery) { this.jdbi = dbi; this.validationQuery = validationQuery; this.timeBoundHealthCheck = new TimeBoundHealthCheck(executorService, duration); } @Override protected Result check() throws Exception { return timeBoundHealthCheck.check(() -> { try (Handle handle = jdbi.open()) { handle.execute(validationQuery); return Result.healthy(); } catch (Exception e) { log.error("jDBI Healthcheck failed. validation-query={}", validationQuery, e); return Result.unhealthy(VALIDATION_QUERY_FAILED); } }); } }
package com.github.arteam.jdbi3; import com.codahale.metrics.health.HealthCheck; import io.dropwizard.db.TimeBoundHealthCheck; import io.dropwizard.util.Duration; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.Jdbi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutorService; /** * Health check which verifies the availability of the database */ public class JdbiHealthCheck extends HealthCheck { private static final Logger log = LoggerFactory.getLogger(JdbiHealthCheck.class); protected static final String VALIDATION_QUERY_FAILED = "Validation query failed"; private final Jdbi jdbi; private final String validationQuery; private final TimeBoundHealthCheck timeBoundHealthCheck; public JdbiHealthCheck(ExecutorService executorService, Duration duration, Jdbi dbi, String validationQuery) { this.jdbi = dbi; this.validationQuery = validationQuery; this.timeBoundHealthCheck = new TimeBoundHealthCheck(executorService, duration); } @Override protected Result check() throws Exception { return timeBoundHealthCheck.check(() -> { try (Handle handle = jdbi.open()) { handle.execute(validationQuery); return Result.healthy(); } catch (Exception e) { log.error("jDBI Healthcheck failed. validation-query={}", validationQuery, e); return Result.unhealthy(VALIDATION_QUERY_FAILED); } }); } }
EDIT prevent default submit behaviour, add redirect
{% extends 'backend/layout.twig.php' %} {% block content %} <article class="container itemCenter center column"> {% if message.content is defined %} <div class="item alert {{ message.type }}"> {{ message.content }} </div> {% endif %} <header> <h1>Register a new user</h1> </header> <form action="/backend/users/register" method="post"> <div class="form-group"> <label>Name</label> <input name="name" placeholder="Real Name" value="{{ formVars.name }}" class="input-control" /> </div> <div class="form-group"> <label>Email</label> <input name="email" placeholder="Email" value="{{ formVars.email }}" class="input-control" /> </div> <div class="form-group"> <label>Password</label> <input name="passwd" placeholder="password" class="input-control" /> </div> <div class="form-group"> <label>User Level</label> <input name="userLevel" value="{{ formVars.userLevel }}" class="input-control" placeholder="3" style="flex: 6" /> </div> <div class="form-group"> <label>&nbsp;</label> <button type="submit">Save</button> <button onclick="event.preventDefault(); window.location.href='/backend/users'">Cancel</button> </div> </form> </article> {% endblock %}
{% extends 'backend/layout.twig.php' %} {% block content %} <article class="container itemCenter center column"> {% if message.content is defined %} <div class="item alert {{ message.type }}"> {{ message.content }} </div> {% endif %} <header> <h1>Register a new user</h1> </header> <form action="/backend/users/register" method="post"> <div class="form-group"> <label>Name</label> <input name="name" placeholder="Real Name" value="{{ formVars.name }}" class="input-control" /> </div> <div class="form-group"> <label>Email</label> <input name="email" placeholder="Email" value="{{ formVars.email }}" class="input-control" /> </div> <div class="form-group"> <label>Password</label> <input name="passwd" placeholder="password" class="input-control" /> </div> <div class="form-group"> <label>User Level</label> <input name="userLevel" value="{{ formVars.userLevel }}" class="input-control" placeholder="3" style="flex: 6" /> </div> <div class="form-group"> <label>&nbsp;</label> <button type="submit">Save</button> <button>Cancel</button> </div> </form> </article> {% endblock %}
Check that there are no uninstalled modules
<?php namespace Backend\Modules\ContentBlocks\Tests\Action; use Common\WebTestCase; class ModulesTest extends WebTestCase { public function testAuthenticationIsNeeded(): void { $client = static::createClient(); $this->logout($client); $client->setMaxRedirects(1); $client->request('GET', '/private/en/extensions/modules'); // we should get redirected to authentication with a reference to blog index in our url self::assertStringEndsWith( '/private/en/authentication?querystring=%2Fprivate%2Fen%2Fextensions%2Fmodules', $client->getHistory()->current()->getUri() ); } public function testIndexHasModuels(): void { $client = static::createClient(); $this->login($client); $client->request('GET', '/private/en/extensions/modules'); self::assertContains( 'Installed modules', $client->getResponse()->getContent() ); self::assertNotContains( 'Not installed modules', $client->getResponse()->getContent() ); self::assertContains( 'Upload module', $client->getResponse()->getContent() ); self::assertContains( 'Find modules', $client->getResponse()->getContent() ); } }
<?php namespace Backend\Modules\ContentBlocks\Tests\Action; use Common\WebTestCase; class ModulesTest extends WebTestCase { public function testAuthenticationIsNeeded(): void { $client = static::createClient(); $this->logout($client); $client->setMaxRedirects(1); $client->request('GET', '/private/en/extensions/modules'); // we should get redirected to authentication with a reference to blog index in our url self::assertStringEndsWith( '/private/en/authentication?querystring=%2Fprivate%2Fen%2Fextensions%2Fmodules', $client->getHistory()->current()->getUri() ); } public function testIndexHasModuels(): void { $client = static::createClient(); $this->login($client); $client->request('GET', '/private/en/extensions/modules'); self::assertContains( 'Installed modules', $client->getResponse()->getContent() ); self::assertContains( 'Not installed modules', $client->getResponse()->getContent() ); self::assertContains( 'Upload module', $client->getResponse()->getContent() ); self::assertContains( 'Find modules', $client->getResponse()->getContent() ); } }
Send email to acadoffice when user acknowledge his AWS.
<?php include_once( "header.php" ); include_once( "methods.php" ); include_once( 'tohtml.php' ); include_once( "check_access_permissions.php" ); mustHaveAnyOfTheseRoles( Array( 'USER' ) ); echo userHTML( ); $user = $_SESSION[ 'user' ]; if( $_POST ) { $data = array( 'speaker' => $user ); $data = array_merge( $_POST, $data ); echo( "Sending your acknowledgment to database " ); $res = updateTable( 'upcoming_aws', 'id,speaker', 'acknowledged', $data ); if( $res ) { echo printInfo( "You have successfully acknowledged your AWS schedule. Please mark your calendar as well." ); $email = "<p>" . loginToHTML( $user ) . " has just acknowledged his/her AWS date. </p>"; $email .= "<p>" . humanReadableDate( 'now' ) . "</p>"; $subject = loginToText( $user ) . " has acknowledged his/her AWS date"; $to = '[email protected]'; $cc = '[email protected]'; sendPlainTextEmail( $email, $subject, $to, $cc ); goToPage( "user_aws.php", 1 ); exit; } else { echo printWarning( "Failed to update database ..." ); } } echo goBackToPageLink( "user_aws.php", "Go back" ); ?>
<?php include_once( "header.php" ); include_once( "methods.php" ); include_once( 'tohtml.php' ); include_once( "check_access_permissions.php" ); mustHaveAnyOfTheseRoles( Array( 'USER' ) ); echo userHTML( ); $user = $_SESSION[ 'user' ]; if( $_POST ) { $data = array( 'speaker' => $user ); $data = array_merge( $_POST, $data ); echo( "Sending your acknowledgment to database " ); $res = updateTable( 'upcoming_aws', 'id,speaker', 'acknowledged', $data ); if( $res ) { echo printInfo( "You have successfully acknowledged your AWS schedule. Please mark your calendar as well." ); $email = "<p>" . loginToHTML( $user ) . " has just acknowledged his/her AWS date. </p>"; $email .= "<p>" . humanReadableDate( 'now' ) . "</p>"; $subject = "$user has acknowledged his/her AWS date"; $to = '[email protected]'; $cc = '[email protected]'; sendPlainTextEmail( $email, $subject, $to, $cc ); goToPage( "user_aws.php", 1 ); exit; } else { echo printWarning( "Failed to update database ..." ); } } echo goBackToPageLink( "user_aws.php", "Go back" ); ?>
Use the correct class name in the jobs widget
import _ from 'underscore'; import { getCurrentUser } from 'girder/auth'; import JobListWidget from 'girder_plugins/jobs/views/JobListWidget'; import events from '../events'; import Panel from './Panel'; var JobsPanel = Panel.extend({ events: _.extend(Panel.prototype.events, { 'g:login': 'render', 'g:login-changed': 'render', 'g:logout': 'render' }), initialize: function (settings) { this.spec = settings.spec; this.listenTo(events, 'h:submit', function () { this._jobsListWidget.collection.fetch(undefined, true); }); }, render: function () { var CE = JobListWidget.prototype.columnEnum; var columns = CE.COLUMN_STATUS_ICON | CE.COLUMN_TITLE; Panel.prototype.render.apply(this, arguments); if (getCurrentUser()) { if (!this._jobsListWidget) { this._jobsListWidget = new JobListWidget({ columns: columns, showHeader: false, pageLimit: 5, showPaging: false, triggerJobClick: true, parentView: this }); this.listenTo(this._jobsListWidget, 'g:jobClicked', function (job) { // when clicking on a job open to girder's job view in a new window window.open( '/#job/' + job.id, '_blank' ); }); } this._jobsListWidget.setElement(this.$('.s-panel-content')).render(); } } }); export default JobsPanel;
import _ from 'underscore'; import { getCurrentUser } from 'girder/auth'; import JobListWidget from 'girder_plugins/jobs/views/JobListWidget'; import events from '../events'; import Panel from './Panel'; var JobsPanel = Panel.extend({ events: _.extend(Panel.prototype.events, { 'g:login': 'render', 'g:login-changed': 'render', 'g:logout': 'render' }), initialize: function (settings) { this.spec = settings.spec; this.listenTo(events, 'h:submit', function () { this._jobsListWidget.collection.fetch(undefined, true); }); }, render: function () { var CE = JobListWidget.prototype.columnEnum; var columns = CE.COLUMN_STATUS_ICON | CE.COLUMN_TITLE; Panel.prototype.render.apply(this, arguments); if (getCurrentUser()) { if (!this._jobsListWidget) { this._jobsListWidget = new JobListWidget({ columns: columns, showHeader: false, pageLimit: 5, showPaging: false, triggerJobClick: true, parentView: this }); this.listenTo(this._jobsListWidget, 'g:jobClicked', function (job) { // when clicking on a job open to girder's job view in a new window window.open( '/#job/' + job.id, '_blank' ); }); } this._jobsListWidget.setElement(this.$('.h-panel-content')).render(); } } }); export default JobsPanel;
Fix $this usage when in Closure
<?php namespace Krucas\Notification; use Illuminate\Support\ServiceProvider; class NotificationServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('edvinaskrucas/notification'); $this->app['events']->fire('notification.booted', $this->app['notification']); } /** * Register the service provider. * * @return void */ public function register() { $this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config'); $this->app['notification'] = $this->app->share(function ($app) { $config = $app['config']; $notification = new Notification( $config->get('notification::default_container'), $config->get('notification::default_types'), $config->get('notification::default_format'), $config->get('notification::default_formats') ); $notification->setEventDispatcher($app['events']); return $notification; }); $this->app->bind('Krucas\Notification\Subscriber', function ($app) { return new Subscriber($app['session.store'], $app['config']); }); $this->app['events']->subscribe('Krucas\Notification\Subscriber'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
<?php namespace Krucas\Notification; use Illuminate\Support\ServiceProvider; class NotificationServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('edvinaskrucas/notification'); $this->app['events']->fire('notification.booted', $this->app['notification']); } /** * Register the service provider. * * @return void */ public function register() { $this->app['config']->package('edvinaskrucas/notification', __DIR__.'/../config'); $this->app['notification'] = $this->app->share(function ($app) { $config = $app['config']; $notification = new Notification( $config->get('notification::default_container'), $config->get('notification::default_types'), $config->get('notification::default_format'), $config->get('notification::default_formats') ); $notification->setEventDispatcher($this->app['events']); return $notification; }); $this->app->bind('Krucas\Notification\Subscriber', function ($app) { return new Subscriber($app['session.store'], $app['config']); }); $this->app['events']->subscribe('Krucas\Notification\Subscriber'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
Change constructor of Vehicle to accept an Interface instead of just Source.
from .measurements import Measurement from .sinks.base import MeasurementNotifierSink class Vehicle(object): def __init__(self, interface=None): self.sources = set() self.sinks = set() self.measurements = {} if interface is not None: self.add_source(interface) self.controller = interface self.notifier = MeasurementNotifierSink() self.sinks.add(self.notifier) def get(self, measurement_class): name = Measurement.name_from_class(measurement_class) return self._construct_measurement(name) def listen(self, measurement_class, listener): self.notifier.register(measurement_class, listener) def unlisten(self, measurement_class, listener): self.notifier.unregister(measurement_class, listener) def _receive(self, message, **kwargs): name = message['name'] self.measurements[name] = message for sink in self.sinks: sink.receive(message, **kwargs) def _construct_measurement(self, measurement_id): raw_measurement = self.measurements.get(measurement_id, None) if raw_measurement is not None: return Measurement.from_dict(raw_measurement) def add_source(self, source): if source is not None: self.sources.add(source) source.callback = self._receive source.start() def add_sink(self, sink): if sink is not None: self.sinks.add(sink) if hasattr(sink, 'start'): sink.start()
from .measurements import Measurement from .sinks.base import MeasurementNotifierSink class Vehicle(object): def __init__(self, source=None): self.sources = set() self.sinks = set() self.measurements = {} self.add_source(source) self.notifier = MeasurementNotifierSink() self.sinks.add(self.notifier) def get(self, measurement_class): name = Measurement.name_from_class(measurement_class) return self._construct_measurement(name) def listen(self, measurement_class, listener): self.notifier.register(measurement_class, listener) def unlisten(self, measurement_class, listener): self.notifier.unregister(measurement_class, listener) def _receive(self, message, **kwargs): name = message['name'] self.measurements[name] = message for sink in self.sinks: sink.receive(message, **kwargs) def _construct_measurement(self, measurement_id): raw_measurement = self.measurements.get(measurement_id, None) if raw_measurement is not None: return Measurement.from_dict(raw_measurement) def add_source(self, source): if source is not None: self.sources.add(source) source.callback = self._receive source.start() def add_sink(self, sink): if sink is not None: self.sinks.add(sink) if hasattr(sink, 'start'): sink.start()
Add missing method to interface
from nevow.compy import Interface class IType(Interface): def validate(self, value): pass class IStructure(Interface): pass class IWidget(Interface): def render(self, ctx, key, args, errors): pass def renderImmutable(self, ctx, key, args, errors): pass def processInput(self, ctx, key, args): pass class IFormFactory(Interface): def formFactory(self, ctx, name): pass class IFormData(Interface): pass class IFormErrors(Interface): pass class IKey(Interface): def key(self): pass class ILabel(Interface): def label(self): pass class IConvertible(Interface): def fromType(self, value): pass def toType(self, value): pass class IStringConvertible(IConvertible): pass class IBooleanConvertible(IConvertible): pass class IDateTupleConvertible(IConvertible): pass class IFileConvertible(IConvertible): pass class ISequenceConvertible(IConvertible): pass class IForm( Interface ): pass class IValidator(Interface): def validate(self, field, value): pass
from nevow.compy import Interface class IType(Interface): def validate(self, value): pass class IStructure(Interface): pass class IWidget(Interface): def render(self, ctx, key, args, errors): pass def processInput(self, ctx, key, args): pass class IFormFactory(Interface): def formFactory(self, ctx, name): pass class IFormData(Interface): pass class IFormErrors(Interface): pass class IKey(Interface): def key(self): pass class ILabel(Interface): def label(self): pass class IConvertible(Interface): def fromType(self, value): pass def toType(self, value): pass class IStringConvertible(IConvertible): pass class IBooleanConvertible(IConvertible): pass class IDateTupleConvertible(IConvertible): pass class IFileConvertible(IConvertible): pass class ISequenceConvertible(IConvertible): pass class IForm( Interface ): pass class IValidator(Interface): def validate(self, field, value): pass
Remove requests dependency upper version constraint Removes the undocumented and outdated upper version constraint for the requests dependency.
# coding=utf-8 import sys cmdclass = {} try: from setuptools import setup except ImportError: from distutils.core import setup else: from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) cmdclass['test'] = PyTest setup( name='openprovider.py', version='0.11.3', author='Antagonist B.V.', author_email='[email protected]', packages=['openprovider', 'openprovider.modules', 'openprovider.data'], url='https://github.com/AntagonistHQ/openprovider.py', license='LICENSE.rst', description='An unofficial library for the OpenProvider API', long_description=open('README.rst').read(), install_requires=[ "requests >= 2.3.0", "lxml >= 3.3.5", ], tests_require=[ "betamax>=0.7.0", "Faker", "pytest", ], cmdclass=cmdclass, )
# coding=utf-8 import sys cmdclass = {} try: from setuptools import setup except ImportError: from distutils.core import setup else: from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) cmdclass['test'] = PyTest setup( name='openprovider.py', version='0.11.3', author='Antagonist B.V.', author_email='[email protected]', packages=['openprovider', 'openprovider.modules', 'openprovider.data'], url='https://github.com/AntagonistHQ/openprovider.py', license='LICENSE.rst', description='An unofficial library for the OpenProvider API', long_description=open('README.rst').read(), install_requires=[ "requests >= 2.3.0, <= 2.5.1", "lxml >= 3.3.5", ], tests_require=[ "betamax>=0.7.0", "Faker", "pytest", ], cmdclass=cmdclass, )
Revert "Remove IF EXISTS from DROP TABLE when resetting the db." This reverts commit 271668a20a2262fe6211b9f61146ad90d8096486 [formerly a7dce25964cd740b0d0db86b255ede60c913e73d]. Former-commit-id: 08199327c411663a199ebf36379e88a514935399
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE IF EXISTS categories ''') db.execute(''' DROP TABLE IF EXISTS articles ''') db.execute(''' DROP TABLE IF EXISTS snippets ''') db.execute(''' DROP TABLE IF EXISTS articles_categories ''') db.execute(''' CREATE TABLE categories (id TEXT PRIMARY KEY, title TEXT) ''') db.execute(''' INSERT INTO categories VALUES ("unassigned", "unassigned") ''') db.execute(''' CREATE TABLE articles_categories (article_id TEXT, category_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE, FOREIGN KEY(category_id) REFERENCES categories(id) ON DELETE CASCADE) ''') db.execute(''' CREATE TABLE articles (page_id TEXT PRIMARY KEY, url TEXT, title TEXT) ''') db.execute(''' CREATE TABLE snippets (id TEXT PRIMARY KEY, snippet TEXT, section TEXT, article_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE) ''') return db def create_indices(): db = init_db() db.execute('''CREATE INDEX IF NOT EXISTS snippets_articles ON snippets(article_id);''')
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE categories ''') db.execute(''' DROP TABLE articles ''') db.execute(''' DROP TABLE snippets ''') db.execute(''' DROP TABLE articles_categories ''') db.execute(''' CREATE TABLE categories (id TEXT PRIMARY KEY, title TEXT) ''') db.execute(''' INSERT INTO categories VALUES ("unassigned", "unassigned") ''') db.execute(''' CREATE TABLE articles_categories (article_id TEXT, category_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE, FOREIGN KEY(category_id) REFERENCES categories(id) ON DELETE CASCADE) ''') db.execute(''' CREATE TABLE articles (page_id TEXT PRIMARY KEY, url TEXT, title TEXT) ''') db.execute(''' CREATE TABLE snippets (id TEXT PRIMARY KEY, snippet TEXT, section TEXT, article_id TEXT, FOREIGN KEY(article_id) REFERENCES articles(page_id) ON DELETE CASCADE) ''') return db def create_indices(): db = init_db() db.execute('''CREATE INDEX IF NOT EXISTS snippets_articles ON snippets(article_id);''')
Change perms to use specific validator for badge awarding
'use strict'; module.exports = function () { return { 'cd-badges': { 'listBadges': [{ role: 'none' }], // NOTE: Must be defined by visibility ? 'getBadge': [{ role: 'none' }], 'sendBadgeApplication': [{ role: 'basic-user', customValidator: [{ role: 'cd-dojos', cmd: 'can_award_badge' }] }], 'acceptBadge': [{ role: 'basic-user', // TODO : this is buggy, it seems the userId in the badge is not set making the validation not working // customValidator: [{ // role: 'cd-badges', // cmd: 'ownBadge' // }] }], // NOTE: Must be defined by visibility ? 'loadUserBadges': [{ role: 'basic-user' }], 'loadBadgeCategories': [{ role: 'none' }], 'loadBadgeByCode': [{ role: 'none' }], 'claimBadge': [{ role: 'basic-user' }], 'exportBadges': [{ role: 'basic-user', customValidator: [{ role: 'cd-users', cmd: 'is_self' }] }], 'kpiNumberOfBadgesAwarded': [{ role: 'cdf-admin' }], 'kpiNumberOfBadgesPublished' :[{ role: 'cdf-admin' }] } }; };
'use strict'; module.exports = function () { return { 'cd-badges': { 'listBadges': [{ role: 'none' }], // NOTE: Must be defined by visibility ? 'getBadge': [{ role: 'none' }], 'sendBadgeApplication': [{ role: 'basic-user', customValidator: [{ role: 'cd-dojos', cmd: 'have_permissions', perm: 'dojo-admin' }] }], 'acceptBadge': [{ role: 'basic-user', // TODO : this is buggy, it seems the userId in the badge is not set making the validation not working // customValidator: [{ // role: 'cd-badges', // cmd: 'ownBadge' // }] }], // NOTE: Must be defined by visibility ? 'loadUserBadges': [{ role: 'basic-user' }], 'loadBadgeCategories': [{ role: 'none' }], 'loadBadgeByCode': [{ role: 'none' }], 'claimBadge': [{ role: 'basic-user' }], 'exportBadges': [{ role: 'basic-user', customValidator: [{ role: 'cd-users', cmd: 'is_self' }] }], 'kpiNumberOfBadgesAwarded': [{ role: 'cdf-admin' }], 'kpiNumberOfBadgesPublished' :[{ role: 'cdf-admin' }] } }; };
Add provenance type as item to reset.
Application.Services.factory('toggleDragButton', [toggleDragButton]); function toggleDragButton() { var service = { addToReview: { 'samples': false, 'notes': false, 'files': false, 'provenance': false }, addToProv: { samples: false, notes: false, files: false, provenance: false }, toggle: function (type, button) { switch (type) { case "samples": service[button].samples = !service[button].samples; break; case "notes": service[button].notes = !service[button].notes; break; case "files": service[button].files = !service[button].files; break; case "provenance": service[button].provenance = !service[button].provenance; break; } }, reset: function(button) { service[button] = { 'samples': false, 'notes': false, 'files': false, 'provenance': false }; }, get: function (type, button) { return service[button][type]; } }; return service; }
Application.Services.factory('toggleDragButton', [toggleDragButton]); function toggleDragButton() { var service = { addToReview: { 'samples': false, 'notes': false, 'files': false, 'provenance': false }, toggle: function (type, button) { switch (type) { case "samples": service[button].samples = !service[button].samples; break; case "notes": service[button].notes = !service[button].notes; break; case "files": service[button].files = !service[button].files; break; case "provenance": service[button].provenance = !service[button].provenance; break; } }, reset: function(){ service.addToReview= { 'samples': false, 'notes': false, 'files': false, 'provenance': false }; }, get: function (type, button) { return service[button][type]; } }; return service; }
Use the method available in Java 7 instead of the one in Java 8 Change-Id: I1f2dcd2420eb0b06141f15a1d99d287bdb299361
// Copyright 2016 Google Inc. All Rights Reserved. package com.google.copybara; import com.google.common.truth.Truth; import com.google.copybara.config.Config; import com.beust.jcommander.internal.Nullable; import org.junit.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; public class CopybaraTest { @Test public void doNothing() throws IOException, RepoException { Config.Yaml config = new Config.Yaml(); config.setName("name"); config.setSourceOfTruth(new Repository.Yaml() { @Override public Repository withOptions(Options options) { return new Repository() { @Override public void checkoutReference(@Nullable String reference, Path workdir) throws RepoException { try { Files.createDirectories(workdir); Files.write(workdir.resolve("file.txt"), reference.getBytes()); } catch (IOException e) { throw new RepoException("Unexpected error", e); } } }; } }); config.setDestinationPath("src/copybara"); Path workdir = Files.createTempDirectory("workdir"); new Copybara(workdir).runForSourceRef(config.withOptions(new Options()), "some_sha1"); Truth.assertThat(Files.readAllLines(workdir.resolve("file.txt"), StandardCharsets.UTF_8)) .contains("some_sha1"); } }
// Copyright 2016 Google Inc. All Rights Reserved. package com.google.copybara; import com.google.common.truth.Truth; import com.google.copybara.config.Config; import com.google.copybara.config.Config.Yaml; import com.beust.jcommander.internal.Nullable; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class CopybaraTest { @Test public void doNothing() throws IOException, RepoException { Config.Yaml config = new Config.Yaml(); config.setName("name"); config.setSourceOfTruth(new Repository.Yaml() { @Override public Repository withOptions(Options options) { return new Repository() { @Override public void checkoutReference(@Nullable String reference, Path workdir) throws RepoException { try { Files.createDirectories(workdir); Files.write(workdir.resolve("file.txt"), reference.getBytes()); } catch (IOException e) { throw new RepoException("Unexpected error", e); } } }; } }); config.setDestinationPath("src/copybara"); Path workdir = Files.createTempDirectory("workdir"); new Copybara(workdir).runForSourceRef(config.withOptions(new Options()), "some_sha1"); Truth.assertThat(Files.readAllLines(workdir.resolve("file.txt"))).contains("some_sha1"); } }
Use alternate GitHub download URL
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import find_packages, setup VERSION = "1.0.0" with open("requirements.txt", "rt") as f: requirements= f.read().splitlines() setup(name="sacad", version=VERSION, author="desbma", packages=find_packages(), entry_points={"console_scripts": ["sacad = sacad:cl_main"]}, package_data={"": ["LICENSE", "README.md", "requirements.txt"]}, test_suite="tests", install_requires=requirements, description="Search and download music album covers", url="https://github.com/desbma/sacad", download_url="https://github.com/desbma/sacad/archive/%s.tar.gz" % (VERSION), keywords=["dowload", "album", "cover", "art", "albumart", "music"], classifiers=["Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Topic :: Internet :: WWW/HTTP", "Topic :: Multimedia :: Graphics", "Topic :: Utilities"])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import find_packages, setup VERSION = "1.0.0" with open("requirements.txt", "rt") as f: requirements= f.read().splitlines() setup(name="sacad", version=VERSION, author="desbma", packages=find_packages(), entry_points={"console_scripts": ["sacad = sacad:cl_main"]}, package_data={"": ["LICENSE", "README.md", "requirements.txt"]}, test_suite="tests", install_requires=requirements, description="Search and download music album covers", url="https://github.com/desbma/sacad", download_url="https://github.com/desbma/sacad/tarball/%s" % (VERSION), keywords=["dowload", "album", "cover", "art", "albumart", "music"], classifiers=["Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Topic :: Internet :: WWW/HTTP", "Topic :: Multimedia :: Graphics", "Topic :: Utilities"])
Fix id of first organisation.
<?php use Illuminate\Database\Seeder; class OrganisationsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('organisations')->insert([ 'id' => 1, 'name' => 'Wellington Gliding Club', 'addr1' => 'PO Box 30 200', 'addr2' => 'Lower Hutt', 'addr3' => '', 'addr4' => '', 'country' => 'New Zealand', 'contact_name' => 'Flash Gordon', 'email' => '[email protected]', 'timezone' => 'Pacific/Auckland', 'aircraft_prefix' => 'ZK', 'tow_height_charging' => 1, 'tow_time_based' => 0, 'default_location' => 'Greytown', 'name_othercharges' => 'Airways', 'def_launch_lat' => '-41.104941', 'def_launch_lon' => '175.499121', 'map_centre_lat' => '-41.104941', 'map_centre_lon' => '175.499121', 'twitter_consumerKey' => '????', 'twitter_consumerSecret' => '????', 'twitter_accessToken' => '????', 'twitter_accessTokenSecret' => '????', ]); } }
<?php use Illuminate\Database\Seeder; class OrganisationsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('organisations')->insert([ 'name' => 'Wellington Gliding Club', 'addr1' => 'PO Box 30 200', 'addr2' => 'Lower Hutt', 'addr3' => '', 'addr4' => '', 'country' => 'New Zealand', 'contact_name' => 'Flash Gordon', 'email' => '[email protected]', 'timezone' => 'Pacific/Auckland', 'aircraft_prefix' => 'ZK', 'tow_height_charging' => 1, 'tow_time_based' => 0, 'default_location' => 'Greytown', 'name_othercharges' => 'Airways', 'def_launch_lat' => '-41.104941', 'def_launch_lon' => '175.499121', 'map_centre_lat' => '-41.104941', 'map_centre_lon' => '175.499121', 'twitter_consumerKey' => '????', 'twitter_consumerSecret' => '????', 'twitter_accessToken' => '????', 'twitter_accessTokenSecret' => '????', ]); } }
Use dot reporter for mocha
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // !jshint all code jshint: { options: { jshintrc: true }, all: ['Gruntfile.js', 'src/*.js', 'test/*.js'] }, // Mocha tests mochaTest: { options: { reporter: 'dot', require: ['test/init'], mocha: require('mocha') }, test: ['test/*.spec.js'] }, // Production-ready uglified build uglify: { options: { banner: '/**\n' + '* smatch - A scala-style pattern matching utility for ' + 'javascript.\n' + '* @author Travis Kaufman <[email protected]>\n' + '* @copyright 2013 Travis Kaufman\n' + '* @license MIT\n' + '* @version <%= pkg.version %>\n' + '*/\n' }, files: { 'dist/smatch.min.js': ['lib/smatch.js'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.registerTask('build', ['jshint', 'mochaTest', 'uglify']); };
module.exports = function(grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // !jshint all code jshint: { options: { jshintrc: true }, all: ['Gruntfile.js', 'src/*.js', 'test/*.js'] }, // Mocha tests mochaTest: { options: { reporter: 'list', require: ['test/init'], mocha: require('mocha') }, test: ['test/*.spec.js'] }, // Production-ready uglified build uglify: { options: { banner: '/**\n' + '* smatch - A scala-style pattern matching utility for ' + 'javascript.\n' + '* @author Travis Kaufman <[email protected]>\n' + '* @copyright 2013 Travis Kaufman\n' + '* @license MIT\n' + '* @version <%= pkg.version %>\n' + '*/\n' }, files: { 'dist/smatch.min.js': ['lib/smatch.js'] } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.registerTask('build', ['jshint', 'mochaTest', 'uglify']); };
Switch left/right mouse buttons, remove zoom on middle
'use strict'; define( ['three', 'OrbitControls'], function(THREE) { return class Camera { // ############################################## // # Constructor ################################ // ############################################## constructor(scene, renderer, fov, aspectRatio, near, far, cameraPosition) { this.scene = scene; this.near = near; this.far = far; this.cameraPosition = cameraPosition; this.camera = new THREE.PerspectiveCamera(fov, aspectRatio, near, far); this.camera.position.set(cameraPosition.x, cameraPosition.y, cameraPosition.z); this.camera.zoom = 0.5; this.camera.updateProjectionMatrix(); scene.camera = this; this.controls = new THREE.OrbitControls(this.camera, renderer.domElement); this.controls.enableDamping = true; this.controls.dampingFactor = 0.125; this.controls.enableZoom = true; this.controls.rotateSpeed = 0.15; this.controls.enableKeys = false; this.controls.mouseButtons = { ORBIT: THREE.MOUSE.RIGHT, PAN: THREE.MOUSE.LEFT }; } } } );
'use strict'; define( ['three', 'OrbitControls'], function(THREE) { return class Camera { // ############################################## // # Constructor ################################ // ############################################## constructor(scene, renderer, fov, aspectRatio, near, far, cameraPosition) { this.scene = scene; this.near = near; this.far = far; this.cameraPosition = cameraPosition; this.camera = new THREE.PerspectiveCamera(fov, aspectRatio, near, far); this.camera.position.set(cameraPosition.x, cameraPosition.y, cameraPosition.z); this.camera.zoom = 0.5; this.camera.updateProjectionMatrix(); scene.camera = this; this.controls = new THREE.OrbitControls(this.camera, renderer.domElement); this.controls.enableDamping = true; this.controls.dampingFactor = 0.125; this.controls.enableZoom = true; this.controls.rotateSpeed = 0.15; this.controls.enableKeys = false; } } } );
Make missing password and error If the URL is set but no password this is clearly a config error.
package io.quarkus.vertx.http.deployment.devmode; import java.util.Optional; import org.jboss.logging.Logger; import io.quarkus.deployment.dev.remote.RemoteDevClient; import io.quarkus.deployment.dev.remote.RemoteDevClientProvider; import io.quarkus.runtime.LiveReloadConfig; import io.quarkus.runtime.configuration.ConfigInstantiator; public class HttpRemoteDevClientProvider implements RemoteDevClientProvider { private static final Logger log = Logger.getLogger(HttpRemoteDevClientProvider.class); /** * Used for remote dev mode, a bit of a hack to expose the config to the client */ public static volatile LiveReloadConfig liveReloadConfig; @Override public Optional<RemoteDevClient> getClient() { if (liveReloadConfig == null) { liveReloadConfig = new LiveReloadConfig(); ConfigInstantiator.handleObject(liveReloadConfig); } if (!liveReloadConfig.url.isPresent()) { return Optional.empty(); } if (!liveReloadConfig.password.isPresent()) { throw new RuntimeException( "Live reload URL set but no password, remote dev requires a password, set quarkus.live-reload.password on both server and client"); } return Optional.of(new HttpRemoteDevClient(liveReloadConfig.url.get(), liveReloadConfig.password.get(), liveReloadConfig.connectTimeout)); } }
package io.quarkus.vertx.http.deployment.devmode; import java.util.Optional; import org.jboss.logging.Logger; import io.quarkus.deployment.dev.remote.RemoteDevClient; import io.quarkus.deployment.dev.remote.RemoteDevClientProvider; import io.quarkus.runtime.LiveReloadConfig; import io.quarkus.runtime.configuration.ConfigInstantiator; public class HttpRemoteDevClientProvider implements RemoteDevClientProvider { private static final Logger log = Logger.getLogger(HttpRemoteDevClientProvider.class); /** * Used for remote dev mode, a bit of a hack to expose the config to the client */ public static volatile LiveReloadConfig liveReloadConfig; @Override public Optional<RemoteDevClient> getClient() { if (liveReloadConfig == null) { liveReloadConfig = new LiveReloadConfig(); ConfigInstantiator.handleObject(liveReloadConfig); } if (!liveReloadConfig.url.isPresent()) { return Optional.empty(); } if (!liveReloadConfig.password.isPresent()) { log.warn( "Live reload URL set but no password, remote dev requires a password, set quarkus.live-reload.password on both server and client"); return Optional.empty(); } return Optional.of(new HttpRemoteDevClient(liveReloadConfig.url.get(), liveReloadConfig.password.get(), liveReloadConfig.connectTimeout)); } }
Change from Date.now to performance.now for time delta extension
/*global Engine2D*/ /** * @author jackdalton */ ;(function() { /** * Delta timer constructor. * * @param {boolean} [true] autoInit - Automatically initialize timer. */ if (typeof Engine2D == "undefined") throw new Error("engine2d.js must be included before engine2d.collision.js"); Engine2D.GameScene.prototype.DeltaTimer = function(autoInit) { autoInit = autoInit || true; var self = this; var now = autoInit ? performance.now() : null, then, delta; /** * Updates timer. * * @private */ var updateTimer = function() { then = now; now = performance.now(); delta = now - then; }; /** * Initializes timer. */ self.init = function() { now = performance.now(); }; /** * Updates timer. * * @returns {integer} delta - Delta time in milliseconds. */ self.update = function() { updateTimer(); return delta; }; /** * Gets last recorded delta without updating timer. */ self.getDelta = function() { return delta; }; /** * Resets timer. */ self.resetTimer = function() { now = null, then = null, delta = null; }; }; })();
/*global Engine2D*/ /** * @author jackdalton */ ;(function() { /** * Delta timer constructor. * * @param {boolean} [true] autoInit - Automatically initialize timer. */ if (typeof Engine2D == "undefined") throw new Error("engine2d.js must be included before engine2d.collision.js"); Engine2D.GameScene.prototype.DeltaTimer = function(autoInit) { autoInit = autoInit || true; var self = this; var now = autoInit ? Date.now() : null, then, delta; /** * Updates timer. * * @private */ var updateTimer = function() { then = now; now = Date.now(); delta = now - then; }; /** * Initializes timer. */ self.init = function() { now = Date.now(); }; /** * Updates timer. * * @returns {integer} delta - Delta time in milliseconds. */ self.update = function() { updateTimer(); return delta; }; /** * Gets last recorded delta without updating timer. */ self.getDelta = function() { return delta; }; /** * Resets timer. */ self.resetTimer = function() { now = null, then = null, delta = null; }; }; })();
[examples] Use `action` provided by storybook
import React from 'react'; import { action } from '@kadira/storybook'; import Button from 'src/Button'; import FlexRow from '../FlexRow'; function BasicButtonExample() { return ( <FlexRow> <Button basic="Blue Button" aside="Default color" tag="Tag" icon="add" onClick={action('clicked')} /> <Button color="red" basic="Red" aside="Variants" tag="Tag" icon="add" /> <Button color="white" basic="White" aside="Variants" tag="Tag" icon="add" /> <Button color="black" basic="Black" aside="Variants" tag="Tag" icon="add" /> </FlexRow> ); } export default BasicButtonExample;
import React from 'react'; import Button from 'src/Button'; import FlexRow from '../FlexRow'; function handleButtonClick() { // eslint-disable-next-line no-console console.log('Button clicked'); } function BasicButtonExample() { return ( <FlexRow> <Button basic="Blue Button" aside="Default color" tag="Tag" icon="add" onClick={handleButtonClick} /> <Button color="red" basic="Red" aside="Variants" tag="Tag" icon="add" /> <Button color="white" basic="White" aside="Variants" tag="Tag" icon="add" /> <Button color="black" basic="Black" aside="Variants" tag="Tag" icon="add" /> </FlexRow> ); } export default BasicButtonExample;
Remove regular expression as condition for new reminder
const { IntentDialog, DialogAction, EntityRecognizer } = require('botbuilder'); const consts = require('../helpers/consts'); const config = require('../../config'); const utils = require('../helpers/utils'); const { witRecognizer } = require('../helpers/witRecognizer'); module.exports = new IntentDialog({ recognizers: [witRecognizer] }) .matches('set_timezone', DialogAction.beginDialog('/setTimezone')) .matches('show_reminders', DialogAction.beginDialog('/showReminders')) .matches('show_timezone', DialogAction.beginDialog('/showTimezone')) .onDefault((session, args) => { const message = session.message.text; const { entities } = args; // Extract all the useful entities. const reminder = EntityRecognizer.findEntity(entities, 'reminder'); const datetime = EntityRecognizer.findEntity(entities, 'datetime'); const greeting = EntityRecognizer.findEntity(entities, 'greeting'); // The user wants to set a new reminder. // If datetime is undefined, the bot will prompt the user to choose one. if (reminder) { session.beginDialog('/newReminder', { reminder, datetime, message }); } // If the user just sends a greeting, send a greeting back and show an example of how to set a reminder. else if (greeting && !reminder && !datetime) { session.endDialog(consts.Messages.GREETING_RESPONSE, utils.getRandomGreeting(), utils.getRandomReminder()); } // Send a default response else { session.endDialog(consts.Messages.DEFAULT_RESPONSE, utils.getRandomReminder()); } });
const { IntentDialog, DialogAction, EntityRecognizer } = require('botbuilder'); const consts = require('../helpers/consts'); const config = require('../../config'); const utils = require('../helpers/utils'); const { witRecognizer } = require('../helpers/witRecognizer'); module.exports = new IntentDialog({ recognizers: [witRecognizer] }) .matches('set_timezone', DialogAction.beginDialog('/setTimezone')) .matches('show_reminders', DialogAction.beginDialog('/showReminders')) .matches('show_timezone', DialogAction.beginDialog('/showTimezone')) .onDefault((session, args) => { const message = session.message.text; const { entities } = args; // Extract all the useful entities. const reminder = EntityRecognizer.findEntity(entities, 'reminder'); const datetime = EntityRecognizer.findEntity(entities, 'datetime'); const greeting = EntityRecognizer.findEntity(entities, 'greeting'); // The user wants to set a new reminder. // If datetime is undefined, the bot will prompt the user to choose one. if (reminder && message.match(/remind me/i)) session.beginDialog('/newReminder', { reminder, datetime, message }); // If the user just sends a greeting, send a greeting back and show an example of how to set a reminder. else if (greeting && !reminder && !datetime) session.endDialog(consts.Messages.GREETING_RESPONSE, utils.getRandomGreeting(), utils.getRandomReminder()); // Send a default response else session.endDialog(consts.Messages.DEFAULT_RESPONSE, utils.getRandomReminder()); });
Fix to correctly use per-widget taks source.
package org.andstatus.todoagenda.task; import android.app.Activity; import android.content.Context; import org.andstatus.todoagenda.EventProvider; import org.andstatus.todoagenda.task.dmfs.DmfsOpenTasksProvider; import org.andstatus.todoagenda.task.samsung.SamsungTasksProvider; import java.util.List; public class TaskProvider extends EventProvider { private static final String PROVIDER_DMFS = "DMFS_OPEN_TASKS"; private static final String PROVIDER_SAMSUNG = "SAMSUNG"; public TaskProvider(Context context, int widgetId) { super(context, widgetId); } public List<TaskEvent> getEvents() { AbstractTaskProvider provider = getProvider(); return provider.getTasks(); } public boolean hasPermission() { AbstractTaskProvider provider = getProvider(); return provider.hasPermission(); } public void requestPermission(Activity activity) { AbstractTaskProvider provider = getProvider(); provider.requestPermission(activity); } private AbstractTaskProvider getProvider() { String taskSource = getSettings().getTaskSource(); if (PROVIDER_DMFS.equals(taskSource)) { return new DmfsOpenTasksProvider(context, widgetId); } if (PROVIDER_SAMSUNG.equals(taskSource)) { return new SamsungTasksProvider(context, widgetId); } return new EmptyTaskProvider(context, widgetId); } }
package org.andstatus.todoagenda.task; import android.app.Activity; import android.content.Context; import org.andstatus.todoagenda.EventProvider; import org.andstatus.todoagenda.prefs.ApplicationPreferences; import org.andstatus.todoagenda.task.dmfs.DmfsOpenTasksProvider; import org.andstatus.todoagenda.task.samsung.SamsungTasksProvider; import java.util.List; public class TaskProvider extends EventProvider { private static final String PROVIDER_DMFS = "DMFS_OPEN_TASKS"; private static final String PROVIDER_SAMSUNG = "SAMSUNG"; public TaskProvider(Context context, int widgetId) { super(context, widgetId); } public List<TaskEvent> getEvents() { AbstractTaskProvider provider = getProvider(); return provider.getTasks(); } public boolean hasPermission() { AbstractTaskProvider provider = getProvider(); return provider.hasPermission(); } public void requestPermission(Activity activity) { AbstractTaskProvider provider = getProvider(); provider.requestPermission(activity); } private AbstractTaskProvider getProvider() { String taskSource = ApplicationPreferences.getTaskSource(context); if (PROVIDER_DMFS.equals(taskSource)) { return new DmfsOpenTasksProvider(context, widgetId); } if (PROVIDER_SAMSUNG.equals(taskSource)) { return new SamsungTasksProvider(context, widgetId); } return new EmptyTaskProvider(context, widgetId); } }
Change register response access_token to scalar_token
/* Copyright 2016 OpenMarket 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. */ var q = require("q"); var request = require('browser-request'); var SdkConfig = require('./SdkConfig'); class ScalarAuthClient { getScalarToken(openid_token_object) { var defer = q.defer(); var scalar_rest_url = SdkConfig.get().integrations_rest_url; request({ method: 'POST', uri: scalar_rest_url+'/register', body: openid_token_object, json: true, }, (err, response, body) => { if (err) { defer.reject(err); } else if (response.statusCode / 100 !== 2) { defer.reject({statusCode: response.statusCode}); } else if (!body || !body.scalar_token) { defer.reject(new Error("Missing scalar_token in response")); } else { defer.resolve(body.scalar_token); } }); return defer.promise; } } module.exports = ScalarAuthClient;
/* Copyright 2016 OpenMarket 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. */ var q = require("q"); var request = require('browser-request'); var SdkConfig = require('./SdkConfig'); class ScalarAuthClient { getScalarToken(openid_token_object) { var defer = q.defer(); var scalar_rest_url = SdkConfig.get().integrations_rest_url; request({ method: 'POST', uri: scalar_rest_url+'/register', body: openid_token_object, json: true, }, (err, response, body) => { if (err) { defer.reject(err); } else if (response.statusCode / 100 !== 2) { defer.reject({statusCode: response.statusCode}); } else { defer.resolve(body.access_token); } }); return defer.promise; } } module.exports = ScalarAuthClient;
Make sure prior article is in prior month when seeding
<?php namespace Database\Seeders; use App\Models\Article; use Illuminate\Support\Carbon; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class ArticlesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $now = Carbon::now()->subMonth()->subDays(5); $articleFirst = Article::create([ 'title' => 'My New Blog', 'main' => 'This is *my* new blog. It uses `Markdown`.', 'published' => 1, 'created_at' => $now, ]); DB::table('articles') ->where('id', $articleFirst->id) ->update(['updated_at' => $now->toDateTimeString()]); $now = Carbon::now()->subHours(2)->subMinutes(25); $articleWithCode = <<<EOF I wrote some code. I liked writing this: ```php <?php declare(strict_types=1); class Foo { public function __construct() { echo 'Foo class constructed'; } } ``` EOF; $articleSecond = Article::create([ 'title' => 'Some code I did', 'main' => $articleWithCode, 'published' => 1, 'created_at' => $now, ]); DB::table('articles') ->where('id', $articleSecond->id) ->update(['updated_at' => $now->toDateTimeString()]); } }
<?php namespace Database\Seeders; use App\Models\Article; use Illuminate\Support\Carbon; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class ArticlesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $now = Carbon::now()->subMonth(); $articleFirst = Article::create([ 'title' => 'My New Blog', 'main' => 'This is *my* new blog. It uses `Markdown`.', 'published' => 1, 'created_at' => $now, ]); DB::table('articles') ->where('id', $articleFirst->id) ->update(['updated_at' => $now->toDateTimeString()]); $now = Carbon::now()->subHours(2)->subMinutes(25); $articleWithCode = <<<EOF I wrote some code. I liked writing this: ```php <?php declare(strict_types=1); class Foo { public function __construct() { echo 'Foo class constructed'; } } ``` EOF; $articleSecond = Article::create([ 'title' => 'Some code I did', 'main' => $articleWithCode, 'published' => 1, 'created_at' => $now, ]); DB::table('articles') ->where('id', $articleSecond->id) ->update(['updated_at' => $now->toDateTimeString()]); } }
Add process_id into the $state.go statements. Have chooseExistingProcess make a REST call to get the list of processes.
(function (module) { module.controller('ProjectHomeController', ProjectHomeController); ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state", "Restangular"]; function ProjectHomeController(project, mcmodal, templates, $state, Restangular) { var ctrl = this; ctrl.project = project; ctrl.chooseTemplate = chooseTemplate; ctrl.chooseExistingProcess = chooseExistingProcess; ctrl.createSample = createSample; ctrl.useTemplate = useTemplate; ctrl.templates = templates; ///////////////////////// function chooseTemplate() { mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) { $state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''}); }); } function useTemplate(templateName) { $state.go('projects.project.processes.create', {process: templateName, process_id: ''}); } function createSample() { $state.go('projects.project.processes.create', {process: 'As Received', process_id: ''}); } function chooseExistingProcess() { Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) { mcmodal.chooseExistingProcess(processes).then(function (existingProcess) { var processName = existingProcess.process_name ? existingProcess.process_name : 'TEM'; $state.go('projects.project.processes.create', {process: processName, process_id: existingProcess.id}); }); }); } } }(angular.module('materialscommons')));
(function (module) { module.controller('ProjectHomeController', ProjectHomeController); ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state"]; function ProjectHomeController(project, mcmodal, templates, $state) { var ctrl = this; ctrl.project = project; ctrl.chooseTemplate = chooseTemplate; ctrl.chooseExistingProcess = chooseExistingProcess; ctrl.createSample = createSample; ctrl.useTemplate = useTemplate; ctrl.templates = templates; ///////////////////////// function chooseTemplate() { mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) { $state.go('projects.project.processes.create', {process: processTemplateName}); }); } function useTemplate(templateName) { $state.go('projects.project.processes.create', {process: templateName}); } function createSample() { $state.go('projects.project.processes.create', {process: 'As Received'}); } function chooseExistingProcess() { mcmodal.chooseExistingProcess(ctrl.project).then(function (existingProcess) { $state.go('projects.project.processes.create', {process: existingProcess.process_name, process_id: existingProcess.id}); }); } } }(angular.module('materialscommons')));
Use singleton() for service binding as Laravel 5.4 depreciated share() method
<?php namespace MartinLindhe\VueInternationalizationGenerator; use Illuminate\Support\ServiceProvider; class GeneratorProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Perform post-registration booting of services. * * @return void */ public function boot() { $this->app->singleton('vue-i18n.generate', function () { return new Commands\GenerateInclude; }); $this->commands( 'vue-i18n.generate' ); $this->publishes([ __DIR__.'/config/vue-i18n-generator.php' => config_path('vue-i18n-generator.php'), ]); $this->mergeConfigFrom( __DIR__.'/config/vue-i18n-generator.php', 'vue-i18n-generator' ); } /** * Register the service provider. * * @return void */ public function register() { } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['vue-i18n-generator']; } }
<?php namespace MartinLindhe\VueInternationalizationGenerator; use Illuminate\Support\ServiceProvider; class GeneratorProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Perform post-registration booting of services. * * @return void */ public function boot() { $this->app[ 'vue-i18n.generate' ] = $this->app->share(function () { return new Commands\GenerateInclude; }); $this->commands( 'vue-i18n.generate' ); $this->publishes([ __DIR__.'/config/vue-i18n-generator.php' => config_path('vue-i18n-generator.php'), ]); $this->mergeConfigFrom( __DIR__.'/config/vue-i18n-generator.php', 'vue-i18n-generator' ); } /** * Register the service provider. * * @return void */ public function register() { } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['vue-i18n-generator']; } }
Use a better undefined check
var Delegator = require('dom-delegator') module.exports = BaseEvent function BaseEvent(lambda) { return EventHandler; function EventHandler(fn, data, opts) { var handler = { fn: fn, data: data !== undefined ? data : {}, opts: opts || {}, handleEvent: handleEvent } if (fn && fn.type === 'dom-delegator-handle') { return Delegator.transformHandle(fn, handleLambda.bind(handler)) } return handler; } function handleLambda(ev, broadcast) { if (this.opts.startPropagation && ev.startPropagation) { ev.startPropagation(); } return lambda.call(this, ev, broadcast) } function handleEvent(ev) { var self = this if (self.opts.startPropagation && ev.startPropagation) { ev.startPropagation() } lambda.call(self, ev, broadcast) function broadcast(value) { if (typeof self.fn === 'function') { self.fn(value) } else { self.fn.write(value) } } } }
var Delegator = require('dom-delegator') module.exports = BaseEvent function BaseEvent(lambda) { return EventHandler; function EventHandler(fn, data, opts) { var handler = { fn: fn, data: typeof data != 'undefined' ? data : {}, opts: opts || {}, handleEvent: handleEvent } if (fn && fn.type === 'dom-delegator-handle') { return Delegator.transformHandle(fn, handleLambda.bind(handler)) } return handler; } function handleLambda(ev, broadcast) { if (this.opts.startPropagation && ev.startPropagation) { ev.startPropagation(); } return lambda.call(this, ev, broadcast) } function handleEvent(ev) { var self = this if (self.opts.startPropagation && ev.startPropagation) { ev.startPropagation() } lambda.call(self, ev, broadcast) function broadcast(value) { if (typeof self.fn === 'function') { self.fn(value) } else { self.fn.write(value) } } } }
Fix changelist footer fixed transition
var $ = require('jquery'); var ActionsUpdater = function($changelist) { this.$changelist = $changelist; }; ActionsUpdater.prototype = { removeLabel: function($actions) { var $input = $actions.find('[name="action"]').first(); if ($input.length == 0) { return; } var $label = $($input[0].previousSibling); if ($label.get(0).nodeType == 3) { $label.remove(); } }, wrapLabels: function($actions) { var $wrapper = $('<div>').addClass('labels'); $actions.find('span.all, span.action-counter, span.clear, span.question') .wrapAll($wrapper); }, moveActions: function($actions) { var $paginator = this.$changelist.find('.paginator'); var $wrapper = $('<div>').addClass('changelist-footer'); $wrapper.insertAfter($paginator); $actions.detach(); $paginator.detach(); $wrapper .append($actions) .append($paginator) .append($('<div>').addClass('cf')); }, run: function() { var $actions = this.$changelist.find('.actions'); try { this.removeLabel($actions); this.wrapLabels($actions); this.moveActions($actions); } catch (e) { console.error(e, e.stack); } $actions.addClass('initialized'); } }; $(document).ready(function() { $('#changelist').each(function() { new ActionsUpdater($(this)).run(); }); });
var $ = require('jquery'); var ActionsUpdater = function($changelist) { this.$changelist = $changelist; }; ActionsUpdater.prototype = { removeLabel: function($actions) { var $input = $actions.find('[name="action"]').first(); if ($input.length == 0) { return; } var $label = $($input[0].previousSibling); if ($label.get(0).nodeType == 3) { $label.remove(); } }, wrapLabels: function($actions) { var $wrapper = $('<div>').addClass('labels'); $actions.find('span.all, span.action-counter, span.clear, span.question') .wrapAll($wrapper); }, moveActions: function($actions) { var $paginator = this.$changelist.find('.paginator'); var $wrapper = $('<div>').addClass('changelist-footer'); $wrapper.insertAfter($paginator); $actions.detach(); $paginator.detach(); $wrapper.append($actions); $wrapper.append($paginator); }, run: function() { var $actions = this.$changelist.find('.actions'); try { this.removeLabel($actions); this.wrapLabels($actions); this.moveActions($actions); } catch (e) { console.error(e, e.stack); } $actions.addClass('initialized'); } }; $(document).ready(function() { $('#changelist').each(function() { new ActionsUpdater($(this)).run(); }); });
Put higher level functions first
(function(){ var mod = angular.module('caspy.api', ['ngResource', 'caspy.server']); mod.config(['$resourceProvider', function($resourceProvider) { $resourceProvider.defaults.stripTrailingSlashes = false; }] ); mod.factory('caspyAPI', ['$q', '$http', '$resource', 'Constants', function($q, $http, $resource, Constants) { var api = { root: null , resources: {} , get_resource: function(name) { if (typeof api.resources[name] !== 'undefined') return api.resources[name]; return api.resources[name] = api.get_endpoint(name) .then(api.build_resource); } , get_endpoint: function(name) { if (api.root) return api.resolve(name); return $http.get(Constants.apiRootUrl) .then(function(response) { api.root = response.data; return api.resolve(name); }) } , build_resource: function(endpoint) { return $resource(endpoint); } , resolve: function(name) { var d = $q.defer(); if (typeof api.root[name] === 'undefined') { d.reject(new Error(name + ' endpoint not available')); } else { d.resolve(api.root[name]); } return d.promise; } }; return api; }] ); })();
(function(){ var mod = angular.module('caspy.api', ['ngResource', 'caspy.server']); mod.config(['$resourceProvider', function($resourceProvider) { $resourceProvider.defaults.stripTrailingSlashes = false; }] ); mod.factory('caspyAPI', ['$q', '$http', '$resource', 'Constants', function($q, $http, $resource, Constants) { var api = { root: null , resources: {} , resolve: function(name) { var d = $q.defer(); if (typeof api.root[name] === 'undefined') { d.reject(new Error(name + ' endpoint not available')); } else { d.resolve(api.root[name]); } return d.promise; } , get_endpoint: function(name) { if (api.root) return api.resolve(name); return $http.get(Constants.apiRootUrl) .then(function(response) { api.root = response.data; return api.resolve(name); }) } , get_resource: function(name) { if (typeof api.resources[name] !== 'undefined') return api.resources[name]; return api.resources[name] = api.get_endpoint(name) .then(api.build_resource); } , build_resource: function(endpoint) { return $resource(endpoint); } }; return api; }] ); })();
Change script run message output
import os import sys from optparse import OptionParser from conda_verify.errors import RecipeError from conda_verify.verify import Verify from conda_verify.utilities import render_metadata, iter_cfgs def cli(): p = OptionParser( usage="usage: %prog [options] <path to recipes or packages>", description="tool for (passively) verifying conda recipes and conda " "packages for the Anaconda distribution") p.add_option('-v', '--version', help="display the version being used and exit", action="store_true") opts, args = p.parse_args() if opts.version: from conda_verify import __version__ sys.exit('conda-verify {}' .format(__version__)) verifier = Verify() for path in args: meta_file = os.path.join(path, 'meta.yaml') if os.path.isfile(meta_file): print('Verifying {}...' .format(meta_file)) for cfg in iter_cfgs(): meta = render_metadata(path, cfg) try: verifier.verify_recipe(rendered_meta=meta, recipe_dir=path) except RecipeError as e: sys.stderr.write("RecipeError: %s\n" % e) elif path.endswith(('.tar.bz2', '.tar')): print('Verifying {}...' .format(path)) verifier.verify_package(path_to_package=path)
import os import sys from optparse import OptionParser from conda_verify.errors import RecipeError from conda_verify.verify import Verify from conda_verify.utilities import render_metadata, iter_cfgs def cli(): p = OptionParser( usage="usage: %prog [options] <path to recipes or packages>", description="tool for (passively) verifying conda recipes and conda " "packages for the Anaconda distribution") p.add_option('-v', '--version', help="display the version being used and exit", action="store_true") opts, args = p.parse_args() if opts.version: from conda_verify import __version__ sys.exit('conda-verify {}' .format(__version__)) verifier = Verify() for path in args: if os.path.isfile(os.path.join(path, 'meta.yaml')): print("==> %s <==" % path) for cfg in iter_cfgs(): meta = render_metadata(path, cfg) try: verifier.verify_recipe(rendered_meta=meta, recipe_dir=path) except RecipeError as e: sys.stderr.write("RecipeError: %s\n" % e) elif path.endswith(('.tar.bz2', '.tar')): print('Verifying {}...' .format(path)) verifier.verify_package(path_to_package=path)
Fix stupid git app committing unwanted stuff~
# coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = "," PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ]
# coding: utf-8 """ Created on 2016-08-23 @author: naoey """ VERSION = "0.0.3" BOT_PREFIX = ":" PATHS = { "logs_dir": "./../logs/", "database": "./../slash_bot.db", "discord_creds": "./../private/discord.json", "rito_creds": "./../private/rito.json", "assets": "./../assets/", } MODULES = { "League of Legends": { "location": "games.lol", "class": "LeagueOfLegends", "active": True, "prefix": "lol", "config": { "static_refresh_interval": { "value": "604800", "description": "The time interval in seconds before refreshing static data" } } }, "osu!": { "location": "games.osu.Osu", "class": "Osu", "active": False, "prefix": "osu", "config": {}, }, "MyAnimeList": { "location": "anime.mal.MyAnimeList", "class": "MyAnimeList", "active": False, "prefix": "mal", "config": {}, }, } API_LIMITS = { "riot": { "10": "10", "600": "500", } } GLOBAL = { } DISCORD_STATUS_ITER = [ "procrastination \(^-^)/", ]
Make sequence editor text area
$(function() { var dt = {sPaginationType: 'full_numbers', bProcessing: true, bServerSide: true, sAjaxSource: '/sample/ajax/pid/'+pid+'/', bAutoWidth:false , aaSorting: [[ 0, 'desc' ]], //fnDrawCallback: _map_callbacks(), fnServerData: function ( sSource, aoData, fnCallback ) { $.getJSON( sSource, aoData, function (json) { fnCallback(json) _map_callbacks() }) } } if ($(window).width() <= 600) dt = $.extend({ 'bScrollCollapse': true, 'sScrollX': '100%', }, dt) $('.robot_actions').dataTable(dt) function _map_callbacks() { //setTimeout(function() { $('a.view').button({ icons: { primary: 'ui-icon-search' } }) //}, 500) } $.each(['name', 'acronym', 'mass'], function(i,e) { $('.'+e).editable('/sample/ajax/updatep/pid/'+pid+'/ty/'+e+'/', { height: '100%', type: 'text', submit: 'Ok', style: 'display: inline', }).addClass('editable'); }) $('.seq').editable('/sample/ajax/updatep/pid/'+pid+'/ty/seq/', { type: 'textarea', rows: 5, width: '100%', submit: 'Ok', style: 'display: inline', }).addClass('editable'); })
$(function() { var dt = {sPaginationType: 'full_numbers', bProcessing: true, bServerSide: true, sAjaxSource: '/sample/ajax/pid/'+pid+'/', bAutoWidth:false , aaSorting: [[ 0, 'desc' ]], //fnDrawCallback: _map_callbacks(), fnServerData: function ( sSource, aoData, fnCallback ) { $.getJSON( sSource, aoData, function (json) { fnCallback(json) _map_callbacks() }) } } if ($(window).width() <= 600) dt = $.extend({ 'bScrollCollapse': true, 'sScrollX': '100%', }, dt) $('.robot_actions').dataTable(dt) function _map_callbacks() { //setTimeout(function() { $('a.view').button({ icons: { primary: 'ui-icon-search' } }) //}, 500) } $.each(['name', 'acronym', 'mass'], function(i,e) { $('.'+e).editable('/sample/ajax/updatep/pid/'+pid+'/ty/'+e+'/', { height: '100%', type: 'text', submit: 'Ok', style: 'display: inline', }).addClass('editable'); }) $('.seq').editable('/sample/ajax/updatep/pid/'+pid+'/ty/seq/', { type: 'text', height: '100%', width: '50%', submit: 'Ok', style: 'display: inline', }).addClass('editable'); })
Add \r\n to the end of each header too
""" Module for a Response object. A Response is returned by Routes when the underlying coroutine is done. """ from http_parser.util import IOrderedDict from .util import HTTP_CODES class Response(object): """ A response is responsible (no pun intended) for delivering data to the client, again. The method `to_bytes()` transforms this into a bytes response. """ def __init__(self, code: int, body: str, headers: dict): """ Create a new response. """ self.code = code self.body = str(body) self.headers = IOrderedDict(headers) def _recalculate_headers(self): """ Override certain headers, like Content-Size. """ self.headers["Content-Length"] = len(self.body) if 'Content-Type' not in self.headers: self.headers["Content-Type"] = "text/plain" def to_bytes(self): """ Return the correct response. """ self._recalculate_headers() fmt = "HTTP/1.1 {code} {msg}\r\n{headers}\r\n{body}\r\n" headers_fmt = "" # Calculate headers for name, val in self.headers.items(): headers_fmt += "{}: {}\r\n".format(name, val) built = fmt.format(code=self.code, msg=HTTP_CODES.get(self.code, "Unknown"), headers=headers_fmt, body=self.body) return built.encode()
""" Module for a Response object. A Response is returned by Routes when the underlying coroutine is done. """ from http_parser.util import IOrderedDict from .util import HTTP_CODES class Response(object): """ A response is responsible (no pun intended) for delivering data to the client, again. The method `to_bytes()` transforms this into a bytes response. """ def __init__(self, code: int, body: str, headers: dict): """ Create a new response. """ self.code = code self.body = str(body) self.headers = IOrderedDict(headers) def _recalculate_headers(self): """ Override certain headers, like Content-Size. """ self.headers["Content-Length"] = len(self.body) def to_bytes(self): """ Return the correct response. """ self._recalculate_headers() fmt = "HTTP/1.1 {code} {msg}\r\n{headers}\r\n\r\n{body}\r\n" headers_fmt = "" # Calculate headers for name, val in self.headers.items(): headers_fmt += "{}: {}".format(name, val) built = fmt.format(code=self.code, msg=HTTP_CODES.get(self.code, "Unknown"), headers=headers_fmt, body=self.body) return built.encode()
Fix running bower on non-windows
var join = require('path').join; var execFileSync = require('child_process').execFileSync; var cache = {}; var originalWhich = require('which'); var isWin = process.platform === 'win32'; function which(name, opt, cb) { if (typeof opt === 'function') { cb = opt; opt = {}; } if (isWin) { var result = whichSync(name); if (result) { cb(null, result); } else { cb(new Error('Could not find ' + name + ' in PATH')); } } else { originalWhich(name, opt, cb); } } function whichSync(name, opt) { if (name in cache) { return cache[name]; } if (isWin) { var WHERE_PATH = join(process.env.WINDIR, 'System32', 'where.exe'); var stdout = execFileSync(WHERE_PATH, ['$PATH:' + name], { stdio: ['pipe', 'pipe', 'ignore'] }).toString(); var matches = stdout.split('\r\n'); if (matches.length === 0) { throw new Error('Could not find ' + name + ' in PATH'); } var result = matches[0].trim(); cache[name] = result; return result; } var result = originalWhich.sync(name, opt); cache[name] = result; return result; } which.sync = whichSync; module.exports = which;
var join = require('path').join; var execFileSync = require('child_process').execFileSync; var WHERE_PATH = join(process.env.WINDIR, 'System32', 'where.exe'); var cache = {}; var originalWhich = require('which'); var isWin = process.platform === 'win32'; function which(name, opt, cb) { if (typeof opt === 'function') { cb = opt; opt = {}; } if (isWin) { var result = whichSync(name); if (result) { cb(null, result); } else { cb(new Error('Could not find ' + name + ' in PATH')); } } else { originalWhich(name, opt, cb); } } function whichSync(name, opt) { if (name in cache) { return cache[name]; } if (isWin) { var stdout = execFileSync(WHERE_PATH, ['$PATH:' + name], { stdio: ['pipe', 'pipe', 'ignore'] }).toString(); var matches = stdout.split('\r\n'); if (matches.length === 0) { throw new Error('Could not find ' + name + ' in PATH'); } var result = matches[0].trim(); cache[name] = result; return result; } var result = originalWhich.sync(name, opt); cache[name] = result; return result; } which.sync = whichSync; module.exports = which;
Rename summernote to context in module.
define([], function () { var HelpDialog = function (context) { var self = this; var ui = $.summernote.ui; var $editor = context.layoutInfo.editor; var options = context.options; var lang = options.langInfo; this.initialize = function () { var $container = options.dialogsInBody ? $(document.body) : $editor; var body = [ '<p class="text-center">', '<a href="//summernote.org/" target="_blank">Summernote @VERSION</a> · ', '<a href="//github.com/summernote/summernote" target="_blank">Project</a> · ', '<a href="//github.com/summernote/summernote/issues" target="_blank">Issues</a>', '</p>' ].join(''); this.$dialog = ui.dialog({ title: lang.options.help, body: body }).render().appendTo($container); }; this.destroy = function () { ui.hideDialog(this.$dialog); this.$dialog.remove(); }; /** * show help dialog * * @return {Promise} */ this.showHelpDialog = function () { return $.Deferred(function (deferred) { ui.onDialogHidden(self.$dialog, function () { deferred.resolve(); }); ui.showDialog(self.$dialog); }).promise(); }; this.show = function () { context.invoke('editor.saveRange'); this.showHelpDialog().then(function () { context.invoke('editor.restoreRange'); }); }; }; return HelpDialog; });
define([], function () { var HelpDialog = function (summernote) { var self = this; var ui = $.summernote.ui; var $editor = summernote.layoutInfo.editor; var options = summernote.options; var lang = options.langInfo; this.initialize = function () { var $container = options.dialogsInBody ? $(document.body) : $editor; var body = [ '<p class="text-center">', '<a href="//summernote.org/" target="_blank">Summernote @VERSION</a> · ', '<a href="//github.com/summernote/summernote" target="_blank">Project</a> · ', '<a href="//github.com/summernote/summernote/issues" target="_blank">Issues</a>', '</p>' ].join(''); this.$dialog = ui.dialog({ title: lang.options.help, body: body }).render().appendTo($container); }; this.destroy = function () { ui.hideDialog(this.$dialog); this.$dialog.remove(); }; /** * show help dialog * * @return {Promise} */ this.showHelpDialog = function () { return $.Deferred(function (deferred) { ui.onDialogHidden(self.$dialog, function () { deferred.resolve(); }); ui.showDialog(self.$dialog); }).promise(); }; this.show = function () { summernote.invoke('editor.saveRange'); this.showHelpDialog().then(function () { summernote.invoke('editor.restoreRange'); }); }; }; return HelpDialog; });
Allow to override request fingerprint call.
import time from scrapy.dupefilters import BaseDupeFilter from scrapy.utils.request import request_fingerprint from . import connection class RFPDupeFilter(BaseDupeFilter): """Redis-based request duplication filter""" def __init__(self, server, key): """Initialize duplication filter Parameters ---------- server : Redis instance key : str Where to store fingerprints """ self.server = server self.key = key @classmethod def from_settings(cls, settings): server = connection.from_settings(settings) # create one-time key. needed to support to use this # class as standalone dupefilter with scrapy's default scheduler # if scrapy passes spider on open() method this wouldn't be needed key = "dupefilter:%s" % int(time.time()) return cls(server, key) @classmethod def from_crawler(cls, crawler): return cls.from_settings(crawler.settings) def request_seen(self, request): fp = self.request_fingerprint(request) added = self.server.sadd(self.key, fp) return not added def request_fingerprint(self, request): return request_fingerprint(request) def close(self, reason): """Delete data on close. Called by scrapy's scheduler""" self.clear() def clear(self): """Clears fingerprints data""" self.server.delete(self.key)
import time from scrapy.dupefilters import BaseDupeFilter from scrapy.utils.request import request_fingerprint from . import connection class RFPDupeFilter(BaseDupeFilter): """Redis-based request duplication filter""" def __init__(self, server, key): """Initialize duplication filter Parameters ---------- server : Redis instance key : str Where to store fingerprints """ self.server = server self.key = key @classmethod def from_settings(cls, settings): server = connection.from_settings(settings) # create one-time key. needed to support to use this # class as standalone dupefilter with scrapy's default scheduler # if scrapy passes spider on open() method this wouldn't be needed key = "dupefilter:%s" % int(time.time()) return cls(server, key) @classmethod def from_crawler(cls, crawler): return cls.from_settings(crawler.settings) def request_seen(self, request): fp = request_fingerprint(request) added = self.server.sadd(self.key, fp) return not added def close(self, reason): """Delete data on close. Called by scrapy's scheduler""" self.clear() def clear(self): """Clears fingerprints data""" self.server.delete(self.key)
Update openfisca-core requirement from <33.0,>=27.0 to >=27.0,<35.0 Updates the requirements on [openfisca-core](https://github.com/openfisca/openfisca-core) to permit the latest version. - [Release notes](https://github.com/openfisca/openfisca-core/releases) - [Changelog](https://github.com/openfisca/openfisca-core/blob/master/CHANGELOG.md) - [Commits](https://github.com/openfisca/openfisca-core/compare/27.0.0...34.0.0) Signed-off-by: dependabot[bot] <[email protected]>
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = "OpenFisca-Country-Template", version = "3.9.5", author = "OpenFisca Team", author_email = "[email protected]", classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: GNU Affero General Public License v3", "Operating System :: POSIX", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Information Analysis", ], description = "OpenFisca tax and benefit system for Country-Template", keywords = "benefit microsimulation social tax", license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html", url = "https://github.com/openfisca/country-template", include_package_data = True, # Will read MANIFEST.in data_files = [ ("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]), ], install_requires = [ "OpenFisca-Core[web-api] >=27.0,<35.0", ], extras_require = { "dev": [ "autopep8 ==1.4.4", "flake8 >=3.5.0,<3.8.0", "flake8-print", "pycodestyle >=2.3.0,<2.6.0", # To avoid incompatibility with flake ] }, packages=find_packages(), )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = "OpenFisca-Country-Template", version = "3.9.5", author = "OpenFisca Team", author_email = "[email protected]", classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: GNU Affero General Public License v3", "Operating System :: POSIX", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Information Analysis", ], description = "OpenFisca tax and benefit system for Country-Template", keywords = "benefit microsimulation social tax", license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html", url = "https://github.com/openfisca/country-template", include_package_data = True, # Will read MANIFEST.in data_files = [ ("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]), ], install_requires = [ "OpenFisca-Core[web-api] >=27.0,<33.0", ], extras_require = { "dev": [ "autopep8 ==1.4.4", "flake8 >=3.5.0,<3.8.0", "flake8-print", "pycodestyle >=2.3.0,<2.6.0", # To avoid incompatibility with flake ] }, packages=find_packages(), )
Exclude htdocs, because that just takes way too long to scan.
#!/usr/bin/env python # # Utility script to run pyflakes with the modules we care about and # exclude errors we know to be fine. import os import subprocess import sys module_exclusions = [ 'djblets', 'django_evolution', 'dist', 'ez_setup.py', 'htdocs', 'settings_local.py', 'ReviewBoard.egg-info', ] def scan_for_modules(): return [entry for entry in os.listdir(os.getcwd()) if ((os.path.isdir(entry) or entry.endswith(".py")) and entry not in module_exclusions)] def main(): cur_dir = os.path.dirname(__file__) os.chdir(os.path.join(cur_dir, "..", "..")) modules = sys.argv[1:] if not modules: # The user didn't specify anything specific. Scan for modules. modules = scan_for_modules() p = subprocess.Popen(['pyflakes'] + modules, stderr=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) contents = p.stdout.readlines() # Read in the exclusions file exclusions = {} fp = open(os.path.join(cur_dir, "pyflakes.exclude"), "r") for line in fp.readlines(): exclusions[line.rstrip()] = 1 fp.close() # Now filter thin for line in contents: line = line.rstrip() if line not in exclusions: print line if __name__ == "__main__": main()
#!/usr/bin/env python # # Utility script to run pyflakes with the modules we care about and # exclude errors we know to be fine. import os import subprocess import sys module_exclusions = [ 'djblets', 'django_evolution', 'dist', 'ez_setup.py', 'settings_local.py', 'ReviewBoard.egg-info', ] def scan_for_modules(): return [entry for entry in os.listdir(os.getcwd()) if ((os.path.isdir(entry) or entry.endswith(".py")) and entry not in module_exclusions)] def main(): cur_dir = os.path.dirname(__file__) os.chdir(os.path.join(cur_dir, "..", "..")) modules = sys.argv[1:] if not modules: # The user didn't specify anything specific. Scan for modules. modules = scan_for_modules() p = subprocess.Popen(['pyflakes'] + modules, stderr=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) contents = p.stdout.readlines() # Read in the exclusions file exclusions = {} fp = open(os.path.join(cur_dir, "pyflakes.exclude"), "r") for line in fp.readlines(): exclusions[line.rstrip()] = 1 fp.close() # Now filter thin for line in contents: line = line.rstrip() if line not in exclusions: print line if __name__ == "__main__": main()
Use an if statement for rounding delay counter rather than modulo
/** * @depends ../core/AudioletNode.js */ var Delay = new Class({ Extends: AudioletNode, initialize: function(audiolet, maximumDelayTime, delayTime) { AudioletNode.prototype.initialize.apply(this, [audiolet, 2, 1]); this.maximumDelayTime = maximumDelayTime; this.delayTime = new AudioletParameter(this, 1, delayTime || 1); this.buffer = new Float32Array(maximumDelayTime * this.audiolet.device.sampleRate); this.readWriteIndex = 0; }, generate: function(inputBuffers, outputBuffers) { var inputBuffer = inputBuffers[0]; var outputBuffer = outputBuffers[0]; if (inputBuffer.isEmpty) { outputBuffer.isEmpty = true; return; } // Local processing variables var delayTimeParameter = this.delayTime; var buffer = this.buffer; var readWriteIndex = this.readWriteIndex; var sampleRate = this.audiolet.device.sampleRate; var inputChannel = inputBuffer.getChannelData(0); var outputChannel = outputBuffer.getChannelData(0); var bufferLength = inputBuffer.length; for (var i = 0; i < bufferLength; i++) { var delayTime = delayTimeParameter.getValue(i) * sampleRate; outputChannel[i] = buffer[readWriteIndex]; buffer[readWriteIndex] = inputChannel[i]; readWriteIndex += 1; if (readWriteIndex >= delayTime) { readWriteIndex = 0; } } this.readWriteIndex = readWriteIndex; } });
/** * @depends ../core/AudioletNode.js */ var Delay = new Class({ Extends: AudioletNode, initialize: function(audiolet, maximumDelayTime, delayTime) { AudioletNode.prototype.initialize.apply(this, [audiolet, 2, 1]); this.maximumDelayTime = maximumDelayTime; this.delayTime = new AudioletParameter(this, 1, delayTime || 1); this.buffer = new Float32Array(maximumDelayTime * this.audiolet.device.sampleRate); this.readWriteIndex = 0; }, generate: function(inputBuffers, outputBuffers) { var inputBuffer = inputBuffers[0]; var outputBuffer = outputBuffers[0]; if (inputBuffer.isEmpty) { outputBuffer.isEmpty = true; return; } // Local processing variables var delayTimeParameter = this.delayTime; var buffer = this.buffer; var readWriteIndex = this.readWriteIndex; var sampleRate = this.audiolet.device.sampleRate; var inputChannel = inputBuffer.getChannelData(0); var outputChannel = outputBuffer.getChannelData(0); var bufferLength = inputBuffer.length; for (var i = 0; i < bufferLength; i++) { var delayTime = delayTimeParameter.getValue(i) * sampleRate; outputChannel[i] = buffer[readWriteIndex]; buffer[readWriteIndex] = inputChannel[i]; readWriteIndex = (readWriteIndex + 1) % delayTime; } this.readWriteIndex = readWriteIndex; } });
Refactor @listeningTo to use dependency cache
import React, {Component, PropTypes} from 'react'; import lodash from 'lodash'; export function listeningTo(storeTokens, getter) { return decorator; function decorator(ChildComponent) { class ListeningContainerComponent extends Component { static contextTypes = { dependencyCache: PropTypes.instanceOf(Map) } static Original = ChildComponent getStores() { const {dependencyCache} = this.context; return lodash.map(storeTokens, name => { if (typeof this.props[name] === 'string') { return this.props[name]; } else { return dependencyCache.get([name]); } }); } componentDidMount() { lodash.each(this.stores, store => { store.on('change', this.setStateFromStores); }); } componentWillUnmount() { lodash.each(this.stores, store => { store.removeListener('change', this.setStateFromStores); }); } constructor(props, context) { super(props, context); this.stores = this.getStores(); this.state = { childProps: getter(this.props) }; this.setStateFromStores = () => { this.setState({ childProps: getter(this.props) }); }; } render() { const {childProps} = this.state; return <ChildComponent {...this.props} {...childProps}/>; } } return ListeningContainerComponent; } }
import React, {Component, PropTypes} from 'react'; import lodash from 'lodash'; export function listeningTo(storeNames, getter) { return decorator; function decorator(ChildComponent) { class ListeningContainerComponent extends Component { static contextTypes = { dependencies: PropTypes.object.isRequired } static Original = ChildComponent componentDidMount() { const {dependencies} = this.context; const stores = lodash.map(storeNames, name => dependencies[name]); lodash.each(stores, store => { store.on('change', this.setStateFromStores); }); } componentWillUnmount() { const {dependencies} = this.context; const stores = lodash.map(storeNames, name => dependencies[name]); lodash.each(stores, store => { store.removeListener('change', this.setStateFromStores); }); } constructor(props, context) { super(props, context); const {dependencies} = this.context; this.state = { childProps: getter(dependencies) }; this.setStateFromStores = () => { this.setState({ childProps: getter(dependencies) }); }; } render() { const {childProps} = this.state; return <ChildComponent {...this.props} {...childProps}/>; } } return ListeningContainerComponent; } }