text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove temporary patch for broken TestNG 6.9.13 Now that 6.9.13.2 is out this is not needed anymore.
/* * Copyright 2016 the original author or authors. * * 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.gradle.buildinit.plugins.internal; import com.google.common.base.Throwables; import java.io.IOException; import java.util.Properties; public class DefaultTemplateLibraryVersionProvider implements TemplateLibraryVersionProvider { private final Properties libraryVersions = new Properties(); public DefaultTemplateLibraryVersionProvider() { try { this.libraryVersions.load(getClass().getResourceAsStream("/org/gradle/buildinit/tasks/templates/library-versions.properties")); } catch (IOException e) { throw Throwables.propagate(e); } } public String getVersion(String module) { return libraryVersions.getProperty(module); } }
/* * Copyright 2016 the original author or authors. * * 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.gradle.buildinit.plugins.internal; import com.google.common.base.Throwables; import org.gradle.api.JavaVersion; import java.io.IOException; import java.util.Properties; public class DefaultTemplateLibraryVersionProvider implements TemplateLibraryVersionProvider { private final Properties libraryVersions = new Properties(); public DefaultTemplateLibraryVersionProvider() { try { this.libraryVersions.load(getClass().getResourceAsStream("/org/gradle/buildinit/tasks/templates/library-versions.properties")); } catch (IOException e) { throw Throwables.propagate(e); } } public String getVersion(String module) { if (module.equals("testng") && !JavaVersion.current().isJava8Compatible()) { // Use the highest version that runs on Java 7 return "6.9.12"; } return libraryVersions.getProperty(module); } }
Hide tooltip when showing modal
$(function() { $('.gcal-control').click(function() { target = $(this).data('target'); if($(this).hasClass('gcal-control-disabled')) { $(this).removeClass('gcal-control-disabled'); $('.event.'+target).slideDown(500); } else { $(this).addClass('gcal-control-disabled'); $('.event.'+target).slideUp(500); } $(this).blur(); }); $('#event-modal').on('show.bs.modal', function(event) { var trigger = $(event.relatedTarget); $('#event-title').html(trigger.data('summary')); $('#event-date').html(trigger.data('date')); $('#event-when').html(trigger.data('time')); $('#event-where').html(trigger.data('where')); $('#event-desc').html(trigger.data('details')); trigger.tooltip('hide'); }); //Not the standard method Bootstrap's docs recommend, but we'll need //the data-toggle attribute for the details modal. $('.event,.month-control').tooltip(); });
$(function() { $('.gcal-control').click(function() { target = $(this).data('target'); if($(this).hasClass('gcal-control-disabled')) { $(this).removeClass('gcal-control-disabled'); $('.event.'+target).slideDown(500); } else { $(this).addClass('gcal-control-disabled'); $('.event.'+target).slideUp(500); } $(this).blur(); }); $('#event-modal').on('show.bs.modal', function(event) { var trigger = $(event.relatedTarget); $('#event-title').html(trigger.data('summary')); $('#event-date').html(trigger.data('date')); $('#event-when').html(trigger.data('time')); $('#event-where').html(trigger.data('where')); $('#event-desc').html(trigger.data('details')); }); //Not the standard method Bootstrap's docs recommend, but we'll need //the data-toggle attribute for the details modal. $('.event,.month-control').tooltip(); });
Remove contenttypes from INSTALLED_APPS for testing; no longer needed.
#!/usr/bin/env python import os, sys from django.conf import settings import django DEFAULT_SETTINGS = dict( INSTALLED_APPS=( 'model_utils', 'model_utils.tests', ), DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3" } }, ) def runtests(*test_args): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() if not test_args: test_args = ['tests'] parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) from django.test.simple import DjangoTestSuiteRunner failures = DjangoTestSuiteRunner( verbosity=1, interactive=True, failfast=False).run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests()
#!/usr/bin/env python import os, sys from django.conf import settings import django DEFAULT_SETTINGS = dict( INSTALLED_APPS=( 'django.contrib.contenttypes', 'model_utils', 'model_utils.tests', ), DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3" } }, ) def runtests(*test_args): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() if not test_args: test_args = ['tests'] parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) from django.test.simple import DjangoTestSuiteRunner failures = DjangoTestSuiteRunner( verbosity=1, interactive=True, failfast=False).run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests()
Fix regexp to include modules whose names begin with "ui-"
let tests = [ // what result to expect, string to match against [ true, '/home/mike/git/work/stripes-experiments/stripes-connect' ], [ true, '/home/mike/git/work/stripes-loader/' ], [ true, '/home/mike/git/work/stripes-experiments/okapi-console/' ], [ true, '/home/mike/git/work/stripes-experiments/stripes-core/src/' ], [ false, '/home/mike/git/work/stripes-experiments/stripes-core/node_modules/camelcase' ], [ true, '/home/mike/git/work/ui-okapi-console' ], ]; // The regexp used in webpack.config.base.js to choose which source files get transpiled let re = /\/(stripes|ui)-(?!.*\/node_modules\/)/; let failed = 0; for (let i = 0; i < tests.length; i++) { var test = tests[i]; var expected = test[0]; var string = test[1]; var result = !!string.match(re); print(i + ": '" + string + "': " + "expected " + expected + ", got " + result + ": " + (result == expected ? "OK" : "FAIL")); if (result != expected) failed++; } let passed = tests.length - failed; print("Passed " + passed + " of " + tests.length + " tests"); if (failed > 0) { print("FAILED " + failed + " of " + tests.length + " tests"); }
let tests = [ // what result to expect, string to match against [ true, '/home/mike/git/work/stripes-experiments/stripes-connect' ], [ true, '/home/mike/git/work/stripes-loader/' ], [ true, '/home/mike/git/work/stripes-experiments/okapi-console/' ], [ true, '/home/mike/git/work/stripes-experiments/stripes-core/src/' ], [ false, '/home/mike/git/work/stripes-experiments/stripes-core/node_modules/camelcase' ], ]; // The regexp used in webpack.config.base.js to choose which source files get transpiled let re = /\/stripes-(?!.*\/node_modules\/)/; let failed = 0; for (let i = 0; i < tests.length; i++) { var test = tests[i]; var expected = test[0]; var string = test[1]; var result = !!string.match(re); print(i + ": '" + string + "': " + "expected " + expected + ", got " + result + ": " + (result == expected ? "OK" : "FAIL")); if (result != expected) failed++; } let passed = tests.length - failed; print("Passed " + passed + " of " + tests.length + " tests"); if (failed > 0) { print("FAILED " + failed + " of " + tests.length + " tests"); }
Enable flag in first invocation to ensure ember-basic-dropdown doesn't include its styles
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-power-select', included: function(appOrAddon) { var app = appOrAddon.app || appOrAddon; if (!app.__emberPowerSelectIncludedInvoked) { app.__emberPowerSelectIncludedInvoked = true; // Since ember-power-select styles already `@import` styles of ember-basic-dropdown, // this flag tells to ember-basic-dropdown to skip importing its styles. app.__skipEmberBasicDropdownStyles = true; this._super.included.apply(this, arguments); // Don't include the precompiled css file if the user uses ember-cli-sass if (!app.registry.availablePlugins['ember-cli-sass']) { var addonConfig = app.options['ember-power-select']; if (!addonConfig || !addonConfig.theme) { app.import('vendor/ember-power-select.css'); } else { app.import('vendor/ember-power-select-'+addonConfig.theme+'.css'); } } } }, contentFor: function(type, config) { var emberBasicDropdown = this.addons.filter(function(addon) { return addon.name === 'ember-basic-dropdown'; })[0] return emberBasicDropdown.contentFor(type, config); } };  
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-power-select', included: function(appOrAddon) { var app = appOrAddon.app || appOrAddon; if (!app.__emberPowerSelectIncludedInvoked) { app.__emberPowerSelectIncludedInvoked = true; this._super.included.apply(this, arguments); // Don't include the precompiled css file if the user uses ember-cli-sass if (!app.registry.availablePlugins['ember-cli-sass']) { var addonConfig = app.options['ember-power-select']; if (!addonConfig || !addonConfig.theme) { app.import('vendor/ember-power-select.css'); } else { app.import('vendor/ember-power-select-'+addonConfig.theme+'.css'); } } } }, contentFor: function(type, config) { var emberBasicDropdown = this.addons.filter(function(addon) { return addon.name === 'ember-basic-dropdown'; })[0] return emberBasicDropdown.contentFor(type, config); } };  
Support gameon-id header while we transition to new auth..
package org.gameon.map.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; @WebFilter( filterName = "corsFilter", urlPatterns = {"/*"} ) public class AuthFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String id = request.getParameter("id"); // TODO: a bunch of verification... if ( id == null ) id = ((HttpServletRequest)request).getHeader("gameon-id"); if ( id == null ) { id = "game-on.org-provisional"; } request.setAttribute("player.id", id); chain.doFilter(request, response); } @Override public void destroy() { } }
package org.gameon.map.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; @WebFilter( filterName = "corsFilter", urlPatterns = {"/*"} ) public class AuthFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String id = request.getParameter("id"); // TODO: a bunch of verification... if ( id == null ) id = "game-on.org-provisional"; request.setAttribute("player.id", id); chain.doFilter(request, response); } @Override public void destroy() { } }
Fix initializer warning when testing against Ember 2.1.
export default function(app, files) { const login = "Gaurav0"; const gist_id = "35de43cb81fc35ddffb2"; const commit = "f354c6698b02fe3243656c8dc5aa0303cc7ae81c"; files.push({ filename: "initializers.setup-test.js", content: ` import Ember from 'ember'; export default { name: 'setup-test', initialize: function() { var app = arguments[1] || arguments[0]; app.setupForTesting(); app.injectTestHelpers(); window.QUnit = window.parent.QUnit; } }; ` }); let gistFiles = {}; files.forEach(function(file) { let gistFile = server.create('gist-file', { filename: file.filename, login: login, gist_id: gist_id, commit: commit, content: file.content }); gistFiles[gistFile.filename] = gistFile; }); server.create('user', {login: login}); const owner = server.create('owner', {login: login}); server.create('gist', { id: gist_id, owner: owner, files: gistFiles }); visit('/35de43cb81fc35ddffb2'); return waitForLoadedIFrame(); }
export default function(app, files) { const login = "Gaurav0"; const gist_id = "35de43cb81fc35ddffb2"; const commit = "f354c6698b02fe3243656c8dc5aa0303cc7ae81c"; files.push({ filename: "initializers.setup-test.js", content: "import Ember from 'ember';\n\nexport default {\n name: 'setup-test',\n initialize: function(container, app) {\n app.setupForTesting();\n app.injectTestHelpers();\n window.QUnit = window.parent.QUnit;\n }\n};" }); let gistFiles = {}; files.forEach(function(file) { let gistFile = server.create('gist-file', { filename: file.filename, login: login, gist_id: gist_id, commit: commit, content: file.content }); gistFiles[gistFile.filename] = gistFile; }); server.create('user', {login: login}); const owner = server.create('owner', {login: login}); server.create('gist', { id: gist_id, owner: owner, files: gistFiles }); visit('/35de43cb81fc35ddffb2'); return waitForLoadedIFrame(); }
Fix data loss bug in migration. We should be deleting the signature to invalidate it, not the action itself.
""" Removes signatures, so they can be easily recreated during deployment. This migration is intended to be used between "eras" of signatures. As the serialization format of recipes changes, the signatures need to also change. This could be handled automatically, but it is easier to deploy if we just remove everything in a migration, and allow the normal processes to regenerate the signatures. """ # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def remove_signatures(apps, schema_editor): Recipe = apps.get_model('recipes', 'Recipe') Action = apps.get_model('recipes', 'Action') Signature = apps.get_model('recipes', 'Signature') for recipe in Recipe.objects.exclude(signature=None): sig = recipe.signature recipe.signature = None recipe.save() sig.delete() for action in Action.objects.exclude(signature=None): sig = action.signature action.signature = None action.save() sig.delete() for sig in Signature.objects.all(): sig.delete() class Migration(migrations.Migration): dependencies = [ ('recipes', '0045_update_action_hashes'), ] operations = [ # This function as both a forward and reverse migration migrations.RunPython(remove_signatures, remove_signatures), ]
""" Removes signatures, so they can be easily recreated during deployment. This migration is intended to be used between "eras" of signatures. As the serialization format of recipes changes, the signatures need to also change. This could be handled automatically, but it is easier to deploy if we just remove everything in a migration, and allow the normal processes to regenerate the signatures. """ # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def remove_signatures(apps, schema_editor): Recipe = apps.get_model('recipes', 'Recipe') Action = apps.get_model('recipes', 'Action') Signature = apps.get_model('recipes', 'Signature') for recipe in Recipe.objects.exclude(signature=None): sig = recipe.signature recipe.signature = None recipe.save() sig.delete() for action in Action.objects.exclude(signature=None): sig = action.signature action.signature = None action.save() action.delete() for sig in Signature.objects.all(): sig.delete() class Migration(migrations.Migration): dependencies = [ ('recipes', '0045_update_action_hashes'), ] operations = [ # This function as both a forward and reverse migration migrations.RunPython(remove_signatures, remove_signatures), ]
Include south migration in package.
#!/usr/bin/env python from setuptools import setup def read(name): from os import path return open(path.join(path.dirname(__file__), name)).read() setup( name='django-facebook-auth', version='3.6.1', description="Authorisation app for Facebook API.", long_description=read("README.rst"), maintainer="Tomasz Wysocki", maintainer_email="tomasz@wysocki.info", install_requires=( 'celery', 'Django<1.8', 'facepy>=1.0.3', ), packages=[ 'facebook_auth', 'facebook_auth.migrations', 'facebook_auth.management', 'facebook_auth.management.commands', 'facebook_auth.south_migrations', ], )
#!/usr/bin/env python from setuptools import setup def read(name): from os import path return open(path.join(path.dirname(__file__), name)).read() setup( name='django-facebook-auth', version='3.6.0', description="Authorisation app for Facebook API.", long_description=read("README.rst"), maintainer="Tomasz Wysocki", maintainer_email="tomasz@wysocki.info", install_requires=( 'celery', 'Django<1.8', 'facepy>=1.0.3', ), packages=[ 'facebook_auth', 'facebook_auth.migrations', 'facebook_auth.management', 'facebook_auth.management.commands', ], )
Use consistent terminology in tests as in the README
/* global describe, it */ const should = require('should') const cb = require('../index') const fs = require('fs') describe('A valid proof converted to binary and back ', function () { describe('Using test1.json', function () { it('should return proof equal to original JSON', function (done) { fs.readFile('./test/json/test1.json', 'utf-8', function (err, jsonSample) { should.not.exist(err) should.exist(jsonSample) cb.objectToBinary(jsonSample, function (err, proofBinary) { should.not.exist(err) should.exist(proofBinary) cb.binaryToObject(proofBinary, function (err, proofObject) { should.not.exist(err) should.exist(proofObject) jsonSample = jsonSample.replace(/(\r\n|\n|\r| )/gm, '') // remove any whitespace/cf/lf let resultJSON = JSON.stringify(proofObject) resultJSON.should.equal(jsonSample) done() }) }) }) }) }) })
/* global describe, it */ const should = require('should') const cb = require('../index') const fs = require('fs') describe('Testing valid format receipts should convert to CHP and back to same source JSON ', function () { describe('Using test1.json - ', function () { it('JSON >> CHP >> JSON should return result equal to origin JSON', function (done) { fs.readFile('./test/json/test1.json', 'utf-8', function (err, sourceFileJSON) { should.not.exist(err) should.exist(sourceFileJSON) cb.objectToBinary(sourceFileJSON, function (err, chpData) { should.not.exist(err) should.exist(chpData) cb.binaryToObject(chpData, function (err, resultObject) { should.not.exist(err) should.exist(resultObject) sourceFileJSON = sourceFileJSON.replace(/(\r\n|\n|\r| )/gm, '') // remove any whitespace/cf/lf let resultJSON = JSON.stringify(resultObject) resultJSON.should.equal(sourceFileJSON) done() }) }) }) }) }) })
Load config file only once
import glob, json, os, readline, sys def complete_filename(text, state): return (glob.glob(text+'*')+[None])[state] class PlayoffSettings: def __init__(self): self.settings = None self.interactive = False self.settings_file = None if len(sys.argv) > 1: self.settings_file = sys.argv[1] else: self.interactive = True def load(self): if self.settings_file is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete_filename) self.settings_file = raw_input('JSON settings file: ') if self.settings is None: self.settings = json.load(open(self.settings_file)) def has_section(self, key): self.load() return key in self.settings def get(self, *keys): self.load() section = self.settings for key in keys: section = section[key] return section
import glob, json, os, readline, sys def complete_filename(text, state): return (glob.glob(text+'*')+[None])[state] class PlayoffSettings: def __init__(self): self.interactive = False self.settings_file = None if len(sys.argv) > 1: self.settings_file = sys.argv[1] else: self.interactive = True def load(self): if self.settings_file is None: readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete_filename) self.settings_file = raw_input('JSON settings file: ') self.settings = json.load(open(self.settings_file)) def has_section(self, key): self.load() return key in self.settings def get(self, *keys): self.load() section = self.settings for key in keys: section = section[key] return section
TASK: Package TS implement must return null on exception
<?php namespace Neos\MarketPlace\TypoScriptObjects; /* * This file is part of the Neos.MarketPlace package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use TYPO3\Flow\Annotations as Flow; use Packagist\Api\Client; use Packagist\Api\Result\Package; use TYPO3\Flow\Log\SystemLoggerInterface; use TYPO3\TypoScript\TypoScriptObjects\AbstractArrayTypoScriptObject; /** * Package TypoScript Implementation * * @api */ class PackageImplementation extends AbstractArrayTypoScriptObject { /** * @var SystemLoggerInterface * @Flow\Inject */ protected $systemLogger; /** * @return string */ public function getName() { return $this->tsValue('name'); } /** * Evaluate this TypoScript object and return the result * * @return Package|null */ public function evaluate() { try { $client = new Client(); return $client->get($this->getName()); } catch (\Exception $exception) { $this->systemLogger->logException($exception); return null; } } }
<?php namespace Neos\MarketPlace\TypoScriptObjects; /* * This file is part of the Neos.MarketPlace package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Packagist\Api\Client; use Packagist\Api\Result\Package; use TYPO3\TypoScript\TypoScriptObjects\AbstractArrayTypoScriptObject; /** * Package TypoScript Implementation * * @api */ class PackageImplementation extends AbstractArrayTypoScriptObject { /** * @return string */ public function getName() { return $this->tsValue('name'); } /** * Evaluate this TypoScript object and return the result * * @return mixed */ public function evaluate() { $client = new Client(); return $client->get($this->getName()); } }
Fix junit - By removing retarded stuffs from taskcard class
package seedu.address.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.address.model.task.ReadOnlyTask; public class TaskCard extends UiPart<Region> { private static final String FXML = "TaskListCard.fxml"; @FXML private HBox cardPane; @FXML private Label name; @FXML private Label id; @FXML private Label date; @FXML private Label info; @FXML private Label priority; @FXML private FlowPane tags; public TaskCard(ReadOnlyTask task, int displayedIndex) { super(FXML); name.setText(task.getTaskName().taskName); id.setText(displayedIndex + ". "); date.setText(task.getDate().value); info.setText(task.getInfo().value); priority.setText(task.getPriority().value); initTags(task); } private void initTags(ReadOnlyTask task) { task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } }
package seedu.address.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.address.model.task.ReadOnlyTask; public class TaskCard extends UiPart<Region> { private static final String FXML = "TaskListCard.fxml"; @FXML private HBox cardPane; @FXML private Label name; @FXML private Label id; @FXML private Label date; @FXML private Label info; @FXML private Label priority; @FXML private FlowPane tags; public TaskCard(ReadOnlyTask task, int displayedIndex) { super(FXML); name.setText(task.getTaskName().taskName); id.setText(displayedIndex + ". "); date.setText("Deadline: " + task.getDate().value); info.setText("Information : " + task.getInfo().value); priority.setText("Priority Level : " + task.getPriority().value); initTags(task); } private void initTags(ReadOnlyTask task) { task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } }
Fix the current active template detection
'use strict'; angular.module('seblucas.slGridListToggle', []) .directive('slGridListToggle', function() { return { restrict: 'E', require: '^ngModel', scope: { templatePrefix: '=' }, template: '<div class="btn-group btn-group-lg pull-right"> \ <button ng-repeat="item in toggles" type="button" class="btn btn-default" ng-class="{active: isTemplateActive(item)}" ng-click="toggleTemplate(item)"> \ <span class="glyphicon glyphicon-{{item}}"></span> \ </button> \ </div>', link: function(scope, element, attrs, ngModel) { scope.toggles = ['th', 'list']; ngModel.$render = function() { scope.currentTemplate = ngModel.$modelValue; }; scope.toggleTemplate = function(value) { scope.currentTemplate = scope.templatePrefix + value +'.html'; ngModel.$setViewValue(scope.currentTemplate); }; scope.isTemplateActive = function(value) { return scope.currentTemplate.indexOf ('.' + value + '.html') > 0; }; } }; });
'use strict'; angular.module('seblucas.slGridListToggle', []) .directive('slGridListToggle', function() { return { restrict: 'E', require: '^ngModel', scope: { templatePrefix: '=' }, template: '<div class="btn-group btn-group-lg pull-right"> \ <button ng-repeat="item in toggles" type="button" class="btn btn-default" ng-class="{active: isTemplateActive(item)}" ng-click="toggleTemplate(item)"> \ <span class="glyphicon glyphicon-{{item}}"></span> \ </button> \ </div>', link: function(scope, element, attrs, ngModel) { scope.toggles = ['th', 'list']; ngModel.$render = function() { scope.currentTemplate = ngModel.$modelValue; }; scope.toggleTemplate = function(value) { scope.currentTemplate = scope.templatePrefix + value +'.html'; ngModel.$setViewValue(scope.currentTemplate); }; scope.isTemplateActive = function(value) { return scope.currentTemplate.indexOf (value) > 0; }; } }; });
Remove the relevant list item from the AppView after deleting a resource
$(function() { window.resources = new ResourceList; window.AppView = Backbone.View.extend({ el: $('#app'), resourceTemplate: _.template($('#resourceTemplate').html()), initialize: function() { _.bindAll(this, 'addResource', 'refreshResources', 'loadResource', 'changeResources', 'removeResource'); resources.bind('add', this.addResource); resources.bind('change', this.changeResources); resources.bind('remove', this.removeResource); resources.bind('refresh', this.refreshResources); resources.fetch(); }, addResource: function(resource) { var html = this.resourceTemplate({ id: resource.elementID(), url: resource.url(), name: resource.get('name') }); this.$("#resourceList").append(html); }, refreshResources: function() { resources.each(this.addResource); Backbone.history.start() }, changeResources: function() { this.$("#resourceList").html(''); resources.each(this.addResource); }, removeResource: function(model) { this.$("#" + model.elementID()).remove(); } }); });
$(function() { window.resources = new ResourceList; window.AppView = Backbone.View.extend({ el: $('#app'), resourceTemplate: _.template($('#resourceTemplate').html()), initialize: function() { _.bindAll(this, 'addResource', 'refreshResources', 'loadResource', 'changeResources'); resources.bind('add', this.addResource); resources.bind('change', this.changeResources); resources.bind('remove', this.removeResource); resources.bind('refresh', this.refreshResources); resources.fetch(); }, addResource: function(resource) { console.log(resource); console.log(resource.elementID); var html = this.resourceTemplate({ id: resource.elementID(), url: resource.url(), name: resource.get('name') }); this.$("#resourceList").append(html); }, refreshResources: function() { resources.each(this.addResource); Backbone.history.start() }, changeResources: function() { this.$("#resourceList").html(''); resources.each(this.addResource); }, removeResource: function(models) { console.log(models); console.log('remove resource event handler'); } }); });
Fix tests up to recent Enum change
'use strict'; var isError = require('es5-ext/lib/Error/is-error'); module.exports = function (t, a) { var week = t.create('Enumweektest', ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']); a(week('MO'), 'MO', "Valid"); a.throws(function () { week('FOO'); }, "Invalid"); return { "Is": function (a) { a(week.is({ toString: function () { return 'MO'; } }), false, "Not string"); a(week.is('TU'), true, "Option"); a(week.is('FOO'), false, "Other string"); }, "Normalize": function () { a(week.normalize('MO'), 'MO', "Valid"); a(week.normalize('FOO'), null, "Invalid"); a(week.normalize({ toString: function () { return 'MO'; } }), 'MO', "Coercible"); a(week.normalize({}), null, "Invalid #2"); }, "Validate": function () { a(week.validate('MO'), null, "Valid"); a(isError(week.validate('FOO')), true, "Invalid"); a(week.validate({ toString: function () { return 'MO'; } }), null, "Coercible"); a(isError(week.validate({})), true, "Invalid #2"); } }; };
'use strict'; var isError = require('es5-ext/lib/Error/is-error'); module.exports = function (t, a) { var week = t.create('Enumweektest', { options: ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'] }); a(week('MO'), 'MO', "Valid"); a.throws(function () { week('FOO'); }, "Invalid"); return { "Is": function (a) { a(week.is({ toString: function () { return 'MO'; } }), false, "Not string"); a(week.is('TU'), true, "Option"); a(week.is('FOO'), false, "Other string"); }, "Normalize": function () { a(week.normalize('MO'), 'MO', "Valid"); a(week.normalize('FOO'), null, "Invalid"); a(week.normalize({ toString: function () { return 'MO'; } }), 'MO', "Coercible"); a(week.normalize({}), null, "Invalid #2"); }, "Validate": function () { a(week.validate('MO'), null, "Valid"); a(isError(week.validate('FOO')), true, "Invalid"); a(week.validate({ toString: function () { return 'MO'; } }), null, "Coercible"); a(isError(week.validate({})), true, "Invalid #2"); } }; };
Use callback(null, file) when pushing only one file
'use strict'; var postcssCached = require('postcss-cached'); var through = require('through2'); var applySourceMap = require('vinyl-sourcemaps-apply'); var gulpUtil = require('gulp-util'); module.exports = function(options) { options = Object(options); var postcssCachedInstance = postcssCached(); var gulpPlugin = through.obj(function(file, encoding, callback) { var fileOptions = Object.create(options); fileOptions.from = file.path; fileOptions.map = fileOptions.map || file.sourceMap; try { var result = postcssCachedInstance .process(file.contents.toString('utf8'), fileOptions); file.contents = new Buffer(result.css); if (fileOptions.map) { applySourceMap(file, result.map); } callback(null, file); } catch(e) { callback(new gulpUtil.PluginError('gulp-postcss-cached', e)); } }); gulpPlugin.use = function(postcssPlugin) { postcssCachedInstance.use(postcssPlugin); return this; }; return gulpPlugin; };
'use strict'; var postcssCached = require('postcss-cached'); var through = require('through2'); var applySourceMap = require('vinyl-sourcemaps-apply'); var gulpUtil = require('gulp-util'); module.exports = function(options) { options = Object(options); var postcssCachedInstance = postcssCached(); var gulpPlugin = through.obj(function(file, encoding, callback) { var fileOptions = Object.create(options); fileOptions.from = file.path; fileOptions.map = fileOptions.map || file.sourceMap; try { var result = postcssCachedInstance .process(file.contents.toString('utf8'), fileOptions); file.contents = new Buffer(result.css); if (fileOptions.map) { applySourceMap(file, result.map); } this.push(file); callback(); } catch(e) { callback(new gulpUtil.PluginError('gulp-postcss-cached', e)); } }); gulpPlugin.use = function(postcssPlugin) { postcssCachedInstance.use(postcssPlugin); return this; }; return gulpPlugin; };
Use of register_blueprint will be deprecated, why not upgrade?
from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") app.blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
from sanic import response from sanic import Sanic from sanic.blueprints import Blueprint # Usage # curl -H "Host: example.com" localhost:8000 # curl -H "Host: sub.example.com" localhost:8000 # curl -H "Host: bp.example.com" localhost:8000/question # curl -H "Host: bp.example.com" localhost:8000/answer app = Sanic() bp = Blueprint("bp", host="bp.example.com") @app.route('/', host=["example.com", "somethingelse.com", "therestofyourdomains.com"]) async def hello(request): return response.text("Some defaults") @app.route('/', host="example.com") async def hello(request): return response.text("Answer") @app.route('/', host="sub.example.com") async def hello(request): return response.text("42") @bp.route("/question") async def hello(request): return response.text("What is the meaning of life?") @bp.route("/answer") async def hello(request): return response.text("42") app.register_blueprint(bp) if __name__ == '__main__': app.run(host="0.0.0.0", port=8000)
Undo change that did not fix issue
# -*- coding: utf-8 -*- """ This module is used to manage optional dependencies. Example usage:: from birdy.dependencies import ipywidgets as widgets """ import warnings from .exceptions import IPythonWarning # TODO: we ignore warnings for now. They are only needed when birdy is used in a notebook, # but we currently don't know how to handle this (see #89 and #138). warnings.filterwarnings('ignore', category=IPythonWarning) try: import ipywidgets except ImportError: ipywidgets = None warnings.warn('Jupyter Notebook is not supported. Please install *ipywidgets*.', IPythonWarning) try: import IPython except ImportError: IPython = None warnings.warn('IPython is not supported. Please install *ipython*.', IPythonWarning) try: import ipyleaflet except ImportError: ipyleaflet = None warnings.warn('Ipyleaflet is not supported. Please install *ipyleaflet*.', IPythonWarning)
# -*- coding: utf-8 -*- """ This module is used to manage optional dependencies. Example usage:: from birdy.dependencies import ipywidgets as widgets """ import warnings from .exceptions import IPythonWarning # TODO: we ignore warnings for now. They are only needed when birdy is used in a notebook, # but we currently don't know how to handle this (see #89 and #138). warnings.filterwarnings('ignore', category=IPythonWarning) try: import ipywidgets except ImportError: ipywidgets = None warnings.warn('Jupyter Notebook is not supported. Please install *ipywidgets*.', IPythonWarning) try: import IPython except ImportError: IPython = None warnings.warn('IPython is not supported. Please install *ipython*.', IPythonWarning) try: import ipyleaflet # noqa: F401 except ImportError: ipyleaflet = None warnings.warn('Ipyleaflet is not supported. Please install *ipyleaflet*.', IPythonWarning)
Switch to keyup to repaint any time the block is changed.
function CodeBlockDefinition() { window.wagtailStreamField.blocks.StructBlockDefinition.apply(this, arguments); } CodeBlockDefinition.prototype.render = function(placeholder, prefix, initialState, initialError) { var block = window.wagtailStreamField.blocks.StructBlockDefinition.prototype.render.apply( this, arguments ); var languageField = $(document).find('#' + prefix + '-language'); var codeField = $(document).find('#' + prefix + '-code'); var targetField = $(document).find('#' + prefix + '-target'); function updateLanguage() { var languageCode = languageField.val(); targetField.removeClass().addClass('language-' + languageCode); prismRepaint(); } function prismRepaint() { Prism.highlightElement(targetField[0]); } function populateTargetCode() { var codeText = codeField.val(); targetField.text(codeText); prismRepaint(targetField); } updateLanguage(); populateTargetCode(); languageField.on('change', updateLanguage); codeField.on('keyup', populateTargetCode); return block; } window.telepath.register('wagtailcodeblock.blocks.CodeBlock', CodeBlockDefinition);
function CodeBlockDefinition() { window.wagtailStreamField.blocks.StructBlockDefinition.apply(this, arguments); } CodeBlockDefinition.prototype.render = function(placeholder, prefix, initialState, initialError) { var block = window.wagtailStreamField.blocks.StructBlockDefinition.prototype.render.apply( this, arguments ); var languageField = $(document).find('#' + prefix + '-language'); var codeField = $(document).find('#' + prefix + '-code'); var targetField = $(document).find('#' + prefix + '-target'); function updateLanguage() { var languageCode = languageField.val(); targetField.removeClass().addClass('language-' + languageCode); prismRepaint(); } function prismRepaint() { Prism.highlightElement(targetField[0]); } function populateTargetCode() { var codeText = codeField.val(); targetField.text(codeText); prismRepaint(targetField); } updateLanguage(); populateTargetCode(); languageField.on('change', updateLanguage); codeField.on('change', populateTargetCode); codeField.keypress(function() { prismRepaint(); }); return block; } window.telepath.register('wagtailcodeblock.blocks.CodeBlock', CodeBlockDefinition);
Reset back to using sqlite default. Add console.EmailBackend default
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'dr.sqlite3', }, } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.contenttypes', 'registration', 'test_app', ) DEBUG = True ALLOWED_HOSTS = ['*'] SECRET_KEY = '_' SITE_ID = 1 ROOT_URLCONF = 'test_app.urls' TEMPLATE_LOADERS = ( 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ACCOUNT_ACTIVATION_DAYS = 7 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# coding: utf-8 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'registration', }, } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.contenttypes', 'registration', 'test_app', ) DEBUG = True ALLOWED_HOSTS = ['*'] SECRET_KEY = 'aa2^x-^2u9(zaigih^7!3onca_rql1rnk6ec6=sahm*r$vd2-$)=5' SITE_ID = 1 ROOT_URLCONF = 'test_app.urls' TEMPLATE_LOADERS = ( 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ACCOUNT_ACTIVATION_DAYS = 7 EMAIL_HOST = "" EMAIL_HOST_PASSWORD = "" EMAIL_HOST_USER = "" EMAIL_PORT = "" EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = ""
Remove unused classes in btc ticker.
import loadTemplate from '../../../utils/loadTemplate'; import baseVw from '../../baseVw'; import { getExchangeRate } from '../../../utils/currency'; import app from '../../../app'; const RATE_EXPIRY_S = '300'; export default class extends baseVw { constructor(options = {}) { super({ className: 'aboutBTCTicker', ...options, }); this.listenTo(app.settings, 'change:localCurrency', this.updatePrice); } get localCurrency() { return app.settings.get('localCurrency'); } getCurrentPrice() { return getExchangeRate(this.localCurrency); } updatePrice() { const latestPrice = this.getCurrentPrice(); if (latestPrice !== this.currentBTCPrice) { this.currentBTCPrice = latestPrice; this.render(); } } remove() { clearInterval(this.refreshCode); super.remove(); } render() { if (this.refreshCode == null) { this.refreshCode = setInterval(() => this.updatePrice(), RATE_EXPIRY_S * 1000); } if (this.currentBTCPrice == null) { this.currentBTCPrice = this.getCurrentPrice(); } loadTemplate('modals/about/btcticker.html', (t) => { this.$el.html(t({ currentBTCPrice: this.currentBTCPrice, localCurrency: this.localCurrency, })); }); return this; } }
import loadTemplate from '../../../utils/loadTemplate'; import baseVw from '../../baseVw'; import { getExchangeRate } from '../../../utils/currency'; import app from '../../../app'; const RATE_EXPIRY_S = '300'; export default class extends baseVw { constructor(options = {}) { super({ className: 'aboutBTCTicker pureFlex alwaysFirst', ...options, }); this.listenTo(app.settings, 'change:localCurrency', this.updatePrice); } get localCurrency() { return app.settings.get('localCurrency'); } getCurrentPrice() { return getExchangeRate(this.localCurrency); } updatePrice() { const latestPrice = this.getCurrentPrice(); if (latestPrice !== this.currentBTCPrice) { this.currentBTCPrice = latestPrice; this.render(); } } remove() { clearInterval(this.refreshCode); super.remove(); } render() { if (this.refreshCode == null) { this.refreshCode = setInterval(() => this.updatePrice(), RATE_EXPIRY_S * 1000); } if (this.currentBTCPrice == null) { this.currentBTCPrice = this.getCurrentPrice(); } loadTemplate('modals/about/btcticker.html', (t) => { this.$el.html(t({ currentBTCPrice: this.currentBTCPrice, localCurrency: this.localCurrency, })); }); return this; } }
Fix to actually get status from request
<?php defined('SYSPATH') or die('No direct script access.'); class Kohana_Error_Exception { public static function handler(Exception $e) { if (Kohana::$environment === Kohana::DEVELOPMENT) { Kohana_Exception::handler($e); } // It's a nice time to log :) Kohana::$log->add(Kohana_Log::ERROR, Kohana_Exception::text($e)); if ( ! defined('SUPPRESS_REQUEST')) { $request = array( // Get status from current request 'action' => Request::initial()->response()->status(), // If exception has a message this can be passed on 'message' => rawurlencode($e->getMessage()), ); // Override status if HTTP_Exception thrown if ($e instanceof HTTP_Exception) { $request['action'] = $e->getCode(); } echo Request::factory(Route::get('kohana_error')->uri($request)) ->execute() ->send_headers() ->response; } } }
<?php defined('SYSPATH') or die('No direct script access.'); class Kohana_Error_Exception { public static function handler(Exception $e) { if (Kohana::$environment === Kohana::DEVELOPMENT) { Kohana_Exception::handler($e); } // It's a nice time to log :) Kohana::$log->add(Kohana_Log::ERROR, Kohana_Exception::text($e)); if ( ! defined('SUPPRESS_REQUEST')) { $request = array( // Get status from current request 'action' => Request::current()->status(), // If exception has a message this can be passed on 'message' => rawurlencode($e->getMessage()), ); // Override status if HTTP_Exception thrown if ($e instanceof HTTP_Exception) { $request['action'] = $e->getCode(); } echo Request::factory(Route::get('kohana_error')->uri($request)) ->execute() ->send_headers() ->response; } } }
Document that Password uses PBKDF2 internally
// Package password contains functions for securely storing // and checking passwords. // // Passwords are encoded using a per-password salt and then // hashed using PBKDF2 with the chosen algorithm (sha256 by default). // Password provides the Check() method for verifying that // the given plaintext matches the encoded password. This // method is not vulnerable to timing attacks. // // Password objects can be stored directly by Gondola's ORM. // // // "foo" is the username, "bar" is the password. // type User struct { // UserId int64 `orm:",primary_key,auto_increment"` // Username string // Password password.Password // } // // Creating a new user // user := &User{Username:"foo", Password: password.New("bar")} // // o is a gnd.la/orm.Orm object // o.MustSave(user) // // Signin in an existing user // var user *User // if err := o.One(orm.Eq("Username", "foo"), &user); err == nil { // if user.Password.Check("bar") == nil { // // user has provided the correct password // } // } // // Password objects can also be stored on anything that accepts strings. See // the examples to learn how to manually store and verify a password. package password
// Package password contains functions for securely storing // and checking passwords. // // Passwords are encoded using a per-password salt and then // hashed with the chosen algorithm (sha256 by default). // Password provides the Check() method for verifying that // the given plaintext matches the encoded password. This // method is not vulnerable to timing attacks. // // Password objects can be stored directly by Gondola's ORM. // // // "foo" is the username, "bar" is the password. // type User struct { // UserId int64 `orm:",primary_key,auto_increment"` // Username string // Password password.Password // } // // Creating a new user // user := &User{Username:"foo", Password: password.New("bar")} // // o is a gnd.la/orm.Orm object // o.MustSave(user) // // Signin in an existing user // var user *User // if err := o.One(orm.Eq("Username", "foo"), &user); err == nil { // if user.Password.Check("bar") == nil { // // user has provided the correct password // } // } // // Password objects can also be stored on anything that accepts strings. See // the examples to learn how to manually store and verify a password. package password
Remove name from shows because we don't use it any more
<?php include( '../config.php' ); $url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes; $data = file_get_contents( $url ); $shows = new SimpleXMLElement( $data ); $items = array(); foreach( $shows->channel->item as $show ): preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches ); $dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) ); if( !isset( $items[ $dateString ] ) ): $items[ $dateString ] = array(); endif; $item = array(); $item[ 'image' ] = '/images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) ); $items[ $dateString ][] = $item; endforeach; header( 'Access-Control-Allow-Origin: *' ); header( 'Content-Type: application/json' ); echo json_encode( $items );
<?php include( '../config.php' ); $url = 'http://www.myepisodes.com/rss.php?feed=mylist&uid=mirrorer&pwdmd5=' . $myEpisodes; $data = file_get_contents( $url ); $shows = new SimpleXMLElement( $data ); $items = array(); foreach( $shows->channel->item as $show ): preg_match( '#\[(.+?)\]\[(.+?)\]\[(.+?)\]\[(.+?)\]#mis', $show->title, $matches ); $dateString = date( 'Y-m-d', strtotime( $matches[ 4 ] ) ); if( !isset( $items[ $dateString ] ) ): $items[ $dateString ] = array(); endif; $item = array(); $item[ 'image' ] = '/images/?query=' . preg_replace( '#\s+#mis', '-', strtolower( trim( $matches[ 1 ] ) ) ); $item[ 'name' ] = trim( $matches[ 1 ] ); $items[ $dateString ][] = $item; endforeach; header( 'Access-Control-Allow-Origin: *' ); header( 'Content-Type: application/json' ); echo json_encode( $items );
Add email address and proxy policy to troupes
define([ "jquery", "backbone", "backform" ], function( $, Backbone, Backform) { var Form = Backform.Form.extend({ fields: [ {name: "name", label: "Name", control: "input"}, {name: "shortname", label: "Short Name", control: "input"}, {name: "shortdescription", label: "Short Public Description", control: "input"}, {name: "location", label: "Location", control: "input"}, {name: "staffemail", label: "Staff Email Address", control: "input"}, {control: "spacer"}, {name: "description", label: "Long Public Description", control: "textarea"}, {name: "proxypolicy", label: "Policies for Proxied Characters", control: "textarea"}, //{control: "button", label: "Add New"}, ] }); return Form; } );
define([ "jquery", "backbone", "backform" ], function( $, Backbone, Backform) { var Form = Backform.Form.extend({ fields: [ {name: "name", label: "Name", control: "input"}, {name: "shortname", label: "Short Name", control: "input"}, {name: "shortdescription", label: "Short Public Description", control: "input"}, {name: "location", label: "Location", control: "input"}, {control: "spacer"}, {name: "description", label: "Long Public Description", control: "textarea"}, //{control: "button", label: "Add New"}, ] }); return Form; } );
Sort env vars by descending length to prevent partial replacement Fixes #8
#!/usr/bin/env node --harmony import spawn from "cross-spawn"; import os from "os"; import { exec } from "child_process"; import exit from 'exit'; function normalize( args, isWindows ) { return args.map( arg => { Object.keys( process.env ) .sort( ( x, y ) => x.length < y.length ) // sort by descending length to prevent partial replacement .forEach( key => { const regex = new RegExp( `\\$${ key }|%${ key }%`, "i" ); arg = arg.replace( regex, process.env[ key ] ); } ); return arg; } ) } let args = process.argv.slice( 2 ); if ( args.length === 1 ) { const [ command ] = normalize( args ); const proc = exec( command, ( error, stdout, stderr ) => { if ( error ) { console.error( `exec error: ${ error }` ); return; } process.stdout.write( stdout ); process.stderr.write( stderr ); exit(proc.code); }); } else { args = normalize( args ); const command = args.shift(); const proc = spawn.sync( command, args, { stdio: "inherit" } ); exit(proc.status); }
#!/usr/bin/env node --harmony import spawn from "cross-spawn"; import os from "os"; import { exec } from "child_process"; import exit from 'exit'; function normalize( args, isWindows ) { return args.map( arg => { Object.keys( process.env ).forEach( key => { const regex = new RegExp( `\\$${ key }|%${ key }%`, "i" ); arg = arg.replace( regex, process.env[ key ] ); } ); return arg; } ) } let args = process.argv.slice( 2 ); if ( args.length === 1 ) { const [ command ] = normalize( args ); const proc = exec( command, ( error, stdout, stderr ) => { if ( error ) { console.error( `exec error: ${ error }` ); return; } process.stdout.write( stdout ); process.stderr.write( stderr ); exit(proc.code); }); } else { args = normalize( args ); const command = args.shift(); const proc = spawn.sync( command, args, { stdio: "inherit" } ); exit(proc.status); }
Use a Symbol for storing the prop cache where available.
// render modes export const NO_RENDER = { render: false }; export const SYNC_RENDER = { renderSync: true }; export const DOM_RENDER = { build: true }; export const EMPTY = {}; export const EMPTY_BASE = ''; // is this a DOM environment export const HAS_DOM = typeof document!=='undefined'; export const TEXT_CONTENT = !HAS_DOM || 'textContent' in document ? 'textContent' : 'nodeValue'; export const ATTR_KEY = typeof Symbol!=='undefined' ? Symbol('preactattr') : '__preactattr_'; export const UNDEFINED_ELEMENT = 'x-undefined-element'; // DOM properties that should NOT have "px" added when numeric export const NON_DIMENSION_PROPS = { boxFlex:1,boxFlexGroup:1,columnCount:1,fillOpacity:1,flex:1,flexGrow:1, flexPositive:1,flexShrink:1,flexNegative:1,fontWeight:1,lineClamp:1,lineHeight:1, opacity:1,order:1,orphans:1,strokeOpacity:1,widows:1,zIndex:1,zoom:1 };
// render modes export const NO_RENDER = { render: false }; export const SYNC_RENDER = { renderSync: true }; export const DOM_RENDER = { build: true }; export const EMPTY = {}; export const EMPTY_BASE = ''; // is this a DOM environment export const HAS_DOM = typeof document!=='undefined'; export const TEXT_CONTENT = !HAS_DOM || 'textContent' in document ? 'textContent' : 'nodeValue'; export const ATTR_KEY = '__preactattr_'; export const UNDEFINED_ELEMENT = 'x-undefined-element'; // DOM properties that should NOT have "px" added when numeric export const NON_DIMENSION_PROPS = { boxFlex:1,boxFlexGroup:1,columnCount:1,fillOpacity:1,flex:1,flexGrow:1, flexPositive:1,flexShrink:1,flexNegative:1,fontWeight:1,lineClamp:1,lineHeight:1, opacity:1,order:1,orphans:1,strokeOpacity:1,widows:1,zIndex:1,zoom:1 };
Return a Markup object when the host is not supported This might be an issue with the Markdown parser used by lektor (mistune), but when a Markup() object is returned, then regular links must also be marked as Markup() or they won't be escaped.
# -*- coding: utf-8 -*- """ lektor-embed-x ~~~~~~~~~~~~~~ Simply embed rich contents from popular sites in Lektor-generated pages :copyright: (c) 2016 by Khaled Monsoor :license: The MIT License """ from embedx import OnlineContent from lektor.pluginsystem import Plugin from markupsafe import Markup __version__ = '0.1.2' __author__ = 'Khaled Monsoor <k@kmonsoor.com>' class EmbedXMixin(object): def autolink(self, link, is_email): if is_email: return super(EmbedXMixin, self).autolink(link, True) else: try: content = OnlineContent(link) # print content.get_embed_code() return Markup(content.get_embed_code()) except (NotImplementedError, ValueError): print('This host or this specific content is not supported yet. link: {0}'.format(link)) return Markup(super(EmbedXMixin, self).autolink(link, False)) class EmbedXPlugin(Plugin): name = u'lektor-embed-x' description = u'Simply embed rich content from popular sites in Lektor-generated pages' def on_markdown_config(self, config, **extra): config.renderer_mixins.append(EmbedXMixin)
# -*- coding: utf-8 -*- """ lektor-embed-x ~~~~~~~~~~~~~~ Simply embed rich contents from popular sites in Lektor-generated pages :copyright: (c) 2016 by Khaled Monsoor :license: The MIT License """ from embedx import OnlineContent from lektor.pluginsystem import Plugin from markupsafe import Markup __version__ = '0.1.2' __author__ = 'Khaled Monsoor <k@kmonsoor.com>' class EmbedXMixin(object): def autolink(self, link, is_email): if is_email: return super(EmbedXMixin, self).autolink(link, True) else: try: content = OnlineContent(link) # print content.get_embed_code() return Markup(content.get_embed_code()) except (NotImplementedError, ValueError): print('This host or this specific content is not supported yet. link: {0}'.format(link)) return super(EmbedXMixin, self).autolink(link, False) class EmbedXPlugin(Plugin): name = u'lektor-embed-x' description = u'Simply embed rich content from popular sites in Lektor-generated pages' def on_markdown_config(self, config, **extra): config.renderer_mixins.append(EmbedXMixin)
Update to follow DTC website changes Now, entry title is optionnal and may be found in h3 HTML element. Entry content is mandatory and may be found in div[class="item-content"] HTML element. Moreover, the title may contain simple quotes (here, encoded) so the bridge have to decode first to apply format library function. In case we don't do that, the format function double encode the quote and something like &amp;#039; could appear.
<?php class DansTonChatBridge extends BridgeAbstract { const MAINTAINER = 'Astalaseven'; const NAME = 'DansTonChat Bridge'; const URI = 'https://danstonchat.com/'; const CACHE_TIMEOUT = 21600; //6h const DESCRIPTION = 'Returns latest quotes from DansTonChat.'; public function collectData(){ $html = getSimpleHTMLDOM(self::URI . 'latest.html') or returnServerError('Could not request DansTonChat.'); foreach($html->find('div.item') as $element) { $item = array(); $item['uri'] = $element->find('a', 0)->href; $item['title'] = 'DansTonChat ' . html_entity_decode($element->find('h3 a', 0)->plaintext, ENT_QUOTES); $item['content'] = $element->find('div.item-content a', 0)->innertext; $this->items[] = $item; } } }
<?php class DansTonChatBridge extends BridgeAbstract { const MAINTAINER = 'Astalaseven'; const NAME = 'DansTonChat Bridge'; const URI = 'https://danstonchat.com/'; const CACHE_TIMEOUT = 21600; //6h const DESCRIPTION = 'Returns latest quotes from DansTonChat.'; public function collectData(){ $html = getSimpleHTMLDOM(self::URI . 'latest.html') or returnServerError('Could not request DansTonChat.'); foreach($html->find('div.item') as $element) { $item = array(); $item['uri'] = $element->find('a', 0)->href; $item['title'] = 'DansTonChat ' . $element->find('a', 1)->plaintext; $item['content'] = $element->find('a', 0)->innertext; $this->items[] = $item; } } }
Fix typo in apparmor tests Signed-off-by: Ralf Haferkamp <6972bdd7dec75710593d62d13eab0eaf0ce26d83@suse.com>
package apparmor_test import ( "github.com/cri-o/cri-o/internal/config/apparmor" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) // The actual test suite var _ = t.Describe("Config", func() { var sut *apparmor.Config BeforeEach(func() { sut = apparmor.New() Expect(sut).NotTo(BeNil()) if !sut.IsEnabled() { Skip("AppArmor is disabled") } }) t.Describe("IsEnabled", func() { It("should be true per default", func() { // Given // When res := sut.IsEnabled() // Then Expect(res).To(BeTrue()) }) }) t.Describe("LoadProfile", func() { It("should succeed with unconfined", func() { // Given // When err := sut.LoadProfile("unconfined") // Then Expect(err).To(BeNil()) }) }) })
package apparmor_test import ( "github.com/cri-o/cri-o/internal/config/apparmor" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) // The actual test suite var _ = t.Describe("Config", func() { var sut *apparmor.Config BeforeEach(func() { sut = apparmor.New() Expect(sut).NotTo(BeNil()) if !sut.IsEnabled() { Skip("AppArmor is disabled") } }) t.Describe("IsEnabled", func() { It("should be true per default", func() { // Given // When res := sut.IsEnabled() // Then Expect(res).To(BeTrue()) }) }) t.Describe("LoadProfile", func() { It("should succeed with unconfied", func() { // Given // When err := sut.LoadProfile("unconfied") // Then Expect(err).To(BeNil()) }) }) })
Add Pin & Stripe Request classes
<?php /* * This file is part of the Omnipay package. * * (c) Adrian Macneil <adrian@adrianmacneil.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Omnipay\PayPal\Message; /** * PayPal Express Complete Authorize Request */ class ExpressCompleteAuthorizeRequest extends AuthorizeRequest { protected $paymentAction; public function getPaymentAction() { return $this->paymentAction; } public function setPaymentAction($value) { $this->paymentAction = $value; return $this; } public function getData() { $data = $this->getBaseData('DoExpressCheckoutPayment'); $this->validate(array('amount')); $data['PAYMENTREQUEST_0_PAYMENTACTION'] = $this->getPaymentAction(); $data['PAYMENTREQUEST_0_AMT'] = $this->getAmountDecimal(); $data['PAYMENTREQUEST_0_CURRENCYCODE'] = $this->getCurrency(); $data['PAYMENTREQUEST_0_DESC'] = $this->getDescription(); $data['TOKEN'] = $this->httpRequest->query->get('token'); $data['PAYERID'] = $this->httpRequest->query->get('PayerID'); return $data; } }
<?php /* * This file is part of the Omnipay package. * * (c) Adrian Macneil <adrian@adrianmacneil.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Omnipay\PayPal\Message; use Symfony\Component\HttpFoundation\Request as HttpRequest; /** * PayPal Express Complete Authorize Request */ class ExpressCompleteAuthorizeRequest extends AuthorizeRequest { protected $paymentAction; public function getPaymentAction() { return $this->paymentAction; } public function setPaymentAction($value) { $this->paymentAction = $value; return $this; } public function getData() { $data = $this->getBaseData('DoExpressCheckoutPayment'); $this->validate(array('amount')); $data['PAYMENTREQUEST_0_PAYMENTACTION'] = $this->getPaymentAction(); $data['PAYMENTREQUEST_0_AMT'] = $this->getAmountDecimal(); $data['PAYMENTREQUEST_0_CURRENCYCODE'] = $this->getCurrency(); $data['PAYMENTREQUEST_0_DESC'] = $this->getDescription(); $data['TOKEN'] = $this->httpRequest->query->get('token'); $data['PAYERID'] = $this->httpRequest->query->get('PayerID'); return $data; } }
Use the actual primary key value instead of the key name for updating/deleting.
<?php namespace Picqer\Financials\Exact\Persistance; trait Storable { public function save() { if ($this->exists()) { $this->fill($this->update()); } else { $this->fill($this->insert()); } return $this; } public function insert() { return $this->connection()->post($this->url, $this->json()); } public function update() { return $this->connection()->put($this->url . "(guid'" . $this->attributes[$this->primaryKey] . "')", $this->json()); } public function delete() { return $this->connection()->delete($this->url . "(guid'" . $this->attributes[$this->primaryKey] . "')"); } }
<?php namespace Picqer\Financials\Exact\Persistance; trait Storable { public function save() { if ($this->exists()) { $this->fill($this->update()); } else { $this->fill($this->insert()); } return $this; } public function insert() { return $this->connection()->post($this->url, $this->json()); } public function update() { return $this->connection()->put($this->url . "(guid'$this->primaryKey')", $this->json()); } public function delete() { return $this->connection()->delete($this->url . "(guid'$this->primaryKey')"); } }
Add a new 'count' utility function
#!/usr/bin/env python3 """Small utility functions for use in various places.""" __all__ = ["pick", "is_dunder", "convert_to_od", "counter_to_iterable", "count"] import collections import itertools def pick(arg, default): """Handler for default versus given argument.""" return default if arg is None else arg def is_dunder(name): """Return True if a __dunder__ name, False otherwise.""" return name[:2] == name[-2:] == "__" and "_" not in (name[2:3], name[-3:-2]) def convert_to_od(mapping, order): """Convert mapping to an OrderedDict instance using order.""" return collections.OrderedDict([(i, mapping[i]) for i in order]) def counter_to_iterable(counter): """Convert a counter to an iterable / iterator.""" for item in itertools.starmap(itertools.repeat, counter): yield from item def count(iterable): """Yield (item, count) two-tuples of the iterable.""" seen = [] full = list(iterable) for item in full: if item in seen: continue seen.append(item) yield (item, full.count(item))
#!/usr/bin/env python3 """Small utility functions for use in various places.""" __all__ = ["pick", "is_dunder", "convert_to_od", "counter_to_iterable"] import collections import itertools def pick(arg, default): """Handler for default versus given argument.""" return default if arg is None else arg def is_dunder(name): """Return True if a __dunder__ name, False otherwise.""" return name[:2] == name[-2:] == "__" and "_" not in (name[2:3], name[-3:-2]) def convert_to_od(mapping, order): """Convert mapping to an OrderedDict instance using order.""" return collections.OrderedDict([(i, mapping[i]) for i in order]) def counter_to_iterable(counter): """Convert a counter to an iterable / iterator.""" for item in itertools.starmap(itertools.repeat, counter): yield from item
Add idToken to graphql requests
import { GRAPHQL_URL } from 'constants'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import withScroll from 'scroll-behavior'; import ApolloClient, { createNetworkInterface } from 'apollo-client'; // import { Provider } from 'react-redux'; import { ApolloProvider } from 'react-apollo'; import createAppStore from './store'; import getRoutes from './routes'; import { checkLogin } from './actions'; const networkInterface = createNetworkInterface(GRAPHQL_URL); networkInterface.use([{ /* eslint-disable no-param-reassign */ applyMiddleware(req, next) { if (!req.options.headers) { req.options.headers = {}; // Create the header object if needed. } // get the authentication token from local storage if it exists const idToken = localStorage.getItem('idToken') || null; if (idToken) { req.options.headers.authorization = `Bearer '${idToken}`; } next(); }, /* eslint-enable no-param-reassign */ }]); const client = new ApolloClient({ networkInterface, }); const scrollBrowserHistory = withScroll(browserHistory); const store = createAppStore(scrollBrowserHistory, client); const history = syncHistoryWithStore(scrollBrowserHistory, store); checkLogin(store.dispatch); const rootEl = document.getElementById('app'); ReactDOM.render( <ApolloProvider store={store} client={client}> <Router history={history}>{getRoutes(store)}</Router> </ApolloProvider>, rootEl );
import { GRAPHQL_URL } from 'constants'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import withScroll from 'scroll-behavior'; import ApolloClient, { createNetworkInterface } from 'apollo-client'; // import { Provider } from 'react-redux'; import { ApolloProvider } from 'react-apollo'; import createAppStore from './store'; import getRoutes from './routes'; import { checkLogin } from './actions'; const networkInterface = createNetworkInterface(GRAPHQL_URL); const client = new ApolloClient({ networkInterface, }); const scrollBrowserHistory = withScroll(browserHistory); const store = createAppStore(scrollBrowserHistory, client); const history = syncHistoryWithStore(scrollBrowserHistory, store); checkLogin(store.dispatch); const rootEl = document.getElementById('app'); ReactDOM.render( <ApolloProvider store={store} client={client}> <Router history={history}>{getRoutes(store)}</Router> </ApolloProvider>, rootEl );
Add function to get the skeletal muscle result
from wcontrol.conf.config import BMI, BFP, MUSCLE class results(object): def __init__(self, control, gender): self.bmi = self.get_bmi(control.bmi) self.fat = self.get_fat(control.fat, gender) self.muscle = self.get_muscle(control.muscle, gender) def get_bmi(self, bmi): for limit, msg in BMI: if bmi <= limit: return msg def get_fat(self, fat, gender): for limit_w, limit_m, msg in BFP: if gender == 'Feminine' and fat <= limit_w: return msg if gender == 'Masculine' and fat <= limit_m: return msg def get_muscle(self, muscle, gender): for limit_w, limit_m, msg in MUSCLE: if gender == 'Feminine' and muscle <= limit_w: return msg if gender == 'Masculine' and muscle <= limit_m: return msg
from wcontrol.conf.config import BMI, BFP class results(object): def __init__(self, control, gender): self.bmi = self.get_bmi(control.bmi) self.fat = self.get_fat(control.fat, gender) def get_bmi(self, bmi): for limit, msg in BMI: if bmi <= limit: return msg def get_fat(self, fat, gender): for limit_w, limit_m, msg in BFP: if gender == 'Feminine' and fat <= limit_w: return msg if gender == 'Masculine' and fat <= limit_m: return msg
Use raw_id_fields for users and snippets.
from django.contrib import admin from cab.models import Language, Snippet, SnippetFlag class LanguageAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ['name']} class SnippetAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'author', 'rating_score', 'pub_date') list_filter = ('language',) date_hierarchy = 'pub_date' search_fields = ('author__username', 'title', 'description', 'code',) raw_id_fields = ('author',) class SnippetFlagAdmin(admin.ModelAdmin): list_display = ('snippet', 'flag') list_filter = ('flag',) actions = ['remove_and_ban'] raw_id_fields = ('snippet', 'user',) def remove_and_ban(self, request, queryset): for obj in queryset: obj.remove_and_ban() self.message_user(request, 'Snippets removed successfully') remove_and_ban.short_description = 'Remove snippet and ban user' admin.site.register(Language, LanguageAdmin) admin.site.register(Snippet, SnippetAdmin) admin.site.register(SnippetFlag, SnippetFlagAdmin)
from django.contrib import admin from cab.models import Language, Snippet, SnippetFlag class LanguageAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ['name']} class SnippetAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'author', 'rating_score', 'pub_date') list_filter = ('language',) date_hierarchy = 'pub_date' search_fields = ('author__username', 'title', 'description', 'code',) class SnippetFlagAdmin(admin.ModelAdmin): list_display = ('snippet', 'flag') list_filter = ('flag',) actions = ['remove_and_ban'] def remove_and_ban(self, request, queryset): for obj in queryset: obj.remove_and_ban() self.message_user(request, 'Snippets removed successfully') remove_and_ban.short_description = 'Remove snippet and ban user' admin.site.register(Language, LanguageAdmin) admin.site.register(Snippet, SnippetAdmin) admin.site.register(SnippetFlag, SnippetFlagAdmin)
Add blank space in email message
""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s\n') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s\n') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('\nThis election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
""" Glue some events together """ from django.conf import settings from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext as _ import helios.views, helios.signals import views def vote_cast_send_message(user, voter, election, cast_vote, **kwargs): ## FIXME: this doesn't work for voters that are not also users # prepare the message subject = _("%(election_name)s - vote cast") % {'election_name' : election.name} body = _('You have successfully cast a vote in\n\n%(election_name)s') % {'election_name' : election.name} body += _('Your ballot is archived at:\n\n%(cast_url)s') % {'cast_url' : helios.views.get_castvote_url(cast_vote)} if election.use_voter_aliases: body += _('This election uses voter aliases to protect your privacy.' 'Your voter alias is :\n\n%(voter_alias)s') % {'voter_alias' : voter.alias} body += """ -- %s """ % settings.SITE_TITLE # send it via the notification system associated with the auth system user.send_message(subject, body) helios.signals.vote_cast.connect(vote_cast_send_message) def election_tallied(election, **kwargs): pass helios.signals.election_tallied.connect(election_tallied)
Add the repos URL in Metadata
from setuptools import setup, find_packages import os # The version of the wrapped library is the starting point for the # version number of the python package. # In bugfix releases of the python package, add a '-' suffix and an # incrementing integer. # For example, a packaging bugfix release version 1.4.4 of the # js.jquery package would be version 1.4.4-1 . version = '3.3.1' def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() long_description = ( read('README.rst') + '\n' + read('js', 'amcharts', 'test_amcharts.txt') + '\n' + read('CHANGES.txt')) setup( name='js.amcharts', version=version, description="Fanstatic packaging of amCharts", long_description=long_description, classifiers=[], keywords='', author='Fanstatic Developers', author_email='fanstatic@googlegroups.com', license='BSD', url='https://github.com/securactive/js.amcharts', packages=find_packages(),namespace_packages=['js'], include_package_data=True, zip_safe=False, install_requires=[ 'fanstatic', 'setuptools', ], entry_points={ 'fanstatic.libraries': [ 'amcharts = js.amcharts:library', ], }, )
from setuptools import setup, find_packages import os # The version of the wrapped library is the starting point for the # version number of the python package. # In bugfix releases of the python package, add a '-' suffix and an # incrementing integer. # For example, a packaging bugfix release version 1.4.4 of the # js.jquery package would be version 1.4.4-1 . version = '3.3.1' def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() long_description = ( read('README.rst') + '\n' + read('js', 'amcharts', 'test_amcharts.txt') + '\n' + read('CHANGES.txt')) setup( name='js.amcharts', version=version, description="Fanstatic packaging of amCharts", long_description=long_description, classifiers=[], keywords='', author='Fanstatic Developers', author_email='fanstatic@googlegroups.com', license='BSD', packages=find_packages(),namespace_packages=['js'], include_package_data=True, zip_safe=False, install_requires=[ 'fanstatic', 'setuptools', ], entry_points={ 'fanstatic.libraries': [ 'amcharts = js.amcharts:library', ], }, )
Use strictEqual instead of equal
'use strict' /* eslint-env mocha */ const assert = require('assert') const { isValidEmail, getDomainPart, getLocalPart } = require('../index') describe('email-js', function () { describe('getLocalPart()', function () { it('returns the local part', function () { assert.strictEqual(getLocalPart('cake@example.org'), 'cake') assert.strictEqual(getLocalPart('cake.tower@gmail.com'), 'cake.tower') }) }) describe('getDomainPart()', function () { it('returns the domain', function () { assert.strictEqual(getDomainPart('cake@example.org'), 'example.org') assert.strictEqual(getDomainPart('cake.tower@gmail.com'), 'gmail.com') }) }) describe('isValidEmail()', function () { it('validates the email', function () { assert.strictEqual(isValidEmail('cake@example.org'), true) assert.strictEqual(isValidEmail('root@localhost'), true) assert.strictEqual(isValidEmail('root'), false) assert.strictEqual(isValidEmail('@localhost'), false) }) }) })
'use strict' /* eslint-env mocha */ const assert = require('assert') const { isValidEmail, getDomainPart, getLocalPart } = require('../index') describe('email-js', function () { describe('getLocalPart()', function () { it('returns the local part', function () { assert.equal(getLocalPart('cake@example.org'), 'cake') assert.equal(getLocalPart('cake.tower@gmail.com'), 'cake.tower') }) }) describe('getDomainPart()', function () { it('returns the domain', function () { assert.equal(getDomainPart('cake@example.org'), 'example.org') assert.equal(getDomainPart('cake.tower@gmail.com'), 'gmail.com') }) }) describe('isValidEmail()', function () { it('validates the email', function () { assert.equal(isValidEmail('cake@example.org'), true) assert.equal(isValidEmail('root@localhost'), true) assert.equal(isValidEmail('root'), false) assert.equal(isValidEmail('@localhost'), false) }) }) })
Tidy up info a little for the PluginModule popup edit form git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40389 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } function module_users_rank_info() { return array( 'name' => tra('Most Active Users'), 'description' => tra('Display the specified number of users and their score, starting from the one with the highest score.'), 'prefs' => array('feature_score'), 'params' => array(), 'common_params' => array('nonums', 'rows') ); } function module_users_rank($mod_reference, $module_params) { global $tikilib, $smarty; $users_rank = $tikilib->rank_users($mod_reference["rows"]); $smarty->assign('users_rank', $users_rank); }
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } function module_users_rank_info() { return array( 'name' => tra('Most-active Users'), 'description' => tra('Displays the specified number of users and their score, starting from the one with the highest score.'), 'prefs' => array('feature_score'), 'params' => array(), 'common_params' => array('nonums', 'rows') ); } function module_users_rank($mod_reference, $module_params) { global $tikilib, $smarty; $users_rank = $tikilib->rank_users($mod_reference["rows"]); $smarty->assign('users_rank', $users_rank); }
Increase max depth to 6 At 2, it only has enough depth to log in.
# -*- coding: utf-8 -*- """ Scrapy settings for a11y project For simplicity, this file contains only settings considered important or commonly used. You can find more settings consulting the documentation: http://doc.scrapy.org/en/latest/topics/settings.html http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html """ # Main settings used by crawler: handle with care! -------- SPIDER_MODULES = ['pa11ycrawler.spiders'] NEWSPIDER_MODULE = 'pa11ycrawler.spiders' DEFAULT_ITEM_CLASS = 'pa11ycrawler.items.A11yItem' # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'pa11ycrawler.pipelines.DuplicatesPipeline': 200, 'pa11ycrawler.pipelines.DropDRFPipeline': 250, 'pa11ycrawler.pipelines.Pa11yPipeline': 300, } # Other items you are likely to want to override --------------- CONCURRENT_REQUESTS = 16 CONCURRENT_REQUESTS_PER_DOMAIN = 8 COOKIES_DEBUG = False COOKIES_ENABLED = True DEPTH_LIMIT = 6 LOG_LEVEL = 'INFO' LOG_FORMAT = '%(asctime)s [%(levelname)s] [%(name)s]: %(message)s'
# -*- coding: utf-8 -*- """ Scrapy settings for a11y project For simplicity, this file contains only settings considered important or commonly used. You can find more settings consulting the documentation: http://doc.scrapy.org/en/latest/topics/settings.html http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html """ # Main settings used by crawler: handle with care! -------- SPIDER_MODULES = ['pa11ycrawler.spiders'] NEWSPIDER_MODULE = 'pa11ycrawler.spiders' DEFAULT_ITEM_CLASS = 'pa11ycrawler.items.A11yItem' # Configure item pipelines # See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'pa11ycrawler.pipelines.DuplicatesPipeline': 200, 'pa11ycrawler.pipelines.DropDRFPipeline': 250, 'pa11ycrawler.pipelines.Pa11yPipeline': 300, } # Other items you are likely to want to override --------------- CONCURRENT_REQUESTS = 16 CONCURRENT_REQUESTS_PER_DOMAIN = 8 COOKIES_DEBUG = False COOKIES_ENABLED = True DEPTH_LIMIT = 2 LOG_LEVEL = 'INFO' LOG_FORMAT = '%(asctime)s [%(levelname)s] [%(name)s]: %(message)s'
Refresh streams list when player is closed
import urllib.request import subprocess LIMIT = 10 PLAYER = 'vlc' STREAMS_URL = 'http://streams.twitch.tv/kraken/streams?limit='+str(LIMIT)+'&offset=0&game=Music&broadcaster_language=&on_site=1' while True: with urllib.request.urlopen(STREAMS_URL) as response: html = response.read().decode('utf8') i = 0 urls = [] for line in html.split(','): if 'status' in line: status = line.split('"')[-2] status = ''.join(i for i in status if ord(i)<128) #filter non ascii characters if 'display_name' in line: name = line.split('"')[-2] print(str(i) + ') ' + name + ' : ' + status) i += 1 if 'url' in line: url = line.split('"')[-2] urls.append(url) choice = LIMIT while (choice >= LIMIT): choice = int(input('Choose a stream\n')) cmd = ['livestreamer', urls[choice], 'audio'] if PLAYER != 'vlc': cmd.append('-p') cmd.append(PLAYER) subprocess.call(cmd, shell=False) print('\n\n\n')
import urllib.request import subprocess LIMIT = 10 PLAYER = 'vlc' url = 'http://streams.twitch.tv/kraken/streams?limit='+str(LIMIT)+'&offset=0&game=Music&broadcaster_language=&on_site=1' with urllib.request.urlopen(url) as response: html = response.read().decode('utf8') i = 0 urls = [] for line in html.split(','): if 'status' in line: status = line.split('"')[-2] status = ''.join(i for i in status if ord(i)<128) #filter non ascii characters if 'display_name' in line: name = line.split('"')[-2] print(str(i) + ') ' + name + ' : ' + status) i += 1 if 'url' in line: url = line.split('"')[-2] urls.append(url) choice = LIMIT while (choice >= LIMIT): choice = int(input('Choose a stream\n')) cmd = ['livestreamer', urls[choice], 'audio'] if PLAYER != 'vlc': cmd.append('-p') cmd.append(PLAYER) subprocess.Popen(cmd, shell=False)
Support absolute urls in ios icon meta
'use strict'; module.exports = appleLinkTags; var hasTarget = require('./has-target'); function appleLinkTags(manifest, config) { if (manifest.apple === false) { return []; } var links = []; var sizes; var rootURL = config.rootURL || '/'; var precomposed; if(manifest.apple && manifest.apple.precomposed) { precomposed = '-precomposed'; } else { precomposed = ''; } if (manifest.icons && manifest.icons.length) { for(var icon of manifest.icons) { if (!icon.targets || hasTarget(icon, 'apple')) { if (icon.sizes) { sizes = ` sizes="${icon.sizes}"` } else { sizes = ''; } if (/^https?:\/\//i.test(icon.src)) { rootURL = ''; } links.push(`<link rel="apple-touch-icon${precomposed}" href="${rootURL}${icon.src.replace(/^\//,'')}"${sizes}>`); } } } return links; }
'use strict'; module.exports = appleLinkTags; var hasTarget = require('./has-target'); function appleLinkTags(manifest, config) { if (manifest.apple === false) { return []; } var links = []; var sizes; var rootURL = config.rootURL || '/'; var precomposed; if(manifest.apple && manifest.apple.precomposed) { precomposed = '-precomposed'; } else { precomposed = ''; } if (manifest.icons && manifest.icons.length) { for(var icon of manifest.icons) { if (!icon.targets || hasTarget(icon, 'apple')) { if (icon.sizes) { sizes = ` sizes="${icon.sizes}"` } else { sizes = ''; } links.push(`<link rel="apple-touch-icon${precomposed}" href="${rootURL}${icon.src.replace(/^\//,'')}"${sizes}>`); } } } return links; }
Use NewBuildingsSearchForm as main page search form. intead of non-complete SearchForm.
from django.shortcuts import render from new_buildings.models import ResidentalComplex from new_buildings.forms import NewBuildingsSearchForm from feedback.models import Feedback def corporation_benefit_plan(request): return render(request, 'corporation_benefit_plan.html') def index(request): # Only 2 requests to DB feedbacks = Feedback.objects.all( )[:4].select_related().prefetch_related('social_media_links') # Only 2 requests to DB residental_complexes = ResidentalComplex.objects.filter( is_popular=True).prefetch_related('type_of_complex') context = { 'feedbacks': feedbacks, 'form': NewBuildingsSearchForm, 'residental_complexes': residental_complexes, } return render(request, 'index.html', context, ) def privacy_policy(request): return render(request, 'privacy_policy.html') def thanks(request): return render(request, 'thanks.html')
from django.shortcuts import render, render_to_response from django.template import RequestContext from new_buildings.models import Builder, ResidentalComplex, NewApartment from new_buildings.forms import SearchForm from feedback.models import Feedback def corporation_benefit_plan(request): return render(request, 'corporation_benefit_plan.html') def index(request): # Only 2 requests to DB feedbacks = Feedback.objects.all()[:4].select_related().prefetch_related('social_media_links') # Only 2 requests to DB residental_complexes = ResidentalComplex.objects.filter( is_popular=True).prefetch_related('type_of_complex') context = { 'feedbacks': feedbacks, 'form': SearchForm, 'residental_complexes': residental_complexes, } return render(request, 'index.html', context, ) def privacy_policy(request): return render(request, 'privacy_policy.html') def thanks(request): return render(request, 'thanks.html')
Extend the visible time after-click for a dropdown
import Ember from 'ember'; export default Ember.Controller.extend({ flashError: null, nextFlashError: null, showUserOptions: false, stepFlash: function() { this.set('flashError', this.get('nextFlashError')); this.set('nextFlashError', null); }, resetDropdownOption: function(controller, option) { controller.set(option, !controller.get(option)); if (controller.get(option)) { Ember.$(document).on('mousedown.useroptions', function() { Ember.run.later(function() { controller.set(option, false); }, 150); Ember.$(document).off('mousedown.useroptions'); }); } }, actions: { search: function(query) { this.transitionToRoute('search', {queryParams: {q: query}}); }, toggleUserOptions: function() { this.resetDropdownOption(this, 'showUserOptions'); }, }, });
import Ember from 'ember'; export default Ember.Controller.extend({ flashError: null, nextFlashError: null, showUserOptions: false, stepFlash: function() { this.set('flashError', this.get('nextFlashError')); this.set('nextFlashError', null); }, resetDropdownOption: function(controller, option) { controller.set(option, !controller.get(option)); if (controller.get(option)) { Ember.$(document).on('mousedown.useroptions', function() { Ember.run.later(function() { controller.set(option, false); }, 100); Ember.$(document).off('mousedown.useroptions'); }); } }, actions: { search: function(query) { this.transitionToRoute('search', {queryParams: {q: query}}); }, toggleUserOptions: function() { this.resetDropdownOption(this, 'showUserOptions'); }, }, });
Move property string to use a linked list.
package codechicken.lib.block.property; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import net.minecraft.block.properties.PropertyHelper; import java.util.*; /** * Created by covers1624 on 2/6/2016. */ public class PropertyString extends PropertyHelper<String> { private final List<String> valuesSet; public PropertyString(String name, Collection<String> values) { super(name, String.class); valuesSet = new LinkedList<String>(values); } public PropertyString(String name, String... values) { super(name, String.class); valuesSet = new LinkedList<String>(); Collections.addAll(valuesSet, values); } public List<String> values() { return ImmutableList.copyOf(valuesSet); } @Override public Collection<String> getAllowedValues() { return ImmutableList.copyOf(valuesSet); } @Override public Optional<String> parseValue(String value) { if (valuesSet.contains(value)) { return Optional.of(value); } return Optional.absent(); } @Override public String getName(String value) { return value; } }
package codechicken.lib.block.property; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import net.minecraft.block.properties.PropertyHelper; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; /** * Created by covers1624 on 2/6/2016. */ public class PropertyString extends PropertyHelper<String> { private final HashSet<String> valuesSet; public PropertyString(String name, Collection<String> values) { super(name, String.class); valuesSet = new HashSet<String>(values); } public PropertyString(String name, String... values) { super(name, String.class); valuesSet = new HashSet<String>(); Collections.addAll(valuesSet, values); } public List<String> values() { return Lists.newLinkedList(valuesSet); } @Override public Collection<String> getAllowedValues() { return ImmutableSet.copyOf(valuesSet); } @Override public Optional<String> parseValue(String value) { if (valuesSet.contains(value)) { return Optional.of(value); } return Optional.absent(); } @Override public String getName(String value) { return value; } }
Order methods line -> function -> class -> file.
<?hh // strict namespace HackPack\HackUnit\Event; use HackPack\HackUnit\Util\TraceItem; class Skip { public function __construct(private TraceItem $callSite) { } public function assertionLine() : ?int { return $this->callSite['line'] === -1 ? null : $this->callSite['line']; } public function testMethod() : ?string { return $this->callSite['function'] === '' ? null : $this->callSite['function']; } public function testClass() : ?string { return $this->callSite['class'] === '' ? null : $this->callSite['class']; } public function testFile() : ?string { return $this->callSite['file'] === '' ? null : $this->callSite['file']; } }
<?hh // strict namespace HackPack\HackUnit\Event; use HackPack\HackUnit\Util\TraceItem; class Skip { public function __construct(private TraceItem $callSite) { } public function testMethod() : ?string { return $this->callSite['function'] === '' ? null : $this->callSite['function']; } public function testClass() : ?string { return $this->callSite['class'] === '' ? null : $this->callSite['class']; } public function testFile() : ?string { return $this->callSite['file'] === '' ? null : $this->callSite['file']; } public function assertionLine() : ?int { return $this->callSite['line'] === -1 ? null : $this->callSite['line']; } }
Make publisher store emit the right event name
from flask_socketio import SocketIO from flask import current_app from zou.app import config host = config.KEY_VALUE_STORE["host"] port = config.KEY_VALUE_STORE["port"] redis_db = config.KV_EVENTS_DB_INDEX redis_url = "redis://%s:%s/%s" % (host, port, redis_db) socketio = None def publish(event, data): if socketio is not None: socketio.emit(event, data, namespace="/events") else: current_app.logger.error( "Publisher store not initialized, run init() befor emitting events" ) def init(): """ Initialize key value store that will be used for the event publishing. That way the main API takes advantage of Redis pub/sub capabilities to push events to the event stream API. """ global socketio socketio = SocketIO(message_queue=redis_url) return socketio
from flask_socketio import SocketIO from flask import current_app from zou.app import config host = config.KEY_VALUE_STORE["host"] port = config.KEY_VALUE_STORE["port"] redis_db = config.KV_EVENTS_DB_INDEX redis_url = "redis://%s:%s/%s" % (host, port, redis_db) socketio = None def publish(event, data): data = { "type": event, "data": data } if socketio is not None: socketio.emit("event", data, namespace="/events") else: current_app.logger.error( "Publisher store not initialized, run init() befor emitting events" ) def init(): """ Initialize key value store that will be used for the event publishing. That way the main API takes advantage of Redis pub/sub capabilities to push events to the event stream API. """ global socketio socketio = SocketIO(message_queue=redis_url) return socketio
Fix bug where public station podcast feed would not display when logged out
<?php class FeedsController extends Zend_Controller_Action { public function stationRssAction() { $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); if ((Application_Model_Preference::getStationPodcastPrivacy() && $this->getRequest()->getParam("sharing_token") != Application_Model_Preference::getStationPodcastDownloadKey()) && !RestAuth::verifyAuth(true, true, $this)) { $this->getResponse() ->setHttpResponseCode(401); return; } header('Content-Type: text/xml; charset=UTF-8'); echo Application_Service_PodcastService::createStationRssFeed(); } }
<?php class FeedsController extends Zend_Controller_Action { public function stationRssAction() { $this->view->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); if (!RestAuth::verifyAuth(true, true, $this) && (Application_Model_Preference::getStationPodcastPrivacy() && $this->getRequest()->getParam("sharing_token") != Application_Model_Preference::getStationPodcastDownloadKey())) { $this->getResponse() ->setHttpResponseCode(401); return; } header('Content-Type: text/xml; charset=UTF-8'); echo Application_Service_PodcastService::createStationRssFeed(); } }
Enable data collection by default
// // Metric Logger // // Scrapes various data sources and visualizes // collected data in a web ui. const apiEndpoints = ["github.js", "explorer.js"] const data = require("./datalogger.js").init(apiEndpoints) const express = require("express") const app = express() const process = require("process") const PORT = process.env.SIA_METRIC_PORT || 8080 //Servers static files. app.use(express.static("public")) app.use("/charts/", express.static("node_modules/chart.js/dist/")) app.use("/js/moment.js", express.static("node_modules/moment/moment.js")) app.use("/js/bignumber.js", express.static("node_modules/bignumber.js/bignumber.js")) //Data endpoint. app.get("/data", (req, res) => { if (req.query.callback){ res.send(`function ${req.query.callback}(callback){ callback(${JSON.stringify(data.latest(req.query.length))}) }`) } else { res.send(JSON.stringify(data.latest(req.query.length))) } }) app.listen(PORT, () => console.log(`Running server on port ${PORT}`) ) data.startLogging()
// // Metric Logger // // Scrapes various data sources and visualizes // collected data in a web ui. const apiEndpoints = ["github.js", "explorer.js"] const data = require("./datalogger.js").init(apiEndpoints) const express = require("express") const app = express() const process = require("process") const PORT = process.env.SIA_METRIC_PORT || 8080 //Servers static files. app.use(express.static("public")) app.use("/charts/", express.static("node_modules/chart.js/dist/")) app.use("/js/moment.js", express.static("node_modules/moment/moment.js")) app.use("/js/bignumber.js", express.static("node_modules/bignumber.js/bignumber.js")) //Data endpoint. app.get("/data", (req, res) => { if (req.query.callback){ res.send(`function ${req.query.callback}(callback){ callback(${JSON.stringify(data.latest(req.query.length))}) }`) } else { res.send(JSON.stringify(data.latest(req.query.length))) } }) app.listen(PORT, () => console.log(`Running server on port ${PORT}`) ) //data.startLogging()
Fix the test to expect the new behaviour
<?php /** * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace Test\BackgroundJob; class Job extends \Test\TestCase { private $run = false; protected function setUp() { parent::setUp(); $this->run = false; } public function testRemoveAfterException() { $jobList = new DummyJobList(); $job = new TestJob($this, function () { throw new \Exception(); }); $jobList->add($job); $logger = $this->getMockBuilder('OCP\ILogger') ->disableOriginalConstructor() ->getMock(); $logger->expects($this->once()) ->method('error') ->with('Error while running background job: '); $this->assertCount(1, $jobList->getAll()); $job->execute($jobList, $logger); $this->assertTrue($this->run); $this->assertCount(1, $jobList->getAll()); } public function markRun() { $this->run = true; } }
<?php /** * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace Test\BackgroundJob; class Job extends \Test\TestCase { private $run = false; protected function setUp() { parent::setUp(); $this->run = false; } public function testRemoveAfterException() { $jobList = new DummyJobList(); $job = new TestJob($this, function () { throw new \Exception(); }); $jobList->add($job); $this->assertCount(1, $jobList->getAll()); $job->execute($jobList); $this->assertTrue($this->run); $this->assertCount(0, $jobList->getAll()); } public function markRun() { $this->run = true; } }
Fix error logging in galaxy-cachefile-external-validator bin/galaxy-cachefile-external-validator is a symlink to bin/travis.py
#!/usr/bin/env python import sys import logging from cargoport.utils import yield_packages, download_url, package_to_path, verify_file logging.basicConfig(level=logging.DEBUG) log = logging.getLogger() def main(): retcode = 0 for package in yield_packages(sys.stdin): print package # Remove the '+' at the beginning package['id'] = package['id'][1:] output_package_path = package_to_path(**package) + package['ext'] err = download_url(package['url'], output_package_path) if err is not None: log.error("Could not download file: %s", err) retcode = 1 else: log.info("%s downloaded successfully", output_package_path) err = verify_file(output_package_path, package['sha256sum']) if err is not None: log.error("Could not verify file: %s", err) retcode = 1 else: log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum']) exit(retcode) if __name__ == '__main__': main()
#!/usr/bin/env python import sys import logging from cargoport.utils import yield_packages, download_url, package_to_path, verify_file logging.basicConfig(level=logging.DEBUG) log = logging.getLogger() def main(): retcode = 0 for package in yield_packages(sys.stdin): print package # Remove the '+' at the beginning package['id'] = package['id'][1:] output_package_path = package_to_path(**package) + package['ext'] err = download_url(package['url'], output_package_path) if err is not None: log.error("Could not download file", err) retcode = 1 else: log.info("%s downloaded successfully", output_package_path) err = verify_file(output_package_path, package['sha256sum']) if err is not None: log.error("Could not verify file", err) retcode = 1 else: log.info("%s verified successfully with hash %s", output_package_path, package['sha256sum']) exit(retcode) if __name__ == '__main__': main()
Remove output; use correct function
'use strict'; const drive = require('./src/drive'); const handbrake = require('./src/handbrake'); const Progress = require('./src/progress'); let progress; drive.watch((drive) => { handbrake.rip(drive, { error: onError, start: onStart, output: onOutput, progress: onProgress, end: onEnd }); }); function onError(error) { console.log('ERROR!'); console.log(error); } function onStart() { console.log('Handbrake CLI is ready.'); progress = new Progress('Ripping Disc'); } function onOutput(output) { } function onProgress(p) { progress.tick(p.percentComplete, `Encoding @${p.fps} - ETA ${p.eta}`); } function onEnd() { progress.tick(1, 'Completed'); }
'use strict'; const drive = require('./src/drive'); const handbrake = require('./src/handbrake'); const Progress = require('./src/progress'); let progress; drive.watch((drive) => { handbrake.rip(drive, { error: onError, start: onStart, output: onOutput, progress: onProgress, end: onEnd }); }); function onError(error) { console.log('ERROR!'); console.log(error); } function onStart() { console.log('Handbrake CLI is ready.'); progress = new Progress('Ripping Disc'); } function onOutput(output) { console.log(output); } function onProgress(p) { progress.perc(p.percentComplete, `Encoding @${p.fps} - ETA ${p.eta}`); } function onEnd() { progress.perc(1, 'Completed'); }
Use relative path for html plugin
const HtmlWebPackPlugin = require("html-webpack-plugin") module.exports = { entry: { main: __dirname + "/src/DragRange.jsx", viewer: __dirname + "/src/index.js", }, output: { filename: "[name].js", path: __dirname + "/dist", }, devtool: "source-map", module: { rules: [ { test: /\.jsx?$/, exclude: [/node_modules/], use: { loader: "babel-loader", } }, { test: /\.html$/, use: [ { loader: "html-loader", options: { minimize: true }, } ] }, ], }, plugins: [ new HtmlWebPackPlugin({ template: "./src/index.html", filename: "./index.html", }) ], }
const HtmlWebPackPlugin = require("html-webpack-plugin") module.exports = { entry: { main: __dirname + "/src/DragRange.jsx", viewer: __dirname + "/src/index.js", }, output: { filename: "[name].js", path: __dirname + "/dist", }, devtool: "source-map", module: { rules: [ { test: /\.jsx?$/, exclude: [/node_modules/], use: { loader: "babel-loader", } }, { test: /\.html$/, use: [ { loader: "html-loader", options: { minimize: true }, } ] }, ], }, plugins: [ new HtmlWebPackPlugin({ template: __dirname + "/src/index.html", filename: __dirname + "/index.html", }) ], }
Add Remediation Points to issues
'use strict'; module.exports = function (err, data) { if (err) { return 'Debug output: %j' + data + '\n' + JSON.stringify(err); } if (!data.length) { return; } var returnString = ''; for (var i = 0, il = data.length; i < il; ++i) { returnString += JSON.stringify({ type: 'issue', check_name: 'Vulnerable module "' + data[i].module + '" identified', description: '`' + data[i].module + '` ' + data[i].title, categories: ['Security'], remediation_points: 300000, content: { body: data[i].content }, location: { path: 'npm-shrinkwrap.json', lines: { begin: data[i].line.start, end: data[i].line.end } } }) + '\0\n'; } return returnString; };
'use strict'; module.exports = function (err, data) { if (err) { return 'Debug output: %j' + data + '\n' + JSON.stringify(err); } if (!data.length) { return; } var returnString = ''; for (var i = 0, il = data.length; i < il; ++i) { returnString += JSON.stringify({ type: 'issue', check_name: 'Vulnerable module "' + data[i].module + '" identified', description: '`' + data[i].module + '` ' + data[i].title, categories: ['Security'], content: { body: data[i].content }, location: { path: 'npm-shrinkwrap.json', lines: { begin: data[i].line.start, end: data[i].line.end } } }) + '\0\n'; } return returnString; };
Mark redundant properties as deprecated
/* * Copyright 2015 Eric F. Savage, code@efsavage.com * * 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.ajah.rest.api.model.relay.user; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * @author <a href="http://efsavage.com">Eric F. Savage</a>, * <a href="mailto:code@efsavage.com">code@efsavage.com</a>. */ @JsonInclude(Include.NON_NULL) public class UserNameRelay { public String first; public String middle; public String last; public String suffix; public String display; @Deprecated public String firstName; @Deprecated public String middleName; @Deprecated public String lastName; @Deprecated public String displayName; }
/* * Copyright 2015 Eric F. Savage, code@efsavage.com * * 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.ajah.rest.api.model.relay.user; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * @author <a href="http://efsavage.com">Eric F. Savage</a>, <a * href="mailto:code@efsavage.com">code@efsavage.com</a>. */ @JsonInclude(Include.NON_NULL) public class UserNameRelay { public String first; public String middle; public String last; public String suffix; public String display; public String firstName; public String middleName; public String lastName; public String displayName; }
Fix site so there is no more admin login page If you logged in with persona, went to the admin, then clicked on "logout", you'd end up on the admin login page which you had to manually leave by typing a url in the urlbar. This fixes that.
from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.contrib.auth.decorators import login_required from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.http import HttpResponse from funfactory.monkeypatches import patch patch() from django.contrib import admin from adminplus import AdminSitePlus admin.site = AdminSitePlus() admin.autodiscover() admin.site.login = login_required(admin.site.login) urlpatterns = patterns('', (r'', include('fjord.analytics.urls')), (r'', include('fjord.base.urls')), (r'', include('fjord.feedback.urls')), (r'', include('fjord.search.urls')), # TODO: Remove this stub. /about and /search point to it. url(r'stub', lambda r: HttpResponse('this is a stub'), name='stub'), # Generate a robots.txt (r'^robots\.txt$', lambda r: HttpResponse( "User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow', mimetype="text/plain" ) ), (r'^browserid/', include('django_browserid.urls')), (r'^admin/', include(admin.site.urls)), ) # In DEBUG mode, serve media files through Django. if settings.DEBUG: urlpatterns += staticfiles_urlpatterns()
from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.http import HttpResponse from funfactory.monkeypatches import patch patch() from django.contrib import admin from adminplus import AdminSitePlus admin.site = AdminSitePlus() admin.autodiscover() urlpatterns = patterns('', (r'', include('fjord.analytics.urls')), (r'', include('fjord.base.urls')), (r'', include('fjord.feedback.urls')), (r'', include('fjord.search.urls')), # TODO: Remove this stub. /about and /search point to it. url(r'stub', lambda r: HttpResponse('this is a stub'), name='stub'), # Generate a robots.txt (r'^robots\.txt$', lambda r: HttpResponse( "User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow', mimetype="text/plain" ) ), (r'^browserid/', include('django_browserid.urls')), (r'^admin/', include(admin.site.urls)), ) # In DEBUG mode, serve media files through Django. if settings.DEBUG: urlpatterns += staticfiles_urlpatterns()
Fix getting grid factory in controller
<?php namespace AppBundle\Controller; use AppBundle\Form\XoGridType; use AppBundle\Game\GridFactory; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class DefaultController extends Controller { /** * @Route("/", name="homepage") */ public function indexAction(Request $request) { $grid = $this->getGridFactory()->createStandardGrid(); $form = $this->createForm(new XoGridType(), $grid); $form->handleRequest($request); if (false !== $winner = $grid->getWinner()) { $request->getSession()->getFlashBag()->add('winner', 'The winner is ' . $winner); } return $this->render('default/index.html.twig', ['form' => $form->createView()]); } /** * @return GridFactory */ private function getGridFactory() { return $this->get('grid_factory'); } }
<?php namespace AppBundle\Controller; use AppBundle\Form\XoGridType; use AppBundle\Game\GridFactory; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class DefaultController extends Controller { /** * @Route("/", name="homepage") */ public function indexAction(Request $request) { $grid = $this->getGridFactory()->createStandardGrid(); $form = $this->createForm(new XoGridType(), $grid); $form->handleRequest($request); if (false !== $winner = $grid->getWinner()) { $request->getSession()->getFlashBag()->add('winner', 'The winner is ' . $winner); } return $this->render('default/index.html.twig', ['form' => $form->createView()]); } /** * @return GridFactory */ private function getGridFactory() { $this->get('grid_factory'); } }
Use dispatch callback in connect middleware
var React = require('react'); var urllite = require('urllite'); var renderDocumentString = require('../utils/renderDocumentString'); var connectMiddleware = function(router) { return function(req, res, next) { // Get the part of the URL we care about. // TODO: Allow this to be mounted at a different base and strip that from pathname var parsed = urllite(req.url); var url = parsed.pathname + parsed.search + parsed.hash; router.dispatch(url, {initialOnly: true}, function(err, rres) { if (err) { // The React router doesn't want to handle it. That's okay, let // something else. if (err.name === 'Unhandled') return next(); // Uh oh. A real error. return next(err); } var contentType = rres.contentType(); // Guess from contentType if not present res.statusCode = rres._notFound ? 404 : 200; res.setHeader('Content-Type', contentType); res.end(renderDocumentString(rres)); }); }; }; module.exports = connectMiddleware;
var React = require('react'); var urllite = require('urllite'); var renderDocumentString = require('../utils/renderDocumentString'); var connectMiddleware = function(router) { return function(req, res, next) { // Get the part of the URL we care about. // TODO: Allow this to be mounted at a different base and strip that from pathname var parsed = urllite(req.url); var url = parsed.pathname + parsed.search + parsed.hash; var rres = router.dispatch(url, {initialOnly: true}); rres.request .on('error', function(err) { // The React router doesn't want to handle it. That's okay, let // something else. if (err.name === 'Unhandled') return next(); // Uh oh. A real error. return next(err); }) .on('end', function() { var contentType = rres.contentType(); // Guess from contentType if not present res.statusCode = rres._notFound ? 404 : 200; res.setHeader('Content-Type', contentType); res.end(renderDocumentString(rres)); }); }; }; module.exports = connectMiddleware;
Remove attribute from domain and get from entity
from infosystem.database import db from infosystem.common.subsystem import entity class Domain(entity.Entity, db.Model): attributes = ['name', 'parent_id'] attributes += entity.Entity.attributes name = db.Column(db.String(60), nullable=False, unique=True) parent_id = db.Column( db.CHAR(32), db.ForeignKey("domain.id"), nullable=True) def __init__(self, id, name, active=True, parent_id=None, created_at=None, created_by=None, updated_at=None, updated_by=None): super().__init__(id, active, created_at, created_by, updated_at, updated_by) self.name = name self.parent_id = parent_id
from infosystem.database import db from infosystem.common.subsystem import entity class Domain(entity.Entity, db.Model): attributes = ['active', 'name', 'parent_id'] attributes += entity.Entity.attributes active = db.Column(db.Boolean(), nullable=False) name = db.Column(db.String(60), nullable=False, unique=True) parent_id = db.Column( db.CHAR(32), db.ForeignKey("domain.id"), nullable=True) def __init__(self, id, name, active=True, parent_id=None, created_at=None, created_by=None, updated_at=None, updated_by=None): super().__init__(id, created_at, created_by, updated_at, updated_by) self.active = active self.name = name self.parent_id = parent_id
Add a try guard around git description
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. // Support for Node 0.10 // See https://github.com/webpack/css-loader/issues/144 require('es6-promise').polyfill(); var childProcess = require('child_process'); var buildExtension = require('@jupyterlab/extension-builder/lib/builder').buildExtension; var webpack = require('webpack'); console.log('Generating bundles...'); try { var notice = childProcess.execSync('git describe', { encoding: 'utf8' }); } catch { var notice = 'unknown'; } buildExtension({ name: 'main', entry: './build/main', outputDir: './build', config: { output: { publicPath: 'lab/', }, module: { noParse: [/xterm\.js/] // Xterm ships a UMD module }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'GIT_DESCRIPTION': JSON.stringify(notice.trim()) } }) ] } }); module.exports = { entry: { loader: './build/loader' }, output: { path: __dirname + '/build', filename: '[name].bundle.js', libraryTarget: 'this', library: 'jupyter' }, node: { fs: 'empty' }, debug: true, bail: true, devtool: 'source-map' }
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. // Support for Node 0.10 // See https://github.com/webpack/css-loader/issues/144 require('es6-promise').polyfill(); var childProcess = require('child_process'); var buildExtension = require('@jupyterlab/extension-builder/lib/builder').buildExtension; var webpack = require('webpack'); console.log('Generating bundles...'); var notice = childProcess.execSync('git describe', { encoding: 'utf8' }); buildExtension({ name: 'main', entry: './build/main', outputDir: './build', config: { output: { publicPath: 'lab/', }, module: { noParse: [/xterm\.js/] // Xterm ships a UMD module }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'GIT_DESCRIPTION': JSON.stringify(notice.trim()) } }) ] } }); module.exports = { entry: { loader: './build/loader' }, output: { path: __dirname + '/build', filename: '[name].bundle.js', libraryTarget: 'this', library: 'jupyter' }, node: { fs: 'empty' }, debug: true, bail: true, devtool: 'source-map' }
Change the Cart and Orders top bar again
(function () { 'use strict'; angular .module('orders') .run(menuConfig); menuConfig.$inject = ['Menus']; function menuConfig(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', { title: 'Orders', state: 'orders.list', type: 'item', roles: ['*'] }); Menus.addMenuItem('topbar', { title: 'Cart', state: 'cart', type: 'item', roles: ['*'] }); // Add the dropdown list item Menus.addSubMenuItem('topbar', 'orders', { title: 'List Orders', state: 'orders.list' }); // Add the dropdown create item Menus.addSubMenuItem('topbar', 'orders', { title: 'Create Order', state: 'orders.create', roles: ['user'] }); } })();
(function () { 'use strict'; angular .module('orders') .run(menuConfig); menuConfig.$inject = ['Menus']; function menuConfig(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', { title: 'Orders', state: 'orders', type: 'dropdown', roles: ['*'] }); // Add the dropdown list item Menus.addSubMenuItem('topbar', 'orders', { title: 'List Orders', state: 'orders.list' }); // Add the dropdown create item Menus.addSubMenuItem('topbar', 'orders', { title: 'Create Order', state: 'orders.create', roles: ['user'] }); } })();
Add `test_not_match` to `no_such_file` tests
import pytest from thefuck.rules.no_such_file import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [ Command(script='mv foo bar/foo', stderr="mv: cannot move 'foo' to 'bar/foo': No such file or directory"), Command(script='mv foo bar/', stderr="mv: cannot move 'foo' to 'bar/': No such file or directory"), ]) def test_match(command): assert match(command, None) @pytest.mark.parametrize('command', [ Command(script='mv foo bar/', stderr=""), Command(script='mv foo bar/foo', stderr="mv: permission denied"), ]) def test_not_match(command): assert not match(command, None) @pytest.mark.parametrize('command, new_command', [ (Command(script='mv foo bar/foo', stderr="mv: cannot move 'foo' to 'bar/foo': No such file or directory"), 'mkdir -p bar && mv foo bar/foo'), (Command(script='mv foo bar/', stderr="mv: cannot move 'foo' to 'bar/': No such file or directory"), 'mkdir -p bar && mv foo bar/'), ]) def test_get_new_command(command, new_command): assert get_new_command(command, None) == new_command
import pytest from thefuck.rules.no_such_file import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [ Command(script='mv foo bar/foo', stderr="mv: cannot move 'foo' to 'bar/foo': No such file or directory"), Command(script='mv foo bar/', stderr="mv: cannot move 'foo' to 'bar/': No such file or directory"), ]) def test_match(command): assert match(command, None) @pytest.mark.parametrize('command, new_command', [ (Command(script='mv foo bar/foo', stderr="mv: cannot move 'foo' to 'bar/foo': No such file or directory"), 'mkdir -p bar && mv foo bar/foo'), (Command(script='mv foo bar/', stderr="mv: cannot move 'foo' to 'bar/': No such file or directory"), 'mkdir -p bar && mv foo bar/'), ]) def test_get_new_command(command, new_command): assert get_new_command(command, None) == new_command
Allow appending an array of elements or a Grindstone object
/** * Append child elements to the current object * @param {string|object} element * @returns {object} current instance of Grindstone */ $.fn.append = function(element) { var isHTML = typeof element === 'string' && element.match(/(<).+(>)/); var i = -1, len = this.length; this.each(function() { i++; if (typeof element === 'string') { if (isHTML) { this.innerHTML += element; } else { var textNode = document.createTextNode(element); this.appendChild(textNode); } } else if (priv.isElementArray(element)) { if (i == len - 1) { // Append elements directly if last. for (var j = 0; j < element.length; j++) { this.appendChild(element[j]); } } else { // Append cloned elements for all but the last. for (var j = 0; j < element.length; j++) { this.appendChild(element[j].cloneNode(true)); } } } else { if (i == len - 1) { // Append element itself if last. this.appendChild(element); } else { // Append a clone for all but the last. this.appendChild(element.cloneNode(true)); } } }); return this; };
/** * Append a new child element to the current object * @param {string|object} element * @returns {object} current instance of Grindstone */ $.fn.append = function(element) { var isHTML = typeof element === 'string' && element.match(/(<).+(>)/); var i = -1, len = this.length; this.each(function() { i++; if (typeof element === 'string') { if (isHTML) { this.innerHTML += element; } else { var textNode = document.createTextNode(element); this.appendChild(textNode); } } else { if (i == len - 1) { // Append element itself if last. this.appendChild(element); } else { // Append a clone for all but the last. this.appendChild(element.cloneNode(true)); } } }); return this; };
Add req.method to error message on not found
/* * Ensures something has been found during the request. Returns 404 if * res.template is unset, res.locals is empty and statusCode has not been set * to 204. * * Should be placed at the very end of the middleware pipeline, * after all project specific routes but before the error handler & responder. * * @module midwest/middleware/ensure-found */ 'use strict'; const _ = require('lodash'); module.exports = function ensureFound(req, res, next) { // it seems most reasonable to check if res.locals is empty before res.statusCode // because the former is much more common if (res.template || res.master || !_.isEmpty(res.locals) || res.statusCode === 204) { next(); } else { // generates Not Found error if there is no page to render and no truthy // values in data const err = new Error(`Not found: ${req.method.toUpperCase()} ${req.path}`); err.status = 404; next(err); } };
/* * Ensures something has been found during the request. Returns 404 if * res.template is unset, res.locals is empty and statusCode has not been set * to 204. * * Should be placed at the very end of the middleware pipeline, * after all project specific routes but before the error handler & responder. * * @module midwest/middleware/ensure-found */ 'use strict'; const _ = require('lodash'); module.exports = function ensureFound(req, res, next) { // it seems most reasonable to check if res.locals is empty before res.statusCode // because the former is much more common if (res.template || res.master || !_.isEmpty(res.locals) || res.statusCode === 204) { next(); } else { // generates Not Found error if there is no page to render and no truthy // values in data const err = new Error(`Not found: ${req.path}`); err.status = 404; next(err); } };
Use `set` instead of `remember` for CloudFront IPs [API-189]
<?php namespace App\Console\Commands; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Storage; use Illuminate\Console\Command; class UpdateCloudfrontIps extends Command { protected $signature = 'update:cloudfront-ips'; protected $description = 'Update file cache of CloudFront IPs for TrustProxies'; public function handle() { // This throws an exception if the URL is unreachable $contents = file_get_contents('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips'); if ($contents === false) { return; } // API-189: Remember for two hours, and keep the file as fallback // This command should be run on both app and utility after deploy Cache::set('list-cloudfront-ips', $contents, 60 * 60 * 2); Storage::put('list-cloudfront-ips.json', $contents); $this->info('Cloudfront IPs updated!'); } }
<?php namespace App\Console\Commands; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Storage; use Illuminate\Console\Command; class UpdateCloudfrontIps extends Command { protected $signature = 'update:cloudfront-ips'; protected $description = 'Update file cache of CloudFront IPs for TrustProxies'; public function handle() { // This throws an exception if the URL is unreachable $contents = file_get_contents('http://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips'); if ($contents === false) { return; } // API-189: Remember for two hours, and keep the file as fallback // This command should be run on both app and utility after deploy Cache::remember('list-cloudfront-ips', 60 * 60 * 2, function () use ($contents) { return $contents; }); Storage::put('list-cloudfront-ips.json', $contents); $this->info('Cloudfront IPs updated!'); } }
Remove an annoying log and remove introduction of oceanic fauna namespace, where there is no need for an additional namespace.
/** * * Copyright (c) 2020 Silicon Labs * * 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. * * * @jest-environment node */ const electronMain = require('../src-electron/main-process/electron-main.js') const window = require('../src-electron/main-process/window.js') test('Make sure electron main process loads', () => { expect(electronMain.loaded).toBeTruthy() }) test('Test constructing queries for the window', () => { var query = window.createQueryString(1, 'someUiMode') expect(query).toBe(`?sessionId=1&uiMode=someUiMode`) query = window.createQueryString() expect(query).toBe(``) }) require('../src-electron/main-process/preference.js')
/** * * Copyright (c) 2020 Silicon Labs * * 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. * * * @jest-environment node */ const electronMain = require('../src-electron/main-process/electron-main.js') const window = require('../src-electron/main-process/window.js') test('Make sure electron main process loads', () => { expect(electronMain.loaded).toBeTruthy() }) test('Test constructing queries for the window', () => { var query = window.createQueryString(1, 'tuna') console.log(query) expect(query).toBe(`?sessionId=1&uiMode=tuna`) query = window.createQueryString() expect(query).toBe(``) }) require('../src-electron/main-process/preference.js')
Revert "[TEST] refactor test to get it passing on Travis CI" This reverts commit b92684d252e92a75115ce8617a15c107b5a34b09.
from unittest import TestCase import create_minimal_image from create_minimal_image import main POPEN_COMMAND_LIST = [] class CreateMinimalImageTest(TestCase): def setUp(self): global POPEN_COMMAND_LIST POPEN_COMMAND_LIST = [] create_minimal_image._run_popen_command = stubbed_run_popen_command def test_main_will_correctly_return_shared_objects_and_locations(self): self.maxDiff = None main("/usr/lib/jvm") self.assertEquals(POPEN_COMMAND_LIST, get_expected_popen_comands()) def stubbed_run_popen_command(command): POPEN_COMMAND_LIST.append(" ".join(command)) try: with open("tests/fixtures/{0}.txt".format("_".join(command).replace("/", "_")), "r") as f: std_out = f.read() return std_out except: return "" def get_expected_popen_comands(): with open("tests/fixtures/expected_popen_commands.txt", "r") as f: expected_popen_commands = f.read().split("\n") return [command for command in expected_popen_commands if command != ""]
from unittest import TestCase import create_minimal_image from create_minimal_image import main POPEN_COMMAND_LIST = "" class CreateMinimalImageTest(TestCase): def setUp(self): global POPEN_COMMAND_LIST POPEN_COMMAND_LIST = "" create_minimal_image._run_popen_command = stubbed_run_popen_command def test_main_will_correctly_return_shared_objects_and_locations(self): self.maxDiff = None main("/usr/lib/jvm") self.assertEquals(POPEN_COMMAND_LIST, get_expected_popen_comands()) def stubbed_run_popen_command(command): global POPEN_COMMAND_LIST POPEN_COMMAND_LIST += " ".join(command) + "\n" try: with open("tests/fixtures/{0}.txt".format("_".join(command).replace("/", "_")), "r") as f: std_out = f.read() return std_out except: return "" def get_expected_popen_comands(): with open("tests/fixtures/expected_popen_commands.txt", "r") as f: expected_popen_commands = f.read() return expected_popen_commands
Fix navigation active item bug
(function(){ "use strict"; angular .module('VinculacionApp') .controller('MainController', MainController); MainController.$inject = [ '$rootScope', '$state' ]; function MainController ($rootScope, $state) { var vm = this; vm.expand = false; vm.navItems = [ { title: "HOME", ref: "dashboard.home", icon: "glyphicon glyphicon-home", active: $state.current.url === '/home' }, { title: "PROYECTOS", ref: "dashboard.projects", icon: "glyphicon glyphicon-folder-open", active: $state.current.url.includes('/proyectos') }, { title: "SOLICITUDES", ref: "dashboard.requests", icon: "glyphicon glyphicon-tasks", active: $state.current.url === '/solicitudes' }, { title: "LOG OUT", ref: "landing", icon: "glyphicon glyphicon-log-out", active: false } ]; $rootScope.$on('$stateChangeStart', changeActiveItem); function changeActiveItem (event, toState) { vm.navItems[0].active = toState.url === '/home'; vm.navItems[1].active = toState.url.includes('/proyectos'); vm.navItems[2].active = toState.url === '/solicitudes'; } } })();
(function(){ "use strict"; angular .module('VinculacionApp') .controller('MainController', MainController); function MainController () { var vm = this; vm.expand = false; vm.navItems = [ { title: "HOME", ref: "dashboard.home", icon: "glyphicon glyphicon-home", active: true }, { title: "PROYECTOS", ref: "dashboard.projects", icon: "glyphicon glyphicon-folder-open", active: false }, { title: "SOLICITUDES", ref: "dashboard.requests", icon: "glyphicon glyphicon-tasks", active: false }, { title: "LOG OUT", ref: "landing", icon: "glyphicon glyphicon-log-out", active: false } ]; } })();
Switch to generating REST end points from docker image
import os from girder.utility.webroot import Webroot from .rest_slicer_cli import( genRESTEndPointsForSlicerCLIsInSubDirs, genRESTEndPointsForSlicerCLIsInDocker ) _template = os.path.join( os.path.dirname(__file__), 'webroot.mako' ) def load(info): girderRoot = info['serverRoot'] histomicsRoot = Webroot(_template) histomicsRoot.updateHtmlVars(girderRoot.vars) histomicsRoot.updateHtmlVars({'title': 'HistomicsTK'}) info['serverRoot'].histomicstk = histomicsRoot info['serverRoot'].girder = girderRoot # cliRootDir = os.path.dirname(__file__) # genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir) _ = genRESTEndPointsForSlicerCLIsInDocker( info, 'HistomicsTK', 'dsarchive/histomicstk' )
import os from girder.utility.webroot import Webroot from .rest_slicer_cli import( genRESTEndPointsForSlicerCLIsInSubDirs, genRESTEndPointsForSlicerCLIsInDocker ) _template = os.path.join( os.path.dirname(__file__), 'webroot.mako' ) def load(info): girderRoot = info['serverRoot'] histomicsRoot = Webroot(_template) histomicsRoot.updateHtmlVars(girderRoot.vars) histomicsRoot.updateHtmlVars({'title': 'HistomicsTK'}) info['serverRoot'].histomicstk = histomicsRoot info['serverRoot'].girder = girderRoot # cliRootDir = os.path.dirname(__file__) # genRESTEndPointsForSlicerCLIsInSubDirs(info, 'HistomicsTK', cliRootDir) genRESTEndPointsForSlicerCLIsInDocker(info, 'HistomicsTK', 'dsarchive/histomicstk')
Add option to bulk-add users Warning: excel import is shaky with importing groups; json import is recommended.
from leaflet.admin import LeafletGeoAdmin from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin # Register models from .models import Author, Book, BookInstance, BookHolding, BookOwning, BookBatch from django.contrib.auth.models import User class BookResource(resources.ModelResource): class Meta: model = Book class BookAdmin(ImportExportModelAdmin): resource_class = BookResource class BookCodeResource(resources.ModelResource): class Meta: model = BookInstance exclude = ('id','ownings', 'holdings', 'arrived') import_id_fields = ['book_code'] skip_unchanged = True class BookCodeAdmin(ImportExportModelAdmin): resource_class = BookCodeResource class UserResource(resources.ModelResource): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'groups', 'username') import_id_fields = ['username'] skip_unchanged = True class UserAdmin(ImportExportModelAdmin): resource_class = UserResource pass admin.site.register(Author) admin.site.register(Book, BookAdmin) admin.site.register(BookInstance, BookCodeAdmin) admin.site.register(BookHolding, LeafletGeoAdmin) admin.site.register(BookOwning, LeafletGeoAdmin) admin.site.register(BookBatch, LeafletGeoAdmin) admin.site.unregister(User) admin.site.register(User, UserAdmin)
from leaflet.admin import LeafletGeoAdmin from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin # Register your models here. from .models import Author, Book, BookInstance, BookHolding, BookOwning, BookBatch class BookResource(resources.ModelResource): class Meta: model = Book class BookAdmin(ImportExportModelAdmin): resource_class = BookResource class BookCodeResource(resources.ModelResource): class Meta: model = BookInstance exclude = ('id','ownings', 'holdings', 'arrived') import_id_fields = ['book_code'] skip_unchanged = True class BookCodeAdmin(ImportExportModelAdmin): resource_class = BookCodeResource admin.site.register(Author) admin.site.register(Book, BookAdmin) admin.site.register(BookInstance, BookCodeAdmin) admin.site.register(BookHolding, LeafletGeoAdmin) admin.site.register(BookOwning, LeafletGeoAdmin) admin.site.register(BookBatch, LeafletGeoAdmin)
Raise a ValueError from _get_archive_filelist instead of Exception Raising the Exception base class is considered bad style, as the more specialized child classes carry more information about the kind of error that occurred. And often no-one actually tries to catch the Exception class.
# -*- coding: utf-8 -*- # # Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com> # # 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 typing import List # noqa: F401, pylint: disable=unused-import import tarfile import zipfile def _get_archive_filelist(filename): # type: (str) -> List[str] names = [] # type: List[str] if tarfile.is_tarfile(filename): with tarfile.open(filename) as tar_file: names = sorted(tar_file.getnames()) elif zipfile.is_zipfile(filename): with zipfile.ZipFile(filename) as zip_file: names = sorted(zip_file.namelist()) else: raise ValueError("Can not get filenames from '{!s}'. " "Not a tar or zip file".format(filename)) if "./" in names: names.remove("./") return names
# -*- coding: utf-8 -*- # # Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com> # # 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 typing import List # noqa: F401, pylint: disable=unused-import import tarfile import zipfile def _get_archive_filelist(filename): # type: (str) -> List[str] names = [] # type: List[str] if tarfile.is_tarfile(filename): with tarfile.open(filename) as tar_file: names = sorted(tar_file.getnames()) elif zipfile.is_zipfile(filename): with zipfile.ZipFile(filename) as zip_file: names = sorted(zip_file.namelist()) else: raise Exception("Can not get filenames from '%s'. " "Not a tar or zip file" % filename) if "./" in names: names.remove("./") return names
Fix incorrect observation mutation DAO query
/* * Copyright 2019 Google LLC * * 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 * * https://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.android.gnd.persistence.local.room; import androidx.room.Dao; import androidx.room.Query; import io.reactivex.Completable; import io.reactivex.Single; import java.util.List; /** Data access object for database operations related to {@link ObservationMutationEntity}. */ @Dao public interface ObservationMutationDao extends BaseDao<ObservationMutationEntity> { @Query("DELETE FROM observation_mutation WHERE id IN (:ids)") Completable deleteAll(List<Long> ids); @Query("SELECT * FROM observation_mutation WHERE feature_id = :featureId") Single<List<ObservationMutationEntity>> findByFeatureId(String featureId); @Query("SELECT * FROM observation_mutation WHERE observation_id = :observationId") Single<List<ObservationMutationEntity>> findByObservationId(String observationId); }
/* * Copyright 2019 Google LLC * * 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 * * https://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.android.gnd.persistence.local.room; import androidx.room.Dao; import androidx.room.Query; import io.reactivex.Completable; import io.reactivex.Single; import java.util.List; /** Data access object for database operations related to {@link ObservationMutationEntity}. */ @Dao public interface ObservationMutationDao extends BaseDao<ObservationMutationEntity> { @Query("DELETE FROM observation_mutation WHERE id IN (:ids)") Completable deleteAll(List<Long> ids); @Query("SELECT * FROM observation_mutation WHERE observation_id = :featureId") Single<List<ObservationMutationEntity>> findByFeatureId(String featureId); @Query("SELECT * FROM observation_mutation WHERE observation_id = :observationId") Single<List<ObservationMutationEntity>> findByObservationId(String observationId); }
Add newline to follow a POSIX rule.
package com.nulabinc.zxcvbn.matchers; import java.util.HashMap; import java.util.List; import java.util.Map; public class Dictionary { private final String name; private final List<String> frequencies; private final Map<String, Integer> rankedDictionary; public Dictionary(String name, List<String> frequencies) { this.name = name; this.frequencies = frequencies; this.rankedDictionary = toRankedDictionary(frequencies); } private Map<String, Integer> toRankedDictionary(final List<String> frequencies) { Map<String, Integer> result = new HashMap<>(); int i = 1; // rank starts at 1, not 0 for (String word : frequencies) { result.put(word, i); i++; } return result; } public String getName() { return name; } public List<String> getFrequencies() { return frequencies; } public Map<String, Integer> getRankedDictionary() { return rankedDictionary; } }
package com.nulabinc.zxcvbn.matchers; import java.util.HashMap; import java.util.List; import java.util.Map; public class Dictionary { private final String name; private final List<String> frequencies; private final Map<String, Integer> rankedDictionary; public Dictionary(String name, List<String> frequencies) { this.name = name; this.frequencies = frequencies; this.rankedDictionary = toRankedDictionary(frequencies); } private Map<String, Integer> toRankedDictionary(final List<String> frequencies) { Map<String, Integer> result = new HashMap<>(); int i = 1; // rank starts at 1, not 0 for (String word : frequencies) { result.put(word, i); i++; } return result; } public String getName() { return name; } public List<String> getFrequencies() { return frequencies; } public Map<String, Integer> getRankedDictionary() { return rankedDictionary; } }
Update placeholders in ownpad configuration template
<?php /** @var OC_L10N $l */ /** @var array $_ */ ?> <div class="section"> <form id="ownpad_settings"> <h2><?php p($l->t('Collaborative documents'));?></h2> <p><?php p($l->t('This is used to link collaborative documents inside ownCloud.')); ?></p> <p> <label for="ownpad_etherpad_host"><?php p($l->t('Etherpad Host')); ?></label> <input type="text" name="ownpad_etherpad_host" id="ownpad_etherpad_host" value="<?php p($_['ownpad_etherpad_host']); ?>" placeholder="https://mensuel.framapad.org" /> </p> <p> <label for="ownpad_ethercalc_host"><?php p($l->t('Ethercalc Host')); ?></label> <input type="text" name="ownpad_ethercalc_host" id="ownpad_ethercalc_host" value="<?php p($_['ownpad_ethercalc_host']); ?>" placeholder="https://framacalc.org" /> </p> <div id="ownpad-saved-message"> <span class="msg success"><?php p($l->t('Saved')); ?></span> </div> </div>
<?php /** @var OC_L10N $l */ /** @var array $_ */ ?> <div class="section"> <form id="ownpad_settings"> <h2><?php p($l->t('Collaborative documents'));?></h2> <p><?php p($l->t('This is used to link collaborative documents inside ownCloud.')); ?></p> <p> <label for="ownpad_etherpad_host"><?php p($l->t('Etherpad Host')); ?></label> <input type="text" name="ownpad_etherpad_host" id="ownpad_etherpad_host" value="<?php p($_['ownpad_etherpad_host']); ?>" placeholder="http://lite.framapad.org" /> </p> <p> <label for="ownpad_ethercalc_host"><?php p($l->t('Ethercalc Host')); ?></label> <input type="text" name="ownpad_ethercalc_host" id="ownpad_ethercalc_host" value="<?php p($_['ownpad_ethercalc_host']); ?>" placeholder="http://wwW.framacalc.org" /> </p> <div id="ownpad-saved-message"> <span class="msg success"><?php p($l->t('Saved')); ?></span> </div> </div>
Sort method for list of errors
package BSChecker; import java.util.ArrayList; import java.util.Comparator; /** * * @author tedpyne * Defines abstract class for types of grammatical errors */ public abstract class Error { /** * @param text The block of text to find errors in * @return an ArrayList of int[2] pointers to the start and end indices of the roor in the submitted text * int[0],int[1] are start and end tokens in error */ public abstract ArrayList<int[]> findErrors(String text); /** * * @param line The text to search through * @param string The word to find in the text * @param found The number of occurrences already found * @return The location of the n+1th instance */ public static int locationOf(String line, String string, int found) { int loc = 0; for(int i = 0; i <= found; i++){ loc = line.indexOf(string,loc) +1; } return loc; } /** * Sorts the list of all errors by location. * @param list All the located errors */ public static void sort(ArrayList<int[]> list) { list.sort(new Comparator<int[]>() { public int compare(int[] o1, int[] o2) { if(o1[0] == o2[0]) return 0; else if(o1[0] < o2[0]) return -1; else return 1; } }); } }
package BSChecker; import java.util.ArrayList; /** * * @author tedpyne * Defines abstract class for types of grammatical errors */ public abstract class Error { /** * @param text The block of text to find errors in * @return an ArrayList of int[2] pointers to the start and end indices of the roor in the submitted text * int[0],int[1] are start and end tokens in error */ public abstract ArrayList<int[]> findErrors(String text); /** * * @param line The text to search through * @param string The word to find in the text * @param found The number of occurrences already found * @return The location of the n+1th instance */ public static int locationOf(String line, String string, int found) { int loc = 0; for(int i = 0; i <= found; i++){ loc = line.indexOf(string,loc) +1; } return loc; } }
Fix issue with MySQL not found errors
var mysql = require('mysql'), sql = require("./sql"), MySQL; MySQL = module.exports = function MySQL(options) { this.connection = mysql.createClient(options); }; MySQL.prototype = { constructor: MySQL, connect: function (fn) { this.connection.useDatabase(this.connection.database, fn); }, disconnect: function (fn) { this.connection.end(fn); }, getBin: function (params, fn) { var values = [params.id, params.revision]; this.connection.query(sql.getBin, values, function (err, results, fields) { if (err || !results.length) { return fn(!err && !results.length ? 'not-found' : err); } fn(null, results[0]); }); }, setBin: function () { }, getLatestBin: function () { }, getBinsByOwner: function (where) { }, generateBinId: function () { } };
var mysql = require('mysql'), sql = require("./sql"), MySQL; MySQL = module.exports = function MySQL(options) { this.connection = mysql.createClient(options); }; MySQL.prototype = { constructor: MySQL, connect: function (fn) { this.connection.useDatabase(this.connection.database, fn); }, disconnect: function (fn) { this.connection.end(fn); }, getBin: function (params, fn) { var values = [params.id, params.revision]; this.connection.query(sql.getBin, values, function (err, results, fields) { if (err || !results.length) { fn(!err && !results.length ? 'not-found' : err); } fn(null, results[0]); }); }, setBin: function () { }, getLatestBin: function () { }, getBinsByOwner: function (where) { }, generateBinId: function () { } };
Remove deprecated react rule (added in eslint > 1.4)
module.exports = { extends: 'commercetools', plugins: ['react'], ecmaFeatures: { jsx: true }, env: { browser: true }, rules: { 'react/display-name': 0, 'react/jsx-boolean-value': 2, 'react/jsx-no-undef': 2, 'react/jsx-sort-props': 0, 'react/jsx-uses-react': 2, 'react/jsx-uses-vars': 2, 'react/no-did-mount-set-state': 2, 'react/no-did-update-set-state': 2, 'react/no-multi-comp': 0, 'react/no-unknown-property': 2, 'react/prop-types': 2, 'react/react-in-jsx-scope': 2, 'react/self-closing-comp': 2, 'react/wrap-multilines': 2 } };
module.exports = { extends: 'commercetools', plugins: ['react'], ecmaFeatures: { jsx: true }, env: { browser: true }, rules: { 'react/display-name': 0, 'react/jsx-boolean-value': 2, 'react/jsx-quotes': 2, 'react/jsx-no-undef': 2, 'react/jsx-sort-props': 0, 'react/jsx-uses-react': 2, 'react/jsx-uses-vars': 2, 'react/no-did-mount-set-state': 2, 'react/no-did-update-set-state': 2, 'react/no-multi-comp': 0, 'react/no-unknown-property': 2, 'react/prop-types': 2, 'react/react-in-jsx-scope': 2, 'react/self-closing-comp': 2, 'react/wrap-multilines': 2 } };
Add type of mailer in contructor
<?php namespace SfVlc\MainBundle\Mailer; use SfVlc\MainBundle\Form\Model\Contact; use SfVlc\MainBundle\Mailer\ContactConfigurationInterface; class Mailer { protected $mailer; protected $settings; function __construct(\Swift_Mailer $mailer, ContactConfigurationInterface $settings) { $this->mailer = $mailer; $this->settings = $settings; } public function sendContactEmail(Contact $contact) { $message = \Swift_Message::newInstance() ->setSubject($this->settings->getSubject()) ->setFrom($contact->email) ->setTo($this->settings->getTo()) ->setBody($contact->name . ' ' . $contact->message) ; $this->mailer->send($message); } }
<?php namespace SfVlc\MainBundle\Mailer; use SfVlc\MainBundle\Form\Model\Contact; use SfVlc\MainBundle\Mailer\ContactConfigurationInterface; class Mailer { protected $mailer; protected $settings; function __construct($mailer, ContactConfigurationInterface $settings) { $this->mailer = $mailer; $this->settings = $settings; } public function sendContactEmail(Contact $contact) { $message = \Swift_Message::newInstance() ->setSubject($this->settings->getSubject()) ->setFrom($contact->email) ->setTo($this->settings->getTo()) ->setBody($contact->name . ' ' . $contact->message) ; $this->mailer->send($message); } }
Add support for second `config` param
import { ApolloClient } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { createUploadLink } from 'apollo-upload-client'; import csrf from '~/lib/utils/csrf'; export default (resolvers = {}, config = {}) => { let uri = `${gon.relative_url_root}/api/graphql`; if (config.baseUrl) { // Prepend baseUrl and ensure that `///` are replaced with `/` uri = `${config.baseUrl}${uri}`.replace(/\/{3,}/g, '/'); } return new ApolloClient({ link: createUploadLink({ uri, headers: { [csrf.headerKey]: csrf.token, }, }), cache: new InMemoryCache(config.cacheConfig), resolvers, }); };
import { ApolloClient } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { createUploadLink } from 'apollo-upload-client'; import csrf from '~/lib/utils/csrf'; export default (resolvers = {}, baseUrl = '') => { let uri = `${gon.relative_url_root}/api/graphql`; if (baseUrl) { // Prepend baseUrl and ensure that `///` are replaced with `/` uri = `${baseUrl}${uri}`.replace(/\/{3,}/g, '/'); } return new ApolloClient({ link: createUploadLink({ uri, headers: { [csrf.headerKey]: csrf.token, }, }), cache: new InMemoryCache(), resolvers, }); };
Use gopass to catch the password without displaying it
package config import ( "bufio" "fmt" "github.com/howeyc/gopass" "log" "os" "strings" ) func getUsername(configuration *Configuration) { for { reader := bufio.NewReader(os.Stdin) fmt.Print("Spotify Username: ") username, err := reader.ReadString('\n') if err != nil { log.Fatal(err) } if len(username)-1 > 0 { configuration.Username = strings.TrimSpace(username) return } else { fmt.Println("Empty username, please try again") } } } func getPassword(configuration *Configuration) { for { fmt.Print("Spotify Password (will not be stored): ") password := string(gopass.GetPasswd()) if len(password) > 0 { configuration.Password = strings.TrimSpace(password) return } else { fmt.Println("Empty password, please try again") } } } func StartWizard(configuration *Configuration) *Configuration { getUsername(configuration) getPassword(configuration) return configuration }
package config import ( "bufio" "fmt" "log" "os" "strings" ) func getUsername(configuration *Configuration) { for { reader := bufio.NewReader(os.Stdin) fmt.Print("Spotify Username: ") username, err := reader.ReadString('\n') if err != nil { log.Fatal(err) } if len(username)-1 > 0 { configuration.Username = strings.TrimSpace(username) return } else { fmt.Println("Empty username, please try again") } } } func getPassword(configuration *Configuration) { for { reader := bufio.NewReader(os.Stdin) fmt.Print("Spotify Password (will not be stored): ") password, err := reader.ReadString('\n') if err != nil { log.Fatal(err) } if len(password)-1 > 0 { configuration.Password = strings.TrimSpace(password) return } else { fmt.Println("Empty password, please try again") } } } func StartWizard(configuration *Configuration) *Configuration { getUsername(configuration) getPassword(configuration) return configuration }
Implement shells for law index collection chooser.
import React, { PropTypes } from 'react'; import { List } from 'immutable'; import { range } from 'lodash'; import ImmutableTypes from 'react-immutable-proptypes'; import { Grid, Cell, Button } from 'react-mdl'; const shell = List(range(4).map(() => '')); const LawCollectionChooser = ({ collections, selected, onSelect }) => ( <Grid> {(collections.size ? collections : shell).map((title, idx) => ( <Cell key={title || `shell-${idx}`} col={3} tablet={4} phone={4} > <Button ripple raised disabled={title === ''} accent={selected === title} onClick={() => onSelect(selected !== title ? title : '')} style={{ width: '100%' }} > {title} </Button> </Cell> ))} </Grid> ); LawCollectionChooser.propTypes = { collections: ImmutableTypes.listOf(PropTypes.string).isRequired, onSelect: PropTypes.func.isRequired, selected: PropTypes.string, }; export default LawCollectionChooser;
import React, { PropTypes } from 'react'; import ImmutableTypes from 'react-immutable-proptypes'; import { Grid, Cell, Button } from 'react-mdl'; const LawCollectionChooser = ({ collections, selected, onSelect }) => ( <Grid noSpacing> {collections.map(title => ( <Cell key={title} col={3} tablet={4} phone={1}> <Button ripple raised accent={selected === title} onClick={() => onSelect(selected !== title ? title : '')} > {title} </Button> </Cell> ))} </Grid> ); LawCollectionChooser.propTypes = { collections: ImmutableTypes.listOf(PropTypes.string).isRequired, onSelect: PropTypes.func.isRequired, selected: PropTypes.string, }; export default LawCollectionChooser;
Fix typo in unused readUnsignedByte method of MinecraftProtocol
package net.md_5.bungee.protocol; import io.netty.buffer.ByteBuf; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class MinecraftInput { private final ByteBuf buf; public byte readByte() { return buf.readByte(); } public short readUnsignedByte() { return buf.readUnsignedByte(); } public int readInt() { return buf.readInt(); } public String readString() { short len = buf.readShort(); char[] c = new char[ len ]; for ( int i = 0; i < c.length; i++ ) { c[i] = buf.readChar(); } return new String( c ); } }
package net.md_5.bungee.protocol; import io.netty.buffer.ByteBuf; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class MinecraftInput { private final ByteBuf buf; public byte readByte() { return buf.readByte(); } public short readUnisgnedByte() { return buf.readUnsignedByte(); } public int readInt() { return buf.readInt(); } public String readString() { short len = buf.readShort(); char[] c = new char[ len ]; for ( int i = 0; i < c.length; i++ ) { c[i] = buf.readChar(); } return new String( c ); } }
style: Change eslint rule no-empty: allowEmptyCatch
module.exports = { "env": { "node": true }, "extends": "eslint:recommended", "rules": { "indent": [ "error", 2 ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ], "no-unused-vars": [ "error", { "vars": "all", "args": "none" } ], "no-empty": [ "error", { "allowEmptyCatch": true } ] } };
module.exports = { "env": { "node": true }, "extends": "eslint:recommended", "rules": { "indent": [ "error", 2 ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ], "no-unused-vars": [ "error", { "vars": "all", "args": "none" } ] } };
Fix rules x,y on image_obj Coordinates for manual cropping. The first pair are X and Y coordinates, for the left, top point and the second pair are X and Y coordinates, for the right, bottom point (thus forming the square to crop);
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop """ if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign """ new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_y1), (image.crop_x2, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop """ if image.halign != "": new['halign'] = image.halign if image.valign != "": new['valign'] = image.valign """ new['fit_in'] = image.fit_in new['smart'] = image.smart if image.crop_x1 > 0 or image.crop_x2 > 0 or image.crop_y1 > 0 or \ image.crop_y2 > 0: new['crop'] = ((image.crop_x1, image.crop_x2), (image.crop_y1, image.crop_y2)) kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
Reduce scope of event broadcast
'use strict'; /** * @ngdoc function * @name websocketTesterApp.controller:MainCtrl * @description * # MainCtrl * Controller of the websocketTesterApp */ angular.module('websocketTesterApp') .controller('MainCtrl', function ($window, $scope, $log, $websocket) { var self, socket; self = this; function pushDialogue(message) { $scope.$broadcast('ADD_LOG_LINE', message); } self.connect = function(url) { try { socket = $websocket(url); } catch (e) { pushDialogue('*** Error: ' + e.message); return; } socket.onOpen(function() { pushDialogue('*** Connected to: ' + url); }); socket.onClose(function() { pushDialogue('*** Disconnected from: ' + url); }); socket.onError(function() { pushDialogue('*** Error: Check browser console for more information'); }); socket.onMessage(function(message) { pushDialogue('->' + message.data); }); }; self.disconnect = function() { socket.close(); }; self.send = function(message) { socket.send(message).then(function() { pushDialogue('<-' + message); }); }; });
'use strict'; /** * @ngdoc function * @name websocketTesterApp.controller:MainCtrl * @description * # MainCtrl * Controller of the websocketTesterApp */ angular.module('websocketTesterApp') .controller('MainCtrl', function ($window, $rootScope, $log, $websocket) { var self, socket; self = this; function pushDialogue(message) { $rootScope.$broadcast('ADD_LOG_LINE', message); } self.connect = function(url) { try { socket = $websocket(url); } catch (e) { pushDialogue('*** Error: ' + e.message); return; } socket.onOpen(function() { pushDialogue('*** Connected to: ' + url); }); socket.onClose(function() { pushDialogue('*** Disconnected from: ' + url); }); socket.onError(function() { pushDialogue('*** Error: Check browser console for more information'); }); socket.onMessage(function(message) { pushDialogue('->' + message.data); }); }; self.disconnect = function() { socket.close(); }; self.send = function(message) { socket.send(message).then(function() { pushDialogue('<-' + message); }); }; });
Correct bug introduced in the previous commit (last update in feed entries).
from google.appengine.ext import db from google.appengine.api.users import User class Cfp(db.Model): name = db.StringProperty() fullname = db.StringProperty() website = db.LinkProperty() begin_conf_date = db.DateProperty() end_conf_date = db.DateProperty() submission_deadline = db.DateProperty() notification_date = db.DateProperty() country = db.StringProperty() city = db.StringProperty() rate = db.RatingProperty() submitters = db.ListProperty(User) category = db.StringProperty() keywords = db.StringListProperty() last_update = db.DateTimeProperty(auto_now=True) def setWebsite(self, link): self.website = db.Link(link) def setAcceptanceRate(self, rate): self.rate = db.Rating(rate) def rfc3339_update(self): return self.last_update.strftime('%Y-%m-%dT%H:%M:%SZ')
from google.appengine.ext import db from google.appengine.api.users import User class Cfp(db.Model): name = db.StringProperty() fullname = db.StringProperty() website = db.LinkProperty() begin_conf_date = db.DateProperty() end_conf_date = db.DateProperty() submission_deadline = db.DateProperty() notification_date = db.DateProperty() country = db.StringProperty() city = db.StringProperty() rate = db.RatingProperty() submitters = db.ListProperty(User) category = db.StringProperty() keywords = db.StringListProperty() last_update = db.DateTimeProperty(auto_now=True) def setWebsite(self, link): self.website = db.Link(link) def setAcceptanceRate(self, rate): self.rate = db.Rating(rate) def rfc3339_update(): return last_update.strftime('%Y-%m-%dT%H:%M:%SZ')
Fix <0 TBB and <0 category headers not showing
(function poll() { if ( typeof ynabToolKit !== "undefined" && ynabToolKit.actOnChangeInit === true) { ynabToolKit.removeZeroCategories = function () { var coverOverbudgetingCategories = $( ".modal-budget-overspending .options-shown .ynab-select-options" ).children('li:not(:first-child)'); coverOverbudgetingCategories.each(function(i) { var t = $(this).text(); // Category balance text. var categoryBalance = parseInt(t.substr(t.indexOf(":"), t.length).replace(/[^\d-]/g, '')); if ($(this).hasClass('is-selectable') && categoryBalance <= 0) { $(this).remove(); } }); }; ynabToolKit.removeZeroCategories(); // Run itself once } else { setTimeout(poll, 250); } })();
(function poll() { if ( typeof ynabToolKit !== "undefined" && ynabToolKit.actOnChangeInit === true) { ynabToolKit.removeZeroCategories = function () { var coverOverbudgetingCategories = $( ".modal-budget-overspending .options-shown .ynab-select-options" ).children('li'); coverOverbudgetingCategories.each(function(i) { var t = $(this).text(); // Category balance text. var categoryBalance = parseInt(t.substr(t.indexOf(":"), t.length).replace(/[^\d-]/g, '')); if (categoryBalance <= 0) { $(this).remove(); } }); }; ynabToolKit.removeZeroCategories(); // Run itself once } else { setTimeout(poll, 250); } })();
Update test function for testing mapping of full organism names
<?php namespace Tests\AppBundle\API\Mapping; use Symfony\Component\HttpFoundation\ParameterBag; use Tests\AppBundle\API\WebserviceTestCase; use AppBundle\API\Mapping; class FullByOrganismNameTest extends WebserviceTestCase { private $em; private $fullByOrganismName; public function setUp() { $kernel = self::bootKernel(); $this->em = $kernel->getContainer() ->get('doctrine') ->getManager('test'); $this->fullByOrganismName = $kernel->getContainer()->get(Mapping\FullByOrganismName::class); } public function tearDown() { parent::tearDown(); $this->em->close(); $this->em = null; // avoid memory leaks } public function testExecute() { $result = $this->fullByOrganismName->execute(); $this->assertEquals(195203, count($result)); $this->assertEquals(10, $result['Dunaliella tertiolecta']); $this->assertEquals([213,196104], $result['Onoclea sensibilis']); $this->assertEquals(353, $result['Ranunculaceae']); $this->assertEquals(1224, $result['Nymphaea']); $this->assertEquals(12341, $result['Diphasiastrum alpinum']); } }
<?php namespace Tests\AppBundle\API\Mapping; use Symfony\Component\HttpFoundation\ParameterBag; use Tests\AppBundle\API\WebserviceTestCase; class FullByOrganismNameTest extends WebserviceTestCase { public function testExecute() { $service = $this->webservice->factory('mapping', 'fullByOrganismName'); $result = $service->execute(new ParameterBag(array('dbversion' => $this->default_db)), null); $this->assertEquals(195203, count($result)); $this->assertEquals(10, $result['Dunaliella tertiolecta']); $this->assertEquals([213,196104], $result['Onoclea sensibilis']); $this->assertEquals(353, $result['Ranunculaceae']); $this->assertEquals(1224, $result['Nymphaea']); $this->assertEquals(12341, $result['Diphasiastrum alpinum']); } }
Use shutil for 'which docker'
import os import pytest import shutil hasdocker = pytest.mark.skipif(shutil.which("docker") is None, reason="Docker must be installed.") """A decorator to skip a test if docker is not installed.""" @hasdocker def test_build(parse_and_run): """Test vanilla assignment build """ path = parse_and_run(["init", "cpl"]) parse_and_run(["new", "a1"]) dockerfile_path = os.path.join(path, "assignments", "a1", "gradesheet", "Dockerfile") with open(dockerfile_path, 'w') as dockerfile: dockerfile.write("FROM ubuntu:12.04") parse_and_run(["build", "a1"])
import os import pytest from subprocess import Popen, PIPE def has_installed(program): """Checks to see if a program is installed using ``which``. :param str program: the name of the program we're looking for :rtype bool: :return: True if it's installed, otherwise False. """ proc = Popen(["which", program], stdout=PIPE, stderr=PIPE) exit_code = proc.wait() return exit_code == 0 hasdocker = pytest.mark.skipif(not has_installed("docker"), reason="Docker must be installed.") """A decorator to skip a test if docker is not installed.""" @hasdocker def test_build(parse_and_run): """Test vanilla assignment build """ path = parse_and_run(["init", "cpl"]) parse_and_run(["new", "a1"]) dockerfile_path = os.path.join(path, "assignments", "a1", "gradesheet", "Dockerfile") with open(dockerfile_path, 'w') as dockerfile: dockerfile.write("FROM ubuntu:12.04") parse_and_run(["build", "a1"])
Use of instead of in for iteration
function checkDuplicateUser(playQueue, video, config) { if (config.userQueueLimit <= -1) return false; var count = 0; for (element of playQueue) { if (element.userId === video.userId) count++; } return (count > config.userQueueLimit); } function checkDuplicateVideo(playQueue, video, config) { for (element of playQueue) { if (element.vid === video.vid) return true; } return false; } function checkVideoLength(playQueue, video, config) { if (config.maxLength > -1) { if (video.length_seconds > config.maxLength) { return true; } } return false; } var checks = [ [checkDuplicateVideo, 'That video is already in the queue'], [checkDuplicateUser, 'You already have two videos in the queue'], [checkVideoLength, 'That video is too long!'], ]; function shouldDisallowQueue(playQueue, video, config) { for (check of checks) { if (config.checksEnabled[check[0].name]) { result = check[0](playQueue, video, config); if (result) return check[1]; } } return false; } module.exports = shouldDisallowQueue;
function checkDuplicateUser(playQueue, video, config) { if (config.userQueueLimit <= -1) return false; var count = 0; for (element in playQueue) { if (element.userId === video.userId) count++; } return (count > config.userQueueLimit); } function checkDuplicateVideo(playQueue, video, config) { for (element in playQueue) { if (element.vid === video.vid) return true; } return false; } function checkVideoLength(playQueue, video, config) { if (config.maxLength > -1) { if (video.length_seconds > config.maxLength) { return true; } } return false; } var checks = [ [checkDuplicateVideo, 'That video is already in the queue'], [checkDuplicateUser, 'You already have two videos in the queue'], [checkVideoLength, 'That video is too long!'], ]; function shouldDisallowQueue(playQueue, video, config) { for (check of checks) { if (config.checksEnabled[check[0].name]) { result = check[0](playQueue, video, config); if (result) return check[1]; } } return false; } module.exports = shouldDisallowQueue;
phpdoc: Use class level method definition to re-define method return type
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Cache * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Cache\Storage; /** * @category Zend * @package Zend_Cache * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * * @method IteratorInterface getIterator() Get the storage iterator */ interface IterableInterface extends \IteratorAggregate { }
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Cache * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Cache\Storage; /** * @category Zend * @package Zend_Cache * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface IterableInterface extends \IteratorAggregate { /** * Get the storage iterator * * @return IteratorInterface */ // PHP 5.3.3: Fatal error: Can't inherit abstract function IteratorAggregate::getIterator() // (previously declared abstract in Zend\Cache\Storage\IterableInterface) //public function getIterator(); }
fix(terminal): Print output directly on console with no formatting
'use strict'; var util = require('util'); function Terminal() { this.subLevel = 1; } /** * Display received data in format on terminal * @param {Object|string} data */ Terminal.prototype.show = function (data) { if (data['type'] === 'notify') { if (data['tag'] === 'START_FLAG_UP') { this.subLevel++; } if (data['tag'] === 'START_FLAG_DOWN') { this.subLevel--; } return this.subLevel; } if (this.subLevel > 0) { if (data['type'] === 'message') { var tab = ' '; for (var i = 0 ; i < this.subLevel - 1 ; i++) { tab += tab; } delete data['type']; //console.log(tab + '*', util.inspect(data['data'], false, null)); process.stdout.write(data['data']); } } return this.subLevel; }; module.exports = Terminal;
'use strict'; var util = require('util'); function Terminal() { this.subLevel = 1; } /** * Display received data in format on terminal * @param {Object|string} data */ Terminal.prototype.show = function (data) { if (data['type'] === 'notify') { if (data['tag'] === 'START_FLAG_UP') { this.subLevel++; } if (data['tag'] === 'START_FLAG_DOWN') { this.subLevel--; } return this.subLevel; } if (this.subLevel > 0) { if (data['type'] === 'message') { var tab = ' '; for (var i = 0 ; i < this.subLevel - 1 ; i++) { tab += tab; } delete data['type']; console.log(tab + '*', util.inspect(data['data'], false, null)); } } return this.subLevel; }; module.exports = Terminal;
Update classifiers; conditionally require `futures` on Python 2 The `concurrent` library is part of Python 3 stdlib, by requiring futures we would fetch the old py2 version which causes syntax errors on py3.
from setuptools import setup setup( name='beets-alternatives', version='0.8.3-dev', description='beets plugin to manage multiple files', long_description=open('README.md').read(), author='Thomas Scholtes', author_email='thomas-scholtes@gmx.de', url='http://www.github.com/geigerzaehler/beets-alternatives', license='MIT', platforms='ALL', test_suite='test', packages=['beetsplug'], install_requires=[ 'beets>=1.4.7', 'futures; python_version<"3"', ], classifiers=[ 'Topic :: Multimedia :: Sound/Audio', 'Topic :: Multimedia :: Sound/Audio :: Players :: MP3', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], )
from setuptools import setup setup( name='beets-alternatives', version='0.8.3-dev', description='beets plugin to manage multiple files', long_description=open('README.md').read(), author='Thomas Scholtes', author_email='thomas-scholtes@gmx.de', url='http://www.github.com/geigerzaehler/beets-alternatives', license='MIT', platforms='ALL', test_suite='test', packages=['beetsplug'], install_requires=[ 'beets>=1.4.7', 'futures', ], classifiers=[ 'Topic :: Multimedia :: Sound/Audio', 'Topic :: Multimedia :: Sound/Audio :: Players :: MP3', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
feat: Add title for every router use router.afterEach to set document title.
import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import Home from './Home'; // import Counter from './Counter' const Counter = resolve => require.ensure([], () => resolve(require('./Counter').default), 'counter'); const GeographicalIp = resolve => require.ensure([], () => resolve(require('./GeographicalIp').default)); const routes = [ { name: 'home', path: '/', component: Home, meta: { title: 'Home' } }, { name: 'counter', path: '/counter', component: Counter, meta: { title: 'Counter' } }, { name: 'geographicalIp', path: '/geographical-ip', component: GeographicalIp, meta: { title: 'Geographical Ip' } } ] const router = new VueRouter({ routes, mode: 'history' }) router.afterEach(to => { if (to.meta.title !== undefined) { document.title = `${ to.meta.title } - Vue-vuex-starter-kit` } }) export default router
import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import Home from './Home'; // import Counter from './Counter' const Counter = resolve => require.ensure([], () => resolve(require('./Counter').default), 'counter'); const GeographicalIp = resolve => require.ensure([], () => resolve(require('./GeographicalIp').default)); const routes = [ { name: 'home', path: '/', component: Home, meta: { title: 'Home' } }, { name: 'counter', path: '/counter', component: Counter, meta: { title: 'Counter' } }, { name: 'geographicalIp', path: '/geographical-ip', component: GeographicalIp, meta: { title: 'Geographical Ip' } } ] const router = new VueRouter({ routes, mode: 'history' }) export default router
Remove cube credentials from import script
#!/usr/bin/python import django.contrib.auth.models as auth_models import django.contrib.contenttypes as contenttypes def get_password(): print "*" * 80 password = raw_input("Please enter string to use as admin password: ") check_password = None while check_password != password: print check_password = raw_input("Please re-enter for confirmation: ") return password def main(): # Read only user: # auth_models.User.objects.create_user('cube', 'toolkit_admin_readonly@localhost', '********') # Read/write user: cube_password = get_password() user_rw = auth_models.User.objects.create_user('admin', 'toolkit_admin@localhost', cube_password) # Create dummy ContentType: ct = contenttypes.models.ContentType.objects.get_or_create( model='', app_label='toolkit' )[0] # Create 'write' permission: write_permission = auth_models.Permission.objects.get_or_create( name='Write access to all toolkit content', content_type=ct, codename='write' )[0] # Give "admin" user the write permission: user_rw.user_permissions.add(write_permission) if __name__ == "__main__": main()
#!/usr/bin/python import django.contrib.auth.models as auth_models import django.contrib.contenttypes as contenttypes def main(): # Read only user: # auth_models.User.objects.create_user('cube', 'toolkit_admin_readonly@localhost', '***REMOVED***') # Read/write user: user_rw = auth_models.User.objects.create_user('admin', 'toolkit_admin@localhost', '***REMOVED***') # Create dummy ContentType: ct = contenttypes.models.ContentType.objects.get_or_create( model='', app_label='toolkit' )[0] # Create 'write' permission: write_permission = auth_models.Permission.objects.get_or_create( name='Write access to all toolkit content', content_type=ct, codename='write' )[0] # Give "admin" user the write permission: user_rw.user_permissions.add(write_permission) if __name__ == "__main__": main()
Fix docstring for Target values
from citrination_client.base.errors import CitrinationClientError class Target(object): """ The optimization target for a design run. Consists of the name of the output column to optimize and the objective (either "Max" or "Min") """ def __init__(self, name, objective): """ Constructor. :param name: The name of the target output column :type name: str :param objective: The optimization objective; "Min", "Max", or a scalar value (such as "5.0") :type objective: str """ try: self._objective = float(objective) except ValueError: if objective.lower() not in ["max", "min"]: raise CitrinationClientError( "Target objective must either be \"min\" or \"max\"" ) self._objective = objective self._name = name def to_dict(self): return { "descriptor": self._name, "objective": self._objective }
from citrination_client.base.errors import CitrinationClientError class Target(object): """ The optimization target for a design run. Consists of the name of the output column to optimize and the objective (either "Max" or "Min") """ def __init__(self, name, objective): """ Constructor. :param name: The name of the target output column :type name: str :param objective: The optimization objective; either "Min" or "Max" :type objective: str """ try: self._objective = float(objective) except ValueError: if objective.lower() not in ["max", "min"]: raise CitrinationClientError( "Target objective must either be \"min\" or \"max\"" ) self._objective = objective self._name = name def to_dict(self): return { "descriptor": self._name, "objective": self._objective }
Fix to long decimal places
package net.izenith.Commands; import java.text.DecimalFormat; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permission; import net.izenith.Main.Util; import net.md_5.bungee.api.ChatColor; public class PlayTime implements HubCommand{ @Override public String getName() { return "playtime"; } @Override public String[] getAliases() { return new String[]{"play","givemearimjobandbitemyear"}; } @Override public void onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Long time = Util.getOnlineTime(Bukkit.getPlayer(args[0])); Double timeHours = new Double(time)/(1000*60*60); DecimalFormat df = new DecimalFormat("#.##"); String shortTime = df.format(timeHours); sender.sendMessage(ChatColor.BLUE + args[0] + " has played for " + ChatColor.GREEN + shortTime + " hours"); } @Override public boolean onlyPlayers() { return false; } @Override public boolean hasPermission() { return false; } @Override public Permission getPermission() { return null; } }
package net.izenith.Commands; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permission; import net.izenith.Main.Util; import net.md_5.bungee.api.ChatColor; public class PlayTime implements HubCommand{ @Override public String getName() { return "playtime"; } @Override public String[] getAliases() { return new String[]{"play","givemearimjobandbitemyear"}; } @Override public void onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Long time = Util.getOnlineTime(Bukkit.getPlayer(args[0])); Double timeHours = new Double(time)/(1000*60*60); sender.sendMessage(ChatColor.BLUE + args[0] + " has played for " + ChatColor.GREEN + timeHours + " hours"); } @Override public boolean onlyPlayers() { return false; } @Override public boolean hasPermission() { return false; } @Override public Permission getPermission() { return null; } }
Add group and order by to infoOpTargetDominions
<?php namespace OpenDominion\Models; class Realm extends AbstractModel { public function councilThreads() { return $this->hasMany(Council\Thread::class); } public function dominions() { return $this->hasMany(Dominion::class); } public function infoOps() { return $this->hasMany(InfoOp::class, 'source_realm_id'); } public function infoOpTargetDominions() { return $this->hasManyThrough( Dominion::class, InfoOp::class, 'source_realm_id', 'id', null, 'target_dominion_id' ) ->groupBy('target_dominion_id') ->orderBy('updated_at', 'desc'); } public function monarch() { // return $this->hasOne(Dominion::class, 'id', 'monarch_dominion_id'); } public function round() { return $this->belongsTo(Round::class); } public function hasInfoOp(Dominion $targetDominion, string $infoOp) { // } }
<?php namespace OpenDominion\Models; class Realm extends AbstractModel { public function councilThreads() { return $this->hasMany(Council\Thread::class); } public function dominions() { return $this->hasMany(Dominion::class); } public function infoOps() { return $this->hasMany(InfoOp::class, 'source_realm_id'); } public function infoOpTargetDominions() { return $this->hasManyThrough( Dominion::class, InfoOp::class, 'source_realm_id', 'id', null, 'target_dominion_id' ); } public function monarch() { // return $this->hasOne(Dominion::class, 'id', 'monarch_dominion_id'); } public function round() { return $this->belongsTo(Round::class); } public function hasInfoOp(Dominion $targetDominion, string $infoOp) { // } }