text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Allow HTTP client PRESERVE_AUTHORIZATION_KEY to be unset
package io.airlift.http.client.jetty; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClientTransport; import org.eclipse.jetty.client.HttpRequest; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.util.ssl.SslContextFactory; import java.net.URI; import static java.lang.Boolean.TRUE; import static org.eclipse.jetty.http.HttpHeader.AUTHORIZATION; class AuthorizationPreservingHttpClient extends HttpClient { private static final String PRESERVE_AUTHORIZATION_KEY = "airlift_preserve_authorization"; public AuthorizationPreservingHttpClient(HttpClientTransport transport, SslContextFactory sslContextFactory) { super(transport, sslContextFactory); } @Override protected Request copyRequest(HttpRequest oldRequest, URI newUri) { Request newRequest = super.copyRequest(oldRequest, newUri); if (isPreserveAuthorization(oldRequest)) { setPreserveAuthorization(newRequest, true); for (HttpField field : oldRequest.getHeaders()) { if (field.getHeader() == AUTHORIZATION) { newRequest.header(field.getName(), field.getValue()); } } } return newRequest; } public static void setPreserveAuthorization(Request request, boolean preserveAuthorization) { request.attribute(PRESERVE_AUTHORIZATION_KEY, preserveAuthorization); } private static boolean isPreserveAuthorization(Request request) { return TRUE.equals(request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY)); } }
package io.airlift.http.client.jetty; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClientTransport; import org.eclipse.jetty.client.HttpRequest; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.http.HttpField; import org.eclipse.jetty.util.ssl.SslContextFactory; import java.net.URI; import static org.eclipse.jetty.http.HttpHeader.AUTHORIZATION; class AuthorizationPreservingHttpClient extends HttpClient { private static final String PRESERVE_AUTHORIZATION_KEY = "airlift_preserve_authorization"; public AuthorizationPreservingHttpClient(HttpClientTransport transport, SslContextFactory sslContextFactory) { super(transport, sslContextFactory); } @Override protected Request copyRequest(HttpRequest oldRequest, URI newUri) { Request newRequest = super.copyRequest(oldRequest, newUri); if (isPreserveAuthorization(oldRequest)) { setPreserveAuthorization(newRequest, true); for (HttpField field : oldRequest.getHeaders()) { if (field.getHeader() == AUTHORIZATION) { newRequest.header(field.getName(), field.getValue()); } } } return newRequest; } public static void setPreserveAuthorization(Request request, boolean preserveAuthorization) { request.attribute(PRESERVE_AUTHORIZATION_KEY, preserveAuthorization); } private static boolean isPreserveAuthorization(Request request) { return (boolean) request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY); } }
Fix broken billing statement command tests
from datetime import datetime from optparse import make_option from go.billing.models import Account from go.billing.tasks import month_range, generate_monthly_statement from go.base.command_utils import BaseGoCommand, get_user_by_email class Command(BaseGoCommand): help = "Generate monthly billing statements for an account." option_list = BaseGoCommand.option_list + ( make_option( '--email-address', dest='email_address', help="Email address of the account to generate statements for."), make_option( '--month', dest='month', action='append', help="Month to generate statements for in the form YYYY-MM, " "e.g. 2014-01. Multiple may be specified.")) def handle(self, *args, **opts): user = get_user_by_email(opts['email_address']) account_number = user.get_profile().user_account account = Account.objects.get(account_number=account_number) self.stdout.write( "Generating statements for account %s..." % (opts['email_address'],)) months = [datetime.strptime(m, '%Y-%m') for m in opts['month']] for month in months: from_date, to_date = month_range(0, month) generate_monthly_statement(account.id, from_date, to_date) self.stdout.write( "Generated statement for %s." % (datetime.strftime(month, '%Y-%m'),))
from datetime import datetime from optparse import make_option from go.billing.models import Account from go.billing.tasks import month_range, generate_monthly_statement from go.base.command_utils import BaseGoCommand, get_user_by_email class Command(BaseGoCommand): help = "Generate monthly billing statements for an account." option_list = BaseGoCommand.option_list + ( make_option( '--email-address', dest='email_address', help="Email address of the account to generate statements for."), make_option( '--month', dest='month', action='append', help="Month to generate statements for in the form YYYY-MM, " "e.g. 2014-01. Multiple may be specified.")) def handle(self, *args, **opts): user = get_user_by_email(opts['email_address']) account_number = user.get_profile().user_account account = Account.objects.get(account_number=account_number) self.stdout.write( "Generating statements for account %s..." % (opts['email_address'],)) months = [datetime.strptime(m, '%Y-%m') for m in opts['months']] for month in months: from_date, to_date = month_range(0, month) generate_monthly_statement(account.id, from_date, to_date) self.stdout.write("Generated statement for %s." % (month,))
Add a 'try' block for current versions of Node.js to try and '.close' the server.
'use strict'; var NET = require('net'); var PORTS = {}; function CreateServer( port, callback ){ if( (typeof port === 'number') ){ port = parseFloat(port); if( (PORTS[port.toString()]) ){ process.nextTick(CreateServer,port,callback); return; } PORTS[port.toString()] = true; NET.createServer() .on('error',function CreateServerError(error){ delete PORTS[port.toString()]; /* Older versions of Node.js throw hard // errors when .closing an error'd server. */ try{ this.close(); } catch(error){ /* Ignore the error, simply try and close // the server if for whatever reason it // is somehow listening. */ } if(error.code === 'EADDRINUSE') callback(null,false,port); else callback(true,error,port); }) .on('listening',function CreateServerListening(){ this.close(function CreateServerClose(){ delete PORTS[port.toString()]; callback(null,true,port); }); }) .listen(port); } else if(typeof callback === 'function') callback(null,false); } module.exports = CreateServer;
'use strict'; var NET = require('net'); var PORTS = {}; function CreateServer( port, callback ){ if( (typeof port === 'number') ){ port = parseFloat(port); if( (PORTS[port.toString()]) ){ process.nextTick(CreateServer,port,callback); return; } PORTS[port.toString()] = true; NET.createServer() .on('error',function CreateServerError(error){ delete PORTS[port.toString()]; if(error.code === 'EADDRINUSE'){ callback(null,false,port); } else{ callback(true,error,port); } }) .listen(port,function CreateServerListening(){ this.close(function CreateServerClose(){ delete PORTS[port.toString()]; callback(null,true,port); }); }); } else if(typeof callback === 'function') callback(null,false); } module.exports = CreateServer;
Split array data sent to actions into GET and SET.
<?php namespace Air\Routing\Dispatcher; use Air\Routing\ResolvedRequest\ResolvedRequestInterface; use Interop\Container\ContainerInterface; class Dispatcher implements DispatcherInterface { /** * @var ContainerInterface $container The DI container. */ private $container; /** * @param ContainerInterface $container The DI container. */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * Dispatch a route. * * @param ResolvedRequestInterface $resolvedRequest A resolved request. * @return string The response. */ public function dispatch(ResolvedRequestInterface $resolvedRequest) { $route = $resolvedRequest->getRoute(); $request = $resolvedRequest->getRequest(); $controller = $this->container->get($route->getController()); // Call the before hook, if defined. if (method_exists($controller, 'before')) { $controller->before(); } // Call the action. $response = call_user_func_array( [$controller, 'action' . $route->getAction()], [ $resolvedRequest->getUriParameters(), [ 'post' => $request->getPostData(), 'get' => $request->getQueryParameters() ] ] ); // Call the after hook, if defined. if (method_exists($controller, 'after')) { $controller->after(); } return $response; } }
<?php namespace Air\Routing\Dispatcher; use Air\Routing\ResolvedRequest\ResolvedRequestInterface; use Interop\Container\ContainerInterface; class Dispatcher implements DispatcherInterface { /** * @var ContainerInterface $container The DI container. */ private $container; /** * @param ContainerInterface $container The DI container. */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * Dispatch a route. * * @param ResolvedRequestInterface $resolvedRequest A resolved request. * @return string The response. */ public function dispatch(ResolvedRequestInterface $resolvedRequest) { $route = $resolvedRequest->getRoute(); $request = $resolvedRequest->getRequest(); $controller = $this->container->get($route->getController()); // Call the before hook, if defined. if (method_exists($controller, 'before')) { $controller->before(); } // Call the action. $response = call_user_func_array( [$controller, 'action' . $route->getAction()], [ $resolvedRequest->getUriParameters(), [ 'params' => $request->getQueryParameters() ] ] ); // Call the after hook, if defined. if (method_exists($controller, 'after')) { $controller->after(); } return $response; } }
Set organization code to fhirdemo
var moment = require('moment'); var System = { create: function(activityInstance, user, language, nation) { var now = moment(); return { "User": { "HealthCareRole": user.startsWith("Patient") ? "Citizen" : "Physician", "HealthCareOrganization": { "CodeValue": "fhirdemo", "CodeSystem": {}, "CodeSystemVersion": {} }, "HealthCareSpecialty": { "CodeValue": {}, "CodeSystem": {}, "CodeSystemVersion": {} }, "Language": { "CodeValue": language, "CodeSystem": "2.16.840.1.113883.6.99", "CodeSystemVersion": {} }, "Nation": { "CodeValue": nation, "CodeSystem": "ISO 3166-1", "CodeSystemVersion": {} } }, "Application": { "QueryID": activityInstance, "FeedbackType": "S", "CheckMoment": { "CheckDate": now.format('YYYY-MM-DD'), "CheckTime": now.format('HH:mm:ss') } } }; } }; module.exports = System;
var moment = require('moment'); var System = { create: function(activityInstance, user, language, nation) { var now = moment(); return { "User": { "HealthCareRole": user.startsWith("Patient") ? "Citizen" : "Physician", "HealthCareOrganization": { "CodeValue": {}, "CodeSystem": {}, "CodeSystemVersion": {} }, "HealthCareSpecialty": { "CodeValue": {}, "CodeSystem": {}, "CodeSystemVersion": {} }, "Language": { "CodeValue": language, "CodeSystem": "2.16.840.1.113883.6.99", "CodeSystemVersion": {} }, "Nation": { "CodeValue": nation, "CodeSystem": "ISO 3166-1", "CodeSystemVersion": {} } }, "Application": { "QueryID": activityInstance, "FeedbackType": "S", "CheckMoment": { "CheckDate": now.format('YYYY-MM-DD'), "CheckTime": now.format('HH:mm:ss') } } }; } }; module.exports = System;
Return payload even if request arg is not passed in.
""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return payload rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload
""" Django-aware exception handler for integration with Errordite. Adds django user and request information to the exception as appropriate. """ from errordite import ErrorditeHandler class DjangoErrorditeHandler(ErrorditeHandler): """ Django-aware Errordite handler than enriches logs with request info. """ def enrich_errordite_payload(self, payload, record): """ Overrides base class implementation to add Django-specific error data - specifically user and HTTP request information. """ payload = super(DjangoErrorditeHandler, self).enrich_errordite_payload( payload, record ) if not hasattr(record, 'request'): return rq = record.request payload['Url'] = rq.get_full_path() if 'HTTP_USER_AGENT' in rq.META: payload['UserAgent'] = rq.META['HTTP_USER_AGENT'] data = payload['ExceptionInfo'].get('Data', {}) if 'HTTP_X_FORWARDED_FOR' in rq.META: data['X-Forwarded-For'] = rq.META['HTTP_X_FORWARDED_FOR'] if 'REMOTE_ADDR' in rq.META: data['client_ip'] = rq.META['REMOTE_ADDR'] if hasattr(rq, 'user'): if rq.user is not None: if rq.user.is_anonymous(): data['user'] = "anonymous" else: data['user'] = rq.user.username payload['ExceptionInfo']['Data'] = data return payload
Allow for null user agents in sessions.
<?php namespace Entity; use \Doctrine\Common\Collections\ArrayCollection; /** * @Table(name="sessions", indexes={ * @index(name="cleanup_idx", columns={"expires"}) * }) * @Entity */ class Session extends \DF\Doctrine\Entity { public function __construct() { $this->last_modified = time(); $this->user_agent = $_SERVER['HTTP_USER_AGENT']; if (empty($this->user_agent)) $this->user_agent = 'none'; } /** * @Column(name="id", type="string", length=128) * @Id */ protected $id; /** @Column(name="user_agent", type="string", length=255, nullable=true) */ protected $user_agent; /** @Column(name="expires", type="integer") */ protected $expires; public function setLifetime($lifetime) { $this->expires = time()+$lifetime; } /** @Column(name="last_modified", type="integer") */ protected $last_modified; /** @Column(name="data", type="text", nullable=true) */ protected $data; /* * Validate session. * @return boolean */ public function isValid() { if ($this->expires < time()) return false; $current_ua = $_SERVER['HTTP_USER_AGENT']; if (empty($current_ua)) $current_ua = 'none'; if (strcmp($this->user_agent, $current_ua) !== 0) return false; return true; } }
<?php namespace Entity; use \Doctrine\Common\Collections\ArrayCollection; /** * @Table(name="sessions", indexes={ * @index(name="cleanup_idx", columns={"expires"}) * }) * @Entity */ class Session extends \DF\Doctrine\Entity { public function __construct() { $this->last_modified = time(); $this->user_agent = $_SERVER['HTTP_USER_AGENT']; } /** * @Column(name="id", type="string", length=128) * @Id */ protected $id; /** @Column(name="user_agent", type="string", length=255) */ protected $user_agent; /** @Column(name="expires", type="integer") */ protected $expires; public function setLifetime($lifetime) { $this->expires = time()+$lifetime; } /** @Column(name="last_modified", type="integer") */ protected $last_modified; /** @Column(name="data", type="text", nullable=true) */ protected $data; /* * Validate session. * @return boolean */ public function isValid() { if ($this->expires < time()) return false; $current_ua = $_SERVER['HTTP_USER_AGENT']; if (strcmp($this->user_agent, $current_ua) !== 0) return false; return true; } }
Hide navigation if not authenticated
<!DOCTYPE html> <html> <head> <title>Budget</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito:300,300i" /> <link rel="stylesheet" href="/style.css" /> </head> <body> @if (Auth::check()) <div class="navigation"> <ul> <li> <a href="/dashboard">Dashboard</a> </li> <li> <a href="/reports">Reports</a> </li> </ul> <ul> <li> <a href="/settings">Settings</a> </li> <li> <a href="/logout">Log out</a> </li> </ul> </div> @endif <div class="body"> @yield('body') </div> </body> </html>
<!DOCTYPE html> <html> <head> <title>Budget</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito:300,300i" /> <link rel="stylesheet" href="/style.css" /> </head> <body> <div class="navigation"> <ul> <li> <a href="/dashboard">Dashboard</a> </li> <li> <a href="/reports">Reports</a> </li> </ul> <ul> <li> <a href="/settings">Settings</a> </li> <li> <a href="/logout">Log out</a> </li> </ul> </div> <div class="body"> @yield('body') </div> </body> </html>
Change back to close when player closes inventyory
package xyz.upperlevel.uppercore.gui; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerQuitEvent; import xyz.upperlevel.uppercore.Uppercore; public class GuiListener implements Listener { @EventHandler public void onPlayerQuit(PlayerQuitEvent e) { GuiSystem.close(e.getPlayer()); } @EventHandler public void onInventoryClose(InventoryCloseEvent e) { if (e.getPlayer() instanceof Player && !GuiSystem.isCalled()) { //Cannot call Inventory actions in an inventory event Bukkit.getScheduler().runTaskLater( Uppercore.get(), () -> GuiSystem.close((Player) e.getPlayer()), 0 ); } } @EventHandler public void onInventoryClick(InventoryClickEvent e) { if (e.getClickedInventory() == e.getInventory()) GuiSystem.onClick(e); if (e.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) { if (GuiSystem.getHistory((Player) e.getWhoClicked()) != null) e.setCancelled(true); } } }
package xyz.upperlevel.uppercore.gui; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerQuitEvent; import xyz.upperlevel.uppercore.Uppercore; public class GuiListener implements Listener { @EventHandler public void onPlayerQuit(PlayerQuitEvent e) { GuiSystem.close(e.getPlayer()); } @EventHandler public void onInventoryClose(InventoryCloseEvent e) { if (e.getPlayer() instanceof Player && !GuiSystem.isCalled()) { //Cannot call Inventory actions in an inventory event Bukkit.getScheduler().runTaskLater( Uppercore.get(), () -> GuiSystem.back((Player) e.getPlayer()), 0 ); } } @EventHandler public void onInventoryClick(InventoryClickEvent e) { if (e.getClickedInventory() == e.getInventory()) GuiSystem.onClick(e); if (e.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) { if (GuiSystem.getHistory((Player) e.getWhoClicked()) != null) e.setCancelled(true); } } }
Change Array check using Array.isArray
var camelCase = require('camel-case'); var snakeCase = require('snake-case'); var paramCase = require('param-case'); var changeKeys = function changeKeys(transformer, obj) { if (Array.isArray(obj)) { var r = []; for (var i = 0; i < obj.length; i++) { console.log(obj[i]); r.push(changeKeys(transformer, obj[i])); } return r; } else if (typeof obj === 'object') { var objectKeys = Object.keys(obj); return objectKeys.map(function keysMap(key) { return transformer(key); }).reduce(function keysReducer(object, changedKey, index) { var objValue = obj[objectKeys[index]]; var transformedValue = changeKeys(transformer, objValue); object[changedKey] = transformedValue; return object; }, {}); } else { return obj; } }; var changeCaseObject = {}; changeCaseObject.camel = changeCaseObject.camelCase = function camelCaseObject(obj) { return changeKeys(camelCase, obj); }; changeCaseObject.snake = changeCaseObject.snakeCase = function snakeCaseObject(obj) { return changeKeys(snakeCase, obj); }; changeCaseObject.param = changeCaseObject.paramCase = function paramCaseObject(obj) { return changeKeys(paramCase, obj); }; module.exports = changeCaseObject;
var camelCase = require('camel-case'); var snakeCase = require('snake-case'); var paramCase = require('param-case'); var changeKeys = function changeKeys(transformer, obj) { if (Object.prototype.toString.call(obj) === '[object Array]') { var r = []; for (var i = 0; i < obj.length; i++) { console.log(obj[i]); r.push(changeKeys(transformer, obj[i])); } return r; } else if (typeof obj === 'object') { var objectKeys = Object.keys(obj); return objectKeys.map(function keysMap(key) { return transformer(key); }).reduce(function keysReducer(object, changedKey, index) { var objValue = obj[objectKeys[index]]; var transformedValue = changeKeys(transformer, objValue); object[changedKey] = transformedValue; return object; }, {}); } else { return obj; } }; var changeCaseObject = {}; changeCaseObject.camel = changeCaseObject.camelCase = function camelCaseObject(obj) { return changeKeys(camelCase, obj); }; changeCaseObject.snake = changeCaseObject.snakeCase = function snakeCaseObject(obj) { return changeKeys(snakeCase, obj); }; changeCaseObject.param = changeCaseObject.paramCase = function paramCaseObject(obj) { return changeKeys(paramCase, obj); }; module.exports = changeCaseObject;
Add metadata/query/result cache flush to "cache:clear" CLI command.
<?php use \DF\Phalcon\Cli\Task; use \PVL\SyncManager; class CacheTask extends Task { public function clearAction() { // Flush Doctrine cache. $em = $this->di->get('em'); $cacheDriver = $em->getConfiguration()->getMetadataCacheImpl(); $cacheDriver->deleteAll(); $queryCacheDriver = $em->getConfiguration()->getQueryCacheImpl(); $queryCacheDriver->deleteAll(); $resultCacheDriver = $em->getConfiguration()->getResultCacheImpl(); $resultCacheDriver->deleteAll(); $this->printLn('Doctrine ORM cache flushed.'); // Flush local cache. \DF\Cache::clean(); $this->printLn('Local cache flushed.'); // Flush CloudFlare cache. if (DF_APPLICATION_ENV == 'production') { $apis = $this->config->apis->toArray(); if (isset($apis['cloudflare'])) { $url_base = 'https://www.cloudflare.com/api_json.html'; $url_params = array( 'tkn' => $apis['cloudflare']['api_key'], 'email' => $apis['cloudflare']['email'], 'a' => 'fpurge_ts', 'z' => $apis['cloudflare']['domain'], 'v' => '1', ); $url = $url_base . '?' . http_build_query($url_params); $result_raw = @file_get_contents($url); $result = @json_decode($result_raw, true); if ($result['result'] == 'success') $this->printLn('CloudFlare cache flushed successfully.'); else $this->printLn('CloudFlare error: ' . $result['msg']); } } } }
<?php use \DF\Phalcon\Cli\Task; use \PVL\SyncManager; class CacheTask extends Task { public function clearAction() { // Flush local cache. \DF\Cache::clean(); $this->printLn('Local cache flushed.'); // Flush CloudFlare cache. if (DF_APPLICATION_ENV == 'production') { $apis = $this->config->apis->toArray(); if (isset($apis['cloudflare'])) { $url_base = 'https://www.cloudflare.com/api_json.html'; $url_params = array( 'tkn' => $apis['cloudflare']['api_key'], 'email' => $apis['cloudflare']['email'], 'a' => 'fpurge_ts', 'z' => $apis['cloudflare']['domain'], 'v' => '1', ); $url = $url_base . '?' . http_build_query($url_params); $result_raw = @file_get_contents($url); $result = @json_decode($result_raw, true); if ($result['result'] == 'success') $this->printLn('CloudFlare cache flushed successfully.'); else $this->printLn('CloudFlare error: ' . $result['msg']); } } } }
Use connectIf to ensure web connection
"use strict"; module.exports = function (grunt) { grunt.registerTask("fixInstrument", function () { // Because code generation uses templates that are instrumented, the __cov_XXX variables must be global var fs = require("fs"); configuration.files.src.forEach(function (fileName) { var srcPath = "tmp/coverage/instrument/" + fileName, instrumentedLines = fs .readFileSync(srcPath) .toString() .split("\n"), // Assuming the __cov_ variable is on the second line secondLine = instrumentedLines[1]; if (0 === secondLine.indexOf("var ")) { instrumentedLines[1] = "global." + secondLine.substr(4); fs.writeFileSync(srcPath, instrumentedLines.join("\n")); console.log(fileName + " updated"); } }); }); grunt.registerTask("istanbul", [ "instrument", "fixInstrument", "copy:instrumentSourcesJson", "connectIf", "mochaTest:coverage", "storeCoverage", "makeReport", "coverage" ]); };
"use strict"; module.exports = function (grunt) { grunt.registerTask("fixInstrument", function () { // Because code generation uses templates that are instrumented, the __cov_XXX variables must be global var fs = require("fs"); configuration.files.src.forEach(function (fileName) { var srcPath = "tmp/coverage/instrument/" + fileName, instrumentedLines = fs .readFileSync(srcPath) .toString() .split("\n"), // Assuming the __cov_ variable is on the second line secondLine = instrumentedLines[1]; if (0 === secondLine.indexOf("var ")) { instrumentedLines[1] = "global." + secondLine.substr(4); fs.writeFileSync(srcPath, instrumentedLines.join("\n")); console.log(fileName + " updated"); } }); }); grunt.registerTask("istanbul", [ "instrument", "fixInstrument", "copy:instrumentSourcesJson", "mochaTest:coverage", "storeCoverage", "makeReport", "coverage" ]); };
Change ambigous variable name to be more clear what it is
# -*- coding: utf-8 -*- """ pykwalify """ # python stdlib import logging import logging.config import os __author__ = 'Grokzen <[email protected]>' __version_info__ = (1, 6, 0) __version__ = '.'.join(map(str, __version_info__)) log_level_to_string_map = { 5: "DEBUG", 4: "INFO", 3: "WARNING", 2: "ERROR", 1: "CRITICAL", 0: "INFO" } def init_logging(log_level): """ Init logging settings with default set to INFO """ log_level = log_level_to_string_map[min(log_level, 5)] msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if log_level in os.environ else "%(levelname)s - %(message)s" logging_conf = { "version": 1, "root": { "level": log_level, "handlers": ["console"] }, "handlers": { "console": { "class": "logging.StreamHandler", "level": log_level, "formatter": "simple", "stream": "ext://sys.stdout" } }, "formatters": { "simple": { "format": " {0}".format(msg) } } } logging.config.dictConfig(logging_conf) partial_schemas = {}
# -*- coding: utf-8 -*- """ pykwalify """ # python stdlib import logging import logging.config import os __author__ = 'Grokzen <[email protected]>' __version_info__ = (1, 6, 0) __version__ = '.'.join(map(str, __version_info__)) log_level_to_string_map = { 5: "DEBUG", 4: "INFO", 3: "WARNING", 2: "ERROR", 1: "CRITICAL", 0: "INFO" } def init_logging(log_level): """ Init logging settings with default set to INFO """ l = log_level_to_string_map[min(log_level, 5)] msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if l in os.environ else "%(levelname)s - %(message)s" logging_conf = { "version": 1, "root": { "level": l, "handlers": ["console"] }, "handlers": { "console": { "class": "logging.StreamHandler", "level": l, "formatter": "simple", "stream": "ext://sys.stdout" } }, "formatters": { "simple": { "format": " {0}".format(msg) } } } logging.config.dictConfig(logging_conf) partial_schemas = {}
Add a throbber for "sending sub request" in UserCard
import * as ActionTypes from '../action-types'; import * as ActionHelpers from '../action-helpers'; const {request, response, fail} = ActionHelpers; export default function userViews(state = {}, action) { switch (action.type) { case request(ActionTypes.SUBSCRIBE): case request(ActionTypes.SEND_SUBSCRIPTION_REQUEST): case request(ActionTypes.UNSUBSCRIBE): { const userId = action.payload.id; const userView = state[userId]; return {...state, [userId]: {...userView, isSubscribing: true}}; } case response(ActionTypes.SUBSCRIBE): case response(ActionTypes.SEND_SUBSCRIPTION_REQUEST): case response(ActionTypes.UNSUBSCRIBE): case fail(ActionTypes.SUBSCRIBE): case fail(ActionTypes.SEND_SUBSCRIPTION_REQUEST): case fail(ActionTypes.UNSUBSCRIBE): { const userId = action.request.id; const userView = state[userId]; return {...state, [userId]: {...userView, isSubscribing: false}}; } case request(ActionTypes.BAN): case request(ActionTypes.UNBAN): { const userId = action.payload.id; const userView = state[userId]; return {...state, [userId]: {...userView, isBlocking: true}}; } case response(ActionTypes.BAN): case response(ActionTypes.UNBAN): case fail(ActionTypes.BAN): case fail(ActionTypes.UNBAN): { const userId = action.request.id; const userView = state[userId]; return {...state, [userId]: {...userView, isBlocking: false}}; } } return state; }
import * as ActionTypes from '../action-types'; import * as ActionHelpers from '../action-helpers'; const {request, response, fail} = ActionHelpers; export default function userViews(state = {}, action) { switch (action.type) { case request(ActionTypes.SUBSCRIBE): case request(ActionTypes.UNSUBSCRIBE): { const userId = action.payload.id; const userView = state[userId]; return {...state, [userId]: {...userView, isSubscribing: true}}; } case response(ActionTypes.SUBSCRIBE): case response(ActionTypes.UNSUBSCRIBE): case fail(ActionTypes.SUBSCRIBE): case fail(ActionTypes.UNSUBSCRIBE): { const userId = action.request.id; const userView = state[userId]; return {...state, [userId]: {...userView, isSubscribing: false}}; } case request(ActionTypes.BAN): case request(ActionTypes.UNBAN): { const userId = action.payload.id; const userView = state[userId]; return {...state, [userId]: {...userView, isBlocking: true}}; } case response(ActionTypes.BAN): case response(ActionTypes.UNBAN): case fail(ActionTypes.BAN): case fail(ActionTypes.UNBAN): { const userId = action.request.id; const userView = state[userId]; return {...state, [userId]: {...userView, isBlocking: false}}; } } return state; }
Change search from Contains to Starts With.
/// <reference path="../../../../../argos-sdk/libraries/ext/ext-core-debug.js"/> /// <reference path="../../../../../argos-sdk/libraries/sdata/sdata-client-debug"/> /// <reference path="../../../../../argos-sdk/libraries/Simplate.js"/> /// <reference path="../../../../../argos-sdk/src/View.js"/> /// <reference path="../../../../../argos-sdk/src/List.js"/> Ext.namespace("Mobile.SalesLogix.Account"); (function() { Mobile.SalesLogix.Account.List = Ext.extend(Sage.Platform.Mobile.List, { //Templates contentTemplate: new Simplate([ '<h3>{%: $.AccountName %}</h3>', '<h4>{%: $.AccountManager && $.AccountManager.UserInfo ? $.AccountManager.UserInfo.UserName : "" %}</h4>' ]), //Localization titleText: 'Accounts', activitiesText: 'Activities', notesText: 'Notes', scheduleText: 'Schedule', //View Properties detailView: 'account_detail', icon: 'content/images/icons/Company_24.png', id: 'account_list', insertView: 'account_edit', queryOrderBy: 'AccountName', querySelect: [ 'AccountName', 'AccountManager/UserInfo/UserName' ], resourceKind: 'accounts', formatSearchQuery: function(query) { return String.format('AccountNameUpper like "{0}%"', query.toUpperCase()); } }); })();
/// <reference path="../../../../../argos-sdk/libraries/ext/ext-core-debug.js"/> /// <reference path="../../../../../argos-sdk/libraries/sdata/sdata-client-debug"/> /// <reference path="../../../../../argos-sdk/libraries/Simplate.js"/> /// <reference path="../../../../../argos-sdk/src/View.js"/> /// <reference path="../../../../../argos-sdk/src/List.js"/> Ext.namespace("Mobile.SalesLogix.Account"); (function() { Mobile.SalesLogix.Account.List = Ext.extend(Sage.Platform.Mobile.List, { //Templates contentTemplate: new Simplate([ '<h3>{%: $.AccountName %}</h3>', '<h4>{%: $.AccountManager && $.AccountManager.UserInfo ? $.AccountManager.UserInfo.UserName : "" %}</h4>' ]), //Localization titleText: 'Accounts', activitiesText: 'Activities', notesText: 'Notes', scheduleText: 'Schedule', //View Properties detailView: 'account_detail', icon: 'content/images/icons/Company_24.png', id: 'account_list', insertView: 'account_edit', queryOrderBy: 'AccountName', querySelect: [ 'AccountName', 'AccountManager/UserInfo/UserName' ], resourceKind: 'accounts', formatSearchQuery: function(query) { return String.format('AccountNameUpper like "%{0}%"', query.toUpperCase()); } }); })();
Update ApplicationSearchProvider to reflect conf.settings.Application changes.
import logging from molly.apps.search.providers import BaseSearchProvider from molly.conf import applications logger = logging.getLogger('molly.providers.apps.search.application_search') class ApplicationSearchProvider(BaseSearchProvider): def __init__(self, local_names=None): self.local_names = local_names self.applications = None def perform_search(self, request, query, application=None): if self.applications == None: self.find_applications() if application: if not application in self.applications: return [] apps = [self.applications[application]] else: apps = self.applications.values() results = [] for app in apps: try: results += app.perform_search(request, query, application) except Exception, e: logger.exception("Application search provider raised exception: %r", e) pass print apps return results def find_applications(self): self.applications = {} for local_name in applications: application = applications[local_name] if self.local_names and not application in self.local_names: continue try: search_module_name = '%s.search' % application.application_name _temp = __import__(search_module_name, globals(), locals(), ['SearchProvider'], -1) if not hasattr(_temp, 'SearchProvider'): raise ImportError except ImportError: continue else: search_provider = _temp.SearchProvider self.applications[application.local_name] = search_provider
import logging from molly.apps.search.providers import BaseSearchProvider from molly.conf import applications logger = logging.getLogger('molly.providers.apps.search.application_search') class ApplicationSearchProvider(BaseSearchProvider): def __init__(self, application_names=None): self.application_names = application_names self.applications = None def perform_search(self, request, query, application=None): if self.applications == None: self.find_applications() if application: if not application in self.applications: return [] apps = [self.applications[application]] else: apps = self.applications.values() results = [] for app in apps: try: results += app.perform_search(request, query, application) except Exception, e: logger.exception("Application search provider raised exception: %r", e) pass print apps return results def find_applications(self): self.applications = {} for app_name in applications: application = applications[app_name] if self.application_names and not application in self.application_names: continue try: search_module_name = '%s.search' % application.name _temp = __import__(search_module_name, globals(), locals(), ['SearchProvider'], -1) if not hasattr(_temp, 'SearchProvider'): raise ImportError except ImportError: continue else: search_provider = _temp.SearchProvider self.applications[application.slug] = search_provider
Make toString include the description, which may be helpful.
package net.happygiraffe.jslint; /** * @author dom * @version $Id$ */ public enum Option { ADSAFE ("if use of some browser features should be restricted"), BITWISE ("if bitwise operators should not be allowed"), BROWSER ("if the standard browser globals should be predefined"), CAP ("if upper case HTML should be allowed"), DEBUG ("if debugger statements should be allowed"), EQEQEQ ("if === should be required"), EVIL ("if eval should be allowed"), FRAGMENT ("if HTML fragments should be allowed"), LAXBREAK ("if line breaks should not be checked"), NOMEN ("if names should be checked"), PASSFAIL ("if the scan should stop on first error"), PLUSPLUS ("if increment/decrement should not be allowed"), RHINO ("if the Rhino environment globals should be predefined"), UNDEF ("if undefined variables are errors"), WHITE ("if strict whitespace rules apply"), WIDGET ("if the Yahoo Widgets globals should be predefined"); private String description; Option(String description) { this.description = description; } /** * Return a description of what this option affects. */ public String getDescription() { return description; } /** * Return the lowercase name of this option. */ public String getLowerName() { return name().toLowerCase(); } /** * Provide a JavaScript form of this option. */ @Override public String toString() { return getLowerName() + "[" + getDescription() + "]"; } }
package net.happygiraffe.jslint; /** * @author dom * @version $Id$ */ public enum Option { ADSAFE ("if use of some browser features should be restricted"), BITWISE ("if bitwise operators should not be allowed"), BROWSER ("if the standard browser globals should be predefined"), CAP ("if upper case HTML should be allowed"), DEBUG ("if debugger statements should be allowed"), EQEQEQ ("if === should be required"), EVIL ("if eval should be allowed"), FRAGMENT ("if HTML fragments should be allowed"), LAXBREAK ("if line breaks should not be checked"), NOMEN ("if names should be checked"), PASSFAIL ("if the scan should stop on first error"), PLUSPLUS ("if increment/decrement should not be allowed"), RHINO ("if the Rhino environment globals should be predefined"), UNDEF ("if undefined variables are errors"), WHITE ("if strict whitespace rules apply"), WIDGET ("if the Yahoo Widgets globals should be predefined"); private String description; Option(String description) { this.description = description; } /** * Return a description of what this option affects. */ public String getDescription() { return description; } /** * Return the lowercase name of this option. */ public String getLowerName() { return name().toLowerCase(); } /** * Provide a JavaScript form of this option. */ @Override public String toString() { return getLowerName() + ":true"; } }
Fix the Print widget french language translations fixes #818
define ({ title: 'Titre', format: 'Format', layout: 'Disposition', settings: 'Paramètres', mapScaleExtent: 'Échelle/étendue de la carte', preserve: 'Préserver', mapScale: 'échelle de la carte', mapExtent: 'étendue de la carte', fullLayoutOptions: 'Options complètes de mise en page', scaleBarUnits: 'Unités de la barre d\'échelle', miles: 'Miles', kilometers: 'Kilomètres', meters: 'Mètres', feet: 'Pieds', includeLegend: 'Inclure la légende', printQualityOptions: 'Qualité d`impression', dpiInput: { label: 'DPI', invalidMessage: 'S\\\'il vous plaît entrer une valeur numérique.', rangeMessage: 'S\\\'il vous plaît entrer une valeur entre 100 et 300.' }, mapOnlyOptions: 'Options MAP_ONLY', width: 'Largeur', height: 'Hauteur', printButton: { busyLabel: 'Impression', label: 'Imprimer' }, clearHistoryButton: { label: 'Effacer l\'historique d\'impression' }, printResults: { progressBar: { label: 'Création de l\\'impression' }, errorMessage: 'Erreur, réessayez' } });
define ({ title: 'Titre', format: 'Format', layout: 'Disposition', settings: 'Paramètres', mapScaleExtent: 'Échelle/étendue de la carte', preserve: 'Préserver', mapScale: 'échelle de la carte', mapExtent: 'étendue de la carte', fullLayoutOptions: 'Options complètes de mise en page', scaleBarUnits: 'Unités de la barre d\'échelle', miles: 'Miles', kilometers: 'Kilomètres', meters: 'Mètres', feet: 'Pieds', includeLegend: 'Inclure la légende', printQualityOptions: 'Qualité d`impression', dpiInput: { label: 'DPI', invalidMessage: 'S\'il vous plaît entrer une valeur numérique.', rangeMessage: 'S\'il vous plaît entrer une valeur entre 100 et 300.' }, mapOnlyOptions: 'Options MAP_ONLY', width: 'Largeur', height: 'Hauteur', printButton: { busyLabel: 'Impression', label: 'Imprimer' }, clearHistoryButton: { label: 'Effacer l\'historique d\'impression' }, printResults: { progressBar: { label: 'Création de l\'impression' }, errorMessage: 'Erreur, réessayez' } });
Set streams too since it's the same
<?php namespace Anomaly\PreferencesModule\Http\Middleware\Command; use Anomaly\PreferencesModule\Preference\Contract\PreferenceRepositoryInterface; use Illuminate\Config\Repository; use Illuminate\Contracts\Bus\SelfHandling; /** * Class SetDatetime * * @link http://anomaly.is/streams-platform * @author AnomalyLabs, Inc. <[email protected]> * @author Ryan Thompson <[email protected]> * @package Anomaly\PreferencesModule\Http\Middleware\Command */ class SetDatetime implements SelfHandling { /** * Handle the command. * * @param Repository $config * @param PreferenceRepositoryInterface $preferences */ function handle(Repository $config, PreferenceRepositoryInterface $preferences) { // Set the timezone. if ($timezone = $preferences->get('streams::timezone')) { $config->set('app.timezone', $timezone); $config->set('streams::datetime.timezone', $timezone); } // Set the date format. if ($format = $preferences->get('streams::date_format')) { $config->set('streams::datetime.date_format', $format); } // Set the time format. if ($format = $preferences->get('streams::time_format')) { $config->set('streams::datetime.time_format', $format); } } }
<?php namespace Anomaly\PreferencesModule\Http\Middleware\Command; use Anomaly\PreferencesModule\Preference\Contract\PreferenceRepositoryInterface; use Illuminate\Config\Repository; use Illuminate\Contracts\Bus\SelfHandling; /** * Class SetDatetime * * @link http://anomaly.is/streams-platform * @author AnomalyLabs, Inc. <[email protected]> * @author Ryan Thompson <[email protected]> * @package Anomaly\PreferencesModule\Http\Middleware\Command */ class SetDatetime implements SelfHandling { /** * Handle the command. * * @param Repository $config * @param PreferenceRepositoryInterface $preferences */ function handle(Repository $config, PreferenceRepositoryInterface $preferences) { // Set the timezone. if ($timezone = $preferences->get('streams::timezone')) { $config->set('app.timezone', $timezone); } // Set the date format. if ($format = $preferences->get('streams::date_format')) { $config->set('streams::datetime.date_format', $format); } // Set the time format. if ($format = $preferences->get('streams::time_format')) { $config->set('streams::datetime.time_format', $format); } } }
Change log level to info
var path = require('path'); var devConfig = { context: path.join(__dirname, '/app'), entry: [ './app.js' ], output: { path: path.join(__dirname, '/build/'), publicPath: '/public/assets/js/', filename: 'app.js', }, devtool: 'eval-source-map', devServer: { contentBase: 'public', historyApiFallback: false }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'], }, { test: /\.css$/, exclude: /node_modules/, loaders: ['style', 'css'] }, { test: /\.scss$/, exclude: /node_modules/, loaders: ['style', 'css', 'sass'] }, { test: /\.(jpg|png|ttf|eot|woff|woff2|svg)$/, exclude: /node_modules/, loader: 'url?limit=100000' } ] } } if (process.env.NODE_ENV === 'production') { devConfig.devtool = ''; devConfig.devServer = {}; }; module.exports = devConfig;
var path = require('path'); var devConfig = { context: path.join(__dirname, '/app'), entry: [ './app.js' ], output: { path: path.join(__dirname, '/build/'), publicPath: '/public/assets/js/', filename: 'app.js', }, devtool: 'eval-source-map', devServer: { contentBase: 'public', historyApiFallback: false, stats: 'errors-only' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'], }, { test: /\.css$/, exclude: /node_modules/, loaders: ['style', 'css'] }, { test: /\.scss$/, exclude: /node_modules/, loaders: ['style', 'css', 'sass'] }, { test: /\.(jpg|png|ttf|eot|woff|woff2|svg)$/, exclude: /node_modules/, loader: 'url?limit=100000' } ] } } if (process.env.NODE_ENV === 'production') { devConfig.devtool = ''; devConfig.devServer = {}; }; module.exports = devConfig;
Add team eligibility to API
from rest_framework import serializers from greta.models import Repository from competition.models import Team from .models import TeamClient, TeamSubmission class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ('id', 'name', 'slug', 'eligible_to_win') class RepoSerializer(serializers.ModelSerializer): class Meta: model = Repository fields = ('name', 'description', 'forked_from', 'path', 'is_ready') forked_from = serializers.RelatedField() path = serializers.SerializerMethodField('get_path') is_ready = serializers.SerializerMethodField('get_is_ready') def get_path(self, repo): return repo.path def get_is_ready(self, repo): return repo.is_ready() class TeamSubmissionSerializer(serializers.ModelSerializer): class Meta: model = TeamSubmission fields = ('name', 'commit') class TeamClientSerializer(serializers.ModelSerializer): class Meta: model = TeamClient fields = ('team', 'repository', 'tag', 'language') team = TeamSerializer() repository = RepoSerializer() tag = serializers.SerializerMethodField('get_tag') language = serializers.SerializerMethodField('get_language') def get_tag(self, teamclient): try: latest_sub= teamclient.submissions.latest() return TeamSubmissionSerializer(latest_sub).data except TeamSubmission.DoesNotExist: return None def get_language(self, teamclient): return teamclient.base.language
from rest_framework import serializers from greta.models import Repository from competition.models import Team from .models import TeamClient, TeamSubmission class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ('id', 'name', 'slug') class RepoSerializer(serializers.ModelSerializer): class Meta: model = Repository fields = ('name', 'description', 'forked_from', 'path', 'is_ready') forked_from = serializers.RelatedField() path = serializers.SerializerMethodField('get_path') is_ready = serializers.SerializerMethodField('get_is_ready') def get_path(self, repo): return repo.path def get_is_ready(self, repo): return repo.is_ready() class TeamSubmissionSerializer(serializers.ModelSerializer): class Meta: model = TeamSubmission fields = ('name', 'commit') class TeamClientSerializer(serializers.ModelSerializer): class Meta: model = TeamClient fields = ('team', 'repository', 'tag', 'language') team = TeamSerializer() repository = RepoSerializer() tag = serializers.SerializerMethodField('get_tag') language = serializers.SerializerMethodField('get_language') def get_tag(self, teamclient): try: latest_sub= teamclient.submissions.latest() return TeamSubmissionSerializer(latest_sub).data except TeamSubmission.DoesNotExist: return None def get_language(self, teamclient): return teamclient.base.language
Add max-width to emoji completions.
import React from 'react'; import AutocompleteProvider from './AutocompleteProvider'; import Q from 'q'; import {emojioneList, shortnameToImage, shortnameToUnicode} from 'emojione'; import Fuse from 'fuse.js'; const EMOJI_REGEX = /:\w*:?/g; const EMOJI_SHORTNAMES = Object.keys(emojioneList); let instance = null; export default class EmojiProvider extends AutocompleteProvider { constructor() { super(EMOJI_REGEX); this.fuse = new Fuse(EMOJI_SHORTNAMES); } getCompletions(query: string, selection: {start: number, end: number}) { let completions = []; let {command, range} = this.getCurrentCommand(query, selection); if (command) { completions = this.fuse.search(command[0]).map(result => { let shortname = EMOJI_SHORTNAMES[result]; let imageHTML = shortnameToImage(shortname); return { completion: shortnameToUnicode(shortname), component: ( <div className="mx_Autocomplete_Completion"> <span style={{maxWidth: '1em'}} dangerouslySetInnerHTML={{__html: imageHTML}}></span>&nbsp;&nbsp;{shortname} </div> ), range, }; }).slice(0, 4); } return Q.when(completions); } getName() { return 'Emoji'; } static getInstance() { if (instance == null) instance = new EmojiProvider(); return instance; } }
import React from 'react'; import AutocompleteProvider from './AutocompleteProvider'; import Q from 'q'; import {emojioneList, shortnameToImage, shortnameToUnicode} from 'emojione'; import Fuse from 'fuse.js'; const EMOJI_REGEX = /:\w*:?/g; const EMOJI_SHORTNAMES = Object.keys(emojioneList); let instance = null; export default class EmojiProvider extends AutocompleteProvider { constructor() { super(EMOJI_REGEX); this.fuse = new Fuse(EMOJI_SHORTNAMES); } getCompletions(query: string, selection: {start: number, end: number}) { let completions = []; let {command, range} = this.getCurrentCommand(query, selection); if (command) { completions = this.fuse.search(command[0]).map(result => { let shortname = EMOJI_SHORTNAMES[result]; let imageHTML = shortnameToImage(shortname); return { completion: shortnameToUnicode(shortname), component: ( <div className="mx_Autocomplete_Completion"> <span dangerouslySetInnerHTML={{__html: imageHTML}}></span> {shortname} </div> ), range, }; }).slice(0, 4); } return Q.when(completions); } getName() { return 'Emoji'; } static getInstance() { if (instance == null) instance = new EmojiProvider(); return instance; } }
Swap the speeds of the two-mode drivetrain
package edu.stuy.commands; import static edu.stuy.RobotMap.*; import edu.stuy.Robot; import edu.wpi.first.wpilibj.command.Command; /** * */ public class DrivetrainTankDriveCommand extends Command { public DrivetrainTankDriveCommand() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); requires(Robot.drivetrain); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { double left = Robot.oi.driverPad.getLeftY(); double right = Robot.oi.driverPad.getRightY(); if (Robot.oi.driverPad.getRawLeftTrigger() || Robot.oi.driverPad.getRawRightTrigger()) { // Slow mode (when a trigger is pressed) Robot.drivetrain.tankDrive(-left * DRIVETRAIN_SLOWNESS_FACTOR, -right * DRIVETRAIN_SLOWNESS_FACTOR); } else { // Fast mode (default) Robot.drivetrain.tankDrive(-left, -right); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
package edu.stuy.commands; import static edu.stuy.RobotMap.*; import edu.stuy.Robot; import edu.wpi.first.wpilibj.command.Command; /** * */ public class DrivetrainTankDriveCommand extends Command { public DrivetrainTankDriveCommand() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); requires(Robot.drivetrain); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { double left = Robot.oi.driverPad.getLeftY(); double right = Robot.oi.driverPad.getRightY(); if (Robot.oi.driverPad.getRawLeftTrigger() || Robot.oi.driverPad.getRawRightTrigger()) { // Fast mode (when a trigger is pressed) Robot.drivetrain.tankDrive(-left, -right); } else { // Slow mode (default) Robot.drivetrain.tankDrive(-left * DRIVETRAIN_SLOWNESS_FACTOR, -right * DRIVETRAIN_SLOWNESS_FACTOR); } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
Fix up some windows menu items
module.exports = function menu (mainWindow) { var otherMenu = [ { label: '&File', submenu: [ { label: '&Open', accelerator: 'Ctrl+O' }, { label: '&Quit', accelerator: 'Ctrl+Q', click: function () { mainWindow.close() } } ] }, { label: '&View', submenu: [ { label: '&Reload', accelerator: 'Ctrl+R', click: function () { mainWindow.restart() } }, { label: 'Toggle &Full Screen', accelerator: 'F11', click: function () { mainWindow.setFullScreen(!mainWindow.isFullScreen()) } }, { label: 'Toggle &Developer Tools', accelerator: 'Ctrl+Shift+I', click: function () { mainWindow.toggleDevTools() } } ] }, { label: 'Help', submenu: [ { label: 'Repository', click: function () { require('shell').openExternal('http://github.com/jlord/git-it-electron') } } ] } ] return otherMenu }
module.exports = function menu (mainWindow) { var otherMenu = [ { label: '&File', submenu: [ { label: '&Open', accelerator: 'Ctrl+O' }, { label: '&Close', accelerator: 'Ctrl+W', click: function () { mainWindow.close() } } ] }, { label: '&View', submenu: [ { label: '&Reload', accelerator: 'Ctrl+R', click: function () { mainWindow.restart() } }, { label: 'Toggle &Full Screen', accelerator: 'F11', click: function () { mainWindow.setFullScreen(!mainWindow.isFullScreen()) } }, { label: 'Toggle &Developer Tools', accelerator: 'Alt+Ctrl+I', click: function () { mainWindow.toggleDevTools() } } ] }, { label: 'Help', submenu: [ { label: 'Repository', click: function () { require('shell').openExternal('http://github.com/jlord/git-it-electron') } } ] } ] return otherMenu }
Change the order when loading xml data
# -*- coding: utf-8 -*- ############################################################################## # ############################################################################## { "name": "Account Streamline", "version": "0.1", "author": "XCG Consulting", "category": 'Accounting', "description": """Enhancements to the account module to streamline its usage. """, 'website': 'http://www.openerp-experts.com', 'init_xml': [], "depends": [ 'base', 'account_accountant', 'account_voucher', 'account_payment', 'account_sequence', 'analytic_structure', 'advanced_filter'], "data": [ 'data/partner_data.xml', 'wizard/account_reconcile_view.xml', 'account_move_line_search_unreconciled.xml', 'account_move_line_tree.xml', 'account_move_view.xml', 'account_view.xml', 'partner_view.xml', 'payment_selection.xml', 'account_move_line_journal_items.xml', 'account_move_line_journal_view.xml', 'account_menu_entries.xml', 'data/analytic.code.csv', 'data/analytic.dimension.csv', 'data/analytic.structure.csv' ], #'demo_xml': [], 'test': [], 'installable': True, 'active': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- ############################################################################## # ############################################################################## { "name": "Account Streamline", "version": "0.1", "author": "XCG Consulting", "category": 'Accounting', "description": """Enhancements to the account module to streamline its usage. """, 'website': 'http://www.openerp-experts.com', 'init_xml': [], "depends": [ 'base', 'account_accountant', 'account_voucher', 'account_payment', 'account_sequence', 'analytic_structure', 'advanced_filter'], "data": [ 'data/partner_data.xml', 'wizard/account_reconcile_view.xml', 'account_move_line_search_unreconciled.xml', 'account_move_line_tree.xml', 'account_move_view.xml', 'account_view.xml', 'partner_view.xml', 'payment_selection.xml', 'account_move_line_journal_items.xml', 'account_menu_entries.xml', 'account_move_line_journal_view.xml', 'data/analytic.code.csv', 'data/analytic.dimension.csv', 'data/analytic.structure.csv' ], #'demo_xml': [], 'test': [], 'installable': True, 'active': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Load RSF should bypass consistency filter This commit updates the `ConsistencyFilter` to allow a call to `load-rsf` to bypass it. This is necessary if we need to update the metadata for a register to make it consistent with the environment, as otherwise we are blocked by all requests to an inconsistent register throwing an exception.
package uk.gov.register.filters; import uk.gov.register.core.RegisterContext; import uk.gov.register.core.RegisterName; import uk.gov.register.exceptions.InconsistencyException; import javax.inject.Inject; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import java.io.IOException; @Provider public class ConsistencyFilter implements ContainerRequestFilter { private final javax.inject.Provider<RegisterName> registerPrimaryKey; private final UriInfo uriInfo; private final javax.inject.Provider<RegisterContext> registerContext; @Inject public ConsistencyFilter(final javax.inject.Provider<RegisterName> registerPrimaryKey, final UriInfo uriInfo, javax.inject.Provider<RegisterContext> registerContext) { this.registerPrimaryKey = registerPrimaryKey; this.uriInfo = uriInfo; this.registerContext = registerContext; } @Override public void filter(final ContainerRequestContext requestContext) throws IOException { final String path = uriInfo.getPath(); if (skipFilter(path)) { return; } if (!registerContext.get().hasConsistentState()) { throw new InconsistencyException( String.format("Register %s doesn't match with specification.", registerPrimaryKey.get().value())); } } private boolean skipFilter(final String path) { return path.contains("delete-register-data") || path.contains("load-rsf"); } }
package uk.gov.register.filters; import uk.gov.register.core.RegisterContext; import uk.gov.register.core.RegisterName; import uk.gov.register.exceptions.InconsistencyException; import javax.inject.Inject; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import java.io.IOException; @Provider public class ConsistencyFilter implements ContainerRequestFilter { private final javax.inject.Provider<RegisterName> registerPrimaryKey; private final UriInfo uriInfo; private final javax.inject.Provider<RegisterContext> registerContext; @Inject public ConsistencyFilter(final javax.inject.Provider<RegisterName> registerPrimaryKey, final UriInfo uriInfo, javax.inject.Provider<RegisterContext> registerContext) { this.registerPrimaryKey = registerPrimaryKey; this.uriInfo = uriInfo; this.registerContext = registerContext; } @Override public void filter(final ContainerRequestContext requestContext) throws IOException { final String path = uriInfo.getPath(); if (skipFilter(path)) { return; } if (!registerContext.get().hasConsistentState()) { throw new InconsistencyException( String.format("Register %s doesn't match with specification.", registerPrimaryKey.get().value())); } } private boolean skipFilter(final String path) { return path.contains("delete-register-data"); } }
Use proper async handling so that multiple tests are called sequentially and a callback is fired when completed
module.exports = function( grunt ) { // Create a new multi task. grunt.registerMultiTask( 'casperjs', 'This triggers casperjs.', function() { // Tell grunt this task is asynchronous. var done = this.async(), files = grunt.file.expandFiles(this.file.src), filepaths = []; grunt.file.expandFiles(this.file.src).forEach(function(filepath) { filepaths.push(filepath); }); grunt.utils.async.forEachSeries(filepaths, function runCasper(filepath, callback) { grunt.helper('casperjs', filepath, function(err){ if (err) { grunt.warn(err); } callback(); }); }, done); }); grunt.registerHelper('casperjs', function(filepath, callback) { var command = 'casperjs "' + filepath + '"', exec = require('child_process').exec; function puts( error, stdout, stderr ) { grunt.log.write( '\nRunning tests from "' + filepath + '":\n' ); grunt.log.write( stdout ); //grunt.log.error( stderr ); if ( error !== null ) { callback(error); } else { callback(); } } exec( command, puts ); }); };
module.exports = function( grunt ) { // Create a new multi task. grunt.registerMultiTask( 'casperjs', 'This triggers casperjs.', function() { // Tell grunt this task is asynchronous. var done = this.async(), files = grunt.file.expandFiles(this.file.src); grunt.file.expandFiles(this.file.src).forEach(function(filepath) { grunt.helper('casperjs', filepath, function(err){ if (err) { grunt.warn(err); done(false); } else { done(); } }); }); }); grunt.registerHelper('casperjs', function(filepath, callback) { var command = 'casperjs "' + filepath + '"', exec = require('child_process').exec; function puts( error, stdout, stderr ) { grunt.log.write( '\nRunning tests from "' + filepath + '":\n' ); grunt.log.write( stdout ); //grunt.log.error( stderr ); if ( error !== null ) { callback(error); } else { callback(); } } exec( command, puts ); }); };
Fix mobilization block title edit
import React, { PropTypes } from 'react' import classnames from 'classnames' import { DropDownMenu, NavbarEditionWrapper } from '../../../../scripts/components' const MenuItems = ({ blocks, mobile, ...menuProps }) => { const items = blocks.map(block => ( <div key={block.id} className={classnames({ 'menu-item inline-block': !mobile })}> <NavbarEditionWrapper key={`navbar-edition-wrapper-${block.id}`} block={block} className='btn btn-transparent block white p2' {...menuProps} /> </div> )) return !mobile ? ( <div className='lg-show center'> <div className='bg-darken-4'> {items} </div> </div> ) : ( <div className='lg-hide'> <DropDownMenu wrapperClassName='absolute right-0 top-0 m1' buttonClassName='btn bg-darken-4 white rounded' menuClassName='rounded bg-darken-4 white top-0 right-0' menuStyle={{ marginTop: '40px' }} icon='bars' > {items} </DropDownMenu> </div> ) } MenuItems.defaultProps = { mobile: false } MenuItems.propTypes = { blocks: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number }) ).isRequired, mobile: PropTypes.bool } export default MenuItems
import React, { PropTypes } from 'react' import classnames from 'classnames' import { DropDownMenu, NavbarEditionWrapper } from '../../../../scripts/components' const MenuItems = ({ blocks, mobile, menuProps }) => { const items = blocks.map(block => ( <div key={block.id} className={classnames({ 'menu-item inline-block': !mobile })}> <NavbarEditionWrapper key={`navbar-edition-wrapper-${block.id}`} block={block} className='btn btn-transparent block white p2' {...menuProps} /> </div> )) return !mobile ? ( <div className='lg-show center'> <div className='bg-darken-4'> {items} </div> </div> ) : ( <div className='lg-hide'> <DropDownMenu wrapperClassName='absolute right-0 top-0 m1' buttonClassName='btn bg-darken-4 white rounded' menuClassName='rounded bg-darken-4 white top-0 right-0' menuStyle={{ marginTop: '40px' }} icon='bars' > {items} </DropDownMenu> </div> ) } MenuItems.defaultProps = { mobile: false } MenuItems.propTypes = { blocks: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number }) ).isRequired, mobile: PropTypes.bool } export default MenuItems
Enable DebugBar service when using local env
<?php namespace Strimoid\Providers; use GuzzleHttp\Client; use Illuminate\Support\ServiceProvider; use Pdp\Parser; use Pdp\PublicSuffixListManager; use Strimoid\Helpers\OEmbed; use Strimoid\Models\UserSettings; class AppServiceProvider extends ServiceProvider { /** * Register bindings in the container. * * @return void */ public function boot() { if ($this->app->environment('local')) { $this->app->register('Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider'); $this->app->register('Barryvdh\Debugbar\ServiceProvider'); } $rollbarToken = config('services.rollbar.access_token'); if (! empty($rollbarToken)) { $this->app->register('Jenssegers\Rollbar\RollbarServiceProvider'); } } /** * Register bindings in the container. * * @return void */ public function register() { $this->app->bind('guzzle', function () { return new Client([ 'connect_timeout' => 3, 'timeout' => 10, ]); }); $this->app->bind('settings', function () { return new UserSettings(); }); $this->app->bind('pdp', function () { $pslManager = new PublicSuffixListManager(); $parser = new Parser($pslManager->getList()); return $parser; }); $this->app->bind('oembed', function () { return new OEmbed(); }); } }
<?php namespace Strimoid\Providers; use GuzzleHttp\Client; use Illuminate\Support\ServiceProvider; use Pdp\Parser; use Pdp\PublicSuffixListManager; use Strimoid\Helpers\OEmbed; use Strimoid\Models\UserSettings; class AppServiceProvider extends ServiceProvider { /** * Register bindings in the container. * * @return void */ public function boot() { if ($this->app->environment('local')) { $this->app->register('Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider'); } $rollbarToken = config('services.rollbar.access_token'); if (! empty($rollbarToken)) { $this->app->register('Jenssegers\Rollbar\RollbarServiceProvider'); } } /** * Register bindings in the container. * * @return void */ public function register() { $this->app->bind('guzzle', function () { return new Client([ 'connect_timeout' => 3, 'timeout' => 10, ]); }); $this->app->bind('settings', function () { return new UserSettings(); }); $this->app->bind('pdp', function () { $pslManager = new PublicSuffixListManager(); $parser = new Parser($pslManager->getList()); return $parser; }); $this->app->bind('oembed', function () { return new OEmbed(); }); } }
Check if migration exists before publishing
<?php namespace Kyranb\Footprints; use Kyranb\Footprints\Facades\FootprintsFacade; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\ServiceProvider; class FootprintsServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. */ public function boot() { $this->publishConfig(); $this->publishMigration(); } /** * Publish Footprints configuration */ protected function publishConfig() { // Publish config files $this->publishes([ realpath(__DIR__.'/config/footprints.php') => config_path('footprints.php'), ]); } /** * Publish Footprints migration */ protected function publishMigration() { $published_migration = glob( database_path( '/migrations/*_create_visits_table.php' ) ); if( count( $published_migration ) === 0 ) { $this->publishes([ __DIR__.'/database/migrations/migrations.stub' => database_path('/migrations/'.date('Y_m_d_His').'_create_visits_table.php'), ], 'migrations'); } } /** * Register any package services. */ public function register() { // Bring in configuration values $this->mergeConfigFrom( __DIR__.'/config/footprints.php', 'footprints' ); $this->app->singleton(Footprints::class, function () { return new Footprints(); }); // Define alias 'Footprints' $this->app->booting(function () { $loader = AliasLoader::getInstance(); $loader->alias('Footprints', FootprintsFacade::class); }); } }
<?php namespace Kyranb\Footprints; use Kyranb\Footprints\Facades\FootprintsFacade; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\ServiceProvider; class FootprintsServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. */ public function boot() { $this->publishes([ realpath(__DIR__.'/config/footprints.php') => config_path('footprints.php'), ]); $this->publishes([ __DIR__.'/database/migrations/migrations.stub' => database_path('/migrations/'.date('Y_m_d_His').'_create_visits_table.php'), ], 'migrations'); } /** * Register any package services. */ public function register() { // Bring in configuration values $this->mergeConfigFrom( __DIR__.'/config/footprints.php', 'footprints' ); $this->app->singleton(Footprints::class, function () { return new Footprints(); }); // Define alias 'Footprints' $this->app->booting(function () { $loader = AliasLoader::getInstance(); $loader->alias('Footprints', FootprintsFacade::class); }); } }
Fix bug in setting attributes
package nl.surfnet.mockoleth.controllers; import java.io.UnsupportedEncodingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.ResponseBody; import nl.surfnet.mockoleth.model.Attribute; import nl.surfnet.mockoleth.model.Configuration; @Controller public class RestApiController { private final static Logger LOGGER = LoggerFactory .getLogger(RestApiController.class); @Autowired Configuration configuration; @RequestMapping("/test") public String test() throws UnsupportedEncodingException { return "test-view"; } @RequestMapping(value = {"/set-attribute"}, method = RequestMethod.POST) @ResponseBody public String setAttribute(@RequestBody Attribute attribute) throws UnsupportedEncodingException { LOGGER.info("Request to set attribute {} to {}", attribute.getValue(), attribute.getName()); configuration.getAttributes().put(attribute.getName(), attribute.getValue()); return "success"; } @RequestMapping(value = {"/reset"}, method = RequestMethod.POST) @ResponseBody public String reset() throws UnsupportedEncodingException { LOGGER.info("Resetting to default configuration"); return "success"; } }
package nl.surfnet.mockoleth.controllers; import java.io.UnsupportedEncodingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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.ResponseBody; import nl.surfnet.mockoleth.model.Attribute; import nl.surfnet.mockoleth.model.Configuration; @Controller public class RestApiController { private final static Logger LOGGER = LoggerFactory .getLogger(RestApiController.class); @Autowired Configuration configuration; @RequestMapping("/test") public String test() throws UnsupportedEncodingException { return "test-view"; } @RequestMapping(value = {"/set-attribute"}, method = RequestMethod.POST) @ResponseBody public String setAttribute(@RequestBody Attribute attribute) throws UnsupportedEncodingException { LOGGER.info("Request to set attribute {} to {}", attribute.getValue(), attribute.getName()); configuration.getAttributes().put(attribute.getValue(), attribute.getName()); return "success"; } @RequestMapping(value = {"/reset"}, method = RequestMethod.POST) @ResponseBody public String reset() throws UnsupportedEncodingException { LOGGER.info("Resetting to default configuration"); return "success"; } }
Make threadMessages function easier to import
function threadIdFor(message) { const recipienList = message.recipients || []; return recipienList.concat(message.sender). filter(character => character). map(character => character.id). sort(). join("-"); } export function threadMessages(messageList) { const threads = {}; messageList.forEach(message => { const threadId = threadIdFor(message); threads[threadId] = threads[threadId] || []; threads[threadId].push(message); }); return Object.keys(threads). map(threadId => threads[threadId]). sort((a, b) => { const lastTimestampA = a[a.length - 1].sentAt; const lastTimestampB = b[b.length - 1].sentAt; return parseInt(lastTimestampA.replace(/[^0-9]/g, ''), 10) - parseInt(lastTimestampB.replace(/[^0-9]/g, ''), 10); }). map(messageGroup => { const randomMessage = messageGroup[0]; const recipients = randomMessage.recipients || []; if (randomMessage.sender) { recipients.push(randomMessage.sender); } return { participants: recipients, messages: messageGroup }; }); } export default { threadMessages };
function threadIdFor(message) { const recipienList = message.recipients || []; return recipienList.concat(message.sender). filter(character => character). map(character => character.id). sort(). join("-"); } function threadMessages(messageList) { const threads = {}; messageList.forEach(message => { const threadId = threadIdFor(message); threads[threadId] = threads[threadId] || []; threads[threadId].push(message); }); return Object.keys(threads). map(threadId => threads[threadId]). sort((a, b) => { const lastTimestampA = a[a.length - 1].sentAt; const lastTimestampB = b[b.length - 1].sentAt; return parseInt(lastTimestampA.replace(/[^0-9]/g, ''), 10) - parseInt(lastTimestampB.replace(/[^0-9]/g, ''), 10); }). map(messageGroup => { const randomMessage = messageGroup[0]; const recipients = randomMessage.recipients || []; if (randomMessage.sender) { recipients.push(randomMessage.sender); } return { participants: recipients, messages: messageGroup }; }); } export default { threadMessages };
Fix errors in mysql rpc demo
<?php require('json-rpc.php'); if (function_exists('xdebug_disable')) { xdebug_disable(); } class MysqlDemo { public function query($query) { $link = new mysqli('localhost', 'user', 'password', 'db_name'); if (mysqli_connect_errno()) { throw new Exception("MySQL Connection: " . mysqli_connect_error()); } if (preg_match("/create|drop/", $query)) { throw new Exception("Sorry you are not allowed to execute '" . $query . "'"); } if (!preg_match("/(select.*from *test|insert *into *test.*|delete *from *test|update *test)/", $query)) { throw new Exception("Sorry you can't execute '" . $query . "' you are only allowed to select, insert, delete " . "or update 'test' table"); } if ($res = $link->query($query)) { if ($res === true) { return true; } if ($res->num_rows > 0) { while ($row = $res->fetch_array(MYSQLI_NUM)) { $result[] = $row; } return $result; } else { return array(); } } else { throw new Exception("MySQL Error: " . mysqli_error($link)); } } } handle_json_rpc(new MysqlDemo()); ?>
<?php require('json-rpc.php'); if (function_exists('xdebug_disable')) { xdebug_disable(); } $link = new mysqli('localhost', 'user', 'password', 'db_name'); class MysqlDemo { public function query($query) { global $link; if (preg_match("/create|drop/", $query)) { throw new Exception("Sorry you are not allowed to execute '" . $query . "'"); } if (!preg_match("/(select.*from *test|insert *into *test.*|delete *from *test|update *test)/", $query)) { throw new Exception("Sorry you can't execute '" . $query . "' you are only allowed to select, insert, delete " . "or update 'test' table"); } if ($res = $link->query($query)) { if ($res === true) { return true; } if ($res->num_rows > 0) { while ($row = $res->fetch_array(MYSQLI_NUM)) { $result[] = $row; } return $result; } else { return array(); } } else { throw new Exception("MySQL Error: " . mysql_error()); } } } handle_json_rpc(new MysqlDemo()); ?>
Print error in case of no results
import asyncio import json import urllib.parse import aiohttp import waterbug class Commands: @waterbug.expose class prisjakt: @waterbug.expose @asyncio.coroutine def search(responder, *line): qstring = urllib.parse.urlencode({ "class": "Search_Supersearch", "method": "search", "skip_login": 1, "modes": "product", "limit": 3, "q": responder.line }) url = "http://www.prisjakt.nu/ajax/server.php?{}".format(qstring) print("Running search") try: response = yield from asyncio.wait_for(aiohttp.request('GET', url), 5) except (asyncio.TimeoutError, aiohttp.HttpException): responder("Couldn't fetch result") return print("Ran search") body = json.loads((yield from response.read_and_close()).decode('utf-8')) product = body['message']['product'] if len(product['items']) > 0: for item in body['message']['product']['items']: responder("{name} ({price[display]}) - {url}".format(**item)) if product['more_hits_available']: responder("More: http://www.prisjakt.nu/search.php?{}".format( urllib.parse.urlencode({"s": responder.line}))) else: responder("No products found")
import asyncio import json import urllib.parse import aiohttp import waterbug class Commands: @waterbug.expose class prisjakt: @waterbug.expose @asyncio.coroutine def search(responder, *line): qstring = urllib.parse.urlencode({ "class": "Search_Supersearch", "method": "search", "skip_login": 1, "modes": "product", "limit": 3, "q": responder.line }) url = "http://www.prisjakt.nu/ajax/server.php?{}".format(qstring) print("Running search") try: response = yield from asyncio.wait_for(aiohttp.request('GET', url), 5) except (asyncio.TimeoutError, aiohttp.HttpException): responder("Couldn't fetch result") return print("Ran search") body = json.loads((yield from response.read_and_close()).decode('utf-8')) for item in body['message']['product']['items']: responder("{name} ({price[display]}) - {url}".format(**item)) if body['message']['product']['more_hits_available']: responder("More: http://www.prisjakt.nu/search.php?{}".format( urllib.parse.urlencode({"s": responder.line})))
Fix bootstrap js ref at guest layout
<!doctype html> <html> <head> @include('includes.head') </head> <body> <div id="wrapper"> @include('includes.header') @include('includes.sidebar') <!-- Page Content --> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> @yield("title") </div> <!-- /.col-lg-12 --> </div> @if (Session::has('message')) <div class="alert alert-info">{{ Session::get('message') }}</div> @endif @yield('content') </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <!-- jQuery --> <script src="{{URL::asset('js/jquery.min.js')}}"></script> <!-- Bootstrap Core JavaScript --> <script src="{{URL::asset('js/bootstrap.min.js')}}"></script> <!-- Metis Menu Plugin JavaScript --> <script src="{{URL::asset('js/metisMenu.min.js')}}"></script> <!-- Custom Theme JavaScript --> <script src="{{URL::asset('js/sb-admin-2.js')}}"></script> <script> @yield('script') </script> </body> </html>
<!doctype html> <html> <head> @include('includes.head') </head> <body> <div id="wrapper"> @include('includes.header') @include('includes.sidebar') <!-- Page Content --> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> @yield("title") </div> <!-- /.col-lg-12 --> </div> @if (Session::has('message')) <div class="alert alert-info">{{ Session::get('message') }}</div> @endif @yield('content') </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <!-- jQuery --> <script src="{{URL::asset('js/jquery.min.js')}}"></script> <!-- Bootstrap Core JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <!-- Metis Menu Plugin JavaScript --> <script src="{{URL::asset('js/metisMenu.min.js')}}"></script> <!-- Custom Theme JavaScript --> <script src="{{URL::asset('js/sb-admin-2.js')}}"></script> <script> @yield('script') </script> </body> </html>
Bring error message to the top, when clicked.
$(function(){ $('.holoform .field_error').live('click', function(e){ $('.field.recently-focused') .removeClass('recently-focused'); $(this) .closest('.field') .addClass('recently-focused'); }); $('ul.radio-optiongroups').each(function(){ var $list = $(this), $select = $('<select />', {'class': 'hg'}); $list .children('li.field').children('label').find('input[type="radio"]') .each(function(){ var $radio = $(this), $label = $radio.closest('label'); $select .append( $('<option />', { 'text': $label.text(), 'value': $radio.val() }) .data({ 'radio': $radio, 'suboptions': $radio.closest('li.field') }) ); if ($radio.is(':checked')) { $select.val($radio.val()); } $label .hide() .insertBefore($list); }); $select .appendTo($list.closest('fieldset').find('legend:first').html('')) .change(function(){ $(this).find(':selected').data('suboptions') .siblings(':visible') .slideUp() .end() .slideDown(); }) .find(':selected').data('suboptions') .siblings() .hide() .end() .show(); }); });
$(function(){ $('ul.radio-optiongroups').each(function(){ var $list = $(this), $select = $('<select />', {'class': 'hg'}); $list .children('li.field').children('label').find('input[type="radio"]') .each(function(){ var $radio = $(this), $label = $radio.closest('label'); $select .append( $('<option />', { 'text': $label.text(), 'value': $radio.val() }) .data({ 'radio': $radio, 'suboptions': $radio.closest('li.field') }) ); if ($radio.is(':checked')) { $select.val($radio.val()); } $label .hide() .insertBefore($list); }); $select .appendTo($list.closest('fieldset').find('legend:first').html('')) .change(function(){ $(this).find(':selected').data('suboptions') .siblings(':visible') .slideUp() .end() .slideDown(); }) .find(':selected').data('suboptions') .siblings() .hide() .end() .show(); }); });
Raise ImproperlyConfigured if resource has no scopes defined
from django.core.exceptions import ImproperlyConfigured from rest_framework.permissions import BasePermission SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OAuth2ScopePermission(BasePermission): """ Make sure request is authenticated and token has right scope set. """ def has_permission(self, request, view): token = request.auth read_only = request.method in SAFE_METHODS if not token: return False if hasattr(token, 'scope'): scopes = self.get_scopes(request, view) if scopes['required'] is not None: is_valid = token.is_valid(scopes['required']) if is_valid == False: return False else: # View did not define any required scopes is_valid = False # Check for method specific scopes if read_only: if scopes['read'] is not None: return token.is_valid(scopes['read']) else: if scopes['write'] is not None: return token.is_valid(scopes['write']) return is_valid assert False, ('OAuth2ScopePermission requires the ' '`oauth_api.authentication.OAuth2Authentication` ' 'class to be used.') def get_scopes(self, request, view): required = getattr(view, 'required_scopes', None) read = getattr(view, 'read_scopes', None) write = getattr(view, 'write_scopes', None) if not required and not read and not write: raise ImproperlyConfigured('OAuth protected resources requires scopes. Please add required_scopes, read_scopes or write_scopes.') return { 'required': required, 'read': read, 'write': write, }
from rest_framework.permissions import BasePermission SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OAuth2ScopePermission(BasePermission): """ Make sure request is authenticated and token has right scope set. """ def has_permission(self, request, view): token = request.auth read_only = request.method in SAFE_METHODS if not token: return False if hasattr(token, 'scope'): scopes = self.get_scopes(request, view) if scopes['required'] is not None: is_valid = token.is_valid(scopes['required']) if is_valid == False: return False else: # View did not define any required scopes is_valid = False # Check for method specific scopes if read_only: if scopes['read'] is not None: return token.is_valid(scopes['read']) else: if scopes['write'] is not None: return token.is_valid(scopes['write']) return is_valid return False def get_scopes(self, request, view): return { 'required': getattr(view, 'required_scopes', None), 'read': getattr(view, 'read_scopes', None), 'write': getattr(view, 'write_scopes', None), }
Support className & id attrs and stream of arrays.
import Bacon from "baconjs" import React from "react" export default React.createClass({ getInitialState() { return {} }, tryDispose() { const {dispose} = this.state if (dispose) { dispose() this.replaceState({}) } }, trySubscribe(props) { this.tryDispose() const {children} = props if (children) { let stream = children if (stream instanceof Array) { const {className, id} = props stream = <div className={className} id={id}>{stream}</div> } if (!(stream instanceof Bacon.Observable)) stream = Bacon.combineTemplate(stream) this.setState({dispose: stream.onValue(DOM => this.setState({DOM}))}) } }, componentWillReceiveProps(nextProps) { this.trySubscribe(nextProps) }, componentWillMount() { this.trySubscribe(this.props) const {willMount} = this.props !willMount || willMount(this) }, componentDidMount() { const {didMount} = this.props !didMount || didMount(this) }, shouldComponentUpdate(nextProps, nextState) { return nextState.DOM !== this.state.DOM }, componentWillUnmount() { this.tryDispose() const {willUnmount} = this.props !willUnmount || willUnmount(this) }, render() { const {DOM} = this.state if (!DOM) return null if (!(DOM instanceof Array)) return DOM const {className, id} = this.props return <div className={className} id={id}>{DOM}</div> } })
import Bacon from "baconjs" import React from "react" export default React.createClass({ getInitialState() { return {} }, tryDispose() { const {dispose} = this.state if (dispose) { dispose() this.replaceState({}) } }, trySubscribe(tDOM) { this.tryDispose() if (tDOM) this.setState( {dispose: (tDOM instanceof Bacon.Observable ? tDOM : Bacon.combineTemplate(tDOM instanceof Array ? <div>{tDOM}</div> : tDOM)) .onValue(DOM => this.setState({DOM}))}) }, componentWillReceiveProps(nextProps) { this.trySubscribe(nextProps.children) }, componentWillMount() { this.trySubscribe(this.props.children) const {willMount} = this.props !willMount || willMount(this) }, componentDidMount() { const {didMount} = this.props !didMount || didMount(this) }, shouldComponentUpdate(nextProps, nextState) { return nextState.DOM !== this.state.DOM }, componentWillUnmount() { this.tryDispose() const {willUnmount} = this.props !willUnmount || willUnmount(this) }, render() { const {DOM} = this.state return DOM ? DOM : null } })
Add server as a task, allowing webserver and watch to run simutanously
module.exports = function(grunt) { grunt.initConfig({ connect: { server: { options: { port: 1337, base: 'dist', } } }, rubyHaml: { dist: { files: grunt.file.expandMapping(['views/*.haml'], 'dist/', { rename: function(base, path) { return base + path.replace(/\.haml$/, '.html').replace('views/', ''); } }) } }, sass: { dist: { files: { 'dist/assets/stylesheets/main.css' : 'assets/stylesheets/main.scss' } } }, watch: { haml: { files: ['views/**/*.haml'], tasks: ['rubyHaml'], options: { livereload: true } }, sass: { files: ['assets/stylesheets/**/*.scss'], tasks: ['sass'], options: { livereload: true } } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.task.loadNpmTasks('grunt-ruby-haml'); grunt.task.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.registerTask('default', ['rubyHaml', 'sass']) grunt.registerTask('server', ['connect', 'watch']) }
module.exports = function(grunt) { grunt.initConfig({ connect: { server: { options: { port: 1337, base: 'dist', keepalive: true } } }, rubyHaml: { dist: { files: grunt.file.expandMapping(['views/*.haml'], 'dist/', { rename: function(base, path) { return base + path.replace(/\.haml$/, '.html').replace('views/', ''); } }) } }, sass: { dist: { files: { 'dist/assets/stylesheets/main.css' : 'assets/stylesheets/main.scss' } } }, watch: { haml: { files: ['views/**/*.haml'], tasks: ['rubyHaml'], options: { livereload: true } }, sass: { files: ['assets/stylesheets/**/*.scss'], tasks: ['sass'], options: { livereload: true } } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.task.loadNpmTasks('grunt-ruby-haml'); grunt.task.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.registerTask('default', ['rubyHaml', 'sass']) }
Put Project "Manage" item back Summary: Ref T12174. This isn't really a "newManageItem()" since Projects have a separate manage screen. That is, I incorrectly changed the "Manage [This Project]" item into a "Edit Menu" item, so some options (like "Archive Project") incorrectly became inaccessible. Test Plan: Viewed a project, saw the right menu item, clicked it, could archive/etc project. Also edited the menu. Reviewers: chad Reviewed By: chad Maniphest Tasks: T12174 Differential Revision: https://secure.phabricator.com/D17275
<?php final class PhabricatorProjectProfileMenuEngine extends PhabricatorProfileMenuEngine { protected function isMenuEngineConfigurable() { return true; } protected function isMenuEnginePersonalizable() { return false; } public function getItemURI($path) { $project = $this->getProfileObject(); $id = $project->getID(); return "/project/{$id}/item/{$path}"; } protected function getBuiltinProfileItems($object) { $items = array(); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_PROFILE) ->setMenuItemKey(PhabricatorProjectDetailsProfileMenuItem::MENUITEMKEY); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_POINTS) ->setMenuItemKey(PhabricatorProjectPointsProfileMenuItem::MENUITEMKEY); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_WORKBOARD) ->setMenuItemKey(PhabricatorProjectWorkboardProfileMenuItem::MENUITEMKEY); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_MEMBERS) ->setMenuItemKey(PhabricatorProjectMembersProfileMenuItem::MENUITEMKEY); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_SUBPROJECTS) ->setMenuItemKey( PhabricatorProjectSubprojectsProfileMenuItem::MENUITEMKEY); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_MANAGE) ->setMenuItemKey(PhabricatorProjectManageProfileMenuItem::MENUITEMKEY); return $items; } }
<?php final class PhabricatorProjectProfileMenuEngine extends PhabricatorProfileMenuEngine { protected function isMenuEngineConfigurable() { return true; } protected function isMenuEnginePersonalizable() { return false; } public function getItemURI($path) { $project = $this->getProfileObject(); $id = $project->getID(); return "/project/{$id}/item/{$path}"; } protected function getBuiltinProfileItems($object) { $items = array(); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_PROFILE) ->setMenuItemKey(PhabricatorProjectDetailsProfileMenuItem::MENUITEMKEY); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_POINTS) ->setMenuItemKey(PhabricatorProjectPointsProfileMenuItem::MENUITEMKEY); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_WORKBOARD) ->setMenuItemKey(PhabricatorProjectWorkboardProfileMenuItem::MENUITEMKEY); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_MEMBERS) ->setMenuItemKey(PhabricatorProjectMembersProfileMenuItem::MENUITEMKEY); $items[] = $this->newItem() ->setBuiltinKey(PhabricatorProject::ITEM_SUBPROJECTS) ->setMenuItemKey( PhabricatorProjectSubprojectsProfileMenuItem::MENUITEMKEY); $items[] = $this->newManageItem(); return $items; } }
Update group finder to new schemas
from .contentbase import LOCATION_ROOT CHERRY_LAB_UUID = 'cfb789b8-46f3-4d59-a2b3-adc39e7df93a' def groupfinder(login, request): if ':' not in login: return None namespace, localname = login.split(':', 1) user = None # We may get called before the context is found and the root set root = request.registry[LOCATION_ROOT] if namespace == 'remoteuser': if localname in ['TEST', 'IMPORT']: return ['group:admin'] if namespace in ('mailto', 'remoteuser'): users = root.by_item_type['user'] try: user = users[localname] except KeyError: return None elif namespace == 'accesskey': access_keys = root.by_item_type['access_key'] try: access_key = access_keys[localname] except KeyError: return None userid = access_key.properties['user_uuid'] user = root.by_item_type['user'][userid] if user is None: return None principals = ['userid:%s' % user.uuid] lab = user.properties.get('lab') if lab: principals.append('lab:%s' % lab) submits_for = user.properties.get('submits_for', []) principals.extend('lab:%s' % lab_uuid for lab_uuid in submits_for) principals.extend('submits_for:%s' % lab_uuid for lab_uuid in submits_for) if CHERRY_LAB_UUID in submits_for: principals.append('group:admin') return principals
from .contentbase import LOCATION_ROOT CHERRY_LAB_UUID = 'cfb789b8-46f3-4d59-a2b3-adc39e7df93a' def groupfinder(login, request): if ':' not in login: return None namespace, localname = login.split(':', 1) user = None # We may get called before the context is found and the root set root = request.registry[LOCATION_ROOT] if namespace == 'remoteuser': if localname in ['TEST', 'IMPORT']: return ['group:admin'] if namespace in ('mailto', 'remoteuser'): users = root.by_item_type['user'] try: user = users[localname] except KeyError: return None elif namespace == 'accesskey': access_keys = root.by_item_type['access_key'] try: access_key = access_keys[localname] except KeyError: return None userid = access_key.properties['user_uuid'] user = root.by_item_type['user'][userid] if user is None: return None principals = ['userid:%s' % user.uuid] lab_uuids = user.properties.get('lab_uuids', []) principals.extend('lab:' + lab_uuid for lab_uuid in lab_uuids) if CHERRY_LAB_UUID in lab_uuids: principals.append('group:admin') return principals
Fix payload sent to RabbitMQ.
'use strict'; const amqplib = require('amqplib'); const amqpUri = require('amqp-uri'); /** * Nortstar client service. */ module.exports = { /** * Configure RabbitMQ client. */ getClient() { if (!this.client) { this.client = amqplib.connect(amqpUri(sails.config.amqp.connection)); } return this.client; }, getChannel() { return this.getClient().then(conn => conn.createChannel()); }, publishUserPasswordResetTransactional(message) { const queueName = 'transactionalQueue'; const exchangeName = 'transactionalExchange'; const bindingPattern = '*.*.transactional'; const routingKey = 'user.password_reset.transactional'; const msgBuffer = new Buffer(JSON.stringify(message), 'utf-8'); this.bindQueueToExchange(queueName, exchangeName, bindingPattern) .then((channel) => { channel.publish(exchangeName, routingKey, msgBuffer) .then(result => result); }); }, bindQueueToExchange(queueName, exchangeName, routingKey) { return new Promise((resolve, reject) => { this.getChannel() .then((channel) => { channel.assertExchange(exchangeName, 'topic').then(() => { channel.assertQueue(queueName).then(() => { channel.bindQueue(queueName, exchangeName, routingKey) .then(() => resolve(channel)); }); }); }) .catch(error => reject(error)); }); }, };
'use strict'; const amqplib = require('amqplib'); const amqpUri = require('amqp-uri'); /** * Nortstar client service. */ module.exports = { /** * Configure RabbitMQ client. */ getClient() { if (!this.client) { this.client = amqplib.connect(amqpUri(sails.config.amqp.connection)); } return this.client; }, getChannel() { return this.getClient().then(conn => conn.createChannel()); }, publishUserPasswordResetTransactional(message) { const queueName = 'transactionalQueue'; const exchangeName = 'transactionalExchange'; const bindingPattern = '*.*.transactional'; const routingKey = 'user.password_reset.transactional'; const msgBuffer = new Buffer(message.toString()); this.bindQueueToExchange(queueName, exchangeName, bindingPattern) .then((channel) => { channel.publish(exchangeName, routingKey, msgBuffer) .then(result => result); }); }, bindQueueToExchange(queueName, exchangeName, routingKey) { return new Promise((resolve, reject) => { this.getChannel() .then((channel) => { channel.assertExchange(exchangeName, 'topic').then(() => { channel.assertQueue(queueName).then(() => { channel.bindQueue(queueName, exchangeName, routingKey) .then(() => resolve(channel)); }); }); }) .catch(error => reject(error)); }); }, };
Use the correct module name for 'msgpack' Python module
#!/usr/bin/env python import os import sys from serfclient import __version__ try: from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) except ImportError: from distutils.core import setup PyTest = lambda x: x try: long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() except: long_description = None setup( name='serfclient', version=__version__, description='Python client for the Serf orchestration tool', long_description=long_description, url='TBD', author='Kushal Pisavadia', author_email='[email protected]', maintainer='Kushal Pisavadia', maintainer_email='[email protected]', keywords=['Serf', 'orchestration', 'service discovery'], license='MIT', packages=['serfclient'], install_requires=['msgpack-python'], tests_require=['pytest'], cmdclass={'test': PyTest} )
#!/usr/bin/env python import os import sys from serfclient import __version__ try: from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) except ImportError: from distutils.core import setup PyTest = lambda x: x try: long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() except: long_description = None setup( name='serfclient', version=__version__, description='Python client for the Serf orchestration tool', long_description=long_description, url='TBD', author='Kushal Pisavadia', author_email='[email protected]', maintainer='Kushal Pisavadia', maintainer_email='[email protected]', keywords=['Serf', 'orchestration', 'service discovery'], license='MIT', packages=['serfclient'], install_requires=['msgpack'], tests_require=['pytest'], cmdclass={'test': PyTest} )
Set log level to info Set log level to info for presentation
package game; import com.badlogic.gdx.Game; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import game.MenuScreens.MainMenu; /** * Created by eriks on 26/10/2016. */ /** * Games entry point. */ public class BlueSky extends Game { // Game world size in arbitrary scale, these are not pixels public static final int GAME_WIDTH = 640; public static final int GAME_HEIGHT = 640; // Game version for global use public static final double VERSION = 0.2; SpriteBatch batch; private static SimpleLogger myLog = SimpleLogger.getLogger(); /** * Analogue to instantiation. Loads all the assets to the memory. Creates a {@link SimpleLogger} and {@link SpriteBatch}. */ public void create(){ batch = new SpriteBatch(); // Pre-loading all the assets for the game Assets.load(); myLog.setLogFile("BlueSky"); myLog.setLogLevel(SimpleLogger.INFO); myLog.info("Starting..."); this.setScreen(new MainMenu(this)); } /** * Renders a {@link Screen} */ public void render(){ super.render(); } /** * Disposes of all teh assets that are not collected by garbage collector. This method runs automatically. */ public void dispose(){ batch.dispose(); Assets.dispose(); } }
package game; import com.badlogic.gdx.Game; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import game.MenuScreens.MainMenu; /** * Created by eriks on 26/10/2016. */ /** * Games entry point. */ public class BlueSky extends Game { // Game world size in arbitrary scale, these are not pixels public static final int GAME_WIDTH = 640; public static final int GAME_HEIGHT = 640; // Game version for global use public static final double VERSION = 0.2; SpriteBatch batch; private static SimpleLogger myLog = SimpleLogger.getLogger(); /** * Analogue to instantiation. Loads all the assets to the memory. Creates a {@link SimpleLogger} and {@link SpriteBatch}. */ public void create(){ batch = new SpriteBatch(); // Pre-loading all the assets for the game Assets.load(); myLog.setLogFile("BlueSky"); myLog.setLogLevel(SimpleLogger.DEBUG); myLog.info("Starting..."); this.setScreen(new MainMenu(this)); } /** * Renders a {@link Screen} */ public void render(){ super.render(); } /** * Disposes of all teh assets that are not collected by garbage collector. This method runs automatically. */ public void dispose(){ batch.dispose(); Assets.dispose(); } }
Fix issue where multiple directories and files weren't linted
'use strict'; var fs = require('vow-fs'); var linter = require('./linter'); var Vow = require('Vow'); var LessHint = function () { }; LessHint.prototype.checkDirectory = function (path) { return fs.listDir(path).then(function (files) { return Vow.all(files.map(function(file) { var fullPath = path + '/' + file; return fs.stat(fullPath).then(function (stats) { if (stats.isDirectory()) { return this.checkDirectory(fullPath); } if (file.substr(0, 1) === '.') { return; } return this.checkFile(fullPath); }, this); }, this)).then(function(errors) { return [].concat.apply([], errors); }); }, this); }; LessHint.prototype.checkFile = function (path) { return fs.read(path, 'utf8').then(function (data) { return this.checkString(data, path); }, this); }; LessHint.prototype.checkPath = function (path) { return fs.stat(path).then(function (stats) { if (stats.isDirectory()) { return this.checkDirectory(path); } return this.checkFile(path); }, this); }; LessHint.prototype.checkString = function (input, path) { return linter.lint(input, path, this.config); }; LessHint.prototype.configure = function (config) { this.config = config; }; module.exports = LessHint;
'use strict'; var fs = require('vow-fs'); var linter = require('./linter'); var LessHint = function () { }; LessHint.prototype.checkDirectory = function (path) { return fs.listDir(path).then(function (files) { return files.forEach(function (file) { var fullPath = path + '/' + file; return fs.stat(fullPath).then(function (stats) { if (stats.isDirectory()) { return this.checkDirectory(fullPath); } if (file.substr(0, 1) === '.') { return; } return this.checkFile(fullPath); }, this); }, this); }, this); }; LessHint.prototype.checkFile = function (path) { return fs.read(path, 'utf8').then(function (data) { return this.checkString(data, path); }, this); }; LessHint.prototype.checkPath = function (path) { return fs.stat(path).then(function (stats) { if (stats.isDirectory()) { return this.checkDirectory(path); } return this.checkFile(path); }, this); }; LessHint.prototype.checkString = function (input, path) { return linter.lint(input, path, this.config); }; LessHint.prototype.configure = function (config) { this.config = config; }; module.exports = LessHint;
Update idSelector to match latest gonzales AST
'use strict'; var path = require('path'); module.exports = function (options) { var filename = path.basename(options.path); var config = options.config; var node = options.node; var excludes; var message; var start; // Bail if the linter isn't wanted if (!config.idSelector || (config.idSelector && !config.idSelector.enabled)) { return null; } // Not applicable, bail if (node.type !== 'selector') { return null; } excludes = config.idSelector.exclude.map(function (id) { // Remove # return id.replace(/^\#/, ''); }); node.forEach('simpleSelector', function (selector) { selector.content.some(function (selector) { var name = selector.first('ident').content; if (selector.type === 'id' && excludes.indexOf(name) === -1) { message = 'Selectors should not use IDs.'; start = selector.start; return true; } return false; }); }); if (message) { return { column: start.column, file: filename, line: start.line, linter: 'idSelector', message: message }; } return true; };
'use strict'; var path = require('path'); module.exports = function (options) { var filename = path.basename(options.path); var config = options.config; var node = options.node; var excludes; var message; var start; // Bail if the linter isn't wanted if (!config.idSelector || (config.idSelector && !config.idSelector.enabled)) { return null; } // Not applicable, bail if (node.type !== 'selector') { return null; } excludes = config.idSelector.exclude.map(function (id) { // Remove # return id.replace(/^\#/, ''); }); node.forEach('simpleSelector', function (selector) { selector.content.some(function (selector) { var name = selector.content[0]; if (selector.type === 'id' && excludes.indexOf(name) === -1) { message = 'Selectors should not use IDs.'; start = selector.start; return true; } return false; }); }); if (message) { return { column: start.column, file: filename, line: start.line, linter: 'idSelector', message: message }; } return true; };
Clear the client before every test
<?php namespace LaVestima\HannaAgency\InfrastructureBundle\Tests; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class BaseWebTestCase extends WebTestCase { protected $client; public function __construct($name = null, array $data = [], $dataName = '') { $this->createNewClient(); parent::__construct($name, $data, $dataName); } protected function createNewClient() { $this->client = static::createClient(); } public function setUp() { $this->createNewClient(); } protected function logInAdmin() { $this->client = static::createClient([], [ 'PHP_AUTH_USER' => 'admin', 'PHP_AUTH_PW' => 'admin', ]); } protected function logInCustomer() { $this->client = static::createClient([], [ 'PHP_AUTH_USER' => 'customer', 'PHP_AUTH_PW' => 'customer', ]); } // protected function logInUser() // { // $this->client = static::createClient([], [ // 'PHP_AUTH_USER' => 'user', // 'PHP_AUTH_PW' => 'user', // ]); // } protected function logInGuest() { $this->client = static::createClient([], [ 'PHP_AUTH_USER' => 'guest', 'PHP_AUTH_PW' => 'guest', ]); } }
<?php namespace LaVestima\HannaAgency\InfrastructureBundle\Tests; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class BaseWebTestCase extends WebTestCase { protected $client; public function __construct($name = null, array $data = [], $dataName = '') { $this->client = static::createClient(); parent::__construct($name, $data, $dataName); } // public function setUp() // { // // } protected function logInAdmin() { $this->client = static::createClient([], [ 'PHP_AUTH_USER' => 'admin', 'PHP_AUTH_PW' => 'admin', ]); } protected function logInCustomer() { $this->client = static::createClient([], [ 'PHP_AUTH_USER' => 'customer', 'PHP_AUTH_PW' => 'customer', ]); } // protected function logInUser() // { // $this->client = static::createClient([], [ // 'PHP_AUTH_USER' => 'user', // 'PHP_AUTH_PW' => 'user', // ]); // } protected function logInGuest() { $this->client = static::createClient([], [ 'PHP_AUTH_USER' => 'guest', 'PHP_AUTH_PW' => 'guest', ]); } }
Replace double quote by simple quote, no need interpolation
#! /usr/bin/env python2.7 from collections import Counter from pprint import pprint from re import search from sys import argv def count_extension(filename): with open(filename, 'r') as file: # New empty counter. ext_dict = Counter() for line in file: # Remove newlines / carriage returns. line = line.strip() # Should be a non-empty line, with 200 OK and GET method. if line and 'GET' in line and line.split('|')[13] == '200': ext_line = line.split('|')[3] if '.' in ext_line: # extensions should be like this regex. clean_ext = search('[a-zA-Z0-9]+', \ ext_line.split('.')[-1]) # If regex returning None or a digit, do not add it. if clean_ext is not None and \ clean_ext.group(0).isdigit() is not True: # lower the extension. ext_dict[clean_ext.group(0).lower()] += 1 pprint(sorted(((v,k) for k,v in ext_dict.iteritems()), reverse=True)) if __name__ == '__main__': count_extension(argv[1])
#! /usr/bin/env python2.7 from collections import Counter from pprint import pprint from re import search from sys import argv def count_extension(filename): with open(filename, 'r') as file: # New empty counter. ext_dict = Counter() for line in file: # Remove newlines / carriage returns. line = line.strip() # Should be a non-empty line, with 200 OK and GET method. if line and "GET" in line and line.split('|')[13] == '200': ext_line = line.split('|')[3] if '.' in ext_line: # extensions should be like this regex. clean_ext = search('[a-zA-Z0-9]+', \ ext_line.split('.')[-1]) # If regex returning None or a digit, do not add it. if clean_ext is not None and \ clean_ext.group(0).isdigit() is not True: # lower the extension. ext_dict[clean_ext.group(0).lower()] += 1 pprint(sorted(((v,k) for k,v in ext_dict.iteritems()), reverse=True)) if __name__ == '__main__': count_extension(argv[1])
Fix mconsole options for php 7.2
<?php namespace Milax\Mconsole\Models; use Illuminate\Database\Eloquent\Model; class MconsoleOption extends Model { use \Cacheable; protected $fillable = ['group', 'label', 'key', 'value', 'type', 'options', 'enabled', 'rules']; protected $casts = [ 'options' => 'array', 'rules' => 'array', ]; /** * Get option value by its key * * @param string $key * @return mixed */ public static function getByKey($key) { if ($option = self::getCached()->where('key', $key)->first()) { if (is_array($option->options) && count($option->options) >= 2) { if (isset($option->options[0]) && isset($option->options[1])) { switch ($option->value) { case '1': return true; case '0': return false; } } else { return $option->value; } } else { if (is_array($option->rules) && in_array('integer', $option->rules)) { return (int) $option->value; } else { return $option->value; } } } else { return null; } } }
<?php namespace Milax\Mconsole\Models; use Illuminate\Database\Eloquent\Model; class MconsoleOption extends Model { use \Cacheable; protected $fillable = ['group', 'label', 'key', 'value', 'type', 'options', 'enabled', 'rules']; protected $casts = [ 'options' => 'array', 'rules' => 'array', ]; /** * Get option value by its key * * @param string $key * @return mixed */ public static function getByKey($key) { if ($option = self::getCached()->where('key', $key)->first()) { if (count($option->options) >= 2) { if (isset($option->options[0]) && isset($option->options[1])) { switch ($option->value) { case '1': return true; case '0': return false; } } else { return $option->value; } } else { if (is_array($option->rules) && in_array('integer', $option->rules)) { return (int) $option->value; } else { return $option->value; } } } else { return null; } } }
Define precedence and associativity for operators
# '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3} operators = { '+': {'prec': 10, 'assoc': 'left'}, '*': {'prec': 20, 'assoc': 'left'} } class TokenStream: def __init__(self, input_stream): self.input_stream = input_stream def is_whitespace(self, char): return char in ' \t' def is_digit(self, char): return char.isdigit() def is_operator(self, char): return char in operators def read_while(self, predicate_func): _str = "" while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()): _str += self.input_stream.next() return _str def read_number(self): number = self.read_while(self.is_digit) return {'type': 'num', 'value': int(number)} def read_operator(self): operator = self.read_while(self.is_operator) return {'type': 'op', 'value': operator} def read_next(self): _ = self.read_while(self.is_whitespace) if self.input_stream.is_eof(): return None char = self.input_stream.peek() if self.is_digit(char): return self.read_number() if self.is_operator(char): return self.read_operator() self.input_stream.croak("Can't handle character: " + char) self.input_stream.next() return None
# '2+3' -> {type:num, value: 2}, {type:op, value:'+'}, {type:num, value: 3} class TokenStream: def __init__(self, input_stream): self.input_stream = input_stream def is_whitespace(self, char): return char in ' \t' def is_digit(self, char): return char.isdigit() def is_operator(self, char): return char in '+*' def read_while(self, predicate_func): _str = "" while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()): _str += self.input_stream.next() return _str def read_number(self): number = self.read_while(self.is_digit) return {'type': 'num', 'value': int(number)} def read_operator(self): operator = self.read_while(self.is_operator) return {'type': 'op', 'value': operator} def read_next(self): _ = self.read_while(self.is_whitespace) if self.input_stream.is_eof(): return None char = self.input_stream.peek() if self.is_digit(char): return self.read_number() if self.is_operator(char): return self.read_operator() self.input_stream.croak("Can't handle character: " + char) self.input_stream.next() return None
Fix another unicode literal for Python 3.2
import sys import unittest import pexpect from pexpect import replwrap class REPLWrapTestCase(unittest.TestCase): def test_python(self): py = replwrap.python(sys.executable) res = py.run_command("5+6") self.assertEqual(res.strip(), "11") def test_multiline(self): py = replwrap.python(sys.executable) res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) # Should raise ValueError if input is incomplete try: py.run_command("for a in range(3):") except ValueError: pass else: assert False, "Didn't raise ValueError for incorrect input" # Check that the REPL was reset (SIGINT) after the incomplete input res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) def test_existing_spawn(self): child = pexpect.spawnu("python") repl = replwrap.REPLWrapper(child, replwrap.u(">>> "), "import sys; sys.ps1=%r" % replwrap.PEXPECT_PROMPT) res = repl.run_command("print(7*6)") self.assertEqual(res.strip(), "42") if __name__ == '__main__': unittest.main()
import sys import unittest import pexpect from pexpect import replwrap class REPLWrapTestCase(unittest.TestCase): def test_python(self): py = replwrap.python(sys.executable) res = py.run_command("5+6") self.assertEqual(res.strip(), "11") def test_multiline(self): py = replwrap.python(sys.executable) res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) # Should raise ValueError if input is incomplete try: py.run_command("for a in range(3):") except ValueError: pass else: assert False, "Didn't raise ValueError for incorrect input" # Check that the REPL was reset (SIGINT) after the incomplete input res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) def test_existing_spawn(self): child = pexpect.spawnu("python") repl = replwrap.REPLWrapper(child, u">>> ", "import sys; sys.ps1=%r" % replwrap.PEXPECT_PROMPT) res = repl.run_command("print(7*6)") self.assertEqual(res.strip(), "42") if __name__ == '__main__': unittest.main()
Fix "Path must be a string" issue with jslint
module.exports = function (grunt) { var DEV = "production" !== process.env.NODE_ENV; var PUBLIC_DEST = "../public"; require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.registerTask('default', ['build', 'watch']); grunt.registerTask('build', ['jshint', 'browserify', 'uglify', 'stylus']); // Project configuration. grunt.initConfig({ jshint: { options: { jshintrc: ".jshintrc", convertJSX: true, reporterOutput: "" }, src: ['src/**/*.js'] }, uglify: { prod: { src: PUBLIC_DEST+'/bundle.js', dest: PUBLIC_DEST+'/bundle.min.js' } }, stylus: { app: { src: 'src/index.styl', dest: PUBLIC_DEST+'/bundle.css' } }, browserify: { app: { src: 'src/index.js', dest: PUBLIC_DEST+'/bundle.js', options: { transform: ["reactify"], debug: DEV } } }, watch: { options: { livereload: 35092, debounceDelay: 1000 // Because of PlayFramework apparently }, js: { files: ['src/**/*.js'], tasks: ['jshint', 'browserify'], }, css: { files: ['src/**/*.styl'], tasks: ['stylus'] } } }); };
module.exports = function (grunt) { var DEV = "production" !== process.env.NODE_ENV; var PUBLIC_DEST = "../public"; require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.registerTask('default', ['build', 'watch']); grunt.registerTask('build', ['jshint', 'browserify', 'uglify', 'stylus']); // Project configuration. grunt.initConfig({ jshint: { options: { jshintrc: ".jshintrc", convertJSX: true }, src: ['src/**/*.js'] }, uglify: { prod: { src: PUBLIC_DEST+'/bundle.js', dest: PUBLIC_DEST+'/bundle.min.js' } }, stylus: { app: { src: 'src/index.styl', dest: PUBLIC_DEST+'/bundle.css' } }, browserify: { app: { src: 'src/index.js', dest: PUBLIC_DEST+'/bundle.js', options: { transform: ["reactify"], debug: DEV } } }, watch: { options: { livereload: 35092, debounceDelay: 1000 // Because of PlayFramework apparently }, js: { files: ['src/**/*.js'], tasks: ['jshint', 'browserify'], }, css: { files: ['src/**/*.styl'], tasks: ['stylus'] } } }); };
Add method to get handler in sound rewriter
package us.myles.ViaVersion.api.rewriters; import us.myles.ViaVersion.api.protocol.ClientboundPacketType; import us.myles.ViaVersion.api.protocol.Protocol; import us.myles.ViaVersion.api.remapper.PacketHandler; import us.myles.ViaVersion.api.remapper.PacketRemapper; import us.myles.ViaVersion.api.type.Type; public class SoundRewriter { protected final Protocol protocol; protected final IdRewriteFunction idRewriter; public SoundRewriter(Protocol protocol) { this.protocol = protocol; this.idRewriter = id -> protocol.getMappingData().getSoundMappings().getNewId(id); } public SoundRewriter(Protocol protocol, IdRewriteFunction idRewriter) { this.protocol = protocol; this.idRewriter = idRewriter; } // The same for entity sound public void registerSound(ClientboundPacketType packetType) { protocol.registerOutgoing(packetType, new PacketRemapper() { @Override public void registerMap() { map(Type.VAR_INT); // Sound Id handler(getSoundHandler()); } }); } public PacketHandler getSoundHandler() { return wrapper -> { int soundId = wrapper.get(Type.VAR_INT, 0); int mappedId = idRewriter.rewrite(soundId); if (mappedId == -1) { wrapper.cancel(); } else if (soundId != mappedId) { wrapper.set(Type.VAR_INT, 0, mappedId); } }; } }
package us.myles.ViaVersion.api.rewriters; import us.myles.ViaVersion.api.protocol.ClientboundPacketType; import us.myles.ViaVersion.api.protocol.Protocol; import us.myles.ViaVersion.api.remapper.PacketRemapper; import us.myles.ViaVersion.api.type.Type; public class SoundRewriter { protected final Protocol protocol; protected final IdRewriteFunction idRewriter; public SoundRewriter(Protocol protocol) { this.protocol = protocol; this.idRewriter = id -> protocol.getMappingData().getSoundMappings().getNewId(id); } public SoundRewriter(Protocol protocol, IdRewriteFunction idRewriter) { this.protocol = protocol; this.idRewriter = idRewriter; } // The same for entity sound public void registerSound(ClientboundPacketType packetType) { protocol.registerOutgoing(packetType, new PacketRemapper() { @Override public void registerMap() { map(Type.VAR_INT); // Sound Id handler(wrapper -> { int soundId = wrapper.get(Type.VAR_INT, 0); int mappedId = idRewriter.rewrite(soundId); if (mappedId == -1) { wrapper.cancel(); } else if (soundId != mappedId) { wrapper.set(Type.VAR_INT, 0, mappedId); } }); } }); } }
Add all the paths so includes/extends work
from collections import defaultdict from django.template.base import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) for path in self.template_dirs: loader.add_path(path) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): try: tmpl = loader.load_template(template_name) except loader.TemplateNotFound: raise TemplateDoesNotExist(template_name) except Exception as e: raise TemplateSyntaxError(e).with_traceback(e.__traceback__) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['user'] = request.user context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) ctx = defaultdict(str) ctx.update(context) return self.template(ctx)
from collections import defaultdict from django.template.base import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEngine): def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() super(KnightsTemplater, self).__init__(params) def from_string(self, template_code): tmpl = compiler.kompile(template_code) return Template(tmpl) def get_template(self, template_name): try: tmpl = loader.load_template(template_name, self.template_dirs) except loader.TemplateNotFound: raise TemplateDoesNotExist(template_name) except Exception as e: raise TemplateSyntaxError(e).with_traceback(e.__traceback__) return Template(tmpl) class Template(object): def __init__(self, template): self.template = template def render(self, context=None, request=None): if context is None: context = {} if request is not None: context['user'] = request.user context['request'] = request context['csrf_input'] = csrf_input_lazy(request) context['csrf_token'] = csrf_token_lazy(request) ctx = defaultdict(str) ctx.update(context) return self.template(ctx)
Remove reference to deprecated TicketDB class
<?php ini_set('display_errors', 1); error_reporting(E_ALL); require_once('class.TicketAdminPage.php'); require_once('class.FlipsideTicketDB.php'); $page = new TicketAdminPage('Burning Flipside - Tickets'); $page->add_js(JS_DATATABLE); $page->add_css(CSS_DATATABLE); $page->add_js_from_src('js/sold_tickets.js'); $page->body .= ' <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Sold Tickets</h1> </div> </div> <div class="row"> <table class="table" id="tickets"> <thead> <tr> <th>Short Code</th> <th>First Name</th> <th>Last Name</th> <th>Type</th> </tr> </thead> <tbody></tbody> </table> </div> </div> </div> '; $page->print_page(); // vim: set tabstop=4 shiftwidth=4 expandtab: ?>
<?php ini_set('display_errors', 1); error_reporting(E_ALL); require_once('class.TicketAdminPage.php'); require_once('class.FlipsideTicketDB.php'); $page = new TicketAdminPage('Burning Flipside - Tickets'); $page->add_js(JS_DATATABLE); $page->add_css(CSS_DATATABLE); $page->add_js_from_src('js/sold_tickets.js'); $db = new FlipsideTicketDB(); $ticket_count = $db->getTicketCount(); if($ticket_count == 0 || $ticket_count === FALSE) { $page->add_notification('There are currently no tickets created! Click <a href="ticket_gen.php" class="alert-link">here</a> to generate tickets.'); } $page->body .= ' <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Sold Tickets</h1> </div> </div> <div class="row"> <table class="table" id="tickets"> <thead> <tr> <th>Short Code</th> <th>First Name</th> <th>Last Name</th> <th>Type</th> </tr> </thead> <tbody></tbody> </table> </div> </div> </div> '; $page->print_page(); // vim: set tabstop=4 shiftwidth=4 expandtab: ?>
Load modules and set readtables only once Don't re-setup modules and readtables for each file to prevent the module cache from breaking the plugin when processing multiple files.
var sweet = require('sweet.js'); var gutil = require('gulp-util'); var applySourceMap = require('vinyl-sourcemaps-apply'); var es = require('event-stream'); var merge = require('merge'); module.exports = function(opts) { if(opts.modules){ opts.modules = opts.modules.map(function(mod) { return sweet.loadNodeModule(process.cwd(), mod); }); } if(opts.readtables){ opts.readtables.forEach(function(mod) { sweet.setReadtable(mod); }); } return es.through(function(file) { if(file.isNull()) { return this.emit('data', file); } if(file.isStream()) { return this.emit( 'error', new Error('gulp-sweetjs: Streaming not supported') ); } var dest = gutil.replaceExtension(file.path, '.js'); opts = merge({ sourceMap: !!file.sourceMap, filename: file.path, }, opts); try { var res = sweet.compile(file.contents.toString('utf8'), opts); } catch(err) { console.log('error'); return this.emit('error', err); } if(res.sourceMap) { applySourceMap(file, res.sourceMap); } file.contents = new Buffer(res.code); file.path = dest; this.emit('data', file); }); };
var sweet = require('sweet.js'); var gutil = require('gulp-util'); var applySourceMap = require('vinyl-sourcemaps-apply'); var es = require('event-stream'); var merge = require('merge'); module.exports = function(opts) { var moduleCache = {}; return es.through(function(file) { if(file.isNull()) { return this.emit('data', file); } if(file.isStream()) { return this.emit( 'error', new Error('gulp-sweetjs: Streaming not supported') ); } var dest = gutil.replaceExtension(file.path, '.js'); opts = merge({ sourceMap: !!file.sourceMap, filename: file.path, modules: [], readtables: [] }, opts); opts.modules = opts.modules.map(function(mod) { if(moduleCache[mod]) { return moduleCache[mod]; } moduleCache[mod] = sweet.loadNodeModule(process.cwd(), mod); return moduleCache[mod]; }); opts.readtables.forEach(function(mod) { sweet.setReadtable(mod); }); try { var res = sweet.compile(file.contents.toString('utf8'), opts); } catch(err) { console.log('error'); return this.emit('error', err); } if(res.sourceMap) { applySourceMap(file, res.sourceMap); } file.contents = new Buffer(res.code); file.path = dest; this.emit('data', file); }); };
Rename multiple target test so it is unique. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@289222 91177308-0d34-0410-b5e6-96231b3b80d8
"""Test the lldb public C++ api when creating multiple targets simultaneously.""" from __future__ import print_function import os import re import subprocess import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestMultipleTargets(TestBase): mydir = TestBase.compute_mydir(__file__) NO_DEBUG_INFO_TESTCASE = True @skipIfNoSBHeaders @skipIfHostIncompatibleWithRemote def test_multiple_debuggers(self): env = {self.dylibPath: self.getLLDBLibraryEnvVal()} self.driver_exe = os.path.join(os.getcwd(), "multi-target") self.buildDriver('main.cpp', self.driver_exe) self.addTearDownHook(lambda: os.remove(self.driver_exe)) self.signBinary(self.driver_exe) # check_call will raise a CalledProcessError if multi-process-driver doesn't return # exit code 0 to indicate success. We can let this exception go - the test harness # will recognize it as a test failure. if self.TraceOn(): print("Running test %s" % self.driver_exe) check_call([self.driver_exe, self.driver_exe], env=env) else: with open(os.devnull, 'w') as fnull: check_call([self.driver_exe, self.driver_exe], env=env, stdout=fnull, stderr=fnull)
"""Test the lldb public C++ api when creating multiple targets simultaneously.""" from __future__ import print_function import os import re import subprocess import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestMultipleSimultaneousDebuggers(TestBase): mydir = TestBase.compute_mydir(__file__) NO_DEBUG_INFO_TESTCASE = True @skipIfNoSBHeaders @skipIfHostIncompatibleWithRemote def test_multiple_debuggers(self): env = {self.dylibPath: self.getLLDBLibraryEnvVal()} self.driver_exe = os.path.join(os.getcwd(), "multi-target") self.buildDriver('main.cpp', self.driver_exe) self.addTearDownHook(lambda: os.remove(self.driver_exe)) self.signBinary(self.driver_exe) # check_call will raise a CalledProcessError if multi-process-driver doesn't return # exit code 0 to indicate success. We can let this exception go - the test harness # will recognize it as a test failure. if self.TraceOn(): print("Running test %s" % self.driver_exe) check_call([self.driver_exe, self.driver_exe], env=env) else: with open(os.devnull, 'w') as fnull: check_call([self.driver_exe, self.driver_exe], env=env, stdout=fnull, stderr=fnull)
Change to 3 spaces in front of toctree elements
import shutil import os import re work = os.getcwd() found = [] regex = re.compile(r'pydarkstar\.(.*)\.rst') for root, dirs, files in os.walk(work): for f in files: m = regex.match(f) if m: found.append((root, f)) for root, f in found: path = os.path.join(root, f) with open(path, 'r') as handle: lines = handle.readlines() with open(path, 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) line = re.sub(r'\s+module$', '', line) line = re.sub(r'^pydarkstar\.', '', line) #print('{:2d} {}'.format(i, line.rstrip())) handle.write(line) #print('') # fix main file with open('pydarkstar.rst', 'r') as handle: lines = handle.readlines() z = 0 with open('pydarkstar.rst', 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) if re.match(r'^\s\s\spydarkstar.*$', line): handle.write(' {}'.format(line.lstrip())) else: handle.write(line)
import shutil import os import re work = os.getcwd() found = [] regex = re.compile(r'pydarkstar\.(.*)\.rst') for root, dirs, files in os.walk(work): for f in files: m = regex.match(f) if m: found.append((root, f)) for root, f in found: path = os.path.join(root, f) with open(path, 'r') as handle: lines = handle.readlines() with open(path, 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) line = re.sub(r'\s+module$', '', line) line = re.sub(r'^pydarkstar\.', '', line) #print('{:2d} {}'.format(i, line.rstrip())) handle.write(line) #print('') # fix main file with open('pydarkstar.rst', 'r') as handle: lines = handle.readlines() z = 0 with open('pydarkstar.rst', 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) if re.match(r'^\s\s\spydarkstar.*$', line): handle.write(' {}'.format(line.lstrip())) else: handle.write(line) if '.. toctree::' in line: if z: handle.write(' :maxdepth: {}\n'.format(z)) else: z += 1
Add dot notation to search record belongs to
<?php namespace ilateral\SilverStripe\Searchable\Extensions; use ilateral\SilverStripe\Searchable\Model\SearchTable; use ilateral\SilverStripe\Searchable\Searchable; use SilverStripe\Core\Config\Config; use SilverStripe\ORM\DataExtension; class SearchableObjectExtension extends DataExtension { private static $belongs_to = [ 'SearchRecord' => SearchTable::class . '.BaseObject' ]; /** * After base object is written, sync fields to search table * * @return null */ public function onAfterWrite() { /** @var \SilverStripe\ORM\DataObject */ $owner = $this->getOwner(); $ancestors = $owner->getClassAncestry(); $search = $owner->SearchRecord(); $objects = Config::inst()->get(Searchable::class, 'objects'); // if objects isn't set cancel if (!is_array($objects)) { return; } $write = false; foreach (array_keys($objects) as $classname) { if (in_array($classname, $ancestors)) { foreach ($objects[$classname] as $field) { if (isset($owner->$field)) { $search->$field = $owner->$field; $write = true; } } } } if ($write) { $search->write(); } } /** * Delete the linked search record if this record is deleted * * @return null */ public function onAfterDelete() { $this->getOwner()->SearchRecord()->delete(); } }
<?php namespace ilateral\SilverStripe\Searchable\Extensions; use ilateral\SilverStripe\Searchable\Model\SearchTable; use ilateral\SilverStripe\Searchable\Searchable; use SilverStripe\Core\Config\Config; use SilverStripe\ORM\DataExtension; class SearchableObjectExtension extends DataExtension { private static $belongs_to = [ 'SearchRecord' => SearchTable::class ]; /** * After base object is written, sync fields to search table * * @return null */ public function onAfterWrite() { /** @var \SilverStripe\ORM\DataObject */ $owner = $this->getOwner(); $ancestors = $owner->getClassAncestry(); $search = $owner->SearchRecord(); $objects = Config::inst()->get(Searchable::class, 'objects'); // if objects isn't set cancel if (!is_array($objects)) { return; } $write = false; foreach (array_keys($objects) as $classname) { if (in_array($classname, $ancestors)) { foreach ($objects[$classname] as $field) { if (isset($owner->$field)) { $search->$field = $owner->$field; $write = true; } } } } if ($write) { $search->write(); } } /** * Delete the linked search record if this record is deleted * * @return null */ public function onAfterDelete() { $this->getOwner()->SearchRecord()->delete(); } }
Fix the service name for the LineCounter
#!/usr/bin/env python from flask import Flask from flask_restplus import Resource, Api, reqparse from werkzeug.datastructures import FileStorage from time import sleep from random import randint import socket app = Flask(__name__) api = Api(app, version='1.0', title='LineCounter', description='This REST service exposes an endpoint that counts the lines of a given text file') upload_parser = api.parser() upload_parser.add_argument('text', location='files', type=FileStorage) requests_list = [] @api.route('/lines') @api.expect(upload_parser) class LineCounter(Resource): def post(self): requests_list.append(1) args = upload_parser.parse_args() text = args['text'] sleep(randint(2, 30)) if text: result = len(text.read().decode('utf-8').split('\n')) requests_list.pop() return {'count': result} else: requests_list.pop() return {'count': 0} @api.route('/info') class ServiceName(Resource): def get(self): return { 'service_name': 'LineCounter', 'hostname': socket.gethostname(), 'nb_requests': len(requests_list) } if __name__ == '__main__': app.run(threaded=True, host='0.0.0.0')
#!/usr/bin/env python from flask import Flask from flask_restplus import Resource, Api, reqparse from werkzeug.datastructures import FileStorage from time import sleep from random import randint import socket app = Flask(__name__) api = Api(app, version='1.0', title='LineCounter', description='This REST service exposes an endpoint that counts the lines of a given text file') upload_parser = api.parser() upload_parser.add_argument('text', location='files', type=FileStorage) requests_list = [] @api.route('/lines') @api.expect(upload_parser) class LineCounter(Resource): def post(self): requests_list.append(1) args = upload_parser.parse_args() text = args['text'] sleep(randint(2, 30)) if text: result = len(text.read().decode('utf-8').split('\n')) requests_list.pop() return {'count': result} else: requests_list.pop() return {'count': 0} @api.route('/info') class ServiceName(Resource): def get(self): return { 'service_name': 'WordCounter', 'hostname': socket.gethostname(), 'nb_requests': len(requests_list) } if __name__ == '__main__': app.run(threaded=True, host='0.0.0.0')
Add `filename` option to configuration tree
<?php namespace Farmatholin\SegmentIoBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('segment_io'); $rootNode ->children() ->scalarNode('write_key') ->cannotBeEmpty() ->isRequired() ->end() ->arrayNode('options') ->children() ->scalarNode('consumer') ->defaultValue('socket') ->end() ->booleanNode('debug') ->defaultFalse() ->end() ->booleanNode('ssl') ->defaultFalse() ->end() ->integerNode('max_queue_size') ->defaultValue(10000) ->end() ->integerNode('batch_size') ->defaultValue(100) ->end() ->floatNode('timeout') ->defaultValue(0.5) ->end() ->scalarNode('filename') ->defaultValue(null) ->end() ->end() ->end() ->end() ; return $treeBuilder; } }
<?php namespace Farmatholin\SegmentIoBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('segment_io'); $rootNode ->children() ->scalarNode('write_key') ->cannotBeEmpty() ->isRequired() ->end() ->arrayNode('options') ->children() ->scalarNode('consumer') ->defaultValue('socket') ->end() ->booleanNode('debug') ->defaultFalse() ->end() ->booleanNode('ssl') ->defaultFalse() ->end() ->integerNode('max_queue_size') ->defaultValue(10000) ->end() ->integerNode('batch_size') ->defaultValue(100) ->end() ->floatNode('timeout') ->defaultValue(0.5) ->end() ->end() ->end() ->end() ; return $treeBuilder; } }
Rename master -> masters and slave -> slaves in server status
'use strict'; const has = require('has'); function collectPoolStatus(stats, { type, host, pool }) { const poolStats = [ ['_allConnections', 'open'], ['_freeConnections', 'sleeping'], ['_acquiringConnections', 'waiting'] ] .filter(([mysqljsProp]) => has(pool, mysqljsProp) && Array.isArray(pool[mysqljsProp])) .reduce( (stats, [mysqljsProp, floraProp]) => ({ ...stats, [floraProp]: pool[mysqljsProp].length }), {} ); poolStats.open -= poolStats.sleeping; return { ...stats, [type]: { [host]: poolStats } }; } // a cluster contains master/slave pools function collectClusterStatus(stats, [database, poolCluster]) { return { ...stats, [database]: Object.entries(poolCluster._nodes) .map(([identifier, { pool }]) => { const [type, host] = identifier.split('_'); return { type: `${type.toLowerCase()}s`, host, pool }; }) .reduce(collectPoolStatus, {}) }; } module.exports = (pools) => Object.entries(pools).reduce( (stats, [server, databases]) => ({ ...stats, [server]: Object.entries(databases) .filter(([, poolCluster]) => has(poolCluster, '_nodes') && typeof poolCluster._nodes === 'object') .reduce(collectClusterStatus, {}) }), {} );
'use strict'; const has = require('has'); function collectPoolStatus(stats, { type, host, pool }) { const poolStats = [ ['_allConnections', 'open'], ['_freeConnections', 'sleeping'], ['_acquiringConnections', 'waiting'] ] .filter(([mysqljsProp]) => has(pool, mysqljsProp) && Array.isArray(pool[mysqljsProp])) .reduce( (stats, [mysqljsProp, floraProp]) => ({ ...stats, [floraProp]: pool[mysqljsProp].length }), {} ); poolStats.open -= poolStats.sleeping; return { ...stats, [type]: { [host]: poolStats } }; } // a cluster contains master/slave pools function collectClusterStatus(stats, [database, poolCluster]) { return { ...stats, [database]: Object.entries(poolCluster._nodes) .map(([identifier, { pool }]) => { const [type, host] = identifier.split('_'); return { type: type.toLowerCase(), host, pool }; }) .reduce(collectPoolStatus, {}) }; } module.exports = (pools) => Object.entries(pools).reduce( (stats, [server, databases]) => ({ ...stats, [server]: Object.entries(databases) .filter(([, poolCluster]) => has(poolCluster, '_nodes') && typeof poolCluster._nodes === 'object') .reduce(collectClusterStatus, {}) }), {} );
Fix delete command in pod initializer
class InitCommands(object): COPY = 'copy' CREATE = 'create' DELETE = 'delete' @classmethod def is_copy(cls, command): return command == cls.COPY @classmethod def is_create(cls, command): return command == cls.CREATE @classmethod def is_delete(cls, command): return command == cls.DELETE def get_output_args(command, outputs_path, original_outputs_path=None): get_or_create = 'if [ ! -d "{dir}" ]; then mkdir -p {dir}; fi;'.format(dir=outputs_path) delete_dir = 'if [ -d {path} ]; then rm -r {path}/*; fi;'.format(path=outputs_path) copy_file_if_exist = 'if [ -f {original_path} ]; then cp {original_path} {path}; fi;'.format( original_path=original_outputs_path, path=outputs_path) copy_dir_if_exist = 'if [ -d {original_path} ]; then cp -r {original_path} {path}; fi;'.format( original_path=original_outputs_path, path=outputs_path) if InitCommands.is_create(command=command): return '{} {}'.format(get_or_create, delete_dir) if InitCommands.is_copy(command=command): return '{} {} {} {}'.format( get_or_create, delete_dir, copy_dir_if_exist, copy_file_if_exist) if InitCommands.is_delete(command=command): return '{}'.format(delete_dir)
class InitCommands(object): COPY = 'copy' CREATE = 'create' DELETE = 'delete' @classmethod def is_copy(cls, command): return command == cls.COPY @classmethod def is_create(cls, command): return command == cls.CREATE @classmethod def is_delete(cls, command): return command == cls.DELETE def get_output_args(command, outputs_path, original_outputs_path=None): get_or_create = 'if [ ! -d "{dir}" ]; then mkdir -p {dir}; fi;'.format(dir=outputs_path) delete_dir = 'if [ -d {path} ]; then rm -r {path}; fi;'.format(path=outputs_path) copy_file_if_exist = 'if [ -f {original_path} ]; then cp {original_path} {path}; fi;'.format( original_path=original_outputs_path, path=outputs_path) copy_dir_if_exist = 'if [ -d {original_path} ]; then cp -r {original_path} {path}; fi;'.format( original_path=original_outputs_path, path=outputs_path) if InitCommands.is_create(command=command): return '{} {}'.format(get_or_create, delete_dir) if InitCommands.is_copy(command=command): return '{} {} {} {}'.format( get_or_create, delete_dir, copy_dir_if_exist, copy_file_if_exist) if InitCommands.is_delete(command=command): return '{}'.format(delete_dir)
Make sure that have intervals of the form [start, end).
class IntervalStorage(object): def __init__(self, interval_map=None): if interval_map == None: self.interval_map = {} else: if not isinstance(interval_map, dict): raise ValueError("Interval map must be a dictionary containing entries as keys and interval tuples as values.") self.interval_map = interval_map def add_interval(self, entry, start, end): self.validate_interval(start, end) self.interval_map[entry] = (start, end) def get_entry(self, point): for entry, interval in self.interval_map.iteritems(): start, end = interval[0], interval[1] if start <= point and point < end: return entry raise ValueError("Point '%s' is not contained in any stored interval." % point) def validate_interval(self, start, end): if start > end: raise ValueError("Start must be lower than end in a valid interval.") if start > 1 or start < 0 or end > 1 or end < 0: raise ValueError("Intervals must be subsets of the interval [0,1].") if self.has_intersection(start, end): raise ValueError("Intervals cannot have an intersection with intervals that already exist in the storage object.") def has_intersection(self, start, end): for value in self.interval_map.itervalues(): if (value[0] <= start and start < value[1]) or \ (value[0] < end and end <= value[1]) or \ (start <= value[0] and value[1] < end): return True return False
class IntervalStorage(object): def __init__(self, interval_map=None): if interval_map == None: self.interval_map = {} else: if not isinstance(interval_map, dict): raise ValueError("Interval map must be a dictionary containing entries as keys and interval tuples as values.") self.interval_map = interval_map def add_interval(self, entry, start, end): self.validate_interval(start, end) self.interval_map[entry] = (start, end) def get_entry(self, point): for entry, interval in self.interval_map.iteritems(): start, end = interval[0], interval[1] if start <= point and point < end: return entry raise ValueError("Point '%s' is not contained in any stored interval." % point) def validate_interval(self, start, end): if start > end: raise ValueError("Start must be lower than end in a valid interval.") if start > 1 or start < 0 or end > 1 or end < 0: raise ValueError("Intervals must be subsets of the interval [0,1].") if self.has_intersection(start, end): raise ValueError("Intervals cannot have an intersection with intervals that already exist in the storage object.") def has_intersection(self, start, end): for value in self.interval_map.itervalues(): if (value[0] <= start and start <= value[1]) or \ (value[0] <= end and end <= value[1]) or \ (start <= value[0] and value[1] <= end): return True return False
Handle import error on older python versions
try: import queue except ImportError: import Queue import threading class Producer(object): def __init__(self, period_in_seconds, queue, function): self._period_in_seconds = period_in_seconds self._queue = queue self._function = function self._event = threading.Event() self._thread = threading.Thread(target=self._loop) def start(self): self._thread.start() def stop(self): self._event.set() self._thread.join() def _loop(self): while not self._event.wait(self._period_in_seconds): self.__put_item_into_the_queue() def __put_item_into_the_queue(self): try: self._queue.put(self._function) except queue.Full: pass class Consumer(object): STOP_SENTINEL = "STOP" def __init__(self, queue, function): self._queue = queue self._function = function self._thread = threading.Thread(target=self._loop) self.no_date_from_the_queue = True def start(self): self._thread.start() def stop(self): self._queue.put(self.STOP_SENTINEL) self._thread.join() def _loop(self): for result in iter(self._queue.get, self.STOP_SENTINEL): self.no_date_from_the_queue = result is None if result: self._function(result)
import queue import threading class Producer(object): def __init__(self, period_in_seconds, queue, function): self._period_in_seconds = period_in_seconds self._queue = queue self._function = function self._event = threading.Event() self._thread = threading.Thread(target=self._loop) def start(self): self._thread.start() def stop(self): self._event.set() self._thread.join() def _loop(self): while not self._event.wait(self._period_in_seconds): self.__put_item_into_the_queue() def __put_item_into_the_queue(self): try: self._queue.put(self._function) except queue.Full: pass class Consumer(object): STOP_SENTINEL = "STOP" def __init__(self, queue, function): self._queue = queue self._function = function self._thread = threading.Thread(target=self._loop) self.no_date_from_the_queue = True def start(self): self._thread.start() def stop(self): self._queue.put(self.STOP_SENTINEL) self._thread.join() def _loop(self): for result in iter(self._queue.get, self.STOP_SENTINEL): self.no_date_from_the_queue = result is None if result: self._function(result)
:bug: Change config property to app from name
'use strict'; var CloudFoundry = require('cf-nodejs-client'), Promise = require('bluebird'), util = require('util'), Spinner = require('cli-spinner').Spinner, spinner = new Spinner('%s'), cf = new CloudFoundry.CloudFoundry(), routes = new CloudFoundry.Routes(), manifest = require('./lib/manifest'), config = require('./lib/config'), apps = new CloudFoundry.Apps(); module.exports = function (options) { spinner.start(); config(options).then(function (config) { cf.setEndPoint(config.endpoint); routes.setEndPoint(config.endpoint); apps.setEndPoint(config.endpoint); return cf.getInfo().then(function (result) { return cf.login(result.authorization_endpoint, config.username, config.password); }).then(function (auth) { return apps.getApps(auth.token_type, auth.access_token).then(function (result) { var guid; result.resources.forEach(function (item) { if (item.entity.name === config.app) { guid = item.metadata.guid; } }); if (guid) { return manifest(auth, guid).then(function (settings) { spinner.stop(); return settings; }); } }); }) }).catch(function (error) { spinner.stop(true); console.error('Error: ' + error); process.exit(1); }); }
'use strict'; var CloudFoundry = require('cf-nodejs-client'), Promise = require('bluebird'), util = require('util'), Spinner = require('cli-spinner').Spinner, spinner = new Spinner('%s'), cf = new CloudFoundry.CloudFoundry(), routes = new CloudFoundry.Routes(), manifest = require('./lib/manifest'), config = require('./lib/config'), apps = new CloudFoundry.Apps(); module.exports = function (options) { spinner.start(); config(options).then(function (config) { cf.setEndPoint(config.endpoint); routes.setEndPoint(config.endpoint); apps.setEndPoint(config.endpoint); return cf.getInfo().then(function (result) { return cf.login(result.authorization_endpoint, config.username, config.password); }).then(function (auth) { return apps.getApps(auth.token_type, auth.access_token).then(function (result) { var guid; // ha--node-starter result.resources.forEach(function (item) { if (item.entity.name === config.name) { guid = item.metadata.guid; } }); if (guid) { return manifest(auth, guid).then(function (settings) { spinner.stop(); return settings; }); } }); }) }).catch(function (error) { spinner.stop(true); console.error('Error: ' + error); process.exit(1); }); }
example: Add example of removing physics body
FamousFramework.scene('famous-tests:physics:basic:particle', { behaviors: { '.particle': { 'size': [200, 200], 'align': [0.5, 0.5], 'mount-point': [0.5, 0.5], 'style': { 'background': 'whitesmoke', 'border-radius': '50%' } }, '.one': { 'position': function(position1) { return position1; } }, '.two': { 'position': function(position2) { return position2; } } }, events: { '$lifecycle': { 'post-load': function($state) { $state .applyPhysicsForce('gravity1D', [ 'position1' ]) .applyPhysicsConstraint('distance', [ 'position1', 'position2' ], { length: 400 }); } }, '.one': { 'click': function($state) { $state.removePhysicsForce('gravity1D'); } }, '.two': { 'click': function($state) { $state.removePhysicsConstraint('distance'); $state.removePhysicsBody('position2'); } } }, states: { 'position1': [0, 0, 0], 'position2': [0, -200, 0] }, tree: ` <node class="particle one"></node> <node class="particle two"></node> ` });
FamousFramework.scene('famous-tests:physics:basic:particle', { behaviors: { '.particle': { 'size': [200, 200], 'align': [0.5, 0.5], 'mount-point': [0.5, 0.5], 'style': { 'background': 'whitesmoke', 'border-radius': '50%' } }, '.one': { 'position': function(position1) { return position1; } }, '.two': { 'position': function(position2) { return position2; } } }, events: { '$lifecycle': { 'post-load': function($state) { $state .applyPhysicsForce('gravity1D', [ 'position1' ]) .applyPhysicsConstraint('distance', [ 'position1', 'position2' ], { length: 400 }); } }, '.one': { 'click': function($state) { $state.removePhysicsForce('gravity1D'); } }, '.two': { 'click': function($state) { $state.removePhysicsConstraint('distance'); } } }, states: { 'position1': [0, 0, 0], 'position2': [0, -200, 0] }, tree: ` <node class="particle one"></node> <node class="particle two"></node> ` });
Reset the num threads to the env variable, not the default
from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: self.assertEqual(threads, str(get_thread_count())) self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) finally: # reset the env variable/set to default. Should not fail even if # threads are launched because the value is the same. env[key] = current config.reload_config() if __name__ == '__main__': unittest.main()
from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: self.assertEqual(threads, str(get_thread_count())) self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) finally: # reset the env variable/set to default. Should not fail even if # threads are launched because the value is the same. env[key] = current config.reload_config() if __name__ == '__main__': unittest.main()
Fix formatting of sizes between 1000 and 1024
jQuery.fn.log = function (msg){ console.log("%s: %o", msg, this); return this; }; $(document).ready(function(){ $.ajaxSetup({cache: false}); $.getJSON("/disco/version", function (data){ $("#version").text(data); }); }); function format_size(num){ units = ['KB', 'MB', 'GB', 'TB']; for (i = 0; i < units.length; i++) { // Don't use 1024 here otherwise (1023).toPrecision(3) becomes 1.02e+3 if (num < 1000) return num.toPrecision(3) + units[i]; num /= 1024; } } function show_msg(m){ $("#msg").text(m.replace(/\"/g, "")).show().fadeOut(2000); } function post_req(url, data, func){ $.ajax({data: data, dataType: "JSON", url: url, type: "POST", processData: false, error: function (XMLHttpRequest, textStatus, errorThrown){ show_msg("Request to " + url + " failed: " + textStatus); }, success: function (x){ show_msg(x); if (func) func(x); } }); }
jQuery.fn.log = function (msg){ console.log("%s: %o", msg, this); return this; }; $(document).ready(function(){ $.ajaxSetup({cache: false}); $.getJSON("/disco/version", function (data){ $("#version").text(data); }); }); function format_size(num){ units = ['KB', 'MB', 'GB', 'TB']; for (i = 0; i < units.length; i++) { if (num < 1024) return num.toPrecision(3) + units[i]; num /= 1024; } } function show_msg(m){ $("#msg").text(m.replace(/\"/g, "")).show().fadeOut(2000); } function post_req(url, data, func){ $.ajax({data: data, dataType: "JSON", url: url, type: "POST", processData: false, error: function (XMLHttpRequest, textStatus, errorThrown){ show_msg("Request to " + url + " failed: " + textStatus); }, success: function (x){ show_msg(x); if (func) func(x); } }); }
Add 'background' attribute for 'table' tag to the whitelist
package com.fsck.k9.message.html; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Cleaner; import org.jsoup.safety.Whitelist; public class HtmlSanitizer { private final HeadCleaner headCleaner; private final Cleaner cleaner; HtmlSanitizer() { Whitelist whitelist = Whitelist.relaxed() .addTags("font", "hr", "ins", "del") .addAttributes("table", "align", "background", "bgcolor", "border", "cellpadding", "cellspacing", "width") .addAttributes("tr", "align", "bgcolor", "valign") .addAttributes("th", "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "sorted", "valign", "width") .addAttributes("td", "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width") .addAttributes(":all", "class", "style", "id") .addProtocols("img", "src", "http", "https", "cid", "data"); cleaner = new Cleaner(whitelist); headCleaner = new HeadCleaner(); } public Document sanitize(String html) { Document dirtyDocument = Jsoup.parse(html); Document cleanedDocument = cleaner.clean(dirtyDocument); headCleaner.clean(dirtyDocument, cleanedDocument); return cleanedDocument; } }
package com.fsck.k9.message.html; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Cleaner; import org.jsoup.safety.Whitelist; public class HtmlSanitizer { private final HeadCleaner headCleaner; private final Cleaner cleaner; HtmlSanitizer() { Whitelist whitelist = Whitelist.relaxed() .addTags("font", "hr", "ins", "del") .addAttributes("table", "align", "bgcolor", "border", "cellpadding", "cellspacing", "width") .addAttributes("tr", "align", "bgcolor", "valign") .addAttributes("th", "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "sorted", "valign", "width") .addAttributes("td", "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width") .addAttributes(":all", "class", "style", "id") .addProtocols("img", "src", "http", "https", "cid", "data"); cleaner = new Cleaner(whitelist); headCleaner = new HeadCleaner(); } public Document sanitize(String html) { Document dirtyDocument = Jsoup.parse(html); Document cleanedDocument = cleaner.clean(dirtyDocument); headCleaner.clean(dirtyDocument, cleanedDocument); return cleanedDocument; } }
Add call_script output to workflow_dict traceback
# -*- coding: utf-8 -*- import logging from util import full_stack from util import call_script from django.conf import settings from drivers import factory_for from system.models import Configuration from notification.util import get_clone_args from ...base import BaseStep from ....exceptions.error_codes import DBAAS_0017 LOG = logging.getLogger(__name__) class CloneDatabase(BaseStep): def __unicode__(self): return "Replicating database data..." def do(self, workflow_dict): try: if 'databaseinfra' not in workflow_dict \ or 'clone' not in workflow_dict : return False args = get_clone_args(workflow_dict['clone'], workflow_dict['database']) script_name = factory_for(workflow_dict['clone'].databaseinfra).clone() python_bin= Configuration.get_by_name('python_venv_bin') return_code, output = call_script(script_name, working_dir=settings.SCRIPTS_PATH , args=args, split_lines=False, python_bin=python_bin) LOG.info("Script Output: {}".format(output)) LOG.info("Return code: {}".format(return_code)) if return_code != 0: workflow_dict['exceptions']['traceback'].append(output) return False return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0017) workflow_dict['exceptions']['traceback'].append(traceback) return False def undo(self, workflow_dict): LOG.info("Nothing to do here...") return True
# -*- coding: utf-8 -*- import logging from util import full_stack from util import call_script from django.conf import settings from drivers import factory_for from system.models import Configuration from notification.util import get_clone_args from ...base import BaseStep from ....exceptions.error_codes import DBAAS_0017 LOG = logging.getLogger(__name__) class CloneDatabase(BaseStep): def __unicode__(self): return "Replicating database data..." def do(self, workflow_dict): try: if 'databaseinfra' not in workflow_dict \ or 'clone' not in workflow_dict : return False args = get_clone_args(workflow_dict['clone'], workflow_dict['database']) script_name = factory_for(workflow_dict['clone'].databaseinfra).clone() python_bin= Configuration.get_by_name('python_venv_bin') return_code, output = call_script(script_name, working_dir=settings.SCRIPTS_PATH , args=args, split_lines=False, python_bin=python_bin) LOG.info("Script Output: {}".format(output)) LOG.info("Return code: {}".format(return_code)) if return_code != 0: return False return True except Exception: traceback = full_stack() workflow_dict['exceptions']['error_codes'].append(DBAAS_0017) workflow_dict['exceptions']['traceback'].append(traceback) return False def undo(self, workflow_dict): LOG.info("Nothing to do here...") return True
Change deprecated config for USM
import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import angular from 'rollup-plugin-angular'; import typescript from 'rollup-plugin-typescript'; var sass = require('node-sass'); import {nameLibrary,PATH_SRC,PATH_DIST} from './config-library.js'; export default { input: PATH_SRC+nameLibrary+'.ts', output: { name: nameLibrary, format: 'umd', file: PATH_DIST+nameLibrary+".umd.js", sourcemap:true, }, external: [ '@angular/core', "@angular/platform-browser", "rxjs/Rx", "@angular/forms" ], plugins: [ angular( { preprocessors:{ template:template => template, style: scss => { let css; if(scss){ css = sass.renderSync({ data: scss }).css.toString(); console.log(css); }else{ css = ''; } return css; }, } } ), typescript({ typescript:require('typescript') }), resolve({ module: true, main: true }), commonjs({ include: 'node_modules/**', }) ], onwarn: warning => { const skip_codes = [ 'THIS_IS_UNDEFINED', 'MISSING_GLOBAL_NAME' ]; if (skip_codes.indexOf(warning.code) != -1) return; console.error(warning); } };
import resolve from 'rollup-plugin-node-resolve'; import commonjs from 'rollup-plugin-commonjs'; import angular from 'rollup-plugin-angular'; import typescript from 'rollup-plugin-typescript'; var sass = require('node-sass'); import {nameLibrary,PATH_SRC,PATH_DIST} from './config-library.js'; export default { entry: PATH_SRC+nameLibrary+'.ts', format: 'umd', moduleName: nameLibrary, external: [ '@angular/core', "@angular/platform-browser", "rxjs/Rx", "@angular/forms" ], sourceMap:true, dest:PATH_DIST+nameLibrary+".umd.js", plugins: [ angular( { preprocessors:{ template:template => template, style: scss => { let css; if(scss){ css = sass.renderSync({ data: scss }).css.toString(); console.log(css); }else{ css = ''; } return css; }, } } ), typescript({ typescript:require('typescript') }), resolve({ module: true, main: true }), commonjs({ include: 'node_modules/**', }) ], onwarn: warning => { const skip_codes = [ 'THIS_IS_UNDEFINED', 'MISSING_GLOBAL_NAME' ]; if (skip_codes.indexOf(warning.code) != -1) return; console.error(warning); } };
Fix issue preventing inventory groups from loading A conditional was in place to check if a URL included the base path, if so, it was supposed to use the URL as-is, otherwise it should get the URL by referencing a property in an object containing default URLs. The conditional checked only for 'api/v1'. Since we're at v2, the check failed eventually resulting in a `replace` call on an undefined value. I replaced the conditional to pattern match api/v*/ instead.
/************************************************* * Copyright (c) 2015 Ansible, Inc. * * All Rights Reserved *************************************************/ export default angular.module('rbacUiControl', []) .service('rbacUiControlService', ['$q', 'GetBasePath', 'Rest', 'Wait', function($q, GetBasePath, Rest, Wait){ this.canAdd = function(apiPath) { var canAddVal = $q.defer(); if (/api\/v[0-9]+\//.test(apiPath)) { Rest.setUrl(apiPath); } else { Rest.setUrl(GetBasePath(apiPath)); } Wait("start"); Rest.options() .success(function(data) { if (data.actions.POST) { canAddVal.resolve(true); } else { canAddVal.reject(false); } Wait("stop"); }); return canAddVal.promise; }; }]);
/************************************************* * Copyright (c) 2015 Ansible, Inc. * * All Rights Reserved *************************************************/ export default angular.module('rbacUiControl', []) .service('rbacUiControlService', ['$q', 'GetBasePath', 'Rest', 'Wait', function($q, GetBasePath, Rest, Wait){ this.canAdd = function(apiPath) { var canAddVal = $q.defer(); if (apiPath.indexOf("api/v1") > -1) { Rest.setUrl(apiPath); } else { Rest.setUrl(GetBasePath(apiPath)); } Wait("start"); Rest.options() .success(function(data) { if (data.actions.POST) { canAddVal.resolve(true); } else { canAddVal.reject(false); } Wait("stop"); }); return canAddVal.promise; }; }]);
Change the browse page layout temporarily
import React from 'react'; import { connect } from 'react-redux'; import { fetchRecipes, setSearchTerm } from '../actions/'; import Header from '../components/Header'; import SearchHeader from '../components/SearchHeader'; import Card from '../components/Card'; class Browse extends React.Component { constructor(props) { super(props); this.setSearchTerm = this.setSearchTerm.bind(this); } componentDidMount() { if (this.props.recipes.length === 0) { this.props.dispatchFetchRecipes(); } } setSearchTerm(e) { this.props.dispatchSetSearchTerm(e.target.value); } render() { return ( <main className="browse"> <Header page={'browse'}> <SearchHeader handleSearchTermChange={this.setSearchTerm} searchTerm={this.props.searchTerm} page={'browse'} /> </Header> <div className="container"> {this.props.recipes.map(recipe => <Card key={recipe.id} name={recipe.name} desc={recipe.desc} img={recipe.img} id={recipe.id} />)} </div> </main> ); } } const mapStateToProps = state => ({ recipes: state.recipes, searchTerm: state.searchTerm }); export default connect( mapStateToProps, { dispatchFetchRecipes: fetchRecipes, dispatchSetSearchTerm: setSearchTerm } )(Browse);
import React from 'react'; import { connect } from 'react-redux'; import { fetchRecipes, setSearchTerm } from '../actions/'; import Header from '../components/Header'; import SearchHeader from '../components/SearchHeader'; import Card from '../components/Card'; class Browse extends React.Component { constructor(props) { super(props); this.setSearchTerm = this.setSearchTerm.bind(this); } componentDidMount() { if (this.props.recipes.length === 0) { this.props.dispatchFetchRecipes(); } } setSearchTerm(e) { this.props.dispatchSetSearchTerm(e.target.value); } render() { return ( <main className="browse"> <Header page={'browse'}> <SearchHeader handleSearchTermChange={this.setSearchTerm} searchTerm={this.props.searchTerm} page={'browse'} /> </Header> <div className="container"> <div className="row"> {this.props.recipes.map(recipe => <Card key={recipe.id} name={recipe.name} desc={recipe.desc} img={recipe.img} id={recipe.id} />)} </div> </div> </main> ); } } const mapStateToProps = state => ({ recipes: state.recipes, searchTerm: state.searchTerm }); export default connect( mapStateToProps, { dispatchFetchRecipes: fetchRecipes, dispatchSetSearchTerm: setSearchTerm } )(Browse);
Define constant for the max epic count
const localStorageKey = 'recent-epics'; const maxEpicCount = 10; const hasLocalStorage = () => { return typeof(Storage) !== "undefined" }; const getRecentEpics = () => { if (!hasLocalStorage) { return } const rawRecentEpics = localStorage.getItem(localStorageKey); if (rawRecentEpics) { var parsed = []; try { parsed = JSON.parse(rawRecentEpics); } catch (e) { console.log('failed to parse recent-epics from local storage: ' + err); } if (parsed && parsed.constructor === Array) { return parsed; } } else { console.log(`no ${localStorageKey} in local storage`); } return []; }; const pushRecentEpic = (epic) => { if (!hasLocalStorage) { return } var epics = getRecentEpics(); for (var i = 0; i < epics.length; i++) { if (epics[i].key === epic.key) { epics.splice(i, 1); } } epics.unshift(epic); if (epics.length > maxEpicCount) { epics.pop(); } localStorage.setItem(localStorageKey, JSON.stringify(epics)); }; export { getRecentEpics, pushRecentEpic };
const localStorageKey = 'recent-epics'; const hasLocalStorage = () => { return typeof(Storage) !== "undefined" }; const getRecentEpics = () => { if (!hasLocalStorage) { return } const rawRecentEpics = localStorage.getItem(localStorageKey); if (rawRecentEpics) { var parsed = []; try { parsed = JSON.parse(rawRecentEpics); } catch (e) { console.log('failed to parse recent-epics from local storage: ' + err); } if (parsed && parsed.constructor === Array) { return parsed; } } else { console.log(`no ${localStorageKey} in local storage`); } return []; }; const pushRecentEpic = (epic) => { if (!hasLocalStorage) { return } var epics = getRecentEpics(); for (var i = 0; i < epics.length; i++) { if (epics[i].key === epic.key) { epics.splice(i, 1); } } epics.unshift(epic); if (epics.length > 10) { epics.pop(); } localStorage.setItem(localStorageKey, JSON.stringify(epics)); }; export { getRecentEpics, pushRecentEpic };
conan: Copy find modules to root of module path
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class CPPCheckTargetCMakeConan(ConanFile): name = "cppcheck-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/cppcheck-target-cmake" license = "MIT" def source(self): zip_name = "cppcheck-target-cmake.zip" download("https://github.com/polysquare/" "cppcheck-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="Find*.cmake", dst="", src="cppcheck-target-cmake-" + VERSION, keep_path=True) self.copy(pattern="*.cmake", dst="cmake/cppcheck-target-cmake", src="cppcheck-target-cmake-" + VERSION, keep_path=True)
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class CPPCheckTargetCMakeConan(ConanFile): name = "cppcheck-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard", "tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util", "tooling-cmake-util/master@smspillaz/tooling-cmake-util", "cmake-unit/master@smspillaz/cmake-unit") url = "http://github.com/polysquare/cppcheck-target-cmake" license = "MIT" def source(self): zip_name = "cppcheck-target-cmake.zip" download("https://github.com/polysquare/" "cppcheck-target-cmake/archive/{version}.zip" "".format(version="v" + VERSION), zip_name) unzip(zip_name) os.unlink(zip_name) def package(self): self.copy(pattern="*.cmake", dst="cmake/cppcheck-target-cmake", src="cppcheck-target-cmake-" + VERSION, keep_path=True)
Change main method by generate.
package foundation.stack.datamill.security; import org.jose4j.jwk.*; import org.jose4j.keys.HmacKey; import org.jose4j.lang.ByteUtil; /** * @author Ravi Chodavarapu ([email protected]) */ public interface KeyGenerators { class Symmetric { private Symmetric() { } public static void generate() throws Exception { byte[] bytes = ByteUtil.randomBytes(ByteUtil.byteLength(512)); OctetSequenceJsonWebKey key = new OctetSequenceJsonWebKey(new HmacKey(bytes)); key.setKeyId("k" + System.currentTimeMillis()); System.out.println(new JsonWebKeySet(key).toJson(JsonWebKey.OutputControlLevel.INCLUDE_SYMMETRIC)); } } class RSA { private RSA() { } public static void generate() throws Exception { RsaJsonWebKey key = RsaJwkGenerator.generateJwk(2048); key.setKeyId("k" + System.currentTimeMillis()); System.out.println("Public & Private:"); System.out.println(new JsonWebKeySet(key).toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE)); System.out.println(); System.out.println("Only Public:"); System.out.println(new JsonWebKeySet(key).toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY)); } } }
package foundation.stack.datamill.security; import org.jose4j.jwk.*; import org.jose4j.keys.HmacKey; import org.jose4j.lang.ByteUtil; /** * @author Ravi Chodavarapu ([email protected]) */ public interface KeyGenerators { class Symmetric { private Symmetric() { } public static void main(String[] arguments) throws Exception { byte[] bytes = ByteUtil.randomBytes(ByteUtil.byteLength(512)); OctetSequenceJsonWebKey key = new OctetSequenceJsonWebKey(new HmacKey(bytes)); key.setKeyId("k" + System.currentTimeMillis()); System.out.println(new JsonWebKeySet(key).toJson(JsonWebKey.OutputControlLevel.INCLUDE_SYMMETRIC)); } } class RSA { private RSA() { } public static void main(String[] arguments) throws Exception { RsaJsonWebKey key = RsaJwkGenerator.generateJwk(2048); key.setKeyId("k" + System.currentTimeMillis()); System.out.println("Public & Private:"); System.out.println(new JsonWebKeySet(key).toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE)); System.out.println(); System.out.println("Only Public:"); System.out.println(new JsonWebKeySet(key).toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY)); } } }
fix(data): Fix weighted/chance tables not serializing
package valandur.webapi.serialize.view.misc; import com.fasterxml.jackson.annotation.JsonValue; import org.spongepowered.api.util.weighted.NestedTableEntry; import org.spongepowered.api.util.weighted.RandomObjectTable; import org.spongepowered.api.util.weighted.TableEntry; import org.spongepowered.api.util.weighted.WeightedObject; import valandur.webapi.api.serialize.BaseView; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class RandomObjectTableView extends BaseView<RandomObjectTable> { @JsonValue public Map<Double, Object> entries; public RandomObjectTableView(RandomObjectTable<Object> value) { super(value); entries = new HashMap<>(); for (TableEntry entry : value.getEntries()) { if (entry instanceof NestedTableEntry) { try { // Get the property with reflection because it's not exposed for some reason Field field = NestedTableEntry.class.getDeclaredField("table"); field.setAccessible(true); Object tbl = field.get(entry); entries.put(entry.getWeight(), tbl); } catch (IllegalAccessException | NoSuchFieldException ignored) { } } else if (entry instanceof WeightedObject) { entries.put(entry.getWeight(), ((WeightedObject)entry).get()); } } } }
package valandur.webapi.serialize.view.misc; import com.fasterxml.jackson.annotation.JsonValue; import org.spongepowered.api.util.weighted.NestedTableEntry; import org.spongepowered.api.util.weighted.RandomObjectTable; import org.spongepowered.api.util.weighted.TableEntry; import org.spongepowered.api.util.weighted.WeightedObject; import valandur.webapi.api.serialize.BaseView; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class RandomObjectTableView extends BaseView<RandomObjectTable<Object>> { @JsonValue public Map<Double, Object> entries; public RandomObjectTableView(RandomObjectTable<Object> value) { super(value); entries = new HashMap<>(); for (TableEntry entry : value.getEntries()) { if (entry instanceof NestedTableEntry) { try { // Get the property with reflection because it's not exposed for some reason Field field = NestedTableEntry.class.getDeclaredField("table"); field.setAccessible(true); Object tbl = field.get(entry); entries.put(entry.getWeight(), tbl); } catch (IllegalAccessException | NoSuchFieldException ignored) { } } else if (entry instanceof WeightedObject) { entries.put(entry.getWeight(), ((WeightedObject)entry).get()); } } } }
Make separator line match width of board
import sys, random, time boardSize = (10,10) while True: foo, bar, baz, globals()['board'] = None if globals().get('board') is None else [ ( [sys.stdout.write('X' if cell else ' ') for cell in row], sys.stdout.write('\n') ) for row in board ], time.sleep(1), sys.stdout.write('=' * boardSize[0] +'\n'), [ [random.random() < 0.5 for i in range(boardSize[0])] for j in range(boardSize[1]) ] if 'board' not in globals() else [ map( lambda z: (z[1] in (2,3) and board[y][z[0]]) or z[1]==3, [ ( x, sum( [ int( y0 in range(len(board)) and x0 in range(len(board[y0])) and board[y0][x0] ) for x0,y0 in ( (x - 1, y - 1), (x, y -1), (x + 1, y - 1), (x - 1, y), (x + 1, y), (x - 1, y + 1), (x, y + 1), (x + 1, y + 1) ) ] ) ) for x in range(len(board[y]))] ) for y in range(len(board)) ]
import sys, random, time boardSize = (10,10) while True: foo, bar, baz, globals()['board'] = None if globals().get('board') is None else [ ( [sys.stdout.write('X' if cell else ' ') for cell in row], sys.stdout.write('\n') ) for row in board ], time.sleep(1), sys.stdout.write('==============\n'), [ [random.random() < 0.5 for i in range(boardSize[0])] for j in range(boardSize[1]) ] if 'board' not in globals() else [ map( lambda z: (z[1] in (2,3) and board[y][z[0]]) or z[1]==3, [ ( x, sum( [ int( y0 in range(len(board)) and x0 in range(len(board[y0])) and board[y0][x0] ) for x0,y0 in ( (x - 1, y - 1), (x, y -1), (x + 1, y - 1), (x - 1, y), (x + 1, y), (x - 1, y + 1), (x, y + 1), (x + 1, y + 1) ) ] ) ) for x in range(len(board[y]))] ) for y in range(len(board)) ]
Allow data property to not be use
from astropy.io import fits import numpy as np from ..io import input_data class BaseStatisticMixIn(object): """ Common properties to all statistics """ # Disable this flag when a statistic does not need a header need_header_flag = True # Disable this when the data property will not be used. no_data_flag = False @property def header(self): return self._header @header.setter def header(self, input_hdr): if not self.need_header_flag: input_hdr = None elif not isinstance(input_hdr, fits.header.Header): raise TypeError("The header must be a" " astropy.io.fits.header.Header.") self._header = input_hdr @property def data(self): return self._data @data.setter def data(self, values): if self.no_data_flag: values = None elif not isinstance(values, np.ndarray): raise TypeError("Data is not a numpy array.") self._data = values def input_data_header(self, data, header): ''' Check if the header is given separately from the data type. ''' if header is not None: self.data = input_data(data, no_header=True) self.header = header else: self.data, self.header = input_data(data)
from astropy.io import fits import numpy as np from ..io import input_data class BaseStatisticMixIn(object): """ Common properties to all statistics """ # Disable this flag when a statistic does not need a header need_header_flag = True @property def header(self): return self._header @header.setter def header(self, input_hdr): if not self.need_header_flag: input_hdr = None elif not isinstance(input_hdr, fits.header.Header): raise TypeError("The header must be a" " astropy.io.fits.header.Header.") self._header = input_hdr @property def data(self): return self._data @data.setter def data(self, values): if not isinstance(values, np.ndarray): raise TypeError("Data is not a numpy array.") self._data = values def input_data_header(self, data, header): ''' Check if the header is given separately from the data type. ''' if header is not None: self.data = input_data(data, no_header=True) self.header = header else: self.data, self.header = input_data(data)
Make email and name order fit to the default django settings file
from django import forms from django.conf import settings from django.template import loader from django.core.mail import send_mail class BaseEmailFormMixin(object): from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [email for _, email in settings.MANAGERS] subject_template_name = 'contact_form/email_subject.txt' message_template_name = 'contact_form/email_template.txt' def get_message(self): return loader.render_to_string(self.message_template_name, self.get_context()) def get_subject(self): subject = loader.render_to_string(self.subject_template_name, self.get_context()) return ''.join(subject.splitlines()) def get_context(self): if not self.is_valid(): raise ValueError("Cannot generate Context when form is invalid.") return self.cleaned_data def get_message_dict(self): return { "from_email": self.from_email, "recipient_list": self.recipient_list, "subject": self.get_subject(), "message": self.get_message(), } def send_email(self, request, fail_silently=False): self.request = request send_mail(fail_silently=fail_silently, **self.get_message_dict()) class ContactForm(forms.Form, BaseEmailFormMixin): pass class ContactModelForm(forms.ModelForm, BaseEmailFormMixin): """ You'll need to declare the model yourself. """ pass
from django import forms from django.conf import settings from django.template import loader from django.core.mail import send_mail class BaseEmailFormMixin(object): from_email = settings.DEFAULT_FROM_EMAIL recipient_list = [email for email, _ in settings.MANAGERS] subject_template_name = 'contact_form/email_subject.txt' message_template_name = 'contact_form/email_template.txt' def get_message(self): return loader.render_to_string(self.message_template_name, self.get_context()) def get_subject(self): subject = loader.render_to_string(self.subject_template_name, self.get_context()) return ''.join(subject.splitlines()) def get_context(self): if not self.is_valid(): raise ValueError("Cannot generate Context when form is invalid.") return self.cleaned_data def get_message_dict(self): return { "from_email": self.from_email, "recipient_list": self.recipient_list, "subject": self.get_subject(), "message": self.get_message(), } def send_email(self, request, fail_silently=False): self.request = request send_mail(fail_silently=fail_silently, **self.get_message_dict()) class ContactForm(forms.Form, BaseEmailFormMixin): pass class ContactModelForm(forms.ModelForm, BaseEmailFormMixin): """ You'll need to declare the model yourself. """ pass
Add related_name to initial migration so it doesn't try to later
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='SavedSearch', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ('url', models.CharField(max_length=200, db_index=True)), ('querystring', models.TextField(blank=True)), ('default', models.BooleanField(default=False)), ('date_created', models.DateTimeField(default=django.utils.timezone.now, editable=False)), ('user', models.ForeignKey(related_name=b'seeker_searches', to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': (b'name',), 'verbose_name_plural': b'saved searches', }, bases=(models.Model,), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='SavedSearch', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ('url', models.CharField(max_length=200, db_index=True)), ('querystring', models.TextField(blank=True)), ('default', models.BooleanField(default=False)), ('date_created', models.DateTimeField(default=django.utils.timezone.now, editable=False)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], options={ 'ordering': (b'name',), 'verbose_name_plural': b'saved searches', }, bases=(models.Model,), ), ]
Write task output to skype window
package pl.mkrystek.mkbot.task; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.mkrystek.mkbot.window.SkypeWindow; public class TaskExecutionEngine { private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutionEngine.class); private final ScheduledExecutorService scheduler; private final SkypeWindow skypeWindow; private List<ReplyTask> replyTasks; private List<ScheduledTask> scheduledTasks; public TaskExecutionEngine(ScheduledExecutorService scheduler, SkypeWindow skypeWindow) { this.skypeWindow = skypeWindow; this.scheduler = scheduler; } public void init(List<ReplyTask> replyTasks, List<ScheduledTask> scheduledTasks) { this.replyTasks = replyTasks; this.scheduledTasks = scheduledTasks; } public void start() { scheduler.scheduleAtFixedRate(() -> skypeWindow.getNewMessages().forEach(skypeMessage -> replyTasks.forEach(replyTask -> { if (replyTask.checkIfApplies(skypeMessage)) { String reply = replyTask.performAction(skypeMessage); LOGGER.debug("Writing message on skype: {}", reply); skypeWindow.writeMessage(reply); } })), 0, 100, TimeUnit.MILLISECONDS); } public void shutdown() { scheduler.shutdownNow(); } }
package pl.mkrystek.mkbot.task; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.mkrystek.mkbot.window.SkypeWindow; public class TaskExecutionEngine { private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutionEngine.class); private final ScheduledExecutorService scheduler; private final SkypeWindow skypeWindow; private List<ReplyTask> replyTasks; private List<ScheduledTask> scheduledTasks; public TaskExecutionEngine(ScheduledExecutorService scheduler, SkypeWindow skypeWindow) { this.skypeWindow = skypeWindow; this.scheduler = scheduler; } public void init(List<ReplyTask> replyTasks, List<ScheduledTask> scheduledTasks) { this.replyTasks = replyTasks; this.scheduledTasks = scheduledTasks; } public void start() { scheduler.scheduleAtFixedRate(() -> skypeWindow.getNewMessages().forEach(skypeMessage -> replyTasks.forEach(replyTask -> { if (replyTask.checkIfApplies(skypeMessage)) { LOGGER.debug("Writing message on skype: {}", replyTask.performAction(skypeMessage)); } })), 0, 1, TimeUnit.SECONDS); } public void shutdown() { scheduler.shutdownNow(); } }
Fix Editor Save Button not allowing unpublish Closes #2918
/* global console */ var EditorControllerMixin = Ember.Mixin.create({ //## Computed post properties isPublished: Ember.computed.equal('status', 'published'), isDraft: Ember.computed.equal('status', 'draft'), /** * By default, a post will not change its publish state. * Only with a user-set value (via setSaveType action) * can the post's status change. */ willPublish: function (key, value) { if (arguments.length > 1) { return value; } return this.get('isPublished'); }.property('isPublished'), actions: { save: function () { var status = this.get('willPublish') ? 'published' : 'draft', self = this; this.set('status', status); this.get('model').save().then(function () { console.log('saved'); self.notifications.showSuccess('Post status saved as <strong>' + self.get('status') + '</strong>.'); }, this.notifications.showErrors); }, setSaveType: function (newType) { if (newType === 'publish') { this.set('willPublish', true); } else if (newType === 'draft') { this.set('willPublish', false); } else { console.warn('Received invalid save type; ignoring.'); } } } }); export default EditorControllerMixin;
/* global console */ var EditorControllerMixin = Ember.Mixin.create({ //## Computed post properties isPublished: Ember.computed.equal('status', 'published'), isDraft: Ember.computed.equal('status', 'draft'), /** * By default, a post will not change its publish state. * Only with a user-set value (via setSaveType action) * can the post's status change. */ willPublish: function (key, val) { if (val) { return val; } return this.get('isPublished'); }.property('isPublished'), actions: { save: function () { var status = this.get('willPublish') ? 'published' : 'draft', self = this; this.set('status', status); this.get('model').save().then(function () { console.log('saved'); self.notifications.showSuccess('Post status saved as <strong>' + self.get('status') + '</strong>.'); }, this.notifications.showErrors); }, setSaveType: function (newType) { if (newType === 'publish') { this.set('willPublish', true); } else if (newType === 'draft') { this.set('willPublish', false); } else { console.warn('Received invalid save type; ignoring.'); } } } }); export default EditorControllerMixin;
Rebuild wordcount on thread indexing
<?php class SV_WordCountSearch_XenForo_Search_DataHandler_Thread extends XFCP_SV_WordCountSearch_XenForo_Search_DataHandler_Thread { protected function _insertIntoIndex(XenForo_Search_Indexer $indexer, array $data, array $parentData = null) { $wordcount = 0; if (!empty($data['threadmark_count']) && empty($thread['word_count']) || empty($data['threadmark_count']) && !empty($thread['word_count'])) { $wordcount = $this->_getThreadModel()->rebuildThreadWordCount( $data['thread_id'] ); } $metadata = array(); $metadata[SV_WordCountSearch_Globals::WordCountField] = $wordcount; if ($indexer instanceof SV_SearchImprovements_Search_IndexerProxy) { $indexer->setProxyMetaData($metadata); } else { $indexer = new SV_SearchImprovements_Search_IndexerProxy( $indexer, $metadata ); } parent::_insertIntoIndex($indexer, $data, $parentData); } public function quickIndex(XenForo_Search_Indexer $indexer, array $contentIds) { $indexer = new SV_SearchImprovements_Search_IndexerProxy($indexer, array()); return parent::quickIndex($indexer, $contentIds); } }
<?php class SV_WordCountSearch_XenForo_Search_DataHandler_Thread extends XFCP_SV_WordCountSearch_XenForo_Search_DataHandler_Thread { protected function _insertIntoIndex(XenForo_Search_Indexer $indexer, array $data, array $parentData = null) { $wordcount = 0; if (!empty($data['word_count'])) { $wordcount = $this->_getThreadModel()->rebuildThreadWordCount( $data['thread_id'] ); } $metadata = array(); $metadata[SV_WordCountSearch_Globals::WordCountField] = $wordcount; if ($indexer instanceof SV_SearchImprovements_Search_IndexerProxy) { $indexer->setProxyMetaData($metadata); } else { $indexer = new SV_SearchImprovements_Search_IndexerProxy( $indexer, $metadata ); } parent::_insertIntoIndex($indexer, $data, $parentData); } public function quickIndex(XenForo_Search_Indexer $indexer, array $contentIds) { $indexer = new SV_SearchImprovements_Search_IndexerProxy($indexer, array()); return parent::quickIndex($indexer, $contentIds); } }
Add git pull back in
<?php require 'core.php'; // No unauthenticated deploys! protectPage(); // Run relevant deploy. $hash = $_GET['project']; $targets = getDeployTargets(); foreach ($targets as $target) { if ($target->getIdentifier() == $hash) { $result = 'Trying to execute deploy as: ' . shell_exec('whoami'); $result .= shell_exec('/usr/bin/git pull 2>&1'); // Execute script. if ($result == null) { echo json_encode([ 'status' => 'warning', 'message' => 'It doesn\'t look like your website deployed properly. Executing your script returned null.', 'result' => $result, ]); // Null output from script.git l } else if ($result == '0') { echo json_encode([ 'status' => 'success', 'message' => 'Your website should be online and ready! Your script ran without a problem.', 'result' => $result, ]); // If script returns 0, that means success. } else if ($result == '1') { echo json_encode([ 'status' => 'danger', 'message' => 'There was a problem deploying your site. Your script returned a failure.', 'result' => $result, ]); // If script returns 1, that means failure. } else { echo json_encode([ 'status' => 'info', 'message' => 'Your script returned something weird. You should look into this further.', 'result' => $result, ]); // If script returns something else, we dunno. } } }
<?php require 'core.php'; // No unauthenticated deploys! protectPage(); // Run relevant deploy. $hash = $_GET['project']; $targets = getDeployTargets(); foreach ($targets as $target) { if ($target->getIdentifier() == $hash) { //$result = shell_exec('/usr/bin/git pull 2>&1'); // Execute script. $result = shell_exec('whoami'); if ($result == null) { echo json_encode([ 'status' => 'warning', 'message' => 'It doesn\'t look like your website deployed properly. Executing your script returned null.', 'result' => $result, ]); // Null output from script. } else if ($result == '0') { echo json_encode([ 'status' => 'success', 'message' => 'Your website should be online and ready! Your script ran without a problem.', 'result' => $result, ]); // If script returns 0, that means success. } else if ($result == '1') { echo json_encode([ 'status' => 'danger', 'message' => 'There was a problem deploying your site. Your script returned a failure.', 'result' => $result, ]); // If script returns 1, that means failure. } else { echo json_encode([ 'status' => 'info', 'message' => 'Your script returned something weird. You should look into this further.', 'result' => $result, ]); // If script returns something else, we dunno. } } }
Allow users to enlarge project images
@extends('layout.base') @section('body') <div id="viewport"> @include('layout.header') <div id="main"> <div id="crumbtrail"> <ul> <li class="fa fa-home"> <li>Project <li>{{ $project->title }} </ul> </div> <section class="project"> <div class="subsection left-aligned flip desktop-right"> <h2>{{ $project->title }}</h2> <table> <tr><td>Project:</td><td>{{ $project->title }}</td></tr> <tr><td>Release:</td><td>{{ $project->released }}</td></tr> <tr><td>Technologies:</td><td>{{ $project->tech }}</td></tr> <tr><td>View:</td><td><a href="{{ $project->url }}">{{ substr($project->url,0,35).'...' }}</a></td></tr> </table> {{ Parsedown::instance()->text($project->text) }} </div> <div class="subsection left-aligned flip desktop-left"> @foreach($project->images as $image) <a href="/img/projects/{{ $image->filename }}"> <img src="/img/projects/{{ $image->filename }}" width="100%" height="100%" class="project-image"> </a> @endforeach </div> </section> </div> </div> @stop
@extends('layout.base') @section('body') <div id="viewport"> @include('layout.header') <div id="main"> <div id="crumbtrail"> <ul> <li class="fa fa-home"> <li>Project <li>{{ $project->title }} </ul> </div> <section class="project"> <div class="subsection left-aligned flip desktop-right"> <h2>{{ $project->title }}</h2> <table> <tr><td>Project:</td><td>{{ $project->title }}</td></tr> <tr><td>Release:</td><td>{{ $project->released }}</td></tr> <tr><td>Technologies:</td><td>{{ $project->tech }}</td></tr> <tr><td>View:</td><td><a href="{{ $project->url }}">{{ substr($project->url,0,35).'...' }}</a></td></tr> </table> {{ Parsedown::instance()->text($project->text) }} </div> <div class="subsection left-aligned flip desktop-left"> @foreach($project->images as $image) <img src="/img/projects/{{ $image->filename }}" width="100%" height="100%" class="project-image"> @endforeach </div> </section> </div> </div> @stop
Use Throwable and fixed throws annotation
<?php namespace League\Tactician\Doctrine\ORM; use Doctrine\ORM\EntityManagerInterface; use League\Tactician\Command; use Exception; use League\Tactician\Middleware; use Throwable; /** * Wraps command execution inside a Doctrine ORM transaction */ class TransactionMiddleware implements Middleware { /** * @var EntityManagerInterface */ private $entityManager; /** * @param EntityManagerInterface $entityManager */ public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } /** * Executes the given command and optionally returns a value * * @param object $command * @param callable $next * @return mixed * @throws Throwable */ public function execute($command, callable $next) { $this->entityManager->beginTransaction(); try { $returnValue = $next($command); $this->entityManager->flush(); $this->entityManager->commit(); } catch (Exception $e) { $this->entityManager->close(); $this->entityManager->rollback(); throw $e; } catch (Throwable $e) { $this->entityManager->close(); $this->entityManager->rollback(); throw $e; } return $returnValue; } }
<?php namespace League\Tactician\Doctrine\ORM; use Doctrine\ORM\EntityManagerInterface; use League\Tactician\Command; use Error; use Exception; use League\Tactician\Middleware; /** * Wraps command execution inside a Doctrine ORM transaction */ class TransactionMiddleware implements Middleware { /** * @var EntityManagerInterface */ private $entityManager; /** * @param EntityManagerInterface $entityManager */ public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } /** * Executes the given command and optionally returns a value * * @param object $command * @param callable $next * @return mixed * @throws Exception */ public function execute($command, callable $next) { $this->entityManager->beginTransaction(); try { $returnValue = $next($command); $this->entityManager->flush(); $this->entityManager->commit(); } catch (Exception $e) { $this->entityManager->close(); $this->entityManager->rollback(); throw $e; } catch (Error $e) { $this->entityManager->close(); $this->entityManager->rollback(); throw $e; } return $returnValue; } }
CA-40618: Change path to the supplemental pack Signed-off-by: Javier Alvarez-Valle <[email protected]>
import subprocess, sys, os.path class DRAC_NO_SUPP_PACK(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) class DRAC_POWERON_FAILED(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) def run2(command): run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return out, err = [ e.splitlines() for e in run.communicate() ] return run.returncode, out, err drac_path='/opt/dell/srvadmin/sbin/racadm' def DRAC( power_on_ip, user, password): if( not os.path.exists(drac_path)): raise DRAC_NO_SUPP_PACK() cmd='%s -r %s -u %s -p %s serveraction powerup' % (drac_path, power_on_ip, user, password) retcode,out,err=run2(cmd) if(len(err)==0): return str(True) else: raise DRAC_POWERON_FAILED() def main(): if len(sys.argv)<3: exit(0) ip=sys.argv[1] user=sys.argv[2] password=sys.argv[3] print DRAC(ip,user,password) if __name__ == "__main__": main()
import subprocess, sys, os.path class DRAC_NO_SUPP_PACK(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) class DRAC_POWERON_FAILED(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) def run2(command): run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return out, err = [ e.splitlines() for e in run.communicate() ] return run.returncode, out, err drac_path='/usr/sbin/racadm' def DRAC( power_on_ip, user, password): if( not os.path.exists(drac_path)): raise DRAC_NO_SUPP_PACK() cmd='%s -r %s -u %s -p %s serveraction powerup' % (drac_path, power_on_ip, user, password) retcode,out,err=run2(cmd) if(len(err)==0): return str(True) else: raise DRAC_POWERON_FAILED() def main(): if len(sys.argv)<3: exit(0) ip=sys.argv[1] user=sys.argv[2] password=sys.argv[3] print DRAC(ip,user,password) if __name__ == "__main__": main()
Rework the versions form widget
from __future__ import unicode_literals from django import forms from django.contrib.contenttypes.admin import GenericStackedInline from .forms import object_version_choices from .models import PublishAction class ActionInline(GenericStackedInline): model = PublishAction fields = ('scheduled_time', 'publish_version') extra = 0 def get_formset(self, request, obj=None, form=None, **kwargs): BaseFormset = super(ActionInline, self).get_formset(request, obj, **kwargs) class ActionFormset(BaseFormset): """ Customised formset to save the user who has created/updated the action. """ def save_new(self, form, commit): obj = super(ActionFormset, self).save_new(form, commit=False) obj.user = request.user obj.save() return obj def save_existing(self, form, instance, commit): obj = super(ActionFormset, self).save_existing(form, instance, commit=False) obj.user = request.user obj.save() return obj # Customised widget which limits the users choices to versions which have been saved for # this object. ActionFormset.form.base_fields['publish_version'].widget = forms.widgets.Select( choices=object_version_choices(obj=obj), ) return ActionFormset
from __future__ import unicode_literals from django import forms from django.contrib.contenttypes.admin import GenericStackedInline from .forms import object_version_choices from .models import PublishAction class ActionInline(GenericStackedInline): model = PublishAction fields = ('scheduled_time', 'publish_version') extra = 0 def get_formset(self, request, obj=None, form=None, **kwargs): class VersionForm(forms.ModelForm): """ Customised form which limits the users choices to versions which have been saved for this object. """ class Meta: widgets = { 'publish_version': forms.widgets.Select( choices=object_version_choices(obj=obj), ), } BaseFormset = super(ActionInline, self).get_formset( request, obj, form=VersionForm, **kwargs ) class ActionFormset(BaseFormset): """ Customised formset to save the user who has created/updated the action. """ def save_new(self, form, commit): obj = super(ActionFormset, self).save_new(form, commit=False) obj.user = request.user obj.save() return obj def save_existing(self, form, instance, commit): obj = super(ActionFormset, self).save_existing(form, instance, commit=False) obj.user = request.user obj.save() return obj return ActionFormset
Add ignore_404 setting to config
<?php /* * This file is part of the Raygunbundle package. * * (c) nietonfir <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Nietonfir\RaygunBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('nietonfir_raygun'); $rootNode ->children() ->scalarNode('api_key') ->isRequired() ->cannotBeEmpty() ->end() // api_key ->booleanNode('async') ->defaultTrue() ->end() // async ->booleanNode('debug_mode') ->defaultFalse() ->end() // debug_mode ->booleanNode('ignore_404') ->defaultFalse() ->end() // ignore_404 ->end() ->validate() ->ifTrue(function($v){return $v['debug_mode'];}) ->then(function($v){$v['async'] = false;return $v;}) ->end(); return $treeBuilder; } }
<?php /* * This file is part of the Raygunbundle package. * * (c) nietonfir <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Nietonfir\RaygunBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/configuration.html} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('nietonfir_raygun'); $rootNode ->children() ->scalarNode('api_key') ->isRequired() ->cannotBeEmpty() ->end() // api_key ->booleanNode('async') ->defaultTrue() ->end() // async ->booleanNode('debug_mode') ->defaultFalse() ->end() // debug_mode ->end() ->validate() ->ifTrue(function($v){return $v['debug_mode'];}) ->then(function($v){$v['async'] = false;return $v;}) ->end(); return $treeBuilder; } }
Put prefix to enum values. Removed old hack.
from scripts import utils class CUBAEnumGenerator(object): """Generator class for cuba.py enumeration. """ def generate(self, cuba_dict, simphony_metadata_dict, output): """Generates the cuba file from the yaml-extracted dictionary of cuba and simphony_metadata files. Writes the generated code in the file object output """ lines = [ '# code auto-generated by the\n', '# simphony-metadata/scripts/generate.py script.\n', '# cuba.yml VERSION: {}\n'.format(cuba_dict['VERSION']), 'from enum import Enum, unique\n', '\n', '\n', '@unique\n', 'class CUBA(Enum):\n' ] template = ' {} = "{}"\n' all_keys = set( cuba_dict['CUBA_KEYS']) | set(simphony_metadata_dict['CUDS_KEYS']) for keyword in sorted(list(all_keys)): lines.append(template.format(keyword, utils.with_cuba_prefix(keyword))) output.writelines(lines)
from scripts.old_single_meta_class_generator import CUBA_DATA_CONTAINER_EXCLUDE class CUBAEnumGenerator(object): """Generator class for cuba.py enumeration. """ def generate(self, cuba_dict, simphony_metadata_dict, output): """Generates the cuba file from the yaml-extracted dictionary of cuba and simphony_metadata files. Writes the generated code in the file object output """ lines = [ '# code auto-generated by the\n', '# simphony-metadata/scripts/generate.py script.\n', '# cuba.yml VERSION: {}\n'.format(cuba_dict['VERSION']), 'from enum import Enum, unique\n', '\n', '\n', '@unique\n', 'class CUBA(Enum):\n' ] template = ' {} = "{}"\n' all_keys = set( cuba_dict['CUBA_KEYS']) | set(simphony_metadata_dict['CUDS_KEYS']) for keyword in sorted(list(all_keys)): if keyword in CUBA_DATA_CONTAINER_EXCLUDE: continue lines.append(template.format(keyword, keyword)) output.writelines(lines)
Allow OAR file rule to use non-OSGI jars Change-Id: If2a82bdb5b217270ca02760f1c6cfc6f8f0dc7da
#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: parts = mvnCoords.split(':') if len(parts) > 3: parts.insert(2, parts.pop()) # move version to the 3rd position groupId, artifactId, version = parts[0:3] groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files)
#!/usr/bin/env python #FIXME Add license from zipfile import ZipFile def generateOar(output, files=[]): # Note this is not a compressed zip with ZipFile(output, 'w') as zip: for file, mvnCoords in files: filename = file.split('/')[-1] if mvnCoords == 'NONE': dest = filename else: groupId, artifactId, version = mvnCoords.split(':') groupId = groupId.replace('.', '/') extension = filename.split('.')[-1] if extension == 'jar': filename = '%s-%s.jar' % ( artifactId, version ) elif 'features.xml' in filename: filename = '%s-%s-features.xml' % ( artifactId, version ) dest = 'm2/%s/%s/%s/%s' % ( groupId, artifactId, version, filename ) zip.write(file, dest) if __name__ == '__main__': import sys if len(sys.argv) < 2: print 'USAGE' sys.exit(1) output = sys.argv[1] args = sys.argv[2:] if len(args) % 2 != 0: print 'There must be an even number of args: file mvn_coords' sys.exit(2) files = zip(*[iter(args)]*2) generateOar(output, files)
Bump version and set license to MIT
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-munigeo', version='0.1.4', packages=['munigeo'], include_package_data=True, license='MIT', description='A Django app for processing municipality-related geospatial data.', long_description=README, author='Juha Yrjölä', author_email='[email protected]', install_requires=[ 'Django', 'requests', 'requests_cache', 'django_mptt', 'django_modeltranslation', 'six', 'pyyaml', ], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)' 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Scientific/Engineering :: GIS', ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-munigeo', version='0.1', packages=['munigeo'], include_package_data=True, license='AGPLv3', description='A Django app for processing municipality-related geospatial data.', long_description=README, author='Juha Yrjölä', author_email='[email protected]', install_requires=[ 'Django', 'requests', 'requests_cache', 'django_mptt', 'django_modeltranslation', 'six', 'pyyaml', ], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)' 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Scientific/Engineering :: GIS', ], )
Handle Errors by default by checking error handlers
<?php namespace Flubber; define('FLIB', dirname(__FILE__).'/'); define('FLVERSION', 2.0); // Load the core functions require_once 'Functions.php'; use Flubber\FLException as FLException, Flubber\Datastore as Datastore, Flubber\Request as Request, Flubber\Locale as Locale, Flubber\Session as Session; // Load All Locale strings. Locale::autoload(); // Load datastore Datastore::init(); // Load Session Session::init(); // Initialize request Request::init(); class Flubber { protected $request = null; function __construct() { } /* * Initialize Main application */ public function start() { global $FLRequest; // Run module passing the request to get appropriate response try { if ($FLRequest->handler == null) { throw new FLException('Not Found', array('status' => 404)); } $module = gethandler($FLRequest->handler); call_user_func_array( array($module, $FLRequest->method), $FLRequest->params); } catch (FLException $e) { $FLRequest->exception = $e; $FLRequest->handler = 'Error'; $error = null; if (file_exists(HANDLER_PATH.'/Error.php')) { $error = gethandler('Error'); } else { $error = ( new ErrorHandler() ); } $error->notify(); } catch (\Exception $e) { echo $e->getmessage(); } finally { return true; } } } ?>
<?php namespace Flubber; define('FLIB', dirname(__FILE__).'/'); define('FLVERSION', 2.0); // Load the core functions require_once 'Functions.php'; use Flubber\Datastore as Datastore, Flubber\Request as Request, Flubber\FLException as FLException, Flubber\Locale as Locale, Flubber\Session as Session; // Load All Locale strings. Locale::autoload(); // Load datastore Datastore::init(); // Load Session Session::init(); // Initialize request Request::init(); class Flubber { protected $request = null; function __construct() { } /* * Initialize Main application */ public function start() { global $FLRequest; // Run module passing the request to get appropriate response try { $module = gethandler($FLRequest->handler); call_user_func_array( array($module, $FLRequest->method), $FLRequest->params); } catch (FLException $e) { $FLRequest->exception = $e; $FLRequest->handler = 'Error'; $error = gethandler($FLRequest->handler); $error->notify(); } catch (\Exception $e) { echo $e->getmessage(); } finally { return true; } } } ?>
Add a properly string for outputing
from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: output_data = data.replace("\n", '') output_data = output_data[0:60] + '...' else: output_data = data output.printRequest(method, conf['domain'], fullpath, params, desc, output_data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result
from . import output import json import sys import urllib.parse import http.client def getRequest(id, conf): db = conf['db'] headers = conf['headers'] test = db[id] method = test['method'].upper() fullpath = conf['path'] + test['path'] desc = test['desc'] params = '' server = conf['domain'] + ':' + conf['port'] try: conn = http.client.HTTPConnection(server) except IOError as err: conf['errors'].append("Server " + server + " not found!") output.validationError(conf) sys.exit(1) if method == 'GET': conn.request(method, fullpath) else: params = urllib.parse.urlencode(test['data']) res = conn.request(method, fullpath, params, headers) res = conn.getresponse() data = res.read().decode("utf-8").strip() if len(data) > 60: data = data[0:60] + '...' output.printRequest(method, conf['domain'], fullpath, params, desc, data, res.status) result = {} result['status'] = res.status result['header'] = res.getheaders() try: result['data'] = json.loads(data) except ValueError: print("Invalid JSON outout") # finally: # result['data'] = None return result
Add nose tests to validate Exception raising.
import unittest from polycircles import polycircles from nose.tools import raises class TestExceptions(unittest.TestCase): @raises(ValueError) def test_less_than_3_vertices_no_1(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=2) @raises(ValueError) def test_less_than_3_vertices_no_2(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=-3) @raises(ValueError) def test_less_than_3_vertices_no_3(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=0) @raises(ValueError) def test_erroneous_latitude_1(self): polycircle = polycircles.Polycircle(latitude=-100, longitude=30, radius=100) @raises(ValueError) def test_erroneous_latitude_2(self): polycircle = polycircles.Polycircle(latitude=100, longitude=30, radius=100) @raises(ValueError) def test_erroneous_latitude_3(self): polycircle = polycircles.Polycircle(latitude=200, longitude=30, radius=100) @raises(ValueError) def test_erroneous_longitude_1(self): polycircle = polycircles.Polycircle(latitude=30, longitude=-200, radius=100) @raises(ValueError) def test_erroneous_longitude_2(self): polycircle = polycircles.Polycircle(latitude=30, longitude=200, radius=100) if __name__ == '__main__': unittest.main(verbose=2)
import unittest from polycircles import polycircles from nose.tools import raises class TestExceptions(unittest.TestCase): @raises(ValueError) def test_less_than_3_vertices_no_1(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=2) @raises(ValueError) def test_less_than_3_vertices_no_2(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=-3) @raises(ValueError) def test_less_than_3_vertices_no_3(self): polycircle = polycircles.Polycircle(latitude=30, longitude=30, radius=100, number_of_vertices=0) if __name__ == '__main__': unittest.main(verbose=2)
Add Accept header to use version 1.1
from libcloud.utils.py3 import httplib from libcloud.common.types import InvalidCredsError from libcloud.common.base import JsonResponse from libcloud.common.base import ConnectionKey class MaxihostResponse(JsonResponse): valid_response_codes = [httplib.OK, httplib.ACCEPTED, httplib.CREATED, httplib.NO_CONTENT] def parse_error(self): if self.status == httplib.UNAUTHORIZED: body = self.parse_body() raise InvalidCredsError(body['message']) else: body = self.parse_body() if 'message' in body: error = '%s (code: %s)' % (body['message'], self.status) else: error = body return error def success(self): return self.status in self.valid_response_codes class MaxihostConnection(ConnectionKey): """ Connection class for the Maxihost driver. """ host = 'api.maxihost.com' responseCls = MaxihostResponse def add_default_headers(self, headers): """ Add headers that are necessary for every request This method adds apikey to the request. """ headers['Authorization'] = 'Bearer %s' % (self.key) headers['Content-Type'] = 'application/json' headers['Accept']: 'application/vnd.maxihost.v1.1+json' return headers
from libcloud.utils.py3 import httplib from libcloud.common.types import InvalidCredsError from libcloud.common.base import JsonResponse from libcloud.common.base import ConnectionKey class MaxihostResponse(JsonResponse): valid_response_codes = [httplib.OK, httplib.ACCEPTED, httplib.CREATED, httplib.NO_CONTENT] def parse_error(self): if self.status == httplib.UNAUTHORIZED: body = self.parse_body() raise InvalidCredsError(body['message']) else: body = self.parse_body() if 'message' in body: error = '%s (code: %s)' % (body['message'], self.status) else: error = body return error def success(self): return self.status in self.valid_response_codes class MaxihostConnection(ConnectionKey): """ Connection class for the Maxihost driver. """ host = 'api.maxihost.com' responseCls = MaxihostResponse def add_default_headers(self, headers): """ Add headers that are necessary for every request This method adds apikey to the request. """ headers['Authorization'] = 'Bearer %s' % (self.key) headers['Content-Type'] = 'application/json' return headers
Enable loading of SQL scripts with arbitrary name
""" http://djangosnippets.org/snippets/2311/ Ensure South will update our custom SQL during a call to `migrate`. """ import logging import traceback from south.signals import post_migrate logger = logging.getLogger(__name__) def run_initial_sql(sender, **kwargs): import os import re from django.db import connection, transaction, models app_label = kwargs.get('app') app_dir = os.path.normpath(os.path.join(os.path.dirname( models.get_app(app_label).__file__), 'sql')) if not os.path.exists(app_dir): return r = re.compile(r'^.*\.sql$') sql_files = [os.path.join(app_dir, f) for f in os.listdir(app_dir) if r.match(f) is not None] sql_files.sort() cursor = connection.cursor() for sql_file in sql_files: try: logger.info("Loading initial SQL data from '%s'" % sql_file) f = open(sql_file) sql = f.read() f.close() cursor.execute(sql) except Exception, e: logger.error("Failed to install custom SQL file '%s': %s\n" % (sql_file, e)) traceback.print_exc() transaction.rollback_unless_managed() else: transaction.commit_unless_managed() post_migrate.connect(run_initial_sql)
""" http://djangosnippets.org/snippets/2311/ Ensure South will update our custom SQL during a call to `migrate`. """ import logging import traceback from south.signals import post_migrate logger = logging.getLogger(__name__) def run_initial_sql(sender, **kwargs): app_label = kwargs.get('app') import os from django.db import connection, transaction, models app_dir = os.path.normpath(os.path.join(os.path.dirname( models.get_app(app_label).__file__), 'sql')) backend_name = connection.settings_dict['ENGINE'].split('.')[-1] sql_files = [os.path.join(app_dir, "%s.%s.sql" % (app_label, backend_name)), os.path.join(app_dir, "%s.sql" % app_label)] cursor = connection.cursor() for sql_file in sql_files: try: if os.path.exists(sql_file): logger.info("Loading initial SQL data from '%s'" % sql_file) f = open(sql_file) sql = f.read() f.close() cursor.execute(sql) except Exception, e: logger.error("Failed to install custom SQL file '%s': %s\n" % (sql_file, e)) traceback.print_exc() transaction.rollback_unless_managed() else: transaction.commit_unless_managed() post_migrate.connect(run_initial_sql)
Fix link to home in header
import React from "react"; import { Link } from "react-router"; import { Header, Footer } from "formidable-landers"; // Variables and Stylesheet import LOGO from "../../static/logo.svg"; import "../styles/styles.css"; class App extends React.Component { render() { const SpectacleLogoLink = ( <h1 className="u-noMargin"> <Link to="/" className="Logo" dangerouslySetInnerHTML={{__html: LOGO}} /> </h1> ); return ( <div className="Site"> <Header logoProject={SpectacleLogoLink} padding="20px 6vw 30px" theme="dark" > <div className="default"> <Link to="/about" activeClassName="is-active">About</Link> <Link to="/docs" activeClassName="is-active">Docs</Link> <a href="https://www.github.com/FormidableLabs/spectacle/issues">Issues</a> <a href="https://github.com/FormidableLabs/spectacle">GitHub</a> </div> </Header> { this.props.children } <Footer padding="5rem 6vw 6rem" /> </div> ); } } App.propTypes = { children: React.PropTypes.node }; App.defaultProps = { children: null }; export default App;
import React from "react"; import { Link } from "react-router"; import { Header, Footer } from "formidable-landers"; // Variables and Stylesheet import LOGO from "../../static/logo.svg"; import "../styles/styles.css"; class App extends React.Component { render() { const SpectacleLogoLink = ( <h1 className="u-noMargin"> <a href="/" className="Logo" dangerouslySetInnerHTML={{__html: LOGO}} /> </h1> ); return ( <div className="Site"> <Header logoProject={SpectacleLogoLink} padding="20px 6vw 30px" theme="dark" > <div className="default"> <Link to="/about" activeClassName="is-active">About</Link> <Link to="/docs" activeClassName="is-active">Docs</Link> <a href="https://www.github.com/FormidableLabs/spectacle/issues">Issues</a> <a href="https://github.com/FormidableLabs/spectacle">GitHub</a> </div> </Header> { this.props.children } <Footer padding="5rem 6vw 6rem" /> </div> ); } } App.propTypes = { children: React.PropTypes.node }; App.defaultProps = { children: null }; export default App;