text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Add ability to delete entries This also sorts entries as they are added. These two additions will allow us to move entries via a GUI
class Interpolator { constructor() { this.data = []; } addIndexValue(index, value) { this.data.push({index: index, value: value}); // make sure items are in ascdending order by index this.data.sort((a, b) => a.index - b.index); } removeIndex(index) { for (var i = 0; i < this.data.length; i++) { if (this.data[i].index === index) { this.data.splice(i, 1); break; } } } valueAtIndex(target_index) { if (target_index < this.data[0].index || this.data[this.data.length - 1].index < target_index) { return null; } else { var start = null var end = null; for (var i = 0; i < this.data.length; i++) { let current = this.data[i]; if (current.index === target_index) { return current.value; } else { if (current.index <= target_index) { start = current; } else if (target_index < current.index) { end = current; break; } } } let index_delta = end.index - start.index; let percent = (target_index - start.index) / index_delta; let value_delta = end.value - start.value; return start.value + value_delta * percent; } } to_array() { return this.data.reduce((accum, item) => { accum.push(item.index); accum.push(item.value); return accum; }, []); } }
class Interpolator { constructor() { this.data = []; } addIndexValue(index, value) { this.data.push({index: index, value: value}); // make sure items are in ascdending order by index //this.data.sort((a, b) => a.index - b.index); } valueAtIndex(target_index) { if (target_index < this.data[0].index || this.data[this.data.length - 1].index < target_index) { return null; } else { var start = null var end = null; for (var i = 0; i < this.data.length; i++) { let current = this.data[i]; if (current.index === target_index) { return current.value; } else { if (current.index <= target_index) { start = current; } else if (target_index < current.index) { end = current; break; } } } let index_delta = end.index - start.index; let percent = (target_index - start.index) / index_delta; let value_delta = end.value - start.value; return start.value + value_delta * percent; } } to_array() { return this.data.reduce((accum, item) => { accum.push(item.index); accum.push(item.value); return accum; }, []); } }
Work on includes, left debug messages inside (for later)
package in.twizmwaz.cardinal.util; import org.bukkit.Bukkit; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import java.io.File; import java.io.IOException; import java.util.logging.Level; public class DomUtils { public static Document parse(File file) throws JDOMException, IOException { SAXBuilder saxBuilder = new SAXBuilder(); Document original = saxBuilder.build(file); Bukkit.getLogger().info("1"); for (Element include : original.getRootElement().getChildren("include")) { Bukkit.getLogger().info("2"); File path = file.getParentFile(); Bukkit.getLogger().info("3"); String source = include.getAttributeValue("src"); Bukkit.getLogger().info("4"); while (source.contains("../")) { source = source.replace("../", ""); path = path.getParentFile(); } Bukkit.getLogger().info("5"); File including = new File(path, source); Bukkit.getLogger().info("6"); try { for (Element element : parse(including).getRootElement().getChildren()) { Bukkit.getLogger().info(element.getName() + ""); original.getRootElement().addContent(element.detach()); } } catch (JDOMException | IOException e) { Bukkit.getLogger().log(Level.WARNING, "File '" + including.getName() + "' was not included correctly!"); } } return original; } }
package in.twizmwaz.cardinal.util; import org.bukkit.Bukkit; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Path; public class DomUtils { public static Document parse(File file) throws JDOMException, IOException { SAXBuilder saxBuilder = new SAXBuilder(); Document original = saxBuilder.build(file); Path repo = file.getParentFile().getParentFile().toPath(); for (Element include : original.getRootElement().getChildren("include")) { try { Path included; try { included = repo.resolve(include.getAttributeValue("src")).normalize(); for (Element element : parse(included.toFile()).getRootElement().getChildren()) { original.getRootElement().addContent(element.detach()); } } catch (FileNotFoundException e) { included = file.getParentFile().toPath().resolve(include.getAttributeValue("src")).normalize(); for (Element element : parse(included.toFile()).getRootElement().getChildren()) { original.getRootElement().addContent(element.detach()); Bukkit.getLogger().info(element.getName()); } } } catch (Exception e) { e.printStackTrace(); } } return original; } }
Update default queryset for formsets
from django.core.urlresolvers import reverse from django.shortcuts import redirect, render_to_response from django.template import RequestContext from campaign.forms import CampaignFormSet, ProspectusForm from campaign.models import PROSPECTUS_FIELD_HELP, Campaign def create_edit_prospectus(request): if request.method == 'POST': prospectus_form = ProspectusForm(request.POST) campaign_formset = CampaignFormSet(request.POST, queryset=Campaign.objects.none()) if prospectus_form.is_valid(): prospectus_form.save(commit=False) if request.user.is_authenticated(): prospectus_form.instance.owner = request.user if campaign_formset.is_valid(): prospectus_form.instance.save() for campaign in campaign_formset.save(commit=False): campaign.prospectus = prospectus_form.instance campaign.save() return redirect(reverse('index')) else: prospectus_form = ProspectusForm() campaign_formset = CampaignFormSet(queryset=Campaign.objects.none()) return render_to_response('campaign/new_prospectus.html', {'prospectus_form': prospectus_form, 'campaign_forms': campaign_formset, 'prospectus_help': PROSPECTUS_FIELD_HELP}, RequestContext(request))
from django.core.urlresolvers import reverse from django.shortcuts import redirect, render_to_response from django.template import RequestContext from campaign.forms import CampaignFormSet, ProspectusForm from campaign.models import PROSPECTUS_FIELD_HELP def create_edit_prospectus(request): if request.method == 'POST': prospectus_form = ProspectusForm(request.POST) campaign_formset = CampaignFormSet(request.POST) if prospectus_form.is_valid(): prospectus_form.save(commit=False) if request.user.is_authenticated(): prospectus_form.instance.owner = request.user if campaign_formset.is_valid(): prospectus_form.instance.save() for campaign in campaign_formset.save(commit=False): campaign.prospectus = prospectus_form.instance campaign.save() return redirect(reverse('index')) else: prospectus_form = ProspectusForm() campaign_formset = CampaignFormSet() return render_to_response('campaign/new_prospectus.html', {'prospectus_form': prospectus_form, 'campaign_forms': campaign_formset, 'prospectus_help': PROSPECTUS_FIELD_HELP}, RequestContext(request))
Add ConcurrentSkipListSet set with naturel order of elements
package com.spring.example.concurrency.collections; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; public class SetCollection { /** * ConcurrentSkipListSet store elements like natural order collection * * @param args command line arguments */ public static void main(String[] args) { Set<Integer> set = new ConcurrentSkipListSet<>(); //Init set in one thread for (int i = 0; i < 10; i++) { if (i % 2 == 0) set.add(i + 500); else set.add(i); } System.out.println(set); new Thread(() -> { for (Integer element : set) { System.out.println("Set : " + set); System.out.println("Set element: " + element); System.out.println("Set size: " + set.size()); } }).start(); new Thread(() -> { for (int i = 0; i < 200; i++) { if (i % 2 == 0) set.add(i + 500); else set.add(i); } }).start(); } //Set in natural order public static void skipSet() { Set<Integer> set = new ConcurrentSkipListSet<>(); new Thread(() -> { for (int i = 0; i < 200; i++) { if (i % 2 == 0) set.add(i); else set.add(i + 500); } System.out.println(set); }).start(); } }
package com.spring.example.concurrency.collections; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; public class SetCollection { /** * ConcurrentSkipListSet store elements like natural order collection * * @param args command line arguments */ public static void main(String[] args) { Set<Integer> set = new ConcurrentSkipListSet<>(); //Init set in one thread for (int i = 0; i < 10; i++) { if (i % 2 == 0) set.add(i + 500); else set.add(i); } System.out.println(set); new Thread(() -> { for (Integer element : set) { System.out.println("Set : " + set); System.out.println("Set element: " + element); System.out.println("Set size: " + set.size()); } }).start(); new Thread(() -> { for (int i = 0; i < 200; i++) { if (i % 2 == 0) set.add(i + 500); else set.add(i); } }).start(); } }
Fix the fspath interface and div docstring.
from zope.interface import Interface from filesystems import _PY3 class Path(Interface): def __str__(): """ Render the path as a string. """ if _PY3: def __fspath__(): """ Render the path as a string. """ def __truediv__(other): """ Traverse to a child of this path. """ else: def __div__(other): """ Traverse to a child of this path. """ def basename(): """ The tail component of this path. """ def dirname(): """ The head components of this path. """ def heritage(): """ The top-down set of this path's parents. """ def descendant(*segments): """ Traverse to a descendant of this path. """ def parent(): """ Traverse to the parent of this path. """ def sibling(name): """ Traverse to a sibling of this path. """ def relative_to(path): """ Resolve a path relative to this one. """
from zope.interface import Interface from filesystems import _PY3 class Path(Interface): def __str__(): """ Render the path as a string. """ if _PY3: def __truediv__(other): """ Traverse to a child of this path. """ def __fspath__(other): """ Render the path as a string. """ else: def __div__(other): """ Render the path as a string. """ def basename(): """ The tail component of this path. """ def dirname(): """ The head components of this path. """ def heritage(): """ The top-down set of this path's parents. """ def descendant(*segments): """ Traverse to a descendant of this path. """ def parent(): """ Traverse to the parent of this path. """ def sibling(name): """ Traverse to a sibling of this path. """ def relative_to(path): """ Resolve a path relative to this one. """
Fix bug when no DI for methods is used
(function (ng) { 'use strict'; /** * Angular.js utility for cleaner dependency injection. */ var $inject = function (cls, self, args) { var i; var key; var str; var func; var depNames = []; var deps = []; var l = cls.$inject.length; // Inject all dependencies into the self reference. for (i = 0; i < l; i++) { key = '_' + cls.$inject[i]; self[key] = args[i]; } for (key in cls.prototype) { if (typeof cls.prototype[key] === 'function') { func = cls.prototype[key]; str = func.toString(); // List of dependencies. depNames = str.match(/\/\*\s*\$inject:([^*]+)/); // Skip methods without the $inject comment. if (depNames && depNames.length < 2) continue; depNames = depNames[1].split(','); // Map the dependency names to the actual dependencies. args = depNames.map(function (name) { return self['_' + name.trim()]; }); // Add the "this" value to the arguments list. args.unshift(func); self[key] = func.bind.apply(func, args); } } }; var $injectService = function () { return $inject; }; ng.module('cg.inject', []) .factory('$inject', $injectService); })(angular);
(function (ng) { 'use strict'; /** * Angular.js utility for cleaner dependency injection. */ var $inject = function (cls, self, args) { var i; var key; var str; var func; var depNames = []; var deps = []; var l = cls.$inject.length; // Inject all dependencies into the self reference. for (i = 0; i < l; i++) { key = '_' + cls.$inject[i]; self[key] = args[i]; } for (key in cls.prototype) { if (typeof cls.prototype[key] === 'function') { func = cls.prototype[key]; str = func.toString(); // List of dependencies. depNames = str.match(/\/\*\s*\$inject:([^*]+)/); // Skip methods without the $inject comment. if (depNames.length < 2) continue; depNames = depNames[1].split(','); // Map the dependency names to the actual dependencies. args = depNames.map(function (name) { return self['_' + name.trim()]; }); // Add the "this" value to the arguments list. args.unshift(func); self[key] = func.bind.apply(func, args); } } }; var $injectService = function () { return $inject; }; ng.module('cg.inject', []) .factory('$inject', $injectService); })(angular);
TST: Remove deleted subpackage. Add better args to pytest
#!/usr/bin/env python # tests require pytest-cov and pytest-xdist import os import signal import sys import pytest try: from pcaspy import Driver, SimpleServer from multiprocessing import Process def to_subproc(): prefix = 'BSTEST:' pvdb = { 'VAL': { 'prec': 3, }, } class myDriver(Driver): def __init__(self): super(myDriver, self).__init__() if __name__ == '__main__': server = SimpleServer() server.createPV(prefix, pvdb) driver = myDriver() # process CA transactions while True: try: server.process(0.1) except KeyboardInterrupt: break p = Process(target=to_subproc) except ImportError: p = None def run(): if p is not None: p.start() try: # adding rxs to show extra info on skips and xfails args = ['--cov bluesky -srx -vv'] args.extend(sys.argv) pytest.main(args) finally: if p is not None: os.kill(p.pid, signal.SIGINT) p.join() if __name__ == '__main__': run()
#!/usr/bin/env python # tests require pytest-cov and pytest-xdist import os import signal import sys from bluesky.testing.noseclasses import KnownFailure import pytest try: from pcaspy import Driver, SimpleServer from multiprocessing import Process def to_subproc(): prefix = 'BSTEST:' pvdb = { 'VAL': { 'prec': 3, }, } class myDriver(Driver): def __init__(self): super(myDriver, self).__init__() if __name__ == '__main__': server = SimpleServer() server.createPV(prefix, pvdb) driver = myDriver() # process CA transactions while True: try: server.process(0.1) except KeyboardInterrupt: break p = Process(target=to_subproc) except ImportError: p = None def run(): if p is not None: p.start() try: args = ['--cov bluesky'] args.extend(sys.argv) pytest.main(args) finally: if p is not None: os.kill(p.pid, signal.SIGINT) p.join() if __name__ == '__main__': run()
:wrench: Improve minification of browser bundle.
"use strict"; const webpack = require('webpack'); const nodeExternals = require('webpack-node-externals'); const env = process.env.NODE_ENV; const config = { context: `${__dirname}/src`, resolve: { extensions: ['','.ts','.js'] }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin() ], module: { preLoaders: [ { test: /\.ts$/, loader: 'tslint' } ], loaders: [ { test: /\.ts$/, loader: 'ts', exclude: /node_modules/ } ] } }; /** * Build for: * - `production` -> minifiy + UMD * - `browser` -> UMD * otherwhise (`lib`) -> CJS + declaration files */ switch(env) { case 'production': config.plugins.push( new webpack.optimize.UglifyJsPlugin({ comments: false, beatuify: false, compress: { pure_getters: true, unsafe: true, unsafe_comps: true, warnings: false } }) ); case 'browser': config.output = { library: 'UDI', libraryTarget: 'umd' }; break; case 'test': config.target = 'node'; config.externals = [nodeExternals()]; config.devtool = 'cheap-module-source-map'; default: config.ts = { compilerOptions: { declaration: true } }; break; } module.exports = config;
"use strict"; const webpack = require('webpack'); const nodeExternals = require('webpack-node-externals'); const env = process.env.NODE_ENV; const config = { context: `${__dirname}/src`, resolve: { extensions: ['','.ts','.js'] }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin() ], module: { preLoaders: [ { test: /\.ts$/, loader: 'tslint' } ], loaders: [ { test: /\.ts$/, loader: 'ts', exclude: /node_modules/ } ] } }; /** * Build for: * - `production` -> minifiy + UMD * - `browser` -> UMD * otherwhise (`lib`) -> CJS + declaration files */ switch(env) { case 'production': config.plugins.push( new webpack.optimize.UglifyJsPlugin({ compressor: { pure_getters: true, unsafe: true, unsafe_comps: true, warnings: false } }) ); case 'browser': config.output = { library: 'UDI', libraryTarget: 'umd' }; break; case 'test': config.target = 'node'; config.externals = [nodeExternals()]; config.devtool = 'cheap-module-source-map'; default: config.ts = { compilerOptions: { declaration: true } }; break; } module.exports = config;
Make event search actually useful
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) query = request.GET.get('query') if query: events = events.filter( message__icontains=query, ) return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, )
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases import GroupEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import DateTimePaginator from sentry.models import Event, Group from sentry.utils.apidocs import scenario, attach_scenarios @scenario('ListAvailableSamples') def list_available_samples_scenario(runner): group = Group.objects.filter(project=runner.default_project).first() runner.request( method='GET', path='/issues/%s/events/' % group.id ) class GroupEventsEndpoint(GroupEndpoint): doc_section = DocSection.EVENTS @attach_scenarios([list_available_samples_scenario]) def get(self, request, group): """ List an Issue's Events `````````````````````` This endpoint lists an issue's events. :pparam string issue_id: the ID of the issue to retrieve. :auth: required """ events = Event.objects.filter( group=group ) query = request.GET.get('query') if query: events = events.filter( message__iexact=query, ) return self.paginate( request=request, queryset=events, order_by='-datetime', on_results=lambda x: serialize(x, request.user), paginator_cls=DateTimePaginator, )
Use updated registry in Ember 2.1
import Ember from 'ember'; export function initialize(instance) { var config; if (instance.resolveRegistration) { // Ember 2.1+ // http://emberjs.com/blog/2015/08/16/ember-2-1-beta-released.html#toc_registry-and-container-reform config = instance.resolveRegistration('config:environment'); } else { config = instance.container.lookupFactory('config:environment'); } // Default to true when not set let _includeRouteName = true; if (config['ember-body-class'] && config['ember-body-class'].includeRouteName === false) { _includeRouteName = false; } Ember.Route.reopen({ classNames: [], bodyClasses: [], // Backwards compatibility _getRouteName() { const nameParts = this.get('routeName').split('.'); return nameParts[nameParts.length - 1]; }, addClasses: Ember.on('activate', function() { const $body = Ember.$('body'); ['bodyClasses', 'classNames'].forEach((classes) => { this.get(classes).forEach(function(klass) { $body.addClass(klass); }); }); if (_includeRouteName) { $body.addClass(this._getRouteName()); } }), removeClasses: Ember.on('deactivate', function() { const $body = Ember.$('body'); ['bodyClasses', 'classNames'].forEach((classes) => { this.get(classes).forEach(function(klass) { $body.removeClass(klass); }); }); if (_includeRouteName) { $body.removeClass(this._getRouteName()); } }), }); } export default { name: 'body-class', initialize: initialize };
import Ember from 'ember'; export function initialize(instance) { const config = instance.container.lookupFactory('config:environment'); // Default to true when not set let _includeRouteName = true; if (config['ember-body-class'] && config['ember-body-class'].includeRouteName === false) { _includeRouteName = false; } Ember.Route.reopen({ classNames: [], bodyClasses: [], // Backwards compatibility addClasses: Ember.on('activate', function() { const $body = Ember.$('body'); ['bodyClasses', 'classNames'].forEach((classes) => { this.get(classes).forEach(function(klass) { $body.addClass(klass); }); }); if (_includeRouteName) { let routeName = this.get('routeName').split('.').get('lastObject'); $body.addClass(routeName); } }), removeClasses: Ember.on('deactivate', function() { const $body = Ember.$('body'); ['bodyClasses', 'classNames'].forEach((classes) => { this.get(classes).forEach(function(klass) { $body.removeClass(klass); }); }); if (_includeRouteName) { let routeName = this.get('routeName').split('.').get('lastObject'); $body.removeClass(routeName); } }), }); } export default { name: 'body-class', initialize: initialize };
Revert "only calls unhighlight on mouseout when necessary" This reverts commit 0172733d1299ed3b86a3bb91345d4611f72e166b.
$(document).ready(function() { $(".btn.year").click(function(e){ var target = $(e.target); target.toggleClass("primary"); renderSelection(); }); $(".btn.story").click(function(e){ var target = $(e.target); target.toggleClass("primary"); renderSelection(); }); function renderSelection(){ var stories = []; $(".btn.story").each(function(i, e){ var btn = $(e); if(btn.hasClass("primary")) stories.push(btn.text().toLowerCase()); }); var years = []; $(".btn.year").each(function(i, e){ var btn = $(e); if(btn.hasClass("primary")) years.push(parseInt(btn.text())); }); showFiltered(years, stories); } $(".btn.story").hover( function(e){ var btn = $(e.target); if(btn.hasClass("primary")) highlightStories(btn.text()); }, function(e){ unhighlight(); } ); $(".btn.year").hover( function(e){ var btn = $(e.target); if(btn.hasClass("primary")) highlightYear(parseInt(btn.text())); }, function(e){ unhighlight(); } ); });
$(document).ready(function() { $(".btn.year").click(function(e){ var target = $(e.target); target.toggleClass("primary"); renderSelection(); }); $(".btn.story").click(function(e){ var target = $(e.target); target.toggleClass("primary"); renderSelection(); }); function renderSelection(){ var stories = []; $(".btn.story").each(function(i, e){ var btn = $(e); if(btn.hasClass("primary")) stories.push(btn.text().toLowerCase()); }); var years = []; $(".btn.year").each(function(i, e){ var btn = $(e); if(btn.hasClass("primary")) years.push(parseInt(btn.text())); }); showFiltered(years, stories); } $(".btn.story").hover( function(e){ var btn = $(e.target); if(btn.hasClass("primary")) highlightStories(btn.text()); }, function(e){ var btn = $(e.target); if(btn.hasClass("primary")) unhighlight(); } ); $(".btn.year").hover( function(e){ var btn = $(e.target); if(btn.hasClass("primary")) highlightYear(parseInt(btn.text())); }, function(e){ var btn = $(e.target); if(btn.hasClass("primary")) unhighlight(); } ); });
Fix page size text when 'All' is selected
import React, { Component, PropTypes } from 'react'; const propTypes = { pageSize: PropTypes.number.isRequired, totalSize: PropTypes.number.isRequired, onChange: PropTypes.func.isRequired, className: PropTypes.string, }; class PageSize extends Component { render() { const { pageSize, totalSize, onChange, className = 'col-md-6', } = this.props; return ( <div className={className} style={{ margin: '1rem 0 1rem 0', }} > <select onChange={(e) => onChange(parseInt(e.target.value, 10))} value={pageSize} className="form-control sema-field" style={{ display: 'inline-block', width: '80px', margin: '0 0 0 5px', }} > <option value={5}>5</option> <option value={10}>10</option> <option value={50}>50</option> <option value={100}>100</option> <option value={-1}>All</option> </select> <span className="sema-label">{`${pageSize !== -1 ? ' of' : ''} ${totalSize}`}</span> </div> ); } } PageSize.propTypes = propTypes; export default PageSize;
import React, { Component, PropTypes } from 'react'; const propTypes = { pageSize: PropTypes.number.isRequired, totalSize: PropTypes.number.isRequired, onChange: PropTypes.func.isRequired, className: PropTypes.string, }; class PageSize extends Component { render() { const { pageSize, totalSize, onChange, className = 'col-md-6', } = this.props; return ( <div className={className} style={{ margin: '1rem 0 1rem 0', }} > <select onChange={(e) => onChange(parseInt(e.target.value, 10))} value={pageSize} className="form-control sema-field" style={{ display: 'inline-block', width: '80px', margin: '0 0 0 5px', }} > <option value={5}>5</option> <option value={10}>10</option> <option value={50}>50</option> <option value={100}>100</option> <option value={-1}>All</option> </select> <span className="sema-label">{`${pageSize !== -1 && ' of'} ${totalSize}`}</span> </div> ); } } PageSize.propTypes = propTypes; export default PageSize;
Fix exception call in loop()
<?php declare(strict_types=1); namespace Funktions; use Exception; /** * Return a value based on a test * * @param boolean $test * @param callable $truthy * @param callable $falsy * @return mixed */ function condition(bool $test, callable $truthy, callable $falsy) { if ($test) { return call_user_func($truthy); } return call_user_func($falsy); } /** * Loop over items and pass them to a generator * * @param iterable $iterable * @param callable $callable * @return array */ function loop(iterable $iterable, callable $callable): array { $array = []; foreach ($iterable as $item) { $generator = call_user_func($callable, $item); if ($generator instanceof Generator === false) { throw new Exception('Callable must be a generator'); } $array = array_merge($array, iterator_to_array($generator)); } return $array; } /** * Loop in a generator until a returned condition * * @param callable $callable * @return array */ function loop_until(callable $callable): array { $array = []; do { $generator = call_user_func($callable); if ($generator instanceof Generator === false) { throw Exception('Callable must be a generator'); } $array = array_merge($array, iterator_to_array($generator)); } while(!$generator->getReturn()); return $array; }
<?php declare(strict_types=1); namespace Funktions; /** * Return a value based on a test * * @param boolean $test * @param callable $truthy * @param callable $falsy * @return mixed */ function condition(bool $test, callable $truthy, callable $falsy) { if ($test) { return call_user_func($truthy); } return call_user_func($falsy); } /** * Loop over items and pass them to a generator * * @param iterable $iterable * @param callable $callable * @return array */ function loop(iterable $iterable, callable $callable): array { $array = []; foreach ($iterable as $item) { $generator = call_user_func($callable, $item); if ($generator instanceof Generator === false) { throw Exception('Callable must be a generator'); } $array = array_merge($array, iterator_to_array($generator)); } return $array; } /** * Loop in a generator until a returned condition * * @param callable $callable * @return array */ function loop_until(callable $callable): array { $array = []; do { $generator = call_user_func($callable); if ($generator instanceof Generator === false) { throw Exception('Callable must be a generator'); } $array = array_merge($array, iterator_to_array($generator)); } while(!$generator->getReturn()); return $array; }
Change way to load cordova.js
/*globals Polymer */ 'use strict'; Polymer( { is: 'cordova-core', properties: { /** * Return if cordova deviceready event has been fired. */ ready: { notify: true, readOnly: true, type: Boolean, value: false }, /** * Return if cordova application is paused. */ paused: { notify: true, readOnly: true, type: Boolean, value: false } }, attached() { const cordovaEl = document.querySelector('[src="cordova.js"]'); document.addEventListener( 'deviceready', this._setReady.bind(this, true), false ); document.addEventListener( 'pause', this._setPaused.bind(this, true), false ); document.addEventListener( 'resume', this._setPaused.bind(this, false), false ); if (!cordovaEl) { let script = document.createElement('script'); script.src = 'cordova.js'; document.body.appendChild(script); } }, detached() { document.removeEventListener('deviceready', this._setReady); document.removeEventListener('pause', this._setPaused); document.removeEventListener('resume', this._setPaused); } } );
/*globals Polymer */ 'use strict'; Polymer( { is: 'cordova-core', properties: { /** * Return if cordova deviceready event has been fired. */ ready: { notify: true, readOnly: true, type: Boolean, value: false }, /** * Return if cordova application is paused. */ paused: { notify: true, readOnly: true, type: Boolean, value: false } }, attached() { const cordovaEl = document.querySelector('#cordova'); document.addEventListener( 'deviceready', this._setReady.bind(this, true), false ); document.addEventListener( 'pause', this._setPaused.bind(this, true), false ); document.addEventListener( 'resume', this._setPaused.bind(this, false), false ); if (!cordovaEl) { let script = document.createElement('script'); script.id = 'cordova'; script.src = 'cordova.js'; document.body.appendChild(script); } }, detached() { document.removeEventListener('deviceready', this._setReady); document.removeEventListener('pause', this._setPaused); document.removeEventListener('resume', this._setPaused); } } );
Trim initial slash on names
<?php namespace StrictPhp\TypeFinder; use phpDocumentor\Reflection\DocBlock; use phpDocumentor\Reflection\DocBlock\Tag\VarTag; use phpDocumentor\Reflection\TypeResolver; use phpDocumentor\Reflection\Types\ContextFactory; use ReflectionProperty; final class PropertyTypeFinder { /** * @param ReflectionProperty $reflectionProperty * * @return \phpDocumentor\Reflection\Type[] */ public function __invoke(ReflectionProperty $reflectionProperty) { $typeResolver = new TypeResolver(); $context = (new ContextFactory())->createFromReflector($reflectionProperty); return array_unique(array_filter(array_merge( [], [], ...array_map( function (VarTag $varTag) use ($typeResolver, $context) { return array_map( function ($type) use ($typeResolver, $context) { return $typeResolver->resolve(ltrim($type, '\\'), $context); }, $varTag->getTypes() ); }, // note: this will not compute imports for us! Need a better alternative! (new DocBlock($reflectionProperty))->getTagsByName('var') ) ))); } }
<?php namespace StrictPhp\TypeFinder; use phpDocumentor\Reflection\DocBlock; use phpDocumentor\Reflection\DocBlock\Tag\VarTag; use phpDocumentor\Reflection\TypeResolver; use phpDocumentor\Reflection\Types\ContextFactory; use ReflectionProperty; final class PropertyTypeFinder { /** * @param ReflectionProperty $reflectionProperty * * @return \phpDocumentor\Reflection\Type[] */ public function __invoke(ReflectionProperty $reflectionProperty) { $typeResolver = new TypeResolver(); $context = (new ContextFactory())->createFromReflector($reflectionProperty->getDeclaringClass()); return array_unique(array_filter(array_merge( [], [], ...array_map( function (VarTag $varTag) use ($typeResolver, $context) { return array_map( function ($type) use ($typeResolver, $context) { return $typeResolver->resolve($type, $context); }, $varTag->getTypes() ); }, // note: this will not compute imports for us! Need a better alternative! (new DocBlock($reflectionProperty))->getTagsByName('var') ) ))); } }
Change URL for deleting competition Still doesn't work, see issue #48
angular.module("AdminHome", []).controller("AdminHomeController", function ($scope, $http) { $scope.competitionId = competitionId updateCompetitionList() $scope.addCompetition = function () { var competition = {name: $scope.competitionName} $http.post("/api/competitions", competition).then(function (response) { console.log(response) updateCompetitionList() }, function (error) { console.log(error) }) } $scope.removeCompetition = function (competition) { swal({ title: "Remove competition?", text: "Are you sure you want to remove the competition: " + competition.name + '?', type: "warning", showCancelButton: true, confirmButtonText: "Remove it!", confirmButtonColor: "#ec6c62" }, function() { $http.delete("/api/competitions/" + competition._id).then(function (response) { console.log(response) updateCompetitionList() }, function (error) { console.log(error) }) }); } function updateCompetitionList() { $http.get("/api/competitions/").then(function (response) { $scope.competitions = response.data console.log($scope.competitions) }) } })
angular.module("AdminHome", []).controller("AdminHomeController", function ($scope, $http) { $scope.competitionId = competitionId updateCompetitionList() $scope.addCompetition = function () { var competition = {name: $scope.competitionName} $http.post("/api/competitions", competition).then(function (response) { console.log(response) updateCompetitionList() }, function (error) { console.log(error) }) } $scope.removeCompetition = function (competition) { swal({ title: "Remove competition?", text: "Are you sure you want to remove the competition: " + competition.name + '?', type: "warning", showCancelButton: true, confirmButtonText: "Remove it!", confirmButtonColor: "#ec6c62" }, function() { $http.get("/api/competitions/" + competition._id + "/delete").then(function (response) { console.log(response) updateCompetitionList() }, function (error) { console.log(error) }) }); } function updateCompetitionList() { $http.get("/api/competitions/").then(function (response) { $scope.competitions = response.data console.log($scope.competitions) }) } })
Print key on click (try 5 - button)
function displayKeys() { // Retrieve all keyPairs var sql = "select K.name from key K"; dbRetrieve(sql, [], function(res) { // Populate key list var html = '<hr>'; for (var i = 0; i < 1; ++i) { var keyName = res.rows.item(i).name; html += '<button onclick="showPubKey(this.innerHTML);">' + keyName + '</button>'; } // Update GUI document.getElementById("key_list").innerHTML = html; }); } function showPubKey(keyName) { // Retrieve all keyPairs var sql = "select K.keyPair from key K where K.name = ?"; dbRetrieve(sql, [keyName.toString()], function(res) { if (res.rows.length === 1) { // Extract public key and create qr-code var key = buf2hex(cryptoJS.publicKey(hex2buf(res.rows.item(0).keyPair))); alert(key); cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, key, function (success) { alert('succes'); alert("Encode succes: " + success); }, function (fail) { alert('fail'); alert("Encoding failed: " + fail); } ); } }); }
function displayKeys() { // Retrieve all keyPairs var sql = "select K.name from key K"; dbRetrieve(sql, [], function(res) { // Populate key list var html = '<hr>'; for (var i = 0; i < res.rows.length; ++i) { var keyName = res.rows.item(i).name; html += '<span onclick="showPubKey($(this).text());">' + keyName + '</span><br/><hr>'; } // Update GUI document.getElementById("key_list").innerHTML = html; }); } function showPubKey(keyName) { // Retrieve all keyPairs var sql = "select K.keyPair from key K where K.name = ?"; dbRetrieve(sql, [keyName.toString()], function(res) { if (res.rows.length === 1) { // Extract public key and create qr-code var key = buf2hex(cryptoJS.publicKey(hex2buf(res.rows.item(0).keyPair))); alert(key); cordova.plugins.barcodeScanner.encode(cordova.plugins.barcodeScanner.Encode.TEXT_TYPE, key, function (success) { alert('succes'); alert("Encode succes: " + success); }, function (fail) { alert('fail'); alert("Encoding failed: " + fail); } ); } }); }
Revert "Unsetting non-existant key does not throw notice/error, so unset without checking" This reverts commit 532b3e771755fda3909fc46a02211dfc3317730d.
<?php namespace Puphpet\Domain\PuppetModule; class Server extends PuppetModuleAbstract implements PuppetModuleInterface { protected $server; public function __construct($server) { $this->server = is_array($server) ? $server : array(); } /** * Return ready to use server array * * @return array */ public function getFormatted() { if (empty($this->server)) { return array(); } $this->formatBashAliases() ->formatPackages(); return $this->server; } /** * Submitted .bash_aliases contents * * @return self */ protected function formatBashAliases() { $this->server['bashaliases'] = !empty($this->server['bashaliases']) ? trim(str_replace("\r\n", "\n", $this->server['bashaliases'])) : ''; return $this; } /** * A comma-delimited string of package names * * @return self */ protected function formatPackages() { $this->server['packages'] = !empty($this->server['packages']) ? explode(',', $this->server['packages']) : array(); $key = array_search('python-software-properties', $this->server['packages']); // python-software-properties is installed by default, remove to prevent duplicate Puppet function if ($key !== FALSE) { unset($this->server['packages'][$key]); } $this->server['packages'] = $this->quoteArray($this->server['packages']); return $this; } }
<?php namespace Puphpet\Domain\PuppetModule; class Server extends PuppetModuleAbstract implements PuppetModuleInterface { protected $disallowedPackages = ['python-software-properties']; protected $server; public function __construct($server) { $this->server = is_array($server) ? $server : array(); } /** * Return ready to use server array * * @return array */ public function getFormatted() { if (empty($this->server)) { return array(); } $this->formatBashAliases() ->formatPackages(); return $this->server; } /** * Submitted .bash_aliases contents * * @return self */ protected function formatBashAliases() { $this->server['bashaliases'] = !empty($this->server['bashaliases']) ? trim(str_replace("\r\n", "\n", $this->server['bashaliases'])) : ''; return $this; } /** * A comma-delimited string of package names * * @return self */ protected function formatPackages() { $this->server['packages'] = !empty($this->server['packages']) ? explode(',', $this->server['packages']) : array(); foreach ($this->disallowedPackages as $disallowed) { unset($this->server['packages'][$disallowed]); } $this->server['packages'] = $this->quoteArray($this->server['packages']); return $this; } }
Fix build on python 2.6
# -*- coding: utf-8 -*- from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ @unittest.skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise
# -*- coding: utf-8 -*- from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir from unittest import skipIf ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ @skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise
Add support for Monolog 1.2.0
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Monolog\Handler; use Monolog\Logger; use Monolog\Handler\TestHandler; use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; /** * DebugLogger. * * @author Jordi Boggiano <[email protected]> */ class DebugHandler extends TestHandler implements DebugLoggerInterface { /** * {@inheritdoc} */ public function getLogs() { $records = array(); foreach ($this->records as $record) { $records[] = array( 'timestamp' => $record['datetime']->getTimestamp(), 'message' => $record['message'], 'priority' => $record['level'], 'priorityName' => $record['level_name'], 'context' => $record['context'], ); } return $records; } /** * {@inheritdoc} */ public function countErrors() { $cnt = 0; $levels = array(Logger::ERROR, Logger::CRITICAL, Logger::ALERT); if (defined('Monolog\Logger::EMERGENCY')) { $levels[] = Logger::EMERGENCY; } foreach ($levels as $level) { if (isset($this->recordsByLevel[$level])) { $cnt += count($this->recordsByLevel[$level]); } } return $cnt; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Monolog\Handler; use Monolog\Logger; use Monolog\Handler\TestHandler; use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; /** * DebugLogger. * * @author Jordi Boggiano <[email protected]> */ class DebugHandler extends TestHandler implements DebugLoggerInterface { /** * {@inheritdoc} */ public function getLogs() { $records = array(); foreach ($this->records as $record) { $records[] = array( 'timestamp' => $record['datetime']->getTimestamp(), 'message' => $record['message'], 'priority' => $record['level'], 'priorityName' => $record['level_name'], 'context' => $record['context'], ); } return $records; } /** * {@inheritdoc} */ public function countErrors() { $cnt = 0; foreach (array(Logger::ERROR, Logger::CRITICAL, Logger::ALERT) as $level) { if (isset($this->recordsByLevel[$level])) { $cnt += count($this->recordsByLevel[$level]); } } return $cnt; } }
Fix double quotes in analyzer testcase
from django.test import TestCase from breach.models import SampleSet, Victim, Target from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', prefix='test', alphabet='0123456789' ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140' ) self.samplesets = [ SampleSet.objects.create( victim=victim, amount=1, knownsecret='testsecret', knownalphabet='01', candidatealphabet='0', data='bigbigbigbigbigbig' ), SampleSet.objects.create( victim=victim, amount=1, knownsecret='testsecret', knownalphabet='01', candidatealphabet='1', data='small' ) ] def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
from django.test import TestCase from breach.models import SampleSet, Victim, Target from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint="http://di.uoa.gr/", prefix="test", alphabet="0123456789" ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140' ) self.samplesets = [ SampleSet.objects.create( victim=victim, amount=1, knownsecret="testsecret", knownalphabet="01", candidatealphabet="0", data="bigbigbigbigbigbig" ), SampleSet.objects.create( victim=victim, amount=1, knownsecret="testsecret", knownalphabet="01", candidatealphabet="1", data="small" ) ] def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
Use mounted instead of compiled Because compiled is removed. Signed-off-by: Kenji Okimoto <[email protected]>
'use strict'; $(document).ready(()=> { new Vue({ el: "#fluent-log", paramAttributes: ["logUrl", "initialAutoReload"], data: { "autoFetch": false, "logs": [], "limit": 30, "processing": false }, mounted: function(){ this.fetchLogs(); var self = this; var timer; this.$watch("autoFetch", function(newValue){ if(newValue === true) { timer = setInterval(function(){ self.fetchLogs(); var $log = $(".log", self.$el); $log.scrollTop($log.innerHeight()); }, 1000); } else { clearInterval(timer); } }); if(this.initialAutoReload) { this.autoFetch = true; } }, computed: { isPresentedLogs: function(){ return this.logs.length > 0; } }, methods: { fetchLogs: function() { if(this.processing) return; this.processing = true; var self = this; new Promise(function(resolve, reject) { $.getJSON(self.logUrl + "?limit=" + self.limit, resolve).fail(reject); }).then(function(logs){ self.logs = logs; setTimeout(function(){ self.processing = false; }, 256); // delay to reduce flicking loading icon })["catch"](function(error){ self.processing = false; }); } } }); });
'use strict'; $(document).ready(()=> { new Vue({ el: "#fluent-log", paramAttributes: ["logUrl", "initialAutoReload"], data: { "autoFetch": false, "logs": [], "limit": 30, "processing": false }, compiled: function(){ this.fetchLogs(); var self = this; var timer; this.$watch("autoFetch", function(newValue){ if(newValue === true) { timer = setInterval(function(){ self.fetchLogs(); var $log = $(".log", self.$el); $log.scrollTop($log.innerHeight()); }, 1000); } else { clearInterval(timer); } }); if(this.initialAutoReload) { this.autoFetch = true; } }, computed: { isPresentedLogs: function(){ return this.logs.length > 0; } }, methods: { fetchLogs: function() { if(this.processing) return; this.processing = true; var self = this; new Promise(function(resolve, reject) { $.getJSON(self.logUrl + "?limit=" + self.limit, resolve).fail(reject); }).then(function(logs){ self.logs = logs; setTimeout(function(){ self.processing = false; }, 256); // delay to reduce flicking loading icon })["catch"](function(error){ self.processing = false; }); } } }); });
Add a new option allowing client code to turn off parallelism
import featureflow as ff from random_samples import ShuffledSamples from random_samples import InfiniteSampler from preprocess import PreprocessingPipeline def learning_pipeline(): class LearningPipeline(ff.BaseModel): samples = ff.PickleFeature(ff.IteratorNode) shuffled = ff.PickleFeature( ShuffledSamples, nsamples=ff.Var('nsamples'), dtype=ff.Var('dtype'), needs=samples) return LearningPipeline def infinite_streaming_learning_pipeline(cls): roots = filter(lambda feature: feature.is_root, cls.features.itervalues()) if len(roots) != 1: raise ValueError('cls must have a single root feature') root = roots[0] class InfiniteLearningPipeline(cls): dataset = ff.Feature( InfiniteSampler, nsamples=ff.Var('nsamples'), dtype=ff.Var('dtype'), feature_filter=ff.Var('feature_filter'), parallel=ff.Var('parallel')) pipeline = ff.ClobberPickleFeature( PreprocessingPipeline, needs=cls.features, store=True) @classmethod def load_network(cls): if not cls.exists(): raise RuntimeError('No network has been trained or saved') instance = cls() for p in instance.pipeline: try: return p.network except AttributeError: pass raise RuntimeError('There is no network in the pipeline') root.needs = InfiniteLearningPipeline.dataset InfiniteLearningPipeline.__name__ = cls.__name__ InfiniteLearningPipeline.__module__ = cls.__module__ return InfiniteLearningPipeline
import featureflow as ff from random_samples import ShuffledSamples from random_samples import InfiniteSampler from preprocess import PreprocessingPipeline def learning_pipeline(): class LearningPipeline(ff.BaseModel): samples = ff.PickleFeature(ff.IteratorNode) shuffled = ff.PickleFeature( ShuffledSamples, nsamples=ff.Var('nsamples'), dtype=ff.Var('dtype'), needs=samples) return LearningPipeline def infinite_streaming_learning_pipeline(cls): roots = filter(lambda feature: feature.is_root, cls.features.itervalues()) if len(roots) != 1: raise ValueError('cls must have a single root feature') root = roots[0] class InfiniteLearningPipeline(cls): dataset = ff.Feature( InfiniteSampler, nsamples=ff.Var('nsamples'), dtype=ff.Var('dtype')) pipeline = ff.ClobberPickleFeature( PreprocessingPipeline, needs=cls.features, store=True) @classmethod def load_network(cls): if not cls.exists(): raise RuntimeError('No network has been trained or saved') instance = cls() for p in instance.pipeline: try: return p.network except AttributeError: pass raise RuntimeError('There is no network in the pipeline') root.needs = InfiniteLearningPipeline.dataset InfiniteLearningPipeline.__name__ = cls.__name__ InfiniteLearningPipeline.__module__ = cls.__module__ return InfiniteLearningPipeline
Remove from Spaces till implement toggle switch
<?php namespace humhub\modules\twitter; return [ 'id' => 'twitter', 'class' => 'humhub\modules\twitter\Module', 'namespace' => 'humhub\modules\twitter', 'events' => [ [ 'class' => \humhub\modules\dashboard\widgets\Sidebar::className(), 'event' => \humhub\modules\dashboard\widgets\Sidebar::EVENT_INIT, 'callback' => [ 'humhub\modules\twitter\Events', 'addTwitterFrame' ] ], // [ // 'class' => \humhub\modules\space\widgets\Sidebar::className(), // 'event' => \humhub\modules\space\widgets\Sidebar::EVENT_INIT, // 'callback' => [ // 'humhub\modules\twitter\Events', // 'addTwitterFrame' // ] // ], [ 'class' => \humhub\modules\admin\widgets\AdminMenu::className(), 'event' => \humhub\modules\admin\widgets\AdminMenu::EVENT_INIT, 'callback' => [ 'humhub\modules\twitter\Events', 'onAdminMenuInit' ] ] ] ]; ?>
<?php namespace humhub\modules\twitter; return [ 'id' => 'twitter', 'class' => 'humhub\modules\twitter\Module', 'namespace' => 'humhub\modules\twitter', 'events' => [ [ 'class' => \humhub\modules\dashboard\widgets\Sidebar::className(), 'event' => \humhub\modules\dashboard\widgets\Sidebar::EVENT_INIT, 'callback' => [ 'humhub\modules\twitter\Events', 'addTwitterFrame' ] ], [ 'class' => \humhub\modules\space\widgets\Sidebar::className(), 'event' => \humhub\modules\space\widgets\Sidebar::EVENT_INIT, 'callback' => [ 'humhub\modules\twitter\Events', 'addTwitterFrame' ] ], [ 'class' => \humhub\modules\admin\widgets\AdminMenu::className(), 'event' => \humhub\modules\admin\widgets\AdminMenu::EVENT_INIT, 'callback' => [ 'humhub\modules\twitter\Events', 'onAdminMenuInit' ] ] ] ]; ?>
Fix some print statments for Python3 compatibility.
import csv def read_axf(axf_string): blocks = {} state = 'new_block' for line in axf_string.split('\n'): if line == '[$]' or line == '': pass elif line.startswith('['): block_key = line.replace('[',"").replace(']',"") else: if block_key not in blocks: blocks[block_key] = [] blocks[block_key].append(line) for k in blocks.keys(): if k == 'data': is_data = False data_block = {} for row in csv.reader(blocks[k]): if is_data: data_block[row[1]] = {} for col_name, col_value in zip(header_row, row): data_block[row[1]][col_name] = col_value else: header_row = row is_data = True else: # probably notice or header ... do something awesome with them pass return data_block def read_axf_file(axf_file): with open(axf_file, 'r') as f: return read_axf(f.read()) if __name__ == "__main__": print(read_axf_file('../tests/data/IDV60700.axf'))
import csv def read_axf(axf_string): blocks = {} state = 'new_block' for line in axf_string.split('\n'): if line == '[$]' or line == '': pass elif line.startswith('['): block_key = line.replace('[',"").replace(']',"") print block_key else: if block_key not in blocks: blocks[block_key] = [] blocks[block_key].append(line) for k in blocks.keys(): if k == 'data': is_data = False data_block = {} for row in csv.reader(blocks[k]): if is_data: data_block[row[1]] = {} for col_name, col_value in zip(header_row, row): data_block[row[1]][col_name] = col_value else: header_row = row is_data = True else: # probably notice or header ... do something awesome with them pass return data_block def read_axf_file(axf_file): with open(axf_file, 'r') as f: return read_axf(f.read()) if __name__ == "__main__": print read_axf_file('../tests/data/IDV60700.axf')
Fix template var exports for directors
from flask import render_template as flask_render_template from db.models import EvalSettings from util.ldap import ldap_is_active from util.ldap import ldap_is_alumni from util.ldap import ldap_is_eboard from util.ldap import ldap_is_financial_director from util.ldap import ldap_is_eval_director from util.ldap import ldap_is_intromember def render_template(request, template_name, **kwargs): user_name = request.headers.get('x-webauth-user') #TODO maybe use the webauth request decorator lockdown = EvalSettings.query.first().site_lockdown is_active = ldap_is_active(user_name) is_alumni = ldap_is_alumni(user_name) is_eboard = ldap_is_eboard(user_name) is_financial = ldap_is_financial_director(user_name) is_eval = ldap_is_eval_director(user_name) is_intromember = ldap_is_intromember(user_name) if is_eval: lockdown = False # TODO FIXME AUTH BREACH if user_name == 'loothelion': is_eboard = True return flask_render_template( template_name, lockdown=lockdown, is_active=is_active, is_alumni=is_alumni, is_eboard=is_eboard, is_eval_director=is_eval, is_financial_director=is_financial, is_intromember=is_intromember, **kwargs)
from flask import render_template as flask_render_template from db.models import EvalSettings from util.ldap import ldap_is_active from util.ldap import ldap_is_alumni from util.ldap import ldap_is_eboard from util.ldap import ldap_is_financial_director from util.ldap import ldap_is_eval_director from util.ldap import ldap_is_intromember def render_template(request, template_name, **kwargs): user_name = request.headers.get('x-webauth-user') #TODO maybe use the webauth request decorator lockdown = EvalSettings.query.first().site_lockdown is_active = ldap_is_active(user_name) is_alumni = ldap_is_alumni(user_name) is_eboard = ldap_is_eboard(user_name) is_financial = ldap_is_financial_director(user_name) is_eval = ldap_is_eval_director(user_name) is_intromember = ldap_is_intromember(user_name) if is_eval: lockdown = False # TODO FIXME AUTH BREACH if user_name == 'loothelion': is_eboard = True return flask_render_template( template_name, lockdown=lockdown, is_active=is_active, is_alumni=is_alumni, is_eboard=is_eboard, is_eval=is_eval, is_financial=is_financial, is_intromember=is_intromember, **kwargs)
Fix crashes from misc. events
from __future__ import print_function import time from slackclient import SlackClient import mh_python as mh import argparse import random def main(): parser = argparse.ArgumentParser( description="Slack chatbot using MegaHAL") parser.add_argument( "-t", "--token", type=str, help="Slack token", required=True) args = vars(parser.parse_args()) token = args['token'] sc = SlackClient(token) mh.initbrain() try: if sc.rtm_connect(): while True: for event in sc.rtm_read(): if 'type' in event and event['type'] == 'message' \ and 'text' in event: message = event['text'].encode('ascii', 'ignore') print("Handling message: %s" % message) if random.random() < 0.1: reply = mh.doreply(message) print("Replying: %s" % reply) sc.rtm_send_message(event['channel'], reply) else: mh.learn(message) time.sleep(1) else: print("Connection Failed, invalid token?") finally: mh.cleanup() if __name__ == '__main__': main()
from __future__ import print_function import time from slackclient import SlackClient import mh_python as mh import argparse import random def main(): parser = argparse.ArgumentParser( description="Slack chatbot using MegaHAL") parser.add_argument( "-t", "--token", type=str, help="Slack token", required=True) args = vars(parser.parse_args()) token = args['token'] sc = SlackClient(token) mh.initbrain() try: if sc.rtm_connect(): while True: for event in sc.rtm_read(): if event['type'] == 'message': message = event['text'] print("Handling message: %s" % message) if random.random() < 0.1: reply = mh.doreply(message) print("Replying: %s" % reply) sc.rtm_send_message(event['channel'], reply) else: mh.learn(message) time.sleep(1) else: print("Connection Failed, invalid token?") finally: mh.cleanup() if __name__ == '__main__': main()
Add HtmlWebpackPlugin for generating dev html files
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ filename: 'index.html', template: './src/index.template.html' }), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/, include: __dirname }, { test: /\.css$/, loader: "style-loader!css-loader" }, { test: /\.png$/, loader: "url-loader?limit=100000" }, { test: /\.jpg$/, loader: "file-loader" } ] } };
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './src/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.HotModuleReplacementPlugin() ], module: { loaders: [ { test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/, include: __dirname }, { test: /\.css$/, loader: "style-loader!css-loader" }, { test: /\.png$/, loader: "url-loader?limit=100000" }, { test: /\.jpg$/, loader: "file-loader" } ] } };
Add get in progress content mehtod
import http from '../http'; export default class collections { static get(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response; }) } static getAll() { return http.get(`/zebedee/collections`) .then(response => { return response; }) } static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } static approve(collectionID) { return http.post(`/zebedee/approve/${collectionID}`); } static delete(collectionID) { return http.delete(`/zebedee/collection/${collectionID}`); } static update(collectionID, body) { body.id = collectionID; return http.put(`/zebedee/collection/${collectionID}`, body); } static deletePage(collectionID, pageURI) { return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`); } static cancelDelete(collectionID, pageURI) { return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } static async checkContentIsInCollection(pageURI) { return http.get(`/zebedee/checkcollectionsforuri?uri=${pageURI}`) } static getInProgressContent(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response.inProgress; }) } }
import http from '../http'; export default class collections { static get(collectionID) { return http.get(`/zebedee/collectionDetails/${collectionID}`) .then(response => { return response; }) } static getAll() { return http.get(`/zebedee/collections`) .then(response => { return response; }) } static create(body) { return http.post(`/zebedee/collection`, body) .then(response => { return response; }) } static approve(collectionID) { return http.post(`/zebedee/approve/${collectionID}`); } static delete(collectionID) { return http.delete(`/zebedee/collection/${collectionID}`); } static update(collectionID, body) { body.id = collectionID; return http.put(`/zebedee/collection/${collectionID}`, body); } static deletePage(collectionID, pageURI) { return http.delete(`/zebedee/content/${collectionID}?uri=${pageURI}`); } static cancelDelete(collectionID, pageURI) { return http.delete(`/zebedee/DeleteContent/${collectionID}?uri=${pageURI}`); } static async checkContentIsInCollection(pageURI) { return http.get(`/zebedee/checkcollectionsforuri?uri=${pageURI}`) } }
Add signal handler deregistration example
package com.github.hypfvieh.dbus.examples.signal; import java.io.IOException; import org.freedesktop.dbus.connections.impl.DBusConnection; import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder; import org.freedesktop.dbus.exceptions.DBusException; import org.freedesktop.dbus.handlers.AbstractPropertiesChangedHandler; import org.freedesktop.dbus.interfaces.Properties.PropertiesChanged; /** * This example code demonstrates how to register a callback for a signal. * A global {@link PropertiesChanged} handler is installed, which is queried * for every properties changed event on the bus. * * @author hypfvieh */ public class PropertiesChangedSignal { public static void main(String[] _args) throws Exception { // Open connection to the system bus. try (DBusConnection connection = DBusConnectionBuilder.forSystemBus().build()) { // Add a signal handler. final var token = connection.addSigHandler(PropertiesChanged.class, new PropChangedHandler()); // Pause to see events written to stdout (your code would differ). System.out.println("sleeping"); Thread.sleep(60000L); System.out.println("shutting down"); // Remove the signal handler. token.close(); } } /** * This handler will be called for every property change signal. */ public static class PropChangedHandler extends AbstractPropertiesChangedHandler { @Override public void handle(PropertiesChanged _s) { System.out.println("changed: " + _s.getPropertiesChanged()); } } }
package com.github.hypfvieh.dbus.examples.signal; import java.io.IOException; import org.freedesktop.dbus.connections.impl.DBusConnection; import org.freedesktop.dbus.connections.impl.DBusConnectionBuilder; import org.freedesktop.dbus.exceptions.DBusException; import org.freedesktop.dbus.handlers.AbstractPropertiesChangedHandler; import org.freedesktop.dbus.interfaces.Properties.PropertiesChanged; /** * Sample on how to register a callback for a signal. * <p> * In this case a global {@link PropertiesChanged} handler is installed. * It will be queried for every properties changed event on the bus. * * @author hypfvieh */ public class PropertiesChangedSignal { public static void main(String[] _args) throws DBusException, InterruptedException, IOException { // open connection to SYSTEM Bus try (DBusConnection connection = DBusConnectionBuilder.forSystemBus().build()) { // add our signal handler connection.addSigHandler(PropertiesChanged.class, new PropChangedHandler()); // just do some sleep so you can see the events on stdout (you would probably do something else here) System.out.println("sleeping"); Thread.sleep(60000L); System.out.println("shutting down"); } } /** * This handler will be called for every property change signal. */ public static class PropChangedHandler extends AbstractPropertiesChangedHandler { @Override public void handle(PropertiesChanged _s) { System.out.println("changed: " + _s.getPropertiesChanged()); } } }
Clean up how UI is used
'use strict'; var Q = require('q'), scorer = require('./scorer'), ui = require('./ui'); module.exports = { play: function(board, player_x, player_o) { var self = this; return Q.promise(function(resolve) { self .get_play(board, player_x, player_o) .then(function(choice) { board.set(choice, scorer.turn(board)); if (!scorer.is_over(board)) { resolve(self.play(board, player_x, player_o)); } else { var ending_message = (scorer.is_tied(board)) ? 'Tied!' : scorer.winner(board) + ' wins!'; ui.ending(board, ending_message); resolve(); } }); }); }, get_play: function(board, player_x, player_o) { var current_player; if (scorer.turn(board) === 'x') { current_player = player_x; } else { current_player = player_o; } if (current_player.type === 'human') { ui.print_board(board); } return current_player.play(board); } };
'use strict'; var Q = require('q'), scorer = require('./scorer'), print = require('./board/print'); module.exports = { play: function(board, player_x, player_o) { var self = this; return Q.promise(function(resolve) { self .get_play(board, player_x, player_o) .then(function(choice) { board.set(choice, scorer.turn(board)); if (scorer.is_over(board)) { resolve(); } else { resolve(self.play(board, player_x, player_o)); } }); }); }, get_play: function(board, player_x, player_o) { var current_player; if (scorer.turn(board) === 'x') { current_player = player_x; } else { current_player = player_o; } if (current_player.type === 'human') { print.rows(board.horizontal_rows()); } return current_player.play(board); } };
Fix issue with multiple files upload Correctly handle onChange event using fileOrGroup primise
'use strict'; /** * @ngdoc directive * @name angular-uploadcare.directive:Uploadcare * @description Provides a directive for the Uploadcare widget. * # Uploadcare */ angular.module('ng-uploadcare', []) .directive('uploadcareWidget', function () { return { restrict: 'A', require: 'ngModel', scope: { onWidgetReady: '&', onUploadComplete: '&', onChange: '&', ngModel: '=' }, controller: ['$scope', '$element', '$attrs', '$log', function($scope, $element, $attrs, $log) { if(!uploadcare) { $log.error('Uploadcare script has not been loaded!.'); return; } $element.attr('type', 'hidden'); $scope.widget = uploadcare.Widget($element); $scope.onWidgetReady({widget: $scope.widget}); $scope.widget.onUploadComplete(function(info) { $scope.onUploadComplete({info: info}); }); $scope.widget.onChange(function(fileOrGroup) { // add data binding for hidden inputs if (fileOrGroup) { fileOrGroup.promise().done(function(info) { $scope.$apply(function () { $scope.ngModel = $element.val() }); }); } $scope.onChange({file: fileOrGroup}); }) }] }; });
'use strict'; /** * @ngdoc directive * @name angular-uploadcare.directive:Uploadcare * @description Provides a directive for the Uploadcare widget. * # Uploadcare */ angular.module('ng-uploadcare', []) .directive('uploadcareWidget', function () { return { restrict: 'A', require: 'ngModel', scope: { onWidgetReady: '&', onUploadComplete: '&', onChange: '&', }, controller: ['$scope', '$element', '$attrs', '$parse', '$log', function($scope, $element, $attrs, $parse, $log) { if(!uploadcare) { $log.error('Uploadcare script has not been loaded!.'); return; } $element.attr('type', 'hidden'); $scope.widget = uploadcare.Widget($element); $scope.onWidgetReady({widget: $scope.widget}); $scope.widget.onUploadComplete(function(info) { $scope.onUploadComplete({info: info}); }); $scope.widget.onChange(function(file) { // add data binding for hidden inputs $scope.$apply(function () { $parse($attrs.ngModel).assign($scope.$parent, $element.val()); }); $scope.onChange({file: file}); }) }] }; });
Add bumpversion as a dev requirement.
from setuptools import setup, find_packages setup( name='jawa', packages=find_packages(), version='2.1.1', python_requires='>=3.6', description='Doing fun stuff with JVM ClassFiles.', long_description=open('README.md', 'r').read(), long_description_content_type='text/markdown', author='Tyler Kennedy', author_email='[email protected]', url='http://github.com/TkTech/Jawa', keywords=[ 'java', 'disassembly', 'disassembler', 'assembly' ], include_package_data=True, classifiers=[ 'Programming Language :: Python', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Disassemblers', 'Topic :: Software Development :: Assemblers' ], install_requires=[ 'click>=5.0' ], tests_require=[ 'pytest>=2.10', ], extras_require={ 'dev': [ 'pytest', 'sphinx', 'sphinxcontrib-googleanalytics', 'sphinx_rtd_theme', 'sphinx-click', 'ghp-import', 'pyyaml', 'ipython', 'twine', 'wheel', 'bumpversion' ] }, entry_points=''' [console_scripts] jawa=jawa.cli:cli ''' )
from setuptools import setup, find_packages setup( name='jawa', packages=find_packages(), version='2.1.1', python_requires='>=3.6', description='Doing fun stuff with JVM ClassFiles.', long_description=open('README.md', 'r').read(), long_description_content_type='text/markdown', author='Tyler Kennedy', author_email='[email protected]', url='http://github.com/TkTech/Jawa', keywords=[ 'java', 'disassembly', 'disassembler', 'assembly' ], include_package_data=True, classifiers=[ 'Programming Language :: Python', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Disassemblers', 'Topic :: Software Development :: Assemblers' ], install_requires=[ 'click>=5.0' ], tests_require=[ 'pytest>=2.10', ], extras_require={ 'dev': [ 'pytest', 'sphinx', 'sphinxcontrib-googleanalytics', 'sphinx_rtd_theme', 'sphinx-click', 'ghp-import', 'pyyaml', 'ipython', 'twine', 'wheel' ] }, entry_points=''' [console_scripts] jawa=jawa.cli:cli ''' )
Fix index names in migrations This can be reverted when we upgrade to Laravel 5.7.
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Flarum\Database\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Builder; return [ 'up' => function (Builder $schema) { // Delete rows with non-existent entities so that we will be able to create // foreign keys without any issues. $schema->getConnection() ->table('post_likes') ->whereNotExists(function ($query) { $query->selectRaw(1)->from('posts')->whereColumn('id', 'post_id'); }) ->orWhereNotExists(function ($query) { $query->selectRaw(1)->from('users')->whereColumn('id', 'user_id'); }) ->delete(); $schema->table('post_likes', function (Blueprint $table) use ($schema) { $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); Migration::fixIndexNames($schema, $table); }); }, 'down' => function (Builder $schema) { $schema->table('post_likes', function (Blueprint $table) use ($schema) { $table->dropForeign(['post_id', 'user_id']); Migration::fixIndexNames($schema, $table); }); } ];
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Builder; return [ 'up' => function (Builder $schema) { // Delete rows with non-existent entities so that we will be able to create // foreign keys without any issues. $schema->getConnection() ->table('post_likes') ->whereNotExists(function ($query) { $query->selectRaw(1)->from('posts')->whereColumn('id', 'post_id'); }) ->orWhereNotExists(function ($query) { $query->selectRaw(1)->from('users')->whereColumn('id', 'user_id'); }) ->delete(); $schema->table('post_likes', function (Blueprint $table) { $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); }, 'down' => function (Builder $schema) { $schema->table('post_likes', function (Blueprint $table) { $table->dropForeign(['post_id', 'user_id']); }); } ];
Add bluepring to table definition
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAnimalTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('animal', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string("name", 255); $table->integer("dob")->nullable(); $table->enum("gender", ["male", "female"]); $table->integer("father")->unsigned()->nullable(); $table->integer("mother")->unsigned()->nullable(); $table->boolean("active")->default(false); $table->boolean("own")->default(false); $table->dateTime('created_at'); $table->dateTime('updated_at'); }); Schema::table('animal', function (Blueprint $table) { $table->foreign("father")->references("id")->on("animal"); $table->foreign("mother")->references("id")->on("animal"); $table->unique(["name", "dob"]); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('animal'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAnimalTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('animal', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->string("name", 255); $table->integer("dob")->nullable(); $table->enum("gender", ["male", "female"]); $table->integer("father")->unsigned()->nullable(); $table->integer("mother")->unsigned()->nullable(); $table->boolean("active")->default(false); $table->boolean("own")->default(false); $table->dateTime('created_at'); $table->dateTime('updated_at'); }); Schema::table('animal', function($table) { $table->foreign("father")->references("id")->on("animal"); $table->foreign("mother")->references("id")->on("animal"); $table->unique(["name", "dob"]); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('animal'); } }
Reduce reprocessing factor from 90% to 86%.
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\TaxRate; use App\ReprocessedMaterial; use Illuminate\Support\Facades\Log; class UpdateOreValues implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 3; /** * Execute the job. * * @return void */ public function handle() { // Grab all tax rate records, and all stored current values for materials (keyed by id). $tax_rates = TaxRate::all(); $material_values = ReprocessedMaterial::select('materialTypeID', 'average_price')->get()->keyBy('materialTypeID'); // Loop through the rates, calculating the total value per unit of ore. foreach ($tax_rates as $rate) { $total_unit_cost = 0; $materials = $rate->reprocessed_materials; foreach ($materials as $material) { $total_unit_cost += $material_values[$material->materialTypeID]->average_price * ($material->quantity * 0.86); } $rate->value = $total_unit_cost / 100; $rate->save(); Log::info('UpdateOreValues: calculated and saved unit cost for ore ' . $rate->type_id); } } }
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\TaxRate; use App\ReprocessedMaterial; use Illuminate\Support\Facades\Log; class UpdateOreValues implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $tries = 3; /** * Execute the job. * * @return void */ public function handle() { // Grab all tax rate records, and all stored current values for materials (keyed by id). $tax_rates = TaxRate::all(); $material_values = ReprocessedMaterial::select('materialTypeID', 'average_price')->get()->keyBy('materialTypeID'); // Loop through the rates, calculating the total value per unit of ore. foreach ($tax_rates as $rate) { $total_unit_cost = 0; $materials = $rate->reprocessed_materials; foreach ($materials as $material) { $total_unit_cost += $material_values[$material->materialTypeID]->average_price * ($material->quantity * 0.9); } $rate->value = $total_unit_cost / 100; $rate->save(); Log::info('UpdateOreValues: calculated and saved unit cost for ore ' . $rate->type_id); } } }
Correct remove element callback to onClick from onChange
import React, { Component, PropTypes } from 'react'; class CheckList extends Component { checkInputKeyPress(evt) { if (evt.key === 'Enter') { this.props.taskCallbacks.add(this.props.cardId, evt.target.value); evt.target.value = ''; } } render() { let tasks = this.props.tasks.map((task, taskIndex) => ( <li key={ task.id } className="checklist__task"> <input type="checkbox" defaultChecked={ task.done } onChange={ this.props.taskCallbacks.toggle.bind(null, this.props.cardId, task.id, taskIndex) } /> { task.name } <a href="#" className="checklist__task--remove" onClick={ this.props.taskCallbacks.delete.bind(null, this.props.cardId, task.id, taskIndex) }/> </li> )); return ( <div className="checklist"> <ul> { tasks } </ul> <input type="text" className="checklist--add-task" placeholder="Type then hit Enter to add a task" onKeyPress={this.checkInputKeyPress.bind(this)}/> </div> ); } } CheckList.propTypes = { cardId: PropTypes.number, tasks: PropTypes.arrayOf(PropTypes.object), taskCallbacks: PropTypes.object }; export default CheckList;
import React, { Component, PropTypes } from 'react'; class CheckList extends Component { checkInputKeyPress(evt) { if (evt.key === 'Enter') { this.props.taskCallbacks.add(this.props.cardId, evt.target.value); evt.target.value = ''; } } render() { let tasks = this.props.tasks.map((task, taskIndex) => ( <li key={ task.id } className="checklist__task"> <input type="checkbox" defaultChecked={ task.done } onChange={ this.props.taskCallbacks.toggle.bind(null, this.props.cardId, task.id, taskIndex) } /> { task.name } <a href="#" className="checklist__task--remove" onChange={ this.props.taskCallbacks.delete.bind(null, this.props.cardId, task.id, taskIndex) }/> </li> )); return ( <div className="checklist"> <ul> { tasks } </ul> <input type="text" className="checklist--add-task" placeholder="Type then hit Enter to add a task" onKeyPress={this.checkInputKeyPress.bind(this)}/> </div> ); } } CheckList.propTypes = { cardId: PropTypes.number, tasks: PropTypes.arrayOf(PropTypes.object), taskCallbacks: PropTypes.object }; export default CheckList;
Add wrapping modulators for js and rename amd.
compiler.mode.compile = def( [ compiler.bootstrap.generator, compiler.compile.compiler, compiler.compile.configurator ], function (generator, compiler, configurator) { var run = function (config, outdir /*, mains */) { var mains = Array.prototype.slice.call(arguments, 2); var modulator = configurator.load(config); mains.forEach(function (main) { compiler.compile(modulator, main, outdir + '/' + main + '.js'); }); var hookup = '(function () {\n' + ' var pather = ephox.bolt.module.bootstrap.pather;\n' + ' var install = ephox.bolt.module.bootstrap.install;\n' + ' install.install(ephox.bolt.module.runtime, pather.compile());\n' + '})();'; var modulators = mains.map(function (main) { return modulator.modulate(main).config(); }).join(',\n '); var configuration = 'ephox.bolt.module.runtime.configure(function (pather) {\n' + ' return [\n' + ' ' + modulators + '\n' + ' ];\n' + '});'; generator.generate(outdir + '/bootstrap.js', hookup + '\n' + configuration); }; return { run: run }; } );
compiler.mode.compile = def( [ compiler.bootstrap.generator, compiler.compile.compiler, compiler.compile.configurator ], function (generator, compiler, configurator) { var run = function (config, outdir /*, mains */) { var mains = Array.prototype.slice.call(arguments, 2); var modulator = configurator.load(config); var compile = function (main) { compiler.compile(modulator, main, outdir + '/' + main + '.js'); }; mains.forEach(compile); var hookup = '(function () {\n' + ' var pather = ephox.bolt.module.bootstrap.pather;\n' + ' var install = ephox.bolt.module.bootstrap.install;\n' + ' install.install(ephox.bolt.module.runtime, pather.compile());\n' + '})();'; var modulators = mains.map(function (main) { return modulator.modulate(main).config(); }).join(',\n '); var configuration = 'ephox.bolt.module.runtime.configure(function (pather) {\n' + ' return [\n' + ' ' + modulators + '\n' + ' ];\n' + '});'; generator.generate(outdir + '/bootstrap.js', hookup + '\n' + configuration); }; return { run: run }; } );
Make the python script silent
#! /usr/bin/env python import sys import re import yaml FILE = sys.argv[1] YAML = sys.argv[2] TYPE = sys.argv[3] header = open(YAML, "r") text = open(FILE, "r") copy = open(FILE+"_NEW", "wt") docs = yaml.load_all(header) for doc in docs: if not doc == None: if 'figure' in doc.keys(): for line in text: mfig = False for f in doc['figure']: my_regex = r"^!\{" + re.escape(f['id']) + r"\}$" if re.search(my_regex, line, re.IGNORECASE): mfig = True if TYPE == 'preprint': ftype = "figure" fwidth = "\\columnwidth" if "wide" in f.keys(): ftype = "figure*" fwidth = "\\textwidth" copy.write("\n\\begin{" + ftype + "}[bt]\n") copy.write("\t\\centering\n") copy.write("\t\\includegraphics[width=" + fwidth + "]{" + f['file'] + "}\n") copy.write("\t\\caption{" + f['caption'] + "}\n") copy.write("\t\\label{" + f['id'] + "}\n") copy.write("\\end{" + ftype + "}\n\n") if not mfig: copy.write(line) header.close() text.close() copy.close()
#! /usr/bin/env python import sys import re import yaml FILE = sys.argv[1] YAML = sys.argv[2] TYPE = sys.argv[3] header = open(YAML, "r") text = open(FILE, "r") copy = open(FILE+"_NEW", "wt") docs = yaml.load_all(header) for doc in docs: if not doc == None: if 'figure' in doc.keys(): for line in text: mfig = False for f in doc['figure']: my_regex = r"^!\{" + re.escape(f['id']) + r"\}$" if re.search(my_regex, line, re.IGNORECASE): mfig = True print line if TYPE == 'preprint': ftype = "figure" fwidth = "\\columnwidth" if "wide" in f.keys(): ftype = "figure*" fwidth = "\\textwidth" copy.write("\n\\begin{" + ftype + "}[bt]\n") copy.write("\t\\centering\n") print f copy.write("\t\\includegraphics[width=" + fwidth + "]{" + f['file'] + "}\n") copy.write("\t\\caption{" + f['caption'] + "}\n") copy.write("\t\\label{" + f['id'] + "}\n") copy.write("\\end{" + ftype + "}\n\n") if not mfig: copy.write(line) header.close() text.close() copy.close()
Add GUI support for Travis
module.exports = function(config) { var configuration = { client: { captureConsole: false }, plugins: [ 'karma-chai', 'karma-sinon', 'karma-mocha', 'karma-chrome-launcher' ], frameworks: ['mocha', 'sinon', 'chai'], files: [ //- lib "lib/three.js/build/three.js", "lib/ColladaLoader/index.js", "lib/isMobile/isMobile.min.js", "lib/detector/index.js", //- app "src/javascript/helpers/*.js", "src/javascript/control/*.js", "src/javascript/models/*.js", "src/javascript/scene/*.js", "src/javascript/simulator/*.js", //- test 'test/utils/**/*.js', 'test/unit/**/*.js' ], reporters: ['progress'], browsers: ['Chrome'], singleRun: false } if(process.env.TRAVIS){ configuration.browsers = ['Chrome_travis_ci']; } config.set(configuration); }
module.exports = function(config) { config.set({ client: { captureConsole: false }, plugins: [ 'karma-chai', 'karma-sinon', 'karma-mocha', 'karma-chrome-launcher' ], frameworks: ['mocha', 'sinon', 'chai'], files: [ //- lib "lib/three.js/build/three.js", "lib/ColladaLoader/index.js", "lib/isMobile/isMobile.min.js", "lib/detector/index.js", //- app "src/javascript/helpers/*.js", "src/javascript/control/*.js", "src/javascript/models/*.js", "src/javascript/scene/*.js", "src/javascript/simulator/*.js", //- test 'test/utils/**/*.js', 'test/unit/**/*.js' ], reporters: ['progress'], browsers: ['Chrome'], singleRun: false }); }
Use id_sequence_to_embedding and only forward document
import tensorflow as tf from ..embedding import id_sequence_to_embedding, embeddings from ..linear import linear from ..dropout import dropout def char2doc(document, *, char_space_size, char_embedding_size, document_embedding_size, dropout_prob, hidden_layer_size, output_layer_size, context_vector_size): with tf.variable_scope("char2doc"): char_embeddings = embeddings(id_space_size=char_space_size, embedding_size=char_embedding_size) document_embedding = id_sequence_to_embedding( document, char_embeddings, output_embedding_size=document_embedding_size, context_vector_size=context_vector_size) hidden_layer = dropout(_activate(linear(_activate(document_embedding), hidden_layer_size)), dropout_prob) return linear(hidden_layer, output_layer_size) def _activate(tensor): return tf.nn.elu(tensor)
import tensorflow as tf from ..embedding import embeddings_to_embedding, ids_to_embeddings, embeddings from ..linear import linear from ..dropout import dropout def char2doc(forward_document, backward_document, *, char_space_size, char_embedding_size, document_embedding_size, dropout_prob, hidden_layer_size, output_layer_size, context_vector_size): with tf.variable_scope("char2doc"): char_embeddings = embeddings(id_space_size=char_space_size, embedding_size=char_embedding_size) def char_ids_to_doc_embedding(document): return embeddings_to_embedding( ids_to_embeddings(document, char_embeddings), output_embedding_size=document_embedding_size, context_vector_size=context_vector_size) document_embedding = tf.concat( 1, list(map(char_ids_to_doc_embedding, [forward_document, backward_document]))) hidden_layer = dropout(_activate(linear(_activate(document_embedding), hidden_layer_size)), dropout_prob) return linear(hidden_layer, output_layer_size) def _activate(tensor): return tf.nn.elu(tensor)
Clean POST data after validation
<?php /** * FormSafe * * PHP version 5 * * @category Library * @package PyritePHP * @author Stéphane Lavergne <[email protected]> * @copyright 2016 Stéphane Lavergne * @license https://opensource.org/licenses/MIT MIT * @link https://github.com/vphantom/pyrite-php */ namespace FormSafe; /** * Produce an opaque form name unique to current session * * @param string $form_name Application-wide unique name for this form * * @return string */ function hashname($form_name) { return 'form' . md5($form_name . session_id()); } on( 'form_begin', function ($form_name) { $name = hashname($form_name); $token = md5(mcrypt_create_iv(32)); $_SESSION[$name] = $token; return '<input type="hidden" name="'.$name.'" value="'.$token.'" />'; } ); on( 'form_validate', function ($form_name) { $name = hashname($form_name); $sess = (isset($_SESSION[$name]) ? $_SESSION[$name] : false); $_SESSION[$name] = ' '; unset($_SESSION[$name]); if ($sess && isset($_POST[$name]) && $_POST[$name] === $sess) { unset $_POST[$name]; return true; } else { $_POST = array(); return false; }; } );
<?php /** * FormSafe * * PHP version 5 * * @category Library * @package PyritePHP * @author Stéphane Lavergne <[email protected]> * @copyright 2016 Stéphane Lavergne * @license https://opensource.org/licenses/MIT MIT * @link https://github.com/vphantom/pyrite-php */ namespace FormSafe; /** * Produce an opaque form name unique to current session * * @param string $form_name Application-wide unique name for this form * * @return string */ function hashname($form_name) { return 'form' . md5($form_name . session_id()); } on( 'form_begin', function ($form_name) { $name = hashname($form_name); $token = md5(mcrypt_create_iv(32)); $_SESSION[$name] = $token; return '<input type="hidden" name="'.$name.'" value="'.$token.'" />'; } ); on( 'form_validate', function ($form_name) { $name = hashname($form_name); $sess = (isset($_SESSION[$name]) ? $_SESSION[$name] : false); $_SESSION[$name] = ' '; unset($_SESSION[$name]); if ($sess && isset($_POST[$name]) && $_POST[$name] === $sess) { return true; } else { $_POST = array(); return false; }; } );
Make it work with new tg Jinja quickstart
from setuptools import setup, find_packages import os version = '0.5.1' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description="Admin Controller add-on for basic TG identity model.", long_description=README + "\n" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin', author='Christopher Perkins', author_email='[email protected]', url='tgtools.googlecode.com', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'tgext.crud>=0.5.1', # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
from setuptools import setup, find_packages import os version = '0.5.1' here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read() except IOError: README = CHANGES = '' setup(name='tgext.admin', version=version, description="Admin Controller add-on for basic TG identity model.", long_description=README + "\n" + CHANGES, # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=[ "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ], keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin', author='Christopher Perkins', author_email='[email protected]', url='tgtools.googlecode.com', license='MIT', packages=find_packages(exclude=['ez_setup']), namespace_packages=['tgext'], include_package_data=True, zip_safe=True, install_requires=[ 'setuptools', 'tgext.crud>=0.4', # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
Add use strict to brunch config
'use strict' exports.config = { files: { javascripts: { joinTo: { 'vendor.js': /^vendor/ }, entryPoints: { 'app/index.js': 'app.js' } }, stylesheets: { joinTo: 'app.css' } }, plugins: { postcss: { processors: [ require('postcss-import')(), require('postcss-cssnext')() ] }, static: { processors: [ require('html-brunch-static')({ handlebars: { enableProcessor: true, helpers: { urlprefix () { const url = process.env.DOMAIN || 'makenew.github.io' const baseurl = typeof process.env.BASEURL === 'string' ? process.env.BASEURL : '/tasty-brunch' return `https://${url}${baseurl}` }, join (context, block) { return context.join(block.hash.delimiter) }, updated_time () { return new Date().toISOString() } } } }) ] } } }
exports.config = { files: { javascripts: { joinTo: { 'vendor.js': /^vendor/ }, entryPoints: { 'app/index.js': 'app.js' } }, stylesheets: { joinTo: 'app.css' } }, plugins: { postcss: { processors: [ require('postcss-import')(), require('postcss-cssnext')() ] }, static: { processors: [ require('html-brunch-static')({ handlebars: { enableProcessor: true, helpers: { urlprefix () { const url = process.env.DOMAIN || 'makenew.github.io' const baseurl = typeof process.env.BASEURL === 'string' ? process.env.BASEURL : '/tasty-brunch' return `https://${url}${baseurl}` }, join (context, block) { return context.join(block.hash.delimiter) }, updated_time () { return new Date().toISOString() } } } }) ] } } }
fix(Bundle): Update new package name including @plone scope.
process.traceDeprecation = true; const package_json = require("./package.json"); const path = require("path"); const patternslib_config = require("@patternslib/patternslib/webpack/webpack.config"); const mf_config = require("@patternslib/patternslib/webpack/webpack.mf"); module.exports = (env, argv) => { let config = { entry: { "bundle.min": path.resolve(__dirname, "src/index.js"), }, }; config = patternslib_config(env, argv, config, ["@plone/mockup"]); config.output.path = path.resolve(__dirname, "dist/"); config.plugins.push( mf_config({ package_json: package_json, remote_entry: config.entry["bundle.min"], }) ); if (process.env.NODE_ENV === "development") { // Note: ``publicPath`` is set to "auto" in Patternslib, // so for the devServer the public path set to "/". config.devServer.port = "8000"; config.devServer.static.directory = path.resolve(__dirname, "./docs/_site/"); } if (env && env.DEPLOYMENT === "plone") { config.output.path = path.resolve( __dirname, "../plone.staticresources/src/plone/staticresources/static/bundle-plone/" ); } return config; };
process.traceDeprecation = true; const package_json = require("./package.json"); const path = require("path"); const patternslib_config = require("@patternslib/patternslib/webpack/webpack.config"); const mf_config = require("@patternslib/patternslib/webpack/webpack.mf"); module.exports = (env, argv) => { let config = { entry: { "bundle.min": path.resolve(__dirname, "src/index.js"), }, }; config = patternslib_config(env, argv, config, ["mockup"]); config.output.path = path.resolve(__dirname, "dist/"); config.plugins.push( mf_config({ package_json: package_json, remote_entry: config.entry["bundle.min"], }) ); if (process.env.NODE_ENV === "development") { // Note: ``publicPath`` is set to "auto" in Patternslib, // so for the devServer the public path set to "/". config.devServer.port = "8000"; config.devServer.static.directory = path.resolve(__dirname, "./docs/_site/"); } if (env && env.DEPLOYMENT === "plone") { config.output.path = path.resolve( __dirname, "../plone.staticresources/src/plone/staticresources/static/bundle-plone/" ); } return config; };
fix: Use timezone.now() instead of datetime.now()
# -*- coding: utf-8 -*- from datetime import timedelta from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.utils import timezone from nopassword.models import LoginCode class NoPasswordBackend(ModelBackend): def authenticate(self, request, username=None, code=None, **kwargs): if username is None: username = kwargs.get(get_user_model().USERNAME_FIELD) if not username or not code: return try: user = get_user_model()._default_manager.get_by_natural_key(username) if not self.user_can_authenticate(user): return timeout = getattr(settings, 'NOPASSWORD_LOGIN_CODE_TIMEOUT', 900) timestamp = timezone.now() - timedelta(seconds=timeout) # We don't delete the login code when authenticating, # as that is done during validation of the login form # and validation should not have any side effects. # It is the responsibility of the view/form to delete the token # as soon as the login was successfull. user.login_code = LoginCode.objects.get(user=user, code=code, timestamp__gt=timestamp) return user except (get_user_model().DoesNotExist, LoginCode.DoesNotExist): return def send_login_code(self, code, context, **kwargs): raise NotImplementedError
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from nopassword.models import LoginCode class NoPasswordBackend(ModelBackend): def authenticate(self, request, username=None, code=None, **kwargs): if username is None: username = kwargs.get(get_user_model().USERNAME_FIELD) if not username or not code: return try: user = get_user_model()._default_manager.get_by_natural_key(username) if not self.user_can_authenticate(user): return timeout = getattr(settings, 'NOPASSWORD_LOGIN_CODE_TIMEOUT', 900) timestamp = datetime.now() - timedelta(seconds=timeout) # We don't delete the login code when authenticating, # as that is done during validation of the login form # and validation should not have any side effects. # It is the responsibility of the view/form to delete the token # as soon as the login was successfull. user.login_code = LoginCode.objects.get(user=user, code=code, timestamp__gt=timestamp) return user except (get_user_model().DoesNotExist, LoginCode.DoesNotExist): return def send_login_code(self, code, context, **kwargs): raise NotImplementedError
Fix the README file opening
from setuptools import setup NAME = "sphinxcontrib-runcode" VERSION = "0.0.1" DESCRIPTION = "Post included code in an executable pastebin like codepad / ideone." LONG_DESCRIPTION = open('README.md').read() AUTHOR = "Senthil Kumaran (Uthcode)" AUTHOR_EMAIL = "[email protected]" LICENSE = "BSD" URL = "http://github.com/uthcode/sphinxcontrib-runcode" DOWNLOAD_URL = "https://github.com/uthcode/sphinxcontrib-runcode/tree/downloads/packages" CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Text Processing', ] PLATFORMS = 'any' REQUIRES = ['Sphinx'] PACKAGES = ['sphinxcontrib'] ZIP_SAFE = False INCLUDE_PACKAGE_DATA = True NAMESPACE_PACKAGES = ['sphinxcontrib'] setup(name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, license=LICENSE, url=URL, download_url=DOWNLOAD_URL, classifiers=CLASSIFIERS, platforms=PLATFORMS, requires=REQUIRES, packages=PACKAGES, zip_safe=ZIP_SAFE, include_package_data=INCLUDE_PACKAGE_DATA, namespace_packages=NAMESPACE_PACKAGES)
from setuptools import setup NAME = "sphinxcontrib-runcode" VERSION = "0.0.1" DESCRIPTION = "Post included code in an executable pastebin like codepad / ideone." LONG_DESCRIPTION = open('README').read() AUTHOR = "Senthil Kumaran (Uthcode)" AUTHOR_EMAIL = "[email protected]" LICENSE = "BSD" URL = "http://github.com/uthcode/sphinxcontrib-runcode" DOWNLOAD_URL = "https://github.com/uthcode/sphinxcontrib-runcode/tree/downloads/packages" CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Text Processing', ] PLATFORMS = 'any' REQUIRES = ['Sphinx'] PACKAGES = ['sphinxcontrib'] ZIP_SAFE = False INCLUDE_PACKAGE_DATA = True NAMESPACE_PACKAGES = ['sphinxcontrib'] setup(name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, license=LICENSE, url=URL, download_url=DOWNLOAD_URL, classifiers=CLASSIFIERS, platforms=PLATFORMS, requires=REQUIRES, packages=PACKAGES, zip_safe=ZIP_SAFE, include_package_data=INCLUDE_PACKAGE_DATA, namespace_packages=NAMESPACE_PACKAGES)
Use self for php 5.3
<?php namespace Mockery\Generator; class DefinedTargetClass { private $rfc; public function __construct(\ReflectionClass $rfc) { $this->rfc = $rfc; } public static function factory($name) { return new self(new \ReflectionClass($name)); } public function getName() { return $this->rfc->getName(); } public function isAbstract() { return $this->rfc->isAbstract(); } public function isFinal() { return $this->rfc->isFinal(); } public function getMethods() { return array_map(function ($method) { return new Method($method); }, $this->rfc->getMethods()); } public function getInterfaces() { return array_map(function ($interface) { return new self($interface); }, $this->rfc->getInterfaces()); } public function __toString() { return $this->getName(); } public function getNamespaceName() { return $this->rfc->getNamespaceName(); } public function inNamespace() { return $this->rfc->inNamespace(); } public function getShortName() { return $this->rfc->getShortName(); } }
<?php namespace Mockery\Generator; class DefinedTargetClass { private $rfc; public function __construct(\ReflectionClass $rfc) { $this->rfc = $rfc; } public static function factory($name) { return new static(new \ReflectionClass($name)); } public function getName() { return $this->rfc->getName(); } public function isAbstract() { return $this->rfc->isAbstract(); } public function isFinal() { return $this->rfc->isFinal(); } public function getMethods() { return array_map(function ($method) { return new Method($method); }, $this->rfc->getMethods()); } public function getInterfaces() { return array_map(function ($interface) { return new static($interface); }, $this->rfc->getInterfaces()); } public function __toString() { return $this->getName(); } public function getNamespaceName() { return $this->rfc->getNamespaceName(); } public function inNamespace() { return $this->rfc->inNamespace(); } public function getShortName() { return $this->rfc->getShortName(); } }
Increase the timeout value for the VOMS Admin start-up from 60s to 120s. Primarily, this is driven by occasional timeouts in the VMU tests, which can run slowly on a heavily loaded host. git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@18485 4e558342-562e-0410-864c-e07659590f8c
import os import unittest import osgtest.library.core as core import osgtest.library.osgunittest as osgunittest class TestSetupVomsAdmin(osgunittest.OSGTestCase): def test_01_wait_for_voms_admin(self): core.state['voms.started-webapp'] = False core.skip_ok_unless_installed('voms-admin-server') line, gap = core.monitor_file(core.config['voms.webapp-log'], core.state['voms.webapp-log-stat'], 'VOMS-Admin started succesfully', 120.0) self.assert_(line is not None, 'VOMS Admin webapp started') core.state['voms.started-webapp'] = True core.log_message('VOMS Admin started after %.1f seconds' % gap) def test_02_open_access(self): core.skip_ok_unless_installed('voms-admin-server', 'voms-admin-client') self.skip_ok_unless(core.state['voms.started-webapp'], 'VOMS Admin webapp not started') command = ('voms-admin', '--nousercert', '--vo', core.config['voms.vo'], 'add-ACL-entry', '/' + core.config['voms.vo'], 'ANYONE', 'VOMS_CA', 'CONTAINER_READ,MEMBERSHIP_READ', 'true') core.check_system(command, 'Add VOMS Admin ACL entry')
import os import unittest import osgtest.library.core as core import osgtest.library.osgunittest as osgunittest class TestSetupVomsAdmin(osgunittest.OSGTestCase): def test_01_wait_for_voms_admin(self): core.state['voms.started-webapp'] = False core.skip_ok_unless_installed('voms-admin-server') line, gap = core.monitor_file(core.config['voms.webapp-log'], core.state['voms.webapp-log-stat'], 'VOMS-Admin started succesfully', 60.0) self.assert_(line is not None, 'VOMS Admin webapp started') core.state['voms.started-webapp'] = True core.log_message('VOMS Admin started after %.1f seconds' % gap) def test_02_open_access(self): core.skip_ok_unless_installed('voms-admin-server', 'voms-admin-client') self.skip_ok_unless(core.state['voms.started-webapp'], 'VOMS Admin webapp not started') command = ('voms-admin', '--nousercert', '--vo', core.config['voms.vo'], 'add-ACL-entry', '/' + core.config['voms.vo'], 'ANYONE', 'VOMS_CA', 'CONTAINER_READ,MEMBERSHIP_READ', 'true') core.check_system(command, 'Add VOMS Admin ACL entry')
Create var for temp and pass into HTML document
//Geolocation Function is listed below. function geoLocation() { var output = document.getElementById("out"); /*$.getJSON('https://ipinfo.io/geo', function(response) { var loc = response.loc.split(','); var coords = { latitude: loc[0], longitude: loc[1] }; var city = response.city; var state = response.region; var postal = response.postal; var country = response.country; output.innerHTML = "<p>Here is the weather for " + city + ", " + state;*/ $.getJSON('http://ip-api.com/json', function(response) { var city = response.city; var state = response.region; var zip = response.zip; var country = response.countryCode; var ip = response.query; output.innerHTML = "<p>Here is the weather for " + city + ", " + state; $.getJSON('http://api.openweathermap.org/data/2.5/weather?zip=' + zip + ',' + country + "&appid=ec96c6ed7e722bdd15cfebffbff509a6", function(data) { //var main = data.main.split(','); var temp = data.main.temp; console.log(temp); var weatherConditions = document.getElementById("conditions"); conditions.innerHTML = "<p>The current temperature is " + temp; }); }); }
//Geolocation Function is listed below. function geoLocation() { var output = document.getElementById("out"); /*$.getJSON('https://ipinfo.io/geo', function(response) { var loc = response.loc.split(','); var coords = { latitude: loc[0], longitude: loc[1] }; var city = response.city; var state = response.region; var postal = response.postal; var country = response.country; output.innerHTML = "<p>Here is the weather for " + city + ", " + state;*/ $.getJSON('http://ip-api.com/json', function(response) { var city = response.city; var state = response.region; var zip = response.zip; var country = response.countryCode; var ip = response.query; output.innerHTML = "<p>Here is the weather for " + city + ", " + state; $.getJSON('http://api.openweathermap.org/data/2.5/weather?zip=' + zip + ',' + country + "&appid=ec96c6ed7e722bdd15cfebffbff509a6", function(data) { var main = data.main.split(','); var conditons = { temp: main[0] }; console.log(temp); var weatherConditions = document.getElementById("conditions"); conditions.innerHTML = "<p>The current temperature is " + temp; }); }); }
Replace slug field with get_slug function
from django.db import models from django.utils.safestring import mark_safe from django.utils.translation import pgettext as _ from django_prices.models import PriceField from mptt.models import MPTTModel from satchless.item import ItemRange from satchless.util.models import Subtyped from unidecode import unidecode import re class Category(MPTTModel): name = models.CharField(_('Category field', 'name'), max_length=128) slug = models.SlugField(_('Category field', 'slug'), max_length=50, unique=True) description = models.TextField(_('Category field', 'description'), blank=True) parent = models.ForeignKey('self', null=True, related_name='children', blank=True, verbose_name=_('Category field', 'parent')) def __unicode__(self): return self.name class Product(Subtyped, ItemRange): name = models.CharField(_('Product field', 'name'), max_length=128) price = PriceField(_('Product field', 'price'), currency='USD', max_digits=12, decimal_places=4) category = models.ForeignKey(Category, verbose_name=_('Product field', 'category')) def __unicode__(self): return self.name def get_slug(self): value = unidecode(self.name) value = re.sub('[^\w\s-]', '', value).strip().lower() return mark_safe(re.sub('[-\s]+', '-', value)) @models.permalink def get_absolute_url(self): return ('product:details', [self.get_slug(), self.id])
from django.db import models from django.utils.translation import pgettext as _ from django_prices.models import PriceField from satchless.util.models import Subtyped from satchless.item import ItemRange from mptt.models import MPTTModel class Category(MPTTModel): name = models.CharField(_('Category field', 'name'), max_length=128) slug = models.SlugField(_('Category field', 'slug'), max_length=50, unique=True) description = models.TextField(_('Category field', 'description'), blank=True) parent = models.ForeignKey('self', null=True, related_name='children', blank=True, verbose_name=_('Category field', 'parent')) def __unicode__(self): return self.name class Product(Subtyped, ItemRange): name = models.CharField(_('Product field', 'name'), max_length=128) slug = models.SlugField(_('Product field', 'slug'), max_length=50, unique=True) price = PriceField(_('Product field', 'price'), currency='USD', max_digits=12, decimal_places=4) category = models.ForeignKey(Category, verbose_name=_('Product field', 'category')) def __unicode__(self): return self.name
Use the same app as deployed by the setup script Former-commit-id: 8fa2a956df16ece64642433626314625326d275c
import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys class TemplateTestCase(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.addCleanup(self.browser.quit) self.browser.get('http://localhost:8080/intermine-demo/templates.do') def elem(self, selector): return self.browser.find_element_by_css_selector(selector) def testTemplatesPageTitle(self): self.assertIn('Template queries', self.browser.title) def testFindTemplate(self): template_link = self.browser.find_element_by_link_text("Search for Managers") self.assertIsNotNone(template_link, "Expected to find link") self.assertTrue(template_link.is_displayed(), "Expected link to be visible to user") def testRunTemplate(self): template_link = self.browser.find_element_by_link_text("Search for Managers") template_link.click() self.assertIn('Search for Managers', self.browser.title) button = self.elem("#smallGreen.button input") self.assertIsNotNone(button, "Expected to find button to run template") button.click() summary = self.elem(".im-table-summary") self.assertIsNotNone(button, "Expected to find a summary of the template results") self.assertEqual("Showing 1 to 2 of 2 rows", summary.text)
import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys class TemplateTestCase(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.addCleanup(self.browser.quit) self.browser.get('http://localhost:8080/intermine-test/templates.do') def elem(self, selector): return self.browser.find_element_by_css_selector(selector) def testTemplatesPageTitle(self): self.assertIn('Template queries', self.browser.title) def testFindTemplate(self): template_link = self.browser.find_element_by_link_text("Search for Managers") self.assertIsNotNone(template_link, "Expected to find link") self.assertTrue(template_link.is_displayed(), "Expected link to be visible to user") def testRunTemplate(self): template_link = self.browser.find_element_by_link_text("Search for Managers") template_link.click() self.assertIn('Search for Managers', self.browser.title) button = self.elem("#smallGreen.button input") self.assertIsNotNone(button, "Expected to find button to run template") button.click() summary = self.elem(".im-table-summary") self.assertIsNotNone(button, "Expected to find a summary of the template results") self.assertEqual("Showing 1 to 2 of 2 rows", summary.text)
Fix problem with clearing purpose in search Closes #480
import React, { Component, PropTypes } from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; import Panel from 'react-bootstrap/lib/Panel'; import Select from 'react-select'; class AdvancedSearch extends Component { render() { const { isFetchingPurposes, onFiltersChange, filters, purposeOptions, } = this.props; const purposeSelectValue = purposeOptions.some(option => option.value === filters.purpose) ? filters.purpose : undefined; return ( <Panel collapsible defaultExpanded={Boolean(purposeSelectValue)} header="Tarkennettu haku" > <h4>Tilan käyttötarkoitus</h4> <Select clearable isLoading={isFetchingPurposes} name="purpose-filter-select" onChange={option => onFiltersChange({ purpose: option ? option.value : '' })} options={purposeOptions} placeholder=" " searchable={false} value={purposeSelectValue} /> <h4>Tilan henkilömäärä vähintään</h4> <FormControl min="0" name="people-capacity-filter" onChange={event => onFiltersChange({ people: event.target.value })} type="number" value={filters.people} /> </Panel> ); } } AdvancedSearch.propTypes = { isFetchingPurposes: PropTypes.bool.isRequired, onFiltersChange: PropTypes.func.isRequired, filters: PropTypes.object.isRequired, purposeOptions: PropTypes.array.isRequired, }; export default AdvancedSearch;
import React, { Component, PropTypes } from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; import Panel from 'react-bootstrap/lib/Panel'; import Select from 'react-select'; class AdvancedSearch extends Component { render() { const { isFetchingPurposes, onFiltersChange, filters, purposeOptions, } = this.props; const purposeSelectValue = purposeOptions.some(option => option.value === filters.purpose) ? filters.purpose : undefined; return ( <Panel collapsible defaultExpanded={Boolean(purposeSelectValue)} header="Tarkennettu haku" > <h4>Tilan käyttötarkoitus</h4> <Select clearable isLoading={isFetchingPurposes} name="purpose-filter-select" onChange={option => onFiltersChange({ purpose: option.value })} options={purposeOptions} placeholder=" " searchable={false} value={purposeSelectValue} /> <h4>Tilan henkilömäärä vähintään</h4> <FormControl min="0" name="people-capacity-filter" onChange={event => onFiltersChange({ people: event.target.value })} type="number" value={filters.people} /> </Panel> ); } } AdvancedSearch.propTypes = { isFetchingPurposes: PropTypes.bool.isRequired, onFiltersChange: PropTypes.func.isRequired, filters: PropTypes.object.isRequired, purposeOptions: PropTypes.array.isRequired, }; export default AdvancedSearch;
Implement HTTPS support for Docker
require('dotenv').config({ silent: true, }) let makeHostConfig = (env, prefix) => { let host = env[prefix + '_HOST'] || '127.0.0.1' let port = parseInt(env[prefix + '_PORT'], 10) || 3030 let https = env[prefix + '_HTTPS'] === 'true' || env[prefix + '_HTTPS'] === true let default_port, protocol if (https) { default_port = 443 protocol = 'https' } else { default_port = 80 protocol = 'http' } let url = protocol + '://' + host + (port === default_port ? '' : ':' + port) return { host, port, url, protocol, https, } } const env = process.env.APP_ENV || 'local' const atom = { announcement_url: process.env.ATOM_PLUGIN_ANNOUNCEMENT_URL || '#', } module.exports = { node: makeHostConfig(process.env, 'NODE'), api: makeHostConfig(process.env, 'API'), external: makeHostConfig(process.env, 'APP'), websocket: { host: process.env.ECHO_HOST || 'localhost', port: process.env.ECHO_PORT || '6002', }, debug: process.env.APP_DEBUG === 'true' || process.env.APP_DEBUG === true, env, production: env === 'production', dev: env !== 'production', atom, analytics_track_id: process.env.GOOGLE_ANALYTICS_TRACK_ID }
require('dotenv').config({ silent: true, }) let makeHostConfig = (env, prefix) => { let host = env[prefix + '_HOST'] || '127.0.0.1' let port = parseInt(env[prefix + '_PORT'], 10) || 3030 let https = env[prefix + '_HTTPS'] === 'true' || env[prefix + '_HTTPS'] === true let default_port, protocol if (https) { default_port = 443 protocol = 'https' } else { default_port = 80 protocol = 'http' } let url = protocol + '://' + host + (port === default_port ? '' : ':' + port) return { host, port, url, protocol, https, } } const env = process.env.APP_ENV || 'local' const atom = { announcement_url: process.env.ATOM_PLUGIN_ANNOUNCEMENT_URL || '#', } module.exports = { node: makeHostConfig(process.env, 'NODE'), api: makeHostConfig(process.env, 'API'), external: makeHostConfig(process.env, 'APP'), websocket: makeHostConfig(process.env, 'ECHO'), debug: process.env.APP_DEBUG === 'true' || process.env.APP_DEBUG === true, env, production: env === 'production', dev: env !== 'production', atom, analytics_track_id: process.env.GOOGLE_ANALYTICS_TRACK_ID }
Add error for invalid harness type
const { applyFieldDescriptor, createFieldDescriptor } = require("./fields.js"); class EntryFacade { constructor(entry) { this._entry = entry; } get entry() { return entry; } get fields() { return [ createFieldDescriptor( this.entry, "Username", "property", "username" ), createFieldDescriptor( this.entry, "Password", "property", "password", { protected: true } ) ]; } get title() { return this.entry.getProperty("title"); } get type() { return ""; } consumeInputHarness(harness) { if (harness && harness.type) { if (harness.type !== this.type) { throw new Error(`Failed consuming entry data: Expected type "${this.type}" but received "${harness.type}"`); } (harness.fields || []).forEach(field => applyFieldDescriptor(field)); } else { throw new Error("Failed consuming entry data: Invalid item passed as a harness"); } } generateInputHarness() { return { type: this.type, fields: this.fields }; } } module.exports = EntryFacade;
const { applyFieldDescriptor, createFieldDescriptor } = require("./fields.js"); class EntryFacade { constructor(entry) { this._entry = entry; } get entry() { return entry; } get fields() { return [ createFieldDescriptor( this.entry, "Username", "property", "username" ), createFieldDescriptor( this.entry, "Password", "property", "password", { protected: true } ) ]; } get title() { return this.entry.getProperty("title"); } get type() { return ""; } consumeInputHarness(harness) { if (harness && harness.type) { (harness.fields || []).forEach(field => applyFieldDescriptor(field)); } else { throw new Error("Invalid item passed as a harness"); } } generateInputHarness() { return { type: this.type, fields: this.fields }; } } module.exports = EntryFacade;
Add a postbuild task to grunt to remove unnecessary build artifacts
module.exports = function(grunt) { // load grunt tasks from package.json require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ clean: { dist: [ 'dist', 'robert/**/*.pyc', ], postbuild: [ 'dist/static/sass', ], }, compass: { dist: { options: { sassDir: 'robert/static/sass/', cssDir: 'robert/static/css/', outputStyle: 'compressed', } } }, concurrent: { server: { options: { logConcurrentOutput: true, }, tasks: ['watch', 'shell:devserver'] } }, shell: { options: { stdout: true, stderr: true, }, devserver: { command: 'python run_devserver.py', }, freeze: { command: 'python freeze.py', } }, watch: { options: { livereload: true, }, python: { files: ['robert/**/*.py'], tasks: [] }, sass: { files: ['robert/static/sass/*.scss'], tasks: ['compass'], }, templates: { files: ['robert/templates/*.html'], tasks: [], }, articles: { files: ['articles/*.md'], tasks: [], }, }, }); grunt.registerTask('default', [ 'build', 'concurrent:server', ]); grunt.registerTask('build', [ 'clean:dist', 'compass', 'shell:freeze', 'clean:postbuild', ]); };
module.exports = function(grunt) { // load grunt tasks from package.json require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ clean: { dist: [ 'dist', 'robert/**/*.pyc', ] }, compass: { dist: { options: { sassDir: 'robert/static/sass/', cssDir: 'robert/static/css/', outputStyle: 'compressed', } } }, concurrent: { server: { options: { logConcurrentOutput: true, }, tasks: ['watch', 'shell:devserver'] } }, shell: { options: { stdout: true, stderr: true, }, devserver: { command: 'python run_devserver.py', }, freeze: { command: 'python freeze.py', } }, watch: { options: { livereload: true, }, python: { files: ['robert/**/*.py'], tasks: [] }, sass: { files: ['robert/static/sass/*.scss'], tasks: ['compass'], }, templates: { files: ['robert/templates/*.html'], tasks: [], }, articles: { files: ['articles/*.md'], tasks: [], }, }, }); grunt.registerTask('default', [ 'build', 'concurrent:server', ]); grunt.registerTask('build', [ 'clean', 'compass', 'shell:freeze', ]); };
Set link failedCount to zero on success
<?php class Denkmal_Maintenance_Cli extends CM_Maintenance_Cli { /** * @synchronized */ protected function _registerCallbacks() { parent::_registerCallbacks(); $this->_registerClockworkCallbacks(new DateInterval('PT12H'), array( 'Scraper' => function () { foreach (Denkmal_Scraper_Source_Abstract::getAll() as $scraper) { $scraper->run(); } }, 'Check links' => function () { $linkList = new Denkmal_Paging_Link_All(); foreach ($linkList as $link) { /** @var Denkmal_Model_Link $link */ try { CM_Util::getContents($link->getUrl()); $link->setFailedCount(0); } catch (CM_Exception_Invalid $ex) { $link->setFailedCount($link->getFailedCount() + 1); } } }, )); } public static function getPackageName() { return 'maintenance'; } }
<?php class Denkmal_Maintenance_Cli extends CM_Maintenance_Cli { /** * @synchronized */ protected function _registerCallbacks() { parent::_registerCallbacks(); $this->_registerClockworkCallbacks(new DateInterval('PT12H'), array( 'Scraper' => function () { foreach (Denkmal_Scraper_Source_Abstract::getAll() as $scraper) { $scraper->run(); } }, 'Check links' => function () { $linkList = new Denkmal_Paging_Link_All(); foreach ($linkList as $link) { /** @var Denkmal_Model_Link $link */ try { CM_Util::getContents($link->getUrl()); } catch (CM_Exception_Invalid $ex) { $link->setFailedCount($link->getFailedCount() + 1); } } }, )); } public static function getPackageName() { return 'maintenance'; } }
Refactor to use 'in' instead of 'has_key'
import re from django.http import QueryDict class HttpMethodOverrideMiddleware: """ Facilitate for overriding the HTTP method with the X-HTTP-Method-Override header or a '_method' HTTP POST parameter. """ def process_request(self, request): if 'HTTP_X_HTTP_METHOD_OVERRIDE' in request.META \ or '_method' in request.POST: request.method = ( request.META.get('HTTP_X_HTTP_METHOD_OVERRIDE') or request.POST.get('_method') ).upper() if '_method' in request.POST: request._raw_post_data = re.sub(r'_method=(PUT|PATCH|DELETE)&?', '', request.raw_post_data) class HttpPutMiddleware: """ Facilitate for HTTP PUT in the same way Django facilitates for HTTP GET and HTTP POST; populate a QueryDict instance with the request body in request.PUT. """ def process_request(self, request): if request.method == 'PUT': request.PUT = QueryDict(request.raw_post_data) class HttpPatchMiddleware: """ Facilitate for HTTP PATCH in the same way Django facilitates for HTTP GET and HTTP POST; populate a QueryDict instance with the request body in request.PATCH. """ def process_request(self, request): if request.method == 'PATCH': request.PATCH = QueryDict(request.raw_post_data)
import re from django.http import QueryDict class HttpMethodOverrideMiddleware: """ Facilitate for overriding the HTTP method with the X-HTTP-Method-Override header or a '_method' HTTP POST parameter. """ def process_request(self, request): if request.META.has_key('HTTP_X_HTTP_METHOD_OVERRIDE') \ or request.POST.has_key('_method'): request.method = ( request.META.get('HTTP_X_HTTP_METHOD_OVERRIDE') or request.POST.get('_method') ).upper() if '_method' in request.POST: request._raw_post_data = re.sub(r'_method=(PUT|PATCH|DELETE)&?', '', request.raw_post_data) class HttpPutMiddleware: """ Facilitate for HTTP PUT in the same way Django facilitates for HTTP GET and HTTP POST; populate a QueryDict instance with the request body in request.PUT. """ def process_request(self, request): if request.method == 'PUT': request.PUT = QueryDict(request.raw_post_data) class HttpPatchMiddleware: """ Facilitate for HTTP PATCH in the same way Django facilitates for HTTP GET and HTTP POST; populate a QueryDict instance with the request body in request.PATCH. """ def process_request(self, request): if request.method == 'PATCH': request.PATCH = QueryDict(request.raw_post_data)
Document how output generators work
from abc import ABCMeta, abstractmethod from sslyze.cli import CompletedServerScan from sslyze.cli import FailedServerScan from sslyze.server_connectivity import ServerConnectivityInfo class OutputGenerator(object): """The abstract class output generator classes should inherit from. Each method must be implemented and will be called in the order below, as the SSLyze CLI runs scans. """ __metaclass__ = ABCMeta def __init__(self, file_to): # type: (file) -> None self._file_to = file_to def close(self): # type: (None) -> None self._file_to.close() @abstractmethod def command_line_parsed(self, available_plugins, args_command_list): """The CLI was just started and successfully parsed the command line. """ @abstractmethod def server_connectivity_test_failed(self, failed_scan): # type: (FailedServerScan) -> None """The CLI found a server that it could not connect to; no scans will be performed against this server. """ @abstractmethod def server_connectivity_test_succeeded(self, server_connectivity_info): # type: (ServerConnectivityInfo) -> None """The CLI found a server that it was able to connect to; scans will be run against this server. """ @abstractmethod def scans_started(self): # type: (None) -> None """The CLI has finished testing connectivity with the supplied servers and will now start the scans. """ @abstractmethod def server_scan_completed(self, server_scan_result): # type: (CompletedServerScan) -> None """The CLI has finished scanning one single server. """ @abstractmethod def scans_completed(self, total_scan_time): # type: (float) -> None """The CLI has finished scanning all the supplied servers and will now exit. """
from abc import ABCMeta, abstractmethod from sslyze.cli import CompletedServerScan from sslyze.cli import FailedServerScan from sslyze.server_connectivity import ServerConnectivityInfo class OutputGenerator(object): """The abstract class output generator classes should inherit from. Each method must be implemented and will be called in the order below, as the SSLyze CLI runs scans. """ __metaclass__ = ABCMeta def __init__(self, file_to): # type: (file) -> None self._file_to = file_to def close(self): # type: (None) -> None self._file_to.close() @abstractmethod def command_line_parsed(self, available_plugins, args_command_list): pass @abstractmethod def server_connectivity_test_failed(self, failed_scan): # type: (FailedServerScan) -> None pass @abstractmethod def server_connectivity_test_succeeded(self, server_connectivity_info): # type: (ServerConnectivityInfo) -> None pass @abstractmethod def scans_started(self): # type: (None) -> None pass @abstractmethod def server_scan_completed(self, server_scan_result): # type: (CompletedServerScan) -> None pass @abstractmethod def scans_completed(self, total_scan_time): # type: (float) -> None pass
Switch bookkeeping to record line offsets instead of line lengths. This should be simpler and more efficient.
type SourceLocation = { line: number, column: number }; export default class LinesAndColumns { constructor(string: string) { this.string = string; const offsets = []; let offset = 0; while (true) { offsets.push(offset); let next = string.indexOf('\n', offset); if (next < 0) { break; } else { next += '\n'.length; } offset = next; } this.offsets = offsets; } locationForIndex(index: number): ?SourceLocation { if (index < 0 || index >= this.string.length) { return null; } let line = 0; const offsets = this.offsets; while (offsets[line + 1] <= index) { line++; } const column = index - offsets[line]; return ({ line, column }: SourceLocation); } indexForLocation(location: SourceLocation): ?number { let { line, column } = location; if (line < 0 || line >= this.offsets.length) { return null; } if (column < 0 || column >= this._lengthOfLine(line)) { return null; } return this.offsets[line] + column; } /** * @private */ _lengthOfLine(line: number): number { const offset = this.offsets[line]; const nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1]; return nextOffset - offset; } }
type SourceLocation = { line: number, column: number }; export default class LinesAndColumns { constructor(string: string) { this.string = string; const lineLengths = []; let start = 0; while (true) { let end = string.indexOf('\n', start); if (end < 0) { end = string.length; } else { end += '\n'.length; } lineLengths.push(end - start); if (end === string.length) { break; } start = end; } this.lineLengths = lineLengths; } locationForIndex(index: number): ?SourceLocation { if (index < 0 || index >= this.string.length) { return null; } let line = 0; let column = index; const lineLengths = this.lineLengths; while (lineLengths[line] <= column && line + 1 < lineLengths.length) { column -= lineLengths[line]; line++; } return ({ line, column }: SourceLocation); } indexForLocation(location: SourceLocation): ?number { let { line, column } = location; if (line < 0 || line >= this.lineLengths.length) { return null; } if (column < 0 || column >= this.lineLengths[line]) { return null; } let index = 0; for (let i = line - 1; i >= 0; i--) { index += this.lineLengths[i]; } return index + column; } }
Add gateway token header for health check
const config = require('../config.js'); const {getCollection} = require('./dataAccess/dbMethods'); const logger = require('../../log.js'); const url = require('url'); const superagent = require('superagent'); const generateApiGatewayToken = require('../authentication/apiGateway'); module.exports = { nomisApiCheck, dbCheck }; function dbCheck() { return new Promise((resolve, reject) => { getCollection('SELECT 1 AS [ok]', null, resolve, reject); }); } function nomisApiCheck() { return new Promise((resolve, reject) => { const gwToken = process.env.NODE_ENV === 'test' ? 'dummy' : `Bearer ${generateApiGatewayToken()}`; superagent .get(url.resolve(`${config.nomis.apiUrl}`, '/api/info/health')) .set('Authorization', gwToken) .timeout({ response: 2000, deadline: 2500 }) .end((error, result) => { try { if (error) { logger.error(error, 'Error calling Nomis API'); return reject(error.status); } if (result.status === 200) { return resolve('OK'); } return reject(result.status); } catch (exception) { logger.error(exception, 'Exception calling Nomis API'); return reject(exception); } }); }); }
const config = require('../config.js'); const {getCollection} = require('./dataAccess/dbMethods'); const logger = require('../../log.js'); const url = require('url'); const superagent = require('superagent'); module.exports = { nomisApiCheck, dbCheck }; function dbCheck() { return new Promise((resolve, reject) => { getCollection('SELECT 1 AS [ok]', null, resolve, reject); }); } function nomisApiCheck() { return new Promise((resolve, reject) => { superagent .get(url.resolve(`${config.nomis.apiUrl}`, '/api/info/health')) .timeout({ response: 2000, deadline: 2500 }) .end((error, result) => { try { if (error) { logger.error(error, 'Error calling Nomis API'); return reject(error.status); } if (result.status === 200) { return resolve('OK'); } return reject(result.status); } catch (exception) { logger.error(exception, 'Exception calling Nomis API'); return reject(exception); } }); }); }
Reset email form value on success closes #3663 - Set value of email input as nil string
/* jshint unused: false */ import ajax from 'ghost/utils/ajax'; import ValidationEngine from 'ghost/mixins/validation-engine'; var ForgottenController = Ember.Controller.extend(ValidationEngine, { email: '', submitting: false, // ValidationEngine settings validationType: 'forgotten', actions: { submit: function () { var self = this, data = self.getProperties('email'); this.toggleProperty('submitting'); this.validate({ format: false }).then(function () { ajax({ url: self.get('ghostPaths.url').api('authentication', 'passwordreset'), type: 'POST', data: { passwordreset: [{ email: data.email }] } }).then(function (resp) { self.toggleProperty('submitting'); self.notifications.showSuccess('Please check your email for instructions.', {delayed: true}); self.set('email', ''); self.transitionToRoute('signin'); }).catch(function (resp) { self.toggleProperty('submitting'); self.notifications.showAPIError(resp, { defaultErrorText: 'There was a problem logging in, please try again.' }); }); }).catch(function (errors) { self.toggleProperty('submitting'); self.notifications.showErrors(errors); }); } } }); export default ForgottenController;
/* jshint unused: false */ import ajax from 'ghost/utils/ajax'; import ValidationEngine from 'ghost/mixins/validation-engine'; var ForgottenController = Ember.Controller.extend(ValidationEngine, { email: '', submitting: false, // ValidationEngine settings validationType: 'forgotten', actions: { submit: function () { var self = this, data = self.getProperties('email'); this.toggleProperty('submitting'); this.validate({ format: false }).then(function () { ajax({ url: self.get('ghostPaths.url').api('authentication', 'passwordreset'), type: 'POST', data: { passwordreset: [{ email: data.email }] } }).then(function (resp) { self.toggleProperty('submitting'); self.notifications.showSuccess('Please check your email for instructions.', {delayed: true}); self.transitionToRoute('signin'); }).catch(function (resp) { self.toggleProperty('submitting'); self.notifications.showAPIError(resp, { defaultErrorText: 'There was a problem logging in, please try again.' }); }); }).catch(function (errors) { self.toggleProperty('submitting'); self.notifications.showErrors(errors); }); } } }); export default ForgottenController;
Fix error when trying to edit a category with empty slug
/** Application route for Discourse @class ApplicationRoute @extends Ember.Route @namespace Discourse @module Discourse **/ Discourse.ApplicationRoute = Em.Route.extend({ events: { showLogin: function() { Discourse.Route.showModal(this, 'login'); }, showCreateAccount: function() { Discourse.Route.showModal(this, 'createAccount'); }, showForgotPassword: function() { Discourse.Route.showModal(this, 'forgotPassword'); }, showNotActivated: function(props) { Discourse.Route.showModal(this, 'notActivated'); this.controllerFor('notActivated').setProperties(props); }, showImageSelector: function(composerView) { Discourse.Route.showModal(this, 'imageSelector'); this.controllerFor('imageSelector').setProperties({ localSelected: true, composerView: composerView }); }, editCategory: function(category) { var router = this; if (category.get('isUncategorized')) { Discourse.Route.showModal(router, 'editCategory', category); router.controllerFor('editCategory').set('selectedTab', 'general'); } else { Discourse.Category.findBySlugOrId(category.get('slug') || category.get('id')).then(function (c) { console.log('ok show it now please'); Discourse.Site.instance().updateCategory(c); Discourse.Route.showModal(router, 'editCategory', c); router.controllerFor('editCategory').set('selectedTab', 'general'); }); } } } });
/** Application route for Discourse @class ApplicationRoute @extends Ember.Route @namespace Discourse @module Discourse **/ Discourse.ApplicationRoute = Em.Route.extend({ events: { showLogin: function() { Discourse.Route.showModal(this, 'login'); }, showCreateAccount: function() { Discourse.Route.showModal(this, 'createAccount'); }, showForgotPassword: function() { Discourse.Route.showModal(this, 'forgotPassword'); }, showNotActivated: function(props) { Discourse.Route.showModal(this, 'notActivated'); this.controllerFor('notActivated').setProperties(props); }, showImageSelector: function(composerView) { Discourse.Route.showModal(this, 'imageSelector'); this.controllerFor('imageSelector').setProperties({ localSelected: true, composerView: composerView }); }, editCategory: function(category) { var router = this; if (category.get('isUncategorized')) { Discourse.Route.showModal(router, 'editCategory', category); router.controllerFor('editCategory').set('selectedTab', 'general'); } else { Discourse.Category.findBySlugOrId(category.get('slug')).then(function (c) { Discourse.Site.instance().updateCategory(c); Discourse.Route.showModal(router, 'editCategory', c); router.controllerFor('editCategory').set('selectedTab', 'general'); }); } } } });
Remove stale bytecode when running tests.
import os from setuptools import setup, find_packages long_description = ( open('README.rst').read() + '\n' + open('CHANGES.txt').read()) setup(name='morepath', version='0.10.dev0', description="A micro web-framework with superpowers", long_description=long_description, author="Martijn Faassen", author_email="[email protected]", url='http://morepath.readthedocs.org', license="BSD", packages=find_packages(), include_package_data=True, zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Environment :: Web Environment', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Internet :: WWW/HTTP :: WSGI', 'Programming Language :: Python :: 2.7', 'Development Status :: 4 - Beta' ], keywords="web wsgi routing morepath", install_requires=[ 'setuptools', 'webob >= 1.3.1', 'venusifork >= 2.0a2', 'reg >= 0.9.2' ], extras_require = dict( test=['pytest >= 2.5.2', 'py >= 1.4.20', 'pytest-cov', 'pytest-remove-stale-bytecode', 'WebTest >= 2.0.14'], ), )
import os from setuptools import setup, find_packages long_description = ( open('README.rst').read() + '\n' + open('CHANGES.txt').read()) setup(name='morepath', version='0.10.dev0', description="A micro web-framework with superpowers", long_description=long_description, author="Martijn Faassen", author_email="[email protected]", url='http://morepath.readthedocs.org', license="BSD", packages=find_packages(), include_package_data=True, zip_safe=False, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Environment :: Web Environment', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Internet :: WWW/HTTP :: WSGI', 'Programming Language :: Python :: 2.7', 'Development Status :: 4 - Beta' ], keywords="web wsgi routing morepath", install_requires=[ 'setuptools', 'webob >= 1.3.1', 'venusifork >= 2.0a2', 'reg >= 0.9.2' ], extras_require = dict( test=['pytest >= 2.5.2', 'py >= 1.4.20', 'pytest-cov', 'WebTest >= 2.0.14'], ), )
Update jest config to let ts-jest process JS modules - no longer uses babel-jest, although the aim is to let ts-jest pass it to that afterwards
const { jsWithTs: tsjPreset } = require('ts-jest/presets') const externalTsModules = require('./build/external').externalTsModules const externalTsModuleMappings = {} for (const externalTsModule of externalTsModules) { Object.assign(externalTsModuleMappings, { [`^${externalTsModule}$`]: `<rootDir>/external/${externalTsModule}/ts`, [`^${externalTsModule}/lib/(.*)`]: `<rootDir>/external/${externalTsModule}/ts/$1`, }) } module.exports = { globals: { 'ts-jest': { tsConfig: true, }, browser: {}, }, testMatch: ['<rootDir>/src/**/*.test.(js|jsx|ts|tsx)'], rootDir: '.', transform: { ...tsjPreset.transform, }, modulePaths: ['<rootDir>'], moduleNameMapper: { '\\.(css|less)$': 'identity-obj-proxy', ...externalTsModuleMappings, }, moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'], setupFiles: ['jest-webextension-mock', './setupJest.js'], unmockedModulePathPatterns: [ '<rootDir>/node_modules/react', '<rootDir>/node_modules/react-dom', '<rootDir>/node_modules/react-addons-test-utils', '<rootDir>/node_modules/fbjs', ], }
const externalTsModules = require('./build//external').externalTsModules const externalTsModuleMappings = {} for (const externalTsModule of externalTsModules) { Object.assign(externalTsModuleMappings, { [`^${externalTsModule}$`]: `<rootDir>/external/${externalTsModule}/ts`, [`^${externalTsModule}/lib/(.*)`]: `<rootDir>/external/${externalTsModule}/ts/$1`, }) } module.exports = { globals: { 'ts-jest': { tsConfigFile: 'tsconfig.jest.json', }, browser: {}, }, testMatch: ['<rootDir>/src/**/*.test.(js|jsx|ts|tsx)'], rootDir: '.', transform: { '^.+\\.(js|jsx)$': '<rootDir>/node_modules/babel-jest', '^.+\\.(ts|tsx)$': '<rootDir>/node_modules/ts-jest', }, modulePaths: ['<rootDir>'], moduleNameMapper: { '\\.(css|less)$': 'identity-obj-proxy', ...externalTsModuleMappings, }, moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'], setupFiles: ['jest-webextension-mock', './setupJest.js'], unmockedModulePathPatterns: [ '<rootDir>/node_modules/react', '<rootDir>/node_modules/react-dom', '<rootDir>/node_modules/react-addons-test-utils', '<rootDir>/node_modules/fbjs', ], }
Fix this issue with arrow function
'use strict'; const PluginError = require('plugin-error'); const rocambole = require('rocambole'); const through = require('through2'); module.exports = () => { let out = ''; return through.obj(function (file, enc, cb) { if (file.isNull()) { return cb(null, file); } if (file.isStream()) { return cb(new PluginError('gulp-debug-finder', 'Streaming not supported.')); } try { const contents = file.contents.toString(); rocambole.moonwalk(contents, (node) => { const expression = node.callee || {}; if (node.type !== 'CallExpression' || expression.type !== 'MemberExpression') { return; } const maybeIdent = expression.object || {}; if (maybeIdent.type === 'Identifier' && maybeIdent.name === 'console' && expression.property) { out = 'There are JavaScript debug statements present.'; } }); } catch (e) { this.emit('error', new PluginError('gulp-debug-finder', e, { fileName: file.path })); } return cb(); }, function (cb) { if (out) { this.emit('error', new PluginError('gulp-debug-finder', out, { showStack: false })); } return cb(); }); };
'use strict'; const PluginError = require('plugin-error'); const rocambole = require('rocambole'); const through = require('through2'); module.exports = () => { let out = ''; return through.obj((file, enc, cb) => { if (file.isNull()) { return cb(null, file); } if (file.isStream()) { return cb(new PluginError('gulp-debug-finder', 'Streaming not supported.')); } try { const contents = file.contents.toString(); rocambole.moonwalk(contents, (node) => { const expression = node.callee || {}; if (node.type !== 'CallExpression' || expression.type !== 'MemberExpression') { return; } const maybeIdent = expression.object || {}; if (maybeIdent.type === 'Identifier' && maybeIdent.name === 'console' && expression.property) { out = 'There are JavaScript debug statements present.'; } }); } catch (e) { this.emit('error', new PluginError('gulp-debug-finder', e, { fileName: file.path })); } return cb(); }, function (cb) { if (out) { this.emit('error', new PluginError('gulp-debug-finder', out, { showStack: false })); } return cb(); }); };
Fix memory leak, added a missing release() after using ByteBuf
package com.notnoop.apns.internal.netty.encoding; import java.io.IOException; import com.notnoop.apns.DeliveryError; import com.notnoop.apns.DeliveryResult; import com.notnoop.apns.internal.Utilities; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.FixedLengthFrameDecoder; public class ApnsResultDecoder extends FixedLengthFrameDecoder { private static final int FRAME_LENGTH = 6; public ApnsResultDecoder() { super(FRAME_LENGTH); } @Override protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { //System.out.println("Receive " + in.readableBytes()); ByteBuf frame = (ByteBuf) super.decode(ctx, in); if (frame == null) { return null; } byte[] bytes = new byte[FRAME_LENGTH]; frame.readBytes(bytes).release(); int command = bytes[0] & 0xFF; if (command != 8) { throw new IOException("Unexpected command byte " + command); } int statusCode = bytes[1] & 0xFF; DeliveryError e = DeliveryError.ofCode(statusCode); int id = Utilities.parseBytes(bytes[2], bytes[3], bytes[4], bytes[5]); return new DeliveryResult(e, id); } }
package com.notnoop.apns.internal.netty.encoding; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.FixedLengthFrameDecoder; import java.io.IOException; import com.notnoop.apns.DeliveryError; import com.notnoop.apns.DeliveryResult; import com.notnoop.apns.internal.Utilities; public class ApnsResultDecoder extends FixedLengthFrameDecoder { private static final int FRAME_LENGTH = 6; public ApnsResultDecoder() { super(FRAME_LENGTH); } @Override protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { //System.out.println("Receive " + in.readableBytes()); ByteBuf frame = (ByteBuf) super.decode(ctx, in); if (frame == null) { return null; } byte[] bytes = new byte[FRAME_LENGTH]; frame.readBytes(bytes); int command = bytes[0] & 0xFF; if (command != 8) { throw new IOException("Unexpected command byte " + command); } int statusCode = bytes[1] & 0xFF; DeliveryError e = DeliveryError.ofCode(statusCode); int id = Utilities.parseBytes(bytes[2], bytes[3], bytes[4], bytes[5]); return new DeliveryResult(e, id); } }
Improve behaviour of sortable lists Use the position of the pointer instead of the position of the dragged item to determine where the item will be dropped. Depending on where an item is grabbed, it was previously impossible (or very hard) to drop it at the start/end of a list.
(function(global) { 'use strict'; global.setupSortableList = function setupSortableList($wrapper) { /* Works with the sortable_lists and sortable_list macros defined in * web/templates/_sortable_list.html */ // Render the lists sortable if ($wrapper.data('disable-dragging') === undefined) { var $lists = $wrapper.find('ul'); $lists.sortable({ connectWith: $lists, placeholder: 'i-label sortable-item placeholder', containment: $wrapper, tolerance: 'pointer', forcePlaceholderSize: true }); } // Move an item from the enabled list to the disabled one (or vice versa). function toggleEnabled($li) { var $list = $li.closest('ul'); var targetClass = $list.hasClass('enabled') ? '.disabled' : '.enabled'; var $destination = $list.closest('.js-sortable-list-widget').find('ul' + targetClass); $li.detach().appendTo($destination); } $wrapper.find('ul li .toggle-enabled').on('click', function() { toggleEnabled($(this).closest('li')); }); // Prevents dragging the row when the action buttons are clicked. $wrapper.find('.actions').on('mousedown', function(evt) { evt.stopPropagation(); }); }; })(window);
(function(global) { 'use strict'; global.setupSortableList = function setupSortableList($wrapper) { /* Works with the sortable_lists and sortable_list macros defined in * web/templates/_sortable_list.html */ // Render the lists sortable if ($wrapper.data('disable-dragging') === undefined) { var $lists = $wrapper.find('ul'); $lists.sortable({ connectWith: $lists, placeholder: 'i-label sortable-item placeholder', containment: $wrapper, forcePlaceholderSize: true }); } // Move an item from the enabled list to the disabled one (or vice versa). function toggleEnabled($li) { var $list = $li.closest('ul'); var targetClass = $list.hasClass('enabled') ? '.disabled' : '.enabled'; var $destination = $list.closest('.js-sortable-list-widget').find('ul' + targetClass); $li.detach().appendTo($destination); } $wrapper.find('ul li .toggle-enabled').on('click', function() { toggleEnabled($(this).closest('li')); }); // Prevents dragging the row when the action buttons are clicked. $wrapper.find('.actions').on('mousedown', function(evt) { evt.stopPropagation(); }); }; })(window);
Fix for truncated whitespace on DB level
from django.db import models class Scroll(models.Model): # Constants SCROLL_TOP = """``` ╞╤═════════════════════════════════════════════╤╡ │ Scroll ### │ ╞═════════════════════════════════════════════╡ │ • • • • • • • • •│""" SCROLL_BOTTOM = """\n │ • • • • • • • • •│ ╞╧═════════════════════════════════════════════╧╡```""" # Fields identifier = models.IntegerField() content = models.TextField( default="" help_text="Lines starting with @ will be skipped. Initial whitespace is trimmed by DB, so an extra @ line is a fix." ) source = models.CharField(max_length=160) published = models.BooleanField(default=False) suggestion = models.CharField(max_length=500, blank=True, default="") class Meta: ordering = ["-id"] def __str__(self): return "Scroll #{} ID:{} Pub:{}".format(self.identifier, self.id, self.published) def lines(self): return self.content.split("\n") def render_for_discord(self): lines = self.lines() output = self.SCROLL_TOP.replace("###", ("000"+str(self.identifier))[-3:]) for line in lines: line = line.replace("\r", "") line = line.replace("\n", "") if line[0] == "@": continue output += "\n │ " + (line + " " * 42)[:42] + " │ " output += self.SCROLL_BOTTOM return output
from django.db import models class Scroll(models.Model): # Constants SCROLL_TOP = """``` ╞╤═════════════════════════════════════════════╤╡ │ Scroll ### │ ╞═════════════════════════════════════════════╡ │ • • • • • • • • •│""" SCROLL_BOTTOM = """\n │ • • • • • • • • •│ ╞╧═════════════════════════════════════════════╧╡```""" # Fields identifier = models.IntegerField() content = models.TextField(default="") source = models.CharField(max_length=160) published = models.BooleanField(default=False) suggestion = models.CharField(max_length=500, blank=True, default="") class Meta: ordering = ["-id"] def __str__(self): return "Scroll #{} ID:{} Pub:{}".format(self.identifier, self.id, self.published) def lines(self): return self.content.split("\n") def render_for_discord(self): lines = self.lines() output = self.SCROLL_TOP.replace("###", ("000"+str(self.identifier))[-3:]) for line in lines: line = line.replace("\r", "") line = line.replace("\n", "") output += "\n │ " + (line + " " * 42)[:42] + " │ " output += self.SCROLL_BOTTOM return output
Fix events to work on mysql Closes https://bugs.launchpad.net/graphite/+bug/993625
import time import os from django.db import models from django.contrib import admin from tagging.managers import ModelTaggedItemManager if os.environ.get('READTHEDOCS'): TagField = lambda *args, **kwargs: None else: from tagging.fields import TagField class Event(models.Model): class Admin: pass when = models.DateTimeField() what = models.CharField(max_length=255) data = models.TextField(blank=True) tags = TagField(default="") def get_tags(self): return Tag.objects.get_for_object(self) def __str__(self): return "%s: %s" % (self.when, self.what) @staticmethod def find_events(time_from=None, time_until=None, tags=None): if tags is not None: query = Event.tagged.with_all(tags) else: query = Event.objects.all() if time_from is not None: query = query.filter(when__gte=time_from) if time_until is not None: query = query.filter(when__lte=time_until) result = list(query.order_by("when")) return result def as_dict(self): return dict( when=self.when, what=self.what, data=self.data, tags=self.tags, id=self.id, ) # We use this rather than tagging.register() so that tags can be exposed # in the admin UI ModelTaggedItemManager().contribute_to_class(Event, 'tagged')
import time import os from django.db import models from django.contrib import admin if os.environ.get('READTHEDOCS'): TagField = lambda *args, **kwargs: None else: from tagging.fields import TagField class Event(models.Model): class Admin: pass when = models.DateTimeField() what = models.CharField(max_length=255) data = models.TextField(blank=True) tags = TagField(default="") def get_tags(self): return Tag.objects.get_for_object(self) def __str__(self): return "%s: %s" % (self.when, self.what) @staticmethod def find_events(time_from=None, time_until=None, tags=None): query = Event.objects.all() if time_from is not None: query = query.filter(when__gte=time_from) if time_until is not None: query = query.filter(when__lte=time_until) if tags is not None: for tag in tags: query = query.filter(tags__iregex=r'\b%s\b' % tag) result = list(query.order_by("when")) return result def as_dict(self): return dict( when=self.when, what=self.what, data=self.data, tags=self.tags, id=self.id, )
Add title to Graph object constructor
from datetime import datetime from app import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) name = db.Column(db.String()) pw_hash = db.Column(db.String()) graphs = db.relationship("Graph", backref="user", lazy="dynamic") def __init__(self, username, email, name, password): self.username = username self.email = email self.name = name self.pw_hash = bcrypt.generate_password_hash(password).decode("utf-8") def __repr__(self): return self.username def check_password(self, password): return bcrypt.check_password_hash(self.pw_hash, password) class Graph(db.Model): __tablename__ = "graphs" id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime) title = db.Column(db.String()) serialized_string = db.Column(db.String()) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) def __init__(self, title, serialized_string): self.created_at = datetime.utcnow() self.title = title self.serialized_string = serialized_string def __repr__(self): return self.title
from datetime import datetime from app import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) name = db.Column(db.String()) pw_hash = db.Column(db.String()) graphs = db.relationship("Graph", backref="user", lazy="dynamic") def __init__(self, username, email, name, password): self.username = username self.email = email self.name = name self.pw_hash = bcrypt.generate_password_hash(password).decode("utf-8") def __repr__(self): return self.username def check_password(self, password): return bcrypt.check_password_hash(self.pw_hash, password) class Graph(db.Model): __tablename__ = "graphs" id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime) title = db.Column(db.String()) serialized_string = db.Column(db.String()) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) def __init__(self, serialized_string): self.created_at = datetime.utcnow() self.serialized_string = serialized_string def __repr__(self): return self.title
[Method: Change identifier from String to IndentifierExpression] Add the methods to manage the changes.
package ast; import symbols.value.Value; public class Member extends Lvalue { private Lvalue _lvalue; private final IdentifierExpression _identifier; private Call _call; private Expression _expression; private boolean _isLValue; public Member(Lvalue lvalue, IdentifierExpression identifier, Call call, Expression expression) { _lvalue = lvalue; _identifier = identifier; _call = call; _expression = expression; _isLValue = false; } public Lvalue getLvalue() { return _lvalue; } public void setLvalue(Lvalue lvalue) { _lvalue = lvalue; } public String getIdentifier() { return _identifier != null ? _identifier.getIdentifier() : null; } public IdentifierExpression getIdentifierExpr() { return _identifier; } public void setIdentifier(String identifier) { _identifier.setIdentifier(identifier); } public Call getCall() { return _call; } public void setCall(Call call) { _call = call; } public Expression getExpression() { return _expression; } public void setExpression(Expression expression) { _expression = expression; } public boolean isLValue() { return _isLValue; } public void setIsLValue() { _isLValue = true; } @Override public Value accept(ASTVisitor visitor) throws ASTVisitorException { return visitor.visit(this); } }
package ast; import symbols.value.Value; public class Member extends Lvalue { private Lvalue _lvalue; private String _identifier; private Call _call; private Expression _expression; private boolean _isLValue; public Member(Lvalue lvalue, String identifier, Call call, Expression expression) { this._lvalue = lvalue; this._identifier = identifier; this._call = call; this._expression = expression; _isLValue = false; } public Lvalue getLvalue() { return this._lvalue; } public void setLvalue(Lvalue lvalue) { this._lvalue = lvalue; } public String getIdentifier() { return this._identifier; } public void setIdentifier(String identifier) { this._identifier = identifier; } public Call getCall() { return this._call; } public void setCall(Call call) { this._call = call; } public Expression getExpression() { return this._expression; } public void setExpression(Expression expression) { this._expression = expression; } public boolean isLValue() { return _isLValue; } public void setIsLValue() { this._isLValue = true; } @Override public Value accept(ASTVisitor visitor) throws ASTVisitorException { return visitor.visit(this); } }
Use separate cache and log directory per environment
<?php namespace App; use Matthias\SymfonyConsoleForm\Bundle\SymfonyConsoleFormBundle; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Bundle\TwigBundle\TwigBundle; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\Kernel as SymfonyKernel; class Kernel extends SymfonyKernel { /** @var string */ private $vendorDirectory; public function __construct(string $environment, bool $debug, string $vendorDirectory) { parent::__construct($environment, $debug); $this->vendorDirectory = $vendorDirectory; } public function registerBundles(): array { return [ new FrameworkBundle(), new TwigBundle(), new SymfonyConsoleFormBundle(), ]; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__ . '/config.yml'); if ($this->environment === 'test') { $loader->load(__DIR__ . '/config_test.yml'); } } public function getCacheDir(): string { return __DIR__ . '/cache/' . $this->environment; } public function getLogDir(): string { return __DIR__ . '/logs/' . $this->environment; } protected function buildContainer(): ContainerInterface { $container = parent::buildContainer(); $container->setParameter('vendor_directory', $this->vendorDirectory); return $container; } }
<?php namespace App; use Matthias\SymfonyConsoleForm\Bundle\SymfonyConsoleFormBundle; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Bundle\TwigBundle\TwigBundle; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\Kernel as SymfonyKernel; class Kernel extends SymfonyKernel { /** @var string */ private $vendorDirectory; public function __construct(string $environment, bool $debug, string $vendorDirectory) { parent::__construct($environment, $debug); $this->vendorDirectory = $vendorDirectory; } public function registerBundles(): array { return [ new FrameworkBundle(), new TwigBundle(), new SymfonyConsoleFormBundle(), ]; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__ . '/config.yml'); if ($this->environment === 'test') { $loader->load(__DIR__ . '/config_test.yml'); } } public function getCacheDir(): string { return __DIR__ . '/cache'; } public function getLogDir(): string { return __DIR__ . '/logs'; } protected function buildContainer(): ContainerInterface { $container = parent::buildContainer(); $container->setParameter('vendor_directory', $this->vendorDirectory); return $container; } }
Throw exception when access login action and module is not enabled.
<?php namespace thinkerg\IshtarGate\controllers; use Yii; use thinkerg\IshtarGate\models\LoginForm; use yii\web\HttpException; /** * * @author Thinker_g * * @property $module \thinkerg\IshtarGate\Module; * */ class GateController extends \yii\web\Controller { public function actionIndex() { return $this->render('index'); } public function actionSignin() { if (! $this->module->enabled) { throw new HttpException(403, 'The module must be ENABLED to access this action.'); } $model = new LoginForm(); $model->hashCallable = $this->module->hashCallable; if ($model->load(Yii::$app->getRequest()->post()) && $model->validate()) { if (array_key_exists($model->username, $this->module->credentials) && ($model->password == $this->module->credentials[$model->username])) { Yii::$app->getSession()->set($this->module->sessKey, $model->username); $this->goHome(); } else { $model->addError('password', 'Invalid username or password.'); } } return $this->render('signin', ['model' => $model]); } public function actionSignout() { Yii::$app->getSession()->remove($this->module->sessKey); $this->goHome(); } }
<?php namespace thinkerg\IshtarGate\controllers; use Yii; use thinkerg\IshtarGate\models\LoginForm; /** * * @author Thinker_g * * @property $module \thinkerg\IshtarGate\Module; * */ class GateController extends \yii\web\Controller { public function actionIndex() { return $this->render('index'); } public function actionSignin() { $model = new LoginForm(); $model->hashCallable = $this->module->hashCallable; if ($model->load(Yii::$app->getRequest()->post()) && $model->validate()) { if (array_key_exists($model->username, $this->module->credentials) && ($model->password == $this->module->credentials[$model->username])) { Yii::$app->getSession()->set($this->module->sessKey, $model->username); $this->goHome(); } else { $model->addError('password', 'Invalid username or password.'); } } return $this->render('signin', ['model' => $model]); } public function actionSignout() { Yii::$app->getSession()->remove($this->module->sessKey); $this->goHome(); } }
Enable versioning during unit tests
import sys import os sys.path.insert(0, os.curdir) import unittest import clusto import ConfigParser DB='sqlite:///:memory:' ECHO=False class ClustoTestResult(unittest.TestResult): def addError(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ print >>sys.stderr, "ERROR HERE!" clusto.rollback_transaction() self.errors.append((test, self._exc_info_to_string(err, test))) class ClustoTestBase(unittest.TestCase): def data(self): pass def setUp(self): conf = ConfigParser.ConfigParser() conf.add_section('clusto') conf.set('clusto', 'dsn', DB) conf.set('clusto', 'versioning', '1') clusto.connect(conf,echo=ECHO) clusto.clear() clusto.SESSION.close() clusto.init_clusto() self.data() def tearDown(self): if clusto.SESSION.is_active: raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__)) clusto.clear() clusto.disconnect() clusto.METADATA.drop_all(clusto.SESSION.bind) def defaultTestResult(self): if not hasattr(self._testresult): self._testresult = ClustoTestResult() return self._testresult
import sys import os sys.path.insert(0, os.curdir) import unittest import clusto import ConfigParser DB='sqlite:///:memory:' ECHO=False class ClustoTestResult(unittest.TestResult): def addError(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ print >>sys.stderr, "ERROR HERE!" clusto.rollback_transaction() self.errors.append((test, self._exc_info_to_string(err, test))) class ClustoTestBase(unittest.TestCase): def data(self): pass def setUp(self): conf = ConfigParser.ConfigParser() conf.add_section('clusto') conf.set('clusto', 'dsn', DB) clusto.connect(conf,echo=ECHO) clusto.clear() clusto.SESSION.close() clusto.init_clusto() self.data() def tearDown(self): if clusto.SESSION.is_active: raise Exception("SESSION IS STILL ACTIVE in %s" % str(self.__class__)) clusto.clear() clusto.disconnect() clusto.METADATA.drop_all(clusto.SESSION.bind) def defaultTestResult(self): if not hasattr(self._testresult): self._testresult = ClustoTestResult() return self._testresult
Return Pubmed title and abstract
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() # print response title, abstract = parse_pubmed_xml(response) return title, abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) title = root.findall('.//ArticleTitle').text abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return title, abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml&rettype=xml' % pmid) r1 = conn.getresponse() #print "Request Status: " + str(r1.status) + " " + str(r1.reason) response = r1.read() #print response[3] abstract = parse_pubmed_xml(response) return abstract, str(r1.status) + ' ' + str(r1.reason) def parse_pubmed_xml(xml): #print xml if xml.strip() == '': print "PMID not found" sys.exit() else: root = ET.fromstring(xml) abstext = root.findall('.//AbstractText') if len(abstext) > 0: abstext = abstext[0].text else: print "Abstract not found" sys.exit() return abstext def main(): print get_pubmed_abs(sys.argv[1]) if __name__ == "__main__": main()
Remove JavaDoc reference to test class. The test class is no available by JavaDoc.
package org.junit.experimental.runners; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.junit.runners.Suite; import org.junit.runners.model.RunnerBuilder; /** * If you put tests in inner classes, Ant, for example, won't find them. By running the outer class * with Enclosed, the tests in the inner classes will be run. You might put tests in inner classes * to group them for convenience or to share constants. Abstract inner classes are ignored. * <p> * So, for example: * <pre> * &#064;RunWith(Enclosed.class) * public class ListTests { * ...useful shared stuff... * public static class OneKindOfListTest {...} * public static class AnotherKind {...} * abstract public static class Ignored {...} * } * </pre> */ public class Enclosed extends Suite { /** * Only called reflectively. Do not use programmatically. */ public Enclosed(Class<?> klass, RunnerBuilder builder) throws Throwable { super(builder, klass, filterAbstractClasses(klass.getClasses())); } private static Class<?>[] filterAbstractClasses(final Class<?>[] classes) { final List<Class<?>> filteredList= new ArrayList<Class<?>>(classes.length); for (final Class<?> clazz : classes) { if (!Modifier.isAbstract(clazz.getModifiers())) { filteredList.add(clazz); } } return filteredList.toArray(new Class<?>[filteredList.size()]); } }
package org.junit.experimental.runners; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.junit.runners.Suite; import org.junit.runners.model.RunnerBuilder; /** * If you put tests in inner classes, Ant, for example, won't find them. By running the outer class * with Enclosed, the tests in the inner classes will be run. You might put tests in inner classes * to group them for convenience or to share constants. Abstract inner classes are ignored. * <p> * So, for example: * <pre> * &#064;RunWith(Enclosed.class) * public class ListTests { * ...useful shared stuff... * public static class OneKindOfListTest {...} * public static class AnotherKind {...} * abstract public static class Ignored {...} * } * </pre> * * @see org.junit.tests.manipulation.SortableTest */ public class Enclosed extends Suite { /** * Only called reflectively. Do not use programmatically. */ public Enclosed(Class<?> klass, RunnerBuilder builder) throws Throwable { super(builder, klass, filterAbstractClasses(klass.getClasses())); } private static Class<?>[] filterAbstractClasses(final Class<?>[] classes) { final List<Class<?>> filteredList= new ArrayList<Class<?>>(classes.length); for (final Class<?> clazz : classes) { if (!Modifier.isAbstract(clazz.getModifiers())) { filteredList.add(clazz); } } return filteredList.toArray(new Class<?>[filteredList.size()]); } }
Add handling for building scikit-umfpack on the Mac, which doesn't have the librt file added to the umfpack dependencies.
#!/usr/bin/env python # 05.12.2005, c from __future__ import division, print_function, absolute_import import sys def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info, dict_append config = Configuration('umfpack', parent_package, top_path) config.add_data_dir('tests') umf_info = get_info('umfpack', notfound_action=1) ## The following addition is needed when linking against a umfpack built ## from the latest SparseSuite. Not (strictly) needed when linking against ## the version in the ubuntu repositories. if not sys.platform == 'darwin': umf_info['libraries'].insert(0, 'rt') umfpack_i_file = config.paths('umfpack.i')[0] def umfpack_i(ext, build_dir): if umf_info: return umfpack_i_file blas_info = get_info('blas_opt') build_info = {} dict_append(build_info, **umf_info) dict_append(build_info, **blas_info) config.add_extension('__umfpack', sources=[umfpack_i], depends=['umfpack.i'], **build_info) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
#!/usr/bin/env python # 05.12.2005, c from __future__ import division, print_function, absolute_import def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info, dict_append config = Configuration('umfpack', parent_package, top_path) config.add_data_dir('tests') umf_info = get_info('umfpack', notfound_action=1) ## The following addition is needed when linking against a umfpack built ## from the latest SparseSuite. Not (strictly) needed when linking against ## the version in the ubuntu repositories. umf_info['libraries'].insert(0, 'rt') umfpack_i_file = config.paths('umfpack.i')[0] def umfpack_i(ext, build_dir): if umf_info: return umfpack_i_file blas_info = get_info('blas_opt') build_info = {} dict_append(build_info, **umf_info) dict_append(build_info, **blas_info) config.add_extension('__umfpack', sources=[umfpack_i], depends=['umfpack.i'], **build_info) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
Remove IOException from execute() and query()
package io.sigpipe.sing.query; import java.util.List; import java.util.Set; import io.sigpipe.sing.dataset.feature.FeatureType; import io.sigpipe.sing.graph.DataContainer; import io.sigpipe.sing.graph.Vertex; public class MetaQuery extends Query { private DataContainer aggregateData = new DataContainer(); public MetaQuery() { } public DataContainer result() { return aggregateData; } @Override public void execute(Vertex root) throws QueryException { this.query(root); } private void query(Vertex vertex) throws QueryException { DataContainer container = vertex.getData(); if (container != null) { this.aggregateData.merge(container); } if (vertex.numNeighbors() == 0) { /* This is a leaf node */ return; } String childFeature = vertex.getFirstNeighbor().getLabel().getName(); List<Expression> expList = this.expressions.get(childFeature); if (expList != null) { Set<Vertex> matches = evaluate(vertex, expList); for (Vertex match : matches) { if (match == null) { continue; } if (match.getLabel().getType() == FeatureType.NULL) { continue; } query(match); } } else { /* No expression operates on this vertex. Consider all children. */ for (Vertex neighbor : vertex.getAllNeighbors()) { query(neighbor); } } } }
package io.sigpipe.sing.query; import java.io.IOException; import java.util.List; import java.util.Set; import io.sigpipe.sing.dataset.feature.FeatureType; import io.sigpipe.sing.graph.DataContainer; import io.sigpipe.sing.graph.Vertex; public class MetaQuery extends Query { private DataContainer aggregateData = new DataContainer(); public MetaQuery() { } public DataContainer result() { return aggregateData; } @Override public void execute(Vertex root) throws IOException, QueryException { this.query(root); } private void query(Vertex vertex) throws IOException, QueryException { DataContainer container = vertex.getData(); if (container != null) { this.aggregateData.merge(container); } if (vertex.numNeighbors() == 0) { /* This is a leaf node */ return; } String childFeature = vertex.getFirstNeighbor().getLabel().getName(); List<Expression> expList = this.expressions.get(childFeature); if (expList != null) { Set<Vertex> matches = evaluate(vertex, expList); for (Vertex match : matches) { if (match == null) { continue; } if (match.getLabel().getType() == FeatureType.NULL) { continue; } query(match); } } else { /* No expression operates on this vertex. Consider all children. */ for (Vertex neighbor : vertex.getAllNeighbors()) { query(neighbor); } } } }
Disable station administrator role for demo account.
<?php namespace App\Entity\Fixture; use App\Acl; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use App\Entity; class RolePermission extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $em) { /** @var Entity\Station $station */ $station = $this->getReference('station'); $permissions = [ 'admin_role' => [ [Acl::GLOBAL_ALL, null], ], 'demo_role' => [ [Acl::STATION_ALL, $station], [Acl::STATION_VIEW, $station], ], ]; foreach($permissions as $role_reference => $perm_names) { /** @var Entity\Role $role */ $role = $this->getReference($role_reference); foreach($perm_names as $perm_name) { $rp = new Entity\RolePermission($role, $perm_name[1], $perm_name[0]); $em->persist($rp); } } $em->flush(); } public function getDependencies() { return [ Role::class ]; } }
<?php namespace App\Entity\Fixture; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use App\Entity; class RolePermission extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $em) { $permissions = [ 'admin_role' => [ 'administer all', ], 'demo_role' => [ 'administer api keys', 'administer stations', 'view administration', ], ]; foreach($permissions as $role_reference => $perm_names) { /** @var Entity\Role $role */ $role = $this->getReference($role_reference); foreach($perm_names as $perm_name) { $rp = new Entity\RolePermission($role); $rp->setActionName($perm_name); $em->persist($rp); } } $em->flush(); } public function getDependencies() { return [ Role::class ]; } }
Update each series results to be embedded in the reduce
import when from 'when'; let openFiles = ['a.js', 'b.js', 'c.js'], saveFile = (file) => { console.log('saveFile', file); return new Promise((resolve, reject) => { setTimeout( () => { console.log('timeout', file); resolve(file); }, 2000 ); }); }; openFiles.reduce( (promise, file) => promise.then((results) => { return saveFile(file) .then((result) => { results.push(result); return results; }); }), Promise.resolve([]) ) .then((...args) => { console.log('promise done', args); }) .catch((error) => { console.log('promise error', error); }); when.reduce(openFiles, (results, file) => { return saveFile(file) .then((result) => { results.push(result); return results; }); }, []) .then((...args) => { console.log('when done', args); }) .catch((error) => { console.log('when error', error); });
import when from 'when'; let openFiles = ['a.js', 'b.js', 'c.js'], saveFile = (file) => { console.log('saveFile', file); return new Promise((resolve, reject) => { setTimeout( () => { console.log('timeout', file); resolve(file); }, 2000 ); }); }; let results = []; openFiles.reduce( (promise, file) => { return promise .then(saveFile.bind(null, file)) .then((result) => { results.push(result); return results; }); }, Promise.resolve() ) .then((...args) => { console.log('promise done', args); }) .catch((error) => { console.log('promise error', error); }); when.reduce(openFiles, (results, file) => { return saveFile(file) .then((result) => { results.push(result); return results; }); }, []) .then((...args) => { console.log('when done', args); }) .catch((error) => { console.log('when error', error); });
Fix regression Use the proxy path
package fr.synchrotron.soleil.ica.ci.service.legacymavenproxy; import org.vertx.java.core.Vertx; import org.vertx.java.core.http.HttpClient; import org.vertx.java.core.http.HttpServerRequest; /** * @author Gregory Boissinot */ public class HttpArtifactCaller { private final Vertx vertx; private final String repoHost; private final int repoPort; private final String repoURIPath; public HttpArtifactCaller(Vertx vertx, String repoHost, int repoPort, String repoURIPath) { this.vertx = vertx; this.repoHost = repoHost; this.repoPort = repoPort; this.repoURIPath = repoURIPath; } public Vertx getVertx() { return vertx; } public String getRepoHost() { return repoHost; } public String buildRequestPath(final HttpServerRequest request) { final String prefix = HttpArtifactProxyEndpointVerticle.PROXY_PATH; String artifactPath = request.path().substring(prefix.length() + 1); return repoURIPath.endsWith("/") ? (repoURIPath + artifactPath) : (repoURIPath + "/" + artifactPath); } public HttpClient getPClient() { return getVertx().createHttpClient() .setHost(repoHost) .setPort(repoPort) .setConnectTimeout(10000); } }
package fr.synchrotron.soleil.ica.ci.service.legacymavenproxy; import org.vertx.java.core.Vertx; import org.vertx.java.core.http.HttpClient; import org.vertx.java.core.http.HttpServerRequest; /** * @author Gregory Boissinot */ public class HttpArtifactCaller { private final Vertx vertx; private final String repoHost; private final int repoPort; private final String repoURIPath; public HttpArtifactCaller(Vertx vertx, String repoHost, int repoPort, String repoURIPath) { this.vertx = vertx; this.repoHost = repoHost; this.repoPort = repoPort; this.repoURIPath = repoURIPath; } public Vertx getVertx() { return vertx; } public String getRepoHost() { return repoHost; } public String buildRequestPath(final HttpServerRequest request) { final String prefix = "/maven"; String artifactPath = request.path().substring(prefix.length() + 1); return repoURIPath.endsWith("/") ? (repoURIPath + artifactPath) : (repoURIPath + "/" + artifactPath); } public HttpClient getPClient() { return getVertx().createHttpClient() .setHost(repoHost) .setPort(repoPort) .setConnectTimeout(10000); } }
Fix location of line length check
# coding: utf-8 """ pyalysis.analysers.raw ~~~~~~~~~~~~~~~~~~~~~~ :copyright: 2014 by Daniel Neuhäuser and Contributors :license: BSD, see LICENSE.rst for details """ import codecs from blinker import Signal from pyalysis.utils import detect_encoding, Location from pyalysis.warnings import LineTooLong class LineAnalyser(object): """ Line-level analyser of Python source code. """ on_analyse = Signal() on_line = Signal() def __init__(self, module): self.module = module self.encoding = detect_encoding(module) self.warnings = [] def emit(self, warning_cls, message): self.warnings.append( warning_cls( message, self.module.name, Location(self.lineno, 0), Location(self.lineno, len(self.line)) ) ) def analyse(self): self.on_analyse.send(self) reader = codecs.lookup(self.encoding).streamreader(self.module) for i, line in enumerate(reader, 1): self.lineno = i self.line = line self.on_line.send(self, lineno=i, line=line) return self.warnings @LineAnalyser.on_line.connect def check_line_length(analyser, lineno, line): if len(line.rstrip()) > 79: analyser.emit( LineTooLong, u'Line is longer than 79 characters. ' u'You should keep it below that', )
# coding: utf-8 """ pyalysis.analysers.raw ~~~~~~~~~~~~~~~~~~~~~~ :copyright: 2014 by Daniel Neuhäuser and Contributors :license: BSD, see LICENSE.rst for details """ import codecs from blinker import Signal from pyalysis.utils import detect_encoding, Location from pyalysis.warnings import LineTooLong class LineAnalyser(object): """ Line-level analyser of Python source code. """ on_analyse = Signal() on_line = Signal() def __init__(self, module): self.module = module self.encoding = detect_encoding(module) self.warnings = [] def emit(self, warning_cls, message, lineno, start, end): self.warnings.append( warning_cls( message, self.module.name, Location(lineno, start), Location(lineno, end) ) ) def analyse(self): self.on_analyse.send(self) reader = codecs.lookup(self.encoding).streamreader(self.module) for i, line in enumerate(reader, 1): self.on_line.send(self, lineno=i, line=line) return self.warnings @LineAnalyser.on_line.connect def check_line_length(analyser, lineno, line): if len(line.rstrip()) > 79: analyser.emit( LineTooLong, u'Line is longer than 79 characters. ' u'You should keep it below that', lineno, 79, len(line.rstrip()) )
Add ability to customize handler
<?php namespace Salesforce; use Salesforce\Version; use Salesforce\Authentication\AuthenticationInterface; use GuzzleHttp\Client as HttpClient; class Connection { /** * Array of Salesforce instance configuration options * which are set after logging into the * @see Salesforce\Authentication\AuthenticationInterface */ protected $authentication; protected $httpClient; protected $version; /** * Constructor * @param Salesforce\Authentication\AuthenticationInterface $authentication */ public function __construct(AuthenticationInterface $authentication, $version = Version::DEFAULT_VERSION) { $this->authentication = $authentication; $this->version = $version; } public function getHttpClient($handler = null) { if(empty($this->httpClient)) { $this->initializeHttpClient($handler); } return $this->httpClient; } /** * Initialize the HTTP client * @return GuzzleHttp\Client */ protected function initializeHttpClient($handler = null) { $params = [ 'base_uri' => "{$this->authentication->getInstanceUrl()}/services/data/{$this->version}/", 'headers' => [ 'Authorization' => 'Bearer ' . $this->authentication->getAccessToken(), 'Content-type' => 'application/json', 'Accept' => 'application/json', ] ]; if ($handler) { $params['handler'] = $handler; } $this->httpClient = new HttpClient($params); Resource::setHttpClient($this->httpClient); Query::setHttpClient($this->httpClient); Search::setHttpClient($this->httpClient); } }
<?php namespace Salesforce; use Salesforce\Version; use Salesforce\Authentication\AuthenticationInterface; use GuzzleHttp\Client as HttpClient; class Connection { /** * Array of Salesforce instance configuration options * which are set after logging into the * @see Salesforce\Authentication\AuthenticationInterface */ protected $authentication; protected $httpClient; protected $version; /** * Constructor * @param Salesforce\Authentication\AuthenticationInterface $authentication */ public function __construct(AuthenticationInterface $authentication, $version = Version::DEFAULT_VERSION) { $this->authentication = $authentication; $this->version = $version; } public function getHttpClient() { if(empty($this->httpClient)) { $this->initializeHttpClient(); } return $this->httpClient; } /** * Initialize the HTTP client * @return GuzzleHttp\Client */ protected function initializeHttpClient() { $this->httpClient = new HttpClient([ 'base_uri' => "{$this->authentication->getInstanceUrl()}/services/data/{$this->version}/", 'headers' => [ 'Authorization' => 'Bearer ' . $this->authentication->getAccessToken(), 'Content-type' => 'application/json', 'Accept' => 'application/json', ] ]); Resource::setHttpClient($this->httpClient); Query::setHttpClient($this->httpClient); Search::setHttpClient($this->httpClient); } }
Fix even more legacy mongo compatability
/* global db, ObjectId */ var addedActions = []; db.cooperatives.find({}).forEach(function (cooperative) { var actions = []; if (cooperative.actions) { cooperative.actions.forEach(function (action) { if (action instanceof ObjectId) { addedActions.push(action); actions.push(action); return; } db.actions.insert({ name: action.name, date: action.date, cost: action.cost, description: action.description, types: action.types, cooperative: cooperative._id, user: cooperative.editors[0].editorId, comments: action.comments.map(function (comment) { return { user: comment.user, author: db.users.find({ _id: ObjectId(comment.user) }).profile.name, comment: comment.comment, date: comment.date }; }) }, function (err, docs) { addedActions.push(docs[0]._id); actions.push(docs[0]._id); }); }); db.cooperatives.update({ _id: cooperative._id }, { $set: { actions: actions }}); } }); db.actions.find({}).forEach(function (action) { var isNew = false; addedActions.forEach(function (id) { isNew = (isNew || id === action._id); }); if (!isNew) { db.actions.remove({ _id: action._id }); } });
/* global db, ObjectId */ var addedActions = []; db.cooperatives.find({}).forEach(function (cooperative) { var actions = []; if (cooperative.actions) { cooperative.actions.forEach(function (action) { if (action instanceof ObjectId) { addedActions.push(action); actions.push(action); return; } db.actions.insert({ name: action.name, date: action.date, cost: action.cost, description: action.description, types: action.types, cooperative: cooperative._id, user: cooperative.editors[0].editorId, comments: action.comments.map(function (comment) { return { user: comment.user, author: db.users.find({ _id: ObjectId(comment.user) }).profile.name, comment: comment.comment, date: comment.date }; }) }, function (err, docs) { addedActions.push(docs[0]._id); actions.push(docs[0]._id); }); }); db.cooperatives.update({ _id: cooperative._id }, { $set: { actions: actions }}); } }); db.actions.find({}).forEach(function (action) { var isNew = addedActions.find(function (id) { return id === action._id; }); if (!isNew) { db.actions.remove({ _id: action._id }); } });
Make numba fake import robust
from contextlib import contextmanager from poliastro import jit @contextmanager def _fake_numba_import(): # Black magic, beware # https://stackoverflow.com/a/2484402/554319 import sys class FakeImportFailure: def __init__(self, modules): self.modules = modules def find_module(self, fullname, *args, **kwargs): if fullname in self.modules: raise ImportError('Debug import failure for %s' % fullname) fail_loader = FakeImportFailure(['numba']) import poliastro.jit from poliastro import jit del poliastro.jit del jit del sys.modules['poliastro.jit'] del sys.modules['numba'] sys.meta_path.insert(0, fail_loader) yield sys.meta_path.remove(fail_loader) import numba from poliastro import jit def test_ijit_returns_same_function_without_args(): def expected_foo(): return True foo = jit.ijit(expected_foo) assert foo is expected_foo def test_ijit_returns_same_function_with_args(): def expected_foo(): return True foo = jit.ijit(1)(expected_foo) assert foo is expected_foo def test_no_numba_emits_warning(recwarn): with _fake_numba_import(): from poliastro import jit assert len(recwarn) == 1 w = recwarn.pop(UserWarning) assert issubclass(w.category, UserWarning) assert "Could not import numba package" in str(w.message)
from poliastro import jit def _fake_numba_import(): # Black magic, beware # https://stackoverflow.com/a/2484402/554319 import sys class FakeImportFailure: def __init__(self, modules): self.modules = modules def find_module(self, fullname, *args, **kwargs): if fullname in self.modules: raise ImportError('Debug import failure for %s' % fullname) fail_loader = FakeImportFailure(['numba']) import poliastro.jit from poliastro import jit del poliastro.jit del jit del sys.modules['poliastro.jit'] del sys.modules['numba'] sys.meta_path.insert(0, fail_loader) def test_ijit_returns_same_function_without_args(): def expected_foo(): return True foo = jit.ijit(expected_foo) assert foo is expected_foo def test_ijit_returns_same_function_with_args(): def expected_foo(): return True foo = jit.ijit(1)(expected_foo) assert foo is expected_foo def test_no_numba_emits_warning(recwarn): _fake_numba_import() from poliastro import jit assert len(recwarn) == 1 w = recwarn.pop(UserWarning) assert issubclass(w.category, UserWarning) assert "Could not import numba package" in str(w.message)
Store the notification id when fetching notifications
import { takeLatest, put, call } from 'redux-saga/effects'; import { REQUEST_FEED_NOTIFICATIONS_SUCCESS, REQUEST_FEED_NOTIFICATIONS, REQUEST_FEED_NOTIFICATIONS_FAILURE, } from 'actions/feedActions'; import moreNotificationsCall from 'api/feedApiCall'; export function* getFeedNotificationsFlow(action) { const receivedNotificationTypes = { deck_created: 'DECK_CREATED', deck_updated: 'DECK_UPDATED', }; try { const responseListOfNotifications = yield call( moreNotificationsCall, action.meta, ); if (!responseListOfNotifications) { throw new Error('Received undefined list.'); } const listOfNotifications = responseListOfNotifications.map( responseNotification => ({ id: responseNotification.id, timestamp: responseNotification.attributes.createdAt, type: receivedNotificationTypes[ responseNotification.attributes.eventType.toLowerCase() ], targetDeck: responseNotification.attributes.deckName, concernedUser: responseNotification.attributes.userName, }), ); yield put({ type: REQUEST_FEED_NOTIFICATIONS_SUCCESS, payload: { listOfNotifications, }, }); } catch (error) { yield put({ type: REQUEST_FEED_NOTIFICATIONS_FAILURE, payload: { message: error.message, }, }); } } function* feedUpdateWatcher() { yield takeLatest(REQUEST_FEED_NOTIFICATIONS, getFeedNotificationsFlow); } export default feedUpdateWatcher;
import { takeLatest, put, call } from 'redux-saga/effects'; import { REQUEST_FEED_NOTIFICATIONS_SUCCESS, REQUEST_FEED_NOTIFICATIONS, REQUEST_FEED_NOTIFICATIONS_FAILURE, } from 'actions/feedActions'; import moreNotificationsCall from 'api/feedApiCall'; export function* getFeedNotificationsFlow(action) { const receivedNotificationTypes = { deck_created: 'DECK_CREATED', deck_updated: 'DECK_UPDATED', }; try { const responseListOfNotifications = yield call( moreNotificationsCall, action.meta, ); if (!responseListOfNotifications) { throw new Error('Received undefined list.'); } const listOfNotifications = responseListOfNotifications.map( responseNotification => ({ timestamp: responseNotification.attributes.createdAt, type: receivedNotificationTypes[ responseNotification.attributes.eventType.toLowerCase() ], targetDeck: responseNotification.attributes.deckName, concernedUser: responseNotification.attributes.userName, }), ); yield put({ type: REQUEST_FEED_NOTIFICATIONS_SUCCESS, payload: { listOfNotifications, }, }); } catch (error) { yield put({ type: REQUEST_FEED_NOTIFICATIONS_FAILURE, payload: { message: error.message, }, }); } } function* feedUpdateWatcher() { yield takeLatest(REQUEST_FEED_NOTIFICATIONS, getFeedNotificationsFlow); } export default feedUpdateWatcher;
Change icon for non-target tool and remove length tool
Template.viewerMain.helpers({ 'toolbarOptions': function() { var toolbarOptions = {}; var buttonData = []; buttonData.push({ id: 'resetViewport', title: 'Reset Viewport', classes: 'imageViewerCommand', iconClasses: 'fa fa-undo' }); buttonData.push({ id: 'wwwc', title: 'WW/WC', classes: 'imageViewerTool', iconClasses: 'fa fa-sun-o' }); buttonData.push({ id: 'zoom', title: 'Zoom', classes: 'imageViewerTool', iconClasses: 'fa fa-search' }); buttonData.push({ id: 'pan', title: 'Pan', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows' }); buttonData.push({ id: 'stackScroll', title: 'Stack Scroll', classes: 'imageViewerTool', iconClasses: 'fa fa-bars' }); buttonData.push({ id: 'lesion', title: 'Target Tool', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows-alt' }); buttonData.push({ id: 'nonTarget', title: 'Non-Target Tool', classes: 'imageViewerTool', iconClasses: 'fa fa-long-arrow-up' }); toolbarOptions.buttonData = buttonData; toolbarOptions.includePlayClipButton = false; toolbarOptions.includeLayoutButton = false; return toolbarOptions; } });
Template.viewerMain.helpers({ 'toolbarOptions': function() { var toolbarOptions = {}; var buttonData = []; buttonData.push({ id: 'resetViewport', title: 'Reset Viewport', classes: 'imageViewerCommand', iconClasses: 'fa fa-undo' }); buttonData.push({ id: 'wwwc', title: 'WW/WC', classes: 'imageViewerTool', iconClasses: 'fa fa-sun-o' }); buttonData.push({ id: 'zoom', title: 'Zoom', classes: 'imageViewerTool', iconClasses: 'fa fa-search' }); buttonData.push({ id: 'pan', title: 'Pan', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows' }); buttonData.push({ id: 'stackScroll', title: 'Stack Scroll', classes: 'imageViewerTool', iconClasses: 'fa fa-bars' }); buttonData.push({ id: 'length', title: 'Length Measurement', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows-v' }); buttonData.push({ id: 'lesion', title: 'Lesion Tool', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows-alt' }); buttonData.push({ id: 'nonTarget', title: 'Non-Target Tool', classes: 'imageViewerTool', iconClasses: 'fa fa-arrows-v' }); toolbarOptions.buttonData = buttonData; toolbarOptions.includePlayClipButton = false; toolbarOptions.includeLayoutButton = false; return toolbarOptions; } });
Drop empty field keys in migration
from django.core.management.base import BaseCommand from corehq.apps.custom_data_fields.models import CustomDataFieldsDefinition, CustomDataField from corehq.apps.users.models import CommCareUser from corehq.apps.domain.models import Domain from dimagi.utils.couch.database import iter_docs class Command(BaseCommand): """ Create a CustomDataFieldsDefinition based on existing custom user information on each domain """ help = '' def handle(self, *args, **options): for domain in Domain.get_all_names(): fields_definition = CustomDataFieldsDefinition.get_or_create( domain, 'UserFields' ) user_ids = (CommCareUser.ids_by_domain(domain) + CommCareUser.ids_by_domain(domain, is_active=False)) existing_field_slugs = set([field.slug for field in fields_definition.fields]) for user in iter_docs(CommCareUser.get_db(), user_ids): user_data = user.get('user_data', {}) for key in user_data.keys(): if key and key not in existing_field_slugs: existing_field_slugs.add(key) fields_definition.fields.append(CustomDataField( slug=key, label=key, is_required=False )) # Only save a definition for domains which use custom user data if fields_definition.fields: fields_definition.save()
from django.core.management.base import BaseCommand from corehq.apps.custom_data_fields.models import CustomDataFieldsDefinition, CustomDataField from corehq.apps.users.models import CommCareUser from corehq.apps.domain.models import Domain from dimagi.utils.couch.database import iter_docs class Command(BaseCommand): """ Create a CustomDataFieldsDefinition based on existing custom user information on each domain """ help = '' def handle(self, *args, **options): for domain in Domain.get_all_names(): fields_definition = CustomDataFieldsDefinition.get_or_create( domain, 'UserFields' ) user_ids = (CommCareUser.ids_by_domain(domain) + CommCareUser.ids_by_domain(domain, is_active=False)) existing_field_slugs = set([field.slug for field in fields_definition.fields]) for user in iter_docs(CommCareUser.get_db(), user_ids): user_data = user.get('user_data', {}) for key in user_data.keys(): if key not in existing_field_slugs: existing_field_slugs.add(key) fields_definition.fields.append(CustomDataField( slug=key, label=key, is_required=False )) # Only save a definition for domains which use custom user data if fields_definition.fields: fields_definition.save()
Make Tweets model list generic Also fix sorting
YUI.add("model-list-tweets", function(Y) { "use strict"; var tristis = Y.namespace("Tristis"), models = Y.namespace("Tristis.Models"), Tweets; Tweets = Y.Base.create("tweets", Y.LazyModelList, [ Y.namespace("Extensions").ModelListMore ], { sync : function(action, options, done) { var args = {}, last; if(action === "more") { last = this.item(this.size() - 1); if(last) { args.since_id = last.id_str; } } args = Y.merge( { count : 50 }, this.get("config") || {}, args ); tristis.twitter.get(this.get("api"), args, done); }, // Sort tweets by date comparator : function(model) { return Date.parse(model.created_at); }, // Sort tweets by newest first _compare : function(a, b) { return b - a; } }, { ATTRS : { api : null, config : null } }); models.Tweets = Tweets; }, "@VERSION@", { requires : [ // YUI "base-build", "lazy-model-list", // Extensions "extension-model-list-more" ] });
YUI.add("model-list-tweets", function(Y) { "use strict"; var tristis = Y.namespace("Tristis"), models = Y.namespace("Tristis.Models"), Tweets; Tweets = Y.Base.create("tweets", Y.LazyModelList, [ Y.namespace("Extensions").ModelListMore ], { sync : function(action, options, done) { var args = {}, last; if(action === "more") { last = this.item(this.size() - 1); if(last) { args.since_id = last.id_str; } } // TODO: Make list/home agnostic somehow. Config-based? tristis.twitter.get("lists/statuses", Y.merge({ list_id : this.get("list_id"), // TODO: configurable? include_rts : true, count : 50 }, args), done); }, comparator : function(model) { return Date.parse(model.created_at); } }, { ATTRS : { list_id : null } }); models.Tweets = Tweets; }, "@VERSION@", { requires : [ // YUI "base-build", "lazy-model-list", // Extensions "extension-model-list-more" ] });
Mark initial migration so django knows to skip it.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('lti_context_id', models.CharField(max_length=128, null=True)), ('lti_tool_consumer_instance_guid', models.CharField(max_length=1024, null=True)), ('api_course_id', models.IntegerField(null=True)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], options={ 'verbose_name': 'course', 'verbose_name_plural': 'courses', }, ), migrations.AlterUniqueTogether( name='course', unique_together=set([('lti_context_id', 'lti_tool_consumer_instance_guid')]), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('lti_context_id', models.CharField(max_length=128, null=True)), ('lti_tool_consumer_instance_guid', models.CharField(max_length=1024, null=True)), ('api_course_id', models.IntegerField(null=True)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], options={ 'verbose_name': 'course', 'verbose_name_plural': 'courses', }, ), migrations.AlterUniqueTogether( name='course', unique_together=set([('lti_context_id', 'lti_tool_consumer_instance_guid')]), ), ]
Remove lint from minified version
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // contrib-watch watch: { all: { files: ['src/**/*.js', 'lib/**/*.js', 'test/**/*.js', 'Gruntfile.js'], tasks: ['test', 'build'] } }, // contrib-jshint jshint: { all: ['Gruntfile.js', 'src/jquery.countdown.js', 'test/**/*.js'] }, // contrib-qunit qunit: { all: 'test/**/*.html' }, // contrib-uglify uglify: { options: { preserveComments: function(node, comment) { // Preserve the license banner return comment.col === 0 && comment.pos === 0; } }, all: { files: { 'src/jquery.countdown.min.js': ['src/jquery.countdown.js'] } } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); // Project tasks grunt.registerTask('license', function() { }); grunt.registerTask('test', ['jshint', 'qunit']); grunt.registerTask('build', ['license', 'uglify']); grunt.registerTask('default', ['test', 'build', 'watch']); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // contrib-watch watch: { all: { files: ['src/**/*.js', 'lib/**/*.js', 'test/**/*.js', 'Gruntfile.js'], tasks: ['test', 'build'] } }, // contrib-jshint jshint: { all: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'] }, // contrib-qunit qunit: { all: 'test/**/*.html' }, // contrib-uglify uglify: { options: { preserveComments: function(node, comment) { // Preserve the license banner return comment.col === 0 && comment.pos === 0; } }, all: { files: { 'src/jquery.countdown.min.js': ['src/jquery.countdown.js'] } } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); // Project tasks grunt.registerTask('license', function() { }); grunt.registerTask('test', ['jshint', 'qunit']); grunt.registerTask('build', ['license', 'uglify']); grunt.registerTask('default', ['test', 'build', 'watch']); };
Add handling for non-unicode return values from datetime.strftime Hopefully fixes #3.
import locale from functools import partial from format_date import FormatDate import sublime import sublime_plugin class InsertDateCommand(sublime_plugin.TextCommand, FormatDate): """Prints Date according to given format string""" def run(self, edit, format=None, prompt=False, tz_in=None, tz_out=None): if prompt: self.view.window().show_input_panel( "Date format string:", str(format) if format else '', # pass this function as callback partial(self.run, edit, tz_in=tz_in, tz_out=tz_out), None, None ) return # call already handled if format == '' or (isinstance(format, basestring) and format.isspace()): # emtpy string or whitespaces entered in input panel return # do the actual parse action try: text = self.parse(format, tz_in, tz_out) except Exception as e: sublime.error_message("[InsertDate]\n%s: %s" % (type(e).__name__, e)) return if text == '' or text.isspace(): # don't bother replacing selections with actually nothing return # Fix potential unicode/codepage issues if type(text) == str: # print(text) try: text = text.decode(locale.getpreferredencoding()) except UnicodeDecodeError: text = text.decode('utf-8') for r in self.view.sel(): # Insert when sel is empty to not select the contents if r.empty(): self.view.insert (edit, r.a, text) else: self.view.replace(edit, r, text)
import sublime import sublime_plugin from functools import partial from format_date import FormatDate class InsertDateCommand(sublime_plugin.TextCommand, FormatDate): """Prints Date according to given format string""" def run(self, edit, format=None, prompt=False, tz_in=None, tz_out=None): if prompt: self.view.window().show_input_panel( "Date format string:", str(format) if format else '', # pass this function as callback partial(self.run, edit, tz_in=tz_in, tz_out=tz_out), None, None ) return # call already handled if format == '' or (isinstance(format, basestring) and format.isspace()): # emtpy string or whitespaces entered in input panel return # do the actual parse action try: text = self.parse(format, tz_in, tz_out) except Exception as e: sublime.error_message("[InsertDate]\n%s: %s" % (type(e).__name__, e)) return if text == '' or text.isspace(): # don't bother replacing selections with actually nothing return if type(text) == str: # print(text) text = text.decode('utf-8') for r in self.view.sel(): if r.empty(): self.view.insert (edit, r.a, text) else: self.view.replace(edit, r, text)
Clean the recent files list before displaying it in the startup dialog.
#!/usr/bin/env python #coding=utf8 from whacked4 import config from whacked4.ui import windows class StartDialog(windows.StartDialogBase): """ This dialog is meant to be displayed on startup of the application. It allows the user to quickly access some common functions without having to dig down into a menu first. """ def __init__(self, parent): windows.StartDialogBase.__init__(self, parent) client_width = self.FileList.GetClientSizeTuple()[0] - 4 self.FileList.InsertColumn(0, 'Filename', width=client_width) # Populate the list of recently accessed Dehacked patches. config.settings.recent_files_clean() recent_files = config.settings['recent_files'] for index, filename in enumerate(recent_files): self.FileList.InsertStringItem(index, filename) def open_file_list(self, event): """ Opens a Dehacked patch directly from the file list. """ self.Hide() filename = config.settings['recent_files'][event.GetIndex()] self.GetParent().open_file(filename) def new_file(self, event): self.Hide() self.GetParent().new_file() def open_file(self, event): self.Hide() self.GetParent().open_file_dialog() def cancel(self, event): self.Hide()
#!/usr/bin/env python #coding=utf8 from whacked4 import config from whacked4.ui import windows class StartDialog(windows.StartDialogBase): """ This dialog is meant to be displayed on startup of the application. It allows the user to quickly access some common functions without having to dig down into a menu first. """ def __init__(self, parent): windows.StartDialogBase.__init__(self, parent) client_width = self.FileList.GetClientSizeTuple()[0] - 4 self.FileList.InsertColumn(0, 'Filename', width=client_width) # Populate the list of recently accessed Dehacked patches. recent_files = config.settings['recent_files'] for index, filename in enumerate(recent_files): self.FileList.InsertStringItem(index, filename) def open_file_list(self, event): """ Opens a Dehacked patch directly from the file list. """ self.Hide() filename = config.settings['recent_files'][event.GetIndex()] self.GetParent().open_file(filename) def new_file(self, event): self.Hide() self.GetParent().new_file() def open_file(self, event): self.Hide() self.GetParent().open_file_dialog() def cancel(self, event): self.Hide()
[KFE-203] Remove references to deleted field
package com.kushkipagos.android.example; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.kushkipagos.android.Card; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.sendButton); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { EditText nameText = (EditText) findViewById(R.id.nameText); EditText numberText = (EditText) findViewById(R.id.numberText); EditText monthText = (EditText) findViewById(R.id.monthText); EditText yearText = (EditText) findViewById(R.id.yearText); EditText cvvText = (EditText) findViewById(R.id.cvvText); Card card = new Card(nameText.getText().toString(), numberText.getText().toString(), cvvText.getText().toString(), monthText.getText().toString(), yearText.getText().toString()); ExampleAsyncTask exampleAsyncTask = new ExampleAsyncTask(getApplicationContext(), card); exampleAsyncTask.execute(); } }); } }
package com.kushkipagos.android.example; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.kushkipagos.android.Card; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.sendButton); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TextView textField = (TextView) findViewById(R.id.txtEncryptedMessage); EditText nameText = (EditText) findViewById(R.id.nameText); EditText numberText = (EditText) findViewById(R.id.numberText); EditText monthText = (EditText) findViewById(R.id.monthText); EditText yearText = (EditText) findViewById(R.id.yearText); EditText cvvText = (EditText) findViewById(R.id.cvvText); Card card = new Card(nameText.getText().toString(), numberText.getText().toString(), cvvText.getText().toString(), monthText.getText().toString(), yearText.getText().toString()); textField.setText(""); ExampleAsyncTask exampleAsyncTask = new ExampleAsyncTask(getApplicationContext(), card); exampleAsyncTask.execute(); } }); } }
Fix links in decktree on deck edit without new revision
import UserProfileStore from '../stores/UserProfileStore'; import {navigateAction} from 'fluxible-router'; import striptags from 'striptags'; export default function saveDeckEdit(context, payload, done) { //enrich with user id let userid = context.getStore(UserProfileStore).userid; if (userid == null || userid === '') { context.executeAction(navigateAction, { url: '/' }); } else { //enrich with user id payload.userid = userid; context.service.update('deck.update', payload, null, {timeout: 30 * 1000}, (err, res) => { if (err) { context.dispatch('SAVE_DECK_EDIT_FAILURE', err); } else { context.dispatch('SAVE_DECK_EDIT_SUCCESS', res); console.log(payload.selector); context.dispatch('UPDATE_TREE_NODE_SUCCESS', { selector: payload.selector, nodeSpec: { title: striptags(payload.title), id: payload.selector.sid, path: payload.selector.spath } }); //update the URL: redirect to view after edit let newURL = '/deck/' + payload.selector.id + '/' + payload.selector.stype + '/' + payload.selector.sid + '/' + payload.selector.spath; context.executeAction(navigateAction, { url: newURL }); } done(); }); } }
import UserProfileStore from '../stores/UserProfileStore'; import {navigateAction} from 'fluxible-router'; import striptags from 'striptags'; export default function saveDeckEdit(context, payload, done) { //enrich with user id let userid = context.getStore(UserProfileStore).userid; if (userid == null || userid === '') { context.executeAction(navigateAction, { url: '/' }); } else { //enrich with user id payload.userid = userid; context.service.update('deck.update', payload, null, {timeout: 30 * 1000}, (err, res) => { if (err) { context.dispatch('SAVE_DECK_EDIT_FAILURE', err); } else { context.dispatch('SAVE_DECK_EDIT_SUCCESS', res); context.dispatch('UPDATE_TREE_NODE_SUCCESS', {selector: payload.selector, nodeSpec: {title: striptags(payload.title)}}); //update the URL: redirect to view after edit let newURL = '/deck/' + payload.selector.id + '/' + payload.selector.stype + '/' + payload.selector.sid + '/' + payload.selector.spath; context.executeAction(navigateAction, { url: newURL }); } done(); }); } }
Sort entryproducts api by latest entrys, limit to 20
'use strict'; const hooks = require('./hooks'); const Promise = require('bluebird'); module.exports = function(){ const app = this; app.use('/entryproducts', { find() { const sequelize = app.get('sequelize'); var products = [], idsResult = []; return sequelize.models['Entry'].findAll({ attributes: [ [sequelize.fn('COUNT', sequelize.col('ProductId')), 'count'], 'ProductId' ], group: ['ProductId'], where: { ProductId: { $ne: null } } }).then(ids => { idsResult = ids.map(id => id.dataValues); return sequelize.models['Product'].findAll({ attributes: ['id', 'barcode', 'vendor', 'name', 'detailname', 'createdAt'], limit: 20, order: [['updatedAt', 'DESC']], where: { id: { $in: ids.map(itm => { return itm.ProductId }) } } }) }).then(products => { return products.map(product => { product = product.dataValues; let id = idsResult.filter(itm => { return itm.ProductId === product.id; })[0]; product = Object.assign(product,id); delete product.ProductId; return product; }) }) } }); // Get our initialize service to that we can bind hooks const entryProductsService = app.service('/entryproducts'); // Set up our before hooks entryProductsService.before(hooks.before); // Set up our after hooks entryProductsService.after(hooks.after); };
'use strict'; const hooks = require('./hooks'); const Promise = require('bluebird'); module.exports = function(){ const app = this; app.use('/entryproducts', { find() { const sequelize = app.get('sequelize'); var products = [], idsResult = []; return sequelize.models['Entry'].findAll({ attributes: [ [sequelize.fn('COUNT', sequelize.col('ProductId')), 'count'], 'ProductId' ], group: ['ProductId'], where: { ProductId: { $ne: null } } }).then(ids => { idsResult = ids.map(id => id.dataValues); return sequelize.models['Product'].findAll({ attributes: ['id', 'barcode', 'vendor', 'name', 'detailname'], where: { id: { $in: ids.map(itm => { return itm.ProductId }) } } }) }).then(products => { return products.map(product => { product = product.dataValues; let id = idsResult.filter(itm => { return itm.ProductId === product.id; })[0]; product = Object.assign(product,id); delete product.ProductId; return product; }) }) } }); // Get our initialize service to that we can bind hooks const entryProductsService = app.service('/entryproducts'); // Set up our before hooks entryProductsService.before(hooks.before); // Set up our after hooks entryProductsService.after(hooks.after); };
Improve infected human approach AI. The approach AI now only kicks in when the player is within 400 pixels of the enemy. The direction it chooses to look in is a bit more sane now. It will figure out whether the distance is greater in the X or Y location, and pick a direction based on that. Now they actually appear to walk toward the player correctly.
from pygame.locals import * from thecure import get_engine from thecure.sprites.base import Direction, WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 APPROACH_DISTANCE = 400 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player distance_x = abs(player.rect.x - self.rect.x) distance_y = abs(player.rect.y - self.rect.y) if (self.frame_state == 'walking' or (distance_x <= self.APPROACH_DISTANCE and distance_y <= self.APPROACH_DISTANCE)): x_dir = None y_dir = None if player.rect.x > self.rect.x: x = 1 x_dir = Direction.RIGHT elif player.rect.x < self.rect.x: x = -1 x_dir = Direction.LEFT else: x = 0 if player.rect.y > self.rect.y: y = 1 y_dir = Direction.DOWN elif player.rect.y < self.rect.y: y = -1 y_dir = Direction.UP else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() if distance_x > distance_y: self.set_direction(x_dir) elif distance_y > distance_x: self.set_direction(y_dir) else: self.frame_state = 'default' self.anim_timer.stop()
from pygame.locals import * from thecure import get_engine from thecure.sprites.base import WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player if player.rect.x > self.rect.x: x = 1 elif player.rect.x < self.rect.x: x = -1 else: x = 0 if player.rect.y > self.rect.y: y = 1 elif player.rect.y < self.rect.y: y = -1 else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() self.recompute_direction() else: self.frame_state = 'default' self.anim_timer.stop()
Fix the routing match issue
<?php namespace Vitaminate\Routing; use Vitaminate\Http\Request; use Vitaminate\Routing\Route; use Vitaminate\Routing\Contracts\RouteCollectionInterface; /** * Class Matcher * * @author Mystro Ken <[email protected]> * @package Vitaminate\Routing */ class RouteMatcher { /** * Get the matched route from the request. * * @param Request $request * @param RouteCollectionInterface $routeCollection * @return null|\Vitaminate\Routing\Route */ public function getRoute(Request $request, RouteCollectionInterface $routeCollection) { $routeMatch = null; $url = parse_url($request->getRequestUri()); $parameters = $request->query->all(); $path = $url["path"]; /** * @var Route $route */ foreach ($routeCollection->getRoutes() as $route) { $routePath = $route->getPath(); $routeParameters = $route->getParameters(); $parametersMatch = array_intersect($routeParameters, $parameters) if( $path != $routePath ) continue; if( sizeof($parametersMatch) !== sizeof($routeParameters) ) continue; if( serialize($parametersMatch) !== serialize($routeParameters) ) continue; $routeMatch = $route; break; } return $routeMatch; } }
<?php namespace Vitaminate\Routing; use Vitaminate\Http\Request; use Vitaminate\Routing\Route; use Vitaminate\Routing\Contracts\RouteCollectionInterface; /** * Class Matcher * * @author Mystro Ken <[email protected]> * @package Vitaminate\Routing */ class RouteMatcher { /** * Get the matched route from the request. * * @param Request $request * @param RouteCollectionInterface $routeCollection * @return null|\Vitaminate\Routing\Route */ public function getRoute(Request $request, RouteCollectionInterface $routeCollection) { $routeMatch = null; $url = parse_url($request->getRequestUri()); $parameters = $request->query->all(); $path = $url["path"]; /** * @var Route $route */ foreach ($routeCollection->getRoutes() as $route) { $routePath = $route->getPath(); $routeParameters = $route->getParameters(); if( $path != $routePath ) continue; if( sizeof($parameters) !== sizeof($routeParameters) ) continue; if( serialize($parameters) !== serialize($routeParameters) ) continue; $routeMatch = $route; break; } return $routeMatch; } }
Fix Symfony 3 incompatible form type
<?php namespace Mapbender\DigitizerBundle\Element\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class DigitizerAdminType extends AbstractType { public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'application' => null )); } /** * @inheritdoc */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('target', 'Mapbender\CoreBundle\Element\Type\TargetElementType', array( 'element_class' => 'Mapbender\CoreBundle\Element\Map', 'application' => $options['application'], 'required' => false, // dummy property path required for compatibility for TargetElementType // on Mapbender <=3.0.8.4 (no longer required on 3.0.8.5 RC and higher) 'property_path' => '[target]', )) ->add('displayOnInactive', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType' ,array( 'required' => false, 'label' => 'mb.digitizer.displayOnInactive', )) ->add('schemes', 'Mapbender\ManagerBundle\Form\Type\YAMLConfigurationType', array( 'required' => false, 'attr' => array( 'class' => 'code-yaml', ), )) ; } }
<?php namespace Mapbender\DigitizerBundle\Element\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class DigitizerAdminType extends AbstractType { public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'application' => null )); } /** * @inheritdoc */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('target', 'Mapbender\CoreBundle\Element\Type\TargetElementType', array( 'element_class' => 'Mapbender\CoreBundle\Element\Map', 'application' => $options['application'], 'required' => false, // dummy property path required for compatibility for TargetElementType // on Mapbender <=3.0.8.4 (no longer required on 3.0.8.5 RC and higher) 'property_path' => '[target]', )) ->add('displayOnInactive','checkbox',array('required' => false, 'label' => 'mb.digitizer.displayOnInactive')) ->add('schemes', 'Mapbender\ManagerBundle\Form\Type\YAMLConfigurationType', array( 'required' => false, 'attr' => array( 'class' => 'code-yaml', ), )) ; } }