text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix councourse script for gpdb
#!/usr/bin/python2 import optparse import subprocess import sys from gporca import GporcaCommon def make(): ciCommon = GporcaCommon() return subprocess.call(["make", "-j" + str(ciCommon.num_cpus())], cwd="gpdb_src") def install(output_dir): subprocess.call(["make", "install"], cwd="gpdb_src") subprocess.call("mkdir -p " + output_dir, shell=True) return subprocess.call("cp -r /usr/local/gpdb/* " + output_dir, shell=True) def main(): parser = optparse.OptionParser() parser.add_option("--build_type", dest="build_type", default="RELEASE") parser.add_option("--compiler", dest="compiler") parser.add_option("--cxxflags", dest="cxxflags") parser.add_option("--output_dir", dest="output_dir", default="install") (options, args) = parser.parse_args() ciCommon = GporcaCommon() status = ciCommon.install_system_deps() if status: return status for dependency in args: status = ciCommon.install_dependency(dependency) if status: return status status = ciCommon.configure() if status: return status status = make() if status: return status status = install(options.output_dir) if status: return status return 0 if __name__ == "__main__": sys.exit(main())
#!/usr/bin/python2 import optparse import subprocess import sys from gporca import GporcaCommon def make(): return subprocess.call(["make", "-j" + str(num_cpus())], cwd="gpdb_src") def install(output_dir): subprocess.call(["make", "install"], cwd="gpdb_src") subprocess.call("mkdir -p " + output_dir, shell=True) return subprocess.call("cp -r /usr/local/gpdb/* " + output_dir, shell=True) def main(): parser = optparse.OptionParser() parser.add_option("--build_type", dest="build_type", default="RELEASE") parser.add_option("--compiler", dest="compiler") parser.add_option("--cxxflags", dest="cxxflags") parser.add_option("--output_dir", dest="output_dir", default="install") (options, args) = parser.parse_args() ciCommon = GporcaCommon() status = ciCommon.install_system_deps() if status: return status for dependency in args: status = ciCommon.install_dependency(dependency) if status: return status status = ciCommon.configure() if status: return status status = make() if status: return status status = install(options.output_dir) if status: return status return 0 if __name__ == "__main__": sys.exit(main())
Add onMarkClick event to SimpleTextGraph, set pointer cursor
import React from "react"; import CircularProgress from "material-ui/CircularProgress"; import "./style.css"; /* This is a very basic graph that displays a text message */ export default class SimpleTextGraph extends React.Component { render() { const { response, queryConfiguration, width, height, configuration: { data: { circle, circleColor } }, onMarkClick } = this.props; let body; if (response && !response.isFetching) { body = ( <div className="SimpleTextGraph"> {(() => { if(circle){ const padding = 16; const side = width * 0.3; return ( <div style={{ position: "fixed", left: width / 2 - side / 2 + padding, width: side + "px", height: side + "px", borderRadius: "50%", background: circleColor || "gray", textAlign: "center" }}/> ); } })()} <div className="BigNumber"> {response.results.length} </div> <br /> {queryConfiguration.title} </div> ); } else { body = ( <CircularProgress color="#eeeeee" /> ); } const cursor = onMarkClick ? "pointer" : undefined; return ( <div className="text-center" style={{ height: height, cursor: cursor}}> { body } </div> ); } } SimpleTextGraph.propTypes = { configuration: React.PropTypes.object, response: React.PropTypes.object };
import React from "react"; import CircularProgress from "material-ui/CircularProgress"; import "./style.css"; /* This is a very basic graph that displays a text message */ export default class SimpleTextGraph extends React.Component { render() { const { response, queryConfiguration, width, height, configuration: { data: { circle, circleColor } } } = this.props; let body; if (response && !response.isFetching) { body = ( <div className="SimpleTextGraph"> {(() => { if(circle){ const padding = 16; const side = width * 0.3; return ( <div style={{ position: "fixed", left: width / 2 - side / 2 + padding, width: side + "px", height: side + "px", borderRadius: "50%", background: circleColor || "gray", textAlign: "center" }}/> ); } })()} <div className="BigNumber"> {response.results.length} </div> <br /> {queryConfiguration.title} </div> ); } else { body = ( <CircularProgress color="#eeeeee" /> ); } return ( <div className="text-center" style={{ height: height }}> { body } </div> ); } } SimpleTextGraph.propTypes = { configuration: React.PropTypes.object, response: React.PropTypes.object };
Fix path cannot be set when creating new library
import os from pathlib import Path from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from django.db.utils import IntegrityError from photonix.photos.models import Library, LibraryPath, LibraryUser from photonix.photos.utils.db import record_photo from photonix.photos.utils.fs import determine_destination, download_file User = get_user_model() class Command(BaseCommand): help = 'Create a library for a user' def create_library(self, username, library_name, path): # Get user user = User.objects.get(username=username) # Create Library library, _ = Library.objects.get_or_create( name=library_name, ) library_path, _ = LibraryPath.objects.get_or_create( library=library, type='St', backend_type='Lo', path=path, ) library_user, _ = LibraryUser.objects.get_or_create( library=library, user=user, owner=True, ) print(f'Library "{library_name}" with path "{path}" created successfully for user "{username}"') def add_arguments(self, parser): # Positional arguments parser.add_argument('username', type=str) parser.add_argument('library_name', type=str) parser.add_argument('--path', type=str, default='/data/photos') def handle(self, *args, **options): self.create_library(options['username'], options['library_name'], options['path'])
import os from pathlib import Path from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from django.db.utils import IntegrityError from photonix.photos.models import Library, LibraryPath, LibraryUser from photonix.photos.utils.db import record_photo from photonix.photos.utils.fs import determine_destination, download_file User = get_user_model() class Command(BaseCommand): help = 'Create a library for a user' def create_library(self, username, library_name): # Get user user = User.objects.get(username=username) # Create Library library, _ = Library.objects.get_or_create( name=library_name, ) library_path, _ = LibraryPath.objects.get_or_create( library=library, type='St', backend_type='Lo', path='/data/photos/', url='/photos/', ) library_user, _ = LibraryUser.objects.get_or_create( library=library, user=user, owner=True, ) print(f'Library "{library_name}" created successfully for user "{username}"') def add_arguments(self, parser): # Positional arguments parser.add_argument('username', nargs='+', type=str) parser.add_argument('library_name', nargs='+', type=str) def handle(self, *args, **options): self.create_library(options['username'][0], options['library_name'][0])
Improve jQuery object iteration; remove unused deconstructed property
import Component from 'ember-forge-ui/components/ef-list'; import Ember from 'ember'; const { get } = Ember; /** * @module * @augments ember-forge-ui/components/ef-list */ export default Component.extend({ // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- // Attributes // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- // Events /** * init event hook * * Configure the list * * @function * @returns {undefined} */ init() { this._super(...arguments); }, /** * didInsertElement event hook * * Apply correct styling to list * * @returns {undefined} */ didInsertElement() { this._super(...arguments); this.styleList(); }, // ------------------------------------------------------------------------- // Properties // ------------------------------------------------------------------------- // Observers // ------------------------------------------------------------------------- // Methods /** * Apply/remove class names dependent on whether an ordered list * * @private * @override * @returns {undefined} */ setListType() { this._super(...arguments); if(get(this, 'ordered')) { get(this, 'classNames').removeObject('list-group'); } else { get(this, 'classNames').addObject('list-group'); } }, /** * Apply/remove class names dependent on whether an ordered list * * @private * @returns {undefined} */ styleList() { if(get(this, 'ordered')) { this.$('.list-group-item').removeClass('list-group-item'); } } });
import Component from 'ember-forge-ui/components/ef-list'; import Ember from 'ember'; const { computed, get } = Ember; /** * @module * @augments ember-forge-ui/components/ef-list */ export default Component.extend({ // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- // Attributes // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- // Events /** * init event hook * * Configure the list * * @function * @returns {undefined} */ init() { this._super(...arguments); }, /** * didInsertElement event hook * * Apply correct styling to list * * @returns {undefined} */ didInsertElement() { this._super(...arguments); this.styleList(); }, // ------------------------------------------------------------------------- // Properties // ------------------------------------------------------------------------- // Observers // ------------------------------------------------------------------------- // Methods /** * Apply/remove class names dependent on whether an ordered list * * @private * @override * @returns {undefined} */ setListType() { this._super(...arguments); if(get(this, 'ordered')) { get(this, 'classNames').removeObject('list-group'); } else { get(this, 'classNames').addObject('list-group'); } }, /** * Apply/remove class names dependent on whether an ordered list * * @private * @returns {undefined} */ styleList() { if(get(this, 'ordered')) { this.$('.list-group-item').each(function() { $(this).removeClass('list-group-item'); }); } } });
Resolve includeDir relative to the project context
var Async = require('async'), Fs = require('fs'), Glob = require('glob'), Path = require('path'), RawSource = require('webpack-core/lib/RawSource'); module.exports = function(options) { this.options = options; }; module.exports.prototype.apply = function(compiler) { var options = this.options; compiler.plugin('compilation', function(compilation) { compilation.plugin('additional-assets', function(callback) { // Copy over any include files to the build output target var includesDir = options.includesDir || './src/client/styles/includes/**/*.styl'; includesDir = Path.resolve(compiler.options.context, includesDir); Glob.glob(includesDir, function(err, files) { if (err) { return callback(err); } Async.forEach(files, function(file, callback) { Fs.readFile(file, function(err, data) { if (err) { // If the file suddenly disappeared, then the error should be fatal as this // is unexpected, being previously returned from the glob API. return callback(err); } file = Path.relative(compiler.options.context, file); compilation.assets[options.remap ? options.remap(file) : file] = new RawSource(data); callback(); }); }, callback); }); }); }); };
var Async = require('async'), Fs = require('fs'), Glob = require('glob'), Path = require('path'), RawSource = require('webpack-core/lib/RawSource'); module.exports = function(options) { this.options = options; }; module.exports.prototype.apply = function(compiler) { var options = this.options; compiler.plugin('compilation', function(compilation) { compilation.plugin('additional-assets', function(callback) { // Copy over any include files to the build output target Glob.glob(options.includesDir || './src/client/styles/includes/**/*.styl', function(err, files) { if (err) { return callback(err); } Async.forEach(files, function(file, callback) { Fs.readFile(file, function(err, data) { if (err) { // If the file suddenly disappeared, then the error should be fatal as this // is unexpected, being previously returned from the glob API. return callback(err); } file = Path.relative(compiler.options.context, file); compilation.assets[options.remap ? options.remap(file) : file] = new RawSource(data); callback(); }); }, callback); }); }); }); };
Fix a bug on business model
<?php /* * This file is part of the Antvel Shop package. * * (c) Gustavo Ocanto <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Antvel\User\Models; use Antvel\Antvel; use Illuminate\Database\Eloquent\Model; class Business extends Model { /** * The database table. * * @var string */ protected $table = 'businesses'; /** * Avoiding timestamps. * * @var boolean */ public $timestamps = false; /** * The table primary key. * * @var string */ public $primaryKey = 'user_id'; /** * The auto-increment controller. * * @var boolean */ public $incrementing = false; /** * Mass assignable attributes. * * @var array */ protected $fillable = ['user_id', 'business_name', 'local_phone', 'creation_date']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['user_id']; /** * Returns the business user. * * @return Illuminate\Database\Eloquent\Relations\Relation */ public function user() { return $this->belongsTo(Antvel::user()); } /** * Returns the user full name. * * @return string */ public function getFullNameAttribute() { return ucwords($this->business_name); } }
<?php /* * This file is part of the Antvel Shop package. * * (c) Gustavo Ocanto <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Antvel\User\Models; use Antvel\Antvel; use Illuminate\Database\Eloquent\Model; class Business extends Model { /** * The database table. * * @var string */ protected $table = 'businesses'; /** * Avoiding timestamps. * * @var boolean */ public $timestamps = false; /** * The table primary key. * * @var string */ public $primaryKey = 'user_id'; /** * The auto-increment controller. * * @var boolean */ public $incrementing = false; /** * Mass assignable attributes. * * @var array */ protected $fillable = ['user_id', 'business_name', 'local_phone', 'creation_date']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['user_id']; /** * Returns the business user. * * @return Illuminate\Database\Eloquent\Relations\Relation */ public function user() { return $this->belongsTo(Antvel::user()); } /** * Returns the user full name. * * @return string */ public function getFullNameAttribute() { return ucwords($this->profile->business_name); } }
Fix closing tag in genericWidget directive
(function() { 'use strict'; angular.module('app.widgets', [ 'app.services', 'rzModule', 'web.colorpicker' ]) .value('WidgetTypes', []) .factory('Widgets', WidgetsService) .directive('genericWidget', GenericWidgetDirective); WidgetsService.$inject = ['WidgetTypes']; function WidgetsService(widgetTypes) { var service = { registerType: registerType, getWidgetTypes: getWidgetTypes } return service; //////////////// function registerType(name) { widgetTypes.push(name); console.log("Registered widget type: " + name); } function getWidgetTypes() { return widgetTypes; } } GenericWidgetDirective.$inject = ['$compile', 'Widgets']; function GenericWidgetDirective($compile, widgets) { var directive = { restrict: 'AE', replace: true, scope: { type: '=', ngModel: '=' }, link: function (scope, element, attrs) { element.html('<widget-' + scope.type + ' ng-model="ngModel"></widget-' + scope.type + '>'); $compile(element.contents())(scope); } } return directive; } })();
(function() { 'use strict'; angular.module('app.widgets', [ 'app.services', 'rzModule', 'web.colorpicker' ]) .value('WidgetTypes', []) .factory('Widgets', WidgetsService) .directive('genericWidget', GenericWidgetDirective); WidgetsService.$inject = ['WidgetTypes']; function WidgetsService(widgetTypes) { var service = { registerType: registerType, getWidgetTypes: getWidgetTypes } return service; //////////////// function registerType(name) { widgetTypes.push(name); console.log("Registered widget type: " + name); } function getWidgetTypes() { return widgetTypes; } } GenericWidgetDirective.$inject = ['$compile', 'Widgets']; function GenericWidgetDirective($compile, widgets) { var directive = { restrict: 'AE', replace: true, scope: { type: '=', ngModel: '=' }, link: function (scope, element, attrs) { element.html('<widget-' + scope.type + ' ng-model="ngModel"><widget-' + scope.type + '>'); $compile(element.contents())(scope); } } return directive; } })();
Fix blocks and use ViewData
<?php namespace Enhavo\Bundle\ShopBundle\Block; use Enhavo\Bundle\AppBundle\View\ViewData; use Enhavo\Bundle\BlockBundle\Model\BlockInterface; use Enhavo\Bundle\ShopBundle\Entity\ProductListBlock; use Enhavo\Bundle\ShopBundle\Factory\ProductListBlockFactory; use Enhavo\Bundle\ShopBundle\Form\Type\ProductListBlockType as ProductListBlockFormType; use Enhavo\Bundle\BlockBundle\Block\AbstractBlockType; use Symfony\Component\OptionsResolver\OptionsResolver; class ProductListBlockType extends AbstractBlockType { public function createViewData(BlockInterface $block, ViewData $viewData, $resource, array $options) { $viewData['products'] = $this->container->get('sylius.repository.product')->findAll(); } public function configureOptions(OptionsResolver $optionsResolver) { parent::configureOptions($optionsResolver); $optionsResolver->setDefaults([ 'model' => ProductListBlock::class, 'parent' => ProductListBlock::class, 'form' => ProductListBlockFormType::class, 'factory' => ProductListBlockFactory::class, 'repository' => 'ProductListBlock::class', 'template' => 'theme/block/product-list.html.twig', 'label' => 'ProductList', 'translation_domain' => 'EnhavoShopBundle', 'groups' => ['default', 'content'] ]); } public function getType() { return 'shop_product_list'; } }
<?php namespace Enhavo\Bundle\ShopBundle\Block; use Enhavo\Bundle\BlockBundle\Model\BlockInterface; use Enhavo\Bundle\ShopBundle\Entity\ProductListBlock; use Enhavo\Bundle\ShopBundle\Factory\ProductListBlockFactory; use Enhavo\Bundle\ShopBundle\Form\Type\ProductListBlockType as ProductListBlockFormType; use Enhavo\Bundle\BlockBundle\Block\AbstractBlockType; use Symfony\Component\OptionsResolver\OptionsResolver; class ProductListBlockType extends AbstractBlockType { public function createViewData(BlockInterface $block, $resource, array $options) { $data = parent::createViewData($block, $resource, $options); $data['products'] = $this->container->get('sylius.repository.product')->findAll(); return $data; } public function configureOptions(OptionsResolver $optionsResolver) { parent::configureOptions($optionsResolver); $optionsResolver->setDefaults([ 'model' => ProductListBlock::class, 'parent' => ProductListBlock::class, 'form' => ProductListBlockFormType::class, 'factory' => ProductListBlockFactory::class, 'repository' => 'ProductListBlock::class', 'template' => 'theme/block/product-list.html.twig', 'label' => 'ProductList', 'translation_domain' => 'EnhavoShopBundle', 'groups' => ['default', 'content'] ]); } public function getType() { return 'shop_product_list'; } }
Add keywords and update package name
#!/usr/bin/env python # -*- coding: utf-8 -*- # # License: MIT # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: """ django twitter bootstrap form setup script """ __author__ = "Guillaume Luchet <[email protected]>" __version__ = "0.1" import sys from setuptools import setup, find_packages author_data = __author__.split(" ") maintainer = " ".join(author_data[0:-1]) maintainer_email = author_data[-1] long_desc = open('README.md').read() if __name__ == "__main__": setup( name="django-twitterbootstrap-form", version=__version__, description="Render Django forms as described using the twitter bootstrap HTML layout", long_description=long_desc, author=maintainer, author_email=maintainer_email, maintainer=maintainer, maintainer_email=maintainer_email, url="https://github.com/geelweb/django-twitter-bootstrap-form", download_url="https://github.com/geelweb/django-twitter-bootstrap-form/tarball/0.1", license='MIT', namespace_packages = ['geelweb', 'geelweb.django'], packages=find_packages('src'), package_dir = {'':'src'}, package_data = { 'geelweb.django.twitter_bootstrap_form': [ 'templates/twitter_bootstrap_form/*.html', ], }, keywords = ['django', 'twitter', 'bootstrap', 'form'], )
#!/usr/bin/env python # -*- coding: utf-8 -*- # # License: MIT # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: """ django twitter bootstrap form setup script """ __author__ = "Guillaume Luchet <[email protected]>" __version__ = "0.1" import sys from setuptools import setup, find_packages author_data = __author__.split(" ") maintainer = " ".join(author_data[0:-1]) maintainer_email = author_data[-1] long_desc = open('README.md').read() if __name__ == "__main__": setup( name="django twitter bootstrap form", version=__version__, description="Render Django forms as described using the twitter bootstrap HTML layout", long_description=long_desc, author=maintainer, author_email=maintainer_email, maintainer=maintainer, maintainer_email=maintainer_email, url="https://github.com/geelweb/django-twitter-bootstrap-form", license='MIT', namespace_packages = ['geelweb', 'geelweb.django'], packages=find_packages('src'), package_dir = {'':'src'}, package_data = { 'geelweb.django.twitter_bootstrap_form': [ 'templates/twitter_bootstrap_form/*.html', ], }, zip_safe=False )
Add a line between outputs.
#! /usr/bin/env python from __future__ import print_function import os import sys import json def pretty_print(equation): print(equation["description"]["terse"]) eqn_dict = equation["unicode-pretty-print"] equation_text = eqn_dict["multiline"] for line in equation_text: print(line) if "parameters" in eqn_dict: print("where:") for param, param_dict in eqn_dict["parameters"].iteritems(): label = param_dict["label"] print(param,'=',label) def main(query): here = sys.path[0] json_dir = os.path.join(here, 'equajson') for filename in os.listdir(json_dir): if not filename.endswith('.json'): continue filepath = os.path.join(json_dir, filename) with open(filepath) as json_file: try: equation = json.load(json_file) except ValueError: sys.stderr.write("Invalid JSON for file: `{}'\n".format(json_file.name)) continue # try the next file description = equation["description"]["verbose"] if query.lower() in description.lower(): pretty_print(equation) print() if __name__ == '__main__': num_args = len(sys.argv) - 1 if num_args != 1: sys.stderr.write("Usage: python "+sys.argv[0]+" query"+'\n') sys.exit(1) main(sys.argv[1])
#! /usr/bin/env python from __future__ import print_function import os import sys import json def pretty_print(equation): print(equation["description"]["terse"]) eqn_dict = equation["unicode-pretty-print"] equation_text = eqn_dict["multiline"] for line in equation_text: print(line) if "parameters" in eqn_dict: print("where:") for param, param_dict in eqn_dict["parameters"].iteritems(): label = param_dict["label"] print(param,'=',label) def main(query): here = sys.path[0] json_dir = os.path.join(here, 'equajson') for filename in os.listdir(json_dir): if not filename.endswith('.json'): continue filepath = os.path.join(json_dir, filename) with open(filepath) as json_file: try: equation = json.load(json_file) except ValueError: sys.stderr.write("Invalid JSON for file: `{}'\n".format(json_file.name)) continue # try the next file description = equation["description"]["verbose"] if query.lower() in description.lower(): pretty_print(equation) if __name__ == '__main__': num_args = len(sys.argv) - 1 if num_args != 1: sys.stderr.write("Usage: python "+sys.argv[0]+" query"+'\n') sys.exit(1) main(sys.argv[1])
Add correct margin to x-axis
(function(d3, fc, sc) { 'use strict'; sc.chart.xAxis = function() { var xAxisHeight = 23; var yAxisWidth = 60; var xScale = fc.scale.dateTime(); var xAxis = d3.svg.axis() .scale(xScale) .orient('bottom'); var dataJoin = fc.util.dataJoin() .selector('g.x-axis') .element('g') .attr('class', 'x-axis'); function preventTicksMoreFrequentThanPeriod(period) { var scaleTickSeconds = (xScale.ticks()[1] - xScale.ticks()[0]) / 1000; if (scaleTickSeconds < period.seconds) { xAxis.ticks(period.d3TimeInterval.unit, period.d3TimeInterval.value); } else { xAxis.ticks(6); } } function xAxisChart(selection) { selection.each(function(model) { var container = d3.select(this); var xAxisContainer = dataJoin(container, [model]) .layout({ position: 'absolute', left: 0, bottom: 0, right: yAxisWidth, height: xAxisHeight }); container.layout(); xScale.range([0, xAxisContainer.layout('width')]) .domain(model.viewDomain); preventTicksMoreFrequentThanPeriod(model.period); xAxisContainer.call(xAxis); }); } return xAxisChart; }; })(d3, fc, sc);
(function(d3, fc, sc) { 'use strict'; sc.chart.xAxis = function() { var xAxisHeight = 23; var xScale = fc.scale.dateTime(); var xAxis = d3.svg.axis() .scale(xScale) .orient('bottom'); var dataJoin = fc.util.dataJoin() .selector('g.x-axis') .element('g') .attr('class', 'x-axis'); function preventTicksMoreFrequentThanPeriod(period) { var scaleTickSeconds = (xScale.ticks()[1] - xScale.ticks()[0]) / 1000; if (scaleTickSeconds < period.seconds) { xAxis.ticks(period.d3TimeInterval.unit, period.d3TimeInterval.value); } else { xAxis.ticks(6); } } function xAxisChart(selection) { selection.each(function(model) { var container = d3.select(this); var xAxisContainer = dataJoin(container, [model]) .layout({ position: 'absolute', left: 0, bottom: 0, right: 0, height: xAxisHeight }); container.layout(); xScale.range([0, xAxisContainer.layout('width')]) .domain(model.viewDomain); preventTicksMoreFrequentThanPeriod(model.period); xAxisContainer.call(xAxis); }); } return xAxisChart; }; })(d3, fc, sc);
Add error message if there is one
<?php namespace fennecweb\ajax\upload; use \PDO as PDO; /** * Web Service. * Uploads Project biom files and save them in the database */ class Project extends \fennecweb\WebService { /** * @param $querydata[] * @returns result of file upload */ public function execute($querydata) { $db = $this->openDbConnection($querydata); $files = array(); for ($i=0; $i<sizeof($_FILES['files']['tmp_names']); $i++) { $valid = $this->validateFile($_FILES['files']['tmp_names'][$i]); $file = array( "name" => $_FILES['files']['names'][$i], "size" => $_FILES['files']['sizes'][$i], "error" => ($valid === true ? null : $valid) ); $files[] = $file; } return array("files" => $files); } /** * Function that checks the uploaded file for validity * @param String $filename the uploaded file to check * @returns Either TRUE if the file is valid or a String containing the error message */ protected function validateFile($filename) { if (!is_uploaded_file($filename)) { return "Error. There was an error in your request."; } } }
<?php namespace fennecweb\ajax\upload; use \PDO as PDO; /** * Web Service. * Uploads Project biom files and save them in the database */ class Project extends \fennecweb\WebService { /** * @param $querydata[] * @returns result of file upload */ public function execute($querydata) { $db = $this->openDbConnection($querydata); $files = array(); for ($i=0; $i<sizeof($_FILES['files']['tmp_names']); $i++) { $valid = $this->validateFile($_FILES['files']['tmp_names'][$i]); $file = array( "name" => $_FILES['files']['names'][$i], "size" => $_FILES['files']['sizes'][$i], "error" => null ); $files[] = $file; } return array("files" => $files); } /** * Function that checks the uploaded file for validity * @param String $filename the uploaded file to check * @returns Either TRUE if the file is valid or a String containing the error message */ protected function validateFile($filename) { if (!is_uploaded_file($filename)) { return "Error. There was an error in your request."; } } }
Remove unneeded console logs, improve messaging to player.
'use strict'; const CommandUtil = require('../src/command_util').CommandUtil; const l10nFile = __dirname + '/../l10n/commands/kill.yml'; const _ = require('../src/helpers'); const l10n = require('../src/l10n')(l10nFile); const util = require('util'); exports.command = (rooms, items, players, npcs, Commands) => { return (args, player) => { const room = rooms.getAt(player.getLocation()); const npc = CommandUtil.findNpcInRoom(npcs, args, room, player, true); if (!npc) { return player.warn(`Kill ${args}? If you can find them, maybe.`); } if (npc.isPacifist()) { return player.warn(`${npc.getShortDesc()} radiates a calming aura.`); } if (!player.hasEnergy(5)) { return player.noEnergy(); } util.log(player.getName() + ' is on the offensive...'); const fightingPlayer = _.has(npc.getInCombat(), player); if (fightingPlayer) { return player.say(`You are already fighting that ${npc.getShortDesc()}!`); } else if (npc.isInCombat()) { return player.say('That ${npc.getShortDesc()} is busy fighting someone else, no fair!'); } npc.emit('combat', player, room, players, npcs, rooms, cleanup); function cleanup(success) { // cleanup here... } }; };
'use strict'; const CommandUtil = require('../src/command_util').CommandUtil; const l10nFile = __dirname + '/../l10n/commands/kill.yml'; const _ = require('../src/helpers'); const l10n = require('../src/l10n')(l10nFile); const util = require('util'); exports.command = (rooms, items, players, npcs, Commands) => { return (args, player) => { const room = rooms.getAt(player.getLocation()); const npc = CommandUtil.findNpcInRoom(npcs, args, room, player, true); if (!npc) { return player.warn(`Kill ${args}? If you can find them, maybe.`); } if (!npc.isPacifist) { console.log('fucked up ', npc); } if (npc.isPacifist()) { return player.warn(`${npc.getShortDesc()} radiates a calming aura.`); } if (!player.hasEnergy(5)) { return player.noEnergy(); } util.log(player.getName() + ' is on the offensive...'); const fightingPlayer = _.has(npc.getInCombat(), player); if (fightingPlayer) { player.say('You are already fighting them!'); return; } else if (npc.isInCombat()) { player.say('They are busy fighting someone else, no fair!'); return; } npc.emit('combat', player, room, players, npcs, rooms, cleanup); function cleanup(success) { // cleanup here... } }; };
Fix for the failing notfns on Oracle
package edu.duke.cabig.c3pr.dao; import java.util.List; import org.springframework.transaction.annotation.Transactional; import edu.duke.cabig.c3pr.domain.PlannedNotification; import edu.duke.cabig.c3pr.domain.RecipientScheduledNotification; /** * Hibernate implementation of ArmDao * * @see edu.duke.cabig.c3pr.dao.RecipientScheduledNotificationDao * @author Priyatam */ public class RecipientScheduledNotificationDao extends GridIdentifiableDao<RecipientScheduledNotification> { @Override public Class<RecipientScheduledNotification> domainClass() { return RecipientScheduledNotification.class; } /* * Returns all Arm objects (non-Javadoc) * * @see edu.duke.cabig.c3pr.dao.Arm#getAll() */ @Transactional(readOnly=true) public List<RecipientScheduledNotification> getAll() { return getHibernateTemplate().find("from RecipientScheduledNotification"); } //readOnly was chnaged from true to false to get notifications to work on ORacle @Transactional(readOnly=false) public RecipientScheduledNotification getInitializedRecipientScheduledNotificationById(int id){ RecipientScheduledNotification recipientScheduledNotification = getById(id); return recipientScheduledNotification; } @Transactional(readOnly=false) public void saveOrUpdate(RecipientScheduledNotification recipientScheduledNotification){ //do not remove the flush...imperative for the notifications flow. getHibernateTemplate().saveOrUpdate(recipientScheduledNotification); getHibernateTemplate().flush(); } }
package edu.duke.cabig.c3pr.dao; import java.util.List; import org.springframework.transaction.annotation.Transactional; import edu.duke.cabig.c3pr.domain.PlannedNotification; import edu.duke.cabig.c3pr.domain.RecipientScheduledNotification; /** * Hibernate implementation of ArmDao * * @see edu.duke.cabig.c3pr.dao.RecipientScheduledNotificationDao * @author Priyatam */ public class RecipientScheduledNotificationDao extends GridIdentifiableDao<RecipientScheduledNotification> { @Override public Class<RecipientScheduledNotification> domainClass() { return RecipientScheduledNotification.class; } /* * Returns all Arm objects (non-Javadoc) * * @see edu.duke.cabig.c3pr.dao.Arm#getAll() */ @Transactional(readOnly=true) public List<RecipientScheduledNotification> getAll() { return getHibernateTemplate().find("from RecipientScheduledNotification"); } @Transactional(readOnly=true) public RecipientScheduledNotification getInitializedRecipientScheduledNotificationById(int id){ RecipientScheduledNotification recipientScheduledNotification = getById(id); return recipientScheduledNotification; } @Transactional(readOnly=false) public void saveOrUpdate(RecipientScheduledNotification recipientScheduledNotification){ //do not remove the flush...imperative for the notifications flow. getHibernateTemplate().saveOrUpdate(recipientScheduledNotification); getHibernateTemplate().flush(); } }
Remove some more ST2 specific code
from __future__ import absolute_import import sublime import traceback from markdown import Markdown, util from markdown.extensions import Extension import importlib class StMarkdown(Markdown): def __init__(self, *args, **kwargs): Markdown.__init__(self, *args, **kwargs) self.Meta = {} def registerExtensions(self, extensions, configs): """ Register extensions with this instance of Markdown. Keyword arguments: * extensions: A list of extensions, which can either be strings or objects. See the docstring on Markdown. * configs: A dictionary mapping module names to config options. """ for ext in extensions: try: if isinstance(ext, util.string_type): ext = self.build_extension(ext, configs.get(ext, [])) if isinstance(ext, Extension): ext.extendMarkdown(self, globals()) elif ext is not None: raise TypeError( 'Extension "%s.%s" must be of type: "markdown.Extension"' % (ext.__class__.__module__, ext.__class__.__name__)) except: print(str(traceback.format_exc())) continue return self
from __future__ import absolute_import import sublime import traceback ST3 = int(sublime.version()) >= 3000 if ST3: from markdown import Markdown, util from markdown.extensions import Extension import importlib else: from markdown import Markdown, util from markdown.extensions import Extension class StMarkdown(Markdown): def __init__(self, *args, **kwargs): Markdown.__init__(self, *args, **kwargs) self.Meta = {} def registerExtensions(self, extensions, configs): """ Register extensions with this instance of Markdown. Keyword arguments: * extensions: A list of extensions, which can either be strings or objects. See the docstring on Markdown. * configs: A dictionary mapping module names to config options. """ for ext in extensions: try: if isinstance(ext, util.string_type): ext = self.build_extension(ext, configs.get(ext, [])) if isinstance(ext, Extension): ext.extendMarkdown(self, globals()) elif ext is not None: raise TypeError( 'Extension "%s.%s" must be of type: "markdown.Extension"' % (ext.__class__.__module__, ext.__class__.__name__)) except: print(str(traceback.format_exc())) continue return self
Update to use token instead of email+pass
import discord import asyncio from tqdm import tqdm import argparse parser = argparse.ArgumentParser(description='Discord channel scraper') requiredNamed = parser.add_argument_group('Required arguments:') requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.', required=True) requiredNamed.add_argument('-o', '--output', type=str, help='Output file in form *.txt. Will be stored in the same directory.', required=True) args = parser.parse_args() client = discord.Client() @client.event async def on_ready(): print('Connection successful.') print('Your ID: ' + client.user.id) target = open(args.output, 'w') print(args.output, 'has been opened.') messageCount = 0 channel = discord.Object(id=args.channel) print("Scraping messages... Don't send any messages while scraping!") with tqdm(leave=True,unit=' messages') as scraped: async for msg in client.logs_from(channel, 10000000000): line = "{} - {} - {}".format(msg.timestamp,msg.author.name, msg.content) line = line.encode('utf-8') toWrite = "{}".format(line) target.write(toWrite) target.write("\n") messageCount += 1 scraped.update(1) print('-----') print('Scraping complete.') #---------------------------- client.run(usertoken,bot=False)
import discord import asyncio from tqdm import tqdm import argparse parser = argparse.ArgumentParser(description='Discord channel scraper') requiredNamed = parser.add_argument_group('Required arguments:') requiredNamed.add_argument('-c', '--channel', type=str, help='Channel to scrape. Requires the channel ID.', required=True) requiredNamed.add_argument('-o', '--output', type=str, help='Output file in form *.txt. Will be stored in the same directory.', required=True) args = parser.parse_args() client = discord.Client() @client.event async def on_ready(): print('Connection successful.') print('Your ID: ' + client.user.id) target = open(args.output, 'w') print(args.output, 'has been opened.') messageCount = 0 channel = discord.Object(id=args.channel) print("Scraping messages... Don't send any messages while scraping!") with tqdm(leave=True,unit=' messages') as scraped: async for msg in client.logs_from(channel, 10000000000): line = "{} - {} - {}".format(msg.timestamp,msg.author.name, msg.content) line = line.encode('utf-8') toWrite = "{}".format(line) target.write(toWrite) target.write("\n") messageCount += 1 scraped.update(1) print('-----') print('Scraping complete.') #---------------------------- client.run('email', 'password')
Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5402 d6536bca-fef9-0310-8506-e4c0a848fbcf
from numpy import * from numpy.testing import * from scipy.weave import inline_tools class TestInline(TestCase): """ These are long running tests... I'd like to benchmark these things somehow. """ @dec.slow def test_exceptions(self): a = 3 code = """ if (a < 2) throw_error(PyExc_ValueError, "the variable 'a' should not be less than 2"); else return_val = PyInt_FromLong(a+1); """ result = inline_tools.inline(code,['a']) assert(result == 4) ## Unfortunately, it is not always possible to catch distutils compiler ## errors, since SystemExit is used. Until that is fixed, these tests ## cannot be run in the same process as the test suite. ## try: ## a = 1 ## result = inline_tools.inline(code,['a']) ## assert(1) # should've thrown a ValueError ## except ValueError: ## pass ## from distutils.errors import DistutilsError, CompileError ## try: ## a = 'string' ## result = inline_tools.inline(code,['a']) ## assert(1) # should've gotten an error ## except: ## # ?CompileError is the error reported, but catching it doesn't work ## pass if __name__ == "__main__": nose.run(argv=['', __file__])
from numpy import * from numpy.testing import * from scipy.weave import inline_tools class TestInline(TestCase): """ These are long running tests... I'd like to benchmark these things somehow. """ @dec.slow def test_exceptions(self): a = 3 code = """ if (a < 2) throw_error(PyExc_ValueError, "the variable 'a' should not be less than 2"); else return_val = PyInt_FromLong(a+1); """ result = inline_tools.inline(code,['a']) assert(result == 4) try: a = 1 result = inline_tools.inline(code,['a']) assert(1) # should've thrown a ValueError except ValueError: pass from distutils.errors import DistutilsError, CompileError try: a = 'string' result = inline_tools.inline(code,['a']) assert(1) # should've gotten an error except: # ?CompileError is the error reported, but catching it doesn't work pass if __name__ == "__main__": nose.run(argv=['', __file__])
Remove a debugging flush() after every trace
# Copyright (C) 2010 Peter Teichman import datetime import math import os import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = None def init(self, filename): if self._fd is not None: self._fd.close() if filename is None: self._fd = None else: # rotate logs if os.path.exists(filename): now = datetime.datetime.now() stamp = now.strftime("%Y-%m-%d.%H%M%S") os.rename(filename, "%s.%s" % (filename, stamp)) self._fd = open(filename, "w") def is_enabled(self): return self._fd is not None def now(self): """Microsecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*100000) def now_ms(self): """Millisecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*1000) def trace(self, statName, statValue, userData=None): if not self.is_enabled(): return extra = "" if userData is not None: extra = " " + repr(userData) self._fd.write("%s %d%s\n" % (statName, statValue, extra))
# Copyright (C) 2010 Peter Teichman import datetime import math import os import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = None def init(self, filename): if self._fd is not None: self._fd.close() if filename is None: self._fd = None else: # rotate logs if os.path.exists(filename): now = datetime.datetime.now() stamp = now.strftime("%Y-%m-%d.%H%M%S") os.rename(filename, "%s.%s" % (filename, stamp)) self._fd = open(filename, "w") def is_enabled(self): return self._fd is not None def now(self): """Microsecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*100000) def now_ms(self): """Millisecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*1000) def trace(self, statName, statValue, userData=None): if not self.is_enabled(): return extra = "" if userData is not None: extra = " " + repr(userData) self._fd.write("%s %d%s\n" % (statName, statValue, extra)) self._fd.flush()
Add "file_exists" check for the CI.
<?php declare(strict_types=1); namespace App\Sync\Task; use App\Doctrine\ReloadableEntityManagerInterface; use App\Entity\Repository\SettingsRepository; use App\Radio\Adapters; use App\Radio\CertificateLocator; use Psr\Log\LoggerInterface; class ReloadFrontendAfterSslChangeTask extends AbstractTask { public function __construct( protected Adapters $adapters, protected SettingsRepository $settingsRepo, ReloadableEntityManagerInterface $em, LoggerInterface $logger ) { parent::__construct($em, $logger); } public function run(bool $force = false): void { $threshold = $this->settingsRepo->readSettings()->getSyncLongLastRun(); $certs = CertificateLocator::findCertificate(); $pathsToCheck = [ $certs->getCertPath(), $certs->getKeyPath(), ]; $certsUpdated = false; foreach ($pathsToCheck as $path) { if (file_exists($path) && filemtime($path) > $threshold) { $certsUpdated = true; break; } } if ($certsUpdated) { $this->logger->info('SSL certificates have updated; hot-reloading stations that support it.'); foreach ($this->iterateStations() as $station) { $frontend = $this->adapters->getFrontendAdapter($station); if ($frontend->supportsReload()) { $frontend->reload($station); } } } else { $this->logger->info('SSL certificates have not updated.'); } } }
<?php declare(strict_types=1); namespace App\Sync\Task; use App\Doctrine\ReloadableEntityManagerInterface; use App\Entity\Repository\SettingsRepository; use App\Radio\Adapters; use App\Radio\CertificateLocator; use Psr\Log\LoggerInterface; class ReloadFrontendAfterSslChangeTask extends AbstractTask { public function __construct( protected Adapters $adapters, protected SettingsRepository $settingsRepo, ReloadableEntityManagerInterface $em, LoggerInterface $logger ) { parent::__construct($em, $logger); } public function run(bool $force = false): void { $threshold = $this->settingsRepo->readSettings()->getSyncLongLastRun(); $certs = CertificateLocator::findCertificate(); $pathsToCheck = [ $certs->getCertPath(), $certs->getKeyPath(), ]; $certsUpdated = false; foreach ($pathsToCheck as $path) { if (filemtime($path) > $threshold) { $certsUpdated = true; break; } } if ($certsUpdated) { $this->logger->info('SSL certificates have updated; hot-reloading stations that support it.'); foreach ($this->iterateStations() as $station) { $frontend = $this->adapters->getFrontendAdapter($station); if ($frontend->supportsReload()) { $frontend->reload($station); } } } else { $this->logger->info('SSL certificates have not updated.'); } } }
Make agents able to see each other.
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import agent import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, agent.Agent): return "a%s" % delta elif isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta elif isinstance(entity, structure.Food): return "f%s" % delta return ""
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta elif isinstance(entity, structure.Food): return "f%s" % delta return ""
Change is checked when either condition or watch changes
var Gaffa = require('gaffa'); function change(behaviour){ var gaffa = behaviour.gaffa; if(!behaviour.condition.value){ return; } var throttleTime = behaviour.throttle; if(!isNaN(throttleTime)){ var now = new Date(); if(!behaviour.lastTrigger || now - behaviour.lastTrigger > throttleTime){ behaviour.lastTrigger = now; behaviour.triggerActions('change'); }else{ clearTimeout(behaviour.timeout); behaviour.timeout = setTimeout(function(){ behaviour.lastTrigger = now; behaviour.triggerActions('change'); }, throttleTime - (now - behaviour.lastTrigger) ); } }else{ behaviour.triggerActions('change'); } } } function ModelChangeBehaviour(){} ModelChangeBehaviour = Gaffa.createSpec(ModelChangeBehaviour, Gaffa.Behaviour); ModelChangeBehaviour.prototype._type = 'modelChange'; ModelChangeBehaviour.prototype.condition = new Gaffa.Property({ update: change, value: true }); ModelChangeBehaviour.prototype.watch = new Gaffa.Property(change); module.exports = ModelChangeBehaviour;
var Gaffa = require('gaffa'); function executeBehaviour(behaviour, value){ behaviour.gaffa.actions.trigger(behaviour.actions.change, behaviour); } function ModelChangeBehaviour(){} ModelChangeBehaviour = Gaffa.createSpec(ModelChangeBehaviour, Gaffa.Behaviour); ModelChangeBehaviour.prototype._type = 'modelChange'; ModelChangeBehaviour.prototype.condition = new Gaffa.Property({value: true}); ModelChangeBehaviour.prototype.watch = new Gaffa.Property({ update: function(behaviour, value){ var gaffa = behaviour.gaffa; if(!behaviour.condition.value){ return; } var throttleTime = behaviour.throttle; if(!isNaN(throttleTime)){ var now = new Date(); if(!behaviour.lastTrigger || now - behaviour.lastTrigger > throttleTime){ behaviour.lastTrigger = now; executeBehaviour(behaviour, value); }else{ clearTimeout(behaviour.timeout); behaviour.timeout = setTimeout(function(){ behaviour.lastTrigger = now; executeBehaviour(behaviour, value); }, throttleTime - (now - behaviour.lastTrigger) ); } }else{ executeBehaviour(behaviour, value); } } }); module.exports = ModelChangeBehaviour;
Sort to get determinist ordering
var request = require('supertest'); var assert = require('assert'); var storageFactory = require('../lib/storage/storage-factory'); var storage = storageFactory.getStorageInstance('test'); var app = require('../webserver/app')(storage); describe('ping plugins route', function () { var server; var PORT = 3355; var API_ROOT = '/api/plugins'; var agent = request.agent(app); before(function (done) { server = app.listen(PORT, function () { if (server.address()) { console.log('starting server in port ' + PORT); done(); } else { console.log('something went wrong... couldn\'t listen to that port.'); process.exit(1); } }); }); after(function () { server.close(); }); describe('plugin list', function () { describe('with an anonymous user ', function () { it('should return list of plugins', function (done) { agent .get(API_ROOT + '/') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .send() .end(function (err, res) { assert.equal(res.body.length, 2); var plugins = res.body.sort(function(a, b){ return a.name > b.name; }); assert.equal(plugins[0].name, 'http-contains'); assert.equal(plugins[1].name, 'http-head'); done(err); }); }); }); }); });
var request = require('supertest'); var assert = require('assert'); var storageFactory = require('../lib/storage/storage-factory'); var storage = storageFactory.getStorageInstance('test'); var app = require('../webserver/app')(storage); describe('ping plugins route', function () { var server; var PORT = 3355; var API_ROOT = '/api/plugins'; var agent = request.agent(app); before(function (done) { server = app.listen(PORT, function () { if (server.address()) { console.log('starting server in port ' + PORT); done(); } else { console.log('something went wrong... couldn\'t listen to that port.'); process.exit(1); } }); }); after(function () { server.close(); }); describe('plugin list', function () { describe('with an anonymous user ', function () { it('should return list of plugins', function (done) { agent .get(API_ROOT + '/') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .send() .end(function (err, res) { assert.equal(res.body.length, 2); assert.equal(res.body[0].name, 'http-head'); done(err); }); }); }); }); });
Fix login permissions for ticketing
from django.conf.urls.defaults import patterns, url from django.contrib.auth.decorators import login_required from oscar.core.application import Application from ticketing import views class TicketingApplication(Application): name = 'ticketing' ticket_list_view = views.TicketListView ticket_create_view = views.TicketCreateView ticket_update_view = views.TicketUpdateView def get_urls(self): urlpatterns = super(TicketingApplication, self).get_urls() urlpatterns += patterns('', url( r'accounts/support/$', self.ticket_list_view.as_view(), name='customer-ticket-list' ), url( r'accounts/support/ticket/create/$', self.ticket_create_view.as_view(), name='customer-ticket-create' ), url( r'accounts/support/ticket/(?P<pk>\d+)/update/$', self.ticket_update_view.as_view(), name='customer-ticket-update' ), ) return self.post_process_urls(urlpatterns) def get_url_decorator(self, url_name): return login_required application = TicketingApplication()
from django.conf.urls.defaults import patterns, url from oscar.core.application import Application from ticketing import views class TicketingApplication(Application): name = 'ticketing' ticket_list_view = views.TicketListView ticket_create_view = views.TicketCreateView ticket_update_view = views.TicketUpdateView def get_urls(self): urlpatterns = super(TicketingApplication, self).get_urls() urlpatterns += patterns('', url( r'accounts/support/$', self.ticket_list_view.as_view(), name='customer-ticket-list' ), url( r'accounts/support/ticket/create/$', self.ticket_create_view.as_view(), name='customer-ticket-create' ), url( r'accounts/support/ticket/(?P<pk>\d+)/update/$', self.ticket_update_view.as_view(), name='customer-ticket-update' ), ) return self.post_process_urls(urlpatterns) application = TicketingApplication()
Set a maximum to the number of elements that may be requested
from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ page_size = 25 page_size_query_param = "max_results" max_page_size = 100 def get_paginated_response(self, data): links = OrderedDict() if self.page.has_next(): links['next'] = OrderedDict([ ('href', self.get_next_link()), ('title', _('page suivante')), ]) if self.page.has_previous(): links['prev'] = OrderedDict([ ('href', self.get_previous_link()), ('title', _('page précédente')), ]) meta = OrderedDict([ ('max_results', self.page.paginator.per_page), ('total', self.page.paginator.count), ('page', self.page.number), ]) return Response(OrderedDict([ ('_items', data), ('_links', links), ('_meta', meta), ]))
from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ page_size = 25 page_size_query_param = "max_results" def get_paginated_response(self, data): links = OrderedDict() if self.page.has_next(): links['next'] = OrderedDict([ ('href', self.get_next_link()), ('title', _('page suivante')), ]) if self.page.has_previous(): links['prev'] = OrderedDict([ ('href', self.get_previous_link()), ('title', _('page précédente')), ]) meta = OrderedDict([ ('max_results', self.page.paginator.per_page), ('total', self.page.paginator.count), ('page', self.page.number), ]) return Response(OrderedDict([ ('_items', data), ('_links', links), ('_meta', meta), ]))
Configure mission form type option
<?php namespace ModuleGenerator\PhpGenerator\Constant; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Validator\Constraints\NotBlank; final class ConstantType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add( 'name', TextType::class, [ 'label' => 'Name', 'required' => true, 'constraints' => [ new NotBlank(), ], ] )->add( 'value', $options['value_type_class_name'], [ 'label' => $options['value_label'], 'required' => true, 'constraints' => $options['value_constraints'], ] ); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'data_class' => ConstantDataTransferObject::class, 'label' => 'Constant', 'required' => true, 'value_type_class_name' => TextType::class, 'value_label' => 'Value', 'value_constraints' => [ new NotBlank(), ], ] ); } }
<?php namespace ModuleGenerator\PhpGenerator\Constant; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Validator\Constraints\NotBlank; final class ConstantType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add( 'name', TextType::class, [ 'label' => 'Name', 'required' => true, 'constraints' => [ new NotBlank(), ], ] )->add( 'value', $options['type_class_name'], [ 'label' => $options['value_label'], 'required' => true, 'constraints' => $options['value_constraints'], ] ); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'data_class' => ConstantDataTransferObject::class, 'label' => 'Constant', 'required' => true, 'value_label' => 'Value', 'value_constraints' => [ new NotBlank(), ], ] ); } }
Refactor to better define data helper
const request = require('request'); /** * Function checks that a string given is string with some number of * characters * * @params {string} str string value to check for validity * @return true if the string is valid; otherwise, return false */ function isValidString(str) { if ((str === undefined) || (typeof(str) !== "string") || (str.length <= 0)) { return false; } return true; } let clothing = exports = module.exports = { retrieveClothingInfo: (clothing_url) => { return new Promise((accept, reject) => { if (!isValidString(clothing_url)) { return reject("No clothing_url provided"); } const options = { headers: {'user-agent': 'node.js'} } request(clothing_url, options, function (error, response, body) { if (error || !response || response.statusCode !== 200) { console.log(body); return reject("Invalid clothing_url"); } const price = body.match(/\$([\d.]+)/); const image = body.match(/<meta[\S ]+og:image[\S ]+content="(\S+)"/); accept({ price: price && parseFloat(price[1]), image: image && image[1], }); }); }); } }
const request = require('request'); /** * Function checks that a string given is string with some number of * characters * * @params {string} str string value to check for validity * @return true if the string is valid; otherwise, return false */ function isValidString(str) { if ((str === undefined) || (typeof(str) !== "string") || (str.length <= 0)) { return false; } return true; } let user = exports = module.exports = { retrieveClothingInfo: (clothing_url) => { return new Promise((accept, reject) => { if (!isValidString(clothing_url)) { return reject("No clothing_url provided"); } const options = { headers: {'user-agent': 'node.js'} } request(clothing_url, options, function (error, response, body) { if (error || !response || response.statusCode !== 200) { console.log(body); return reject("Invalid clothing_url"); } const price = body.match(/\$([\d.]+)/); const image = body.match(/<meta[\S ]+og:image[\S ]+content="(\S+)"/); accept({ price: price && parseFloat(price[1]), image: image && image[1], }); }); }); } }
Add protection against multiple Fancybox init.
$(document).ready(function () { $.fancybox.defaults.locales = $.extend({}, $.fancybox.defaults.locales, { ru: { CLOSE: Translator.trans('fancybox.close'), NEXT: Translator.trans('fancybox.next'), PREV: Translator.trans('fancybox.prev'), ERROR: Translator.trans('fancybox.error'), EXPAND: Translator.trans('fancybox.expand'), SHRINK: Translator.trans('fancybox.shrink'), PLAY_START: Translator.trans('fancybox.play_start'), PLAY_STOP: Translator.trans('fancybox.play_stop') } }); $('body').on('click', 'a.fancybox_ajax', function (e) { e.preventDefault(); var $link = $(this); if ($link.data('submitted')) { return; } $link .append(AJAX_LOADER) .data('submitted', true); $.ajax({ type: 'get', url: $link.attr('href') }).done(function (html) { $.fancybox({ caption: { type: 'inside' }, content: html, title: $link.attr('title') }); }).error(onAjaxError); }); });
$(document).ready(function () { $.fancybox.defaults.locales = $.extend({}, $.fancybox.defaults.locales, { ru: { CLOSE: Translator.trans('fancybox.close'), NEXT: Translator.trans('fancybox.next'), PREV: Translator.trans('fancybox.prev'), ERROR: Translator.trans('fancybox.error'), EXPAND: Translator.trans('fancybox.expand'), SHRINK: Translator.trans('fancybox.shrink'), PLAY_START: Translator.trans('fancybox.play_start'), PLAY_STOP: Translator.trans('fancybox.play_stop') } }); $('body').on('click', 'a.fancybox_ajax', function (e) { e.preventDefault(); var $link = $(this); $.ajax({ type: 'get', url: $link.attr('href') }).done(function (html) { $.fancybox({ caption: { type: 'inside' }, content: html, title: $link.attr('title') }); }).error(onAjaxError); }); });
Make cite definition more robust
"use strict"; // Provides several classes frequently used in Arethusa angular.module('arethusa.util').service('commons', [ function ArethusaClasses() { // Used to define plugin settings function Setting(label, model, change) { this.label = label; this.model = model; this.change = change; } this.setting = function(l, m, c) { return new Setting(l, m, c); }; // Used by retrievers to place documents in the document store function Doc(xml, json, conf) { this.xml = xml; this.json = json; this.conf = conf; } this.doc = function(x, j, c) { return new Doc(x, j, c); }; // Used by retrievers to define sentences function Sentence(id, tokens, cite) { var self = this; this.id = id; this.tokens = tokens; this.cite = cite || ''; this.toString = function() { return arethusaUtil.inject([], self.tokens, function(memo, id, token) { memo.push(token.string); }).join(' '); }; } this.sentence = function(i, t, c) { return new Sentence(i, t, c); }; // A simple token container function Token(string, sentenceId) { this.string = string; this.sentenceId = sentenceId; } this.token = function (s, sentenceId) { return new Token(s, sentenceId); }; } ]);
"use strict"; // Provides several classes frequently used in Arethusa angular.module('arethusa.util').service('commons', [ function ArethusaClasses() { // Used to define plugin settings function Setting(label, model, change) { this.label = label; this.model = model; this.change = change; } this.setting = function(l, m, c) { return new Setting(l, m, c); }; // Used by retrievers to place documents in the document store function Doc(xml, json, conf) { this.xml = xml; this.json = json; this.conf = conf; } this.doc = function(x, j, c) { return new Doc(x, j, c); }; // Used by retrievers to define sentences function Sentence(id, tokens, cite) { var self = this; this.id = id; this.tokens = tokens; this.cite = cite; this.toString = function() { return arethusaUtil.inject([], self.tokens, function(memo, id, token) { memo.push(token.string); }).join(' '); }; } this.sentence = function(i, t, c) { return new Sentence(i, t, c); }; // A simple token container function Token(string, sentenceId) { this.string = string; this.sentenceId = sentenceId; } this.token = function (s, sentenceId) { return new Token(s, sentenceId); }; } ]);
Make the skip apply to any system missing crypt
# -*- coding: utf-8 -*- # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re # Import Salt Libs import salt.utils.pycrypto import salt.utils.platform # Import Salt Testing Libs from tests.support.unit import TestCase, skipIf log = logging.getLogger(__name__) class PycryptoTestCase(TestCase): ''' TestCase for salt.utils.pycrypto module ''' # The crypt module is only available on Unix systems # https://docs.python.org/dev/library/crypt.html @skipIf(not salt.utils.pycrypto.HAS_CRYPT, 'crypt module not available') def test_gen_hash(self): ''' Test gen_hash ''' passwd = 'test_password' id = '$' if salt.utils.platform.is_darwin(): id = '' ret = salt.utils.pycrypto.gen_hash(password=passwd) self.assertTrue(ret.startswith('$6{0}'.format(id))) ret = salt.utils.pycrypto.gen_hash(password=passwd, algorithm='md5') self.assertTrue(ret.startswith('$1{0}'.format(id))) ret = salt.utils.pycrypto.gen_hash(password=passwd, algorithm='sha256') self.assertTrue(ret.startswith('$5{0}'.format(id))) def test_secure_password(self): ''' test secure_password ''' ret = salt.utils.pycrypto.secure_password() check = re.compile(r'[!@#$%^&*()_=+]') assert check.search(ret) is None assert ret
# -*- coding: utf-8 -*- # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re # Import Salt Libs import salt.utils.pycrypto import salt.utils.platform # Import Salt Testing Libs from tests.support.unit import TestCase, skipIf log = logging.getLogger(__name__) class PycryptoTestCase(TestCase): ''' TestCase for salt.utils.pycrypto module ''' @skipIf(salt.utils.platform.is_windows(), 'No crypto module for Windows') def test_gen_hash(self): ''' Test gen_hash ''' passwd = 'test_password' id = '$' if salt.utils.platform.is_darwin(): id = '' ret = salt.utils.pycrypto.gen_hash(password=passwd) self.assertTrue(ret.startswith('$6{0}'.format(id))) ret = salt.utils.pycrypto.gen_hash(password=passwd, algorithm='md5') self.assertTrue(ret.startswith('$1{0}'.format(id))) ret = salt.utils.pycrypto.gen_hash(password=passwd, algorithm='sha256') self.assertTrue(ret.startswith('$5{0}'.format(id))) def test_secure_password(self): ''' test secure_password ''' ret = salt.utils.pycrypto.secure_password() check = re.compile(r'[!@#$%^&*()_=+]') assert check.search(ret) is None assert ret
Check OutputConfiguration for avoiding NPE
package com.cookpad.puree.outputs; import com.cookpad.puree.PureeFilter; import com.cookpad.puree.storage.PureeStorage; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public abstract class PureeOutput { protected OutputConfiguration conf; protected PureeStorage storage; protected List<PureeFilter> filters = new ArrayList<>(); public void registerFilter(PureeFilter filter) { filters.add(filter); } public void initialize(PureeStorage storage) { this.storage = storage; OutputConfiguration defaultConfiguration = new OutputConfiguration(); this.conf = configure(defaultConfiguration); if (conf == null) { conf = defaultConfiguration; } } public void receive(JSONObject jsonLog) { try { final JSONObject filteredLog = applyFilters(jsonLog); if (filteredLog == null) { return; } emit(filteredLog); } catch (JSONException ignored) { } } protected JSONObject applyFilters(JSONObject jsonLog) throws JSONException { JSONObject filteredLog = jsonLog; for (PureeFilter filter : filters) { filteredLog = filter.apply(filteredLog); if (filteredLog == null) { return null; } } return filteredLog; } public void flush() { // do nothing because PureeOutput don't have any buffers. } public abstract String type(); public abstract OutputConfiguration configure(OutputConfiguration conf); public abstract void emit(JSONObject jsonLog); }
package com.cookpad.puree.outputs; import com.cookpad.puree.PureeFilter; import com.cookpad.puree.storage.PureeStorage; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public abstract class PureeOutput { protected OutputConfiguration conf; protected PureeStorage storage; protected List<PureeFilter> filters = new ArrayList<>(); public void registerFilter(PureeFilter filter) { filters.add(filter); } public void initialize(PureeStorage storage) { this.storage = storage; this.conf = configure(new OutputConfiguration()); } public void receive(JSONObject jsonLog) { try { final JSONObject filteredLog = applyFilters(jsonLog); if (filteredLog == null) { return; } emit(filteredLog); } catch (JSONException ignored) { } } protected JSONObject applyFilters(JSONObject jsonLog) throws JSONException { JSONObject filteredLog = jsonLog; for (PureeFilter filter : filters) { filteredLog = filter.apply(filteredLog); if (filteredLog == null) { return null; } } return filteredLog; } public void flush() { // do nothing because PureeOutput don't have any buffers. } public abstract String type(); public abstract OutputConfiguration configure(OutputConfiguration conf); public abstract void emit(JSONObject jsonLog); }
Fix QuickFind: stop relying on keys being integers
class UnionFind: def __init__(self, it=None): self.uf = {} if it is None else {i : i for i in it} self.count = len(self.uf) def __iter__(self): return iter(self.uf.keys()) def __getitem__(self, key): return self.uf[key] def __setitem__(self, key, val): if key is not val: raise RuntimeError("key and val must be the same object") self.uf[key] = key class QuickFind(UnionFind): def find(self, key): return self.uf[key] def union(self, key1, key2): u1 = self.find(key1) u2 = self.find(key2) if u1 == u2: return for k in self.uf: if self.uf[k] == u1: self.uf[k] = u2 self.count -= 1 class QuickUnion(UnionFind): def find(self, key): while self.uf[key] != key: key = self.uf[key] return key def union(self, key1, key2): u1 = self.find(key1) u2 = self.find(key2) if u1 == u2: return self.uf[u1] = u2 self.count -= 1
class UnionFind: def __init__(self, it=None): self.uf = {} if it is None else {i : i for i in it} self.count = len(self.uf) def __iter__(self): return iter(self.uf.keys()) def __getitem__(self, key): return self.uf[key] def __setitem__(self, key, val): if key is not val: raise RuntimeError("key and val must be the same object") self.uf[key] = key class QuickFind(UnionFind): def find(self, key): return self.uf[key] def union(self, key1, key2): u1 = self.find(key1) u2 = self.find(key2) if u1 == u2: return for i in range(len(self.uf)): if self.uf[i] == u1: self.uf[i] = u2 self.count -= 1 class QuickUnion(UnionFind): def find(self, key): while self.uf[key] != key: key = self.uf[key] return key def union(self, key1, key2): u1 = self.find(key1) u2 = self.find(key2) if u1 == u2: return self.uf[u1] = u2 self.count -= 1
Add code to silence requests logger in the handler
import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index requests_log = logging.getLogger('requests') requests_log.propagate = False def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: params = { 'host': socket.gethostname(), 'index': self.index, 'source': record.pathname, 'sourcetype': 'json' } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
import logging import socket import traceback from threading import Thread import requests class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _async_emit(self, record): try: params = { 'host': socket.gethostname(), 'index': self.index, 'source': record.pathname, 'sourcetype': 'json' } url = 'https://%s:%s/services/receivers/simple' % (self.host, self.port) payload = self.format(record) auth = (self.username, self.password) r = requests.post( url, auth=auth, data=payload, params=params ) r.close() except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
Add explicit render layer binding instead of assuming all render passes can be used for compositing
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Application import Application from UM.Resources import Resources from UM.Math.Matrix import Matrix from UM.View.RenderPass import RenderPass from UM.View.GL.OpenGL import OpenGL class CompositePass(RenderPass): def __init__(self, width, height): super().__init__("composite", width, height, 999) self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "composite.shader")) self._gl = OpenGL.getInstance().getBindingsObject() self._renderer = Application.getInstance().getRenderer() self._layer_bindings = [ "default", "selection" ] def setCompositeShader(self, shader): self._shader = shader def setLayerBindings(self, bindings): self._layer_bindings = bindings def render(self): self._shader.bind() texture_unit = 0 for binding in self._layer_bindings: render_pass = self._renderer.getRenderPass(binding) if not render_pass: continue self._gl.glActiveTexture(getattr(self._gl, "GL_TEXTURE{0}".format(texture_unit))) self._gl.glBindTexture(self._gl.GL_TEXTURE_2D, render_pass.getTextureId()) texture_unit += 1 self._renderer.renderFullScreenQuad(self._shader) for i in range(texture_unit): self._gl.glActiveTexture(getattr(self._gl, "GL_TEXTURE{0}".format(i))) self._gl.glBindTexture(self._gl.GL_TEXTURE_2D, 0) self._shader.release()
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Application import Application from UM.Resources import Resources from UM.Math.Matrix import Matrix from UM.View.RenderPass import RenderPass from UM.View.GL.OpenGL import OpenGL class CompositePass(RenderPass): def __init__(self, width, height): super().__init__("composite", width, height) self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "composite.shader")) self._gl = OpenGL.getInstance().getBindingsObject() self._renderer = Application.getInstance().getRenderer() def setCompositeShader(self, shader): self._shader = shader def renderContents(self): pass def renderOutput(self): self._shader.bind() texture_unit = 0 for render_pass in self._renderer.getRenderPasses(): self._gl.glActiveTexture(texture_unit) self._gl.glBindTexture(self._gl.GL_TEXTURE_2D, render_pass.getTextureId()) texture_unit += 1 self._renderer.renderQuad(self._shader) for i in range(texture_unit): self._gl.glActiveTexture(texture_unit) self._gl.glBindTexture(self._gl.GL_TEXTURE_2D, 0) self._shader.release()
Fix tooltips not hiding after clicking button
isic.views.LayoutHeaderView = isic.View.extend({ events: { 'click .isic-link-home': function () { isic.router.navigate('index', {trigger: true}); }, 'click .isic-link-dataset-upload': function () { isic.router.navigate('uploadDataset', {trigger: true}); }, 'click .isic-link-studies': function () { isic.router.navigate('studies', {trigger: true}); } }, initialize: function () { this.datasetContributor = false; this._updateUserInfo(); girder.events.on('g:login', this._updateUserInfo, this); this.render(); }, render: function () { this.$el.html(isic.templates.layoutHeader({ datasetContributor: this.datasetContributor })); // Specify trigger for tooltip to ensure that tooltip hides when button // is clicked. See http://stackoverflow.com/a/33585981/2522042. this.$('a[title]').tooltip({ placement: 'bottom', trigger: 'hover', delay: {show: 300} }); new isic.views.LayoutHeaderUserView({ el: this.$('.isic-current-user-wrapper'), parentView: this }).render(); }, _updateUserInfo: function (){ // Check whether user has permission to contribute datasets var datasetModel = new isic.models.DatasetModel(); datasetModel.userCanContribute(girder.currentUser).then(_.bind(function (datasetContributor) { if (this.datasetContributor != datasetContributor) { this.datasetContributor = datasetContributor; this.render(); } }, this)); } });
isic.views.LayoutHeaderView = isic.View.extend({ events: { 'click .isic-link-home': function () { isic.router.navigate('index', {trigger: true}); }, 'click .isic-link-dataset-upload': function () { isic.router.navigate('uploadDataset', {trigger: true}); }, 'click .isic-link-studies': function () { isic.router.navigate('studies', {trigger: true}); } }, initialize: function () { this.datasetContributor = false; this._updateUserInfo(); girder.events.on('g:login', this._updateUserInfo, this); this.render(); }, render: function () { this.$el.html(isic.templates.layoutHeader({ datasetContributor: this.datasetContributor })); this.$('a[title]').tooltip({ placement: 'bottom', delay: {show: 300} }); new isic.views.LayoutHeaderUserView({ el: this.$('.isic-current-user-wrapper'), parentView: this }).render(); }, _updateUserInfo: function (){ // Check whether user has permission to contribute datasets var datasetModel = new isic.models.DatasetModel(); datasetModel.userCanContribute(girder.currentUser).then(_.bind(function (datasetContributor) { if (this.datasetContributor != datasetContributor) { this.datasetContributor = datasetContributor; this.render(); } }, this)); } });
Revert year range end back to 2015 (2016 is not over)
#!/usr/bin/env python import sys import os import collections import data import figs class Counter(collections.Counter): year_range = range(2004, 2015) def restrict_to_year_range(self, multiplier=1): output = [] for year in self.year_range: output.append(multiplier * self[year]) return output out_dir = sys.argv[-1] with open(sys.argv[1]) as stream: reader = data.RawReader(stream) neighborhood = None new_counts, old_counts = Counter(), Counter() for row in reader: year = int(row['year']) if neighborhood is None: neighborhood = row['neighborhood'] if neighborhood != row['neighborhood']: if not neighborhood: neighborhood = "unknown" fig = figs.FlowOverTime( Counter.year_range, new_counts.restrict_to_year_range(), old_counts.restrict_to_year_range(multiplier=-1), ) filename = os.path.join( out_dir, neighborhood.lower().replace(' ', '_') + '.png', ) fig.save(filename) fig.close() print "saved", filename neighborhood = row['neighborhood'] new_counts, old_counts = Counter(), Counter() new_counts[year] = int(row['new']) old_counts[year] = int(row['old'])
#!/usr/bin/env python import sys import os import collections import data import figs class Counter(collections.Counter): year_range = range(2004, 2016) def restrict_to_year_range(self, multiplier=1): output = [] for year in self.year_range: output.append(multiplier * self[year]) return output out_dir = sys.argv[-1] with open(sys.argv[1]) as stream: reader = data.RawReader(stream) neighborhood = None new_counts, old_counts = Counter(), Counter() for row in reader: year = int(row['year']) if neighborhood is None: neighborhood = row['neighborhood'] if neighborhood != row['neighborhood']: if not neighborhood: neighborhood = "unknown" fig = figs.FlowOverTime( Counter.year_range, new_counts.restrict_to_year_range(), old_counts.restrict_to_year_range(multiplier=-1), ) filename = os.path.join( out_dir, neighborhood.lower().replace(' ', '_') + '.png', ) fig.save(filename) fig.close() print "saved", filename neighborhood = row['neighborhood'] new_counts, old_counts = Counter(), Counter() new_counts[year] = int(row['new']) old_counts[year] = int(row['old'])
Use null as the defaultValue for Image URLs (denoting an image placeholder)
// Register ContentNode types (including meta information). ContentNode.types = { "document": { name: "Document", allowedChildren: ["section"], properties: [ { "key": "title", "name": "Title", "defaultValue": "A document title" } ] }, "section": { name: "Section", allowedChildren: ["paragraph", "image"], properties: [ { "key": "name", "name": "Section name", "defaultValue": "Hooray I'm a new section " } ] }, "paragraph": { name: "Paragraph", allowedChildren: [], properties: [ { "key": "content", "name": "Content", "defaultValue": "Hooray I'm a newborn paragraph." } ] }, "image": { name: "Image", allowedChildren: [], properties: [ { "key": "url", "name": "Image URL", "defaultValue": null } ] }, "text": { name: "Text", allowedChildren: [], properties: [ { "key": "content", "name": "Content", "defaultValue": "Hurray, I'm a new node" }, { "key": "em_level", "name": "Emphasis level", "defaultValue": "0" } ] } };
// Register ContentNode types (including meta information). ContentNode.types = { "document": { name: "Document", allowedChildren: ["section"], properties: [ { "key": "title", "name": "Title", "defaultValue": "A document title" } ] }, "section": { name: "Section", allowedChildren: ["paragraph", "image"], properties: [ { "key": "name", "name": "Section name", "defaultValue": "Hooray I'm a new section " } ] }, "paragraph": { name: "Paragraph", allowedChildren: [], properties: [ { "key": "content", "name": "Content", "defaultValue": "Hooray I'm a newborn paragraph." } ] }, "image": { name: "Image", allowedChildren: [], properties: [ { "key": "url", "name": "Image URL", "defaultValue": "" } ] }, "text": { name: "Text", allowedChildren: [], properties: [ { "key": "content", "name": "Content", "defaultValue": "Hurray, I'm a new node" }, { "key": "em_level", "name": "Emphasis level", "defaultValue": "0" } ] } };
Set "contentType" on AJAX call.
$(document).ready(function() { var editor = ace.edit("json"); editor.setTheme("ace/theme/github"); editor.session.setMode("ace/mode/json"); editor.setFontSize(14); editor.$blockScrolling = "Infinity"; $("#submit_json").click(function() { try { $.ajax({ method: "POST", contentType: 'application/json', url: "/" + $("#conn_name").val() + "/" + $("#db_name").val() + "/" + $("#coll_name").val() + "/save", data: editor.getValue() }) .success(function(msg) { show_notification(msg,"success"); }) .error(function(msg) { show_notification(msg.responseText,"danger"); }); } catch (err) { show_notification(err,"danger"); } }); // prettify the json var jsonString = editor.getValue(); var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2); editor.setValue(jsonPretty); });
$(document).ready(function() { var editor = ace.edit("json"); editor.setTheme("ace/theme/github"); editor.session.setMode("ace/mode/json"); editor.setFontSize(14); editor.$blockScrolling = "Infinity"; $("#submit_json").click(function() { try { var json = $.parseJSON(editor.getValue()); $.ajax({ method: "POST", url: "/" + $("#conn_name").val() + "/" + $("#db_name").val() + "/" + $("#coll_name").val() + "/save", data: json }) .success(function(msg) { show_notification(msg,"success"); }) .error(function(msg) { show_notification(msg.responseText,"danger"); }); } catch (err) { show_notification(err,"danger"); } }); // prettify the json var jsonString = editor.getValue(); var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2); editor.setValue(jsonPretty); });
Fix generating icon name for files without extension
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['popover-confirm'], iconClass: function () { var filename = this.get('filename'), regex, match, extension; if (filename) { regex = /\.([0-9a-z]+)$/i; match = filename.match(/\.([0-9a-z]+)$/i); extension = match && match[1]; if (extension) { return 'glyphicon-' + extension.toLowerCase(); } } }.property('filename'), isShowingDidChange: function () { if (!!this.get('isShowing')) { this.show(); } else { this.hide(); } }.observes('isShowing'), didInsertElement: function () { this._super(); this.$().hide(); }, // Uber hacky way to make Bootstrap 'popover' plugin work with Ember metamorph show: function () { // Delay until related properties are computed Ember.run.next(this, function () { var html = this.$().html(); // Content needs to be visible, // so that popover position is calculated properly. this.$().show(); this.$().popover({ html: true, content: html, placement: 'top' }); this.$().popover('show'); this.$().hide(); }); }, hide: function () { this.$().popover('destroy'); }, actions: { confirm: function () { this.hide(); this.sendAction('confirm'); }, cancel: function() { this.hide(); this.sendAction('cancel'); } } });
import Ember from 'ember'; export default Ember.Component.extend({ classNames: ['popover-confirm'], iconClass: function () { var filename = this.get('filename'), regex, extension; if (filename) { regex = /\.([0-9a-z]+)$/i; extension = filename.match(/\.([0-9a-z]+)$/i)[1]; if (extension) { return 'glyphicon-' + extension.toLowerCase(); } } }.property('filename'), isShowingDidChange: function () { if (!!this.get('isShowing')) { this.show(); } else { this.hide(); } }.observes('isShowing'), didInsertElement: function () { this._super(); this.$().hide(); }, // Uber hacky way to make Bootstrap 'popover' plugin work with Ember metamorph show: function () { // Delay until related properties are computed Ember.run.next(this, function () { var html = this.$().html(); // Content needs to be visible, // so that popover position is calculated properly. this.$().show(); this.$().popover({ html: true, content: html, placement: 'top' }); this.$().popover('show'); this.$().hide(); }); }, hide: function () { this.$().popover('destroy'); }, actions: { confirm: function () { this.hide(); this.sendAction('confirm'); }, cancel: function() { this.hide(); this.sendAction('cancel'); } } });
Allow Property Models to be undefined
const Config = use('config'); const Errors = use('core/errors'); const DefaultProperty = require('./default'); const PrimaryKeyPattern = new RegExp('^'+Config.router.primaryKeyPattern + '$'); class ModelProperty extends DefaultProperty { constructor(modelName) { super(); const Factories = use('core/factories'); this._addValidator((value, propertyName) => { if (value != null && ( (typeof value === "object" && (!PrimaryKeyPattern.test(value.id))) || (typeof value !== "object" && (!PrimaryKeyPattern.test(value))) ) ) { throw new Errors.Validation(`property ${propertyName} should be positive integer or model instance, given '${value}'`); } }); this._addValidator((value, propertyName) => { try { Factories(modelName); } catch (error) { if (error instanceof Errors.Fatal) { throw new Errors.Validation(`property ${propertyName} should be a model ${modelName}, but such model is not defined`); } else { throw error; } } }); this._addOutputModification((outputObject, propertyName) => { if(outputObject[propertyName] !== null) { outputObject[propertyName] = { id: outputObject[propertyName], link: modelName.toLowerCase() + "/" + outputObject[propertyName] }; } }); this._inputModification = (value) => { return (value !== null && typeof value === "object" && PrimaryKeyPattern.test(value.id)) ? value.id : value; }; } } module.exports = ModelProperty;
const Config = use('config'); const Errors = use('core/errors'); const DefaultProperty = require('./default'); const PrimaryKeyPattern = new RegExp('^'+Config.router.primaryKeyPattern + '$'); class ModelProperty extends DefaultProperty { constructor(modelName) { super(); const Factories = use('core/factories'); this._addValidator((value, propertyName) => { if (value !== null && ( (typeof value === "object" && (!PrimaryKeyPattern.test(value.id))) || (typeof value !== "object" && (!PrimaryKeyPattern.test(value))) ) ) { throw new Errors.Validation(`property ${propertyName} should be positive integer or model instance, given '${value}'`); } }); this._addValidator((value, propertyName) => { try { Factories(modelName); } catch (error) { if (error instanceof Errors.Fatal) { throw new Errors.Validation(`property ${propertyName} should be a model ${modelName}, but such model is not defined`); } else { throw error; } } }); this._addOutputModification((outputObject, propertyName) => { outputObject[propertyName] = { id: outputObject[propertyName], link: modelName.toLowerCase() + "/" + outputObject[propertyName] }; }); this._inputModification = (value) => { return (value !== null && typeof value === "object" && PrimaryKeyPattern.test(value.id)) ? value.id : value; }; } } module.exports = ModelProperty;
Fix a bad function name
"use strict"; var createParser = require("postcss-selector-parser"), keyframes = /keyframes$/i; exports.keyframes = keyframes; // TODO: this is probably inefficient, but oh well for now exports.parse = function parse(selector) { var values = []; createParser(function(selectors) { // Walk classes selectors.eachClass(function(part) { values.push(part.value); }); // Walk IDs selectors.eachId(function(part) { values.push(part.value); }); // Walk @keyframes definitions selectors.eachTag(function(part) { // This is a slightly ridiculous conditional, but postcss-selector-parser // spits out @keyframes <name> as [ @keyframes, <name> ] so we have to do // this flopping around to find the real value. Blech. if(part.parent.nodes[0] && part.parent.nodes[0] !== part && part.parent.nodes[0].value.search(keyframes) > -1) { values.push(part.value); } }); }).process(selector); return values; };
"use strict"; var createParser = require("postcss-selector-parser"), keyframes = /keyframes$/i; exports.keyframes = keyframes; // TODO: this is probably inefficient, but oh well for now exports.parse = function identifiers(selector) { var values = []; createParser(function(selectors) { // Walk classes selectors.eachClass(function(part) { values.push(part.value); }); // Walk IDs selectors.eachId(function(part) { values.push(part.value); }); // Walk @keyframes definitions selectors.eachTag(function(part) { // This is a slightly ridiculous conditional, but postcss-selector-parser // spits out @keyframes <name> as [ @keyframes, <name> ] so we have to do // this flopping around to find the real value. Blech. if(part.parent.nodes[0] && part.parent.nodes[0] !== part && part.parent.nodes[0].value.search(keyframes) > -1) { values.push(part.value); } }); }).process(selector); return values; };
[BUG] Fix for scroll janky on virtual scroll after apply change
import { requestAnimFrame } from '../../utils/utils'; import { StyleTranslator } from './StyleTranslator'; import { TranslateXY } from '../../utils/translate'; export function ScrollerDirective($timeout){ return { restrict: 'E', require:'^dtBody', transclude: true, replace: true, template: `<div ng-style="scrollerStyles()" ng-transclude></div>`, link: function($scope, $elm, $attrs, ctrl){ var ticking = false, lastScrollY = 0, lastScrollX = 0, parent = $elm.parent(); ctrl.options.internal.styleTranslator = new StyleTranslator(ctrl.options.rowHeight); ctrl.options.internal.setYOffset = function(offsetY){ parent[0].scrollTop = offsetY; }; function update(){ $scope.$applyAsync(() => { ctrl.options.internal.offsetY = lastScrollY; ctrl.options.internal.offsetX = lastScrollX; ctrl.updatePage(); if(ctrl.options.scrollbarV){ ctrl.getRows(); } }); ticking = false; }; function requestTick() { if(!ticking) { requestAnimFrame(update); ticking = true; } }; $elm.parent().on('scroll', function(ev) { lastScrollY = this.scrollTop; lastScrollX = this.scrollLeft; requestTick(); }); $scope.scrollerStyles = function(scope){ return { height: ctrl.count * ctrl.options.rowHeight + 'px' } }; } }; };
import { requestAnimFrame } from '../../utils/utils'; import { StyleTranslator } from './StyleTranslator'; import { TranslateXY } from '../../utils/translate'; export function ScrollerDirective($timeout){ return { restrict: 'E', require:'^dtBody', transclude: true, replace: true, template: `<div ng-style="scrollerStyles()" ng-transclude></div>`, link: function($scope, $elm, $attrs, ctrl){ var ticking = false, lastScrollY = 0, lastScrollX = 0, parent = $elm.parent(); ctrl.options.internal.styleTranslator = new StyleTranslator(ctrl.options.rowHeight); ctrl.options.internal.setYOffset = function(offsetY){ parent[0].scrollTop = offsetY; }; function update(){ ctrl.options.internal.offsetY = lastScrollY; ctrl.options.internal.offsetX = lastScrollX; ctrl.updatePage(); if(ctrl.options.scrollbarV){ ctrl.getRows(); } $scope.$applyAsync(); ticking = false; }; function requestTick() { if(!ticking) { requestAnimFrame(update); ticking = true; } }; $elm.parent().on('scroll', function(ev) { lastScrollY = this.scrollTop; lastScrollX = this.scrollLeft; requestTick(); }); $scope.scrollerStyles = function(scope){ return { height: ctrl.count * ctrl.options.rowHeight + 'px' } }; } }; };
Improve the url parsing - we need only the path to be able to decide
package hellowicket; import org.apache.wicket.core.request.handler.PageProvider; import org.apache.wicket.core.request.handler.RenderPageRequestHandler; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.IRequestMapper; import org.apache.wicket.request.Request; import org.apache.wicket.request.Url; import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler; import hellowicket.dbupdates.HelloDbUpdatesReference; import hellowicket.fortune.FortunePage; import hellowicket.plaintext.HelloTextReference; /** * Custom request mapper optimized for the application needs */ public class RequestMapper implements IRequestMapper { private static final Url FORTUNES_URL = Url.parse("fortunes"); @Override public IRequestHandler mapRequest(final Request request) { final String url = request.getUrl().getPath(); switch (url) { case "json": return new ResourceReferenceRequestHandler(new HelloJsonReference()); case "db": return new ResourceReferenceRequestHandler(new HelloDbReference()); case "updates": return new ResourceReferenceRequestHandler(new HelloDbUpdatesReference()); case "plaintext": return new ResourceReferenceRequestHandler(new HelloTextReference()); case "fortunes": return new RenderPageRequestHandler(new PageProvider(FortunePage.class)); default: } return null; } @Override public int getCompatibilityScore(final Request request) { return 0; } @Override public Url mapHandler(final IRequestHandler requestHandler) { return FORTUNES_URL; } }
package hellowicket; import org.apache.wicket.core.request.handler.PageProvider; import org.apache.wicket.core.request.handler.RenderPageRequestHandler; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.IRequestMapper; import org.apache.wicket.request.Request; import org.apache.wicket.request.Url; import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler; import hellowicket.dbupdates.HelloDbUpdatesReference; import hellowicket.fortune.FortunePage; import hellowicket.plaintext.HelloTextReference; /** * Custom request mapper optimized for the application needs */ public class RequestMapper implements IRequestMapper { private static final Url FORTUNES_URL = Url.parse("fortunes"); @Override public IRequestHandler mapRequest(final Request request) { final String url = request.getUrl().toString(); switch (url) { case "json": return new ResourceReferenceRequestHandler(new HelloJsonReference()); case "db": return new ResourceReferenceRequestHandler(new HelloDbReference()); case "updates": return new ResourceReferenceRequestHandler(new HelloDbUpdatesReference()); case "plaintext": return new ResourceReferenceRequestHandler(new HelloTextReference()); case "fortunes": return new RenderPageRequestHandler(new PageProvider(FortunePage.class)); default: } return null; } @Override public int getCompatibilityScore(final Request request) { return 0; } @Override public Url mapHandler(final IRequestHandler requestHandler) { return FORTUNES_URL; } }
Add option to print astor reconstructed source of template
import ast from .context import ContextScope from .parser import Parser from .utils import Helpers def kompile(src, raw=False, filename='<compiler>', **kwargs): ''' Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): return map(str, self._root(context) def _root(self, context): yield '' yield ... yield from self.head(context) Blocks create new methods, and add a 'yield from self.{block}(context)' to the current function ''' parser = Parser(src) parser.load_library('knights.tags') parser.load_library('knights.helpers') parser.build_method('_root') if parser.parent: # Remove _root from the method list parser.methods = [ method for method in parser.methods if method.name != '_root' ] klass = parser.build_class() # Wrap it in a module inst = ast.Module(body=[klass]) ast.fix_missing_locations(inst) if kwargs.get('astor', False): import astor print(astor.to_source(inst)) # Compile code to create class code = compile(inst, filename=filename, mode='exec', optimize=2) # Execute it and return the instance g = { '_': Helpers(parser.helpers), 'parent': parser.parent, 'ContextScope': ContextScope, } eval(code, g) klass = g['Template'] if raw: return klass return klass()
import ast from .context import ContextScope from .parser import Parser from .utils import Helpers def kompile(src, raw=False, filename='<compiler>'): ''' Creates a new class based on the supplied template, and returnsit. class Template(object): def __call__(self, context): return ''.join(self._iterator(context)) def _iterator(self, context): return map(str, self._root(context) def _root(self, context): yield '' yield ... yield from self.head(context) Blocks create new methods, and add a 'yield from self.{block}(context)' to the current function ''' parser = Parser(src) parser.load_library('knights.tags') parser.load_library('knights.helpers') parser.build_method('_root') if parser.parent: # Remove _root from the method list parser.methods = [ method for method in parser.methods if method.name != '_root' ] klass = parser.build_class() # Wrap it in a module inst = ast.Module(body=[klass]) ast.fix_missing_locations(inst) # Compile code to create class code = compile(inst, filename=filename, mode='exec', optimize=2) # Execute it and return the instance g = { '_': Helpers(parser.helpers), 'parent': parser.parent, 'ContextScope': ContextScope, } eval(code, g) klass = g['Template'] if raw: return klass return klass()
Add expectation on Error output
var request = require('supertest'); var JSONAPIValidator = require('jsonapi-validator').Validator; validateJSONapi = function(res) { var validator = new JSONAPIValidator(); validator.validate(res.body); } describe('Error handling', function() { describe('GET /fake', function() { it('Should return 404', function(done) { request(sails.hooks.http.app) .get('/fake') .expect(404) .expect(validateJSONapi) .expect({ 'errors': [ { status: "404", title: 'Resource not found' } ] }) .end(done); }); }); describe('GET /users/42', function() { it('Should return 404', function(done) { request(sails.hooks.http.app) .get('/users/42') .expect(404) .expect(validateJSONapi) .expect({ 'errors': [ { status: "404", title: 'Resource not found', detail: 'No record found with the specified id.' } ] }) .end(done); }); }); describe('GET categories?invalid=true', function() { it('Should return 400', function(done) { request(sails.hooks.http.app) .get('/categories?invalid=true') .expect(400) .expect(validateJSONapi) .expect({ 'errors': [ { status: "400", title: 'Bad request' } ] }) .end(done); }); }); });
var request = require('supertest'); var JSONAPIValidator = require('jsonapi-validator').Validator; validateJSONapi = function(res) { var validator = new JSONAPIValidator(); validator.validate(res.body); } describe('Error handling', function() { describe('GET /fake', function() { it('Should return 404', function(done) { request(sails.hooks.http.app) .get('/fake') .expect(404) .expect(validateJSONapi) .end(done); }); }); describe('GET /users/42', function() { it('Should return 404', function(done) { request(sails.hooks.http.app) .get('/users/42') .expect(404) .expect(validateJSONapi) describe('GET categories?invalid=true', function() { it('Should return 400', function(done) { request(sails.hooks.http.app) .get('/categories?invalid=true') .expect(400) .expect(validateJSONapi) .expect({ 'errors': [ { status: "400", title: 'Bad request' } ] }) .end(done); }); }); });
Change remaining console.log calls to angular's logger.
'use strict'; angular.module('seaWebApp') .controller('JobCtrl', function($scope, $log, $http, $location, $routeParams) { $scope.jobId = $routeParams.jobId; $scope.jobDone = false; $scope.refreshJob = function() { $http({method: 'GET', url: 'http://localhost:8001/jobs/' + $scope.jobId + '/'}). success(function(data, status) { $scope.status = status; $scope.jobData = data; $scope.result = data.result[0]; $log.debug('Job refresh success'); if (data.status === 'Done') { $scope.jobDone = true; } }). error(function(data, status) { $scope.jobData = data || 'Job refresh failed'; $scope.status = status; $log.debug('Job refresh failed'); }); }; $scope.deleteJob = function() { $http({method: 'DELETE', url:'http://localhost:8001/jobs/' + $scope.jobId + '/'}). success(function() { $log.debug('Job deleted'); $location.path( '/home' ); }). error(function() { $log.debug('Job deletion failed'); }); }; $scope.refreshJob(); });
'use strict'; angular.module('seaWebApp') .controller('JobCtrl', function($scope, $http, $location, $routeParams) { $scope.jobId = $routeParams.jobId; $scope.jobDone = false; $scope.refreshJob = function() { $http({method: 'GET', url: 'http://localhost:8001/jobs/' + $scope.jobId + '/'}). success(function(data, status) { $scope.status = status; $scope.jobData = data; $scope.result = data.result[0]; console.log('Job refresh success'); if (data.status === 'Done') { $scope.jobDone = true; } }). error(function(data, status) { $scope.jobData = data || 'Job refresh failed'; $scope.status = status; console.log('Job refresh failed'); }); }; $scope.deleteJob = function() { $http({method: 'DELETE', url:'http://localhost:8001/jobs/' + $scope.jobId + '/'}). success(function() { console.log('Job deleted'); $location.path( '/home' ); }). error(function() { console.log('Job deletion failed'); }); }; $scope.refreshJob(); });
Allow to get key for serializer. Signed-off-by: Mior Muhammad Zaki <[email protected]>
<?php namespace Orchestra\Support; use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Support\Collection as BaseCollection; abstract class Serializer { /** * Data serializer key name. * * @var string */ protected $key = 'data'; /** * Invoke the serializer. * * @param mixed $parameters * * @return mixed */ public function __invoke(...$parameters) { if (method_exists($this, 'serialize')) { return $this->serialize(...$parameters); } return $this->serializeBasicDataset($parameters[0]); } /** * Resolve paginated dataset. * * @param mixed $dataset * * @return array */ final protected function serializeBasicDataset($dataset) { $key = $this->resolveSerializerKey($dataset); if ($dataset instanceof Paginator) { $collection = $dataset->toArray(); $collection[$key] = $collection['data']; unset($collection['data']); return $collection; } return [ $key => $dataset->toArray(), ]; } /** * Get serializer key. * * @return string */ final public function getKey(): string { return $this->key; } /** * Resolve serializer key. * * @param mixed $dataset * * @return string */ protected function resolveSerializerKey($dataset) { if ($dataset instanceof BaseCollection || $dataset instanceof Paginator) { return Str::plural($this->getKey()); } return $this->getKey(); } }
<?php namespace Orchestra\Support; use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Support\Collection as BaseCollection; abstract class Serializer { /** * Data serializer key name. * * @var string */ protected $key = 'data'; /** * Invoke the serializer. * * @param mixed $parameters * * @return mixed */ public function __invoke(...$parameters) { if (method_exists($this, 'serialize')) { return $this->serialize(...$parameters); } return $this->serializeBasicDataset($parameters[0]); } /** * Resolve paginated dataset. * * @param mixed $dataset * * @return array */ final protected function serializeBasicDataset($dataset) { $key = $this->resolveSerializerKey($dataset); if ($dataset instanceof Paginator) { $collection = $dataset->toArray(); $collection[$key] = $collection['data']; unset($collection['data']); return $collection; } return [ $key => $dataset->toArray(), ]; } /** * Resolve serializer key. * * @param mixed $dataset * * @return string */ protected function resolveSerializerKey($dataset) { if ($dataset instanceof BaseCollection || $dataset instanceof Paginator) { return Str::plural($this->key); } return $this->key; } }
Fix users count for unit test
#!/usr/bin/python # coding=utf-8 ################################################################################ from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import Mock from mock import patch from diamond.collector import Collector from users import UsersCollector import sys ################################################################################ class TestUsersCollector(CollectorTestCase): def setUp(self): config = get_collector_config('UsersCollector', { 'utmp': self.getFixturePath('utmp.centos6'), }) self.collector = UsersCollector(config, None) @patch.object(Collector, 'publish') def test_should_work_with_real_data(self, publish_mock): # Because of the compiled nature of pyutmp, we can't actually test # different operating system versions then the currently running # one if sys.platform.startswith('linux'): self.collector.collect() metrics = { 'kormoc': 2, 'root': 3, 'total': 5, } self.setDocExample(self.collector.__class__.__name__, metrics) self.assertPublishedMany(publish_mock, metrics) ################################################################################ if __name__ == "__main__": unittest.main()
#!/usr/bin/python # coding=utf-8 ################################################################################ from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import Mock from mock import patch from diamond.collector import Collector from users import UsersCollector import sys ################################################################################ class TestUsersCollector(CollectorTestCase): def setUp(self): config = get_collector_config('UsersCollector', { 'utmp': self.getFixturePath('utmp.centos6'), }) self.collector = UsersCollector(config, None) @patch.object(Collector, 'publish') def test_should_work_with_real_data(self, publish_mock): # Because of the compiled nature of pyutmp, we can't actually test # different operating system versions then the currently running # one if sys.platform.startswith('linux'): self.collector.collect() metrics = { 'kormoc': 2, 'root': 2, 'total': 4, } self.setDocExample(self.collector.__class__.__name__, metrics) self.assertPublishedMany(publish_mock, metrics) ################################################################################ if __name__ == "__main__": unittest.main()
Add name fields to generated templates
"""Generator functions for thesaurus files""" import json from web.MetaInfo import MetaInfo def generate_language_template(language_id, structure_id, version=None): """Generate a template for the given language and structure""" meta_info = MetaInfo() if structure_id not in meta_info.data_structures: raise ValueError language_name = meta_info.languages.get( language_id, {'name': 'Human-Readable Language Name'} )['name'] meta = { 'language': language_id, 'language_name': language_name, 'structure': structure_id, } if version: meta['language_version'] = version concepts = { id: { 'name': name, 'code': [""], } for category in meta_info.structure(structure_id).categories.values() for (id, name) in category.items() } return json.dumps({'meta': meta, 'concepts': concepts}, indent=2) def generate_meta_template(structure_id, structure_name): """Generate a template for a `meta file`""" meta = { 'structure': structure_id, 'structure_name': structure_name, } categories = { 'First Category Name': { 'concept_id1': 'Name of Concept 1', 'concept_id2': 'Name of Concept 2' }, 'Second Category Name': { 'concept_id3': 'Name of Concept 3', 'concept_id4': 'Name of Concept 4' } } return json.dumps({'meta': meta, 'categories': categories})
import json from web.MetaInfo import MetaInfo def generate_language_template(language_id, structure_id, version=None): meta_info = MetaInfo() if structure_id not in meta_info.data_structures: raise ValueError language_name = meta_info.languages.get( language_id, {'name': 'Human-Readable Language Name'} )['name'] meta = { 'language': language_id, 'language_name': language_name, 'structure': structure_id, } if version: meta['language_version'] = version concepts = { id: {'code': [""]} for category in meta_info.structure(structure_id).categories.values() for (id, name) in category.items() } return json.dumps({'meta': meta, 'concepts': concepts}, indent=2) def generate_meta_template(structure_id, structure_name): meta = { 'structure': structure_id, 'structure_name': structure_name, } categories = { 'First Category Name': { 'concept_id1': 'Name of Concept 1', 'concept_id2': 'Name of Concept 2' }, 'Second Category Name': { 'concept_id3': 'Name of Concept 3', 'concept_id4': 'Name of Concept 4' } } return json.dumps({'meta': meta, 'categories': categories})
Return promise when loading sidebar
class Sidebar { constructor() { const self = this; const doc = $(document); doc.on('click', 'a[href][data-open-sidebar]', function (e) { e.preventDefault(); var sidebar = $('#' + $(this).data('open-sidebar')), href = $(this).attr('href'); self.load(sidebar, href); }); doc.on('click', '.sidebar .cancel-button', function () { self.close($(this).closest('.sidebar')); }); return this; } load(sidebar, url) { sidebar.addClass('sidebar--open'); return $.ajax(url) .done(response => sidebar.find('.content').html(response)) .fail(response => { // It's possible that laravel forgot the site we were logged into. // So when the 'springboard' route returns a 401 unauthorized // status code, then we'll redirect to the site selector. if (response.status === 401) { window.location.href = config.base_url; } }); } close(sidebar) { sidebar.removeClass('sidebar--open').find('.content').html(''); } } export default Sidebar;
class Sidebar { constructor() { const self = this; const doc = $(document); doc.on('click', 'a[href][data-open-sidebar]', function (e) { e.preventDefault(); var sidebar = $('#' + $(this).data('open-sidebar')), href = $(this).attr('href'); self.load(sidebar, href); }); doc.on('click', '.sidebar .cancel-button', function () { self.close($(this).closest('.sidebar')); }); return this; } load(sidebar, url) { sidebar.addClass('sidebar--open'); $.ajax(url) .done(response => sidebar.find('.content').html(response)) .fail(response => { // It's possible that laravel forgot the site we were logged into. // So when the 'springboard' route returns a 401 unauthorized // status code, then we'll redirect to the site selector. if (response.status === 401) { window.location.href = config.base_url; } }); } close(sidebar) { sidebar.removeClass('sidebar--open').find('.content').html(''); } } export default Sidebar;
Read commandline args as isbns
#!/usr/bin/env python import yaml import sys import os from amazon.api import AmazonAPI # Change to script directory os.chdir(os.path.dirname(sys.argv[0])) class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book books = Books('config.yml') for isbn in sys.argv[1:]: book = books.lookup(isbn) with open('raw_data/{0}.yml'.format(isbn), 'w') as out: out.write(yaml.dump(book, default_flow_style = False))
#!/usr/bin/env python import yaml from amazon.api import AmazonAPI class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book book = Books('config.yml').lookup('9781449389734') print yaml.dump(book, default_flow_style = False)
Use query builder to delete versions
<?php declare(strict_types=1); /* * This file is part of SolidInvoice project. * * (c) Pierre du Plessis <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace SolidInvoice\CoreBundle\Repository; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\ORM\ORMException; use Doctrine\ORM\NonUniqueResultException; use Doctrine\ORM\NoResultException; use Doctrine\Persistence\ManagerRegistry; use SolidInvoice\CoreBundle\Entity\Version; class VersionRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Version::class); } /** * Updates the current version. * * @param $version */ public function updateVersion($version): void { $entityManager = $this->getEntityManager(); $qb = $this->createQueryBuilder('v'); $qb->delete() ->getQuery() ->execute(); $entity = new Version($version); try { $entityManager->persist($entity); $entityManager->flush(); } catch (ORMException $e) { // noop } } public function getCurrentVersion(): string { $qb = $this->createQueryBuilder('v'); $qb->select('v.version') ->setMaxResults(1); try { return $qb->getQuery()->getSingleScalarResult(); } catch (NoResultException|NonUniqueResultException $e) { return '0.0.0'; } } }
<?php declare(strict_types=1); /* * This file is part of SolidInvoice project. * * (c) Pierre du Plessis <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace SolidInvoice\CoreBundle\Repository; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\ORM\NonUniqueResultException; use Doctrine\ORM\NoResultException; use Doctrine\Persistence\ManagerRegistry; use SolidInvoice\CoreBundle\Entity\Version; class VersionRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Version::class); } /** * Updates the current version. * * @param $version */ public function updateVersion($version) { $entityManager = $this->getEntityManager(); $query = $entityManager->createQuery('DELETE FROM '.Version::class); $query->execute(); $entity = new Version($version); $entityManager->persist($entity); $entityManager->flush(); } public function getCurrentVersion(): string { $qb = $this->createQueryBuilder('v'); $qb->select('v.version') ->setMaxResults(1); try { return $qb->getQuery()->getSingleScalarResult(); } catch (NoResultException|NonUniqueResultException $e) { return '0.0.0'; } } }
Fix % overflow on 32 bit systems See http://php.net/manual/en/function.fmod.php Partially fixes #1
<?php /** * This file is part of the Random.php package. * * Copyright (C) 2013 Shota Nozaki <[email protected]> * * Licensed under the MIT License */ namespace Random\Engine; class LinearCongruentialEngine extends AbstractEngine { const DEFAULT_SEED = 1; /** * @var integer */ private $a; /** * @var integer */ private $c; /** * @var integer */ private $m; /** * @var integer */ private $x; /** * @param integer $a * @param integer $c * @param integer $m * @param integer $s */ public function __construct($a, $c, $m, $s = self::DEFAULT_SEED) { $this->a = $a; $this->c = $c; $this->m = $m; $this->seed($s); } /** * {@inheritdoc} */ public function max() { return $this->m - 1; } /** * {@inheritdoc} */ public function min() { return $this->c == 0 ? 1 : 0; } /** * {@inheritdoc} */ public function next() { return $this->x = (int) fmod($this->a * $this->x + $this->c, $this->m); } /** * {@inheritdoc} */ public function seed($seed) { $this->x = $seed; } }
<?php /** * This file is part of the Random.php package. * * Copyright (C) 2013 Shota Nozaki <[email protected]> * * Licensed under the MIT License */ namespace Random\Engine; class LinearCongruentialEngine extends AbstractEngine { const DEFAULT_SEED = 1; /** * @var integer */ private $a; /** * @var integer */ private $c; /** * @var integer */ private $m; /** * @var integer */ private $x; /** * @param integer $a * @param integer $c * @param integer $m * @param integer $s */ public function __construct($a, $c, $m, $s = self::DEFAULT_SEED) { $this->a = $a; $this->c = $c; $this->m = $m; $this->seed($s); } /** * {@inheritdoc} */ public function max() { return $this->m - 1; } /** * {@inheritdoc} */ public function min() { return $this->c == 0 ? 1 : 0; } /** * {@inheritdoc} */ public function next() { return $this->x = ($this->a * $this->x + $this->c) % $this->m; } /** * {@inheritdoc} */ public function seed($seed) { $this->x = $seed; } }
Add Twig Extensions on boot
<?php namespace Pipe\Silex; use Silex\Application; use Silex\ServiceProviderInterface; use Symfony\Component\HttpFoundation\Response; class PipeServiceProvider implements ServiceProviderInterface { function register(Application $app) { $app->register(new \Silex\Provider\UrlGeneratorServiceProvider()); $app["pipe"] = $app->share(function($app) { return new PipeService($app); }); $app->get("/_pipe/assets/{logicalPath}", function($logicalPath) use ($app) { $asset = $app["pipe"]->environment->find($logicalPath); if (!$asset) { return $app->abort(404, "Asset '$logicalPath' not found"); } $res = new Response($asset->getBody(), 200); $res->headers->set("Content-Type", $asset->getContentType()); $res->headers->set("Content-Length", strlen($asset->getBody())); if (isset($app["logger"]) and $app["logger"] !== null) { $app["logger"]->log("Pipe: Serving '$logicalPath'"); } return $res; }) ->assert("logicalPath", ".+") ->bind("pipe.assets"); } function boot(Application $app) { if (isset($app["twig"])) { $app["twig"]->addExtension(new PipeTwigExtension); } } }
<?php namespace Pipe\Silex; use Silex\Application; use Silex\ServiceProviderInterface; use Symfony\Component\HttpFoundation\Response; class PipeServiceProvider implements ServiceProviderInterface { function register(Application $app) { $app->register(new \Silex\Provider\UrlGeneratorServiceProvider()); $app["pipe"] = $app->share(function($app) { return new PipeService($app); }); $app->get("/_pipe/assets/{logicalPath}", function($logicalPath) use ($app) { $asset = $app["pipe"]->environment->find($logicalPath); if (!$asset) { return $app->abort(404, "Asset '$logicalPath' not found"); } $res = new Response($asset->getBody(), 200); $res->headers->set("Content-Type", $asset->getContentType()); $res->headers->set("Content-Length", strlen($asset->getBody())); if (isset($app["logger"]) and $app["logger"] !== null) { $app["logger"]->log("Pipe: Serving '$logicalPath'"); } return $res; }) ->assert("logicalPath", ".+") ->bind("pipe.assets"); if (isset($app["twig"])) { $app["twig"]->addExtension(new PipeTwigExtension); } } function boot(Application $app) {} }
Add unit tests for update with a parameter.
/** * Copyright (C) 2011 Akiban Technologies Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses. */ package com.akiban.sql.optimizer; import com.akiban.sql.compiler.TypeComputer; import com.akiban.sql.parser.*; import com.akiban.sql.StandardException; import com.akiban.sql.types.DataTypeDescriptor; /** Calculate types from schema information. */ public class AISTypeComputer extends TypeComputer { public AISTypeComputer() { } @Override protected DataTypeDescriptor computeType(ValueNode node) throws StandardException { switch (node.getNodeType()) { case NodeTypes.COLUMN_REFERENCE: return columnReference((ColumnReference)node); default: return super.computeType(node); } } protected DataTypeDescriptor columnReference(ColumnReference node) throws StandardException { ColumnBinding columnBinding = (ColumnBinding)node.getUserData(); assert (columnBinding != null) : "column is not bound yet"; return columnBinding.getType(); } }
/** * Copyright (C) 2011 Akiban Technologies Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses. */ package com.akiban.sql.optimizer; import com.akiban.sql.compiler.TypeComputer; import com.akiban.sql.parser.*; import com.akiban.sql.StandardException; import com.akiban.sql.types.DataTypeDescriptor; /** Calculate types from schema information. */ public class AISTypeComputer extends TypeComputer { public AISTypeComputer() { } protected DataTypeDescriptor computeType(ValueNode node) throws StandardException { switch (node.getNodeType()) { case NodeTypes.COLUMN_REFERENCE: return columnReference((ColumnReference)node); default: return super.computeType(node); } } protected DataTypeDescriptor columnReference(ColumnReference node) throws StandardException { ColumnBinding columnBinding = (ColumnBinding)node.getUserData(); assert (columnBinding != null) : "column is not bound yet"; return columnBinding.getType(); } }
Revert "Remove dependency that was fixed upstream" This reverts commit 9ee219d85849629eac53a28e72fa374a6c805ea4.
#!/usr/bin/env python import os import re from setuptools import setup, find_packages def get_ini_variable(name): with open(os.path.join(os.path.dirname(__file__), 'src', 'ros_get', '__init__.py')) as f: return re.compile(r".*%s = '(.*?)'" % name, re.S).match(f.read()).group(1) with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as r_file: readme = r_file.read() setup( name='ros_get', license='MIT', version=get_ini_variable('__version__'), url=get_ini_variable('__url__'), author=get_ini_variable('__author__'), author_email=get_ini_variable('__email__'), description='Simple tools for working with ROS source packages', long_description=readme, package_dir={'': 'src'}, # tell distutils packages are under src packages=find_packages('src'), # include all packages under src install_requires=[ 'argcomplete', 'catkin_pkg', 'catkin_tools', 'colorlog', 'future', 'mock', 'rosdep', 'rosdistro >= 0.6.8', 'rosinstall_generator', 'trollius', # remove when catkin>0.4.4 is released 'vcstools', 'xdg==1.0.7', ], entry_points={'console_scripts': ['ros-get=ros_get.__main__:main']}, )
#!/usr/bin/env python import os import re from setuptools import setup, find_packages def get_ini_variable(name): with open(os.path.join(os.path.dirname(__file__), 'src', 'ros_get', '__init__.py')) as f: return re.compile(r".*%s = '(.*?)'" % name, re.S).match(f.read()).group(1) with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as r_file: readme = r_file.read() setup( name='ros_get', license='MIT', version=get_ini_variable('__version__'), url=get_ini_variable('__url__'), author=get_ini_variable('__author__'), author_email=get_ini_variable('__email__'), description='Simple tools for working with ROS source packages', long_description=readme, package_dir={'': 'src'}, # tell distutils packages are under src packages=find_packages('src'), # include all packages under src install_requires=[ 'argcomplete', 'catkin_pkg', 'catkin_tools', 'colorlog', 'future', 'mock', 'rosdep', 'rosdistro >= 0.6.8', 'rosinstall_generator', 'vcstools', 'xdg==1.0.7', ], entry_points={'console_scripts': ['ros-get=ros_get.__main__:main']}, )
Save in the same place inside 'state', 'selected' & 'dragging' element
export const updateElementInWorkspace = (workspace, payload) => { const { selectionState } = workspace if(!selectionState.dragStarted) { return workspace } const { currentMousePosition } = payload const { element } = selectionState const originalElement = workspace.entities[element.id] return Object.assign({}, workspace, { ...workspace, entities: { ...workspace.entities, [element.id]: { ...originalElement, position: { x: element.startPosition.x + currentMousePosition.x - element.mouseDownPosition.x, y: element.startPosition.y + currentMousePosition.y - element.mouseDownPosition.y, } } } }) } export const addDragStartedToWorkspace = (workspace, payload) => { const { elementId, elementPosition, mousePosition } = payload return setDragStateToWorkspace( workspace, { dragStarted: true, element: { id: elementId, mouseDownPosition: mousePosition, startPosition: elementPosition } } ) } export const addDragStoppedToWorkspace = (workspace, payload) => { return setDragStateToWorkspace( workspace, { dragStarted: false } ) } export const setDragStateToWorkspace = (workspace, dragState) => { return Object.assign({}, workspace, { ...workspace, selectionState: { ...workspace.selectionState, ...dragState } }) }
export const updateElementInWorkspace = (workspace, payload) => { const { selectionState } = workspace if(!selectionState.dragStarted) { return workspace } const { currentMousePosition } = payload const { elementId, startElementPosition, startMousePosition } = selectionState const element = workspace.entities[elementId] return Object.assign({}, workspace, { ...workspace, entities: { ...workspace.entities, [elementId]: { ...element, position: { x: startElementPosition.x + currentMousePosition.x - startMousePosition.x, y: startElementPosition.y + currentMousePosition.y - startMousePosition.y, } } } }) } export const addDragStartedToWorkspace = (workspace, payload) => { const { elementId, elementPosition, mousePosition } = payload return setDragStateToWorkspace( workspace, { dragStarted: true, elementId: elementId, startElementPosition: elementPosition, startMousePosition: mousePosition } ) } export const addDragStoppedToWorkspace = (workspace, payload) => { return setDragStateToWorkspace( workspace, { dragStarted: false } ) } export const setDragStateToWorkspace = (workspace, dragState) => { return Object.assign({}, workspace, { ...workspace, selectionState: { ...workspace.selectionState, ...dragState } }) }
Work on classical_risk test_case_1 and test_case_2
import unittest from nose.plugins.attrib import attr from openquake.qa_tests_data.classical_risk import ( case_1, case_2, case_3, case_4) from openquake.calculators.tests import CalculatorTestCase class ClassicalRiskTestCase(CalculatorTestCase): @attr('qa', 'risk', 'classical_risk') def test_case_1(self): out = self.run_calc(case_1.__file__, 'job_risk.ini', exports='xml') @attr('qa', 'risk', 'classical_risk') def test_case_2(self): raise unittest.SkipTest @attr('qa', 'risk', 'classical_risk') def test_case_3(self): out = self.run_calc(case_3.__file__, 'job_haz.ini,job_risk.ini', exports='csv') [fname] = out['avg_losses-rlzs', 'csv'] self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fname) @attr('qa', 'risk', 'classical_risk') def test_case_4(self): out = self.run_calc(case_4.__file__, 'job_haz.ini,job_risk.ini', exports='csv') fnames = out['avg_losses-rlzs', 'csv'] self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fnames[0]) self.assertEqualFiles('expected/rlz-001-avg_loss.csv', fnames[1])
import unittest from nose.plugins.attrib import attr from openquake.qa_tests_data.classical_risk import ( case_1, case_2, case_3, case_4) from openquake.calculators.tests import CalculatorTestCase class ClassicalRiskTestCase(CalculatorTestCase): @attr('qa', 'risk', 'classical_risk') def test_case_1(self): raise unittest.SkipTest @attr('qa', 'risk', 'classical_risk') def test_case_2(self): raise unittest.SkipTest @attr('qa', 'risk', 'classical_risk') def test_case_3(self): out = self.run_calc(case_3.__file__, 'job_haz.ini,job_risk.ini', exports='csv') [fname] = out['avg_losses-rlzs', 'csv'] self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fname) @attr('qa', 'risk', 'classical_risk') def test_case_4(self): out = self.run_calc(case_4.__file__, 'job_haz.ini,job_risk.ini', exports='csv') fnames = out['avg_losses-rlzs', 'csv'] self.assertEqualFiles('expected/rlz-000-avg_loss.csv', fnames[0]) self.assertEqualFiles('expected/rlz-001-avg_loss.csv', fnames[1])
Improve by using breadth search instead of depth search
<?php class AlgorithmConnectedComponents extends Algorithm{ /** * * @var Graph */ private $graph; /** * * @param Graph $graph */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * check whether this graph consists of only a single component * * could be improved by not checking for actual number of components but stopping when there's more than one * * @return boolean * @uses AlgorithmSearchBreadthFirst::getNumberOfVertices() */ public function isSingle(){ $alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst()); return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices()); } /** * @return int number of components * @uses Graph::getVertices() * @uses AlgorithmSearchBreadthFirst::getVerticesIds() */ public function getNumberOfComponents(){ $visitedVertices = array(); $components = 0; foreach ($this->graph->getVertices() as $vid=>$vertex){ //for each vertices if ( ! isset( $visitedVertices[$vid] ) ){ //did I visit this vertex before? $alg = new AlgorithmSearchBreadthFirst($vertex); $newVertices = $alg->getVerticesIds(); //get all vertices of this component ++$components; foreach ($newVertices as $vid){ //mark the vertices of this component as visited $visitedVertices[$vid] = true; } } } return $components; //return number of components } }
<?php class AlgorithmConnectedComponents extends Algorithm{ /** * * @var Graph */ private $graph; /** * * @param Graph $graph */ public function __construct(Graph $graph){ $this->graph = $graph; } /** * check whether this graph consists of only a single component * * could be improved by not checking for actual number of components but stopping when there's more than one * * @return boolean * @uses AlgorithmSearchBreadthFirst::getNumberOfVertices() */ public function isSingle(){ $alg = new AlgorithmSearchBreadthFirst($this->graph->getVertexFirst()); return ($this->graph->getNumberOfVertices() === $alg->getNumberOfVertices()); } /** * @return int number of components * @uses Graph::getVertices() * @uses AlgorithmSearchDepthFirst::getVertices() */ public function getNumberOfComponents(){ $visitedVertices = array(); $components = 0; foreach ($this->graph->getVertices() as $vertex){ //for each vertices if ( ! isset( $visitedVertices[$vertex->getId()] ) ){ //did I visit this vertex before? $alg = new AlgorithmSearchDepthFirst($vertex); $newVertices = $alg->getVertices(); //get all vertices of this component $components++; foreach ($newVertices as $v){ //mark the vertices of this component as visited $visitedVertices[$v->getId()] = true; } } } return $components; //return number of components } }
Complete refactoring, including addition of kind to all core objects
/* * See LICENSE file in distribution for copyright and licensing information. */ package ioke.lang; import java.util.IdentityHashMap; /** * * @author <a href="mailto:[email protected]">Ola Bini</a> */ public class Context extends IokeObject { IokeObject ground; public IokeObject message; public IokeObject surroundingContext; public Context(Runtime runtime, IokeObject ground, String documentation, IokeObject message, IokeObject surroundingContext) { super(runtime, documentation); this.ground = ground.getRealContext(); this.message = message; this.surroundingContext = surroundingContext; if(runtime.context != null) { this.mimics(runtime.context); } setCell("self", getRealContext()); } public void init() { setKind("Context"); } public IokeObject getRealContext() { return ground; } public IokeObject findCell(IokeObject m, IokeObject context, String name, IdentityHashMap<IokeObject, Object> visited) { IokeObject nn = super.findCell(m, context, name, visited); if(nn == runtime.nul) { return ground.findCell(m, context, name, visited); } else { return nn; } } @Override public String toString() { return "Context:" + System.identityHashCode(this) + "<" + ground + ">"; } }// Context
/* * See LICENSE file in distribution for copyright and licensing information. */ package ioke.lang; import java.util.IdentityHashMap; /** * * @author <a href="mailto:[email protected]">Ola Bini</a> */ public class Context extends IokeObject { IokeObject ground; public IokeObject message; public IokeObject surroundingContext; public Context(Runtime runtime, IokeObject ground, String documentation, IokeObject message, IokeObject surroundingContext) { super(runtime, documentation); this.ground = ground.getRealContext(); this.message = message; this.surroundingContext = surroundingContext; if(runtime.context != null) { this.mimics(runtime.context); } setCell("self", getRealContext()); } public void init() { } public IokeObject getRealContext() { return ground; } public IokeObject findCell(IokeObject m, IokeObject context, String name, IdentityHashMap<IokeObject, Object> visited) { IokeObject nn = super.findCell(m, context, name, visited); if(nn == runtime.nul) { return ground.findCell(m, context, name, visited); } else { return nn; } } @Override public String toString() { return "Context:" + System.identityHashCode(this) + "<" + ground + ">"; } }// Context
Add timezone settings to the test project.
import os local_path = lambda path: os.path.join(os.path.dirname(__file__), path) APP_ROOT = os.path.abspath( os.path.join(os.path.dirname(__file__), '..')) DEBUG = True SECRET_KEY = 'not-so-secret-for-tests' INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.humanize', 'name', 'tests'] ROOT_URLCONF = 'tests.urls' from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS TEMPLATE_CONTEXT_PROCESSORS += ( 'django.core.context_processors.request', 'name.context_processors.name') MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') # Minimal template settings for testing Django 1.8. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'name.context_processors.name' ], }, }, ] STATIC_URL = '/static/' TIME_ZONE = 'UTC' USE_TZ = True
import os local_path = lambda path: os.path.join(os.path.dirname(__file__), path) APP_ROOT = os.path.abspath( os.path.join(os.path.dirname(__file__), '..')) DEBUG = True SECRET_KEY = 'not-so-secret-for-tests' INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.humanize', 'name', 'tests'] ROOT_URLCONF = 'tests.urls' from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS TEMPLATE_CONTEXT_PROCESSORS += ( 'django.core.context_processors.request', 'name.context_processors.name') MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') # Minimal template settings for testing Django 1.8. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'name.context_processors.name' ], }, }, ] STATIC_URL = '/static/'
Fix logging of errors, Karma expects a string. Reset errors after every cycle.
(function() { var global = this; var karma = global.__karma__; karma.start = function(runner) { var suites = global.__karma_benchmark_suites__; var hasTests = !!suites.length; var errors = []; if (!hasTests) { return complete(); } runNextSuite(); function logResult(event) { var suite = this; var result = event.target; karma.result({ id: result.id, description: suite.name+': '+result.name, suite: [], success: errors.length === 0, log: errors, skipped: false, time: result.stats.mean * 1000, benchmark: { suite: suite.name, name: result.name, stats: result.stats, count: result.count, cycles: result.cycles, error: result.error, hz: result.hz } }); // Reset errors errors = []; } function logError(evt) { errors.push(evt.target.error.toString()); } function runNextSuite() { if (!suites.length) { return complete(); } suites.shift() .on('cycle', logResult) .on('abort error', logError) .on('complete', runNextSuite) .run({ async: true }); } function complete() { karma.complete({ coverage: global.__coverage__ }); } }; }).call(this);
(function() { var global = this; var karma = global.__karma__; karma.start = function(runner) { var suites = global.__karma_benchmark_suites__; var hasTests = !!suites.length; var errors = []; if (!hasTests) { return complete(); } runNextSuite(); function logResult(event) { var suite = this; var result = event.target; karma.result({ id: result.id, description: suite.name+': '+result.name, suite: [], success: errors.length === 0, log: errors, skipped: false, time: result.stats.mean * 1000, benchmark: { suite: suite.name, name: result.name, stats: result.stats, count: result.count, cycles: result.cycles, error: result.error, hz: result.hz } }); } function logError(evt) { errors.push(evt.target.error); } function runNextSuite() { if (!suites.length) { return complete(); } suites.shift() .on('cycle', logResult) .on('abort error', logError) .on('complete', runNextSuite) .run({ async: true }); } function complete() { karma.complete({ coverage: global.__coverage__ }); } }; }).call(this);
Correct bug to initialize mogodbUri
var mongo = require('mongodb'); var mongoUri = process.env.MONGOLAB_URI ||process.env.MONGOHQ_URL ||'mongodb://localhost/mydb'; if (process.env.VCAP_SERVICES) { var env = JSON.parse(process.env.VCAP_SERVICES); console.log('Env: ', env); mongoUri = env['mongodb-1.8'][0].credentials.url; } console.log('mongoUri: ', mongoUri); exports.mongoUri = mongoUri; exports.BSON = mongo.BSONPure; exports.cleardb = function(doneit) { mongo.Db.connect(mongoUri, function (err, db) { if (err) {return console.dir(err);} db.collection('events', function(err, collection) { if (err) {return console.dir(err);} collection.remove({},{w:1}, function(err, result) { if (err) {return console.dir(err);} db.collection('subscriptions', function(er, collection) { if (err) {return console.dir(err);} collection.remove({},{w:1}, function(err, result) { if (err) {return console.dir(err);} console.log('Event and Subscription records deleted'); db.close(); doneit(); }); }); }); }); }); }
var mongo = require('mongodb'); var mongoUri = process.env.MONGOLAB_URI ||process.env.MONGOHQ_URL ||'mongodb://localhost/mydb'; if (process.env.VCAP_SERVICES) { var env = JSON.parse(process.env.VCAP_SERVICES); console.log('Env: ', env); mongoUri = env['mongo-1.8'][0].credentials.url; } console.log('mongoUri: ', mongoUri); exports.mongoUri = mongoUri; exports.BSON = mongo.BSONPure; exports.cleardb = function(doneit) { mongo.Db.connect(mongoUri, function (err, db) { if (err) {return console.dir(err);} db.collection('events', function(err, collection) { if (err) {return console.dir(err);} collection.remove({},{w:1}, function(err, result) { if (err) {return console.dir(err);} db.collection('subscriptions', function(er, collection) { if (err) {return console.dir(err);} collection.remove({},{w:1}, function(err, result) { if (err) {return console.dir(err);} console.log('Event and Subscription records deleted'); db.close(); doneit(); }); }); }); }); }); }
Change name from MatrixData to DenseData
import numpy as np from sympy import IndexedBase class DenseData(IndexedBase): def __init__(self, name, shape, dtype): self.name = name self.shape = shape self.dtype = dtype self.pointer = None self.initializer = None def set_initializer(self, lambda_initializer): assert(callable(lambda_initializer)) self.initializer = lambda_initializer def initialize(self): assert(self.initializer is not None) self.initializer(self.data) def _allocate_memory(self): self.pointer = np.zeros(self.shape, self.dtype, order='C') @property def data(self): if self.pointer is None: self._allocate_memory() return self.pointer class TimeData(DenseData): def __init__(self, name, spc_shape, time_dim, time_order, save, dtype): if save: time_dim = time_dim + time_order else: time_dim = time_order + 1 shape = tuple((time_dim,) + spc_shape) super(TimeData, self).__init__(name, shape, dtype) self.save = save self.time_order = time_order def _allocate_memory(self): super(TimeData, self)._allocate_memory(self) if self.pad_time: self.pointer = self.pointer[self.time_order]
import numpy as np from sympy import IndexedBase class MatrixData(IndexedBase): def __init__(self, name, shape, dtype): self.name = name self.shape = shape self.dtype = dtype self.pointer = None self.initializer = None def set_initializer(self, lambda_initializer): assert(callable(lambda_initializer)) self.initializer = lambda_initializer def initialize(self): assert(self.initializer is not None) self.initializer(self.data) def _allocate_memory(self): self.pointer = np.zeros(self.shape, self.dtype, order='C') @property def data(self): if self.pointer is None: self._allocate_memory() return self.pointer class TimeData(MatrixData): def __init__(self, name, spc_shape, time_dim, time_order, save, dtype): if save: time_dim = time_dim + time_order else: time_dim = time_order + 1 shape = tuple((time_dim,) + spc_shape) super(TimeData, self).__init__(name, shape, dtype) self.save = save self.time_order = time_order def _allocate_memory(self): MatrixData._allocate_memory(self) if self.pad_time: self.pointer = self.pointer[self.time_order]
Add ability to delete spending on spendings' index view
@extends('layout') @section('title', __('general.spendings')) @section('body') <div class="wrapper my-3"> <h2>{{ __('general.spendings') }}</h2> <div class="box mt-3"> @if (count($spendings)) @foreach ($spendings as $spending) <div class="box__section row"> <div class="row__column"> <div class="color-dark">{{ $spending->description }}</div> <div class="mt-1" style="font-size: 14px; font-weight: 600;">{{ $spending->formatted_happened_on }}</div> </div> <div class="row__column row__column--middle"> @if ($spending->tag) @include('partials.tag', ['payload' => $spending->tag]) @endif </div> <div class="row__column row__column--middle" style="color: red;">&euro; {{ $spending->formatted_amount }}</div> <div class="row__column row__column--middle row__column--compact"> <form method="POST" action="/spendings/{{ $spending->id }}"> {{ method_field('DELETE') }} {{ csrf_field() }} <button class="button link"> <i class="far fa-trash-alt"></i> </button> </form> </div> </div> @endforeach @else <div class="box__section text-center">You don't have any spendings</div> @endif </div> </div> @endsection
@extends('layout') @section('title', __('general.spendings')) @section('body') <div class="wrapper my-3"> <h2>{{ __('general.spendings') }}</h2> <div class="box mt-3"> @if (count($spendings)) @foreach ($spendings as $spending) <div class="box__section row"> <div class="row__column"> <div class="color-dark">{{ $spending->description }}</div> <div class="mt-1" style="font-size: 14px; font-weight: 600;">{{ $spending->formatted_happened_on }}</div> </div> <div class="row__column row__column--middle"> @if ($spending->tag) @include('partials.tag', ['payload' => $spending->tag]) @endif </div> <div class="row__column row__column--middle text-right" style="color: red;">&euro; {{ $spending->formatted_amount }}</div> </div> @endforeach @else <div class="box__section text-center">You don't have any spendings</div> @endif </div> </div> @endsection
Update some function syntax and add options to the downloadBox call
var utils = require("./lib/utils"); var tmp = require("tmp"); var path = require("path"); var Config = require("truffle-config"); var Box = { unbox: function(url, destination, options) { options = options || {}; options.logger = options.logger || { log: () => {} }; const downloadBoxOptions = { force: options.force, } return Promise.resolve() .then(() => { options.logger.log("Downloading..."); return utils.downloadBox(url, destination, downloadBoxOptions) }) .then(() => { options.logger.log("Unpacking..."); return utils.unpackBox(destination); }) .then((boxConfig) => { options.logger.log("Setting up..."); return utils.setupBox(boxConfig, destination) }) .then((boxConfig) => boxConfig); }, sandbox: function(name, callback) { var self = this; if (typeof name === "function") { callback = name; name = "default"; } tmp.dir(function(err, dir, cleanupCallback) { if (err) { return callback(err); } self.unbox("https://github.com/trufflesuite/truffle-init-" + name, dir) .then(function() { var config = Config.load(path.join(dir, "truffle.js"), {}); callback(null, config); }) .catch(callback); }); } }; module.exports = Box;
var utils = require("./lib/utils"); var tmp = require("tmp"); var path = require("path"); var Config = require("truffle-config"); var Box = { unbox: function(url, destination, options) { options = options || {}; options.logger = options.logger || {log: function() {}} return Promise.resolve() .then(function() { options.logger.log("Downloading..."); return utils.downloadBox(url, destination) }) .then(function() { options.logger.log("Unpacking..."); return utils.unpackBox(destination); }) .then(function(boxConfig) { options.logger.log("Setting up..."); return utils.setupBox(boxConfig, destination) }) .then(function(boxConfig) { return boxConfig; }); }, sandbox: function(name, callback) { var self = this; if (typeof name === "function") { callback = name; name = "default"; } tmp.dir(function(err, dir, cleanupCallback) { if (err) { return callback(err); } self.unbox("https://github.com/trufflesuite/truffle-init-" + name, dir) .then(function() { var config = Config.load(path.join(dir, "truffle.js"), {}); callback(null, config); }) .catch(callback); }); } }; module.exports = Box;
Call _set in next loop
import EventEmitter from 'events'; export default class Observer extends EventEmitter { constructor() { super(); this._name = null; this._model = null; this._value = null; this._format = (v) => v; this._handleSet = (e) => this._set(e); } destroy() { this._unbindModel(); } name(value) { if (value === null) { return this._name; } this._name = value; return this; } model(value = null) { if (value === null) { return this._model; } this._model = value; this._bindModel(); setTimeout(() => { this._set({ changed: false, name: this._name, value: value.get(this._name) }); }); return this; } format(value = null) { if (value === null) { return this._format; } this._format = value; return this; } value(itemValue = null) { if (itemValue === null) { return this._value; } this._value = itemValue; return this; } _bindModel() { if (this._model) { this._model.setMaxListeners(this._model.getMaxListeners() + 1); this._model.addListener('set', this._handleSet); } } _unbindModel() { if (this._model) { this._model.setMaxListeners(this._model.getMaxListeners() - 1); this._model.removeListener('set', this._handleSet); } } _set() {} }
import EventEmitter from 'events'; export default class Observer extends EventEmitter { constructor() { super(); this._name = null; this._model = null; this._value = null; this._format = (v) => v; this._handleSet = (e) => this._set(e); } destroy() { this._unbindModel(); } name(value) { if (value === null) { return this._name; } this._name = value; return this; } model(value = null) { if (value === null) { return this._model; } this._model = value; this._bindModel(); this._set({ changed: false, name: this._name, value: value.get(this._name) }); return this; } format(value = null) { if (value === null) { return this._format; } this._format = value; return this; } value(itemValue = null) { if (itemValue === null) { return this._value; } this._value = itemValue; return this; } _bindModel() { if (this._model) { this._model.setMaxListeners(this._model.getMaxListeners() + 1); this._model.addListener('set', this._handleSet); } } _unbindModel() { if (this._model) { this._model.setMaxListeners(this._model.getMaxListeners() - 1); this._model.removeListener('set', this._handleSet); } } _set() {} }
Add reducer cases for thread/board destroyed
import initialState from './initialState'; import { LOGO_SPIN_STARTED, LOGO_SPIN_ENDED, PAGE_SCROLL_STARTED, PAGE_SCROLL_ENDED, APP_INIT, STATUS_UPDATE, PROVIDER_CHANGE, BOARD_CHANGE, SCROLL_HEADER, THREAD_REQUESTED, THREAD_DESTROYED, BOARD_REQUESTED, BOARD_DESTROYED, } from '../constants'; export default function (state = initialState.status, action) { switch (action.type) { // case APP_INIT: // return Object.assign({}, state, { // isMainPage: true // }) case PAGE_SCROLL_STARTED: return Object.assign({}, state, { isScrolling: true, currentPage: action.payload }) case PAGE_SCROLL_ENDED: return Object.assign({}, state, { isScrolling: false, currentPage: action.payload }) case SCROLL_HEADER: return Object.assign({}, state, { isHeaderVisible: action.payload }) case PROVIDER_CHANGE: return Object.assign({}, state, { provider: action.payload }) case BOARD_REQUESTED: return Object.assign({}, state, { boardID: action.payload }) case THREAD_REQUESTED: return Object.assign({}, state, { threadID: action.payload }) case STATUS_UPDATE: return Object.assign({}, state, { alertMessage: action.payload }) case THREAD_DESTROYED: return Object.assign({}, state, { threadID: null }) case BOARD_DESTROYED: return Object.assign({}, state, { boardID: null }) default: return state } }
import initialState from './initialState'; import { LOGO_SPIN_STARTED, LOGO_SPIN_ENDED, PAGE_SCROLL_STARTED, PAGE_SCROLL_ENDED, APP_INIT, STATUS_UPDATE, PROVIDER_CHANGE, BOARD_CHANGE, SCROLL_HEADER, THREAD_REQUESTED, BOARD_REQUESTED, } from '../constants'; export default function (state = initialState.status, action) { switch (action.type) { // case APP_INIT: // return Object.assign({}, state, { // isMainPage: true // }) case PAGE_SCROLL_STARTED: return Object.assign({}, state, { isScrolling: true, currentPage: action.payload }) case PAGE_SCROLL_ENDED: return Object.assign({}, state, { isScrolling: false, currentPage: action.payload }) case SCROLL_HEADER: return Object.assign({}, state, { isHeaderVisible: action.payload }) case PROVIDER_CHANGE: return Object.assign({}, state, { provider: action.payload }) case BOARD_REQUESTED: return Object.assign({}, state, { boardID: action.payload }) case THREAD_REQUESTED: return Object.assign({}, state, { threadID: action.payload }) case STATUS_UPDATE: return Object.assign({}, state, { statusMessage: action.payload }) default: return state } }
Stop fetching items for each killmail since they are not necessary.
module.exports = (function() { var m = require('mithril') function zeroPad(num) { return num < 10 ? `0${num}` : num; } var zKillboard = {} zKillboard.fetchKillmails = function(solarSystems, from, to, page) { var solarSystemID = solarSystems.map(solarSystem => solarSystem.id).join(','); var startTime = `${from.getFullYear()}${zeroPad(from.getMonth() + 1)}${zeroPad(from.getDate())}${zeroPad(from.getHours())}${zeroPad(from.getMinutes())}`; var endTime = `${to.getFullYear()}${zeroPad(to.getMonth() + 1)}${zeroPad(to.getDate())}${zeroPad(to.getHours())}${zeroPad(to.getMinutes())}`; return m.request({ method: 'GET', url: `https://zkillboard.com/api/solarSystemID/${solarSystemID}/startTime/${startTime}/endTime/${endTime}/page/${page}/no-items/`, background: true }) }; zKillboard.fetchAll = function(solarSystemID, from, to) { var deferred = m.deferred(), kms = []; function go(page) { zKillboard.fetchKillmails(solarSystemID, from, to, page) .then(data => { kms = kms.concat(data) if (data.length === 200) { go(page + 1) } else { deferred.resolve(kms) } }); } go(1); return deferred.promise; } return zKillboard; })();
module.exports = (function() { var m = require('mithril') function zeroPad(num) { return num < 10 ? `0${num}` : num; } var zKillboard = {} zKillboard.fetchKillmails = function(solarSystems, from, to, page) { var solarSystemID = solarSystems.map(solarSystem => solarSystem.id).join(','); var startTime = `${from.getFullYear()}${zeroPad(from.getMonth() + 1)}${zeroPad(from.getDate())}${zeroPad(from.getHours())}${zeroPad(from.getMinutes())}`; var endTime = `${to.getFullYear()}${zeroPad(to.getMonth() + 1)}${zeroPad(to.getDate())}${zeroPad(to.getHours())}${zeroPad(to.getMinutes())}`; return m.request({ method: 'GET', url: `https://zkillboard.com/api/solarSystemID/${solarSystemID}/startTime/${startTime}/endTime/${endTime}/page/${page}/`, background: true }) }; zKillboard.fetchAll = function(solarSystemID, from, to) { var deferred = m.deferred(), kms = []; function go(page) { zKillboard.fetchKillmails(solarSystemID, from, to, page) .then(data => { kms = kms.concat(data) if (data.length === 200) { go(page + 1) } else { deferred.resolve(kms) } }); } go(1); return deferred.promise; } return zKillboard; })();
Change a title of the option
module.exports = function() { return this .title('Benchmarks') .helpful() .arg() .name('treeish-list') .title('List of revisions to compare (git treeish)') .arr() .end() .opt() .name('benchmarks') .short('b').long('benchmark') .arr() .title('List of benchmarks to run') .end() .opt() .name('no-wc') .short('w').long('no-wc') .flag() .title('Run benchmarks without using working copy, use only specified revisions') .end() .opt() .name('rerun') .long('rerun') .flag() .title('Reuse previously checked out and made revisions, run benchmarks only') .end() .opt() .name('techs') .long('techs') .short('t') .title('Techs to run tests for') .arr() .end() .opt() .name('rme') .short('r').long('rme') .title('Delta for RME') .end() .opt() .name('delay') .short('d').long('delay') .title('Delay between benchmarks') .end() .act(function(opts,args) { return require('../bench')(opts, args).start(); }) .end(); };
module.exports = function() { return this .title('Benchmarks') .helpful() .arg() .name('treeish-list') .title('List of revisions to compare (git treeish)') .arr() .end() .opt() .name('benchmarks') .short('b').long('benchmark') .arr() .title('List of benchmarks to run') .end() .opt() .name('no-wc') .short('w').long('no-wc') .flag() .title('Run benchmarks without using working copy, use only specified revisions') .end() .opt() .name('rerun') .long('rerun') .flag() .title('Reuse previously checked out and made revisions, run benchmarks only') .end() .opt() .name('techs') .long('techs') .short('t') .title('Tech to run testing') .arr() .end() .opt() .name('rme') .short('r').long('rme') .title('Delta for RME') .end() .opt() .name('delay') .short('d').long('delay') .title('Delay between benchmarks') .end() .act(function(opts,args) { return require('../bench')(opts, args).start(); }) .end(); };
Add flag indicating method comes from chain execution
'use strict' export default class LodashWrapper { constructor (_) { this.steps = [] let step = 1 const record = (name, isChained, args, result) => { if (name === 'chain' || typeof (name) === 'undefined') { return } this.steps.push({ step: step++, funcName: name, args: JSON.stringify(args, null, 2), isChained, result: JSON.stringify(result, null, 2) }) } const availableFunctions = _.keys(_) const handler = { get: (original, propertyName) => { if (!availableFunctions.includes(propertyName)) { return original[propertyName] } // console.info(`Getting ${propertyName}`) original[propertyName].dexterLabFuncName = propertyName return new Proxy(original[propertyName], handler) }, apply: (original, thisArg, args) => { // console.info(`Calling ${original.dexterLabFuncName}`) const result = original.apply(thisArg, args) if (result.__wrapped__) { record(original.dexterLabFuncName, true, args, result.value()) return new Proxy(result, handler) } record(original.dexterLabFuncName, false, args, result) return result } } // let the Inception begins :-) this.lodash = new Proxy(_.runInContext(), handler) } get stats () { return this.steps } resetStats () { this.steps = [] } }
'use strict' export default class LodashWrapper { constructor (_) { this.steps = [] let step = 1 const record = (name, args, result) => { if (name === 'chain' || typeof (name) === 'undefined') { return } this.steps.push({ step: step++, funcName: name, args: JSON.stringify(args, null, 2), result: JSON.stringify(result, null, 2) }) } const availableFunctions = _.keys(_) const handler = { get: (original, propertyName) => { if (!availableFunctions.includes(propertyName)) { return original[propertyName] } // console.info(`Getting ${propertyName}`) original[propertyName].dexterLabFuncName = propertyName return new Proxy(original[propertyName], handler) }, apply: (original, thisArg, args) => { // console.info(`Calling ${original.dexterLabFuncName}`) const result = original.apply(thisArg, args) if (result.__wrapped__) { record(original.dexterLabFuncName, args, result.value()) return new Proxy(result, handler) } record(original.dexterLabFuncName, args, result) return result } } // let the Inception begins :-) this.lodash = new Proxy(_.runInContext(), handler) } get stats () { return this.steps } resetStats () { this.steps = [] } }
Fix typo at RSS bit
'use strict'; var moment = require('moment'); var _ = require('lodash'); var config = require('../config'); var paths = require('../elements/PathsMixin'); module.exports = function() { return t('feed', {xmlns: 'http://www.w3.org/2005/Atom'}, [ t('title', {}, config.title), t('link', {href: 'config.baseUrl' + 'atom.xml', rel: 'self'}, ' '), t('link', {href: config.baseUrl}, ' '), t('updated', {}, moment().format()), t('id', {}, config.baseUrl), t('author', {}, [ t('name', {}, config.author.name), t('email', {}, config.author.email), ]), _.map(paths.getAllPosts(), function(post, name) { return t('entry', {}, [ t('title', {}, post.title), t('link', {href: config.baseUrl + name}, ''), t('updated', {}, moment(post.date, 'YYYY-MM-DD').format()), t('content', {type: 'html'}, paths.getPostForPath(name)), ]); }).join('') ]); }; function t(name, attributes, content) { var attrStr = _.map(attributes, function(val, key) { return key + '=' + '"' + val + '"'; }).join(' '); if(_.isArray(content)) { content = content.join(''); } return '<' + name + ' ' + attrStr + '>' + content + '>/' + name + '>'; }
'use strict'; var moment = require('moment'); var _ = require('lodash'); var config = require('../config'); var paths = require('../elements/PathsMixin'); module.exports = function(page) { return t('feed', {xmlns: 'http://www.w3.org/2005/Atom'}, [ t('title', {}, config.title), t('link', {href: "#{config.baseUrl}atom.xml", rel: 'self'}, ' '), t('link', {href: config.baseUrl}, ' '), t('updated', {}, moment().format()), t('id', {}, config.baseUrl), t('author', {}, [ t('name', {}, config.author.name), t('email', {}, config.author.email), ]), _.map(paths.getAllPosts(), function(post, name) { return t('entry', {}, [ t('title', {}, post.title), t('link', {href: config.baseUrl + name}, ''), t('updated', {}, moment(post.date, 'YYYY-MM-DD').format()), t('content', {type: 'html'}, paths.getPostForPath(name)), ]); }).join('') ]); }; function t(name, attributes, content) { var attrStr = _.map(attributes, function(val, key) { return key + '=' + '"' + val + '"'; }).join(' '); if(_.isArray(content)) { content = content.join(''); } return '<' + name + ' ' + attrStr + '>' + content + '>/' + name + '>'; }
Make trigger name in .py match .yaml
from flask import request, Flask from st2reactor.sensor.base import Sensor class EchoFlaskSensor(Sensor): def __init__(self, sensor_service, config): super(EchoFlaskSensor, self).__init__( sensor_service=sensor_service, config=config ) self._host = '127.0.0.1' self._port = 5000 self._path = '/echo' self._log = self._sensor_service.get_logger(__name__) self._app = Flask(__name__) def setup(self): pass def run(self): @self._app.route(self._path, methods=['POST']) def echo(): payload = request.get_json(force=True) self._sensor_service.dispatch(trigger="examples.echoflasksensor", payload=payload) return request.data self._log.info('Listening for payload on http://{}:{}{}'.format( self._host, self._port, self._path)) self._app.run(host=self._host, port=self._port, threaded=True) def cleanup(self): pass def add_trigger(self, trigger): # This method is called when trigger is created pass def update_trigger(self, trigger): # This method is called when trigger is updated pass def remove_trigger(self, trigger): # This method is called when trigger is deleted pass
from flask import request, Flask from st2reactor.sensor.base import Sensor class EchoFlaskSensor(Sensor): def __init__(self, sensor_service, config): super(EchoFlaskSensor, self).__init__( sensor_service=sensor_service, config=config ) self._host = '127.0.0.1' self._port = 5000 self._path = '/echo' self._log = self._sensor_service.get_logger(__name__) self._app = Flask(__name__) def setup(self): pass def run(self): @self._app.route(self._path, methods=['POST']) def echo(): payload = request.get_json(force=True) self._sensor_service.dispatch(trigger="examples.echo_flask", payload=payload) return request.data self._log.info('Listening for payload on http://{}:{}{}'.format( self._host, self._port, self._path)) self._app.run(host=self._host, port=self._port, threaded=True) def cleanup(self): pass def add_trigger(self, trigger): # This method is called when trigger is created pass def update_trigger(self, trigger): # This method is called when trigger is updated pass def remove_trigger(self, trigger): # This method is called when trigger is deleted pass
Fix not using right debugging method
/* eslint-disable no-console */ const debug = (...args) => console.log('[Service Worker]', ...args); const isCacheableRequest = request => request.method === 'GET' && !new URL(request.url).search.match(/[?&]nocache[&$]/); self.addEventListener('install', () => debug('Installed')); self.addEventListener('activate', () => debug('Activated')); let nextFetchId = 1; self.addEventListener('fetch', event => { const fetchId = nextFetchId++; const fetchDebug = (...args) => debug('[Fetch #' + fetchId + ']', ...args); fetchDebug(event.request); if (!isCacheableRequest(event.request)) { fetchDebug('Ignored (marked as not cacheable)'); return; } event.respondWith( fetch(event.request).then( response => { fetchDebug(response); const responseClone = response.clone(); caches.open('v1').then(cache => cache.put(event.request, responseClone). then(() => fetchDebug('Cached')) ); return response; }, error => { fetchDebug(error); return caches.match(event.request).then(cachedResponse => { fetchDebug('Cached response', cachedResponse); return cachedResponse || error; }); } ) ); });
/* eslint-disable no-console */ const debug = (...args) => console.log('[Service Worker]', ...args); const isCacheableRequest = request => request.method === 'GET' && !new URL(request.url).search.match(/[?&]nocache[&$]/); self.addEventListener('install', () => debug('Installed')); self.addEventListener('activate', () => debug('Activated')); let nextFetchId = 1; self.addEventListener('fetch', event => { const fetchId = nextFetchId++; const fetchDebug = (...args) => debug('[Fetch #' + fetchId + ']', ...args); fetchDebug(event.request); if (!isCacheableRequest(event.request)) { fetchDebug('Ignored (marked as not cacheable)'); return; } event.respondWith( fetch(event.request).then( response => { fetchDebug(response); const responseClone = response.clone(); caches.open('v1').then(cache => cache.put(event.request, responseClone). then(() => fetchDebug('Cached')) ); return response; }, error => { debug(error); return caches.match(event.request).then(cachedResponse => { debug('Cached response', cachedResponse); return cachedResponse || error; }); } ) ); });
Convert temperatures to degrees Celsius.
/* global angular, console */ (function () { 'use strict'; angular .module('plotWidget') .controller('PlotWidgetController', PlotWidgetController); PlotWidgetController.$inject = ['$scope', 'weatherRestService']; function PlotWidgetController($scope, weatherRestService) { var vm = this; init(); // #################################################################### function init() { $scope.plotOptions = { showRangeSelector: true, title: $scope.quantity, color: 'rgb(42, 101, 212)', gridLineColor: 'rgb(200, 200, 200)', rangeSelectorPlotFillColor: '#575df5', rangeSelectorPlotStrokeColor: '#676877' }; } weatherRestService.data('2014-08-30', '2014-09-30', $scope.quantity) // weatherRestService.data(null, null, $scope.quantity) .then(function(data) { var newData = [], conversionFunc = function(v) { return v; }; if(/temp/i.test($scope.quantity)) { conversionFunc = function(v) { return (v-32)/1.8; }; $scope.plotOptions.ylabel = "Celsius"; } for(var i=0, len=data.data.timePoints.length; i<len; ++i) { newData.push([new Date(data.data.timePoints[i]), conversionFunc(data.data.dataPoints[i])]); } $scope.plotData = newData; }); } }());
/* global angular, console */ (function () { 'use strict'; angular .module('plotWidget') .controller('PlotWidgetController', PlotWidgetController); PlotWidgetController.$inject = ['$scope', 'weatherRestService']; function PlotWidgetController($scope, weatherRestService) { var vm = this; init(); // #################################################################### function init() { $scope.plotOptions = { showRangeSelector: true, title: $scope.quantity, color: 'rgb(42, 101, 212)', gridLineColor: 'rgb(200, 200, 200)', rangeSelectorPlotFillColor: '#575df5', rangeSelectorPlotStrokeColor: '#676877' }; } weatherRestService.data('2014-08-30', '2014-08-31', $scope.quantity) // weatherRestService.data(null, null, 'inHumidity') .then(function(data) { var newData = []; for(var i=0, len=data.data.timePoints.length; i<len; ++i) { newData.push([new Date(data.data.timePoints[i]), data.data.dataPoints[i]]); } $scope.plotData = newData; }); } }());
Read More module: removed MainController check We don’t actually care if the controller is Main or not, since Admin also has a feed attribute that we can test.
<?php class ReadMore extends Modules { public function __init() { # Replace comment codes before markup modules filters them. $this->setPriority("markup_post_text", 4); } public function markup_post_text($text, $post = null) { if (!is_string($text) or !preg_match("/<!-- *more(.+?)?-->/i", $text, $matches)) return $text; $route = Route::current(); $controller = $route->controller; if (!isset($post) or $route->action == "view" or $controller->feed) return preg_replace("/<!-- *more(.+?)?-->/i", "", $text); $more = oneof(trim(fallback($matches[1])), __("&hellip;more", "read_more")); $url = (!$post->no_results) ? $post->url() : "#" ; $split = preg_split("/<!-- *more(.+?)?-->/i", $text, -1, PREG_SPLIT_NO_EMPTY); return $split[0].'<a class="read_more" href="'.$url.'">'.$more.'</a>'; } public function title_from_excerpt($text) { $split = preg_split('/<a class="read_more"/', $text); return $split[0]; } }
<?php class ReadMore extends Modules { public function __init() { # Replace comment codes before markup modules filters them. $this->setPriority("markup_post_text", 4); } public function markup_post_text($text, $post = null) { if (!is_string($text) or !preg_match("/<!-- *more(.+?)?-->/i", $text, $matches)) return $text; $route = Route::current(); $controller = $route->controller; if (!isset($post) or $route->action == "view" or ($controller instanceof MainController and $controller->feed)) return preg_replace("/<!-- *more(.+?)?-->/i", "", $text); $more = oneof(trim(fallback($matches[1])), __("&hellip;more", "read_more")); $url = (!$post->no_results) ? $post->url() : "#" ; $split = preg_split("/<!-- *more(.+?)?-->/i", $text, -1, PREG_SPLIT_NO_EMPTY); return $split[0].'<a class="read_more" href="'.$url.'">'.$more.'</a>'; } public function title_from_excerpt($text) { $split = preg_split('/<a class="read_more"/', $text); return $split[0]; } }
Remove ambiguity of desc ordering
// Author: tngan const request = require('superagent'); const path = require('path'); const url = require('url'); const DOMAIN = 'https://api.stackexchange.com'; const API_VERSION = '2.2'; function query(category) { // Internal functions const append = key => value => { this.queryParams = Object.assign(this.getDefaultQueryParams(), this.queryParams, { [key]: value }); return this; }; // this.queryParams = {}; this.getDefaultQueryParams = () => { const now = Date.now()/1000 | 0; return { order: 'asc', site: 'stackoverflow', pagesize: '100', fromdate: now, todate: now }; }; this.url = url.resolve(DOMAIN, path.join(API_VERSION, category)); // Public functions this.fromDate = append('fromdate'); this.toDate = append('todate'); this.order = append('order'); this.tagged = append('tagged'); this.site = append('site'); this.pageSize = append('pagesize'); this.page = append('page'); this.sort = append('sort'); this.site = append('site'); this.exec = callback => { request .get(this.url) .query(this.queryParams) .set('Accept', 'application/json') .end(callback); // Avoid memory leak delete this; }; } module.exports = function(category) { return new query(category); };
// Author: tngan const request = require('superagent'); const path = require('path'); const url = require('url'); const DOMAIN = 'https://api.stackexchange.com'; const API_VERSION = '2.2'; function query(category) { // Internal functions const append = key => value => { this.queryParams = Object.assign(this.getDefaultQueryParams(), this.queryParams, { [key]: value }); return this; }; // this.queryParams = {}; this.getDefaultQueryParams = () => { const now = Date.now()/1000 | 0; return { order: 'desc', site: 'stackoverflow', pagesize: '100', fromdate: now, todate: now }; }; this.url = url.resolve(DOMAIN, path.join(API_VERSION, category)); // Public functions this.fromDate = append('fromdate'); this.toDate = append('todate'); this.order = append('order'); this.tagged = append('tagged'); this.site = append('site'); this.pageSize = append('pagesize'); this.page = append('page'); this.sort = append('sort'); this.site = append('site'); this.exec = callback => { request .get(this.url) .query(this.queryParams) .set('Accept', 'application/json') .end(callback); // Avoid memory leak delete this; }; } module.exports = function(category) { return new query(category); };
Fix Pagerfanta adapter result caching
<?php namespace Brouzie\Sphinxy\Pagerfanta\Adapter; use Brouzie\Sphinxy\Query\ResultSet; use Brouzie\Sphinxy\QueryBuilder; use Pagerfanta\Adapter\AdapterInterface; /** * Sphinxy Pagerfanta Adapter * * @author Konstantin.Myakshin <[email protected]> */ class SphinxyQbAdapter implements AdapterInterface { /** * @var QueryBuilder */ protected $qb; /** * @var ResultSet|null */ protected $previousResultSet; public function __construct(QueryBuilder $qb) { $this->qb = $qb; } /** * @inheritdoc */ public function getNbResults() { if (null !== $this->previousResultSet) { return $this->previousResultSet->getAllowedCount(); } return $this->qb ->setMaxResults(1) ->setFirstResult(0) ->getResult() ->getAllowedCount(); } /** * @inheritdoc */ public function getSlice($offset, $length) { $this->previousResultSet = $this->qb ->setMaxResults($length) ->setFirstResult($offset) ->getResult(); return $this->previousResultSet->getIterator(); } /** * @return ResultSet|null */ public function getPreviousResultSet() { return $this->previousResultSet; } }
<?php namespace Brouzie\Sphinxy\Pagerfanta\Adapter; use Brouzie\Sphinxy\Query\ResultSet; use Brouzie\Sphinxy\QueryBuilder; use Pagerfanta\Adapter\AdapterInterface; /** * Sphinxy Pagerfanta Adapter * * @author Konstantin.Myakshin <[email protected]> */ class SphinxyQbAdapter implements AdapterInterface { /** * @var QueryBuilder */ protected $qb; /** * @var ResultSet|null */ protected $previousResultSet; public function __construct(QueryBuilder $qb) { $this->qb = $qb; } /** * @inheritdoc */ public function getNbResults() { if (null !== $this->previousResultSet) { return $this->previousResultSet->getAllowedCount(); } $this->getSlice(0, 1); return $this->previousResultSet->getAllowedCount(); } /** * @inheritdoc */ public function getSlice($offset, $length) { $this->previousResultSet = $this ->qb ->setMaxResults($length) ->setFirstResult($offset) ->getResult(); return $this->previousResultSet->getIterator(); } /** * @return ResultSet|null */ public function getPreviousResultSet() { return $this->previousResultSet; } }
Remove a debugging print that should never have been left there anyway.
from django.conf import settings import importlib # Merge two lots of mesobox-compatible context additions def merge_context_additions(additions): context = {} boxes = {} for c in additions: try: context.update(c.get("context")) except TypeError: pass try: for k, v in c.get("boxes").items(): if k in boxes: boxes[k].append(v) else: boxes[k] = v except TypeError: pass except AttributeError: pass return {"context": context, "boxes": boxes} def context_processor(request): additions = {} # Get the boxes and accompanying context additions from all the installed apps. for app in settings.INSTALLED_APPS: try: module = importlib.import_module(app+".boxes") except ImportError: continue # Run each function now. for b in module.BOX_INCLUDES: b_func = getattr(module, b) if not b_func: raise Exception("Method %s not implemented in module %s" % (b, app)) additions = merge_context_additions([additions, b_func(request)]) # Merge boxes down to being part of the context additions dict now they have all been assembled result = additions['context'] result['boxes'] = additions['boxes'] return result
from django.conf import settings import importlib # Merge two lots of mesobox-compatible context additions def merge_context_additions(additions): context = {} boxes = {} for c in additions: try: context.update(c.get("context")) except TypeError: pass try: for k, v in c.get("boxes").items(): if k in boxes: boxes[k].append(v) else: boxes[k] = v except TypeError: pass except AttributeError: pass return {"context": context, "boxes": boxes} def context_processor(request): additions = {} # Get the boxes and accompanying context additions from all the installed apps. for app in settings.INSTALLED_APPS: print(app) try: module = importlib.import_module(app+".boxes") except ImportError: continue # Run each function now. for b in module.BOX_INCLUDES: b_func = getattr(module, b) if not b_func: raise Exception("Method %s not implemented in module %s" % (b, app)) additions = merge_context_additions([additions, b_func(request)]) # Merge boxes down to being part of the context additions dict now they have all been assembled result = additions['context'] result['boxes'] = additions['boxes'] return result
Refactor build and print method
from ListNode import * class Solution(): def addTwoNumbers(self, l1, l2): head_node = current_node = ListNode(None) carry = 0 p = l1 q = l2 while p or q or carry: x = y = 0 if p is not None: x = p.val p = p.next if q is not None: y = q.val q = q.next sum = x + y + carry sum, carry = sum % 10, int(sum / 10) current_node.next = ListNode(sum) current_node = current_node.next return head_node.next def buildTree(nums): head = node = ListNode(None) for num in nums: node.next = ListNode(num) node = node.next return head.next def printTree(node): while node: print(node.val, end='') node = node.next if node: print(' -> ', end='') print() if __name__ == '__main__': nums1 = [2, 4] nums2 = [2, 5, 9] printTree(Solution().addTwoNumbers(buildTree(nums1), buildTree(nums2)))
from ListNode import * class Solution(): def addTwoNumbers(self, l1, l2): current_node = ListNode(None) head_node = current_node carry = 0 p = l1 q = l2 while p or q or carry: x = y = 0 if p is not None: x = p.val p = p.next if q is not None: y = q.val q = q.next sum = x + y + carry sum, carry = sum % 10, int(sum / 10) current_node.next = ListNode(sum) current_node = current_node.next return head_node.next def buildTree(nums): node = ListNode(nums[0]) node.next = ListNode(nums[1]) node.next.next = ListNode(nums[2]) return node def printTree(node): print(node.val, "->", node.next.val, "->", node.next.next.val, sep=" ") if __name__ == "__main__": nums1 = [2, 4, 3] nums2 = [5, 6, 4] print( printTree(Solution().addTwoNumbers(buildTree(nums1), buildTree(nums2))))
Fix what seems to be a mistake in fromColorResAndDrawable Based off the name of the function, it seems that `fromColorResAndDrawable` should take in a `Drawable` object, not a `String` imageUrl.
package com.github.florent37.materialviewpager.header; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; /** * Created by florentchampigny on 10/06/15. */ public class HeaderDesign { protected int color; protected int colorRes; protected String imageUrl; protected Drawable drawable; private HeaderDesign() { } public static HeaderDesign fromColorAndUrl(@ColorInt int color, String imageUrl) { HeaderDesign headerDesign = new HeaderDesign(); headerDesign.color = color; headerDesign.imageUrl = imageUrl; return headerDesign; } public static HeaderDesign fromColorResAndUrl(@ColorRes int colorRes, String imageUrl) { HeaderDesign headerDesign = new HeaderDesign(); headerDesign.colorRes = colorRes; headerDesign.imageUrl = imageUrl; return headerDesign; } public static HeaderDesign fromColorAndDrawable(@ColorInt int color, Drawable drawable) { HeaderDesign headerDesign = new HeaderDesign(); headerDesign.drawable = drawable; headerDesign.color = color; return headerDesign; } public static HeaderDesign fromColorResAndDrawable(@ColorRes int colorRes, Drawable drawable) { HeaderDesign headerDesign = new HeaderDesign(); headerDesign.colorRes = colorRes; headerDesign.drawable = drawable; return headerDesign; } public int getColor() { return color; } public int getColorRes() { return colorRes; } public String getImageUrl() { return imageUrl; } public Drawable getDrawable() { return drawable; } }
package com.github.florent37.materialviewpager.header; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; /** * Created by florentchampigny on 10/06/15. */ public class HeaderDesign { protected int color; protected int colorRes; protected String imageUrl; protected Drawable drawable; private HeaderDesign() { } public static HeaderDesign fromColorAndUrl(@ColorInt int color, String imageUrl) { HeaderDesign headerDesign = new HeaderDesign(); headerDesign.color = color; headerDesign.imageUrl = imageUrl; return headerDesign; } public static HeaderDesign fromColorResAndUrl(@ColorRes int colorRes, String imageUrl) { HeaderDesign headerDesign = new HeaderDesign(); headerDesign.colorRes = colorRes; headerDesign.imageUrl = imageUrl; return headerDesign; } public static HeaderDesign fromColorAndDrawable(@ColorInt int color, Drawable drawable) { HeaderDesign headerDesign = new HeaderDesign(); headerDesign.drawable = drawable; headerDesign.color = color; return headerDesign; } public static HeaderDesign fromColorResAndDrawable(@ColorRes int colorRes, String imageUrl) { HeaderDesign headerDesign = new HeaderDesign(); headerDesign.colorRes = colorRes; headerDesign.imageUrl = imageUrl; return headerDesign; } public int getColor() { return color; } public int getColorRes() { return colorRes; } public String getImageUrl() { return imageUrl; } public Drawable getDrawable() { return drawable; } }
tests: Test IAM Policy with no "services" 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 = {} policy_json = construct_policy(pipeline_settings=settings) assert json.loads(policy_json) == {} 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 # 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)
Add constant for the poll timeout value and fix quotes https://bugzilla.redhat.com/show_bug.cgi?id=1393982
/* global miqSparkleOn miqSparkleOff showErrorMessage clearMessages */ var GitImport = { TASK_POLL_TIMEOUT: 1500, retrieveDatastoreClickHandler: function() { $('.git-retrieve-datastore').click(function(event) { event.preventDefault(); miqSparkleOn(); clearMessages(); $.post('retrieve_git_datastore', $('#retrieve-git-datastore-form').serialize(), function(data) { var parsedData = JSON.parse(data); var messages = parsedData.message; if (messages && messages.level === 'error') { showErrorMessage(messages.message); miqSparkleOff(); } else { GitImport.pollForGitTaskCompletion(parsedData); } }); }); }, pollForGitTaskCompletion: function(gitData) { $.get('check_git_task', gitData, function(data) { var parsedData = JSON.parse(data); if (parsedData.state) { setTimeout(GitImport.pollForGitTaskCompletion, GitImport.TASK_POLL_TIMEOUT, gitData); } else { GitImport.gitTaskCompleted(parsedData); } }); }, gitTaskCompleted: function(data) { if (data.success) { var postMessageData = { git_repo_id: data.git_repo_id, git_branches: data.git_branches, git_tags: data.git_tags, message: data.message }; parent.postMessage(postMessageData, '*'); } else { parent.postMessage({message: data.message}, '*'); } }, };
/* global miqSparkleOn miqSparkleOff showErrorMessage clearMessages */ var GitImport = { retrieveDatastoreClickHandler: function() { $('.git-retrieve-datastore').click(function(event) { event.preventDefault(); miqSparkleOn(); clearMessages(); $.post('retrieve_git_datastore', $('#retrieve-git-datastore-form').serialize(), function(data) { var parsedData = JSON.parse(data); var messages = parsedData.message; if (messages && messages.level === "error") { showErrorMessage(messages.message); miqSparkleOff(); } else { GitImport.pollForGitTaskCompletion(parsedData); } }); }); }, pollForGitTaskCompletion: function(gitData) { $.get('check_git_task', gitData, function(data) { var parsedData = JSON.parse(data); if (parsedData.state) { setTimeout(GitImport.pollForGitTaskCompletion, 1500, gitData); } else { GitImport.gitTaskCompleted(parsedData); } }); }, gitTaskCompleted: function(data) { if (data.success) { var postMessageData = { git_repo_id: data.git_repo_id, git_branches: data.git_branches, git_tags: data.git_tags, message: data.message }; parent.postMessage(postMessageData, '*'); } else { parent.postMessage({message: data.message}, '*'); } }, };
Fix dev status trove classifier.
import os import relman import setuptools BASEPATH = os.path.abspath(os.path.dirname(__file__)) def load_requirements(filename): """load requirements from a pip requirements file.""" lineiter = (line.strip() for line in open(os.path.join(BASEPATH, filename))) return [line for line in lineiter if line and not line.startswith("#")] setuptools.setup( name="relman", version=relman.__version__, description="Release manager", long_description='Release manager - Automation Toolkit', classifiers=[ "Topic :: Software Development :: Build Tools", "Topic :: Software Development :: Documentation", "Development Status :: 4 - Beta", "Operating System :: POSIX :: Linux", "Programming Language :: Python", "License :: Public Domain", "Intended Audience :: Developers", "Intended Audience :: System Administrators" ], keywords="jira confluence python", author="David Lapsley, Alex Chan", author_email="[email protected], [email protected]", url="http://www.cisco.com", license="ASL", packages=setuptools.find_packages(exclude=["tests"]), include_package_data=True, data_files=[ ('etc', ['etc/sample.cfg']), ], zip_safe=False, install_requires=load_requirements("requirements.txt"), test_suite="tests", entry_points={ "console_scripts": [ "relman = relman.main:run" ] } )
import os import relman import setuptools BASEPATH = os.path.abspath(os.path.dirname(__file__)) def load_requirements(filename): """load requirements from a pip requirements file.""" lineiter = (line.strip() for line in open(os.path.join(BASEPATH, filename))) return [line for line in lineiter if line and not line.startswith("#")] setuptools.setup( name="relman", version=relman.__version__, description="Release manager", long_description='Release manager - Automation Toolkit', classifiers=[ "Topic :: Software Development :: Build Tools", "Topic :: Software Development :: Documentation" "Development Status :: 4 - Beta", "Operating System :: POSIX :: Linux", "Programming Language :: Python", "License :: Public Domain", "Intended Audience :: Developers", "Intended Audience :: System Administrators" ], keywords="jira confluence python", author="David Lapsley, Alex Chan", author_email="[email protected], [email protected]", url="http://www.cisco.com", license="ASL", packages=setuptools.find_packages(exclude=["tests"]), include_package_data=True, data_files=[ ('etc', ['etc/sample.cfg']), ], zip_safe=False, install_requires=load_requirements("requirements.txt"), test_suite="tests", entry_points={ "console_scripts": [ "relman = relman.main:run" ] } )
Add a test for CmdRunner.
from nose.tools import * from libeeyore.cpp.cppcompiler import CppCompiler from libeeyore.cpp.cmdrunner import CmdRunner class FakeProcess( object ): def __init__( self, sys_op, retcode ): self.sys_op = sys_op self.returncode = retcode def communicate( self, inp = None ): if inp is None: istr = "" else: istr = inp self.sys_op.calls.append( "communicate(%s)" % istr ) return "", "" class FakeSystemOperations( object ): def __init__( self, retcode = 0 ): self.calls = [] self.retcode = retcode def Popen( self, args, stdin = None ): self.calls.append( "Popen(%s)" % ",".join( args ) ) return FakeProcess( self, self.retcode ) def test_CppCompiler_success(): fs = FakeSystemOperations() c = CppCompiler( fs ) c.run( "myprog", "testexe" ) assert_equal( fs.calls, [ "Popen(g++,-x,c++,-o,testexe,-)", "communicate(myprog)", ] ) # TODO: not just an exception @raises( Exception ) def test_CppCompiler_failure(): fs = FakeSystemOperations( 1 ) c = CppCompiler( fs ) c.run( "myprog", "testexe" ) def test_CmdRunner(): fs = FakeSystemOperations( 3 ) r = CmdRunner( fs ) retcode = r.run( "exename" ) assert_equal( fs.calls, [ "Popen(exename)", "communicate()", ] ) assert_equal( retcode, 3 )
from nose.tools import * from libeeyore.cpp.cppcompiler import CppCompiler class FakeProcess( object ): def __init__( self, sys_op, retcode ): self.sys_op = sys_op self.returncode = retcode def communicate( self, inp = None ): if inp is None: istr = "" else: istr = inp self.sys_op.calls.append( "communicate(%s)" % istr ) return "", "" class FakeSystemOperations( object ): def __init__( self, retcode = 0 ): self.calls = [] self.retcode = retcode def Popen( self, args, stdin = None ): self.calls.append( "Popen(%s)" % ",".join( args ) ) return FakeProcess( self, self.retcode ) def test_CppCompiler_success(): fs = FakeSystemOperations() c = CppCompiler( fs ) c.run( "myprog", "testexe" ) assert_equal( fs.calls, [ "Popen(g++,-x,c++,-o,testexe,-)", "communicate(myprog)", ] ) # TODO: not just an exception @raises( Exception ) def test_CppCompiler_failure(): fs = FakeSystemOperations( 1 ) c = CppCompiler( fs ) c.run( "myprog", "testexe" )
Set max connection pool limit
var path = require('path'), config; config = { production: { url: process.env.BASE_URL || 'http://blog.ertrzyiks.pl/', mail: {}, database: { client: 'postgres', connection: process.env.DATABASE_URL, pool: { min: 0, max: 2 } }, server: { host: '0.0.0.0', port: process.env.PORT }, storage: { active: 'ghost-cloudinary-store', 'ghost-cloudinary-store': { cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET } }, paths:{ contentPath: path.join(__dirname, '/content/') } }, development: { url: 'http://localhost:2368', mail: {}, fileStorage: true, database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-dev.db') }, debug: false }, server: { host: '0.0.0.0', port: '2368' }, paths: { contentPath: path.join(__dirname, '/content/') } } }; module.exports = config;
var path = require('path'), config; config = { production: { url: process.env.BASE_URL || 'http://blog.ertrzyiks.pl/', mail: {}, database: { client: 'postgres', connection: process.env.DATABASE_URL }, server: { host: '0.0.0.0', port: process.env.PORT }, storage: { active: 'ghost-cloudinary-store', 'ghost-cloudinary-store': { cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET } }, paths:{ contentPath: path.join(__dirname, '/content/') } }, development: { url: 'http://localhost:2368', mail: {}, fileStorage: true, database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-dev.db') }, debug: false }, server: { host: '0.0.0.0', port: '2368' }, paths: { contentPath: path.join(__dirname, '/content/') } } }; module.exports = config;
Terminate viz process at end of experiment.
'''Main file for running experiments. ''' import logging from cortex._lib import (config, data, exp, optimizer, setup_cortex, setup_experiment, train) from cortex._lib.utils import print_section import torch __author__ = 'R Devon Hjelm' __author_email__ = '[email protected]' logger = logging.getLogger('cortex') viz_process = None def run(model=None): '''Main function. ''' # Parse the command-line arguments try: args = setup_cortex(model=model) if args.command == 'setup': # Performs setup only. config.setup() exit(0) else: config.set_config() print_section('EXPERIMENT') model = setup_experiment(args, model=model) print_section('DATA') data.setup(**exp.ARGS['data']) print_section('NETWORKS') if args.reload and not args.load_models: pass else: model.build() if args.load_models: d = torch.load(args.load_models, map_location='cpu') for k in args.reloads: model.nets[k].load_state_dict(d['nets'][k].state_dict()) print_section('OPTIMIZER') optimizer.setup(model, **exp.ARGS['optimizer']) except KeyboardInterrupt: print('Cancelled') exit(0) train.main_loop(model, **exp.ARGS['train']) viz_process.terminate()
'''Main file for running experiments. ''' import logging from cortex._lib import (config, data, exp, optimizer, setup_cortex, setup_experiment, train) from cortex._lib.utils import print_section import torch __author__ = 'R Devon Hjelm' __author_email__ = '[email protected]' logger = logging.getLogger('cortex') viz_process = None def run(model=None): '''Main function. ''' # Parse the command-line arguments try: args = setup_cortex(model=model) if args.command == 'setup': # Performs setup only. config.setup() exit(0) else: config.set_config() print_section('EXPERIMENT') model = setup_experiment(args, model=model) print_section('DATA') data.setup(**exp.ARGS['data']) print_section('NETWORKS') if args.reload and not args.load_models: pass else: model.build() if args.load_models: d = torch.load(args.load_models, map_location='cpu') for k in args.reloads: model.nets[k].load_state_dict(d['nets'][k].state_dict()) print_section('OPTIMIZER') optimizer.setup(model, **exp.ARGS['optimizer']) except KeyboardInterrupt: print('Cancelled') exit(0) train.main_loop(model, **exp.ARGS['train'])
Change name of date to datetime
RESOURCE_METHODS = ['GET', 'POST', 'DELETE'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] schema = { 'name': { 'type': 'string', 'minlength': 3, 'maxlength': 50, 'required': True, }, 'datetime': { 'type': 'datetime', }, 'reference': { 'type': 'string', 'minlength': 2, 'maxlength': 50, 'required': True, }, 'details': { 'type': 'string', 'minlength': 0, 'maxlength': 300, 'required': False }, 'reporter': { 'type': 'string', 'minlength': 3, 'maxlength': 20, 'required': True, }, } event = { 'item_title': 'event', 'additional_lookup': { 'url': 'regex("[\w]+")', 'field': 'name', }, 'cache_control': 'max-age=10, must-revalidate', 'cache_expires': 10, 'resource_methods': ['GET', 'POST'], 'schema': schema } DOMAIN = { 'event': event, } MONGO_HOST = 'localhost' MONGO_PORT = 27017 MONGO_USERNAME = '' MONGO_PASSWORD = '' MONGO_DBNAME = 'historia'
RESOURCE_METHODS = ['GET', 'POST', 'DELETE'] ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE'] schema = { 'name': { 'type': 'string', 'minlength': 3, 'maxlength': 50, 'required': True, }, 'date': { 'type': 'datetime', }, 'reference': { 'type': 'string', 'minlength': 2, 'maxlength': 50, 'required': True, }, 'details': { 'type': 'string', 'minlength': 0, 'maxlength': 300, 'required': False }, 'reporter': { 'type': 'string', 'minlength': 3, 'maxlength': 20, 'required': True, }, } event = { 'item_title': 'event', 'additional_lookup': { 'url': 'regex("[\w]+")', 'field': 'name', }, 'cache_control': 'max-age=10, must-revalidate', 'cache_expires': 10, 'resource_methods': ['GET', 'POST'], 'schema': schema } DOMAIN = { 'event': event, } MONGO_HOST = 'localhost' MONGO_PORT = 27017 MONGO_USERNAME = '' MONGO_PASSWORD = '' MONGO_DBNAME = 'historia'
Add a new function to get value by key in a file content
<?php namespace Botonomous; use Botonomous\utility\FileUtility; /** * Class Dictionary. */ class Dictionary { const DICTIONARY_DIR = 'dictionary'; const DICTIONARY_FILE_SUFFIX = 'json'; private $data; /** * @param $key * * @throws \Exception * * @return array|mixed */ private function load($key) { $stopWordsPath = __DIR__.DIRECTORY_SEPARATOR.self::DICTIONARY_DIR.DIRECTORY_SEPARATOR.$key.'.'. self::DICTIONARY_FILE_SUFFIX; return (new FileUtility())->jsonFileToArray($stopWordsPath); } /** * @return array */ public function getData() { return $this->data; } /** * @param array $data */ public function setData(array $data) { $this->data = $data; } /** * @param $fileName * * @return mixed */ public function get($fileName) { $data = $this->getData(); if (!isset($data[$fileName])) { $data[$fileName] = $this->load($fileName); $this->setData($data); } return $data[$fileName]; } /** * Return value for the key in the file content. * * @param $fileName * @param $key * @param array $replacements * @return mixed * @throws \Exception */ public function getValueByKey($fileName, $key, $replacements = []) { $fileContent = $this->get($fileName); if (!array_key_exists($key, $fileContent)) { throw new \Exception("Key: '{$key}' does not exist in file: {$fileName}"); } $found = $fileContent[$key]; if (empty($replacements)) { return $found; } foreach ($replacements as $key => $value) { $found = str_replace('{'.$key.'}', $value, $found); } return $found; } }
<?php namespace Botonomous; use Botonomous\utility\FileUtility; /** * Class Dictionary. */ class Dictionary { const DICTIONARY_DIR = 'dictionary'; const DICTIONARY_FILE_SUFFIX = 'json'; private $data; /** * @param $key * * @throws \Exception * * @return array|mixed */ private function load($key) { $stopWordsPath = __DIR__.DIRECTORY_SEPARATOR.self::DICTIONARY_DIR.DIRECTORY_SEPARATOR.$key.'.'. self::DICTIONARY_FILE_SUFFIX; return (new FileUtility())->jsonFileToArray($stopWordsPath); } /** * @return array */ public function getData() { return $this->data; } /** * @param array $data */ public function setData(array $data) { $this->data = $data; } /** * @param $key * * @return mixed */ public function get($key) { $data = $this->getData(); if (!isset($data[$key])) { $data[$key] = $this->load($key); $this->setData($data); } return $data[$key]; } }
Fix the focus jump in post.
import React, { Component, PropTypes } from 'react'; import ReactDisqusComments from 'react-disqus-comments'; import Page from '../Page'; import styles from './index.scss'; const setOverflow = (overflow) => { const html = document.querySelector('html'); const body = document.body; html.style.overflow = overflow; body.style.overflow = overflow; } class Post extends Component { static propTypes = { head: PropTypes.object.isRequired, }; componentDidMount() { setOverflow('auto'); } componentWillUnmount() { setOverflow('hidden'); } render() { const { props } = this; // it's up to you to choose what to do with this layout ;) const pageDate = props.head.date ? new Date(props.head.date) : null; const author = props.head.author; return ( <main className={styles.main} tabIndex={-1} ref={e => this.main = e}> <article className={styles.article}> <Page {...props} header={ <header> <span>{author}, </span> <time key={pageDate.toISOString()}> { pageDate.toDateString() } </time> </header> } /> <ReactDisqusComments shortname='makersden-io' title={props.head.title} identifier={props.head.title.replace(/\s/g, '') + pageDate} /> </article> </main> ); } } export default Post;
import React, { Component, PropTypes } from 'react'; import ReactDisqusComments from 'react-disqus-comments'; import Page from '../Page'; import styles from './index.scss'; const setOverflow = (overflow) => { const html = document.querySelector('html'); const body = document.body; html.style.overflow = overflow; body.style.overflow = overflow; } class Post extends Component { static propTypes = { head: PropTypes.object.isRequired, }; componentDidMount() { this.main.focus(); setOverflow('auto'); } componentWillUnmount() { setOverflow('hidden'); } render() { const { props } = this; // it's up to you to choose what to do with this layout ;) const pageDate = props.head.date ? new Date(props.head.date) : null; const author = props.head.author; return ( <main className={styles.main} tabIndex={-1} ref={e => this.main = e}> <article className={styles.article}> <Page {...props} header={ <header> <span>{author}, </span> <time key={pageDate.toISOString()}> { pageDate.toDateString() } </time> </header> } /> <ReactDisqusComments shortname='makersden-io' title={props.head.title} identifier={props.head.title.replace(/\s/g, '') + pageDate} /> </article> </main> ); } } export default Post;
Fix bugs -- token is added into response json only when authentication succeeded and invalid username and password always show up even though username and password are correct
<?php /** * This file is Copyright (c). * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Component\Authentication; use Doctrine\ORM\EntityManager; use Component\Entity\User; use Component\Response\JsonResponse; class Authentication { private $entityManager; function __construct(EntityManager $entityManager) { $this->entityManager = $entityManager; } /** * @param string $username * @param string $password * @param string $token * @return JsonResponse */ public function verify($username, $password, $token) { $tokenNode = array(); if (!empty($token)) { $tokenNode["token"] = $token; } if (empty($username) || empty($password)) { return new JsonResponse("Insufficient argument", JsonResponse::BAD_REQUEST, array(), $tokenNode); } try { $userRepo = $this->entityManager->getRepository(User::getClassName()); if (empty($userRepo)) { return new JsonResponse("Invalid entity supplied.", JsonResponse::BAD_REQUEST, array(), $tokenNode); } $found = $userRepo->findOneBy(array("username" => $username)); if (!$found || !password_verify($password, $found->getPassword())) { return new JsonResponse("Invalid username or password.", JsonResponse::BAD_REQUEST, array(), $tokenNode); } return new JsonResponse("verified", JsonResponse::OK, array(), $tokenNode); } catch (\Exception $e) { return new JsonResponse($e->getMessage(), JsonResponse::INTERNAL_SERVER_ERROR); } } }
<?php /** * This file is Copyright (c). * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Component\Authentication; use Doctrine\ORM\EntityManager; use Component\Entity\User; use Component\Response\JsonResponse; class Authentication { private $entityManager; function __construct(EntityManager $entityManager) { $this->entityManager = $entityManager; } /** * @param string $username * @param string $password * @param string $token * @return JsonResponse */ public function verify($username, $password, $token) { if (empty($username) || empty($password)) { return new JsonResponse("Insufficient argument", JsonResponse::BAD_REQUEST); } try { $userRepo = $this->entityManager->getRepository(User::getClassName()); if (empty($userRepo)) { return new JsonResponse("Invalid entity supplied.", JsonResponse::BAD_REQUEST); } $found = $userRepo->findOneBy(array("username" => $username)); if (!$found || password_verify($password, $found->getPassword())) { return new JsonResponse("Invalid username or password.", JsonResponse::BAD_REQUEST); } return new JsonResponse("verified", JsonResponse::OK, array(), array("token" => $token)); } catch (\Exception $e) { return new JsonResponse($e->getMessage(), JsonResponse::INTERNAL_SERVER_ERROR); } } }
Switch the main post detail view to a CBV
from datetime import datetime from django.http import Http404 from django.shortcuts import get_object_or_404 from django.views.generic import ( ArchiveIndexView, YearArchiveView, MonthArchiveView, DetailView, ) from tinyblog.models import Post class TinyBlogPostView(DetailView): template_name = 'tinyblog/post.html' def get_object(self): post = get_object_or_404( Post, created__year=int(self.kwargs['year']), created__month=int(self.kwargs['month']), slug=self.kwargs['slug'] ) if post.created > datetime.now(): if not self.request.user.is_staff: raise Http404 return post post = TinyBlogPostView.as_view() class TinyBlogIndexView(ArchiveIndexView): date_field = 'created' def get_queryset(self): return Post.published_objects.all() index_view = TinyBlogIndexView.as_view() class TinyBlogYearView(YearArchiveView): date_field = 'created' make_object_list = True def get_queryset(self): return Post.published_objects.all() year_view = TinyBlogYearView.as_view() class TinyBlogMonthView(MonthArchiveView): date_field = 'created' month_format = '%m' def get_queryset(self): return Post.published_objects.all() month_view = TinyBlogMonthView.as_view()
from datetime import datetime from django.http import Http404 from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.views.generic import ( ArchiveIndexView, YearArchiveView, MonthArchiveView, ) from tinyblog.models import Post def post(request, year, month, slug): post = get_object_or_404(Post, created__year=year, created__month=month, slug=slug) if post.created > datetime.now(): if not request.user.is_staff: raise Http404 return render_to_response('tinyblog/post.html', {'post': post}, context_instance=RequestContext(request)) class TinyBlogIndexView(ArchiveIndexView): date_field = 'created' def get_queryset(self): return Post.published_objects.all() index_view = TinyBlogIndexView.as_view() class TinyBlogYearView(YearArchiveView): date_field = 'created' make_object_list = True def get_queryset(self): return Post.published_objects.all() year_view = TinyBlogYearView.as_view() class TinyBlogMonthView(MonthArchiveView): date_field = 'created' month_format = '%m' def get_queryset(self): return Post.published_objects.all() month_view = TinyBlogMonthView.as_view()
Set cookie if image uploaded
<?php require_once '../repository/ImageRepository.php'; /** * Siehe Dokumentation im DefaultController. */ class ImageController { public function index() { $imageRepository = new ImageRepository(); $view = new View('image_index'); $view->title = 'Upload'; $view->heading = 'Upload '; $view->image = $imageRepository->readAll(); $view->display(); } public function upload() { $imageRepository = new ImageRepository(); $view = new View('image_upload'); $view->title = 'Upload'; $view->heading = 'Upload'; $view->image = $imageRepository->readAll(); $view->display(); } public function doUpload() { if ($_POST['post']) { $title = $_POST['title']; $image = $_FILES['image']['name']; $image_path = $_FILES['image']['tmp_name']; $userid = 1; $imageRepository = new ImageRepository(); if (!$imageRepository->upload($title, $image, $image_path, $userid)){ header("Location: /image/upload"); }else { $value = "uploaded"; setcookie("imageUploaded", $value, time()+ 5); header("Location: /"); } } } }
<?php require_once '../repository/ImageRepository.php'; /** * Siehe Dokumentation im DefaultController. */ class ImageController { public function index() { $imageRepository = new ImageRepository(); $view = new View('image_index'); $view->title = 'Upload'; $view->heading = 'Upload '; $view->image = $imageRepository->readAll(); $view->display(); } public function upload() { $imageRepository = new ImageRepository(); $view = new View('image_upload'); $view->title = 'Upload'; $view->heading = 'Upload'; $view->image = $imageRepository->readAll(); $view->display(); } public function doUpload() { if ($_POST['post']) { $title = $_POST['title']; $image = $_FILES['image']['name']; $image_path = $_FILES['image']['tmp_name']; $userid = 1; $imageRepository = new ImageRepository(); if (!$imageRepository->upload($title, $image, $image_path, $userid)){ header("Location: /image/upload"); }else { header("Location: /"); } } } }
Fix ability to build prod static files
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'source-map', entry: { app: './lib/index.js' }, output: { filename: '[name].min.js', path: path.join(__dirname, 'dist'), publicPath: '' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.NoErrorsPlugin(), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') }, '__DEVTOOLS__': false }), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }), new ExtractTextPlugin('app.css', { allChunks: true }), new HtmlWebpackPlugin({ title: 'Fresh Food Connect', filename: 'index.html', template: 'index.template.html', favicon: path.join(__dirname, 'assets/images/favicon.ico') }) ], module: { loaders: [ { test: /\.scss$/, loader: 'style!css!sass' }, {test: /\.png$/, loader: "url-loader?mimetype=image/png"}, { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!cssnext-loader') }, { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ } ] }, cssnext: { browsers: 'last 2 versions' } };
var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'source-map', entry: { app: './lib/index.js' }, output: { filename: '[name].min.js', path: path.join(__dirname, 'dist'), publicPath: '' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.NoErrorsPlugin(), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') }, '__DEVTOOLS__': false }), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }), new ExtractTextPlugin('app.css', { allChunks: true }), new HtmlWebpackPlugin({ title: 'Fresh Food Connect', filename: 'index.html', template: 'index.template.html', favicon: path.join(__dirname, 'assets/images/favicon.ico') }) ], module: { loaders: [ { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!cssnext-loader') }, { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ } ] }, cssnext: { browsers: 'last 2 versions' } };
Enable SLURM allocation synchronization action.
// @ngInject export default function actionConfig(ActionConfigurationProvider, DEFAULT_EDIT_ACTION) { ActionConfigurationProvider.register('SLURM.Allocation', { order: [ 'details', 'pull', 'edit', 'cancel', 'destroy' ], options: { pull: { title: gettext('Synchronise') }, details: { title: gettext('Details'), component: 'slurmAllocationDetailsDialog', enabled: true, useResolve: true, type: 'form', dialogSize: 'lg', }, edit: angular.merge({}, DEFAULT_EDIT_ACTION, { successMessage: gettext('Allocation has been updated.'), fields: { cpu_limit: { type: 'integer', label: gettext('CPU limit, minutes'), required: true, resource_default_value: true, }, gpu_limit: { type: 'integer', label: gettext('GPU limit, minutes'), required: true, resource_default_value: true, }, ram_limit: { type: 'integer', label: gettext('RAM limit, MB'), required: true, resource_default_value: true, } } }), } }); }
// @ngInject export default function actionConfig(ActionConfigurationProvider, DEFAULT_EDIT_ACTION) { ActionConfigurationProvider.register('SLURM.Allocation', { order: [ 'details', 'edit', 'cancel', 'destroy' ], options: { details: { title: gettext('Details'), component: 'slurmAllocationDetailsDialog', enabled: true, useResolve: true, type: 'form', dialogSize: 'lg', }, edit: angular.merge({}, DEFAULT_EDIT_ACTION, { successMessage: gettext('Allocation has been updated.'), fields: { cpu_limit: { type: 'integer', label: gettext('CPU limit, minutes'), required: true, resource_default_value: true, }, gpu_limit: { type: 'integer', label: gettext('GPU limit, minutes'), required: true, resource_default_value: true, }, ram_limit: { type: 'integer', label: gettext('RAM limit, MB'), required: true, resource_default_value: true, } } }), } }); }
Replace log4j reference with Logback.
package com.yammer.dropwizard.json; import ch.qos.logback.classic.Level; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.Version; import org.codehaus.jackson.map.*; import org.codehaus.jackson.map.annotate.JsonCachable; import org.codehaus.jackson.type.JavaType; import java.io.IOException; class LogbackModule extends Module { @JsonCachable private static class LevelDeserializer extends JsonDeserializer<Level> { @Override public Level deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { final String text = jp.getText(); if ("false".equalsIgnoreCase(text)) { return Level.OFF; } if ("true".equalsIgnoreCase(text)) { return Level.ALL; } return Level.toLevel(text, Level.INFO); } } private static class LogbackDeserializers extends Deserializers.Base { @Override public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, DeserializerProvider provider, BeanDescription beanDesc, BeanProperty property) throws JsonMappingException { if (Level.class.isAssignableFrom(type.getRawClass())) { return new LevelDeserializer(); } return super.findBeanDeserializer(type, config, provider, beanDesc, property); } } @Override public String getModuleName() { return "LogbackModule"; } @Override public Version version() { return Version.unknownVersion(); } @Override public void setupModule(SetupContext context) { context.addDeserializers(new LogbackDeserializers()); } }
package com.yammer.dropwizard.json; import ch.qos.logback.classic.Level; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.Version; import org.codehaus.jackson.map.*; import org.codehaus.jackson.map.annotate.JsonCachable; import org.codehaus.jackson.type.JavaType; import java.io.IOException; class LogbackModule extends Module { @JsonCachable private static class LevelDeserializer extends JsonDeserializer<Level> { @Override public Level deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { final String text = jp.getText(); if ("false".equalsIgnoreCase(text)) { return Level.OFF; } if ("true".equalsIgnoreCase(text)) { return Level.ALL; } return Level.toLevel(text, Level.INFO); } } private static class LogbackDeserializers extends Deserializers.Base { @Override public JsonDeserializer<?> findBeanDeserializer(JavaType type, DeserializationConfig config, DeserializerProvider provider, BeanDescription beanDesc, BeanProperty property) throws JsonMappingException { if (Level.class.isAssignableFrom(type.getRawClass())) { return new LevelDeserializer(); } return super.findBeanDeserializer(type, config, provider, beanDesc, property); } } @Override public String getModuleName() { return "log4j"; } @Override public Version version() { return Version.unknownVersion(); } @Override public void setupModule(SetupContext context) { context.addDeserializers(new LogbackDeserializers()); } }
Add .min name to minified .js
'use strict'; var gulp = require('gulp'), nib = require('nib'), $ = require('gulp-load-plugins')({ lazy: false }); var paths = require('./paths.js'); module.exports = { copyAssets: function () { return function () { var assets = gulp.src(paths.src.assets) .pipe(gulp.dest(paths.dest.root)); return assets; }; }, buildHTML: function () { return function () { return gulp.src(paths.src.jade) // 'pretty' jade means uncompressed. .pipe($.jade({pretty: paths.isDev})) .pipe(gulp.dest(paths.dest.root)); }; }, buildCSS: function () { return function () { return gulp.src(paths.src.cssMaster) // 'nib' adds autoprefixing and some other niceties. .pipe($.stylus({use: nib(), compress: !paths.isDev})) .pipe($.if(paths.isDev, $.rename('app.css'), $.rename('app.min.css'))) .pipe(gulp.dest(paths.dest.root)); }; }, buildJS: function () { return function () { return gulp.src(paths.src.js) .pipe($.angularFilesort()) .pipe($.if(!paths.isDev, $.uglify({preserveComments: 'some'}))) .pipe($.rename({extname: '.min.js'})) .pipe(gulp.dest(paths.dest.root)); }; } };
'use strict'; // TODO: // - Rename to .min for minified js - get paths right for components. var gulp = require('gulp'), nib = require('nib'), $ = require('gulp-load-plugins')({ lazy: false }); var paths = require('./paths.js'); module.exports = { copyAssets: function () { return function () { var assets = gulp.src(paths.src.assets) .pipe(gulp.dest(paths.dest.root)); return assets; }; }, buildHTML: function () { return function () { return gulp.src(paths.src.jade) // 'pretty' jade means uncompressed. .pipe($.jade({pretty: paths.isDev})) .pipe(gulp.dest(paths.dest.root)); }; }, buildCSS: function () { return function () { return gulp.src(paths.src.cssMaster) // 'nib' adds autoprefixing and some other niceties. .pipe($.stylus({use: nib(), compress: !paths.isDev})) .pipe($.if(paths.isDev, $.rename('app.css'), $.rename('app.min.css'))) .pipe(gulp.dest(paths.dest.root)); }; }, buildJS: function () { return function () { return gulp.src(paths.src.js) .pipe($.angularFilesort()) .pipe($.if(!paths.isDev, $.uglify({preserveComments: 'some'}))) // .pipe($.if(!paths.isDev, $.rename('app.min.js'))) .pipe(gulp.dest(paths.dest.root)); }; }, };
Fix up grammar errors in the comments
(function(Backbone) { var superDelegateEvents = Backbone.View.prototype.delegateEvents; _.extend(Backbone.View.prototype, { // Hook up `listen` processing in `delegateEvents`. delegateEvents: function(events) { superDelegateEvents.call(this, events); this._setupListening(); }, // Take the value of the `listen` property and process it into // `listenTo` calls. `listen` should have the following form: // // `{object: {"event": "functionNameOrDeclaration"}}` // // `object` should have `Backbone.Events` mixed in and should be // available on `this` after `initialize` e.g. it can be created // in `initialize` or somewhere down the prototype chain. _setupListening: function() { var listen; if (!(listen = _.result(this, 'listen'))) return; this.stopListening(); for (var prop in listen) { var object = this[prop]; if (!object) throw new Error('Property "' + prop + '" does not exist'); var events = listen[prop]; for (var event in events) { var method = events[event]; if (!_.isFunction(method)) method = this[events[event]]; if (!method) throw new Error('Method "' + events[event] + '" does not exist'); this.listenTo(object, event, method); } } } }); }).call(this, Backbone);
(function(Backbone) { var superDelegateEvents = Backbone.View.prototype.delegateEvents; _.extend(Backbone.View.prototype, { // Hook up `listen` processing in `delegateEvents`. delegateEvents: function(events) { superDelegateEvents.call(this, events); this._setupListening(); }, // Take a the value of the `listen` property and process them into // `listenTo` calls. `listen` should have the following form: // // `{object: {"event": "functionNameOrDeclaration"}` // // `object` should have `Backbone.Events` mixed in and should be // available on `this` after `initialize` e.g. you can initialize // it in `initialize` or have somewhere on the prototype chain. _setupListening: function() { var listen; if (!(listen = _.result(this, 'listen'))) return; this.stopListening(); for (var prop in listen) { var object = this[prop]; if (!object) throw new Error('Property "' + prop + '" does not exist'); var events = listen[prop]; for (var event in events) { var method = events[event]; if (!_.isFunction(method)) method = this[events[event]]; if (!method) throw new Error('Method "' + events[event] + '" does not exist'); this.listenTo(object, event, method); } } } }); }).call(this, Backbone);
Change name of the default task
/** * @author Frank David Corona Prendes <[email protected]> * @copyright MIT 2016 Frank David Corona Prendes * @description Tarea Gulp para la compresion de ficheros JS * @version 1.0.1 */ (function () { 'use strict'; var gulp = require('gulp'); var uglify = require('gulp-uglify'); var pump = require('pump'); var argv = require('yargs').argv; var recursive = require('recursive-readdir'); var logger = require('gulp-logger'); gulp.task('default', function () { recursive('"' + [argv.source + '"' + '/**/*.js'], function (err, file) { var options = { mangle: false }; pump([ gulp.src([argv.source + '/**/*.js']) .pipe(logger({ before: 'Starting compression...', after: 'Compression complete!', showChange: true })) .pipe(uglify(options, uglify)), gulp.dest(argv.destino + '/dist/') ]); }); }); })();
/** * @author Frank David Corona Prendes <[email protected]> * @copyright MIT 2016 Frank David Corona Prendes * @description Tarea Gulp para la compresion de ficheros JS * @version 1.0.1 */ (function () { 'use strict'; var gulp = require('gulp'); var uglify = require('gulp-uglify'); var pump = require('pump'); var argv = require('yargs').argv; var recursive = require('recursive-readdir'); var logger = require('gulp-logger'); gulp.task('gcompress', function () { recursive('"' + [argv.source + '"' + '/**/*.js'], function (err, file) { var options = { mangle: false }; pump([ gulp.src([argv.source + '/**/*.js']) .pipe(logger({ before: 'Starting compression...', after: 'Compression complete!', showChange: true })) .pipe(uglify(options, uglify)), gulp.dest(argv.destino + '/dist/') ]); }); }); })();
Test against string version of ID.
'use strict'; const assert = require('assert'); const mongoose = require('mongoose'); mongoose.Promise = global.Promise; const dataSchema = new mongoose.Schema({ 'contents': String }); dataSchema.plugin(require('../../index')); const dataModel = mongoose.model('data', dataSchema); describe('createOrUpdate', () => { let dataId = null; before(done => { mongoose.connect('mongodb://localhost/test'); dataModel.find().remove(done); }); after(done => { dataModel.find().remove(() => { mongoose.connection.close(done); }); }); it('create without document', done => { dataModel.createOrUpdate({ '_id': dataId }, { 'contents': 'Lorem ipsum dolor sit amet' }).then(data => { dataId = data._id.toString(); done(); }).catch(err => { console.log(err); }); }); it('update with existing document', done => { dataModel.createOrUpdate({ '_id': dataId }, { 'contents': 'Hello, world!' }).then(data => { assert.equal(data._id.toString(), dataId); assert.equal(data.contents, 'Hello, world!'); done(); }).catch(err => { console.log(err); }); }); });
'use strict'; const assert = require('assert'); const mongoose = require('mongoose'); mongoose.Promise = global.Promise; const dataSchema = new mongoose.Schema({ 'contents': String }); dataSchema.plugin(require('../../index')); const dataModel = mongoose.model('data', dataSchema); describe('createOrUpdate', () => { let dataId = null; before(done => { mongoose.connect('mongodb://localhost/test'); dataModel.find().remove(done); }); after(done => { dataModel.find().remove(() => { mongoose.connection.close(done); }); }); it('create without document', done => { dataModel.createOrUpdate({ '_id': dataId }, { 'contents': 'Lorem ipsum dolor sit amet' }).then(data => { dataId = data._id; done(); }).catch(err => { console.log(err); }); }); it('update with existing document', done => { dataModel.createOrUpdate({ '_id': dataId }, { 'contents': 'Hello, world!' }).then(data => { assert.equal(data._id, dataId); assert.equal(data.contents, 'Hello, world!'); done(); }).catch(err => { console.log(err); }); }); });
Handle case where deconstruct receives string
""" Select widget for MonthField. Copied and modified from https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#base-widget-classes """ from datetime import date from django.forms import widgets class MonthSelectorWidget(widgets.MultiWidget): def __init__(self, attrs=None): # create choices for days, months, years # example below, the rest snipped for brevity. years = [(year, year) for year in range(2000, 2020)] months = [ (month, month) for month in range(1, 13)] _widgets = ( widgets.Select(attrs=attrs, choices=months), widgets.Select(attrs=attrs, choices=years), ) super(MonthSelectorWidget, self).__init__(_widgets, attrs) def decompress(self, value): if value: if isinstance(value, basestring): m = int(value[5:7]) y = int(value[:4]) return [ m, y ] return [value.month, value.year] return [ None, None] def format_output(self, rendered_widgets): return ''.join(rendered_widgets) def value_from_datadict(self, data, files, name): datelist = [ widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)] try: D = date(day=1, month=int(datelist[0]), year=int(datelist[1])) except ValueError: return '' else: return str(D)
""" Select widget for MonthField. Copied and modified from https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#base-widget-classes """ from datetime import date from django.forms import widgets class MonthSelectorWidget(widgets.MultiWidget): def __init__(self, attrs=None): # create choices for days, months, years # example below, the rest snipped for brevity. years = [(year, year) for year in range(2000, 2020)] months = [ (month, month) for month in range(1, 13)] _widgets = ( widgets.Select(attrs=attrs, choices=months), widgets.Select(attrs=attrs, choices=years), ) super(MonthSelectorWidget, self).__init__(_widgets, attrs) def decompress(self, value): if value: return [value.month, value.year] return [ None, None] def format_output(self, rendered_widgets): return ''.join(rendered_widgets) def value_from_datadict(self, data, files, name): datelist = [ widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)] try: D = date(day=1, month=int(datelist[0]), year=int(datelist[1])) except ValueError: return '' else: return str(D)