text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Add alias "test" to "nodeunit" task
module.exports = function( grunt ) { "use strict"; grunt.initConfig({ bump: { options: { files: [ "package.json" ], // Commit commit: true, commitMessage: "Release v%VERSION%", commitFiles: [ "package.json" ], // Tag createTag: true, tagName: "%VERSION%", tagMessage: "Version %VERSION%", // Push push: true, pushTo: "origin" } }, jshint: { options: { jshintrc: ".jshintrc" }, all: [ "Gruntfile.js", "tasks/*.js", "test/*.js" ] }, jscs: { src: "<%= jshint.all %>" }, nodeunit: { methods: "test/methods.js", enmasse: "test/enmasse.js" } }); // Load grunt tasks from NPM packages require( "load-grunt-tasks" )( grunt ); grunt.loadTasks( "tasks" ); grunt.registerTask( "test", "nodeunit" ); grunt.registerTask( "default", [ "jshint", "jscs", "nodeunit" ] ); };
module.exports = function( grunt ) { "use strict"; grunt.initConfig({ bump: { options: { files: [ "package.json" ], // Commit commit: true, commitMessage: "Release v%VERSION%", commitFiles: [ "package.json" ], // Tag createTag: true, tagName: "%VERSION%", tagMessage: "Version %VERSION%", // Push push: true, pushTo: "origin" } }, jshint: { options: { jshintrc: ".jshintrc" }, all: [ "Gruntfile.js", "tasks/*.js", "test/*.js" ] }, jscs: { src: "<%= jshint.all %>" }, nodeunit: { methods: "test/methods.js", enmasse: "test/enmasse.js" } }); // Load grunt tasks from NPM packages require( "load-grunt-tasks" )( grunt ); grunt.loadTasks( "tasks" ); grunt.registerTask( "default", [ "jshint", "jscs", "nodeunit" ] ); };
Use the real path to load yaml resources
<?php namespace LAG\AdminBundle\Resource\Loader; use Exception; use Symfony\Component\Filesystem\Exception\FileNotFoundException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Symfony\Component\Yaml\Yaml; class ResourceLoader { /** * Load admins configuration in the yaml files found in the given resource path. An exception will be thrown if the * path is invalid. * * @throws Exception */ public function load(string $resourcesPath): array { $fileSystem = new Filesystem(); $resourcesPath = realpath($resourcesPath); if (!$fileSystem->exists($resourcesPath)) { throw new FileNotFoundException(null, 0, null, $resourcesPath); } if (!is_dir($resourcesPath)) { throw new Exception(sprintf('The resources path %s should be a directory', $resourcesPath)); } $finder = new Finder(); $finder ->files() ->name('*.yaml') ->in($resourcesPath) ; $data = []; foreach ($finder as $fileInfo) { $yaml = Yaml::parse(file_get_contents($fileInfo->getRealPath()), Yaml::PARSE_CUSTOM_TAGS); if (!is_array($yaml)) { continue; } foreach ($yaml as $name => $admin) { $data[$name] = $admin; } } return $data; } }
<?php namespace LAG\AdminBundle\Resource\Loader; use Exception; use Symfony\Component\Filesystem\Exception\FileNotFoundException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Symfony\Component\Yaml\Yaml; class ResourceLoader { /** * Load admins configuration in the yaml files found in the given resource path. An exception will be thrown if the * path is invalid. * * @throws Exception */ public function load(string $resourcesPath): array { $fileSystem = new Filesystem(); if (!$fileSystem->exists($resourcesPath)) { throw new FileNotFoundException(null, 0, null, $resourcesPath); } if (!is_dir($resourcesPath)) { throw new Exception(sprintf('The resources path %s should be a directory', $resourcesPath)); } $finder = new Finder(); $finder ->files() ->name('*.yaml') ->in($resourcesPath) ; $data = []; foreach ($finder as $fileInfo) { $yaml = Yaml::parse(file_get_contents($fileInfo->getRealPath()), Yaml::PARSE_CUSTOM_TAGS); if (!is_array($yaml)) { continue; } foreach ($yaml as $name => $admin) { $data[$name] = $admin; } } return $data; } }
Make it just return the string if it is not base64
import zlib import base64 import binascii from django.db import models from django.core import exceptions class ZipField(models.Field): def db_type(self, connection): return 'bytea' def pre_save(self, model_instance, add): value = getattr(model_instance, self.attname) assert isinstance(value, (bytes, str)), 'Values must be of type str or bytes, got {}'.format(type(value)) if not value and not self.blank: raise exceptions.ValidationError('"{}" on {!r} can not be blank or empty'.format(self.attname, model_instance)) if isinstance(value, str): value = value.encode() return base64.b64encode(zlib.compress(value)) def from_db_value(self, value, expression, connection, context): if value is None: return value assert value return zlib.decompress(base64.b64decode(value)) def to_python(self, value): assert value if value is None or isinstance(value, ZipField): return value try: base64.decodebytes(bytes(value, 'utf8')) except binascii.Error: # it's not base64, return it. return value return zlib.decompress(base64.b64decode(value))
import zlib import base64 import binascii from django.db import models from django.core import exceptions class ZipField(models.Field): def db_type(self, connection): return 'bytea' def pre_save(self, model_instance, add): value = getattr(model_instance, self.attname) assert isinstance(value, (bytes, str)), 'Values must be of type str or bytes, got {}'.format(type(value)) if not value and not self.blank: raise exceptions.ValidationError('"{}" on {!r} can not be blank or empty'.format(self.attname, model_instance)) if isinstance(value, str): value = value.encode() return base64.b64encode(zlib.compress(value)) def from_db_value(self, value, expression, connection, context): if value is None: return value assert value return zlib.decompress(base64.b64decode(value)) def to_python(self, value): assert value if value is None or isinstance(value, ZipField): return value # TODO: Not sure if this is necessary or just solving a temporary error try: base64.decodestring(bytes(value, 'utf8')) except binascii.Error: value = base64.b64encode(zlib.compress(bytes(value, 'utf8'))) # END TODO return zlib.decompress(base64.b64decode(value))
Remove return state from main `main`
import time import transitions from panoptes.utils.logger import has_logger @has_logger class PanState(transitions.State): """ Base class for PANOPTES transitions """ def __init__(self, *args, **kwargs): name = kwargs.get('name', self.__class__) self.panoptes = kwargs.get('panoptes', None) super().__init__(name=name, on_enter=['execute']) self._sleep_delay = 3 # seconds def main(self): assert self.panoptes is not None msg = "Must implement `main` method inside class {}. Exiting".format(self.name) self.panoptes.logger.warning(msg) def sleep(self, seconds=None): """ sleep for `seconds` or `_sleep_delay` seconds This puts the state into a loop that is responsive to outside messages. Args: seconds(float): Seconds to sleep for, defaults to `_sleep_delay`. """ assert self.panoptes is not None if seconds is None: seconds = self._sleep_delay if seconds > 10: step_time = seconds / 4 while seconds: seconds = seconds - step_time # NOTE: DO SOMETHING RESPONSIVE HERE time.sleep(step_time) else: time.sleep(seconds)
import time import transitions from panoptes.utils.logger import has_logger @has_logger class PanState(transitions.State): """ Base class for PANOPTES transitions """ def __init__(self, *args, **kwargs): name = kwargs.get('name', self.__class__) self.panoptes = kwargs.get('panoptes', None) super().__init__(name=name, on_enter=['execute']) self._sleep_delay = 3 # seconds def main(self): assert self.panoptes is not None msg = "Must implement `main` method inside class {}. Exiting".format(self.name) self.panoptes.logger.warning(msg) return 'exit' def sleep(self, seconds=None): """ sleep for `seconds` or `_sleep_delay` seconds This puts the state into a loop that is responsive to outside messages. Args: seconds(float): Seconds to sleep for, defaults to `_sleep_delay`. """ assert self.panoptes is not None if seconds is None: seconds = self._sleep_delay if seconds > 10: step_time = seconds / 4 while seconds: seconds = seconds - step_time # NOTE: DO SOMETHING RESPONSIVE HERE time.sleep(step_time) else: time.sleep(seconds)
Replace reference to non-existent Precondtions2 Removed in jclouds 1.6.
/** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. jclouds licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jclouds.karaf.recipe; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Strings.emptyToNull; import com.google.common.base.Predicate; public class RecipeProviderPredicates { public static Predicate<RecipeProvider> id(final String id) { checkNotNull(emptyToNull(id), "id must be defined"); return new Predicate<RecipeProvider>() { /** * {@inheritDoc} */ @Override public boolean apply(RecipeProvider recipeProvider) { return recipeProvider.getId().equals(id); } /** * {@inheritDoc} */ @Override public String toString() { return "id(" + id + ")"; } }; } }
/** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. jclouds licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jclouds.karaf.recipe; import com.google.common.base.Predicate; import org.jclouds.util.Preconditions2; public class RecipeProviderPredicates { public static Predicate<RecipeProvider> id(final String id) { Preconditions2.checkNotEmpty(id, "id must be defined"); return new Predicate<RecipeProvider>() { /** * {@inheritDoc} */ @Override public boolean apply(RecipeProvider recipeProvider) { return recipeProvider.getId().equals(id); } /** * {@inheritDoc} */ @Override public String toString() { return "id(" + id + ")"; } }; } }
Add check for active and registered users
""" This migration subscribes each user to USER_SUBSCRIPTIONS_AVAILABLE if a subscription does not already exist. """ import logging import sys from website.app import init_app from website import models from website.notifications.model import NotificationSubscription from website.notifications import constants from website.notifications.utils import to_subscription_key from scripts import utils as scripts_utils logger = logging.getLogger(__name__) app = init_app() def add_global_subscriptions(): notification_type = 'email_transactional' user_events = constants.USER_SUBSCRIPTIONS_AVAILABLE for user in models.User.find(): if user.is_active and user.is_registered: for user_event in user_events: user_event_id = to_subscription_key(user._id, user_event) subscription = NotificationSubscription.load(user_event_id) if not subscription: subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event) subscription.add_user_to_subscription(user, notification_type) subscription.save() logger.info('No subscription found. {} created.'.format(subscription)) else: logger.info('Subscription {} found.'.format(subscription)) if __name__ == '__main__': dry = '--dry' in sys.argv if not dry: scripts_utils.add_file_logger(logger, __file__) add_global_subscriptions()
""" This migration subscribes each user to USER_SUBSCRIPTIONS_AVAILABLE if a subscription does not already exist. """ import logging import sys from website.app import init_app from website import models from website.notifications.model import NotificationSubscription from website.notifications import constants from website.notifications.utils import to_subscription_key from scripts import utils as scripts_utils logger = logging.getLogger(__name__) app = init_app() def add_global_subscriptions(): notification_type = 'email_transactional' user_events = constants.USER_SUBSCRIPTIONS_AVAILABLE for user in models.User.find(): for user_event in user_events: user_event_id = to_subscription_key(user._id, user_event) subscription = NotificationSubscription.load(user_event_id) if not subscription: subscription = NotificationSubscription(_id=user_event_id, owner=user, event_name=user_event) subscription.add_user_to_subscription(user, notification_type) subscription.save() logger.info('No subscription found. {} created.'.format(subscription)) else: logger.info('Subscription {} found.'.format(subscription)) if __name__ == '__main__': dry = '--dry' in sys.argv if not dry: scripts_utils.add_file_logger(logger, __file__) add_global_subscriptions()
Fix a problem with this object passed to each expanded test function
/*! * data-driven * Copyright(c) 2013 Fluent Software Solutions Ltd <[email protected]> * MIT Licensed */ module.exports = function(data, fn) { var mochaIt = it var mochaBefore = before data.forEach(function(testData) { try { it = function(title, f) { for (var key in testData) { title = title.replace('{'+key+'}',testData[key]) } if (f !== undefined) { var testFn = f.length < 2 ? function() { f.call(this,testData) } : function(done) { f.call(this,testData,done) } } mochaIt(title, testFn) } before = function(f) { var testFn = f.length < 2 ? function() { f(testData) } : function(done) { f(testData,done) } mochaBefore(testFn) } fn() } finally { it = mochaIt before = mochaBefore } }) }
/*! * data-driven * Copyright(c) 2013 Fluent Software Solutions Ltd <[email protected]> * MIT Licensed */ module.exports = function(data, fn) { var mochaIt = it var mochaBefore = before data.forEach(function(testData) { try { it = function(title, f) { for (var key in testData) { title = title.replace('{'+key+'}',testData[key]) } if (f !== undefined) { var testFn = f.length < 2 ? function() { f(testData) } : function(done) { f(testData,done) } } mochaIt(title, testFn) } before = function(f) { var testFn = f.length < 2 ? function() { f(testData) } : function(done) { f(testData,done) } mochaBefore(testFn) } fn() } finally { it = mochaIt before = mochaBefore } }) }
Add support for 'scenario' blocks
import sublime, sublime_plugin, re class ToggleRspecFocusCommand(sublime_plugin.TextCommand): def run(self, edit, surplus=False): for region in self.view.sel(): line = self.view.line(region) line_contents = self.view.substr(line) focus_regex = r'.*(?:it|describe|context|scenario)\s+(?:\"[^\"]+\"|\'[^\']+\'|.+)(\,\s\:focus)(.+)do' focus_match = re.search(focus_regex, line_contents) # If :focus is found, remove it if focus_match: line_without_focus = re.sub(focus_match.group(1), "", line_contents) self.view.replace(edit, line, line_without_focus) # Otherwise, add focus else: unfocus_regex = r'(.*(?:it|describe|context|scenario)\s+(?:\"[^\"]+\"|\'[^\']+\'|.+))(\,?.+)do' unfocus_match = re.search(unfocus_regex, line_contents) if unfocus_match: line_with_focus = unfocus_match.group(1) + ", :focus" + unfocus_match.group(2) + "do" self.view.replace(edit, line, line_with_focus)
import sublime, sublime_plugin, re class ToggleRspecFocusCommand(sublime_plugin.TextCommand): def run(self, edit, surplus=False): for region in self.view.sel(): line = self.view.line(region) line_contents = self.view.substr(line) focus_regex = r'.*(?:it|describe|context)\s+(?:\"[^\"]+\"|\'[^\']+\'|.+)(\,\s\:focus)(.+)do' focus_match = re.search(focus_regex, line_contents) # If :focus is found, remove it if focus_match: line_without_focus = re.sub(focus_match.group(1), "", line_contents) self.view.replace(edit, line, line_without_focus) # Otherwise, add focus else: unfocus_regex = r'(.*(?:it|describe|context)\s+(?:\"[^\"]+\"|\'[^\']+\'|.+))(\,?.+)do' unfocus_match = re.search(unfocus_regex, line_contents) if unfocus_match: line_with_focus = unfocus_match.group(1) + ", :focus" + unfocus_match.group(2) + "do" self.view.replace(edit, line, line_with_focus)
Make actions and properties module conform to plugin-api
const Plugin = require('imdone-api') const _path = require('path') const { statSync } = require('fs') module.exports = class ExtensionPlugin extends Plugin { constructor(project) { super(project) console.log('loading extensions') this.configDir = _path.join(project.path, '.imdone') this.cardActionsFunction = this.loadExtensionModule( () => [], 'actions', 'card' ).bind(this) this.boardActionsFunction = this.loadExtensionModule( () => [], 'actions', 'board' ).bind(this) this.cardPropertiesFunction = this.loadExtensionModule( () => { return {} }, 'properties', 'card' ).bind(this) } getCardProperties(task) { return this.cardPropertiesFunction(task) } getCardActions(task) { return this.cardActionsFunction(task) } getBoardActions() { return this.boardActionsFunction().map(({ title, action }) => ({ name: title, action, })) } getConfigPath(relativePath) { return _path.join(this.configDir, ...relativePath) } loadExtensionModule(_default, ...path) { let extension = _default const extensionPath = this.getConfigPath(path) try { statSync(extensionPath + '.js') delete require.cache[require.resolve(extensionPath)] extension = require(extensionPath) } catch (e) { console.log('No extension found at:', extensionPath) } return extension } }
const Plugin = require('imdone-api') const _path = require('path') const { statSync } = require('fs') module.exports = class ExtensionPlugin extends Plugin { constructor(project) { super(project) console.log('loading extensions') this.configDir = _path.join(project.path, '.imdone') this.cardActionsFunction = this.loadExtensionModule( () => [], 'actions', 'card' ) this.boardActionsFunction = this.loadExtensionModule( () => [], 'actions', 'board' ) this.cardPropertiesFunction = this.loadExtensionModule( () => { return {} }, 'properties', 'card' ) } getCardProperties(task) { return this.cardPropertiesFunction(task) } getCardActions(task) { return this.cardActionsFunction(this.project, task) } getBoardActions() { return this.boardActionsFunction(this.project).map(({ title, action }) => ({ name: title, action, })) } getConfigPath(relativePath) { return _path.join(this.configDir, ...relativePath) } loadExtensionModule(_default, ...path) { let extension = _default const extensionPath = this.getConfigPath(path) try { statSync(extensionPath + '.js') delete require.cache[require.resolve(extensionPath)] extension = require(extensionPath) } catch (e) { console.log('No extension found at:', extensionPath) } return extension } }
Use null user by default instead of 0
<?php namespace Yajra\Auditable; use Illuminate\Database\Eloquent\Model; class AuditableTraitObserver { /** * Model's creating event hook. * * @param Model $model */ public function creating(Model $model) { if (! $model->created_by) { $model->created_by = $this->getAuthenticatedUserId(); } if (! $model->updated_by) { $model->updated_by = $this->getAuthenticatedUserId(); } } /** * Get authenticated user id depending on model's auth guard. * * @return int */ protected function getAuthenticatedUserId() { return auth()->check() ? auth()->id() : null; } /** * Model's updating event hook. * * @param Model $model */ public function updating(Model $model) { if (! $model->isDirty('updated_by')) { $model->updated_by = $this->getAuthenticatedUserId(); } } /** * Model's deleting event hook * * @param Model $model */ public function deleting(Model $model) { if (! $model->deleted_by) { $model->deleted_by = $this->getAuthenticatedUserId(); } } }
<?php namespace Yajra\Auditable; use Illuminate\Database\Eloquent\Model; class AuditableTraitObserver { /** * Model's creating event hook. * * @param Model $model */ public function creating(Model $model) { if (! $model->created_by) { $model->created_by = $this->getAuthenticatedUserId(); } if (! $model->updated_by) { $model->updated_by = $this->getAuthenticatedUserId(); } } /** * Get authenticated user id depending on model's auth guard. * * @return int */ protected function getAuthenticatedUserId() { return auth()->check() ? auth()->id() : 0; } /** * Model's updating event hook. * * @param Model $model */ public function updating(Model $model) { if (! $model->isDirty('updated_by')) { $model->updated_by = $this->getAuthenticatedUserId(); } } /** * Model's deleting event hook * * @param Model $model */ public function deleting(Model $model) { if (! $model->deleted_by) { $model->deleted_by = $this->getAuthenticatedUserId(); } } }
Add missing import to getTILrc
import fs from 'fs'; import { getTILrc } from './helpers'; export function mkdir(dir) { return new Promise((resolve, reject) => { fs.mkdir(dir, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } export function exists(dir) { return new Promise((resolve, reject) => { // TODO check for correct permissions if exists fs.access(dir, fs.R_OK | fs.W_OK, (err) => { if (err) { reject(err); } else { resolve(true); } }); }); } export function mkdirIfNotExists(dir) { return exists(dir).then(() => { return Promise.resolve(); }, () => { return mkdir(dir); }); } export function saveRC(data) { return new Promise((resolve, reject) => { const extractedData = extractData({ ...config, ...data }); const prettyData = JSON.stringify(extractedData, null, 2); fs.writeFile(getTILrc(), prettyData, (err) => { if (err) { reject(err); } else { resolve(extractedData); } }); }); } export function loadRC() { return new Promise((resolve, reject) => { fs.readFile(getTILrc(), 'utf8', (err, data) => { // TODO check file persmissions if (err) { reject(err); } else { resolve(JSON.parse(data)); } }); }); }
import fs from 'fs'; export function mkdir(dir) { return new Promise((resolve, reject) => { fs.mkdir(dir, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } export function exists(dir) { return new Promise((resolve, reject) => { // TODO check for correct permissions if exists fs.access(dir, fs.R_OK | fs.W_OK, (err) => { if (err) { reject(err); } else { resolve(true); } }); }); } export function mkdirIfNotExists(dir) { return exists(dir).then(() => { return Promise.resolve(); }, () => { return mkdir(dir); }); } export function saveRC(data) { return new Promise((resolve, reject) => { const extractedData = extractData({ ...config, ...data }); const prettyData = JSON.stringify(extractedData, null, 2); fs.writeFile(getTILrc(), prettyData, (err) => { if (err) { reject(err); } else { resolve(extractedData); } }); }); } export function loadRC() { return new Promise((resolve, reject) => { fs.readFile(getTILrc(), 'utf8', (err, data) => { // TODO check file persmissions if (err) { reject(err); } else { resolve(JSON.parse(data)); } }); }); }
Add newline to end of file
<?php namespace Paulboco\Powerball\Drawings; class DrawingFacade { /** * The file handler instance. * * @var Paulboco\Powerball\Drawings\FileHandler */ private $handler; /** * The file handler instance. * * @var Paulboco\Powerball\Drawings\FileParser */ private $parser; /** * Create a new drawings facade instance. * * @param string|null $url * @return void */ public function __construct($url = null) { $this->handler = $this->getHandler($url); $this->parser = new FileParser; } /** * Get all drawings as an array of drawing objects. * * @return array */ public function all() { $contents = $this->handler->getContents(); return $this->parser->parse($contents); } /** * Get the content length of the winning numbers file. * * @return integer */ public function length() { return $this->handler->getContentLength(); } /** * Get a new file handler instance. * * @return Paulboco\Powerball\Drawings\FileHandler */ private function getHandler($url) { return new FileHandler(new FileValidator, new FileSizer, $url); } }
<?php namespace Paulboco\Powerball\Drawings; class DrawingFacade { /** * The file handler instance. * * @var Paulboco\Powerball\Drawings\FileHandler */ private $handler; /** * The file handler instance. * * @var Paulboco\Powerball\Drawings\FileParser */ private $parser; /** * Create a new drawings facade instance. * * @param string|null $url * @return void */ public function __construct($url = null) { $this->handler = $this->getHandler($url); $this->parser = new FileParser; } /** * Get all drawings as an array of drawing objects. * * @return array */ public function all() { $contents = $this->handler->getContents(); return $this->parser->parse($contents); } /** * Get the content length of the winning numbers file. * * @return integer */ public function length() { return $this->handler->getContentLength(); } /** * Get a new file handler instance. * * @return Paulboco\Powerball\Drawings\FileHandler */ private function getHandler($url) { return new FileHandler(new FileValidator, new FileSizer, $url); } }
Revert omission of image size Turns out this is still required in SVG mode :D
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Emoji\Listener; use Flarum\Event\ConfigureFormatter; use Illuminate\Contracts\Events\Dispatcher; class FormatEmoticons { /** * @param Dispatcher $events */ public function subscribe(Dispatcher $events) { $events->listen(ConfigureFormatter::class, [$this, 'addEmoticons']); } /** * @param ConfigureFormatter $event */ public function addEmoticons(ConfigureFormatter $event) { $event->configurator->Emoji->useEmojiOne(); $event->configurator->Emoji->omitImageSize(); $event->configurator->Emoji->useSVG(); $event->configurator->Emoji->addAlias(':)', '๐Ÿ™‚'); $event->configurator->Emoji->addAlias(':D', '๐Ÿ˜ƒ'); $event->configurator->Emoji->addAlias(':P', '๐Ÿ˜›'); $event->configurator->Emoji->addAlias(':(', '๐Ÿ™'); $event->configurator->Emoji->addAlias(':|', '๐Ÿ˜'); $event->configurator->Emoji->addAlias(';)', '๐Ÿ˜‰'); $event->configurator->Emoji->addAlias(':\'(', '๐Ÿ˜ข'); $event->configurator->Emoji->addAlias(':O', '๐Ÿ˜ฎ'); $event->configurator->Emoji->addAlias('>:(', '๐Ÿ˜ก'); } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Emoji\Listener; use Flarum\Event\ConfigureFormatter; use Illuminate\Contracts\Events\Dispatcher; class FormatEmoticons { /** * @param Dispatcher $events */ public function subscribe(Dispatcher $events) { $events->listen(ConfigureFormatter::class, [$this, 'addEmoticons']); } /** * @param ConfigureFormatter $event */ public function addEmoticons(ConfigureFormatter $event) { $event->configurator->Emoji->useEmojiOne(); $event->configurator->Emoji->useSVG(); $event->configurator->Emoji->addAlias(':)', '๐Ÿ™‚'); $event->configurator->Emoji->addAlias(':D', '๐Ÿ˜ƒ'); $event->configurator->Emoji->addAlias(':P', '๐Ÿ˜›'); $event->configurator->Emoji->addAlias(':(', '๐Ÿ™'); $event->configurator->Emoji->addAlias(':|', '๐Ÿ˜'); $event->configurator->Emoji->addAlias(';)', '๐Ÿ˜‰'); $event->configurator->Emoji->addAlias(':\'(', '๐Ÿ˜ข'); $event->configurator->Emoji->addAlias(':O', '๐Ÿ˜ฎ'); $event->configurator->Emoji->addAlias('>:(', '๐Ÿ˜ก'); } }
Use a bit better regex for XML error workaround, actually failable compile
import re import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(success=False, message=err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = re.sub(r"&(\s)", r"&amp;\1", xmlsrc) ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret
import xml.etree.ElementTree as ET from os import path from tmc.exercise_tests.basetest import BaseTest, TestResult class CheckTest(BaseTest): def __init__(self): super().__init__("Check") def applies_to(self, exercise): return path.isfile(path.join(exercise.path(), "Makefile")) def test(self, exercise): _, _, err = self.run(["make", "clean", "all", "run-test"], exercise) ret = [] testpath = path.join(exercise.path(), "test", "tmc_test_results.xml") if not path.isfile(testpath): return [TestResult(False, err)] xmlsrc = "" with open(testpath) as fp: xmlsrc = fp.read() xmlsrc = xmlsrc.replace(r"&", "&amp;") ns = "{http://check.sourceforge.net/ns}" root = ET.fromstring(xmlsrc) for test in root.iter(ns + "test"): success = True name = test.find(ns + "description").text message = None if test.get("result") == "failure": success = False message = test.find(ns + "message").text ret.append(TestResult(success=success, name=name, message=message.replace(r"&amp;", "&"))) return ret
Remove interest group delete button I think we decided sometime that we'd make it not possible to delete groups, so it doens't make any sense having the button here.
// @flow import React, { Component } from 'react'; import GroupForm from 'app/components/GroupForm'; import styles from './InterestGroup.css'; import { Flex, Content } from 'app/components/Layout'; import { Link } from 'react-router'; import Button from 'app/components/Button'; export default class InterestGroupEdit extends Component { props: { interestGroup: Object, initialValues: Object, removeInterestGroup: number => Promise<*>, uploadFile: string => Promise<*>, handleSubmitCallback: Object => Promise<*> }; render() { const { interestGroup, initialValues, removeInterestGroup, uploadFile, handleSubmitCallback } = this.props; return ( <Content> <h2> <Link to={`/interestGroups/${interestGroup.id}`}> <i className="fa fa-angle-left" /> Tilbake </Link> </h2> <Flex justifyContent="space-between" alignItems="baseline"> <div> <h1>Endre gruppe</h1> </div> </Flex> <GroupForm handleSubmitCallback={handleSubmitCallback} group={interestGroup} uploadFile={uploadFile} initialValues={initialValues} /> </Content> ); } }
// @flow import React, { Component } from 'react'; import GroupForm from 'app/components/GroupForm'; import styles from './InterestGroup.css'; import { Flex, Content } from 'app/components/Layout'; import { Link } from 'react-router'; import Button from 'app/components/Button'; export default class InterestGroupEdit extends Component { props: { interestGroup: Object, initialValues: Object, removeInterestGroup: number => Promise<*>, uploadFile: string => Promise<*>, handleSubmitCallback: Object => Promise<*> }; render() { const { interestGroup, initialValues, removeInterestGroup, uploadFile, handleSubmitCallback } = this.props; return ( <Content> <h2> <Link to={`/interestGroups/${interestGroup.id}`}> <i className="fa fa-angle-left" /> Tilbake </Link> </h2> <Flex justifyContent="space-between" alignItems="baseline"> <div> <h1>Endre gruppe</h1> <Button onClick={() => removeInterestGroup(interestGroup.id)} className={styles.deleteButton} > Slett gruppen </Button> </div> </Flex> <GroupForm handleSubmitCallback={handleSubmitCallback} group={interestGroup} uploadFile={uploadFile} initialValues={initialValues} /> </Content> ); } }
Send json to semanticizer stdin
import json import subprocess class Semanticizer: ''' Wrapper for semanticizest go implementation. ''' def __init__(self, model='nl.go.model', stPath='./bin/semanticizest'): ''' Create an instance of Semanticizer. Arguments: model -- Language model created by semanticizest-dumpparser stPath -- Path to semanticizest go implementation. ''' args = [stPath, model] self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) def all_candidates(self, sentence): ''' Given a sentence, generate a list of candidate entity links. Returns a list of candidate entity links, where each candidate entity is represented by a dictionary containing: - target -- Title of the target link - offset -- Offset of the anchor on the original sentence - length -- Length of the anchor on the original sentence - commonness -- commonness of the link - senseprob -- probability of the link - linkcount - ngramcount ''' self.proc.stdin.write(json.dumps(sentence) + '\n\n') stdoutdata = self.proc.stdout.readline() return self._responseGenerator(stdoutdata) def _responseGenerator(self, data): # Should be a generator instead of returning an array ? dataJson = json.loads(data) return dataJson if dataJson is not None else [] def __del__(self): # Will eventually get called self.proc.terminate() def __exit__(self): self.__del__()
import json import subprocess class Semanticizer: ''' Wrapper for semanticizest go implementation. ''' def __init__(self, model='nl.go.model', stPath='./bin/semanticizest'): ''' Create an instance of Semanticizer. Arguments: model -- Language model created by semanticizest-dumpparser stPath -- Path to semanticizest go implementation. ''' args = [stPath, model] self.proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) def all_candidates(self, sentence): ''' Given a sentence, generate a list of candidate entity links. Returns a list of candidate entity links, where each candidate entity is represented by a dictionary containing: - target -- Title of the target link - offset -- Offset of the anchor on the original sentence - length -- Length of the anchor on the original sentence - commonness -- commonness of the link - senseprob -- probability of the link - linkcount - ngramcount ''' self.proc.stdin.write(sentence + '\n\n') stdoutdata = self.proc.stdout.readline() return self._responseGenerator(stdoutdata) def _responseGenerator(self, data): # Should be a generator instead of returning an array ? dataJson = json.loads(data) return dataJson if dataJson is not None else [] def __del__(self): # Will eventually get called self.proc.terminate() def __exit__(self): self.__del__()
Check if not already started before starting updates
'use strict'; var postal = require('postal'); var raf = require('raf'); var FluzoStore = require('fluzo-store')(postal); var fluzo_channel = postal.channel('fluzo'); var render_pending = false; var render_suscriptions = []; var updating = false; var Fluzo = { Store: FluzoStore, action: FluzoStore.action, clearRenderRequests: function () { render_pending = false; }, requestRender: function () { render_pending = true; }, onRender: function (cb) { render_suscriptions.push(cb); var index = render_suscriptions.length - 1; return function () { render_suscriptions.splice(index, 1); }; }, renderIfRequested: function (delta) { if (render_pending) { var now = Date.now(); render_suscriptions.forEach(function (cb) { cb(now, delta); }); this.clearRenderRequests(); } }, startUpdating: function () { if (!updating) { updating = true; (function tick(delta) { if (updating) { raf(tick); } Fluzo.renderIfRequested(delta); })(0); } }, stopUpdating: function () { updating = false; } }; fluzo_channel.subscribe('store.changed.*', Fluzo.requestRender); module.exports = Fluzo;
'use strict'; var postal = require('postal'); var raf = require('raf'); var FluzoStore = require('fluzo-store')(postal); var fluzo_channel = postal.channel('fluzo'); var render_pending = false; var render_suscriptions = []; var updating = false; var Fluzo = { Store: FluzoStore, action: FluzoStore.action, clearRenderRequests: function () { render_pending = false; }, requestRender: function () { render_pending = true; }, onRender: function (cb) { render_suscriptions.push(cb); var index = render_suscriptions.length - 1; return function () { render_suscriptions.splice(index, 1); }; }, renderIfRequested: function (delta) { if (render_pending) { var now = Date.now(); render_suscriptions.forEach(function (cb) { cb(now, delta); }); this.clearRenderRequests(); } }, startUpdating: function () { updating = true; (function tick(delta) { if (updating) { raf(tick); } Fluzo.renderIfRequested(delta); })(0); }, stopUpdating: function () { updating = false; } }; fluzo_channel.subscribe('store.changed.*', Fluzo.requestRender); module.exports = Fluzo;
Fix utilities path from helpers to commands
var elixir = require('laravel-elixir'); var gulp = require('gulp'); var imagemin = require('gulp-imagemin'); var pngquant = require('imagemin-pngquant'); var notify = require('gulp-notify'); var _ = require('underscore'); var utilities = require('laravel-elixir/ingredients/commands/utilities'); /* |---------------------------------------------------------------- | ImageMin Processor |---------------------------------------------------------------- | | This task will trigger your images to be processed using | imagemin processor. | | Minify PNG, JPEG, GIF and SVG images | */ elixir.extend('imagemin', function(src, output, options) { var config = this; var baseDir = config.assetsDir + 'img'; src = utilities.buildGulpSrc(src, baseDir, '**/*'); options = _.extend({ progressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] }, options); gulp.task('imagemin', function() { return gulp.src(src) .pipe(imagemin(options)) .pipe(gulp.dest(output || 'public/img')) .pipe(notify({ title: 'ImageMin Complete!', message: 'All images have be optimised.', icon: __dirname + '/../laravel-elixir/icons/pass.png' })); }); this.registerWatcher('imagemin', [ baseDir + '/**/*.png', baseDir + '/**/*.gif', baseDir + '/**/*.svg', baseDir + '/**/*.jpg', baseDir + '/**/*.jpeg' ]); return this.queueTask('imagemin'); });
var elixir = require('laravel-elixir'); var gulp = require('gulp'); var imagemin = require('gulp-imagemin'); var pngquant = require('imagemin-pngquant'); var notify = require('gulp-notify'); var _ = require('underscore'); var utilities = require('laravel-elixir/ingredients/helpers/utilities'); /* |---------------------------------------------------------------- | ImageMin Processor |---------------------------------------------------------------- | | This task will trigger your images to be processed using | imagemin processor. | | Minify PNG, JPEG, GIF and SVG images | */ elixir.extend('imagemin', function(src, output, options) { var config = this; var baseDir = config.assetsDir + 'img'; src = utilities.buildGulpSrc(src, baseDir, '**/*'); options = _.extend({ progressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] }, options); gulp.task('imagemin', function() { return gulp.src(src) .pipe(imagemin(options)) .pipe(gulp.dest(output || 'public/img')) .pipe(notify({ title: 'ImageMin Complete!', message: 'All images have be optimised.', icon: __dirname + '/../laravel-elixir/icons/pass.png' })); }); this.registerWatcher('imagemin', [ baseDir + '/**/*.png', baseDir + '/**/*.gif', baseDir + '/**/*.svg', baseDir + '/**/*.jpg', baseDir + '/**/*.jpeg' ]); return this.queueTask('imagemin'); });
Fix default branch selection in post-commit UI. The refactoring and improvements I did to `RB.CollectionView` broke the selection of the default branch in the post-commit section of the New Review Request UI. This wasn't super critical, except in the case where there's only a single branch, in which case the commits would never be listed. I've updated the function naming to match the new name in CollectionView. Testing done: Loaded a repository in the New Review Request UI and saw the list of commits on the default branch without having to click anything. Reviewed at https://reviews.reviewboard.org/r/8032/
/* * A view for a collection of branches. * * This is presented as a <select> in the document. * * Users can listen to the "selected" event to know which branch is currently * chosen. This event will be triggered with the branch model as its argument. */ RB.BranchesView = RB.CollectionView.extend({ tagName: 'select', itemViewType: RB.BranchView, events: { 'change': '_onChange' }, /* * Render the view. */ render: function() { _super(this).render.apply(this, arguments); this.collection.each(function(branch) { if (branch.get('isDefault')) { this.trigger('selected', branch); } }, this); return this; }, /* * Override for CollectionView._onAdded. * * If the newly-added branch is the default (for example, 'trunk' in SVN or * 'master' in git), start with it selected. */ _onAdded: function(branch) { _super(this)._onAdded.apply(this, arguments); if (this._rendered && branch.get('isDefault')) { this.trigger('selected', branch); } }, /* * Callback for the 'change' event on the select node. * * Triggers 'selected' with the given model. */ _onChange: function() { var selectedIx = this.$el.prop('selectedIndex'); this.trigger('selected', this.collection.models[selectedIx]); } });
/* * A view for a collection of branches. * * This is presented as a <select> in the document. * * Users can listen to the "selected" event to know which branch is currently * chosen. This event will be triggered with the branch model as its argument. */ RB.BranchesView = RB.CollectionView.extend({ tagName: 'select', itemViewType: RB.BranchView, events: { 'change': '_onChange' }, /* * Render the view. */ render: function() { _super(this).render.apply(this, arguments); this.collection.each(function(branch) { if (branch.get('isDefault')) { this.trigger('selected', branch); } }, this); return this; }, /* * Override for CollectionView._add. * * If the newly-added branch is the default (for example, 'trunk' in SVN or * 'master' in git), start with it selected. */ _add: function(branch) { _super(this)._add.apply(this, arguments); if (this._rendered && branch.get('isDefault')) { this.trigger('selected', branch); } }, /* * Callback for the 'change' event on the select node. * * Triggers 'selected' with the given model. */ _onChange: function() { var selectedIx = this.$el.prop('selectedIndex'); this.trigger('selected', this.collection.models[selectedIx]); } });
Make logged in user endpoint available w/o token
from rest_framework import serializers, views, permissions, response from .models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'private') def to_representation(self, obj): default = super(UserSerializer, self).to_representation(obj) if obj.is_superuser: default['is_superuser'] = True if obj.is_staff: default['is_staff'] = True return default class UserDetailSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = UserSerializer.Meta.fields + ('first_name', 'last_name',) class UserEmailSerializer(UserSerializer): class Meta: model = User fields = UserDetailSerializer.Meta.fields + ('email',) class UserFullSerializer(UserSerializer): class Meta: model = User fields = UserEmailSerializer.Meta.fields + ('address',) class ProfileView(views.APIView): permission_classes = [permissions.IsAuthenticated] def has_permission(self, request, view): token = request.auth if token and not token.is_valid(['read:user']): return False return super(ProfileView, self).has_permission( request, view ) def get(self, request, format=None): token = request.auth user = request.user if token: if token.is_valid(['read:email']): serializer = UserEmailSerializer(user) elif token.is_valid(['read:profile']): serializer = UserDetailSerializer(user) else: serializer = UserSerializer(user) else: # if token is None, user is currently logged in user serializer = UserFullSerializer(user) return response.Response(serializer.data)
from rest_framework import serializers, views, permissions, response from oauth2_provider.contrib.rest_framework import TokenHasScope from .models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id',) def to_representation(self, obj): default = super(UserSerializer, self).to_representation(obj) if obj.is_superuser: default['is_superuser'] = True if obj.is_staff: default['is_staff'] = True return default class UserDetailSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = UserSerializer.Meta.fields + ('first_name', 'last_name',) class UserEmailSerializer(UserSerializer): class Meta: model = User fields = UserDetailSerializer.Meta.fields + ('email',) class ProfileView(views.APIView): permission_classes = [permissions.IsAuthenticated, TokenHasScope] required_scopes = ['read:user'] def get(self, request, format=None): token = request.auth user = request.user if token.is_valid(['read:email']): serializer = UserEmailSerializer(user) elif token.is_valid(['read:profile']): serializer = UserDetailSerializer(user) else: serializer = UserSerializer(user) return response.Response(serializer.data)
Fix exceptions in dependency injection configuration
<?php namespace Bundle\DoctrineUserBundle\DependencyInjection; use Symfony\Components\DependencyInjection\Extension\Extension; use Symfony\Components\DependencyInjection\Loader\XmlFileLoader; use Symfony\Components\DependencyInjection\Loader\YamlFileLoader; use Symfony\Components\DependencyInjection\ContainerBuilder; class DoctrineUserExtension extends Extension { public function configLoad(array $config, ContainerBuilder $container) { $loader = new XmlFileLoader($container, __DIR__.'/../Resources/config'); $loader->load('auth.xml'); $loader->load('form.xml'); $loader->load('templating.xml'); if(!isset($config['db_driver'])) { throw new \InvalidArgumentException('You must provide the doctrine_user.db_driver configuration'); } if('orm' === $config['db_driver']) { $loader->load('orm.xml'); } elseif('odm' === $config['db_driver']) { $loader->load('odm.xml'); } else { throw new \InvalidArgumentException(sprintf('The %s driver is not supported', $config['db_driver'])); } } /** * Returns the base path for the XSD files. * * @return string The XSD base path */ public function getXsdValidationBasePath() { return null; } public function getNamespace() { return 'http://www.symfony-project.org/schema/dic/symfony'; } public function getAlias() { return 'doctrine_user'; } }
<?php namespace Bundle\DoctrineUserBundle\DependencyInjection; use Symfony\Components\DependencyInjection\Extension\Extension; use Symfony\Components\DependencyInjection\Loader\XmlFileLoader; use Symfony\Components\DependencyInjection\Loader\YamlFileLoader; use Symfony\Components\DependencyInjection\ContainerBuilder; class DoctrineUserExtension extends Extension { public function configLoad(array $config, ContainerBuilder $container) { $loader = new XmlFileLoader($container, __DIR__.'/../Resources/config'); $loader->load('auth.xml'); $loader->load('form.xml'); $loader->load('templating.xml'); if(!isset($config['db_driver'])) { throw new \InvalidConfigurationException('You must provide the auth.db_driver configuration'); } if('orm' === $config['db_driver']) { $loader->load('orm.xml'); } elseif('odm' === $config['db_driver']) { $loader->load('odm.xml'); } else { throw new \InvalidConfigurationException(sprintf('The %s driver is not supported', $config['db_driver'])); } } /** * Returns the base path for the XSD files. * * @return string The XSD base path */ public function getXsdValidationBasePath() { return null; } public function getNamespace() { return 'http://www.symfony-project.org/schema/dic/symfony'; } public function getAlias() { return 'doctrine_user'; } }
Fix remove core source dependency
import { error } from '../debug'; function camelToDash(str) { return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); } export default function style({ node, expr }, ...propertyNames) { if (!propertyNames.length) { return (list, { type: globalType, oldValue, changelog }) => { switch (globalType) { case 'modify': Object.keys(changelog).forEach((key) => { switch (changelog[key].type) { case 'delete': node.style.removeProperty(camelToDash(key)); break; default: node.style.setProperty(camelToDash(key), list[key]); } }); break; default: if (list) { if (typeof list !== 'object') { error(TypeError, "style: '%evaluate' must be an object: %type", { evaluate: expr.evaluate, type: typeof list }); } Object.keys(list).forEach(key => node.style.setProperty(camelToDash(key), list[key])); } else if (typeof oldValue === 'object' && oldValue !== null) { Object.keys(oldValue).forEach(key => node.style.removeProperty(camelToDash(key))); } } }; } return (value) => { propertyNames.map(camelToDash).forEach(key => node.style.setProperty(key, value)); }; }
import { camelToDash } from '@hybrids/core/src/utils'; import { error } from '../debug'; export default function style({ node, expr }, ...propertyNames) { if (!propertyNames.length) { return (list, { type: globalType, oldValue, changelog }) => { switch (globalType) { case 'modify': Object.keys(changelog).forEach((key) => { switch (changelog[key].type) { case 'delete': node.style.removeProperty(camelToDash(key)); break; default: node.style.setProperty(camelToDash(key), list[key]); } }); break; default: if (list) { if (typeof list !== 'object') { error(TypeError, "style: '%evaluate' must be an object: %type", { evaluate: expr.evaluate, type: typeof list }); } Object.keys(list).forEach(key => node.style.setProperty(camelToDash(key), list[key])); } else if (typeof oldValue === 'object' && oldValue !== null) { Object.keys(oldValue).forEach(key => node.style.removeProperty(camelToDash(key))); } } }; } return (value) => { propertyNames.map(camelToDash).forEach(key => node.style.setProperty(key, value)); }; }
Return Count Check compilable UT input
package com.puppycrawl.tools.checkstyle.coding; /* ะบะพะผะผะตะฝั‚ะฐั€ะธะน ะฝะฐ ั€ัƒััะบะพะผ */ public class InputReturnCount { public boolean equals(Object obj) { int i = 1; switch (i) { case 1: return true; case 2: return true; case 3: return true; case 4: return true; case 5: return true; case 6: return true; } return false; } void foo(int i) { switch (i) { case 1: return; case 2: return; case 3: return; case 4: return; case 5: return; case 6: return; } return; } void foo1(int i) { if (i == 1) { return; } Object obj = new Object() { void method1(int i) { switch (i) { case 1: return; case 2: return; case 3: return; case 4: return; case 5: return; } return; } }; return; } } class Test { public Test() {} }
package com.puppycrawl.tools.checkstyle.checks.coding; /* ะบะพะผะผะตะฝั‚ะฐั€ะธะน ะฝะฐ ั€ัƒััะบะพะผ */ public class InputReturnCount { public boolean equals(Object obj) { int i = 1; switch (i) { case 1: return true; case 2: return true; case 3: return true; case 4: return true; case 5: return true; case 6: return true; } return false; } void foo(int i) { switch (i) { case 1: return; case 2: return; case 3: return; case 4: return; case 5: return; case 6: return; } return; } void foo1(int i) { if (i == 1) { return; } Object obj = new Object() { void method1(int i) { switch (i) { case 1: return; case 2: return; case 3: return; case 4: return; case 5: return; } return; } }; return; } } class Test { public Test() {} }
Remove banner comment from minified bundled file. Fixes #55
'use strict'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { dist: { files: { 'build/stanzaio.bundle.js': ['<%= pkg.main %>'] }, options: { bundleOptions: { standalone: 'XMPP' } } } }, uglify: { dist: { files: { 'build/stanzaio.bundle.min.js': ['build/stanzaio.bundle.js'] } } }, jshint: { files: [ 'Gruntfile.js', 'index.js', 'lib/**.js', 'lib/stanza/**.js', 'lib/plugins/**.js', 'lib/transports/**.js', 'test/**.js' ], options: grunt.file.readJSON('.jshintrc') }, tape: { options: { pretty: true }, files: ['test/**.js'] } }); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-tape'); grunt.loadNpmTasks('grunt-nsp-package'); grunt.registerTask('default', ['jshint', 'browserify', 'uglify', 'tape', 'validate-package']); };
'use strict'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), browserify: { dist: { files: { 'build/stanzaio.bundle.js': ['<%= pkg.main %>'] }, options: { bundleOptions: { standalone: 'XMPP' } } } }, uglify: { options: { banner: '/*! stanzaio <%= grunt.template.today("yyyy-mm-dd") %>*/' }, dist: { files: { 'build/stanzaio.bundle.min.js': ['build/stanzaio.bundle.js'] } } }, jshint: { files: [ 'Gruntfile.js', 'index.js', 'lib/**.js', 'lib/stanza/**.js', 'lib/plugins/**.js', 'lib/transports/**.js', 'test/**.js' ], options: grunt.file.readJSON('.jshintrc') }, tape: { options: { pretty: true }, files: ['test/**.js'] } }); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-tape'); grunt.loadNpmTasks('grunt-nsp-package'); grunt.registerTask('default', ['jshint', 'browserify', 'uglify', 'tape', 'validate-package']); };
:bug: Fix static css source map
// @flow import path from 'path' import invariant from 'assert' import { createChunkGenerator, getFileKey } from 'pundle-api' import manifest from '../package.json' function createComponent() { return createChunkGenerator({ name: 'pundle-chunk-generator-static', version: manifest.version, async callback({ chunk, job, context }) { if (chunk.format !== 'css' || !chunk.entry) return null const file = job.files.get(getFileKey(chunk)) invariant(file, 'Entry for chunk not found in generator-static') let { contents } = file const output: { contents: string, sourceMap: ?string, format: string, } = { contents: '', sourceMap: null, format: chunk.format, } const publicPath = context.getPublicPath(chunk) const sourceMapUrl = context.getPublicPath({ ...chunk, format: 'css.map' }) if (sourceMapUrl && file.sourceMap) { contents = `${ typeof contents === 'string' ? contents : contents.toString() }\n/*# sourceMappingURL=${path.posix.relative(path.dirname(publicPath), sourceMapUrl)} */` output.sourceMap = { filePath: sourceMapUrl, contents: file.sourceMap, } } output.contents = contents return output }, }) } module.exports = createComponent
// @flow import path from 'path' import invariant from 'assert' import { createChunkGenerator, getFileKey } from 'pundle-api' import manifest from '../package.json' function createComponent() { return createChunkGenerator({ name: 'pundle-chunk-generator-static', version: manifest.version, async callback({ chunk, job, context }) { if (chunk.format !== 'css' || !chunk.entry) return null const file = job.files.get(getFileKey(chunk)) invariant(file, 'Entry for chunk not found in generator-static') let { contents } = file const output: { contents: string, sourceMap: ?string, format: string, } = { contents: '', sourceMap: null, format: chunk.format, } const publicPath = context.getPublicPath(chunk) const sourceMapUrl = context.getPublicPath({ ...chunk, format: 'css.map' }) if (sourceMapUrl && file.sourceMap) { contents = `${ typeof contents === 'string' ? contents : contents.toString() }\n/*# sourceMappingURL=${path.posix.relative(path.dirname(publicPath), sourceMapUrl)} */` output.sourceMap = { filePath: sourceMapUrl, contents: JSON.stringify(file.sourceMap), } } output.contents = contents return output }, }) } module.exports = createComponent
Set local debug to true.
<?php // direct access protection if(!defined('KIRBY')) die('Direct access is not allowed'); /* ----------------------------------------------------------------------------- Troubleshooting -------------------------------------------------------------------------------- */ c::set('troubleshoot', false); /* ----------------------------------------------------------------------------- Debug -------------------------------------------------------------------------------- */ c::set('debug', true); /* ----------------------------------------------------------------------------- Environment -------------------------------------------------------------------------------- */ c::set('environment', 'local'); /* ----------------------------------------------------------------------------- URL -------------------------------------------------------------------------------- */ c::set('url', ''); // To use root relative URLs: c::set('url', '/'); /* ----------------------------------------------------------------------------- Timezone -------------------------------------------------------------------------------- */ c::set('timezone', 'UTC'); /* ----------------------------------------------------------------------------- Cache -------------------------------------------------------------------------------- */ c::set('cache', false); c::set('cache.driver', 'file'); // Valid values: file, memcached or apc /* ----------------------------------------------------------------------------- Thumbs -------------------------------------------------------------------------------- */ c::set('thumbs.driver','im'); // The thumbnail library which is being used by Kirby's thumb function/class ('gd' or 'im') thumb::$defaults['bin'] = '/usr/local/bin/convert'; // Path to the convert bin for 'im' thumb driver setting (see: http://j.mp/1LJ8n9E) /* ----------------------------------------------------------------------------- Lazyload images -------------------------------------------------------------------------------- Use `lazysizes.init()` in main.scripts.js and mobile.scripts.js */ c::set('lazyload', true); // Set to true to lazyload images /* ----------------------------------------------------------------------------- Analytics, tracking, site stats -------------------------------------------------------------------------------- */ c::set('analytics.tool', false);
<?php // direct access protection if(!defined('KIRBY')) die('Direct access is not allowed'); /* ----------------------------------------------------------------------------- Troubleshooting -------------------------------------------------------------------------------- */ c::set('troubleshoot', false); /* ----------------------------------------------------------------------------- Debug -------------------------------------------------------------------------------- */ c::set('debug', false); /* ----------------------------------------------------------------------------- Environment -------------------------------------------------------------------------------- */ c::set('environment', 'local'); /* ----------------------------------------------------------------------------- URL -------------------------------------------------------------------------------- */ c::set('url', ''); // To use root relative URLs: c::set('url', '/'); /* ----------------------------------------------------------------------------- Timezone -------------------------------------------------------------------------------- */ c::set('timezone', 'UTC'); /* ----------------------------------------------------------------------------- Cache -------------------------------------------------------------------------------- */ c::set('cache', false); c::set('cache.driver', 'file'); // Valid values: file, memcached or apc /* ----------------------------------------------------------------------------- Thumbs -------------------------------------------------------------------------------- */ c::set('thumbs.driver','im'); // The thumbnail library which is being used by Kirby's thumb function/class ('gd' or 'im') thumb::$defaults['bin'] = '/usr/local/bin/convert'; // Path to the convert bin for 'im' thumb driver setting (see: http://j.mp/1LJ8n9E) /* ----------------------------------------------------------------------------- Lazyload images -------------------------------------------------------------------------------- Use `lazysizes.init()` in main.scripts.js and mobile.scripts.js */ c::set('lazyload', true); // Set to true to lazyload images /* ----------------------------------------------------------------------------- Analytics, tracking, site stats -------------------------------------------------------------------------------- */ c::set('analytics.tool', false);
[FIX] medical_prescription_sale: Add dependency * Add dependency on stock to manifest file. This is needed by some of the demo data in the module, which was not installing due to its absence.
# -*- coding: utf-8 -*- # ยฉ 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Prescription Sales', 'summary': 'Create Sale Orders from Prescriptions', 'version': '9.0.0.1.0', 'author': "LasLabs, Odoo Community Association (OCA)", 'category': 'Medical', 'depends': [ 'sale', 'stock', 'medical_prescription', 'medical_pharmacy', 'medical_prescription_thread', ], "website": "https://laslabs.com", "license": "AGPL-3", "data": [ 'data/ir_sequence.xml', 'data/product_category_data.xml', 'wizards/medical_sale_wizard_view.xml', 'wizards/medical_sale_temp_view.xml', 'views/prescription_order_line_view.xml', 'views/prescription_order_view.xml', 'views/sale_order_view.xml', 'views/medical_physician_view.xml', 'views/medical_patient_view.xml', ], 'demo': [ 'demo/medical_medicament_demo.xml', 'demo/medical_medication_demo.xml', 'demo/medical_prescription_order_demo.xml', 'demo/medical_prescription_order_line_demo.xml', ], 'installable': True, 'auto_install': False, }
# -*- coding: utf-8 -*- # ยฉ 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Prescription Sales', 'summary': 'Create Sale Orders from Prescriptions', 'version': '9.0.0.1.0', 'author': "LasLabs, Odoo Community Association (OCA)", 'category': 'Medical', 'depends': [ 'sale', 'medical_prescription', 'medical_pharmacy', 'medical_prescription_thread', ], "website": "https://laslabs.com", "license": "AGPL-3", "data": [ 'data/ir_sequence.xml', 'data/product_category_data.xml', 'wizards/medical_sale_wizard_view.xml', 'wizards/medical_sale_temp_view.xml', 'views/prescription_order_line_view.xml', 'views/prescription_order_view.xml', 'views/sale_order_view.xml', 'views/medical_physician_view.xml', 'views/medical_patient_view.xml', ], 'demo': [ 'demo/medical_medicament_demo.xml', 'demo/medical_medication_demo.xml', 'demo/medical_prescription_order_demo.xml', 'demo/medical_prescription_order_line_demo.xml', ], 'installable': True, 'auto_install': False, }
Adjust root url setting for production build
/* eslint-env node */ var pkg = require('../package.json'); module.exports = function (environment) { var rootURL = environment === 'production' ? '' : '/'; var ENV = { modulePrefix: 'purecloud-skype', environment: environment, rootURL: rootURL, locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { version: pkg.version, buildNumber: process.env.BUILD_NUMBER || 'BUILDNUM' } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; ENV.APP.autoboot = false; } if (environment === 'production') { ENV.IS_LOCAL = false; } return ENV; };
/* eslint-env node */ var pkg = require('../package.json'); module.exports = function (environment) { var rootURL = '/'; var ENV = { modulePrefix: 'purecloud-skype', environment: environment, rootURL: rootURL, locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { version: pkg.version, buildNumber: process.env.BUILD_NUMBER || 'BUILDNUM' } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; ENV.APP.autoboot = false; } if (environment === 'production') { ENV.IS_LOCAL = false; } return ENV; };
Update gulp paths to scan recusrively
var gulp = require('gulp'); var phpunit = require('gulp-phpunit'); var phplint = require('gulp-phplint'); var watch = require('gulp-watch'); var notifier = require('node-notifier'); var debug = require('gulp-debug'); var map = ['src/**/*.php', 'tests/**/*.php']; gulp.task('dev', function(cb) { var options = { debug: true, statusLine: true, configurationFile: './build/phpunit.xml' }; watch(map, function() { gulp .src(map) .pipe(phplint('')) .pipe(phplint.reporter(function (file) { var report = file.phplintReport || {}; if (report.error) { /*notifier.notify({ 'title': 'PhpLint', 'Message': 'Lint failed' });*/ } })) .pipe(phpunit('./vendor/bin/phpunit', options)) .on('end', cb); }) });
var gulp = require('gulp'); var phpunit = require('gulp-phpunit'); var phplint = require('gulp-phplint'); var watch = require('gulp-watch'); var notifier = require('node-notifier'); var debug = require('gulp-debug'); var map = ['src/*.php', 'tests/*.php']; gulp.task('dev', function(cb) { var options = { debug: true, statusLine: true, configurationFile: './build/phpunit.xml' }; watch(map, function() { gulp .src(map) .pipe(phplint('')) .pipe(phplint.reporter(function (file) { var report = file.phplintReport || {}; if (report.error) { /*notifier.notify({ 'title': 'PhpLint', 'Message': 'Lint failed' });*/ } })) .pipe(phpunit('./vendor/bin/phpunit', options)) .on('end', cb); }) });
Fix transpilation error to support React Native Recent versions of Babel will throw a TransformError in certain runtimes if any property on `Symbol` is assigned a value. This fixes the issue, which is the last remaining issue for React Native support.
var objectTypes = { "boolean": false, "function": true, "object": true, "number": false, "string": false, "undefined": false }; /*eslint-disable */ var _root = (objectTypes[typeof self] && self) || (objectTypes[typeof window] && window); var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { _root = freeGlobal; } /*eslint-enable */ var _id = 0; function ensureSymbol(root) { if (!root.Symbol) { root.Symbol = function symbolFuncPolyfill(description) { return "@@Symbol(" + description + "):" + (_id++) + "}"; }; } return root.Symbol; } function ensureObservable(Symbol) { /* eslint-disable dot-notation */ if (!Symbol.observable) { if (typeof Symbol.for === "function") { Symbol["observable"] = Symbol.for("observable"); } else { Symbol["observable"] = "@@observable"; } } /* eslint-disable dot-notation */ } function symbolForPolyfill(key) { return "@@" + key; } function ensureFor(Symbol) { /* eslint-disable dot-notation */ if (!Symbol.for) { Symbol["for"] = symbolForPolyfill; } /* eslint-enable dot-notation */ } function polyfillSymbol(root) { var Symbol = ensureSymbol(root); ensureObservable(Symbol); ensureFor(Symbol); return Symbol; } module.exports = polyfillSymbol(_root);
var objectTypes = { "boolean": false, "function": true, "object": true, "number": false, "string": false, "undefined": false }; /*eslint-disable */ var _root = (objectTypes[typeof self] && self) || (objectTypes[typeof window] && window); var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { _root = freeGlobal; } /*eslint-enable */ var _id = 0; function ensureSymbol(root) { if (!root.Symbol) { root.Symbol = function symbolFuncPolyfill(description) { return "@@Symbol(" + description + "):" + (_id++) + "}"; }; } return root.Symbol; } function ensureObservable(Symbol) { if (!Symbol.observable) { if (typeof Symbol.for === "function") { Symbol.observable = Symbol.for("observable"); } else { Symbol.observable = "@@observable"; } } } function symbolForPolyfill(key) { return "@@" + key; } function ensureFor(Symbol) { if (!Symbol.for) { Symbol.for = symbolForPolyfill; } } function polyfillSymbol(root) { var Symbol = ensureSymbol(root); ensureObservable(Symbol); ensureFor(Symbol); return Symbol; } module.exports = polyfillSymbol(_root);
Return new AppUtil instance from init call
module.exports = { init: init }; var util = require("util"); var FrameInputStream = require("./frame_input_stream"); function AppUtil(argv){ this.argv = argv; } function init(argv){ return new AppUtil(argv); } AppUtil.prototype.log = function(message){ if(this.argv.verbose){ util.print(message + "\n"); } }; AppUtil.prototype.fatalError = function(message){ process.stderr.write(message + "\n"); process.exit(1); }; AppUtil.prototype.fatalErrorEvent = function(format){ var self = this; return function(error){ self.fatalError(util.format(format, error.message)); }; }; AppUtil.prototype.parseHeaderLines = function(){ var headers = {}; var headerPattern = /([^:]+):(.*)/; for(var i = 0; i < arguments.length; i++){ var arg = arguments[i]; if(!(arg instanceof Array)){ arg = [arg]; } for(var j = 0; j < arg.length; j++){ var lines = ("" + arg[j]).split("\n"); for(var k = 0; k < lines.length; k++){ var line = lines[k]; var match = line.match(headerPattern); if(match){ headers[match[1]] = FrameInputStream.prototype.decodeHeaderValue(match[2]); } } } } return headers; };
module.exports = new AppUtil(); var util = require("util"); var FrameInputStream = require("./frame_input_stream"); function AppUtil(){ } AppUtil.prototype.init = function(argv){ this.argv = argv; return this; }; AppUtil.prototype.log = function(message){ if(this.argv.verbose){ util.print(message + "\n"); } }; AppUtil.prototype.fatalError = function(message){ process.stderr.write(message + "\n"); process.exit(1); }; AppUtil.prototype.fatalErrorEvent = function(format){ var self = this; return function(error){ self.fatalError(util.format(format, error.message)); }; }; AppUtil.prototype.parseHeaderLines = function(){ var headers = {}; var headerPattern = /([^:]+):(.*)/; for(var i = 0; i < arguments.length; i++){ var arg = arguments[i]; if(!(arg instanceof Array)){ arg = [arg]; } for(var j = 0; j < arg.length; j++){ var lines = ("" + arg[j]).split("\n"); for(var k = 0; k < lines.length; k++){ var line = lines[k]; var match = line.match(headerPattern); if(match){ headers[match[1]] = FrameInputStream.prototype.decodeHeaderValue(match[2]); } } } } return headers; };
Allow integer-only session name and hash for the example
#!/usr/bin/env python3 import traceback from telethon.interactive_telegram_client import (InteractiveTelegramClient, print_title) def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file: value_pair = line.split('=') left = value_pair[0].strip() right = value_pair[1].strip() if right.isnumeric(): result[left] = int(right) else: result[left] = right return result if __name__ == '__main__': # Load the settings and initialize the client settings = load_settings() client = InteractiveTelegramClient( session_user_id=str(settings.get('session_name', 'anonymous')), user_phone=str(settings['user_phone']), api_id=settings['api_id'], api_hash=str(settings['api_hash'])) print('Initialization done!') try: client.run() except Exception as e: print('Unexpected error ({}): {} at\n{}'.format( type(e), e, traceback.format_exc())) finally: print_title('Exit') print('Thanks for trying the interactive example! Exiting...') client.disconnect()
#!/usr/bin/env python3 import traceback from telethon.interactive_telegram_client import (InteractiveTelegramClient, print_title) def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file: value_pair = line.split('=') left = value_pair[0].strip() right = value_pair[1].strip() if right.isnumeric(): result[left] = int(right) else: result[left] = right return result if __name__ == '__main__': # Load the settings and initialize the client settings = load_settings() client = InteractiveTelegramClient( session_user_id=settings.get('session_name', 'anonymous'), user_phone=str(settings['user_phone']), api_id=settings['api_id'], api_hash=settings['api_hash']) print('Initialization done!') try: client.run() except Exception as e: print('Unexpected error ({}): {} at\n{}'.format( type(e), e, traceback.format_exc())) finally: print_title('Exit') print('Thanks for trying the interactive example! Exiting...') client.disconnect()
Allow to set context to null
<?php /* * Mendo Framework * * (c) Mathieu Decaffmeyer <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Mendo\Router; use Mendo\Http\Request\HttpRequestInterface; /** * @author Mathieu Decaffmeyer <[email protected]> */ class UrlMaker implements UrlMakerInterface { private $routers; private $httpRequest; public function __construct(RouterCollection $routers) { $this->routers = $routers; } public function setContext(HttpRequestInterface $httpRequest = null) { $this->httpRequest = $httpRequest; } public function getContext() { return $this->httpRequest; } public function makeUrl(RouteData $routeData, $language = null) { if (!$this->httpRequest) { return $this->routers->get($routeData->getRouteName())->makeUrl($routeData, $language); } if (!$language) { $language = $this->httpRequest->getLanguage(); } $path = $this->routers->get($routeData->getRouteName())->makeUrl($routeData, $language); $httpRequest = clone $this->httpRequest; $httpRequest->setPath($path); $makeAbsoluteUrl = false; if ($language) { $makeAbsoluteUrl = ($httpRequest->getLanguage() !== $language); $httpRequest->setLanguage($language); } return $httpRequest->getUrl($makeAbsoluteUrl); } }
<?php /* * Mendo Framework * * (c) Mathieu Decaffmeyer <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Mendo\Router; use Mendo\Http\Request\HttpRequestInterface; /** * @author Mathieu Decaffmeyer <[email protected]> */ class UrlMaker implements UrlMakerInterface { private $routers; private $httpRequest; public function __construct(RouterCollection $routers) { $this->routers = $routers; } public function setContext(HttpRequestInterface $httpRequest) { $this->httpRequest = $httpRequest; } public function getContext() { return $this->httpRequest; } public function makeUrl(RouteData $routeData, $language = null) { if (!$this->httpRequest) { return $this->routers->get($routeData->getRouteName())->makeUrl($routeData, $language); } if (!$language) { $language = $this->httpRequest->getLanguage(); } $path = $this->routers->get($routeData->getRouteName())->makeUrl($routeData, $language); $httpRequest = clone $this->httpRequest; $httpRequest->setPath($path); $makeAbsoluteUrl = false; if ($language) { $makeAbsoluteUrl = ($httpRequest->getLanguage() !== $language); $httpRequest->setLanguage($language); } return $httpRequest->getUrl($makeAbsoluteUrl); } }
Fix the response from Wit:
'use strict'; const _ = require('lodash'); const Promise = require('bluebird'); const Facebook = require('./facebook'); const sessions = require('./sessions'); const keepr = require('./keepr'); const config = require('../../config'); module.exports = { actions: { send: ({sessionId}, {text}) => { const recipientId = sessions.getSessions()[sessionId].fbid; console.log('Response from Wit: ' + text); if (recipientId) { return Facebook.sendTextMessage(recipientId, text); } else { return Promise.reject('Oops! Couldn\'t find user for session: ' + sessionId); } }, ['fetch_latest_news_by_keyword'](request) { const entities = request.entities; const sessionId = request.sessionId; const context = require.context; const keyword = entities.local_search_query[0].value; console.log('Keyword' + keyword); const recipientId = sessions.getSessions()[sessionId].fbid; if (recipientId) { return keepr.latestNewsByKeyword(keyword).then((response) => { const numbers = response.numbers; const newsWithUrls = _.filter(numbers, (tweet) => { return tweet.urls.length > 0; }); return Facebook.sendTextMessage(recipientId, newsWithUrls.slice(0, 3)).catch((error) => { console.log(error); }); }); } return Promise.reject('Oops! Couldn\'t find user for session: ' + sessionId); }, } };
'use strict'; const _ = require('lodash'); const Promise = require('bluebird'); const Facebook = require('./facebook'); const sessions = require('./sessions'); const keepr = require('./keepr'); const config = require('../../config'); module.exports = { actions: { send: (request, response) => { const sessionId = request.sessionId; const context = request.context; const entities = request.entities; const recipientId = sessions.getSessions()[sessionId].fbid; if (recipientId) { return Facebook.sendTextMessage(recipientId, message); } else { return Promise.reject('Oops! Couldn\'t find user for session: ' + sessionId); } }, ['fetch_latest_news_by_keyword'](request) { const entities = request.entities; const sessionId = request.sessionId; const context = require.context; const keyword = entities.local_search_query[0].value; console.log('Keyword' + keyword); const recipientId = sessions.getSessions()[sessionId].fbid; if (recipientId) { return keepr.latestNewsByKeyword(keyword).then((response) => { const numbers = response.numbers; const newsWithUrls = _.filter(numbers, (tweet) => { return tweet.urls.length > 0; }); return Facebook.sendTextMessage(recipientId, newsWithUrls.slice(0, 3)).catch((error) => { console.log(error); }); }); } return Promise.reject('Oops! Couldn\'t find user for session: ' + sessionId); }, } };
Throw SQLException and ClassNotFoundException from getJdbcConnection method
package database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Connect to SQL Server database using ConnectionCredentials object. */ public class DatabaseConnector { private String connectionUrl = ""; private ConnectionCredentials credentials; /** * Constructor * @param credentials ConnectionCredentials object containing the required configuration to connect to the database server instance. */ public DatabaseConnector(ConnectionCredentials credentials) { this.credentials = credentials; } /** * Get a JDBC connection using ConnectionCredentials object. * @return the JDBC connection */ public Connection getJdbcConnection() throws ClassNotFoundException, SQLException { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection jdbcConnection = DriverManager.getConnection( getConnectionUrl(credentials), credentials.getUsername(), credentials.getPassword() ); return jdbcConnection; } /** * Builds the required connection URL required by DriverManager. * @param credentials ConnectionCredentials object containing the required configuration to connect to the database server instance. * @return the connection URL built from the credentials */ private String getConnectionUrl(ConnectionCredentials credentials) { String serverName = credentials.getServerName(); String databaseName = credentials.getDatabaseName(); connectionUrl = String.format( "jdbc:sqlserver://%s;databaseName=%s;", serverName, databaseName ); return connectionUrl; } }
package database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Connect to SQL Server database using ConnectionCredentials object. */ public class DatabaseConnector { private String connectionUrl = ""; private ConnectionCredentials credentials; /** * Constructor * @param credentials ConnectionCredentials object containing the required configuration to connect to the database server instance. */ public DatabaseConnector(ConnectionCredentials credentials) { this.credentials = credentials; } /** * Get a JDBC connection using ConnectionCredentials object. * @return the JDBC connection */ public Connection getJdbcConnection() throws ClassNotFoundException, SQLException { Connection jdbcConnection; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); jdbcConnection = DriverManager.getConnection( getConnectionUrl(credentials), credentials.getUsername(), credentials.getPassword() ); } catch(Exception exc) { exc.printStackTrace(); throw (exc); } return jdbcConnection; } /** * Builds the required connection URL required by DriverManager. * @param credentials ConnectionCredentials object containing the required configuration to connect to the database server instance. * @return the connection URL built from the credentials */ private String getConnectionUrl(ConnectionCredentials credentials) { String serverName = credentials.getServerName(); String databaseName = credentials.getDatabaseName(); connectionUrl = String.format( "jdbc:sqlserver://%s;databaseName=%s;", serverName, databaseName ); return connectionUrl; } }
Add the import for CommandError
# This script deactivates a particular generation from optparse import make_option from django.core.management.base import BaseCommand, CommandError from mapit.models import Generation class Command(BaseCommand): help = 'Deactivate a generation' args = '<GENERATION-ID>' option_list = BaseCommand.option_list + ( make_option('--commit', action='store_true', dest='commit', help='Actually update the database'), make_option('--force', action='store_true', dest='force', help='Force deactivation, even if it would leave no active generations')) def handle(self, generation_id, **options): generation_to_deactivate = Generation.objects.get(id=int(generation_id, 10)) if not generation_to_deactivate.active: raise CommandError, "The generation %s wasn't active" % (generation_id,) active_generations = Generation.objects.filter(active=True).count() if active_generations <= 1 and not options['force']: raise CommandError, "You're trying to deactivate the only active generation. If this is what you intended, please re-run the command with --force" generation_to_deactivate.active = False if options['commit']: generation_to_deactivate.save() print "%s - deactivated" % generation_to_deactivate else: print "%s - not deactivated, dry run" % generation_to_deactivate
# This script deactivates a particular generation from optparse import make_option from django.core.management.base import BaseCommand from mapit.models import Generation class Command(BaseCommand): help = 'Deactivate a generation' args = '<GENERATION-ID>' option_list = BaseCommand.option_list + ( make_option('--commit', action='store_true', dest='commit', help='Actually update the database'), make_option('--force', action='store_true', dest='force', help='Force deactivation, even if it would leave no active generations')) def handle(self, generation_id, **options): generation_to_deactivate = Generation.objects.get(id=int(generation_id, 10)) if not generation_to_deactivate.active: raise CommandError, "The generation %s wasn't active" % (generation_id,) active_generations = Generation.objects.filter(active=True).count() if active_generations <= 1 and not options['force']: raise CommandError, "You're trying to deactivate the only active generation. If this is what you intended, please re-run the command with --force" generation_to_deactivate.active = False if options['commit']: generation_to_deactivate.save() print "%s - deactivated" % generation_to_deactivate else: print "%s - not deactivated, dry run" % generation_to_deactivate
Copy doc to index.html to fix the project page.
/*jshint node: true, camelcase: false */ 'use strict'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { files: [ 'Gruntfile.js', 'jquery.iframe-transport.js' ], options: { jshintrc: '.jshintrc' } }, uglify: { options: { banner: '/*! <%= pkg.name %> v<%= pkg.version %> | <%= pkg.license %> */\n' }, build: { files: { 'build/jquery.iframe-transport-<%= pkg.version %>.min.js': 'jquery.iframe-transport.js' } } }, docco: { debug: { src: ['jquery.iframe-transport.js'], options: { output: 'docs/' } } }, copy: { doc: { src: 'docs/jquery.iframe-transport.html', dest: 'docs/index.html', nonull: true } }, 'gh-pages': { options: { base: 'docs' }, src: ['**'] } }); // Loading dependencies for (var key in grunt.file.readJSON('package.json').devDependencies) { if (key !== 'grunt' && key.indexOf('grunt') === 0) { grunt.loadNpmTasks(key); } } grunt.registerTask('default', ['jshint', 'uglify']); grunt.registerTask('doc', ['docco', 'copy:doc', 'gh-pages']); };
/*jshint node: true, camelcase: false */ 'use strict'; module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { files: [ 'Gruntfile.js', 'jquery.iframe-transport.js' ], options: { jshintrc: '.jshintrc' } }, uglify: { options: { banner: '/*! <%= pkg.name %> v<%= pkg.version %> | <%= pkg.license %> */\n' }, build: { files: { 'build/jquery.iframe-transport-<%= pkg.version %>.min.js': 'jquery.iframe-transport.js' } } }, docco: { debug: { src: ['jquery.iframe-transport.js'], options: { output: 'docs/' } } }, 'gh-pages': { options: { base: 'docs' }, src: ['**'] } }); // Loading dependencies for (var key in grunt.file.readJSON('package.json').devDependencies) { if (key !== 'grunt' && key.indexOf('grunt') === 0) { grunt.loadNpmTasks(key); } } grunt.registerTask('default', ['jshint', 'uglify']); grunt.registerTask('doc', ['docco', 'gh-pages']); };
Fix weird "0" notification numbers Summary: The JsShrink change swapped an "== 0" for "=== 0" in JS, but we're currently sending a string down. Fixes T3230. Test Plan: I'm not 100% sure this actually fixes it but probably? Let me know if you still see it. Reviewers: chad, btrahan Reviewed By: chad CC: aran Maniphest Tasks: T3230 Differential Revision: https://secure.phabricator.com/D5997
<?php final class PhabricatorNotificationPanelController extends PhabricatorNotificationController { public function processRequest() { $request = $this->getRequest(); $user = $request->getUser(); $query = new PhabricatorNotificationQuery(); $query->setViewer($user); $query->setUserPHID($user->getPHID()); $query->setLimit(15); $stories = $query->execute(); if ($stories) { $builder = new PhabricatorNotificationBuilder($stories); $notifications_view = $builder->buildView(); $content = $notifications_view->render(); } else { $content = hsprintf( '<div class="phabricator-notification no-notifications">%s</div>', pht('You have no notifications.')); } $content = hsprintf( '<div class="phabricator-notification-header">%s</div>'. '%s'. '<div class="phabricator-notification-view-all">%s</div>', pht('Notifications'), $content, phutil_tag( 'a', array( 'href' => '/notification/', ), 'View All Notifications')); $unread_count = id(new PhabricatorFeedStoryNotification()) ->countUnread($user); $json = array( 'content' => $content, 'number' => (int)$unread_count, ); return id(new AphrontAjaxResponse())->setContent($json); } }
<?php final class PhabricatorNotificationPanelController extends PhabricatorNotificationController { public function processRequest() { $request = $this->getRequest(); $user = $request->getUser(); $query = new PhabricatorNotificationQuery(); $query->setViewer($user); $query->setUserPHID($user->getPHID()); $query->setLimit(15); $stories = $query->execute(); if ($stories) { $builder = new PhabricatorNotificationBuilder($stories); $notifications_view = $builder->buildView(); $content = $notifications_view->render(); } else { $content = hsprintf( '<div class="phabricator-notification no-notifications">%s</div>', pht('You have no notifications.')); } $content = hsprintf( '<div class="phabricator-notification-header">%s</div>'. '%s'. '<div class="phabricator-notification-view-all">%s</div>', pht('Notifications'), $content, phutil_tag( 'a', array( 'href' => '/notification/', ), 'View All Notifications')); $unread_count = id(new PhabricatorFeedStoryNotification()) ->countUnread($user); $json = array( 'content' => $content, 'number' => $unread_count, ); return id(new AphrontAjaxResponse())->setContent($json); } }
Move template functions out of `Config.load()`
import os import yaml from subprocess import check_output, CalledProcessError from colors import red from jinja2 import Template class Config(): @staticmethod def env(key): """Return the value of the `key` environment variable.""" try: return os.environ[key] except KeyError: print(red('[ERROR] No environment variable with key {}'.format(key))) exit(1) @staticmethod def git_commit(): """Return the SHA1 of the latest Git commit (HEAD).""" try: return check_output(['git', 'rev-parse', '--short', 'HEAD']).strip() except CalledProcessError: print(red('[ERROR] Current directory is not a Git repository')) exit(1) @staticmethod def git_branch(): """Return the name of the current Git branch.""" try: return check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip() except CalledProcessError: print(red('[ERROR] Current directory is not a Git repository')) exit(1) @staticmethod def load(config_file='brume.yml'): """ Return the YAML configuration for a project based on the `config_file` template. By default, the template exposes the `env` function. The `git_branch` and `git_commit` values are exposed only when a `.git` folder exists in the current directory """ template_functions = {} template_functions['env'] = Config.env if os.path.isdir('.git'): template_functions['git_commit'] = Config.git_commit() template_functions['git_branch'] = Config.git_branch() template = Template(open(config_file, 'r').read()) return yaml.load( template.render(**template_functions) )
import os import yaml from subprocess import check_output, CalledProcessError from colors import red from jinja2 import Template class Config(): @staticmethod def load(config_file='brume.yml'): """Return the YAML configuration for a project based on the `config_file` template.""" template_functions = {} def env(key): """Return the value of the `key` environment variable.""" try: return os.environ[key] except KeyError: print(red('[ERROR] No environment variable with key {}'.format(key))) exit(1) template_functions['env'] = env if os.path.isdir('.git'): def git_commit(): """Return the SHA1 of the latest Git commit (HEAD).""" try: return check_output(['git', 'rev-parse', '--short', 'HEAD']).strip() except CalledProcessError: print(red('[ERROR] Current directory is not a Git repository')) exit(1) def git_branch(): """Return the name of the current Git branch.""" try: return check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip() except CalledProcessError: print(red('[ERROR] Current directory is not a Git repository')) exit(1) template_functions['git_commit'] = git_commit() template_functions['git_branch'] = git_branch() template = Template(open(config_file, 'r').read()) return yaml.load( template.render(**template_functions) )
BAP-10771: Migrate data audit command to be executed in new message queue. Sort entities in data audit grid filter alphabetically
<?php namespace Oro\Bundle\DataAuditBundle\Datagrid; use Oro\Bundle\DataAuditBundle\Provider\AuditConfigProvider; use Oro\Bundle\DataGridBundle\Datasource\ResultRecord; use Oro\Bundle\EntityBundle\Provider\EntityClassNameProviderInterface; class EntityTypeProvider { /** @var EntityClassNameProviderInterface */ protected $entityClassNameProvider; /** @var AuditConfigProvider */ protected $configProvider; /** * @param EntityClassNameProviderInterface $entityClassNameProvider * @param AuditConfigProvider $configProvider */ public function __construct( EntityClassNameProviderInterface $entityClassNameProvider, AuditConfigProvider $configProvider ) { $this->entityClassNameProvider = $entityClassNameProvider; $this->configProvider = $configProvider; } /** * @param string $gridName * @param string $keyName * @param array $node * * @return callable */ public function getEntityType($gridName, $keyName, $node) { return function (ResultRecord $record) { return $this->entityClassNameProvider->getEntityClassName( $record->getValue('objectClass') ); }; } /** * @return array [entity class => entity type, ...] */ public function getEntityTypes() { $result = []; $classNames = $this->configProvider->getAllAuditableEntities(); foreach ($classNames as $className) { $result[$className] = $this->entityClassNameProvider->getEntityClassName($className); } asort($result, SORT_STRING | SORT_FLAG_CASE); return $result; } }
<?php namespace Oro\Bundle\DataAuditBundle\Datagrid; use Oro\Bundle\DataAuditBundle\Provider\AuditConfigProvider; use Oro\Bundle\DataGridBundle\Datasource\ResultRecord; use Oro\Bundle\EntityBundle\Provider\EntityClassNameProviderInterface; class EntityTypeProvider { /** @var EntityClassNameProviderInterface */ protected $entityClassNameProvider; /** @var AuditConfigProvider */ protected $configProvider; /** * @param EntityClassNameProviderInterface $entityClassNameProvider * @param AuditConfigProvider $configProvider */ public function __construct( EntityClassNameProviderInterface $entityClassNameProvider, AuditConfigProvider $configProvider ) { $this->entityClassNameProvider = $entityClassNameProvider; $this->configProvider = $configProvider; } /** * @param string $gridName * @param string $keyName * @param array $node * * @return callable */ public function getEntityType($gridName, $keyName, $node) { return function (ResultRecord $record) { return $this->entityClassNameProvider->getEntityClassName( $record->getValue('objectClass') ); }; } /** * @return array [entity class => entity type, ...] */ public function getEntityTypes() { $result = []; $classNames = $this->configProvider->getAllAuditableEntities(); foreach ($classNames as $className) { $result[$className] = $this->entityClassNameProvider->getEntityClassName($className); } return $result; } }
Fix rootURL issue with docs
'use strict'; module.exports = function(environment) { const ENV = { modulePrefix: 'dummy', environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. EMBER_NATIVE_DECORATOR_SUPPORT: true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; ENV.APP.autoboot = false; } if (environment === 'production') { // Allow ember-cli-addon-docs to update the rootURL in compiled assets ENV.rootURL = 'ADDON_DOCS_ROOT_URL'; } return ENV; };
'use strict'; module.exports = function(environment) { const ENV = { modulePrefix: 'dummy', environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. EMBER_NATIVE_DECORATOR_SUPPORT: true }, EXTEND_PROTOTYPES: { // Prevent Ember Data from overriding Date.parse. Date: false } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; ENV.APP.autoboot = false; } if (environment === 'production') { // Allow ember-cli-addon-docs to update the rootURL in compiled assets ENV.rootURL = 'ADDON_DOCS_ROOT_URL'; ENV.locationType = 'hash'; ENV.rootURL = '/ember-shepherd/'; } return ENV; };
Update lazy helper to support the idea of a reset on bad state.
# Lazy objects, for the serializer to find them we put them here class LazyDriver(object): _driver = None @classmethod def get(cls): import os if cls._driver is None: from pyvirtualdisplay import Display cls._display = display display = Display(visible=0, size=(1024, 768)) display.start() from selenium import webdriver # Configure headless mode chrome_options = webdriver.ChromeOptions() #Oops chrome_options.add_argument('--verbose') chrome_options.add_argument('--ignore-certificate-errors') log_path = "/tmp/chromelogpanda{0}".format(os.getpid()) if not os.path.exists(log_path): os.mkdir(log_path) chrome_options.add_argument("--log-path {0}/log.txt".format(log_path)) chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-setuid-sandbox") cls._driver = webdriver.Chrome(chrome_options=chrome_options) return cls._driver @classmethod def reset(cls): cls._display.stop() cls._driver.Dispose() class LazyPool(object): _pool = None @classmethod def get(cls): if cls._pool is None: import urllib3 cls._pool = urllib3.PoolManager() return cls._pool
# Lazy objects, for the serializer to find them we put them here class LazyDriver(object): _driver = None @classmethod def get(cls): import os if cls._driver is None: from pyvirtualdisplay import Display display = Display(visible=0, size=(800, 600)) display.start() from selenium import webdriver # Configure headless mode chrome_options = webdriver.ChromeOptions() #Oops chrome_options.add_argument('--verbose') chrome_options.add_argument('--ignore-certificate-errors') log_path = "/tmp/chromelogpanda{0}".format(os.getpid()) if not os.path.exists(log_path): os.mkdir(log_path) chrome_options.add_argument("--log-path {0}/log.txt".format(log_path)) chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-setuid-sandbox") cls._driver = webdriver.Chrome(chrome_options=chrome_options) return cls._driver class LazyPool(object): _pool = None @classmethod def get(cls): if cls._pool is None: import urllib3 cls._pool = urllib3.PoolManager() return cls._pool
Fix get images array index
<?php namespace Milax\Mconsole\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Milax\Mconsole\Models\Image as ImageModel; use Image; use File; class ImagesController extends Controller { protected $uploadDir; protected $uploadUrl; protected $scriptUrl; public function __construct() { $this->uploadDir = storage_path('tmp/images/'); $this->previewUrl = '/storage/images/'; $this->scriptUrl = '/mconsole/api/images/delete/'; } /** * Get all images for given model and id * * @return Resposne */ public function get(Request $request) { $input = $request->all(); $input['related_class'] = urldecode($input['related_class']); return app('API')->images->get($input['group'], $input['related_class'], $input['related_id'], $this->previewUrl, $this->scriptUrl); } /** * Upload images * * @param Request $request * @return Response */ public function uploadImage() { echo app('API')->images->upload(); } /** * Delete image * * @param int $fileName [Image file id] * @return Response */ public function deleteImage($id) { app('API')->images->delete($id); } }
<?php namespace Milax\Mconsole\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Milax\Mconsole\Models\Image as ImageModel; use Image; use File; class ImagesController extends Controller { protected $uploadDir; protected $uploadUrl; protected $scriptUrl; public function __construct() { $this->uploadDir = storage_path('tmp/images/'); $this->previewUrl = '/storage/images/'; $this->scriptUrl = '/mconsole/api/images/delete/'; } /** * Get all images for given model and id * * @return Resposne */ public function get(Request $request) { $input = $request->all(); $input['related_class'] = urldecode($input['related']); return app('API')->images->get($input['group'], $input['related_class'], $input['related_id'], $this->previewUrl, $this->scriptUrl); } /** * Upload images * * @param Request $request * @return Response */ public function uploadImage() { echo app('API')->images->upload(); } /** * Delete image * * @param int $fileName [Image file id] * @return Response */ public function deleteImage($id) { app('API')->images->delete($id); } }
Remove before normalization and use blue light as default
<?php namespace Avanzu\AdminThemeBundle\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('avanzu_admin_theme'); $rootNode->children() ->scalarNode('bower_bin') ->defaultValue('/usr/local/bin/bower') ->end() ->scalarNode('use_assetic') ->defaultValue(true) ->end() ->scalarNode('use_twig') ->defaultValue(true) ->end() ->arrayNode('options') ->children() ->scalarNode('skin') ->defaultValue('skin-blue-light') ->end() ->end() // ->beforeNormalization()->castToArray()->end() ->end(); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
<?php namespace Avanzu\AdminThemeBundle\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('avanzu_admin_theme'); $rootNode->children() ->scalarNode('bower_bin') ->defaultValue('/usr/local/bin/bower') ->end() ->scalarNode('use_assetic') ->defaultValue(true) ->end() ->scalarNode('use_twig') ->defaultValue(true) ->end() ->arrayNode('options') ->children() ->scalarNode('skin')->end() ->beforeNormalization()->castToArray()->end() ->end() ->end(); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
Fix super call for python2
import sys import xml.etree.ElementTree as ET from ..distributions import Distribution from .baseclock import BaseClock from .strict import StrictClock class RatePriorClock (BaseClock): # Class stub for putting priors on clock rates def __init__(self, clock_config, global_config): try: super().__init__(clock_config, global_config) except TypeError: # Python 2 has no argument-less super() super(RatePriorClock, self).__init__(clock_config, global_config) self.distribution = Distribution.from_string( clock_config.get( "rate", "lognormal(-6.9077552789821368, 2.3025850929940459)"), context="clock {:s}".format(self.name), is_point=True) self.initial_mean = self.distribution.mean() if clock_config.get( "estimate_rate", True) and self.distribution.dist == "point": self.distribution = Distribution(0, "uniform", (0, sys.maxsize)) def add_prior(self, prior): # TODO: Lift some logic from beastxml.BeastXML.add_calibration # and surroundings to parse prior specifications. # Uniform prior on mean clock rate sub_prior = ET.SubElement( prior, "prior", {"id": "clockPrior:%s" % self.name, "name": "distribution", "x": "@clockRate.c:%s" % self.name}) self.distribution.generate_xml_element( sub_prior) class StrictClockWithPrior (RatePriorClock, StrictClock): pass
import sys import xml.etree.ElementTree as ET from ..distributions import Distribution from .baseclock import BaseClock from .strict import StrictClock class RatePriorClock (BaseClock): # Class stub for putting priors on clock rates def __init__(self, clock_config, global_config): super().__init__(clock_config, global_config) self.distribution = Distribution.from_string( clock_config.get( "rate", "lognormal(-6.9077552789821368, 2.3025850929940459)"), context="clock {:s}".format(self.name), is_point=True) self.initial_mean = self.distribution.mean() if clock_config.get( "estimate_rate", True) and self.distribution.dist == "point": self.distribution = Distribution(0, "uniform", (0, sys.maxsize)) def add_prior(self, prior): # TODO: Lift some logic from beastxml.BeastXML.add_calibration # and surroundings to parse prior specifications. # Uniform prior on mean clock rate sub_prior = ET.SubElement( prior, "prior", {"id": "clockPrior:%s" % self.name, "name": "distribution", "x": "@clockRate.c:%s" % self.name}) self.distribution.generate_xml_element( sub_prior) class StrictClockWithPrior (RatePriorClock, StrictClock): pass
CHange name so it isn't reset
import sys import os ''' Easier searching for good RFI flagging values ''' try: ms_name = sys.argv[1] except IndexError: ms_name = raw_input("Input vis? : ") # Just want the number of SPWs tb.open(os.path.join(ms_name, "SPECTRAL_WINDOW")) nchans = tb.getcol('NUM_CHAN') tb.close() spws = range(len(nchans)) default('flagdata') for spw in spws: print("On spw "+str(spw)+" of "+str(len(nchans))) freqdevscale = 4.0 timedevscale = 4.0 while True: print("Starting at ") flagdata(vis=ms_name, mode='rflag', field='3C48*', spw=str(spw), datacolumn='corrected', action='calculate', display='both', freqdevscale=freqdevscale, timedevscale=timedevscale, flagbackup=False) adjust = True if raw_input("New thresholds? : ") == "T" else False if adjust: print("Current freqdevscale and timedevscale: %s %s" % (freqdevscale, timedevscale)) freqdevscale = float(raw_input("New freqdevscale : ")) timedevscale = float(raw_input("New timedevscale : ")) else: break
import sys import os ''' Easier searching for good RFI flagging values ''' try: vis = sys.argv[1] except IndexError: vis = raw_input("Input vis? : ") # Just want the number of SPWs tb.open(os.path.join(vis, "SPECTRAL_WINDOW")) nchans = tb.getcol('NUM_CHAN') tb.close() spws = range(len(nchans)) default('flagdata') for spw in spws: print("On spw "+str(spw)+" of "+str(len(nchans))) freqdevscale = 4.0 timedevscale = 4.0 while True: print("Starting at ") flagdata(vis=vis, mode='rflag', field='3C48*', spw=str(spw), datacolumn='corrected', action='calculate', display='both', freqdevscale=freqdevscale, timedevscale=timedevscale, flagbackup=False) adjust = True if raw_input("New thresholds? : ") == "T" else False if adjust: print("Current freqdevscale and timedevscale: %s %s" % (freqdevscale, timedevscale)) freqdevscale = float(raw_input("New freqdevscale : ")) timedevscale = float(raw_input("New timedevscale : ")) else: break
Change redirects to project form
ProjectsController.$inject = [ 'TbUtils', 'projects', '$rootScope' ]; function ProjectsController(TbUtils, projects, $rootScope) { const vm = this; vm.searchObj = term => { return { Name: term }; }; vm.searchResults = []; vm.pageSize = 9; vm.get = projects.getProjectsWithPagination; vm.getAll = projects.getProjects; vm.hideLoadBtn = () => vm.projects.length !== vm.searchResults.length; vm.projects = []; vm.goToProject = project => { TbUtils.go('main.project', { projectId: project.Id }); }; vm.goToNewProject = project => { TbUtils.go('main.new-project'); }; vm.goToEdit = project => { TbUtils.go('main.edit-project', { project: btoa(JSON.stringify(project)) }); }; vm.loading = true; vm.removeProjectClicked = removeProjectClicked; vm.toTitleCase = TbUtils.toTitleCase; TbUtils.getAndLoad(vm.get, vm.projects, () => { vm.loading = false; }, 0, vm.pageSize); function removeProjectClicked(project) { TbUtils.confirm('Eliminar Proyecto', `Esta seguro de eliminar ${project.Name}?`, resolve => { if (resolve) { vm.loading = true; TbUtils.deleteAndNotify(projects.deleteProject, project, vm.projects, () => { vm.loading = false; }); } }); } } module.exports = { name: 'ProjectsController', ctrl: ProjectsController };
ProjectsController.$inject = [ 'TbUtils', 'projects', '$rootScope' ]; function ProjectsController(TbUtils, projects, $rootScope) { const vm = this; vm.searchObj = term => { return { Name: term }; }; vm.searchResults = []; vm.pageSize = 9; vm.get = projects.getProjectsWithPagination; vm.getAll = projects.getProjects; vm.hideLoadBtn = () => vm.projects.length !== vm.searchResults.length; vm.projects = []; vm.goToProject = project => { TbUtils.go('main.project', { projectId: project.Id }); }; vm.goToNewProject = project => { TbUtils.go('main.addproject'); }; vm.goToEdit = project => { TbUtils.go('main.editproject', { project: JSON.stringify(project) }); }; vm.loading = true; vm.removeProjectClicked = removeProjectClicked; vm.toTitleCase = TbUtils.toTitleCase; TbUtils.getAndLoad(vm.get, vm.projects, () => { vm.loading = false; }, 0, vm.pageSize); function removeProjectClicked(project) { TbUtils.confirm('Eliminar Proyecto', `Esta seguro de eliminar ${project.Name}?`, resolve => { if (resolve) { vm.loading = true; TbUtils.deleteAndNotify(projects.deleteProject, project, vm.projects, () => { vm.loading = false; }); } }); } } module.exports = { name: 'ProjectsController', ctrl: ProjectsController };
Fix strategizer choice view choice selection in update view
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.u2.view', name: 'StrategizerChoiceView', extends: 'foam.u2.view.ChoiceView', documentation: 'A choice view that gets its choices array from Strategizer.', imports: [ 'strategizer' ], properties: [ { class: 'String', name: 'desiredModelId', required: true }, { class: 'String', name: 'target' } ], methods: [ function init() { this.SUPER(); this.onDetach(this.desiredModelId$.sub(this.updateChoices)); this.onDetach(this.target$.sub(this.updateChoices)); this.updateChoices(); } ], listeners: [ { name: 'updateChoices', code: function() { var self = this; self.strategizer.query(null, self.desiredModelId, self.target).then((strategyReferences) => { self.choices = strategyReferences .reduce((arr, sr) => { if ( ! sr.strategy ) { console.warn('Invalid strategy reference: ' + sr.id); return arr; } return arr.concat([[sr.strategy, sr.strategy.name]]); }, [[null, 'Select...']]) .filter(x => x); }); } } ] });
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.u2.view', name: 'StrategizerChoiceView', extends: 'foam.u2.view.ChoiceView', documentation: 'A choice view that gets its choices array from Strategizer.', imports: [ 'strategizer' ], properties: [ { class: 'String', name: 'desiredModelId', required: true }, { class: 'String', name: 'target' } ], methods: [ function init() { this.onDetach(this.desiredModelId$.sub(this.updateChoices)); this.onDetach(this.target$.sub(this.updateChoices)); this.updateChoices(); } ], listeners: [ { name: 'updateChoices', code: function() { var self = this; self.strategizer.query(null, self.desiredModelId, self.target).then((strategyReferences) => { self.choices = strategyReferences .reduce((arr, sr) => { if ( ! sr.strategy ) { console.warn('Invalid strategy reference: ' + sr.id); return arr; } return arr.concat([[sr.strategy.id, sr.strategy.name]]); }, [[null, 'Select...']]) .filter(x => x); }); } } ] });
Use .search for browser compatibility.
module.exports = WatchIgnorePlugin function WatchIgnorePlugin(paths) { this.paths = paths } WatchIgnorePlugin.prototype.apply = function (compiler) { compiler.plugin('after-environment', function () { compiler.watchFileSystem = new IgnoringWatchFileSystem(compiler.watchFileSystem, this.paths) }.bind(this)) } function IgnoringWatchFileSystem(wfs, paths) { this.wfs = wfs this.paths = paths } IgnoringWatchFileSystem.prototype.watch = function (files, dirs, missing, startTime, delay, callback, callbackUndelayed) { var ignored = function (path) { return this.paths.some(function (p) { return path.search(p) >= 0 }) }.bind(this) var notIgnored = function (path) { return !ignored(path) } var ignoredFiles = files.filter(ignored) var ignoredDirs = dirs.filter(ignored) this.wfs.watch(files.filter(notIgnored), dirs.filter(notIgnored), missing, startTime, delay, function (err, filesModified, dirsModified, fileTimestamps, dirTimestamps) { if (err) return callback(err) ignoredFiles.forEach(function (path) { fileTimestamps[path] = 1 }) ignoredDirs.forEach(function (path) { dirTimestamps[path] = 1 }) callback(err, filesModified, dirsModified, fileTimestamps, dirTimestamps) }, callbackUndelayed) }
module.exports = WatchIgnorePlugin function WatchIgnorePlugin(paths) { this.paths = paths } WatchIgnorePlugin.prototype.apply = function (compiler) { compiler.plugin('after-environment', function () { compiler.watchFileSystem = new IgnoringWatchFileSystem(compiler.watchFileSystem, this.paths) }.bind(this)) } function IgnoringWatchFileSystem(wfs, paths) { this.wfs = wfs this.paths = paths } IgnoringWatchFileSystem.prototype.watch = function (files, dirs, missing, startTime, delay, callback, callbackUndelayed) { var ignored = function (path) { return this.paths.some(function (p) { return path.match(p) }) }.bind(this) var notIgnored = function (path) { return !ignored(path) } var ignoredFiles = files.filter(ignored) var ignoredDirs = dirs.filter(ignored) this.wfs.watch(files.filter(notIgnored), dirs.filter(notIgnored), missing, startTime, delay, function (err, filesModified, dirsModified, fileTimestamps, dirTimestamps) { if (err) return callback(err) ignoredFiles.forEach(function (path) { fileTimestamps[path] = 1 }) ignoredDirs.forEach(function (path) { dirTimestamps[path] = 1 }) callback(err, filesModified, dirsModified, fileTimestamps, dirTimestamps) }, callbackUndelayed) }
Change default welcome page to include menu (We'll jettison the welcome page in due course)
<!DOCTYPE html> <html> <head> <title>Laravel</title> <link href="//fonts.googleapis.com/css?family=Lato:300" rel="stylesheet" type="text/css"> <style> html, body { height: 100%; } body { margin: 0; padding: 0; font-weight: 300; font-family: 'Lato'; } .outer { width: 100%; height: 100%; display: table; } .container { text-align: center; display: table-cell; vertical-align: middle; } .menu { padding: 4px; } .content { text-align: center; display: inline-block; } .title { font-size: 96px; } </style> </head> <body> <div class="menu"> <a href="auth/login">Login</a> | <a href="auth/register">Register</a> </div> <div class="outer"> <div class="container"> <div class="content"> <div class="title">Laravel 5</div> </div> </div> </div> </body> </html>
<!DOCTYPE html> <html> <head> <title>Laravel</title> <link href="//fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css"> <style> html, body { height: 100%; } body { margin: 0; padding: 0; width: 100%; display: table; font-weight: 100; font-family: 'Lato'; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 96px; } </style> </head> <body> <div class="container"> <div class="content"> <div class="title">Laravel 5</div> </div> </div> </body> </html>
Correct unit tests to comply with new team name RE
from django.test import TestCase from django.template.defaultfilters import slugify from django.core.exceptions import ValidationError from competition.validators import greater_than_zero, non_negative, validate_name class ValidationFunctionTest(TestCase): def test_greater_than_zero(self): """Check greater_than_zero validator""" self.assertRaises(ValidationError, greater_than_zero, 0) self.assertRaises(ValidationError, greater_than_zero, -1) self.assertIsNone(greater_than_zero(1)) def test_non_negative(self): """Check non_negative validator""" self.assertRaises(ValidationError, non_negative, -1) self.assertIsNone(non_negative(0)) self.assertIsNone(non_negative(1)) def test_validate_name(self): """Check name validator""" # Try some valid names valid_names = ['MegaMiner-AI 10: Galapagos', 'Chess 2012', '2012 Chess', 'B.L.O.O.M. 2: Revenge of the Flowers'] for name in valid_names: self.assertIsNone(validate_name(name)) self.assertRaises(ValidationError, validate_name, "..") self.assertRaises(ValidationError, validate_name, "_..") self.assertRaises(ValidationError, validate_name, "_") self.assertRaises(ValidationError, validate_name, "____") self.assertRaises(ValidationError, validate_name, ".Nope") self.assertRaises(ValidationError, validate_name, ".Nope")
from django.test import TestCase from django.template.defaultfilters import slugify from django.core.exceptions import ValidationError from competition.validators import greater_than_zero, non_negative, validate_name class ValidationFunctionTest(TestCase): def test_greater_than_zero(self): """Check greater_than_zero validator""" self.assertRaises(ValidationError, greater_than_zero, 0) self.assertRaises(ValidationError, greater_than_zero, -1) self.assertIsNone(greater_than_zero(1)) def test_non_negative(self): """Check non_negative validator""" self.assertRaises(ValidationError, non_negative, -1) self.assertIsNone(non_negative(0)) self.assertIsNone(non_negative(1)) def test_validate_name(self): """Check name validator""" # Try some valid names valid_names = ['MegaMiner-AI 10: Galapagos', 'Chess 2012', '2012 Chess', 'B.L.O.O.M. 2: Revenge of the Flowers', '__main__'] for name in valid_names: self.assertIsNone(validate_name(name)) self.assertRaises(ValidationError, validate_name, "..") self.assertRaises(ValidationError, validate_name, "_..") self.assertRaises(ValidationError, validate_name, "_") self.assertRaises(ValidationError, validate_name, "____") self.assertRaises(ValidationError, validate_name, ".Nope") self.assertRaises(ValidationError, validate_name, ".Nope")
Load fixtures for the Abac tests
<?php namespace PhpAbac\Test; use PhpAbac\Abac; class AbacTest extends AbacTestCase { /** @var Abac **/ protected $abac; public function setUp() { $this->abac = new Abac(new \PDO( 'mysql:host=' . $GLOBALS['MYSQL_DB_HOST'] . ';' . 'dbname=' . $GLOBALS['MYSQL_DB_DBNAME'], $GLOBALS['MYSQL_DB_USER'], $GLOBALS['MYSQL_DB_PASSWD'], [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ] )); $this->abac->resetSchema(); $this->loadFixture('rules'); } public function tearDown() { Abac::clearContainer(); } public function testEnforce() { $this->abac->enforce('nationality-access', 1); } public function testContainer() { $item = new \stdClass(); $item->property = 'test'; // Test Set method Abac::set('test-item', $item); // Test Has method $this->assertTrue(Abac::has('test-item')); // Test Get method $containedItem = Abac::get('test-item'); $this->assertInstanceof('StdClass', $containedItem); $this->assertEquals('test', $containedItem->property); // Test clearContainer Abac::clearContainer(); $this->assertFalse(Abac::has('test-item')); } }
<?php namespace PhpAbac\Test; use PhpAbac\Abac; class AbacTest extends \PHPUnit_Framework_TestCase { public function setUp() { new Abac(new \PDO( 'mysql:host=' . $GLOBALS['MYSQL_DB_HOST'] . ';' . 'dbname=' . $GLOBALS['MYSQL_DB_DBNAME'], $GLOBALS['MYSQL_DB_USER'], $GLOBALS['MYSQL_DB_PASSWD'], [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ] )); } public function tearDown() { Abac::clearContainer(); } public function testContainer() { $item = new \stdClass(); $item->property = 'test'; // Test Set method Abac::set('test-item', $item); // Test Has method $this->assertTrue(Abac::has('test-item')); // Test Get method $containedItem = Abac::get('test-item'); $this->assertInstanceof('StdClass', $containedItem); $this->assertEquals('test', $containedItem->property); // Test clearContainer Abac::clearContainer(); $this->assertFalse(Abac::has('test-item')); } }
FIX mailing_contact merge fields value
############################################################################## # # Copyright (C) 2021 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <[email protected]> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import fields, models class MailchimpMergeFields(models.Model): _inherit = "mailchimp.merge.fields" # Allows to use fields from mail.mass_mailing.contact records in merge fields field_id = fields.Many2one(domain=[ ('model_id.model', 'in', ['res.partner', 'mail.mass_mailing.contact']), ('ttype', 'not in', ['one2many', 'many2one', 'many2many'])] ) def get_value(self, mailing_contact): contact_fields = self.filtered( lambda f: f.field_id.model == "mail.mass_mailing.contact") partner_fields = self - contact_fields res = super(MailchimpMergeFields, partner_fields).get_value(mailing_contact) for custom_field in contact_fields: if custom_field.field_id and hasattr( mailing_contact, custom_field.field_id.name): value = getattr(mailing_contact, custom_field.field_id.name) else: value = '' res.update({custom_field.tag: value or ''}) return res
############################################################################## # # Copyright (C) 2021 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <[email protected]> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import fields, models class MailchimpMergeFields(models.Model): _inherit = "mailchimp.merge.fields" # Allows to use fields from mail.mass_mailing.contact records in merge fields field_id = fields.Many2one(domain=[ ('model_id.model', 'in', ['res.partner', 'mail.mass_mailing.contact']), ('ttype', 'not in', ['one2many', 'many2one', 'many2many'])] ) def get_value(self, mailing_contact): contact_fields = self.filtered( lambda f: f.field_id.model == "mail.mass_mailing.contact") partner_fields = self - contact_fields res = super(MailchimpMergeFields, partner_fields).get_value(mailing_contact) for custom_field in contact_fields: if custom_field.field_id and hasattr( self, custom_field.field_id.name): value = getattr(self, custom_field.field_id.name) else: value = '' res.update({custom_field.tag: value or ''}) return res
Fix main failing on no event_callback
"""Read events and parameters from your Axis device.""" import asyncio import argparse import logging import sys from axis import AxisDevice async def main(args): loop = asyncio.get_event_loop() device = AxisDevice( loop=loop, host=args.host, username=args.username, password=args.password, port=args.port) if args.params: await loop.run_in_executor(None, device.vapix.initialize_params) await loop.run_in_executor(None, device.vapix.initialize_ports) await loop.run_in_executor(None, device.vapix.initialize_users) if not args.events: return if args.events: def event_handler(action, event): print(action, event) device.enable_events(event_callback=event_handler) device.start() try: while True: await asyncio.sleep(1) except KeyboardInterrupt: pass finally: device.stop() if __name__ == "__main__": logging.basicConfig(format='%(message)s', level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('host', type=str) parser.add_argument('username', type=str) parser.add_argument('password', type=str) parser.add_argument('-p', '--port', type=int, default=80) parser.add_argument('--events', action='store_true') parser.add_argument('--params', action='store_true') args = parser.parse_args() asyncio.run(main(args))
"""Read events and parameters from your Axis device.""" import asyncio import argparse import logging import sys from axis import AxisDevice async def main(args): loop = asyncio.get_event_loop() device = AxisDevice( loop=loop, host=args.host, username=args.username, password=args.password, port=args.port) if args.params: await loop.run_in_executor(None, device.vapix.initialize_params) await loop.run_in_executor(None, device.vapix.initialize_ports) await loop.run_in_executor(None, device.vapix.initialize_users) if not args.events: return if args.events: device.start() try: while True: await asyncio.sleep(1) except KeyboardInterrupt: pass finally: device.stop() if __name__ == "__main__": logging.basicConfig(format='%(message)s', level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument('host', type=str) parser.add_argument('username', type=str) parser.add_argument('password', type=str) parser.add_argument('-p', '--port', type=int, default=80) parser.add_argument('--events', action='store_true') parser.add_argument('--params', action='store_true') args = parser.parse_args() asyncio.run(main(args))
Enable Wikidata for Wikimedia Commons Change-Id: Ibc8734f65dcd97dc7af9674efe8655fe01dc61d3
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The Wikimedia Commons family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'commons' self.langs = { 'commons': 'commons.wikimedia.org', } self.interwiki_forward = 'wikipedia' self.category_redirect_templates = { 'commons': (u'Category redirect', u'Categoryredirect', u'Synonym taxon category redirect', u'Invalid taxon category redirect', u'Monotypic taxon category redirect', u'See cat', u'Seecat', u'See category', u'Catredirect', u'Cat redirect', u'Cat-red', u'Catredir', u'Redirect category'), } self.disambcatname = { 'commons': u'Disambiguation' } def ssl_pathprefix(self, code): return "/wikipedia/commons" def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata')
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The Wikimedia Commons family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'commons' self.langs = { 'commons': 'commons.wikimedia.org', } self.interwiki_forward = 'wikipedia' self.category_redirect_templates = { 'commons': (u'Category redirect', u'Categoryredirect', u'Synonym taxon category redirect', u'Invalid taxon category redirect', u'Monotypic taxon category redirect', u'See cat', u'Seecat', u'See category', u'Catredirect', u'Cat redirect', u'Cat-red', u'Catredir', u'Redirect category'), } self.disambcatname = { 'commons': u'Disambiguation' } def ssl_pathprefix(self, code): return "/wikipedia/commons"
Secure index access and type safe comparision in statistic median
<?php declare(strict_types=1); namespace Phpml\Math\Statistic; use Phpml\Exception\InvalidArgumentException; class Mean { /** * @param array $numbers * * @return float * * @throws InvalidArgumentException */ public static function arithmetic(array $numbers) { self::checkArrayLength($numbers); return array_sum($numbers) / count($numbers); } /** * @param array $numbers * * @return float|mixed * * @throws InvalidArgumentException */ public static function median(array $numbers) { self::checkArrayLength($numbers); $count = count($numbers); $middleIndex = (int)floor($count / 2); sort($numbers, SORT_NUMERIC); $median = $numbers[$middleIndex]; if (0 === $count % 2) { $median = ($median + $numbers[$middleIndex - 1]) / 2; } return $median; } /** * @param array $numbers * * @return mixed * * @throws InvalidArgumentException */ public static function mode(array $numbers) { self::checkArrayLength($numbers); $values = array_count_values($numbers); return array_search(max($values), $values); } /** * @param array $array * * @throws InvalidArgumentException */ private static function checkArrayLength(array $array) { if (0 == count($array)) { throw InvalidArgumentException::arrayCantBeEmpty(); } } }
<?php declare(strict_types=1); namespace Phpml\Math\Statistic; use Phpml\Exception\InvalidArgumentException; class Mean { /** * @param array $numbers * * @return float * * @throws InvalidArgumentException */ public static function arithmetic(array $numbers) { self::checkArrayLength($numbers); return array_sum($numbers) / count($numbers); } /** * @param array $numbers * * @return float|mixed * * @throws InvalidArgumentException */ public static function median(array $numbers) { self::checkArrayLength($numbers); $count = count($numbers); $middleIndex = floor($count / 2); sort($numbers, SORT_NUMERIC); $median = $numbers[$middleIndex]; if (0 == $count % 2) { $median = ($median + $numbers[$middleIndex - 1]) / 2; } return $median; } /** * @param array $numbers * * @return mixed * * @throws InvalidArgumentException */ public static function mode(array $numbers) { self::checkArrayLength($numbers); $values = array_count_values($numbers); return array_search(max($values), $values); } /** * @param array $array * * @throws InvalidArgumentException */ private static function checkArrayLength(array $array) { if (0 == count($array)) { throw InvalidArgumentException::arrayCantBeEmpty(); } } }
Fix unaesthetic bug where All Questions sidebar item is highlighted even when New Question sidebar item is selected and All Questions is not
// @flow import React, { Component } from "react"; import "./AdminSidebar.css"; import { Col, Nav, NavItem, NavLink } from "reactstrap"; import { NavLink as Link } from "react-router-dom"; import LessonSidebar from "../LessonSidebar"; class AdminSidebar extends Component { render() { return ( <Col sm="3" md="2" className="sidebar"> <Nav pills vertical> <NavItem> <NavLink tag={Link} to="/admin/users"> Users </NavLink> </NavItem> <NavItem> <NavLink tag={Link} to="/admin/loggers"> Logger </NavLink> </NavItem> <NavItem> <NavLink tag={Link} exact to="/admin/questions"> All Questions </NavLink> </NavItem> <NavItem> <NavLink tag={Link} to="/admin/questions/new"> New Question </NavLink> </NavItem> <NavItem> <NavLink tag={Link} to="/admin/lessons/new"> New Lesson </NavLink> </NavItem> <NavItem>Lessons</NavItem> <LessonSidebar admin={true} /> </Nav> </Col> ); } } export default AdminSidebar;
// @flow import React, { Component } from "react"; import "./AdminSidebar.css"; import { Col, Nav, NavItem, NavLink } from "reactstrap"; import { NavLink as Link } from "react-router-dom"; import LessonSidebar from "../LessonSidebar"; class AdminSidebar extends Component { render() { return ( <Col sm="3" md="2" className="sidebar"> <Nav pills vertical> <NavItem> <NavLink tag={Link} to="/admin/users"> Users </NavLink> </NavItem> <NavItem> <NavLink tag={Link} to="/admin/loggers"> Logger </NavLink> </NavItem> <NavItem> <NavLink tag={Link} to="/admin/questions"> All Questions </NavLink> </NavItem> <NavItem> <NavLink tag={Link} to="/admin/questions/new"> New Question </NavLink> </NavItem> <NavItem> <NavLink tag={Link} to="/admin/lessons/new"> New Lesson </NavLink> </NavItem> <NavItem>Lessons</NavItem> <LessonSidebar admin={true} /> </Nav> </Col> ); } } export default AdminSidebar;
Sort rules lists (take 2)
(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; var sys = this.sys; var ruleGroupID = params.groupid; console.log("ruleGroupID="+ruleGroupID); var sql = 'SELECT ruleID,string,adminID,name ' + 'FROM rules ' + 'JOIN ruleStrings USING(ruleStringID) ' + 'JOIN admin USING(adminID) ' + 'WHERE ruleGroupID=? ' + 'ORDER BY string;'; sys.db.all(sql,[ruleGroupID],function(err,rows){ if (err||!rows) {return oops(response,err,'classes/getrules(1)')}; var ret = {admin:[],commenters:[]}; for (var i=0,ilen=rows.length;i<ilen;i+=1) { var row = rows[i]; if (row.adminID == 1) { ret.admin.push(row); } else { ret.commenters.push(row); } } response.writeHead(200, {'Content-Type': 'application/json'}); response.end(JSON.stringify(ret)); }); } exports.cogClass = cogClass; })();
(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; var sys = this.sys; var ruleGroupID = params.groupid; console.log("ruleGroupID="+ruleGroupID); var sql = 'SELECT ruleID,string,adminID,name ' + 'FROM rules ' + 'JOIN ruleStrings USING(ruleStringID) ' + 'JOIN admin USING(adminID) ' + 'ORDER BY string ' + 'WHERE ruleGroupID=?;'; sys.db.all(sql,[ruleGroupID],function(err,rows){ if (err||!rows) {return oops(response,err,'classes/getrules(1)')}; var ret = {admin:[],commenters:[]}; for (var i=0,ilen=rows.length;i<ilen;i+=1) { var row = rows[i]; if (row.adminID == 1) { ret.admin.push(row); } else { ret.commenters.push(row); } } response.writeHead(200, {'Content-Type': 'application/json'}); response.end(JSON.stringify(ret)); }); } exports.cogClass = cogClass; })();
Set default value for city
var User = require('../models/user.js'); var TwitterStrategy = require('passport-twitter').Strategy; module.exports = function (passport) { passport.use(new TwitterStrategy({ consumerKey: process.env.NMDICO_CONSUMER_KEY, consumerSecret: process.env.NMDICO_CONSUMER_SECRET, callbackURL: process.env.NMDICO_URL + '/auth/twitter/callback' }, function (token, tokenSecret, profile, done) { User.findOne({'twitter.id': profile.id}, function (err, user) { if (user) { return done(err, user); } else { var newUser = { iconHash: require('crypto').randomBytes(8).toString('hex'), twitter: { id: profile.id, username: profile.username, tokenSecret: tokenSecret }, location: { city: 'Earth' } }; User.create(newUser, function (err, user) { return done(err, user); }); } }); } )); passport.serializeUser(function (user, done) { done(null, user._id); }); passport.deserializeUser(function (id, done) { User.findById(id, function (err, user) { done(err, user); }); }); };
var User = require('../models/user.js'); var TwitterStrategy = require('passport-twitter').Strategy; module.exports = function (passport) { passport.use(new TwitterStrategy({ consumerKey: process.env.NMDICO_CONSUMER_KEY, consumerSecret: process.env.NMDICO_CONSUMER_SECRET, callbackURL: process.env.NMDICO_URL + '/auth/twitter/callback' }, function (token, tokenSecret, profile, done) { User.findOne({'twitter.id': profile.id}, function (err, user) { if (user) { return done(err, user); } else { var newUser = { iconHash: require('crypto').randomBytes(8).toString('hex'), twitter: { id: profile.id, username: profile.username, tokenSecret: tokenSecret }, }; User.create(newUser, function (err, user) { return done(err, user); }); } }); } )); passport.serializeUser(function (user, done) { done(null, user._id); }); passport.deserializeUser(function (id, done) { User.findById(id, function (err, user) { done(err, user); }); }); };
Fix a typo: patform -> platform
import six import hashlib import ecdsa # We can use pyelliptic (uses OpenSSL) but this is more cross-platform # We use curve standard for Bitcoin by default CURVE = ecdsa.SECP256k1 class SigningKey(ecdsa.SigningKey, object): def get_pubkey(self): return b'\x04' + self.get_verifying_key().to_string() def sign(self, msg): return super(SigningKey, self).sign( msg, sigencode=ecdsa.util.sigencode_der, hashfunc=hashlib.sha256) class VerifyingKey(ecdsa.VerifyingKey, object): def verify(self, signature, data): return super(VerifyingKey, self).verify( signature, data, hashfunc=hashlib.sha256, sigdecode=ecdsa.util.sigdecode_der) def private(seed, salt, kdf=None, curve=CURVE): assert callable(kdf) if six.PY3 and isinstance(seed, six.string_types): seed = seed.encode() if isinstance(salt, (list, tuple)): salt = "|".join(salt) if six.PY3: salt = salt.encode() return SigningKey.from_string(kdf(seed, salt), curve=curve) def public(pub, curve=CURVE): assert pub[0] == b'\x04'[0] return VerifyingKey.from_string(pub[1:], curve=curve)
import six import hashlib import ecdsa # We can use pyelliptic (uses OpenSSL) but this is more cross-patform # We use curve standard for Bitcoin by default CURVE = ecdsa.SECP256k1 class SigningKey(ecdsa.SigningKey, object): def get_pubkey(self): return b'\x04' + self.get_verifying_key().to_string() def sign(self, msg): return super(SigningKey, self).sign( msg, sigencode=ecdsa.util.sigencode_der, hashfunc=hashlib.sha256) class VerifyingKey(ecdsa.VerifyingKey, object): def verify(self, signature, data): return super(VerifyingKey, self).verify( signature, data, hashfunc=hashlib.sha256, sigdecode=ecdsa.util.sigdecode_der) def private(seed, salt, kdf=None, curve=CURVE): assert callable(kdf) if six.PY3 and isinstance(seed, six.string_types): seed = seed.encode() if isinstance(salt, (list, tuple)): salt = "|".join(salt) if six.PY3: salt = salt.encode() return SigningKey.from_string(kdf(seed, salt), curve=curve) def public(pub, curve=CURVE): assert pub[0] == b'\x04'[0] return VerifyingKey.from_string(pub[1:], curve=curve)
Add code comment for server-start-chatting
import io from 'socket.io-client'; function realtimeConnector(cookie, realtimeUrl, roomId, handleNewMessageCallback, handleNextCallback, disableChatCallback) { this._chatting = false; this._socket = io.connect(realtimeUrl, {'forceNew': true}); this._socket.on('connect', () => { this._socket.emit('client-join-room', roomId, cookie); }); this._socket.on('server-start-chatting', () => { // If already chatting, ignore this message if (!this._chatting) { disableChatCallback(false); this._chatting = true; } }); this._socket.on('server-message', (message, from) => { handleNewMessageCallback(message, from); }); this._socket.on('server-next', () => { handleNextCallback(); }); this._socket.on('disconnect', () => { disableChatCallback(true); this._chatting = false; }); this.broadcastMessage = function(message) { this._socket.emit('client-message', message); }; this.broadcastNext = function() { this._socket.emit('client-next'); disableChatCallback(true); this._chatting = false; }; this.disconnect = function() { this._socket.disconnect(); } this.reconnect = function() { this._socket.connect(); } }; module.exports = realtimeConnector;
import io from 'socket.io-client'; function realtimeConnector(cookie, realtimeUrl, roomId, handleNewMessageCallback, handleNextCallback, disableChatCallback) { this._chatting = false; this._socket = io.connect(realtimeUrl, {'forceNew': true}); this._socket.on('connect', () => { this._socket.emit('client-join-room', roomId, cookie); }); this._socket.on('server-start-chatting', () => { if (!this._chatting) { disableChatCallback(false); this._chatting = true; } }); this._socket.on('server-message', (message, from) => { handleNewMessageCallback(message, from); }); this._socket.on('server-next', () => { handleNextCallback(); }); this._socket.on('disconnect', () => { disableChatCallback(true); this._chatting = false; }); this.broadcastMessage = function(message) { this._socket.emit('client-message', message); }; this.broadcastNext = function() { this._socket.emit('client-next'); disableChatCallback(true); this._chatting = false; }; this.disconnect = function() { this._socket.disconnect(); } this.reconnect = function() { this._socket.connect(); } }; module.exports = realtimeConnector;
Fix type hint, setEncryption accept string parameter
<?php /* * This file is part of SwiftMailer. * (c) 2004-2009 Chris Corbyn * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Sends Messages over SMTP with ESMTP support. * @package Swift * @subpackage Transport * @author Chris Corbyn */ class Swift_SmtpTransport extends Swift_Transport_EsmtpTransport { /** * Create a new SmtpTransport, optionally with $host, $port and $security. * @param string $host * @param int $port * @param string $security */ public function __construct($host = 'localhost', $port = 25, $security = null) { call_user_func_array( array($this, 'Swift_Transport_EsmtpTransport::__construct'), Swift_DependencyContainer::getInstance() ->createDependenciesFor('transport.smtp') ); $this->setHost($host); $this->setPort($port); $this->setEncryption($security); } /** * Create a new SmtpTransport instance. * @param string $host * @param int $port * @param string $security * @return Swift_SmtpTransport */ public static function newInstance($host = 'localhost', $port = 25, $security = null) { return new self($host, $port, $security); } }
<?php /* * This file is part of SwiftMailer. * (c) 2004-2009 Chris Corbyn * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Sends Messages over SMTP with ESMTP support. * @package Swift * @subpackage Transport * @author Chris Corbyn */ class Swift_SmtpTransport extends Swift_Transport_EsmtpTransport { /** * Create a new SmtpTransport, optionally with $host, $port and $security. * @param string $host * @param int $port * @param int $security */ public function __construct($host = 'localhost', $port = 25, $security = null) { call_user_func_array( array($this, 'Swift_Transport_EsmtpTransport::__construct'), Swift_DependencyContainer::getInstance() ->createDependenciesFor('transport.smtp') ); $this->setHost($host); $this->setPort($port); $this->setEncryption($security); } /** * Create a new SmtpTransport instance. * @param string $host * @param int $port * @param int $security * @return Swift_SmtpTransport */ public static function newInstance($host = 'localhost', $port = 25, $security = null) { return new self($host, $port, $security); } }
Use actual constant name (molar_gas_constant)
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None, backend=math): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float with unit Extracellular concentration of ion ion_conc_in: float with unit Intracellular concentration of ion charge: integer Charge of the ion T: float with unit Absolute temperature constants: object (optional, default: None) constant attributes accessed: F - Faraday constant R - Ideal Gas constant units: object (optional, default: None) unit attributes: coulomb, joule, kelvin, mol backend: module (optional, default: math) module used to calculate log using `log` method, can be substituted with sympy to get symbolic answers Returns ------- Membrane potential """ if constants is None: F = 96485.33289 R = 8.3144598 if units is not None: F *= units.coulomb / units.mol R *= units.joule / units.kelvin / units.mol else: F = constants.Faraday_constant R = constants.molar_gas_constant return (R * T) / (charge * F) * backend.log(ion_conc_out / ion_conc_in)
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None, backend=math): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float with unit Extracellular concentration of ion ion_conc_in: float with unit Intracellular concentration of ion charge: integer Charge of the ion T: float with unit Absolute temperature constants: object (optional, default: None) constant attributes accessed: F - Faraday constant R - Ideal Gas constant units: object (optional, default: None) unit attributes: coulomb, joule, kelvin, mol backend: module (optional, default: math) module used to calculate log using `log` method, can be substituted with sympy to get symbolic answers Returns ------- Membrane potential """ if constants is None: F = 96485.33289 R = 8.3144598 if units is not None: F *= units.coulomb / units.mol R *= units.joule / units.kelvin / units.mol else: F = constants.Faraday_constant R = constants.ideal_gas_constant return (R * T) / (charge * F) * backend.log(ion_conc_out / ion_conc_in)
Fix issue with guava preconditions check in logback setup
package com.intuso.housemate.platform.pc; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; import com.intuso.housemate.client.v1_0.api.HousemateException; import org.slf4j.LoggerFactory; import java.io.File; /** * Created by tomc on 03/03/16. */ public class Logback { private static final String LOGBACK_FILE = "logback.xml"; static { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { cleanup(); } }); } public static void configure(File configDir) { File logbackFile = new File(configDir, LOGBACK_FILE); if(!logbackFile.exists()) throw new HousemateException("Could not find logback configuration at " + logbackFile.getAbsoluteFile()); final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); final JoranConfigurator joranConfigurator = new JoranConfigurator(); joranConfigurator.setContext(context); context.reset(); try { joranConfigurator.doConfigure(logbackFile); } catch (JoranException ignored) {} StatusPrinter.printInCaseOfErrorsOrWarnings(context); } public static void cleanup() { ((LoggerContext) LoggerFactory.getILoggerFactory()).stop(); } }
package com.intuso.housemate.platform.pc; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; import com.google.common.base.Preconditions; import org.slf4j.LoggerFactory; import java.io.File; /** * Created by tomc on 03/03/16. */ public class Logback { private static final String LOGBACK_FILE = "logback.xml"; static { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { cleanup(); } }); } public static void configure(File configDir) { File logbackFile = new File(configDir, LOGBACK_FILE); Preconditions.checkState(logbackFile.exists(), "Could not find logback configuration at %s", logbackFile.getAbsoluteFile()); final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); final JoranConfigurator joranConfigurator = new JoranConfigurator(); joranConfigurator.setContext(context); context.reset(); try { joranConfigurator.doConfigure(logbackFile); } catch (JoranException ignored) {} StatusPrinter.printInCaseOfErrorsOrWarnings(context); } public static void cleanup() { ((LoggerContext) LoggerFactory.getILoggerFactory()).stop(); } }
Document finder tests better and use better terminology (the thing that collects found objects isn't a finder, it's a collector)
import unittest from testdoc.finder import find_tests class MockCollector(object): def __init__(self): self.log = [] def got_module(self, module): self.log.append(('module', module)) def got_test_class(self, klass): self.log.append(('class', klass)) def got_test(self, method): self.log.append(('method', method)) class TestPassiveFinder(unittest.TestCase): """One approach to finding tests is to look inside a module for test classes and then look inside those test classes for test methods. The default finder uses this approach. """ def setUp(self): self.collector = MockCollector() def test_empty(self): from testdoc.tests import empty find_tests(self.collector, empty) self.assertEqual(self.collector.log, [('module', empty)]) def test_hasemptycase(self): from testdoc.tests import hasemptycase find_tests(self.collector, hasemptycase) self.assertEqual( self.collector.log, [ ('module', hasemptycase), ('class', hasemptycase.SomeTest)]) def test_hastests(self): from testdoc.tests import hastests find_tests(self.collector, hastests) self.assertEqual( self.collector.log, [ ('module', hastests), ('class', hastests.SomeTest), ('method', hastests.SomeTest.test_foo_handles_qux), ('method', hastests.SomeTest.test_bar), ('class', hastests.AnotherTest), ('method', hastests.AnotherTest.test_baz)])
import unittest from testdoc.finder import find_tests class MockFinder(object): def __init__(self): self.log = [] def got_module(self, module): self.log.append(('module', module)) def got_test_class(self, klass): self.log.append(('class', klass)) def got_test(self, method): self.log.append(('method', method)) class TestFinder(unittest.TestCase): def setUp(self): self.finder = MockFinder() def test_empty(self): from testdoc.tests import empty find_tests(self.finder, empty) self.assertEqual(self.finder.log, [('module', empty)]) def test_hasemptycase(self): from testdoc.tests import hasemptycase find_tests(self.finder, hasemptycase) self.assertEqual( self.finder.log, [ ('module', hasemptycase), ('class', hasemptycase.SomeTest)]) def test_hastests(self): from testdoc.tests import hastests find_tests(self.finder, hastests) self.assertEqual( self.finder.log, [ ('module', hastests), ('class', hastests.SomeTest), ('method', hastests.SomeTest.test_foo_handles_qux), ('method', hastests.SomeTest.test_bar), ('class', hastests.AnotherTest), ('method', hastests.AnotherTest.test_baz)])
Fix posting messages with smiles
package com.perm.kate.api; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.TreeMap; import java.util.Map.Entry; public class Params { TreeMap<String, String> args = new TreeMap<String, String>(); String method_name; public Params(String method_name){ this.method_name=method_name; } public void put(String param_name, String param_value) { if(param_value==null || param_value.length()==0) return; args.put(param_name, param_value); } public void put(String param_name, Long param_value) { if(param_value==null) return; args.put(param_name, Long.toString(param_value)); } public void put(String param_name, Integer param_value) { if(param_value==null) return; args.put(param_name, Integer.toString(param_value)); } public void putDouble(String param_name, double param_value) { args.put(param_name, Double.toString(param_value)); } public String getParamsString() { String params=""; try { for(Entry<String, String> entry:args.entrySet()){ if(params.length()!=0) params+="&"; params+=(entry.getKey()+"="+URLEncoder.encode(entry.getValue(), "utf-8")); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return params; } }
package com.perm.kate.api; import java.net.URLEncoder; import java.util.TreeMap; import java.util.Map.Entry; public class Params { TreeMap<String, String> args = new TreeMap<String, String>(); String method_name; public Params(String method_name){ this.method_name=method_name; } public void put(String param_name, String param_value) { if(param_value==null || param_value.length()==0) return; args.put(param_name, param_value); } public void put(String param_name, Long param_value) { if(param_value==null) return; args.put(param_name, Long.toString(param_value)); } public void put(String param_name, Integer param_value) { if(param_value==null) return; args.put(param_name, Integer.toString(param_value)); } public void putDouble(String param_name, double param_value) { args.put(param_name, Double.toString(param_value)); } public String getParamsString() { String params=""; for(Entry<String, String> entry:args.entrySet()){ if(params.length()!=0) params+="&"; params+=(entry.getKey()+"="+URLEncoder.encode(entry.getValue())); } return params; } }
Add call to AuthService for logout
/** * LoginActions * Actions for helping with login */ import { browserHistory } from 'react-router'; import Parse from 'parse'; import AuthService from '../middleware/api/Authentication'; export const LOGIN_REQUEST = "LOGIN_REQUEST"; export const LOGIN_SUCCESS = "LOGIN_SUCCESS"; export const LOGIN_FAIL = "LOGIN_FAIL"; export const LOGOUT_REQUEST = "LOGOUT_REQUEST"; export const SIGNUP_USER = "SIGNUP_USER"; function requestLogin (username) { return { type: LOGIN_REQUEST, username, isLoggedIn: true } } function loginSuccess (username) { return { type: LOGIN_SUCCESS, username, isLoggedIn: true } } function logoutUser (username) { return { type: LOGOUT_REQUEST, username, isLoggedIn: false } } function signupUser (username) { return { type: SIGNUP_USER, username, isLoggedIn: true } } export function loginRequest (username, password) { AuthService.login(username, password) return requestLogin(username) } export function success (username) { browserHistory.push('/home') return loginSuccess(username) } export function userLogout () { let username = Parse.User.current() AuthService.logout() browserHistory.push('/login') return logoutUser(username) } export function signup (username, password) { AuthService.signup (username, password) browserHistory.push('/home') return signupUser(username) }
/** * LoginActions * Actions for helping with login */ import { browserHistory } from 'react-router'; import Parse from 'parse'; import AuthService from '../middleware/api/Authentication'; export const LOGIN_REQUEST = "LOGIN_REQUEST"; export const LOGIN_SUCCESS = "LOGIN_SUCCESS"; export const LOGIN_FAIL = "LOGIN_FAIL"; export const LOGOUT_REQUEST = "LOGOUT_REQUEST"; export const SIGNUP_USER = "SIGNUP_USER"; function requestLogin (username) { return { type: LOGIN_REQUEST, username, isLoggedIn: true } } function loginSuccess (username) { return { type: LOGIN_SUCCESS, username, isLoggedIn: true } } function logoutUser (username) { return { type: LOGOUT_REQUEST, username, isLoggedIn: false } } function signupUser (username) { return { type: SIGNUP_USER, username, isLoggedIn: true } } export function loginRequest (username, password) { AuthService.login(username, password) return requestLogin(username) } export function success (username) { browserHistory.push('/home') return loginSuccess(username) } export function userLogout () { let username = Parse.User.current() browserHistory.push('/login') return logoutUser(username) } export function signup (username, password) { AuthService.signup (username, password) browserHistory.push('/home') return signupUser(username) }
Fix layer selector bug not working properly
niclabs.insight.filter.LayerSelector = (function($) { /** * Construct a layer for the dashboard * * The layer selector provides an option to switch between layers of the dashboard * * @class niclabs.insight.filter.LayerSelector * @augments niclabs.insight.filter.Filter * @param {niclabs.insight.Dashboard} dashboard - dashboard that this filter belongs to * @param {Object} options - configuration options for the filter */ var LayerSelector = function(dashboard, options) { var view = niclabs.insight.filter.Filter(dashboard, options); var layers = {}; // Configure the view var select = $('<select>'); // Hide the selector if there are no elements select.hide(); select.on('change', function() { dashboard.active($(this).val()); }); // Add the selector to the view view.$.append(select); /** * Add a layer to the selector * * @memberof niclabs.insight.filter.LayerSelector * @param {string} id - id for the layer * @param {name} name - name of the layer */ view.add = function(id, name) { layers[id] = name; select.append($('<option>').attr('value', id).text(name)); // Show the selector if there is more than one layer // Note: layers.length returns undefined if (Object.keys(layers).length > 1) select.show(); }; return view; }; // Register the handler niclabs.insight.handler('layer-selector', 'filter', LayerSelector); return LayerSelector; })(jQuery);
niclabs.insight.filter.LayerSelector = (function($) { /** * Construct a layer for the dashboard * * The layer selector provides an option to switch between layers of the dashboard * * @class niclabs.insight.filter.LayerSelector * @augments niclabs.insight.filter.Filter * @param {niclabs.insight.Dashboard} dashboard - dashboard that this filter belongs to * @param {Object} options - configuration options for the filter */ var LayerSelector = function(dashboard, options) { var view = niclabs.insight.filter.Filter(dashboard, options); var layers = {}; // Configure the view var select = $('<select>'); // Hide the selector if there are no elements select.hide(); select.on('change', function() { dashboard.active($(this).val()); }); // Add the selector to the view view.$.append(select); /** * Add a layer to the selector * * @memberof niclabs.insight.filter.LayerSelector * @param {string} id - id for the layer * @param {name} name - name of the layer */ view.add = function(id, name) { layers[id] = name; select.append($('<option>').attr('value', id).text(name)); // Show the selector if there is more than one layer if (layers.length > 1) select.show(); }; return view; }; // Register the handler niclabs.insight.handler('layer-selector', 'filter', LayerSelector); return LayerSelector; })(jQuery);
Update tests to match new render names.
const renders = require('../test/renders'); const pretty = require('pretty'); import assert from 'power-assert'; const AllComponents = require('../lib/components').default; const templates = require('../lib/templates').default; describe('Rendering Tests', () => { Object.keys(templates).forEach(framework => { describe(`Framework ${framework}`, () => { Object.keys(AllComponents).forEach(component => { describe(`Component ${component}`, () => { it(`Renders ${component} for ${framework}`, (done) => { const instance = new AllComponents[component](); instance.id = 'abc123'; assert.equal(renders[`component-${framework}-${component}`], pretty(instance.render())); done(); }); it(`Renders ${component} for ${framework} as required`, (done) => { const instance = new AllComponents[component]({ validate: { required: true } }); instance.id = 'abc123'; assert.equal(renders[`component-${framework}-${component}-required`], pretty(instance.render())); done(); }); it(`Renders ${component} for ${framework} as multiple`, (done) => { const instance = new AllComponents[component]({ multiple: true }); instance.id = 'abc123'; assert.equal(renders[`component-${framework}-${component}-multiple`], pretty(instance.render())); done(); }); }); }); }); }); });
const renders = require('../test/renders'); const pretty = require('pretty'); import assert from 'power-assert'; const AllComponents = require('../lib/components').default; const templates = require('../lib/templates').default; describe('Rendering Tests', () => { Object.keys(templates).forEach(framework => { describe(`Framework ${framework}`, () => { Object.keys(AllComponents).forEach(component => { describe(`Component ${component}`, () => { it(`Renders ${component} for ${framework}`, (done) => { const instance = new AllComponents[component](); instance.id = 'abc123'; assert.equal(renders[`${framework}-${component}`], pretty(instance.render())); done(); }); it(`Renders ${component} for ${framework} as required`, (done) => { const instance = new AllComponents[component]({ validate: { required: true } }); instance.id = 'abc123'; assert.equal(renders[`${framework}-${component}-required`], pretty(instance.render())); done(); }); it(`Renders ${component} for ${framework} as multiple`, (done) => { const instance = new AllComponents[component]({ multiple: true }); instance.id = 'abc123'; console.log(renders[`${framework}-${component}-multiple`], pretty(instance.render())); assert.equal(renders[`${framework}-${component}-multiple`], pretty(instance.render())); done(); }); }); }); }); }); });
Fix onLoad loading bug if livereactload transformer is not set
module.exports = { onLoad: function(callback) { if (typeof callback !== 'function') { throw new Error('"onLoad" must have a callback function'); } withLiveReactload(setupOnLoadHandlers) withoutLiveReactload(function() { setupOnLoadHandlers({}) }) function setupOnLoadHandlers(lrload) { var winOnload = window.onload; if (!winOnload || !winOnload.__is_livereactload) { window.onload = function () { // initial load event callback(lrload.state); lrload.winloadDone = true; if (typeof winOnload === 'function' && !winOnload.__is_livereactload) { winOnload(); } } } window.onload.__is_livereactload = true; if (lrload.winloadDone) { // reload event callback(lrload.state) } } }, setState: function(state) { withLiveReactload(function(lrload) { lrload.state = state; }) }, expose: function(cls, id) { withLiveReactload(function(lrload) { if (lrload.makeHot) { lrload.makeHot({exports: cls}, 'CUSTOM_' + id); } }) } } function withLiveReactload(cb) { if (typeof window !== 'undefined') { var lrload = window.__livereactload; if (lrload) { cb(lrload); } } } function withoutLiveReactload(cb) { if (typeof window === 'undefined' || !window.__livereactload) { cb(); } }
module.exports = { onLoad: function(callback) { if (typeof callback !== 'function') { throw new Error('"onLoad" must have a callback function'); } withLiveReactload(function(lrload) { var winOnload = window.onload; if (!winOnload || !winOnload.__is_livereactload) { window.onload = function() { // initial load event callback(lrload.state); lrload.winloadDone = true; if (typeof winOnload === 'function' && !winOnload.__is_livereactload) { winOnload(); } } } window.onload.__is_livereactload = true; if (lrload.winloadDone) { // reload event callback(lrload.state) } }) }, setState: function(state) { withLiveReactload(function(lrload) { lrload.state = state; }) }, expose: function(cls, id) { withLiveReactload(function(lrload) { if (lrload.makeHot) { lrload.makeHot({exports: cls}, 'CUSTOM_' + id); } }) } } function withLiveReactload(cb) { if (typeof window !== 'undefined') { var lrload = window.__livereactload; if (lrload) { cb(lrload); } } }
Fix test to handle unkown transport on travis CI testing platform
<?php /** * Created by PhpStorm. * User: evaisse * Date: 02/06/15 * Time: 17:23 */ namespace evaisse\SimpleHttpBundle\Tests\Unit; class SslTest extends AbstractTests { /** * @expectedException evaisse\SimpleHttpBundle\Http\Exception\SslException * @expectedException evaisse\SimpleHttpBundle\Http\Exception\UnknownTransportException */ public function testSslValidationException() { list($helper, $httpKernel, $container) = $this->createContext(); $a = $helper->prepare("GET", 'https://www.pcwebshop.co.uk/'); $a->execute($httpKernel); } public function testDisablingSslVerif() { list($helper, $httpKernel, $container) = $this->createContext(); $a = $helper->prepare("GET", 'https://www.pcwebshop.co.uk/'); $a->setIgnoreSslErrors(true); $a->execute($httpKernel); $this->assertEquals($a->getResponse()->getStatusCode(), 200); } public function testDisablingSslVerif2() { list($helper, $httpKernel, $container) = $this->createContext(); $a = $helper->prepare("GET", 'https://www.pcwebshop.co.uk/'); $a->ignoreSslErrors(true); $a->execute($httpKernel); $this->assertEquals($a->getResponse()->getStatusCode(), 200); } }
<?php /** * Created by PhpStorm. * User: evaisse * Date: 02/06/15 * Time: 17:23 */ namespace evaisse\SimpleHttpBundle\Tests\Unit; class SslTest extends AbstractTests { /** * @expectedException evaisse\SimpleHttpBundle\Http\Exception\SslException */ public function testSslValidationException() { list($helper, $httpKernel, $container) = $this->createContext(); $a = $helper->prepare("GET", 'https://www.pcwebshop.co.uk/'); $a->execute($httpKernel); } public function testDisablingSslVerif() { list($helper, $httpKernel, $container) = $this->createContext(); $a = $helper->prepare("GET", 'https://www.pcwebshop.co.uk/'); $a->setIgnoreSslErrors(true); $a->execute($httpKernel); $this->assertEquals($a->getResponse()->getStatusCode(), 200); } public function testDisablingSslVerif2() { list($helper, $httpKernel, $container) = $this->createContext(); $a = $helper->prepare("GET", 'https://www.pcwebshop.co.uk/'); $a->ignoreSslErrors(true); $a->execute($httpKernel); $this->assertEquals($a->getResponse()->getStatusCode(), 200); } }
Set default for queue transport.
<?php namespace Vivait\DelayedEventBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * 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('vivait_delayed_event'); $rootNode ->children() ->scalarNode('queue_transport') ->defaultValue('beanstalkd') // ->validate() // ->ifTrue(function($value) { return !$this->container->hasDefinition('vivait_inspector.queue.'. $value); }) // ->thenInvalid('Invalid queue transport "%s"') // ->end() ->end() // ->scalarNode('serializer') //// ->validate() //// ->ifTrue(function($value) { return !$this->container->hasDefinition('vivait_inspector.serializer.'. $value); }) //// ->thenInvalid('Invalid serializer "%s"') //// ->end() // ->end() ->end() ->end(); return $treeBuilder; } }
<?php namespace Vivait\DelayedEventBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * 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('vivait_delayed_event'); $rootNode ->children() ->scalarNode('queue_transport') // ->validate() // ->ifTrue(function($value) { return !$this->container->hasDefinition('vivait_inspector.queue.'. $value); }) // ->thenInvalid('Invalid queue transport "%s"') // ->end() ->end() ->scalarNode('serializer') // ->validate() // ->ifTrue(function($value) { return !$this->container->hasDefinition('vivait_inspector.serializer.'. $value); }) // ->thenInvalid('Invalid serializer "%s"') // ->end() ->end() ->end() ->end(); return $treeBuilder; } }
Fix a bug, when token ReflectionClass throws an exception that class is not an interface
<?php /** * Go! OOP&AOP PHP framework * * @copyright Copyright 2012, Lissachenko Alexander <[email protected]> * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ namespace Go\Aop\Support; use ReflectionClass; use Go\Aop\PointFilter; use TokenReflection\ReflectionClass as ParsedReflectionClass; /** * Inheritance class matcher that match single class name or any subclass */ class InheritanceClassFilter implements PointFilter { /** * Instance class name to match * * @var string */ protected $parentClass = ''; /** * Inheritance class matcher constructor * * @param string $parentClassName Name of the parent class or interface to match */ public function __construct($parentClassName) { $this->parentClass = $parentClassName; } /** * {@inheritdoc} */ public function matches($class) { /** @var $point ReflectionClass|ParsedReflectionClass */ if (!$class instanceof ReflectionClass && !$class instanceof ParsedReflectionClass) { return false; } return $class->isSubclassOf($this->parentClass) || in_array($this->parentClass, $class->getInterfaceNames()); } /** * Returns the kind of point filter * * @return integer */ public function getKind() { return self::KIND_CLASS; } }
<?php /** * Go! OOP&AOP PHP framework * * @copyright Copyright 2012, Lissachenko Alexander <[email protected]> * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ namespace Go\Aop\Support; use ReflectionClass; use Go\Aop\PointFilter; use TokenReflection\ReflectionClass as ParsedReflectionClass; /** * Inheritance class matcher that match single class name or any subclass */ class InheritanceClassFilter implements PointFilter { /** * Instance class name to match * * @var string */ protected $parentClass = ''; /** * Inheritance class matcher constructor * * @param string $parentClassName Name of the parent class or interface to match */ public function __construct($parentClassName) { $this->parentClass = $parentClassName; } /** * {@inheritdoc} */ public function matches($class) { /** @var $point ReflectionClass|ParsedReflectionClass */ if (!$class instanceof ReflectionClass && !$class instanceof ParsedReflectionClass) { return false; } return $class->isSubclassOf($this->parentClass) || $class->implementsInterface($this->parentClass); } /** * Returns the kind of point filter * * @return integer */ public function getKind() { return self::KIND_CLASS; } }
Remove connect task from gruntfile
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-typescript'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-open'); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), typescript: { base: { src: ['ts/**/*.ts'], dest: 'js/ImprovedInitiative.js', options: { module: 'amd', target: 'es5', declaration: true } }, test: { src: ['test/**/*.ts'], dest: 'js/test.js', options: { module: 'amd', target: 'es5' } } }, less: { development: { options: { paths: ["."] }, files: { "tracker.css": "tracker.less" } } }, watch: { typescript: { files: '**/*.ts', tasks: ['typescript'] }, lesscss: { files: '**/*.less', tasks: ['less'] } } }); grunt.registerTask('default', 'watch'); };
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-typescript'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-open'); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), connect: { server: { options: { port: 8080, base: './' } } }, typescript: { base: { src: ['ts/**/*.ts'], dest: 'js/ImprovedInitiative.js', options: { module: 'amd', target: 'es5', declaration: true } }, test: { src: ['test/**/*.ts'], dest: 'js/test.js', options: { module: 'amd', target: 'es5' } } }, less: { development: { options: { paths: ["."] }, files: { "tracker.css": "tracker.less" } } }, watch: { typescript: { files: '**/*.ts', tasks: ['typescript'] }, lesscss: { files: '**/*.less', tasks: ['less'] } } }); grunt.registerTask('default', ['connect', 'watch']); };
Use just a random string instead of uuid in shell name. python 2.4 lacks uuid module. Change-Id: I5a1d5339741af2f4defa67d17f557639cd30bb91 Reviewed-on: http://review.couchbase.org/12462 Tested-by: Aliaksey Artamonau <[email protected]> Tested-by: Farshid Ghods <[email protected]> Reviewed-by: Farshid Ghods <[email protected]>
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Provides info about a particular server. """ from usage import usage import restclient import simplejson import subprocess import sys import string import random class Info: def __init__(self): self.debug = False def _remoteShellName(self): tmp = ''.join(random.choice(string.ascii_letters) for i in xrange(20)) return 'ctl-%[email protected]' % tmp def runCmd(self, cmd, server, port, user, password, opts): for (o, a) in opts: if o == '-d' or o == '--debug': self.debug = True rest = restclient.RestClient(server, port, {'debug':self.debug}) opts = {'error_msg': 'server-info error'} data = rest.restCmd('GET', '/nodes/self', user, password, opts) json = rest.getJson(data) for x in ['license', 'licenseValid', 'licenseValidUntil']: if x in json: del(json[x]) if cmd == 'server-eshell': name = self._remoteShellName() p = subprocess.call(['erl','-name',name, '-setcookie',json['otpCookie'],'-hidden','-remsh',json['otpNode']]) else: print simplejson.dumps(json, sort_keys=True, indent=2)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Provides info about a particular server. """ from usage import usage import restclient import simplejson import subprocess import sys from uuid import uuid1 class Info: def __init__(self): self.debug = False def runCmd(self, cmd, server, port, user, password, opts): for (o, a) in opts: if o == '-d' or o == '--debug': self.debug = True rest = restclient.RestClient(server, port, {'debug':self.debug}) opts = {'error_msg': 'server-info error'} data = rest.restCmd('GET', '/nodes/self', user, password, opts) json = rest.getJson(data) for x in ['license', 'licenseValid', 'licenseValidUntil']: if x in json: del(json[x]) if cmd == 'server-eshell': name = 'ctl-%[email protected]' % str(uuid1()) p = subprocess.call(['erl','-name',name, '-setcookie',json['otpCookie'],'-hidden','-remsh',json['otpNode']]) else: print simplejson.dumps(json, sort_keys=True, indent=2)
Use CI mode automatically if colours are not supported
<?php namespace Concise\Console; use Concise\Console\TestRunner\DefaultTestRunner; use Concise\Console\ResultPrinter\ResultPrinterProxy; use Concise\Console\ResultPrinter\DefaultResultPrinter; use Concise\Console\ResultPrinter\CIResultPrinter; class Command extends \PHPUnit_TextUI_Command { protected $ci = false; protected function createRunner() { $resultPrinter = $this->getResultPrinter(); if (array_key_exists('verbose', $this->arguments) && $this->arguments['verbose']) { $resultPrinter->setVerbose(true); } $testRunner = new DefaultTestRunner(); $testRunner->setPrinter(new ResultPrinterProxy($resultPrinter)); return $testRunner; } public function getResultPrinter() { if ($this->ci || `tput colors` < 2) { return new CIResultPrinter(); } return new DefaultResultPrinter(); } /** * @codeCoverageIgnore */ protected function handleArguments(array $argv) { $this->longOptions['test-colors'] = null; $this->longOptions['ci'] = null; parent::handleArguments($argv); foreach ($this->options[0] as $option) { switch ($option[0]) { case '--test-colors': $testColors = new TestColors(new DefaultTheme()); echo $testColors->renderAll(); exit(0); break; case '--ci': $this->ci = true; break; } } } }
<?php namespace Concise\Console; use Concise\Console\TestRunner\DefaultTestRunner; use Concise\Console\ResultPrinter\ResultPrinterProxy; use Concise\Console\ResultPrinter\DefaultResultPrinter; use Concise\Console\ResultPrinter\CIResultPrinter; class Command extends \PHPUnit_TextUI_Command { protected $ci = false; protected function createRunner() { $resultPrinter = $this->getResultPrinter(); if (array_key_exists('verbose', $this->arguments) && $this->arguments['verbose']) { $resultPrinter->setVerbose(true); } $testRunner = new DefaultTestRunner(); $testRunner->setPrinter(new ResultPrinterProxy($resultPrinter)); return $testRunner; } public function getResultPrinter() { if ($this->ci) { return new CIResultPrinter(); } return new DefaultResultPrinter(); } /** * @codeCoverageIgnore */ protected function handleArguments(array $argv) { $this->longOptions['test-colors'] = null; $this->longOptions['ci'] = null; parent::handleArguments($argv); foreach ($this->options[0] as $option) { switch ($option[0]) { case '--test-colors': $testColors = new TestColors(new DefaultTheme()); echo $testColors->renderAll(); exit(0); break; case '--ci': $this->ci = true; break; } } } }
Add mozfile to the dependency list
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup, find_packages PACKAGE_VERSION = '0.1' deps = ['flask', 'manifestparser', 'mongoengine', 'mozfile', 'mozillapulse'] setup(name='test-informant', version=PACKAGE_VERSION, description='A web service for monitoring and reporting the state of test manifests.', long_description='See https://github.com/ahal/test-informant', classifiers=['Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='mozilla', author='Andrew Halberstadt', author_email='[email protected]', url='https://github.com/ahal/test-informant', license='MPL 2.0', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=deps)
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup, find_packages PACKAGE_VERSION = '0.1' deps = ['flask', 'manifestparser', 'mongoengine', 'mozillapulse'] setup(name='test-informant', version=PACKAGE_VERSION, description='A web service for monitoring and reporting the state of test manifests.', long_description='See https://github.com/ahal/test-informant', classifiers=['Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords='mozilla', author='Andrew Halberstadt', author_email='[email protected]', url='https://github.com/ahal/test-informant', license='MPL 2.0', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=deps)
Add tests for add_header example
import glob from mitmproxy import utils, script from mitmproxy.proxy import config from netlib import tutils as netutils from netlib.http import Headers from . import tservers, tutils from examples import ( add_header, modify_form, ) def test_load_scripts(): example_dir = utils.Data(__name__).path("../../examples") scripts = glob.glob("%s/*.py" % example_dir) tmaster = tservers.TestMaster(config.ProxyConfig()) for f in scripts: if "har_extractor" in f: continue if "flowwriter" in f: f += " -" if "iframe_injector" in f: f += " foo" # one argument required if "filt" in f: f += " ~a" if "modify_response_body" in f: f += " foo bar" # two arguments required try: s = script.Script(f, script.ScriptContext(tmaster)) # Loads the script file. except Exception as v: if "ImportError" not in str(v): raise else: s.unload() def test_add_header(): flow = tutils.tflow(resp=netutils.tresp()) add_header.response({}, flow) assert flow.response.headers["newheader"] == "foo" def test_modify_form(): form_header = Headers(content_type="application/x-www-form-urlencoded") flow = tutils.tflow(req=netutils.treq(headers=form_header)) modify_form.request({}, flow) assert flow.request.urlencoded_form["mitmproxy"] == ["rocks"]
import glob from mitmproxy import utils, script from mitmproxy.proxy import config from netlib import tutils as netutils from netlib.http import Headers from . import tservers, tutils from examples import ( modify_form, ) def test_load_scripts(): example_dir = utils.Data(__name__).path("../../examples") scripts = glob.glob("%s/*.py" % example_dir) tmaster = tservers.TestMaster(config.ProxyConfig()) for f in scripts: if "har_extractor" in f: continue if "flowwriter" in f: f += " -" if "iframe_injector" in f: f += " foo" # one argument required if "filt" in f: f += " ~a" if "modify_response_body" in f: f += " foo bar" # two arguments required try: s = script.Script(f, script.ScriptContext(tmaster)) # Loads the script file. except Exception as v: if "ImportError" not in str(v): raise else: s.unload() def test_modify_form(): form_header = Headers(content_type="application/x-www-form-urlencoded") flow = tutils.tflow(req=netutils.treq(headers=form_header)) modify_form.request({}, flow) assert flow.request.urlencoded_form["mitmproxy"] == ["rocks"]
Copy the type in the copy constructor. git-svn-id: 2eebe84b5b32eb059849d530d3c549d0da009da8@126243 cb919951-1609-0410-8833-993d306c94f7
/** * File: ConstantExpression.java * * Author: David Hay ([email protected]) * Creation Date: Apr 22, 2010 * Creation Time: 4:11:11 PM * * Copyright 2010 Local Matters, Inc. * All Rights Reserved * * Last checkin: * $Author$ * $Revision$ * $Date$ */ package org.lesscss4j.model.expression; import org.lesscss4j.model.AbstractElement; import org.lesscss4j.transform.EvaluationContext; public class LiteralExpression extends AbstractElement implements Expression { /** Textual value of the literal expression */ private String _value; /** The token type of this literal as defined in {@link org.lesscss4j.parser.antlr.LessCssLexer} */ private int _type; public LiteralExpression() { } public LiteralExpression(LiteralExpression copy) { super(copy); _value = copy._value; _type = copy._type; } public LiteralExpression(String value) { _value = value; } public String getValue() { return _value; } public void setValue(String value) { _value = value; } public int getType() { return _type; } public void setType(int type) { _type = type; } public Expression evaluate(EvaluationContext context) { return this; } @Override public String toString() { return getValue(); } public LiteralExpression clone() { return new LiteralExpression(this); } }
/** * File: ConstantExpression.java * * Author: David Hay ([email protected]) * Creation Date: Apr 22, 2010 * Creation Time: 4:11:11 PM * * Copyright 2010 Local Matters, Inc. * All Rights Reserved * * Last checkin: * $Author$ * $Revision$ * $Date$ */ package org.lesscss4j.model.expression; import org.lesscss4j.model.AbstractElement; import org.lesscss4j.transform.EvaluationContext; public class LiteralExpression extends AbstractElement implements Expression { /** Textual value of the literal expression */ private String _value; /** The token type of this literal as defined in {@link org.lesscss4j.parser.antlr.LessCssLexer} */ private int _type; public LiteralExpression() { } public LiteralExpression(LiteralExpression copy) { super(copy); _value = copy._value; } public LiteralExpression(String value) { _value = value; } public String getValue() { return _value; } public void setValue(String value) { _value = value; } public int getType() { return _type; } public void setType(int type) { _type = type; } public Expression evaluate(EvaluationContext context) { return this; } @Override public String toString() { return getValue(); } public LiteralExpression clone() { return new LiteralExpression(this); } }
Fix survey ID, machine description display
<h2><span class="label label-default">Pending surveys</span></h2> <table class="table table-striped table-hover"> <thead> <tr> <th>Survey ID</th> <th>Description</th> <th>Date Scheduled</th> <th>Test type</th> <th>Accession</th> <th>Survey Note</th> <th></th> </tr> </thead> <tbody> @foreach ($pendingSurveys as $pending) <tr> <td><a href="{{ route('surveys.edit', $pending->id)}}">{{ $pending->id }}</a></td> <td><a href="{{ route('machines.show', $pending->machine->id) }}">{{ $pending->machine->description }}</a></td> <td>{{ $pending->test_date}}</td> <td>{{ $pending->type->test_type}}</td> <td>{{ $pending->accession }}</td> <td>{{ $pending->notes }}</td> <td><a href="{{ route('surveys.edit', $pending->id) }}" class="btn btn-default btn-xs" role="button" data-toggle="tooltip" title="Modify this machine"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a> </td> </tr> @endforeach </tbody> </table>
<h2><span class="label label-default">Pending surveys</span></h2> <table class="table table-striped table-hover"> <thead> <tr> <th>Survey ID</th> <th>Description</th> <th>Date Scheduled</th> <th>Test type</th> <th>Accession</th> <th>Survey Note</th> <th></th> </tr> </thead> <tbody> @foreach ($pendingSurveys as $pending) <tr> <td><a href="{{ route('surveys.edit', $pending->surveyId)}}">{{ $pending->surveyId }}</a></td> <td><a href="{{ route('machines.show', $pending->machineId) }}">{{ $pending->description }}</a></td> <td>{{ $pending->test_date}}</td> <td>{{ $pending->type->test_type}}</td> <td>{{ $pending->accession }}</td> <td>{{ $pending->notes }}</td> <td><a href="{{ route('surveys.edit', $pending->surveyId) }}" class="btn btn-default btn-xs" role="button" data-toggle="tooltip" title="Modify this machine"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a> </td> </tr> @endforeach </tbody> </table>
Use tabs to split request and response.
const React = require('react') const {Card, CardHeader, CardText} = require('material-ui/Card') const {Tabs, Tab} = require('material-ui/Tabs') /* eslint-disable react/jsx-indent */ module.exports = ({ request, response = { headers: [] } }) => { const headerMapper = (header, index) => <li key={`${header.key}-${index}`}>{`${header.key}: ${header.value}`}</li> console.log('response', response) return <Card> <CardHeader title={request.url} subtitle={request.method} actAsExpander showExpandableButton /> <CardText expandable> <Tabs> <Tab label='Request'> <ul> {request.headers.map(headerMapper)} </ul> </Tab> <Tab label='Response'> <ul> {response.headers.map(headerMapper)} </ul> {request.url} </Tab> </Tabs> </CardText> </Card> } /* eslint-enable react/jsx-indent */
const React = require('react') const {Card, CardActions, CardHeader, CardText} = require('material-ui/Card') const FlatButton = require('material-ui/FlatButton').default /* eslint-disable react/jsx-indent */ module.exports = ({ request, response = { headers: [] } }) => { const headerMapper = (header, index) => <li key={`${header.key}-${index}`}>{`${header.key}: ${header.value}`}</li> return <Card> <CardHeader title={request.url} subtitle={request.method} actAsExpander showExpandableButton /> <CardActions> <FlatButton label='Details' /> <FlatButton label='Action2' /> </CardActions> <CardText expandable> <h4>Request</h4> <ul> {request.headers.map(headerMapper)} </ul> <h4>Response</h4> <ul> {response.headers.map(headerMapper)} </ul> </CardText> </Card> } /* eslint-enable react/jsx-indent */
Convert lifetime to float instead of sympy type.
"""Add electron lifetime """ from sympy.parsing.sympy_parser import parse_expr from pax import units from cax import config from cax.task import Task class AddElectronLifetime(Task): "Add electron lifetime to dataset" def __init__(self): self.collection_purity = config.mongo_collection('purity') Task.__init__(self) def each_run(self): if 'processor' in self.run_doc: return # Fetch the latest electron lifetime fit doc = self.collection_purity.find_one(sort=(('calculation_time', -1),)) function = parse_expr(doc['electron_lifetime_function']) # Compute value from this function on this dataset lifetime = function.evalf(subs={"t" : self.run_doc['start'].timestamp()}) lifetime = float(lifetime) # Convert away from Sympy type. run_number = self.run_doc['number'] self.log.info("Run %d: calculated lifetime of %d us" % (run_number, lifetime)) if not config.DATABASE_LOG: return # Update run database key = 'processor.DEFAULT.electron_lifetime_liquid' self.collection.find_and_modify({'_id': self.run_doc['_id']}, {'$set': {key: lifetime * units.us}})
"""Add electron lifetime """ from sympy.parsing.sympy_parser import parse_expr from pax import units from cax import config from cax.task import Task class AddElectronLifetime(Task): "Add electron lifetime to dataset" def __init__(self): self.collection_purity = config.mongo_collection('purity') Task.__init__(self) def each_run(self): if 'processor' in self.run_doc: return # Fetch the latest electron lifetime fit doc = self.collection_purity.find_one(sort=(('calculation_time', -1),)) function = parse_expr(doc['electron_lifetime_function']) # Compute value from this function on this dataset lifetime = function.evalf(subs={"t" : self.run_doc['start'].timestamp()}) run_number = self.run_doc['number'] self.log.info("Run %d: calculated lifetime of %d us" % (run_number, lifetime)) if not config.DATABASE_LOG: return # Update run database key = 'processor.DEFAULT.electron_lifetime_liquid' self.collection.find_and_modify({'_id': self.run_doc['_id']}, {'$set': {key: lifetime * units.us}})
Tweak YUI `root` to not use "/build/" in URLs
var isProduction = process.env.NODE_ENV === 'production', version = require('../package').version, YUI_VERSION = '3.9.1'; module.exports = { version: YUI_VERSION, config: JSON.stringify({ combine: isProduction, filter : isProduction ? 'min' : 'raw', root : YUI_VERSION + '/', modules: { 'mapbox-css': 'http://api.tiles.mapbox.com/mapbox.js/v0.6.7/mapbox.css', 'mapbox': { fullpath: 'http://api.tiles.mapbox.com/mapbox.js/v0.6.7/mapbox.js', requires: ['mapbox-css'] } }, groups: { 'app': { combine : isProduction, comboBase: '/combo/' + version + '?', base : '/', root : '/', modules: { 'hide-address-bar': {path: 'vendor/hide-address-bar.js'}, 'lew-app': { path : 'js/app.js', requires: [ 'node-base', 'event-resize', 'graphics', 'mapbox', 'hide-address-bar' ] } } } } }) };
var isProduction = process.env.NODE_ENV === 'production', version = require('../package').version; module.exports = { version: '3.9.1', config: JSON.stringify({ combine: isProduction, filter : isProduction ? 'min' : 'raw', modules: { 'mapbox-css': 'http://api.tiles.mapbox.com/mapbox.js/v0.6.7/mapbox.css', 'mapbox': { fullpath: 'http://api.tiles.mapbox.com/mapbox.js/v0.6.7/mapbox.js', requires: ['mapbox-css'] } }, groups: { 'app': { combine : isProduction, comboBase: '/combo/' + version + '?', base : '/', root : '/', modules: { 'hide-address-bar': {path: 'vendor/hide-address-bar.js'}, 'lew-app': { path : 'js/app.js', requires: [ 'node-base', 'event-resize', 'graphics', 'mapbox', 'hide-address-bar' ] } } } } }) };
Fix mix ng1-ng2 example with $ctrl. The name of the default controller of the component is $ctrl.
"use strict"; (function () { angular .module("dummy", []); var upgradeAdapter = new ng.upgrade.UpgradeAdapter(); angular.element(document.body).ready(function () { upgradeAdapter.bootstrap(document.body, ["dummy"]); }); upgradeAdapter.addProvider(ng.http.HTTP_PROVIDERS); var fooS = ng.core .Injectable() .Class({ constructor: [ng.http.Http, function FooService(http) { this.http = http; }], getFoo: function () { return this.http.get("/src/client/app/greetings.json").map( function (res) { return res.json(); } ).toPromise(); } }); upgradeAdapter.addProvider(fooS); angular.module("dummy") .factory("FooService", upgradeAdapter.downgradeNg2Provider(fooS)); angular.module("dummy") .component("foo", { template: "<p>{{ $ctrl.hello }} from mix Angular 1 and Angular 2 </p>", controller: function (FooService) { var vm = this; FooService.getFoo().then(function (foos) { vm.hello = foos.hello; }); } }); }());
"use strict"; (function () { angular .module("dummy", []); var upgradeAdapter = new ng.upgrade.UpgradeAdapter(); angular.element(document.body).ready(function () { upgradeAdapter.bootstrap(document.body, ["dummy"]); }); upgradeAdapter.addProvider(ng.http.HTTP_PROVIDERS); var fooS = ng.core .Injectable() .Class({ constructor: [ng.http.Http, function FooService(http) { this.http = http; }], getFoo: function () { return this.http.get("/src/client/app/greetings.json").map( function (res) { return res.json(); } ).toPromise(); } }); upgradeAdapter.addProvider(fooS); angular.module("dummy") .factory("FooService", upgradeAdapter.downgradeNg2Provider(fooS)); angular.module("dummy") .component("foo", { template: "<p>{{ foo.hello }} from mix Angular 1 and Angular 2 </p>", controller: function (FooService) { var vm = this; FooService.getFoo().then(function (foos) { vm.hello = foos.hello; }); } }); }());
Fix parsing empty content values
var textPattern = /^text\/*/; module.exports = function parseResponse(response) { var key, contentType; for (key in response) { if (Buffer.isBuffer(response[key])) { if (key === 'value') { if (response.content_type && response[key].length !== 0) { contentType = getContentType(response); if (contentType === 'application/json') { response[key] = JSON.parse(response[key]); } else if (textPattern.test(contentType)) { response[key] = response[key].toString(); } } else { response[key] = response[key].toString(); } } else if (key !== 'vclock') { response[key] = response[key].toString(); } } else if (typeof response[key] === 'object') { response[key] = parseResponse(response[key]); } } return response; }; function getContentType(response) { return response.content_type.toString().toLowerCase(); }
var textPattern = /^text\/*/; module.exports = function parseResponse(response) { var key, contentType; for (key in response) { if (Buffer.isBuffer(response[key])) { if (key === 'value') { if (response.content_type) { contentType = getContentType(response); if (contentType === 'application/json') { response[key] = JSON.parse(response[key]); } else if (textPattern.test(contentType)) { response[key] = response[key].toString(); } } else { response[key] = response[key].toString(); } } else if (key !== 'vclock') { response[key] = response[key].toString(); } } else if (typeof response[key] === 'object') { response[key] = parseResponse(response[key]); } } return response; }; function getContentType(response) { return response.content_type.toString().toLowerCase(); }
Change deprecated flyway methods to new FluentConfiguration
package com.cloud.flyway; import com.cloud.legacymodel.exceptions.CloudRuntimeException; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.flywaydb.core.api.configuration.FluentConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FlywayDB { private static final Logger logger = LoggerFactory.getLogger(FlywayDB.class); public void check() { logger.info("Start database migration"); final InitialContext cxt; final DataSource dataSource; try { cxt = new InitialContext(); dataSource = (DataSource) cxt.lookup("java:/comp/env/jdbc/cosmic"); } catch (final NamingException e) { logger.error(e.getMessage(), e); throw new CloudRuntimeException(e.getMessage(), e); } final FluentConfiguration flywayConfig = new FluentConfiguration() .encoding("UTF-8") .dataSource(dataSource) .table("schema_version"); final Flyway flyway = new Flyway(flywayConfig); try { flyway.migrate(); } catch (final FlywayException e) { logger.error(e.getMessage(), e); throw new CloudRuntimeException(e.getMessage(), e); } logger.info("Database migration successful"); } }
package com.cloud.flyway; import com.cloud.legacymodel.exceptions.CloudRuntimeException; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.FlywayException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class FlywayDB { private static final Logger logger = LoggerFactory.getLogger(FlywayDB.class); public void check() { logger.info("Start database migration"); final InitialContext cxt; final DataSource dataSource; try { cxt = new InitialContext(); dataSource = (DataSource) cxt.lookup("java:/comp/env/jdbc/cosmic"); } catch (final NamingException e) { logger.error(e.getMessage(), e); throw new CloudRuntimeException(e.getMessage(), e); } final Flyway flyway = new Flyway(); flyway.setDataSource(dataSource); flyway.setTable("schema_version"); flyway.setEncoding("UTF-8"); try { flyway.migrate(); } catch (final FlywayException e) { logger.error(e.getMessage(), e); throw new CloudRuntimeException(e.getMessage(), e); } logger.info("Database migration successful"); } }
Move debugger line to the top
"""lambda_function.py main entry point for aws lambda""" import json import urllib.request from typing import Dict, Optional import settings from logger import logger from spot import to_msw_id def close(fulfillment_state: str, message: Dict[str, str]) -> dict: """Close dialog generator""" return { 'dialogAction': { 'type': 'Close', 'fulfillmentState': fulfillment_state, 'message': message } } def lambda_handler(event: dict, context: dict) -> Optional[dict]: """Lambda Handler Entry point for every lambda function call """ logger.debug('event=%s context=%s', event, context) if not settings.MSW_API: logger.error("Couldn't read SF_MSW_API env variable") return None spot = event.get("slots", {}).get("SurfSpot", None) spot = to_msw_id(spot) if spot is not None else None if not spot: logger.error("Couldn't parse spot id") return close('Fulfilled', {'contentType': 'PlainText', 'content': 'Surf spot not found :('}) res = json.loads(urllib.request.urlopen( "http://magicseaweed.com/api/{}/forecast/?spot_id={}".format( settings.MSW_API, spot)).read()) logger.debug('json.response=%s', res) return close('Fulfilled', {'contentType': 'PlainText', 'content': 'Number of stars: {}'.format( res[0]['solidRating'])})
"""lambda_function.py main entry point for aws lambda""" import json import urllib.request from typing import Dict, Optional import settings from logger import logger from spot import to_msw_id def close(fulfillment_state: str, message: Dict[str, str]) -> dict: """Close dialog generator""" return { 'dialogAction': { 'type': 'Close', 'fulfillmentState': fulfillment_state, 'message': message } } def lambda_handler(event: dict, context: dict) -> Optional[dict]: """Lambda Handler Entry point for every lambda function call """ if not settings.MSW_API: logger.error("Couldn't read SF_MSW_API env variable") return None spot = event.get("slots", {}).get("SurfSpot", None) spot = to_msw_id(spot) if spot is not None else None if not spot: logger.error("Couldn't parse spot id") return close('Fulfilled', {'contentType': 'PlainText', 'content': 'Surf spot not found :('}) logger.debug('event=%s context=%s', event, context) res = json.loads(urllib.request.urlopen( "http://magicseaweed.com/api/{}/forecast/?spot_id={}".format( settings.MSW_API, spot)).read()) logger.debug('json.response=%s', res) return close('Fulfilled', {'contentType': 'PlainText', 'content': 'Number of stars: {}'.format( res[0]['solidRating'])})
Check for when push to buffer is false and break if so
'use strict'; const assert = require ('assert'); const Duplex = require('stream').Duplex; /** * Creates in memory writable and readable stream * @return {MemDuplex} a MemDuplex instance */ class MemDuplex extends Duplex { constructor() { super({ highWaterMark: 8 * 1024 * 1024 }); // 8MB this.buffers = []; this.cur = 0; // Once writable stream is finished it will emit a finish // event this.once('finish', () => { this._read(); }); } _write(chunk, enc, cb) { assert(Buffer.isBuffer(chunk)); this.buffers.push(chunk); this._read(); cb(); } _read() { while (this.cur < this.buffers.length) { const pushed = this.push(this.buffers[this.cur], 'binary'); this.cur++; if (!pushed) { break; } } // finished is property of writable stream // indicating writing is done. // Once the writing is done and we have pushed // out everything buffered, we're done if (this.cur >= this.buffers.length && this._writableState.finished) { this.push(null); // End of buffer } } } module.exports = MemDuplex;
'use strict'; const assert = require ('assert'); const Duplex = require('stream').Duplex; /** * Creates in memory writable and readable stream * @return {MemDuplex} a MemDuplex instance */ class MemDuplex extends Duplex { constructor() { super({ highWaterMark: 8 * 1024 * 1024 }); // 8MB this.buffers = []; this.cur = 0; // Once writable stream is finished it will emit a finish // event this.once('finish', () => { this._read(); }); } _write(chunk, enc, cb) { assert(Buffer.isBuffer(chunk)); this.buffers.push(chunk); this._read(); cb(); } _read() { while (this.cur < this.buffers.length) { this.push(this.buffers[this.cur], 'binary'); this.cur++; } // finished is property of writable stream // indicating writing is done. // Once the writing is done and we have pushed // out everything buffered, we're done if (this.cur >= this.buffers.length && this._writableState.finished) { this.push(null); // End of buffer } } } module.exports = MemDuplex;
Remove CLIENT_INTERACTIVE flags from config This is very likely the cause of #225. I was not able to re-produce it on my machine, but reading through this makes me think it is the right thing to do: http://dev.mysql.com/doc/refman//5.5/en/mysql-real-connect.html
var ClientConstants = require('./protocol/constants/client'); var Charsets = require('./protocol/constants/charsets'); module.exports = Config; function Config(options) { this.host = options.host || 'localhost'; this.port = options.port || 3306; this.socketPath = options.socketPath; this.user = options.user || undefined; this.password = options.password || undefined; this.database = options.database; this.insecureAuth = options.insecureAuth || false; this.debug = options.debug; this.typeCast = (options.typeCast === undefined) ? true : options.typeCast; this.maxPacketSize = 0; this.charsetNumber = (options.charset) ? Charsets[options.charset] : Charsets.UTF8_GENERAL_CI; this.clientFlags = ClientConstants.CLIENT_LONG_PASSWORD | ClientConstants.CLIENT_FOUND_ROWS | ClientConstants.CLIENT_LONG_FLAG | ClientConstants.CLIENT_CONNECT_WITH_DB | ClientConstants.CLIENT_ODBC | ClientConstants.CLIENT_LOCAL_FILES | ClientConstants.CLIENT_IGNORE_SPACE | ClientConstants.CLIENT_PROTOCOL_41 | ClientConstants.CLIENT_IGNORE_SIGPIPE | ClientConstants.CLIENT_TRANSACTIONS | ClientConstants.CLIENT_RESERVED | ClientConstants.CLIENT_SECURE_CONNECTION | ClientConstants.CLIENT_MULTI_RESULTS; if (options.multipleStatements) { this.clientFlags |= ClientConstants.CLIENT_MULTI_STATEMENTS; } }
var ClientConstants = require('./protocol/constants/client'); var Charsets = require('./protocol/constants/charsets'); module.exports = Config; function Config(options) { this.host = options.host || 'localhost'; this.port = options.port || 3306; this.socketPath = options.socketPath; this.user = options.user || undefined; this.password = options.password || undefined; this.database = options.database; this.insecureAuth = options.insecureAuth || false; this.debug = options.debug; this.typeCast = (options.typeCast === undefined) ? true : options.typeCast; this.maxPacketSize = 0; this.charsetNumber = (options.charset) ? Charsets[options.charset] : Charsets.UTF8_GENERAL_CI; this.clientFlags = ClientConstants.CLIENT_LONG_PASSWORD | ClientConstants.CLIENT_FOUND_ROWS | ClientConstants.CLIENT_LONG_FLAG | ClientConstants.CLIENT_CONNECT_WITH_DB | ClientConstants.CLIENT_ODBC | ClientConstants.CLIENT_LOCAL_FILES | ClientConstants.CLIENT_IGNORE_SPACE | ClientConstants.CLIENT_PROTOCOL_41 | ClientConstants.CLIENT_INTERACTIVE | ClientConstants.CLIENT_IGNORE_SIGPIPE | ClientConstants.CLIENT_TRANSACTIONS | ClientConstants.CLIENT_RESERVED | ClientConstants.CLIENT_SECURE_CONNECTION | ClientConstants.CLIENT_MULTI_RESULTS; if (options.multipleStatements) { this.clientFlags |= ClientConstants.CLIENT_MULTI_STATEMENTS; } }
Allow translator plugin to store selected language in sessionStorage/cookie and remember the settings
๏ปฟangular.module('emixApp', ['ngRoute', 'ngCookies', 'emixApp.controllers', 'emixApp.directives', 'emixApp.services', 'mgcrea.ngStrap', 'ngMorris', 'pascalprecht.translate' ]) .config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/dashboard', { controller: 'dashboard_index', templateUrl: 'ngApp/pages/dashboard/index.html' }) .when('/section', { controller: 'section_index', templateUrl: 'ngApp/pages/section/index.html' }) .otherwise({ redirectTo: '/dashboard' }); }]) .config(['$translateProvider', function ($translateProvider) { $translateProvider.useStaticFilesLoader({ prefix: Emix.Web.translationsFolder, suffix: '.json' }); $translateProvider.preferredLanguage('it_IT'); $translateProvider.storageKey('lang'); $translateProvider.storagePrefix('emix'); $translateProvider.useLocalStorage(); }]); angular.module('emixApp.services', []); angular.module('emixApp.controllers', []); angular.module('emixApp.directives', []);
๏ปฟangular.module('emixApp', ['ngRoute', 'emixApp.controllers', 'emixApp.directives', 'emixApp.services', 'mgcrea.ngStrap', 'ngMorris', //'ngGoogleMap' 'pascalprecht.translate' ]) .config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/dashboard', { controller: 'dashboard_index', templateUrl: 'ngApp/pages/dashboard/index.html' }) .when('/section', { controller: 'section_index', templateUrl: 'ngApp/pages/section/index.html' }) .otherwise({ redirectTo: '/dashboard' }); }]) .config(['$translateProvider', function ($translateProvider) { $translateProvider.useStaticFilesLoader({ prefix: Emix.Web.translationsFolder, suffix: '.json' }); $translateProvider.preferredLanguage('it_IT'); $translateProvider.storageKey('lang'); $translateProvider.storagePrefix('emix'); // $translateProvider.useLocalStorage(); }]); angular.module('emixApp.services', []); angular.module('emixApp.controllers', []); angular.module('emixApp.directives', []);
Add more flexible entity filter function
/** * Created by faide on 4/21/2015. */ export default class Scene { constructor(id = `scene_${Date.now().toString()}`, entities = [], map = null) { "use strict"; this._name = id; this._id = Symbol(this.name); this.__entities = entities; this.__map = map; } get id() { "use strict"; return this._id; } get name() { "use strict"; return this._name; } get map() { "use strict"; return this.__map; } *filter(predicate) { "use strict"; for (let entity of this.entities) { if (predicate(entity)) { yield entity; } } } get entities() { "use strict"; return this.__entities; } addEntity(e) { "use strict"; this.__entities[e.id] = e; } removeEntity(e_id) { "use strict"; delete this.__entities[e_id]; } each(cb, lock_or_filter, thisArg) { "use strict"; let filter = (typeof lock_or_filter === 'function') ? lock_or_filter : (e) => e.has(lock_or_filter), entities = this.filter(filter), e = entities.next(); while (!e.done) { if (thisArg) { cb.call(thisArg, e.value); } else { cb(e.value); } e = entities.next(); } } }
/** * Created by faide on 4/21/2015. */ export default class Scene { constructor(id = `scene_${Date.now().toString()}`, entities = [], map = null) { "use strict"; this._name = id; this._id = Symbol(this.name); this.__entities = entities; this.__map = map; } get id() { "use strict"; return this._id; } get name() { "use strict"; return this._name; } get map() { "use strict"; return this.__map; } *filter(predicate) { "use strict"; for (let entity of this.entities) { if (predicate(entity)) { yield entity; } } } get entities() { "use strict"; return this.__entities; } addEntity(e) { "use strict"; this.__entities[e.id] = e; } removeEntity(e_id) { "use strict"; delete this.__entities[e_id]; } each(cb, lock, thisArg) { "use strict"; let entities = this.filter((e) => e.has(lock)); let e = entities.next(); while (!e.done) { if (thisArg) { cb.call(thisArg, e.value); } else { cb(e.value); } e = entities.next(); } } }
Fix schema misstep in SQL code
(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; var sys = this.sys; var getRandomKey = this.sys.getRandomKey; var classID = params.classid; var getClassMemberships = this.utils.getClassMemberships; sys.db.run('BEGIN TRANSACTION',function(err){ if (err){return oops(response,err,'class/addmembers(1)')}; addMembers(0,params.addmembers.length); }); function addMembers(pos,limit) { if (pos === limit) { endTransaction(); return; } var sql = 'INSERT INTO memberships VALUES(NULL,?,?,?,NULL,NULL);'; var addmemberID = params.addmembers[pos]; var addmemberKey = getRandomKey(8,36); sys.db.run(sql,[classID,addmemberID,addmemberKey],function(err){ if (err){return oops(response,err,'class/addmembers(2)')}; addMembers(pos+1,limit); }); }; function endTransaction() { sys.db.run('END TRANSACTION',function(err){ if (err){return oops(response,err,'class/addmembers(3)')}; getClassMemberships(params,request,response); }); }; } exports.cogClass = cogClass; })();
(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.utils.apiError; var sys = this.sys; var getRandomKey = this.sys.getRandomKey; var classID = params.classid; var getClassMemberships = this.utils.getClassMemberships; sys.db.run('BEGIN TRANSACTION',function(err){ if (err){return oops(response,err,'class/addmembers(1)')}; addMembers(0,params.addmembers.length); }); function addMembers(pos,limit) { if (pos === limit) { endTransaction(); return; } var sql = 'INSERT INTO memberships VALUES(NULL,?,?,?,NULL);'; var addmemberID = params.addmembers[pos]; var addmemberKey = getRandomKey(8,36); sys.db.run(sql,[classID,addmemberID,addmemberKey],function(err){ if (err){return oops(response,err,'class/addmembers(2)')}; addMembers(pos+1,limit); }); }; function endTransaction() { sys.db.run('END TRANSACTION',function(err){ if (err){return oops(response,err,'class/addmembers(3)')}; getClassMemberships(params,request,response); }); }; } exports.cogClass = cogClass; })();
Refactor out Object.assign in favor of { ...merge }
const Howl = require('howler').Howl; module.exports = { initialize(soundsData) { let soundOptions; const soundNames = Object.getOwnPropertyNames(soundsData); this.sounds = soundNames.reduce((memo, name) => { soundOptions = soundsData[name]; // Allow strings instead of objects, for when all that is needed is a URL if ( typeof soundOptions === 'string' ) { soundOptions = { urls: [soundOptions] }; } return { ...memo, [name]: new Howl(soundOptions) } }, {}); return this.sounds; }, play(soundName, spriteName) { const sound = this.sounds[soundName]; if ( typeof sound === 'undefined' ) { return console.warn(` The sound '${soundName}' was requested, but redux-sounds doesn't have anything registered under that name. See https://github.com/joshwcomeau/redux-sounds#unregistered-sound `); } else if ( spriteName && typeof sound._sprite[spriteName] === 'undefined' ) { const validSprites = Object.keys(sound._sprite).join(', '); return console.warn(` The sound '${soundName}' was found, but it does not have a sprite specified for '${spriteName}'. It only has access to the following sprites: ${validSprites}. See https://github.com/joshwcomeau/redux-sounds#invalid-sprite `); } sound.play(spriteName); } }
const Howl = require('howler').Howl; module.exports = { initialize(soundsData) { let soundOptions; const soundNames = Object.getOwnPropertyNames(soundsData); this.sounds = soundNames.reduce((memo, name) => { soundOptions = soundsData[name]; // Allow strings instead of objects, for when all that is needed is a URL if ( typeof soundOptions === 'string' ) { soundOptions = { urls: [soundOptions] }; } // TODO: Replace this with a ...merge. Get rid of Object.assign polyfill. return Object.assign(memo, { [name]: new Howl(soundOptions) }); }, {}); return this.sounds; }, play(soundName, spriteName) { const sound = this.sounds[soundName]; if ( typeof sound === 'undefined' ) { return console.warn(` The sound '${soundName}' was requested, but redux-sounds doesn't have anything registered under that name. See https://github.com/joshwcomeau/redux-sounds#unregistered-sound `); } else if ( spriteName && typeof sound._sprite[spriteName] === 'undefined' ) { const validSprites = Object.keys(sound._sprite).join(', '); return console.warn(` The sound '${soundName}' was found, but it does not have a sprite specified for '${spriteName}'. It only has access to the following sprites: ${validSprites}. See https://github.com/joshwcomeau/redux-sounds#invalid-sprite `); } sound.play(spriteName); } }
Add `is_runable` to Producer base class. Signed-off-by: Michael Markert <[email protected]>
class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` to run the producer, after running `out` attribute has to be set to path to produced output - ``configure(jvm, *options)`` to configure itself with the given jvm and options (must set configured to True if fully configured) - ``is_runable`` to state if producer can be run in current state """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def is_runable(): """ :returns: if producer is runable :rtype: bool """ raise NotImplementedError("runable must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass
class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` - to run the producer - ``configure(jvm, *options)`` - to configure itself with the given jvm and options (must set configured to True if fully configured) """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass
fix: Remove going back a directory for properties See also: PSOBAT-1197
"""Create Spinnaker Pipeline.""" import argparse import logging from ..args import add_debug from ..consts import LOGGING_FORMAT from .create_pipeline import SpinnakerPipeline def main(): """Run newer stuffs.""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() add_debug(parser) parser.add_argument("--app", help="The application name to create", required=True) parser.add_argument( "--triggerjob", help="The jenkins job to monitor for pipeline triggering", required=True) parser.add_argument( "--properties", help="Location of json file that contains application.json details", default="./raw.properties.json", required=False) # parser.add_argument("--vpc", # help="The vpc to create the security group", # required=True) args = parser.parse_args() logging.getLogger(__package__.split('.')[0]).setLevel(args.debug) log.debug('Parsed arguments: %s', args) # Dictionary containing application info. This is passed to the class for # processing appinfo = { 'app': args.app, # 'vpc': args.vpc, 'triggerjob': args.triggerjob, 'properties': args.properties } spinnakerapps = SpinnakerPipeline(app_info=appinfo) spinnakerapps.create_pipeline() if __name__ == "__main__": main()
"""Create Spinnaker Pipeline.""" import argparse import logging from ..args import add_debug from ..consts import LOGGING_FORMAT from .create_pipeline import SpinnakerPipeline def main(): """Run newer stuffs.""" logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser() add_debug(parser) parser.add_argument("--app", help="The application name to create", required=True) parser.add_argument( "--triggerjob", help="The jenkins job to monitor for pipeline triggering", required=True) parser.add_argument( "--properties", help="Location of json file that contains application.json details", default="../raw.properties.json", required=False) # parser.add_argument("--vpc", # help="The vpc to create the security group", # required=True) args = parser.parse_args() logging.getLogger(__package__.split('.')[0]).setLevel(args.debug) log.debug('Parsed arguments: %s', args) # Dictionary containing application info. This is passed to the class for # processing appinfo = { 'app': args.app, # 'vpc': args.vpc, 'triggerjob': args.triggerjob, 'properties': args.properties } spinnakerapps = SpinnakerPipeline(app_info=appinfo) spinnakerapps.create_pipeline() if __name__ == "__main__": main()
Address consistent json field case convention - use camelCase
package images import ( "encoding/json" "errors" ) type IdentityImage struct { KeyUID string Name string Payload []byte Width int Height int FileSize int ResizeTarget int } func (i IdentityImage) GetType() (ImageType, error) { it := GetType(i.Payload) if it == UNKNOWN { return it, errors.New("unsupported file type") } return it, nil } func (i IdentityImage) GetDataURI() (string, error) { return GetPayloadDataURI(i.Payload) } func (i IdentityImage) MarshalJSON() ([]byte, error) { uri, err := i.GetDataURI() if err != nil { return nil, err } temp := struct { KeyUID string `json:"keyUid"` Name string `json:"type"` URI string `json:"uri"` Width int `json:"width"` Height int `json:"height"` FileSize int `json:"fileSize"` ResizeTarget int `json:"resizeTarget"` }{ KeyUID: i.KeyUID, Name: i.Name, URI: uri, Width: i.Width, Height: i.Height, FileSize: i.FileSize, ResizeTarget: i.ResizeTarget, } return json.Marshal(temp) }
package images import ( "encoding/json" "errors" ) type IdentityImage struct { KeyUID string Name string Payload []byte Width int Height int FileSize int ResizeTarget int } func (i IdentityImage) GetType() (ImageType, error) { it := GetType(i.Payload) if it == UNKNOWN { return it, errors.New("unsupported file type") } return it, nil } func (i IdentityImage) GetDataURI() (string, error) { return GetPayloadDataURI(i.Payload) } func (i IdentityImage) MarshalJSON() ([]byte, error) { uri, err := i.GetDataURI() if err != nil { return nil, err } temp := struct { KeyUID string `json:"key_uid"` Name string `json:"type"` URI string `json:"uri"` Width int `json:"width"` Height int `json:"height"` FileSize int `json:"file_size"` ResizeTarget int `json:"resize_target"` }{ KeyUID: i.KeyUID, Name: i.Name, URI: uri, Width: i.Width, Height: i.Height, FileSize: i.FileSize, ResizeTarget: i.ResizeTarget, } return json.Marshal(temp) }
Fix link top on topmenu
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>{{title}}</title> <link rel=stylesheet href=theme/{{theme}}/css/style.css> </head> <body> <header> <h1><a href="?p={{page}}">{{title}}</a></h1> <nav> <ul> <li><a href="?">top</a></li> <li><a href="?p={{page}}&a=edit">edit</a></li> <li><a href="?a=add">add</a></li> <li><a href="?p={{page}}&a=remove">remove</a></li> </ul> </nav> </header> <div id=container> <nav>{{sidebar}}</nav> <main> <div>{{content}}</div> <footer> <ul class=file-list> @foreach(file in files) <li><a href="{{file.url}}">{{file.name}}</a> ({{file.type}}, {{file.size}}bytes)</li> @endforeach </ul> </footer> </main> </div> {{script}} </body> </html>
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>{{title}}</title> <link rel=stylesheet href=theme/{{theme}}/css/style.css> </head> <body> <header> <h1><a href="?p={{page}}">{{title}}</a></h1> <nav> <ul> <li><a href="?p=index">top</a></li> <li><a href="?p={{page}}&a=edit">edit</a></li> <li><a href="?a=add">add</a></li> <li><a href="?p={{page}}&a=remove">remove</a></li> </ul> </nav> </header> <div id=container> <nav>{{sidebar}}</nav> <main> <div>{{content}}</div> <footer> <ul class=file-list> @foreach(file in files) <li><a href="{{file.url}}">{{file.name}}</a> ({{file.type}}, {{file.size}}bytes)</li> @endforeach </ul> </footer> </main> </div> {{script}} </body> </html>
Patch added for upcoming events. TicketCo is working on a fix for the API
<?php namespace TicketCo\Resources; use DateTime; class Events extends API { /** * @var string */ protected $resource = 'events'; /** * Get all events * * @param array $filters Filter by providing one or more of these params; * tags - Filter by tags. E.g ['tags' => 'teater,standup'] * title - Filter by title. E.g ['title' => 'red'] * street_address - ['street_address' => 'Oslo'] * location - Location name: ['location' => 'Concert'] * start_at - Exact start date: ['start_at' => '2017-1-1'] * @return mixed * @throws \Exception */ public function all($filters = []) { return $this->request($filters); } /** * Patch for upcoming events after API changes * @throws \Exception */ public function upcoming() { date_default_timezone_set('Europe/Oslo'); $events = $this->request(); $now = new DateTime(); return $events->filter(function($event) use ($now) { $dt = new DateTime($event->start_at); return $dt >= $now; }); } /** * Retrieve a single event * * @param int $id * @return mixed * @throws \Exception */ public function get($id) { return $this->request([], $id); } /** * Returns status of event * * @param int $id * @return mixed * @throws \Exception */ public function status($id) { return $this->request([], $id . '/status'); } }
<?php namespace TicketCo\Resources; class Events extends API { /** * @var string */ protected $resource = 'events'; /** * Get all events * * @param array $filters Filter by providing one or more of these params; * tags - Filter by tags. E.g ['tags' => 'teater,standup'] * title - Filter by title. E.g ['title' => 'red'] * street_address - ['street_address' => 'Oslo'] * location - Location name: ['location' => 'Concert'] * start_at - Exact start date: ['start_at' => '2017-1-1'] * @return mixed * @throws \Exception */ public function all($filters = []) { return $this->request($filters); } /** * Retrieve a single event * * @param int $id * @return mixed * @throws \Exception */ public function get($id) { return $this->request([], $id); } /** * Returns status of event * * @param int $id * @return mixed * @throws \Exception */ public function status($id) { return $this->request([], $id . '/status'); } }
Remove numberToString/stringToNumber in pycrypto support package and add some int to long conversions so it can happily pass the tests (I bet this is enough to get it working)
# Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this file. """PyCrypto RSA implementation.""" from cryptomath import * from .rsakey import * from .python_rsakey import Python_RSAKey if pycryptoLoaded: from Crypto.PublicKey import RSA class PyCrypto_RSAKey(RSAKey): def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0): if not d: self.rsa = RSA.construct( (long(n), long(e)) ) else: self.rsa = RSA.construct( (long(n), long(e), long(d), long(p), long(q)) ) def __getattr__(self, name): return getattr(self.rsa, name) def hasPrivateKey(self): return self.rsa.has_private() def _rawPrivateKeyOp(self, m): c = self.rsa.decrypt((m,)) return c def _rawPublicKeyOp(self, c): m = self.rsa.encrypt(c, None)[0] return m def generate(bits): key = PyCrypto_RSAKey() def f(numBytes): return bytes(getRandomBytes(numBytes)) key.rsa = RSA.generate(bits, f) return key generate = staticmethod(generate)
# Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this file. """PyCrypto RSA implementation.""" from .cryptomath import * from .rsakey import * from .python_rsakey import Python_RSAKey if pycryptoLoaded: from Crypto.PublicKey import RSA class PyCrypto_RSAKey(RSAKey): def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0): if not d: self.rsa = RSA.construct( (n, e) ) else: self.rsa = RSA.construct( (n, e, d, p, q) ) def __getattr__(self, name): return getattr(self.rsa, name) def hasPrivateKey(self): return self.rsa.has_private() def _rawPrivateKeyOp(self, m): s = numberToString(m, numBytes(self.n)) c = stringToNumber(self.rsa.decrypt((s,))) return c def _rawPublicKeyOp(self, c): s = numberToString(c, numBytes(self.n)) m = stringToNumber(self.rsa.encrypt(s, None)[0]) return m def generate(bits): key = PyCrypto_RSAKey() def f(numBytes): return bytes(getRandomBytes(numBytes)) key.rsa = RSA.generate(bits, f) return key generate = staticmethod(generate)
Fix copy and paste error
from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(XCodeGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__)
from conans.model import Generator from conans.paths import BUILD_INFO_XCODE class XCodeGenerator(Generator): template = ''' HEADER_SEARCH_PATHS = $(inherited) {include_dirs} LIBRARY_SEARCH_PATHS = $(inherited) {lib_dirs} OTHER_LDFLAGS = $(inherited) {linker_flags} {libs} GCC_PREPROCESSOR_DEFINITIONS = $(inherited) {compiler_flags} OTHER_CFLAGS = $(inherited) OTHER_CPLUSPLUSFLAGS = $(inherited) ''' def __init__(self, deps_cpp_info, cpp_info): super(VisualStudioGenerator, self).__init__(deps_cpp_info, cpp_info) self.include_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.include_paths) self.lib_dirs = " ".join('"%s"' % p.replace("\\", "/") for p in deps_cpp_info.lib_paths) self.libs = " ".join(['-l%s' % lib for lib in deps_cpp_info.libs]) self.definitions = " ".join('"%s"' % d for d in deps_cpp_info.defines) self.compiler_flags = " ".join(deps_cpp_info.cppflags + deps_cpp_info.cflags) self.linker_flags = " ".join(deps_cpp_info.sharedlinkflags) @property def filename(self): return BUILD_INFO_XCODE @property def content(self): return self.template.format(**self.__dict__)