text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Put import back on top
from dateutil.relativedelta import relativedelta from django.apps import apps from django.utils import timezone class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_NOTIFICATION, ) return self.filter(last_login__lte=threshold, notified=False) def users_to_delete(self): """Finds all users who have been inactive and were notified.""" user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_DELETION, ) return self.filter(last_login__lte=threshold, notified=True)
from dateutil.relativedelta import relativedelta from django.utils import timezone class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" from django.apps import apps user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_NOTIFICATION, ) return self.filter(last_login__lte=threshold, notified=False) def users_to_delete(self): """Finds all users who have been inactive and were notified.""" from django.apps import apps user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_DELETION, ) return self.filter(last_login__lte=threshold, notified=True)
Fix and ungodly number of linter errors
angular.module('bolt.createProfile', []) .controller('CreateProfileController', function ($location, $scope, Profile, $window) { $scope.createProfile = function (first, last, email, phone, distance) { $location.path('/'); var newData = { firstName: first, lastName: last, email: email, phone: phone.toString(), preferredDistance: distance }; $window.localStorage.setItem('firstName', first); $window.localStorage.setItem('lastName', last); $window.localStorage.setItem('phone', phone); $window.localStorage.setItem('email', email); $window.localStorage.setItem('preferredDistance', distance); Profile.getUser() .then(function (currentUser) { Profile.updateUser(newData, currentUser) .catch(function (err) { console.error(err); }); }); }; });
angular.module('bolt.createProfile', []) .controller('CreateProfileController', function($location, $scope, Profile, $window) { $scope.createProfile = function(first, last, email, phone, distance) { $location.path('/'); var newData = { firstName: first, lastName: last, email: email, phone: phone.toString(), preferredDistance: distance }; $window.localStorage.setItem('firstName', first); $window.localStorage.setItem('lastName', last); $window.localStorage.setItem('phone', phone); $window.localStorage.setItem('email', email); $window.localStorage.setItem('preferredDistance', distance); Profile.getUser() .then(function(currentUser) { Profile.updateUser(newData, currentUser) .catch(function (err) { console.error(err); }); }); }; })
Remove _actors variable and stick with _actorRefs
/* * This class represents actors in the game */ 'use strict'; import Ball from 'Ball.js'; const actorsDefinitions = { ball: { xVelocity: 0, yVelocity: 0, radius: 10 } }; export default class { constructor(canvasWidth, canvasHeight) { this._actorRefs = []; // Initializing ball let bX = canvasWidth / 2; let bY = canvasHeight - 25; let ball = actorsDefinitions.ball this.addActor(new Ball(bX, bY, ball.xVelocity, ball.yVelocity, ball.radius)); } getActors() { return this._actorRefs.map((e)=> { return e.getAnatomy(); }); } moveActors() { this._actorRefs.forEach((e)=> e.move()); } addActor(actor) { this._actorRefs.push(actor); } }
/* * This class represents actors in the game */ 'use strict'; import Ball from 'Ball.js'; const actorsDefinitions = { ball: { xVelocity: 0, yVelocity: 0, radius: 10 } }; export default class { constructor(canvasWidth, canvasHeight) { this._actorRefs = []; this._actors = []; // Initializing ball let bX = canvasWidth / 2; let bY = canvasHeight - 25; let ball = actorsDefinitions.ball this.addActor(new Ball(bX, bY, ball.xVelocity, ball.yVelocity, ball.radius)); } getVisibleActors() { return this._actors.filter((a)=> a.visible) || []; } addActor(actor) { this._actorRefs.push(actor); this._actors.push(actor.getAnatomy()); } }
Throw an exception if the configured driver does not exist.
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class InverterServiceProvider extends ServiceProvider { /** * Indicates that the loading of this provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap any inverter services. * * @return void */ public function boot() { // } /** * Register any inverter services. * * @return void */ public function register() { switch (env('INV_DRIVER')) { case 'stecagrid': $driver = 'StecaGrid'; break; default: $this->app->abort(501, 'Configured driver not supported.'); break; } $this->app->singleton('App\Contracts\Inverter', 'App\Services\Inverters\\'.$driver); } /** * Get the services provided by this provider. * * @return array */ public function provides() { return ['App\Contracts\Inverter']; } }
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class InverterServiceProvider extends ServiceProvider { /** * Indicates that the loading of this provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap any inverter services. * * @return void */ public function boot() { // } /** * Register any inverter services. * * @return void */ public function register() { switch (env('INV_DRIVER')) { case 'stecagrid': $driver = 'StecaGrid'; break; } $this->app->singleton('App\Contracts\Inverter', 'App\Services\Inverters\\'.$driver); } /** * Get the services provided by this provider. * * @return array */ public function provides() { return ['App\Contracts\Inverter']; } }
Adjust the output parsing of git name-rev to handle the output of the latest git version. Signed-off-by: Simon Hausmann <0a3c2b6956b68ea9079d8d9063677b62a646d61b@kde.org>
#!/usr/bin/python # # p4-debug.py # # Author: Simon Hausmann <hausmann@kde.org> # License: MIT <http://www.opensource.org/licenses/mit-license.php> # # removes unused p4 import tags # import os, string, sys import popen2, getopt branch = "refs/heads/master" try: opts, args = getopt.getopt(sys.argv[1:], "", [ "branch=" ]) except getopt.GetoptError: print "fixme, syntax error" sys.exit(1) for o, a in opts: if o == "--branch": branch = "refs/heads/" + a sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch) output = sout.read() tagIdx = output.index(" tags/p4/") try: caretIdx = output.index("^") except: caretIdx = len(output) - 1 rev = int(output[tagIdx + 9 : caretIdx]) allTags = os.popen("git tag -l p4/").readlines() for i in range(len(allTags)): allTags[i] = int(allTags[i][3:-1]) allTags.sort() allTags.remove(rev) for rev in allTags: print os.popen("git tag -d p4/%s" % rev).read()
#!/usr/bin/python # # p4-debug.py # # Author: Simon Hausmann <hausmann@kde.org> # License: MIT <http://www.opensource.org/licenses/mit-license.php> # # removes unused p4 import tags # import os, string, sys import popen2, getopt branch = "refs/heads/master" try: opts, args = getopt.getopt(sys.argv[1:], "", [ "branch=" ]) except getopt.GetoptError: print "fixme, syntax error" sys.exit(1) for o, a in opts: if o == "--branch": branch = "refs/heads/" + a sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch) output = sout.read() tagIdx = output.index(" tags/p4/") caretIdx = output.index("^") rev = int(output[tagIdx + 9 : caretIdx]) allTags = os.popen("git tag -l p4/").readlines() for i in range(len(allTags)): allTags[i] = int(allTags[i][3:-1]) allTags.sort() allTags.remove(rev) for rev in allTags: print os.popen("git tag -d p4/%s" % rev).read()
Fix failing user profile test
from django.core.urlresolvers import reverse from django.test import TestCase from fortuitus.fcore.factories import UserF from fortuitus.fcore.models import FortuitusProfile class HomeViewTestCase(TestCase): def test_renders_template(self): """ Tests is home page is rendered properly. """ response = self.client.get(reverse('home')) self.assertEqual(200, response.status_code) self.assertTemplateUsed('fortuitus/fcore/home.html') class ProfileTestCase(TestCase): def test_profile_created(self): """ Tests that profile is automatically created along with User. """ u = UserF.create() p = FortuitusProfile.objects.all()[0] self.assertEqual(u.fortuitusprofile, p) def test_profiles_not_conflicted(self): """ Tests that second profile is created and not conflicted with the first user nor his profile. """ u1 = UserF.create(username='u1') p1 = FortuitusProfile.objects.get(user_id=u1.pk) u2 = UserF.create(username='u2') p2 = FortuitusProfile.objects.get(user_id=u2.pk) self.assertNotEqual(p1, p2)
from django.core.urlresolvers import reverse from django.test import TestCase from fortuitus.fcore.factories import UserF from fortuitus.fcore.models import FortuitusProfile class HomeViewTestCase(TestCase): def test_renders_template(self): """ Tests is home page is rendered properly. """ response = self.client.get(reverse('home')) self.assertEqual(200, response.status_code) self.assertTemplateUsed('fortuitus/fcore/home.html') class ProfileTestCase(TestCase): def test_profile_created(self): """ Tests that profile is automatically created along with User. """ u = UserF.create() p = FortuitusProfile.objects.all()[0] self.assertEqual(u.fortuitusprofile, p) def test_profiles_not_conflicted(self): """ Tests that second profile is created and not conflicted with the first user nor his profile. """ u1 = UserF.create() p1 = FortuitusProfile.objects.get(user_id=u1.pk) u2 = UserF.create() p2 = FortuitusProfile.objects.get(user_id=u2.pk) self.assertNotEqual(p1, p2)
Use for-loop rather than the filter method
var NotificationsController = SingleModelController.createComponent("NotificationsController"); NotificationsController.defineAlias("model", "notifications"); NotificationsController.defineMethod("updateView", function () { if (!this.view) return; var bottom = 0; for (let notification of this.notifications.notifications) { var element = this.view.querySelector("[data-ica-notification-id='{0}']".format(notification.componentId)); // Check existing element if (element) { element.style.bottom = bottom + "px"; } else { // Create new view // Match controller var Controller; switch (notification.constructor) { case BasicNotification: Controller = BasicNotificationController; break; case ProgressNotification: Controller = ProgressNotificationController; break; case XHRProgressNotification: Controller = XHRProgressNotificationController; break; default: console.warn("Unhandled item:", notification.constructor); continue; } // Create view var fragment = Controller.createViewFragment(); element = fragment.querySelector(".notification"); element.style.bottom = bottom + "px"; this.view.appendChild(fragment); new Controller(notification, element).componentOf = this; } bottom += element.offsetHeight + 8; // 16 px margin top & bottom } });
var NotificationsController = SingleModelController.createComponent("NotificationsController"); NotificationsController.defineAlias("model", "notifications"); NotificationsController.defineMethod("updateView", function () { if (!this.view) return; var bottom = 0; this.notifications.notifications = this.notifications.notifications.filter(function (notification) { var element = this.view.querySelector("[data-ica-notification-id='{0}']".format(notification.componentId)); // Check existing element if (element) { element.style.bottom = bottom + "px"; } else { // Create new view // Match controller var Controller; switch (notification.constructor) { case BasicNotification: Controller = BasicNotificationController; break; case ProgressNotification: Controller = ProgressNotificationController; break; case XHRProgressNotification: Controller = XHRProgressNotificationController; break; default: console.warn("Unhandled item:", notification.constructor); return false; } // Create view var fragment = Controller.createViewFragment(); element = fragment.querySelector(".notification"); element.style.bottom = bottom + "px"; this.view.appendChild(fragment); new Controller(notification, element).componentOf = this; } bottom += element.offsetHeight + 8; // 16 px margin top & bottom return true; }.bind(this)); });
Move import to top of the file
from django.db import models from pgcrypto_fields.sql import aggregates class Decrypt(models.Aggregate): """`Decrypt` creates an alias for `DecryptFunctionSQL`. `alias` is `{self.lookup}__decrypt` where 'decrypt' is `self.name.lower()`. `self.lookup` is defined in `models.Aggregate.__init__`. """ def add_to_query(self, query, alias, col, source, is_summary): """Add the aggregate to the query.""" klass = getattr(aggregates, self.name) aggregate = klass( col, source=source, is_summary=is_summary, **self.extra ) query.aggregates[alias] = aggregate class PGPPub(Decrypt): """PGP public key based aggregation.""" name = 'PGPPub' class PGPSym(Decrypt): """PGP symmetric key based aggregation.""" name = 'PGPSym'
from django.db import models class Decrypt(models.Aggregate): """`Decrypt` creates an alias for `DecryptFunctionSQL`. `alias` is `{self.lookup}__decrypt` where 'decrypt' is `self.name.lower()`. `self.lookup` is defined in `models.Aggregate.__init__`. """ def add_to_query(self, query, alias, col, source, is_summary): """Add the aggregate to the query.""" from pgcrypto_fields.sql import aggregates klass = getattr(aggregates, self.name) aggregate = klass( col, source=source, is_summary=is_summary, **self.extra ) query.aggregates[alias] = aggregate class PGPPub(Decrypt): """PGP public key based aggregation.""" name = 'PGPPub' class PGPSym(Decrypt): """PGP symmetric key based aggregation.""" name = 'PGPSym'
Handle exception when getting Sensor Status from Empty Database
package com.cesca.sensors.controller; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.cesca.sensors.entity.DHTSensor; import com.cesca.sensors.service.DHTSensorService; @RestController @RequestMapping("/REST/DHTSensor") public class DHTSensorController { @Autowired public DHTSensorService dhtSensorService; private Logger log = Logger.getLogger(this.getClass()); @RequestMapping(method = RequestMethod.GET) public DHTSensor getLatestData(){ try { DHTSensor sensor = this.dhtSensorService.getLatestData(); return sensor; } catch (Exception e) { log.error("Failed to get latest data from Database"); } return null; } @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) public DHTSensor addData(@RequestBody DHTSensor dht){ return this.dhtSensorService.addDHTSensorData(dht); } }
package com.cesca.sensors.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.cesca.sensors.entity.DHTSensor; import com.cesca.sensors.service.DHTSensorService; @RestController @RequestMapping("/REST/DHTSensor") public class DHTSensorController { @Autowired public DHTSensorService dhtSensorService; @RequestMapping(method = RequestMethod.GET) public DHTSensor getLatestData(){ return this.dhtSensorService.getLatestData(); } @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) public DHTSensor addData(@RequestBody DHTSensor dht){ return this.dhtSensorService.addDHTSensorData(dht); } }
Maintain references to stores on Flux object
var Dispatcher = require("./dispatcher"); var Flux = function(stores, actions) { var dispatcher = new Dispatcher(stores), dispatchBinder = { dispatch: function(type, payload) { dispatcher.dispatch({type: type, payload: payload}); } }; this.dispatcher = dispatcher; this.actions = {}; this.stores = stores; for (var key in actions) { if (actions.hasOwnProperty(key)) { this.actions[key] = actions[key].bind(dispatchBinder); } } for (key in stores) { if (stores.hasOwnProperty(key)) { stores[key].flux = this; } } }; Flux.prototype.store = function(name) { return this.stores[name]; }; module.exports = Flux;
var Dispatcher = require("./dispatcher"); var Flux = function(stores, actions) { var dispatcher = new Dispatcher(stores), dispatchBinder = { dispatch: function(type, payload) { dispatcher.dispatch({type: type, payload: payload}); } }; this.dispatcher = dispatcher; this.actions = {}; for (var key in actions) { if (actions.hasOwnProperty(key)) { this.actions[key] = actions[key].bind(dispatchBinder); } } for (key in stores) { if (stores.hasOwnProperty(key)) { stores[key].flux = this; } } }; Flux.prototype.store = function(name) { return this.dispatcher.stores[name]; }; module.exports = Flux;
Remove extraneous GROUP BY name, which broken [release_versions] order
<?php /** * api: cron * title: Update `tags` table * description: Splits out tags from according column in project `release`. * version: 0.2 * * Manually update tags table. * - Splits up comma separated release.tags field * - Maximum of 7 tags each * - Populates separate tags table with name=>tag list. * */ chdir(dirname(__DIR__)); include("config.php"); /** * Scan each project, * split up `tags` as CSV and just fille up according tags table. * */ foreach (db("SELECT * FROM release_versions")->into() as $entry) { print_r($entry); $name = $entry->name; $tags = array_slice(array_filter(p_csv($entry->tags)), 0, 7); db("DELETE FROM tags WHERE name=?", $name); foreach ($tags as $t) { db("INSERT INTO tags (name, tag) VALUES (?, ?)", $name, $t); } }
<?php /** * api: cron * title: Update `tags` table * description: Splits out tags from according column in project `release`. * version: 0.2 * * Manually update tags table. * - Splits up comma separated release.tags field * - Maximum of 7 tags each * - Populates separate tags table with name=>tag list. * */ chdir(dirname(__DIR__)); include("config.php"); /** * Scan each project, * split up `tags` as CSV and just fille up according tags table. * */ foreach (db("SELECT * FROM release_versions GROUP BY name")->into() as $entry) { print_r($entry); $name = $entry->name; $tags = array_slice(array_filter(p_csv($entry->tags)), 0, 7); db("DELETE FROM tags WHERE name=?", $name); foreach ($tags as $t) { db("INSERT INTO tags (name, tag) VALUES (?, ?)", $name, $t); } }
Make sure there is no leak in tail calls * The JVM usually just null out firstException since it's not used later, but better be clear.
package org.mozartoz.truffle.nodes.call; import org.mozartoz.truffle.nodes.OzNode; import org.mozartoz.truffle.runtime.TailCallException; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.profiles.BranchProfile; public class TailCallCatcherNode extends OzNode { @Child CallNode callNode; private final BranchProfile tailCallProfile = BranchProfile.create(); public TailCallCatcherNode(CallNode callNode) { this.callNode = callNode; } public Object execute(VirtualFrame frame) { try { return callNode.execute(frame); } catch (TailCallException tailCall) { tailCallProfile.enter(); while (true) { try { return callNode.executeCall(frame, tailCall.receiver, tailCall.arguments); } catch (TailCallException exception) { tailCall = exception; } } } } }
package org.mozartoz.truffle.nodes.call; import org.mozartoz.truffle.nodes.OzNode; import org.mozartoz.truffle.runtime.TailCallException; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.profiles.BranchProfile; public class TailCallCatcherNode extends OzNode { @Child CallNode callNode; private final BranchProfile tailCallProfile = BranchProfile.create(); public TailCallCatcherNode(CallNode callNode) { this.callNode = callNode; } public Object execute(VirtualFrame frame) { try { return callNode.execute(frame); } catch (TailCallException firstException) { tailCallProfile.enter(); TailCallException tailCall = firstException; while (true) { try { return callNode.executeCall(frame, tailCall.receiver, tailCall.arguments); } catch (TailCallException exception) { tailCall = exception; } } } } }
[usecase] Update precondition for vehicle information and data
var step = '<font style="font-size:85%">' + '<p>Test Purpose: </p>' + '<p>Verifies the device supports tizen vehicle information and vehicle data API.</p>' + '<p>Pre-condition: </p>' + '<p>Enable bluemonkey plugin following https://wiki.tizen.org/wiki/AMB_Bluemonkey_Plugin</p>' + '<p>Test Step: </p>' + '<p>' + '<ol>' + '<li>' + 'Click the "Get vehicle" button.' + '</li>' + '</ol>' + '</p>' + '<p>Expected Result: </p>' + '<p>Test passes if the detected direction reflects the actual vehicle information</p>' + '</font>'
var step = '<font style="font-size:85%">' + '<p>Test Purpose: </p>' + '<p>Verifies the device supports tizen vehicle information and vehicle data API.</p>' + '<p>Test Step: </p>' + '<p>' + '<ol>' + '<li>' + 'Click the "Get vehicle" button.' + '</li>' + '</ol>' + '</p>' + '<p>Expected Result: </p>' + '<p>Test passes if the detected direction reflects the actual vehicle information</p>' + '</font>'
Revert "remove redundatn end points" This reverts commit 4703d26683e4b58510ff25c112dbf2a7fef8b689.
var local = 'http://localhost:55881' var dev = 'https://dev-api-streetsupport.azurewebsites.net' var staging = 'https://staging-api-streetsupport.azurewebsites.net' var live = 'https://live-api-streetsupport.azurewebsites.net' var env = require('./env') var envs = [local, dev, staging, live] var domainRoot = envs[env] var p = function (url) { return domainRoot + url } module.exports = { serviceProviders: p('/v2/service-providers/'), allServiceProviders: p('/v1/all-service-providers/'), serviceCategories: p('/v2/service-categories/'), categoryServiceProviders: p('/v2/categorised-service-providers/show/'), categoryServiceProvidersByDay: p('/v2/timetabled-service-providers/show/'), organisation: p('/v2/service-providers/show/'), needs: p('/v1/service-provider-needs/'), createVolunteerEnquiry: p('/v1/volunteer-enquiries/'), createOfferOfItems: p('/v1/offers-of-items/'), joinStreetSupportApplications: p('/v1/join-street-support-applications/'), offerSponsorship: p('/v1/sponsorship-offers/'), servicesByCategory: p('/v2/service-categories/'), newlyRegisteredProviders: p('/v1/newly-registered-providers'), cities: p('/v1/cities/') }
var local = 'http://localhost:55881' var dev = 'https://dev-api-streetsupport.azurewebsites.net' var staging = 'https://staging-api-streetsupport.azurewebsites.net' var live = 'https://live-api-streetsupport.azurewebsites.net' var env = require('./env') var envs = [local, dev, staging, live] var domainRoot = envs[env] var p = function (url) { return domainRoot + url } module.exports = { serviceProviders: p('/v2/service-providers/'), allServiceProviders: p('/v1/all-service-providers/'), serviceCategories: p('/v2/service-categories/'), organisation: p('/v2/service-providers/show/'), needs: p('/v1/service-provider-needs/'), createVolunteerEnquiry: p('/v1/volunteer-enquiries/'), createOfferOfItems: p('/v1/offers-of-items/'), joinStreetSupportApplications: p('/v1/join-street-support-applications/'), offerSponsorship: p('/v1/sponsorship-offers/'), servicesByCategory: p('/v2/service-categories/'), newlyRegisteredProviders: p('/v1/newly-registered-providers'), cities: p('/v1/cities/') }
Add ALLOWED_HOSTS to production settings
from local_settings import * ALLOWED_HOSTS = ['uchicagohvz.org'] # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'uchicagohvz', # Or path to database file if using sqlite3. 'USER': 'user', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # REST framework settings REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } # Mandrill email settings EMAIL_HOST = 'smtp.mandrillapp.com' from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD EMAIL_PORT = '587' EMAIL_USE_TLS = True
from local_settings import * # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'uchicagohvz', # Or path to database file if using sqlite3. 'USER': 'user', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # REST framework settings REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } # Mandrill email settings EMAIL_HOST = 'smtp.mandrillapp.com' from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD EMAIL_PORT = '587' EMAIL_USE_TLS = True
Add empty implementations of now-default methods for backwards compatibility Took 8 minutes
package com.darkyen; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.*; import org.jetbrains.annotations.NotNull; /** * Only used to track default settings. */ @State(name="DarkyenusTimeTrackerDefaults", storages = {@Storage("darkyenus-time-tracker-defaults.xml")}) public class TimeTrackerDefaultSettingsComponent implements BaseComponent, PersistentStateComponent<TimeTrackerPersistentState> { private final TimeTrackerPersistentState defaultState = new TimeTrackerPersistentState(); @NotNull @Override public TimeTrackerPersistentState getState() { return defaultState; } public void setDefaultsFrom(@NotNull TimeTrackerPersistentState templateState) { this.defaultState.setDefaultsFrom(templateState); } @Override public void loadState(@NotNull TimeTrackerPersistentState state) { this.defaultState.setDefaultsFrom(state); } @NotNull @Override public String getComponentName() { return "DarkyenusTimeTrackerDefaults"; } @NotNull public static TimeTrackerDefaultSettingsComponent instance() { final Application application = ApplicationManager.getApplication(); final TimeTrackerDefaultSettingsComponent component = application .getComponent(TimeTrackerDefaultSettingsComponent.class); if (component == null) { return new TimeTrackerDefaultSettingsComponent(); } return component; } // Empty defaults for backwards compatibility @Override public void initComponent() {} @Override public void disposeComponent() {} @Override public void noStateLoaded() {} }
package com.darkyen; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.*; import org.jetbrains.annotations.NotNull; /** * Only used to track default settings. */ @State(name="DarkyenusTimeTrackerDefaults", storages = {@Storage("darkyenus-time-tracker-defaults.xml")}) public class TimeTrackerDefaultSettingsComponent implements BaseComponent, PersistentStateComponent<TimeTrackerPersistentState> { private final TimeTrackerPersistentState defaultState = new TimeTrackerPersistentState(); @NotNull @Override public TimeTrackerPersistentState getState() { return defaultState; } public void setDefaultsFrom(@NotNull TimeTrackerPersistentState templateState) { this.defaultState.setDefaultsFrom(templateState); } @Override public void loadState(@NotNull TimeTrackerPersistentState state) { this.defaultState.setDefaultsFrom(state); } @NotNull @Override public String getComponentName() { return "DarkyenusTimeTrackerDefaults"; } @NotNull public static TimeTrackerDefaultSettingsComponent instance() { final Application application = ApplicationManager.getApplication(); final TimeTrackerDefaultSettingsComponent component = application .getComponent(TimeTrackerDefaultSettingsComponent.class); if (component == null) { return new TimeTrackerDefaultSettingsComponent(); } return component; } }
Fix a typo caused error
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('Users', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, username: { type: Sequelize.STRING }, password: { type: Sequelize.STRING }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('Users'); } };
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('Users', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, usernamee: { type: Sequelize.STRING }, password: { type: Sequelize.STRING }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('Users'); } };
Add script's path to the python path
# -*- coding: utf-8 -*- """ leisure ~~~~~~~~ Leisure a local job runner for Disco based project. It provides a useful method for running your disco project without needing a full disco cluster. This makes it a snap to develop and debug jobs on your development machine. To use, simply execute your disco script using the leisure command like so: $ leisure <path to script>/word_count.py Leisure monkey patches all network calls to the Disco/DDFS master so that it can intercept and execute them locally. The worker itself is executed as a subprocess and communicated to via the Disco Worker protocol http://discoproject.org/doc/disco/howto/worker.html :copyright: (c) 2011 by triv.io, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ from __future__ import absolute_import import sys import os from .disco import run_script from . import shuffle import tempfile def main(): script = sys.argv[1] script_dir = os.path.abspath(os.path.dirname(script)) if script_dir not in [os.path.abspath(p) for p in sys.path]: sys.path.append(script_dir) if len(sys.argv) == 3: data_root = sys.argv[2] else: data_root = tempfile.mkdtemp() run_script(script, data_root) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- """ leisure ~~~~~~~~ Leisure a local job runner for Disco based project. It provides a useful method for running your disco project without needing a full disco cluster. This makes it a snap to develop and debug jobs on your development machine. To use, simply execute your disco script using the leisure command like so: $ leisure <path to script>/word_count.py Leisure monkey patches all network calls to the Disco/DDFS master so that it can intercept and execute them locally. The worker itself is executed as a subprocess and communicated to via the Disco Worker protocol http://discoproject.org/doc/disco/howto/worker.html :copyright: (c) 2011 by triv.io, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ from __future__ import absolute_import import sys from .disco import run_script from . import shuffle import tempfile def main(): script = sys.argv[1] if len(sys.argv) == 3: data_root = sys.argv[2] else: data_root = tempfile.mkdtemp() run_script(script, data_root) if __name__ == "__main__": main()
Remove the importing of the "cythonize" function.
from distutils.core import Extension, setup try: from Cython.Distutils import build_ext except ImportError: use_cython = False else: use_cython = True if use_cython: extensions = [ Extension('mathix.vector', ['mathix/vector.pyx']), ] cmdclass = { 'build_ext': build_ext } else: extensions = [ Extension('mathix.vector', ['mathix/vector.c']), ] cmdclass = {} setup( name='mathix', author='Peith Vergil', version='0.1', cmdclass=cmdclass, packages=[ 'mathix', ], keywords='useless simple math library', description='A useless simple math library.', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Cython', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], ext_modules=extensions )
from distutils.core import Extension, setup from Cython.Build import cythonize try: from Cython.Distutils import build_ext except ImportError: use_cython = False else: use_cython = True if use_cython: extensions = [ Extension('mathix.vector', ['mathix/vector.pyx']), ] cmdclass = { 'build_ext': build_ext } else: extensions = [ Extension('mathix.vector', ['mathix/vector.c']), ] cmdclass = {} setup( name='mathix', author='Peith Vergil', version='0.1', cmdclass=cmdclass, packages=[ 'mathix', ], keywords='useless simple math library', description='A useless simple math library.', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Cython', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], ext_modules=cythonize(extensions) )
Remove not needed Testcontainers annotation
package org.synyx.urlaubsverwaltung; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.testcontainers.containers.MariaDBContainer; import static org.testcontainers.containers.MariaDBContainer.IMAGE; @DirtiesContext public abstract class TestContainersBase { static MariaDBContainer<?> mariaDB = new MariaDBContainer<>(IMAGE + ":10.4"); @DynamicPropertySource static void mariaDBProperties(DynamicPropertyRegistry registry) { mariaDB.start(); registry.add("spring.datasource.url", mariaDB::getJdbcUrl); registry.add("spring.datasource.username", mariaDB::getUsername); registry.add("spring.datasource.password", mariaDB::getPassword); } }
package org.synyx.urlaubsverwaltung; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.testcontainers.containers.MariaDBContainer; import org.testcontainers.junit.jupiter.Testcontainers; import static org.testcontainers.containers.MariaDBContainer.IMAGE; @Testcontainers @DirtiesContext public abstract class TestContainersBase { static MariaDBContainer<?> mariaDB = new MariaDBContainer<>(IMAGE + ":10.4"); @DynamicPropertySource static void mariaDBProperties(DynamicPropertyRegistry registry) { mariaDB.start(); registry.add("spring.datasource.url", mariaDB::getJdbcUrl); registry.add("spring.datasource.username", mariaDB::getUsername); registry.add("spring.datasource.password", mariaDB::getPassword); } }
Revert "For getCurrentPosition(), use chrome.runtime.sendMessage() as the callback function; this avoids the problem of undefined lat/longitude because getCurrentPosition did not fetch values before chrome.runtime.sendMessage() fires" This reverts commit b893f4cb3b4c1665e2f4b0d7b92ca6e7ec299a24.
var latitude = null; var longitude = null; function getUserLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { var myLat = position.coords.latitude; var myLong = position.coords.longitude; alert("User location:\n"+myLat+"\n"+myLong); } getUserLocation(); var demo = document.getElementById("demo"); function setDestinationCordinates() { var metas = document.getElementsByTagName('meta'); for (i=0; i<metas.length; i++) { if (metas[i].getAttribute("property") == "zomatocom:location:latitude") { latitude = metas[i].getAttribute("content"); } else if (metas[i].getAttribute("property") == "zomatocom:location:longitude") { longitude = metas[i].getAttribute("content"); } } } setDestinationCordinates(); chrome.runtime.sendMessage({ 'latitude' : latitude, 'longitude' : longitude, 'myLat': 12.11, 'myLong': 99.11 });
var latitude = null; var longitude = null; var demo = document.getElementById("demo"); function setDestinationCordinates() { var metas = document.getElementsByTagName('meta'); for (i=0; i<metas.length; i++) { if (metas[i].getAttribute("property") == "zomatocom:location:latitude") { latitude = metas[i].getAttribute("content"); } else if (metas[i].getAttribute("property") == "zomatocom:location:longitude") { longitude = metas[i].getAttribute("content"); } } } setDestinationCordinates(); function getUserLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( chrome.runtime.sendMessage({ 'latitude' : latitude, 'longitude' : longitude, 'myLat': 12.11, 'myLong': 99.11 }) ); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { var myLat = position.coords.latitude; var myLong = position.coords.longitude; alert("User location:\n"+myLat+"\n"+myLong); } getUserLocation();
change: Rename dist script as compile
/** * Copyright (c) Ajay Sreedhar. All rights reserved. * * Licensed under the MIT License. * Please see LICENSE file located in the project root for more information. */ 'use strict'; const loadTasks = require('load-grunt-tasks'); const {copyConfig, babelConfig} = require('./build/grunt-config'); const {cleanBuild, startRenderer, makeRelease} = require('./build/grunt-task'); module.exports = function (grunt) { loadTasks(grunt, {pattern: ['grunt-contrib-copy', 'grunt-babel']}); grunt.initConfig({ copy: copyConfig, babel: babelConfig }); grunt.registerTask('clean', 'Cleans up the output files.', cleanBuild); grunt.registerTask('render', 'Starts the electron renderer.', startRenderer); grunt.registerTask('dist', 'Makes a distributable release.', makeRelease); grunt.registerTask('compile', ['clean', 'babel', 'copy']); grunt.registerTask('start', ['compile', 'render']); };
/** * Copyright (c) Ajay Sreedhar. All rights reserved. * * Licensed under the MIT License. * Please see LICENSE file located in the project root for more information. */ 'use strict'; const loadTasks = require('load-grunt-tasks'); const {copyConfig, babelConfig} = require('./build/grunt-config'); const {cleanBuild, startRenderer, makeRelease} = require('./build/grunt-task'); module.exports = function (grunt) { loadTasks(grunt, {pattern: ['grunt-contrib-copy', 'grunt-babel']}); grunt.initConfig({ copy: copyConfig, babel: babelConfig }); grunt.registerTask('clean', 'Cleans up the output files.', cleanBuild); grunt.registerTask('render', 'Starts the electron renderer.', startRenderer); grunt.registerTask('release', 'Makes an app release.', makeRelease); grunt.registerTask('dist', ['clean', 'babel', 'copy']); grunt.registerTask('start', ['dist', 'render']); };
Replace state connection by store injection and observer decorator
import React from 'react' import { Image, Text, View, } from 'react-native' import { inject, observer } from 'mobx-react' @inject('profileStore') @observer export default class ProfileScreen extends React.Component { render() { return ( <View style={{ alignItems: 'center' }}> <Image source={{ uri: this.props.profileStore.profile.picture.data.url }} style={{ width: 100, height: 100, borderRadius: 50 }} /> <Text style={{ fontSize: 20 }}>{this.props.profileStore.profile.name}</Text> <Text>ID: {this.props.profileStore.profile.id}</Text> </View> ) } }
import React from 'react' import { Image, Text, View, } from 'react-native' import { connect } from 'react-redux' class ProfileScreen extends React.Component { render() { return ( <View style={{ alignItems: 'center' }}> <Image source={{ uri: this.props.profile.picture.data.url }} style={{ width: 100, height: 100, borderRadius: 50 }} /> <Text style={{ fontSize: 20 }}>{this.props.profile.name}</Text> <Text>ID: {this.props.profile.id}</Text> </View> ) } } const mapStateToProps = state => { return { profile: state.profile, } } export default connect( mapStateToProps, )(ProfileScreen)
Use proptypes instead of comments
import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import PlayerLabel from '../components/player-label' class Player extends Component { render () { const { right, color, name } = this.props return ( <div style={{ fontSize: '5vw' }}> <PlayerLabel color={color} right={right}>{name}</PlayerLabel> </div> ) } } function mapStateToProps (state, ownProps) { return { type: state[ownProps.color].type, name: state[ownProps.color].name } } function mapDispatchToProps (dispatch) { return { } } Player.propTypes = { color: PropTypes.oneOf(['black', 'white']), type: PropTypes.oneOf(['human', 'ai']), name: PropTypes.string, // name of the player right: PropTypes.bool // true if label should be on the right side } export default connect(mapStateToProps, mapDispatchToProps)(Player)
import React, { Component } from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import PlayerLabel from '../components/player-label' class Player extends Component { render () { const { right, color, name } = this.props return ( <div style={{ fontSize: '5vw' }}> <PlayerLabel color={color} right={right}>{name}</PlayerLabel> </div> ) } } function mapStateToProps (state, ownProps) { return { type: state[ownProps.color].type, name: state[ownProps.color].name } } function mapDispatchToProps (dispatch) { return { } } Player.propTypes = { color: PropTypes.string, // black | white type: PropTypes.string, // human | ai name: PropTypes.string, // name of the player right: PropTypes.bool // true if label should be on the right side } export default connect(mapStateToProps, mapDispatchToProps)(Player)
Add "remote" field to lxdclient.Config.
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. // +build go1.3 package lxdclient import ( "github.com/juju/errors" "github.com/lxc/lxd" ) // Client is a high-level wrapper around the LXD API client. type Client struct { raw rawClientWrapper namespace string remote string } // Connect opens an API connection to LXD and returns a high-level // Client wrapper around that connection. func Connect(cfg Config) (*Client, error) { if err := cfg.Apply(); err != nil { return nil, errors.Trace(err) } remote := cfg.Remote.ID() raw, err := newRawClient(remote) if err != nil { return nil, errors.Trace(err) } conn := &Client{ raw: raw, namespace: cfg.Namespace, remote: remote, } return conn, nil } func newRawClient(remote string) (*lxd.Client, error) { logger.Debugf("loading LXD client config from %q", lxd.ConfigDir) cfg, err := lxd.LoadConfig() if err != nil { return nil, errors.Trace(err) } logger.Debugf("using LXD remote %q", remote) client, err := lxd.NewClient(cfg, remote) if err != nil { return nil, errors.Trace(err) } return client, nil }
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. // +build go1.3 package lxdclient import ( "github.com/juju/errors" "github.com/lxc/lxd" ) // Client is a high-level wrapper around the LXD API client. type Client struct { raw rawClientWrapper namespace string } // Connect opens an API connection to LXD and returns a high-level // Client wrapper around that connection. func Connect(cfg Config) (*Client, error) { if err := cfg.Apply(); err != nil { return nil, errors.Trace(err) } raw, err := newRawClient(cfg.Remote) if err != nil { return nil, errors.Trace(err) } conn := &Client{ raw: raw, namespace: cfg.Namespace, } return conn, nil } func newRawClient(remote Remote) (*lxd.Client, error) { cfg, err := lxd.LoadConfig() if err != nil { return nil, errors.Trace(err) } client, err := lxd.NewClient(cfg, remote.ID()) if err != nil { return nil, errors.Trace(err) } return client, nil }
Fix linting errors in GoBot
""" GoBot Example """ from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): """ GoBot """ def __init__(self): Bot.__init__(self, "GoBot") self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15)) self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15)) self.l_motor.set(17) self.r_motor.set(13) def run(self): pass if __name__ == "__main__": bot = GoBot() while True: bot.run()
from minibot.bot import Bot from minibot.hardware.rpi.gpio import PWM from minibot.interface.servo import Servo import math import time L_MOTOR_PIN = 12 R_MOTOR_PIN = 18 class GoBot(Bot): def __init__(self): Bot.__init__(self, "GoBot") self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15)) self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15)) self.l_motor.set(17) self.r_motor.set(13) def run(self): pass if __name__ == "__main__": bot = GoBot() while True: bot.run()
Test for Angular Object literal with returns of directiveFactory
// plugin=angular // environment=browser // environment=jquery // loadfiles=config.js, filters.js angular.module('sample', ['ngResource', 'sample.config', 'sample.filters']) .run(function($rootScope, someNumber) { someNumber; //: number $rootScope.rootName; //: string }) .controller('GreetingCtrl', ['$rootScope', '$scope', 'User', 'myConfig', 'version', function($rootScope, $scope, User, myConfig, version) { $rootScope.rootName = $scope.myName = 'John'; $scope.myName; //: string $scope.myConfig = myConfig; //: {myColor} $scope.myConfig; //: {myColor} $scope.version = version; //: string $scope.version; //: string User; //doc: doc for User $scope.user = User.get({login: 'sqs'}); $scope.user.$promise.finally; //: fn(callback: fn()) -> Promise }]) .controller('OtherCtrl', ['$scope', function($scope) { // Test that controllers' $scope objects are distinct. $scope.myName; //: ? }]) .constant('version', 'v1.2.3') // doc for User .factory('User', ['$resource', function($resource) { return $resource('https://api.github.com/users/:login'); }]) ; angular.module('docsScopeProblemExample', []) .directive('myCustomer', function() { return { //+ bindToController, compile, controller, controllerAs, template, templateUrl, ... }; }).directive('myCustomer', function() { return { t //+ template, templateNamespace, templateUrl, ... }; });
// plugin=angular // environment=browser // environment=jquery // loadfiles=config.js, filters.js angular.module('sample', ['ngResource', 'sample.config', 'sample.filters']) .run(function($rootScope, someNumber) { someNumber; //: number $rootScope.rootName; //: string }) .controller('GreetingCtrl', ['$rootScope', '$scope', 'User', 'myConfig', 'version', function($rootScope, $scope, User, myConfig, version) { $rootScope.rootName = $scope.myName = 'John'; $scope.myName; //: string $scope.myConfig = myConfig; //: {myColor} $scope.myConfig; //: {myColor} $scope.version = version; //: string $scope.version; //: string User; //doc: doc for User $scope.user = User.get({login: 'sqs'}); $scope.user.$promise.finally; //: fn(callback: fn()) -> Promise }]) .controller('OtherCtrl', ['$scope', function($scope) { // Test that controllers' $scope objects are distinct. $scope.myName; //: ? }]) .constant('version', 'v1.2.3') // doc for User .factory('User', ['$resource', function($resource) { return $resource('https://api.github.com/users/:login'); }]) ;
Augment read to handle multiple connected DS18B20 devices
import datetime import os import glob import time os.system('modprobe w1-gpio') os.system('modprobe w1-therm') base_dir = '/sys/bus/w1/devices/' device_folders = glob.glob(base_dir + '28-*') devices = map(lambda x: os.path.basename(x), device_folders) device_files = map(lambda x: x + '/w1_slave', device_folders) def read_temp_raw(device): device_file = base_dir + device + '/w1_slave' f = open(device_file, 'r') lines = f.readlines() f.close() return lines def read_temp(device): lines = read_temp_raw(device) while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw(device) equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 temp_f = temp_c * 9.0 / 5.0 + 32.0 return temp_c, temp_f while True: print datetime.datetime.now() for device in devices: print(device, read_temp(device)) time.sleep(1)
import os import glob import time os.system('modprobe w1-gpio') os.system('modprobe w1-therm') base_dir = '/sys/bus/w1/devices/' device_folder = glob.glob(base_dir + '28*')[0] device_file = device_folder + '/w1_slave' def read_temp_raw(): f = open(device_file, 'r') lines = f.readlines() f.close() return lines def read_temp(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 temp_f = temp_c * 9.0 / 5.0 + 32.0 return temp_c, temp_f while True: print(read_temp()) time.sleep(1)
Rename generic names to single letter
<%# Copyright 2013-2017 the original author or authors from the JHipster project. This file is part of the JHipster project, see https://jhipster.github.io/ for more information. 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 <%=packageName%>.service.mapper; import java.util.List; /** * Contract for a generic dto to entity mapper. @param <D> - DTO type parameter. @param <E> - Entity type parameter. */ public interface EntityMapper <D, E> { public E toEntity(D dto); public D toDto(E entity); public List <E> toEntity(List<D> dtoList); public List <D> toDto(List<E> entityList); }
<%# Copyright 2013-2017 the original author or authors from the JHipster project. This file is part of the JHipster project, see https://jhipster.github.io/ for more information. 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 <%=packageName%>.service.mapper; import java.util.List; /** * Contract for a generic dto to entity mapper. @param <DTO> - DTO type parameter. @param <ENTITY> - Entity type parameter. */ public interface EntityMapper <DTO, ENTITY> { public ENTITY toEntity(DTO dto); public DTO toDto(ENTITY entity); public List <ENTITY> toEntity(List<DTO> dtoList); public List <DTO> toDto(List<ENTITY> entityList); }
Fix no table named event_id
#-*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.template import RequestContext from apps.events.models import Event, AttendanceEvent, Attendee import datetime def index(request): events = Event.objects.filter(event_start__gte=datetime.date.today()) if len(events) == 1: return details(request, events[0].id) return render_to_response('events/index.html', {'events': events}, context_instance=RequestContext(request)) def details(request, event_id): event = get_object_or_404(Event, pk=event_id) is_attendance_event = False try: attendance_event = AttendanceEvent.objects.get(pk=event_id) attendance_event.count_attendees = Attendee.objects.filter(event=attendance_event).count() is_attendance_event = True except AttendanceEvent.DoesNotExist: pass if is_attendance_event: return render_to_response('events/details.html', {'event': event, 'attendance_event': attendance_event}, context_instance=RequestContext(request)) else: return render_to_response('events/details.html', {'event': event}, context_instance=RequestContext(request)) def get_attendee(attendee_id): return get_object_or_404(Attendee, pk=attendee_id)
#-*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.template import RequestContext from apps.events.models import Event, AttendanceEvent, Attendee import datetime def index(request): events = Event.objects.filter(event_start__gte=datetime.date.today()) if len(events) == 1: return details(request, events[0].event_id) return render_to_response('events/index.html', {'events': events}, context_instance=RequestContext(request)) def details(request, event_id): event = get_object_or_404(Event, pk=event_id) is_attendance_event = False try: attendance_event = AttendanceEvent.objects.get(pk=event_id) attendance_event.count_attendees = Attendee.objects.filter(event=attendance_event).count() is_attendance_event = True except AttendanceEvent.DoesNotExist: pass if is_attendance_event: return render_to_response('events/details.html', {'event': event, 'attendance_event': attendance_event}, context_instance=RequestContext(request)) else: return render_to_response('events/details.html', {'event': event}, context_instance=RequestContext(request)) def get_attendee(attendee_id): return get_object_or_404(Attendee, pk=attendee_id)
Use connection pool by default during testing
import os CONNECT_ARGS = [] CONNECT_KWARGS = {} LIVE_TEST = 'HOST' in os.environ if LIVE_TEST: HOST = os.environ['HOST'] DATABASE = os.environ.get('DATABASE', 'test') USER = os.environ.get('SQLUSER', 'sa') PASSWORD = os.environ.get('SQLPASSWORD', 'sa') USE_MARS = bool(os.environ.get('USE_MARS', True)) SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH')) import pytds CONNECT_KWARGS = { 'server': HOST, 'database': DATABASE, 'user': USER, 'password': PASSWORD, 'use_mars': USE_MARS, 'bytes_to_unicode': True, 'pooling': True, } if 'tds_version' in os.environ: CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version']) if 'auth' in os.environ: import pytds.login CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])() if 'bytes_to_unicode' in os.environ: CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
import os CONNECT_ARGS = [] CONNECT_KWARGS = {} LIVE_TEST = 'HOST' in os.environ if LIVE_TEST: HOST = os.environ['HOST'] DATABASE = os.environ.get('DATABASE', 'test') USER = os.environ.get('SQLUSER', 'sa') PASSWORD = os.environ.get('SQLPASSWORD', 'sa') USE_MARS = bool(os.environ.get('USE_MARS', True)) SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH')) import pytds CONNECT_KWARGS = { 'server': HOST, 'database': DATABASE, 'user': USER, 'password': PASSWORD, 'use_mars': USE_MARS, 'bytes_to_unicode': True, } if 'tds_version' in os.environ: CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version']) if 'auth' in os.environ: import pytds.login CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])() if 'bytes_to_unicode' in os.environ: CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
Use list comprehension as pylint suggests
""" This linter reports missing primary / unique index """ from collections import OrderedDict from indexdigest.utils import LinterEntry def check_missing_primary_index(database): """ :type database indexdigest.database.Database :rtype: list[LinterEntry] """ for table in database.get_tables(): # list non-primary (and non-unique) indices only # @see https://bugs.mysql.com/bug.php?id=76252 # @see https://github.com/Wikia/app/pull/9863 indices = [ index for index in database.get_table_indices(table) if index.is_primary or index.is_unique ] if indices: # so we have at least one primary or unique index defined continue context = OrderedDict() context['schema'] = database.get_table_schema(table) yield LinterEntry(linter_type='missing_primary_index', table_name=table, message='"{}" table does not have any primary or unique index'. format(table), context=context)
""" This linter reports missing primary / unique index """ from collections import OrderedDict from indexdigest.utils import LinterEntry def check_missing_primary_index(database): """ :type database indexdigest.database.Database :rtype: list[LinterEntry] """ for table in database.get_tables(): # list non-primary (and non-unique) indices only # @see https://bugs.mysql.com/bug.php?id=76252 # @see https://github.com/Wikia/app/pull/9863 indices = list(filter( lambda index: index.is_primary or index.is_unique, database.get_table_indices(table) )) if indices: # so we have at least one primary or unique index defined continue context = OrderedDict() context['schema'] = database.get_table_schema(table) yield LinterEntry(linter_type='missing_primary_index', table_name=table, message='"{}" table does not have any primary or unique index'. format(table), context=context)
Fix a bad eigen vector cast.
import numpy as np from eigen3 import toEigenX import rbdyn as rbd class WLSSolver(object): def __init__(self): self.tasks = [] def addTask(self, task, weight): t = [task, weight] self.tasks.append(t) return t def rmTask(self, taskDef): self.tasks.remove(taskDef) def solve(self, mb, mbc): err = np.mat(np.empty((0, 1))) jac = np.mat(np.empty((0, mb.nrDof()))) for t in self.tasks: t[0].update(mb, mbc) err = np.vstack((err, t[1]*t[0].error())) jac = np.vstack((jac, t[1]*t[0].jacobian())) #alpha1 = np.linalg.lstsq(jac, err)[0] alpha2 = np.linalg.pinv(jac)*err mbc.alpha = rbd.vectorToDof(mb, toEigenX(alpha2))
import numpy as np from eigen3 import toEigen import rbdyn as rbd class WLSSolver(object): def __init__(self): self.tasks = [] def addTask(self, task, weight): t = [task, weight] self.tasks.append(t) return t def rmTask(self, taskDef): self.tasks.remove(taskDef) def solve(self, mb, mbc): err = np.mat(np.empty((0, 1))) jac = np.mat(np.empty((0, mb.nrDof()))) for t in self.tasks: t[0].update(mb, mbc) err = np.vstack((err, t[1]*t[0].error())) jac = np.vstack((jac, t[1]*t[0].jacobian())) #alpha1 = np.linalg.lstsq(jac, err)[0] alpha2 = np.linalg.pinv(jac)*err mbc.alpha = rbd.vectorToDof(mb, toEigen(alpha2))
Reduce complexity of code as requested by codacy...
function eventsourcetest() { var alInfo = $("#alInfo"); var alSuccess = $("#alSuccess"); var ta = document.getElementById("output"); var source = new EventSource("php/gravity.sh.php"); alInfo.hide(); alSuccess.hide(); source.addEventListener("message", function(e) { if(e.data === "***START***"){ alInfo.show(); } else if(e.data === "***END***"){ alInfo.delay(1000).fadeOut(2000, function() { alInfo.hide(); }); } else if(e.data.indexOf("Pi-hole blocking is Enabled") !== -1) { alSuccess.show(); ta.innerHTML += e.data; } else if (e.data !== "") { ta.innerHTML += e.data; } }, false); // Will be called when script has finished source.addEventListener("error", function(e) { source.close(); }, false); } $(function(){ eventsourcetest(); }); // Handle hiding of alerts $(function(){ $("[data-hide]").on("click", function(){ $(this).closest("." + $(this).attr("data-hide")).hide(); }); });
function eventsourcetest() { var alInfo = $("#alInfo"); var alSuccess = $("#alSuccess"); var ta = document.getElementById("output"); var source = new EventSource("php/gravity.sh.php"); alInfo.hide(); alSuccess.hide(); source.addEventListener("message", function(e) { if(e.data === "***START***"){ alInfo.show(); } else if(e.data === "***END***"){ alInfo.delay(1000).fadeOut(2000, function() { alInfo.hide(); }); } else if (e.data !== "") { ta.innerHTML += e.data; if(e.data.indexOf("Pi-hole blocking is Enabled") !== -1) { alSuccess.show(); } } }, false); // Will be called when script has finished source.addEventListener("error", function(e) { source.close(); }, false); } $(function(){ eventsourcetest(); });
Remove init because import does the init already and init function isn't exposed
import stencilUtils from 'bigcommerce/stencil-utils' import account from './theme/account'; import auth from './theme/auth'; import blog from './theme/blog'; import brand from './theme/brand'; import brands from './theme/brands'; import cart from './theme/cart'; import category from './theme/category'; import compare from './theme/compare' import errors from './theme/errors'; import giftCertificate from './theme/gift-certificate'; import home from './theme/home'; import orderComplete from './theme/order-complete'; import page from './theme/page'; import product from './theme/product'; import search from './theme/search'; import sitemap from './theme/sitemap'; import subscribe from './theme/subscribe'; import wishlist from './theme/wishlist'; var modules = { "account": account, "auth": auth, "blog": blog, "brand": brand, "brands": brand, "cart": cart, "category": category, "compare": compare, "errors": errors, "gift-certificate": giftCertificate, "home": home, "order-complete": orderComplete, "page": page, "product": product, "search": search, "sitemap": sitemap, "subscribe": subscribe, "wishlist": wishlist }; export {modules};
import stencilUtils from 'bigcommerce/stencil-utils' import account from './theme/account'; import auth from './theme/auth'; import blog from './theme/blog'; import brand from './theme/brand'; import brands from './theme/brands'; import cart from './theme/cart'; import category from './theme/category'; import compare from './theme/compare' import errors from './theme/errors'; import giftCertificate from './theme/gift-certificate'; import home from './theme/home'; import orderComplete from './theme/order-complete'; import page from './theme/page'; import product from './theme/product'; import search from './theme/search'; import sitemap from './theme/sitemap'; import subscribe from './theme/subscribe'; import wishlist from './theme/wishlist'; stencilUtils.events.init(); var modules = { "account": account, "auth": auth, "blog": blog, "brand": brand, "brands": brand, "cart": cart, "category": category, "compare": compare, "errors": errors, "gift-certificate": giftCertificate, "home": home, "order-complete": orderComplete, "page": page, "product": product, "search": search, "sitemap": sitemap, "subscribe": subscribe, "wishlist": wishlist }; export {modules};
Delete all Jpa method impl
/* * Copyright 2018 EPAM Systems * * 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.epam.ta.reportportal.dao; import com.epam.ta.reportportal.entity.attachment.Attachment; import java.util.stream.Stream; /** * @author <a href="mailto:ivan_budayeu@epam.com">Ivan Budayeu</a> */ public interface AttachmentRepository extends ReportPortalRepository<Attachment, Long> { Stream<Attachment> findAllByProjectIdIsNull(); Stream<Attachment> findAllByLaunchIdIsNull(); Stream<Attachment> findAllByItemIdIsNull(); void deleteAllByIdIsNull(); }
/* * Copyright 2018 EPAM Systems * * 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.epam.ta.reportportal.dao; import com.epam.ta.reportportal.entity.attachment.Attachment; import java.util.stream.Stream; /** * @author <a href="mailto:ivan_budayeu@epam.com">Ivan Budayeu</a> */ public interface AttachmentRepository extends ReportPortalRepository<Attachment, Long> { Stream<Attachment> findAllByProjectIdIsNull(); Stream<Attachment> findAllByLaunchIdIsNull(); Stream<Attachment> findAllByItemIdIsNull(); }
Fix parsing of L errors without parenthesis example: ``` Error L12: 14000 messages dropped since 2015-09-15T17:38:54.097612+00:00 ```
package drain import ( "fmt" "regexp" "strconv" ) type LogplexError struct { Code int // L11, L12, etc. Count int // Count of logs referenced in the error Msg string } func parseLogplexError(msg string) (*LogplexError, error) { // Data:Error L10 (output buffer overflow): // 491 messages dropped since 2015-09-15T16:22:24+00:00. r := regexp.MustCompile( `Error L(?P<num>\d+).*\: (?P<count>\d+) .*`).FindAllStringSubmatch(msg, -1) if len(r) < 1 || len(r[0]) < 3 { return nil, fmt.Errorf("invalid lerror line") } num, err := strconv.Atoi(r[0][1]) if err != nil { return nil, err } count, err := strconv.Atoi(r[0][2]) if err != nil { return nil, err } return &LogplexError{num, count, msg}, nil } func (err LogplexError) Error() string { return fmt.Sprintf("L%d: %s", err.Code, err.Msg) }
package drain import ( "fmt" "regexp" "strconv" ) type LogplexError struct { Code int // L11, L12, etc. Count int // Count of logs referenced in the error Msg string } func parseLogplexError(msg string) (*LogplexError, error) { // Data:Error L10 (output buffer overflow): // 491 messages dropped since 2015-09-15T16:22:24+00:00. r := regexp.MustCompile( `Error L(?P<num>\d+) .*\: (?P<count>\d+) .*`).FindAllStringSubmatch(msg, -1) if len(r) < 1 || len(r[0]) < 3 { return nil, fmt.Errorf("invalid lerror line") } num, err := strconv.Atoi(r[0][1]) if err != nil { return nil, err } count, err := strconv.Atoi(r[0][2]) if err != nil { return nil, err } return &LogplexError{num, count, msg}, nil } func (err LogplexError) Error() string { return fmt.Sprintf("L%d: %s", err.Code, err.Msg) }
Add responsive behaviour to table, add search box
$(function() { var dt = {sPaginationType: 'full_numbers', bAutoWidth: false, aaSorting: [[ 0, 'desc' ]], fnDrawCallback: _iconify, } /*if ($(window).width() <= 600) dt = $.extend({ 'bScrollCollapse': true, 'sScrollX': '100%', }, dt)*/ var dt = $('.robot_actions').dataTable(dt) $('.table input').focus() $('input.search-mobile').keyup(function() { $('.dataTables_filter input').val($(this).val()).trigger('keyup') }).parent('span').addClass('enable') $('#sidebar,.cont_wrap').addClass('searchbox') $('a.add').button({ icons: { primary: 'ui-icon-plus' } }) $(window).resize(function() { _resize() }) function _resize() { $.each([2,3,5,6],function(i,n) { dt.fnSetColumnVis(n, !($(window).width() <= 600)) }) } _resize() function _iconify() { $('a.view').button({ icons: { primary: 'ui-icon-search' }, text: false }) $('a.label').button({ icons: { primary: 'ui-icon-print' }, text: false }) } })
$(function() { var dt = {sPaginationType: 'full_numbers', bAutoWidth:false , aaSorting: [[ 0, 'desc' ]], fnDrawCallback: _iconify, } if ($(window).width() <= 600) dt = $.extend({ 'bScrollCollapse': true, 'sScrollX': '100%', }, dt) $('.robot_actions').dataTable(dt) $('a.add').button({ icons: { primary: 'ui-icon-plus' } }) function _iconify() { $('a.view').button({ icons: { primary: 'ui-icon-search' }, text: false }) $('a.label').button({ icons: { primary: 'ui-icon-print' }, text: false }) } })
Fix 'rollup-plugin-replace' order and variable name
import resolve from 'rollup-plugin-node-resolve'; import eslint from 'rollup-plugin-eslint'; import babel from 'rollup-plugin-babel'; import commonjs from 'rollup-plugin-commonjs'; import replace from 'rollup-plugin-replace'; import pkg from './package.json'; export default [ { input: 'src/index.js', external: ['react', 'react-dom'], output: [ { file: pkg.main, format: 'umd', name: 'reactAccessibleAccordion' }, { file: pkg['jsnext:main'], format: 'es' }, ], name: 'reactAccessibleAccordion', plugins: [ replace({ 'process.env.NODE_ENV': JSON.stringify('production'), }), resolve({ jsnext: true, main: true, browser: true, }), eslint(), babel(), commonjs(), ], }, ];
import resolve from 'rollup-plugin-node-resolve'; import eslint from 'rollup-plugin-eslint'; import babel from 'rollup-plugin-babel'; import commonjs from 'rollup-plugin-commonjs'; import replace from 'rollup-plugin-replace'; import pkg from './package.json'; export default [ { input: 'src/index.js', external: ['react', 'react-dom'], output: [ { file: pkg.main, format: 'umd', name: 'reactAccessibleAccordion' }, { file: pkg['jsnext:main'], format: 'es' }, ], name: 'reactAccessibleAccordion', plugins: [ resolve({ jsnext: true, main: true, browser: true, }), eslint(), babel(), commonjs(), replace({ exclude: 'node_modules/**', ENV: JSON.stringify(process.env.NODE_ENV || 'development'), }), ], }, ];
Index route needs a vehicle loader as well
import React from 'react' import { Route, IndexRoute } from 'react-router' import App from './app' import VehicleLoader from './utilities/vehicle-loader' import VehicleListContainer from './vehicle-list/container' import VehicleContainer from './vehicle/container' import UserEditor from './user-editor/editor' import { requireAuthentication } from './profile/authentication' export default ( <Route path="/" component={App}> <Route component={VehicleLoader}> <IndexRoute component={VehicleListContainer} /> </Route> <Route path="vehicles" component={VehicleLoader}> <Route path=":id" component={requireAuthentication(VehicleContainer)} /> <IndexRoute component={VehicleListContainer} /> </Route> <Route path="profile" component={requireAuthentication(UserEditor)} /> <Route path="register" component={UserEditor} /> <Route path="password" component={requireAuthentication(UserEditor)} /> </Route> )
import React from 'react' import { Route, IndexRoute } from 'react-router' import App from './app' import VehicleLoader from './utilities/vehicle-loader' import VehicleListContainer from './vehicle-list/container' import VehicleContainer from './vehicle/container' import UserEditor from './user-editor/editor' import { requireAuthentication } from './profile/authentication' export default ( <Route path="/" component={App}> <IndexRoute component={VehicleListContainer} /> <Route path="vehicles" component={VehicleLoader}> <Route path=":id" component={requireAuthentication(VehicleContainer)} /> <IndexRoute component={VehicleListContainer} /> </Route> <Route path="profile" component={requireAuthentication(UserEditor)} /> <Route path="register" component={UserEditor} /> <Route path="password" component={requireAuthentication(UserEditor)} /> </Route> )
Raise the time-out a bit after a Travis CI failure
(function () { 'use strict'; var assert = require('assert'), Validator = require('../src/validator.js') ; describe('validator in the wild', function () { this.timeout(16000); it('loads all referenced remote schemas', function (done) { Validator.simple( 'https://www.swisshotels.com/availabilities-filtered/schema', function (error) { assert.ifError(error); done(); } ); }); it('does actual validation', function (done) { Validator.simple('http://json-schema.org/geo', function (error, v) { assert.ifError(error); assert(v.validate( {latitude: 53.0, longitude: 43.0}, 'http://json-schema.org/geo' ).valid); done(); }); }); }); }());
(function () { 'use strict'; var assert = require('assert'), Validator = require('../src/validator.js') ; describe('validator in the wild', function () { this.timeout(10000); it('loads all referenced remote schemas', function (done) { Validator.simple( 'https://www.swisshotels.com/availabilities-filtered/schema', function (error) { assert.ifError(error); done(); } ); }); it('does actual validation', function (done) { Validator.simple('http://json-schema.org/geo', function (error, v) { assert.ifError(error); assert(v.validate( {latitude: 53.0, longitude: 43.0}, 'http://json-schema.org/geo' ).valid); done(); }); }); }); }());
Fix missing post group defaults for Burkina Faso
from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def __init__(self, *args, **kwargs): super(AreaPostData, self).__init__(*args, **kwargs) self.ALL_POSSIBLE_POST_GROUPS = [None] def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national' def party_to_possible_post_groups(self, party_data): return (None,)
from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ) def party_data_to_party_sets(self, party_data): return ['national'] class AreaPostData(BaseAreaPostData): def area_to_post_group(self, area_data): return None def shorten_post_label(self, election, post_label): return post_label def post_id_to_post_group(self, election, post_id): return None def post_id_to_party_set(self, post_id): return 'national'
Revert "Register query on create." This reverts commit 9b1d857a288861a8a93acb242c05d1830e61a7e5.
var express = require('express'); var DataStore = require('./regard-data-store.js'); var Chart = require('../schemas/chart.js'); var router = express.Router(); var dataStore = new DataStore('Adobe', 'Brackets'); router.get('/chartdata', function (req, res, next) { var id = req.query.ids[0]; dataStore.runQuery(id).then(function (result) { res.json({ chartdata: [{ _id: id, values: JSON.parse(result).Results }] }); }); }); router.put('/charts/:id', function (req, res, next) { if (!req.body.chart.queryDefinition) { res.send(400, 'missing query definition'); } var queryName = req.params.id; var queryDefinition = req.body.chart.queryDefinition; dataStore.registerQuery(queryName, queryDefinition).done(function () { next(); }, next); }); module.exports = router;
var express = require('express'); var DataStore = require('./regard-data-store.js'); var Chart = require('../schemas/chart.js'); var router = express.Router(); var dataStore = new DataStore('Adobe', 'Brackets'); router.get('/chartdata', function (req, res, next) { var id = req.query.ids[0]; dataStore.runQuery(id).then(function (result) { res.json({ chartdata: [{ _id: id, values: JSON.parse(result).Results }] }); }, next); }); router.post('/charts', function (req, res, next) { if (!req.body.chart.queryDefinition) { res.send(400, 'missing query definition'); } var queryName = req.body.chart.id; var queryDefinition = req.body.chart.queryDefinition; dataStore.registerQuery(queryName, queryDefinition).done(function () { next(); }, next); }); module.exports = router;
Extend the common Messages class
/* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.common.tool; import java.util.ResourceBundle; import com.redhat.ceylon.common.Messages; class ToolMessages extends Messages { private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools"); public static String msg(String msgKey, Object... msgArgs) { return msg(RESOURCE_BUNDLE, msgKey, msgArgs); } }
/* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.common.tool; import java.text.MessageFormat; import java.util.ResourceBundle; class ToolMessages { private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools"); public static String msg(String msgKey, Object... msgArgs) { String msg = RESOURCE_BUNDLE.getString(msgKey); if (msgArgs != null) { msg = MessageFormat.format(msg, msgArgs); } return msg; } }
Return nil on none error Instead of err with a value of nil. Now it's easier to spot that everything went ok.
package logger import ( "io" "os" ) type ioWriterMsgWriter struct { w io.Writer } func (iw *ioWriterMsgWriter) Write(msg Msg) error { bytes := append(msg.Bytes(), '\n') n, err := iw.w.Write(bytes) if err != nil { return err } else if n != len(bytes) { return io.ErrShortWrite } return nil } func (iw *ioWriterMsgWriter) Close() error { return nil } // NewWriter creates a new logger that writes to the given io.Writer. func NewWriter(name string, w io.Writer) (*Logger, error) { mw := &ioWriterMsgWriter{w} return New(name, mw) } // Error ouput, usefull for testing. var stderr io.Writer = os.Stderr // NewConsole creates a new logger that writes to error output (os.Stderr). func NewConsole(name string) (*Logger, error) { return NewWriter(name, stderr) }
package logger import ( "io" "os" ) type ioWriterMsgWriter struct { w io.Writer } func (iw *ioWriterMsgWriter) Write(msg Msg) error { bytes := append(msg.Bytes(), '\n') n, err := iw.w.Write(bytes) if err != nil { return err } else if n != len(bytes) { return io.ErrShortWrite } return err } func (iw *ioWriterMsgWriter) Close() error { return nil } // NewWriter creates a new logger that writes to the given io.Writer. func NewWriter(name string, w io.Writer) (*Logger, error) { mw := &ioWriterMsgWriter{w} return New(name, mw) } // Error ouput, usefull for testing. var stderr io.Writer = os.Stderr // NewConsole creates a new logger that writes to error output (os.Stderr). func NewConsole(name string) (*Logger, error) { return NewWriter(name, stderr) }
Fix deleting of empty obj
'use strict'; /** * Require modules. */ var isObject = require('is-object'); /** * Pick values from object except the given keys. * * @param {object} obj * @param {array|string} * * @return {object} */ module.exports = function except(obj, keys) { if (!isObject(obj)) { throw new Error('`obj` should be object'); } if (typeof keys === 'string') { keys = [keys]; } if (keys instanceof Array === false) { throw new Error('`keys` should be array'); } for (var i = 0, l = keys.length; i < l; i++) { var parts = keys[i].split('.'); var first = parts.shift(); var value = obj[first]; if (isObject(value) && parts.length > 0) { except(obj[first], parts); if (isObject(obj[first]) && !Object.keys(obj[first]).length) { delete obj[first]; } } else { delete obj[first]; } } /* if (isObject(obj)) { if (!Object.keys(obj).length) { delete obj[first]; } } else { delete obj[first]; } } */ return obj; };
'use strict'; /** * Require modules. */ var isObject = require('is-object'); /** * Pick values from object except the given keys. * * @param {object} obj * @param {array|string} * * @return {object} */ module.exports = function except(obj, keys) { if (!isObject(obj)) { throw new Error('`obj` should be object'); } if (typeof keys === 'string') { keys = [keys]; } if (keys instanceof Array === false) { throw new Error('`keys` should be array'); } for (var i = 0, l = keys.length; i < l; i++) { var parts = keys[i].split('.'); var first = parts.shift(); var value = obj[first]; if (isObject(value) && parts.length > 0) { except(obj[first], parts); delete obj[first]; } if (obj[first] !== undefined) { delete obj[first]; } } return obj; };
Allow a null filter to skip ribbonizing
package com.github.gfx.ribbonizer.plugin; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.function.Consumer; import java.util.stream.Stream; import javax.imageio.ImageIO; public class Ribbonizer { final File inputFile; final File outputFile; final BufferedImage image; public Ribbonizer(File inputFile, File outputFile) throws IOException { this.inputFile = inputFile; this.outputFile = outputFile; image = ImageIO.read(inputFile); } public void save() throws IOException { outputFile.getParentFile().mkdirs(); ImageIO.write(image, "png", outputFile); } public void process(Stream<Consumer<BufferedImage>> filters) { filters.forEach(new Consumer<Consumer<BufferedImage>>() { @Override public void accept(Consumer<BufferedImage> filter) { if (filter != null) { filter.accept(image); } } }); } }
package com.github.gfx.ribbonizer.plugin; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.function.Consumer; import java.util.stream.Stream; import javax.imageio.ImageIO; public class Ribbonizer { final File inputFile; final File outputFile; final BufferedImage image; public Ribbonizer(File inputFile, File outputFile) throws IOException { this.inputFile = inputFile; this.outputFile = outputFile; image = ImageIO.read(inputFile); } public void save() throws IOException { outputFile.getParentFile().mkdirs(); ImageIO.write(image, "png", outputFile); } public void process(Stream<Consumer<BufferedImage>> filters) { filters.forEach(new Consumer<Consumer<BufferedImage>>() { @Override public void accept(Consumer<BufferedImage> filter) { filter.accept(image); } }); } }
Add some actions to settings
from PyQt4 import QtCore, QtGui from utilities.backend_config import Configuration from qt_interfaces.settings_ui_new import Ui_ClientConfiguration from utilities.log_manager import logger # Configuration Ui section class ClientConfigurationUI(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) # register UI self.client_configuration_ui = Ui_ClientConfiguration() self.client_configuration_ui.setupUi(self) self.configuration_manager = Configuration() QtCore.QObject.connect(self.client_configuration_ui.apply_bt, QtCore.SIGNAL("clicked()"), self.save_settings) # save settings action QtCore.QObject.connect(self.client_configuration_ui.cancel_bt, QtCore.SIGNAL("clicked()"), self.close) # close form def save_settings(self): # validate settings self.configuration_manager.save_client_configuration(self.client_configuration_ui) # save configuration QtGui.QMessageBox.about(self, "Success", "Configuration saved successfully!") def reset_settings_to_default(self): logger.debug(1)
from PyQt4 import QtCore, QtGui from utilities.backend_config import Configuration from qt_interfaces.settings_ui_new import Ui_ClientConfiguration from utilities.log_manager import logger # Configuration Ui section class ClientConfigurationUI(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) # register UI self.client_configuration_ui = Ui_ClientConfiguration() self.client_configuration_ui.setupUi(self) self.configuration_manager = Configuration() QtCore.QObject.connect(self.client_configuration_ui.apply_bt, QtCore.SIGNAL("clicked()"), self.save_settings) # valudate and register user def save_settings(self): # validate settings self.configuration_manager.save_client_configuration(self.client_configuration_ui) # save configuration def reset_settings_to_default(self): logger.debug(1)
Fix demo URLs for Dajngo 1.10
from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.views.generic.base import RedirectView from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailsearch.urls import frontend as wagtailsearch_frontend_urls from wagtail.wagtailsearch.signal_handlers import register_signal_handlers as wagtailsearch_register_signal_handlers import os wagtailsearch_register_signal_handlers() urlpatterns = [ # url(r'^blog/', include('blog.urls', namespace="blog")), url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), # url(r'^comments/', include('django_comments_xtd.urls')), url(r'', include(wagtail_urls)), url(r'^docs/', include(wagtaildocs_urls)), ] if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL + 'images/', document_root=os.path.join(settings.MEDIA_ROOT, 'images')) urlpatterns += [ url(r'^favicon\.ico$', RedirectView.as_view(url=settings.STATIC_URL + 'demo/images/favicon.ico')) ]
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.views.generic.base import RedirectView from wagtail.wagtailcore import urls as wagtail_urls from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtaildocs import urls as wagtaildocs_urls from wagtail.wagtailsearch.urls import frontend as wagtailsearch_frontend_urls from wagtail.wagtailsearch.signal_handlers import register_signal_handlers as wagtailsearch_register_signal_handlers import os wagtailsearch_register_signal_handlers() urlpatterns = patterns('', # url(r'^blog/', include('blog.urls', namespace="blog")), url(r'^django-admin/', include(admin.site.urls)), url(r'^admin/', include(wagtailadmin_urls)), # url(r'^comments/', include('django_comments_xtd.urls')), url(r'', include(wagtail_urls)), url(r'^docs/', include(wagtaildocs_urls)), ) if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL + 'images/', document_root=os.path.join(settings.MEDIA_ROOT, 'images')) urlpatterns += patterns('', (r'^favicon\.ico$', RedirectView.as_view(url=settings.STATIC_URL + 'demo/images/favicon.ico')) )
Fix redundant open/close php tag
<?php echo "\n\n"; echo "================\n"; echo pluralize( count( $unittests ), 'unit test' ) . "\n"; echo "================\n\n"; foreach ( $unittests as $unittest ) { echo "\n"; ?>## Unit test: <?php echo $unittest->testName; ?>, with <?php echo pluralize( count( $unittest->tests ), 'test method' ); ?> ##<?php echo "\n\n"; foreach ( $unittest->tests as $test ) { echo $test->methodName . ":\n"; if ( $test->success ) { ?>PASS - <?php echo pluralize( $test->assertCount, 'assertion' ); echo "\n"; } else { ?>FAIL: <?php echo $test->error; echo "\n"; require 'views/testrun/calltrace.txt.php'; } } } ?>
<?php echo "\n\n"; echo "================\n"; echo pluralize( count( $unittests ), 'unit test' ) . "\n"; echo "================\n\n"; ?> <?php foreach ( $unittests as $unittest ) { echo "\n"; ?>## Unit test: <?php echo $unittest->testName; ?>, with <?php echo pluralize( count( $unittest->tests ), 'test method' ); ?> ##<?php echo "\n\n"; foreach ( $unittest->tests as $test ) { echo $test->methodName . ":\n"; if ( $test->success ) { ?>PASS - <?php echo pluralize( $test->assertCount, 'assertion' ); echo "\n"; } else { ?>FAIL: <?php echo $test->error; echo "\n"; require 'views/testrun/calltrace.txt.php'; } } } ?>
Remove remixmail from hosts for now
# This file contains python variables that configure Lamson for email processing. import logging import pymongo hostnames = ['kasm.clayadavis.net', 'openkasm.com', #'remixmail.com', ] # You may add additional parameters such as `username' and `password' if your # relay server requires authentication, `starttls' (boolean) or `ssl' (boolean) # for secure connections. relay_config = {'host': 'localhost', 'port': 8825} #receiver_config = {'host': 'localhost', 'port': 8823} #receiver_config = {'host': 'localhost', 'port': 25} receiver_config = {'host': '0.0.0.0', 'port': 25} handlers = ['app.handlers.kasm'] #router_defaults = {'host': '.+'} hosts = ['localhost', '127.0.0.1'] + hostnames router_defaults = {'host': '|'.join(['(%s)' % x for x in hosts])} template_config = {'dir': 'app', 'module': 'templates'} # the config/boot.py will turn these values into variables set in settings db_client = pymongo.MongoClient() db = db_client.kasm
# This file contains python variables that configure Lamson for email processing. import logging import pymongo hostnames = ['kasm.clayadavis.net', 'openkasm.com', 'remixmail.com'] # You may add additional parameters such as `username' and `password' if your # relay server requires authentication, `starttls' (boolean) or `ssl' (boolean) # for secure connections. relay_config = {'host': 'localhost', 'port': 8825} #receiver_config = {'host': 'localhost', 'port': 8823} #receiver_config = {'host': 'localhost', 'port': 25} receiver_config = {'host': '0.0.0.0', 'port': 25} handlers = ['app.handlers.kasm'] #router_defaults = {'host': '.+'} hosts = ['localhost', '127.0.0.1'] + hostnames router_defaults = {'host': '|'.join(['(%s)' % x for x in hosts])} template_config = {'dir': 'app', 'module': 'templates'} # the config/boot.py will turn these values into variables set in settings db_client = pymongo.MongoClient() db = db_client.kasm
Drop unused support to add decorators via entry points
# Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only from marv_node.io import Abort from marv_node.io import create_group from marv_node.io import create_stream from marv_node.io import fork from marv_node.io import get_logger from marv_node.io import get_requested from marv_node.io import get_stream from marv_node.io import make_file from marv_node.io import pull from marv_node.io import pull_all from marv_node.io import push from marv_node.io import set_header from marv_node.node import input, node from marv_node.tools import select from marv_webapi.tooling import api_endpoint from marv_webapi.tooling import api_group __all__ = [ 'Abort', 'api_endpoint', 'api_group', 'create_group', 'create_stream', 'fork', 'get_logger', 'get_requested', 'get_stream', 'input', 'make_file', 'node', 'pull', 'pull_all', 'push', 'select', 'set_header', ]
# Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import sys from pkg_resources import iter_entry_points from marv_node.io import Abort from marv_node.io import create_group from marv_node.io import create_stream from marv_node.io import fork from marv_node.io import get_logger from marv_node.io import get_requested from marv_node.io import get_stream from marv_node.io import make_file from marv_node.io import pull from marv_node.io import pull_all from marv_node.io import push from marv_node.io import set_header from marv_node.node import input, node from marv_node.tools import select from marv_webapi.tooling import api_endpoint from marv_webapi.tooling import api_group __all__ = [ 'Abort', 'api_endpoint', 'api_group', 'create_group', 'create_stream', 'fork', 'get_logger', 'get_requested', 'get_stream', 'input', 'make_file', 'node', 'pull', 'pull_all', 'push', 'select', 'set_header', ] MODULE = sys.modules[__name__] for ep in iter_entry_points(group='marv_deco'): assert not hasattr(MODULE, ep.name) setattr(MODULE, ep.name, ep.load()) del MODULE
Allow the session expiration length to be configurable
var MongoClient = require('mongodb').MongoClient; module.exports = { init: function(expressConfig, session, cb) { var self = this; var MongoStore = require('connect-mongo')(session); MongoClient.connect(expressConfig.config.url, function(err, mongo) { if (err) { return cb(err); } self.store = new MongoStore({ db: mongo, ttl: expressConfig.config.ttl || 14 * 24 * 60 * 60 // = 14 days. Default }); self.db = mongo; return cb(null); }); }, verifySession: function(token, cb) { //For a given session token, there should only be a maximum of 1 this.db.collection('sessions').findOne({ '_id': token }, function(err, foundSession) { //For the session to be valid, the expiry date must be greater than now. var valid = !err && foundSession && new Date() < new Date(foundSession.expires); foundSession.isValid = valid; return cb(err, foundSession); }); }, revokeSession: function(token, cb) { this.db.collection('sessions').deleteOne({ '_id': token }, cb); }, defaultConfig: { url: 'mongodb://localhost:27017/raincatcher-demo-auth-session-store' } };
var MongoClient = require('mongodb').MongoClient; module.exports = { init: function(expressConfig, session, cb) { var self = this; var MongoStore = require('connect-mongo')(session); MongoClient.connect(expressConfig.config.url, function(err, mongo) { if (err) { return cb(err); } self.store = new MongoStore({db: mongo}); self.db = mongo; return cb(null); }); }, verifySession: function(token, cb) { //For a given session token, there should only be a maximum of 1 this.db.collection('sessions').findOne({ '_id': token }, function(err, foundSession) { //For the session to be valid, the expiry date must be greater than now. var valid = !err && foundSession && new Date() < new Date(foundSession.expires); foundSession.isValid = valid; return cb(err, foundSession); }); }, revokeSession: function(token, cb) { this.db.collection('sessions').deleteOne({ '_id': token }, cb); }, defaultConfig: { url: 'mongodb://localhost:27017/raincatcher-demo-auth-session-store' } };
Add another test case for the CustomPropertyProvider.
package de.gurkenlabs.litiengine.environment.tilemap.xml; import java.util.ArrayList; import org.junit.Test; import junit.framework.Assert; public class CustomPropertyProviderTests { @Test public void testSetCustomProperty() { CustomPropertyProvider propProvider = new CustomPropertyProvider(); propProvider.setCustomProperty("test", "testvalue"); Assert.assertEquals("testvalue", propProvider.getCustomProperty("test")); Assert.assertNull(propProvider.getCustomProperty("test2")); Assert.assertEquals(1, propProvider.getAllCustomProperties().size()); propProvider.setCustomProperty("test", "testvalue2"); Assert.assertEquals("testvalue2", propProvider.getCustomProperty("test")); ArrayList<Property> props = new ArrayList<>(); props.add(new Property("test2", "testvalue3")); props.add(new Property("test3", "testvalue4")); propProvider.setCustomProperties(props); Assert.assertEquals(2, propProvider.getAllCustomProperties().size()); Assert.assertEquals("testvalue3", propProvider.getCustomProperty("test2")); Assert.assertEquals("testvalue4", propProvider.getCustomProperty("test3")); propProvider.setCustomProperties(null); Assert.assertNull(propProvider.getAllCustomProperties()); } }
package de.gurkenlabs.litiengine.environment.tilemap.xml; import java.util.ArrayList; import org.junit.Test; import junit.framework.Assert; public class CustomPropertyProviderTests { @Test public void testSetCustomProperty() { CustomPropertyProvider propProvider = new CustomPropertyProvider(); propProvider.setCustomProperty("test", "testvalue"); Assert.assertEquals("testvalue", propProvider.getCustomProperty("test")); Assert.assertNull(propProvider.getCustomProperty("test2")); Assert.assertEquals(1, propProvider.getAllCustomProperties().size()); propProvider.setCustomProperty("test", "testvalue2"); Assert.assertEquals("testvalue2", propProvider.getCustomProperty("test")); ArrayList<Property> props = new ArrayList<>(); props.add(new Property("test2", "testvalue3")); props.add(new Property("test3", "testvalue4")); propProvider.setCustomProperties(props); Assert.assertEquals(2, propProvider.getAllCustomProperties().size()); Assert.assertEquals("testvalue3", propProvider.getCustomProperty("test2")); Assert.assertEquals("testvalue4", propProvider.getCustomProperty("test3")); } }
Use ros-logging instead of print
import math from dynamic_stack_decider.abstract_action_element import AbstractActionElement class PatternSearch(AbstractActionElement): def __init__(self, blackboard, dsd, parameters=None): super(PatternSearch, self).__init__(blackboard, dsd, parameters) self.index = 0 self.pattern = self.blackboard.config['search_pattern'] def perform(self, reevaluate=False): head_pan, head_tilt = self.pattern[int(self.index)] # Convert to radians head_pan = head_pan / 180.0 * math.pi head_tilt = head_tilt / 180.0 * math.pi rospy.logdebug_throttle_identical(1, f"Searching at {head_pan}, {head_tilt}") self.blackboard.head_capsule.send_motor_goals(head_pan, head_tilt, 1.5, 1.5) # Increment index self.index = (self.index + 0.2) % len(self.pattern)
import math from dynamic_stack_decider.abstract_action_element import AbstractActionElement class PatternSearch(AbstractActionElement): def __init__(self, blackboard, dsd, parameters=None): super(PatternSearch, self).__init__(blackboard, dsd, parameters) self.index = 0 self.pattern = self.blackboard.config['search_pattern'] def perform(self, reevaluate=False): head_pan, head_tilt = self.pattern[int(self.index)] # Convert to radians head_pan = head_pan / 180.0 * math.pi head_tilt = head_tilt / 180.0 * math.pi print("Searching at {}, {}".format(head_pan, head_tilt)) self.blackboard.head_capsule.send_motor_goals(head_pan, head_tilt, 1.5, 1.5) # Increment index self.index = (self.index + 0.2) % len(self.pattern)
Make list objects return the embedded resource data again
from .Base import Base class List(Base): def __init__(self, result, object_type): Base.__init__(self, result) self.object_type = object_type def getResourceName(self): return self.object_type.__name__.lower() + 's' def __iter__(self): for item in self['_embedded'][self.getResourceName()]: yield self.object_type(item) def getTotalCount(self): if 'totalCount' not in self: return None return self['totalCount'] def getOffset(self): if 'offset' not in self: return None return self['offset'] def getCount(self): if 'count' not in self: return None return self['count']
from .Base import Base class List(Base): def __init__(self, result, object_type): Base.__init__(self, result) self.object_type = object_type def __iter__(self): for item in self['data']: yield self.object_type(item) def getTotalCount(self): if 'totalCount' not in self: return None return self['totalCount'] def getOffset(self): if 'offset' not in self: return None return self['offset'] def getCount(self): if 'count' not in self: return None return self['count']
Fix IATISerializer.from_etree() so it uses iati-xslt.xsl
# -*- coding: utf-8 -*- # Akvo RSR is covered by the GNU Affero General Public License. # See more details in the license.txt file located at the root folder of the Akvo RSR module. # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. from lxml import etree import os from tastypie.serializers import Serializer class IATISerializer(Serializer): def from_etree(self, data): """ transform the iati-activity XML into "tastypie compliant" XML using the 'iati-xslt.xsl' stylesheet """ if data.tag == 'iati-activity': with open(os.path.join(os.path.dirname(__file__),'xml', 'iati-xslt.xsl'), 'r') as f: iati_xslt = f.read() etree_xml = etree.XML(iati_xslt) etree_xslt = etree.XSLT(etree_xml) tasty_xml = etree_xslt(data) return self.from_etree(tasty_xml.getroot()) else: return super(IATISerializer, self).from_etree(data)
# -*- coding: utf-8 -*- # Akvo RSR is covered by the GNU Affero General Public License. # See more details in the license.txt file located at the root folder of the Akvo RSR module. # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. from lxml import etree import os from tastypie.serializers import Serializer class IATISerializer(Serializer): def from_etree(self, data): """ transform the iati-activity XML into "tastypie compliant" XML using the 'iati-xslt.xml' stylesheet """ if data.tag == 'iati-activity': with open(os.path.join(os.path.dirname(__file__),'xml', 'iati-xslt.xml'), 'r') as f: iati_xslt = f.read() etree_xml = etree.XML(iati_xslt) etree_xslt = etree.XSLT(etree_xml) tasty_xml = etree_xslt(data) return self.from_etree(tasty_xml.getroot()) else: return super(IATISerializer, self).from_etree(data)
Replace template to component. Use component
"use strict"; const angular = require("angular"); function homeRouting($urlRouterProvider, $stateProvider) { $urlRouterProvider.otherwise("/home"); $stateProvider .state("home", { url: "/home", //template: require("./views/home.html"), // include small templates into routing configuration component: "homeComponent", lazyLoad: ($transition$) => { const $ocLazyLoad = $transition$.injector().get("$ocLazyLoad"); return new Promise((resolve, reject) => { require.ensure([], () => { // load whole module const module = require("./home"); $ocLazyLoad.load({ name: "home" }); if (module.name) { resolve(module.name); } else { reject("Ooops, somethig went wrong!"); } }); }); } }) .state("home.about", { url: "/about", template: require("./views/home.about.html"), controller: "HomeAboutController as vm", }); } export default angular .module("home.routing", []) .config(homeRouting);
"use strict"; const angular = require("angular"); function homeRouting($urlRouterProvider, $stateProvider) { $urlRouterProvider.otherwise("/home"); $stateProvider .state("home", { url: "/home", template: require("./views/home.html"), // include small templates into routing configuration lazyLoad: ($transition$) => { const $ocLazyLoad = $transition$.injector().get("$ocLazyLoad"); return new Promise((resolve, reject) => { require.ensure([], () => { // load whole module const module = require("./home"); $ocLazyLoad.load({ name: "home" }); if (module.name) { resolve(module.name); } else { reject("Ooops, somethig went wrong!"); } }); }); } }) .state("home.about", { url: "/about", template: require("./views/home.about.html"), controller: "HomeAboutController as vm", }); } export default angular .module("home.routing", []) .config(homeRouting);
Change http client request body verbose level
package core import ( "io/ioutil" "net" "net/http" ) var ( // HTTP stuff tr *http.Transport client *http.Client ) // Custom dial for Docker unix socket func unixSocketDial(proto, addr string) (conn net.Conn, err error) { return net.Dial("unix", DGConfig.Docker.UnixSocketPath) } /* Initialize API Client */ func InitAPIClient() { tr = &http.Transport{ Dial: unixSocketDial, } client = &http.Client{Transport: tr} } /* Do HTTP request on API */ func HTTPReq(path string) (int, string) { var resp *http.Response // Docker API response var body []byte // Docker API response body var err error // Error handling // HTTP Get request on the docker unix socket resp, err = client.Get("http://docker" + path) if err != nil { l.Error("Error: http request:", err) return 400, "" } // Read the body body, err = ioutil.ReadAll(resp.Body) if err != nil { l.Error("Error: http response body:", err) return 400, "" } l.Silly("Docker API response body:", "\n"+string(body)) // Return HTTP status code + body return resp.StatusCode, string(body) }
package core import ( "io/ioutil" "net" "net/http" ) var ( // HTTP stuff tr *http.Transport client *http.Client ) // Custom dial for Docker unix socket func unixSocketDial(proto, addr string) (conn net.Conn, err error) { return net.Dial("unix", DGConfig.Docker.UnixSocketPath) } /* Initialize API Client */ func InitAPIClient() { tr = &http.Transport{ Dial: unixSocketDial, } client = &http.Client{Transport: tr} } /* Do HTTP request on API */ func HTTPReq(path string) (int, string) { var resp *http.Response // Docker API response var body []byte // Docker API response body var err error // Error handling // HTTP Get request on the docker unix socket resp, err = client.Get("http://docker" + path) if err != nil { l.Error("Error: http request:", err) return 400, "" } // Read the body body, err = ioutil.ReadAll(resp.Body) if err != nil { l.Error("Error: http response body:", err) return 400, "" } l.Debug("Docker API response body:", "\n"+string(body)) // Return HTTP status code + body return resp.StatusCode, string(body) }
Add MustFindBox method to Config
package rice // LocateMethod defines how a box is located. type LocateMethod int const ( LocateFS = LocateMethod(iota) // Locate on the filesystem according to package path. LocateAppended // Locate boxes appended to the executable. LocateEmbedded // Locate embedded boxes. LocateWorkingDirectory // Locate on the binary working directory ) // Config allows customizing the box lookup behavior. type Config struct { // LocateOrder defines the priority order that boxes are searched for. By // default, the package global FindBox searches for embedded boxes first, // then appended boxes, and then finally boxes on the filesystem. That // search order may be customized by provided the ordered list here. Leaving // out a particular method will omit that from the search space. For // example, []LocateMethod{LocateEmbedded, LocateAppended} will never search // the filesystem for boxes. LocateOrder []LocateMethod } // FindBox searches for boxes using the LocateOrder of the config. func (c *Config) FindBox(boxName string) (*Box, error) { return findBox(boxName, c.LocateOrder) } // MustFindBox searches for boxes using the LocateOrder of the config, like // FindBox does. It does not return an error, instead it panics when an error // occurs. func (c *Config) MustFindBox(boxName string) *Box { box, err := findBox(boxName, c.LocateOrder) if err != nil { panic(err) } return box }
package rice // LocateMethod defines how a box is located. type LocateMethod int const ( LocateFS = LocateMethod(iota) // Locate on the filesystem according to package path. LocateAppended // Locate boxes appended to the executable. LocateEmbedded // Locate embedded boxes. LocateWorkingDirectory // Locate on the binary working directory ) // Config allows customizing the box lookup behavior. type Config struct { // LocateOrder defines the priority order that boxes are searched for. By // default, the package global FindBox searches for embedded boxes first, // then appended boxes, and then finally boxes on the filesystem. That // search order may be customized by provided the ordered list here. Leaving // out a particular method will omit that from the search space. For // example, []LocateMethod{LocateEmbedded, LocateAppended} will never search // the filesystem for boxes. LocateOrder []LocateMethod } // FindBox searches for boxes using the LocateOrder of the config. func (c *Config) FindBox(boxName string) (*Box, error) { return findBox(boxName, c.LocateOrder) }
Move build status to beginning of message
let Config = require('../../config'); let url = require('url'); let webHook = url.resolve(Config.app.url, '/codeship/'); class FormatterService { format(type, build) { return defaultFormat(build) } getStartMessage(chatId) { let hook = this.getWebHook(chatId); return `${FormatterService.EMOJI.ship} Hi! I see you want to receive Codeship notifications. Just add this URL as a Webhook to your Codeship notification settings to receive notifications in this conversation. To receive <b>only failing builds</b> (and the recovering builds) ${hook} To receive <b>all builds</b> (succeeding and failing) ${hook}?mode=all @codeship_bot by @dominic0`; } getWebHook(chatId) { return url.resolve(webHook, `${chatId}`); } } FormatterService.EMOJI = { ship: '\u{1F6A2}', success: '\u{2705}', error: '\u{274C}' }; function defaultFormat(build) { return `${FormatterService.EMOJI[build.status] || ''} <b>${build.project_name}</b> - <code>${build.branch}</code> <b>${build.committer}</b>: ${build.message} <a href="${build.build_url}">Open on Codeship</a>`; } module.exports = new FormatterService();
let Config = require('../../config'); let url = require('url'); let webHook = url.resolve(Config.app.url, '/codeship/'); class FormatterService { format(type, build) { return defaultFormat(build) } getStartMessage(chatId) { let hook = this.getWebHook(chatId); return `${FormatterService.EMOJI.ship} Hi! I see you want to receive Codeship notifications. Just add this URL as a Webhook to your Codeship notification settings to receive notifications in this conversation. To receive <b>only failing builds</b> (and the recovering builds) ${hook} To receive <b>all builds</b> (succeeding and failing) ${hook}?mode=all @codeship_bot by @dominic0`; } getWebHook(chatId) { return url.resolve(webHook, `${chatId}`); } } FormatterService.EMOJI = { ship: '\u{1F6A2}', success: '\u{2705}', error: '\u{274C}' }; function defaultFormat(build) { return `${FormatterService.EMOJI.ship} <b>${build.project_name}</b> - <code>${build.branch}</code> ${FormatterService.EMOJI[build.status] || ''} <b>${build.committer}</b>: ${build.message} <a href="${build.build_url}">Open on Codeship</a>`; } module.exports = new FormatterService();
Fix unacceptably light-hearted string in serious business mode Summary: A serious business lost a bunch of serious business partners today because of this string, I assume. Test Plan: Enabled serious mode, clicked button, was relieved to see no jokes. Reviewers: btrahan Reviewed By: btrahan CC: aran Differential Revision: https://secure.phabricator.com/D6799
<?php final class PhabricatorNotificationClearController extends PhabricatorNotificationController { public function processRequest() { $request = $this->getRequest(); $user = $request->getUser(); if ($request->isDialogFormPost()) { $table = new PhabricatorFeedStoryNotification(); queryfx( $table->establishConnection('w'), 'UPDATE %T SET hasViewed = 1 WHERE userPHID = %s AND hasViewed = 0', $table->getTableName(), $user->getPHID()); return id(new AphrontReloadResponse()) ->setURI('/notification/'); } $dialog = new AphrontDialogView(); $dialog->setUser($user); $dialog->setTitle('Really mark all notifications as read?'); $is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business'); if ($is_serious) { $dialog->appendChild( pht( "All unread notifications will be marked as read. You can not ". "undo this action.")); } else { $dialog->appendChild( pht( "You can't ignore your problems forever, you know.")); } $dialog->addCancelButton('/notification/'); $dialog->addSubmitButton('Mark All Read'); return id(new AphrontDialogResponse())->setDialog($dialog); } }
<?php final class PhabricatorNotificationClearController extends PhabricatorNotificationController { public function processRequest() { $request = $this->getRequest(); $user = $request->getUser(); if ($request->isDialogFormPost()) { $table = new PhabricatorFeedStoryNotification(); queryfx( $table->establishConnection('w'), 'UPDATE %T SET hasViewed = 1 WHERE userPHID = %s AND hasViewed = 0', $table->getTableName(), $user->getPHID()); return id(new AphrontReloadResponse()) ->setURI('/notification/'); } $dialog = new AphrontDialogView(); $dialog->setUser($user); $dialog->setTitle('Really mark all notifications as read?'); $dialog->appendChild( "You can't ignore your problems forever, you know."); $dialog->addCancelButton('/notification/'); $dialog->addSubmitButton('Mark All Read'); return id(new AphrontDialogResponse())->setDialog($dialog); } }
Fix logic error in error flag handling
package main import ( "fmt" "os" "os/exec" ) func proto_0_0(inFlag, outFlag bool, errFlag, workdir string, args []string) error { proc := exec.Command(args[0], args[1:]...) proc.Dir = workdir done := make(chan bool) done_count := 0 done_count += wrapStdin(proc, os.Stdin, inFlag, done) if outFlag { done_count += wrapStdout(proc, os.Stdout, 'o', done) } switch errFlag { case "out": if outFlag { done_count += wrapStderr(proc, os.Stdout, 'o', done) } case "err": done_count += wrapStderr(proc, os.Stdout, 'e', done) case "nil": // no-op default: fmt.Fprintf(os.Stderr, "undefined redirect: '%v'\n", errFlag) fatal("undefined redirect") } err := proc.Run() for i := 0; i < done_count; i++ { <-done } return err }
package main import ( "fmt" "os" "os/exec" ) func proto_0_0(inFlag, outFlag bool, errFlag, workdir string, args []string) error { proc := exec.Command(args[0], args[1:]...) proc.Dir = workdir done := make(chan bool) done_count := 0 done_count += wrapStdin(proc, os.Stdin, inFlag, done) if outFlag { done_count += wrapStdout(proc, os.Stdout, 'o', done) } if errFlag == "out" && outFlag { done_count += wrapStderr(proc, os.Stdout, 'o', done) } else if errFlag == "err" { done_count += wrapStderr(proc, os.Stdout, 'e', done) } else if errFlag != "nil" { fmt.Fprintf(os.Stderr, "undefined redirect: '%v'\n", errFlag) fatal("undefined redirect") } err := proc.Run() for i := 0; i < done_count; i++ { <-done } return err }
Use egal comparision in commonLeft
'use strict'; var every = Array.prototype.every , call = Function.prototype.call , is = require('../../Object/is') , toArray = require('../../Object/to-array') , sortMethod = call.bind(require('../../Object/get-compare-by')('length')); module.exports = function (list) { var lists, r, l; lists = [this].concat(toArray(arguments)).sort(sortMethod); l = r = lists[0].length >>> 0; every.call(lists.slice(1), function (list) { var i; for (i = 0; i < l; ++i) { if (i > r) { break; } else if (!is(this[i], list[i])) { r = i; break; } } return r; }, lists[0]); return r; };
'use strict'; var every = Array.prototype.every , call = Function.prototype.call , toArray = require('../../Object/to-array') , sortMethod = call.bind(require('../../Object/get-compare-by')('length')); module.exports = function (list) { var lists, r, l; lists = [this].concat(toArray(arguments)).sort(sortMethod); l = r = lists[0].length >>> 0; every.call(lists.slice(1), function (list) { var i; for (i = 0; i < l; ++i) { if (i > r) { break; } else if (this[i] !== list[i]) { r = i; break; } } return r; }, lists[0]); return r; };
Update to v2.0.0 with py3 only support
#!/usr/bin/env python import os from setuptools import setup README_PATH = os.path.join(os.path.dirname(__file__), "README.md") with open(README_PATH, "r") as README_FILE: README = README_FILE.read() setup( name="parse_this", version="2.0.0", description=( "Makes it easy to create a command line interface for any " "function, method or classmethod.." ), long_description=README, packages=["parse_this", "test"], author="Bertrand Vidal", author_email="vidal.bertrand@gmail.com", download_url="https://pypi.python.org/pypi/parse_this", url="https://github.com/bertrandvidal/parse_this", license="License :: MIT", classifiers=[ "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Operating System :: OS Independent", "Programming Language :: Python :: 3 :: Only" "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", ], )
#!/usr/bin/env python import os from setuptools import setup README_PATH = os.path.join(os.path.dirname(__file__), "README.md") with open(README_PATH, "r") as README_FILE: README = README_FILE.read() setup( name="parse_this", version="1.0.3", description=( "Makes it easy to create a command line interface for any " "function, method or classmethod.." ), long_description=README, packages=["parse_this", "test"], author="Bertrand Vidal", author_email="vidal.bertrand@gmail.com", download_url="https://pypi.python.org/pypi/parse_this", url="https://github.com/bertrandvidal/parse_this", license="License :: MIT", classifiers=[ "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Operating System :: OS Independent", "Programming Language :: Python :: 3.9", ], )
Add Tests for Exception when adding/removing a listener for an unsupported event
package com.trello.navi; import com.trello.navi.internal.NaviEmitter; import org.junit.Test; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; public class EventHandlingTest { @Test public void handlesEventsNone() { NaviComponent component = NaviEmitter.createActivityEmitter(); assertTrue(component.handlesEvents()); } @Test public void handlesEventsSingle() { NaviComponent component = NaviEmitter.createActivityEmitter(); assertTrue(component.handlesEvents(Event.CREATE)); assertFalse(component.handlesEvents(Event.CREATE_VIEW)); } @Test public void handlesEventsMultiple() { NaviComponent component = NaviEmitter.createActivityEmitter(); assertTrue(component.handlesEvents(Event.CREATE, Event.START, Event.RESUME)); assertFalse(component.handlesEvents(Event.ATTACH, Event.CREATE_VIEW)); assertFalse(component.handlesEvents(Event.CREATE, Event.CREATE_VIEW)); } @Test(expected = IllegalArgumentException.class) public void throwOnRemoveUnsupportedListener() throws Exception { final NaviEmitter emitter = NaviEmitter.createActivityEmitter(); emitter.removeListener(Event.DETACH, mock(Listener.class)); } @Test(expected = IllegalArgumentException.class) public void throwOnAddUnsupportedListener() throws Exception { final NaviEmitter emitter = NaviEmitter.createActivityEmitter(); emitter.addListener(Event.DETACH, mock(Listener.class)); } }
package com.trello.navi; import com.trello.navi.internal.NaviEmitter; import org.junit.Test; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; public class EventHandlingTest { @Test public void handlesEventsNone() { NaviComponent component = NaviEmitter.createActivityEmitter(); assertTrue(component.handlesEvents()); } @Test public void handlesEventsSingle() { NaviComponent component = NaviEmitter.createActivityEmitter(); assertTrue(component.handlesEvents(Event.CREATE)); assertFalse(component.handlesEvents(Event.CREATE_VIEW)); } @Test public void handlesEventsMultiple() { NaviComponent component = NaviEmitter.createActivityEmitter(); assertTrue(component.handlesEvents(Event.CREATE, Event.START, Event.RESUME)); assertFalse(component.handlesEvents(Event.ATTACH, Event.CREATE_VIEW)); assertFalse(component.handlesEvents(Event.CREATE, Event.CREATE_VIEW)); } }
Verify that exception is raised if appropriate.
(function() { 'use strict'; exports.init = function(params) { var fs = require('fs'); var path = require('path'); var service = params['service']; var shell = require('shelljs'); if (!service) { throw new Error('missing required parameter "service"'); } createUser(); enableLogging(); writeUpstart(); enableDaemon(); function createUser() { console.log('creating user ' + service); } function writeUpstart() { //var srcFile = path.join(__dirname, 'template.upstart'); var srcFile = path.join(__dirname, 'foo.upstart'); console.log('upstart contents:'); fs.readFile(srcFile, 'utf8', function(err, data) { if (err) { throw new Error(err); } console.log(data); }); } function enableLogging() { var logPath = path.join(process.env.npm_config_quichean_logging_path, service); console.log('log path: ' + logPath); } function enableDaemon() { console.log('enabling daemon'); } }; })();
(function() { 'use strict'; exports.init = function(params) { var fs = require('fs'); var path = require('path'); var service = params['service']; var shell = require('shelljs'); if (!service) { throw new Error('missing required parameter "service"'); } createUser(); enableLogging(); writeUpstart(); enableDaemon(); function createUser() { console.log('creating user ' + service); } function writeUpstart() { var srcFile = path.join(__dirname, 'template.upstart'); console.log('upstart contents:'); fs.readFile(srcFile, 'utf8', function(err, data) { if (err) { return console.log(err); } console.log(data); }); } function enableLogging() { var logPath = path.join(process.env.npm_config_quichean_logging_path, service); console.log('log path: ' + logPath); } function enableDaemon() { console.log('enabling daemon'); } }; })();
Change lat/lng type to Number
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var photoSchema = new Schema({ description: { type: String }, submitted: { type: Date }, dateTaken: { type: Date }, flickrId: { type: String }, flickrUrl: { type: String }, latitude: { type: Number }, longitude: { type: Number }, uploadStatus: { type: String }, deleted: { type: Boolean }, user: { type: Schema.Types.ObjectId, ref: 'users' } }); // photoSchema.methods.toJSON = function () { // obj = this.toObject(); // delete obj._id; // delete obj.__v; // return obj; // }; //registered on mongoose models module.exports = mongoose.model('photos', photoSchema);
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var photoSchema = new Schema({ description: { type: String }, submitted: { type: Date }, dateTaken: { type: Date }, flickrId: { type: String }, flickrUrl: { type: String }, latitude: { type: String }, longitude: { type: String }, uploadStatus: { type: String }, deleted: { type: Boolean }, user: { type: Schema.Types.ObjectId, ref: 'users' } }); // photoSchema.methods.toJSON = function () { // obj = this.toObject(); // delete obj._id; // delete obj.__v; // return obj; // }; //registered on mongoose models module.exports = mongoose.model('photos', photoSchema);
Use dark theme for monaco editor.
let currentEditor; document.addEventListener("DOMContentLoaded", () => { const config = { apiKey: 'AIzaSyA1r_PfVDCXfTgoUNisci5Ag2MKEEwsZCE', databaseURL: "https://fulfillment-deco-step-2020.firebaseio.com", projectId: "fulfillment-deco-step-2020", }; firebase.initializeApp(config); const ref = getFirebaseRef(); require.config({ paths: {'vs': 'https://unpkg.com/monaco-editor@latest/min/vs'}}); require(['vs/editor/editor.main'], function() { createFirepad(ref, document.getElementById("firepad-container"), "javascript"); }); }); window.onresize = () => { currentEditor.layout(); } function createFirepad(ref, parent, language) { const editor = monaco.editor.create(parent, { language: language, theme: "vs-dark" }); Firepad.fromMonaco(ref, editor); currentEditor = editor; } function getFirebaseRef() { const workspaceID = getParam("workspaceID"); if (workspaceID != null) { return firebase.database().ref().child(workspaceID); } else { // If we were not given a workspace ID redirect to the home page. window.location.href = "/" } }
let currentEditor; document.addEventListener("DOMContentLoaded", () => { const config = { apiKey: 'AIzaSyA1r_PfVDCXfTgoUNisci5Ag2MKEEwsZCE', databaseURL: "https://fulfillment-deco-step-2020.firebaseio.com", projectId: "fulfillment-deco-step-2020", }; firebase.initializeApp(config); const ref = getFirebaseRef(); require.config({ paths: {'vs': 'https://unpkg.com/monaco-editor@latest/min/vs'}}); require(['vs/editor/editor.main'], function() { createFirepad(ref, document.getElementById("firepad-container"), "javascript"); }); }); window.onresize = () => { currentEditor.layout(); } function createFirepad(ref, parent, language) { const editor = monaco.editor.create(parent, { language: language }); Firepad.fromMonaco(ref, editor); currentEditor = editor; } function getFirebaseRef() { const workspaceID = getParam("workspaceID"); if (workspaceID != null) { return firebase.database().ref().child(workspaceID); } else { // If we were not given a workspace ID redirect to the home page. window.location.href = "/" } }
Install varnishadm instead of varnish
from distutils.core import setup setup( name='python-varnish', version='0.2.2', long_description=open('README.rst').read(), description='Simple Python interface for the Varnish management port', author='Justin Quick', author_email='justquick@gmail.com', url='http://github.com/justquick/python-varnish', scripts=['bin/varnish_manager'], py_modules=['varnishadm'], classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], )
from distutils.core import setup setup( name='python-varnish', version='0.2.2', long_description=open('README.rst').read(), description='Simple Python interface for the Varnish management port', author='Justin Quick', author_email='justquick@gmail.com', url='http://github.com/justquick/python-varnish', scripts=['bin/varnish_manager'], py_modules=['varnish'], classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], )
Fix bug when a deploymentBucket is used
const fse = require('fs-extra'); const path = require('path'); const {spawnSync} = require('child_process'); /** * pipenv install * @return {Promise} */ function pipfileToRequirements() { if (!this.options.usePipenv || !fse.existsSync(path.join(this.servicePath, 'Pipfile'))) return; this.serverless.cli.log('Generating requirements.txt from Pipfile...'); const res = spawnSync('pipenv', ['lock', '--requirements'], {cwd: this.servicePath}); if (res.error) { if (res.error.code === 'ENOENT') throw new Error(`pipenv not found! Install it with 'pip install pipenv'.`); throw new Error(res.error); } if (res.status != 0) throw new Error(res.stderr); fse.ensureDir(path.join(this.servicePath, '.serverless')); fse.writeFileSync(path.join(this.servicePath, '.serverless/requirements.txt'), res.stdout); }; module.exports = {pipfileToRequirements};
const fse = require('fs-extra'); const path = require('path'); const {spawnSync} = require('child_process'); /** * pipenv install * @return {Promise} */ function pipfileToRequirements() { if (!this.options.usePipenv || !fse.existsSync(path.join(this.servicePath, 'Pipfile'))) return; this.serverless.cli.log('Generating requirements.txt from Pipfile...'); const res = spawnSync('pipenv', ['lock', '--requirements'], {cwd: this.servicePath}); if (res.error) { if (res.error.code === 'ENOENT') throw new Error(`pipenv not found! Install it with 'pip install pipenv'.`); throw new Error(res.error); } if (res.status != 0) throw new Error(res.stderr); fse.writeFileSync(path.join(this.servicePath, '.serverless/requirements.txt'), res.stdout); }; module.exports = {pipfileToRequirements};
Revert "Added nickname and punct, removed parens" This reverts commit 061de1a57a95cd2911c06bb58c29a8e488b7387e.
import random ateball = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it yes", "Most likely", "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", ] def run(data, settings): if ('8ball' in data['payload']): return random.choice(ateball)
import random ateball = [ "It is certain.", "It is decidedly so.", "Without a doubt.", "Yes, definitely.", "You may rely on it.", "As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.", "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.", "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful.", ] def run(data, settings): if '8ball' in data['payload']: say = '{nick}: {fortune}'.format(nick=data['nick'], fortune=random.choice(ateball)) return say
Use import() instead of System.import()
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const loadPage = name=> ()=> import(`pages/${name}`) const pages = [ 'Home', 'Test', 'NotFound' ] .map(page=> ({ name: page, component: loadPage(page) })) .reduce((sum, { name, component })=> ({...sum, [name]: component}), {}) const options = { mode: 'history', scrollBehavior(to, from, savedPosition) { let ret = { x: 0, y: 0 } if (to.hash) { ret = {selector: to.hash} } else if (savedPosition) { ret = savedPosition } return ret }, routes: [{ path: '/', name: 'Home', component: pages.Home }, { path: '/test', name: 'Test', component: pages.Test }, { path: '*', name: 'NotFound', component: pages.NotFound }] } export default ()=> new Router(options)
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) // Codesplit based on route const Home = ()=> System.import('pages/Home') const Test = ()=> System.import('pages/Test') const NotFound = ()=> System.import('pages/NotFound') const options = { mode: 'history', scrollBehavior(to, from, savedPosition) { let ret = { x: 0, y: 0 } if (to.hash) { ret = {selector: to.hash} } else if (savedPosition) { ret = savedPosition } return ret }, routes: [{ path: '/', name: 'Home', component: Home }, { path: '/test', name: 'Test', component: Test }, { path: '*', name: 'NotFound', component: NotFound }] } export default ()=> new Router(options)
Use more descriptive unit test names
import unittest from libs.upbeatbot import UpBeatBot class TestUpbeatBot(unittest.TestCase): @classmethod def setUpClass(cls): cls.upbeat_bot = UpBeatBot() def test_get_animal_from_message_chosen_animal_returned(self): tweet = 'Hey @upbeatbot send me a dog!' animal = self.upbeat_bot._get_animal_from_message(tweet) self.assertEqual(animal, 'dog') def test__get_animal_from_message_random_animal_returned_with_text(self): tweet = 'Hey @upbeatbot send me a pic!' animal = self.upbeat_bot._get_animal_from_message(tweet) # Not really a test, just ensuring *something* is returned self.assertTrue(animal) def test__get_animal_from_message_random_returned_no_text(self): tweet = '@upbeatbot' # Minimum viable string animal = self.upbeat_bot._get_animal_from_message(tweet) # Ditto as above self.assertTrue(animal)
import unittest from libs.upbeatbot import UpBeatBot class TestUpbeatBot(unittest.TestCase): @classmethod def setUpClass(cls): cls.upbeat_bot = UpBeatBot() def test_chosen_animal_returned(self): tweet = 'Hey @upbeatbot send me a dog!' animal = self.upbeat_bot._get_animal_from_message(tweet) self.assertEqual(animal, 'dog') def test_random_animal_returned_with_text(self): tweet = 'Hey @upbeatbot send me a pic!' animal = self.upbeat_bot._get_animal_from_message(tweet) # Not really a test, just ensuring *something* is returned self.assertTrue(animal) def test_random_returned_no_text(self): tweet = '@upbeatbot' # Minimum viable string animal = self.upbeat_bot._get_animal_from_message(tweet) # Ditto as above self.assertTrue(animal)
Update component to pass tests.
var React = require('react'), DOM = React.DOM; module.exports = React.createClass({ propTypes: { version: React.PropTypes.string, year: React.PropTypes.number, author: React.PropTypes.string, email: React.PropTypes.string, githubUrl: React.PropTypes.string }, getDefaultProps: function () { return { year: new Date().getFullYear(), author: 'YourNameHere', email: 'your@email.com', githubUrl: null }; }, render: function () { return DOM.footer(null, [ DOM.hr(null, null), DOM.div({ className: 'row' }, DOM.div({ className: 'col-xs-12 text-center' }, [ DOM.small({ dangerouslySetInnerHTML: { __html: '&copy; ' + this.props.year + ' ' }}), DOM.a({ className: 'footer__author', href: 'mailto:' + this.props.email }, this.props.author), DOM.small({ className: 'footer__version'}, ' v' + this.props.version) ])), DOM.div({ className: 'row' }, DOM.div({ className: 'col-xs-12 text-center' }, DOM.small(null, DOM.a({ className: 'footer__url', href: this.props.githubUrl }, 'View sourcecode on github') ) ) ) ]); } });
var React = require('react'), DOM = React.DOM; module.exports = React.createClass({ propTypes: { version: React.PropTypes.string, year: React.PropTypes.number, author: React.PropTypes.string, email: React.PropTypes.string, githubUrl: React.PropTypes.string }, getDefaultProps: function () { return { year: new Date().getFullYear(), author: 'YourNameHere', email: 'your@email.com', githubUrl: null }; }, render: function () { return DOM.footer(null, [ DOM.hr(null, null), DOM.div({ className: 'row' }, DOM.div({ className: 'col-xs-12 text-center' }, [ DOM.small({ dangerouslySetInnerHTML: { __html: '&copy; ' + this.props.year + ' ' }}), DOM.a({ className: 'footer__author', href: 'mailto:' + this.props.email }, this.props.author), DOM.small(null, ' v' + this.props.version) ])), DOM.div({ className: 'row' }, DOM.div({ className: 'col-xs-12 text-center' }, DOM.small(null, DOM.a({ className: '', href: this.props.githubUrl }, 'View sourcecode on github') ) ) ) ]); } });
Make test runner work with blank mysql password
import os import os.path import configparser import shutil import subprocess # Setup print("Setting up...") if os.path.isfile("../halite.ini"): shutil.copyfile("../halite.ini", "temp.ini") shutil.copyfile("tests.ini", "../halite.ini") parser = configparser.ConfigParser() parser.read("../halite.ini") # Website tests print("Beginning website backend tests") passwordField = "" if parser["database"]["password"] == "" else "-p"+parser["database"]["password"] os.system("mysql -u "+parser["database"]["username"]+" "+passwordField+" < ../website/sql/Database.sql") subprocess.call(["phpunit", "--stderr", "website/"]) # Environment tests. print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8')) # Tear down print("Almost done...") if os.path.isfile("../temp.ini"): shutil.copyfile("temp.ini", "../halite.ini")
import os import os.path import configparser import shutil import subprocess # Setup print("Setting up...") if os.path.isfile("../halite.ini"): shutil.copyfile("../halite.ini", "temp.ini") shutil.copyfile("tests.ini", "../halite.ini") parser = configparser.ConfigParser() parser.read("../halite.ini") # Website tests print("Beginning website backend tests") os.system("mysql -u "+parser["database"]["username"]+" -p"+parser["database"]["password"]+" < ../website/sql/Database.sql") subprocess.call(["phpunit", "--stderr", "website/"]) # Environment tests. print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8')) # Tear down print("Almost done...") if os.path.isfile("../temp.ini"): shutil.copyfile("temp.ini", "../halite.ini")
Format Java files with google-java-format Change-Id: I97416eb0fbcadea7733900eea59e22000df3764b
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.rabbitmq.message; import com.google.common.base.Supplier; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.server.events.ProjectNameKeySerializer; import com.google.gerrit.server.events.SupplierSerializer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.inject.Provider; public class GsonProvider implements Provider<Gson> { @Override public Gson get() { return new GsonBuilder() .registerTypeAdapter(Supplier.class, new SupplierSerializer()) .registerTypeAdapter(Project.NameKey.class, new ProjectNameKeySerializer()) .create(); } }
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.rabbitmq.message; import com.google.common.base.Supplier; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.server.events.ProjectNameKeySerializer; import com.google.gerrit.server.events.SupplierSerializer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.inject.Provider; public class GsonProvider implements Provider<Gson> { @Override public Gson get() { return new GsonBuilder() .registerTypeAdapter(Supplier.class, new SupplierSerializer()) .registerTypeAdapter(Project.NameKey.class, new ProjectNameKeySerializer()) .create(); } }
Use chalk for ANSI codes fbshipit-source-id: 2b2b9f8
import { Diagnostics } from 'xdl'; import { print as envinfoPrint } from 'envinfo'; import chalk from 'chalk'; import simpleSpinner from '@expo/simple-spinner'; import log from '../log'; async function action(options) { log('Generating diagnostics report...'); log('You can join our slack here: https://slack.expo.io/.'); envinfoPrint(); console.log(chalk.underline('Diagnostics report:')); simpleSpinner.start(); const { url } = await Diagnostics.getDeviceInfoAsync({ uploadLogs: true, }); simpleSpinner.stop(); console.log(` ${url}\n`); log.raw(url); } export default program => { program .command('diagnostics [project-dir]') .description('Uploads diagnostics information and returns a url to share with the Expo team.') .asyncAction(action); };
import { Diagnostics } from 'xdl'; import { print as envinfoPrint } from 'envinfo'; import simpleSpinner from '@expo/simple-spinner'; import log from '../log'; async function action(options) { log('Generating diagnostics report...'); log('You can join our slack here: https://slack.expo.io/.'); envinfoPrint(); console.log(`\x1b[4mDiagnostics report:\x1b[0m`); simpleSpinner.start(); const { url } = await Diagnostics.getDeviceInfoAsync({ uploadLogs: true, }); simpleSpinner.stop(); console.log(` ${url}\n`); log.raw(url); } export default program => { program .command('diagnostics [project-dir]') .description('Uploads diagnostics information and returns a url to share with the Expo team.') .asyncAction(action); };
Fix code integrity check-warning link Signed-off-by: Marius Blüm <38edb439dbcce85f0f597d90d338db16e5438073@lineone.io>
/** * @author Lukas Reschke * * @copyright Copyright (c) 2015, ownCloud, Inc. * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * This gets only loaded if the integrity check has failed and then shows a notification */ $(document).ready(function(){ var text = t( 'core', '<a href="{docUrl}">There were problems with the code integrity check. More information…</a>', { docUrl: OC.generateUrl('/settings/admin/overview#security-warning') } ); OC.Notification.showHtml( text, { type: 'error', isHTML: true } ); });
/** * @author Lukas Reschke * * @copyright Copyright (c) 2015, ownCloud, Inc. * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * This gets only loaded if the integrity check has failed and then shows a notification */ $(document).ready(function(){ var text = t( 'core', '<a href="{docUrl}">There were problems with the code integrity check. More information…</a>', { docUrl: OC.generateUrl('/settings/admin#security-warning') } ); OC.Notification.showHtml( text, { type: 'error', isHTML: true } ); });
fix: Remove fname from error msg We cannot use `callee` in ESM :-(
import * as _ from "../deps/underscore-1.10.2-esm.js" import { to_write } from "./_writer.js" import { BiwaError } from "./error.js" // // assertions - type checks // const make_assert = function(check){ return function(/*args*/){ // We cannot use callee/caller in ESM (=JS strict mode) //var fname = arguments.callee.caller // ? arguments.callee.caller.fname // : ""; const fname = ""; check.apply(this, [fname].concat(_.toArray(arguments))); } } const make_simple_assert = function(type, test, _fname){ return make_assert(function(fname, obj, opt){ if(_fname) fname = _fname; const option = opt ? ("("+opt+"): ") : "" if(!test(obj)){ throw new BiwaError(option + type + " required, but got " + to_write(obj)); } }) } export { make_assert, make_simple_assert }
import * as _ from "../deps/underscore-1.10.2-esm.js" import { to_write } from "./_writer.js" import { BiwaError } from "./error.js" // // assertions - type checks // const make_assert = function(check){ return function(/*args*/){ var fname = arguments.callee.caller ? arguments.callee.caller.fname : ""; check.apply(this, [fname].concat(_.toArray(arguments))); } } const make_simple_assert = function(type, test, _fname){ return make_assert(function(fname, obj, opt){ if(_fname) fname = _fname; const option = opt ? ("("+opt+")") : "" if(!test(obj)){ throw new BiwaError(fname + option + ": " + type + " required, but got " + to_write(obj)); } }) } export { make_assert, make_simple_assert }
Replace all `@` with `%40`. Otherwise Twitter thinks the URL has ended.
$(function () { var host, encoded; if (location.search.length) { var text = unescape(location.search.substring(1)); converter = new Showdown.converter(); $("#message").html(converter.makeHtml(text)); $("#editor").hide(); } else { $("#nav").hide(); $("#message").remove(); $("#editor").show(); } if (location.port === 80) { host = location.protocol + "//" + location.host + "/?"; } else { host = "http://bigeasy.github.com/verbosity/?"; } $("#verbiage").keyup(function () { encoded = escape($(this).val()); }); $("#share").click(function () { url = escape(host + encoded); url = url.replace(/@/g, "%40"); text = escape("** Put your summary message here **\n\n"); location.href = "https://twitter.com/share?url=" + url + "&text=" + text; }); });
$(function () { var host, encoded; if (location.search.length) { var text = unescape(location.search.substring(1)); converter = new Showdown.converter(); $("#message").html(converter.makeHtml(text)); $("#editor").hide(); } else { $("#nav").hide(); $("#message").remove(); $("#editor").show(); } if (location.port === 80) { host = location.protocol + "//" + location.host + "/?" } else { host = "http://bigeasy.github.com/verbosity/?" } $("#verbiage").keyup(function () { encoded = escape($(this).val()); }); $("#share").click(function () { url = escape(host + encoded) text = escape("** Put your summary message here **\n\n") location.href = "https://twitter.com/share?url=" + url + "&text=" + text }); });
Add delimiter param to strToSlice func
// Copyright 2017 Jayson Grace. All rights reserved // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package main import ( "fmt" "os/exec" "regexp" "strings" "sync" ) // exeCmd executes an input command. // Once the command have successfully ben run, it will // return a string with the output result of the command. // TODO: Add concurrent operations to speed things up func exeCmd(cmd string, wg *sync.WaitGroup) string { fmt.Println("Running: ", cmd) parts := strings.Fields(cmd) head := parts[0] parts = parts[1:] out, err := exec.Command(head, parts...).Output() if err != nil { errmsg("%s", err) } warn("%s", out) wg.Done() return string(out) } // strToSlice takes a string and a delimiter in the // form of a regex. It will use this to split a string // into a slice, and return it. func strToSlice(s string, delimiter string) []string { r := regexp.MustCompile(delimiter) slice := r.FindAllString(s, -1) return slice }
// Copyright 2017 Jayson Grace. All rights reserved // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package main import ( "fmt" "os/exec" "regexp" "strings" "sync" ) // exeCmd executes an input command. // Once the command have successfully ben run, it will // return a string with the output result of the command. // TODO: Add concurrent operations to speed things up func exeCmd(cmd string, wg *sync.WaitGroup) string { fmt.Println("Running: ", cmd) parts := strings.Fields(cmd) head := parts[0] parts = parts[1:] out, err := exec.Command(head, parts...).Output() if err != nil { errmsg("%s", err) } warn("%s", out) wg.Done() return string(out) } // strToSlice takes a string and a delimiter in the // form of a regex. It will use this to split a string // into a slice, and return it. func strToSlice(s string, delimiter string) []string { r := regexp.MustCompile("[^\\s]+") slice := r.FindAllString(s, -1) return slice }
Update test with new default messaging
const aws = require('aws-sdk'); const config = require('../config'); const sendRegistrationEmail = require('../sendRegistrationEmail'); describe('sendRegistrationEmail', () => { let sandbox; beforeEach(() => { sandbox = sinon.sandbox.create(); }); afterEach(() => { sandbox.restore(); }); it('sends an email with default messaging using SES', () => { const sendEmail = sinon.spy(); sandbox.stub(aws, 'SES').returns({ sendEmail }); config.emailFromAddress = 'admin@rr.com'; sendRegistrationEmail('new@member.com') expect(sendEmail).to.have.been.calledWith({ Source: 'admin@rr.com', ReplyToAddresses: ['admin@rr.com'], Destination: { ToAddresses: ['new@member.com'] }, Message: { Subject: { Data: 'Thanks for joining!' }, Body: { Text: { Data: "We're excited to have you on board." }, }, }, }); }); });
const aws = require('aws-sdk'); const config = require('../config'); const sendRegistrationEmail = require('../sendRegistrationEmail'); describe('sendRegistrationEmail', () => { let sandbox; beforeEach(() => { sandbox = sinon.sandbox.create(); }); afterEach(() => { sandbox.restore(); }); it('sends an email with default messaging using SES', () => { const sendEmail = sinon.spy(); sandbox.stub(aws, 'SES').returns({ sendEmail }); config.emailFromAddress = 'admin@rr.com'; sendRegistrationEmail('new@member.com') expect(sendEmail).to.have.been.calledWith({ Source: 'admin@rr.com', ReplyToAddresses: ['admin@rr.com'], Destination: { ToAddresses: ['new@member.com'] }, Message: { Subject: { Data: 'Thanks for joining!' }, Body: { Text: { Data: "We're excited to have you on board" }, }, }, }); }); });
Use config to get Nova path prefix
<dropdown-trigger class="h-9 flex items-center" slot-scope="{toggle}" :handle-click="toggle"> <span class="text-90"> {{ auth()->user()->name }} </span> </dropdown-trigger> <dropdown-menu slot="menu" width="100" direction="rtl"> <ul class="list-reset"> <li> <a href="{{ config('nova.path') }}/resources/users/{{ auth()->user()->id }}" class="block no-underline text-90 hover:bg-30 p-3"> Profile </a> <a href="{{ route('nova.logout') }}" class="block no-underline text-90 hover:bg-30 p-3"> {{ __('Logout') }} </a> </li> </ul> </dropdown-menu>
<dropdown-trigger class="h-9 flex items-center" slot-scope="{toggle}" :handle-click="toggle"> <span class="text-90"> {{ auth()->user()->name }} </span> </dropdown-trigger> <dropdown-menu slot="menu" width="100" direction="rtl"> <ul class="list-reset"> <li> <a href="/nova/resources/users/{{ auth()->user()->id }}" class="block no-underline text-90 hover:bg-30 p-3"> Profile </a> <a href="{{ route('nova.logout') }}" class="block no-underline text-90 hover:bg-30 p-3"> {{ __('Logout') }} </a> </li> </ul> </dropdown-menu>
Include contributor in track feed
from django.conf.urls.defaults import url from tastypie.resources import ModelResource from tastypie.constants import ALL from tastypie import fields from jmbo.api import ModelBaseResource from music.models import Track, TrackContributor class TrackContributorResource(ModelBaseResource): class Meta: queryset = TrackContributor.permitted.all() resource_name = 'trackcontributor' def override_urls(self): return [ url(r"^(?P<resource_name>%s)/(?P<slug>[\w-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"), ] class TrackResource(ModelBaseResource): contributor = fields.ToManyField(TrackContributorResource, 'contributor', full=True) class Meta: queryset = Track.permitted.all() resource_name = 'track' filtering = { 'last_played': ALL } ordering = ['last_played'] def override_urls(self): return [ url(r"^(?P<resource_name>%s)/(?P<slug>[\w-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"), ]
from django.conf.urls.defaults import url from tastypie.resources import ModelResource from tastypie.constants import ALL from jmbo.api import ModelBaseResource from music.models import Track class TrackResource(ModelBaseResource): class Meta: queryset = Track.permitted.all() resource_name = 'track' filtering = { 'last_played': ALL } ordering = ['last_played'] def override_urls(self): return [ url(r"^(?P<resource_name>%s)/(?P<slug>[\w-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"), ]
Fix root API server route path (don't show non-rendering template)
var _ = require('underscore'); var cons = require('consolidate'); var path = require('path'); var SocketHook = require('./lib/socket-hook'); var _config = require('./lib/config/default'); var _hooks = {}; var STATIC_ROOT = path.join(__dirname, 'public'); module.exports = LoopbackHookSocket; function LoopbackHookSocket(loopbackApplication, options) { options = _.defaults(options, _config); loopbackApplication.set('loopback-hook-socket', options); if (options.enabled) { start(loopbackApplication, options); } } function start(loopbackApplication, options) { if (options.eventView) { loopbackApplication.use(options.mountPath, function (req, res, next) { loopbackApplication.engine('html', cons.swig); loopbackApplication.set('view engine', 'html'); loopbackApplication.set('views', STATIC_ROOT); loopbackApplication.use(loopbackApplication.loopback.static(STATIC_ROOT)); var events = SocketHook.formatRoutes(loopbackApplication); res.render('index.html', {events: events}); }); } var server = require('http').Server(loopbackApplication); var io = require('socket.io').listen(server); io.on('connection', function (socket) { _hooks[socket.id] = new SocketHook(loopbackApplication, socket, options); }); server.listen(options.port); }
var _ = require('underscore'); var cons = require('consolidate'); var path = require('path'); var SocketHook = require('./lib/socket-hook'); var _config = require('./lib/config/default'); var _hooks = {}; var STATIC_ROOT = path.join(__dirname, 'public'); module.exports = LoopbackHookSocket; function LoopbackHookSocket(loopbackApplication, options) { options = _.defaults(options, _config); loopbackApplication.set('loopback-hook-socket', options); if (options.enabled) { start(loopbackApplication, options); } } function start(loopbackApplication, options) { if (options.eventView) { loopbackApplication.engine('html', cons.swig); loopbackApplication.set('view engine', 'html'); loopbackApplication.set('views', STATIC_ROOT); loopbackApplication.use(loopbackApplication.loopback.static(STATIC_ROOT)); loopbackApplication.use(options.mountPath, function (req, res, next) { var events = SocketHook.formatRoutes(loopbackApplication); res.render('index', {events: events}); }); } var server = require('http').Server(loopbackApplication); var io = require('socket.io').listen(server); io.on('connection', function (socket) { _hooks[socket.id] = new SocketHook(loopbackApplication, socket, options); }); server.listen(options.port); }
Make onRemoved default in interface
/* * This file is part of Bisq. * * Bisq 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. * * Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.network.p2p.storage; import bisq.network.p2p.storage.payload.ProtectedStorageEntry; import java.util.Collection; public interface HashMapChangedListener { void onAdded(Collection<ProtectedStorageEntry> protectedStorageEntries); default void onRemoved(Collection<ProtectedStorageEntry> protectedStorageEntries) { // Often we are only interested in added data as there is no use case for remove } }
/* * This file is part of Bisq. * * Bisq 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. * * Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.network.p2p.storage; import bisq.network.p2p.storage.payload.ProtectedStorageEntry; import java.util.Collection; public interface HashMapChangedListener { void onAdded(Collection<ProtectedStorageEntry> protectedStorageEntries); @SuppressWarnings("UnusedParameters") void onRemoved(Collection<ProtectedStorageEntry> protectedStorageEntries); }
Add newline at the end of file
#!/usr/bin/env python import unittest import glob import sys def create_test_suite(mod): if mod is None: test_file_strings = glob.glob('jinger/test/test_*.py') module_strings = [str[0:len(str)-3].replace('/', '.') for str in test_file_strings] else: module_strings = ['jinger.test.test_%s' % (mod)] suites = [unittest.defaultTestLoader.loadTestsFromName(s) for s in module_strings] testSuite = unittest.TestSuite(suites) return testSuite if __name__ == '__main__': try: mod = sys.argv[1] except IndexError as e: mod = None testSuite = create_test_suite(mod); text_runner = unittest.TextTestRunner().run(testSuite)
#!/usr/bin/env python import unittest import glob import sys def create_test_suite(mod): if mod is None: test_file_strings = glob.glob('jinger/test/test_*.py') module_strings = [str[0:len(str)-3].replace('/', '.') for str in test_file_strings] else: module_strings = ['jinger.test.test_%s' % (mod)] suites = [unittest.defaultTestLoader.loadTestsFromName(s) for s in module_strings] testSuite = unittest.TestSuite(suites) return testSuite if __name__ == '__main__': try: mod = sys.argv[1] except IndexError as e: mod = None testSuite = create_test_suite(mod); text_runner = unittest.TextTestRunner().run(testSuite)
Fix posts factory content binding
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), 'remember_token' => str_random(10), ]; }); $factory->define(App\Post::class, function (Faker\Generator $faker) { return [ 'title' => $faker->sentence(6, true), 'content' => $faker->paragraphs(4, true), ]; });
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), 'remember_token' => str_random(10), ]; }); $factory->define(App\Post::class, function (Faker\Generator $faker) { return [ 'title' => $faker->sentence(6, true), 'body' => $faker->paragraphs(4, true), ]; });
Fix bug in Asset Extension tests.
<?php namespace League\Plates\Extension; class AssetTest extends \PHPUnit_Framework_TestCase { private $extension; public function setUp() { $this->extension = new Asset(realpath('tests/assets')); } public function testCanCreateExtension() { $this->assertInstanceOf('League\Plates\Extension\Asset', $this->extension); } public function testGetFunctionsReturnsAnArray() { $this->assertInternalType('array', $this->extension->getFunctions()); } public function testGetFunctionsReturnsAtLeastOneRecord() { $this->assertTrue(count($this->extension->getFunctions()) > 0); } public function testCachedAssetUrl() { $this->assertTrue($this->extension->cachedAssetUrl('styles.css') === 'styles.css?v=' . filemtime(realpath('tests/assets/styles.css'))); } public function testCachedAssetUrlUsingFilenameMethod() { $this->extension = new Asset(realpath('tests/assets'), true); $this->assertTrue($this->extension->cachedAssetUrl('styles.css') === 'styles.' . filemtime(realpath('tests/assets/styles.css')) . '.css'); } public function testFileNotFoundException() { $this->setExpectedException('LogicException'); $this->extension->cachedAssetUrl('404.css'); } }
<?php namespace League\Plates\Extension; class AssetTest extends \PHPUnit_Framework_TestCase { private $extension; public function setUp() { $this->extension = new Asset(realpath('tests/assets')); } public function testCanCreateExtension() { $this->assertInstanceOf('League\Plates\Extension\Asset', $this->extension); } public function testGetFunctionsReturnsAnArray() { $this->assertInternalType('array', $this->extension->getFunctions()); } public function testGetFunctionsReturnsAtLeastOneRecord() { $this->assertTrue(count($this->extension->getFunctions()) > 0); } public function testCachedAssetUrl() { $this->assertTrue($this->extension->cachedAssetUrl('styles.css') === 'styles.css?v=1384813172'); } public function testCachedAssetUrlUsingFilenameMethod() { $this->extension = new Asset(realpath('tests/assets'), true); $this->assertTrue($this->extension->cachedAssetUrl('styles.css') === 'styles.1384813172.css'); } public function testFileNotFoundException() { $this->setExpectedException('LogicException'); $this->extension->cachedAssetUrl('404.css'); } }
Update to latest blacklight facet wrapping helper
/*global Blacklight */ (function($) { 'use strict'; Blacklight.doResizeFacetLabelsAndCounts = function() { // adjust width of facet columns to fit their contents function longer(a, b) { return b.textContent.length - a.textContent.length; } $('ul.facet-values, ul.pivot-facet').each(function() { var longest = $(this) .find('span.facet-count') .sort(longer)[0]; if (longest && longest.textContent) { var width = longest.textContent.length + 1 + 'ch'; $(this) .find('.facet-count') .first() .width(width); } }); }; Blacklight.onLoad(function() { Blacklight.doResizeFacetLabelsAndCounts(); }); }(jQuery));
/*global Blacklight */ (function($) { 'use strict'; Blacklight.doResizeFacetLabelsAndCounts = function() { // adjust width of facet columns to fit their contents function longer (a,b){ return b.textContent.length - a.textContent.length; } $('ul.facet-values, ul.pivot-facet').each(function(){ var longest = $(this).find('span.facet-count').sort(longer).first(); var clone = longest.clone() .css('visibility','hidden').css('width', 'auto'); $('span.facet-count:visible:first').append(clone); $(this).find('.facet-count').first().width(clone.width()); clone.remove(); }); }; Blacklight.onLoad(function() { Blacklight.doResizeFacetLabelsAndCounts(); }); })(jQuery);
Use option.text instead of option.label.
/** * Patterns checkedflag - Add checked flag to checkbox labels * * Copyright 2013 Simplon B.V. - Wichert Akkerman */ define([ "jquery", "../registry", "../utils" ], function($, patterns, utils) { var select_option = { name: "select-option", trigger: "label select", init: function($el) { return $el .on("change.pat-select-option", select_option._onChange) .trigger("change"); }, destroy: function($el) { return $el.off(".pat-select-option"); }, _onChange: function() { var label = utils.findLabel(this); if (label!==null) { var title = (this.selectedIndex===-1) ? "" : this.options[this.selectedIndex].text; label.setAttribute("data-option", title); } } }; patterns.register(select_option); return select_option; });
/** * Patterns checkedflag - Add checked flag to checkbox labels * * Copyright 2013 Simplon B.V. - Wichert Akkerman */ define([ "jquery", "../registry", "../utils" ], function($, patterns, utils) { var select_option = { name: "select-option", trigger: "label select", init: function($el) { return $el .on("change.pat-select-option", select_option._onChange) .trigger("change"); }, destroy: function($el) { return $el.off(".pat-select-option"); }, _onChange: function() { var label = utils.findLabel(this); if (label!==null) { var title = (this.selectedIndex===-1) ? "" : this.options[this.selectedIndex].label; label.setAttribute("data-option", title); } } }; patterns.register(select_option); return select_option; });
Fix missing productDir config option
#!/usr/bin/env node import 'source-map-support/register' import yargs from 'yargs' import rc from 'rc' import {basename as pathBasename} from 'path' const config = rc('lenticular') yargs .commandDir('cmds') .demandCommand() .options({ 'product-name': { desc: 'Name of your product. Short and unique', default: config.productName || pathBasename(process.cwd()), group: 'Global Options:', }, 'build-region': { desc: `Region for product's build pipeline`, default: config.buildRegion || 'us-west-2', group: 'Global Options:', }, 'product-dir': { desc: `Path to the product (project) directory`, default: process.cwd(), group: 'Global Options:', } }) .group('help', 'Global Options:') .config(config) .help() .argv process.on('unhandledRejection', err => { throw err })
#!/usr/bin/env node import 'source-map-support/register' import yargs from 'yargs' import rc from 'rc' import {basename as pathBasename} from 'path' const config = rc('lenticular') yargs .commandDir('cmds') .demandCommand() .options({ 'product-name': { desc: 'Name of your product. Short and unique', default: config.productName || pathBasename(process.cwd()), group: 'Global Options:', }, 'build-region': { desc: `Region for product's build pipeline`, default: config.buildRegion || 'us-west-2', group: 'Global Options:', }, }) .group('help', 'Global Options:') .config(config) .help() .argv process.on('unhandledRejection', err => { throw err })
Remove senseless trace log of a function_memory_address
// Copyright 2014 Alea Soluciones SLL. All rights reserved. Use of this // source code is governed by a MIT-style license that can be found in the // LICENSE file. package crontask import ( "log" "time" "github.com/gorhill/cronexpr" ) type CronTask struct { task func() cronTime string } func New(task func(), cronTime string) *CronTask { return &CronTask{task, cronTime} } func (t *CronTask) Run() { go func() { for { nextTime := cronexpr.MustParse(t.cronTime).Next(time.Now()) log.Println("Next execution", nextTime) time.Sleep(nextTime.Sub(time.Now())) log.Println("Execution start") t.task() log.Println("Execution end") } }() }
// Copyright 2014 Alea Soluciones SLL. All rights reserved. Use of this // source code is governed by a MIT-style license that can be found in the // LICENSE file. package crontask import ( "log" "time" "github.com/gorhill/cronexpr" ) type CronTask struct { task func() cronTime string } func New(task func(), cronTime string) *CronTask { return &CronTask{task, cronTime} } func (t *CronTask) Run() { go func() { for { nextTime := cronexpr.MustParse(t.cronTime).Next(time.Now()) log.Println("Next execution", nextTime, t.task) time.Sleep(nextTime.Sub(time.Now())) log.Println("Execution start") t.task() log.Println("Execution end") } }() }
[TASK] Add helper.js to grunt watch
module.exports = function (grunt) { grunt.config.merge({ connect: { server: { options: { base: { path: 'build', options: { index: 'index.html' } }, livereload: true } } }, watch: { sources: { options: { livereload: true }, files: ["*.css", "app.js", "helper.js", "lib/**/*.js", "*.html"], tasks: ["dev"] }, config: { options: { reload: true }, files: ["Gruntfile.js", "tasks/*.js"], tasks: [] } } }); grunt.loadNpmTasks("grunt-contrib-connect"); grunt.loadNpmTasks("grunt-contrib-watch"); };
module.exports = function (grunt) { grunt.config.merge({ connect: { server: { options: { base: { path: 'build', options: { index: 'index.html' } }, livereload: true } } }, watch: { sources: { options: { livereload: true }, files: ["*.css", "app.js", "lib/**/*.js", "*.html"], tasks: ["dev"] }, config: { options: { reload: true }, files: ["Gruntfile.js", "tasks/*.js"], tasks: [] } } }); grunt.loadNpmTasks("grunt-contrib-connect"); grunt.loadNpmTasks("grunt-contrib-watch"); };
Remove extra point graphic from player
'use strict'; var Point = require('../../data/point'), Rect = require('../../data/rect'), TileGraphic = require('../../graphics/tile-graphic'), Animation = require('../../graphics/animation'); var url = '/assets/astrosheet.png'; module.exports = function(engine, entity, data) { var graphics = new Animation({ position: data.loc, direction: data.dir, url: url, width: 24, height: 24, frameTime: 100, frameMidpoint: new Point(12, 12), crop: new Rect(0, 0, 120, 120) }); graphics.defineLoop(exports.STAND, [5]); graphics.defineLoop(exports.WALK, [0, 1, 2, 3]); graphics.defineLoop(exports.JUMP, [7]); graphics.defineLoop(exports.DRAW, [15]); graphics.defineLoop(exports.SHOOT, [16, 17]); graphics.playLoop(exports.STAND); engine.renderer.table.attach(entity, graphics); return graphics; }; exports.WALK = 'walk'; exports.STAND = 'stand'; exports.JUMP = 'jump'; exports.SHOOT = 'shoot'; exports.DRAW = 'draw';
'use strict'; var Point = require('../../data/point'), Rect = require('../../data/rect'), TileGraphic = require('../../graphics/tile-graphic'), Animation = require('../../graphics/animation'); var url = '/assets/astrosheet.png', pointUrl = '/assets/point.png'; module.exports = function(engine, entity, data) { var graphics = new Animation({ position: data.loc, direction: data.dir, url: url, width: 24, height: 24, frameTime: 100, frameMidpoint: new Point(12, 12), crop: new Rect(0, 0, 120, 120) }); graphics.defineLoop(exports.STAND, [5]); graphics.defineLoop(exports.WALK, [0, 1, 2, 3]); graphics.defineLoop(exports.JUMP, [7]); graphics.defineLoop(exports.DRAW, [15]); graphics.defineLoop(exports.SHOOT, [16, 17]); graphics.playLoop(exports.STAND); engine.renderer.table.attach(entity, graphics); var pointGraphic = new TileGraphic(data.loc, data.dir, pointUrl, { x: 0, y: 0, width: 1, height: 1 }); engine.renderer.table.attach(entity, pointGraphic); return graphics; }; exports.WALK = 'walk'; exports.STAND = 'stand'; exports.JUMP = 'jump'; exports.SHOOT = 'shoot'; exports.DRAW = 'draw';
Refactor test to use matchers
package com.phsshp; import org.junit.Test; import java.io.File; import java.util.Arrays; import java.util.List; import static com.phsshp.testutils.matchers.MetricsMatcher.metricsMatching; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; public class MetricsReporterTest { @Test public void reportMetricsForJavaFiles() throws Exception { List<File> files = Arrays.asList( new File("src/test/resources/test-project/SomeFile.java"), new File("src/test/resources/test-project/pkg1/AnotherInPackage1.java")); List<Metrics> metrics = new MetricsReporter().report(files); assertThat(metrics, contains( metricsMatching("SomeFile.java", 1), metricsMatching("AnotherInPackage1.java", 3))); } }
package com.phsshp; import com.phsshp.testutils.matchers.MetricsMatcher; import org.junit.Test; import java.io.File; import java.util.Arrays; import java.util.List; import static com.phsshp.testutils.matchers.MetricsMatcher.metricsMatching; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class MetricsReporterTest { @Test public void reportMetricsForJavaFiles() throws Exception { // TODO: crappy test for now List<File> files = Arrays.asList( new File("src/test/resources/test-project/SomeFile.java"), new File("src/test/resources/test-project/pkg1/AnotherInPackage1.java")); List<Metrics> metrics = new MetricsReporter().report(files); assertThat(metrics.size(), is(2)); assertThat(metrics.get(0).getFile().getName(), equalTo("SomeFile.java")); assertThat(metrics.get(0).getValue(), equalTo(1)); assertThat(metrics.get(1).getFile().getName(), equalTo("AnotherInPackage1.java")); assertThat(metrics.get(1).getValue(), equalTo(3)); assertThat(metrics.get(0), metricsMatching("SomeFile.java", 1)); } }
Change min image size to 200x200
import { Meteor } from 'meteor/meteor'; import { $ } from 'meteor/jquery'; /* global cloudinary */ /** * Opens the Cloudinary Upload widget and sets the value of the input field with name equal to nameAttribute to the * resulting URL of the uploaded picture. * @param nameAttribute The value of the associated input field's name attribute. * @memberOf ui/components/form-fields */ export function openCloudinaryWidget(nameAttribute) { cloudinary.openUploadWidget( { cloud_name: Meteor.settings.public.cloudinary.cloud_name, upload_preset: Meteor.settings.public.cloudinary.upload_preset, sources: ['local', 'url', 'camera'], cropping: 'server', cropping_aspect_ratio: 1, max_file_size: '500000', max_image_width: '500', max_image_height: '500', min_image_width: '200', min_image_height: '200', }, (error, result) => { if (error) { console.log('Error during image upload: ', error); return; } // Otherwise get the form elements // console.log('Cloudinary results: ', result); const url = result[0].url; $(`input[name=${nameAttribute}]`).val(url); }); }
import { Meteor } from 'meteor/meteor'; import { $ } from 'meteor/jquery'; /* global cloudinary */ /** * Opens the Cloudinary Upload widget and sets the value of the input field with name equal to nameAttribute to the * resulting URL of the uploaded picture. * @param nameAttribute The value of the associated input field's name attribute. * @memberOf ui/components/form-fields */ export function openCloudinaryWidget(nameAttribute) { cloudinary.openUploadWidget( { cloud_name: Meteor.settings.public.cloudinary.cloud_name, upload_preset: Meteor.settings.public.cloudinary.upload_preset, sources: ['local', 'url', 'camera'], cropping: 'server', cropping_aspect_ratio: 1, max_file_size: '500000', max_image_width: '500', max_image_height: '500', min_image_width: '300', min_image_height: '300', }, (error, result) => { if (error) { console.log('Error during image upload: ', error); return; } // Otherwise get the form elements // console.log('Cloudinary results: ', result); const url = result[0].url; $(`input[name=${nameAttribute}]`).val(url); }); }
Switch component to solve body in body issues
package se.l4.dust.core.internal.template.components; import java.io.IOException; import se.l4.dust.api.template.Emittable; import se.l4.dust.api.template.TemplateEmitter; import se.l4.dust.api.template.TemplateOutputStream; import se.l4.dust.core.internal.template.TemplateEmitterImpl; public class DataContextSwitcher implements Emittable { private final Integer id; private final Emittable[] content; public DataContextSwitcher(Integer id, Emittable[] content) { this.id = id; this.content = content; } @Override public void emit(TemplateEmitter emitter, TemplateOutputStream out) throws IOException { TemplateEmitterImpl emitterImpl = (TemplateEmitterImpl) emitter; Integer old = emitterImpl.switchData(id); Integer oldC = emitterImpl.switchComponent(id); emitterImpl.emit(content); emitterImpl.switchComponent(oldC); emitterImpl.switchData(old); } @Override public String toString() { return "DataSwitch[id=" + id + "]"; } }
package se.l4.dust.core.internal.template.components; import java.io.IOException; import se.l4.dust.api.template.Emittable; import se.l4.dust.api.template.TemplateEmitter; import se.l4.dust.api.template.TemplateOutputStream; import se.l4.dust.core.internal.template.TemplateEmitterImpl; public class DataContextSwitcher implements Emittable { private final Integer id; private final Emittable[] content; public DataContextSwitcher(Integer id, Emittable[] content) { this.id = id; this.content = content; } @Override public void emit(TemplateEmitter emitter, TemplateOutputStream out) throws IOException { TemplateEmitterImpl emitterImpl = (TemplateEmitterImpl) emitter; Integer old = emitterImpl.switchData(id); emitterImpl.emit(content); emitterImpl.switchData(old); } @Override public String toString() { return "DataSwitch[id=" + id + "]"; } }
Remove old criuft. FIx. Partially fix export issue.
""" Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their support files in the ../docs/tutorial folder. """ import subprocess import os # Get the list of tutorial notebooks. tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)] # Run them in-place. for notebook in tutorial_notebooks: print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook), "--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])) subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook), "--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]) # Get the list of generated files. gened_files = [f for f in os.listdir(".") if (".py" not in f)] # Move them to where they need to be. Lowercase the filenames along the way, otherwise it causes issues once the # files are hosted. for file in gened_files: os.rename(file, "../docs/tutorial/{0}".format(file.lower()))
""" Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their support files in the ../docs/tutorial folder. """ import subprocess import os # Get the list of tutorial notebooks. tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in f) and ("checkpoints" not in f)] # Run them in-place. for notebook in tutorial_notebooks: print(" ".join(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook), "--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))])) subprocess.run(["jupyter", "nbconvert", "--to", "rst", "../notebooks/tutorial/{0}".format(notebook), "--output", "../../scripts/{0}".format(notebook.replace(".ipynb", ".rst"))]) # Get the list of generated files. gened_files = [f for f in os.listdir(".") if (".py" not in f)] # Move them to where they need to be. for file in gened_files: os.rename(file, "../docs/tutorial/{0}".format(file))