text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update relative path for favicon
module.exports = { plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `content`, path: `${__dirname}/../content`, }, }, { resolve: `gatsby-plugin-manifest`, options: { icon: `src/images/kitura.svg` }, }, { resolve: `gatsby-transformer-remark`, options: { plugins: [ { resolve: `gatsby-remark-images`, options: { // It's important to specify the maxWidth (in pixels) of // the content container as this plugin uses this as the // base for generating different widths of each image. maxWidth: 1200, }, }, `gatsby-remark-autolink-headers`, `gatsby-remark-prismjs`], } }, `gatsby-transformer-yaml`, `gatsby-plugin-sass`, ] }
module.exports = { plugins: [ { resolve: `gatsby-source-filesystem`, options: { name: `content`, path: `${__dirname}/../content`, }, }, { resolve: `gatsby-plugin-manifest`, options: { icon: `${__dirname}/src/images/kitura.svg` }, }, { resolve: `gatsby-transformer-remark`, options: { plugins: [ { resolve: `gatsby-remark-images`, options: { // It's important to specify the maxWidth (in pixels) of // the content container as this plugin uses this as the // base for generating different widths of each image. maxWidth: 1200, }, }, `gatsby-remark-autolink-headers`, `gatsby-remark-prismjs`], } }, `gatsby-transformer-yaml`, `gatsby-plugin-sass`, ] }
Change view for login url. Add url for index page
"""restaurant URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.contrib import admin from django.contrib.auth import views as auth_views from django.conf.urls import url from views.index_view import index from views.login_view import login_view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', index, name='index'), url(r'^account/login/$', login_view, name='login'), url(r'^account/password_reset/$', auth_views.password_reset, name='password_reset'), url(r'^account/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), ]
"""restaurant URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^account/login/$', auth_views.login, name='login'), url(r'^account/password_reset/$', auth_views.password_reset, name='password_reset'), url(r'^account/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), ]
Change to invalid keys policy.
"use strict" var NCMBInstallationEx = module.exports = (function() { var invalidKeys = [ 'objectId' , 'createDate' , 'updateDate' ]; function NCMBInstallationEx(ncmb) { this.__proto__.ncmb = ncmb; this.__proto__.className = '/installations'; } NCMBInstallationEx.prototype.register = function(attrs, callback) { var ncmb = this.ncmb; var dataToPost = {}; Object.keys(attrs).forEach(function(attr) { if (invalidKeys.indexOf(attr) == -1) { dataToPost[attr] = attrs[attr]; } }); return ncmb.request({ path: "/" + ncmb.version + this.className, method: "POST", data: dataToPost }).then(function(data){ var obj = null; try { obj = JSON.parse(data); } catch(err) { throw err; } if (callback) { return callback(null, this); } return this; }.bind(this)).catch(function(err){ if(callback) return callback(err, null); throw err; }); }; return NCMBInstallationEx; })();
"use strict" var NCMBInstallationEx = module.exports = (function() { var validKeys = [ 'applicationName' , 'appVersion' , 'badge' , 'channels' , 'deviceToken' , 'deviceType' , 'sdkVersion' , 'timeZone' , 'acl' ]; function NCMBInstallationEx(ncmb) { this.__proto__.ncmb = ncmb; this.__proto__.className = '/installations'; } NCMBInstallationEx.prototype.register = function(attrs, callback) { var ncmb = this.ncmb; var dataToPost = {}; Object.keys(attrs).forEach(function(attr) { if (validKeys.indexOf(attr) != -1) { dataToPost[attr] = attrs[attr]; } }); return ncmb.request({ path: "/" + ncmb.version + this.className, method: "POST", data: dataToPost }).then(function(data){ var obj = null; try { obj = JSON.parse(data); } catch(err) { throw err; } if (callback) { return callback(null, this); } return this; }.bind(this)).catch(function(err){ if(callback) return callback(err, null); throw err; }); }; return NCMBInstallationEx; })();
Fix failure handler alway throw exception
package com.admicro.vertxlet.core.handler.impl; import com.admicro.vertxlet.core.handler.FailureHandler; import com.admicro.vertxlet.core.HttpServerVerticle; import com.admicro.vertxlet.core.db.IDbConnector; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.web.RoutingContext; import java.util.Map; public class FailureHandlerImpl implements FailureHandler { private static final Logger _logger = LoggerFactory.getLogger(FailureHandlerImpl.class); @Override public void handle(RoutingContext rc) { _logger.error("Unexpected error occur", rc.failure()); // Guarantee db connections is closed when error occurs Map<String, IDbConnector> iDbAdaptorMap = rc.get(HttpServerVerticle.DATABASE_KEY); for (IDbConnector adaptor : iDbAdaptorMap.values()) { adaptor.close(v -> { }); } rc.response().putHeader("content-type", "text/html") .setStatusCode(500).end("<html><h1>Server internal error</h1></html>"); } }
package com.admicro.vertxlet.core.handler.impl; import com.admicro.vertxlet.core.handler.FailureHandler; import com.admicro.vertxlet.core.HttpServerVerticle; import com.admicro.vertxlet.core.db.IDbConnector; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.web.RoutingContext; import java.util.Map; public class FailureHandlerImpl implements FailureHandler { private static final Logger _logger = LoggerFactory.getLogger(FailureHandlerImpl.class); @Override public void handle(RoutingContext rc) { _logger.error("Unexpected error occur", rc.failure()); rc.fail(new Exception()); // Guarantee db connections is closed when error occurs Map<String, IDbConnector> iDbAdaptorMap = rc.get(HttpServerVerticle.DATABASE_KEY); for (IDbConnector adaptor : iDbAdaptorMap.values()) { adaptor.close(v -> { }); } rc.response().putHeader("content-type", "text/html") .setStatusCode(500).end("<html><h1>Server internal error</h1></html>"); } }
Refactor timezone implementation to fix read/write date attributes
<?php declare(strict_types=1); namespace Rinvex\Support\Traits; use DateTimeZone; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Date; trait HasTimezones { /** * Return a timestamp as DateTime object. * * @param mixed $value * * @return \Illuminate\Support\Carbon */ protected function asDateTime($value) { $datetime = parent::asDateTime($value); $timezone = app()->bound('request.user') ? optional(app('request.user'))->timezone : null; if (! $timezone || $timezone === config('app.timezone')) { return $datetime; } $thisIsUpdateRequest = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) { return $trace['function'] === 'setAttribute'; }); if ($thisIsUpdateRequest) { // When updating attributes, we need to reset user timezone to system timezone before saving! return Date::parse($datetime->toDateTimeString(), $timezone)->setTimezone(config('app.timezone')); } return $datetime->setTimezone(new DateTimeZone($timezone)); } }
<?php declare(strict_types=1); namespace Rinvex\Support\Traits; use DateTimeZone; use Illuminate\Support\Arr; trait HasTimezones { /** * Return a timestamp as DateTime object. * * @param mixed $value * @return \Illuminate\Support\Carbon */ protected function asDateTime($value) { $datetime = parent::asDateTime($value); $setAttributeCalled = Arr::first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 30), function ($trace) { return $trace['function'] === 'setAttribute'; }); // When setting attributes, skip custom timezone setting, // and use default application settings for consistent storage! if (! $setAttributeCalled && app()->bound('request.user') && $timezone = optional(app('request.user'))->timezone) { $datetime->setTimezone(new DateTimeZone($timezone)); } return $datetime; } }
Make verbose loading messages optional
import new import sys DEBUG = False method_count = 0 def method(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab, modules, static): global method_count if DEBUG: print 'define', name, method_count method_count += 1 globals_dict = {} for module_name in modules: if not '[' in module_name and not '.' in module_name: globals_dict[module_name] = __import__(module_name, {}) code = new.code(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab) method = new.function(code, globals_dict, name) return staticmethod(method) if static else method nan = None inf = sys.maxint
import sys method_count = 0 def method(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab, modules, static): global method_count print 'define', name, method_count method_count += 1 globals_dict = {} for module_name in modules: if not '[' in module_name and not '.' in module_name: globals_dict[module_name] = __import__(module_name, {}) code = new.code(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab) method = new.function(code, globals_dict, name) return staticmethod(method) if static else method nan = None inf = sys.maxint
Store local url in a variable and display it once for both text and image.
L.controlCredits = function(t) { return new L.CreditsControl(t) }, L.CreditsControl = L.Control.extend({ options: { position: "bottomright" }, initialize: function(t) { if (!t.text) throw "L.CreditsControl missing required option: text"; if (!t.image) throw "L.CreditsControl missing required option: image"; if (!t.link) throw "L.CreditsControl missing required option: link"; L.setOptions(this, t) }, onAdd: function(t) { this._map = t; var i = L.DomUtil.create("div", "leaflet-credits-control", i); i.style.backgroundImage = "url(" + this.options.image + ")", this.options.width && (i.style.paddingRight = this.options.width + "px"), this.options.height && (i.style.height = this.options.height + "px"); var o = L.DomUtil.create("a", "", i); L.DomUtil.addClass(o,'leaflet-credits-showlink'); var lurl = this.options.link; i.onclick = function(){ window.open(lurl, "_blank"); } return o.target = "_blank", o.innerHTML = this.options.text, this._container = i, this._link = o, i }, setText: function(t) { this._link.innerHTML = t } });
L.controlCredits = function(t) { return new L.CreditsControl(t) }, L.CreditsControl = L.Control.extend({ options: { position: "bottomright" }, initialize: function(t) { if (!t.text) throw "L.CreditsControl missing required option: text"; if (!t.image) throw "L.CreditsControl missing required option: image"; if (!t.link) throw "L.CreditsControl missing required option: link"; L.setOptions(this, t) }, onAdd: function(t) { this._map = t; var i = L.DomUtil.create("div", "leaflet-credits-control", i); i.style.backgroundImage = "url(" + this.options.image + ")", this.options.width && (i.style.paddingRight = this.options.width + "px"), this.options.height && (i.style.height = this.options.height + "px"); var o = L.DomUtil.create("a", "", i); L.DomUtil.addClass(o,'leaflet-credits-showlink'); i.onclick = function(){ window.open(o.href, "_blank"); } return o.target = "_blank", o.innerHTML = this.options.text, i.link = o, this._container = i, this._link = o, i }, setText: function(t) { this._link.innerHTML = t } });
Remove Email module - missed tests
<?php namespace CodeIgniter\Config; use Config\Format; class ConfigTest extends \CIUnitTestCase { public function testCreateSingleInstance() { $Config = Config::get('Format', false); $NamespaceConfig = Config::get('Config\\Format', false); $this->assertInstanceOf(Format::class, $Config); $this->assertInstanceOf(Format::class, $NamespaceConfig); } public function testCreateInvalidInstance() { $Config = Config::get('gfnusvjai', false); $this->assertNull($Config); } public function testCreateSharedInstance() { $Config = Config::get('Format' ); $Config2 = Config::get('Config\\Format'); $this->assertTrue($Config === $Config2); } public function testCreateNonConfig() { $Config = Config::get('Constants', false); $this->assertNull($Config); } }
<?php namespace CodeIgniter\Config; use Config\Email; class ConfigTest extends \CIUnitTestCase { public function testCreateSingleInstance() { $Config = Config::get('Format', false); $NamespaceConfig = Config::get('Config\\Format', false); $this->assertInstanceOf(Format::class, $Config); $this->assertInstanceOf(Format::class, $NamespaceConfig); } public function testCreateInvalidInstance() { $Config = Config::get('gfnusvjai', false); $this->assertNull($Config); } public function testCreateSharedInstance() { $Config = Config::get('Format' ); $Config2 = Config::get('Config\\Format'); $this->assertTrue($Config === $Config2); } public function testCreateNonConfig() { $Config = Config::get('Constants', false); $this->assertNull($Config); } }
Update URLs to be Vantiv
<?php class Litle_LEcheck_Model_URL { public function toOptionArray() { return array( array( 'value' => "https://www.testvantivcnp.com/sandbox/communicator/online", 'label' => 'Sandbox' ), array( 'value' => "https://payments.vantivprelive.com/vap/communicator/online", 'label' => 'Prelive' ), array( 'value' => "https://payments.vantivpostlive.com/vap/communicator/online", 'label' => 'Postlive' ), array( 'value' => "https://payments.vantivcnp.com/vap/communicator/online", 'label' => 'Production' ) ); } }
<?php class Litle_LEcheck_Model_URL { public function toOptionArray() { return array( array( 'value' => "https://www.testlitle.com/sandbox/communicator/online", 'label' => 'Sandbox' ), array( 'value' => "https://prelive.litle.com/vap/communicator/online", 'label' => 'Prelive' ), array( 'value' => "https://postlive.litle.com/vap/communicator/online", 'label' => 'Postlive' ), array( 'value' => "https://payments.litle.com/vap/communicator/online", 'label' => 'Production' ) ); } }
Remove reference to Deadline in window title
import os import sys import avalon.api import avalon.fusion import pyblish_qml def _install_fusion(): from pyblish_qml import settings import pyblish_qml.host as host sys.stdout.write("Setting up Pyblish QML in Fusion\n") if settings.ContextLabel == settings.ContextLabelDefault: settings.ContextLabel = "Fusion" if settings.WindowTitle == settings.WindowTitleDefault: settings.WindowTitle = "Pyblish (Fusion)" def _set_current_working_dir(): # Set current working directory next to comp filename = comp.MapPath(comp.GetAttrs()["COMPS_FileName"]) if filename and os.path.exists(filename): cwd = os.path.dirname(filename) else: # Fallback to Avalon projects root # for unsaved files. cwd = os.environ["AVALON_PROJECTS"] os.chdir(cwd) print("Starting Pyblish setup..") # Install avalon avalon.api.install(avalon.fusion) # force current working directory to NON FUSION path # os.getcwd will return the binary folder of Fusion in this case _set_current_working_dir() # install fusion title _install_fusion() # Run QML in modal mode so it keeps listening to the # server in the main thread and keeps this process # open until QML finishes. print("Running publish_qml.show(modal=True)..") pyblish_qml.show(modal=True)
import os import sys import avalon.api import avalon.fusion import pyblish_qml def _install_fusion(): from pyblish_qml import settings import pyblish_qml.host as host sys.stdout.write("Setting up Pyblish QML in Fusion\n") if settings.ContextLabel == settings.ContextLabelDefault: settings.ContextLabel = "Fusion" if settings.WindowTitle == settings.WindowTitleDefault: settings.WindowTitle = "Pyblish (Fusion to Deadline)" def _set_current_working_dir(): # Set current working directory next to comp filename = comp.MapPath(comp.GetAttrs()["COMPS_FileName"]) if filename and os.path.exists(filename): cwd = os.path.dirname(filename) else: # Fallback to Avalon projects root # for unsaved files. cwd = os.environ["AVALON_PROJECTS"] os.chdir(cwd) print("Starting Pyblish setup..") # Install avalon avalon.api.install(avalon.fusion) # force current working directory to NON FUSION path # os.getcwd will return the binary folder of Fusion in this case _set_current_working_dir() # install fusion title _install_fusion() # Run QML in modal mode so it keeps listening to the # server in the main thread and keeps this process # open until QML finishes. print("Running publish_qml.show(modal=True)..") pyblish_qml.show(modal=True)
Allow empty data in value
def assign_to_variable_spec(data, spec, value): if not spec.startswith('@') or not spec.endswith('@'): raise ValueError("{} is not a reference".format(spec)) parts = spec.strip('@').split('.') data[parts[0]] = {} gen = data[parts[0]] for part in parts[1:-1]: gen[part] = {} gen = gen[part] gen[parts[-1]] = value return data[parts[0]] def resolve_variable_spec(data, spec): if data and spec.startswith('@') and spec.endswith('@'): for element in spec.strip('@').split('.'): data = data.get(element, None) if not data: break if data is None: raise ValueError("unresolved reference: {}".format(spec.strip("@"))) return data return spec
def assign_to_variable_spec(data, spec, value): if not spec.startswith('@') or not spec.endswith('@'): raise ValueError("{} is not a reference".format(spec)) parts = spec.strip('@').split('.') data[parts[0]] = {} gen = data[parts[0]] for part in parts[1:-1]: gen[part] = {} gen = gen[part] gen[parts[-1]] = value return data[parts[0]] def resolve_variable_spec(data, spec): if data and spec.startswith('@') and spec.endswith('@'): for element in spec.strip('@').split('.'): data = data.get(element, None) if not data: break if not data: raise ValueError("unresolved reference: {}".format(spec.strip("@"))) return data return spec
Fix nonprofit model is called nonprofit
/* eslint-disable no-process-exit */ require('babel/register'); require('dotenv').load(); var Rx = require('rx'); var app = require('../server/server'); var Nonprofits = app.models.Nonprofit; var nonprofits = require('./nonprofits.json'); var destroy = Rx.Observable.fromNodeCallback(Nonprofits.destroyAll, Nonprofits); var create = Rx.Observable.fromNodeCallback(Nonprofits.create, Nonprofits); destroy() .flatMap(function() { if (!nonprofits) { return Rx.Observable.throw(new Error('No nonprofits found')); } return create(nonprofits); }) .subscribe( function(nonprofits) { console.log('successfully saved %d nonprofits', nonprofits.length); }, function(err) { throw err; }, function() { console.log('nonprofit seed completed'); process.exit(0); } );
/* eslint-disable no-process-exit */ require('babel/register'); require('dotenv').load(); var Rx = require('rx'); var app = require('../server/server'); var Nonprofits = app.models.Challenge; var nonprofits = require('./nonprofits.json'); var destroy = Rx.Observable.fromNodeCallback(Nonprofits.destroyAll, Nonprofits); var create = Rx.Observable.fromNodeCallback(Nonprofits.create, Nonprofits); destroy() .flatMap(function() { if (!nonprofits) { return Rx.Observable.throw(new Error('No nonprofits found')); } return create(nonprofits); }) .subscribe( function(nonprofits) { console.log('successfully saved %d nonprofits', nonprofits.length); }, function(err) { throw err; }, function() { console.log('nonprofit seed completed'); process.exit(0); } );
Change text-updating logic to match on title rather than ID
$(document).ready(function () { $(".js-define").each(function(index) { $(this).attr('id', "field-" + index); $(this).popover({ "html": true, "placement": "bottom", "content": generateInputElement(index) }); }); $(".js-use").click(function() { window.location.href = "templates/" + $("select").val(); }); }); function updateText(updatedText, id) { // given the id, find the title that matches var updatedElementId = "#field-" + id.split("-")[1]; var titleToUpdate = $(updatedElementId).attr("data-original-title"); $('.js-define[data-original-title="' + titleToUpdate + '"]').each(function() { $(this).text(updatedText); $(this).removeClass("highlighted"); $(this).popover('hide'); }); } function generateInputElement(n) { return $("<input/>", { id: "input-" + n, type:"text", value:"", onchange:"updateText(this.value, this.id);" }); } function showPreview(templateName) { $.get("templates/" + templateName, { "layout" : false }, function(data, status) { $('.js-preview').html(data); $(".js-use").show();enableButton(); }); }
$(document).ready(function () { $(".js-define").each(function(index) { $(this).attr('id', "field-" + index); $(this).popover({ "html": true, "placement": "bottom", "content": generateInputElement(index) }); }); $(".js-use").click(function() { window.location.href = "templates/" + $("select").val(); }); }); function updateText(updatedText, id) { var updatedElementId = "#field-" + id.split("-")[1]; $(updatedElementId).text(updatedText); $(updatedElementId).removeClass("highlighted"); $(updatedElementId).popover('hide'); } function generateInputElement(n) { return $("<input/>", { id: "input-" + n, type:"text", value:"", onchange:"updateText(this.value, this.id);" }); } function showPreview(templateName) { $.get("templates/" + templateName, { "layout" : false }, function(data, status) { $('.js-preview').html(data); $(".js-use").show();enableButton(); }); }
Correct wrong inheritance on sponsorship_typo3 child_depart wizard.
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __openerp__.py # ############################################################################## from openerp.osv import orm from ..model.sync_typo3 import Sync_typo3 class child_depart_wizard(orm.TransientModel): _inherit = 'child.depart.wizard' def child_depart(self, cr, uid, ids, context=None): wizard = self.browse(cr, uid, ids[0], context) child = wizard.child_id res = True if child.state == 'I': res = child.child_remove_from_typo3() res = super(child_depart_wizard, self).child_depart( cr, uid, ids, context) and res return res or Sync_typo3.typo3_index_error(cr, uid, self, context)
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __openerp__.py # ############################################################################## from openerp.osv import orm from ..model.sync_typo3 import Sync_typo3 class end_sponsorship_wizard(orm.TransientModel): _inherit = 'end.sponsorship.wizard' def child_depart(self, cr, uid, ids, context=None): wizard = self.browse(cr, uid, ids[0], context) child = wizard.child_id res = True if child.state == 'I': res = child.child_remove_from_typo3() res = super(end_sponsorship_wizard, self).child_depart( cr, uid, ids, context) and res return res or Sync_typo3.typo3_index_error(cr, uid, self, context)
Add source to the construction table.
@section('title') Construction categories - Cataclysm: Dark Days Ahead @endsection <h1>Construction categories</h1> <div class="row"> <div class="col-md-3"> <ul class="nav nav-pills nav-stacked"> @foreach($categories as $category) <li class="@if($category==$id) active @endif"><a href="{{ route(Route::currentRouteName(), $category) }}">{{{$category}}}</a></li> @endforeach </ul> </div> <div class="col-md-9"> <table class="table table-bordered"> <thead> <tr> <th>Construction</th> <th></th> <th>Source</th> <th></th> <th>Result</th> </tr> </thead> @foreach($data as $d) <tr> <td>{{ link_to_route("construction.view", $d->description, $d->repo_id); }}</td> @if ($d->has_pre_terrain) <td>{{$d->pre_terrain->symbol}}</td> <td>{{$d->pre_terrain->name}}</td> @elseif ($d->pre_flags) <td></td> <td>is:{{$d->pre_flags}}</td> @else <td></td> <td></td> @endif @if ($d->has_post_terrain) <td>{{$d->post_terrain->symbol}}</td> <td>{{$d->post_terrain->name}}</td> @else <td></td> <td></td> @endif </tr> @endforeach </table> </div> </div>
@section('title') Construction categories - Cataclysm: Dark Days Ahead @endsection <h1>Construction categories</h1> <div class="row"> <div class="col-md-3"> <ul class="nav nav-pills nav-stacked"> @foreach($categories as $category) <li class="@if($category==$id) active @endif"><a href="{{ route(Route::currentRouteName(), $category) }}">{{{$category}}}</a></li> @endforeach </ul> </div> <div class="col-md-9"> <table class="table table-bordered"> <thead> <tr> <th>Construction</th> <th></th> <th>Result</th> </tr> </thead> @foreach($data as $d) <tr> <td>{{ link_to_route("construction.view", $d->description, $d->repo_id); }} @if($d->comment!="") ({{{$d->comment}}}) @endif </td> @if ($d->has_post_terrain) <td>{{$d->post_terrain->symbol}}</td> <td>{{$d->post_terrain->name}}</td> @else <td></td> <td></td> @endif </tr> @endforeach </table> </div> </div>
Add link to issue regarding loading defaults via Launcher.initialize().
/* * Copyright (c) 2015 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.director.google.compute; import java.util.HashMap; import java.util.Map; // TODO(duftler): Externalize these defaults. // https://github.com/cloudera/director-google-plugin/issues/2 public class GoogleComputeProviderDefaults { public static Map<String, String> IMAGE_ALIAS_TO_RESOURCE_MAP = new HashMap<String, String>(); static { // TODO(duftler): Populate this map with appropriate choices. IMAGE_ALIAS_TO_RESOURCE_MAP.put( "ubuntu", "https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/images/ubuntu-1404-trusty-v20150316"); } }
/* * Copyright (c) 2015 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cloudera.director.google.compute; import java.util.HashMap; import java.util.Map; // TODO(duftler): Externalize these defaults. public class GoogleComputeProviderDefaults { public static Map<String, String> IMAGE_ALIAS_TO_RESOURCE_MAP = new HashMap<String, String>(); static { // TODO(duftler): Populate this map with appropriate choices. IMAGE_ALIAS_TO_RESOURCE_MAP.put( "ubuntu", "https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/images/ubuntu-1404-trusty-v20150316"); } }
Add @ as an invalid label name character
package com.todoist.model; import java.util.regex.Pattern; public class Sanitizers { public static final String PROJECT_NAME_INVALID_CHARACTERS = "<>\"=#+"; public static final String LABEL_NAME_INVALID_CHARACTERS = "<>\"=#+\\s%!?~:@"; public static final String FILTER_NAME_INVALID_CHARACTERS = "<>\"=#+"; public static final Pattern PROJECT_NAME_INVALID_PATTERN = Pattern.compile("[" + PROJECT_NAME_INVALID_CHARACTERS + "]+"); public static final Pattern LABEL_NAME_INVALID_PATTERN = Pattern.compile("[" + LABEL_NAME_INVALID_CHARACTERS + "]+"); public static final Pattern FILTER_NAME_INVALID_PATTERN = Pattern.compile("[" + FILTER_NAME_INVALID_CHARACTERS + "]+"); public static final String REPLACEMENT = "_"; }
package com.todoist.model; import java.util.regex.Pattern; public class Sanitizers { public static final String PROJECT_NAME_INVALID_CHARACTERS = "<>\"=#+"; public static final String LABEL_NAME_INVALID_CHARACTERS = "<>\"=#+\\s%!?~:"; public static final String FILTER_NAME_INVALID_CHARACTERS = "<>\"=#+"; public static final Pattern PROJECT_NAME_INVALID_PATTERN = Pattern.compile("[" + PROJECT_NAME_INVALID_CHARACTERS + "]+"); public static final Pattern LABEL_NAME_INVALID_PATTERN = Pattern.compile("[" + LABEL_NAME_INVALID_CHARACTERS + "]+"); public static final Pattern FILTER_NAME_INVALID_PATTERN = Pattern.compile("[" + FILTER_NAME_INVALID_CHARACTERS + "]+"); public static final String REPLACEMENT = "_"; }
Make it so that the past speakers go from newest to oldest.
<?php class Speakers extends Illuminate\Filesystem\Filesystem { public $speakersPath; public function __construct() { $this->speakersPath = app_path() . "/views/speakers/details"; } /** * Gets all the speakers for view in the past speakers list. * * @return array of speakers */ public function getAllSpeakers() { // Reverse this listing so we show the newest speakers first. $files = array_reverse($this->files($this->speakersPath)); $results = array(); foreach ($files as $file) { $filename = basename($file, ".blade.php"); $parts = explode('_', $filename); $results[] = array( 'file' => $file, 'view' => 'speakers.details.' . $filename, 'date' => strftime("%B %e, %Y", strtotime($parts[0])), 'name' => str_replace('-', ' ', $parts[1]), ); } return $results; } /** * Return the speaker 'view' name for the front page news. * * @return array of 2 speakers if they exist. */ public function getSpeakerView($meetingDate) { $filename = $this->glob($this->speakersPath . "/" . $meetingDate . "_*.blade.php"); if (!empty($filename)) { return 'speakers.details.' . basename(array_shift($filename), ".blade.php"); } return null; } } ?>
<?php class Speakers extends Illuminate\Filesystem\Filesystem { public $speakersPath; public function __construct() { $this->speakersPath = app_path() . "/views/speakers/details"; } /** * Gets all the speakers for view in the past speakers list. * * @return array of speakers */ public function getAllSpeakers() { $files = $this->files($this->speakersPath); $results = array(); foreach ($files as $file) { $filename = basename($file, ".blade.php"); $parts = explode('_', $filename); $results[] = array( 'file' => $file, 'view' => 'speakers.details.' . $filename, 'date' => strftime("%B %e, %Y", strtotime($parts[0])), 'name' => str_replace('-', ' ', $parts[1]), ); } return $results; } /** * Return the speaker 'view' name for the front page news. * * @return array of 2 speakers if they exist. */ public function getSpeakerView($meetingDate) { $filename = $this->glob($this->speakersPath . "/" . $meetingDate . "_*.blade.php"); if (!empty($filename)) { return 'speakers.details.' . basename(array_shift($filename), ".blade.php"); } return null; } } ?>
Fix bug. youtube block cannot be edited
'use strict'; import ENTITY from '../entities'; import insertAtomicBlock from './insert-atomic-block'; import { replaceAtomicBlock } from './replace-block'; import { Entity } from 'draft-js'; import removeBlock from './remove-block'; const handleAtomicEdit = (editorState, blockKey, valueChanged) => { const block = editorState.getCurrentContent().getBlockForKey(blockKey); const entityKey = block.getEntityAt(0); let blockType; try { blockType = entityKey ? Entity.get(entityKey).getType() : null; } catch (e) { console.log('Get entity type in the block occurs error ', e); return editorState; } switch (blockType) { case ENTITY.audio.type: case ENTITY.blockQuote.type: case ENTITY.annotation.type: case ENTITY.embeddedCode.type: case ENTITY.image.type: case ENTITY.imageDiff.type: case ENTITY.infobox.type: case ENTITY.slideshow.type: case ENTITY.youtube.type: if (valueChanged) { return replaceAtomicBlock(editorState, blockKey, valueChanged); } return removeBlock(editorState, blockKey); default: return editorState; } }; export default { insertAtomicBlock, handleAtomicEdit, };
'use strict'; import ENTITY from '../entities'; import insertAtomicBlock from './insert-atomic-block'; import { replaceAtomicBlock } from './replace-block'; import { Entity } from 'draft-js'; import removeBlock from './remove-block'; const handleAtomicEdit = (editorState, blockKey, valueChanged) => { const block = editorState.getCurrentContent().getBlockForKey(blockKey); const entityKey = block.getEntityAt(0); let blockType; try { blockType = entityKey ? Entity.get(entityKey).getType() : null; } catch (e) { console.log('Get entity type in the block occurs error ', e); return editorState; } switch (blockType) { case ENTITY.audio.type: case ENTITY.blockQuote.type: case ENTITY.annotation.type: case ENTITY.embeddedCode.type: case ENTITY.image.type: case ENTITY.imageDiff.type: case ENTITY.infobox.type: case ENTITY.slideshow.type: if (valueChanged) { return replaceAtomicBlock(editorState, blockKey, valueChanged); } return removeBlock(editorState, blockKey); default: return editorState; } }; export default { insertAtomicBlock, handleAtomicEdit, };
Fix on instead of live
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require_tree . (function($){ $(document).ready(function() { $('a[data-colorbox="true"]').on('click', function(e) { e.preventDefault(); $.colorbox( { height: $(this).data("colorbox-height") || false, width: $(this).data("colorbox-width") || false, iframe: $(this).data("colorbox-iframe") || false, photo: $(this).data("colorbox-photo") || false, innerHeight: $(this).data("colorbox-innerheight") || false, innerWidth: $(this).data("colorbox-innerwidth") || false, href: $(this).attr('href'), opacity: 0.5 }); }); }); }) (jQuery);
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require_tree . (function($){ $(document).ready(function() { $('a[data-colorbox="true"]').live('click', function(e) { e.preventDefault(); $.colorbox( { height: $(this).data("colorbox-height") || false, width: $(this).data("colorbox-width") || false, iframe: $(this).data("colorbox-iframe") || false, photo: $(this).data("colorbox-photo") || false, innerHeight: $(this).data("colorbox-innerheight") || false, innerWidth: $(this).data("colorbox-innerwidth") || false, href: $(this).attr('href'), opacity: 0.5 }); }); }); }) (jQuery);
Add cancelFunc parameter for confirm dialog
define( [ "dojo/dom-construct", "dijit/form/Button", "dijit/Dialog" ], function (domConstruct, Button, Dialog) { "use strict"; var dialog = null; var createButton = function (label, onClickFunc) { return new Button({ label: label, onClick: function () { if (onClickFunc) { /* run callback function */ onClickFunc(); } dialog.hide(); } }); }; return { confirm: function (title, message, buttons, cancelFunc) { var confirmContentNode = domConstruct.create("div", {"class": "confirmDialogContent", innerHTML: message}); var buttonWrapperNode = domConstruct.create("div", {"class": "confirmDialogButtons"}, confirmContentNode); for (var button in buttons) { if (buttons.hasOwnProperty(button)) { createButton(button, buttons[button]).placeAt(buttonWrapperNode).startup(); } } cancelFunc = cancelFunc || function () {}; (dialog = new Dialog({ title: title, content: confirmContentNode, onCancel: cancelFunc })).show(); } }; } );
define( [ "dojo/dom-construct", "dijit/form/Button", "dijit/Dialog" ], function (domConstruct, Button, Dialog) { "use strict"; var dialog = null; var createButton = function (label, onClickFunc) { return new Button({ label: label, onClick: function () { if (onClickFunc) { /* run callback function */ onClickFunc(); } dialog.hide(); } }); }; return { confirm: function (title, message, buttons) { var confirmContentNode = domConstruct.create("div", {"class": "confirmDialogContent", innerHTML: message}); var buttonWrapperNode = domConstruct.create("div", {"class": "confirmDialogButtons"}, confirmContentNode); for (var button in buttons) { if (buttons.hasOwnProperty(button)) { createButton(button, buttons[button]).placeAt(buttonWrapperNode).startup(); } } (dialog = new Dialog({ title: title, content: confirmContentNode })).show(); } }; } );
Fix directory path memory stats test
'use strict'; var MemoryStats = require('../../src/models/memory_stats') , SQliteAdapter = require('../../src/models/sqlite_adapter') , chai = require('chai') , expect = chai.expect , chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); describe('MemoryStats', function() { describe('.constructor', function() { it('returns an instantiated memory stats and its schema attributes', function() { expect(MemoryStats().schemaAttrs).to.include.members(['container_name', 'timestamp_day']); }); it('returns an instantiated memory stats and its table name', function() { expect(MemoryStats().tableName).to.eql('memory_stats'); }); }); after(function() { return SQliteAdapter.deleteDB() .then(null) .catch(function(err) { console.log(err.stack); }); }); });
'use strict'; var MemoryStats = require('../../lib/models/memory_stats') , SQliteAdapter = require('../../lib/models/sqlite_adapter') , chai = require('chai') , expect = chai.expect , chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); describe('MemoryStats', function() { describe('.constructor', function() { it('returns an instantiated memory stats and its schema attributes', function() { expect(MemoryStats().schemaAttrs).to.include.members(['container_name', 'timestamp_day']); }); it('returns an instantiated memory stats and its table name', function() { expect(MemoryStats().tableName).to.eql('memory_stats'); }); }); after(function() { return SQliteAdapter.deleteDB() .then(null) .catch(function(err) { console.log(err.stack); }); }); });
Modify grunt writeln and fix grunt header to make grunt-newer quiet.
function initTimeGrunt(grunt) { const timeGrunt = require('time-grunt'); timeGrunt(grunt); } function initLoadGruntConfig(grunt) { const loadGruntConfig = require('load-grunt-config'); const options = { jitGrunt: { staticMappings: { mochaTest: 'grunt-mocha-test', express: 'grunt-express-server' } } }; loadGruntConfig(grunt, options); } function quietGruntNewer(grunt) { const originalHeader = grunt.log.header; const originalWriteLn = grunt.log.writeln; // Cannot use arrow functions here as the this object is incorrect otherwise. grunt.log.header = function (message) { // Only if the header does not start with newer or newer-postrun. if (!/newer(-postrun)?:/.test(message)) { originalHeader.apply(this, arguments); } return this; }; // Cannot use arrow functions here as the this object is incorrect otherwise. grunt.log.writeln = function (message) { // Only write the message if it is not the text from a grunt-newer task. if (message !== 'No newer files to process.') { originalWriteLn.apply(this, arguments); } // Need to return the object as in grunt-legacy-log#writeln. return this; }; } module.exports = function (grunt) { initTimeGrunt(grunt); initLoadGruntConfig(grunt); quietGruntNewer(grunt); };
function initTimeGrunt(grunt) { const timeGrunt = require('time-grunt'); timeGrunt(grunt); } function initLoadGruntConfig(grunt) { const loadGruntConfig = require('load-grunt-config'); const options = { jitGrunt: { staticMappings: { mochaTest: 'grunt-mocha-test', express: 'grunt-express-server' } } }; loadGruntConfig(grunt, options); } function quietGruntNewer(grunt) { const originalHeader = grunt.log.header; grunt.log.header = (message) => { // Only if the header does not start with newer or newer-postrun. if (!/newer(-postrun)?:/.test(message)) { originalHeader.apply(this, arguments); } } } module.exports = function (grunt) { initTimeGrunt(grunt); initLoadGruntConfig(grunt); quietGruntNewer(grunt); };
Fix error testing on python 2.7
import os import unittest import transpiler class TestTranspiler: def test_transpiler_creates_files_without_format(self): try: os.remove("/tmp/auto_functions.cpp") os.remove("/tmp/auto_functions.h") except OSError: pass transpiler.main(["--output-dir", "/tmp"]) assert os.path.isfile("/tmp/auto_functions.cpp") assert os.path.isfile("/tmp/auto_functions.h") def test_transpiler_creates_files_with_format(self): try: os.remove("/tmp/auto_functions.cpp") os.remove("/tmp/auto_functions.h") except OSError: pass transpiler.main(["--format", "--output-dir", "/tmp"]) assert os.path.isfile("/tmp/auto_functions.cpp") assert os.path.isfile("/tmp/auto_functions.h")
import os import unittest import transpiler class TestTranspiler: def test_transpiler_creates_files_without_format(self): try: os.remove("/tmp/auto_functions.cpp") os.remove("/tmp/auto_functions.h") except FileNotFoundError: pass transpiler.main(["--output-dir", "/tmp"]) assert os.path.isfile("/tmp/auto_functions.cpp") assert os.path.isfile("/tmp/auto_functions.h") def test_transpiler_creates_files_with_format(self): try: os.remove("/tmp/auto_functions.cpp") os.remove("/tmp/auto_functions.h") except FileNotFoundError: pass transpiler.main(["--format", "--output-dir", "/tmp"]) assert os.path.isfile("/tmp/auto_functions.cpp") assert os.path.isfile("/tmp/auto_functions.h")
Make sure to preload facility config on the user profile page.
import store from 'kolibri.coreVue.vuex.store'; import redirectBrowser from 'kolibri.utils.redirectBrowser'; import ProfilePage from './views/ProfilePage'; import ProfileEditPage from './views/ProfileEditPage'; function preload(next) { store.commit('CORE_SET_PAGE_LOADING', true); store.dispatch('getFacilityConfig').then(() => { store.commit('CORE_SET_PAGE_LOADING', false); next(); }); } export default [ { path: '/', component: ProfilePage, beforeEnter(to, from, next) { if (!store.getters.isUserLoggedIn) { redirectBrowser(); } else { preload(next); } }, }, { path: '/edit', component: ProfileEditPage, beforeEnter(to, from, next) { if (!store.getters.isUserLoggedIn) { redirectBrowser(); } else { preload(next); } }, }, { path: '*', redirect: '/', }, ];
import store from 'kolibri.coreVue.vuex.store'; import redirectBrowser from 'kolibri.utils.redirectBrowser'; import ProfilePage from './views/ProfilePage'; import ProfileEditPage from './views/ProfileEditPage'; export default [ { path: '/', component: ProfilePage, beforeEnter(to, from, next) { store.commit('CORE_SET_PAGE_LOADING', false); if (!store.getters.isUserLoggedIn) { redirectBrowser(); } else { next(); } }, }, { path: '/edit', component: ProfileEditPage, beforeEnter(to, from, next) { store.commit('CORE_SET_PAGE_LOADING', false); if (!store.getters.isUserLoggedIn) { redirectBrowser(); } else { next(); } }, }, { path: '*', redirect: '/', }, ];
Support preview mode (don't link, just print matches found)
package main import ( "fmt" "os" "path/filepath" "github.com/gmcnaughton/gofindhdr/findhdr" ) func main() { // inpath := "/Users/gmcnaughton/Pictures/Photos Library.photoslibrary/Masters/2017/02" inpath := "./test" outpath := "./out" optlink := false // Create output folder if optlink { err := os.Mkdir(outpath, 0755) if err != nil && !os.IsExist(err) { fmt.Println("Error creating out directory", err) } } count := 0 findhdr.Find(inpath, func(hdr *findhdr.Hdr) { count++ if optlink { for _, image := range hdr.Images() { link := filepath.Join(outpath, image.Info.Name()) fmt.Println("Linking", link) err := os.Link(image.Path, link) if os.IsExist(err) { fmt.Println("Skipping", err) } else if err != nil { fmt.Println("Error linking", err) } } } else { fmt.Println(hdr) } }) fmt.Printf("Found %d hdrs.\n", count) }
package main import ( "fmt" "os" "path/filepath" "github.com/gmcnaughton/gofindhdr/findhdr" ) func main() { inpath := "/Users/gmcnaughton/Pictures/Photos Library.photoslibrary/Masters/2017/02" // inpath := "./test" outpath := "./out" optlink := true // Create output folder _ = os.Mkdir(outpath, 0755) count := 0 findhdr.Find(inpath, func(hdr *findhdr.Hdr) { for _, image := range hdr.Images() { count++ link := filepath.Join(outpath, image.Info.Name()) if optlink { fmt.Println("Linking", link) err := os.Link(image.Path, link) if os.IsExist(err) { fmt.Printf("Skipping %s (file exists)\n", link) } else if err != nil { fmt.Printf("Error linking %s\n", link) fmt.Println(err) } } else { fmt.Println(hdr) } } fmt.Println() }) fmt.Printf("Found %d hdrs.\n", count) }
Use third person in tests' names
// This is free and unencumbered software released into the public domain. // See the `UNLICENSE` file or <http://unlicense.org/> for more details. package it.svario.xpathapi.jaxp.test; import it.svario.xpathapi.jaxp.XPathAPI; import org.testng.annotations.Test; import org.w3c.dom.Node; import static org.testng.Assert.*; @SuppressWarnings("javadoc") public class TemplateSubstitutionTest extends TestBase { public TemplateSubstitutionTest() throws Exception { super(); } @Test public void replacesTemplates() throws Exception { Node node = XPathAPI.selectSingleNode(doc, "//b[contains(text(), '{}')]", "bb33"); assertNotNull(node); assertEquals(node.getTextContent(), "aabb33"); } @Test public void doesNotReplacesNonTemplates() throws Exception { Node node = XPathAPI.selectSingleNode(doc, "//b[contains(text(), '{}')]"); assertNull(node); } }
// This is free and unencumbered software released into the public domain. // See the `UNLICENSE` file or <http://unlicense.org/> for more details. package it.svario.xpathapi.jaxp.test; import it.svario.xpathapi.jaxp.XPathAPI; import org.testng.annotations.Test; import org.w3c.dom.Node; import static org.testng.Assert.*; @SuppressWarnings("javadoc") public class TemplateSubstitutionTest extends TestBase { public TemplateSubstitutionTest() throws Exception { super(); } @Test public void replacesTemplates() throws Exception { Node node = XPathAPI.selectSingleNode(doc, "//b[contains(text(), '{}')]", "bb33"); assertNotNull(node); assertEquals(node.getTextContent(), "aabb33"); } @Test public void doNotReplacesNonTemplates() throws Exception { Node node = XPathAPI.selectSingleNode(doc, "//b[contains(text(), '{}')]"); assertNull(node); } }
Simplify these decorators, since we don't use the classes here anyway.
"""Helpers for codejail.""" import contextlib import os import shutil import tempfile @contextlib.contextmanager def temp_directory(): """ A context manager to make and use a temp directory. The directory will be removed when done. """ temp_dir = tempfile.mkdtemp(prefix="codejail-") # Make directory readable by other users ('sandbox' user needs to be # able to read it). os.chmod(temp_dir, 0775) try: yield temp_dir finally: # if this errors, something is genuinely wrong, so don't ignore errors. shutil.rmtree(temp_dir) @contextlib.contextmanager def change_directory(new_dir): """ A context manager to change the directory, and then change it back. """ old_dir = os.getcwd() os.chdir(new_dir) try: yield new_dir finally: os.chdir(old_dir)
"""Helpers for codejail.""" import contextlib import os import shutil import tempfile class TempDirectory(object): def __init__(self): self.temp_dir = tempfile.mkdtemp(prefix="codejail-") # Make directory readable by other users ('sandbox' user needs to be # able to read it). os.chmod(self.temp_dir, 0775) def clean_up(self): # if this errors, something is genuinely wrong, so don't ignore errors. shutil.rmtree(self.temp_dir) @contextlib.contextmanager def temp_directory(): """ A context manager to make and use a temp directory. The directory will be removed when done. """ tmp = TempDirectory() try: yield tmp.temp_dir finally: tmp.clean_up() class ChangeDirectory(object): def __init__(self, new_dir): self.old_dir = os.getcwd() os.chdir(new_dir) def clean_up(self): os.chdir(self.old_dir) @contextlib.contextmanager def change_directory(new_dir): """ A context manager to change the directory, and then change it back. """ cd = ChangeDirectory(new_dir) try: yield new_dir finally: cd.clean_up()
Make ghostscript handle PDF/A colorspace correctly Previously, if you tried to verify files generated by pdf_to_pdfa in a verifier (like https://tools.pdfforge.org/validate-pdfa), you would get errors relating to the lack of OutputIntent (6.2.3). The info in https://stackoverflow.com/a/56459053/11416267 and https://www.ghostscript.com/doc/current/VectorDevices.htm#PDFA suggested that `-sColorConversionStrategy=UseDeviceIndependentColor` be added, which corrects those validator errors, and verifies output PDFs as PDF/A-1b.
import tempfile import subprocess import shutil from docassemble.base.error import DAError #from docassemble.base.logger import logmessage def pdf_to_pdfa(filename): outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) directory = tempfile.mkdtemp() commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sColorConversionStrategy=UseDeviceIndependentColor', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename] try: output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode() except subprocess.CalledProcessError as err: output = err.output.decode() raise DAError("pdf_to_pdfa: error running ghostscript. " + output) shutil.move(outfile.name, filename)
import tempfile import subprocess import shutil from docassemble.base.error import DAError #from docassemble.base.logger import logmessage def pdf_to_pdfa(filename): outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) directory = tempfile.mkdtemp() commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename] try: output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode() except subprocess.CalledProcessError as err: output = err.output.decode() raise DAError("pdf_to_pdfa: error running ghostscript. " + output) shutil.move(outfile.name, filename)
Add failing test for Workbook file save function
import {Workbook} from '../src/parsing/workbook.js'; import {expect} from 'chai'; import fs from 'fs'; describe('Workbook parsing', () => { let file = fs.readFileSync('example/example-with-data.xlsx'); let wb = new Workbook(file); it('should build a Workbook instance from a binary file', () => { expect(wb).to.be.an.instanceOf(Workbook); }); it('should return a list of Sheet names', () => { expect(wb.sheetNames()).to.exist; expect(wb.sheetNames()).to.be.an.instanceOf(Array); }); it('should return a Sheet by its name', () => { expect(wb.sheet('Sheet1')).to.exist; expect(wb.sheet('Sheet2')).to.not.exist; }); it('should save the current Workbook into a file', () => { expect(false).to.be.true; }); });
import {Workbook} from '../src/parsing/workbook.js'; import {expect} from 'chai'; import fs from 'fs'; describe('Workbook parsing', () => { let file = fs.readFileSync('example/example-with-data.xlsx'); let wb = new Workbook(file); it('should build a Workbook instance from a binary file', () => { expect(wb).to.be.an.instanceOf(Workbook); }); it('should return a list of Sheet names', () => { expect(wb.sheetNames()).to.exist; expect(wb.sheetNames()).to.be.an.instanceOf(Array); }); it('should return a Sheet by its name', () => { expect(wb.sheet('Sheet1')).to.exist; expect(wb.sheet('Sheet2')).to.not.exist; }); it('should save the current Workbook into a file', () => { }); });
Use singular parameter name. Use ::class notation.
<?php $router->bind('block', function ($id) { return app(\Modules\Block\Repositories\BlockRepository::class)->find($id); }); $router->group(['prefix' =>'/block'], function () { get('blocks', ['as' => 'admin.block.block.index', 'uses' => 'BlockController@index']); get('blocks/create', ['as' => 'admin.block.block.create', 'uses' => 'BlockController@create']); post('blocks', ['as' => 'admin.block.block.store', 'uses' => 'BlockController@store']); get('blocks/{block}/edit', ['as' => 'admin.block.block.edit', 'uses' => 'BlockController@edit']); put('blocks/{block}', ['as' => 'admin.block.block.update', 'uses' => 'BlockController@update']); delete('blocks/{block}', ['as' => 'admin.block.block.destroy', 'uses' => 'BlockController@destroy']); });
<?php $router->bind('blocks', function ($id) { return app('Modules\Block\Repositories\BlockRepository')->find($id); }); $router->group(['prefix' =>'/block'], function () { get('blocks', ['as' => 'admin.block.block.index', 'uses' => 'BlockController@index']); get('blocks/create', ['as' => 'admin.block.block.create', 'uses' => 'BlockController@create']); post('blocks', ['as' => 'admin.block.block.store', 'uses' => 'BlockController@store']); get('blocks/{blocks}/edit', ['as' => 'admin.block.block.edit', 'uses' => 'BlockController@edit']); put('blocks/{blocks}', ['as' => 'admin.block.block.update', 'uses' => 'BlockController@update']); delete('blocks/{blocks}', ['as' => 'admin.block.block.destroy', 'uses' => 'BlockController@destroy']); });
Add phpdoc-style comments to SearchTerm
<?php namespace SearchApi\Models; /** * Class SearchTerm - A search term is a basic unit that will be used to build a query for * Search providers. * * @var $value string This will be a keyword from NerTagger, location from ReverseGeocoder, etc. * @var $category string 'location', 'person', 'organization', etc. * @var $related string[] Array of related keywords * @var $count int Occurences of keyword * @var $isUserInput bool TRUE if term is a user-specified keyword, FALSE if it is not */ class SearchTerm { public $value; public $category; public $related; public $count; public $isUserInput; function __construct( $value, $category, $related, $count, $isUserInput ) { $this->value = $value; $this->category = $category; $this->related = $related; $this->count = $count; $this->isUserInput = $isUserInput; } }
<?php namespace SearchApi\Models; /** * Class SearchTerm - A search term is a basic unit that will be used to build a query for * Search providers. */ class SearchTerm { public $value; // (string) This will be a keyword from NerTagger, location from ReverseGeocoder, etc. public $category; // (string) Category as string: 'location', 'person', 'organization', etc. public $related; // (string[]) Array of related keywords public $count; // (int) Occurences of keyword public $isUserInput; // (bool) TRUE if term is a user-specified keyword, FALSE if it is not function __construct( $value, $category, $related, $count, $isUserInput ) { $this->value = $value; $this->category = $category; $this->related = $related; $this->count = $count; $this->isUserInput = $isUserInput; } }
gn: Fix issue with finding llvm when using python3 With python3, subprocess output is a byte sequence. This needs to be decoded to string so that the string functions work. Fix it so we can find LLVM when building perfetto. Also fix 'print' operator which is a function in python3. Bug: 147789115 Signed-off-by: Joel Fernandes <89f39a38232ac523c7644e47b6ca6563177e40b4@google.com> Change-Id: I4ab9b3c248d471e7ab5a27559152a1954ca43108
# Copyright (C) 2017 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import sys def main(): devnull = open(os.devnull, 'w') for clang in ('clang', 'clang-3.8', 'clang-3.5'): if subprocess.call(['which', clang], stdout=devnull, stderr=devnull) != 0: continue res = subprocess.check_output([clang, '-print-search-dirs']).decode("utf-8") for line in res.splitlines(): if not line.startswith('libraries:'): continue libs = line.split('=', 1)[1].split(':') for lib in libs: if '/clang/' not in lib or not os.path.isdir(lib + '/lib'): continue print(os.path.abspath(lib)) print(clang) print(clang.replace('clang', 'clang++')) return 0 print('Could not find the LLVM lib dir') return 1 if __name__ == '__main__': sys.exit(main())
# Copyright (C) 2017 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import subprocess import sys def main(): devnull = open(os.devnull, 'w') for clang in ('clang', 'clang-3.8', 'clang-3.5'): if subprocess.call(['which', clang], stdout=devnull, stderr=devnull) != 0: continue res = subprocess.check_output([clang, '-print-search-dirs']) for line in res.splitlines(): if not line.startswith('libraries:'): continue libs = line.split('=', 1)[1].split(':') for lib in libs: if '/clang/' not in lib or not os.path.isdir(lib + '/lib'): continue print os.path.abspath(lib) print clang print clang.replace('clang', 'clang++') return 0 print 'Could not find the LLVM lib dir' return 1 if __name__ == '__main__': sys.exit(main())
Read database config from file. Exit process if file not found.
var _ = require('underscore'), fs = require('fs'), path = require('path'), PoemsRepository = require('../lib/repositories/poems_repository.js'); var dbConfig; if(fs.existsSync(path.join(__dirname, "../db/config.json"))) { dbConfig = require("../db/config.json"); } else { console.log("The database config file was not found!"); process.exit(1); } var poemsRepo = new PoemsRepository(dbConfig); exports.list = function(req, res) { poemsRepo.all(function(err, poems) { res.render('poem/list', { poems: poems }); }); }; exports.edit = function(req, res) { poemsRepo.read(req.params.id, function(err, poem) { res.render('poem/edit', { poem: poem }); }); }; exports.createform = function(req, res) { res.render('poem/new'); }; exports.create = function(req, res) { poemsRepo.create({ name: req.body.name }, function(err, poem) { res.redirect('/poem/' + poem.id); }); };
var _ = require('underscore'); var PoemsRepository = require('../lib/repositories/poems_repository.js'); var poemsRepo = new PoemsRepository(); exports.list = function(req, res) { poemsRepo.all(function(err, poems) { res.render('poem/list', { poems: poems }); }); }; exports.edit = function(req, res) { poemsRepo.read(req.params.id, function(err, poem) { res.render('poem/edit', { poem: poem }); }); }; exports.createform = function(req, res) { res.render('poem/new'); }; exports.create = function(req, res) { poemsRepo.create({ name: req.body.name }, function(err, poem) { res.redirect('/poem/' + poem.id); }); };
Add missing licence header to migration
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddAutoStartDurationToMultiplayerRooms extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('multiplayer_rooms', function (Blueprint $table) { $table->unsignedSmallInteger('auto_start_duration')->after('queue_mode')->default(0); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('multiplayer_rooms', function (Blueprint $table) { $table->dropColumn('auto_start_duration'); }); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddAutoStartDurationToMultiplayerRooms extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('multiplayer_rooms', function (Blueprint $table) { $table->unsignedSmallInteger('auto_start_duration')->after('queue_mode')->default(0); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('multiplayer_rooms', function (Blueprint $table) { $table->dropColumn('auto_start_duration'); }); } }
Fix ipams builtin package for darwin Make ipams builtin package work for os x target as ipam driver developers happen to be using os x as well. Signed-off-by: Jana Radhakrishnan <045898bda7d4800fe4909a9831e702ab79e266be@docker.com>
// +build linux freebsd solaris darwin package builtin import ( "fmt" "github.com/docker/libnetwork/datastore" "github.com/docker/libnetwork/ipam" "github.com/docker/libnetwork/ipamapi" "github.com/docker/libnetwork/ipamutils" ) // Init registers the built-in ipam service with libnetwork func Init(ic ipamapi.Callback, l, g interface{}) error { var ( ok bool localDs, globalDs datastore.DataStore ) if l != nil { if localDs, ok = l.(datastore.DataStore); !ok { return fmt.Errorf("incorrect local datastore passed to built-in ipam init") } } if g != nil { if globalDs, ok = g.(datastore.DataStore); !ok { return fmt.Errorf("incorrect global datastore passed to built-in ipam init") } } ipamutils.InitNetworks() a, err := ipam.NewAllocator(localDs, globalDs) if err != nil { return err } return ic.RegisterIpamDriver(ipamapi.DefaultIPAM, a) }
// +build linux freebsd solaris package builtin import ( "fmt" "github.com/docker/libnetwork/datastore" "github.com/docker/libnetwork/ipam" "github.com/docker/libnetwork/ipamapi" "github.com/docker/libnetwork/ipamutils" ) // Init registers the built-in ipam service with libnetwork func Init(ic ipamapi.Callback, l, g interface{}) error { var ( ok bool localDs, globalDs datastore.DataStore ) if l != nil { if localDs, ok = l.(datastore.DataStore); !ok { return fmt.Errorf("incorrect local datastore passed to built-in ipam init") } } if g != nil { if globalDs, ok = g.(datastore.DataStore); !ok { return fmt.Errorf("incorrect global datastore passed to built-in ipam init") } } ipamutils.InitNetworks() a, err := ipam.NewAllocator(localDs, globalDs) if err != nil { return err } return ic.RegisterIpamDriver(ipamapi.DefaultIPAM, a) }
Add reminder to fix backend link
import { ApolloClient } from 'apollo-client'; import { createHttpLink } from 'apollo-link-http'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { setContext } from 'apollo-link-context'; import fetch from 'isomorphic-unfetch'; let apolloClient = null; // Polyfill fetch() on the server (used by apollo-client) if (!process.browser) { global.fetch = fetch; } function create(initialState, { getToken }) { const httpLink = createHttpLink({ // TODO: Fix this to work on intranet uri: 'http://localhost:4000', credentials: 'same-origin', }); const authLink = setContext((_, { headers }) => { const token = getToken(); return { headers: { ...headers, authorization: token ? `Bearer ${token}` : null, }, }; }); return new ApolloClient({ connectToDevTools: process.browser, ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once) link: authLink.concat(httpLink), cache: new InMemoryCache().restore(initialState || {}), }); } export default function initApollo(initialState, options) { // Make sure to create a new client for every server-side request so that data // isn't shared between connections (which would be bad) if (!process.browser) { return create(initialState, options); } // Reuse client on the client-side if (!apolloClient) { apolloClient = create(initialState, options); } return apolloClient; }
import { ApolloClient } from 'apollo-client'; import { createHttpLink } from 'apollo-link-http'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { setContext } from 'apollo-link-context'; import fetch from 'isomorphic-unfetch'; let apolloClient = null; // Polyfill fetch() on the server (used by apollo-client) if (!process.browser) { global.fetch = fetch; } function create(initialState, { getToken }) { const httpLink = createHttpLink({ uri: 'http://localhost:4000', credentials: 'same-origin', }); const authLink = setContext((_, { headers }) => { const token = getToken(); return { headers: { ...headers, authorization: token ? `Bearer ${token}` : null, }, }; }); return new ApolloClient({ connectToDevTools: process.browser, ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once) link: authLink.concat(httpLink), cache: new InMemoryCache().restore(initialState || {}), }); } export default function initApollo(initialState, options) { // Make sure to create a new client for every server-side request so that data // isn't shared between connections (which would be bad) if (!process.browser) { return create(initialState, options); } // Reuse client on the client-side if (!apolloClient) { apolloClient = create(initialState, options); } return apolloClient; }
Fix tiny errors in Python code
# This is fairly specific to using a Yourls server: see http://yourls.org/ import urllib import urllib2 import Util SHORTEN_PART = 'yourls-api.php' def shorten(url, config): def shortenerUrl(part): return '%s/%s' % (config.shortenUrl, part) index = Util.getAndIncrementIndexFile(config.indexFile) shorturl = config.shortenPrefix + index data = urllib.urlencode(dict(signature=config.auth['yourls'], action='shorturl', keyword=shorturl, url=url)) urllib2.urlopen(shortenerUrl(SHORTEN_PART), data) return shortenerUrl(shorturl)
# This is fairly specific to using a Yourls server: see http://yourls.org/ import urllib import urllib2 import Util SHORTEN_PART = 'yourls-api.php' def shorten(url, config): def shortenerUrl(part): return '%s/%s' % (config.shortenUrl, part) index = Util.getAndIncrementIndexFile(config.indexFile) shorturl = config.shortenPrefix + data = urllib.urlencode(dict(signature=config.auth['yourls'], action='shorturl', keyword=shorturl, url=url)) urllib2.urlopen(shortenerUrl(SHORTEN_PART), data) return shortenerUrl(shorturl)
Add second argument checking to prevent unexpected behavior.
var path = require('path') var p = {} Object.keys(path).forEach(function (key) { p[key] = path[key] }) path = p path.replaceExt = require('replace-ext') path.normalizeTrim = function (str) { var escapeRegexp = require('escape-string-regexp') return path.normalize(str).replace(new RegExp(escapeRegexp(path.sep) + '$'), '') } path.base = function (str, includeExt) { if (includeExt) { return path.basename(str) } else { return path.basename(str, path.extname(str)) } } path.removeExt = function (str) { return str.slice(0, -path.extname(str).length) } path.fileNameWithPostfix = function (filePath, postfix) { if (typeof postfix !== 'string') { throw TypeError(`second argument 'postfix' must be string, got ${typeof postfix}`) } var ext = path.extname(filePath) var fileNameWithoutExt = path.basename(filePath, ext) return path.join(path.dirname(filePath), fileNameWithoutExt + postfix + ext) } path.fileNameWithPrefix = function (filePath, prefix) { if (typeof prefix !== 'string') { throw TypeError(`second argument 'prefix' must be string, got ${typeof prefix}`) } var ext = path.extname(filePath) var fileNameWithoutExt = path.basename(filePath, ext) return path.join(path.dirname(filePath), prefix + fileNameWithoutExt + ext) } module.exports = path
var path = require('path') var p = {} Object.keys(path).forEach(function (key) { p[key] = path[key] }) path = p path.replaceExt = require('replace-ext') path.normalizeTrim = function (str) { var escapeRegexp = require('escape-string-regexp') return path.normalize(str).replace(new RegExp(escapeRegexp(path.sep) + '$'), '') } path.base = function (str, includeExt) { if (includeExt) { return path.basename(str) } else { return path.basename(str, path.extname(str)) } } path.removeExt = function (str) { return str.slice(0, -path.extname(str).length) } path.fileNameWithPostfix = function (filePath, postfix) { var ext = path.extname(filePath) var fileNameWithoutExt = path.basename(filePath, ext) return path.join(path.dirname(filePath), fileNameWithoutExt + postfix + ext) } path.fileNameWithPrefix = function (filePath, prefix) { var ext = path.extname(filePath) var fileNameWithoutExt = path.basename(filePath, ext) return path.join(path.dirname(filePath), prefix + fileNameWithoutExt + ext) } module.exports = path
Fix display of undefined attributes
#!/usr/bin/env node exports.command = { description: 'get an attribute for a project', arguments: '<project> <attribute>' }; if (require.main !== module) { return; } var storage = require('../lib/storage.js'); var utilities = require('../lib/utilities.js'); var program = utilities.programDefaults('get', '<project> <attribute>'); program.option('-p, --porcelain', 'Get the value in a machine-readable way'); program.parse(process.argv); storage.setup(function () { if (program.args.length !== 2) { console.error('Please specify a project and attribute.'); process.exit(1); } var name = program.args[0]; var attribute = program.args[1]; var project = storage.getProjectOrDie(name); if (attribute === 'directory') { project.directory = utilities.expand(project.directory); } if (program.porcelain) { console.log(project[attribute] || ''); } else { console.log('%s:%s: "%s"', project.name, attribute, project[attribute] || ''); } });
#!/usr/bin/env node exports.command = { description: 'get an attribute for a project', arguments: '<project> <attribute>' }; if (require.main !== module) { return; } var storage = require('../lib/storage.js'); var utilities = require('../lib/utilities.js'); var program = utilities.programDefaults('get', '<project> <attribute>'); program.option('-p, --porcelain', 'Get the value in a machine-readable way'); program.parse(process.argv); storage.setup(function () { if (program.args.length !== 2) { console.error('Please specify a project and attribute.'); process.exit(1); } var name = program.args[0]; var attribute = program.args[1]; var project = storage.getProjectOrDie(name); if (attribute === 'directory') { project.directory = utilities.expand(project.directory); } if (program.porcelain) { console.log(project[attribute]); } else { console.log('%s:%s: "%s"', project.name, attribute, project[attribute]); } });
Raise coverage. Lets see if this can work with JaCoCo
package sortpom.exception; import org.apache.maven.plugin.MojoFailureException; /** * Converts internal runtime FailureException in a method to a MojoFailureException in order to give nice output to * the Maven framework */ public class ExceptionConverter { private final Runnable method; public ExceptionConverter(Runnable method) { this.method = method; } public void executeAndConvertException() throws MojoFailureException { try { method.run(); } catch (FailureException fex) { if (fex.getCause() != null) { throw new MojoFailureException(fex.getMessage(), fex.getCause()); } else { throw new MojoFailureException(fex.getMessage()); } } } }
package sortpom.exception; import org.apache.maven.plugin.MojoFailureException; /** * Converts internal runtime FailureException in a method to a MojoFailureException in order to give nice output to * the Maven framework */ public class ExceptionConverter { private final Runnable method; private FailureException fex; public ExceptionConverter(Runnable method) { this.method = method; } public void executeAndConvertException() throws MojoFailureException { try { method.run(); } catch (FailureException fex) { this.fex = fex; } if (fex != null) { throwMojoFailureException(); } } private void throwMojoFailureException() throws MojoFailureException { if (fex.getCause() != null) { throw new MojoFailureException(fex.getMessage(), fex.getCause()); } else { throw new MojoFailureException(fex.getMessage()); } } }
Update help for the registry option, which is now a URI.
#!/usr/bin/env node var updater = require('update-notifier'), pkg = require('../package.json'); updater({pkg: pkg}).notify(); var yargs = require('yargs') .option('registry', { description: 'url of the registry to use', default: 'https://registry.npmjs.org' }) .help('help') .version(function() { return require('../package').version; }) .describe('version', 'show version information') .usage('the helpful wombat tool'); var requireDirectory = require('require-directory'), commands = requireDirectory(module, '../commands'); Object.keys(commands).forEach(function(c) { var cmd = commands[c]; yargs.command(cmd); if (cmd.aliases) { cmd.aliases.forEach(function(alias) { yargs.command(alias, false, cmd); }); } }); var argv = yargs.argv; // wombat : npm :: hub : git if (!argv._handled) { var spawn = require('child_process').spawn; var opts = { cwd: process.cwd, env: process.env, stdio: 'inherit', }; var original = process.argv.slice(2); spawn('npm', original, opts) .on('exit',function(code){ process.exit(code); }); }
#!/usr/bin/env node var updater = require('update-notifier'), pkg = require('../package.json'); updater({pkg: pkg}).notify(); var yargs = require('yargs') .option('registry', { description: 'fully-qualified hostname of the registry to use', default: 'https://registry.npmjs.org' }) .help('help') .version(function() { return require('../package').version; }) .describe('version', 'show version information') .usage('the helpful wombat tool'); var requireDirectory = require('require-directory'), commands = requireDirectory(module, '../commands'); Object.keys(commands).forEach(function(c) { var cmd = commands[c]; yargs.command(cmd); if (cmd.aliases) { cmd.aliases.forEach(function(alias) { yargs.command(alias, false, cmd); }); } }); var argv = yargs.argv; // wombat : npm :: hub : git if (!argv._handled) { var spawn = require('child_process').spawn; var opts = { cwd: process.cwd, env: process.env, stdio: 'inherit', }; var original = process.argv.slice(2); spawn('npm', original, opts) .on('exit',function(code){ process.exit(code); }); }
OLMIS-3608: Move variable to comply with Java Code Conventions.
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ package org.openlmis.fulfillment.service; import org.apache.commons.lang3.StringUtils; public class ResourceNames { public static final String SEPARATOR = "/"; public static final String BASE_PATH = "/api"; public static final String USERS = "users"; private ResourceNames() {} public static String getUsersPath() { return getPath(USERS); } private static String getPath(String resourseName) { return StringUtils.joinWith(SEPARATOR, BASE_PATH, resourseName) + SEPARATOR; } }
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2017 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms * of the GNU Affero General Public License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  * See the GNU Affero General Public License for more details. You should have received a copy of * the GNU Affero General Public License along with this program. If not, see * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ package org.openlmis.fulfillment.service; import org.apache.commons.lang3.StringUtils; public class ResourceNames { private ResourceNames() {} public static final String SEPARATOR = "/"; public static final String BASE_PATH = "/api"; public static final String USERS = "users"; public static String getUsersPath() { return getPath(USERS); } private static String getPath(String resourseName) { return StringUtils.joinWith(SEPARATOR, BASE_PATH, resourseName) + SEPARATOR; } }
Set default value for Registry.playbook
from django.db import models from django.conf import settings class Playbook(models.Model): name = models.CharField(max_length=200) inventory = models.CharField(max_length=200, default="hosts") user = models.CharField(max_length=200, default="ubuntu") directory = models.CharField(max_length=200, editable=False, default="dir") def __str__(self): return "%s" % self.name def format_directory(self): directory = self.name.lower() directory = directory.replace(" ","-") return directory def save(self, *args, **kwargs): self.directory = self.format_directory() super(Playbook, self).save(*args, **kwargs) class Meta: verbose_name_plural = "playbooks" class Registry(models.Model): playbook = models.ForeignKey("Playbook", default=1, on_delete=models.CASCADE) name = models.CharField(max_length=200) item = models.FilePathField(path=settings.PLAYBOOK_DIR, recursive=True) def __str__(self): return "%s" % self.name class Meta: verbose_name_plural = "registries"
from django.db import models from django.conf import settings class Playbook(models.Model): name = models.CharField(max_length=200) inventory = models.CharField(max_length=200, default="hosts") user = models.CharField(max_length=200, default="ubuntu") directory = models.CharField(max_length=200, editable=False, default="dir") def __str__(self): return "%s" % self.name def format_directory(self): directory = self.name.lower() directory = directory.replace(" ","-") return directory def save(self, *args, **kwargs): self.directory = self.format_directory() super(Playbook, self).save(*args, **kwargs) class Meta: verbose_name_plural = "playbooks" class Registry(models.Model): playbook = models.ForeignKey(Playbook, on_delete=models.CASCADE) name = models.CharField(max_length=200) item = models.FilePathField(path=settings.PLAYBOOK_DIR, recursive=True) def __str__(self): return "%s" % self.name class Meta: verbose_name_plural = "registries"
Remove console.log from responce time
'use strict'; var config = require('../config').default; var metrics = null; if (config.metrics) { var StatsD = require('node-statsd'); metrics = new StatsD({ host: config.metrics.host, prefix: config.metrics.name + '_' + (process.env.METRICS_NODE ? process.env.METRICS_NODE : '') }); } module.exports = { metrics, responseTime } /** * StatsD a response time with microsecond precision * @return {Function} */ function responseTime() { return function *(next) { const start = process.hrtime(); yield next; const elapsed = process.hrtime(start); if (metrics) metrics.timing('_response_time', + (elapsed[0] * 1e3 + elapsed[1] / 1e6).toFixed(3)); // in ms }; }
'use strict'; var config = require('../config').default; var metrics = null; if (config.metrics) { var StatsD = require('node-statsd'); metrics = new StatsD({ host: config.metrics.host, prefix: config.metrics.name + '_' + (process.env.METRICS_NODE ? process.env.METRICS_NODE : '') }); } module.exports = { metrics, responseTime } /** * StatsD a response time with microsecond precision * @return {Function} */ function responseTime() { return function *(next) { const start = process.hrtime(); yield next; const elapsed = process.hrtime(start); console.log('responseTime', (elapsed[0] * 1e3 + elapsed[1] / 1e6).toFixed(3)) if (metrics) metrics.timing('_response_time', + (elapsed[0] * 1e3 + elapsed[1] / 1e6).toFixed(3)); // in ms }; }
Support JWT as a Bearer token
<?php namespace hiapi\Core\Auth; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; abstract class AuthMiddleware implements MiddlewareInterface { /** * @inheritDoc */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $this->authenticate($request); return $handler->handle($request); } abstract public function authenticate(ServerRequestInterface $request); protected function getAccessToken(ServerRequestInterface $request): ?string { return $this->getBearerToken($request) ?? $this->getParam($request, 'access_token'); } protected function getBearerToken(ServerRequestInterface $request): ?string { $header = $request->getHeaderLine('Authorization'); if (preg_match('/^Bearer\s+([a-zA-Z0-9._-]{30,})$/', $header, $matches)) { return $matches[1]; } return null; } public function getParam(ServerRequestInterface $request, string $name): ?string { return $request->getParsedBody()[$name] ?? $request->getQueryParams()[$name] ?? null; } }
<?php namespace hiapi\Core\Auth; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; abstract class AuthMiddleware implements MiddlewareInterface { /** * @inheritDoc */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $this->authenticate($request); return $handler->handle($request); } abstract public function authenticate(ServerRequestInterface $request); protected function getAccessToken(ServerRequestInterface $request): ?string { return $this->getBearerToken($request) ?? $this->getParam($request, 'access_token'); } protected function getBearerToken(ServerRequestInterface $request): ?string { $header = $request->getHeaderLine('Authorization'); if (preg_match('/^Bearer\s+([a-zA-Z0-9._-]{30,50})$/', $header, $matches)) { return $matches[1]; } return null; } public function getParam(ServerRequestInterface $request, string $name): ?string { return $request->getParsedBody()[$name] ?? $request->getQueryParams()[$name] ?? null; } }
Add log level setting to mailer function
# -*- coding: utf-8 -*- import smtplib import arrow from email.mime.text import MIMEText from logging import INFO as LOGGING_INFO, DEBUG as LOGGING_DEBUG def send_on_email(report, subject, mail_from, mail_to, smtp_auth, log_level=LOGGING_INFO): smtp_login, smtp_password = smtp_auth msg = MIMEText(report.encode('utf-8'), 'html', 'utf-8') msg["Subject"] = subject msg["From"] = mail_from to = ', '.join(mail_to.split()) msg["To"] = to s = smtplib.SMTP_SSL('smtp.mail.ru', 465) if log_level == LOGGING_DEBUG: s.set_debuglevel(1) s.login(smtp_login, smtp_password) s.sendmail(smtp_login, mail_to, msg.as_string()) # sender address must match authenticated user def get_day_offset(): """ Get previous working day offset :return: """ now = arrow.now() offsets = (3, 1, 1, 1, 1, 1, 2) return offsets[now.weekday()] def get_jira_list(l): """ Format any lists to jira string :param l: list to format ["aaa", "bbb", "ccc"] :return: string looks like '"aaa", "bbb", "ccc"' """ return ', '.join('"%s"' % x for x in l)
# -*- coding: utf-8 -*- import smtplib import arrow from email.mime.text import MIMEText def send_on_email(report, subject, mail_from, mail_to, smtp_auth): smtp_login, smtp_password = smtp_auth msg = MIMEText(report.encode('utf-8'), 'html', 'utf-8') msg["Subject"] = subject msg["From"] = mail_from to = ', '.join(mail_to.split()) msg["To"] = to s = smtplib.SMTP_SSL('smtp.mail.ru', 465) # s.set_debuglevel(2) # ToDo: parametrize it s.login(smtp_login, smtp_password) s.sendmail(smtp_login, mail_to, msg.as_string()) # sender address must match authenticated user def get_day_offset(): now = arrow.now() offsets = (3, 1, 1, 1, 1, 1, 2) return offsets[now.weekday()] def get_jira_list(l): """ Format any lists to jira string :param l: list to format ["aaa", "bbb", "ccc"] :return: string looks like '"aaa", "bbb", "ccc"' """ return ', '.join('"%s"' % x for x in l)
Disable delay on server responses
var express = require('express'); var path = require('path'); var logger = require('morgan'); var slow = require('connect-slow'); var HttpError = require('./lib/http-error'); var rootRouter = require('./routes/root/root-router'); var roomsRouter = require('./routes/rooms/rooms-router'); var messagesRouter = require('./routes/messages/messages-router'); var app = express(); app.set('x-powered-by', false); app.use(logger('dev')); app.use('/', rootRouter); //app.use(slow()); app.use('/rooms', roomsRouter); app.use('/messages', messagesRouter); // catch unhandled routes app.use(function (req, res, next) { next(new HttpError(404, 'Not found')); }); // generic error handler app.use(function (err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; res.status(err.status || 500).send(err.message); }); module.exports = app;
var express = require('express'); var path = require('path'); var logger = require('morgan'); var slow = require('connect-slow'); var HttpError = require('./lib/http-error'); var rootRouter = require('./routes/root/root-router'); var roomsRouter = require('./routes/rooms/rooms-router'); var messagesRouter = require('./routes/messages/messages-router'); var app = express(); app.set('x-powered-by', false); app.use(logger('dev')); app.use('/', rootRouter); app.use(slow()); app.use('/rooms', roomsRouter); app.use('/messages', messagesRouter); // catch unhandled routes app.use(function (req, res, next) { next(new HttpError(404, 'Not found')); }); // generic error handler app.use(function (err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; res.status(err.status || 500).send(err.message); }); module.exports = app;
Use no more than 1 process.
#!/usr/bin/env node var app = require('./server/app'), http = require('http'), cluster = require('cluster'), numCPU = 1, //require('os').cpus().length, i = 0; if (cluster.isMaster){ for (i; i<numCPU; i++){ cluster.fork(); } cluster.on('fork', function(worker){ console.log('forked worker ' + worker.process.pid); }); cluster.on('exit', function(worker, code, signal){ console.log('worker ' + worker.process.pid + ' died'); cluster.fork(); }); } else { // -- database var mongoose = require('mongoose'); app.db = mongoose.connect('mongodb://localhost/' + app.conf.db_name); // -- handle node exceptions process.on('uncaughtException', function(err){ console.error('uncaughtException', err.message); console.error(err.stack); process.exit(1); }); // -- start server http.createServer(app).listen(app.conf.port, function(){ console.log("Express server listening on port %d in %s mode", app.conf.port, app.settings.env); }); }
#!/usr/bin/env node var app = require('./server/app'), http = require('http'), cluster = require('cluster'), numCPU = require('os').cpus().length, i = 0; if (cluster.isMaster){ for (i; i<numCPU; i++){ cluster.fork(); } cluster.on('fork', function(worker){ console.log('forked worker ' + worker.process.pid); }); cluster.on('exit', function(worker, code, signal){ console.log('worker ' + worker.process.pid + ' died'); cluster.fork(); }); } else { // -- database var mongoose = require('mongoose'); app.db = mongoose.connect('mongodb://localhost/' + app.conf.db_name); // -- handle node exceptions process.on('uncaughtException', function(err){ console.error('uncaughtException', err.message); console.error(err.stack); process.exit(1); }); // -- start server http.createServer(app).listen(app.conf.port, function(){ console.log("Express server listening on port %d in %s mode", app.conf.port, app.settings.env); }); }
Remove eof double line-break in service test
import { moduleFor, test } from 'ember-qunit'; moduleFor('service:flashes', 'Unit | Service | flashes', { // Specify the other units that are required for this test. // needs: ['service:foo'] }); test('it allows to show an error', function (assert) { let service = this.subject(); assert.equal(service.get('flashes.length'), 0, 'precond - flashes initializes with 0 elements'); service.error('There was an error!'); assert.deepEqual(service.get('flashes.firstObject'), { message: 'There was an error!', type: 'error' }, 'there should be an error message in flashes'); }); test('it allows to show a notice', function (assert) { let service = this.subject(); assert.equal(service.get('flashes.length'), 0, 'precond - flashes initializes with 0 elements'); service.notice('There was a notice!'); assert.deepEqual(service.get('flashes.firstObject'), { message: 'There was a notice!', type: 'notice' }, 'there should be a notice message in flashes'); }); test('it allows to show a success', function (assert) { let service = this.subject(); assert.equal(service.get('flashes.length'), 0, 'precond - flashes initializes with 0 elements'); service.success('There was a success!'); assert.deepEqual(service.get('flashes.firstObject'), { message: 'There was a success!', type: 'success' }, 'there should be a notice message in flashes'); });
import { moduleFor, test } from 'ember-qunit'; moduleFor('service:flashes', 'Unit | Service | flashes', { // Specify the other units that are required for this test. // needs: ['service:foo'] }); test('it allows to show an error', function (assert) { let service = this.subject(); assert.equal(service.get('flashes.length'), 0, 'precond - flashes initializes with 0 elements'); service.error('There was an error!'); assert.deepEqual(service.get('flashes.firstObject'), { message: 'There was an error!', type: 'error' }, 'there should be an error message in flashes'); }); test('it allows to show a notice', function (assert) { let service = this.subject(); assert.equal(service.get('flashes.length'), 0, 'precond - flashes initializes with 0 elements'); service.notice('There was a notice!'); assert.deepEqual(service.get('flashes.firstObject'), { message: 'There was a notice!', type: 'notice' }, 'there should be a notice message in flashes'); }); test('it allows to show a success', function (assert) { let service = this.subject(); assert.equal(service.get('flashes.length'), 0, 'precond - flashes initializes with 0 elements'); service.success('There was a success!'); assert.deepEqual(service.get('flashes.firstObject'), { message: 'There was a success!', type: 'success' }, 'there should be a notice message in flashes'); });
Update the supported file types list exposed to QML to use the new dict correctly
from PyQt5.QtCore import QObject, pyqtSlot, pyqtProperty, pyqtSignal from UM.Application import Application from UM.Logger import Logger class MeshFileHandlerProxy(QObject): def __init__(self, parent = None): super().__init__(parent) self._mesh_handler = Application.getInstance().getMeshFileHandler() @pyqtProperty("QStringList", constant=True) def supportedReadFileTypes(self): file_types = [] all_types = [] for ext, desc in self._mesh_handler.getSupportedFileTypesRead().items(): file_types.append("{0} (*.{1})(*.{1})".format(desc, ext)) all_types.append("*.{0}".format(ext)) file_types.sort() file_types.insert(0, "All Supported Types ({0})({0})".format(" ".join(all_types))) file_types.append("All Files (*.*)(*)") return file_types @pyqtProperty("QStringList", constant=True) def supportedWriteFileTypes(self): #TODO: Implement return [] def createMeshFileHandlerProxy(engine, script_engine): return MeshFileHandlerProxy()
from PyQt5.QtCore import QObject, pyqtSlot, pyqtProperty, pyqtSignal from UM.Application import Application from UM.Logger import Logger class MeshFileHandlerProxy(QObject): def __init__(self, parent = None): super().__init__(parent) self._mesh_handler = Application.getInstance().getMeshFileHandler() @pyqtProperty("QStringList", constant=True) def supportedReadFileTypes(self): fileTypes = [] fileTypes.append("All Supported Files (*{0})(*{0})".format(' *'.join(self._mesh_handler.getSupportedFileTypesRead()))) for ext in self._mesh_handler.getSupportedFileTypesRead(): fileTypes.append("{0} file (*.{0})(*.{0})".format(ext[1:])) fileTypes.append("All Files (*.*)(*)") return fileTypes @pyqtProperty("QStringList", constant=True) def supportedWriteFileTypes(self): return self._mesh_handler.getSupportedFileTypesWrite() def createMeshFileHandlerProxy(engine, scriptEngine): return MeshFileHandlerProxy()
Change argument to require from relative to global path
/** * @module client/main */ 'use strict'; var app = require('app'); require('angular'); /** * Each 'index' generated via grunt process dynamically includes all browserify common-js modules * in js bundle */ require('./controllers/index'); require('./services/index'); require('./router'); var io = require('./lib/socket.io'); var socket = io.connect('http://localhost:3000'); socket.on('postSequence', function (data) { console.log('postSequence: ', data); }); /** * Bundle of all templates to be attached to $templateCache generated by grunt process */ var views = require('./build/views/viewBundle'); /** * Pre-load template cache with compiled jade templates included in JS bundle */ app.run(['$rootScope', '$templateCache', function ( $rootScope, $templateCache) { Object.keys(views.Templates).forEach(function (viewName) { $templateCache.put(viewName, views.Templates[viewName]()); }); } ]); /** * DOM-ready event, start app */ angular.element(document).ready(function () { angular.bootstrap(document, ['app']); });
/** * @module client/main */ 'use strict'; var app = require('./app'); require('angular'); /** * Each 'index' generated via grunt process dynamically includes all browserify common-js modules * in js bundle */ require('./controllers/index'); require('./services/index'); require('./router'); var io = require('./lib/socket.io'); var socket = io.connect('http://localhost:3000'); socket.on('postSequence', function (data) { console.log('postSequence: ', data); }); /** * Bundle of all templates to be attached to $templateCache generated by grunt process */ var views = require('./build/views/viewBundle'); /** * Pre-load template cache with compiled jade templates included in JS bundle */ app.run(['$rootScope', '$templateCache', function ( $rootScope, $templateCache) { Object.keys(views.Templates).forEach(function (viewName) { $templateCache.put(viewName, views.Templates[viewName]()); }); } ]); /** * DOM-ready event, start app */ angular.element(document).ready(function () { angular.bootstrap(document, ['app']); });
Use percent encoding for calculating the signature
package oauth import ( "bytes" "fmt" ) var hex = "0123456789ABCDEF" // encode percent-encodes a string as defined in RFC 3986. func encode(s string) string { var buf bytes.Buffer for _, c := range []byte(s) { if isEncodable(c) { if c == '+' { // replace plus-encoding with percent-encoding buf.WriteString("%2520") } else { buf.WriteByte('%') buf.WriteByte(hex[c>>4]) buf.WriteByte(hex[c&15]) } } else { buf.WriteByte(c) } } return buf.String() } func encodeQuoted(key, value string) string { return fmt.Sprintf("%s=\"%s\"", encode(key), encode(value)) } // isEncodable returns true if a given character should be percent-encoded // according to RFC 3986. func isEncodable(c byte) bool { // return false if c is an unreserved character (see RFC 3986 section 2.3) switch { case (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'): return false case c >= '0' && c <= '9': return false case c == '-' || c == '.' || c == '_' || c == '~': return false } return true }
package oauth import ( "bytes" "fmt" ) var hex = "0123456789ABCDEF" // encode percent-encodes a string as defined in RFC 3986. func encode(s string) string { var buf bytes.Buffer for _, c := range []byte(s) { if isEncodable(c) { buf.WriteByte('%') buf.WriteByte(hex[c>>4]) buf.WriteByte(hex[c&15]) } else { buf.WriteByte(c) } } return buf.String() } func encodeQuoted(key, value string) string { return fmt.Sprintf("%s=\"%s\"", encode(key), encode(value)) } // isEncodable returns true if a given character should be percent-encoded // according to RFC 3986. func isEncodable(c byte) bool { // return false if c is an unreserved character (see RFC 3986 section 2.3) switch { case (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'): return false case c >= '0' && c <= '9': return false case c == '-' || c == '.' || c == '_' || c == '~': return false } return true }
Fix exception handling to extend colander.Invalid
from setuptools import setup setup( name='Py-Authorize', version='1.0.1.3', author='Vincent Catalano', author_email='vincent@vincentcatlano.com', url='https://github.com/vcatalano/py-authorize', download_url='', description='A full-featured Python API for Authorize.net.', long_description=__doc__, license='MIT', install_requires=[ 'colander', ], packages=[ 'authorize', 'authorize.apis', ], classifiers=[ 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2', 'License :: OSI Approved :: MIT License', 'Topic :: Office/Business :: Financial', 'Topic :: Internet :: WWW/HTTP', ], )
from setuptools import setup setup( name='Py-Authorize', version='1.0.1.2', author='Vincent Catalano', author_email='vincent@vincentcatlano.com', url='https://github.com/vcatalano/py-authorize', download_url='', description='A full-featured Python API for Authorize.net.', long_description=__doc__, license='MIT', install_requires=[ 'colander', ], packages=[ 'authorize', 'authorize.apis', ], classifiers=[ 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Programming Language :: Python :: 2', 'License :: OSI Approved :: MIT License', 'Topic :: Office/Business :: Financial', 'Topic :: Internet :: WWW/HTTP', ], )
Check for account activity before password verification
""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() return user
""" byceps.services.authentication.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ..user.models.user import User from ..user import service as user_service from .exceptions import AuthenticationFailed from .password import service as password_service def authenticate(screen_name: str, password: str) -> User: """Try to authenticate the user. Return the user object on success, or raise an exception on failure. """ # Look up user. user = user_service.find_user_by_screen_name(screen_name) if user is None: # Screen name is unknown. raise AuthenticationFailed() # Verify credentials. if not password_service.is_password_valid_for_user(user.id, password): # Password does not match. raise AuthenticationFailed() # Account must be active. if not user.is_active: # User account is disabled. raise AuthenticationFailed() return user
Handle missing fields in dataverse
import arrow import dateparser from share.normalize import * class Person(Parser): given_name = ParseName(ctx).first family_name = ParseName(ctx).last additional_name = ParseName(ctx).middle suffix = ParseName(ctx).suffix class Contributor(Parser): person = Delegate(Person, ctx) cited_name = ctx order_cited = ctx('index') class Link(Parser): url = ctx type = RunPython('get_link_type', ctx) def get_link_type(self, link): if 'dx.doi.org' in link: return 'doi' elif 'dataverse.harvard.edu' in link: return 'provider' return 'misc' class ThroughLinks(Parser): link = Delegate(Link, ctx) class CreativeWork(Parser): title = ctx.name description = Try(ctx.description) contributors = Map(Delegate(Contributor), Try(ctx.authors)) date_published = ParseDate(ctx.published_at) links = Concat( Delegate(ThroughLinks, ctx.url), Delegate(ThroughLinks, ctx.image_url), )
import arrow import dateparser from share.normalize import * class Person(Parser): given_name = ParseName(ctx).first family_name = ParseName(ctx).last additional_name = ParseName(ctx).middle suffix = ParseName(ctx).suffix class Contributor(Parser): person = Delegate(Person, ctx) cited_name = ctx order_cited = ctx('index') class Link(Parser): url = ctx type = RunPython('get_link_type', ctx) def get_link_type(self, link): if 'dx.doi.org' in link: return 'doi' elif 'dataverse.harvard.edu' in link: return 'provider' return 'misc' class ThroughLinks(Parser): link = Delegate(Link, ctx) class CreativeWork(Parser): title = ctx.name description = ctx.description contributors = Map(Delegate(Contributor), ctx.authors) date_published = ParseDate(ctx.published_at) links = Concat( Delegate(ThroughLinks, ctx.url), Delegate(ThroughLinks, ctx.image_url), )
Fix sef map config provider
<?php defined('M2_MICRO') or die('Direct Access to this location is not allowed.'); /** * Sef map array * @name $sef_map * @package M2 Micro Framework * @subpackage Library * @author Alexander Chaika * @since 0.2RC1 */ return array( '/\?module\=blog\&action\=show\&id\=(.*)/' => array( 'table' => 'post', 'field' => 'alias', 'prefix' => '/blog/', 'suffix' => Application::$config['sef_suffix'] ), '/\?module\=blog\&action\=category\&id\=(.*)/' => array( 'table' => 'category', 'field' => 'alias', 'prefix' => '/category/', 'suffix' => Application::$config['sef_suffix'] ) );
<?php defined('M2_MICRO') or die('Direct Access to this location is not allowed.'); /** * Sef map array * @name $sef_map * @package M2 Micro Framework * @subpackage Library * @author Alexander Chaika * @since 0.2RC1 */ return array( '/\?module\=blog\&action\=show\&id\=(.*)/' => array( 'table' => 'post', 'field' => 'alias', 'prefix' => '/blog/', 'suffix' => $config['sef_suffix'] ), '/\?module\=blog\&action\=category\&id\=(.*)/' => array( 'table' => 'category', 'field' => 'alias', 'prefix' => '/category/', 'suffix' => $config['sef_suffix'] ) );
Change URL back to sorseg.ru (brought up instance)
package com.dao.mydebts; import okhttp3.MediaType; /** * @author Oleg Chernovskiy on 05.04.16. */ public class Constants { //private static final String SERVER_ENDPOINT = "sorseg.ru:8080/debt/"; //private static final String SERVER_ENDPOINT = "http://demoth.no-ip.org:8080/debt/"; private static final String SERVER_ENDPOINT = "http://sorseg.ru:1337/debt/"; public static final String SERVER_ENDPOINT_DEBTS = SERVER_ENDPOINT + "debts"; public static final String SERVER_ENDPOINT_CREATE = SERVER_ENDPOINT + "createDebt"; public static final String SERVER_ENDPOINT_APPROVE = SERVER_ENDPOINT + "approve"; public static final MediaType JSON_MIME_TYPE = MediaType.parse("application/json"); public static final int DEBT_REQUEST_LOADER = 0; private Constants() { } }
package com.dao.mydebts; import okhttp3.MediaType; /** * @author Oleg Chernovskiy on 05.04.16. */ public class Constants { //private static final String SERVER_ENDPOINT = "sorseg.ru:8080/debt/"; //private static final String SERVER_ENDPOINT = "http://demoth.no-ip.org:8080/debt/"; private static final String SERVER_ENDPOINT = "http://192.168.1.165:1337/debt/"; public static final String SERVER_ENDPOINT_DEBTS = SERVER_ENDPOINT + "debts"; public static final String SERVER_ENDPOINT_CREATE = SERVER_ENDPOINT + "createDebt"; public static final String SERVER_ENDPOINT_APPROVE = SERVER_ENDPOINT + "approve"; public static final MediaType JSON_MIME_TYPE = MediaType.parse("application/json"); public static final int DEBT_REQUEST_LOADER = 0; private Constants() { } }
Use bassoradio as temp stream for radiodiodi
var util = require('../src/util/seeds'); exports.seed = function(knex, Promise) { const cities = {}; return knex('cities').select('*') .then(rows => { rows.forEach(city => { cities[city.name] = city.id; }); }) .then(() => util.insertOrUpdate(knex, 'radios', { id: 1, name: 'Rakkauden Wappuradio', city_id: cities['Tampere'], stream: 'http://stream.wappuradio.fi/wappuradio.mp3', website: 'https://wappuradio.fi/', })) .then(() => util.insertOrUpdate(knex, 'radios', { id: 2, name: 'Radiodiodi', city_id: cities['Otaniemi'], stream: 'http://stream.basso.fi:8000/stream', // TODO: Change to real website: 'https://radiodiodi.fi/', })); }
var util = require('../src/util/seeds'); exports.seed = function(knex, Promise) { const cities = {}; return knex('cities').select('*') .then(rows => { rows.forEach(city => { cities[city.name] = city.id; }); }) .then(() => util.insertOrUpdate(knex, 'radios', { id: 1, name: 'Rakkauden Wappuradio', city_id: cities['Tampere'], stream: 'http://stream.wappuradio.fi/wappuradio.mp3', website: 'https://wappuradio.fi/', })) .then(() => util.insertOrUpdate(knex, 'radios', { id: 2, name: 'Radiodiodi', city_id: cities['Otaniemi'], stream: null, // TODO website: 'https://radiodiodi.fi/', })); }
Test + travis = error
package main import ( "fmt" "testing" "github.com/spf13/viper" ) func TestSomething(t *testing.T) { viper.SetConfigName("config") viper.AddConfigPath(".") if err := viper.ReadInConfig(); err != nil { fmt.Printf("%v", err) } } /* func TestMain(m *testing.M) { i18n.MustLoadTranslationFile("lang/en-US.all.json") i18n.MustLoadTranslationFile("lang/fr.all.json") mylog.Init(mylog.ERROR) os.Exit(m.Run()) } func TestReadConfigFound(t *testing.T) { if err := readConfig("configForTest"); err != nil { fmt.Printf("%v", err) } }*/ /*func TestReadConfigNotFound(t *testing.T) { if err := readConfig("configError"); err != nil { fmt.Printf("%v", err) } }*/
package main import ( "fmt" "os" "testing" "github.com/nicksnyder/go-i18n/i18n" mylog "github.com/patrickalin/GoMyLog" "github.com/spf13/viper" ) func TestSomething(t *testing.T) { viper.SetConfigName("config") viper.AddConfigPath(".") if err := viper.ReadInConfig(); err != nil { fmt.Printf("%v", err) } } func TestMain(m *testing.M) { i18n.MustLoadTranslationFile("lang/en-US.all.json") i18n.MustLoadTranslationFile("lang/fr.all.json") mylog.Init(mylog.ERROR) os.Exit(m.Run()) } func TestReadConfigFound(t *testing.T) { if err := readConfig("configForTest"); err != nil { fmt.Printf("%v", err) } } /*func TestReadConfigNotFound(t *testing.T) { if err := readConfig("configError"); err != nil { fmt.Printf("%v", err) } }*/
Increase the ES timeout to 1 minute.
import certifi from django.apps import AppConfig from django.conf import settings from django.utils.translation import ugettext_lazy as _ from elasticsearch_dsl.connections import connections class DocsConfig(AppConfig): name = 'docs' verbose_name = _('Documentation') def ready(self): super(DocsConfig, self).ready() # Configure Elasticsearch connections for connection pooling. connections.configure( default={ 'hosts': settings.ES_HOST, 'verify_certs': True, 'ca_certs': certifi.where(), 'timeout': 60.0, }, )
import certifi from django.apps import AppConfig from django.conf import settings from django.utils.translation import ugettext_lazy as _ from elasticsearch_dsl.connections import connections class DocsConfig(AppConfig): name = 'docs' verbose_name = _('Documentation') def ready(self): super(DocsConfig, self).ready() # Configure Elasticsearch connections for connection pooling. connections.configure( default={ 'hosts': settings.ES_HOST, 'verify_certs': True, 'ca_certs': certifi.where(), }, )
Tweak kv migration to improve compatibility across Django versions
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import jsonfield.fields class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL) ] operations = [ migrations.CreateModel( name='KeyValue', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('key', models.CharField(max_length=64, db_index=True)), ('value', jsonfield.fields.JSONField()), ('group', models.ForeignKey(to='auth.Group')), ], ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ] operations = [ migrations.CreateModel( name='KeyValue', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('key', models.CharField(max_length=64, db_index=True)), ('value', jsonfield.fields.JSONField()), ('group', models.ForeignKey(to='auth.Group')), ], ), ]
Improve header collapse by using outerHeight
if (typeof jQuery === 'undefined') { throw new Error('Custom JS requires jQuery...'); } +function ($) { 'use strict'; $(document).ready(function () { var outer = $('#affix-outer'), collapse = $('#affix-collapse'), sticky = $('#affix-sticky'), wrapper = $('#affix-wrapper'), setWrapperHeight = function() { wrapper.css('min-height', sticky.outerHeight()); }, getOffset = function() { return collapse.outerHeight(true/*include margin*/); }; setWrapperHeight(); outer.affix({ offset: { top: getOffset() } }); $(window).on("resize", function(){ setWrapperHeight(); outer.data('bs.affix').options.offset = getOffset(); }); }); }(jQuery);
if (typeof jQuery === 'undefined') { throw new Error('Custom JS requires jQuery...'); } +function ($) { 'use strict'; $(document).ready(function () { var outer = $('#affix-outer'), collapse = $('#affix-collapse'), sticky = $('#affix-sticky'), wrapper = $('#affix-wrapper'), setWrapperHeight = function() { wrapper.css('min-height', sticky.height()); }, getOffset = function() { return collapse.outerHeight(true/*include margin*/); }; setWrapperHeight(); outer.affix({ offset: { top: getOffset() } }); $(window).on("resize", function(){ setWrapperHeight(); outer.data('bs.affix').options.offset = getOffset(); }); }); }(jQuery);
Comment added; Scheduling still in question
var app = require('express'); const router = app.Router({ mergeParams: true }); var retrieval = require('../retrieval/retrieval'); var schedule = require('./algorithms-courseformat/courseMatrixUsage') // .../api/scheduling?courses=['course1','course2',...,'courseN'] router.get('/', function(req, res){ if (!req.query.hasOwnProperty('courses')){ res.status(400).json({message:"Make sure to include an courses GET parameter as JSON array"}); } var courseSelection = JSON.parse(req.query.courses); var coursesLen = courseSelection.length; var courses = []; courseSelection.forEach(function(element) { retrieval.getSingleCourseByCode(element, function(course){ if (course){ courses.push(course); } else { --coursesLen; } if (courses.length == coursesLen){ var sched = schedule.genScheds(courses); res.status(200).json({data:sched}); } }); }, this); }) module.exports = router;
var app = require('express'); const router = app.Router({ mergeParams: true }); var retrieval = require('../retrieval/retrieval'); var schedule = require('./algorithms-courseformat/courseMatrixUsage') router.get('/', function(req, res){ if (!req.query.hasOwnProperty('courses')){ res.status(400).json({message:"Make sure to include an courses GET parameter as JSON array"}); } var courseSelection = JSON.parse(req.query.courses); var coursesLen = courseSelection.length; var courses = []; courseSelection.forEach(function(element) { retrieval.getSingleCourseByCode(element, function(course){ if (course){ courses.push(course); } else { --coursesLen; } if (courses.length == coursesLen){ var sched = schedule.genScheds(courses); res.status(200).json({data:sched}); } }); }, this); }) module.exports = router;
Change formatting in JS files [skip ci]
const types = require('./types'); /** * Redux action creator. Returns action for adding a post. * @param {object} post Posts data * @return {object} Action */ function addPost(post) { return { type: types.POSTS_ADD, payload: post }; } /** * Redux action creator. Return posts sorting action. * @param {string} field Field to sort by * @return {object} Action */ function sortPostsBy(field) { return { type: types.POSTS_SORT_BY, payload: field }; } /** * Redux action creator. Return search term updating action. * @param {string} value Search term value * @return {object} Action */ function changeSearchTerm(value) { return { type: types.SEARCH_TERM, payload: value }; } /** * Redux action creator. Return menu toggling action. * @return {object} Action */ function toggleMenu() { return { type: types.MENU_TOGGLE }; } module.exports = { addPost, sortPostsBy, changeSearchTerm, toggleMenu };
const types = require('./types'); /** * Redux action creator. Returns action for adding a post. * @param {object} post Posts data * @return {object} Action */ function addPost(post) { return {type: types.POSTS_ADD, payload: post}; } /** * Redux action creator. Return posts sorting action. * @param {string} field Field to sort by * @return {object} Action */ function sortPostsBy(field) { return {type: types.POSTS_SORT_BY, payload: field}; } /** * Redux action creator. Return search term updating action. * @param {string} value Search term value * @return {object} Action */ function searchTerm(value) { return {type: types.SEARCH_TERM, payload: value}; } /** * Redux action creator. Return menu toggling action. * @return {object} Action */ function toggleMenu() { return {type: types.MENU_TOGGLE}; } module.exports = {addPost, sortPostsBy, searchTerm, toggleMenu};
Remove vue from selectors and just use embedded html
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Brewer # Copyright (c) 2015 Jack Brewer # # License: MIT """Exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" cmd = 'stylint @ *' defaults = { 'selector': 'source.stylus, source.stylus.embedded.html', '--ignore=,': '', '--warn=,': '', '--error=,': '' } regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable # 177:24 warning hexidecimal color should be a variable colors # 177 warning hexidecimal color should be a variable colors ^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Jack Brewer # Copyright (c) 2015 Jack Brewer # # License: MIT """Exports the Stylint plugin class.""" from SublimeLinter.lint import NodeLinter, util class Stylint(NodeLinter): """Provides an interface to stylint.""" cmd = 'stylint @ *' defaults = { 'selector': 'source.stylus, text.html.vue, source.stylus.embedded.html', '--ignore=,': '', '--warn=,': '', '--error=,': '' } regex = r'''(?xi) # Comments show example output for each line of a Stylint warning # /path/to/file/example.styl ^.*$\s* # 177:24 colors warning hexidecimal color should be a variable # 177:24 warning hexidecimal color should be a variable colors # 177 warning hexidecimal color should be a variable colors ^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s* ''' multiline = True error_stream = util.STREAM_STDOUT tempfile_suffix = 'styl' config_file = ('--config', '.stylintrc', '~')
Set default buffer size to 64M
'use strict'; const ProgramError = require('./error/ProgramError'); class SortOptions { constructor(options = {}) { this.path = 'sort'; this.unique = false; this.numeric = false; this.reverse = false; this.stable = false; this.merge = false; this.ignoreCase = false; this.sortByHash = false; this.tmpDir = null; this.bufferSize = 64 * 1024 * 1024; this.separator = '\t'; this.threads = null; this.keys = []; this.inMemoryBufferSize = 16000; for (const k in options) { if (!this.hasOwnProperty(k)) { throw new ProgramError('Unknown option: ' + k); } this[k] = options[k]; } } /** * * @returns {SortOptions} */ clone() { return new SortOptions(this); } } module.exports = SortOptions;
'use strict'; const ProgramError = require('./error/ProgramError'); class SortOptions { constructor(options = {}) { this.path = 'sort'; this.unique = false; this.numeric = false; this.reverse = false; this.stable = false; this.merge = false; this.ignoreCase = false; this.sortByHash = false; this.tmpDir = null; this.bufferSize = null; this.separator = '\t'; this.threads = null; this.keys = []; this.inMemoryBufferSize = 16000; for (const k in options) { if (!this.hasOwnProperty(k)) { throw new ProgramError('Unknown option: ' + k); } this[k] = options[k]; } } /** * * @returns {SortOptions} */ clone() { return new SortOptions(this); } } module.exports = SortOptions;
Use correct test class name
<?php namespace SimplyTestable\ApiBundle\Tests\Controller; use SimplyTestable\ApiBundle\Tests\Controller\BaseControllerJsonTestCase; class GetActionTest extends BaseControllerJsonTestCase { public static function setUpBeforeClass() { self::setupDatabaseIfNotExists(); } public function testGet() { $email = 'user1@example.com'; $password = 'password1'; $user = $this->createAndFindUser($email, $password); $this->getUserService()->setUser($user); $responseObject = json_decode($this->getUserController('getAction')->getAction()->getContent()); $this->assertEquals($email, $responseObject->email); $this->assertEquals('basic', $responseObject->plan); } }
<?php namespace SimplyTestable\ApiBundle\Tests\Controller; use SimplyTestable\ApiBundle\Tests\Controller\BaseControllerJsonTestCase; class GetTokenTest extends BaseControllerJsonTestCase { public static function setUpBeforeClass() { self::setupDatabaseIfNotExists(); } public function testGet() { $email = 'user1@example.com'; $password = 'password1'; $user = $this->createAndFindUser($email, $password); $this->getUserService()->setUser($user); $responseObject = json_decode($this->getUserController('getAction')->getAction()->getContent()); $this->assertEquals($email, $responseObject->email); $this->assertEquals('basic', $responseObject->plan); } }
Add decodeWithMetadata function and improve documentation
'use strict'; var leb = require('leb'); /** * Provide operations for serializing/deserializing integer data into * variable-length 64-bit LEB128 integer encoding [1]. * * References: * [1] https://en.wikipedia.org/wiki/LEB128 * **/ var LEB128 = { /** * Encode an arbitrarily large positive integer value using a small * number of bytes. This function returns a Buffer containing the * byte values of the 64-bit LEB128-encoded integer. **/ encode: function (value) { if (value < 0) { throw new Error('Negative values are not supported'); } return leb.encodeUInt64(value); }, /** * Decode a data Buffer containing a 64-bit LEB128-encoded integer. **/ decode: function (data, offset) { if (!Buffer.isBuffer(data)) { throw new Error('Data to decode must be a Buffer object'); } return leb.decodeUInt64(data, offset ? offset : 0).value; }, /** * Decode a data Buffer containing a 64-bit LEB128-encoded integer * and return all metadata about the operation * * The metadata contains the following fields: * value: The value of the extracted LEB128-encoded integer * nextIndex: The next unseen/unused byte in the input buffer * lossy: Whether or not the extraction involved loss of precision * * Example return value: { value: 1, nextIndex: 6, lossy: false } **/ decodeWithMetadata: function (data, offset) { return leb.decodeUInt64(data, offset ? offset : 0); } }; // Public API for this object module.exports = LEB128;
'use strict'; var leb = require('leb'); /** * Provide operations for serializing/deserializing integer data into * variable-length LEB128 integer encoding [1]. * * References: * [1] https://en.wikipedia.org/wiki/LEB128 * **/ var LEB128 = { /** * Encode an arbitrarily large positive integer value using a small * number of bytes. This function returns a Buffer containing the * byte values of the LEB128-encoded integer. **/ encode: function (value) { if (value < 0) { throw new Error('Negative values are not supported'); } return leb.encodeUInt64(value); }, /** * Decode a data Buffer containing an LEB128-encoded integer. **/ decode: function (data) { if (!Buffer.isBuffer(data)) { throw new Error('Data to decode must be a Buffer object'); } return leb.decodeUInt64(data).value; } }; // Public API for this object module.exports = LEB128;
Add more Python version classifiers
#!/usr/bin/env python from setuptools import find_packages, setup # Use quickphotos.VERSION for version numbers version_tuple = __import__('quickphotos').VERSION version = '.'.join([str(v) for v in version_tuple]) setup( name='django-quick-photos', version=version, description='Latest Photos from Instagram for Django', long_description=open('README.rst').read(), url='https://github.com/blancltd/django-quick-photos', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], install_requires=[ 'python-instagram>=0.8.0', ], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD', )
#!/usr/bin/env python from setuptools import find_packages, setup # Use quickphotos.VERSION for version numbers version_tuple = __import__('quickphotos').VERSION version = '.'.join([str(v) for v in version_tuple]) setup( name='django-quick-photos', version=version, description='Latest Photos from Instagram for Django', long_description=open('README.rst').read(), url='https://github.com/blancltd/django-quick-photos', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], install_requires=[ 'python-instagram>=0.8.0', ], packages=find_packages(), classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], license='BSD', )
Allow ignore to be called at class and field level
/* * #%L * BroadleafCommerce Common Libraries * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.common.extensibility.jpa.clone; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation for fields that should not undergo enterprise sandbox config validation (if applicable) * * @author jfischer * */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) public @interface IgnoreEnterpriseConfigValidation { }
/* * #%L * BroadleafCommerce Common Libraries * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.common.extensibility.jpa.clone; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker annotation for fields that should not undergo enterprise sandbox config validation (if applicable) * * @author jfischer * */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface IgnoreEnterpriseConfigValidation { }
Fix colorize otput if there is no config settings in global config file
<?php if ( !defined( 'WP_CLI' ) ) return; global $argv; $env = $argv[1]; $config = array(); $config_path = getenv( 'HOME' ) . '/.wp-cli/config.yml'; if ( is_readable( $config_path ) ){ $configurator = \WP_CLI::get_configurator(); $configurator->merge_yml( $config_path ); list( $config, $extra_config ) = $configurator->to_array(); } if ( isset($config['color']) && 'auto' === $config['color'] ) { $colorize = !\cli\Shell::isPiped(); } elseif(isset($config['color'])) { $colorize = $config['color']; }else { $colorize = true; } if ( isset($config['quiet']) && $config['quiet'] ) $logger = new \WP_CLI\Loggers\Quiet; else $logger = new \WP_CLI\Loggers\Regular( $colorize ); \WP_CLI::set_logger( $logger ); try { $environment = new \ViewOne\Environment(); $environment->run($env); } catch (Exception $e) { \WP_CLI::error( $e->getMessage() ); }
<?php if ( !defined( 'WP_CLI' ) ) return; global $argv; $env = $argv[1]; $config = array(); $config_path = getenv( 'HOME' ) . '/.wp-cli/config.yml'; if ( is_readable( $config_path ) ){ $configurator = \WP_CLI::get_configurator(); $configurator->merge_yml( $config_path ); list( $config, $extra_config ) = $configurator->to_array(); } if ( 'auto' === $config['color'] ) { $colorize = !\cli\Shell::isPiped(); } else { $colorize = $config['color']; } if ( isset($config['quiet']) && $config['quiet'] ) $logger = new \WP_CLI\Loggers\Quiet; else $logger = new \WP_CLI\Loggers\Regular( $colorize ); \WP_CLI::set_logger( $logger ); try { $environment = new \ViewOne\Environment(); $environment->run($env); } catch (Exception $e) { \WP_CLI::error( $e->getMessage() ); }
Fix wording for remote shares in settings page
<div class="section" id="fileSharingSettings" > <h2><?php p($l->t('Remote Shares'));?></h2> <input type="checkbox" name="outgoing_server2server_share_enabled" id="outgoingServer2serverShareEnabled" value="1" <?php if ($_['outgoingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> /> <label for="outgoingServer2serverShareEnabled"><?php p($l->t('Allow other instances to mount public links shared from this server'));?></label><br/> <input type="checkbox" name="incoming_server2server_share_enabled" id="incomingServer2serverShareEnabled" value="1" <?php if ($_['incomingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> /> <label for="incomingServer2serverShareEnabled"><?php p($l->t('Allow users to mount public link shares'));?></label><br/> </div>
<div class="section" id="fileSharingSettings" > <h2><?php p($l->t('File Sharing'));?></h2> <input type="checkbox" name="outgoing_server2server_share_enabled" id="outgoingServer2serverShareEnabled" value="1" <?php if ($_['outgoingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> /> <label for="outgoingServer2serverShareEnabled"><?php p($l->t('Allow other instances to mount public links shared from this server'));?></label><br/> <input type="checkbox" name="incoming_server2server_share_enabled" id="incomingServer2serverShareEnabled" value="1" <?php if ($_['incomingServer2serverShareEnabled']) print_unescaped('checked="checked"'); ?> /> <label for="incomingServer2serverShareEnabled"><?php p($l->t('Allow users to mount public link shares'));?></label><br/> </div>
Remove unused import from tests
from collections import defaultdict import pytest from funcy.funcmakers import * def test_callable(): assert make_func(lambda x: x + 42)(0) == 42 def test_int(): assert make_func(0)('abc') == 'a' assert make_func(2)([1,2,3]) == 3 assert make_func(1)({1: 'a'}) == 'a' with pytest.raises(IndexError): make_func(1)('a') with pytest.raises(TypeError): make_func(1)(42) def test_slice(): assert make_func(slice(1, None))('abc') == 'bc' def test_str(): assert make_func('\d+')('ab42c') == '42' assert make_func('\d+')('abc') is None assert make_pred('\d+')('ab42c') is True assert make_pred('\d+')('abc') is False def test_dict(): assert make_func({1: 'a'})(1) == 'a' with pytest.raises(KeyError): make_func({1: 'a'})(2) d = defaultdict(int, a=42) assert make_func(d)('a') == 42 assert make_func(d)('b') == 0 def test_set(): s = set([1,2,3]) assert make_func(s)(1) is True assert make_func(s)(4) is False
import inspect from collections import defaultdict import pytest from funcy.funcmakers import * def test_callable(): assert make_func(lambda x: x + 42)(0) == 42 def test_int(): assert make_func(0)('abc') == 'a' assert make_func(2)([1,2,3]) == 3 assert make_func(1)({1: 'a'}) == 'a' with pytest.raises(IndexError): make_func(1)('a') with pytest.raises(TypeError): make_func(1)(42) def test_slice(): assert make_func(slice(1, None))('abc') == 'bc' def test_str(): assert make_func('\d+')('ab42c') == '42' assert make_func('\d+')('abc') is None assert make_pred('\d+')('ab42c') is True assert make_pred('\d+')('abc') is False def test_dict(): assert make_func({1: 'a'})(1) == 'a' with pytest.raises(KeyError): make_func({1: 'a'})(2) d = defaultdict(int, a=42) assert make_func(d)('a') == 42 assert make_func(d)('b') == 0 def test_set(): s = set([1,2,3]) assert make_func(s)(1) is True assert make_func(s)(4) is False
Use new user data API
var userData = require('./user-data.js') document.addEventListener('DOMContentLoaded', function (event) { var data = userData.getData() updateIndex(data) var clearAllButton = document.getElementById('clear-all-challenges') clearAllButton.addEventListener('click', function () { for (var chal in data) { if (data[chal].completed) { data[chal].completed = false var completedElement = '#' + chal + ' .completed-challenge-list' document.querySelector(completedElement).remove() } } userData.updateData(data, function (err) { if (err) return console.log(err) }) }) function updateIndex (data) { for (var chal in data) { if (data[chal].completed) { var currentText = document.getElementById(chal).innerHTML var completedText = "<span class='completed-challenge-list'>[ Completed ]</span>" document.getElementById(chal).innerHTML = completedText + ' ' + currentText } } } })
var ipc = require('ipc') var fs = require('fs') var userData document.addEventListener('DOMContentLoaded', function (event) { ipc.send('getUserDataPath') ipc.on('haveUserDataPath', function (path) { updateIndex('./data.json') }) var clearAllButton = document.getElementById('clear-all-challenges') clearAllButton.addEventListener('click', function (event) { for (var chal in userData) { if (userData[chal].completed) { userData[chal].completed = false var completedElement = '#' + chal + ' .completed-challenge-list' document.querySelector(completedElement).remove() } } fs.writeFile('./data.json', JSON.stringify(userData, null, ' '), function (err) { if (err) return console.log(err) }) }) function updateIndex (path) { fs.readFile(path, function readFile (err, contents) { if (err) return console.log(err) userData = JSON.parse(contents) for (var chal in userData) { if (userData[chal].completed) { var currentText = document.getElementById(chal).innerHTML var completedText = "<span class='completed-challenge-list'>[ Completed ]</span>" document.getElementById(chal).innerHTML = completedText + ' ' + currentText } } }) } })
Remove ANSI escape sequences from panel output
import re import sublime ANSI_ESCAPE_RE = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]') def normalize(string): return ANSI_ESCAPE_RE.sub('', string.replace('\r\n', '\n').replace('\r', '\n')) def panel(message, run_async=True): message = normalize(str(message)) view = sublime.active_window().active_view() if run_async: sublime.set_timeout_async( lambda: view.run_command("gs_display_panel", {"msg": message}) ) else: view.run_command("gs_display_panel", {"msg": message}) def panel_append(message, run_async=True): message = normalize(str(message)) view = sublime.active_window().active_view() if run_async: sublime.set_timeout_async( lambda: view.run_command("gs_append_panel", {"msg": message}) ) else: view.run_command("gs_append_panel", {"msg": message})
import sublime def universal_newlines(string): return string.replace('\r\n', '\n').replace('\r', '\n') def panel(message, run_async=True): message = universal_newlines(str(message)) view = sublime.active_window().active_view() if run_async: sublime.set_timeout_async( lambda: view.run_command("gs_display_panel", {"msg": message}) ) else: view.run_command("gs_display_panel", {"msg": message}) def panel_append(message, run_async=True): message = universal_newlines(str(message)) view = sublime.active_window().active_view() if run_async: sublime.set_timeout_async( lambda: view.run_command("gs_append_panel", {"msg": message}) ) else: view.run_command("gs_append_panel", {"msg": message})
Allow RemoteController to connect to correct port. Fixes #584
#!/usr/bin/python """ Create a network where different switches are connected to different controllers, by creating a custom Switch() subclass. """ from mininet.net import Mininet from mininet.node import OVSSwitch, Controller, RemoteController from mininet.topolib import TreeTopo from mininet.log import setLogLevel from mininet.cli import CLI setLogLevel( 'info' ) # Two local and one "external" controller (which is actually c0) # Ignore the warning message that the remote isn't (yet) running c0 = Controller( 'c0', port=6633 ) c1 = Controller( 'c1', port=6634 ) c2 = RemoteController( 'c2', ip='127.0.0.1', port=6633 ) cmap = { 's1': c0, 's2': c1, 's3': c2 } class MultiSwitch( OVSSwitch ): "Custom Switch() subclass that connects to different controllers" def start( self, controllers ): return OVSSwitch.start( self, [ cmap[ self.name ] ] ) topo = TreeTopo( depth=2, fanout=2 ) net = Mininet( topo=topo, switch=MultiSwitch, build=False ) for c in [ c0, c1 ]: net.addController(c) net.build() net.start() CLI( net ) net.stop()
#!/usr/bin/python """ Create a network where different switches are connected to different controllers, by creating a custom Switch() subclass. """ from mininet.net import Mininet from mininet.node import OVSSwitch, Controller, RemoteController from mininet.topolib import TreeTopo from mininet.log import setLogLevel from mininet.cli import CLI setLogLevel( 'info' ) # Two local and one "external" controller (which is actually c0) # Ignore the warning message that the remote isn't (yet) running c0 = Controller( 'c0', port=6633 ) c1 = Controller( 'c1', port=6634 ) c2 = RemoteController( 'c2', ip='127.0.0.1' ) cmap = { 's1': c0, 's2': c1, 's3': c2 } class MultiSwitch( OVSSwitch ): "Custom Switch() subclass that connects to different controllers" def start( self, controllers ): return OVSSwitch.start( self, [ cmap[ self.name ] ] ) topo = TreeTopo( depth=2, fanout=2 ) net = Mininet( topo=topo, switch=MultiSwitch, build=False ) for c in [ c0, c1 ]: net.addController(c) net.build() net.start() CLI( net ) net.stop()
Add suport for HTML5 Galleries & Captions See http://make.wordpress.org/core/2014/04/15/html5-galleries-captions- in-wordpress-3-9/ for mor details
<?php /** * Shoestrap initial setup and constants */ function shoestrap_setup() { // Make theme available for translation load_theme_textdomain( 'shoestrap', get_template_directory() . '/lang' ); // Register wp_nav_menu() menus ( http://codex.wordpress.org/Function_Reference/register_nav_menus ) register_nav_menus( array( 'primary_navigation' => __( 'Primary Navigation', 'shoestrap' ), 'secondary_navigation' => __( 'Secondary Navigation', 'shoestrap' ), ) ); // Add post thumbnails ( http://codex.wordpress.org/Post_Thumbnails ) add_theme_support( 'post-thumbnails' ); // Add post formats ( http://codex.wordpress.org/Post_Formats ) add_theme_support( 'post-formats', array( 'aside', 'gallery', 'link', 'image', 'quote', 'status', 'video', 'audio', 'chat' ) ); add_theme_support( 'automatic-feed-links' ); add_theme_support( 'html5', array( 'gallery', 'caption' ) ); // Tell the TinyMCE editor to use a custom stylesheet add_editor_style( '/assets/css/editor-style.css' ); } add_action( 'after_setup_theme', 'shoestrap_setup' );
<?php /** * Shoestrap initial setup and constants */ function shoestrap_setup() { // Make theme available for translation load_theme_textdomain( 'shoestrap', get_template_directory() . '/lang' ); // Register wp_nav_menu() menus ( http://codex.wordpress.org/Function_Reference/register_nav_menus ) register_nav_menus( array( 'primary_navigation' => __( 'Primary Navigation', 'shoestrap' ), 'secondary_navigation' => __( 'Secondary Navigation', 'shoestrap' ), ) ); // Add post thumbnails ( http://codex.wordpress.org/Post_Thumbnails ) add_theme_support( 'post-thumbnails' ); // Add post formats ( http://codex.wordpress.org/Post_Formats ) add_theme_support( 'post-formats', array( 'aside', 'gallery', 'link', 'image', 'quote', 'status', 'video', 'audio', 'chat' ) ); add_theme_support( 'automatic-feed-links' ); // Tell the TinyMCE editor to use a custom stylesheet add_editor_style( '/assets/css/editor-style.css' ); } add_action( 'after_setup_theme', 'shoestrap_setup' );
Add credentials module to core list
from .plcorebase import PlCoreBase from .planetstack import PlanetStack from .project import Project from .singletonmodel import SingletonModel from .service import Service from .service import ServiceAttribute from .tag import Tag from .role import Role from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments from .dashboard import DashboardView from .user import User, UserDashboardView from .serviceclass import ServiceClass from .slice import Slice, SliceDeployments from .site import SitePrivilege, SiteDeployments from .userdeployments import UserDeployments from .image import Image, ImageDeployments from .node import Node from .serviceresource import ServiceResource from .slice import SliceRole from .slice import SlicePrivilege from .credential import UserCredential,SiteCredential,SliceCredential from .site import SiteRole from .site import SitePrivilege from .planetstack import PlanetStackRole from .planetstack import PlanetStackPrivilege from .slicetag import SliceTag from .flavor import Flavor from .sliver import Sliver from .reservation import ReservedResource from .reservation import Reservation from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments from .billing import Account, Invoice, Charge, UsableObject, Payment
from .plcorebase import PlCoreBase from .planetstack import PlanetStack from .project import Project from .singletonmodel import SingletonModel from .service import Service from .service import ServiceAttribute from .tag import Tag from .role import Role from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments from .dashboard import DashboardView from .user import User, UserDashboardView from .serviceclass import ServiceClass from .slice import Slice, SliceDeployments from .site import SitePrivilege, SiteDeployments from .userdeployments import UserDeployments from .image import Image, ImageDeployments from .node import Node from .serviceresource import ServiceResource from .slice import SliceRole from .slice import SlicePrivilege from .site import SiteRole from .site import SitePrivilege from .planetstack import PlanetStackRole from .planetstack import PlanetStackPrivilege from .slicetag import SliceTag from .flavor import Flavor from .sliver import Sliver from .reservation import ReservedResource from .reservation import Reservation from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments from .billing import Account, Invoice, Charge, UsableObject, Payment
Refactor: Allow only the user-data fetching
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import viewsets, mixins, routers from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework.viewsets import GenericViewSet from core import serializers as api from core.models import Image, Pin from core.permissions import IsOwnerOrReadOnly from users.models import User class UserViewSet(mixins.RetrieveModelMixin, GenericViewSet): queryset = User.objects.all() serializer_class = api.UserSerializer class ImageViewSet(mixins.CreateModelMixin, GenericViewSet): queryset = Image.objects.all() serializer_class = api.ImageSerializer def create(self, request, *args, **kwargs): return super(ImageViewSet, self).create(request, *args, **kwargs) class PinViewSet(viewsets.ModelViewSet): queryset = Pin.objects.all() serializer_class = api.PinSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter) filter_fields = ("submitter__username", 'tags__name', ) ordering_fields = ('-id', ) ordering = ('-id', ) permission_classes = [IsOwnerOrReadOnly("submitter"), ] drf_router = routers.DefaultRouter() drf_router.register(r'users', UserViewSet) drf_router.register(r'pins', PinViewSet) drf_router.register(r'images', ImageViewSet)
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import viewsets, mixins, routers from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework.viewsets import GenericViewSet from core import serializers as api from core.models import Image, Pin from core.permissions import IsOwnerOrReadOnly from users.models import User class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = api.UserSerializer class ImageViewSet(mixins.CreateModelMixin, GenericViewSet): queryset = Image.objects.all() serializer_class = api.ImageSerializer def create(self, request, *args, **kwargs): return super(ImageViewSet, self).create(request, *args, **kwargs) class PinViewSet(viewsets.ModelViewSet): queryset = Pin.objects.all() serializer_class = api.PinSerializer filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter) filter_fields = ("submitter__username", 'tags__name', ) ordering_fields = ('-id', ) ordering = ('-id', ) permission_classes = [IsOwnerOrReadOnly("submitter"), ] drf_router = routers.DefaultRouter() drf_router.register(r'users', UserViewSet) drf_router.register(r'pins', PinViewSet) drf_router.register(r'images', ImageViewSet)
Add LogsManager to UserKit constructor
from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager from logs import LogsManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) self.logs = LogsManager(self._rq) @classmethod def version(cls): return cls.api_version
from requestor import Requestor from users import UserManager from invites import InviteManager from emails import EmailManager from session import Session from widget import WidgetManager class UserKit(object): _rq = None api_version = 1.0 api_base_url = None api_key = None users = None invites = None emails = None widget = None def __init__(self, api_key, api_base_url=None, _requestor=None): if api_key is None: raise TypeError('api_key cannot be blank.') if api_base_url is None: api_base_url = 'https://api.userkit.io/v1' else: api_base_url += '/v1' self.api_key = api_key self.api_base_url = api_base_url # make the encapsulated objects self._rq = _requestor or Requestor(self.api_key, self.api_base_url) self.users = UserManager(self._rq) self.invites = InviteManager(self._rq) self.emails = EmailManager(self._rq) self.widget = WidgetManager(self._rq) @classmethod def version(cls): return cls.api_version
Fix stale function reference when calling context menu handler Upon mounting, ContextMenuInterceptor retained the onWillShowContextMenu prop as a direct function reference; when updating the component with a new onWillShowContextMenu, the retained function was not updated. As a result, right-clicking on the wrapped element could potentially call a previously-passed value of onWillShowContextMenu. The solution is to instead retain a function that has dynamic access to the latest onWillShowContextMenu prop.
import React from 'react'; import PropTypes from 'prop-types'; export default class ContextMenuInterceptor extends React.Component { static propTypes = { onWillShowContextMenu: PropTypes.func.isRequired, children: PropTypes.element.isRequired, } static registration = new Map() static handle(event) { for (const [element, callback] of ContextMenuInterceptor.registration) { if (element.contains(event.target)) { callback(event); } } } static dispose() { document.removeEventListener('contextmenu', contextMenuHandler, {capture: true}); } componentDidMount() { // Helpfully, addEventListener dedupes listeners for us. document.addEventListener('contextmenu', contextMenuHandler, {capture: true}); ContextMenuInterceptor.registration.set(this.element, (...args) => this.props.onWillShowContextMenu(...args)); } render() { return <div ref={e => { this.element = e; }}>{this.props.children}</div>; } componentWillUnmount() { ContextMenuInterceptor.registration.delete(this.element); } } function contextMenuHandler(event) { ContextMenuInterceptor.handle(event); }
import React from 'react'; import PropTypes from 'prop-types'; export default class ContextMenuInterceptor extends React.Component { static propTypes = { onWillShowContextMenu: PropTypes.func.isRequired, children: PropTypes.element.isRequired, } static registration = new Map() static handle(event) { for (const [element, callback] of ContextMenuInterceptor.registration) { if (element.contains(event.target)) { callback(event); } } } static dispose() { document.removeEventListener('contextmenu', contextMenuHandler, {capture: true}); } componentDidMount() { // Helpfully, addEventListener dedupes listeners for us. document.addEventListener('contextmenu', contextMenuHandler, {capture: true}); ContextMenuInterceptor.registration.set(this.element, this.props.onWillShowContextMenu); } render() { return <div ref={e => { this.element = e; }}>{this.props.children}</div>; } componentWillUnmount() { ContextMenuInterceptor.registration.delete(this.element); } } function contextMenuHandler(event) { ContextMenuInterceptor.handle(event); }
Fix test which didn't compile git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@1158 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba
package jsr181.jaxb.globalweather; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.ParameterStyle; import javax.jws.soap.SOAPBinding.Style; import javax.jws.soap.SOAPBinding.Use; @WebService(serviceName = "GlobalWeather", targetNamespace = "http://www.webserviceX.NET", endpointInterface = "jsr181.jaxb.globalweather.GlobalWeatherSoap") @SOAPBinding(style = Style.DOCUMENT, use = Use.LITERAL, parameterStyle = ParameterStyle.WRAPPED) public class GlobalWeatherCustomImpl implements GlobalWeatherSoap { public String GetCitiesByCountry(String CountryName) { return null; } public String GetWeather(String CityName, String CountryName) { return "foo"; } }
package jsr181.jaxb.globalweather; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.ParameterStyle; import javax.jws.soap.SOAPBinding.Style; import javax.jws.soap.SOAPBinding.Use; import org.codehaus.xfire.fault.XFireFault; @WebService(serviceName = "GlobalWeather", targetNamespace = "http://www.webserviceX.NET", endpointInterface = "jsr181.jaxb.globalweather.GlobalWeatherSoap") @SOAPBinding(style = Style.DOCUMENT, use = Use.LITERAL, parameterStyle = ParameterStyle.WRAPPED) public class GlobalWeatherCustomImpl implements GlobalWeatherSoap { public String GetCitiesByCountry(String CountryName) throws XFireFault { return null; } public String GetWeather(String CityName, String CountryName) throws XFireFault { return "foo"; } }
Remove Mock and create "empty" object on the fly
import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): # create empty object, because Mock not included to python2 user = type('test', (object,), {})() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket
from unittest.mock import MagicMock import pytest from rocketchat_API.rocketchat import RocketChat @pytest.fixture(scope="session") def rocket(): _rocket = RocketChat() return _rocket @pytest.fixture(scope="session") def create_user(rocket): def _create_user(name="user1", password="password", email="email@domain.com"): user = MagicMock() user.name = name user.password = password user.email = email rocket.users_register( email=user.email, name=user.name, password=user.password, username=user.name ) return user return _create_user @pytest.fixture(scope="session") def user(create_user): _user = create_user() return _user @pytest.fixture(scope="session") def logged_rocket(user): _rocket = RocketChat(user.name, user.password) return _rocket
Make proxy proxy to backend
const merge = require('webpack-merge'); const config = require('./webpack.config'); const host = process.env.SDF_HOST || 'localhost'; const port = process.env.SDF_PORT || '3000'; const backendHost = process.env.SDF_BACKEND_HOST || 'backend'; const backendPort = process.env.SDF_BACKEND_PORT || '3000'; module.exports = merge.smart(config, { devtool: 'eval-source-map', module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader', }, { loader: 'css-loader', options: { sourceMap: true, modules: true, localIdentName: '[name]__[local]___[hash:base64:5]', }, }, ], }, ], }, devServer: { proxy: [ { context: ['/socket.io/', '/login', '/auth', '/logout'], target: `http://${backendHost}:${backendPort}`, }, ], historyApiFallback: { index: '/', }, }, });
const merge = require('webpack-merge'); const config = require('./webpack.config'); const host = process.env.SDF_HOST || 'localhost'; const port = process.env.SDF_PORT || '3000'; module.exports = merge.smart(config, { devtool: 'eval-source-map', module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader', }, { loader: 'css-loader', options: { sourceMap: true, modules: true, localIdentName: '[name]__[local]___[hash:base64:5]', }, }, ], }, ], }, devServer: { proxy: [ { context: ['/socket.io/', '/login', '/auth', '/logout'], target: `http://${host}:${port}`, }, ], historyApiFallback: { index: '/', }, }, });
Change the if condition to check if ref is defined, rather than explicitly null or false.
/** * Copy all properties from `props` onto `obj`. * @param {object} obj Object onto which properties should be copied. * @param {object} props Object from which to copy properties. * @returns {object} * @private */ export function extend(obj, props) { for (let i in props) obj[i] = props[i]; return obj; } /** Invoke or update a ref, depending on whether it is a function or object ref. * @param {object|function} [ref=null] * @param {any} [value] */ export function applyRef(ref, value) { if (ref) { if (typeof ref=='function') ref(value); else ref.current = value; } } /** * Call a function asynchronously, as soon as possible. Makes * use of HTML Promise to schedule the callback if available, * otherwise falling back to `setTimeout` (mainly for IE<11). * @type {(callback: function) => void} */ export const defer = typeof Promise=='function' ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;
/** * Copy all properties from `props` onto `obj`. * @param {object} obj Object onto which properties should be copied. * @param {object} props Object from which to copy properties. * @returns {object} * @private */ export function extend(obj, props) { for (let i in props) obj[i] = props[i]; return obj; } /** Invoke or update a ref, depending on whether it is a function or object ref. * @param {object|function} [ref=null] * @param {any} [value] */ export function applyRef(ref, value) { if (ref!=null&&ref!==false) { if (typeof ref=='function') ref(value); else ref.current = value; } } /** * Call a function asynchronously, as soon as possible. Makes * use of HTML Promise to schedule the callback if available, * otherwise falling back to `setTimeout` (mainly for IE<11). * @type {(callback: function) => void} */ export const defer = typeof Promise=='function' ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;
Use the array API types for the array API type annotations
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Literal', 'Optional', 'Tuple', 'Union', 'array', 'device', 'dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Literal, Optional, Tuple, Union, TypeVar from . import (ndarray, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) array = ndarray device = TypeVar('device') dtype = Literal[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64] SupportsDLPack = TypeVar('SupportsDLPack') SupportsBufferProtocol = TypeVar('SupportsBufferProtocol') PyCapsule = TypeVar('PyCapsule')
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Literal', 'Optional', 'Tuple', 'Union', 'array', 'device', 'dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Literal, Optional, Tuple, Union, TypeVar import numpy as np array = np.ndarray device = TypeVar('device') dtype = Literal[np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float32, np.float64] SupportsDLPack = TypeVar('SupportsDLPack') SupportsBufferProtocol = TypeVar('SupportsBufferProtocol') PyCapsule = TypeVar('PyCapsule')
Allow controllers to be registered via options.
function Plugin(app, chat, options) { if(!options) { throw new Error('No options specified for plugin.'); } if(!options.name) { throw new Error('No name specified for plugin'); } this.name = options.name; if(!options.version) { throw new Error('No version specified for plugin ' + this.name); } this.version = options.version; if(options.models) { this.models = options.models; } if(options.routes) { this.routes = options.routes; } if(options.controllers) { this.controllers = options.controllers; } this.app = app; this.chat = chat; } Plugin.prototype.init = function(callback) { callback(); }; Plugin.prototype.enable = function(callback) { callback(); }; Plugin.prototype.disable = function() { }; module.exports = Plugin;
function Plugin(app, chat, options) { if(!options) { throw new Error('No options specified for plugin.'); } if(!options.name) { throw new Error('No name specified for plugin'); } this.name = options.name; if(!options.version) { throw new Error('No version specified for plugin ' + this.name); } this.version = options.version; if(options.models) { this.models = options.models; } if(options.routes) { this.routes = options.routes; } this.app = app; this.chat = chat; } Plugin.prototype.init = function(callback) { callback(); }; Plugin.prototype.enable = function(callback) { callback(); }; Plugin.prototype.disable = function() { }; module.exports = Plugin;
Make is so that the pupa command can run
#!/usr/bin/env python from setuptools import setup, find_packages from pupa import __version__ long_description = '' setup(name='pupa', version=__version__, packages=find_packages(), author='James Turk', author_email='jturk@sunlightfoundation.com', license='BSD', url='http://github.com/opencivicdata/pupa/', description='scraping framework for muncipal data', long_description=long_description, platforms=['any'], entry_points='''[console_scripts] pupa = pupa.cli.__main__:main''', install_requires=[ 'pymongo>=2.5', 'scrapelib>=0.8', 'validictory>=0.9', ] )
#!/usr/bin/env python from setuptools import setup, find_packages from pupa import __version__ long_description = '' setup(name='pupa', version=__version__, packages=find_packages(), author='James Turk', author_email='jturk@sunlightfoundation.com', license='BSD', url='http://github.com/opencivicdata/pupa/', description='scraping framework for muncipal data', long_description=long_description, platforms=['any'], entry_points='''[console_scripts] pupa = pupa.bin.cli:main''', install_requires=[ 'pymongo>=2.5', 'scrapelib>=0.8', 'validictory>=0.9', ] )
Add standard, standard_level, theme to ga's Go back to the list state after successful creation See #81
'use strict'; module.exports = /*@ngInject*/ function GrammarActivitiesCreateCmsCtrl ( $scope, _, GrammarActivity, $state ) { $scope.grammarActivity = {}; $scope.grammarActivity.question_set = [{}]; function buildConcepts(set) { return _.chain(set) .map(function (s) { return [s.concept_level_0.$id, { quantity: s.number_of_questions, ruleNumber: s.concept_level_0.ruleNumber }]; }) .object() .value(); } $scope.processGrammarActivityForm = function () { var ga = $scope.grammarActivity; var newGrammarActivity = { title: ga.title, description: ga.description, concepts: buildConcepts(ga.question_set), standard: ga.standard, standard_level: ga.standard_level, theme: ga.theme }; GrammarActivity.addToFB(newGrammarActivity).then(function () { $state.go('cms-grammar-activities'); }); }; };
'use strict'; module.exports = /*@ngInject*/ function GrammarActivitiesCreateCmsCtrl ( $scope, _, GrammarActivity ) { $scope.grammarActivity = {}; $scope.grammarActivity.question_set = [{}]; function buildConcepts(set) { return _.chain(set) .map(function (s) { return [s.concept_level_0.$id, { quantity: s.number_of_questions, ruleNumber: s.concept_level_0.ruleNumber }]; }) .object() .value(); } $scope.processGrammarActivityForm = function () { console.log('Processing ', $scope.grammarActivity); var ga = $scope.grammarActivity; var newGrammarActivity = { title: ga.title, description: ga.description, concepts: buildConcepts(ga.question_set) }; console.log(newGrammarActivity); GrammarActivity.addToFB(newGrammarActivity).then(function () { console.log('Added', newGrammarActivity); }); }; };
Use strings.Builder instead of string concatenation. #lint
// Copyright 2015 Google Inc. All Rights Reserved. // This file is available under the Apache license. package errors import ( "fmt" "strings" "github.com/google/mtail/internal/vm/position" "github.com/pkg/errors" ) type compileError struct { pos position.Position msg string } func (e compileError) Error() string { return e.pos.String() + ": " + e.msg } // ErrorList contains a list of compile errors. type ErrorList []*compileError // Add appends an error at a position to the list of errors. func (p *ErrorList) Add(pos *position.Position, msg string) { *p = append(*p, &compileError{*pos, msg}) } // Append puts an ErrorList on the end of this ErrorList. func (p *ErrorList) Append(l ErrorList) { *p = append(*p, l...) } // ErrorList implements the error interface. func (p ErrorList) Error() string { switch len(p) { case 0: return "no errors" case 1: return p[0].Error() } var r strings.Builder for _, e := range p { r.WriteString(fmt.Sprintf("%s\n", e)) } return r.String() } func Errorf(format string, args ...interface{}) error { return errors.Errorf(format, args...) }
// Copyright 2015 Google Inc. All Rights Reserved. // This file is available under the Apache license. package errors import ( "fmt" "github.com/google/mtail/internal/vm/position" "github.com/pkg/errors" ) type compileError struct { pos position.Position msg string } func (e compileError) Error() string { return e.pos.String() + ": " + e.msg } // ErrorList contains a list of compile errors. type ErrorList []*compileError // Add appends an error at a position to the list of errors. func (p *ErrorList) Add(pos *position.Position, msg string) { *p = append(*p, &compileError{*pos, msg}) } // Append puts an ErrorList on the end of this ErrorList. func (p *ErrorList) Append(l ErrorList) { *p = append(*p, l...) } // ErrorList implements the error interface. func (p ErrorList) Error() string { switch len(p) { case 0: return "no errors" case 1: return p[0].Error() } var r string for _, e := range p { r = r + fmt.Sprintf("%s\n", e) } return r[:len(r)-1] } func Errorf(format string, args ...interface{}) error { return errors.Errorf(format, args...) }
Disable shuffle button while shuffling in progress.
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import CircularProgress from '@material-ui/core/CircularProgress'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import ShuffleIcon from '@material-ui/icons/Shuffle'; const { useCallback, useState } = React; const HARDCODED_LOADING_SIZE = 24; // FIXME derive this from some mui property? function ShuffleButton({ onShuffle }) { const [isLoading, setLoading] = useState(false); const { t } = useTranslator(); const onClick = useCallback(() => { setLoading(true); onShuffle().finally(() => { setLoading(false); }); }, [onShuffle]); return ( <Tooltip title={t('playlists.shuffle')} placement="top"> <IconButton className="PlaylistMeta-iconButton" onClick={onClick} disabled={isLoading} > {isLoading ? ( <CircularProgress size={HARDCODED_LOADING_SIZE} /> ) : ( <ShuffleIcon /> )} </IconButton> </Tooltip> ); } ShuffleButton.propTypes = { onShuffle: PropTypes.func.isRequired, }; export default ShuffleButton;
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import CircularProgress from '@material-ui/core/CircularProgress'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import ShuffleIcon from '@material-ui/icons/Shuffle'; const { useCallback, useState } = React; const HARDCODED_LOADING_SIZE = 24; // FIXME derive this from some mui property? function ShuffleButton({ onShuffle }) { const [isLoading, setLoading] = useState(false); const { t } = useTranslator(); const onClick = useCallback(() => { setLoading(true); onShuffle().finally(() => { setLoading(false); }); }, [onShuffle]); return ( <Tooltip title={t('playlists.shuffle')} placement="top"> <IconButton className="PlaylistMeta-iconButton" onClick={onClick} > {isLoading ? ( <CircularProgress size={HARDCODED_LOADING_SIZE} /> ) : ( <ShuffleIcon /> )} </IconButton> </Tooltip> ); } ShuffleButton.propTypes = { onShuffle: PropTypes.func.isRequired, }; export default ShuffleButton;
Add Example 9 Lesson 4
package ru.stqua.pft.addressbook.tests; import org.testng.Assert; import org.testng.annotations.Test; import ru.stqua.pft.addressbook.model.GroupData; import java.util.HashSet; import java.util.List; public class GroupCreationTests extends TestBase{ @Test public void testGroupCreation() { app.getNavigationHelper().gotoGroupPage(); List<GroupData> before = app.getGroupHelper().getGroupList(); GroupData group = new GroupData("test2", null, null); app.getGroupHelper().createGroup(group); List<GroupData> after = app.getGroupHelper().getGroupList(); Assert.assertEquals(after.size(), before.size() + 1); group.setId(after.stream().max((o1, o2) -> Integer.compare(o1.getId(), o2.getId())).get().getId()); before.add(group); Assert.assertEquals(new HashSet<Object>(before), new HashSet<Object>(after)); } }
package ru.stqua.pft.addressbook.tests; import org.testng.Assert; import org.testng.annotations.Test; import ru.stqua.pft.addressbook.model.GroupData; import java.util.HashSet; import java.util.List; public class GroupCreationTests extends TestBase{ @Test public void testGroupCreation() { app.getNavigationHelper().gotoGroupPage(); List<GroupData> before = app.getGroupHelper().getGroupList(); GroupData group = new GroupData("test1", null, null); app.getGroupHelper().createGroup(group); List<GroupData> after = app.getGroupHelper().getGroupList(); Assert.assertEquals(after.size(), before.size() + 1); int max = 0; for (GroupData g : after){ if (g.getId() > max){ max = g.getId(); } } group.setId(max); before.add(group); Assert.assertEquals(new HashSet<Object>(before), new HashSet<Object>(after)); } }
Add jquery and use flotr basic.
window.FlashCanvasOptions = { swfPath: 'lib/FlashCanvas/bin/' }; yepnope([ 'lib/jquery/jquery-1.7.1.min.js', // IE { test : (navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9), yep : [ 'lib/flotr2/lib/base64.js' ] }, { test : (navigator.appVersion.indexOf("MSIE") != -1), yep : [ 'lib/FlashCanvas/bin/flashcanvas.js' ] }, // Libs 'flotr2-basic.min.js', { test : ('ontouchstart' in window), nope : [ 'handles.js' ] }, 'lib/bonzo/bonzo.min.js', 'vis.min.js', { complete : example } ]);
window.FlashCanvasOptions = { swfPath: 'lib/FlashCanvas/bin/' }; yepnope([ { test : (navigator.appVersion.indexOf("MSIE") != -1 && parseFloat(navigator.appVersion.split("MSIE")[1]) < 9), yep : [ 'lib/flotr2/lib/base64.js' ] }, { test : (navigator.appVersion.indexOf("MSIE") != -1), yep : [ 'lib/FlashCanvas/bin/flashcanvas.js' ] }, // Libs 'flotr2.min.js', { test : ('ontouchstart' in window), nope : [ 'handles.js' ] }, 'lib/bonzo/bonzo.min.js', 'vis.min.js', { complete : example } ]);
Fix error of unitdef package import after changing it's name
package coreos import ( "github.com/bernardolins/clustereasy/scope" "github.com/bernardolins/clustereasy/service/etcd" "github.com/bernardolins/clustereasy/service/flannel" "github.com/bernardolins/clustereasy/service/fleet" "github.com/bernardolins/clustereasy/setup/types" "github.com/bernardolins/clustereasy/unit" "github.com/bernardolins/clustereasy/unit/default" ) func CreateScope(node types.Node, cluster types.Cluster) *scope.Scope { etcd2 := etcd2.New() etcd2.Configure(node, cluster) fleet := fleet.New() fleet.Configure(node, cluster) flannel := flannel.New() flannel.Configure(node, cluster) coreos := scope.New("coreos") coreos.AddService(*etcd2) coreos.AddService(*fleet) coreos.AddService(*flannel) configureUnits(coreos, cluster) return coreos } func configureUnits(scope *scope.Scope, cluster types.Cluster) { for _, u := range cluster.GetUnits() { unit := unit.New(u.UnitName(), u.UnitCommand()) scope.AddUnit(unit) } for _, u := range unitdef.DefaultUnits() { scope.AddUnit(u) } }
package coreos import ( "github.com/bernardolins/clustereasy/scope" "github.com/bernardolins/clustereasy/service/etcd" "github.com/bernardolins/clustereasy/service/flannel" "github.com/bernardolins/clustereasy/service/fleet" "github.com/bernardolins/clustereasy/setup/types" "github.com/bernardolins/clustereasy/unit" "github.com/bernardolins/clustereasy/unit/default/coreos" ) func CreateScope(node types.Node, cluster types.Cluster) *scope.Scope { etcd2 := etcd2.New() etcd2.Configure(node, cluster) fleet := fleet.New() fleet.Configure(node, cluster) flannel := flannel.New() flannel.Configure(node, cluster) coreos := scope.New("coreos") coreos.AddService(*etcd2) coreos.AddService(*fleet) coreos.AddService(*flannel) configureUnits(coreos, cluster) return coreos } func configureUnits(scope *scope.Scope, cluster types.Cluster) { for _, u := range cluster.GetUnits() { unit := unit.New(u.UnitName(), u.UnitCommand()) scope.AddUnit(*unit) } for _, u := range unitdef.DefaultUnits() { scope.AddUnit(u) } }
Change the spanish password reminder sent language line for a more readable one.
<?php return [ /* |-------------------------------------------------------------------------- | Password Reminder Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | has failed, such as for an invalid token or invalid new password. | */ 'password' => 'Las contraseñas deben coincidir y contener al menos 6 caracteres', 'reset' => '¡Tu contraseña ha sido restablecida!', 'sent' => '¡Te hemos enviado por correo el enlace para restablecer tu contraseña!', 'token' => 'El token de recuperación de contraseña es inválido.', 'user' => 'No podemos encontrar ningún usuario con ese correo electrónico.', ];
<?php return [ /* |-------------------------------------------------------------------------- | Password Reminder Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | has failed, such as for an invalid token or invalid new password. | */ 'password' => 'Las contraseñas deben coincidir y contener al menos 6 caracteres', 'reset' => '¡Tu contraseña ha sido restablecida!', 'sent' => '¡Recordatorio de contraseña enviado!', 'token' => 'El token de recuperación de contraseña es inválido.', 'user' => 'No podemos encontrar ningún usuario con ese correo electrónico.', ];
Fix a port related issue that persists.
require( 'dotenv' ).config(); var dropboxModule = require( './modules/dropbox.js' ); var googleDocsModule = require( './modules/googleDocs.js' ); var paypalModule = require( './modules/paypal.js' ); var express = require( 'express' ); var app = express(); app.set( 'port', ( process.env.PORT ) ); app.use( express.static( __dirname + '/public' ) ); app.get( '/googleapitoken', function( request, response ) { googleDocsModule.googleAPIAuthorize( request, response ); }); app.get( '/trigger', function( request, response ) { googleDocsModule.verifySecrets() .then(function( res ) { console.log( 'Application verified! Fetching PayPal rate.' ); paypalModule.fetchPaypalRate(); response.send( 'Triggered!' ); }) .catch(function( error ) { var errorMessage = 'Failed to authenticate! (' + error + ')'; console.log( errorMessage ); response.send( errorMessage ); }); }); app.listen( app.get( 'port' ), function() { console.log( 'Node app is running at localhost:' + app.get( 'port' ) ); });
require( 'dotenv' ).config(); var dropboxModule = require( './modules/dropbox.js' ); var googleDocsModule = require( './modules/googleDocs.js' ); var paypalModule = require( './modules/paypal.js' ); var express = require( 'express' ); var app = express(); app.set( 'port', ( process.env.Port || 30000 ) ); app.use( express.static( __dirname + '/public' ) ); app.get( '/googleapitoken', function( request, response ) { googleDocsModule.googleAPIAuthorize( request, response ); }); app.get( '/trigger', function( request, response ) { googleDocsModule.verifySecrets() .then(function( res ) { console.log( 'Application verified! Fetching PayPal rate.' ); paypalModule.fetchPaypalRate(); response.send( 'Triggered!' ); }) .catch(function( error ) { var errorMessage = 'Failed to authenticate! (' + error + ')'; console.log( errorMessage ); response.send( errorMessage ); }); }); app.listen( app.get( 'port' ), function() { console.log( 'Node app is running at localhost:' + app.get( 'port' ) ); });
Change a bit of text
"use strict"; const { Event } = require("sosamba"); const { version: sosambaVersion } = require("sosamba/package.json"); const { version } = require("../package.json"); class CommandErrorEvent extends Event { constructor(...args) { super(...args, { name: "commandError" }); } async run(e, ctx) { if (e.constructor.name !== "ExtensionError") this.log.error(e); try { await ctx.send({ embed: { title: ":x: Error running the command", description: `I am unable to run the command because of a coding error:\n\`\`\`js\n${e.stack}\n\`\`\``, color: 0xFF0000, footer: { text: `Please report this issue on our support server or on GitHub. | tt.bot v${version} running on Sosamba v${sosambaVersion}` } } }); } catch {} } } module.exports = CommandErrorEvent;
"use strict"; const { Event } = require("sosamba"); const { version: sosambaVersion } = require("sosamba/package.json"); const { version } = require("../package.json"); class CommandErrorEvent extends Event { constructor(...args) { super(...args, { name: "commandError" }); } async run(e, ctx) { if (e.constructor.name !== "ExtensionError") this.log.error(e); try { await ctx.send({ embed: { title: ":x: Error running the command", description: `I am unable to run the command because of a coding error:\n\`\`\`js\n${e.stack}\n\`\`\``, color: 0xFF0000, footer: { text: `Please tell the command developers about this. | tt.bot v${version} running on Sosamba v${sosambaVersion}` } } }); } catch {} } } module.exports = CommandErrorEvent;
Fix name - it is testing Character, not Team
from django.test import TestCase from .models import Character, Team class CharacterGetAbsoluteUrl(TestCase): def test_slug_appears_in_url(self): slug_value = "slug-value" team = Team() team.slug = "dont-care" sut = Character() sut.slug = slug_value sut.team = team result = sut.get_absolute_url() self.assertTrue(slug_value in result) def test_team_slug_appears_in_url(self): team_slug = "team-slug" team = Team() team.slug = team_slug sut = Character() sut.slug = "dont-care" sut.team = team result = sut.get_absolute_url() self.assertTrue(team_slug in result)
from django.test import TestCase from .models import Character, Team class TeamGetAbsoluteUrl(TestCase): def test_slug_appears_in_url(self): slug_value = "slug-value" team = Team() team.slug = "dont-care" sut = Character() sut.slug = slug_value sut.team = team result = sut.get_absolute_url() self.assertTrue(slug_value in result) def test_team_slug_appears_in_url(self): team_slug = "team-slug" team = Team() team.slug = team_slug sut = Character() sut.slug = "dont-care" sut.team = team result = sut.get_absolute_url() self.assertTrue(team_slug in result)
Add one more creation way and refactor test descriptions.
// 1: async - basics // To do: make all tests pass, leave the assert lines unchanged! describe('`async` defines an asynchronous function', function() { describe('can be created by putting `async` before', () => { it('a function expression', function() { const f = async function() {}; assert.equal(f instanceof AsyncFunction, true); }); it('a function declaration', function() { async function f() {} assert.equal(f instanceof AsyncFunction, true); }); it('an arrow function', function() { const f = async () => {}; assert.equal(f instanceof AsyncFunction, true); }); it('an object method', function() { const obj = { f: async () => void 0, }; assert.equal(obj.f instanceof AsyncFunction, true); }); }); }); // Note that AsyncFunction is not a global object. // It could be obtained by evaluating the following code. // see also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
// 1: async - basics // To do: make all tests pass, leave the assert lines unchanged! describe('`async` defines an asynchronous function', function() { describe('can be created', () => { it('by prefixing a function expression with `async`', function() { const f = async function() {}; assert.equal(f instanceof AsyncFunction, true); }); it('by prefixing a function declaration with `async`', function() { async function f() {} assert.equal(f instanceof AsyncFunction, true); }); it('by prefixing an arrow function with `async`', function() { const f = async () => {}; assert.equal(f instanceof AsyncFunction, true); }); }); }); // Note that AsyncFunction is not a global object. // It could be obtained by evaluating the following code. // see also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;