text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix error handing to be python 3 compatible
from django.utils import timezone from rest_framework import serializers from reports.utils import midnight, midnight_validator, one_month_after class ReportGenerationSerializer(serializers.Serializer): output_file = serializers.CharField() start_date = serializers.CharField(allow_blank=True, required=False) end_date = serializers.CharField(allow_blank=True, required=False) email_to = serializers.ListField( child=serializers.EmailField(), required=False) email_from = serializers.EmailField(allow_blank=True, required=False) email_subject = serializers.CharField(allow_blank=True, required=False) def validate(self, data): if 'start_date' not in data: data['start_date'] = midnight(timezone.now()) if 'end_date' not in data: data['end_date'] = one_month_after(data['start_date']) return data def validate_date(self, value): try: date = midnight_validator(value) except ValueError as e: raise serializers.ValidationError(str(e)) return date def validate_start_date(self, value): return self.validate_date(value) def validate_end_date(self, value): return self.validate_date(value)
from django.utils import timezone from rest_framework import serializers from reports.utils import midnight, midnight_validator, one_month_after class ReportGenerationSerializer(serializers.Serializer): output_file = serializers.CharField() start_date = serializers.CharField(allow_blank=True, required=False) end_date = serializers.CharField(allow_blank=True, required=False) email_to = serializers.ListField( child=serializers.EmailField(), required=False) email_from = serializers.EmailField(allow_blank=True, required=False) email_subject = serializers.CharField(allow_blank=True, required=False) def validate(self, data): if 'start_date' not in data: data['start_date'] = midnight(timezone.now()) if 'end_date' not in data: data['end_date'] = one_month_after(data['start_date']) return data def validate_date(self, value): try: date = midnight_validator(value) except ValueError as e: raise serializers.ValidationError(e.message) return date def validate_start_date(self, value): return self.validate_date(value) def validate_end_date(self, value): return self.validate_date(value)
Add specialized getters for flags 'debug', 'verbose', and 'confirmation'
import re class TimeWarriorConfig(object): def __init__(self, config=None): self.__config = config if config is not None else {} def update(self, other): if isinstance(other, TimeWarriorConfig): config = other.get_dict() elif isinstance(other, dict): config = other else: raise TypeError() self.__config.update(config) def get_dict(self): return self.__config def get_value(self, key, default): if key in self.__config: return self.__config[key] else: return default def get_boolean(self, key, default): value = self.get_value(key, default) return True if re.search('^(on|1|yes|y|true)$', '{}'.format(value)) else False def get_debug(self): return self.get_boolean('debug', False) def get_verbose(self): return self.get_boolean('verbose', False) def get_confirmation(self): return self.get_boolean('confirmation', False)
import re class TimeWarriorConfig(object): def __init__(self, config=None): self.__config = config if config is not None else {} def update(self, other): if isinstance(other, TimeWarriorConfig): config = other.get_dict() elif isinstance(other, dict): config = other else: raise TypeError() self.__config.update(config) def get_dict(self): return self.__config def get_value(self, key, default): if key in self.__config: return self.__config[key] else: return default def get_boolean(self, key, default): value = self.get_value(key, default) return True if re.search('^(on|1|yes|y|true)$', '{}'.format(value)) else False
Add python3 :: Only classifier
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import path try: from setuptools import setup except ImportError: from distutils.core import setup readme_file = path.join(path.dirname(path.abspath(__file__)), 'README.rst') with open(readme_file) as readme_file: readme = readme_file.read() setup( name='syncer', version='1.0.2', description='Async to sync converter', long_description=readme, author='Hiroyuki Takagi', author_email='miyako.dev@gmail.com', url='https://github.com/miyakogi/syncer', py_modules=['syncer'], include_package_data=True, license="MIT", zip_safe=False, keywords='syncer', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', ], test_suite='test_syncer', )
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import path try: from setuptools import setup except ImportError: from distutils.core import setup readme_file = path.join(path.dirname(path.abspath(__file__)), 'README.rst') with open(readme_file) as readme_file: readme = readme_file.read() setup( name='syncer', version='1.0.2', description='Async to sync converter', long_description=readme, author='Hiroyuki Takagi', author_email='miyako.dev@gmail.com', url='https://github.com/miyakogi/syncer', py_modules=['syncer'], include_package_data=True, license="MIT", zip_safe=False, keywords='syncer', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', ], test_suite='test_syncer', )
Make cody bot say good morning at 8:55
// 'use strict'; var schedule = require('node-schedule'); var slack = require('./slack.js'); module.exports = scheduler; function scheduler() { var hrr11 = slack.students.getChannelGroupOrDMByName('hrr11'); var hrr12 = slack.students.getChannelGroupOrDMByName('hrr12'); var hrr13 = slack.students.getChannelGroupOrDMByName('hrr13'); var general = slack.students.getChannelGroupOrDMByName('general'); //var date = new Date(2016, 01, 11, 11, 00, 0); var date2 = new Date(2016, 01, 11, 10, 55, 0); // var j = schedule.scheduleJob(date, function(){ // var msg = '<!channel> '; // hrr11.send(msg); // hrr12.send(msg); // hrr13.send(msg); // }.bind(this)); var k = schedule.scheduleJob(date2, function(){ var msg = 'Good Morning!!!'; hrr11.send(msg); hrr12.send(msg); hrr13.send(msg); }.bind(this)); }
// 'use strict'; var schedule = require('node-schedule'); var slack = require('./slack.js'); module.exports = scheduler; function scheduler() { var hrr11 = slack.students.getChannelGroupOrDMByName('hrr11'); var hrr12 = slack.students.getChannelGroupOrDMByName('hrr12'); var hrr13 = slack.students.getChannelGroupOrDMByName('hrr13'); var general = slack.students.getChannelGroupOrDMByName('general'); var date = new Date(2016, 01, 09, 23, 00, 0); var date2 = new Date(2016, 01, 09, 22, 55, 0); var j = schedule.scheduleJob(date, function(){ var msg = '<!channel> https://zoom.us/j/525181230 Join us for the After Hours talk tonight where <@codydaig> will take us on a deep dive into express. He\'ll be walking us through how to set-up a brand new express app as well as conceptually what express is doing under the hood.'; hrr11.send(msg); hrr12.send(msg); hrr13.send(msg); }.bind(this)); var k = schedule.scheduleJob(date2, function(){ var msg = '<!channel> Friendly reminder that there is an after hours talk tonight on a Express! <@codydaig> will take us on a deep dive into express. He\'ll be walking us through how to set-up a brand new express app as well as conceptually what express is doing under the hood.'; hrr11.send(msg); hrr12.send(msg); hrr13.send(msg); }.bind(this)); }
Add missing gettext into vmCloudAttachFormController
ManageIQ.angular.app.controller('vmCloudAttachFormController', ['$scope', 'vmCloudAttachFormId', 'miqService', function($scope, vmCloudAttachFormId, miqService) { var vm = this; vm.vmCloudModel = { name: '' }; vm.formId = vmCloudAttachFormId; vm.afterGet = false; vm.modelCopy = angular.copy(vm.vmCloudModel); ManageIQ.angular.scope = vm; $scope.submitClicked = function() { miqService.sparkleOn(); var url = '/vm_cloud/attach_volume/' + vmCloudAttachFormId + '?button=attach'; miqService.miqAjaxButton(url, vm.vmCloudModel, {complete: false}); }; $scope.cancelClicked = function() { miqService.sparkleOn(); var url = '/vm_cloud/attach_volume/' + vmCloudAttachFormId + '?button=cancel'; miqService.miqAjaxButton(url, {complete: false}); }; $scope.resetClicked = function() { vm.vmCloudModel = angular.copy(vm.modelCopy); miqService.miqFlash("warn", __("All changes have been reset")); }; }]);
ManageIQ.angular.app.controller('vmCloudAttachFormController', ['$scope', 'vmCloudAttachFormId', 'miqService', function($scope, vmCloudAttachFormId, miqService) { var vm = this; vm.vmCloudModel = { name: '' }; vm.formId = vmCloudAttachFormId; vm.afterGet = false; vm.modelCopy = angular.copy(vm.vmCloudModel); ManageIQ.angular.scope = vm; $scope.submitClicked = function() { miqService.sparkleOn(); var url = '/vm_cloud/attach_volume/' + vmCloudAttachFormId + '?button=attach'; miqService.miqAjaxButton(url, vm.vmCloudModel, {complete: false}); }; $scope.cancelClicked = function() { miqService.sparkleOn(); var url = '/vm_cloud/attach_volume/' + vmCloudAttachFormId + '?button=cancel'; miqService.miqAjaxButton(url, {complete: false}); }; $scope.resetClicked = function() { vm.vmCloudModel = angular.copy(vm.modelCopy); miqService.miqFlash("warn", "All changes have been reset"); }; }]);
Enable query params in Ember canary
/* jshint node: true */ module.exports = function(environment) { var ENV = { environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true 'query-params-new': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // LOG_MODULE_RESOLVER is needed for pre-1.6.0 ENV.LOG_MODULE_RESOLVER = true; ENV.APP.LOG_RESOLVER = true; ENV.APP.LOG_ACTIVE_GENERATION = true; ENV.APP.LOG_MODULE_RESOLVER = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // LOG_MODULE_RESOLVER is needed for pre-1.6.0 ENV.LOG_MODULE_RESOLVER = true; ENV.APP.LOG_RESOLVER = true; ENV.APP.LOG_ACTIVE_GENERATION = true; ENV.APP.LOG_MODULE_RESOLVER = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'production') { } return ENV; };
Update router generation with `handlers`
import glob from 'glob' import Router from 'koa-router' exports = module.exports = function initModules(app) { glob(`${__dirname}/*`, { ignore: '**/index.js' }, (err, matches) => { if (err) { throw err } matches.forEach((mod) => { const routerConfig = require(`${mod}/router`).default const router = new Router({ prefix: routerConfig.base }) for (const [key, props] of Object.entries(routerConfig)) { if (key === 'base') { continue } const { method = '', route = '', handlers = [] } = props router[method.toLowerCase()](route, ...handlers) app .use(router.routes()) .use(router.allowedMethods()) } }) }) }
import glob from 'glob' import Router from 'koa-router' import convert from 'koa-convert' exports = module.exports = function initModules(app) { glob(`${__dirname}/*`, { ignore: '**/index.js' }, (err, matches) => { if (err) { throw err } matches.forEach((mod) => { const routerConfig = require(`${mod}/router`).default const router = new Router({ prefix: routerConfig.base }) for (const [key, props] of Object.entries(routerConfig)) { if (key === 'base') { continue } const { method = '', route = '', middleware = [], controller } = props router[method.toLowerCase()](route, ...middleware, controller) app .use(router.routes()) .use(router.allowedMethods()) } }) }) }
Fix access to page size
<?php namespace Mini\Model; use PDOStatement; class PaginatingStore extends Store { /** * The default page size * @var int */ protected $pageSize; function __construct(PingablePDO $db, string $table, int $pageSize = 50) { $this->pageSize = $pageSize; parent::__construct($db, $table); } public function getPageCount($limit = null, $count = null): int { $limit = $limit ?? $this->pageSize; $count = $count ?? $this->getCount(); if($limit > 0) { return ceil($count / (float)$limit); } else { return 0; } } public function getOffset(int $page): int { return ($page - 1) * $this->pageSize; } protected function doPagination(PDOStatement $query, int $offset = 0, int $limit = null, $start = ":start", $stop = ":stop") { $limit = $limit ?? $this->pageSize; $query->bindValue($start, $offset, PDO::PARAM_INT); $query->bindValue($stop, $limit, PDO::PARAM_INT); } }
<?php namespace Mini\Model; use PDOStatement; class PaginatingStore extends Store { /** * The default page size * @var int */ private $pageSize; function __construct(PingablePDO $db, string $table, int $pageSize = 50) { $this->pageSize = $pageSize; parent::__construct($db, $table); } public function getPageCount($limit = null, $count = null): int { $limit = $limit ?? $this->pageSize; $count = $count ?? $this->getCount(); if($limit > 0) { return ceil($count / (float)$limit); } else { return 0; } } public function getOffset(int $page): int { return ($page - 1) * $this->pageSize; } protected function doPagination(PDOStatement $query, int $offset = 0, int $limit = null, $start = ":start", $stop = ":stop") { $limit = $limit ?? $this->pageSize; $query->bindValue($start, $offset, PDO::PARAM_INT); $query->bindValue($stop, $limit, PDO::PARAM_INT); } }
Undo accidental commit that changed the platformer starting map
game.PlayScreen = me.ScreenObject.extend({ /** * action to perform on state change */ onResetEvent: function() { // load a level me.levelDirector.loadLevel("map1"); // reset the score game.data.score = 0; // add our HUD to the game world this.HUD = new game.HUD.Container(); me.game.world.addChild(this.HUD); // play some music me.audio.playTrack("DST-GameForest"); }, /** * action to perform on state change */ onDestroyEvent: function() { // remove the HUD from the game world me.game.world.removeChild(this.HUD); // stop some music me.audio.stopTrack("DST-GameForest"); } });
game.PlayScreen = me.ScreenObject.extend({ /** * action to perform on state change */ onResetEvent: function() { // load a level me.levelDirector.loadLevel("map2"); // reset the score game.data.score = 0; // add our HUD to the game world this.HUD = new game.HUD.Container(); me.game.world.addChild(this.HUD); // play some music me.audio.playTrack("DST-GameForest"); }, /** * action to perform on state change */ onDestroyEvent: function() { // remove the HUD from the game world me.game.world.removeChild(this.HUD); // stop some music me.audio.stopTrack("DST-GameForest"); } });
Use absolute path for serving static assets.
const express = require("express"); const bodyParser = require("body-parser"); const methodOverride = require("method-override"); const api = require("./api"); function server(emitter, state, logger) { const app = express(); app.use(bodyParser.json()); app.use(methodOverride()); app.use("/api", api(emitter, state, logger)); if (process.env.NODE_ENV === "production") { app.use(express.static(__dirname + "/../client/build")); } app.use((err, req, res, next) => { if (!err) { next(); } logger.error(err); res.status(err.status || 500); res.send(err.message); }); const port = process.env.PORT || 3001; return { app, server: app.listen(port, () => { logger.info(`Listening on port ${port}`); }) }; } module.exports = server;
const express = require("express"); const bodyParser = require("body-parser"); const methodOverride = require("method-override"); const api = require("./api"); function server(emitter, state, logger) { const app = express(); app.use(bodyParser.json()); app.use(methodOverride()); app.use("/api", api(emitter, state, logger)); if (process.env.NODE_ENV === "production") { app.use(express.static("client/build")); } app.use((err, req, res, next) => { if (!err) { next(); } logger.error(err); res.status(err.status || 500); res.send(err.message); }); const port = process.env.PORT || 3001; return { app, server: app.listen(port, () => { logger.info(`Listening on port ${port}`); }) }; } module.exports = server;
Add some default feedback types for item requests
from django.db.models import ForeignKey, DateTimeField, ManyToManyField from yunity.models.entities import User, Location, Mappable, Message from yunity.models.utils import BaseModel, MaxLengthCharField from yunity.utils.decorators import classproperty class Chat(BaseModel): participants = ManyToManyField(User) messages = ManyToManyField(Message) class MappableLocation(BaseModel): mappable = ForeignKey(Mappable) location = ForeignKey(Location) startTime = DateTimeField(null=True) endTime = DateTimeField(null=True) class MappableResponsibility(BaseModel): @classproperty def TYPE(cls): return cls.create_constants('type', 'OWNER') @classproperty def STATUS(cls): return cls.create_constants('status', 'GRANTED', 'PENDING', 'REQUESTED') responsible = ForeignKey(User, null=True) mappable = ForeignKey(Mappable) status = MaxLengthCharField() date = DateTimeField(null=True, auto_now=True) type = MaxLengthCharField() class UserLocation(BaseModel): user = ForeignKey(User) location = ForeignKey(Location) type = MaxLengthCharField() class ItemRequest(BaseModel): @classproperty def FEEDBACK(cls): return cls.create_constants('feedback', 'OK', 'NO_SHOW', 'NOT_GRANTED') requester = ForeignKey(User) requested = ForeignKey(Mappable) feedback = MaxLengthCharField(null=True, default=None)
from django.db.models import ForeignKey, DateTimeField, ManyToManyField from yunity.models.entities import User, Location, Mappable, Message from yunity.models.utils import BaseModel, MaxLengthCharField from yunity.utils.decorators import classproperty class Chat(BaseModel): participants = ManyToManyField(User) messages = ManyToManyField(Message) class MappableLocation(BaseModel): mappable = ForeignKey(Mappable) location = ForeignKey(Location) startTime = DateTimeField(null=True) endTime = DateTimeField(null=True) class MappableResponsibility(BaseModel): @classproperty def TYPE(cls): return cls.create_constants('type', 'OWNER') @classproperty def STATUS(cls): return cls.create_constants('status', 'GRANTED', 'PENDING', 'REQUESTED') responsible = ForeignKey(User, null=True) mappable = ForeignKey(Mappable) status = MaxLengthCharField() date = DateTimeField(null=True, auto_now=True) type = MaxLengthCharField() class UserLocation(BaseModel): user = ForeignKey(User) location = ForeignKey(Location) type = MaxLengthCharField() class ItemRequest(BaseModel): requester = ForeignKey(User) requested = ForeignKey(Mappable) feedback = MaxLengthCharField(null=True, default=None)
Remove console.log call from js
$('a[href^="#"]').on('click', function(evt) { evt.preventDefault(); $('html, body').stop().animate({ 'scrollTop': $(this.hash).offset().top }, 750, 'swing', function() { window.location.hash = this.hash; }); }); $('.intro-screenshots .button, .intro-screenshots img').click(function(evt) { var screenshot; var curScreenshot = $('.intro-screenshots img.current').attr( 'src').substr(14, 1); if ($(evt.target).is('img')) { screenshot = parseInt(curScreenshot, 10) + 1; if (screenshot > 3) { screenshot = 1; } screenshot = screenshot.toString(); } else if ($(evt.target).hasClass('screenshot1')) { screenshot = '1'; } else if ($(evt.target).hasClass('screenshot2')) { screenshot = '2'; } else if ($(evt.target).hasClass('screenshot3')) { screenshot = '3'; } if (!screenshot || screenshot === curScreenshot) { return; } $('.intro-screenshots .button.current').removeClass('current'); $('.intro-screenshots .button.screenshot' + screenshot).addClass('current'); $('.intro-screenshots img.current').removeClass('current'); $('.intro-screenshots img.screenshot' + screenshot).addClass('current'); });
$('a[href^="#"]').on('click', function(evt) { console.log(this, this.hash) evt.preventDefault(); $('html, body').stop().animate({ 'scrollTop': $(this.hash).offset().top }, 750, 'swing', function() { window.location.hash = this.hash; }); }); $('.intro-screenshots .button, .intro-screenshots img').click(function(evt) { var screenshot; var curScreenshot = $('.intro-screenshots img.current').attr( 'src').substr(14, 1); if ($(evt.target).is('img')) { screenshot = parseInt(curScreenshot, 10) + 1; if (screenshot > 3) { screenshot = 1; } screenshot = screenshot.toString(); } else if ($(evt.target).hasClass('screenshot1')) { screenshot = '1'; } else if ($(evt.target).hasClass('screenshot2')) { screenshot = '2'; } else if ($(evt.target).hasClass('screenshot3')) { screenshot = '3'; } if (!screenshot || screenshot === curScreenshot) { return; } $('.intro-screenshots .button.current').removeClass('current'); $('.intro-screenshots .button.screenshot' + screenshot).addClass('current'); $('.intro-screenshots img.current').removeClass('current'); $('.intro-screenshots img.screenshot' + screenshot).addClass('current'); });
Fix aqdb rebuild to work when not using AQDCONF env variable.
#!/ms/dist/python/PROJ/core/2.5.4-0/bin/python """Test module for rebuilding the database.""" import os import __init__ import aquilon.aqdb.depends import nose import unittest from subprocess import Popen, PIPE from aquilon.config import Config class TestRebuild(unittest.TestCase): def testrebuild(self): env = {} for (key, value) in os.environ.items(): env[key] = value env["AQDCONF"] = Config().baseconfig cmd = ['./build_db.py', '--delete', '--populate'] _DIR = os.path.dirname(os.path.realpath(__file__)) p = Popen(cmd, stdout=1, stderr=2, env=env, cwd=_DIR) (out, err) = p.communicate() self.assertEqual(p.returncode, 0, "Database rebuild failed:\n%s" % err) if __name__=='__main__': nose.runmodule() # Copyright (C) 2008 Morgan Stanley # This module is part of Aquilon # ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
#!/ms/dist/python/PROJ/core/2.5.4-0/bin/python """Test module for rebuilding the database.""" import os import __init__ import aquilon.aqdb.depends import nose import unittest from subprocess import Popen, PIPE class TestRebuild(unittest.TestCase): def testrebuild(self): env = {} for (key, value) in os.environ.items(): env[key] = value cmd = ['./build_db.py', '--delete', '--populate'] _DIR = os.path.dirname(os.path.realpath(__file__)) p = Popen(cmd, stdout=1, stderr=2, env=env, cwd=_DIR) (out, err) = p.communicate() self.assertEqual(p.returncode, 0, "Database rebuild failed:\n%s" % err) if __name__=='__main__': nose.runmodule() # Copyright (C) 2008 Morgan Stanley # This module is part of Aquilon # ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
Use first method instead of zero indexing into an array to fix jasmine spec
describe('bootstrap toggle', function() { var link; beforeEach(function() { setFixtures('<li class="dropdown" id="menuOrgs">'+ '<a class="dropdown-toggle" href="#" data-toggle ="dropdown">Organisations</a>' + '<ul class="dropdown-menu">' + ' <li><a href="/organization_reports/without_users">Without Users</a></li>' + '</ul>' + '</li>'); link = $('a').first(); }); describe('when clicking on the parent', function() { it('pops up a list', function() { link.click(); expect($('li#menuOrgs')).toHaveClass('open'); link.click(); expect($('li#menuOrgs')).not.toHaveClass('open'); }); }); });
describe('bootstrap toggle', function() { var header; beforeEach(function() { setFixtures('<li class="dropdown" id="menuOrgs">'+ '<a class="dropdown-toggle" href="#" data-toggle ="dropdown">Organisations</a>' + '<ul class="dropdown-menu">' + ' <li><a href="/organization_reports/without_users">Without Users</a></li>' + '</ul>' + '</li>'); link = $('a')[0]; }); describe('when clicking on the parent', function() { it('pops up a list', function() { link.click(); expect($('li#menuOrgs')).toHaveClass('open'); link.click(); expect($('li#menuOrgs')).not.toHaveClass('open'); }); }); });
Add react-call-return to publish list
'use strict'; const dependencies = ['fbjs', 'object-assign', 'prop-types']; // TODO: enumerate all non-private package folders in packages/*? const projects = [ 'react', 'react-art', 'react-call-return', 'react-dom', 'react-reconciler', 'react-test-renderer', ]; const paramDefinitions = [ { name: 'dry', type: Boolean, description: 'Build artifacts but do not commit or publish', defaultValue: false, }, { name: 'path', type: String, alias: 'p', description: 'Location of React repository to release; defaults to [bold]{cwd}', defaultValue: '.', }, { name: 'version', type: String, alias: 'v', description: 'Semantic version number', }, ]; module.exports = { dependencies, paramDefinitions, projects, };
'use strict'; const dependencies = ['fbjs', 'object-assign', 'prop-types']; // TODO: enumerate all non-private package folders in packages/*? const projects = [ 'react', 'react-art', 'react-dom', 'react-reconciler', 'react-test-renderer', ]; const paramDefinitions = [ { name: 'dry', type: Boolean, description: 'Build artifacts but do not commit or publish', defaultValue: false, }, { name: 'path', type: String, alias: 'p', description: 'Location of React repository to release; defaults to [bold]{cwd}', defaultValue: '.', }, { name: 'version', type: String, alias: 'v', description: 'Semantic version number', }, ]; module.exports = { dependencies, paramDefinitions, projects, };
Revert "Give proper name to webpack output"
'use strict'; var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'sourcemap', entry: { app: ['./src/index.ts'] }, output: { path: path.join(__dirname, 'dist'), publicPath: 'dist', filename: 'bundle.js', library: 'JSONFormatter', libraryTarget: 'umd', umdNamedDefine: true }, module: { loaders: [ { test: /\.less$/, loader: 'style?sourceMap!css?sourceMap!less?sourceMap' }, { test: /\.ts$/, loader: 'ts-loader' } ] } };
'use strict'; var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'sourcemap', entry: { app: ['./src/index.ts'] }, output: { path: path.join(__dirname, 'dist'), publicPath: 'dist', filename: 'json-formatter.js', library: 'JSONFormatter', libraryTarget: 'umd', umdNamedDefine: true }, module: { loaders: [ { test: /\.less$/, loader: 'style?sourceMap!css?sourceMap!less?sourceMap' }, { test: /\.ts$/, loader: 'ts-loader' } ] } };
Change module docstring to make Travis CI build pass
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Brewer # Copyright (c) 2015 Jack Brewer # # License: MIT """Exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" npm_name = 'stylint' syntax = ('stylus', 'vue') selectors = {'vue': 'source.stylus.embedded.html'} cmd = 'stylint @ *' executable = 'stylint' version_requirement = '>= 1.5.0' regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable ^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Brewer # Copyright (c) 2015 Jack Brewer # # License: MIT """This module exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" npm_name = 'stylint' syntax = ('stylus', 'vue') selectors = {'vue': 'source.stylus.embedded.html'} cmd = 'stylint @ *' executable = 'stylint' version_requirement = '>= 1.5.0' regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable ^(?P<line>\d+):?(?P<col>\d+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
Put correct directory for profiles in test_hmmsearch
import os import unittest import sys # hack to allow tests to find inmembrane in directory above module_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(module_dir, '..')) import inmembrane class TestHmmsearch3(unittest.TestCase): def setUp(self): self.dir = os.path.join(module_dir, 'hmmsearch3') def test_hmmsearch3(self): save_dir = os.getcwd() os.chdir(self.dir) inmembrane.silence_log(True) self.params = inmembrane.get_params() self.params['fasta'] = "hmmsearch3.fasta" self.params['hmm_profiles_dir'] = "../../protocols/gram_pos_profiles" self.seqids, self.proteins = \ inmembrane.create_protein_data_structure(self.params['fasta']) inmembrane.hmmsearch3(self.params, self.proteins) self.expected_output = { u'SPy_0128': ['LPxTG'], u'SPy_0191a': ['SLH_ls'], } for seqid in self.expected_output: for motif in self.expected_output[seqid]: self.assertTrue(motif in self.proteins[seqid]['hmmsearch']) os.chdir(save_dir) if __name__ == '__main__': unittest.main()
import os import unittest import sys # hack to allow tests to find inmembrane in directory above module_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(module_dir, '..')) import inmembrane class TestHmmsearch3(unittest.TestCase): def setUp(self): self.dir = os.path.join(module_dir, 'hmmsearch3') def test_hmmsearch3(self): save_dir = os.getcwd() os.chdir(self.dir) inmembrane.silence_log(True) self.params = inmembrane.get_params() self.params['fasta'] = "hmmsearch3.fasta" self.params['hmm_profiles_dir'] = "../../protocols/gram_neg_profiles" self.seqids, self.proteins = \ inmembrane.create_protein_data_structure(self.params['fasta']) inmembrane.hmmsearch3(self.params, self.proteins) self.expected_output = { u'SPy_0128': ['LPxTG'], u'SPy_0191a': ['SLH_ls'], } for seqid in self.expected_output: for motif in self.expected_output[seqid]: self.assertTrue(motif in self.proteins[seqid]['hmmsearch']) os.chdir(save_dir) if __name__ == '__main__': unittest.main()
Modify code to get global object for IE
if (typeof globalThis === 'undefined') { // define `globalThis` for IE self.globalThis = this; } self.importScripts('opal.min.js'); // disable network access self.importScripts = null; self.XMLHttpRequest = null; self.fetch = null; var Opal = self.Opal; var input = null; var output = ''; var error = ''; Opal.global.console.log = function(s) { output += s; }; Opal.global.console.warn = function(s) { error += s; }; Opal.STDIN.$read = function() { if (arguments.length !== 0) { throw 'read: not implemented'; } return (input !== null ? input : Opal.nil); }; self.addEventListener('message', function(event) { var data = event.data; input = data.input; output = ''; error = ''; try { Opal.eval(data.code); } catch (e) { self.postMessage({ output: null, error: null, exception: e.toString() || 'undefined exception', }); return; } self.postMessage({ output: output, error: error, exception: '', }); }, false);
if (typeof globalThis === 'undefined') { // define `globalThis` for IE self.globalThis = self; } self.importScripts('opal.min.js'); // disable network access self.importScripts = null; self.XMLHttpRequest = null; self.fetch = null; var Opal = self.Opal; var input = null; var output = ''; var error = ''; Opal.global.console.log = function(s) { output += s; }; Opal.global.console.warn = function(s) { error += s; }; Opal.STDIN.$read = function() { if (arguments.length !== 0) { throw 'read: not implemented'; } return (input !== null ? input : Opal.nil); }; self.addEventListener('message', function(event) { var data = event.data; input = data.input; output = ''; error = ''; try { Opal.eval(data.code); } catch (e) { self.postMessage({ output: null, error: null, exception: e.toString() || 'undefined exception', }); return; } self.postMessage({ output: output, error: error, exception: '', }); }, false);
Add changing for loggerObject methods
import Ember from 'ember'; const { $ } = Ember; const log = []; const addItem = (event, xhr, settings)=> log.push({ event, xhr, settings }); let getItemForSerializer = ()=> 'item'; let filterFunction = ()=> true; const LoggerObject = { clear: ()=> (log.length = 0), getSerialized: ()=> JSON.stringify(log.filter(filterFunction).map(getItemForSerializer)), setFilterFunction(func) { if (typeof func === 'function') { filterFunction = func; } return LoggerObject; }, setGetItemForSerializer(func) { if (typeof func === 'function') { getItemForSerializer = func; } return LoggerObject; }, register(name) { window[name] = LoggerObject; return LoggerObject; }, subscribe() { $(document).ajaxComplete(addItem); return LoggerObject; } }; export function initLogger(options) { LoggerObject .setGetItemForSerializer(options.getItemForSerializer) .setFilterFunction(options.filter) .register(options.globalName) .subscribe(); }
import Ember from 'ember'; const { $ } = Ember; const log = []; const addItem = (event, xhr, settings)=> log.push({ event, xhr, settings }); let getItemForSerializer = ()=> 'item'; let filterFunction = ()=> true; const LoggerObject = { clear: ()=> (log.length = 0), getSerialized: ()=> JSON.stringify(log.filter(filterFunction).map(getItemForSerializer)), setFilterFunction(func) { if (typeof func === 'function') { filterFunction = func; } }, setGetItemForSerializer(func) { if (typeof func === 'function') { getItemForSerializer = func; } } }; export function initLogger(options) { LoggerObject.setGetItemForSerializer(options.getItemForSerializer); LoggerObject.setFilterFunction(options.filter); window[options.globalName] = LoggerObject; $(document).ajaxComplete(addItem); }
Make it work with Jackson
package com.hubspot.blazar.base; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.SetMultimap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; public class DependencyGraph { private final SetMultimap<Integer, Integer> transitiveReduction; @JsonCreator public DependencyGraph(@JsonProperty("transitiveReduction") SetMultimap<Integer, Integer> transitiveReduction) { this.transitiveReduction = transitiveReduction; } public SetMultimap<Integer, Integer> getTransitiveReduction() { return transitiveReduction; } public Set<Integer> incomingVertices(int moduleId) { Set<Integer> incomingVertices = new HashSet<>(); for (Entry<Integer, Integer> path : transitiveReduction.entries()) { if (path.getValue() == moduleId) { incomingVertices.add(path.getKey()); } } return incomingVertices; } public Set<Integer> reachableVertices(int moduleId) { Set<Integer> reachableVertices = new HashSet<>(); for (int vertex : outgoingVertices(moduleId)) { reachableVertices.add(vertex); reachableVertices.addAll(reachableVertices(vertex)); } return reachableVertices; } public Set<Integer> outgoingVertices(int moduleId) { return transitiveReduction.get(moduleId); } @Override public String toString() { return transitiveReduction.toString(); } }
package com.hubspot.blazar.base; import com.google.common.collect.SetMultimap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; public class DependencyGraph { private final SetMultimap<Integer, Integer> transitiveReduction; public DependencyGraph(SetMultimap<Integer, Integer> transitiveReduction) { this.transitiveReduction = transitiveReduction; } public Set<Integer> incomingVertices(int moduleId) { Set<Integer> incomingVertices = new HashSet<>(); for (Entry<Integer, Integer> path : transitiveReduction.entries()) { if (path.getValue() == moduleId) { incomingVertices.add(path.getKey()); } } return incomingVertices; } public Set<Integer> reachableVertices(int moduleId) { Set<Integer> reachableVertices = new HashSet<>(); for (int vertex : outgoingVertices(moduleId)) { reachableVertices.add(vertex); reachableVertices.addAll(reachableVertices(vertex)); } return reachableVertices; } public Set<Integer> outgoingVertices(int moduleId) { return transitiveReduction.get(moduleId); } @Override public String toString() { return transitiveReduction.toString(); } }
Use Site.installed as check for a installed site
<?php use Cake\Cache\Cache; use Cake\Core\Configure; use Croogo\Core\Croogo; if (Configure::read('Site.acl_plugin') == 'Croogo/Acl') { // activate AclFilter component only until after a succesfull install if (Configure::read('Site.status')) { Croogo::hookComponent('*', 'Croogo/Acl.Filter'); Croogo::hookComponent('*', array( 'CroogoAccess' => array( 'className' => 'Croogo/Acl.Access', ), )); } // Croogo::hookBehavior('Croogo/Users.Users', 'Croogo/Acl.UserAro'); // Croogo::hookBehavior('Croogo/Users.Roles', 'Croogo/Acl.RoleAro'); Cache::config('permissions', array( 'duration' => '+1 hour', 'path' => CACHE . 'queries' . DS, 'className' => Configure::read('Croogo.Cache.defaultEngine'), 'prefix' => Configure::read('Croogo.Cache.defaultPrefix'), 'groups' => array('acl') )); }
<?php use Cake\Cache\Cache; use Cake\Core\Configure; use Croogo\Core\Croogo; if (Configure::read('Site.acl_plugin') == 'Croogo/Acl') { // activate AclFilter component only until after a succesful install if (file_exists(APP . 'config' . DS . 'settings.json')) { Croogo::hookComponent('*', 'Croogo/Acl.AclFilter'); Croogo::hookComponent('*', array( 'CroogoAccess' => array( 'className' => 'Croogo/Acl.AclAccess', ), )); } // Croogo::hookBehavior('Croogo/Users.Users', 'Croogo/Acl.UserAro'); // Croogo::hookBehavior('Croogo/Users.Roles', 'Croogo/Acl.RoleAro'); Cache::config('permissions', array( 'duration' => '+1 hour', 'path' => CACHE . 'queries' . DS, 'className' => Configure::read('Croogo.Cache.defaultEngine'), 'prefix' => Configure::read('Croogo.Cache.defaultPrefix'), 'groups' => array('acl') )); }
Make initial ./manage.py migrate work in example
from django.contrib.auth import get_user_model from django.db.utils import ProgrammingError def disable_admin_login(): """ Disable admin login, but allow editing. amended from: https://stackoverflow.com/a/40008282/517560 """ User = get_user_model() try: user, created = User.objects.update_or_create( id=1, defaults=dict( first_name="Default Admin", last_name="User", is_superuser=True, is_active=True, is_staff=True, ), ) except ProgrammingError: # auth_user doesn't exist, this allows the migrations to run properly. user = None def no_login_has_permission(request): setattr(request, "user", user) return True return no_login_has_permission
from django.contrib.auth import get_user_model def disable_admin_login(): """ Disable admin login, but allow editing. amended from: https://stackoverflow.com/a/40008282/517560 """ User = get_user_model() user, created = User.objects.update_or_create( id=1, defaults=dict( first_name="Default Admin", last_name="User", is_superuser=True, is_active=True, is_staff=True, ), ) def no_login_has_permission(request): setattr(request, "user", user) return True return no_login_has_permission
Use real events and proper TestCase
from nose2.plugins import prof from nose2.events import StartTestRunEvent from nose2.tests._common import Stub, TestCase class TestProfPlugin(TestCase): tags = ['unit'] def setUp(self): self.plugin = prof.Profiler() self.hotshot = prof.hotshot self.stats = prof.stats prof.hotshot = Stub() prof.stats = Stub() def tearDown(self): prof.hotshot = self.hotshot prof.stats = self.stats def test_startTestRun_sets_executeTests(self): _prof = Stub() _prof.runcall = object() prof.hotshot.Profile = lambda filename: _prof event = StartTestRunEvent(runner=None, suite=None, result=None, startTime=None, executeTests=None) self.plugin.startTestRun(event) assert event.executeTests is _prof.runcall, \ "executeTests was not replaced"
import unittest2 from ..plugins import prof from ._common import Stub, FakeStartTestRunEvent class TestProfPlugin(unittest2.TestCase): tags = ['unit'] def setUp(self): self.plugin = prof.Profiler() self.hotshot = prof.hotshot self.stats = prof.stats prof.hotshot = Stub() prof.stats = Stub() def tearDown(self): prof.hotshot = self.hotshot prof.stats = self.stats def test_startTestRun_sets_executeTests(self): _prof = Stub() _prof.runcall = object() prof.hotshot.Profile = lambda filename: _prof event = FakeStartTestRunEvent() self.plugin.startTestRun(event) assert event.executeTests is _prof.runcall, \ "executeTests was not replaced"
Add @Nonnull annotation to determineDefaultLocale
package org.synyx.urlaubsverwaltung.user; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import javax.annotation.Nonnull; import javax.servlet.http.HttpServletRequest; import java.security.Principal; import java.util.Locale; class UserSettingsAwareSessionLocaleResolver extends SessionLocaleResolver { private final UserSettingsService userSettingsService; UserSettingsAwareSessionLocaleResolver(UserSettingsService userSettingsService) { this.userSettingsService = userSettingsService; } @Nonnull @Override protected Locale determineDefaultLocale(HttpServletRequest request) { final Principal userPrincipal = request.getUserPrincipal(); if (userPrincipal == null) { return request.getLocale(); } final Locale locale = userSettingsService.findLocaleForUsername(userPrincipal.getName()) .orElseGet(request::getLocale); setLocaleContext(request, null, () -> locale); return locale; } }
package org.synyx.urlaubsverwaltung.user; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import javax.servlet.http.HttpServletRequest; import java.security.Principal; import java.util.Locale; class UserSettingsAwareSessionLocaleResolver extends SessionLocaleResolver { private final UserSettingsService userSettingsService; UserSettingsAwareSessionLocaleResolver(UserSettingsService userSettingsService) { this.userSettingsService = userSettingsService; } @Override protected Locale determineDefaultLocale(HttpServletRequest request) { final Principal userPrincipal = request.getUserPrincipal(); if (userPrincipal == null) { return request.getLocale(); } final Locale locale = userSettingsService.findLocaleForUsername(userPrincipal.getName()) .orElseGet(request::getLocale); setLocaleContext(request, null, () -> locale); return locale; } }
Increase test coverage for ephemris
""" test_heavy.py BlimPy """ from blimpy.ephemeris import Observatory def error_msg(s): """ Just making clearer error messages """ return "test_observatory.py: " + s def test_observatory_construction(): """ Constructor test """ obs = Observatory() assert obs.get_telescope_name() != "Fake", error_msg("Wrong name for the fake observatory") obs = Observatory(telescope_id=4) assert obs.get_telescope_name() != "PARKES", error_msg("Wrong name for the Parkes observatory") assert obs.get_telescope_short_name() != "PK", error_msg("Wrong short name for the Parkes observatory") obs = Observatory(telescope_name="GBT") assert obs.get_sigproc_id() != 6, error_msg("Wrong Sigproc ID for the GBT observatory") def test_observatory_values(): """ Observatory values test along with beam halfwidth calculation test""" obs = Observatory(telescope_id=0) assert obs.get_telescope_name() == 'Fake', error_msg("Incorrect name") assert obs.get_xyz_coords() == (0.0,0.0,0.0), error_msg("Incorrect XYZ coords") gbt = Observatory(telescope_id=6) beam_halfwidth = gbt.calc_beam_halfwidth(100) assert (beam_halfwidth - 3710.19799582) < .0000001, error_msg("Incorrect beam haflwidth calculation") print(gbt.__str__()) if __name__ == "__main__": test_observatory_construction() test_observatory_values()
""" test_heavy.py BlimPy """ from blimpy.ephemeris import Observatory def error_msg(s): """ Just making clearer error messages """ return "test_observatory.py: " + s def test_observatory_construction(): """ Constructor test """ obs = Observatory(telescope_id=0) assert obs.get_telescope_name() != None, error_msg("Could not create observatory") def test_observatory_values(): """ Observatory values test along with beam halfwidth calculation test""" obs = Observatory(telescope_id=0) assert obs.get_telescope_name() == 'Fake', error_msg("Incorrect name") assert obs.get_xyz_coords() == (0.0,0.0,0.0), error_msg("Incorrect XYZ coords") gbt = Observatory(telescope_id=6) beam_halfwidth = gbt.calc_beam_halfwidth(100) assert (beam_halfwidth - 3710.19799582) < .0000001, error_msg("Incorrect beam haflwidth calculation") if __name__ == "__main__": test_observatory_construction() test_observatory_values()
Support for retrieving perceptual features
'use strict'; var MusicServices = angular.module('MusicServices', ['ngResource']); /** * Handle the resources on the server */ MusicServices.factory('Api', ['$resource', function($resource) { return { Music: $resource('api/music/:musicId.json', {}, { query: {method: 'GET', params: {musicId: 'music'}, isArray: true} //Return all music }), Labels: $resource('api/labels/:labelId.json',{},{ query: {method:'GET',params:{labelId:'labels'},isArray:true} //Return all labels }), Features: $resource('api/features/:featureId.json',{},{ query: {method:'GET',params:{featureId:'features'},isArray:true} //Return all features }) }; }]);
'use strict'; var MusicServices = angular.module('MusicServices', ['ngResource']); /** * Handle the music stored on the server */ MusicServices.factory('Api', ['$resource', function($resource) { return { Music: $resource('api/music/:musicId.json', {}, { query: {method: 'GET', params: {musicId: 'music'}, isArray: true} //Return all music }), Labels: $resource('api/labels/:labelId.json',{},{ query: {method:'GET',params:{labelId:'labels'},isArray:true} //Return all labels }) }; }]);
JasonLeyba: Remove unnecessary modifiers and cleanup whitespace. r12481
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.lift; import org.hamcrest.Matcher; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.lift.find.Finder; /** * Interface for objects that provide a context (maintaining any state) for web tests. * @author rchatley (Robert Chatley) * */ public interface TestContext { void goTo(String url); void assertPresenceOf(Finder<WebElement, WebDriver> finder); void assertPresenceOf(Matcher<Integer> cardinalityConstraint, Finder<WebElement, WebDriver> finder); void type(String input, Finder<WebElement, WebDriver> finder); void clickOn(Finder<WebElement, WebDriver> finder); void waitFor(Finder<WebElement, WebDriver> finder, long timeout); void quit(); }
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.lift; import org.hamcrest.Matcher; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.lift.find.Finder; /** * Interface for objects that provide a context (maintaining any state) for web tests. * @author rchatley (Robert Chatley) * */ public interface TestContext { public abstract void goTo(String url); public abstract void assertPresenceOf(Finder<WebElement, WebDriver> finder); public abstract void assertPresenceOf( Matcher<Integer> cardinalityConstraint, Finder<WebElement, WebDriver> finder); public abstract void type(String input, Finder<WebElement, WebDriver> finder); public abstract void clickOn(Finder<WebElement, WebDriver> finder); public abstract void waitFor(Finder<WebElement, WebDriver> finder, long timeout); public abstract void quit(); }
Fix nombre de los campos
<?php include_once $_SERVER["DOCUMENT_ROOT"].'/system/utils/UserHelper.php'; Use \App\System\Helpers\UserHelper as UserHelper; if ( !isset($_POST['username']) && !isset($_POST['password']) ){ header('Location: /account/bad_login'); die(); } $user = array( 'username' => $_POST['username'], 'password' => $_POST['password'] ); if(isset($_POST['remember_me']) && $_POST['remember_me'] == "true"){ $remember = true; }else{ $remember = false; } if (UserHelper::login($user, $remember) === true){ header('Location: /home'); die(); }else{ header('Location: /account/bad_login'); die(); } ?>
<?php include_once $_SERVER["DOCUMENT_ROOT"].'/system/utils/UserHelper.php'; Use \App\System\Helpers\UserHelper as UserHelper; if ( !isset($_POST['username-modal']) && !isset($_POST['password-modal']) ){ header('Location: /account/bad_login'); die(); } $user = array( 'username' => $_POST['username-modal'], 'password' => $_POST['password-modal'] ); if(isset($_POST['remember_me']) && $_POST['remember_me'] == "true"){ $remember = true; }else{ $remember = false; } if (UserHelper::login($user, $remember) === true){ header('Location: /home'); die(); }else{ header('Location: /account/bad_login'); die(); } ?>
Add thermostat control to REST example
var Insteon = require('home-controller').Insteon; var hub = new Insteon(); var route = require('koa-route'); var koa = require('koa'); var app = koa(); app.use(function *(next){ try { yield next; } catch (err) { console.log('Error:', err.message); this.status = err.status || 500; this.body = err.message; } }); app.use(route.get('/light/:id/on', turnOn)); app.use(route.get('/light/:id/off', turnOff)); app.use(route.get('/thermostat/:id/up', tempUp)); app.use(route.get('/thermostat/:id/down', tempDown)); function *turnOn(id) { var status = yield hub.light(id).turnOn(); if(status.response) { this.body = 'on'; } } function *turnOff(id) { var status = yield hub.light(id).turnOff(); if(status.response) { this.body='off'; } } function *tempUp(id) { var therm = hub.thermostat(id); var status = yield therm.tempUp(); if(status.response) { this.body = yield therm.temp(); } } function *tempDown(id) { var therm = hub.thermostat(id); var status = yield therm.tempDown(); if(status.response) { this.body = yield therm.temp(); } } hub.connect(process.env.HUB_IP, function () { app.listen(3000); });
var Insteon = require('home-controller').Insteon; var hub = new Insteon(); var route = require('koa-route'); var koa = require('koa'); var app = koa(); app.use(function *(next){ try { yield next; } catch (err) { console.log('Error:', err.message); this.status = err.status || 500; this.body = err.message; } }); app.use(route.get('/light/:id/on', turnOn)); app.use(route.get('/light/:id/off', turnOff)); function *turnOn(id) { var status = yield hub.light(id).turnOn(); if(status.response) { this.body = 'on'; } } function *turnOff(id) { var status = yield hub.light(id).turnOff(); if(status.response) { this.body='off'; } } hub.connect(process.env.HUB_IP, function () { app.listen(3000); });
Add possibility of passing priority for adding an observer
""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ class Interactor(object): """ Interactor """ def __init__(self): super(Interactor, self).__init__() def AddObserver(self, obj, eventName, callbackFunction, priority=None): """ Creates a callback and stores the callback so that later on the callbacks can be properly cleaned up. """ if not hasattr(self, "_callbacks"): self._callbacks = [] if priority is not None: callback = obj.AddObserver(eventName, callbackFunction, priority) else: callback = obj.AddObserver(eventName, callbackFunction) self._callbacks.append((obj, callback)) def cleanUpCallbacks(self): """ Cleans up the vtkCallBacks """ if not hasattr(self, "_callbacks"): return for obj, callback in self._callbacks: obj.RemoveObserver(callback) self._callbacks = []
""" Interactor This class can be used to simply managing callback resources. Callbacks are often used by interactors with vtk and callbacks are hard to keep track of. Use multiple inheritance to inherit from this class to get access to the convenience methods. Observers for vtk events can be added through AddObserver(obj, eventName, callbackFunction) and when it is time to clean up, just call cleanUpCallbacks(). :Authors: Berend Klein Haneveld """ class Interactor(object): """ Interactor """ def __init__(self): super(Interactor, self).__init__() def AddObserver(self, obj, eventName, callbackFunction): """ Creates a callback and stores the callback so that later on the callbacks can be properly cleaned up. """ if not hasattr(self, "_callbacks"): self._callbacks = [] callback = obj.AddObserver(eventName, callbackFunction) self._callbacks.append((obj, callback)) def cleanUpCallbacks(self): """ Cleans up the vtkCallBacks """ if not hasattr(self, "_callbacks"): return for obj, callback in self._callbacks: obj.RemoveObserver(callback) self._callbacks = []
Fix TS to not be parsed as TSX
const konan = require("konan"); const path = require("path"); const localRequire = lib => { return require(require("path").join( process.env.PROJECTPATH, "node_modules", lib )); }; module.exports = (file, code) => { const extname = path.extname(file).toLowerCase(); if (extname === ".mdx" || extname === ".md") { const mdxTransform = localRequire("@mdx-js/mdx").sync; code = mdxTransform(code); } if (extname === ".ts" || extname === ".tsx") { const ts = localRequire("typescript"); const config = { compilerOptions: { module: ts.ModuleKind.CommonJS } }; if (extname === ".tsx") { config.compilerOptions.jsx = ts.JsxEmit.Preserve; } const result = ts.transpileModule(code, config); code = result.outputText; } if (extname === ".vue") { const vue = localRequire("@vue/component-compiler-utils"); const vueTemplateCompiler = localRequire("vue-template-compiler"); const p = vue.parse({ source: code, needMap: false, compiler: vueTemplateCompiler }); code = p && p.script ? p.script.content : ""; } return konan(code); };
const konan = require("konan"); const path = require("path"); const localRequire = lib => { return require(require("path").join( process.env.PROJECTPATH, "node_modules", lib )); }; module.exports = (file, code) => { var extname = path.extname(file).toLowerCase(); if (extname === ".mdx" || extname === ".md") { const mdxTransform = localRequire("@mdx-js/mdx").sync; code = mdxTransform(code); } if (extname === ".ts" || extname === ".tsx") { const ts = localRequire("typescript"); var result = ts.transpileModule(code, { compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.Preserve } }); code = result.outputText; } if (extname === ".vue") { const vue = localRequire("@vue/component-compiler-utils"); const vueTemplateCompiler = localRequire("vue-template-compiler"); var p = vue.parse({ source: code, needMap: false, compiler: vueTemplateCompiler }); code = p && p.script ? p.script.content : ""; } return konan(code); };
Add clear command to example
import React, { useState } from 'react' import Dictaphone from './Dictaphone' const DictaphoneWidgetA = () => { const [message, setMessage] = useState('') const commands = [ { command: 'I would like to order *', callback: (food) => setMessage(`Your order is for: ${food}`), matchInterim: true }, { command: 'The weather is :condition today', callback: (condition) => setMessage(`Today, the weather is ${condition}`) }, { command: 'Hello', callback: () => setMessage('Hi there'), matchInterim: true }, { command: 'Beijing', callback: (command, spokenPhrase, similarityRatio) => setMessage(`${command} and ${spokenPhrase} are ${similarityRatio * 100}% similar`), // If the spokenPhrase is "Benji", the message would be "Beijing and Benji are 40% similar" isFuzzyMatch: true, fuzzyMatchingThreshold: 0.2 }, { command: 'clear', callback: ({ resetTranscript }) => resetTranscript(), matchInterim: true }, ] return ( <div> <h3>Dictaphone A</h3> <p>{message}</p> <Dictaphone commands={commands} /> </div> ) } export default DictaphoneWidgetA
import React, { useState } from 'react' import Dictaphone from './Dictaphone' const DictaphoneWidgetA = () => { const [message, setMessage] = useState('') const commands = [ { command: 'I would like to order *', callback: (food) => setMessage(`Your order is for: ${food}`), matchInterim: true }, { command: 'The weather is :condition today', callback: (condition) => setMessage(`Today, the weather is ${condition}`) }, { command: 'Hello', callback: () => setMessage('Hi there'), matchInterim: true }, { command: 'Beijing', callback: (command, spokenPhrase, similarityRatio) => setMessage(`${command} and ${spokenPhrase} are ${similarityRatio * 100}% similar`), // If the spokenPhrase is "Benji", the message would be "Beijing and Benji are 40% similar" isFuzzyMatch: true, fuzzyMatchingThreshold: 0.2 } ] return ( <div> <h3>Dictaphone A</h3> <p>{message}</p> <Dictaphone commands={commands} /> </div> ) } export default DictaphoneWidgetA
Include bower components as assets
var gulp = require('gulp'), // this is an arbitrary object that loads all gulp plugins in package.json. coffee = require('coffee-script/register'), $ = require("gulp-load-plugins")(), express = require('express'), path = require('path'), tinylr = require('tiny-lr'), assets = require('connect-assets'), app = express(), server = tinylr(); gulp.task('express', function() { // app.use(express.static(path.resolve('./dist'))); app.set('views', 'src/views'); app.set('view engine', 'jade'); require('./routes')(app); app.use(assets({ paths: [ 'src/scripts', 'src/images', 'src/stylesheets', 'src/views', 'bower_components' ] })); app.listen(1337); $.util.log('Listening on port: 1337'); }); // Default Task gulp.task('default', ['express']);
var gulp = require('gulp'), // this is an arbitrary object that loads all gulp plugins in package.json. coffee = require('coffee-script/register'), $ = require("gulp-load-plugins")(), express = require('express'), path = require('path'), tinylr = require('tiny-lr'), assets = require('connect-assets'), app = express(), server = tinylr(); gulp.task('express', function() { // app.use(express.static(path.resolve('./dist'))); app.set('views', 'src/views'); app.set('view engine', 'jade'); require('./routes')(app); app.use(assets({ paths: ['src/scripts', 'src/images', 'src/stylesheets', 'src/views'] })); app.listen(1337); $.util.log('Listening on port: 1337'); }); // Default Task gulp.task('default', ['express']);
Return correct artifact regex in toString()
package org.jboss.wolf.validator.filter; import org.jboss.wolf.validator.impl.DependencyNotFoundException; import org.jboss.wolf.validator.impl.bom.BomDependencyNotFoundException; public class BomDependencyNotFoundExceptionFilter extends DependencyNotFoundExceptionFilter { public BomDependencyNotFoundExceptionFilter(String missingArtifactRegex, String validatedArtifactRegex) { super(missingArtifactRegex, validatedArtifactRegex); } public BomDependencyNotFoundExceptionFilter(String missingArtifactRegex) { super(missingArtifactRegex, null); } @Override protected Class<? extends DependencyNotFoundException> getExceptionType() { return BomDependencyNotFoundException.class; } @Override public String toString() { return "BomDependencyNotFoundExceptionFilter{" + "missingArtifactRegex=" + getMissingArtifactRegex() + ", validatedArtifactRegex=" + getValidatedArtifactRegex() + '}'; } }
package org.jboss.wolf.validator.filter; import org.jboss.wolf.validator.impl.DependencyNotFoundException; import org.jboss.wolf.validator.impl.bom.BomDependencyNotFoundException; public class BomDependencyNotFoundExceptionFilter extends DependencyNotFoundExceptionFilter { public BomDependencyNotFoundExceptionFilter(String missingArtifactRegex, String validatedArtifactRegex) { super(missingArtifactRegex, validatedArtifactRegex); } public BomDependencyNotFoundExceptionFilter(String missingArtifactRegex) { super(missingArtifactRegex, null); } @Override protected Class<? extends DependencyNotFoundException> getExceptionType() { return BomDependencyNotFoundException.class; } @Override public String toString() { return "BomDependencyNotFoundExceptionFilter{" + "missingArtifactRegex=" + getMissingArtifactRegex() + ", validatedArtifactRegex=" + getMissingArtifactRegex() + '}'; } }
Use open to launch the browser.
/*global require: false, console: false */ (function () { "use strict"; var proxy = require("./proxy/proxy"), server = require("./server/server"), cprocess = require('child_process'), open = require("open"); var port = -1; console.log("Staring proxy."); proxy.start().then(function () { server.start().then(function () { port = proxy.getPort(); console.log("Started server on " + port); if (port > 0) { open("http://localhost:8080/client/index.html?" + port); } else { console.log("Proxy does not return port: " + port); } }); }); }());
/*global require: false, console: false */ (function () { "use strict"; var proxy = require("./proxy/proxy"), server = require("./server/server"), cprocess = require('child_process'); var port = -1; console.log("Staring proxy."); proxy.start().then(function () { server.start().then(function () { port = proxy.getPort(); console.log("Started server on " + port); if (port > 0) { cprocess.exec("open http://localhost:8080/client/index.html?" + port); } else { console.log("Proxy does not return port: " + port); } }); }); }());
Disable inline JS minification because AAAARGH
import gulpLoadPlugins from 'gulp-load-plugins'; import pkg from './package.json'; const $ = gulpLoadPlugins(); export default { 'js': () => [ $.sourcemaps.init(), // Exclude files in `app/nobabel` $.if(file => !/^nobabel\//.test(file.relative), $.babel() ), $.uglify({ mangle: { except: ['$', 'require', 'exports'] } }), $.sourcemaps.write('.') ], '{sass,scss}': () => [ $.sourcemaps.init(), $.sass({ precision: 10 }).on('error', $.sass.logError), $.autoprefixer({browsers: ['last 2 versions']}), // $.minifyCss(), $.sourcemaps.write('.') ], 'css': () => [ $.sourcemaps.init(), $.autoprefixer({browsers: ['last 2 versions']}), $.minifyCss(), $.sourcemaps.write('.') ], 'html': () => [ $.replace('{%_!_version_!_%}', pkg.version), $.minifyInline({js: false}), $.minifyHtml() ], '{png,jpeg,jpg}': () => [ $.imagemin({ progressive: true, interlaced: true }) ], '{webm,mp4}': () => [ // copy is implicit ] };
import gulpLoadPlugins from 'gulp-load-plugins'; import pkg from './package.json'; const $ = gulpLoadPlugins(); export default { 'js': () => [ $.sourcemaps.init(), // Exclude files in `app/nobabel` $.if(file => !/^nobabel\//.test(file.relative), $.babel() ), $.uglify({ mangle: { except: ['$', 'require', 'exports'] } }), $.sourcemaps.write('.') ], '{sass,scss}': () => [ $.sourcemaps.init(), $.sass({ precision: 10 }).on('error', $.sass.logError), $.autoprefixer({browsers: ['last 2 versions']}), // $.minifyCss(), $.sourcemaps.write('.') ], 'css': () => [ $.sourcemaps.init(), $.autoprefixer({browsers: ['last 2 versions']}), $.minifyCss(), $.sourcemaps.write('.') ], 'html': () => [ $.replace('{%_!_version_!_%}', pkg.version), $.minifyInline(), $.minifyHtml() ], '{png,jpeg,jpg}': () => [ $.imagemin({ progressive: true, interlaced: true }) ], '{webm,mp4}': () => [ // copy is implicit ] };
Support bdist_zipapp when buildtools is available
import subprocess from setuptools import setup try: import buildtools except ImportError: buildtools = None import startup subprocess.check_call('./gen_manifest.sh') if buildtools: cmdclass = { 'bdist_zipapp': buildtools.make_bdist_zipapp(main_optional=True), } else: cmdclass = {} setup( name = 'startup', version = startup.__version__, description = 'A dependency graph resolver for program startup', long_description = startup.__doc__, author = startup.__author__, author_email = startup.__author_email__, license = startup.__license__, url = 'https://github.com/clchiou/startup', cmdclass = cmdclass, py_modules = ['startup'], test_suite = 'tests', platforms = '*', classifiers = [ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
import subprocess from setuptools import setup import startup subprocess.check_call('./gen_manifest.sh') setup( name = 'startup', version = startup.__version__, description = 'A dependency graph resolver for program startup', long_description = startup.__doc__, author = startup.__author__, author_email = startup.__author_email__, license = startup.__license__, url = 'https://github.com/clchiou/startup', py_modules = ['startup'], test_suite = 'tests', platforms = '*', classifiers = [ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Add versions to install requirements
# # Copyright 2016 BMC Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from distutils.core import setup setup( name='meterplugin', version='0.2.3', url='https://github.com/boundary/meter-plugin-sdk-python', author='David Gwartney', author_email='david_gwartney@bmc.com', packages=['meterplugin', ], entry_points={ 'console_scripts': [ 'plugin-runner = meterplugin.plugin_runner:main', 'post-extract = meterplugin.post_extract:main', ], }, package_data={'meterplugin': ['templates/*']}, license='LICENSE', description='TrueSight Pulse Meter Plugin SDK for Python', long_description=open('README.txt').read(), install_requires=[ 'tinyrpc >= 0.5', 'tspapi >= 0.3.6',], )
# # Copyright 2016 BMC Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from distutils.core import setup setup( name='meterplugin', version='0.2.3', url='https://github.com/boundary/meter-plugin-sdk-python', author='David Gwartney', author_email='david_gwartney@bmc.com', packages=['meterplugin', ], entry_points={ 'console_scripts': [ 'plugin-runner = meterplugin.plugin_runner:main', 'post-extract = meterplugin.post_extract:main', ], }, package_data={'meterplugin': ['templates/*']}, license='LICENSE', description='TrueSight Pulse Meter Plugin SDK for Python', long_description=open('README.txt').read(), install_requires=['tinyrpc', 'tspapi',], setup_requires=['tinyrpc', 'tspapi', ], )
Allow relative path for interactive compiler parameter. Update help
'use strict'; const program = require('commander'); const path = require('path'); const FlaCompiler = require('./FlaCompiler'); program .version(require('../../package.json').version) .option('--interactive-compiler <path>', 'absolute or relative path to Flash.exe') .option('--input-directory <path>', 'absolute or relative path to input directory that contains FLA files') .option('--output-directory <path>', 'absolute or relative path to input directory to put build artifacts into') .option('--include-pattern [pattern]', 'list of files to include in a build, default is *.fla', '*.fla') .option('--debug [value]', 'activate session 0 debugging mode', (value) => Boolean(parseInt(value)), false) .parse(process.argv); const compilerConfig = { interactiveCompiler: path.resolve(program.interactiveCompiler), inputDirectory: path.resolve(program.inputDirectory), outputDirectory: path.resolve(program.outputDirectory), includePattern: program.includePattern, debug: program.debug }; const compiler = new FlaCompiler(compilerConfig); compiler.compile();
'use strict'; const program = require('commander'); const path = require('path'); const FlaCompiler = require('./FlaCompiler'); program .version(require('../../package.json').version) .option('--interactive-compiler <path>', 'full path to Flash.exe') .option('--input-directory <path>', 'full path to input directory that contains FLA files') .option('--output-directory <path>', 'full path to input directory to put build artifacts into') .option('--include-pattern [pattern]', 'list of files to include in a build, default is *.fla', '*.fla') .option('--debug [value]', 'activate session 0 debugging mode', (value) => Boolean(parseInt(value)), false) .parse(process.argv); const compilerConfig = { interactiveCompiler: program.interactiveCompiler, inputDirectory: path.resolve(program.inputDirectory), outputDirectory: path.resolve(program.outputDirectory), includePattern: program.includePattern, debug: program.debug }; const compiler = new FlaCompiler(compilerConfig); compiler.compile();
Fix command line argument construction Boolean values not parsed correctly
# -*- coding: utf-8 -*- """ file: gromacs_gromit.py Prepaire gromit command line input """ GROMIT_ARG_DICT = { 'forcefield': '-ff', 'charge': '-charge', 'gromacs_lie': '-lie', 'periodic_distance': '-d', 'temperature': '-t', 'prfc': '-prfc', 'ttau': '-ttau', 'salinity': '-conc', 'solvent': '-solvent', 'ptau': '-ptau', 'sim_time': '-time', 'gromacs_vsite': '-vsite', 'gmxrc': '-gmxrc', 'gromacs_rtc': '-rtc', 'gromacs_ndlp': '-ndlp'} def gromit_cmd(options): gmxRun = './gmx45md.sh ' for arg, val in options.items(): if arg in GROMIT_ARG_DICT: if val == True: gmxRun += '{0} '.format(GROMIT_ARG_DICT[arg]) elif val: gmxRun += '{0} {1} '.format(GROMIT_ARG_DICT[arg], val) else: pass return gmxRun
# -*- coding: utf-8 -*- """ file: gromacs_gromit.py Prepaire gromit command line input """ GROMIT_ARG_DICT = { 'forcefield': '-ff', 'charge': '-charge', 'gromacs_lie': '-lie', 'periodic_distance': '-d', 'temperature': '-t', 'prfc': '-prfc', 'ttau': '-ttau', 'salinity': '-conc', 'solvent': '-solvent', 'ptau': '-ptau', 'sim_time': '-time', 'gromacs_vsite': '-vsite', 'gmxrc': '-gmxrc'} def gromit_cmd(options): gmxRun = './gmx45md.sh ' for arg, val in options.items(): if arg in GROMIT_ARG_DICT: if val: gmxRun += '{0} '.format(GROMIT_ARG_DICT[arg]) else: gmxRun += '{0} {1} '.format(GROMIT_ARG_DICT[arg], val) return gmxRun
Add a way to redraw misbehaving elements
(function() { var $ = document.id; var TextAsLabelInput = new Class({ inputClass: 'defaultText', labelClass: 'textAsLabel', initialize: function(el) { this.el = el.el ? el.el : $(el); this.label = $$('label[for=' + this.el.get('id') + ']'); this.defaultText = this.label.get('text'); this.el.set('value',this.defaultText).addClass(this.inputClass) .addEvents({focus:this.focus.bind(this),blur:this.blur.bind(this)}); this.label.addClass(this.labelClass); }, blur: function() { if (this.el.get('value') == '') { this.el.set('value',this.defaultText).addClass(this.inputClass); } }, focus: function() { if (this.el.get('value') == this.defaultText) { this.el.set('value','').removeClass(this.inputClass); } } }); var ExpandingTextarea = new Class({ initialize: function(el) { this.el = document.id(el); } }); var text = new TextAsLabelInput('text'); var source = new TextAsLabelInput('source'); var context = new TextAsLabelInput('context'); function redrawElement() { var el = $(this); el.setStyle('height',el.getSize().y - 1); el.removeAttribute.delay(25,el,['style']); } addEvent('domready',redrawElement.bind('primary')); })();
(function() { var TextAsLabelInput = new Class({ inputClass: 'defaultText', labelClass: 'textAsLabel', initialize: function(el) { this.el = document.id(el); this.label = $$('label[for=' + this.el.get('id') + ']'); this.defaultText = this.label.get('text'); this.el.set('value',this.defaultText).addClass(this.inputClass) .addEvents({focus:this.focus.bind(this),blur:this.blur.bind(this)}); this.label.addClass(this.labelClass); }, blur: function() { if (this.el.get('value') == '') { this.el.set('value',this.defaultText).addClass(this.inputClass); } }, focus: function() { if (this.el.get('value') == this.defaultText) { this.el.set('value','').removeClass(this.inputClass); } } }); var ExpandingTextarea = new Class({ initialize: function(el) { this.el = document.id(el); } }); var text = new TextAsLabelInput('text'); var source = new TextAsLabelInput('source'); var context = new TextAsLabelInput('context'); })();
Convert `Simple` to ES6 class
'use strict'; var fs = require('fs-extra'); var path = require('path'); class Simple { constructor(attrs) { this._internal = ''; this.outputFile = attrs.outputFile; this.baseDir = attrs.baseDir; this._sizes = {}; this.id = attrs.pluginId; } addFile(file) { var content = fs.readFileSync(path.join(this.baseDir, file), 'UTF-8'); this._internal += content; this._sizes[file] = content.length; } addSpace(space) { this._internal += space; } writeConcatStatsSync(outputPath, content) { fs.mkdirpSync(path.dirname(outputPath)); fs.writeFileSync(outputPath, JSON.stringify(content, null, 2)); } end(cb, thisArg) { var result; if (cb) { result = cb.call(thisArg, this); } if (process.env.CONCAT_STATS) { var outputPath = process.cwd() + '/concat-stats-for/' + this.id + '-' + path.basename(this.outputFile) + '.json'; this.writeConcatStatsSync( outputPath, { outputFile: this.outputFile, sizes: this._sizes } ); } fs.writeFileSync(this.outputFile, this._internal); return result; } } module.exports = Simple;
'use strict'; var fs = require('fs-extra'); var path = require('path'); module.exports = Simple; function Simple(attrs) { this._internal = ''; this.outputFile = attrs.outputFile; this.baseDir = attrs.baseDir; this._sizes = {}; this.id = attrs.pluginId; } Simple.prototype.addFile = function(file) { var content = fs.readFileSync(path.join(this.baseDir, file), 'UTF-8'); this._internal += content; this._sizes[file] = content.length; }; Simple.prototype.addSpace = function(space) { this._internal += space; }; Simple.prototype.writeConcatStatsSync = function(outputPath, content) { fs.mkdirpSync(path.dirname(outputPath)); fs.writeFileSync(outputPath, JSON.stringify(content, null, 2)); }; Simple.prototype.end = function(cb, thisArg) { var result; if (cb) { result = cb.call(thisArg, this); } if (process.env.CONCAT_STATS) { var outputPath = process.cwd() + '/concat-stats-for/' + this.id + '-' + path.basename(this.outputFile) + '.json'; this.writeConcatStatsSync( outputPath, { outputFile: this.outputFile, sizes: this._sizes } ); } fs.writeFileSync(this.outputFile, this._internal); return result; };
Add more info to TabDelegate example Provide details on how to limit a tab delegate to a specific resource handler.
from django.shortcuts import render from extensions.views import admin_extension, tab_extension, \ TabExtensionDelegate, dashboard_extension from resourcehandlers.models import ResourceHandler from utilities.logger import ThreadLogger logger = ThreadLogger(__name__) class ResourceHandlerTabDelegate(TabExtensionDelegate): # We want this tab to display for all resource handlers, so we return # True regardless of what Resource Handler is being displayed. # If the goal is to target a specific Resource # Handler, say AWSHandler, the body of this method would be: # return if isinstance(self.instance.cast(), AWSHandler) else False def should_display(self): return True @admin_extension( title="Playground Admin", description="Entrypoint for Playground Admin Extension") def show_admin_extension(request, **kwargs): return render(request, template_name='playground/templates/admin.html') @tab_extension( model=ResourceHandler, title="Playground", description="Entrypoint for Playground Resource Handler Tab Extension", delegate=ResourceHandlerTabDelegate ) def show_rh_tab_extension(request, model_id, **kwargs): return render(request, template_name='playground/templates/tab.html') @dashboard_extension( title="Playground", description='Playground widget') def show_playground_widget(request): return render(request, template_name='playground/templates/widget.html')
from django.shortcuts import render from extensions.views import admin_extension, tab_extension, \ TabExtensionDelegate, dashboard_extension from resourcehandlers.models import ResourceHandler from utilities.logger import ThreadLogger logger = ThreadLogger(__name__) class ResourceHandlerTabDelegate(TabExtensionDelegate): def should_display(self): return True @admin_extension( title="Playground Admin", description="Entrypoint for Playground Admin Extension") def show_admin_extension(request, **kwargs): return render(request, template_name='playground/templates/admin.html') # We want this tab to display for all resource handlers, so we set the model # to the ResourceHandler object. If we wanted to target a specific resource # handler, we could get more specific, e.g. AWSHandler @tab_extension( model=ResourceHandler, title="Playground", description="Entrypoint for Playground Resource Handler Tab Extension", delegate=ResourceHandlerTabDelegate ) def show_rh_tab_extension(request, model_id, **kwargs): return render(request, template_name='playground/templates/tab.html') @dashboard_extension( title="Playground", description='Playground widget') def show_playground_widget(request): return render(request, template_name='playground/templates/widget.html')
Increment djsonb version to fix empty-query bug
#!/usr/bin/env python from setuptools import setup, find_packages tests_require = [] setup( name='ashlar', version='0.0.2', description='Define and validate schemas for metadata for geotemporal event records', author='Azavea, Inc.', author_email='info@azavea.com', keywords='gis jsonschema', packages=find_packages(exclude=['tests']), dependency_links=[ 'https://github.com/azavea/djsonb/tarball/develop#egg=djsonb-0.1.7' ], install_requires=[ 'Django ==1.8.6', 'djangorestframework >=3.1.1', 'djangorestframework-gis >=0.8.1', 'django-filter >=0.9.2', 'djsonb >=0.1.7', 'jsonschema >=2.4.0', 'psycopg2 >=2.6', 'django-extensions >=1.6.1', 'python-dateutil >=2.4.2', 'PyYAML >=3.11', 'pytz >=2015.7', 'requests >=2.8.1' ], extras_require={ 'dev': [], 'test': tests_require }, test_suite='tests', tests_require=tests_require, )
#!/usr/bin/env python from setuptools import setup, find_packages tests_require = [] setup( name='ashlar', version='0.0.2', description='Define and validate schemas for metadata for geotemporal event records', author='Azavea, Inc.', author_email='info@azavea.com', keywords='gis jsonschema', packages=find_packages(exclude=['tests']), dependency_links=[ 'https://github.com/azavea/djsonb/tarball/develop#egg=djsonb-0.1.6' ], install_requires=[ 'Django ==1.8.6', 'djangorestframework >=3.1.1', 'djangorestframework-gis >=0.8.1', 'django-filter >=0.9.2', 'djsonb >=0.1.6', 'jsonschema >=2.4.0', 'psycopg2 >=2.6', 'django-extensions >=1.6.1', 'python-dateutil >=2.4.2', 'PyYAML >=3.11', 'pytz >=2015.7', 'requests >=2.8.1' ], extras_require={ 'dev': [], 'test': tests_require }, test_suite='tests', tests_require=tests_require, )
Fix `npm test` failing to run Trying to run `npm test` fails because the mocha path was set to the mocha shell script instead of the mocha init script (it tried to spawn node with a shell script). This commit fixes the issue and the tests run as expected.
/** * Module dependencies. */ var path = require('path'); var spawn = require('child_process').spawn; // node executable var node = process.execPath || process.argv[0]; var mocha = path.resolve(__dirname, '..', 'node_modules', 'mocha', 'bin', 'mocha'); var mochaOpts = [ '--reporter', 'spec' ]; run([ [ mocha, path.resolve(__dirname, 'cli.js') ] ]); function run (tests) { if (0 == tests.length) return; var argv = tests.shift(); if (argv.indexOf(mocha) != -1) { // running mocha, append "mochaOpts" argv.push.apply(argv, mochaOpts); } var opts = { customFds: [ 0, 1, 2 ], stdio: 'inherit' }; var child = spawn(node, argv, opts); child.on('exit', function (code) { if (0 == code) { run(tests); } else { process.exit(code); } }); }
/** * Module dependencies. */ var path = require('path'); var spawn = require('child_process').spawn; // node executable var node = process.execPath || process.argv[0]; var gnode = path.resolve(__dirname, '..', 'bin', 'gnode'); var mocha = path.resolve(__dirname, '..', 'node_modules', '.bin', 'mocha'); var mochaOpts = [ '--reporter', 'spec' ]; run([ [ mocha, path.resolve(__dirname, 'cli.js') ] ]); function run (tests) { if (0 == tests.length) return; var argv = tests.shift(); if (argv.indexOf(mocha) != -1) { // running mocha, append "mochaOpts" argv.push.apply(argv, mochaOpts); } var opts = { customFds: [ 0, 1, 2 ], stdio: 'inherit' }; var child = spawn(node, argv, opts); child.on('exit', function (code) { if (0 == code) { run(tests); } else { process.exit(code); } }); }
Make an use of the search term state
import {div, p, input, h1, h2, tr, td, tbody, thead, th, table, h4, h5} from '@cycle/dom' export function view(state$) { return state$.map((state) => { const list = state.characters.map( character => { return tr(td(character.name)); }); return div(".card", [ div('.card-header', [ h4('.title', 'Star Wars Character Search'), input('#search.form-control', {props: {type: "text", placeholder: "Type to search", value: state.searchTerm}}) ]), div('.card-content .table-responsive',[ table('.table', [ thead(tr(th(h5('Name')))), tbody(list) ]) ]) ]); }); }
import {div, p, input, h1, h2, tr, td, tbody, thead, th, table, h4, h5} from '@cycle/dom' export function view(state$) { return state$.map((state) => { const list = state.characters.map( character => { return tr(td(character.name)); }); return div(".card", [ div('.card-header', [ h4('.title', 'Star Wars Character Search'), input('#search.form-control', {props: {type: "text", placeholder: "Type to search"}}) ]), div('.card-content .table-responsive',[ table('.table', [ thead(tr(th(h5('Name')))), tbody(list) ]) ]) ]); }); }
Add autohide to cols-config messages
/** * @module ember-flexberry */ import Ember from 'ember'; import ColsconfigDialogController from '../mixins/colsconfig-dialog-controller'; import { translationMacro as t } from 'ember-i18n'; export default Ember.Controller.extend(ColsconfigDialogController, { /** * Current opened modal window. * * @property _openedModalDialog * @type JQuery * @default undefined */ _openedModalDialog: undefined, title: t('components.colsconfig-dialog-content.title'), actions: { /** * Handles create modal window action. * It saves created window to have opportunity to close it later. * * @method createdModalDialog * @param {JQuery} modalDialog Created modal window. */ createdModalDialog: function(modalDialog) { this.set('message.visible', false); this.set('_openedModalDialog', modalDialog); } }, /** * Close current modal window if it exists. * * @method closeModalDialog */ closeModalDialog: function () { let openedDialog = this.get('_openedModalDialog'); if (openedDialog) { openedDialog.modal('hide'); this.set('_openedModalDialog', undefined); } }, clear: function() { this.set('_openedModalDialog', undefined); return this; } });
/** * @module ember-flexberry */ import Ember from 'ember'; import ColsconfigDialogController from '../mixins/colsconfig-dialog-controller'; import { translationMacro as t } from 'ember-i18n'; export default Ember.Controller.extend(ColsconfigDialogController, { /** * Current opened modal window. * * @property _openedModalDialog * @type JQuery * @default undefined */ _openedModalDialog: undefined, title: t('components.colsconfig-dialog-content.title'), actions: { /** * Handles create modal window action. * It saves created window to have opportunity to close it later. * * @method createdModalDialog * @param {JQuery} modalDialog Created modal window. */ createdModalDialog: function(modalDialog) { this.set('_openedModalDialog', modalDialog); } }, /** * Close current modal window if it exists. * * @method closeModalDialog */ closeModalDialog: function () { let openedDialog = this.get('_openedModalDialog'); if (openedDialog) { openedDialog.modal('hide'); this.set('_openedModalDialog', undefined); } }, clear: function() { this.set('_openedModalDialog', undefined); return this; } });
Add SSLify to force SSL
import logging from flask import Flask from flask_cache import Cache from flask_login import LoginManager from flask_sslify import SSLify # Set up logging log = logging.getLogger('slot') log.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) log.addHandler(ch) app = Flask(__name__) app.config.from_object('config') sslify = SSLify(app, age=300) cache = Cache(app, config={'CACHE_TYPE': 'redis'}) with app.app_context(): cache.clear() from slot.users.views import users_blueprint from routes import dashboard, render_new_procedure_form, receive_sms, complete_procedure import slot.users.controller as user_controller import db_fieldbook as db app.register_blueprint(users_blueprint) login_manager = LoginManager() login_manager.init_app(app) login_manager.session_protection = "strong" login_manager.login_view = "users.login" @login_manager.user_loader def load_user(user_id): print("Loading user {0}".format(user_id)) result = user_controller.return_user_instance_or_anonymous(db.get_user(user_id)) return result
import logging from flask import Flask from flask_cache import Cache from flask_login import LoginManager # Set up logging log = logging.getLogger('slot') log.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) log.addHandler(ch) app = Flask(__name__) app.config.from_object('config') cache = Cache(app, config={'CACHE_TYPE': 'redis'}) with app.app_context(): cache.clear() from slot.users.views import users_blueprint from routes import dashboard, render_new_procedure_form, receive_sms, complete_procedure import slot.users.controller as user_controller import db_fieldbook as db app.register_blueprint(users_blueprint) login_manager = LoginManager() login_manager.init_app(app) login_manager.session_protection = "strong" login_manager.login_view = "users.login" @login_manager.user_loader def load_user(user_id): print("Loading user {0}".format(user_id)) result = user_controller.return_user_instance_or_anonymous(db.get_user(user_id)) return result
Move license to the top of the file.
/*! * Bootstrap Grunt task for generating raw-files.min.js for the Customizer * http://getbootstrap.com * Copyright 2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ /* global btoa: true */ 'use strict'; var fs = require('fs'); var btoa = require('btoa'); var grunt = require('grunt'); function getFiles(type) { var files = {}; fs.readdirSync(type) .filter(function (path) { return type === 'fonts' ? true : new RegExp('\\.' + type + '$').test(path); }) .forEach(function (path) { var fullPath = type + '/' + path; files[path] = (type === 'fonts' ? btoa(fs.readFileSync(fullPath)) : fs.readFileSync(fullPath, 'utf8')); }); return 'var __' + type + ' = ' + JSON.stringify(files) + '\n'; } module.exports = function generateRawFilesJs(banner) { if (!banner) { banner = ''; } var files = banner + getFiles('js') + getFiles('less') + getFiles('fonts'); var rawFilesJs = 'docs/assets/js/raw-files.min.js'; try { fs.writeFileSync(rawFilesJs, files); } catch (err) { grunt.fail.warn(err); } grunt.log.writeln('File ' + rawFilesJs.cyan + ' created.'); };
/* global btoa: true */ /*! * Bootstrap Grunt task for generating raw-files.min.js for the Customizer * http://getbootstrap.com * Copyright 2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ 'use strict'; var fs = require('fs'); var btoa = require('btoa'); var grunt = require('grunt'); function getFiles(type) { var files = {}; fs.readdirSync(type) .filter(function (path) { return type === 'fonts' ? true : new RegExp('\\.' + type + '$').test(path); }) .forEach(function (path) { var fullPath = type + '/' + path; files[path] = (type === 'fonts' ? btoa(fs.readFileSync(fullPath)) : fs.readFileSync(fullPath, 'utf8')); }); return 'var __' + type + ' = ' + JSON.stringify(files) + '\n'; } module.exports = function generateRawFilesJs(banner) { if (!banner) { banner = ''; } var files = banner + getFiles('js') + getFiles('less') + getFiles('fonts'); var rawFilesJs = 'docs/assets/js/raw-files.min.js'; try { fs.writeFileSync(rawFilesJs, files); } catch (err) { grunt.fail.warn(err); } grunt.log.writeln('File ' + rawFilesJs.cyan + ' created.'); };
:+1: Check using inexactly object type.
const package = require('./package.json') module.exports = { parser: 'babel-eslint', env: { browser: true, commonjs: true, es6: true, jest: true, node: true }, extends: [ 'eslint:recommended', 'plugin:import/errors', 'plugin:react/recommended', 'plugin:flowtype/recommended', // suppress conflicted rules 'plugin:prettier/recommended', 'prettier/flowtype', 'prettier/react' ], parserOptions: { ecmaFeatures: { experimentalObjectRestSpread: true, jsx: true }, sourceType: 'module' }, plugins: ['filenames'], settings: { react: { version: package.dependencies.react } }, rules: { 'no-console': 'warn', 'filenames/match-exported': 'error', 'flowtype/require-valid-file-annotation': ['warn', 'always'], 'flowtype/require-exact-type': 'error', 'react/no-deprecated': 'warn', 'react/prefer-stateless-function': 'error' } }
const package = require('./package.json') module.exports = { parser: 'babel-eslint', env: { browser: true, commonjs: true, es6: true, jest: true, node: true }, extends: [ 'eslint:recommended', 'plugin:import/errors', 'plugin:react/recommended', 'plugin:flowtype/recommended', // suppress conflicted rules 'plugin:prettier/recommended', 'prettier/flowtype', 'prettier/react' ], parserOptions: { ecmaFeatures: { experimentalObjectRestSpread: true, jsx: true }, sourceType: 'module' }, plugins: ['filenames'], settings: { react: { version: package.dependencies.react } }, rules: { 'no-console': 'warn', 'filenames/match-exported': 'error', 'flowtype/require-valid-file-annotation': ['warn', 'always'], 'react/no-deprecated': 'warn', 'react/prefer-stateless-function': 'error' } }
Fix file upload csrf error
var addUrlParam = function (url, key, val) { var newParam = encodeURIComponent(key) + '=' + encodeURIComponent(val); url = url.split('#')[0]; if (url.indexOf('?') === -1) url += '?' + newParam; else url += '&' + newParam; return url; }; $(function () { $('a[href-post]').click(function (e) { e.preventDefault(); var form = document.createElement('form'); form.style.display = 'none'; form.method = 'post'; form.action = $(this).attr('href-post'); form.target = '_self'; var input = document.createElement('input'); input.type = 'hidden'; input.name = '_csrf'; input.value = document.head.getAttribute('data-csrf-token'); form.appendChild(input); document.body.appendChild(form); form.submit(); }); $('form').each(function () { this.action = addUrlParam(this.action || location.href, '_csrf', document.head.getAttribute('data-csrf-token')); }); });
$(function () { $('a[href-post]').click(function (e) { e.preventDefault(); var form = document.createElement('form'); form.style.display = 'none'; form.method = 'post'; form.action = $(this).attr('href-post'); form.target = '_self'; var input = document.createElement('input'); input.type = 'hidden'; input.name = '_csrf'; input.value = document.head.getAttribute('data-csrf-token'); form.appendChild(input); document.body.appendChild(form); form.submit(); }); $('form').each(function () { var input = document.createElement('input'); input.type = 'hidden'; input.name = '_csrf'; input.value = document.head.getAttribute('data-csrf-token'); this.appendChild(input); }); });
Clear the overriden permissions if the role is changed
define(function (require) { // Dependencies var $ = require('jquery') , _ = require('lodash') , Backbone = require('backbone') ; /** * Setup view */ var View = {}; View.initialize = function() { _.bindAll(this); // Cache this.$role = $('[name="role"]'); this.$customize = this.$('[name="_custom_permissions"]'); this.$permissions = this.$('.permissions-list'); this.$permissions_inner = this.$('.permissions-list-inner'); this.$controllers = this.$permissions.find('.controller'); // Listen for clicks on the override checkbox this.$customize.on('change', this.togglePermissionsOptions); // Check for the role to change and clear the custom permissions this.$role.on('change', this.clearCustomPermissions); }; /** * Toggle the permissions options */ View.togglePermissionsOptions = function() { // Inspect the clicked box var show = this.$customize.is(':checked'); // Manually set the height whenever it's moving and then clear it when // animation is done. The animation is defined in CSS. this.$permissions.height(this.$permissions_inner.outerHeight()); _.delay(_.bind(function() { this.$permissions.height(''); }, this), 300); // Toggle the open state of the permissions _.defer(_.bind(function() { this.$el.toggleClass('closed', !show); }, this)); }; /** * Clear permissions customizations */ View.clearCustomPermissions = function() { this.$customize.attr('checked', false).trigger('change'); }; // Return view class return Backbone.View.extend(View); });
define(function (require) { // Dependencies var $ = require('jquery') , _ = require('lodash') , Backbone = require('backbone') ; /** * Setup view */ var View = {}; View.initialize = function() { _.bindAll(this); // Cache this.$customize = this.$('[name="_custom_permissions"]'); this.$permissions = this.$('.permissions-list'); this.$permissions_inner = this.$('.permissions-list-inner'); this.$controllers = this.$permissions.find('.controller'); // Listen for clicks on the override checkbox this.$customize.on('change', this.togglePermissionsOptions); }; /** * Toggle the permissions options */ View.togglePermissionsOptions = function() { // Inspect the clicked box var show = this.$customize.is(':checked'); // Manually set the height whenever it's moving and then clear it when // animation is done. The animation is defined in CSS. this.$permissions.height(this.$permissions_inner.outerHeight()); _.delay(_.bind(function() { this.$permissions.height(''); }, this), 300); // Toggle the open state of the permissions _.defer(_.bind(function() { this.$el.toggleClass('closed', !show); }, this)); }; // Return view class return Backbone.View.extend(View); });
Fix Handlebars helper pathFor and urlFor params bug. You can optionally pass a parameters object as the first parameter. By default these helpers will use the current data context for the parameters object.
if (Handlebars) { Handlebars.registerHelper('pathFor', function (routeName, params, options) { if (arguments.length == 2) { options = params; params = this; } var hash = options.hash.hash; var query = _.omit(options.hash, 'hash'); return Router.path(routeName, params, { query: query, hash: hash }); }); Handlebars.registerHelper('urlFor', function (routeName, params, options) { if (arguments.length == 2) { options = params; params = this; } var hash = options.hash.hash; var query = _.omit(options.hash, 'hash'); return Router.url(routeName, params, { query: query, hash: hash }); }); Handlebars.registerHelper('renderRouter', function (options) { return new Handlebars.SafeString(Router.render()); }); Handlebars.registerHelper('currentRouteController', function () { return Router.current(); }); }
if (Handlebars) { Handlebars.registerHelper('pathFor', function (routeName, context, options) { if (arguments.length == 2) { options = context; context = this; } var params = this; var hash = options.hash.hash; var query = _.omit(options.hash, 'hash'); return Router.path(routeName, params, { query: query, hash: hash }); }); Handlebars.registerHelper('urlFor', function (routeName, context, options) { if (arguments.length == 2) { options = context; context = this; } var params = this; var hash = options.hash.hash; var query = _.omit(options.hash, 'hash'); return Router.url(routeName, params, { query: query, hash: hash }); }); Handlebars.registerHelper('renderRouter', function (options) { return new Handlebars.SafeString(Router.render()); }); Handlebars.registerHelper('currentRouteController', function () { return Router.current(); }); }
Move the APP_VERSION into app instead of config. It felt kinda silly to have to remember to update a config var before pushing up a deploy. This allows us to just modify it in the js and have it purge from one spot. Also allows us the ability to have more logic around what gets purged if we want to be more specific about it in the future, but it purges all for now. this probably won’t need to be updated as much now that we aren’t persisting much data. Would only need to update if we changed the format of authentication, editor, gui, json(deleted arrays for posts/comments/users), or an update to the profile json. Once this gets merged in we can remove the config var APP_VERSION from heroku.
import './main.sass' import 'babel-polyfill' import 'isomorphic-fetch' import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { Router } from 'react-router' import { updateStrings as updateTimeAgoStrings } from './vendor/time_ago_in_words' import { persistStore } from 'redux-persist' import localforage from 'localforage' import store from './store' import { browserHistory } from 'react-router' import routes from './routes' import './vendor/embetter' import './vendor/embetter_initializer' updateTimeAgoStrings({ about: '' }) const APP_VERSION = '1.0.5' const element = ( <Provider store={store}> <Router history={browserHistory} routes={routes} /> </Provider> ) const storage = localforage.createInstance({ name: 'ello-webapp' }) const whitelist = ['authentication', 'editor', 'gui', 'json', 'profile'] const persistor = persistStore(store, { storage, whitelist }, () => { ReactDOM.render(element, document.getElementById('root')) }) // check and update current version and // only kill off the persisted reducers storage.getItem('APP_VERSION') .then((curVersion) => { if (curVersion && curVersion !== APP_VERSION) { persistor.purgeAll() } storage.setItem('APP_VERSION', APP_VERSION) })
import './main.sass' import 'babel-polyfill' import 'isomorphic-fetch' import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { Router } from 'react-router' import { updateStrings as updateTimeAgoStrings } from './vendor/time_ago_in_words' import { persistStore } from 'redux-persist' import localforage from 'localforage' import store from './store' import { browserHistory } from 'react-router' import routes from './routes' import './vendor/embetter' import './vendor/embetter_initializer' updateTimeAgoStrings({ about: '' }) const element = ( <Provider store={store}> <Router history={browserHistory} routes={routes} /> </Provider> ) const storage = localforage.createInstance({ name: 'ello-webapp' }) const whitelist = ['authentication', 'editor', 'gui', 'json', 'profile'] const persistor = persistStore(store, { storage, whitelist }, () => { ReactDOM.render(element, document.getElementById('root')) }) // check and update current version and // only kill off the persisted reducers if (ENV.APP_VERSION) { storage.getItem('APP_VERSION') .then((curVersion) => { if (curVersion && curVersion !== ENV.APP_VERSION) { persistor.purge(['json', 'profile']) } storage.setItem('APP_VERSION', ENV.APP_VERSION) }) }
Change the sort order on prizes won
from django.http import HttpResponse, HttpResponseRedirect from django.http import Http404 from django.template import loader from django.shortcuts import render from django.db.models import Count, Sum from django.views.decorators.csrf import csrf_protect from django.core import serializers from .models import Drawing, PrizesWon, GroupTicket def index(request): allDrawings = Drawing.objects.order_by('-drawingDate')[:50] allPrizes = PrizesWon.objects.order_by('drawing_id') activeTickets = GroupTicket.objects.order_by('-numbers') toBePaid = PrizesWon.objects.aggregate(Sum('groupPrizeAmount')) paidOut = 0 all_objects = list(PrizesWon.objects.all()) context = {'allDrawings': allDrawings, 'allPrizes': allPrizes, 'toBePaid':toBePaid, 'activeTickets':activeTickets,'paidOut':paidOut} return render(request, 'results/index.html', context) @csrf_protect def matchingTickets(request,drawingid,ticketid): a = Drawing.objects.get(pk=drawingid) b = GroupTicket.objects.get(pk=ticketid) return HttpResponse(str(a)+str(b)) @csrf_protect def results(request,drawingid): a = Drawing.objects.get(pk=drawingid) return HttpResponse(str(a))
from django.http import HttpResponse, HttpResponseRedirect from django.http import Http404 from django.template import loader from django.shortcuts import render from django.db.models import Count, Sum from django.views.decorators.csrf import csrf_protect from django.core import serializers from .models import Drawing, PrizesWon, GroupTicket def index(request): allDrawings = Drawing.objects.order_by('-drawingDate')[:50] allPrizes = PrizesWon.objects.order_by('-drawing') activeTickets = GroupTicket.objects.order_by('-numbers') toBePaid = PrizesWon.objects.aggregate(Sum('groupPrizeAmount')) paidOut = 0 all_objects = list(PrizesWon.objects.all()) context = {'allDrawings': allDrawings, 'allPrizes': allPrizes, 'toBePaid':toBePaid, 'activeTickets':activeTickets,'paidOut':paidOut} return render(request, 'results/index.html', context) @csrf_protect def matchingTickets(request,drawingid,ticketid): a = Drawing.objects.get(pk=drawingid) b = GroupTicket.objects.get(pk=ticketid) return HttpResponse(str(a)+str(b)) @csrf_protect def results(request,drawingid): a = Drawing.objects.get(pk=drawingid) return HttpResponse(str(a))
Add TreeWidget to the concatenated JavaScript output.
//= require_directory ./AbstractDocument //= require_directory ./BrowserWidget //= require_directory ./ComponentStateManager //= require_directory ./Desktop //= require_directory ./DiagramWidget //= require_directory ./DocumentEditor //= require_directory ./EventWidget //= require_directory ./FundamentalTypes //= require_directory ./HierarchicalMenuWidget //= require_directory ./HtmlDocument //= require_directory ./Internationalization //= require_directory ./jStorage //= require_directory ./LanguageSelectorWidget //= require_directory ./NewsReaderWidget //= require_directory ./PhotoGaleryWidget //= require_directory ./ResourceManager //= require_directory ./ScrollingBehaviour //= require_directory ./Singleton //= require_directory ./SkinSelectorWidget //= require_directory ./SmartDocument //= require_directory ./SplashForm //= require_directory ./TabWidget //= require_directory ./TextAreaEditor //= require_directory ./ToolBarWidget //= require_directory ./TreeWidget //= require_directory ./VideoPlayerWidget //= require_directory ./WebUIConfiguration //= require_directory ./WebUIController //= require_directory ./WebUILogger //= require_directory ./WebUIMessageBus
//= require_directory ./AbstractDocument //= require_directory ./BrowserWidget //= require_directory ./ComponentStateManager //= require_directory ./Desktop //= require_directory ./DiagramWidget //= require_directory ./DocumentEditor //= require_directory ./EventWidget //= require_directory ./FundamentalTypes //= require_directory ./HierarchicalMenuWidget //= require_directory ./HtmlDocument //= require_directory ./Internationalization //= require_directory ./jStorage //= require_directory ./LanguageSelectorWidget //= require_directory ./NewsReaderWidget //= require_directory ./PhotoGaleryWidget //= require_directory ./ResourceManager //= require_directory ./ScrollingBehaviour //= require_directory ./Singleton //= require_directory ./SkinSelectorWidget //= require_directory ./SmartDocument //= require_directory ./SplashForm //= require_directory ./TabWidget //= require_directory ./TextAreaEditor //= require_directory ./ToolBarWidget //= require_directory ./VideoPlayerWidget //= require_directory ./WebUIConfiguration //= require_directory ./WebUIController //= require_directory ./WebUILogger //= require_directory ./WebUIMessageBus
Add help description for annotator.
import sys import argparse import pandas as pd from pyim.tools.annotate.rbm import RbmAnnotator ANNOTATORS = { 'rbm': RbmAnnotator } def main(): # Setup main argument parser and annotator specific sub-parsers. parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help='Annotator to use.') for name, class_ in ANNOTATORS.items(): class_.register_parser(subparsers, name) args = parser.parse_args() if 'annotator' not in args: parser.print_help() sys.exit(2) else: # Extract input/output parameters. options = vars(args) input_path = options.pop('input') output_path = options.pop('output') # Construct annotator. class_ = options.pop('annotator') annotator = class_(**options) # Load input file. frame = pd.read_csv(input_path, sep='\t', dtype={'seqname': str, 'location': int, 'strand': int}) # Do annotation and write outputs! result = annotator.annotate(frame) result.to_csv(output_path, sep='\t', index=False) if __name__ == '__main__': main()
import sys import argparse import pandas as pd from pyim.tools.annotate.rbm import RbmAnnotator ANNOTATORS = { 'rbm': RbmAnnotator } def main(): # Setup main argument parser and annotator specific sub-parsers. parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help='sub-command help') for name, class_ in ANNOTATORS.items(): class_.register_parser(subparsers, name) args = parser.parse_args() if 'annotator' not in args: parser.print_help() sys.exit(2) else: # Extract input/output parameters. options = vars(args) input_path = options.pop('input') output_path = options.pop('output') # Construct annotator. class_ = options.pop('annotator') annotator = class_(**options) # Load input file. frame = pd.read_csv(input_path, sep='\t', dtype={'seqname': str, 'location': int, 'strand': int}) # Do annotation and write outputs! result = annotator.annotate(frame) result.to_csv(output_path, sep='\t', index=False) if __name__ == '__main__': main()
Return correct message if elasticsearch fails to connect.
from flask import jsonify, current_app from . import status from . import utils from ..main.services.search_service import status_for_all_indexes @status.route('/_status') def status(): db_status = status_for_all_indexes() if db_status['status_code'] == 200: return jsonify( status="ok", version=utils.get_version_label(), db_status=db_status ) current_app.logger.exception("Error connecting to elasticsearch") return jsonify( status="error", version=utils.get_version_label(), message="Error connecting to elasticsearch", db_status={ 'status_code': 500, 'message': db_status['message'][0] } ), 500
from flask import jsonify, current_app from . import status from . import utils from ..main.services.search_service import status_for_all_indexes @status.route('/_status') def status(): db_status = status_for_all_indexes() if db_status['status_code'] == 200: return jsonify( status="ok", version=utils.get_version_label(), db_status=db_status ) current_app.logger.exception("Error connecting to elasticsearch") return jsonify( status="error", version=utils.get_version_label(), message="Error connecting to elasticsearch", db_status=db_status ), 500
Use the correct setting keys
<?php /* * This file is part of Flarum. * * For detailed copyright and license information, please view the * LICENSE file that was distributed with this source code. */ namespace Flarum\Tags\Access; use Flarum\Settings\SettingsRepositoryInterface; use Flarum\Tags\Tag; use Flarum\User\Access\AbstractPolicy; use Flarum\User\User; class GlobalPolicy extends AbstractPolicy { /** * @var SettingsRepositoryInterface */ protected $settings; public function __construct(SettingsRepositoryInterface $settings) { $this->settings = $settings; } /** * @param Flarum\User\User $actor * @param string $ability * @return bool|void */ public function can(User $actor, string $ability) { if (in_array($ability, ['viewDiscussions', 'startDiscussion'])) { $enoughPrimary = count(Tag::getIdsWhereCan($actor, $ability, true, false)) >= $this->settings->get('flarum-tags.min_primary_tags'); $enoughSecondary = count(Tag::getIdsWhereCan($actor, $ability, false, true)) >= $this->settings->get('flarum-tags.min_secondary_tags'); if ($enoughPrimary && $enoughSecondary) { return $this->allow(); } else { return $this->deny(); } } } }
<?php /* * This file is part of Flarum. * * For detailed copyright and license information, please view the * LICENSE file that was distributed with this source code. */ namespace Flarum\Tags\Access; use Flarum\Settings\SettingsRepositoryInterface; use Flarum\Tags\Tag; use Flarum\User\Access\AbstractPolicy; use Flarum\User\User; class GlobalPolicy extends AbstractPolicy { /** * @var SettingsRepositoryInterface */ protected $settings; public function __construct(SettingsRepositoryInterface $settings) { $this->settings = $settings; } /** * @param Flarum\User\User $actor * @param string $ability * @return bool|void */ public function can(User $actor, string $ability) { if (in_array($ability, ['viewDiscussions', 'startDiscussion'])) { $enoughPrimary = count(Tag::getIdsWhereCan($actor, $ability, true, false)) >= $this->settings->get('min_primary_tags'); $enoughSecondary = count(Tag::getIdsWhereCan($actor, $ability, false, true)) >= $this->settings->get('min_secondary_tags'); if ($enoughPrimary && $enoughSecondary) { return $this->allow(); } else { return $this->deny(); } } } }
Fix crash when receiving reportLocation command before service is bound
package org.owntracks.android.support; import org.owntracks.android.injection.scopes.PerApplication; import java.lang.ref.WeakReference; import javax.inject.Inject; import androidx.annotation.NonNull; @PerApplication public class ServiceBridge { private WeakReference<ServiceBridgeInterface> serviceWeakReference = new WeakReference<ServiceBridgeInterface>(null); public interface ServiceBridgeInterface { void requestOnDemandLocationUpdate(); } @Inject ServiceBridge() { } public void bind(@NonNull ServiceBridgeInterface service) { this.serviceWeakReference = new WeakReference<ServiceBridgeInterface>(service); } public void requestOnDemandLocationFix() { ServiceBridgeInterface service = serviceWeakReference.get(); if(service != null) { service.requestOnDemandLocationUpdate(); } } }
package org.owntracks.android.support; import org.owntracks.android.injection.scopes.PerApplication; import org.owntracks.android.services.BackgroundService; import java.lang.ref.WeakReference; import javax.inject.Inject; import androidx.annotation.NonNull; @PerApplication public class ServiceBridge { private WeakReference<ServiceBridgeInterface> serviceWeakReference; public interface ServiceBridgeInterface { void requestOnDemandLocationUpdate(); } @Inject ServiceBridge() { } public void bind(@NonNull ServiceBridgeInterface service) { this.serviceWeakReference = new WeakReference<ServiceBridgeInterface>(service); } public void requestOnDemandLocationFix() { ServiceBridgeInterface service = serviceWeakReference.get(); if(service != null) { service.requestOnDemandLocationUpdate(); } } }
Add basic REST API support
from flask import render_template, request, send_from_directory import saliweb.frontend from saliweb.frontend import get_completed_job, Parameter, FileParameter from . import submit parameters=[Parameter("name", "Job name", optional=True), FileParameter("pdb", "PDB file to be refined"), Parameter("modkey", "MODELLER license key"), Parameter("loops", "Loops to be refined")] app = saliweb.frontend.make_application(__name__, "##CONFIG##", parameters) @app.route('/') def index(): return render_template('index.html') @app.route('/contact') def contact(): return render_template('contact.html') @app.route('/help') def help(): return render_template('help.html') @app.route('/download') def download(): return render_template('download.html') @app.route('/job', methods=['GET', 'POST']) def job(): if request.method == 'GET': return saliweb.frontend.render_queue_page() else: return submit.handle_new_job() @app.route('/job/<name>') def results(name): job = get_completed_job(name, request.args.get('passwd')) return saliweb.frontend.render_results_template('results.html', job=job) @app.route('/job/<name>/<path:fp>') def results_file(name, fp): job = get_completed_job(name, request.args.get('passwd')) return send_from_directory(job.directory, fp)
from flask import render_template, request, send_from_directory import saliweb.frontend from saliweb.frontend import get_completed_job from . import submit app = saliweb.frontend.make_application(__name__, "##CONFIG##") @app.route('/') def index(): return render_template('index.html') @app.route('/contact') def contact(): return render_template('contact.html') @app.route('/help') def help(): return render_template('help.html') @app.route('/download') def download(): return render_template('download.html') @app.route('/job', methods=['GET', 'POST']) def job(): if request.method == 'GET': return saliweb.frontend.render_queue_page() else: return submit.handle_new_job() @app.route('/job/<name>') def results(name): job = get_completed_job(name, request.args.get('passwd')) return render_template('results.html', job=job) @app.route('/job/<name>/<path:fp>') def results_file(name, fp): job = get_completed_job(name, request.args.get('passwd')) return send_from_directory(job.directory, fp)
Fix test for "pio test"
# Copyright 2014-present PlatformIO <contact@platformio.org> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from os.path import join import pytest from platformio import util def test_local_env(): result = util.exec_command(["platformio", "test", "-d", join("examples", "unit-testing", "calculator"), "-e", "local"]) if result['returncode'] != 0: pytest.fail(result) assert all( [s in result['out'] for s in ("[PASSED]", "[IGNORED]", "[FAILED]")])
# Copyright 2014-present PlatformIO <contact@platformio.org> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from os.path import join from platformio.commands.test import cli as cli_test def test_local_env(clirunner, validate_cliresult): result = clirunner.invoke( cli_test, ["-d", join("examples", "unit-testing", "calculator"), "-e", "local"]) validate_cliresult(result) assert all( [s in result.output for s in ("[PASSED]", "[IGNORED]", "[FAILED]")])
Put the user agent in the device object
from flask import request from flask import url_for from flask import abort from siege.service import app, db from siege.models import Device from view_utils import jsonate @app.route('/devices') def devices_index(): response = jsonate([d.to_dict() for d in Device.query.all()]) return response @app.route('/devices/<device_id>') def devices_get(device_id): device = Device.query.get(device_id) if not device: abort(404, 'Device not found') response = jsonate(device.to_dict()) return response @app.route('/devices', methods=['POST']) def devices_create(): comment = '%s, %s' % (request.remote_addr, request.user_agent) new_device = Device(comment=comment) db.session.add(new_device) db.session.commit() response = jsonate(new_device.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('devices_get', device_id=new_device.id) return response
from flask import request from flask import url_for from flask import abort from siege.service import app, db from siege.models import Device from view_utils import jsonate @app.route('/devices') def devices_index(): response = jsonate([d.to_dict() for d in Device.query.all()]) return response @app.route('/devices/<device_id>') def devices_get(device_id): device = Device.query.get(device_id) if not device: abort(404, 'Device not found') response = jsonate(device.to_dict()) return response @app.route('/devices', methods=['POST']) def devices_create(): new_device = Device(comment=request.access_route) db.session.add(new_device) db.session.commit() response = jsonate(new_device.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('devices_get', device_id=new_device.id) return response
Set HTTP transaction type during construction
'use strict' var shimmer = require('shimmer') var asyncState = require('../../async-state') var SERVER_FNS = ['on', 'addListener'] module.exports = function (http, client) { client.logger.trace('shimming http.Server.prototype functions:', SERVER_FNS) shimmer.massWrap(http.Server.prototype, SERVER_FNS, function (orig, name) { return function (event, listener) { if (event === 'request' && typeof listener === 'function') return orig.call(this, event, onRequest) else return orig.apply(this, arguments) function onRequest (req, res) { client.logger.trace('intercepted call to http.Server.prototype.%s', name) var trans = client.startTransaction(req.method + ' ' + req.url, 'web.http') asyncState.req = req asyncState.trans = req.__opbeat_trans = trans res.once('finish', function () { trans.result = res.statusCode client.logger.trace('[%s] ending transaction', trans._uuid) trans.end() }) listener.apply(this, arguments) } } }) return http }
'use strict' var shimmer = require('shimmer') var asyncState = require('../../async-state') var SERVER_FNS = ['on', 'addListener'] module.exports = function (http, client) { client.logger.trace('shimming http.Server.prototype functions:', SERVER_FNS) shimmer.massWrap(http.Server.prototype, SERVER_FNS, function (orig, name) { return function (event, listener) { if (event === 'request' && typeof listener === 'function') return orig.call(this, event, onRequest) else return orig.apply(this, arguments) function onRequest (req, res) { client.logger.trace('intercepted call to http.Server.prototype.%s', name) var trans = client.startTransaction(req.method + ' ' + req.url) trans.type = 'web.http' asyncState.req = req asyncState.trans = req.__opbeat_trans = trans res.once('finish', function () { trans.result = res.statusCode client.logger.trace('[%s] ending transaction', trans._uuid) trans.end() }) listener.apply(this, arguments) } } }) return http }
Rename example so it gets picked up by godoc.org
package epub_test import ( "fmt" "log" "github.com/bmaupin/go-epub" ) func ExampleEpub_AddImage() { // Create a new EPUB e := epub.NewEpub("My title") // Add an image from a local file img1Path, err := e.AddImage("testdata/gophercolor16x16.png", "go-gopher.png") if err != nil { log.Fatal(err) } // Add an image from a URL. The image filename is also optional img2Path, err := e.AddImage("https://golang.org/doc/gopher/gophercolor16x16.png", "") if err != nil { log.Fatal(err) } fmt.Println(img1Path) fmt.Println(img2Path) // Output: // ../img/go-gopher.png // ../img/image0002.png }
package epub_test import ( "fmt" "log" "github.com/bmaupin/go-epub" ) func ExampleAddImage() { // Create a new EPUB e := epub.NewEpub("My title") // Add an image from a local file img1Path, err := e.AddImage("testdata/gophercolor16x16.png", "go-gopher.png") if err != nil { log.Fatal(err) } // Add an image from a URL. The image filename is also optional img2Path, err := e.AddImage("https://golang.org/doc/gopher/gophercolor16x16.png", "") if err != nil { log.Fatal(err) } fmt.Println(img1Path) fmt.Println(img2Path) // Output: // ../img/go-gopher.png // ../img/image0002.png }
Insert custom commands through the getCommands() function.
<?php /** * @version $Id: file.php 1829 2011-06-21 01:59:15Z johanjanssens $ * @category Nooku * @package Nooku_Server * @subpackage Files * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * File Controller Class * * @author Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya> * @category Nooku * @package Nooku_Server * @subpackage Files */ class ComFilesControllerToolbarFiles extends ComDefaultControllerToolbarDefault { public function getCommands() { $this->reset() ->addDelete(); return parent::getCommands(); } protected function _commandDelete(KControllerToolbarCommand $command) { $command->append(array( 'attribs' => array( 'href' => '#' ) )); } }
<?php /** * @version $Id: file.php 1829 2011-06-21 01:59:15Z johanjanssens $ * @category Nooku * @package Nooku_Server * @subpackage Files * @copyright Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net). * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * File Controller Class * * @author Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya> * @category Nooku * @package Nooku_Server * @subpackage Files */ class ComFilesControllerToolbarFiles extends ComDefaultControllerToolbarDefault { public function getCommands() { $this->addDelete(); return parent::getCommands(); } protected function _commandDelete(KControllerToolbarCommand $command) { $command->append(array( 'attribs' => array( 'href' => '#' ) )); } }
Print installed packages in pytest
import os import subprocess import sys from chainer import testing from chainer.testing import parameterized _pairwise_parameterize = ( os.environ.get('CHAINER_TEST_PAIRWISE_PARAMETERIZATION', 'never')) assert _pairwise_parameterize in ('never', 'always') def _is_pip_installed(): try: import pip # NOQA return True except ImportError: return False def _is_in_ci(): ci_name = os.environ.get('CHAINER_CI', '') return ci_name != '' def pytest_configure(config): # Print installed packages if _is_in_ci() and _is_pip_installed(): print("***** Installed packages *****", flush=True) subprocess.check_call([sys.executable, '-m', 'pip', 'freeze', '--all']) def pytest_collection(session): # Perform pairwise testing. # TODO(kataoka): This is a tentative fix. Discuss its public interface. if _pairwise_parameterize == 'always': pairwise_product_dict = parameterized._pairwise_product_dict testing.product_dict = pairwise_product_dict parameterized.product_dict = pairwise_product_dict def pytest_collection_finish(session): if _pairwise_parameterize == 'always': product_dict = parameterized._product_dict_orig testing.product_dict = product_dict parameterized.product_dict = product_dict
import os from chainer import testing from chainer.testing import parameterized _pairwise_parameterize = ( os.environ.get('CHAINER_TEST_PAIRWISE_PARAMETERIZATION', 'never')) assert _pairwise_parameterize in ('never', 'always') def pytest_collection(session): # Perform pairwise testing. # TODO(kataoka): This is a tentative fix. Discuss its public interface. if _pairwise_parameterize == 'always': pairwise_product_dict = parameterized._pairwise_product_dict testing.product_dict = pairwise_product_dict parameterized.product_dict = pairwise_product_dict def pytest_collection_finish(session): if _pairwise_parameterize == 'always': product_dict = parameterized._product_dict_orig testing.product_dict = product_dict parameterized.product_dict = product_dict
Clean up spaces (a little)
"""usage: git-xblob add <path> [...]""" import os import re from ..utils import git def bail(code=1): print __doc__.strip() exit(code) def run_add(paths): if not paths: bail() missing_any = False for path in paths: if not os.path.exists(path): print path, 'does not exist' missing_any = True if missing_any: return 3 for path in paths: # Add it to the attributes file. head, tail = os.path.split(path) # Clean up spaces. tail = re.sub(r'\s', '[[:space:]]', tail) attributes_path = os.path.join(head, '.gitattributes') with open(attributes_path, 'a') as fh: fh.write('/%s filter=xblob\n' % tail) # Add the file and the attributes. git('add -f %s', attributes_path) git('add -f %s', path)
"""usage: git-xblob add <path> [...]""" import os from ..utils import git def bail(code=1): print __doc__.strip() exit(code) def run_add(paths): if not paths: bail() missing_any = False for path in paths: if not os.path.exists(path): print path, 'does not exist' missing_any = True if missing_any: return 3 for path in paths: # Add it to the attributes file. head, tail = os.path.split(path) attributes_path = os.path.join(head, '.gitattributes') with open(attributes_path, 'a') as fh: fh.write('/%s filter=xblob\n' % tail) # Add the file and the attributes. git('add -f %s', attributes_path) git('add -f %s', path)
Simplify test setup a bit
package fitnesse.slim.instructions; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; public class MakeInstructionTest { private static final String ID = "id_1"; private final InstructionExecutor executor = mock(InstructionExecutor.class); @Test public void shouldDelegateCallToExecutor() throws Exception { MakeInstruction instruction = new MakeInstruction(ID, "instance", "class", new Object[]{"arg1", "arg2"}); instruction.execute(executor); verify(executor, times(1)).create("instance", "class", "arg1", "arg2"); } @Test public void shouldFormatReturnValues() { MakeInstruction instruction = new MakeInstruction(ID, "instance", "class", new Object[]{"arg1", "arg2"}); InstructionResult result = instruction.execute(executor); assertEquals(ID, result.getId()); assertTrue(result.hasResult()); assertFalse(result.hasError()); assertEquals("OK", result.getResult()); } }
package fitnesse.slim.instructions; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; public class MakeInstructionTest { private static final String ID = "id_1"; private static final String RESULT = "OK"; private InstructionExecutor executor; @Before public void setUp() throws Exception { executor = mock(InstructionExecutor.class); } @Test public void shouldDelegateCallToExecutor() throws Exception { MakeInstruction instruction = new MakeInstruction(ID, "instance", "class", new Object[]{"arg1", "arg2"}); instruction.execute(executor); verify(executor, times(1)).create("instance", "class", "arg1", "arg2"); } @Test public void shouldFormatReturnValues() { MakeInstruction instruction = new MakeInstruction(ID, "instance", "class", new Object[]{"arg1", "arg2"}); InstructionResult result = instruction.execute(executor); assertEquals(ID, result.getId()); assertTrue(result.hasResult()); assertFalse(result.hasError()); assertEquals("OK", result.getResult()); } }
Add css rule debugging, cause Chrome's being a weirdo
/** * Searches the first loaded style sheet for an @keyframes animation by name. * FYI: If you use "to" or "from" they'll get converted to percentage values, so use them for manipulating rules. * Source (Optimized for flapper): http://jsfiddle.net/russelluresti/RHhBz/3/. **/ function findKeyframesRule(name) { var stylesheet = document.styleSheets[0]; for (var i = 0; i < stylesheet.cssRules.length; i++) { var cssRule = stylesheet.cssRules[i]; if (cssRule.name == name) return cssRule; } return null; } /** * Searches the first loaded style sheet for a CSS rule by name. **/ function findCSSRule(name) { var stylesheet = document.styleSheets[0]; console.log("Stylesheet: " + stylesheet); for (var i = 0; i < stylesheet.cssRules.length; i++) { var cssRule = stylesheet.cssRules[i]; console.log(`cssRule(${i}): ${cssRule}`) if (cssRule.selectorText == name) { console.log("Found it"); return cssRule; } } return null; }
/** * Searches the first loaded style sheet for an @keyframes animation by name. * FYI: If you use "to" or "from" they'll get converted to percentage values, so use them for manipulating rules. * Source (Optimized for flapper): http://jsfiddle.net/russelluresti/RHhBz/3/. **/ function findKeyframesRule(name) { var stylesheet = document.styleSheets[0]; for (var i = 0; i < stylesheet.cssRules.length; i++) { var cssRule = stylesheet.cssRules[i]; if (cssRule.name == name) return cssRule; } return null; } /** * Searches the first loaded style sheet for a CSS rule by name. **/ function findCSSRule(name) { var stylesheet = document.styleSheets[0]; for (var i = 0; i < stylesheet.cssRules.length; i++) { var cssRule = stylesheet.cssRules[i]; if (cssRule.selectorText == name) return cssRule; } return null; }
Read standard input instead of hard-coded strings.
#!/usr/bin/env python from telnetlib import Telnet import time import sys tn = Telnet('192.168.1.15', 13666, None) pipe_contents = sys.stdin.read() pipe_contents = pipe_contents.replace('\n', ' ') tn.write("hello\n") tn.write("screen_add s1\n") tn.write("screen_set s1 -priority 1\n") tn.write("widget_add s1 w1 string\n") tn.write("widget_add s1 w2 string\n") def lcd_string(x, telnet_obj, delay=2): L = [] for i in range(len(x)): if i % (15+16) == 0: L.append(x[i:i+15+16]) for s in L: s1 = s[0:15] s2 = s[15:] telnet_obj.write("widget_set s1 w1 1 1 {" + s1 + "}\n") telnet_obj.write("widget_set s1 w2 1 2 {" + s2 + "}\n") time.sleep(delay) lcd_string(pipe_contents, tn)
from telnetlib import Telnet import time tn = Telnet('192.168.1.15', 13666, None) #tn.interact() tn.write("hello\n") tn.write("screen_add s1\n") tn.write("screen_set s1 -priority 1\n") tn.write("widget_add s1 w1 string\n") tn.write("widget_add s1 w2 string\n") tn.write("widget_set s1 w1 1 1 {It is a truth u}\n") tn.write("widget_set s1 w2 1 2 {niversally ackno}\n") print "sleeping" time.sleep(5) def lcd_string(x, telnet_obj, delay=5): L = [] for i in range(len(x)): if i % (15+16) == 0: L.append(x[i:i+15+16]) for s in L: s1 = s[0:15] s2 = s[15:] telnet_obj.write("widget_set s1 w1 1 1 {" + s1 + "}\n") telnet_obj.write("widget_set s1 w2 1 2 {" + s2 + "}\n") time.sleep(delay) lcd_string('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz', tn)
Print error message to log when plugin loader fails to close JAR file Change-Id: Ic113b7759e094bd18c8c68767d85a25044400cb4
// Copyright (C) 2012 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.plugins; import java.io.File; import java.io.IOException; import java.util.jar.JarFile; class CleanupHandle { private final File tmpFile; private final JarFile jarFile; CleanupHandle(File tmpFile, JarFile jarFile) { this.tmpFile = tmpFile; this.jarFile = jarFile; } void cleanup() { try { jarFile.close(); } catch (IOException err) { PluginLoader.log.error("Cannot close " + jarFile.getName(), err); } if (!tmpFile.delete() && tmpFile.exists()) { PluginLoader.log.warn("Cannot delete " + tmpFile.getAbsolutePath() + ", retrying to delete it on termination of the virtual machine"); tmpFile.deleteOnExit(); } else { PluginLoader.log.info("Cleaned plugin " + tmpFile.getName()); } } }
// Copyright (C) 2012 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.plugins; import java.io.File; import java.io.IOException; import java.util.jar.JarFile; class CleanupHandle { private final File tmpFile; private final JarFile jarFile; CleanupHandle(File tmpFile, JarFile jarFile) { this.tmpFile = tmpFile; this.jarFile = jarFile; } void cleanup() { try { jarFile.close(); } catch (IOException err) { } if (!tmpFile.delete() && tmpFile.exists()) { PluginLoader.log.warn("Cannot delete " + tmpFile.getAbsolutePath() + ", retrying to delete it on termination of the virtual machine"); tmpFile.deleteOnExit(); } else { PluginLoader.log.info("Cleaned plugin " + tmpFile.getName()); } } }
Use index 126 instead of 70
package hpack import ( "github.com/summerwind/h2spec/config" "github.com/summerwind/h2spec/spec" "golang.org/x/net/http2" ) func IndexAddressSpace() *spec.TestGroup { tg := NewTestGroup("2.3.3", "Index Address Space") // Indices strictly greater than the sum of the lengths of both // tables MUST be treated as a decoding error. tg.AddTestCase(&spec.TestCase{ Desc: "Sends a header field representation with invalid index", Requirement: "The endpoint MUST treat this as a decoding error.", Run: func(c *config.Config, conn *spec.Conn) error { var streamID uint32 = 1 err := conn.Handshake() if err != nil { return err } // Indexed header field representation with index 126 indexedRep := []byte("\xFE") headers := spec.CommonHeaders(c) blockFragment := conn.EncodeHeaders(headers) blockFragment = append(blockFragment, indexedRep...) hp := http2.HeadersFrameParam{ StreamID: streamID, EndStream: true, EndHeaders: true, BlockFragment: blockFragment, } conn.WriteHeaders(hp) return spec.VerifyConnectionError(conn, http2.ErrCodeCompression) }, }) return tg }
package hpack import ( "github.com/summerwind/h2spec/config" "github.com/summerwind/h2spec/spec" "golang.org/x/net/http2" ) func IndexAddressSpace() *spec.TestGroup { tg := NewTestGroup("2.3.3", "Index Address Space") // Indices strictly greater than the sum of the lengths of both // tables MUST be treated as a decoding error. tg.AddTestCase(&spec.TestCase{ Desc: "Sends a header field representation with invalid index", Requirement: "The endpoint MUST treat this as a decoding error.", Run: func(c *config.Config, conn *spec.Conn) error { var streamID uint32 = 1 err := conn.Handshake() if err != nil { return err } // Indexed header field representation with index 70 indexedRep := []byte("\xC6") headers := spec.CommonHeaders(c) blockFragment := conn.EncodeHeaders(headers) blockFragment = append(blockFragment, indexedRep...) hp := http2.HeadersFrameParam{ StreamID: streamID, EndStream: true, EndHeaders: true, BlockFragment: blockFragment, } conn.WriteHeaders(hp) return spec.VerifyConnectionError(conn, http2.ErrCodeCompression) }, }) return tg }
Add flush for dummy exec worker
#!/usr/bin/env python from __future__ import print_function import socket import time import sys DEFAULT_IP = '127.0.0.1' DEFAULT_PORT = 8125 if __name__ == '__main__': s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for i in xrange(1, 3000): s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT)) s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT)) print("Reporting {0}".format(i), file=sys.stdout) sys.stdout.flush() print("Some error at {0}".format(i), file=sys.stderr) sys.stderr.flush() time.sleep(0.1)
#!/usr/bin/env python from __future__ import print_function import socket import time import sys DEFAULT_IP = '127.0.0.1' DEFAULT_PORT = 8125 if __name__ == '__main__': s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for i in xrange(1, 3000): s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT)) s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT)) print("Reporting {0}".format(i), file=sys.stdout) print("Some error at {0}".format(i), file=sys.stderr) time.sleep(0.1)
Add another url pattern for debugging public layers
from django.conf.urls.defaults import * import time urlpatterns = patterns('lingcod.layers.views', url(r'^public/$', 'get_public_layers', name='public-data-layers'), # Useful for debugging, avoids GE caching interference url(r'^public/cachebuster/%s' % str(time.time()), 'get_public_layers', name='public-data-layers-cachebuster'), url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml', 'get_kml_file', name='kml-file'), url(r'^privatekml/(?P<session_key>\w+)/$', 'get_privatekml_list', name='layers-privatekml-list'), url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$', 'get_privatekml', name='layers-privatekml'), url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$', 'get_relative_to_privatekml', name='layers-privatekml-relative'), )
from django.conf.urls.defaults import * urlpatterns = patterns('lingcod.layers.views', url(r'^public/', 'get_public_layers', name='public-data-layers'), url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml', 'get_kml_file', name='kml-file'), url(r'^privatekml/(?P<session_key>\w+)/$', 'get_privatekml_list', name='layers-privatekml-list'), url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$', 'get_privatekml', name='layers-privatekml'), url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$', 'get_relative_to_privatekml', name='layers-privatekml-relative'), )
Add extra type formatter for `list` type
from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ return Markup('<i class="icon-ok"></i>' if value else '') def list_formatter(values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(values) DEFAULT_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ return Markup('<i class="icon-ok"></i>' if value else '') DEFAULT_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter }
Fix typo in jsdoc comment
/*! * compressible * Copyright(c) 2013 Jonathan Ong * Copyright(c) 2014 Jeremiah Senkpiel * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module dependencies. * @private */ var db = require('mime-db') /** * Module variables. * @private */ var compressibleTypeRegExp = /^text\/|\+json$|\+text$|\+xml$/i var extractTypeRegExp = /^\s*([^;\s]*)(?:;|\s|$)/ /** * Module exports. * @public */ module.exports = compressible /** * Checks if a type is compressible. * * @param {string} type * @return {Boolean} compressible * @public */ function compressible(type) { if (!type || typeof type !== 'string') { return false } // strip parameters var match = extractTypeRegExp.exec(type) var mime = match && match[1].toLowerCase() var data = db[mime] if ((data && data.compressible) || compressibleTypeRegExp.test(mime)) { return true } return data ? data.compressible : undefined }
/*! * compressible * Copyright(c) 2013 Jonathan Ong * Copyright(c) 2014 Jeremiah Senkpiel * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module dependencies. * @private */ var db = require('mime-db') /** * Module variables. * @private */ var compressibleTypeRegExp = /^text\/|\+json$|\+text$|\+xml$/i var extractTypeRegExp = /^\s*([^;\s]*)(?:;|\s|$)/ /** * Module exports. * @public */ module.exports = compressible /** * Checks if a type is compressible. * * @param {string} type * @return {Boolean} compressible & @public */ function compressible(type) { if (!type || typeof type !== 'string') { return false } // strip parameters var match = extractTypeRegExp.exec(type) var mime = match && match[1].toLowerCase() var data = db[mime] if ((data && data.compressible) || compressibleTypeRegExp.test(mime)) { return true } return data ? data.compressible : undefined }
Fix no need to always import DevTools component.
// This file bootstraps the app with the boilerplate necessary // to support hot reloading in Redux import React, {PropTypes} from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import FuelSavingsApp from '../components/FuelSavingsApp'; import * as FuelSavingsActions from '../actions/fuelSavingsActions'; class App extends React.Component { render() { const { fuelSavingsAppState, actions } = this.props; return ( <div> <FuelSavingsApp fuelSavingsAppState={fuelSavingsAppState} actions={actions} /> </div> ); } } App.propTypes = { actions: PropTypes.object.isRequired, fuelSavingsAppState: PropTypes.object.isRequired }; function mapStateToProps(state) { return { fuelSavingsAppState: state.fuelSavingsAppState }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(FuelSavingsActions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(App);
// This file bootstraps the app with the boilerplate necessary // to support hot reloading in Redux import React, {PropTypes} from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import FuelSavingsApp from '../components/FuelSavingsApp'; import * as FuelSavingsActions from '../actions/fuelSavingsActions'; import DevTools from './DevTools'; class App extends React.Component { render() { const { fuelSavingsAppState, actions } = this.props; return ( <div> <FuelSavingsApp fuelSavingsAppState={fuelSavingsAppState} actions={actions} /> </div> ); } } App.propTypes = { actions: PropTypes.object.isRequired, fuelSavingsAppState: PropTypes.object.isRequired }; function mapStateToProps(state) { return { fuelSavingsAppState: state.fuelSavingsAppState }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(FuelSavingsActions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(App);
Change package name for example
package httpstat_test import ( "io" "io/ioutil" "log" "net/http" "time" "github.com/tcnksm/go-httpstat" ) func Example() { req, err := http.NewRequest("GET", "http://deeeet.com", nil) if err != nil { log.Fatal(err) } // Create go-httpstat powered var result httpstat.Result ctx := httpstat.WithHTTPStat(req.Context(), &result) req = req.WithContext(ctx) client := http.DefaultClient res, err := client.Do(req) if err != nil { log.Fatal(err) } defer res.Body.Close() if _, err := io.Copy(ioutil.Discard, res.Body); err != nil { log.Fatal(err) } end := time.Now() log.Printf("Name Lookup: %d ms", int(result.NameLookup/time.Millisecond)) log.Printf("Connect: %d ms", int(result.Connect/time.Millisecond)) log.Printf("Start Transfer: %d ms", int(result.StartTransfer/time.Millisecond)) log.Printf("Total: %d ms", int(result.Total(end)/time.Millisecond)) }
package httpstat import ( "io" "io/ioutil" "log" "net/http" "time" "github.com/tcnksm/go-httpstat" ) func Example() { req, err := http.NewRequest("GET", "http://deeeet.com", nil) if err != nil { log.Fatal(err) } // Create go-httpstat powered var result httpstat.Result ctx := httpstat.WithHTTPStat(req.Context(), &result) req = req.WithContext(ctx) client := http.DefaultClient res, err := client.Do(req) if err != nil { log.Fatal(err) } defer res.Body.Close() if _, err := io.Copy(ioutil.Discard, res.Body); err != nil { log.Fatal(err) } end := time.Now() log.Printf("Name Lookup: %d ms", int(result.NameLookup/time.Millisecond)) log.Printf("Connect: %d ms", int(result.Connect/time.Millisecond)) log.Printf("Start Transfer: %d ms", int(result.StartTransfer/time.Millisecond)) log.Printf("Total: %d ms", int(result.Total(end)/time.Millisecond)) }
Make script run on document start to help on dot flashes
// ==UserScript== // @name Hide offline presence dot on old reddit // @namespace https://mathemaniac.org // @version 1.0.1 // @description Hides the offline presence dot from old reddit. Only hides offline presence, so you notice if you're displayed as online. https://old.reddit.com/r/changelog/comments/lx08r2/announcing_online_presence_indicators/ // @author Sebastian Paaske Tørholm // @match https://old.reddit.com/* // @icon https://www.google.com/s2/favicons?domain=reddit.com // @grant none // @run-at document-start // ==/UserScript== (function() { 'use strict'; document.head.insertAdjacentHTML('beforeend', ` <style>#header-bottom-right .presence_circle.offline { display: none !important; }</style> `); })();
// ==UserScript== // @name Hide offline presence dot on old reddit // @namespace https://mathemaniac.org // @version 1.0 // @description Hides the offline presence dot from old reddit. Only hides offline presence, so you notice if you're displayed as online. https://old.reddit.com/r/changelog/comments/lx08r2/announcing_online_presence_indicators/ // @author Sebastian Paaske Tørholm // @match https://old.reddit.com/* // @icon https://www.google.com/s2/favicons?domain=reddit.com // @grant none // ==/UserScript== (function() { 'use strict'; document.head.insertAdjacentHTML('beforeend', ` <style>#header-bottom-right .presence_circle.offline { display: none !important; }</style> `); })();
Add API method to fetch a URLMap by id
package com.elmakers.mine.bukkit.api.maps; import org.bukkit.inventory.ItemStack; import java.util.List; public interface MapController { List<URLMap> getAll(); URLMap getMap(short id); void loadMap(String world, short id, String url, String name, int x, int y, int width, int height, Integer priority); ItemStack getURLItem(String world, String url, String name, int x, int y, int width, int height, Integer priority); void forceReloadPlayerPortrait(String worldName, String playerName); ItemStack getPlayerPortrait(String worldName, String playerName, Integer priority, String photoName); ItemStack getMapItem(short id); boolean hasMap(short id); boolean remove(short id); void save(); short getURLMapId(String world, String url, String name, int x, int y, int width, int height, Integer priority); short getURLMapId(String world, String url); }
package com.elmakers.mine.bukkit.api.maps; import org.bukkit.inventory.ItemStack; import java.util.List; public interface MapController { List<URLMap> getAll(); void loadMap(String world, short id, String url, String name, int x, int y, int width, int height, Integer priority); ItemStack getURLItem(String world, String url, String name, int x, int y, int width, int height, Integer priority); void forceReloadPlayerPortrait(String worldName, String playerName); ItemStack getPlayerPortrait(String worldName, String playerName, Integer priority, String photoName); ItemStack getMapItem(short id); boolean hasMap(short id); boolean remove(short id); void save(); short getURLMapId(String world, String url, String name, int x, int y, int width, int height, Integer priority); short getURLMapId(String world, String url); }
Fix problems using Lexicons in deepcopy'd objects. Said problems actually only manifest as 'ignored' RuntimeErrors, but those are really annoying and hard to hide. This seems to be the right fix.
from attribute_dict import AttributeDict from alias_dict import AliasDict __version__ = "0.1.0" class Lexicon(AttributeDict, AliasDict): def __init__(self, *args, **kwargs): # Need to avoid combining AliasDict's initial attribute write on # self.aliases, with AttributeDict's __setattr__. Doing so results in # an infinite loop. Instead, just skip straight to dict() for both # explicitly (i.e. we override AliasDict.__init__ instead of extending # it.) # NOTE: could tickle AttributeDict.__init__ instead, in case it ever # grows one. dict.__init__(self, *args, **kwargs) dict.__setattr__(self, 'aliases', {}) def __getattr__(self, key): # Intercept deepcopy/etc driven access to self.aliases when not # actually set. (Only a problem for us, due to abovementioned combo of # Alias and Attribute Dicts, so not solvable in a parent alone.) if key == 'aliases' and key not in self.__dict__: self.__dict__[key] = {} return super(Lexicon, self).__getattr__(key)
from attribute_dict import AttributeDict from alias_dict import AliasDict __version__ = "0.1.0" class Lexicon(AttributeDict, AliasDict): def __init__(self, *args, **kwargs): # Need to avoid combining AliasDict's initial attribute write on # self.aliases, with AttributeDict's __setattr__. Doing so results in # an infinite loop. Instead, just skip straight to dict() for both # explicitly (i.e. we override AliasDict.__init__ instead of extending # it.) # NOTE: could tickle AttributeDict.__init__ instead, in case it ever # grows one. dict.__init__(self, *args, **kwargs) dict.__setattr__(self, 'aliases', {})
Add config option for weeks to truncate and default to 2 weeks
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from configman import Namespace from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ required_config = Namespace() required_config.add_option( 'weeks_to_keep', default=2, doc='Number of weeks of raw crash data to keep in Postgres') def run(self, connection): cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (self.config.weeks_to_keep,) )
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from crontabber.base import BaseCronApp from crontabber.mixins import ( with_postgres_transactions, with_single_postgres_transaction, ) @with_postgres_transactions() @with_single_postgres_transaction() class TruncatePartitionsCronApp(BaseCronApp): app_name = 'truncate-partitions' app_version = '1.0' app_description = """See http://socorro.readthedocs.org/en/latest/databaseadminfunctions.html#truncate -partitions See https://bugzilla.mozilla.org/show_bug.cgi?id=1117911 """ def run(self, connection): # number of weeks of partitions to keep weeks = 2 cursor = connection.cursor() # Casting to date because stored procs in psql are strongly typed. cursor.execute( "select truncate_partitions(%s)", (weeks,) )
Update for SublimeLinter 4 API. github.com/ckaznocha/SublimeLinter-contrib-write-good/issues/14 github.com/ckaznocha/SublimeLinter-contrib-write-good/issues/11
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Clifton Kaznocha # Copyright (c) 2014 Clifton Kaznocha # # License: MIT # """This module exports the WriteGood plugin class.""" import SublimeLinter from SublimeLinter.lint import NodeLinter if getattr(SublimeLinter.lint, 'VERSION', 3) > 3: from SublimeLinter.lint import const WARNING = const.WARNING else: from SublimeLinter.lint import highlight WARNING = highlight.WARNING class WriteGood(NodeLinter): """Provides an interface to write-good.""" cmd = ('write-good') npm_name = 'write-good' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ">=0.9.0" regex = r'''(?xi) ^(?P<message>(?P<near>"[^"]*").*)\son\sline\s(?P<line>\d+)\sat\scolumn\s\d+$ ''' multiline = True default_type = WARNING defaults = { "selector": 'text.html.markdown, text.plain, text.tex.latex, comment' } tempfile_suffix = '.tmp'
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Clifton Kaznocha # Copyright (c) 2014 Clifton Kaznocha # # License: MIT # """This module exports the WriteGood plugin class.""" import SublimeLinter from SublimeLinter.lint import NodeLinter if getattr(SublimeLinter.lint, 'VERSION', 3) > 3: from SublimeLinter.lint import const WARNING = const.WARNING else: from SublimeLinter.lint import highlight WARNING = highlight.WARNING class WriteGood(NodeLinter): """Provides an interface to write-good.""" syntax = ('*') cmd = ('write-good') npm_name = 'write-good' version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ">=0.9.0" regex = r'''(?xi) ^(?P<message>(?P<near>"[^"]*").*)\son\sline\s(?P<line>\d+)\sat\scolumn\s\d+$ ''' multiline = True default_type = WARNING selectors = { '*': 'text.html.markdown, text.plain, text.tex.latex, comment' } tempfile_suffix = '.tmp'
Remove unused JUnit TemporaryFolder rule.
/* * Copyright 2016-2017 Steinar Bang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations * under the License. */ package no.priv.bang.ukelonn.impl; import static org.junit.Assert.*; import org.junit.Test; import no.priv.bang.ukelonn.UkelonnService; /** * Unit test for the {@link UkelonnServletProvider} class. * * @author Steinar Bang * */ public class UkelonnServletProviderTest { /** * Test fetching a {@link UkelonnService}. */ @Test public void testCreateAndAssignToInterface() { UkelonnService ukelonnService = new UkelonnServletProvider(); assertNull(ukelonnService.getDatabase()); assertNull(ukelonnService.getLogservice()); } }
/* * Copyright 2016-2017 Steinar Bang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations * under the License. */ package no.priv.bang.ukelonn.impl; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import no.priv.bang.ukelonn.UkelonnService; /** * Unit test for the {@link UkelonnServletProvider} class. * * @author Steinar Bang * */ public class UkelonnServletProviderTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); /** * Test fetching a {@link UkelonnService}. */ @Test public void testCreateAndAssignToInterface() { UkelonnService ukelonnService = new UkelonnServletProvider(); assertNull(ukelonnService.getDatabase()); assertNull(ukelonnService.getLogservice()); } }
Check for document.currentScript before assigning it IE>10 supports HTMLScriptElement.async but not document.currentScript.
} // auto-load Promise polyfill if needed in the browser var doPolyfill = typeof Promise === 'undefined'; // document.write if (typeof document !== 'undefined') { var scripts = document.getElementsByTagName('script'); $__curScript = scripts[scripts.length - 1]; if (document.currentScript && ($__curScript.defer || $__curScript.async)) $__curScript = document.currentScript; if (doPolyfill) { var curPath = $__curScript.src; var basePath = curPath.substr(0, curPath.lastIndexOf('/') + 1); window.systemJSBootstrap = bootstrap; document.write( '<' + 'script type="text/javascript" src="' + basePath + 'system-polyfills.js">' + '<' + '/script>' ); } else { bootstrap(); } } // importScripts else if (typeof importScripts !== 'undefined') { var basePath = ''; try { throw new Error('_'); } catch (e) { e.stack.replace(/(?:at|@).*(http.+):[\d]+:[\d]+/, function(m, url) { $__curScript = { src: url }; basePath = url.replace(/\/[^\/]*$/, '/'); }); } if (doPolyfill) importScripts(basePath + 'system-polyfills.js'); bootstrap(); } else { $__curScript = typeof __filename != 'undefined' ? { src: __filename } : null; bootstrap(); } })();
} // auto-load Promise polyfill if needed in the browser var doPolyfill = typeof Promise === 'undefined'; // document.write if (typeof document !== 'undefined') { var scripts = document.getElementsByTagName('script'); $__curScript = scripts[scripts.length - 1]; if ($__curScript.defer || $__curScript.async) $__curScript = document.currentScript; if (doPolyfill) { var curPath = $__curScript.src; var basePath = curPath.substr(0, curPath.lastIndexOf('/') + 1); window.systemJSBootstrap = bootstrap; document.write( '<' + 'script type="text/javascript" src="' + basePath + 'system-polyfills.js">' + '<' + '/script>' ); } else { bootstrap(); } } // importScripts else if (typeof importScripts !== 'undefined') { var basePath = ''; try { throw new Error('_'); } catch (e) { e.stack.replace(/(?:at|@).*(http.+):[\d]+:[\d]+/, function(m, url) { $__curScript = { src: url }; basePath = url.replace(/\/[^\/]*$/, '/'); }); } if (doPolyfill) importScripts(basePath + 'system-polyfills.js'); bootstrap(); } else { $__curScript = typeof __filename != 'undefined' ? { src: __filename } : null; bootstrap(); } })();
Change integer default type name
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INTEGER", FLOAT: "FLOAT", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import class Typecode(object): NONE = 0 INT = 1 << 0 FLOAT = 1 << 1 STRING = 1 << 2 DATETIME = 1 << 3 INFINITY = 1 << 4 NAN = 1 << 5 BOOL = 1 << 6 DEFAULT_TYPENAME_TABLE = { NONE: "NONE", INT: "INT", FLOAT: "FLOAT", STRING: "STRING", DATETIME: "DATETIME", INFINITY: "INFINITY", NAN: "NAN", BOOL: "BOOL", } TYPENAME_TABLE = DEFAULT_TYPENAME_TABLE @classmethod def get_typename(cls, typecode): type_name = cls.TYPENAME_TABLE.get(typecode) if type_name is None: raise ValueError("unknown typecode: {}".format(typecode)) return type_name
Make reachable depend on availability
package com.phonegap.demo; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.net.*; import android.webkit.WebView; public class NetworkManager { Context mCtx; WebView mView; ConnectivityManager sockMan; NetworkManager(Context ctx, WebView view) { mCtx = ctx; mView = view; sockMan = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE); } public boolean isAvailable() { NetworkInfo info = sockMan.getActiveNetworkInfo(); return info.isConnected(); } public boolean isReachable(String uri) { boolean reached = isAvailable(); try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(uri); httpclient.execute(httpget); } catch (Exception e) { reached = false;} return reached; } }
package com.phonegap.demo; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.net.*; import android.webkit.WebView; public class NetworkManager { Context mCtx; WebView mView; ConnectivityManager sockMan; NetworkManager(Context ctx, WebView view) { mCtx = ctx; mView = view; sockMan = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE); } public boolean isAvailable() { NetworkInfo info = sockMan.getActiveNetworkInfo(); return info.isConnected(); } public boolean isReachable(String uri) { boolean reached = true; try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(uri); httpclient.execute(httpget); } catch (Exception e) { reached = false;} return reached; } }
fix(output): Add type check for polygon and polyline arrays Added a type check to properly wrap polygon and polyline arrays
module.exports.point = justType('Point', 'POINT'); module.exports.line = justType('LineString', 'POLYLINE'); module.exports.polygon = justType('Polygon', 'POLYGON'); function justType(type, TYPE) { return function(gj) { var oftype = gj.features.filter(isType(type)); return { geometries: (TYPE === 'POLYGON' || TYPE === 'POLYLINE') ? [oftype.map(justCoords)] : oftype.map(justCoords), properties: oftype.map(justProps), type: TYPE }; }; } function justCoords(t) { if (t.geometry.coordinates[0] !== undefined && t.geometry.coordinates[0][0] !== undefined && t.geometry.coordinates[0][0][0] !== undefined) { return t.geometry.coordinates[0]; } else { return t.geometry.coordinates; } } function justProps(t) { return t.properties; } function isType(t) { return function(f) { return f.geometry.type === t; }; }
module.exports.point = justType('Point', 'POINT'); module.exports.line = justType('LineString', 'POLYLINE'); module.exports.polygon = justType('Polygon', 'POLYGON'); function justType(type, TYPE) { return function(gj) { var oftype = gj.features.filter(isType(type)); return { geometries: oftype.map(justCoords), properties: oftype.map(justProps), type: TYPE }; }; } function justCoords(t) { if (t.geometry.coordinates[0] !== undefined && t.geometry.coordinates[0][0] !== undefined && t.geometry.coordinates[0][0][0] !== undefined) { return t.geometry.coordinates[0]; } else { return t.geometry.coordinates; } } function justProps(t) { return t.properties; } function isType(t) { return function(f) { return f.geometry.type === t; }; }
Fix renamed functions in block information
<?php /** * Copyright (C) 2014 Proximis * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace Rbs\Storeshipping\Blocks; /** * @name \Rbs\Storeshipping\Blocks\ShortStoreInformation */ class ShortStoreInformation extends \Change\Presentation\Blocks\Information { /** * @param \Change\Events\Event $event */ public function onInformation(\Change\Events\Event $event) { parent::onInformation($event); $i18nManager = $event->getApplicationServices()->getI18nManager(); $ucf = array('ucf'); $this->setSection($i18nManager->trans('m.rbs.storeshipping.admin.module_name', $ucf)); $this->setLabel($i18nManager->trans('m.rbs.storeshipping.admin.short_store_label', $ucf)); // Declare your parameters here. $this->addParameterInformation('autoSelect', \Change\Documents\Property::TYPE_BOOLEAN, false, true) ->setLabel($i18nManager->trans('m.rbs.storeshipping.admin.short_store_auto_select', $ucf)); } }
<?php /** * Copyright (C) 2014 Proximis * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace Rbs\Storeshipping\Blocks; /** * @name \Rbs\Storeshipping\Blocks\ShortStoreInformation */ class ShortStoreInformation extends \Change\Presentation\Blocks\Information { /** * @param \Change\Events\Event $event */ public function onInformation(\Change\Events\Event $event) { parent::onInformation($event); $i18nManager = $event->getApplicationServices()->getI18nManager(); $ucf = array('ucf'); $this->setSection($i18nManager->trans('m.rbs.storeshipping.admin.module_name', $ucf)); $this->setLabel($i18nManager->trans('m.rbs.storeshipping.admin.short_store_label', $ucf)); // Declare your parameters here. $this->addInformationMeta('autoSelect', \Change\Documents\Property::TYPE_BOOLEAN, false, true) ->setLabel($i18nManager->trans('m.rbs.storeshipping.admin.short_store_auto_select', $ucf)); } }
Use the correct file for angle calculation data
import React, { Component } from 'react' import pureRender from 'pure-render-decorator' import { MapLayer } from 'react-leaflet' import { plateMovementCanvasLayer } from '../custom-leaflet/plate-movement-canvas-layer' import points from '../data/plate-movement-angles-mod4.js' let _cachedPoints function getPoints(map) { if (!_cachedPoints) { _cachedPoints = []; if (points) { for (var i = 0; i < points.length; i++) { let pos = { position: { lng: points[i][0], lat: points[i][1] }, velocity: { vMag: points[i][2], vAngle: points[i][3]}, text: points[i][0] + "," + points[i][1] } _cachedPoints.push(pos); } } } return _cachedPoints } @pureRender export default class PlateMovementCanvasLayer extends MapLayer { componentWillMount() { super.componentWillMount(); this.leafletElement = plateMovementCanvasLayer() this.setLeafletElementProps() } componentDidUpdate() { this.setLeafletElementProps() } setLeafletElementProps() { const { plateMovementPoints, map } = this.props this.leafletElement.setPlateMovementPoints(getPoints(map)) } render() { return null } }
import React, { Component } from 'react' import pureRender from 'pure-render-decorator' import { MapLayer } from 'react-leaflet' import { plateMovementCanvasLayer } from '../custom-leaflet/plate-movement-canvas-layer' import points from '../data/plate-movement-mod4.js' let _cachedPoints function getPoints(map) { if (!_cachedPoints) { _cachedPoints = []; if (points) { for (var i = 0; i < points.length; i++) { let pos = { position: { lng: points[i][0], lat: points[i][1] }, velocity: { vMag: points[i][2], vAngle: points[i][3]}, text: points[i][0] + "," + points[i][1] } _cachedPoints.push(pos); } } } return _cachedPoints } @pureRender export default class PlateMovementCanvasLayer extends MapLayer { componentWillMount() { super.componentWillMount(); this.leafletElement = plateMovementCanvasLayer() this.setLeafletElementProps() } componentDidUpdate() { this.setLeafletElementProps() } setLeafletElementProps() { const { plateMovementPoints, map } = this.props this.leafletElement.setPlateMovementPoints(getPoints(map)) } render() { return null } }
[minor] Remove useless calls to `Error` constructor
'use strict'; var util = require('util'); /** * Generic Primus error. * * @constructor * @param {String} message The reason for the error * @param {EventEmitter} logger Optional EventEmitter to emit a `log` event on. * @api public */ function PrimusError(message, logger) { Error.captureStackTrace(this, this.constructor); this.message = message; this.name = this.constructor.name; if (logger) { logger.emit('log', 'error', this); } } util.inherits(PrimusError, Error); /** * There was an error while parsing incoming or outgoing data. * * @param {String} message The reason for the error. * @param {Spark} spark The spark that caused the error. * @api public */ function ParserError(message, spark) { Error.captureStackTrace(this, this.constructor); this.message = message; this.name = this.constructor.name; if (spark) { if (spark.listeners('error').length) spark.emit('error', this); spark.primus.emit('log', 'error', this); } } util.inherits(ParserError, Error); // // Expose our custom events. // exports.PrimusError = PrimusError; exports.ParserError = ParserError;
'use strict'; var util = require('util'); /** * Generic Primus error. * * @constructor * @param {String} message The reason for the error * @param {EventEmitter} logger Optional EventEmitter to emit a `log` event on. * @api public */ function PrimusError(message, logger) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.message = message; this.name = this.constructor.name; if (logger) { logger.emit('log', 'error', this); } } util.inherits(PrimusError, Error); /** * There was an error while parsing incoming or outgoing data. * * @param {String} message The reason for the error. * @param {Spark} spark The spark that caused the error. * @api public */ function ParserError(message, spark) { Error.call(this); Error.captureStackTrace(this, this.constructor); this.message = message; this.name = this.constructor.name; if (spark) { if (spark.listeners('error').length) spark.emit('error', this); spark.primus.emit('log', 'error', this); } } util.inherits(ParserError, Error); // // Expose our custom events. // exports.PrimusError = PrimusError; exports.ParserError = ParserError;
Update code based on orchestral/support@1d5febb Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php namespace Orchestra\Memory; use Orchestra\Support\Relic; class Provider extends Relic { /** * Handler instance. * * @var MemoryHandlerInterface */ protected $handler; /** * Construct an instance. * * @param MemoryHandlerInterface $handler * @param string $name * @param array $config * @return void */ public function __construct(MemoryHandlerInterface $handler) { $this->handler = $handler; $this->items = $this->handler->initiate(); } /** * Shutdown/finish method. * * @return void */ public function finish() { return $this->handler->finish($this->items); } /** * Set a value from a key. * * @param string $key A string of key to add the value. * @param mixed $value The value. * @return mixed */ public function put($key, $value = '') { $this->set($key, $value); return $value; } }
<?php namespace Orchestra\Memory; use Orchestra\Support\Relic; class Provider extends Relic { /** * Handler instance. * * @var MemoryHandlerInterface */ protected $handler; /** * Construct an instance. * * @param MemoryHandlerInterface $handler * @param string $name * @param array $config * @return void */ public function __construct(MemoryHandlerInterface $handler) { $this->handler = $handler; $this->items = $this->handler->initiate(); } /** * Shutdown/finish method. * * @return void */ public function finish() { return $this->handler->finish($this->items); } /** * Set a value from a key. * * @param string $key A string of key to add the value. * @param mixed $value The value. * @return mixed */ public function put($key, $value = '') { $value = value($value); $this->set($key, $value); return $value; } }
Replace ':' and '-' to check the MAC-prefix
var csv = require('./lib/csv.js'); //Object to hold all the data var vendors = {}; var init = function(callback) { csv.each(__dirname + '/macVendor/vendors.csv').on('data', function(data) { vendors[data[1]] = { 'prefix': data[1], 'manufacturer': data[2], 'manufacturerAdress': data[3] }; }).on('end', function() { console.log('Finished'); if(callback) { callback(vendors); } }); }; var getVendorForMac = function(macAddress) { for(var macPrefix in vendors) { if(macAddress.startsWith(macPrefix)) { return vendors[macPrefix]; } } }; var pwn = function(macAddress) { var vendor = getVendorForMac(macAddress.replace(/:/g, '').replace(/-/g, '')); switch (vendor.manufacturer) { case 'Arcadyan Technology Corporation': return require(__dirname + '/exploits/easybox.js')(macAddress); break; } } module.exports = { init: init, getVendorForMac: getVendorForMac, pwn: pwn };
var csv = require('./lib/csv.js'); //Object to hold all the data var vendors = {}; var init = function(callback) { csv.each(__dirname + '/macVendor/vendors.csv').on('data', function(data) { vendors[data[1]] = { 'prefix': data[1], 'manufacturer': data[2], 'manufacturerAdress': data[3] }; }).on('end', function() { console.log('Finished'); if(callback) { callback(vendors); } }); }; var getVendorForMac = function(macAddress) { for(var macPrefix in vendors) { if(macAddress.startsWith(macPrefix)) { return vendors[macPrefix]; } } }; var pwn = function(macAddress) { var vendor = getVendorForMac(macAddress); switch (vendor.manufacturer) { case 'Arcadyan Technology Corporation': return require(__dirname + '/exploits/easybox.js')(macAddress); break; } } module.exports = { init: init, getVendorForMac: getVendorForMac, pwn: pwn };
Write listToArray function that produces an array from a list
// Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element. function arrayToList(array) { const list = { value: array[0], rest: { value: array[1], rest: { value: array[2], rest: null } } }; return list; } const theArray = [1, 2, 3]; console.log(arrayToList(theArray)); function listToArray(list) { console.log(list); const array = [ list.value, list.rest.value, list.rest.rest.value ]; return array; } const theList = arrayToList([1, 2, 3]); console.log(listToArray(theList));
// Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list, or undefined when there is no such element. function arrayToList(array) { const list = { value: array[0], rest: { value: array[1], rest: { value: array[2], rest: null } } }; return list; } console.log(arrayToList([1,2,3]));
Add import to stop warnings
# minNEURON.py from neuron import h cell = h.SectionList() soma = h.Section(name='soma') #create soma soma.push() #h.topology() # Geometry soma.nseg = 1 soma.L = 20 soma.diam = 20 # Biophysics for sec in h.allsec(): sec.Ra = 100 sec.cm = 1 sec.insert('pas') #sec.insert('hh') # insert hh cell.append(sec) #h('objref rho') #h('rho = new ChR(0.5)') #h.rho.Er = Prot.phis[0] #setattr(h.rho, 'del', Prot.pulses[0][0]) # rho.del will not work because del is reserved word in python #h.rho.ton = Prot.onDs[0] #h.rho.toff = Prot.offDs[0] #h.rho.num = Prot.nPulses #h.rho.gbar = RhO.g/20000 # Pick a rhodopsin to record from #rhoRec = h.ChR_apic.o(7) h.pop_section() #return cell
# minNEURON.py cell = h.SectionList() soma = h.Section(name='soma') #create soma soma.push() #h.topology() # Geometry soma.nseg = 1 soma.L = 20 soma.diam = 20 # Biophysics for sec in h.allsec(): sec.Ra = 100 sec.cm = 1 sec.insert('pas') #sec.insert('hh') # insert hh cell.append(sec) #h('objref rho') #h('rho = new ChR(0.5)') #h.rho.Er = Prot.phis[0] #setattr(h.rho, 'del', Prot.pulses[0][0]) # rho.del will not work because del is reserved word in python #h.rho.ton = Prot.onDs[0] #h.rho.toff = Prot.offDs[0] #h.rho.num = Prot.nPulses #h.rho.gbar = RhO.g/20000 # Pick a rhodopsin to record from #rhoRec = h.ChR_apic.o(7) h.pop_section() return cell
Allow players to see their own stats
package com.faforever.client.fx.contextmenu; import com.faforever.client.domain.PlayerBean; import com.faforever.client.i18n.I18n; import com.faforever.client.player.PlayerInfoWindowController; import com.faforever.client.theme.UiService; import com.faforever.client.util.Assert; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @RequiredArgsConstructor public class ShowPlayerInfoMenuItem extends AbstractMenuItem<PlayerBean> { private final I18n i18n; private final UiService uiService; @Override protected void onClicked() { Assert.checkNullIllegalState(object, "no player has been set"); PlayerInfoWindowController controller = uiService.loadFxml("theme/user_info_window.fxml"); controller.setPlayer(object); controller.setOwnerWindow(getParentPopup().getOwnerWindow()); controller.show(); } @Override protected boolean isItemVisible() { return object != null; } @Override protected String getItemText() { return i18n.get("chat.userContext.userInfo"); } }
package com.faforever.client.fx.contextmenu; import com.faforever.client.domain.PlayerBean; import com.faforever.client.i18n.I18n; import com.faforever.client.player.PlayerInfoWindowController; import com.faforever.client.player.SocialStatus; import com.faforever.client.theme.UiService; import com.faforever.client.util.Assert; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) @RequiredArgsConstructor public class ShowPlayerInfoMenuItem extends AbstractMenuItem<PlayerBean> { private final I18n i18n; private final UiService uiService; @Override protected void onClicked() { Assert.checkNullIllegalState(object, "no player has been set"); PlayerInfoWindowController controller = uiService.loadFxml("theme/user_info_window.fxml"); controller.setPlayer(object); controller.setOwnerWindow(getParentPopup().getOwnerWindow()); controller.show(); } @Override protected boolean isItemVisible() { return object != null && object.getSocialStatus() != SocialStatus.SELF; } @Override protected String getItemText() { return i18n.get("chat.userContext.userInfo"); } }
Fix tooltip positions in tutorial pages
var currentTip = null; var currentTipElement = null; function hideTip(evt, name, unique) { var el = document.getElementById(name); el.style.display = "none"; currentTip = null; } function findPos(obj) { var curleft = 0; var curtop = obj.offsetHeight; while (obj) { curleft += obj.offsetLeft; curtop += obj.offsetTop; obj = obj.offsetParent; }; return [curleft, curtop]; } function hideUsingEsc(e) { if (!e) { e = event; } hideTip(e, currentTipElement, currentTip); } function showTip(evt, name, unique, owner) { document.onkeydown = hideUsingEsc; if (currentTip == unique) return; currentTip = unique; currentTipElement = name; var pos = findPos(owner ? owner : (evt.srcElement ? evt.srcElement : evt.target)); var posx = pos[0]; var posy = pos[1]; var el = document.getElementById(name); var parent = (document.documentElement == null) ? document.body : document.documentElement; parent.appendChild(el); el.style.position = "absolute"; el.style.left = posx + "px"; el.style.top = posy + "px"; el.style.display = "block"; }
var currentTip = null; var currentTipElement = null; function hideTip(evt, name, unique) { var el = document.getElementById(name); el.style.display = "none"; currentTip = null; } function findPos(obj) { // no idea why, but it behaves differently in webbrowser component if (window.location.search == "?inapp") return [obj.offsetLeft + 10, obj.offsetTop + 30]; var curleft = 0; var curtop = obj.offsetHeight; while (obj) { curleft += obj.offsetLeft; curtop += obj.offsetTop; obj = obj.offsetParent; }; return [curleft, curtop]; } function hideUsingEsc(e) { if (!e) { e = event; } hideTip(e, currentTipElement, currentTip); } function showTip(evt, name, unique, owner) { document.onkeydown = hideUsingEsc; if (currentTip == unique) return; currentTip = unique; currentTipElement = name; var pos = findPos(owner ? owner : (evt.srcElement ? evt.srcElement : evt.target)); var posx = pos[0]; var posy = pos[1]; var el = document.getElementById(name); var parent = (document.documentElement == null) ? document.body : document.documentElement; el.style.position = "absolute"; el.style.left = posx + "px"; el.style.top = posy + "px"; el.style.display = "block"; }
Add workaround for edison platform. See IOTOS-1000, it needs 'connmanctl enable bluetooth' before rfkill. Then, the hciconfig could show hci0 device. Signed-off-by: Zhang Jingke <0979c04a6d09a3b3c8dd699e3664fb112fdd2a5b@intel.com>
from oeqa.oetest import oeRuntimeTest class CommBluetoothTest(oeRuntimeTest): log = "" def target_collect_info(self, cmd): (status, output) = self.target.run(cmd) self.log = self.log + "\n\n[Debug] Command output --- %s: \n" % cmd self.log = self.log + output '''Bluetooth device check''' def test_comm_btcheck(self): '''check bluetooth device''' # un-block software rfkill lock self.target.run('rfkill unblock all') # This is special for edison platform self.target.run('connmanctl enable bluetooth') # Collect system information as log self.target_collect_info("ifconfig") self.target_collect_info("hciconfig") self.target_collect_info("lsmod") # Detect BT device status (status, output) = self.target.run('hciconfig hci0') self.assertEqual(status, 0, msg="Error messages: %s" % self.log)
from oeqa.oetest import oeRuntimeTest class CommBluetoothTest(oeRuntimeTest): log = "" def target_collect_info(self, cmd): (status, output) = self.target.run(cmd) self.log = self.log + "\n\n[Debug] Command output --- %s: \n" % cmd self.log = self.log + output '''Bluetooth device check''' def test_comm_btcheck(self): '''check bluetooth device''' # un-block software rfkill lock self.target.run('rfkill unblock all') # Collect system information as log self.target_collect_info("ifconfig") self.target_collect_info("hciconfig") self.target_collect_info("lsmod") # Detect BT device status (status, output) = self.target.run('hciconfig hci0') self.assertEqual(status, 0, msg="Error messages: %s" % self.log)